Snapshot of upstream SQLite 3.43.2
[sqlcipher.git] / src / btree.c
blob9b59f3ff8ec34968129e43b45e1f6c2a100ce4bd
2 /*
3 ** 2004 April 6
4 **
5 ** The author disclaims copyright to this source code. In place of
6 ** a legal notice, here is a blessing:
7 **
8 ** May you do good and not evil.
9 ** May you find forgiveness for yourself and forgive others.
10 ** May you share freely, never taking more than you give.
12 *************************************************************************
13 ** This file implements an external (disk-based) database using BTrees.
14 ** See the header comment on "btreeInt.h" for additional information.
15 ** Including a description of file format and an overview of operation.
17 #include "btreeInt.h"
20 ** The header string that appears at the beginning of every
21 ** SQLite database.
23 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
26 ** Set this global variable to 1 to enable tracing using the TRACE
27 ** macro.
29 #if 0
30 int sqlite3BtreeTrace=1; /* True to enable tracing */
31 # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
32 #else
33 # define TRACE(X)
34 #endif
37 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
38 ** But if the value is zero, make it 65536.
40 ** This routine is used to extract the "offset to cell content area" value
41 ** from the header of a btree page. If the page size is 65536 and the page
42 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
43 ** This routine makes the necessary adjustment to 65536.
45 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
48 ** Values passed as the 5th argument to allocateBtreePage()
50 #define BTALLOC_ANY 0 /* Allocate any page */
51 #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
52 #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
55 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
56 ** defined, or 0 if it is. For example:
58 ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
60 #ifndef SQLITE_OMIT_AUTOVACUUM
61 #define IfNotOmitAV(expr) (expr)
62 #else
63 #define IfNotOmitAV(expr) 0
64 #endif
66 #ifndef SQLITE_OMIT_SHARED_CACHE
68 ** A list of BtShared objects that are eligible for participation
69 ** in shared cache. This variable has file scope during normal builds,
70 ** but the test harness needs to access it so we make it global for
71 ** test builds.
73 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MAIN.
75 #ifdef SQLITE_TEST
76 BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
77 #else
78 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
79 #endif
80 #endif /* SQLITE_OMIT_SHARED_CACHE */
82 #ifndef SQLITE_OMIT_SHARED_CACHE
84 ** Enable or disable the shared pager and schema features.
86 ** This routine has no effect on existing database connections.
87 ** The shared cache setting effects only future calls to
88 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
90 int sqlite3_enable_shared_cache(int enable){
91 sqlite3GlobalConfig.sharedCacheEnabled = enable;
92 return SQLITE_OK;
94 #endif
98 #ifdef SQLITE_OMIT_SHARED_CACHE
100 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
101 ** and clearAllSharedCacheTableLocks()
102 ** manipulate entries in the BtShared.pLock linked list used to store
103 ** shared-cache table level locks. If the library is compiled with the
104 ** shared-cache feature disabled, then there is only ever one user
105 ** of each BtShared structure and so this locking is not necessary.
106 ** So define the lock related functions as no-ops.
108 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
109 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
110 #define clearAllSharedCacheTableLocks(a)
111 #define downgradeAllSharedCacheTableLocks(a)
112 #define hasSharedCacheTableLock(a,b,c,d) 1
113 #define hasReadConflicts(a, b) 0
114 #endif
116 #ifdef SQLITE_DEBUG
118 ** Return and reset the seek counter for a Btree object.
120 sqlite3_uint64 sqlite3BtreeSeekCount(Btree *pBt){
121 u64 n = pBt->nSeek;
122 pBt->nSeek = 0;
123 return n;
125 #endif
128 ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
129 ** (MemPage*) as an argument. The (MemPage*) must not be NULL.
131 ** If SQLITE_DEBUG is not defined, then this macro is equivalent to
132 ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
133 ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
134 ** with the page number and filename associated with the (MemPage*).
136 #ifdef SQLITE_DEBUG
137 int corruptPageError(int lineno, MemPage *p){
138 char *zMsg;
139 sqlite3BeginBenignMalloc();
140 zMsg = sqlite3_mprintf("database corruption page %u of %s",
141 p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
143 sqlite3EndBenignMalloc();
144 if( zMsg ){
145 sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
147 sqlite3_free(zMsg);
148 return SQLITE_CORRUPT_BKPT;
150 # define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
151 #else
152 # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
153 #endif
155 #ifndef SQLITE_OMIT_SHARED_CACHE
157 #ifdef SQLITE_DEBUG
159 **** This function is only used as part of an assert() statement. ***
161 ** Check to see if pBtree holds the required locks to read or write to the
162 ** table with root page iRoot. Return 1 if it does and 0 if not.
164 ** For example, when writing to a table with root-page iRoot via
165 ** Btree connection pBtree:
167 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
169 ** When writing to an index that resides in a sharable database, the
170 ** caller should have first obtained a lock specifying the root page of
171 ** the corresponding table. This makes things a bit more complicated,
172 ** as this module treats each table as a separate structure. To determine
173 ** the table corresponding to the index being written, this
174 ** function has to search through the database schema.
176 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
177 ** hold a write-lock on the schema table (root page 1). This is also
178 ** acceptable.
180 static int hasSharedCacheTableLock(
181 Btree *pBtree, /* Handle that must hold lock */
182 Pgno iRoot, /* Root page of b-tree */
183 int isIndex, /* True if iRoot is the root of an index b-tree */
184 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
186 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
187 Pgno iTab = 0;
188 BtLock *pLock;
190 /* If this database is not shareable, or if the client is reading
191 ** and has the read-uncommitted flag set, then no lock is required.
192 ** Return true immediately.
194 if( (pBtree->sharable==0)
195 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
197 return 1;
200 /* If the client is reading or writing an index and the schema is
201 ** not loaded, then it is too difficult to actually check to see if
202 ** the correct locks are held. So do not bother - just return true.
203 ** This case does not come up very often anyhow.
205 if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
206 return 1;
209 /* Figure out the root-page that the lock should be held on. For table
210 ** b-trees, this is just the root page of the b-tree being read or
211 ** written. For index b-trees, it is the root page of the associated
212 ** table. */
213 if( isIndex ){
214 HashElem *p;
215 int bSeen = 0;
216 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
217 Index *pIdx = (Index *)sqliteHashData(p);
218 if( pIdx->tnum==iRoot ){
219 if( bSeen ){
220 /* Two or more indexes share the same root page. There must
221 ** be imposter tables. So just return true. The assert is not
222 ** useful in that case. */
223 return 1;
225 iTab = pIdx->pTable->tnum;
226 bSeen = 1;
229 }else{
230 iTab = iRoot;
233 /* Search for the required lock. Either a write-lock on root-page iTab, a
234 ** write-lock on the schema table, or (if the client is reading) a
235 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
236 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
237 if( pLock->pBtree==pBtree
238 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
239 && pLock->eLock>=eLockType
241 return 1;
245 /* Failed to find the required lock. */
246 return 0;
248 #endif /* SQLITE_DEBUG */
250 #ifdef SQLITE_DEBUG
252 **** This function may be used as part of assert() statements only. ****
254 ** Return true if it would be illegal for pBtree to write into the
255 ** table or index rooted at iRoot because other shared connections are
256 ** simultaneously reading that same table or index.
258 ** It is illegal for pBtree to write if some other Btree object that
259 ** shares the same BtShared object is currently reading or writing
260 ** the iRoot table. Except, if the other Btree object has the
261 ** read-uncommitted flag set, then it is OK for the other object to
262 ** have a read cursor.
264 ** For example, before writing to any part of the table or index
265 ** rooted at page iRoot, one should call:
267 ** assert( !hasReadConflicts(pBtree, iRoot) );
269 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
270 BtCursor *p;
271 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
272 if( p->pgnoRoot==iRoot
273 && p->pBtree!=pBtree
274 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
276 return 1;
279 return 0;
281 #endif /* #ifdef SQLITE_DEBUG */
284 ** Query to see if Btree handle p may obtain a lock of type eLock
285 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
286 ** SQLITE_OK if the lock may be obtained (by calling
287 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
289 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
290 BtShared *pBt = p->pBt;
291 BtLock *pIter;
293 assert( sqlite3BtreeHoldsMutex(p) );
294 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
295 assert( p->db!=0 );
296 assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
298 /* If requesting a write-lock, then the Btree must have an open write
299 ** transaction on this file. And, obviously, for this to be so there
300 ** must be an open write transaction on the file itself.
302 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
303 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
305 /* This routine is a no-op if the shared-cache is not enabled */
306 if( !p->sharable ){
307 return SQLITE_OK;
310 /* If some other connection is holding an exclusive lock, the
311 ** requested lock may not be obtained.
313 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
314 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
315 return SQLITE_LOCKED_SHAREDCACHE;
318 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
319 /* The condition (pIter->eLock!=eLock) in the following if(...)
320 ** statement is a simplification of:
322 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
324 ** since we know that if eLock==WRITE_LOCK, then no other connection
325 ** may hold a WRITE_LOCK on any table in this file (since there can
326 ** only be a single writer).
328 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
329 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
330 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
331 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
332 if( eLock==WRITE_LOCK ){
333 assert( p==pBt->pWriter );
334 pBt->btsFlags |= BTS_PENDING;
336 return SQLITE_LOCKED_SHAREDCACHE;
339 return SQLITE_OK;
341 #endif /* !SQLITE_OMIT_SHARED_CACHE */
343 #ifndef SQLITE_OMIT_SHARED_CACHE
345 ** Add a lock on the table with root-page iTable to the shared-btree used
346 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
347 ** WRITE_LOCK.
349 ** This function assumes the following:
351 ** (a) The specified Btree object p is connected to a sharable
352 ** database (one with the BtShared.sharable flag set), and
354 ** (b) No other Btree objects hold a lock that conflicts
355 ** with the requested lock (i.e. querySharedCacheTableLock() has
356 ** already been called and returned SQLITE_OK).
358 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
359 ** is returned if a malloc attempt fails.
361 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
362 BtShared *pBt = p->pBt;
363 BtLock *pLock = 0;
364 BtLock *pIter;
366 assert( sqlite3BtreeHoldsMutex(p) );
367 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
368 assert( p->db!=0 );
370 /* A connection with the read-uncommitted flag set will never try to
371 ** obtain a read-lock using this function. The only read-lock obtained
372 ** by a connection in read-uncommitted mode is on the sqlite_schema
373 ** table, and that lock is obtained in BtreeBeginTrans(). */
374 assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
376 /* This function should only be called on a sharable b-tree after it
377 ** has been determined that no other b-tree holds a conflicting lock. */
378 assert( p->sharable );
379 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
381 /* First search the list for an existing lock on this table. */
382 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
383 if( pIter->iTable==iTable && pIter->pBtree==p ){
384 pLock = pIter;
385 break;
389 /* If the above search did not find a BtLock struct associating Btree p
390 ** with table iTable, allocate one and link it into the list.
392 if( !pLock ){
393 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
394 if( !pLock ){
395 return SQLITE_NOMEM_BKPT;
397 pLock->iTable = iTable;
398 pLock->pBtree = p;
399 pLock->pNext = pBt->pLock;
400 pBt->pLock = pLock;
403 /* Set the BtLock.eLock variable to the maximum of the current lock
404 ** and the requested lock. This means if a write-lock was already held
405 ** and a read-lock requested, we don't incorrectly downgrade the lock.
407 assert( WRITE_LOCK>READ_LOCK );
408 if( eLock>pLock->eLock ){
409 pLock->eLock = eLock;
412 return SQLITE_OK;
414 #endif /* !SQLITE_OMIT_SHARED_CACHE */
416 #ifndef SQLITE_OMIT_SHARED_CACHE
418 ** Release all the table locks (locks obtained via calls to
419 ** the setSharedCacheTableLock() procedure) held by Btree object p.
421 ** This function assumes that Btree p has an open read or write
422 ** transaction. If it does not, then the BTS_PENDING flag
423 ** may be incorrectly cleared.
425 static void clearAllSharedCacheTableLocks(Btree *p){
426 BtShared *pBt = p->pBt;
427 BtLock **ppIter = &pBt->pLock;
429 assert( sqlite3BtreeHoldsMutex(p) );
430 assert( p->sharable || 0==*ppIter );
431 assert( p->inTrans>0 );
433 while( *ppIter ){
434 BtLock *pLock = *ppIter;
435 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
436 assert( pLock->pBtree->inTrans>=pLock->eLock );
437 if( pLock->pBtree==p ){
438 *ppIter = pLock->pNext;
439 assert( pLock->iTable!=1 || pLock==&p->lock );
440 if( pLock->iTable!=1 ){
441 sqlite3_free(pLock);
443 }else{
444 ppIter = &pLock->pNext;
448 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
449 if( pBt->pWriter==p ){
450 pBt->pWriter = 0;
451 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
452 }else if( pBt->nTransaction==2 ){
453 /* This function is called when Btree p is concluding its
454 ** transaction. If there currently exists a writer, and p is not
455 ** that writer, then the number of locks held by connections other
456 ** than the writer must be about to drop to zero. In this case
457 ** set the BTS_PENDING flag to 0.
459 ** If there is not currently a writer, then BTS_PENDING must
460 ** be zero already. So this next line is harmless in that case.
462 pBt->btsFlags &= ~BTS_PENDING;
467 ** This function changes all write-locks held by Btree p into read-locks.
469 static void downgradeAllSharedCacheTableLocks(Btree *p){
470 BtShared *pBt = p->pBt;
471 if( pBt->pWriter==p ){
472 BtLock *pLock;
473 pBt->pWriter = 0;
474 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
475 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
476 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
477 pLock->eLock = READ_LOCK;
482 #endif /* SQLITE_OMIT_SHARED_CACHE */
484 static void releasePage(MemPage *pPage); /* Forward reference */
485 static void releasePageOne(MemPage *pPage); /* Forward reference */
486 static void releasePageNotNull(MemPage *pPage); /* Forward reference */
489 ***** This routine is used inside of assert() only ****
491 ** Verify that the cursor holds the mutex on its BtShared
493 #ifdef SQLITE_DEBUG
494 static int cursorHoldsMutex(BtCursor *p){
495 return sqlite3_mutex_held(p->pBt->mutex);
498 /* Verify that the cursor and the BtShared agree about what is the current
499 ** database connetion. This is important in shared-cache mode. If the database
500 ** connection pointers get out-of-sync, it is possible for routines like
501 ** btreeInitPage() to reference an stale connection pointer that references a
502 ** a connection that has already closed. This routine is used inside assert()
503 ** statements only and for the purpose of double-checking that the btree code
504 ** does keep the database connection pointers up-to-date.
506 static int cursorOwnsBtShared(BtCursor *p){
507 assert( cursorHoldsMutex(p) );
508 return (p->pBtree->db==p->pBt->db);
510 #endif
513 ** Invalidate the overflow cache of the cursor passed as the first argument.
514 ** on the shared btree structure pBt.
516 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
519 ** Invalidate the overflow page-list cache for all cursors opened
520 ** on the shared btree structure pBt.
522 static void invalidateAllOverflowCache(BtShared *pBt){
523 BtCursor *p;
524 assert( sqlite3_mutex_held(pBt->mutex) );
525 for(p=pBt->pCursor; p; p=p->pNext){
526 invalidateOverflowCache(p);
530 #ifndef SQLITE_OMIT_INCRBLOB
532 ** This function is called before modifying the contents of a table
533 ** to invalidate any incrblob cursors that are open on the
534 ** row or one of the rows being modified.
536 ** If argument isClearTable is true, then the entire contents of the
537 ** table is about to be deleted. In this case invalidate all incrblob
538 ** cursors open on any row within the table with root-page pgnoRoot.
540 ** Otherwise, if argument isClearTable is false, then the row with
541 ** rowid iRow is being replaced or deleted. In this case invalidate
542 ** only those incrblob cursors open on that specific row.
544 static void invalidateIncrblobCursors(
545 Btree *pBtree, /* The database file to check */
546 Pgno pgnoRoot, /* The table that might be changing */
547 i64 iRow, /* The rowid that might be changing */
548 int isClearTable /* True if all rows are being deleted */
550 BtCursor *p;
551 assert( pBtree->hasIncrblobCur );
552 assert( sqlite3BtreeHoldsMutex(pBtree) );
553 pBtree->hasIncrblobCur = 0;
554 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
555 if( (p->curFlags & BTCF_Incrblob)!=0 ){
556 pBtree->hasIncrblobCur = 1;
557 if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
558 p->eState = CURSOR_INVALID;
564 #else
565 /* Stub function when INCRBLOB is omitted */
566 #define invalidateIncrblobCursors(w,x,y,z)
567 #endif /* SQLITE_OMIT_INCRBLOB */
570 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
571 ** when a page that previously contained data becomes a free-list leaf
572 ** page.
574 ** The BtShared.pHasContent bitvec exists to work around an obscure
575 ** bug caused by the interaction of two useful IO optimizations surrounding
576 ** free-list leaf pages:
578 ** 1) When all data is deleted from a page and the page becomes
579 ** a free-list leaf page, the page is not written to the database
580 ** (as free-list leaf pages contain no meaningful data). Sometimes
581 ** such a page is not even journalled (as it will not be modified,
582 ** why bother journalling it?).
584 ** 2) When a free-list leaf page is reused, its content is not read
585 ** from the database or written to the journal file (why should it
586 ** be, if it is not at all meaningful?).
588 ** By themselves, these optimizations work fine and provide a handy
589 ** performance boost to bulk delete or insert operations. However, if
590 ** a page is moved to the free-list and then reused within the same
591 ** transaction, a problem comes up. If the page is not journalled when
592 ** it is moved to the free-list and it is also not journalled when it
593 ** is extracted from the free-list and reused, then the original data
594 ** may be lost. In the event of a rollback, it may not be possible
595 ** to restore the database to its original configuration.
597 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
598 ** moved to become a free-list leaf page, the corresponding bit is
599 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
600 ** optimization 2 above is omitted if the corresponding bit is already
601 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
602 ** at the end of every transaction.
604 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
605 int rc = SQLITE_OK;
606 if( !pBt->pHasContent ){
607 assert( pgno<=pBt->nPage );
608 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
609 if( !pBt->pHasContent ){
610 rc = SQLITE_NOMEM_BKPT;
613 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
614 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
616 return rc;
620 ** Query the BtShared.pHasContent vector.
622 ** This function is called when a free-list leaf page is removed from the
623 ** free-list for reuse. It returns false if it is safe to retrieve the
624 ** page from the pager layer with the 'no-content' flag set. True otherwise.
626 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
627 Bitvec *p = pBt->pHasContent;
628 return p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTestNotNull(p, pgno));
632 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
633 ** invoked at the conclusion of each write-transaction.
635 static void btreeClearHasContent(BtShared *pBt){
636 sqlite3BitvecDestroy(pBt->pHasContent);
637 pBt->pHasContent = 0;
641 ** Release all of the apPage[] pages for a cursor.
643 static void btreeReleaseAllCursorPages(BtCursor *pCur){
644 int i;
645 if( pCur->iPage>=0 ){
646 for(i=0; i<pCur->iPage; i++){
647 releasePageNotNull(pCur->apPage[i]);
649 releasePageNotNull(pCur->pPage);
650 pCur->iPage = -1;
655 ** The cursor passed as the only argument must point to a valid entry
656 ** when this function is called (i.e. have eState==CURSOR_VALID). This
657 ** function saves the current cursor key in variables pCur->nKey and
658 ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
659 ** code otherwise.
661 ** If the cursor is open on an intkey table, then the integer key
662 ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
663 ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
664 ** set to point to a malloced buffer pCur->nKey bytes in size containing
665 ** the key.
667 static int saveCursorKey(BtCursor *pCur){
668 int rc = SQLITE_OK;
669 assert( CURSOR_VALID==pCur->eState );
670 assert( 0==pCur->pKey );
671 assert( cursorHoldsMutex(pCur) );
673 if( pCur->curIntKey ){
674 /* Only the rowid is required for a table btree */
675 pCur->nKey = sqlite3BtreeIntegerKey(pCur);
676 }else{
677 /* For an index btree, save the complete key content. It is possible
678 ** that the current key is corrupt. In that case, it is possible that
679 ** the sqlite3VdbeRecordUnpack() function may overread the buffer by
680 ** up to the size of 1 varint plus 1 8-byte value when the cursor
681 ** position is restored. Hence the 17 bytes of padding allocated
682 ** below. */
683 void *pKey;
684 pCur->nKey = sqlite3BtreePayloadSize(pCur);
685 pKey = sqlite3Malloc( pCur->nKey + 9 + 8 );
686 if( pKey ){
687 rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
688 if( rc==SQLITE_OK ){
689 memset(((u8*)pKey)+pCur->nKey, 0, 9+8);
690 pCur->pKey = pKey;
691 }else{
692 sqlite3_free(pKey);
694 }else{
695 rc = SQLITE_NOMEM_BKPT;
698 assert( !pCur->curIntKey || !pCur->pKey );
699 return rc;
703 ** Save the current cursor position in the variables BtCursor.nKey
704 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
706 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
707 ** prior to calling this routine.
709 static int saveCursorPosition(BtCursor *pCur){
710 int rc;
712 assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
713 assert( 0==pCur->pKey );
714 assert( cursorHoldsMutex(pCur) );
716 if( pCur->curFlags & BTCF_Pinned ){
717 return SQLITE_CONSTRAINT_PINNED;
719 if( pCur->eState==CURSOR_SKIPNEXT ){
720 pCur->eState = CURSOR_VALID;
721 }else{
722 pCur->skipNext = 0;
725 rc = saveCursorKey(pCur);
726 if( rc==SQLITE_OK ){
727 btreeReleaseAllCursorPages(pCur);
728 pCur->eState = CURSOR_REQUIRESEEK;
731 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
732 return rc;
735 /* Forward reference */
736 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
739 ** Save the positions of all cursors (except pExcept) that are open on
740 ** the table with root-page iRoot. "Saving the cursor position" means that
741 ** the location in the btree is remembered in such a way that it can be
742 ** moved back to the same spot after the btree has been modified. This
743 ** routine is called just before cursor pExcept is used to modify the
744 ** table, for example in BtreeDelete() or BtreeInsert().
746 ** If there are two or more cursors on the same btree, then all such
747 ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
748 ** routine enforces that rule. This routine only needs to be called in
749 ** the uncommon case when pExpect has the BTCF_Multiple flag set.
751 ** If pExpect!=NULL and if no other cursors are found on the same root-page,
752 ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
753 ** pointless call to this routine.
755 ** Implementation note: This routine merely checks to see if any cursors
756 ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
757 ** event that cursors are in need to being saved.
759 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
760 BtCursor *p;
761 assert( sqlite3_mutex_held(pBt->mutex) );
762 assert( pExcept==0 || pExcept->pBt==pBt );
763 for(p=pBt->pCursor; p; p=p->pNext){
764 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
766 if( p ) return saveCursorsOnList(p, iRoot, pExcept);
767 if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
768 return SQLITE_OK;
771 /* This helper routine to saveAllCursors does the actual work of saving
772 ** the cursors if and when a cursor is found that actually requires saving.
773 ** The common case is that no cursors need to be saved, so this routine is
774 ** broken out from its caller to avoid unnecessary stack pointer movement.
776 static int SQLITE_NOINLINE saveCursorsOnList(
777 BtCursor *p, /* The first cursor that needs saving */
778 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
779 BtCursor *pExcept /* Do not save this cursor */
782 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
783 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
784 int rc = saveCursorPosition(p);
785 if( SQLITE_OK!=rc ){
786 return rc;
788 }else{
789 testcase( p->iPage>=0 );
790 btreeReleaseAllCursorPages(p);
793 p = p->pNext;
794 }while( p );
795 return SQLITE_OK;
799 ** Clear the current cursor position.
801 void sqlite3BtreeClearCursor(BtCursor *pCur){
802 assert( cursorHoldsMutex(pCur) );
803 sqlite3_free(pCur->pKey);
804 pCur->pKey = 0;
805 pCur->eState = CURSOR_INVALID;
809 ** In this version of BtreeMoveto, pKey is a packed index record
810 ** such as is generated by the OP_MakeRecord opcode. Unpack the
811 ** record and then call sqlite3BtreeIndexMoveto() to do the work.
813 static int btreeMoveto(
814 BtCursor *pCur, /* Cursor open on the btree to be searched */
815 const void *pKey, /* Packed key if the btree is an index */
816 i64 nKey, /* Integer key for tables. Size of pKey for indices */
817 int bias, /* Bias search to the high end */
818 int *pRes /* Write search results here */
820 int rc; /* Status code */
821 UnpackedRecord *pIdxKey; /* Unpacked index key */
823 if( pKey ){
824 KeyInfo *pKeyInfo = pCur->pKeyInfo;
825 assert( nKey==(i64)(int)nKey );
826 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
827 if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
828 sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey);
829 if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){
830 rc = SQLITE_CORRUPT_BKPT;
831 }else{
832 rc = sqlite3BtreeIndexMoveto(pCur, pIdxKey, pRes);
834 sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
835 }else{
836 pIdxKey = 0;
837 rc = sqlite3BtreeTableMoveto(pCur, nKey, bias, pRes);
839 return rc;
843 ** Restore the cursor to the position it was in (or as close to as possible)
844 ** when saveCursorPosition() was called. Note that this call deletes the
845 ** saved position info stored by saveCursorPosition(), so there can be
846 ** at most one effective restoreCursorPosition() call after each
847 ** saveCursorPosition().
849 static int btreeRestoreCursorPosition(BtCursor *pCur){
850 int rc;
851 int skipNext = 0;
852 assert( cursorOwnsBtShared(pCur) );
853 assert( pCur->eState>=CURSOR_REQUIRESEEK );
854 if( pCur->eState==CURSOR_FAULT ){
855 return pCur->skipNext;
857 pCur->eState = CURSOR_INVALID;
858 if( sqlite3FaultSim(410) ){
859 rc = SQLITE_IOERR;
860 }else{
861 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
863 if( rc==SQLITE_OK ){
864 sqlite3_free(pCur->pKey);
865 pCur->pKey = 0;
866 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
867 if( skipNext ) pCur->skipNext = skipNext;
868 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
869 pCur->eState = CURSOR_SKIPNEXT;
872 return rc;
875 #define restoreCursorPosition(p) \
876 (p->eState>=CURSOR_REQUIRESEEK ? \
877 btreeRestoreCursorPosition(p) : \
878 SQLITE_OK)
881 ** Determine whether or not a cursor has moved from the position where
882 ** it was last placed, or has been invalidated for any other reason.
883 ** Cursors can move when the row they are pointing at is deleted out
884 ** from under them, for example. Cursor might also move if a btree
885 ** is rebalanced.
887 ** Calling this routine with a NULL cursor pointer returns false.
889 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
890 ** back to where it ought to be if this routine returns true.
892 int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
893 assert( EIGHT_BYTE_ALIGNMENT(pCur)
894 || pCur==sqlite3BtreeFakeValidCursor() );
895 assert( offsetof(BtCursor, eState)==0 );
896 assert( sizeof(pCur->eState)==1 );
897 return CURSOR_VALID != *(u8*)pCur;
901 ** Return a pointer to a fake BtCursor object that will always answer
902 ** false to the sqlite3BtreeCursorHasMoved() routine above. The fake
903 ** cursor returned must not be used with any other Btree interface.
905 BtCursor *sqlite3BtreeFakeValidCursor(void){
906 static u8 fakeCursor = CURSOR_VALID;
907 assert( offsetof(BtCursor, eState)==0 );
908 return (BtCursor*)&fakeCursor;
912 ** This routine restores a cursor back to its original position after it
913 ** has been moved by some outside activity (such as a btree rebalance or
914 ** a row having been deleted out from under the cursor).
916 ** On success, the *pDifferentRow parameter is false if the cursor is left
917 ** pointing at exactly the same row. *pDifferntRow is the row the cursor
918 ** was pointing to has been deleted, forcing the cursor to point to some
919 ** nearby row.
921 ** This routine should only be called for a cursor that just returned
922 ** TRUE from sqlite3BtreeCursorHasMoved().
924 int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
925 int rc;
927 assert( pCur!=0 );
928 assert( pCur->eState!=CURSOR_VALID );
929 rc = restoreCursorPosition(pCur);
930 if( rc ){
931 *pDifferentRow = 1;
932 return rc;
934 if( pCur->eState!=CURSOR_VALID ){
935 *pDifferentRow = 1;
936 }else{
937 *pDifferentRow = 0;
939 return SQLITE_OK;
942 #ifdef SQLITE_ENABLE_CURSOR_HINTS
944 ** Provide hints to the cursor. The particular hint given (and the type
945 ** and number of the varargs parameters) is determined by the eHintType
946 ** parameter. See the definitions of the BTREE_HINT_* macros for details.
948 void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
949 /* Used only by system that substitute their own storage engine */
950 #ifdef SQLITE_DEBUG
951 if( ALWAYS(eHintType==BTREE_HINT_RANGE) ){
952 va_list ap;
953 Expr *pExpr;
954 Walker w;
955 memset(&w, 0, sizeof(w));
956 w.xExprCallback = sqlite3CursorRangeHintExprCheck;
957 va_start(ap, eHintType);
958 pExpr = va_arg(ap, Expr*);
959 w.u.aMem = va_arg(ap, Mem*);
960 va_end(ap);
961 assert( pExpr!=0 );
962 assert( w.u.aMem!=0 );
963 sqlite3WalkExpr(&w, pExpr);
965 #endif /* SQLITE_DEBUG */
967 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
971 ** Provide flag hints to the cursor.
973 void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
974 assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
975 pCur->hints = x;
979 #ifndef SQLITE_OMIT_AUTOVACUUM
981 ** Given a page number of a regular database page, return the page
982 ** number for the pointer-map page that contains the entry for the
983 ** input page number.
985 ** Return 0 (not a valid page) for pgno==1 since there is
986 ** no pointer map associated with page 1. The integrity_check logic
987 ** requires that ptrmapPageno(*,1)!=1.
989 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
990 int nPagesPerMapPage;
991 Pgno iPtrMap, ret;
992 assert( sqlite3_mutex_held(pBt->mutex) );
993 if( pgno<2 ) return 0;
994 nPagesPerMapPage = (pBt->usableSize/5)+1;
995 iPtrMap = (pgno-2)/nPagesPerMapPage;
996 ret = (iPtrMap*nPagesPerMapPage) + 2;
997 if( ret==PENDING_BYTE_PAGE(pBt) ){
998 ret++;
1000 return ret;
1004 ** Write an entry into the pointer map.
1006 ** This routine updates the pointer map entry for page number 'key'
1007 ** so that it maps to type 'eType' and parent page number 'pgno'.
1009 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
1010 ** a no-op. If an error occurs, the appropriate error code is written
1011 ** into *pRC.
1013 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
1014 DbPage *pDbPage; /* The pointer map page */
1015 u8 *pPtrmap; /* The pointer map data */
1016 Pgno iPtrmap; /* The pointer map page number */
1017 int offset; /* Offset in pointer map page */
1018 int rc; /* Return code from subfunctions */
1020 if( *pRC ) return;
1022 assert( sqlite3_mutex_held(pBt->mutex) );
1023 /* The super-journal page number must never be used as a pointer map page */
1024 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
1026 assert( pBt->autoVacuum );
1027 if( key==0 ){
1028 *pRC = SQLITE_CORRUPT_BKPT;
1029 return;
1031 iPtrmap = PTRMAP_PAGENO(pBt, key);
1032 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
1033 if( rc!=SQLITE_OK ){
1034 *pRC = rc;
1035 return;
1037 if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){
1038 /* The first byte of the extra data is the MemPage.isInit byte.
1039 ** If that byte is set, it means this page is also being used
1040 ** as a btree page. */
1041 *pRC = SQLITE_CORRUPT_BKPT;
1042 goto ptrmap_exit;
1044 offset = PTRMAP_PTROFFSET(iPtrmap, key);
1045 if( offset<0 ){
1046 *pRC = SQLITE_CORRUPT_BKPT;
1047 goto ptrmap_exit;
1049 assert( offset <= (int)pBt->usableSize-5 );
1050 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1052 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
1053 TRACE(("PTRMAP_UPDATE: %u->(%u,%u)\n", key, eType, parent));
1054 *pRC= rc = sqlite3PagerWrite(pDbPage);
1055 if( rc==SQLITE_OK ){
1056 pPtrmap[offset] = eType;
1057 put4byte(&pPtrmap[offset+1], parent);
1061 ptrmap_exit:
1062 sqlite3PagerUnref(pDbPage);
1066 ** Read an entry from the pointer map.
1068 ** This routine retrieves the pointer map entry for page 'key', writing
1069 ** the type and parent page number to *pEType and *pPgno respectively.
1070 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
1072 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
1073 DbPage *pDbPage; /* The pointer map page */
1074 int iPtrmap; /* Pointer map page index */
1075 u8 *pPtrmap; /* Pointer map page data */
1076 int offset; /* Offset of entry in pointer map */
1077 int rc;
1079 assert( sqlite3_mutex_held(pBt->mutex) );
1081 iPtrmap = PTRMAP_PAGENO(pBt, key);
1082 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
1083 if( rc!=0 ){
1084 return rc;
1086 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1088 offset = PTRMAP_PTROFFSET(iPtrmap, key);
1089 if( offset<0 ){
1090 sqlite3PagerUnref(pDbPage);
1091 return SQLITE_CORRUPT_BKPT;
1093 assert( offset <= (int)pBt->usableSize-5 );
1094 assert( pEType!=0 );
1095 *pEType = pPtrmap[offset];
1096 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
1098 sqlite3PagerUnref(pDbPage);
1099 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
1100 return SQLITE_OK;
1103 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
1104 #define ptrmapPut(w,x,y,z,rc)
1105 #define ptrmapGet(w,x,y,z) SQLITE_OK
1106 #define ptrmapPutOvflPtr(x, y, z, rc)
1107 #endif
1110 ** Given a btree page and a cell index (0 means the first cell on
1111 ** the page, 1 means the second cell, and so forth) return a pointer
1112 ** to the cell content.
1114 ** findCellPastPtr() does the same except it skips past the initial
1115 ** 4-byte child pointer found on interior pages, if there is one.
1117 ** This routine works only for pages that do not contain overflow cells.
1119 #define findCell(P,I) \
1120 ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1121 #define findCellPastPtr(P,I) \
1122 ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1126 ** This is common tail processing for btreeParseCellPtr() and
1127 ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
1128 ** on a single B-tree page. Make necessary adjustments to the CellInfo
1129 ** structure.
1131 static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
1132 MemPage *pPage, /* Page containing the cell */
1133 u8 *pCell, /* Pointer to the cell text. */
1134 CellInfo *pInfo /* Fill in this structure */
1136 /* If the payload will not fit completely on the local page, we have
1137 ** to decide how much to store locally and how much to spill onto
1138 ** overflow pages. The strategy is to minimize the amount of unused
1139 ** space on overflow pages while keeping the amount of local storage
1140 ** in between minLocal and maxLocal.
1142 ** Warning: changing the way overflow payload is distributed in any
1143 ** way will result in an incompatible file format.
1145 int minLocal; /* Minimum amount of payload held locally */
1146 int maxLocal; /* Maximum amount of payload held locally */
1147 int surplus; /* Overflow payload available for local storage */
1149 minLocal = pPage->minLocal;
1150 maxLocal = pPage->maxLocal;
1151 surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
1152 testcase( surplus==maxLocal );
1153 testcase( surplus==maxLocal+1 );
1154 if( surplus <= maxLocal ){
1155 pInfo->nLocal = (u16)surplus;
1156 }else{
1157 pInfo->nLocal = (u16)minLocal;
1159 pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
1163 ** Given a record with nPayload bytes of payload stored within btree
1164 ** page pPage, return the number of bytes of payload stored locally.
1166 static int btreePayloadToLocal(MemPage *pPage, i64 nPayload){
1167 int maxLocal; /* Maximum amount of payload held locally */
1168 maxLocal = pPage->maxLocal;
1169 if( nPayload<=maxLocal ){
1170 return nPayload;
1171 }else{
1172 int minLocal; /* Minimum amount of payload held locally */
1173 int surplus; /* Overflow payload available for local storage */
1174 minLocal = pPage->minLocal;
1175 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize-4);
1176 return ( surplus <= maxLocal ) ? surplus : minLocal;
1181 ** The following routines are implementations of the MemPage.xParseCell()
1182 ** method.
1184 ** Parse a cell content block and fill in the CellInfo structure.
1186 ** btreeParseCellPtr() => table btree leaf nodes
1187 ** btreeParseCellNoPayload() => table btree internal nodes
1188 ** btreeParseCellPtrIndex() => index btree nodes
1190 ** There is also a wrapper function btreeParseCell() that works for
1191 ** all MemPage types and that references the cell by index rather than
1192 ** by pointer.
1194 static void btreeParseCellPtrNoPayload(
1195 MemPage *pPage, /* Page containing the cell */
1196 u8 *pCell, /* Pointer to the cell text. */
1197 CellInfo *pInfo /* Fill in this structure */
1199 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1200 assert( pPage->leaf==0 );
1201 assert( pPage->childPtrSize==4 );
1202 #ifndef SQLITE_DEBUG
1203 UNUSED_PARAMETER(pPage);
1204 #endif
1205 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
1206 pInfo->nPayload = 0;
1207 pInfo->nLocal = 0;
1208 pInfo->pPayload = 0;
1209 return;
1211 static void btreeParseCellPtr(
1212 MemPage *pPage, /* Page containing the cell */
1213 u8 *pCell, /* Pointer to the cell text. */
1214 CellInfo *pInfo /* Fill in this structure */
1216 u8 *pIter; /* For scanning through pCell */
1217 u32 nPayload; /* Number of bytes of cell payload */
1218 u64 iKey; /* Extracted Key value */
1220 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1221 assert( pPage->leaf==0 || pPage->leaf==1 );
1222 assert( pPage->intKeyLeaf );
1223 assert( pPage->childPtrSize==0 );
1224 pIter = pCell;
1226 /* The next block of code is equivalent to:
1228 ** pIter += getVarint32(pIter, nPayload);
1230 ** The code is inlined to avoid a function call.
1232 nPayload = *pIter;
1233 if( nPayload>=0x80 ){
1234 u8 *pEnd = &pIter[8];
1235 nPayload &= 0x7f;
1237 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1238 }while( (*pIter)>=0x80 && pIter<pEnd );
1240 pIter++;
1242 /* The next block of code is equivalent to:
1244 ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
1246 ** The code is inlined and the loop is unrolled for performance.
1247 ** This routine is a high-runner.
1249 iKey = *pIter;
1250 if( iKey>=0x80 ){
1251 u8 x;
1252 iKey = (iKey<<7) ^ (x = *++pIter);
1253 if( x>=0x80 ){
1254 iKey = (iKey<<7) ^ (x = *++pIter);
1255 if( x>=0x80 ){
1256 iKey = (iKey<<7) ^ 0x10204000 ^ (x = *++pIter);
1257 if( x>=0x80 ){
1258 iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
1259 if( x>=0x80 ){
1260 iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
1261 if( x>=0x80 ){
1262 iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
1263 if( x>=0x80 ){
1264 iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
1265 if( x>=0x80 ){
1266 iKey = (iKey<<8) ^ 0x8000 ^ (*++pIter);
1272 }else{
1273 iKey ^= 0x204000;
1275 }else{
1276 iKey ^= 0x4000;
1279 pIter++;
1281 pInfo->nKey = *(i64*)&iKey;
1282 pInfo->nPayload = nPayload;
1283 pInfo->pPayload = pIter;
1284 testcase( nPayload==pPage->maxLocal );
1285 testcase( nPayload==(u32)pPage->maxLocal+1 );
1286 if( nPayload<=pPage->maxLocal ){
1287 /* This is the (easy) common case where the entire payload fits
1288 ** on the local page. No overflow is required.
1290 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1291 if( pInfo->nSize<4 ) pInfo->nSize = 4;
1292 pInfo->nLocal = (u16)nPayload;
1293 }else{
1294 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1297 static void btreeParseCellPtrIndex(
1298 MemPage *pPage, /* Page containing the cell */
1299 u8 *pCell, /* Pointer to the cell text. */
1300 CellInfo *pInfo /* Fill in this structure */
1302 u8 *pIter; /* For scanning through pCell */
1303 u32 nPayload; /* Number of bytes of cell payload */
1305 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1306 assert( pPage->leaf==0 || pPage->leaf==1 );
1307 assert( pPage->intKeyLeaf==0 );
1308 pIter = pCell + pPage->childPtrSize;
1309 nPayload = *pIter;
1310 if( nPayload>=0x80 ){
1311 u8 *pEnd = &pIter[8];
1312 nPayload &= 0x7f;
1314 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1315 }while( *(pIter)>=0x80 && pIter<pEnd );
1317 pIter++;
1318 pInfo->nKey = nPayload;
1319 pInfo->nPayload = nPayload;
1320 pInfo->pPayload = pIter;
1321 testcase( nPayload==pPage->maxLocal );
1322 testcase( nPayload==(u32)pPage->maxLocal+1 );
1323 if( nPayload<=pPage->maxLocal ){
1324 /* This is the (easy) common case where the entire payload fits
1325 ** on the local page. No overflow is required.
1327 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1328 if( pInfo->nSize<4 ) pInfo->nSize = 4;
1329 pInfo->nLocal = (u16)nPayload;
1330 }else{
1331 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1334 static void btreeParseCell(
1335 MemPage *pPage, /* Page containing the cell */
1336 int iCell, /* The cell index. First cell is 0 */
1337 CellInfo *pInfo /* Fill in this structure */
1339 pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
1343 ** The following routines are implementations of the MemPage.xCellSize
1344 ** method.
1346 ** Compute the total number of bytes that a Cell needs in the cell
1347 ** data area of the btree-page. The return number includes the cell
1348 ** data header and the local payload, but not any overflow page or
1349 ** the space used by the cell pointer.
1351 ** cellSizePtrNoPayload() => table internal nodes
1352 ** cellSizePtrTableLeaf() => table leaf nodes
1353 ** cellSizePtr() => index internal nodes
1354 ** cellSizeIdxLeaf() => index leaf nodes
1356 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
1357 u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
1358 u8 *pEnd; /* End mark for a varint */
1359 u32 nSize; /* Size value to return */
1361 #ifdef SQLITE_DEBUG
1362 /* The value returned by this function should always be the same as
1363 ** the (CellInfo.nSize) value found by doing a full parse of the
1364 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1365 ** this function verifies that this invariant is not violated. */
1366 CellInfo debuginfo;
1367 pPage->xParseCell(pPage, pCell, &debuginfo);
1368 #endif
1370 assert( pPage->childPtrSize==4 );
1371 nSize = *pIter;
1372 if( nSize>=0x80 ){
1373 pEnd = &pIter[8];
1374 nSize &= 0x7f;
1376 nSize = (nSize<<7) | (*++pIter & 0x7f);
1377 }while( *(pIter)>=0x80 && pIter<pEnd );
1379 pIter++;
1380 testcase( nSize==pPage->maxLocal );
1381 testcase( nSize==(u32)pPage->maxLocal+1 );
1382 if( nSize<=pPage->maxLocal ){
1383 nSize += (u32)(pIter - pCell);
1384 assert( nSize>4 );
1385 }else{
1386 int minLocal = pPage->minLocal;
1387 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1388 testcase( nSize==pPage->maxLocal );
1389 testcase( nSize==(u32)pPage->maxLocal+1 );
1390 if( nSize>pPage->maxLocal ){
1391 nSize = minLocal;
1393 nSize += 4 + (u16)(pIter - pCell);
1395 assert( nSize==debuginfo.nSize || CORRUPT_DB );
1396 return (u16)nSize;
1398 static u16 cellSizePtrIdxLeaf(MemPage *pPage, u8 *pCell){
1399 u8 *pIter = pCell; /* For looping over bytes of pCell */
1400 u8 *pEnd; /* End mark for a varint */
1401 u32 nSize; /* Size value to return */
1403 #ifdef SQLITE_DEBUG
1404 /* The value returned by this function should always be the same as
1405 ** the (CellInfo.nSize) value found by doing a full parse of the
1406 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1407 ** this function verifies that this invariant is not violated. */
1408 CellInfo debuginfo;
1409 pPage->xParseCell(pPage, pCell, &debuginfo);
1410 #endif
1412 assert( pPage->childPtrSize==0 );
1413 nSize = *pIter;
1414 if( nSize>=0x80 ){
1415 pEnd = &pIter[8];
1416 nSize &= 0x7f;
1418 nSize = (nSize<<7) | (*++pIter & 0x7f);
1419 }while( *(pIter)>=0x80 && pIter<pEnd );
1421 pIter++;
1422 testcase( nSize==pPage->maxLocal );
1423 testcase( nSize==(u32)pPage->maxLocal+1 );
1424 if( nSize<=pPage->maxLocal ){
1425 nSize += (u32)(pIter - pCell);
1426 if( nSize<4 ) nSize = 4;
1427 }else{
1428 int minLocal = pPage->minLocal;
1429 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1430 testcase( nSize==pPage->maxLocal );
1431 testcase( nSize==(u32)pPage->maxLocal+1 );
1432 if( nSize>pPage->maxLocal ){
1433 nSize = minLocal;
1435 nSize += 4 + (u16)(pIter - pCell);
1437 assert( nSize==debuginfo.nSize || CORRUPT_DB );
1438 return (u16)nSize;
1440 static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
1441 u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
1442 u8 *pEnd; /* End mark for a varint */
1444 #ifdef SQLITE_DEBUG
1445 /* The value returned by this function should always be the same as
1446 ** the (CellInfo.nSize) value found by doing a full parse of the
1447 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1448 ** this function verifies that this invariant is not violated. */
1449 CellInfo debuginfo;
1450 pPage->xParseCell(pPage, pCell, &debuginfo);
1451 #else
1452 UNUSED_PARAMETER(pPage);
1453 #endif
1455 assert( pPage->childPtrSize==4 );
1456 pEnd = pIter + 9;
1457 while( (*pIter++)&0x80 && pIter<pEnd );
1458 assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
1459 return (u16)(pIter - pCell);
1461 static u16 cellSizePtrTableLeaf(MemPage *pPage, u8 *pCell){
1462 u8 *pIter = pCell; /* For looping over bytes of pCell */
1463 u8 *pEnd; /* End mark for a varint */
1464 u32 nSize; /* Size value to return */
1466 #ifdef SQLITE_DEBUG
1467 /* The value returned by this function should always be the same as
1468 ** the (CellInfo.nSize) value found by doing a full parse of the
1469 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1470 ** this function verifies that this invariant is not violated. */
1471 CellInfo debuginfo;
1472 pPage->xParseCell(pPage, pCell, &debuginfo);
1473 #endif
1475 nSize = *pIter;
1476 if( nSize>=0x80 ){
1477 pEnd = &pIter[8];
1478 nSize &= 0x7f;
1480 nSize = (nSize<<7) | (*++pIter & 0x7f);
1481 }while( *(pIter)>=0x80 && pIter<pEnd );
1483 pIter++;
1484 /* pIter now points at the 64-bit integer key value, a variable length
1485 ** integer. The following block moves pIter to point at the first byte
1486 ** past the end of the key value. */
1487 if( (*pIter++)&0x80
1488 && (*pIter++)&0x80
1489 && (*pIter++)&0x80
1490 && (*pIter++)&0x80
1491 && (*pIter++)&0x80
1492 && (*pIter++)&0x80
1493 && (*pIter++)&0x80
1494 && (*pIter++)&0x80 ){ pIter++; }
1495 testcase( nSize==pPage->maxLocal );
1496 testcase( nSize==(u32)pPage->maxLocal+1 );
1497 if( nSize<=pPage->maxLocal ){
1498 nSize += (u32)(pIter - pCell);
1499 if( nSize<4 ) nSize = 4;
1500 }else{
1501 int minLocal = pPage->minLocal;
1502 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1503 testcase( nSize==pPage->maxLocal );
1504 testcase( nSize==(u32)pPage->maxLocal+1 );
1505 if( nSize>pPage->maxLocal ){
1506 nSize = minLocal;
1508 nSize += 4 + (u16)(pIter - pCell);
1510 assert( nSize==debuginfo.nSize || CORRUPT_DB );
1511 return (u16)nSize;
1515 #ifdef SQLITE_DEBUG
1516 /* This variation on cellSizePtr() is used inside of assert() statements
1517 ** only. */
1518 static u16 cellSize(MemPage *pPage, int iCell){
1519 return pPage->xCellSize(pPage, findCell(pPage, iCell));
1521 #endif
1523 #ifndef SQLITE_OMIT_AUTOVACUUM
1525 ** The cell pCell is currently part of page pSrc but will ultimately be part
1526 ** of pPage. (pSrc and pPage are often the same.) If pCell contains a
1527 ** pointer to an overflow page, insert an entry into the pointer-map for
1528 ** the overflow page that will be valid after pCell has been moved to pPage.
1530 static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){
1531 CellInfo info;
1532 if( *pRC ) return;
1533 assert( pCell!=0 );
1534 pPage->xParseCell(pPage, pCell, &info);
1535 if( info.nLocal<info.nPayload ){
1536 Pgno ovfl;
1537 if( SQLITE_OVERFLOW(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){
1538 testcase( pSrc!=pPage );
1539 *pRC = SQLITE_CORRUPT_BKPT;
1540 return;
1542 ovfl = get4byte(&pCell[info.nSize-4]);
1543 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
1546 #endif
1550 ** Defragment the page given. This routine reorganizes cells within the
1551 ** page so that there are no free-blocks on the free-block list.
1553 ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
1554 ** present in the page after this routine returns.
1556 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
1557 ** b-tree page so that there are no freeblocks or fragment bytes, all
1558 ** unused bytes are contained in the unallocated space region, and all
1559 ** cells are packed tightly at the end of the page.
1561 static int defragmentPage(MemPage *pPage, int nMaxFrag){
1562 int i; /* Loop counter */
1563 int pc; /* Address of the i-th cell */
1564 int hdr; /* Offset to the page header */
1565 int size; /* Size of a cell */
1566 int usableSize; /* Number of usable bytes on a page */
1567 int cellOffset; /* Offset to the cell pointer array */
1568 int cbrk; /* Offset to the cell content area */
1569 int nCell; /* Number of cells on the page */
1570 unsigned char *data; /* The page data */
1571 unsigned char *temp; /* Temp area for cell content */
1572 unsigned char *src; /* Source of content */
1573 int iCellFirst; /* First allowable cell index */
1574 int iCellLast; /* Last possible cell index */
1575 int iCellStart; /* First cell offset in input */
1577 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1578 assert( pPage->pBt!=0 );
1579 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
1580 assert( pPage->nOverflow==0 );
1581 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1582 data = pPage->aData;
1583 hdr = pPage->hdrOffset;
1584 cellOffset = pPage->cellOffset;
1585 nCell = pPage->nCell;
1586 assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB );
1587 iCellFirst = cellOffset + 2*nCell;
1588 usableSize = pPage->pBt->usableSize;
1590 /* This block handles pages with two or fewer free blocks and nMaxFrag
1591 ** or fewer fragmented bytes. In this case it is faster to move the
1592 ** two (or one) blocks of cells using memmove() and add the required
1593 ** offsets to each pointer in the cell-pointer array than it is to
1594 ** reconstruct the entire page. */
1595 if( (int)data[hdr+7]<=nMaxFrag ){
1596 int iFree = get2byte(&data[hdr+1]);
1597 if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1598 if( iFree ){
1599 int iFree2 = get2byte(&data[iFree]);
1600 if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1601 if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
1602 u8 *pEnd = &data[cellOffset + nCell*2];
1603 u8 *pAddr;
1604 int sz2 = 0;
1605 int sz = get2byte(&data[iFree+2]);
1606 int top = get2byte(&data[hdr+5]);
1607 if( top>=iFree ){
1608 return SQLITE_CORRUPT_PAGE(pPage);
1610 if( iFree2 ){
1611 if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage);
1612 sz2 = get2byte(&data[iFree2+2]);
1613 if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage);
1614 memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
1615 sz += sz2;
1616 }else if( iFree+sz>usableSize ){
1617 return SQLITE_CORRUPT_PAGE(pPage);
1620 cbrk = top+sz;
1621 assert( cbrk+(iFree-top) <= usableSize );
1622 memmove(&data[cbrk], &data[top], iFree-top);
1623 for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
1624 pc = get2byte(pAddr);
1625 if( pc<iFree ){ put2byte(pAddr, pc+sz); }
1626 else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
1628 goto defragment_out;
1633 cbrk = usableSize;
1634 iCellLast = usableSize - 4;
1635 iCellStart = get2byte(&data[hdr+5]);
1636 if( nCell>0 ){
1637 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
1638 memcpy(temp, data, usableSize);
1639 src = temp;
1640 for(i=0; i<nCell; i++){
1641 u8 *pAddr; /* The i-th cell pointer */
1642 pAddr = &data[cellOffset + i*2];
1643 pc = get2byte(pAddr);
1644 testcase( pc==iCellFirst );
1645 testcase( pc==iCellLast );
1646 /* These conditions have already been verified in btreeInitPage()
1647 ** if PRAGMA cell_size_check=ON.
1649 if( pc>iCellLast ){
1650 return SQLITE_CORRUPT_PAGE(pPage);
1652 assert( pc>=0 && pc<=iCellLast );
1653 size = pPage->xCellSize(pPage, &src[pc]);
1654 cbrk -= size;
1655 if( cbrk<iCellStart || pc+size>usableSize ){
1656 return SQLITE_CORRUPT_PAGE(pPage);
1658 assert( cbrk+size<=usableSize && cbrk>=iCellStart );
1659 testcase( cbrk+size==usableSize );
1660 testcase( pc+size==usableSize );
1661 put2byte(pAddr, cbrk);
1662 memcpy(&data[cbrk], &src[pc], size);
1665 data[hdr+7] = 0;
1667 defragment_out:
1668 assert( pPage->nFree>=0 );
1669 if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
1670 return SQLITE_CORRUPT_PAGE(pPage);
1672 assert( cbrk>=iCellFirst );
1673 put2byte(&data[hdr+5], cbrk);
1674 data[hdr+1] = 0;
1675 data[hdr+2] = 0;
1676 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
1677 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1678 return SQLITE_OK;
1682 ** Search the free-list on page pPg for space to store a cell nByte bytes in
1683 ** size. If one can be found, return a pointer to the space and remove it
1684 ** from the free-list.
1686 ** If no suitable space can be found on the free-list, return NULL.
1688 ** This function may detect corruption within pPg. If corruption is
1689 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
1691 ** Slots on the free list that are between 1 and 3 bytes larger than nByte
1692 ** will be ignored if adding the extra space to the fragmentation count
1693 ** causes the fragmentation count to exceed 60.
1695 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
1696 const int hdr = pPg->hdrOffset; /* Offset to page header */
1697 u8 * const aData = pPg->aData; /* Page data */
1698 int iAddr = hdr + 1; /* Address of ptr to pc */
1699 u8 *pTmp = &aData[iAddr]; /* Temporary ptr into aData[] */
1700 int pc = get2byte(pTmp); /* Address of a free slot */
1701 int x; /* Excess size of the slot */
1702 int maxPC = pPg->pBt->usableSize - nByte; /* Max address for a usable slot */
1703 int size; /* Size of the free slot */
1705 assert( pc>0 );
1706 while( pc<=maxPC ){
1707 /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
1708 ** freeblock form a big-endian integer which is the size of the freeblock
1709 ** in bytes, including the 4-byte header. */
1710 pTmp = &aData[pc+2];
1711 size = get2byte(pTmp);
1712 if( (x = size - nByte)>=0 ){
1713 testcase( x==4 );
1714 testcase( x==3 );
1715 if( x<4 ){
1716 /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
1717 ** number of bytes in fragments may not exceed 60. */
1718 if( aData[hdr+7]>57 ) return 0;
1720 /* Remove the slot from the free-list. Update the number of
1721 ** fragmented bytes within the page. */
1722 memcpy(&aData[iAddr], &aData[pc], 2);
1723 aData[hdr+7] += (u8)x;
1724 return &aData[pc];
1725 }else if( x+pc > maxPC ){
1726 /* This slot extends off the end of the usable part of the page */
1727 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1728 return 0;
1729 }else{
1730 /* The slot remains on the free-list. Reduce its size to account
1731 ** for the portion used by the new allocation. */
1732 put2byte(&aData[pc+2], x);
1734 return &aData[pc + x];
1736 iAddr = pc;
1737 pTmp = &aData[pc];
1738 pc = get2byte(pTmp);
1739 if( pc<=iAddr ){
1740 if( pc ){
1741 /* The next slot in the chain comes before the current slot */
1742 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1744 return 0;
1747 if( pc>maxPC+nByte-4 ){
1748 /* The free slot chain extends off the end of the page */
1749 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1751 return 0;
1755 ** Allocate nByte bytes of space from within the B-Tree page passed
1756 ** as the first argument. Write into *pIdx the index into pPage->aData[]
1757 ** of the first byte of allocated space. Return either SQLITE_OK or
1758 ** an error code (usually SQLITE_CORRUPT).
1760 ** The caller guarantees that there is sufficient space to make the
1761 ** allocation. This routine might need to defragment in order to bring
1762 ** all the space together, however. This routine will avoid using
1763 ** the first two bytes past the cell pointer area since presumably this
1764 ** allocation is being made in order to insert a new cell, so we will
1765 ** also end up needing a new cell pointer.
1767 static SQLITE_INLINE int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
1768 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1769 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
1770 int top; /* First byte of cell content area */
1771 int rc = SQLITE_OK; /* Integer return code */
1772 u8 *pTmp; /* Temp ptr into data[] */
1773 int gap; /* First byte of gap between cell pointers and cell content */
1775 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1776 assert( pPage->pBt );
1777 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1778 assert( nByte>=0 ); /* Minimum cell size is 4 */
1779 assert( pPage->nFree>=nByte );
1780 assert( pPage->nOverflow==0 );
1781 assert( nByte < (int)(pPage->pBt->usableSize-8) );
1783 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1784 gap = pPage->cellOffset + 2*pPage->nCell;
1785 assert( gap<=65536 );
1786 /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
1787 ** and the reserved space is zero (the usual value for reserved space)
1788 ** then the cell content offset of an empty page wants to be 65536.
1789 ** However, that integer is too large to be stored in a 2-byte unsigned
1790 ** integer, so a value of 0 is used in its place. */
1791 pTmp = &data[hdr+5];
1792 top = get2byte(pTmp);
1793 if( gap>top ){
1794 if( top==0 && pPage->pBt->usableSize==65536 ){
1795 top = 65536;
1796 }else{
1797 return SQLITE_CORRUPT_PAGE(pPage);
1799 }else if( top>(int)pPage->pBt->usableSize ){
1800 return SQLITE_CORRUPT_PAGE(pPage);
1803 /* If there is enough space between gap and top for one more cell pointer,
1804 ** and if the freelist is not empty, then search the
1805 ** freelist looking for a slot big enough to satisfy the request.
1807 testcase( gap+2==top );
1808 testcase( gap+1==top );
1809 testcase( gap==top );
1810 if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
1811 u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
1812 if( pSpace ){
1813 int g2;
1814 assert( pSpace+nByte<=data+pPage->pBt->usableSize );
1815 *pIdx = g2 = (int)(pSpace-data);
1816 if( g2<=gap ){
1817 return SQLITE_CORRUPT_PAGE(pPage);
1818 }else{
1819 return SQLITE_OK;
1821 }else if( rc ){
1822 return rc;
1826 /* The request could not be fulfilled using a freelist slot. Check
1827 ** to see if defragmentation is necessary.
1829 testcase( gap+2+nByte==top );
1830 if( gap+2+nByte>top ){
1831 assert( pPage->nCell>0 || CORRUPT_DB );
1832 assert( pPage->nFree>=0 );
1833 rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
1834 if( rc ) return rc;
1835 top = get2byteNotZero(&data[hdr+5]);
1836 assert( gap+2+nByte<=top );
1840 /* Allocate memory from the gap in between the cell pointer array
1841 ** and the cell content area. The btreeComputeFreeSpace() call has already
1842 ** validated the freelist. Given that the freelist is valid, there
1843 ** is no way that the allocation can extend off the end of the page.
1844 ** The assert() below verifies the previous sentence.
1846 top -= nByte;
1847 put2byte(&data[hdr+5], top);
1848 assert( top+nByte <= (int)pPage->pBt->usableSize );
1849 *pIdx = top;
1850 return SQLITE_OK;
1854 ** Return a section of the pPage->aData to the freelist.
1855 ** The first byte of the new free block is pPage->aData[iStart]
1856 ** and the size of the block is iSize bytes.
1858 ** Adjacent freeblocks are coalesced.
1860 ** Even though the freeblock list was checked by btreeComputeFreeSpace(),
1861 ** that routine will not detect overlap between cells or freeblocks. Nor
1862 ** does it detect cells or freeblocks that encroach into the reserved bytes
1863 ** at the end of the page. So do additional corruption checks inside this
1864 ** routine and return SQLITE_CORRUPT if any problems are found.
1866 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
1867 u16 iPtr; /* Address of ptr to next freeblock */
1868 u16 iFreeBlk; /* Address of the next freeblock */
1869 u8 hdr; /* Page header size. 0 or 100 */
1870 u8 nFrag = 0; /* Reduction in fragmentation */
1871 u16 iOrigSize = iSize; /* Original value of iSize */
1872 u16 x; /* Offset to cell content area */
1873 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
1874 unsigned char *data = pPage->aData; /* Page content */
1875 u8 *pTmp; /* Temporary ptr into data[] */
1877 assert( pPage->pBt!=0 );
1878 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1879 assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
1880 assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
1881 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1882 assert( iSize>=4 ); /* Minimum cell size is 4 */
1883 assert( CORRUPT_DB || iStart<=pPage->pBt->usableSize-4 );
1885 /* The list of freeblocks must be in ascending order. Find the
1886 ** spot on the list where iStart should be inserted.
1888 hdr = pPage->hdrOffset;
1889 iPtr = hdr + 1;
1890 if( data[iPtr+1]==0 && data[iPtr]==0 ){
1891 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
1892 }else{
1893 while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
1894 if( iFreeBlk<=iPtr ){
1895 if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */
1896 return SQLITE_CORRUPT_PAGE(pPage);
1898 iPtr = iFreeBlk;
1900 if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */
1901 return SQLITE_CORRUPT_PAGE(pPage);
1903 assert( iFreeBlk>iPtr || iFreeBlk==0 || CORRUPT_DB );
1905 /* At this point:
1906 ** iFreeBlk: First freeblock after iStart, or zero if none
1907 ** iPtr: The address of a pointer to iFreeBlk
1909 ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
1911 if( iFreeBlk && iEnd+3>=iFreeBlk ){
1912 nFrag = iFreeBlk - iEnd;
1913 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
1914 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
1915 if( iEnd > pPage->pBt->usableSize ){
1916 return SQLITE_CORRUPT_PAGE(pPage);
1918 iSize = iEnd - iStart;
1919 iFreeBlk = get2byte(&data[iFreeBlk]);
1922 /* If iPtr is another freeblock (that is, if iPtr is not the freelist
1923 ** pointer in the page header) then check to see if iStart should be
1924 ** coalesced onto the end of iPtr.
1926 if( iPtr>hdr+1 ){
1927 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
1928 if( iPtrEnd+3>=iStart ){
1929 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
1930 nFrag += iStart - iPtrEnd;
1931 iSize = iEnd - iPtr;
1932 iStart = iPtr;
1935 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
1936 data[hdr+7] -= nFrag;
1938 pTmp = &data[hdr+5];
1939 x = get2byte(pTmp);
1940 if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
1941 /* Overwrite deleted information with zeros when the secure_delete
1942 ** option is enabled */
1943 memset(&data[iStart], 0, iSize);
1945 if( iStart<=x ){
1946 /* The new freeblock is at the beginning of the cell content area,
1947 ** so just extend the cell content area rather than create another
1948 ** freelist entry */
1949 if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage);
1950 if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
1951 put2byte(&data[hdr+1], iFreeBlk);
1952 put2byte(&data[hdr+5], iEnd);
1953 }else{
1954 /* Insert the new freeblock into the freelist */
1955 put2byte(&data[iPtr], iStart);
1956 put2byte(&data[iStart], iFreeBlk);
1957 put2byte(&data[iStart+2], iSize);
1959 pPage->nFree += iOrigSize;
1960 return SQLITE_OK;
1964 ** Decode the flags byte (the first byte of the header) for a page
1965 ** and initialize fields of the MemPage structure accordingly.
1967 ** Only the following combinations are supported. Anything different
1968 ** indicates a corrupt database files:
1970 ** PTF_ZERODATA (0x02, 2)
1971 ** PTF_LEAFDATA | PTF_INTKEY (0x05, 5)
1972 ** PTF_ZERODATA | PTF_LEAF (0x0a, 10)
1973 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF (0x0d, 13)
1975 static int decodeFlags(MemPage *pPage, int flagByte){
1976 BtShared *pBt; /* A copy of pPage->pBt */
1978 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
1979 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1980 pBt = pPage->pBt;
1981 pPage->max1bytePayload = pBt->max1bytePayload;
1982 if( flagByte>=(PTF_ZERODATA | PTF_LEAF) ){
1983 pPage->childPtrSize = 0;
1984 pPage->leaf = 1;
1985 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF) ){
1986 pPage->intKeyLeaf = 1;
1987 pPage->xCellSize = cellSizePtrTableLeaf;
1988 pPage->xParseCell = btreeParseCellPtr;
1989 pPage->intKey = 1;
1990 pPage->maxLocal = pBt->maxLeaf;
1991 pPage->minLocal = pBt->minLeaf;
1992 }else if( flagByte==(PTF_ZERODATA | PTF_LEAF) ){
1993 pPage->intKey = 0;
1994 pPage->intKeyLeaf = 0;
1995 pPage->xCellSize = cellSizePtrIdxLeaf;
1996 pPage->xParseCell = btreeParseCellPtrIndex;
1997 pPage->maxLocal = pBt->maxLocal;
1998 pPage->minLocal = pBt->minLocal;
1999 }else{
2000 pPage->intKey = 0;
2001 pPage->intKeyLeaf = 0;
2002 pPage->xCellSize = cellSizePtrIdxLeaf;
2003 pPage->xParseCell = btreeParseCellPtrIndex;
2004 return SQLITE_CORRUPT_PAGE(pPage);
2006 }else{
2007 pPage->childPtrSize = 4;
2008 pPage->leaf = 0;
2009 if( flagByte==(PTF_ZERODATA) ){
2010 pPage->intKey = 0;
2011 pPage->intKeyLeaf = 0;
2012 pPage->xCellSize = cellSizePtr;
2013 pPage->xParseCell = btreeParseCellPtrIndex;
2014 pPage->maxLocal = pBt->maxLocal;
2015 pPage->minLocal = pBt->minLocal;
2016 }else if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
2017 pPage->intKeyLeaf = 0;
2018 pPage->xCellSize = cellSizePtrNoPayload;
2019 pPage->xParseCell = btreeParseCellPtrNoPayload;
2020 pPage->intKey = 1;
2021 pPage->maxLocal = pBt->maxLeaf;
2022 pPage->minLocal = pBt->minLeaf;
2023 }else{
2024 pPage->intKey = 0;
2025 pPage->intKeyLeaf = 0;
2026 pPage->xCellSize = cellSizePtr;
2027 pPage->xParseCell = btreeParseCellPtrIndex;
2028 return SQLITE_CORRUPT_PAGE(pPage);
2031 return SQLITE_OK;
2035 ** Compute the amount of freespace on the page. In other words, fill
2036 ** in the pPage->nFree field.
2038 static int btreeComputeFreeSpace(MemPage *pPage){
2039 int pc; /* Address of a freeblock within pPage->aData[] */
2040 u8 hdr; /* Offset to beginning of page header */
2041 u8 *data; /* Equal to pPage->aData */
2042 int usableSize; /* Amount of usable space on each page */
2043 int nFree; /* Number of unused bytes on the page */
2044 int top; /* First byte of the cell content area */
2045 int iCellFirst; /* First allowable cell or freeblock offset */
2046 int iCellLast; /* Last possible cell or freeblock offset */
2048 assert( pPage->pBt!=0 );
2049 assert( pPage->pBt->db!=0 );
2050 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2051 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
2052 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
2053 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
2054 assert( pPage->isInit==1 );
2055 assert( pPage->nFree<0 );
2057 usableSize = pPage->pBt->usableSize;
2058 hdr = pPage->hdrOffset;
2059 data = pPage->aData;
2060 /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
2061 ** the start of the cell content area. A zero value for this integer is
2062 ** interpreted as 65536. */
2063 top = get2byteNotZero(&data[hdr+5]);
2064 iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell;
2065 iCellLast = usableSize - 4;
2067 /* Compute the total free space on the page
2068 ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
2069 ** start of the first freeblock on the page, or is zero if there are no
2070 ** freeblocks. */
2071 pc = get2byte(&data[hdr+1]);
2072 nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
2073 if( pc>0 ){
2074 u32 next, size;
2075 if( pc<top ){
2076 /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
2077 ** always be at least one cell before the first freeblock.
2079 return SQLITE_CORRUPT_PAGE(pPage);
2081 while( 1 ){
2082 if( pc>iCellLast ){
2083 /* Freeblock off the end of the page */
2084 return SQLITE_CORRUPT_PAGE(pPage);
2086 next = get2byte(&data[pc]);
2087 size = get2byte(&data[pc+2]);
2088 nFree = nFree + size;
2089 if( next<=pc+size+3 ) break;
2090 pc = next;
2092 if( next>0 ){
2093 /* Freeblock not in ascending order */
2094 return SQLITE_CORRUPT_PAGE(pPage);
2096 if( pc+size>(unsigned int)usableSize ){
2097 /* Last freeblock extends past page end */
2098 return SQLITE_CORRUPT_PAGE(pPage);
2102 /* At this point, nFree contains the sum of the offset to the start
2103 ** of the cell-content area plus the number of free bytes within
2104 ** the cell-content area. If this is greater than the usable-size
2105 ** of the page, then the page must be corrupted. This check also
2106 ** serves to verify that the offset to the start of the cell-content
2107 ** area, according to the page header, lies within the page.
2109 if( nFree>usableSize || nFree<iCellFirst ){
2110 return SQLITE_CORRUPT_PAGE(pPage);
2112 pPage->nFree = (u16)(nFree - iCellFirst);
2113 return SQLITE_OK;
2117 ** Do additional sanity check after btreeInitPage() if
2118 ** PRAGMA cell_size_check=ON
2120 static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){
2121 int iCellFirst; /* First allowable cell or freeblock offset */
2122 int iCellLast; /* Last possible cell or freeblock offset */
2123 int i; /* Index into the cell pointer array */
2124 int sz; /* Size of a cell */
2125 int pc; /* Address of a freeblock within pPage->aData[] */
2126 u8 *data; /* Equal to pPage->aData */
2127 int usableSize; /* Maximum usable space on the page */
2128 int cellOffset; /* Start of cell content area */
2130 iCellFirst = pPage->cellOffset + 2*pPage->nCell;
2131 usableSize = pPage->pBt->usableSize;
2132 iCellLast = usableSize - 4;
2133 data = pPage->aData;
2134 cellOffset = pPage->cellOffset;
2135 if( !pPage->leaf ) iCellLast--;
2136 for(i=0; i<pPage->nCell; i++){
2137 pc = get2byteAligned(&data[cellOffset+i*2]);
2138 testcase( pc==iCellFirst );
2139 testcase( pc==iCellLast );
2140 if( pc<iCellFirst || pc>iCellLast ){
2141 return SQLITE_CORRUPT_PAGE(pPage);
2143 sz = pPage->xCellSize(pPage, &data[pc]);
2144 testcase( pc+sz==usableSize );
2145 if( pc+sz>usableSize ){
2146 return SQLITE_CORRUPT_PAGE(pPage);
2149 return SQLITE_OK;
2153 ** Initialize the auxiliary information for a disk block.
2155 ** Return SQLITE_OK on success. If we see that the page does
2156 ** not contain a well-formed database page, then return
2157 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
2158 ** guarantee that the page is well-formed. It only shows that
2159 ** we failed to detect any corruption.
2161 static int btreeInitPage(MemPage *pPage){
2162 u8 *data; /* Equal to pPage->aData */
2163 BtShared *pBt; /* The main btree structure */
2165 assert( pPage->pBt!=0 );
2166 assert( pPage->pBt->db!=0 );
2167 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2168 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
2169 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
2170 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
2171 assert( pPage->isInit==0 );
2173 pBt = pPage->pBt;
2174 data = pPage->aData + pPage->hdrOffset;
2175 /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
2176 ** the b-tree page type. */
2177 if( decodeFlags(pPage, data[0]) ){
2178 return SQLITE_CORRUPT_PAGE(pPage);
2180 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2181 pPage->maskPage = (u16)(pBt->pageSize - 1);
2182 pPage->nOverflow = 0;
2183 pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize;
2184 pPage->aCellIdx = data + pPage->childPtrSize + 8;
2185 pPage->aDataEnd = pPage->aData + pBt->pageSize;
2186 pPage->aDataOfst = pPage->aData + pPage->childPtrSize;
2187 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
2188 ** number of cells on the page. */
2189 pPage->nCell = get2byte(&data[3]);
2190 if( pPage->nCell>MX_CELL(pBt) ){
2191 /* To many cells for a single page. The page must be corrupt */
2192 return SQLITE_CORRUPT_PAGE(pPage);
2194 testcase( pPage->nCell==MX_CELL(pBt) );
2195 /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
2196 ** possible for a root page of a table that contains no rows) then the
2197 ** offset to the cell content area will equal the page size minus the
2198 ** bytes of reserved space. */
2199 assert( pPage->nCell>0
2200 || get2byteNotZero(&data[5])==(int)pBt->usableSize
2201 || CORRUPT_DB );
2202 pPage->nFree = -1; /* Indicate that this value is yet uncomputed */
2203 pPage->isInit = 1;
2204 if( pBt->db->flags & SQLITE_CellSizeCk ){
2205 return btreeCellSizeCheck(pPage);
2207 return SQLITE_OK;
2211 ** Set up a raw page so that it looks like a database page holding
2212 ** no entries.
2214 static void zeroPage(MemPage *pPage, int flags){
2215 unsigned char *data = pPage->aData;
2216 BtShared *pBt = pPage->pBt;
2217 u8 hdr = pPage->hdrOffset;
2218 u16 first;
2220 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno || CORRUPT_DB );
2221 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2222 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
2223 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
2224 assert( sqlite3_mutex_held(pBt->mutex) );
2225 if( pBt->btsFlags & BTS_FAST_SECURE ){
2226 memset(&data[hdr], 0, pBt->usableSize - hdr);
2228 data[hdr] = (char)flags;
2229 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
2230 memset(&data[hdr+1], 0, 4);
2231 data[hdr+7] = 0;
2232 put2byte(&data[hdr+5], pBt->usableSize);
2233 pPage->nFree = (u16)(pBt->usableSize - first);
2234 decodeFlags(pPage, flags);
2235 pPage->cellOffset = first;
2236 pPage->aDataEnd = &data[pBt->pageSize];
2237 pPage->aCellIdx = &data[first];
2238 pPage->aDataOfst = &data[pPage->childPtrSize];
2239 pPage->nOverflow = 0;
2240 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2241 pPage->maskPage = (u16)(pBt->pageSize - 1);
2242 pPage->nCell = 0;
2243 pPage->isInit = 1;
2248 ** Convert a DbPage obtained from the pager into a MemPage used by
2249 ** the btree layer.
2251 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
2252 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2253 if( pgno!=pPage->pgno ){
2254 pPage->aData = sqlite3PagerGetData(pDbPage);
2255 pPage->pDbPage = pDbPage;
2256 pPage->pBt = pBt;
2257 pPage->pgno = pgno;
2258 pPage->hdrOffset = pgno==1 ? 100 : 0;
2260 assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
2261 return pPage;
2265 ** Get a page from the pager. Initialize the MemPage.pBt and
2266 ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
2268 ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
2269 ** about the content of the page at this time. So do not go to the disk
2270 ** to fetch the content. Just fill in the content with zeros for now.
2271 ** If in the future we call sqlite3PagerWrite() on this page, that
2272 ** means we have started to be concerned about content and the disk
2273 ** read should occur at that point.
2275 static int btreeGetPage(
2276 BtShared *pBt, /* The btree */
2277 Pgno pgno, /* Number of the page to fetch */
2278 MemPage **ppPage, /* Return the page in this parameter */
2279 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2281 int rc;
2282 DbPage *pDbPage;
2284 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
2285 assert( sqlite3_mutex_held(pBt->mutex) );
2286 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
2287 if( rc ) return rc;
2288 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
2289 return SQLITE_OK;
2293 ** Retrieve a page from the pager cache. If the requested page is not
2294 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
2295 ** MemPage.aData elements if needed.
2297 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
2298 DbPage *pDbPage;
2299 assert( sqlite3_mutex_held(pBt->mutex) );
2300 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
2301 if( pDbPage ){
2302 return btreePageFromDbPage(pDbPage, pgno, pBt);
2304 return 0;
2308 ** Return the size of the database file in pages. If there is any kind of
2309 ** error, return ((unsigned int)-1).
2311 static Pgno btreePagecount(BtShared *pBt){
2312 return pBt->nPage;
2314 Pgno sqlite3BtreeLastPage(Btree *p){
2315 assert( sqlite3BtreeHoldsMutex(p) );
2316 return btreePagecount(p->pBt);
2320 ** Get a page from the pager and initialize it.
2322 static int getAndInitPage(
2323 BtShared *pBt, /* The database file */
2324 Pgno pgno, /* Number of the page to get */
2325 MemPage **ppPage, /* Write the page pointer here */
2326 int bReadOnly /* True for a read-only page */
2328 int rc;
2329 DbPage *pDbPage;
2330 MemPage *pPage;
2331 assert( sqlite3_mutex_held(pBt->mutex) );
2333 if( pgno>btreePagecount(pBt) ){
2334 *ppPage = 0;
2335 return SQLITE_CORRUPT_BKPT;
2337 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
2338 if( rc ){
2339 *ppPage = 0;
2340 return rc;
2342 pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2343 if( pPage->isInit==0 ){
2344 btreePageFromDbPage(pDbPage, pgno, pBt);
2345 rc = btreeInitPage(pPage);
2346 if( rc!=SQLITE_OK ){
2347 releasePage(pPage);
2348 *ppPage = 0;
2349 return rc;
2352 assert( pPage->pgno==pgno || CORRUPT_DB );
2353 assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
2354 *ppPage = pPage;
2355 return SQLITE_OK;
2359 ** Release a MemPage. This should be called once for each prior
2360 ** call to btreeGetPage.
2362 ** Page1 is a special case and must be released using releasePageOne().
2364 static void releasePageNotNull(MemPage *pPage){
2365 assert( pPage->aData );
2366 assert( pPage->pBt );
2367 assert( pPage->pDbPage!=0 );
2368 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2369 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2370 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2371 sqlite3PagerUnrefNotNull(pPage->pDbPage);
2373 static void releasePage(MemPage *pPage){
2374 if( pPage ) releasePageNotNull(pPage);
2376 static void releasePageOne(MemPage *pPage){
2377 assert( pPage!=0 );
2378 assert( pPage->aData );
2379 assert( pPage->pBt );
2380 assert( pPage->pDbPage!=0 );
2381 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2382 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2383 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2384 sqlite3PagerUnrefPageOne(pPage->pDbPage);
2388 ** Get an unused page.
2390 ** This works just like btreeGetPage() with the addition:
2392 ** * If the page is already in use for some other purpose, immediately
2393 ** release it and return an SQLITE_CURRUPT error.
2394 ** * Make sure the isInit flag is clear
2396 static int btreeGetUnusedPage(
2397 BtShared *pBt, /* The btree */
2398 Pgno pgno, /* Number of the page to fetch */
2399 MemPage **ppPage, /* Return the page in this parameter */
2400 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2402 int rc = btreeGetPage(pBt, pgno, ppPage, flags);
2403 if( rc==SQLITE_OK ){
2404 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
2405 releasePage(*ppPage);
2406 *ppPage = 0;
2407 return SQLITE_CORRUPT_BKPT;
2409 (*ppPage)->isInit = 0;
2410 }else{
2411 *ppPage = 0;
2413 return rc;
2418 ** During a rollback, when the pager reloads information into the cache
2419 ** so that the cache is restored to its original state at the start of
2420 ** the transaction, for each page restored this routine is called.
2422 ** This routine needs to reset the extra data section at the end of the
2423 ** page to agree with the restored data.
2425 static void pageReinit(DbPage *pData){
2426 MemPage *pPage;
2427 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
2428 assert( sqlite3PagerPageRefcount(pData)>0 );
2429 if( pPage->isInit ){
2430 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2431 pPage->isInit = 0;
2432 if( sqlite3PagerPageRefcount(pData)>1 ){
2433 /* pPage might not be a btree page; it might be an overflow page
2434 ** or ptrmap page or a free page. In those cases, the following
2435 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
2436 ** But no harm is done by this. And it is very important that
2437 ** btreeInitPage() be called on every btree page so we make
2438 ** the call for every page that comes in for re-initializing. */
2439 btreeInitPage(pPage);
2445 ** Invoke the busy handler for a btree.
2447 static int btreeInvokeBusyHandler(void *pArg){
2448 BtShared *pBt = (BtShared*)pArg;
2449 assert( pBt->db );
2450 assert( sqlite3_mutex_held(pBt->db->mutex) );
2451 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
2455 ** Open a database file.
2457 ** zFilename is the name of the database file. If zFilename is NULL
2458 ** then an ephemeral database is created. The ephemeral database might
2459 ** be exclusively in memory, or it might use a disk-based memory cache.
2460 ** Either way, the ephemeral database will be automatically deleted
2461 ** when sqlite3BtreeClose() is called.
2463 ** If zFilename is ":memory:" then an in-memory database is created
2464 ** that is automatically destroyed when it is closed.
2466 ** The "flags" parameter is a bitmask that might contain bits like
2467 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
2469 ** If the database is already opened in the same database connection
2470 ** and we are in shared cache mode, then the open will fail with an
2471 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
2472 ** objects in the same database connection since doing so will lead
2473 ** to problems with locking.
2475 int sqlite3BtreeOpen(
2476 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
2477 const char *zFilename, /* Name of the file containing the BTree database */
2478 sqlite3 *db, /* Associated database handle */
2479 Btree **ppBtree, /* Pointer to new Btree object written here */
2480 int flags, /* Options */
2481 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
2483 BtShared *pBt = 0; /* Shared part of btree structure */
2484 Btree *p; /* Handle to return */
2485 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
2486 int rc = SQLITE_OK; /* Result code from this function */
2487 u8 nReserve; /* Byte of unused space on each page */
2488 unsigned char zDbHeader[100]; /* Database header content */
2490 /* True if opening an ephemeral, temporary database */
2491 const int isTempDb = zFilename==0 || zFilename[0]==0;
2493 /* Set the variable isMemdb to true for an in-memory database, or
2494 ** false for a file-based database.
2496 #ifdef SQLITE_OMIT_MEMORYDB
2497 const int isMemdb = 0;
2498 #else
2499 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
2500 || (isTempDb && sqlite3TempInMemory(db))
2501 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
2502 #endif
2504 assert( db!=0 );
2505 assert( pVfs!=0 );
2506 assert( sqlite3_mutex_held(db->mutex) );
2507 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
2509 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
2510 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
2512 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
2513 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
2515 if( isMemdb ){
2516 flags |= BTREE_MEMORY;
2518 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
2519 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
2521 p = sqlite3MallocZero(sizeof(Btree));
2522 if( !p ){
2523 return SQLITE_NOMEM_BKPT;
2525 p->inTrans = TRANS_NONE;
2526 p->db = db;
2527 #ifndef SQLITE_OMIT_SHARED_CACHE
2528 p->lock.pBtree = p;
2529 p->lock.iTable = 1;
2530 #endif
2532 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2534 ** If this Btree is a candidate for shared cache, try to find an
2535 ** existing BtShared object that we can share with
2537 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
2538 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
2539 int nFilename = sqlite3Strlen30(zFilename)+1;
2540 int nFullPathname = pVfs->mxPathname+1;
2541 char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
2542 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2544 p->sharable = 1;
2545 if( !zFullPathname ){
2546 sqlite3_free(p);
2547 return SQLITE_NOMEM_BKPT;
2549 if( isMemdb ){
2550 memcpy(zFullPathname, zFilename, nFilename);
2551 }else{
2552 rc = sqlite3OsFullPathname(pVfs, zFilename,
2553 nFullPathname, zFullPathname);
2554 if( rc ){
2555 if( rc==SQLITE_OK_SYMLINK ){
2556 rc = SQLITE_OK;
2557 }else{
2558 sqlite3_free(zFullPathname);
2559 sqlite3_free(p);
2560 return rc;
2564 #if SQLITE_THREADSAFE
2565 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
2566 sqlite3_mutex_enter(mutexOpen);
2567 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
2568 sqlite3_mutex_enter(mutexShared);
2569 #endif
2570 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
2571 assert( pBt->nRef>0 );
2572 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
2573 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
2574 int iDb;
2575 for(iDb=db->nDb-1; iDb>=0; iDb--){
2576 Btree *pExisting = db->aDb[iDb].pBt;
2577 if( pExisting && pExisting->pBt==pBt ){
2578 sqlite3_mutex_leave(mutexShared);
2579 sqlite3_mutex_leave(mutexOpen);
2580 sqlite3_free(zFullPathname);
2581 sqlite3_free(p);
2582 return SQLITE_CONSTRAINT;
2585 p->pBt = pBt;
2586 pBt->nRef++;
2587 break;
2590 sqlite3_mutex_leave(mutexShared);
2591 sqlite3_free(zFullPathname);
2593 #ifdef SQLITE_DEBUG
2594 else{
2595 /* In debug mode, we mark all persistent databases as sharable
2596 ** even when they are not. This exercises the locking code and
2597 ** gives more opportunity for asserts(sqlite3_mutex_held())
2598 ** statements to find locking problems.
2600 p->sharable = 1;
2602 #endif
2604 #endif
2605 if( pBt==0 ){
2607 ** The following asserts make sure that structures used by the btree are
2608 ** the right size. This is to guard against size changes that result
2609 ** when compiling on a different architecture.
2611 assert( sizeof(i64)==8 );
2612 assert( sizeof(u64)==8 );
2613 assert( sizeof(u32)==4 );
2614 assert( sizeof(u16)==2 );
2615 assert( sizeof(Pgno)==4 );
2617 /* Suppress false-positive compiler warning from PVS-Studio */
2618 memset(&zDbHeader[16], 0, 8);
2620 pBt = sqlite3MallocZero( sizeof(*pBt) );
2621 if( pBt==0 ){
2622 rc = SQLITE_NOMEM_BKPT;
2623 goto btree_open_out;
2625 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
2626 sizeof(MemPage), flags, vfsFlags, pageReinit);
2627 if( rc==SQLITE_OK ){
2628 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
2629 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
2631 if( rc!=SQLITE_OK ){
2632 goto btree_open_out;
2634 pBt->openFlags = (u8)flags;
2635 pBt->db = db;
2636 sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
2637 p->pBt = pBt;
2639 pBt->pCursor = 0;
2640 pBt->pPage1 = 0;
2641 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
2642 #if defined(SQLITE_SECURE_DELETE)
2643 pBt->btsFlags |= BTS_SECURE_DELETE;
2644 #elif defined(SQLITE_FAST_SECURE_DELETE)
2645 pBt->btsFlags |= BTS_OVERWRITE;
2646 #endif
2647 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2648 ** determined by the 2-byte integer located at an offset of 16 bytes from
2649 ** the beginning of the database file. */
2650 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
2651 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
2652 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
2653 pBt->pageSize = 0;
2654 #ifndef SQLITE_OMIT_AUTOVACUUM
2655 /* If the magic name ":memory:" will create an in-memory database, then
2656 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
2657 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
2658 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
2659 ** regular file-name. In this case the auto-vacuum applies as per normal.
2661 if( zFilename && !isMemdb ){
2662 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
2663 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
2665 #endif
2666 nReserve = 0;
2667 }else{
2668 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2669 ** determined by the one-byte unsigned integer found at an offset of 20
2670 ** into the database file header. */
2671 nReserve = zDbHeader[20];
2672 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2673 #ifndef SQLITE_OMIT_AUTOVACUUM
2674 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
2675 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
2676 #endif
2678 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2679 if( rc ) goto btree_open_out;
2680 pBt->usableSize = pBt->pageSize - nReserve;
2681 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
2683 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2684 /* Add the new BtShared object to the linked list sharable BtShareds.
2686 pBt->nRef = 1;
2687 if( p->sharable ){
2688 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2689 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);)
2690 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
2691 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
2692 if( pBt->mutex==0 ){
2693 rc = SQLITE_NOMEM_BKPT;
2694 goto btree_open_out;
2697 sqlite3_mutex_enter(mutexShared);
2698 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2699 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
2700 sqlite3_mutex_leave(mutexShared);
2702 #endif
2705 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2706 /* If the new Btree uses a sharable pBtShared, then link the new
2707 ** Btree into the list of all sharable Btrees for the same connection.
2708 ** The list is kept in ascending order by pBt address.
2710 if( p->sharable ){
2711 int i;
2712 Btree *pSib;
2713 for(i=0; i<db->nDb; i++){
2714 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
2715 while( pSib->pPrev ){ pSib = pSib->pPrev; }
2716 if( (uptr)p->pBt<(uptr)pSib->pBt ){
2717 p->pNext = pSib;
2718 p->pPrev = 0;
2719 pSib->pPrev = p;
2720 }else{
2721 while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
2722 pSib = pSib->pNext;
2724 p->pNext = pSib->pNext;
2725 p->pPrev = pSib;
2726 if( p->pNext ){
2727 p->pNext->pPrev = p;
2729 pSib->pNext = p;
2731 break;
2735 #endif
2736 *ppBtree = p;
2738 btree_open_out:
2739 if( rc!=SQLITE_OK ){
2740 if( pBt && pBt->pPager ){
2741 sqlite3PagerClose(pBt->pPager, 0);
2743 sqlite3_free(pBt);
2744 sqlite3_free(p);
2745 *ppBtree = 0;
2746 }else{
2747 sqlite3_file *pFile;
2749 /* If the B-Tree was successfully opened, set the pager-cache size to the
2750 ** default value. Except, when opening on an existing shared pager-cache,
2751 ** do not change the pager-cache size.
2753 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
2754 sqlite3BtreeSetCacheSize(p, SQLITE_DEFAULT_CACHE_SIZE);
2757 pFile = sqlite3PagerFile(pBt->pPager);
2758 if( pFile->pMethods ){
2759 sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
2762 if( mutexOpen ){
2763 assert( sqlite3_mutex_held(mutexOpen) );
2764 sqlite3_mutex_leave(mutexOpen);
2766 assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
2767 return rc;
2771 ** Decrement the BtShared.nRef counter. When it reaches zero,
2772 ** remove the BtShared structure from the sharing list. Return
2773 ** true if the BtShared.nRef counter reaches zero and return
2774 ** false if it is still positive.
2776 static int removeFromSharingList(BtShared *pBt){
2777 #ifndef SQLITE_OMIT_SHARED_CACHE
2778 MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )
2779 BtShared *pList;
2780 int removed = 0;
2782 assert( sqlite3_mutex_notheld(pBt->mutex) );
2783 MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
2784 sqlite3_mutex_enter(pMainMtx);
2785 pBt->nRef--;
2786 if( pBt->nRef<=0 ){
2787 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2788 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
2789 }else{
2790 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
2791 while( ALWAYS(pList) && pList->pNext!=pBt ){
2792 pList=pList->pNext;
2794 if( ALWAYS(pList) ){
2795 pList->pNext = pBt->pNext;
2798 if( SQLITE_THREADSAFE ){
2799 sqlite3_mutex_free(pBt->mutex);
2801 removed = 1;
2803 sqlite3_mutex_leave(pMainMtx);
2804 return removed;
2805 #else
2806 return 1;
2807 #endif
2811 ** Make sure pBt->pTmpSpace points to an allocation of
2812 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
2813 ** pointer.
2815 static SQLITE_NOINLINE int allocateTempSpace(BtShared *pBt){
2816 assert( pBt!=0 );
2817 assert( pBt->pTmpSpace==0 );
2818 /* This routine is called only by btreeCursor() when allocating the
2819 ** first write cursor for the BtShared object */
2820 assert( pBt->pCursor!=0 && (pBt->pCursor->curFlags & BTCF_WriteFlag)!=0 );
2821 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
2822 if( pBt->pTmpSpace==0 ){
2823 BtCursor *pCur = pBt->pCursor;
2824 pBt->pCursor = pCur->pNext; /* Unlink the cursor */
2825 memset(pCur, 0, sizeof(*pCur));
2826 return SQLITE_NOMEM_BKPT;
2829 /* One of the uses of pBt->pTmpSpace is to format cells before
2830 ** inserting them into a leaf page (function fillInCell()). If
2831 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
2832 ** by the various routines that manipulate binary cells. Which
2833 ** can mean that fillInCell() only initializes the first 2 or 3
2834 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
2835 ** it into a database page. This is not actually a problem, but it
2836 ** does cause a valgrind error when the 1 or 2 bytes of uninitialized
2837 ** data is passed to system call write(). So to avoid this error,
2838 ** zero the first 4 bytes of temp space here.
2840 ** Also: Provide four bytes of initialized space before the
2841 ** beginning of pTmpSpace as an area available to prepend the
2842 ** left-child pointer to the beginning of a cell.
2844 memset(pBt->pTmpSpace, 0, 8);
2845 pBt->pTmpSpace += 4;
2846 return SQLITE_OK;
2850 ** Free the pBt->pTmpSpace allocation
2852 static void freeTempSpace(BtShared *pBt){
2853 if( pBt->pTmpSpace ){
2854 pBt->pTmpSpace -= 4;
2855 sqlite3PageFree(pBt->pTmpSpace);
2856 pBt->pTmpSpace = 0;
2861 ** Close an open database and invalidate all cursors.
2863 int sqlite3BtreeClose(Btree *p){
2864 BtShared *pBt = p->pBt;
2866 /* Close all cursors opened via this handle. */
2867 assert( sqlite3_mutex_held(p->db->mutex) );
2868 sqlite3BtreeEnter(p);
2870 /* Verify that no other cursors have this Btree open */
2871 #ifdef SQLITE_DEBUG
2873 BtCursor *pCur = pBt->pCursor;
2874 while( pCur ){
2875 BtCursor *pTmp = pCur;
2876 pCur = pCur->pNext;
2877 assert( pTmp->pBtree!=p );
2881 #endif
2883 /* Rollback any active transaction and free the handle structure.
2884 ** The call to sqlite3BtreeRollback() drops any table-locks held by
2885 ** this handle.
2887 sqlite3BtreeRollback(p, SQLITE_OK, 0);
2888 sqlite3BtreeLeave(p);
2890 /* If there are still other outstanding references to the shared-btree
2891 ** structure, return now. The remainder of this procedure cleans
2892 ** up the shared-btree.
2894 assert( p->wantToLock==0 && p->locked==0 );
2895 if( !p->sharable || removeFromSharingList(pBt) ){
2896 /* The pBt is no longer on the sharing list, so we can access
2897 ** it without having to hold the mutex.
2899 ** Clean out and delete the BtShared object.
2901 assert( !pBt->pCursor );
2902 sqlite3PagerClose(pBt->pPager, p->db);
2903 if( pBt->xFreeSchema && pBt->pSchema ){
2904 pBt->xFreeSchema(pBt->pSchema);
2906 sqlite3DbFree(0, pBt->pSchema);
2907 freeTempSpace(pBt);
2908 sqlite3_free(pBt);
2911 #ifndef SQLITE_OMIT_SHARED_CACHE
2912 assert( p->wantToLock==0 );
2913 assert( p->locked==0 );
2914 if( p->pPrev ) p->pPrev->pNext = p->pNext;
2915 if( p->pNext ) p->pNext->pPrev = p->pPrev;
2916 #endif
2918 sqlite3_free(p);
2919 return SQLITE_OK;
2923 ** Change the "soft" limit on the number of pages in the cache.
2924 ** Unused and unmodified pages will be recycled when the number of
2925 ** pages in the cache exceeds this soft limit. But the size of the
2926 ** cache is allowed to grow larger than this limit if it contains
2927 ** dirty pages or pages still in active use.
2929 int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2930 BtShared *pBt = p->pBt;
2931 assert( sqlite3_mutex_held(p->db->mutex) );
2932 sqlite3BtreeEnter(p);
2933 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
2934 sqlite3BtreeLeave(p);
2935 return SQLITE_OK;
2939 ** Change the "spill" limit on the number of pages in the cache.
2940 ** If the number of pages exceeds this limit during a write transaction,
2941 ** the pager might attempt to "spill" pages to the journal early in
2942 ** order to free up memory.
2944 ** The value returned is the current spill size. If zero is passed
2945 ** as an argument, no changes are made to the spill size setting, so
2946 ** using mxPage of 0 is a way to query the current spill size.
2948 int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
2949 BtShared *pBt = p->pBt;
2950 int res;
2951 assert( sqlite3_mutex_held(p->db->mutex) );
2952 sqlite3BtreeEnter(p);
2953 res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
2954 sqlite3BtreeLeave(p);
2955 return res;
2958 #if SQLITE_MAX_MMAP_SIZE>0
2960 ** Change the limit on the amount of the database file that may be
2961 ** memory mapped.
2963 int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
2964 BtShared *pBt = p->pBt;
2965 assert( sqlite3_mutex_held(p->db->mutex) );
2966 sqlite3BtreeEnter(p);
2967 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
2968 sqlite3BtreeLeave(p);
2969 return SQLITE_OK;
2971 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
2974 ** Change the way data is synced to disk in order to increase or decrease
2975 ** how well the database resists damage due to OS crashes and power
2976 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
2977 ** there is a high probability of damage) Level 2 is the default. There
2978 ** is a very low but non-zero probability of damage. Level 3 reduces the
2979 ** probability of damage to near zero but with a write performance reduction.
2981 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
2982 int sqlite3BtreeSetPagerFlags(
2983 Btree *p, /* The btree to set the safety level on */
2984 unsigned pgFlags /* Various PAGER_* flags */
2986 BtShared *pBt = p->pBt;
2987 assert( sqlite3_mutex_held(p->db->mutex) );
2988 sqlite3BtreeEnter(p);
2989 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
2990 sqlite3BtreeLeave(p);
2991 return SQLITE_OK;
2993 #endif
2996 ** Change the default pages size and the number of reserved bytes per page.
2997 ** Or, if the page size has already been fixed, return SQLITE_READONLY
2998 ** without changing anything.
3000 ** The page size must be a power of 2 between 512 and 65536. If the page
3001 ** size supplied does not meet this constraint then the page size is not
3002 ** changed.
3004 ** Page sizes are constrained to be a power of two so that the region
3005 ** of the database file used for locking (beginning at PENDING_BYTE,
3006 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
3007 ** at the beginning of a page.
3009 ** If parameter nReserve is less than zero, then the number of reserved
3010 ** bytes per page is left unchanged.
3012 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
3013 ** and autovacuum mode can no longer be changed.
3015 int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
3016 int rc = SQLITE_OK;
3017 int x;
3018 BtShared *pBt = p->pBt;
3019 assert( nReserve>=0 && nReserve<=255 );
3020 sqlite3BtreeEnter(p);
3021 pBt->nReserveWanted = nReserve;
3022 x = pBt->pageSize - pBt->usableSize;
3023 if( nReserve<x ) nReserve = x;
3024 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
3025 sqlite3BtreeLeave(p);
3026 return SQLITE_READONLY;
3028 assert( nReserve>=0 && nReserve<=255 );
3029 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
3030 ((pageSize-1)&pageSize)==0 ){
3031 assert( (pageSize & 7)==0 );
3032 assert( !pBt->pCursor );
3033 if( nReserve>32 && pageSize==512 ) pageSize = 1024;
3034 pBt->pageSize = (u32)pageSize;
3035 freeTempSpace(pBt);
3037 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
3038 pBt->usableSize = pBt->pageSize - (u16)nReserve;
3039 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3040 sqlite3BtreeLeave(p);
3041 return rc;
3045 ** Return the currently defined page size
3047 int sqlite3BtreeGetPageSize(Btree *p){
3048 return p->pBt->pageSize;
3052 ** This function is similar to sqlite3BtreeGetReserve(), except that it
3053 ** may only be called if it is guaranteed that the b-tree mutex is already
3054 ** held.
3056 ** This is useful in one special case in the backup API code where it is
3057 ** known that the shared b-tree mutex is held, but the mutex on the
3058 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
3059 ** were to be called, it might collide with some other operation on the
3060 ** database handle that owns *p, causing undefined behavior.
3062 int sqlite3BtreeGetReserveNoMutex(Btree *p){
3063 int n;
3064 assert( sqlite3_mutex_held(p->pBt->mutex) );
3065 n = p->pBt->pageSize - p->pBt->usableSize;
3066 return n;
3070 ** Return the number of bytes of space at the end of every page that
3071 ** are intentionally left unused. This is the "reserved" space that is
3072 ** sometimes used by extensions.
3074 ** The value returned is the larger of the current reserve size and
3075 ** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES.
3076 ** The amount of reserve can only grow - never shrink.
3078 int sqlite3BtreeGetRequestedReserve(Btree *p){
3079 int n1, n2;
3080 sqlite3BtreeEnter(p);
3081 n1 = (int)p->pBt->nReserveWanted;
3082 n2 = sqlite3BtreeGetReserveNoMutex(p);
3083 sqlite3BtreeLeave(p);
3084 return n1>n2 ? n1 : n2;
3089 ** Set the maximum page count for a database if mxPage is positive.
3090 ** No changes are made if mxPage is 0 or negative.
3091 ** Regardless of the value of mxPage, return the maximum page count.
3093 Pgno sqlite3BtreeMaxPageCount(Btree *p, Pgno mxPage){
3094 Pgno n;
3095 sqlite3BtreeEnter(p);
3096 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
3097 sqlite3BtreeLeave(p);
3098 return n;
3102 ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
3104 ** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
3105 ** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
3106 ** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
3107 ** newFlag==(-1) No changes
3109 ** This routine acts as a query if newFlag is less than zero
3111 ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
3112 ** freelist leaf pages are not written back to the database. Thus in-page
3113 ** deleted content is cleared, but freelist deleted content is not.
3115 ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
3116 ** that freelist leaf pages are written back into the database, increasing
3117 ** the amount of disk I/O.
3119 int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
3120 int b;
3121 if( p==0 ) return 0;
3122 sqlite3BtreeEnter(p);
3123 assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
3124 assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
3125 if( newFlag>=0 ){
3126 p->pBt->btsFlags &= ~BTS_FAST_SECURE;
3127 p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
3129 b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
3130 sqlite3BtreeLeave(p);
3131 return b;
3135 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
3136 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
3137 ** is disabled. The default value for the auto-vacuum property is
3138 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
3140 int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
3141 #ifdef SQLITE_OMIT_AUTOVACUUM
3142 return SQLITE_READONLY;
3143 #else
3144 BtShared *pBt = p->pBt;
3145 int rc = SQLITE_OK;
3146 u8 av = (u8)autoVacuum;
3148 sqlite3BtreeEnter(p);
3149 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
3150 rc = SQLITE_READONLY;
3151 }else{
3152 pBt->autoVacuum = av ?1:0;
3153 pBt->incrVacuum = av==2 ?1:0;
3155 sqlite3BtreeLeave(p);
3156 return rc;
3157 #endif
3161 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
3162 ** enabled 1 is returned. Otherwise 0.
3164 int sqlite3BtreeGetAutoVacuum(Btree *p){
3165 #ifdef SQLITE_OMIT_AUTOVACUUM
3166 return BTREE_AUTOVACUUM_NONE;
3167 #else
3168 int rc;
3169 sqlite3BtreeEnter(p);
3170 rc = (
3171 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
3172 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
3173 BTREE_AUTOVACUUM_INCR
3175 sqlite3BtreeLeave(p);
3176 return rc;
3177 #endif
3181 ** If the user has not set the safety-level for this database connection
3182 ** using "PRAGMA synchronous", and if the safety-level is not already
3183 ** set to the value passed to this function as the second parameter,
3184 ** set it so.
3186 #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
3187 && !defined(SQLITE_OMIT_WAL)
3188 static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
3189 sqlite3 *db;
3190 Db *pDb;
3191 if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
3192 while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
3193 if( pDb->bSyncSet==0
3194 && pDb->safety_level!=safety_level
3195 && pDb!=&db->aDb[1]
3197 pDb->safety_level = safety_level;
3198 sqlite3PagerSetFlags(pBt->pPager,
3199 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
3203 #else
3204 # define setDefaultSyncFlag(pBt,safety_level)
3205 #endif
3207 /* Forward declaration */
3208 static int newDatabase(BtShared*);
3212 ** Get a reference to pPage1 of the database file. This will
3213 ** also acquire a readlock on that file.
3215 ** SQLITE_OK is returned on success. If the file is not a
3216 ** well-formed database file, then SQLITE_CORRUPT is returned.
3217 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
3218 ** is returned if we run out of memory.
3220 static int lockBtree(BtShared *pBt){
3221 int rc; /* Result code from subfunctions */
3222 MemPage *pPage1; /* Page 1 of the database file */
3223 u32 nPage; /* Number of pages in the database */
3224 u32 nPageFile = 0; /* Number of pages in the database file */
3226 assert( sqlite3_mutex_held(pBt->mutex) );
3227 assert( pBt->pPage1==0 );
3228 rc = sqlite3PagerSharedLock(pBt->pPager);
3229 if( rc!=SQLITE_OK ) return rc;
3230 rc = btreeGetPage(pBt, 1, &pPage1, 0);
3231 if( rc!=SQLITE_OK ) return rc;
3233 /* Do some checking to help insure the file we opened really is
3234 ** a valid database file.
3236 nPage = get4byte(28+(u8*)pPage1->aData);
3237 sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
3238 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
3239 nPage = nPageFile;
3241 if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
3242 nPage = 0;
3244 if( nPage>0 ){
3245 u32 pageSize;
3246 u32 usableSize;
3247 u8 *page1 = pPage1->aData;
3248 rc = SQLITE_NOTADB;
3249 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
3250 ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
3251 ** 61 74 20 33 00. */
3252 if( memcmp(page1, zMagicHeader, 16)!=0 ){
3253 goto page1_init_failed;
3256 #ifdef SQLITE_OMIT_WAL
3257 if( page1[18]>1 ){
3258 pBt->btsFlags |= BTS_READ_ONLY;
3260 if( page1[19]>1 ){
3261 goto page1_init_failed;
3263 #else
3264 if( page1[18]>2 ){
3265 pBt->btsFlags |= BTS_READ_ONLY;
3267 if( page1[19]>2 ){
3268 goto page1_init_failed;
3271 /* If the read version is set to 2, this database should be accessed
3272 ** in WAL mode. If the log is not already open, open it now. Then
3273 ** return SQLITE_OK and return without populating BtShared.pPage1.
3274 ** The caller detects this and calls this function again. This is
3275 ** required as the version of page 1 currently in the page1 buffer
3276 ** may not be the latest version - there may be a newer one in the log
3277 ** file.
3279 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
3280 int isOpen = 0;
3281 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
3282 if( rc!=SQLITE_OK ){
3283 goto page1_init_failed;
3284 }else{
3285 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
3286 if( isOpen==0 ){
3287 releasePageOne(pPage1);
3288 return SQLITE_OK;
3291 rc = SQLITE_NOTADB;
3292 }else{
3293 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
3295 #endif
3297 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
3298 ** fractions and the leaf payload fraction values must be 64, 32, and 32.
3300 ** The original design allowed these amounts to vary, but as of
3301 ** version 3.6.0, we require them to be fixed.
3303 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
3304 goto page1_init_failed;
3306 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
3307 ** determined by the 2-byte integer located at an offset of 16 bytes from
3308 ** the beginning of the database file. */
3309 pageSize = (page1[16]<<8) | (page1[17]<<16);
3310 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
3311 ** between 512 and 65536 inclusive. */
3312 if( ((pageSize-1)&pageSize)!=0
3313 || pageSize>SQLITE_MAX_PAGE_SIZE
3314 || pageSize<=256
3316 goto page1_init_failed;
3318 assert( (pageSize & 7)==0 );
3319 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
3320 ** integer at offset 20 is the number of bytes of space at the end of
3321 ** each page to reserve for extensions.
3323 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
3324 ** determined by the one-byte unsigned integer found at an offset of 20
3325 ** into the database file header. */
3326 usableSize = pageSize - page1[20];
3327 if( (u32)pageSize!=pBt->pageSize ){
3328 /* After reading the first page of the database assuming a page size
3329 ** of BtShared.pageSize, we have discovered that the page-size is
3330 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
3331 ** zero and return SQLITE_OK. The caller will call this function
3332 ** again with the correct page-size.
3334 releasePageOne(pPage1);
3335 pBt->usableSize = usableSize;
3336 pBt->pageSize = pageSize;
3337 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3338 freeTempSpace(pBt);
3339 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
3340 pageSize-usableSize);
3341 return rc;
3343 if( nPage>nPageFile ){
3344 if( sqlite3WritableSchema(pBt->db)==0 ){
3345 rc = SQLITE_CORRUPT_BKPT;
3346 goto page1_init_failed;
3347 }else{
3348 nPage = nPageFile;
3351 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
3352 ** be less than 480. In other words, if the page size is 512, then the
3353 ** reserved space size cannot exceed 32. */
3354 if( usableSize<480 ){
3355 goto page1_init_failed;
3357 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3358 pBt->pageSize = pageSize;
3359 pBt->usableSize = usableSize;
3360 #ifndef SQLITE_OMIT_AUTOVACUUM
3361 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
3362 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
3363 #endif
3366 /* maxLocal is the maximum amount of payload to store locally for
3367 ** a cell. Make sure it is small enough so that at least minFanout
3368 ** cells can will fit on one page. We assume a 10-byte page header.
3369 ** Besides the payload, the cell must store:
3370 ** 2-byte pointer to the cell
3371 ** 4-byte child pointer
3372 ** 9-byte nKey value
3373 ** 4-byte nData value
3374 ** 4-byte overflow page pointer
3375 ** So a cell consists of a 2-byte pointer, a header which is as much as
3376 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
3377 ** page pointer.
3379 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
3380 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
3381 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
3382 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
3383 if( pBt->maxLocal>127 ){
3384 pBt->max1bytePayload = 127;
3385 }else{
3386 pBt->max1bytePayload = (u8)pBt->maxLocal;
3388 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
3389 pBt->pPage1 = pPage1;
3390 pBt->nPage = nPage;
3391 return SQLITE_OK;
3393 page1_init_failed:
3394 releasePageOne(pPage1);
3395 pBt->pPage1 = 0;
3396 return rc;
3399 #ifndef NDEBUG
3401 ** Return the number of cursors open on pBt. This is for use
3402 ** in assert() expressions, so it is only compiled if NDEBUG is not
3403 ** defined.
3405 ** Only write cursors are counted if wrOnly is true. If wrOnly is
3406 ** false then all cursors are counted.
3408 ** For the purposes of this routine, a cursor is any cursor that
3409 ** is capable of reading or writing to the database. Cursors that
3410 ** have been tripped into the CURSOR_FAULT state are not counted.
3412 static int countValidCursors(BtShared *pBt, int wrOnly){
3413 BtCursor *pCur;
3414 int r = 0;
3415 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3416 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
3417 && pCur->eState!=CURSOR_FAULT ) r++;
3419 return r;
3421 #endif
3424 ** If there are no outstanding cursors and we are not in the middle
3425 ** of a transaction but there is a read lock on the database, then
3426 ** this routine unrefs the first page of the database file which
3427 ** has the effect of releasing the read lock.
3429 ** If there is a transaction in progress, this routine is a no-op.
3431 static void unlockBtreeIfUnused(BtShared *pBt){
3432 assert( sqlite3_mutex_held(pBt->mutex) );
3433 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
3434 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
3435 MemPage *pPage1 = pBt->pPage1;
3436 assert( pPage1->aData );
3437 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
3438 pBt->pPage1 = 0;
3439 releasePageOne(pPage1);
3444 ** If pBt points to an empty file then convert that empty file
3445 ** into a new empty database by initializing the first page of
3446 ** the database.
3448 static int newDatabase(BtShared *pBt){
3449 MemPage *pP1;
3450 unsigned char *data;
3451 int rc;
3453 assert( sqlite3_mutex_held(pBt->mutex) );
3454 if( pBt->nPage>0 ){
3455 return SQLITE_OK;
3457 pP1 = pBt->pPage1;
3458 assert( pP1!=0 );
3459 data = pP1->aData;
3460 rc = sqlite3PagerWrite(pP1->pDbPage);
3461 if( rc ) return rc;
3462 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
3463 assert( sizeof(zMagicHeader)==16 );
3464 data[16] = (u8)((pBt->pageSize>>8)&0xff);
3465 data[17] = (u8)((pBt->pageSize>>16)&0xff);
3466 data[18] = 1;
3467 data[19] = 1;
3468 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
3469 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
3470 data[21] = 64;
3471 data[22] = 32;
3472 data[23] = 32;
3473 memset(&data[24], 0, 100-24);
3474 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
3475 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3476 #ifndef SQLITE_OMIT_AUTOVACUUM
3477 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
3478 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
3479 put4byte(&data[36 + 4*4], pBt->autoVacuum);
3480 put4byte(&data[36 + 7*4], pBt->incrVacuum);
3481 #endif
3482 pBt->nPage = 1;
3483 data[31] = 1;
3484 return SQLITE_OK;
3488 ** Initialize the first page of the database file (creating a database
3489 ** consisting of a single page and no schema objects). Return SQLITE_OK
3490 ** if successful, or an SQLite error code otherwise.
3492 int sqlite3BtreeNewDb(Btree *p){
3493 int rc;
3494 sqlite3BtreeEnter(p);
3495 p->pBt->nPage = 0;
3496 rc = newDatabase(p->pBt);
3497 sqlite3BtreeLeave(p);
3498 return rc;
3502 ** Attempt to start a new transaction. A write-transaction
3503 ** is started if the second argument is nonzero, otherwise a read-
3504 ** transaction. If the second argument is 2 or more and exclusive
3505 ** transaction is started, meaning that no other process is allowed
3506 ** to access the database. A preexisting transaction may not be
3507 ** upgraded to exclusive by calling this routine a second time - the
3508 ** exclusivity flag only works for a new transaction.
3510 ** A write-transaction must be started before attempting any
3511 ** changes to the database. None of the following routines
3512 ** will work unless a transaction is started first:
3514 ** sqlite3BtreeCreateTable()
3515 ** sqlite3BtreeCreateIndex()
3516 ** sqlite3BtreeClearTable()
3517 ** sqlite3BtreeDropTable()
3518 ** sqlite3BtreeInsert()
3519 ** sqlite3BtreeDelete()
3520 ** sqlite3BtreeUpdateMeta()
3522 ** If an initial attempt to acquire the lock fails because of lock contention
3523 ** and the database was previously unlocked, then invoke the busy handler
3524 ** if there is one. But if there was previously a read-lock, do not
3525 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
3526 ** returned when there is already a read-lock in order to avoid a deadlock.
3528 ** Suppose there are two processes A and B. A has a read lock and B has
3529 ** a reserved lock. B tries to promote to exclusive but is blocked because
3530 ** of A's read lock. A tries to promote to reserved but is blocked by B.
3531 ** One or the other of the two processes must give way or there can be
3532 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
3533 ** when A already has a read lock, we encourage A to give up and let B
3534 ** proceed.
3536 static SQLITE_NOINLINE int btreeBeginTrans(
3537 Btree *p, /* The btree in which to start the transaction */
3538 int wrflag, /* True to start a write transaction */
3539 int *pSchemaVersion /* Put schema version number here, if not NULL */
3541 BtShared *pBt = p->pBt;
3542 Pager *pPager = pBt->pPager;
3543 int rc = SQLITE_OK;
3545 sqlite3BtreeEnter(p);
3546 btreeIntegrity(p);
3548 /* If the btree is already in a write-transaction, or it
3549 ** is already in a read-transaction and a read-transaction
3550 ** is requested, this is a no-op.
3552 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
3553 goto trans_begun;
3555 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
3557 if( (p->db->flags & SQLITE_ResetDatabase)
3558 && sqlite3PagerIsreadonly(pPager)==0
3560 pBt->btsFlags &= ~BTS_READ_ONLY;
3563 /* Write transactions are not possible on a read-only database */
3564 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
3565 rc = SQLITE_READONLY;
3566 goto trans_begun;
3569 #ifndef SQLITE_OMIT_SHARED_CACHE
3571 sqlite3 *pBlock = 0;
3572 /* If another database handle has already opened a write transaction
3573 ** on this shared-btree structure and a second write transaction is
3574 ** requested, return SQLITE_LOCKED.
3576 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
3577 || (pBt->btsFlags & BTS_PENDING)!=0
3579 pBlock = pBt->pWriter->db;
3580 }else if( wrflag>1 ){
3581 BtLock *pIter;
3582 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
3583 if( pIter->pBtree!=p ){
3584 pBlock = pIter->pBtree->db;
3585 break;
3589 if( pBlock ){
3590 sqlite3ConnectionBlocked(p->db, pBlock);
3591 rc = SQLITE_LOCKED_SHAREDCACHE;
3592 goto trans_begun;
3595 #endif
3597 /* Any read-only or read-write transaction implies a read-lock on
3598 ** page 1. So if some other shared-cache client already has a write-lock
3599 ** on page 1, the transaction cannot be opened. */
3600 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
3601 if( SQLITE_OK!=rc ) goto trans_begun;
3603 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
3604 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
3605 do {
3606 sqlite3PagerWalDb(pPager, p->db);
3608 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3609 /* If transitioning from no transaction directly to a write transaction,
3610 ** block for the WRITER lock first if possible. */
3611 if( pBt->pPage1==0 && wrflag ){
3612 assert( pBt->inTransaction==TRANS_NONE );
3613 rc = sqlite3PagerWalWriteLock(pPager, 1);
3614 if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break;
3616 #endif
3618 /* Call lockBtree() until either pBt->pPage1 is populated or
3619 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
3620 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
3621 ** reading page 1 it discovers that the page-size of the database
3622 ** file is not pBt->pageSize. In this case lockBtree() will update
3623 ** pBt->pageSize to the page-size of the file on disk.
3625 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
3627 if( rc==SQLITE_OK && wrflag ){
3628 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
3629 rc = SQLITE_READONLY;
3630 }else{
3631 rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db));
3632 if( rc==SQLITE_OK ){
3633 rc = newDatabase(pBt);
3634 }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
3635 /* if there was no transaction opened when this function was
3636 ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
3637 ** code to SQLITE_BUSY. */
3638 rc = SQLITE_BUSY;
3643 if( rc!=SQLITE_OK ){
3644 (void)sqlite3PagerWalWriteLock(pPager, 0);
3645 unlockBtreeIfUnused(pBt);
3647 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
3648 btreeInvokeBusyHandler(pBt) );
3649 sqlite3PagerWalDb(pPager, 0);
3650 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3651 if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
3652 #endif
3654 if( rc==SQLITE_OK ){
3655 if( p->inTrans==TRANS_NONE ){
3656 pBt->nTransaction++;
3657 #ifndef SQLITE_OMIT_SHARED_CACHE
3658 if( p->sharable ){
3659 assert( p->lock.pBtree==p && p->lock.iTable==1 );
3660 p->lock.eLock = READ_LOCK;
3661 p->lock.pNext = pBt->pLock;
3662 pBt->pLock = &p->lock;
3664 #endif
3666 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
3667 if( p->inTrans>pBt->inTransaction ){
3668 pBt->inTransaction = p->inTrans;
3670 if( wrflag ){
3671 MemPage *pPage1 = pBt->pPage1;
3672 #ifndef SQLITE_OMIT_SHARED_CACHE
3673 assert( !pBt->pWriter );
3674 pBt->pWriter = p;
3675 pBt->btsFlags &= ~BTS_EXCLUSIVE;
3676 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
3677 #endif
3679 /* If the db-size header field is incorrect (as it may be if an old
3680 ** client has been writing the database file), update it now. Doing
3681 ** this sooner rather than later means the database size can safely
3682 ** re-read the database size from page 1 if a savepoint or transaction
3683 ** rollback occurs within the transaction.
3685 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
3686 rc = sqlite3PagerWrite(pPage1->pDbPage);
3687 if( rc==SQLITE_OK ){
3688 put4byte(&pPage1->aData[28], pBt->nPage);
3694 trans_begun:
3695 if( rc==SQLITE_OK ){
3696 if( pSchemaVersion ){
3697 *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
3699 if( wrflag ){
3700 /* This call makes sure that the pager has the correct number of
3701 ** open savepoints. If the second parameter is greater than 0 and
3702 ** the sub-journal is not already open, then it will be opened here.
3704 rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint);
3708 btreeIntegrity(p);
3709 sqlite3BtreeLeave(p);
3710 return rc;
3712 int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
3713 BtShared *pBt;
3714 if( p->sharable
3715 || p->inTrans==TRANS_NONE
3716 || (p->inTrans==TRANS_READ && wrflag!=0)
3718 return btreeBeginTrans(p,wrflag,pSchemaVersion);
3720 pBt = p->pBt;
3721 if( pSchemaVersion ){
3722 *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
3724 if( wrflag ){
3725 /* This call makes sure that the pager has the correct number of
3726 ** open savepoints. If the second parameter is greater than 0 and
3727 ** the sub-journal is not already open, then it will be opened here.
3729 return sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
3730 }else{
3731 return SQLITE_OK;
3735 #ifndef SQLITE_OMIT_AUTOVACUUM
3738 ** Set the pointer-map entries for all children of page pPage. Also, if
3739 ** pPage contains cells that point to overflow pages, set the pointer
3740 ** map entries for the overflow pages as well.
3742 static int setChildPtrmaps(MemPage *pPage){
3743 int i; /* Counter variable */
3744 int nCell; /* Number of cells in page pPage */
3745 int rc; /* Return code */
3746 BtShared *pBt = pPage->pBt;
3747 Pgno pgno = pPage->pgno;
3749 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3750 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3751 if( rc!=SQLITE_OK ) return rc;
3752 nCell = pPage->nCell;
3754 for(i=0; i<nCell; i++){
3755 u8 *pCell = findCell(pPage, i);
3757 ptrmapPutOvflPtr(pPage, pPage, pCell, &rc);
3759 if( !pPage->leaf ){
3760 Pgno childPgno = get4byte(pCell);
3761 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3765 if( !pPage->leaf ){
3766 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
3767 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3770 return rc;
3774 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
3775 ** that it points to iTo. Parameter eType describes the type of pointer to
3776 ** be modified, as follows:
3778 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
3779 ** page of pPage.
3781 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3782 ** page pointed to by one of the cells on pPage.
3784 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3785 ** overflow page in the list.
3787 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
3788 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3789 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
3790 if( eType==PTRMAP_OVERFLOW2 ){
3791 /* The pointer is always the first 4 bytes of the page in this case. */
3792 if( get4byte(pPage->aData)!=iFrom ){
3793 return SQLITE_CORRUPT_PAGE(pPage);
3795 put4byte(pPage->aData, iTo);
3796 }else{
3797 int i;
3798 int nCell;
3799 int rc;
3801 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3802 if( rc ) return rc;
3803 nCell = pPage->nCell;
3805 for(i=0; i<nCell; i++){
3806 u8 *pCell = findCell(pPage, i);
3807 if( eType==PTRMAP_OVERFLOW1 ){
3808 CellInfo info;
3809 pPage->xParseCell(pPage, pCell, &info);
3810 if( info.nLocal<info.nPayload ){
3811 if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
3812 return SQLITE_CORRUPT_PAGE(pPage);
3814 if( iFrom==get4byte(pCell+info.nSize-4) ){
3815 put4byte(pCell+info.nSize-4, iTo);
3816 break;
3819 }else{
3820 if( pCell+4 > pPage->aData+pPage->pBt->usableSize ){
3821 return SQLITE_CORRUPT_PAGE(pPage);
3823 if( get4byte(pCell)==iFrom ){
3824 put4byte(pCell, iTo);
3825 break;
3830 if( i==nCell ){
3831 if( eType!=PTRMAP_BTREE ||
3832 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
3833 return SQLITE_CORRUPT_PAGE(pPage);
3835 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3838 return SQLITE_OK;
3843 ** Move the open database page pDbPage to location iFreePage in the
3844 ** database. The pDbPage reference remains valid.
3846 ** The isCommit flag indicates that there is no need to remember that
3847 ** the journal needs to be sync()ed before database page pDbPage->pgno
3848 ** can be written to. The caller has already promised not to write to that
3849 ** page.
3851 static int relocatePage(
3852 BtShared *pBt, /* Btree */
3853 MemPage *pDbPage, /* Open page to move */
3854 u8 eType, /* Pointer map 'type' entry for pDbPage */
3855 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
3856 Pgno iFreePage, /* The location to move pDbPage to */
3857 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
3859 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
3860 Pgno iDbPage = pDbPage->pgno;
3861 Pager *pPager = pBt->pPager;
3862 int rc;
3864 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3865 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
3866 assert( sqlite3_mutex_held(pBt->mutex) );
3867 assert( pDbPage->pBt==pBt );
3868 if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
3870 /* Move page iDbPage from its current location to page number iFreePage */
3871 TRACE(("AUTOVACUUM: Moving %u to free page %u (ptr page %u type %u)\n",
3872 iDbPage, iFreePage, iPtrPage, eType));
3873 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
3874 if( rc!=SQLITE_OK ){
3875 return rc;
3877 pDbPage->pgno = iFreePage;
3879 /* If pDbPage was a btree-page, then it may have child pages and/or cells
3880 ** that point to overflow pages. The pointer map entries for all these
3881 ** pages need to be changed.
3883 ** If pDbPage is an overflow page, then the first 4 bytes may store a
3884 ** pointer to a subsequent overflow page. If this is the case, then
3885 ** the pointer map needs to be updated for the subsequent overflow page.
3887 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
3888 rc = setChildPtrmaps(pDbPage);
3889 if( rc!=SQLITE_OK ){
3890 return rc;
3892 }else{
3893 Pgno nextOvfl = get4byte(pDbPage->aData);
3894 if( nextOvfl!=0 ){
3895 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
3896 if( rc!=SQLITE_OK ){
3897 return rc;
3902 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3903 ** that it points at iFreePage. Also fix the pointer map entry for
3904 ** iPtrPage.
3906 if( eType!=PTRMAP_ROOTPAGE ){
3907 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
3908 if( rc!=SQLITE_OK ){
3909 return rc;
3911 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
3912 if( rc!=SQLITE_OK ){
3913 releasePage(pPtrPage);
3914 return rc;
3916 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
3917 releasePage(pPtrPage);
3918 if( rc==SQLITE_OK ){
3919 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
3922 return rc;
3925 /* Forward declaration required by incrVacuumStep(). */
3926 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
3929 ** Perform a single step of an incremental-vacuum. If successful, return
3930 ** SQLITE_OK. If there is no work to do (and therefore no point in
3931 ** calling this function again), return SQLITE_DONE. Or, if an error
3932 ** occurs, return some other error code.
3934 ** More specifically, this function attempts to re-organize the database so
3935 ** that the last page of the file currently in use is no longer in use.
3937 ** Parameter nFin is the number of pages that this database would contain
3938 ** were this function called until it returns SQLITE_DONE.
3940 ** If the bCommit parameter is non-zero, this function assumes that the
3941 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
3942 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
3943 ** operation, or false for an incremental vacuum.
3945 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
3946 Pgno nFreeList; /* Number of pages still on the free-list */
3947 int rc;
3949 assert( sqlite3_mutex_held(pBt->mutex) );
3950 assert( iLastPg>nFin );
3952 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
3953 u8 eType;
3954 Pgno iPtrPage;
3956 nFreeList = get4byte(&pBt->pPage1->aData[36]);
3957 if( nFreeList==0 ){
3958 return SQLITE_DONE;
3961 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3962 if( rc!=SQLITE_OK ){
3963 return rc;
3965 if( eType==PTRMAP_ROOTPAGE ){
3966 return SQLITE_CORRUPT_BKPT;
3969 if( eType==PTRMAP_FREEPAGE ){
3970 if( bCommit==0 ){
3971 /* Remove the page from the files free-list. This is not required
3972 ** if bCommit is non-zero. In that case, the free-list will be
3973 ** truncated to zero after this function returns, so it doesn't
3974 ** matter if it still contains some garbage entries.
3976 Pgno iFreePg;
3977 MemPage *pFreePg;
3978 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
3979 if( rc!=SQLITE_OK ){
3980 return rc;
3982 assert( iFreePg==iLastPg );
3983 releasePage(pFreePg);
3985 } else {
3986 Pgno iFreePg; /* Index of free page to move pLastPg to */
3987 MemPage *pLastPg;
3988 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
3989 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
3991 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
3992 if( rc!=SQLITE_OK ){
3993 return rc;
3996 /* If bCommit is zero, this loop runs exactly once and page pLastPg
3997 ** is swapped with the first free page pulled off the free list.
3999 ** On the other hand, if bCommit is greater than zero, then keep
4000 ** looping until a free-page located within the first nFin pages
4001 ** of the file is found.
4003 if( bCommit==0 ){
4004 eMode = BTALLOC_LE;
4005 iNear = nFin;
4007 do {
4008 MemPage *pFreePg;
4009 Pgno dbSize = btreePagecount(pBt);
4010 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
4011 if( rc!=SQLITE_OK ){
4012 releasePage(pLastPg);
4013 return rc;
4015 releasePage(pFreePg);
4016 if( iFreePg>dbSize ){
4017 releasePage(pLastPg);
4018 return SQLITE_CORRUPT_BKPT;
4020 }while( bCommit && iFreePg>nFin );
4021 assert( iFreePg<iLastPg );
4023 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
4024 releasePage(pLastPg);
4025 if( rc!=SQLITE_OK ){
4026 return rc;
4031 if( bCommit==0 ){
4032 do {
4033 iLastPg--;
4034 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
4035 pBt->bDoTruncate = 1;
4036 pBt->nPage = iLastPg;
4038 return SQLITE_OK;
4042 ** The database opened by the first argument is an auto-vacuum database
4043 ** nOrig pages in size containing nFree free pages. Return the expected
4044 ** size of the database in pages following an auto-vacuum operation.
4046 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
4047 int nEntry; /* Number of entries on one ptrmap page */
4048 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
4049 Pgno nFin; /* Return value */
4051 nEntry = pBt->usableSize/5;
4052 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
4053 nFin = nOrig - nFree - nPtrmap;
4054 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
4055 nFin--;
4057 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
4058 nFin--;
4061 return nFin;
4065 ** A write-transaction must be opened before calling this function.
4066 ** It performs a single unit of work towards an incremental vacuum.
4068 ** If the incremental vacuum is finished after this function has run,
4069 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
4070 ** SQLITE_OK is returned. Otherwise an SQLite error code.
4072 int sqlite3BtreeIncrVacuum(Btree *p){
4073 int rc;
4074 BtShared *pBt = p->pBt;
4076 sqlite3BtreeEnter(p);
4077 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
4078 if( !pBt->autoVacuum ){
4079 rc = SQLITE_DONE;
4080 }else{
4081 Pgno nOrig = btreePagecount(pBt);
4082 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
4083 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
4085 if( nOrig<nFin || nFree>=nOrig ){
4086 rc = SQLITE_CORRUPT_BKPT;
4087 }else if( nFree>0 ){
4088 rc = saveAllCursors(pBt, 0, 0);
4089 if( rc==SQLITE_OK ){
4090 invalidateAllOverflowCache(pBt);
4091 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
4093 if( rc==SQLITE_OK ){
4094 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
4095 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
4097 }else{
4098 rc = SQLITE_DONE;
4101 sqlite3BtreeLeave(p);
4102 return rc;
4106 ** This routine is called prior to sqlite3PagerCommit when a transaction
4107 ** is committed for an auto-vacuum database.
4109 static int autoVacuumCommit(Btree *p){
4110 int rc = SQLITE_OK;
4111 Pager *pPager;
4112 BtShared *pBt;
4113 sqlite3 *db;
4114 VVA_ONLY( int nRef );
4116 assert( p!=0 );
4117 pBt = p->pBt;
4118 pPager = pBt->pPager;
4119 VVA_ONLY( nRef = sqlite3PagerRefcount(pPager); )
4121 assert( sqlite3_mutex_held(pBt->mutex) );
4122 invalidateAllOverflowCache(pBt);
4123 assert(pBt->autoVacuum);
4124 if( !pBt->incrVacuum ){
4125 Pgno nFin; /* Number of pages in database after autovacuuming */
4126 Pgno nFree; /* Number of pages on the freelist initially */
4127 Pgno nVac; /* Number of pages to vacuum */
4128 Pgno iFree; /* The next page to be freed */
4129 Pgno nOrig; /* Database size before freeing */
4131 nOrig = btreePagecount(pBt);
4132 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
4133 /* It is not possible to create a database for which the final page
4134 ** is either a pointer-map page or the pending-byte page. If one
4135 ** is encountered, this indicates corruption.
4137 return SQLITE_CORRUPT_BKPT;
4140 nFree = get4byte(&pBt->pPage1->aData[36]);
4141 db = p->db;
4142 if( db->xAutovacPages ){
4143 int iDb;
4144 for(iDb=0; ALWAYS(iDb<db->nDb); iDb++){
4145 if( db->aDb[iDb].pBt==p ) break;
4147 nVac = db->xAutovacPages(
4148 db->pAutovacPagesArg,
4149 db->aDb[iDb].zDbSName,
4150 nOrig,
4151 nFree,
4152 pBt->pageSize
4154 if( nVac>nFree ){
4155 nVac = nFree;
4157 if( nVac==0 ){
4158 return SQLITE_OK;
4160 }else{
4161 nVac = nFree;
4163 nFin = finalDbSize(pBt, nOrig, nVac);
4164 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
4165 if( nFin<nOrig ){
4166 rc = saveAllCursors(pBt, 0, 0);
4168 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
4169 rc = incrVacuumStep(pBt, nFin, iFree, nVac==nFree);
4171 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
4172 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
4173 if( nVac==nFree ){
4174 put4byte(&pBt->pPage1->aData[32], 0);
4175 put4byte(&pBt->pPage1->aData[36], 0);
4177 put4byte(&pBt->pPage1->aData[28], nFin);
4178 pBt->bDoTruncate = 1;
4179 pBt->nPage = nFin;
4181 if( rc!=SQLITE_OK ){
4182 sqlite3PagerRollback(pPager);
4186 assert( nRef>=sqlite3PagerRefcount(pPager) );
4187 return rc;
4190 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
4191 # define setChildPtrmaps(x) SQLITE_OK
4192 #endif
4195 ** This routine does the first phase of a two-phase commit. This routine
4196 ** causes a rollback journal to be created (if it does not already exist)
4197 ** and populated with enough information so that if a power loss occurs
4198 ** the database can be restored to its original state by playing back
4199 ** the journal. Then the contents of the journal are flushed out to
4200 ** the disk. After the journal is safely on oxide, the changes to the
4201 ** database are written into the database file and flushed to oxide.
4202 ** At the end of this call, the rollback journal still exists on the
4203 ** disk and we are still holding all locks, so the transaction has not
4204 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
4205 ** commit process.
4207 ** This call is a no-op if no write-transaction is currently active on pBt.
4209 ** Otherwise, sync the database file for the btree pBt. zSuperJrnl points to
4210 ** the name of a super-journal file that should be written into the
4211 ** individual journal file, or is NULL, indicating no super-journal file
4212 ** (single database transaction).
4214 ** When this is called, the super-journal should already have been
4215 ** created, populated with this journal pointer and synced to disk.
4217 ** Once this is routine has returned, the only thing required to commit
4218 ** the write-transaction for this database file is to delete the journal.
4220 int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zSuperJrnl){
4221 int rc = SQLITE_OK;
4222 if( p->inTrans==TRANS_WRITE ){
4223 BtShared *pBt = p->pBt;
4224 sqlite3BtreeEnter(p);
4225 #ifndef SQLITE_OMIT_AUTOVACUUM
4226 if( pBt->autoVacuum ){
4227 rc = autoVacuumCommit(p);
4228 if( rc!=SQLITE_OK ){
4229 sqlite3BtreeLeave(p);
4230 return rc;
4233 if( pBt->bDoTruncate ){
4234 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
4236 #endif
4237 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0);
4238 sqlite3BtreeLeave(p);
4240 return rc;
4244 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
4245 ** at the conclusion of a transaction.
4247 static void btreeEndTransaction(Btree *p){
4248 BtShared *pBt = p->pBt;
4249 sqlite3 *db = p->db;
4250 assert( sqlite3BtreeHoldsMutex(p) );
4252 #ifndef SQLITE_OMIT_AUTOVACUUM
4253 pBt->bDoTruncate = 0;
4254 #endif
4255 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
4256 /* If there are other active statements that belong to this database
4257 ** handle, downgrade to a read-only transaction. The other statements
4258 ** may still be reading from the database. */
4259 downgradeAllSharedCacheTableLocks(p);
4260 p->inTrans = TRANS_READ;
4261 }else{
4262 /* If the handle had any kind of transaction open, decrement the
4263 ** transaction count of the shared btree. If the transaction count
4264 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
4265 ** call below will unlock the pager. */
4266 if( p->inTrans!=TRANS_NONE ){
4267 clearAllSharedCacheTableLocks(p);
4268 pBt->nTransaction--;
4269 if( 0==pBt->nTransaction ){
4270 pBt->inTransaction = TRANS_NONE;
4274 /* Set the current transaction state to TRANS_NONE and unlock the
4275 ** pager if this call closed the only read or write transaction. */
4276 p->inTrans = TRANS_NONE;
4277 unlockBtreeIfUnused(pBt);
4280 btreeIntegrity(p);
4284 ** Commit the transaction currently in progress.
4286 ** This routine implements the second phase of a 2-phase commit. The
4287 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
4288 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
4289 ** routine did all the work of writing information out to disk and flushing the
4290 ** contents so that they are written onto the disk platter. All this
4291 ** routine has to do is delete or truncate or zero the header in the
4292 ** the rollback journal (which causes the transaction to commit) and
4293 ** drop locks.
4295 ** Normally, if an error occurs while the pager layer is attempting to
4296 ** finalize the underlying journal file, this function returns an error and
4297 ** the upper layer will attempt a rollback. However, if the second argument
4298 ** is non-zero then this b-tree transaction is part of a multi-file
4299 ** transaction. In this case, the transaction has already been committed
4300 ** (by deleting a super-journal file) and the caller will ignore this
4301 ** functions return code. So, even if an error occurs in the pager layer,
4302 ** reset the b-tree objects internal state to indicate that the write
4303 ** transaction has been closed. This is quite safe, as the pager will have
4304 ** transitioned to the error state.
4306 ** This will release the write lock on the database file. If there
4307 ** are no active cursors, it also releases the read lock.
4309 int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
4311 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
4312 sqlite3BtreeEnter(p);
4313 btreeIntegrity(p);
4315 /* If the handle has a write-transaction open, commit the shared-btrees
4316 ** transaction and set the shared state to TRANS_READ.
4318 if( p->inTrans==TRANS_WRITE ){
4319 int rc;
4320 BtShared *pBt = p->pBt;
4321 assert( pBt->inTransaction==TRANS_WRITE );
4322 assert( pBt->nTransaction>0 );
4323 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
4324 if( rc!=SQLITE_OK && bCleanup==0 ){
4325 sqlite3BtreeLeave(p);
4326 return rc;
4328 p->iBDataVersion--; /* Compensate for pPager->iDataVersion++; */
4329 pBt->inTransaction = TRANS_READ;
4330 btreeClearHasContent(pBt);
4333 btreeEndTransaction(p);
4334 sqlite3BtreeLeave(p);
4335 return SQLITE_OK;
4339 ** Do both phases of a commit.
4341 int sqlite3BtreeCommit(Btree *p){
4342 int rc;
4343 sqlite3BtreeEnter(p);
4344 rc = sqlite3BtreeCommitPhaseOne(p, 0);
4345 if( rc==SQLITE_OK ){
4346 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
4348 sqlite3BtreeLeave(p);
4349 return rc;
4353 ** This routine sets the state to CURSOR_FAULT and the error
4354 ** code to errCode for every cursor on any BtShared that pBtree
4355 ** references. Or if the writeOnly flag is set to 1, then only
4356 ** trip write cursors and leave read cursors unchanged.
4358 ** Every cursor is a candidate to be tripped, including cursors
4359 ** that belong to other database connections that happen to be
4360 ** sharing the cache with pBtree.
4362 ** This routine gets called when a rollback occurs. If the writeOnly
4363 ** flag is true, then only write-cursors need be tripped - read-only
4364 ** cursors save their current positions so that they may continue
4365 ** following the rollback. Or, if writeOnly is false, all cursors are
4366 ** tripped. In general, writeOnly is false if the transaction being
4367 ** rolled back modified the database schema. In this case b-tree root
4368 ** pages may be moved or deleted from the database altogether, making
4369 ** it unsafe for read cursors to continue.
4371 ** If the writeOnly flag is true and an error is encountered while
4372 ** saving the current position of a read-only cursor, all cursors,
4373 ** including all read-cursors are tripped.
4375 ** SQLITE_OK is returned if successful, or if an error occurs while
4376 ** saving a cursor position, an SQLite error code.
4378 int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
4379 BtCursor *p;
4380 int rc = SQLITE_OK;
4382 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
4383 if( pBtree ){
4384 sqlite3BtreeEnter(pBtree);
4385 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
4386 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
4387 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
4388 rc = saveCursorPosition(p);
4389 if( rc!=SQLITE_OK ){
4390 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
4391 break;
4394 }else{
4395 sqlite3BtreeClearCursor(p);
4396 p->eState = CURSOR_FAULT;
4397 p->skipNext = errCode;
4399 btreeReleaseAllCursorPages(p);
4401 sqlite3BtreeLeave(pBtree);
4403 return rc;
4407 ** Set the pBt->nPage field correctly, according to the current
4408 ** state of the database. Assume pBt->pPage1 is valid.
4410 static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){
4411 int nPage = get4byte(&pPage1->aData[28]);
4412 testcase( nPage==0 );
4413 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
4414 testcase( pBt->nPage!=(u32)nPage );
4415 pBt->nPage = nPage;
4419 ** Rollback the transaction in progress.
4421 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
4422 ** Only write cursors are tripped if writeOnly is true but all cursors are
4423 ** tripped if writeOnly is false. Any attempt to use
4424 ** a tripped cursor will result in an error.
4426 ** This will release the write lock on the database file. If there
4427 ** are no active cursors, it also releases the read lock.
4429 int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
4430 int rc;
4431 BtShared *pBt = p->pBt;
4432 MemPage *pPage1;
4434 assert( writeOnly==1 || writeOnly==0 );
4435 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
4436 sqlite3BtreeEnter(p);
4437 if( tripCode==SQLITE_OK ){
4438 rc = tripCode = saveAllCursors(pBt, 0, 0);
4439 if( rc ) writeOnly = 0;
4440 }else{
4441 rc = SQLITE_OK;
4443 if( tripCode ){
4444 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
4445 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
4446 if( rc2!=SQLITE_OK ) rc = rc2;
4448 btreeIntegrity(p);
4450 if( p->inTrans==TRANS_WRITE ){
4451 int rc2;
4453 assert( TRANS_WRITE==pBt->inTransaction );
4454 rc2 = sqlite3PagerRollback(pBt->pPager);
4455 if( rc2!=SQLITE_OK ){
4456 rc = rc2;
4459 /* The rollback may have destroyed the pPage1->aData value. So
4460 ** call btreeGetPage() on page 1 again to make
4461 ** sure pPage1->aData is set correctly. */
4462 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
4463 btreeSetNPage(pBt, pPage1);
4464 releasePageOne(pPage1);
4466 assert( countValidCursors(pBt, 1)==0 );
4467 pBt->inTransaction = TRANS_READ;
4468 btreeClearHasContent(pBt);
4471 btreeEndTransaction(p);
4472 sqlite3BtreeLeave(p);
4473 return rc;
4477 ** Start a statement subtransaction. The subtransaction can be rolled
4478 ** back independently of the main transaction. You must start a transaction
4479 ** before starting a subtransaction. The subtransaction is ended automatically
4480 ** if the main transaction commits or rolls back.
4482 ** Statement subtransactions are used around individual SQL statements
4483 ** that are contained within a BEGIN...COMMIT block. If a constraint
4484 ** error occurs within the statement, the effect of that one statement
4485 ** can be rolled back without having to rollback the entire transaction.
4487 ** A statement sub-transaction is implemented as an anonymous savepoint. The
4488 ** value passed as the second parameter is the total number of savepoints,
4489 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
4490 ** are no active savepoints and no other statement-transactions open,
4491 ** iStatement is 1. This anonymous savepoint can be released or rolled back
4492 ** using the sqlite3BtreeSavepoint() function.
4494 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
4495 int rc;
4496 BtShared *pBt = p->pBt;
4497 sqlite3BtreeEnter(p);
4498 assert( p->inTrans==TRANS_WRITE );
4499 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
4500 assert( iStatement>0 );
4501 assert( iStatement>p->db->nSavepoint );
4502 assert( pBt->inTransaction==TRANS_WRITE );
4503 /* At the pager level, a statement transaction is a savepoint with
4504 ** an index greater than all savepoints created explicitly using
4505 ** SQL statements. It is illegal to open, release or rollback any
4506 ** such savepoints while the statement transaction savepoint is active.
4508 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
4509 sqlite3BtreeLeave(p);
4510 return rc;
4514 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
4515 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
4516 ** savepoint identified by parameter iSavepoint, depending on the value
4517 ** of op.
4519 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
4520 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
4521 ** contents of the entire transaction are rolled back. This is different
4522 ** from a normal transaction rollback, as no locks are released and the
4523 ** transaction remains open.
4525 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
4526 int rc = SQLITE_OK;
4527 if( p && p->inTrans==TRANS_WRITE ){
4528 BtShared *pBt = p->pBt;
4529 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
4530 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
4531 sqlite3BtreeEnter(p);
4532 if( op==SAVEPOINT_ROLLBACK ){
4533 rc = saveAllCursors(pBt, 0, 0);
4535 if( rc==SQLITE_OK ){
4536 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
4538 if( rc==SQLITE_OK ){
4539 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
4540 pBt->nPage = 0;
4542 rc = newDatabase(pBt);
4543 btreeSetNPage(pBt, pBt->pPage1);
4545 /* pBt->nPage might be zero if the database was corrupt when
4546 ** the transaction was started. Otherwise, it must be at least 1. */
4547 assert( CORRUPT_DB || pBt->nPage>0 );
4549 sqlite3BtreeLeave(p);
4551 return rc;
4555 ** Create a new cursor for the BTree whose root is on the page
4556 ** iTable. If a read-only cursor is requested, it is assumed that
4557 ** the caller already has at least a read-only transaction open
4558 ** on the database already. If a write-cursor is requested, then
4559 ** the caller is assumed to have an open write transaction.
4561 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
4562 ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
4563 ** can be used for reading or for writing if other conditions for writing
4564 ** are also met. These are the conditions that must be met in order
4565 ** for writing to be allowed:
4567 ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
4569 ** 2: Other database connections that share the same pager cache
4570 ** but which are not in the READ_UNCOMMITTED state may not have
4571 ** cursors open with wrFlag==0 on the same table. Otherwise
4572 ** the changes made by this write cursor would be visible to
4573 ** the read cursors in the other database connection.
4575 ** 3: The database must be writable (not on read-only media)
4577 ** 4: There must be an active transaction.
4579 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
4580 ** is set. If FORDELETE is set, that is a hint to the implementation that
4581 ** this cursor will only be used to seek to and delete entries of an index
4582 ** as part of a larger DELETE statement. The FORDELETE hint is not used by
4583 ** this implementation. But in a hypothetical alternative storage engine
4584 ** in which index entries are automatically deleted when corresponding table
4585 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
4586 ** operations on this cursor can be no-ops and all READ operations can
4587 ** return a null row (2-bytes: 0x01 0x00).
4589 ** No checking is done to make sure that page iTable really is the
4590 ** root page of a b-tree. If it is not, then the cursor acquired
4591 ** will not work correctly.
4593 ** It is assumed that the sqlite3BtreeCursorZero() has been called
4594 ** on pCur to initialize the memory space prior to invoking this routine.
4596 static int btreeCursor(
4597 Btree *p, /* The btree */
4598 Pgno iTable, /* Root page of table to open */
4599 int wrFlag, /* 1 to write. 0 read-only */
4600 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4601 BtCursor *pCur /* Space for new cursor */
4603 BtShared *pBt = p->pBt; /* Shared b-tree handle */
4604 BtCursor *pX; /* Looping over other all cursors */
4606 assert( sqlite3BtreeHoldsMutex(p) );
4607 assert( wrFlag==0
4608 || wrFlag==BTREE_WRCSR
4609 || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
4612 /* The following assert statements verify that if this is a sharable
4613 ** b-tree database, the connection is holding the required table locks,
4614 ** and that no other connection has any open cursor that conflicts with
4615 ** this lock. The iTable<1 term disables the check for corrupt schemas. */
4616 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1))
4617 || iTable<1 );
4618 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
4620 /* Assert that the caller has opened the required transaction. */
4621 assert( p->inTrans>TRANS_NONE );
4622 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
4623 assert( pBt->pPage1 && pBt->pPage1->aData );
4624 assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
4626 if( iTable<=1 ){
4627 if( iTable<1 ){
4628 return SQLITE_CORRUPT_BKPT;
4629 }else if( btreePagecount(pBt)==0 ){
4630 assert( wrFlag==0 );
4631 iTable = 0;
4635 /* Now that no other errors can occur, finish filling in the BtCursor
4636 ** variables and link the cursor into the BtShared list. */
4637 pCur->pgnoRoot = iTable;
4638 pCur->iPage = -1;
4639 pCur->pKeyInfo = pKeyInfo;
4640 pCur->pBtree = p;
4641 pCur->pBt = pBt;
4642 pCur->curFlags = 0;
4643 /* If there are two or more cursors on the same btree, then all such
4644 ** cursors *must* have the BTCF_Multiple flag set. */
4645 for(pX=pBt->pCursor; pX; pX=pX->pNext){
4646 if( pX->pgnoRoot==iTable ){
4647 pX->curFlags |= BTCF_Multiple;
4648 pCur->curFlags = BTCF_Multiple;
4651 pCur->eState = CURSOR_INVALID;
4652 pCur->pNext = pBt->pCursor;
4653 pBt->pCursor = pCur;
4654 if( wrFlag ){
4655 pCur->curFlags |= BTCF_WriteFlag;
4656 pCur->curPagerFlags = 0;
4657 if( pBt->pTmpSpace==0 ) return allocateTempSpace(pBt);
4658 }else{
4659 pCur->curPagerFlags = PAGER_GET_READONLY;
4661 return SQLITE_OK;
4663 static int btreeCursorWithLock(
4664 Btree *p, /* The btree */
4665 Pgno iTable, /* Root page of table to open */
4666 int wrFlag, /* 1 to write. 0 read-only */
4667 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4668 BtCursor *pCur /* Space for new cursor */
4670 int rc;
4671 sqlite3BtreeEnter(p);
4672 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4673 sqlite3BtreeLeave(p);
4674 return rc;
4676 int sqlite3BtreeCursor(
4677 Btree *p, /* The btree */
4678 Pgno iTable, /* Root page of table to open */
4679 int wrFlag, /* 1 to write. 0 read-only */
4680 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
4681 BtCursor *pCur /* Write new cursor here */
4683 if( p->sharable ){
4684 return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur);
4685 }else{
4686 return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4691 ** Return the size of a BtCursor object in bytes.
4693 ** This interfaces is needed so that users of cursors can preallocate
4694 ** sufficient storage to hold a cursor. The BtCursor object is opaque
4695 ** to users so they cannot do the sizeof() themselves - they must call
4696 ** this routine.
4698 int sqlite3BtreeCursorSize(void){
4699 return ROUND8(sizeof(BtCursor));
4703 ** Initialize memory that will be converted into a BtCursor object.
4705 ** The simple approach here would be to memset() the entire object
4706 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
4707 ** do not need to be zeroed and they are large, so we can save a lot
4708 ** of run-time by skipping the initialization of those elements.
4710 void sqlite3BtreeCursorZero(BtCursor *p){
4711 memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
4715 ** Close a cursor. The read lock on the database file is released
4716 ** when the last cursor is closed.
4718 int sqlite3BtreeCloseCursor(BtCursor *pCur){
4719 Btree *pBtree = pCur->pBtree;
4720 if( pBtree ){
4721 BtShared *pBt = pCur->pBt;
4722 sqlite3BtreeEnter(pBtree);
4723 assert( pBt->pCursor!=0 );
4724 if( pBt->pCursor==pCur ){
4725 pBt->pCursor = pCur->pNext;
4726 }else{
4727 BtCursor *pPrev = pBt->pCursor;
4729 if( pPrev->pNext==pCur ){
4730 pPrev->pNext = pCur->pNext;
4731 break;
4733 pPrev = pPrev->pNext;
4734 }while( ALWAYS(pPrev) );
4736 btreeReleaseAllCursorPages(pCur);
4737 unlockBtreeIfUnused(pBt);
4738 sqlite3_free(pCur->aOverflow);
4739 sqlite3_free(pCur->pKey);
4740 if( (pBt->openFlags & BTREE_SINGLE) && pBt->pCursor==0 ){
4741 /* Since the BtShared is not sharable, there is no need to
4742 ** worry about the missing sqlite3BtreeLeave() call here. */
4743 assert( pBtree->sharable==0 );
4744 sqlite3BtreeClose(pBtree);
4745 }else{
4746 sqlite3BtreeLeave(pBtree);
4748 pCur->pBtree = 0;
4750 return SQLITE_OK;
4754 ** Make sure the BtCursor* given in the argument has a valid
4755 ** BtCursor.info structure. If it is not already valid, call
4756 ** btreeParseCell() to fill it in.
4758 ** BtCursor.info is a cache of the information in the current cell.
4759 ** Using this cache reduces the number of calls to btreeParseCell().
4761 #ifndef NDEBUG
4762 static int cellInfoEqual(CellInfo *a, CellInfo *b){
4763 if( a->nKey!=b->nKey ) return 0;
4764 if( a->pPayload!=b->pPayload ) return 0;
4765 if( a->nPayload!=b->nPayload ) return 0;
4766 if( a->nLocal!=b->nLocal ) return 0;
4767 if( a->nSize!=b->nSize ) return 0;
4768 return 1;
4770 static void assertCellInfo(BtCursor *pCur){
4771 CellInfo info;
4772 memset(&info, 0, sizeof(info));
4773 btreeParseCell(pCur->pPage, pCur->ix, &info);
4774 assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
4776 #else
4777 #define assertCellInfo(x)
4778 #endif
4779 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
4780 if( pCur->info.nSize==0 ){
4781 pCur->curFlags |= BTCF_ValidNKey;
4782 btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
4783 }else{
4784 assertCellInfo(pCur);
4788 #ifndef NDEBUG /* The next routine used only within assert() statements */
4790 ** Return true if the given BtCursor is valid. A valid cursor is one
4791 ** that is currently pointing to a row in a (non-empty) table.
4792 ** This is a verification routine is used only within assert() statements.
4794 int sqlite3BtreeCursorIsValid(BtCursor *pCur){
4795 return pCur && pCur->eState==CURSOR_VALID;
4797 #endif /* NDEBUG */
4798 int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
4799 assert( pCur!=0 );
4800 return pCur->eState==CURSOR_VALID;
4804 ** Return the value of the integer key or "rowid" for a table btree.
4805 ** This routine is only valid for a cursor that is pointing into a
4806 ** ordinary table btree. If the cursor points to an index btree or
4807 ** is invalid, the result of this routine is undefined.
4809 i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
4810 assert( cursorHoldsMutex(pCur) );
4811 assert( pCur->eState==CURSOR_VALID );
4812 assert( pCur->curIntKey );
4813 getCellInfo(pCur);
4814 return pCur->info.nKey;
4818 ** Pin or unpin a cursor.
4820 void sqlite3BtreeCursorPin(BtCursor *pCur){
4821 assert( (pCur->curFlags & BTCF_Pinned)==0 );
4822 pCur->curFlags |= BTCF_Pinned;
4824 void sqlite3BtreeCursorUnpin(BtCursor *pCur){
4825 assert( (pCur->curFlags & BTCF_Pinned)!=0 );
4826 pCur->curFlags &= ~BTCF_Pinned;
4830 ** Return the offset into the database file for the start of the
4831 ** payload to which the cursor is pointing.
4833 i64 sqlite3BtreeOffset(BtCursor *pCur){
4834 assert( cursorHoldsMutex(pCur) );
4835 assert( pCur->eState==CURSOR_VALID );
4836 getCellInfo(pCur);
4837 return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
4838 (i64)(pCur->info.pPayload - pCur->pPage->aData);
4842 ** Return the number of bytes of payload for the entry that pCur is
4843 ** currently pointing to. For table btrees, this will be the amount
4844 ** of data. For index btrees, this will be the size of the key.
4846 ** The caller must guarantee that the cursor is pointing to a non-NULL
4847 ** valid entry. In other words, the calling procedure must guarantee
4848 ** that the cursor has Cursor.eState==CURSOR_VALID.
4850 u32 sqlite3BtreePayloadSize(BtCursor *pCur){
4851 assert( cursorHoldsMutex(pCur) );
4852 assert( pCur->eState==CURSOR_VALID );
4853 getCellInfo(pCur);
4854 return pCur->info.nPayload;
4858 ** Return an upper bound on the size of any record for the table
4859 ** that the cursor is pointing into.
4861 ** This is an optimization. Everything will still work if this
4862 ** routine always returns 2147483647 (which is the largest record
4863 ** that SQLite can handle) or more. But returning a smaller value might
4864 ** prevent large memory allocations when trying to interpret a
4865 ** corrupt database.
4867 ** The current implementation merely returns the size of the underlying
4868 ** database file.
4870 sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){
4871 assert( cursorHoldsMutex(pCur) );
4872 assert( pCur->eState==CURSOR_VALID );
4873 return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
4877 ** Given the page number of an overflow page in the database (parameter
4878 ** ovfl), this function finds the page number of the next page in the
4879 ** linked list of overflow pages. If possible, it uses the auto-vacuum
4880 ** pointer-map data instead of reading the content of page ovfl to do so.
4882 ** If an error occurs an SQLite error code is returned. Otherwise:
4884 ** The page number of the next overflow page in the linked list is
4885 ** written to *pPgnoNext. If page ovfl is the last page in its linked
4886 ** list, *pPgnoNext is set to zero.
4888 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
4889 ** to page number pOvfl was obtained, then *ppPage is set to point to that
4890 ** reference. It is the responsibility of the caller to call releasePage()
4891 ** on *ppPage to free the reference. In no reference was obtained (because
4892 ** the pointer-map was used to obtain the value for *pPgnoNext), then
4893 ** *ppPage is set to zero.
4895 static int getOverflowPage(
4896 BtShared *pBt, /* The database file */
4897 Pgno ovfl, /* Current overflow page number */
4898 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
4899 Pgno *pPgnoNext /* OUT: Next overflow page number */
4901 Pgno next = 0;
4902 MemPage *pPage = 0;
4903 int rc = SQLITE_OK;
4905 assert( sqlite3_mutex_held(pBt->mutex) );
4906 assert(pPgnoNext);
4908 #ifndef SQLITE_OMIT_AUTOVACUUM
4909 /* Try to find the next page in the overflow list using the
4910 ** autovacuum pointer-map pages. Guess that the next page in
4911 ** the overflow list is page number (ovfl+1). If that guess turns
4912 ** out to be wrong, fall back to loading the data of page
4913 ** number ovfl to determine the next page number.
4915 if( pBt->autoVacuum ){
4916 Pgno pgno;
4917 Pgno iGuess = ovfl+1;
4918 u8 eType;
4920 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
4921 iGuess++;
4924 if( iGuess<=btreePagecount(pBt) ){
4925 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
4926 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
4927 next = iGuess;
4928 rc = SQLITE_DONE;
4932 #endif
4934 assert( next==0 || rc==SQLITE_DONE );
4935 if( rc==SQLITE_OK ){
4936 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
4937 assert( rc==SQLITE_OK || pPage==0 );
4938 if( rc==SQLITE_OK ){
4939 next = get4byte(pPage->aData);
4943 *pPgnoNext = next;
4944 if( ppPage ){
4945 *ppPage = pPage;
4946 }else{
4947 releasePage(pPage);
4949 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
4953 ** Copy data from a buffer to a page, or from a page to a buffer.
4955 ** pPayload is a pointer to data stored on database page pDbPage.
4956 ** If argument eOp is false, then nByte bytes of data are copied
4957 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4958 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4959 ** of data are copied from the buffer pBuf to pPayload.
4961 ** SQLITE_OK is returned on success, otherwise an error code.
4963 static int copyPayload(
4964 void *pPayload, /* Pointer to page data */
4965 void *pBuf, /* Pointer to buffer */
4966 int nByte, /* Number of bytes to copy */
4967 int eOp, /* 0 -> copy from page, 1 -> copy to page */
4968 DbPage *pDbPage /* Page containing pPayload */
4970 if( eOp ){
4971 /* Copy data from buffer to page (a write operation) */
4972 int rc = sqlite3PagerWrite(pDbPage);
4973 if( rc!=SQLITE_OK ){
4974 return rc;
4976 memcpy(pPayload, pBuf, nByte);
4977 }else{
4978 /* Copy data from page to buffer (a read operation) */
4979 memcpy(pBuf, pPayload, nByte);
4981 return SQLITE_OK;
4985 ** This function is used to read or overwrite payload information
4986 ** for the entry that the pCur cursor is pointing to. The eOp
4987 ** argument is interpreted as follows:
4989 ** 0: The operation is a read. Populate the overflow cache.
4990 ** 1: The operation is a write. Populate the overflow cache.
4992 ** A total of "amt" bytes are read or written beginning at "offset".
4993 ** Data is read to or from the buffer pBuf.
4995 ** The content being read or written might appear on the main page
4996 ** or be scattered out on multiple overflow pages.
4998 ** If the current cursor entry uses one or more overflow pages
4999 ** this function may allocate space for and lazily populate
5000 ** the overflow page-list cache array (BtCursor.aOverflow).
5001 ** Subsequent calls use this cache to make seeking to the supplied offset
5002 ** more efficient.
5004 ** Once an overflow page-list cache has been allocated, it must be
5005 ** invalidated if some other cursor writes to the same table, or if
5006 ** the cursor is moved to a different row. Additionally, in auto-vacuum
5007 ** mode, the following events may invalidate an overflow page-list cache.
5009 ** * An incremental vacuum,
5010 ** * A commit in auto_vacuum="full" mode,
5011 ** * Creating a table (may require moving an overflow page).
5013 static int accessPayload(
5014 BtCursor *pCur, /* Cursor pointing to entry to read from */
5015 u32 offset, /* Begin reading this far into payload */
5016 u32 amt, /* Read this many bytes */
5017 unsigned char *pBuf, /* Write the bytes into this buffer */
5018 int eOp /* zero to read. non-zero to write. */
5020 unsigned char *aPayload;
5021 int rc = SQLITE_OK;
5022 int iIdx = 0;
5023 MemPage *pPage = pCur->pPage; /* Btree page of current entry */
5024 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
5025 #ifdef SQLITE_DIRECT_OVERFLOW_READ
5026 unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
5027 #endif
5029 assert( pPage );
5030 assert( eOp==0 || eOp==1 );
5031 assert( pCur->eState==CURSOR_VALID );
5032 if( pCur->ix>=pPage->nCell ){
5033 return SQLITE_CORRUPT_PAGE(pPage);
5035 assert( cursorHoldsMutex(pCur) );
5037 getCellInfo(pCur);
5038 aPayload = pCur->info.pPayload;
5039 assert( offset+amt <= pCur->info.nPayload );
5041 assert( aPayload > pPage->aData );
5042 if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
5043 /* Trying to read or write past the end of the data is an error. The
5044 ** conditional above is really:
5045 ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
5046 ** but is recast into its current form to avoid integer overflow problems
5048 return SQLITE_CORRUPT_PAGE(pPage);
5051 /* Check if data must be read/written to/from the btree page itself. */
5052 if( offset<pCur->info.nLocal ){
5053 int a = amt;
5054 if( a+offset>pCur->info.nLocal ){
5055 a = pCur->info.nLocal - offset;
5057 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
5058 offset = 0;
5059 pBuf += a;
5060 amt -= a;
5061 }else{
5062 offset -= pCur->info.nLocal;
5066 if( rc==SQLITE_OK && amt>0 ){
5067 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
5068 Pgno nextPage;
5070 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
5072 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
5074 ** The aOverflow[] array is sized at one entry for each overflow page
5075 ** in the overflow chain. The page number of the first overflow page is
5076 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
5077 ** means "not yet known" (the cache is lazily populated).
5079 if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
5080 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
5081 if( pCur->aOverflow==0
5082 || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
5084 Pgno *aNew = (Pgno*)sqlite3Realloc(
5085 pCur->aOverflow, nOvfl*2*sizeof(Pgno)
5087 if( aNew==0 ){
5088 return SQLITE_NOMEM_BKPT;
5089 }else{
5090 pCur->aOverflow = aNew;
5093 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
5094 pCur->curFlags |= BTCF_ValidOvfl;
5095 }else{
5096 /* If the overflow page-list cache has been allocated and the
5097 ** entry for the first required overflow page is valid, skip
5098 ** directly to it.
5100 if( pCur->aOverflow[offset/ovflSize] ){
5101 iIdx = (offset/ovflSize);
5102 nextPage = pCur->aOverflow[iIdx];
5103 offset = (offset%ovflSize);
5107 assert( rc==SQLITE_OK && amt>0 );
5108 while( nextPage ){
5109 /* If required, populate the overflow page-list cache. */
5110 if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPT;
5111 assert( pCur->aOverflow[iIdx]==0
5112 || pCur->aOverflow[iIdx]==nextPage
5113 || CORRUPT_DB );
5114 pCur->aOverflow[iIdx] = nextPage;
5116 if( offset>=ovflSize ){
5117 /* The only reason to read this page is to obtain the page
5118 ** number for the next page in the overflow chain. The page
5119 ** data is not required. So first try to lookup the overflow
5120 ** page-list cache, if any, then fall back to the getOverflowPage()
5121 ** function.
5123 assert( pCur->curFlags & BTCF_ValidOvfl );
5124 assert( pCur->pBtree->db==pBt->db );
5125 if( pCur->aOverflow[iIdx+1] ){
5126 nextPage = pCur->aOverflow[iIdx+1];
5127 }else{
5128 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
5130 offset -= ovflSize;
5131 }else{
5132 /* Need to read this page properly. It contains some of the
5133 ** range of data that is being read (eOp==0) or written (eOp!=0).
5135 int a = amt;
5136 if( a + offset > ovflSize ){
5137 a = ovflSize - offset;
5140 #ifdef SQLITE_DIRECT_OVERFLOW_READ
5141 /* If all the following are true:
5143 ** 1) this is a read operation, and
5144 ** 2) data is required from the start of this overflow page, and
5145 ** 3) there are no dirty pages in the page-cache
5146 ** 4) the database is file-backed, and
5147 ** 5) the page is not in the WAL file
5148 ** 6) at least 4 bytes have already been read into the output buffer
5150 ** then data can be read directly from the database file into the
5151 ** output buffer, bypassing the page-cache altogether. This speeds
5152 ** up loading large records that span many overflow pages.
5154 if( eOp==0 /* (1) */
5155 && offset==0 /* (2) */
5156 && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */
5157 && &pBuf[-4]>=pBufStart /* (6) */
5159 sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
5160 u8 aSave[4];
5161 u8 *aWrite = &pBuf[-4];
5162 assert( aWrite>=pBufStart ); /* due to (6) */
5163 memcpy(aSave, aWrite, 4);
5164 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
5165 if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT;
5166 nextPage = get4byte(aWrite);
5167 memcpy(aWrite, aSave, 4);
5168 }else
5169 #endif
5172 DbPage *pDbPage;
5173 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
5174 (eOp==0 ? PAGER_GET_READONLY : 0)
5176 if( rc==SQLITE_OK ){
5177 aPayload = sqlite3PagerGetData(pDbPage);
5178 nextPage = get4byte(aPayload);
5179 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
5180 sqlite3PagerUnref(pDbPage);
5181 offset = 0;
5184 amt -= a;
5185 if( amt==0 ) return rc;
5186 pBuf += a;
5188 if( rc ) break;
5189 iIdx++;
5193 if( rc==SQLITE_OK && amt>0 ){
5194 /* Overflow chain ends prematurely */
5195 return SQLITE_CORRUPT_PAGE(pPage);
5197 return rc;
5201 ** Read part of the payload for the row at which that cursor pCur is currently
5202 ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
5203 ** begins at "offset".
5205 ** pCur can be pointing to either a table or an index b-tree.
5206 ** If pointing to a table btree, then the content section is read. If
5207 ** pCur is pointing to an index b-tree then the key section is read.
5209 ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
5210 ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
5211 ** cursor might be invalid or might need to be restored before being read.
5213 ** Return SQLITE_OK on success or an error code if anything goes
5214 ** wrong. An error is returned if "offset+amt" is larger than
5215 ** the available payload.
5217 int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5218 assert( cursorHoldsMutex(pCur) );
5219 assert( pCur->eState==CURSOR_VALID );
5220 assert( pCur->iPage>=0 && pCur->pPage );
5221 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
5225 ** This variant of sqlite3BtreePayload() works even if the cursor has not
5226 ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
5227 ** interface.
5229 #ifndef SQLITE_OMIT_INCRBLOB
5230 static SQLITE_NOINLINE int accessPayloadChecked(
5231 BtCursor *pCur,
5232 u32 offset,
5233 u32 amt,
5234 void *pBuf
5236 int rc;
5237 if ( pCur->eState==CURSOR_INVALID ){
5238 return SQLITE_ABORT;
5240 assert( cursorOwnsBtShared(pCur) );
5241 rc = btreeRestoreCursorPosition(pCur);
5242 return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
5244 int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5245 if( pCur->eState==CURSOR_VALID ){
5246 assert( cursorOwnsBtShared(pCur) );
5247 return accessPayload(pCur, offset, amt, pBuf, 0);
5248 }else{
5249 return accessPayloadChecked(pCur, offset, amt, pBuf);
5252 #endif /* SQLITE_OMIT_INCRBLOB */
5255 ** Return a pointer to payload information from the entry that the
5256 ** pCur cursor is pointing to. The pointer is to the beginning of
5257 ** the key if index btrees (pPage->intKey==0) and is the data for
5258 ** table btrees (pPage->intKey==1). The number of bytes of available
5259 ** key/data is written into *pAmt. If *pAmt==0, then the value
5260 ** returned will not be a valid pointer.
5262 ** This routine is an optimization. It is common for the entire key
5263 ** and data to fit on the local page and for there to be no overflow
5264 ** pages. When that is so, this routine can be used to access the
5265 ** key and data without making a copy. If the key and/or data spills
5266 ** onto overflow pages, then accessPayload() must be used to reassemble
5267 ** the key/data and copy it into a preallocated buffer.
5269 ** The pointer returned by this routine looks directly into the cached
5270 ** page of the database. The data might change or move the next time
5271 ** any btree routine is called.
5273 static const void *fetchPayload(
5274 BtCursor *pCur, /* Cursor pointing to entry to read from */
5275 u32 *pAmt /* Write the number of available bytes here */
5277 int amt;
5278 assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
5279 assert( pCur->eState==CURSOR_VALID );
5280 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5281 assert( cursorOwnsBtShared(pCur) );
5282 assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
5283 assert( pCur->info.nSize>0 );
5284 assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
5285 assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
5286 amt = pCur->info.nLocal;
5287 if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
5288 /* There is too little space on the page for the expected amount
5289 ** of local content. Database must be corrupt. */
5290 assert( CORRUPT_DB );
5291 amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
5293 *pAmt = (u32)amt;
5294 return (void*)pCur->info.pPayload;
5299 ** For the entry that cursor pCur is point to, return as
5300 ** many bytes of the key or data as are available on the local
5301 ** b-tree page. Write the number of available bytes into *pAmt.
5303 ** The pointer returned is ephemeral. The key/data may move
5304 ** or be destroyed on the next call to any Btree routine,
5305 ** including calls from other threads against the same cache.
5306 ** Hence, a mutex on the BtShared should be held prior to calling
5307 ** this routine.
5309 ** These routines is used to get quick access to key and data
5310 ** in the common case where no overflow pages are used.
5312 const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
5313 return fetchPayload(pCur, pAmt);
5318 ** Move the cursor down to a new child page. The newPgno argument is the
5319 ** page number of the child page to move to.
5321 ** This function returns SQLITE_CORRUPT if the page-header flags field of
5322 ** the new child page does not match the flags field of the parent (i.e.
5323 ** if an intkey page appears to be the parent of a non-intkey page, or
5324 ** vice-versa).
5326 static int moveToChild(BtCursor *pCur, u32 newPgno){
5327 int rc;
5328 assert( cursorOwnsBtShared(pCur) );
5329 assert( pCur->eState==CURSOR_VALID );
5330 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
5331 assert( pCur->iPage>=0 );
5332 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
5333 return SQLITE_CORRUPT_BKPT;
5335 pCur->info.nSize = 0;
5336 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5337 pCur->aiIdx[pCur->iPage] = pCur->ix;
5338 pCur->apPage[pCur->iPage] = pCur->pPage;
5339 pCur->ix = 0;
5340 pCur->iPage++;
5341 rc = getAndInitPage(pCur->pBt, newPgno, &pCur->pPage, pCur->curPagerFlags);
5342 assert( pCur->pPage!=0 || rc!=SQLITE_OK );
5343 if( rc==SQLITE_OK
5344 && (pCur->pPage->nCell<1 || pCur->pPage->intKey!=pCur->curIntKey)
5346 releasePage(pCur->pPage);
5347 rc = SQLITE_CORRUPT_PGNO(newPgno);
5349 if( rc ){
5350 pCur->pPage = pCur->apPage[--pCur->iPage];
5352 return rc;
5355 #ifdef SQLITE_DEBUG
5357 ** Page pParent is an internal (non-leaf) tree page. This function
5358 ** asserts that page number iChild is the left-child if the iIdx'th
5359 ** cell in page pParent. Or, if iIdx is equal to the total number of
5360 ** cells in pParent, that page number iChild is the right-child of
5361 ** the page.
5363 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
5364 if( CORRUPT_DB ) return; /* The conditions tested below might not be true
5365 ** in a corrupt database */
5366 assert( iIdx<=pParent->nCell );
5367 if( iIdx==pParent->nCell ){
5368 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
5369 }else{
5370 assert( get4byte(findCell(pParent, iIdx))==iChild );
5373 #else
5374 # define assertParentIndex(x,y,z)
5375 #endif
5378 ** Move the cursor up to the parent page.
5380 ** pCur->idx is set to the cell index that contains the pointer
5381 ** to the page we are coming from. If we are coming from the
5382 ** right-most child page then pCur->idx is set to one more than
5383 ** the largest cell index.
5385 static void moveToParent(BtCursor *pCur){
5386 MemPage *pLeaf;
5387 assert( cursorOwnsBtShared(pCur) );
5388 assert( pCur->eState==CURSOR_VALID );
5389 assert( pCur->iPage>0 );
5390 assert( pCur->pPage );
5391 assertParentIndex(
5392 pCur->apPage[pCur->iPage-1],
5393 pCur->aiIdx[pCur->iPage-1],
5394 pCur->pPage->pgno
5396 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
5397 pCur->info.nSize = 0;
5398 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5399 pCur->ix = pCur->aiIdx[pCur->iPage-1];
5400 pLeaf = pCur->pPage;
5401 pCur->pPage = pCur->apPage[--pCur->iPage];
5402 releasePageNotNull(pLeaf);
5406 ** Move the cursor to point to the root page of its b-tree structure.
5408 ** If the table has a virtual root page, then the cursor is moved to point
5409 ** to the virtual root page instead of the actual root page. A table has a
5410 ** virtual root page when the actual root page contains no cells and a
5411 ** single child page. This can only happen with the table rooted at page 1.
5413 ** If the b-tree structure is empty, the cursor state is set to
5414 ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
5415 ** the cursor is set to point to the first cell located on the root
5416 ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
5418 ** If this function returns successfully, it may be assumed that the
5419 ** page-header flags indicate that the [virtual] root-page is the expected
5420 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
5421 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
5422 ** indicating a table b-tree, or if the caller did specify a KeyInfo
5423 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
5424 ** b-tree).
5426 static int moveToRoot(BtCursor *pCur){
5427 MemPage *pRoot;
5428 int rc = SQLITE_OK;
5430 assert( cursorOwnsBtShared(pCur) );
5431 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
5432 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
5433 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
5434 assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
5435 assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
5437 if( pCur->iPage>=0 ){
5438 if( pCur->iPage ){
5439 releasePageNotNull(pCur->pPage);
5440 while( --pCur->iPage ){
5441 releasePageNotNull(pCur->apPage[pCur->iPage]);
5443 pRoot = pCur->pPage = pCur->apPage[0];
5444 goto skip_init;
5446 }else if( pCur->pgnoRoot==0 ){
5447 pCur->eState = CURSOR_INVALID;
5448 return SQLITE_EMPTY;
5449 }else{
5450 assert( pCur->iPage==(-1) );
5451 if( pCur->eState>=CURSOR_REQUIRESEEK ){
5452 if( pCur->eState==CURSOR_FAULT ){
5453 assert( pCur->skipNext!=SQLITE_OK );
5454 return pCur->skipNext;
5456 sqlite3BtreeClearCursor(pCur);
5458 rc = getAndInitPage(pCur->pBt, pCur->pgnoRoot, &pCur->pPage,
5459 pCur->curPagerFlags);
5460 if( rc!=SQLITE_OK ){
5461 pCur->eState = CURSOR_INVALID;
5462 return rc;
5464 pCur->iPage = 0;
5465 pCur->curIntKey = pCur->pPage->intKey;
5467 pRoot = pCur->pPage;
5468 assert( pRoot->pgno==pCur->pgnoRoot || CORRUPT_DB );
5470 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
5471 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
5472 ** NULL, the caller expects a table b-tree. If this is not the case,
5473 ** return an SQLITE_CORRUPT error.
5475 ** Earlier versions of SQLite assumed that this test could not fail
5476 ** if the root page was already loaded when this function was called (i.e.
5477 ** if pCur->iPage>=0). But this is not so if the database is corrupted
5478 ** in such a way that page pRoot is linked into a second b-tree table
5479 ** (or the freelist). */
5480 assert( pRoot->intKey==1 || pRoot->intKey==0 );
5481 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
5482 return SQLITE_CORRUPT_PAGE(pCur->pPage);
5485 skip_init:
5486 pCur->ix = 0;
5487 pCur->info.nSize = 0;
5488 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
5490 if( pRoot->nCell>0 ){
5491 pCur->eState = CURSOR_VALID;
5492 }else if( !pRoot->leaf ){
5493 Pgno subpage;
5494 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
5495 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
5496 pCur->eState = CURSOR_VALID;
5497 rc = moveToChild(pCur, subpage);
5498 }else{
5499 pCur->eState = CURSOR_INVALID;
5500 rc = SQLITE_EMPTY;
5502 return rc;
5506 ** Move the cursor down to the left-most leaf entry beneath the
5507 ** entry to which it is currently pointing.
5509 ** The left-most leaf is the one with the smallest key - the first
5510 ** in ascending order.
5512 static int moveToLeftmost(BtCursor *pCur){
5513 Pgno pgno;
5514 int rc = SQLITE_OK;
5515 MemPage *pPage;
5517 assert( cursorOwnsBtShared(pCur) );
5518 assert( pCur->eState==CURSOR_VALID );
5519 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
5520 assert( pCur->ix<pPage->nCell );
5521 pgno = get4byte(findCell(pPage, pCur->ix));
5522 rc = moveToChild(pCur, pgno);
5524 return rc;
5528 ** Move the cursor down to the right-most leaf entry beneath the
5529 ** page to which it is currently pointing. Notice the difference
5530 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
5531 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
5532 ** finds the right-most entry beneath the *page*.
5534 ** The right-most entry is the one with the largest key - the last
5535 ** key in ascending order.
5537 static int moveToRightmost(BtCursor *pCur){
5538 Pgno pgno;
5539 int rc = SQLITE_OK;
5540 MemPage *pPage = 0;
5542 assert( cursorOwnsBtShared(pCur) );
5543 assert( pCur->eState==CURSOR_VALID );
5544 while( !(pPage = pCur->pPage)->leaf ){
5545 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5546 pCur->ix = pPage->nCell;
5547 rc = moveToChild(pCur, pgno);
5548 if( rc ) return rc;
5550 pCur->ix = pPage->nCell-1;
5551 assert( pCur->info.nSize==0 );
5552 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
5553 return SQLITE_OK;
5556 /* Move the cursor to the first entry in the table. Return SQLITE_OK
5557 ** on success. Set *pRes to 0 if the cursor actually points to something
5558 ** or set *pRes to 1 if the table is empty.
5560 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
5561 int rc;
5563 assert( cursorOwnsBtShared(pCur) );
5564 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5565 rc = moveToRoot(pCur);
5566 if( rc==SQLITE_OK ){
5567 assert( pCur->pPage->nCell>0 );
5568 *pRes = 0;
5569 rc = moveToLeftmost(pCur);
5570 }else if( rc==SQLITE_EMPTY ){
5571 assert( pCur->pgnoRoot==0 || (pCur->pPage!=0 && pCur->pPage->nCell==0) );
5572 *pRes = 1;
5573 rc = SQLITE_OK;
5575 return rc;
5578 /* Move the cursor to the last entry in the table. Return SQLITE_OK
5579 ** on success. Set *pRes to 0 if the cursor actually points to something
5580 ** or set *pRes to 1 if the table is empty.
5582 static SQLITE_NOINLINE int btreeLast(BtCursor *pCur, int *pRes){
5583 int rc = moveToRoot(pCur);
5584 if( rc==SQLITE_OK ){
5585 assert( pCur->eState==CURSOR_VALID );
5586 *pRes = 0;
5587 rc = moveToRightmost(pCur);
5588 if( rc==SQLITE_OK ){
5589 pCur->curFlags |= BTCF_AtLast;
5590 }else{
5591 pCur->curFlags &= ~BTCF_AtLast;
5593 }else if( rc==SQLITE_EMPTY ){
5594 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5595 *pRes = 1;
5596 rc = SQLITE_OK;
5598 return rc;
5600 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
5601 assert( cursorOwnsBtShared(pCur) );
5602 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5604 /* If the cursor already points to the last entry, this is a no-op. */
5605 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
5606 #ifdef SQLITE_DEBUG
5607 /* This block serves to assert() that the cursor really does point
5608 ** to the last entry in the b-tree. */
5609 int ii;
5610 for(ii=0; ii<pCur->iPage; ii++){
5611 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
5613 assert( pCur->ix==pCur->pPage->nCell-1 || CORRUPT_DB );
5614 testcase( pCur->ix!=pCur->pPage->nCell-1 );
5615 /* ^-- dbsqlfuzz b92b72e4de80b5140c30ab71372ca719b8feb618 */
5616 assert( pCur->pPage->leaf );
5617 #endif
5618 *pRes = 0;
5619 return SQLITE_OK;
5621 return btreeLast(pCur, pRes);
5624 /* Move the cursor so that it points to an entry in a table (a.k.a INTKEY)
5625 ** table near the key intKey. Return a success code.
5627 ** If an exact match is not found, then the cursor is always
5628 ** left pointing at a leaf page which would hold the entry if it
5629 ** were present. The cursor might point to an entry that comes
5630 ** before or after the key.
5632 ** An integer is written into *pRes which is the result of
5633 ** comparing the key with the entry to which the cursor is
5634 ** pointing. The meaning of the integer written into
5635 ** *pRes is as follows:
5637 ** *pRes<0 The cursor is left pointing at an entry that
5638 ** is smaller than intKey or if the table is empty
5639 ** and the cursor is therefore left point to nothing.
5641 ** *pRes==0 The cursor is left pointing at an entry that
5642 ** exactly matches intKey.
5644 ** *pRes>0 The cursor is left pointing at an entry that
5645 ** is larger than intKey.
5647 int sqlite3BtreeTableMoveto(
5648 BtCursor *pCur, /* The cursor to be moved */
5649 i64 intKey, /* The table key */
5650 int biasRight, /* If true, bias the search to the high end */
5651 int *pRes /* Write search results here */
5653 int rc;
5655 assert( cursorOwnsBtShared(pCur) );
5656 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5657 assert( pRes );
5658 assert( pCur->pKeyInfo==0 );
5659 assert( pCur->eState!=CURSOR_VALID || pCur->curIntKey!=0 );
5661 /* If the cursor is already positioned at the point we are trying
5662 ** to move to, then just return without doing any work */
5663 if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0 ){
5664 if( pCur->info.nKey==intKey ){
5665 *pRes = 0;
5666 return SQLITE_OK;
5668 if( pCur->info.nKey<intKey ){
5669 if( (pCur->curFlags & BTCF_AtLast)!=0 ){
5670 *pRes = -1;
5671 return SQLITE_OK;
5673 /* If the requested key is one more than the previous key, then
5674 ** try to get there using sqlite3BtreeNext() rather than a full
5675 ** binary search. This is an optimization only. The correct answer
5676 ** is still obtained without this case, only a little more slowly. */
5677 if( pCur->info.nKey+1==intKey ){
5678 *pRes = 0;
5679 rc = sqlite3BtreeNext(pCur, 0);
5680 if( rc==SQLITE_OK ){
5681 getCellInfo(pCur);
5682 if( pCur->info.nKey==intKey ){
5683 return SQLITE_OK;
5685 }else if( rc!=SQLITE_DONE ){
5686 return rc;
5692 #ifdef SQLITE_DEBUG
5693 pCur->pBtree->nSeek++; /* Performance measurement during testing */
5694 #endif
5696 rc = moveToRoot(pCur);
5697 if( rc ){
5698 if( rc==SQLITE_EMPTY ){
5699 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5700 *pRes = -1;
5701 return SQLITE_OK;
5703 return rc;
5705 assert( pCur->pPage );
5706 assert( pCur->pPage->isInit );
5707 assert( pCur->eState==CURSOR_VALID );
5708 assert( pCur->pPage->nCell > 0 );
5709 assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
5710 assert( pCur->curIntKey );
5712 for(;;){
5713 int lwr, upr, idx, c;
5714 Pgno chldPg;
5715 MemPage *pPage = pCur->pPage;
5716 u8 *pCell; /* Pointer to current cell in pPage */
5718 /* pPage->nCell must be greater than zero. If this is the root-page
5719 ** the cursor would have been INVALID above and this for(;;) loop
5720 ** not run. If this is not the root-page, then the moveToChild() routine
5721 ** would have already detected db corruption. Similarly, pPage must
5722 ** be the right kind (index or table) of b-tree page. Otherwise
5723 ** a moveToChild() or moveToRoot() call would have detected corruption. */
5724 assert( pPage->nCell>0 );
5725 assert( pPage->intKey );
5726 lwr = 0;
5727 upr = pPage->nCell-1;
5728 assert( biasRight==0 || biasRight==1 );
5729 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
5730 for(;;){
5731 i64 nCellKey;
5732 pCell = findCellPastPtr(pPage, idx);
5733 if( pPage->intKeyLeaf ){
5734 while( 0x80 <= *(pCell++) ){
5735 if( pCell>=pPage->aDataEnd ){
5736 return SQLITE_CORRUPT_PAGE(pPage);
5740 getVarint(pCell, (u64*)&nCellKey);
5741 if( nCellKey<intKey ){
5742 lwr = idx+1;
5743 if( lwr>upr ){ c = -1; break; }
5744 }else if( nCellKey>intKey ){
5745 upr = idx-1;
5746 if( lwr>upr ){ c = +1; break; }
5747 }else{
5748 assert( nCellKey==intKey );
5749 pCur->ix = (u16)idx;
5750 if( !pPage->leaf ){
5751 lwr = idx;
5752 goto moveto_table_next_layer;
5753 }else{
5754 pCur->curFlags |= BTCF_ValidNKey;
5755 pCur->info.nKey = nCellKey;
5756 pCur->info.nSize = 0;
5757 *pRes = 0;
5758 return SQLITE_OK;
5761 assert( lwr+upr>=0 );
5762 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
5764 assert( lwr==upr+1 || !pPage->leaf );
5765 assert( pPage->isInit );
5766 if( pPage->leaf ){
5767 assert( pCur->ix<pCur->pPage->nCell );
5768 pCur->ix = (u16)idx;
5769 *pRes = c;
5770 rc = SQLITE_OK;
5771 goto moveto_table_finish;
5773 moveto_table_next_layer:
5774 if( lwr>=pPage->nCell ){
5775 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5776 }else{
5777 chldPg = get4byte(findCell(pPage, lwr));
5779 pCur->ix = (u16)lwr;
5780 rc = moveToChild(pCur, chldPg);
5781 if( rc ) break;
5783 moveto_table_finish:
5784 pCur->info.nSize = 0;
5785 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5786 return rc;
5790 ** Compare the "idx"-th cell on the page the cursor pCur is currently
5791 ** pointing to to pIdxKey using xRecordCompare. Return negative or
5792 ** zero if the cell is less than or equal pIdxKey. Return positive
5793 ** if unknown.
5795 ** Return value negative: Cell at pCur[idx] less than pIdxKey
5797 ** Return value is zero: Cell at pCur[idx] equals pIdxKey
5799 ** Return value positive: Nothing is known about the relationship
5800 ** of the cell at pCur[idx] and pIdxKey.
5802 ** This routine is part of an optimization. It is always safe to return
5803 ** a positive value as that will cause the optimization to be skipped.
5805 static int indexCellCompare(
5806 BtCursor *pCur,
5807 int idx,
5808 UnpackedRecord *pIdxKey,
5809 RecordCompare xRecordCompare
5811 MemPage *pPage = pCur->pPage;
5812 int c;
5813 int nCell; /* Size of the pCell cell in bytes */
5814 u8 *pCell = findCellPastPtr(pPage, idx);
5816 nCell = pCell[0];
5817 if( nCell<=pPage->max1bytePayload ){
5818 /* This branch runs if the record-size field of the cell is a
5819 ** single byte varint and the record fits entirely on the main
5820 ** b-tree page. */
5821 testcase( pCell+nCell+1==pPage->aDataEnd );
5822 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
5823 }else if( !(pCell[1] & 0x80)
5824 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5826 /* The record-size field is a 2 byte varint and the record
5827 ** fits entirely on the main b-tree page. */
5828 testcase( pCell+nCell+2==pPage->aDataEnd );
5829 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
5830 }else{
5831 /* If the record extends into overflow pages, do not attempt
5832 ** the optimization. */
5833 c = 99;
5835 return c;
5839 ** Return true (non-zero) if pCur is current pointing to the last
5840 ** page of a table.
5842 static int cursorOnLastPage(BtCursor *pCur){
5843 int i;
5844 assert( pCur->eState==CURSOR_VALID );
5845 for(i=0; i<pCur->iPage; i++){
5846 MemPage *pPage = pCur->apPage[i];
5847 if( pCur->aiIdx[i]<pPage->nCell ) return 0;
5849 return 1;
5852 /* Move the cursor so that it points to an entry in an index table
5853 ** near the key pIdxKey. Return a success code.
5855 ** If an exact match is not found, then the cursor is always
5856 ** left pointing at a leaf page which would hold the entry if it
5857 ** were present. The cursor might point to an entry that comes
5858 ** before or after the key.
5860 ** An integer is written into *pRes which is the result of
5861 ** comparing the key with the entry to which the cursor is
5862 ** pointing. The meaning of the integer written into
5863 ** *pRes is as follows:
5865 ** *pRes<0 The cursor is left pointing at an entry that
5866 ** is smaller than pIdxKey or if the table is empty
5867 ** and the cursor is therefore left point to nothing.
5869 ** *pRes==0 The cursor is left pointing at an entry that
5870 ** exactly matches pIdxKey.
5872 ** *pRes>0 The cursor is left pointing at an entry that
5873 ** is larger than pIdxKey.
5875 ** The pIdxKey->eqSeen field is set to 1 if there
5876 ** exists an entry in the table that exactly matches pIdxKey.
5878 int sqlite3BtreeIndexMoveto(
5879 BtCursor *pCur, /* The cursor to be moved */
5880 UnpackedRecord *pIdxKey, /* Unpacked index key */
5881 int *pRes /* Write search results here */
5883 int rc;
5884 RecordCompare xRecordCompare;
5886 assert( cursorOwnsBtShared(pCur) );
5887 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5888 assert( pRes );
5889 assert( pCur->pKeyInfo!=0 );
5891 #ifdef SQLITE_DEBUG
5892 pCur->pBtree->nSeek++; /* Performance measurement during testing */
5893 #endif
5895 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
5896 pIdxKey->errCode = 0;
5897 assert( pIdxKey->default_rc==1
5898 || pIdxKey->default_rc==0
5899 || pIdxKey->default_rc==-1
5903 /* Check to see if we can skip a lot of work. Two cases:
5905 ** (1) If the cursor is already pointing to the very last cell
5906 ** in the table and the pIdxKey search key is greater than or
5907 ** equal to that last cell, then no movement is required.
5909 ** (2) If the cursor is on the last page of the table and the first
5910 ** cell on that last page is less than or equal to the pIdxKey
5911 ** search key, then we can start the search on the current page
5912 ** without needing to go back to root.
5914 if( pCur->eState==CURSOR_VALID
5915 && pCur->pPage->leaf
5916 && cursorOnLastPage(pCur)
5918 int c;
5919 if( pCur->ix==pCur->pPage->nCell-1
5920 && (c = indexCellCompare(pCur, pCur->ix, pIdxKey, xRecordCompare))<=0
5921 && pIdxKey->errCode==SQLITE_OK
5923 *pRes = c;
5924 return SQLITE_OK; /* Cursor already pointing at the correct spot */
5926 if( pCur->iPage>0
5927 && indexCellCompare(pCur, 0, pIdxKey, xRecordCompare)<=0
5928 && pIdxKey->errCode==SQLITE_OK
5930 pCur->curFlags &= ~BTCF_ValidOvfl;
5931 if( !pCur->pPage->isInit ){
5932 return SQLITE_CORRUPT_BKPT;
5934 goto bypass_moveto_root; /* Start search on the current page */
5936 pIdxKey->errCode = SQLITE_OK;
5939 rc = moveToRoot(pCur);
5940 if( rc ){
5941 if( rc==SQLITE_EMPTY ){
5942 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5943 *pRes = -1;
5944 return SQLITE_OK;
5946 return rc;
5949 bypass_moveto_root:
5950 assert( pCur->pPage );
5951 assert( pCur->pPage->isInit );
5952 assert( pCur->eState==CURSOR_VALID );
5953 assert( pCur->pPage->nCell > 0 );
5954 assert( pCur->curIntKey==0 );
5955 assert( pIdxKey!=0 );
5956 for(;;){
5957 int lwr, upr, idx, c;
5958 Pgno chldPg;
5959 MemPage *pPage = pCur->pPage;
5960 u8 *pCell; /* Pointer to current cell in pPage */
5962 /* pPage->nCell must be greater than zero. If this is the root-page
5963 ** the cursor would have been INVALID above and this for(;;) loop
5964 ** not run. If this is not the root-page, then the moveToChild() routine
5965 ** would have already detected db corruption. Similarly, pPage must
5966 ** be the right kind (index or table) of b-tree page. Otherwise
5967 ** a moveToChild() or moveToRoot() call would have detected corruption. */
5968 assert( pPage->nCell>0 );
5969 assert( pPage->intKey==0 );
5970 lwr = 0;
5971 upr = pPage->nCell-1;
5972 idx = upr>>1; /* idx = (lwr+upr)/2; */
5973 for(;;){
5974 int nCell; /* Size of the pCell cell in bytes */
5975 pCell = findCellPastPtr(pPage, idx);
5977 /* The maximum supported page-size is 65536 bytes. This means that
5978 ** the maximum number of record bytes stored on an index B-Tree
5979 ** page is less than 16384 bytes and may be stored as a 2-byte
5980 ** varint. This information is used to attempt to avoid parsing
5981 ** the entire cell by checking for the cases where the record is
5982 ** stored entirely within the b-tree page by inspecting the first
5983 ** 2 bytes of the cell.
5985 nCell = pCell[0];
5986 if( nCell<=pPage->max1bytePayload ){
5987 /* This branch runs if the record-size field of the cell is a
5988 ** single byte varint and the record fits entirely on the main
5989 ** b-tree page. */
5990 testcase( pCell+nCell+1==pPage->aDataEnd );
5991 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
5992 }else if( !(pCell[1] & 0x80)
5993 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5995 /* The record-size field is a 2 byte varint and the record
5996 ** fits entirely on the main b-tree page. */
5997 testcase( pCell+nCell+2==pPage->aDataEnd );
5998 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
5999 }else{
6000 /* The record flows over onto one or more overflow pages. In
6001 ** this case the whole cell needs to be parsed, a buffer allocated
6002 ** and accessPayload() used to retrieve the record into the
6003 ** buffer before VdbeRecordCompare() can be called.
6005 ** If the record is corrupt, the xRecordCompare routine may read
6006 ** up to two varints past the end of the buffer. An extra 18
6007 ** bytes of padding is allocated at the end of the buffer in
6008 ** case this happens. */
6009 void *pCellKey;
6010 u8 * const pCellBody = pCell - pPage->childPtrSize;
6011 const int nOverrun = 18; /* Size of the overrun padding */
6012 pPage->xParseCell(pPage, pCellBody, &pCur->info);
6013 nCell = (int)pCur->info.nKey;
6014 testcase( nCell<0 ); /* True if key size is 2^32 or more */
6015 testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
6016 testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
6017 testcase( nCell==2 ); /* Minimum legal index key size */
6018 if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
6019 rc = SQLITE_CORRUPT_PAGE(pPage);
6020 goto moveto_index_finish;
6022 pCellKey = sqlite3Malloc( nCell+nOverrun );
6023 if( pCellKey==0 ){
6024 rc = SQLITE_NOMEM_BKPT;
6025 goto moveto_index_finish;
6027 pCur->ix = (u16)idx;
6028 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
6029 memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */
6030 pCur->curFlags &= ~BTCF_ValidOvfl;
6031 if( rc ){
6032 sqlite3_free(pCellKey);
6033 goto moveto_index_finish;
6035 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
6036 sqlite3_free(pCellKey);
6038 assert(
6039 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
6040 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
6042 if( c<0 ){
6043 lwr = idx+1;
6044 }else if( c>0 ){
6045 upr = idx-1;
6046 }else{
6047 assert( c==0 );
6048 *pRes = 0;
6049 rc = SQLITE_OK;
6050 pCur->ix = (u16)idx;
6051 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
6052 goto moveto_index_finish;
6054 if( lwr>upr ) break;
6055 assert( lwr+upr>=0 );
6056 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
6058 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
6059 assert( pPage->isInit );
6060 if( pPage->leaf ){
6061 assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
6062 pCur->ix = (u16)idx;
6063 *pRes = c;
6064 rc = SQLITE_OK;
6065 goto moveto_index_finish;
6067 if( lwr>=pPage->nCell ){
6068 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
6069 }else{
6070 chldPg = get4byte(findCell(pPage, lwr));
6073 /* This block is similar to an in-lined version of:
6075 ** pCur->ix = (u16)lwr;
6076 ** rc = moveToChild(pCur, chldPg);
6077 ** if( rc ) break;
6079 pCur->info.nSize = 0;
6080 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
6081 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
6082 return SQLITE_CORRUPT_BKPT;
6084 pCur->aiIdx[pCur->iPage] = (u16)lwr;
6085 pCur->apPage[pCur->iPage] = pCur->pPage;
6086 pCur->ix = 0;
6087 pCur->iPage++;
6088 rc = getAndInitPage(pCur->pBt, chldPg, &pCur->pPage, pCur->curPagerFlags);
6089 if( rc==SQLITE_OK
6090 && (pCur->pPage->nCell<1 || pCur->pPage->intKey!=pCur->curIntKey)
6092 releasePage(pCur->pPage);
6093 rc = SQLITE_CORRUPT_PGNO(chldPg);
6095 if( rc ){
6096 pCur->pPage = pCur->apPage[--pCur->iPage];
6097 break;
6100 ***** End of in-lined moveToChild() call */
6102 moveto_index_finish:
6103 pCur->info.nSize = 0;
6104 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
6105 return rc;
6110 ** Return TRUE if the cursor is not pointing at an entry of the table.
6112 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
6113 ** past the last entry in the table or sqlite3BtreePrev() moves past
6114 ** the first entry. TRUE is also returned if the table is empty.
6116 int sqlite3BtreeEof(BtCursor *pCur){
6117 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
6118 ** have been deleted? This API will need to change to return an error code
6119 ** as well as the boolean result value.
6121 return (CURSOR_VALID!=pCur->eState);
6125 ** Return an estimate for the number of rows in the table that pCur is
6126 ** pointing to. Return a negative number if no estimate is currently
6127 ** available.
6129 i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
6130 i64 n;
6131 u8 i;
6133 assert( cursorOwnsBtShared(pCur) );
6134 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
6136 /* Currently this interface is only called by the OP_IfSmaller
6137 ** opcode, and it that case the cursor will always be valid and
6138 ** will always point to a leaf node. */
6139 if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
6140 if( NEVER(pCur->pPage->leaf==0) ) return -1;
6142 n = pCur->pPage->nCell;
6143 for(i=0; i<pCur->iPage; i++){
6144 n *= pCur->apPage[i]->nCell;
6146 return n;
6150 ** Advance the cursor to the next entry in the database.
6151 ** Return value:
6153 ** SQLITE_OK success
6154 ** SQLITE_DONE cursor is already pointing at the last element
6155 ** otherwise some kind of error occurred
6157 ** The main entry point is sqlite3BtreeNext(). That routine is optimized
6158 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
6159 ** to the next cell on the current page. The (slower) btreeNext() helper
6160 ** routine is called when it is necessary to move to a different page or
6161 ** to restore the cursor.
6163 ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
6164 ** cursor corresponds to an SQL index and this routine could have been
6165 ** skipped if the SQL index had been a unique index. The F argument
6166 ** is a hint to the implement. SQLite btree implementation does not use
6167 ** this hint, but COMDB2 does.
6169 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
6170 int rc;
6171 int idx;
6172 MemPage *pPage;
6174 assert( cursorOwnsBtShared(pCur) );
6175 if( pCur->eState!=CURSOR_VALID ){
6176 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
6177 rc = restoreCursorPosition(pCur);
6178 if( rc!=SQLITE_OK ){
6179 return rc;
6181 if( CURSOR_INVALID==pCur->eState ){
6182 return SQLITE_DONE;
6184 if( pCur->eState==CURSOR_SKIPNEXT ){
6185 pCur->eState = CURSOR_VALID;
6186 if( pCur->skipNext>0 ) return SQLITE_OK;
6190 pPage = pCur->pPage;
6191 idx = ++pCur->ix;
6192 if( sqlite3FaultSim(412) ) pPage->isInit = 0;
6193 if( !pPage->isInit ){
6194 return SQLITE_CORRUPT_BKPT;
6197 if( idx>=pPage->nCell ){
6198 if( !pPage->leaf ){
6199 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
6200 if( rc ) return rc;
6201 return moveToLeftmost(pCur);
6204 if( pCur->iPage==0 ){
6205 pCur->eState = CURSOR_INVALID;
6206 return SQLITE_DONE;
6208 moveToParent(pCur);
6209 pPage = pCur->pPage;
6210 }while( pCur->ix>=pPage->nCell );
6211 if( pPage->intKey ){
6212 return sqlite3BtreeNext(pCur, 0);
6213 }else{
6214 return SQLITE_OK;
6217 if( pPage->leaf ){
6218 return SQLITE_OK;
6219 }else{
6220 return moveToLeftmost(pCur);
6223 int sqlite3BtreeNext(BtCursor *pCur, int flags){
6224 MemPage *pPage;
6225 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
6226 assert( cursorOwnsBtShared(pCur) );
6227 assert( flags==0 || flags==1 );
6228 pCur->info.nSize = 0;
6229 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
6230 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
6231 pPage = pCur->pPage;
6232 if( (++pCur->ix)>=pPage->nCell ){
6233 pCur->ix--;
6234 return btreeNext(pCur);
6236 if( pPage->leaf ){
6237 return SQLITE_OK;
6238 }else{
6239 return moveToLeftmost(pCur);
6244 ** Step the cursor to the back to the previous entry in the database.
6245 ** Return values:
6247 ** SQLITE_OK success
6248 ** SQLITE_DONE the cursor is already on the first element of the table
6249 ** otherwise some kind of error occurred
6251 ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
6252 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
6253 ** to the previous cell on the current page. The (slower) btreePrevious()
6254 ** helper routine is called when it is necessary to move to a different page
6255 ** or to restore the cursor.
6257 ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
6258 ** the cursor corresponds to an SQL index and this routine could have been
6259 ** skipped if the SQL index had been a unique index. The F argument is a
6260 ** hint to the implement. The native SQLite btree implementation does not
6261 ** use this hint, but COMDB2 does.
6263 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
6264 int rc;
6265 MemPage *pPage;
6267 assert( cursorOwnsBtShared(pCur) );
6268 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
6269 assert( pCur->info.nSize==0 );
6270 if( pCur->eState!=CURSOR_VALID ){
6271 rc = restoreCursorPosition(pCur);
6272 if( rc!=SQLITE_OK ){
6273 return rc;
6275 if( CURSOR_INVALID==pCur->eState ){
6276 return SQLITE_DONE;
6278 if( CURSOR_SKIPNEXT==pCur->eState ){
6279 pCur->eState = CURSOR_VALID;
6280 if( pCur->skipNext<0 ) return SQLITE_OK;
6284 pPage = pCur->pPage;
6285 assert( pPage->isInit );
6286 if( !pPage->leaf ){
6287 int idx = pCur->ix;
6288 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
6289 if( rc ) return rc;
6290 rc = moveToRightmost(pCur);
6291 }else{
6292 while( pCur->ix==0 ){
6293 if( pCur->iPage==0 ){
6294 pCur->eState = CURSOR_INVALID;
6295 return SQLITE_DONE;
6297 moveToParent(pCur);
6299 assert( pCur->info.nSize==0 );
6300 assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
6302 pCur->ix--;
6303 pPage = pCur->pPage;
6304 if( pPage->intKey && !pPage->leaf ){
6305 rc = sqlite3BtreePrevious(pCur, 0);
6306 }else{
6307 rc = SQLITE_OK;
6310 return rc;
6312 int sqlite3BtreePrevious(BtCursor *pCur, int flags){
6313 assert( cursorOwnsBtShared(pCur) );
6314 assert( flags==0 || flags==1 );
6315 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
6316 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
6317 pCur->info.nSize = 0;
6318 if( pCur->eState!=CURSOR_VALID
6319 || pCur->ix==0
6320 || pCur->pPage->leaf==0
6322 return btreePrevious(pCur);
6324 pCur->ix--;
6325 return SQLITE_OK;
6329 ** Allocate a new page from the database file.
6331 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
6332 ** has already been called on the new page.) The new page has also
6333 ** been referenced and the calling routine is responsible for calling
6334 ** sqlite3PagerUnref() on the new page when it is done.
6336 ** SQLITE_OK is returned on success. Any other return value indicates
6337 ** an error. *ppPage is set to NULL in the event of an error.
6339 ** If the "nearby" parameter is not 0, then an effort is made to
6340 ** locate a page close to the page number "nearby". This can be used in an
6341 ** attempt to keep related pages close to each other in the database file,
6342 ** which in turn can make database access faster.
6344 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
6345 ** anywhere on the free-list, then it is guaranteed to be returned. If
6346 ** eMode is BTALLOC_LT then the page returned will be less than or equal
6347 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
6348 ** are no restrictions on which page is returned.
6350 static int allocateBtreePage(
6351 BtShared *pBt, /* The btree */
6352 MemPage **ppPage, /* Store pointer to the allocated page here */
6353 Pgno *pPgno, /* Store the page number here */
6354 Pgno nearby, /* Search for a page near this one */
6355 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
6357 MemPage *pPage1;
6358 int rc;
6359 u32 n; /* Number of pages on the freelist */
6360 u32 k; /* Number of leaves on the trunk of the freelist */
6361 MemPage *pTrunk = 0;
6362 MemPage *pPrevTrunk = 0;
6363 Pgno mxPage; /* Total size of the database file */
6365 assert( sqlite3_mutex_held(pBt->mutex) );
6366 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
6367 pPage1 = pBt->pPage1;
6368 mxPage = btreePagecount(pBt);
6369 /* EVIDENCE-OF: R-21003-45125 The 4-byte big-endian integer at offset 36
6370 ** stores the total number of pages on the freelist. */
6371 n = get4byte(&pPage1->aData[36]);
6372 testcase( n==mxPage-1 );
6373 if( n>=mxPage ){
6374 return SQLITE_CORRUPT_BKPT;
6376 if( n>0 ){
6377 /* There are pages on the freelist. Reuse one of those pages. */
6378 Pgno iTrunk;
6379 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
6380 u32 nSearch = 0; /* Count of the number of search attempts */
6382 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
6383 ** shows that the page 'nearby' is somewhere on the free-list, then
6384 ** the entire-list will be searched for that page.
6386 #ifndef SQLITE_OMIT_AUTOVACUUM
6387 if( eMode==BTALLOC_EXACT ){
6388 if( nearby<=mxPage ){
6389 u8 eType;
6390 assert( nearby>0 );
6391 assert( pBt->autoVacuum );
6392 rc = ptrmapGet(pBt, nearby, &eType, 0);
6393 if( rc ) return rc;
6394 if( eType==PTRMAP_FREEPAGE ){
6395 searchList = 1;
6398 }else if( eMode==BTALLOC_LE ){
6399 searchList = 1;
6401 #endif
6403 /* Decrement the free-list count by 1. Set iTrunk to the index of the
6404 ** first free-list trunk page. iPrevTrunk is initially 1.
6406 rc = sqlite3PagerWrite(pPage1->pDbPage);
6407 if( rc ) return rc;
6408 put4byte(&pPage1->aData[36], n-1);
6410 /* The code within this loop is run only once if the 'searchList' variable
6411 ** is not true. Otherwise, it runs once for each trunk-page on the
6412 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
6413 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
6415 do {
6416 pPrevTrunk = pTrunk;
6417 if( pPrevTrunk ){
6418 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
6419 ** is the page number of the next freelist trunk page in the list or
6420 ** zero if this is the last freelist trunk page. */
6421 iTrunk = get4byte(&pPrevTrunk->aData[0]);
6422 }else{
6423 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
6424 ** stores the page number of the first page of the freelist, or zero if
6425 ** the freelist is empty. */
6426 iTrunk = get4byte(&pPage1->aData[32]);
6428 testcase( iTrunk==mxPage );
6429 if( iTrunk>mxPage || nSearch++ > n ){
6430 rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
6431 }else{
6432 rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
6434 if( rc ){
6435 pTrunk = 0;
6436 goto end_allocate_page;
6438 assert( pTrunk!=0 );
6439 assert( pTrunk->aData!=0 );
6440 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
6441 ** is the number of leaf page pointers to follow. */
6442 k = get4byte(&pTrunk->aData[4]);
6443 if( k==0 && !searchList ){
6444 /* The trunk has no leaves and the list is not being searched.
6445 ** So extract the trunk page itself and use it as the newly
6446 ** allocated page */
6447 assert( pPrevTrunk==0 );
6448 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6449 if( rc ){
6450 goto end_allocate_page;
6452 *pPgno = iTrunk;
6453 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6454 *ppPage = pTrunk;
6455 pTrunk = 0;
6456 TRACE(("ALLOCATE: %u trunk - %u free pages left\n", *pPgno, n-1));
6457 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
6458 /* Value of k is out of range. Database corruption */
6459 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6460 goto end_allocate_page;
6461 #ifndef SQLITE_OMIT_AUTOVACUUM
6462 }else if( searchList
6463 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
6465 /* The list is being searched and this trunk page is the page
6466 ** to allocate, regardless of whether it has leaves.
6468 *pPgno = iTrunk;
6469 *ppPage = pTrunk;
6470 searchList = 0;
6471 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6472 if( rc ){
6473 goto end_allocate_page;
6475 if( k==0 ){
6476 if( !pPrevTrunk ){
6477 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6478 }else{
6479 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6480 if( rc!=SQLITE_OK ){
6481 goto end_allocate_page;
6483 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
6485 }else{
6486 /* The trunk page is required by the caller but it contains
6487 ** pointers to free-list leaves. The first leaf becomes a trunk
6488 ** page in this case.
6490 MemPage *pNewTrunk;
6491 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
6492 if( iNewTrunk>mxPage ){
6493 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6494 goto end_allocate_page;
6496 testcase( iNewTrunk==mxPage );
6497 rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
6498 if( rc!=SQLITE_OK ){
6499 goto end_allocate_page;
6501 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
6502 if( rc!=SQLITE_OK ){
6503 releasePage(pNewTrunk);
6504 goto end_allocate_page;
6506 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
6507 put4byte(&pNewTrunk->aData[4], k-1);
6508 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
6509 releasePage(pNewTrunk);
6510 if( !pPrevTrunk ){
6511 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
6512 put4byte(&pPage1->aData[32], iNewTrunk);
6513 }else{
6514 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6515 if( rc ){
6516 goto end_allocate_page;
6518 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
6521 pTrunk = 0;
6522 TRACE(("ALLOCATE: %u trunk - %u free pages left\n", *pPgno, n-1));
6523 #endif
6524 }else if( k>0 ){
6525 /* Extract a leaf from the trunk */
6526 u32 closest;
6527 Pgno iPage;
6528 unsigned char *aData = pTrunk->aData;
6529 if( nearby>0 ){
6530 u32 i;
6531 closest = 0;
6532 if( eMode==BTALLOC_LE ){
6533 for(i=0; i<k; i++){
6534 iPage = get4byte(&aData[8+i*4]);
6535 if( iPage<=nearby ){
6536 closest = i;
6537 break;
6540 }else{
6541 int dist;
6542 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
6543 for(i=1; i<k; i++){
6544 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
6545 if( d2<dist ){
6546 closest = i;
6547 dist = d2;
6551 }else{
6552 closest = 0;
6555 iPage = get4byte(&aData[8+closest*4]);
6556 testcase( iPage==mxPage );
6557 if( iPage>mxPage || iPage<2 ){
6558 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6559 goto end_allocate_page;
6561 testcase( iPage==mxPage );
6562 if( !searchList
6563 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
6565 int noContent;
6566 *pPgno = iPage;
6567 TRACE(("ALLOCATE: %u was leaf %u of %u on trunk %u"
6568 ": %u more free pages\n",
6569 *pPgno, closest+1, k, pTrunk->pgno, n-1));
6570 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6571 if( rc ) goto end_allocate_page;
6572 if( closest<k-1 ){
6573 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
6575 put4byte(&aData[4], k-1);
6576 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
6577 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
6578 if( rc==SQLITE_OK ){
6579 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6580 if( rc!=SQLITE_OK ){
6581 releasePage(*ppPage);
6582 *ppPage = 0;
6585 searchList = 0;
6588 releasePage(pPrevTrunk);
6589 pPrevTrunk = 0;
6590 }while( searchList );
6591 }else{
6592 /* There are no pages on the freelist, so append a new page to the
6593 ** database image.
6595 ** Normally, new pages allocated by this block can be requested from the
6596 ** pager layer with the 'no-content' flag set. This prevents the pager
6597 ** from trying to read the pages content from disk. However, if the
6598 ** current transaction has already run one or more incremental-vacuum
6599 ** steps, then the page we are about to allocate may contain content
6600 ** that is required in the event of a rollback. In this case, do
6601 ** not set the no-content flag. This causes the pager to load and journal
6602 ** the current page content before overwriting it.
6604 ** Note that the pager will not actually attempt to load or journal
6605 ** content for any page that really does lie past the end of the database
6606 ** file on disk. So the effects of disabling the no-content optimization
6607 ** here are confined to those pages that lie between the end of the
6608 ** database image and the end of the database file.
6610 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
6612 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6613 if( rc ) return rc;
6614 pBt->nPage++;
6615 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
6617 #ifndef SQLITE_OMIT_AUTOVACUUM
6618 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
6619 /* If *pPgno refers to a pointer-map page, allocate two new pages
6620 ** at the end of the file instead of one. The first allocated page
6621 ** becomes a new pointer-map page, the second is used by the caller.
6623 MemPage *pPg = 0;
6624 TRACE(("ALLOCATE: %u from end of file (pointer-map page)\n", pBt->nPage));
6625 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
6626 rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
6627 if( rc==SQLITE_OK ){
6628 rc = sqlite3PagerWrite(pPg->pDbPage);
6629 releasePage(pPg);
6631 if( rc ) return rc;
6632 pBt->nPage++;
6633 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
6635 #endif
6636 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
6637 *pPgno = pBt->nPage;
6639 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
6640 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
6641 if( rc ) return rc;
6642 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6643 if( rc!=SQLITE_OK ){
6644 releasePage(*ppPage);
6645 *ppPage = 0;
6647 TRACE(("ALLOCATE: %u from end of file\n", *pPgno));
6650 assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );
6652 end_allocate_page:
6653 releasePage(pTrunk);
6654 releasePage(pPrevTrunk);
6655 assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
6656 assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
6657 return rc;
6661 ** This function is used to add page iPage to the database file free-list.
6662 ** It is assumed that the page is not already a part of the free-list.
6664 ** The value passed as the second argument to this function is optional.
6665 ** If the caller happens to have a pointer to the MemPage object
6666 ** corresponding to page iPage handy, it may pass it as the second value.
6667 ** Otherwise, it may pass NULL.
6669 ** If a pointer to a MemPage object is passed as the second argument,
6670 ** its reference count is not altered by this function.
6672 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
6673 MemPage *pTrunk = 0; /* Free-list trunk page */
6674 Pgno iTrunk = 0; /* Page number of free-list trunk page */
6675 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
6676 MemPage *pPage; /* Page being freed. May be NULL. */
6677 int rc; /* Return Code */
6678 u32 nFree; /* Initial number of pages on free-list */
6680 assert( sqlite3_mutex_held(pBt->mutex) );
6681 assert( CORRUPT_DB || iPage>1 );
6682 assert( !pMemPage || pMemPage->pgno==iPage );
6684 if( iPage<2 || iPage>pBt->nPage ){
6685 return SQLITE_CORRUPT_BKPT;
6687 if( pMemPage ){
6688 pPage = pMemPage;
6689 sqlite3PagerRef(pPage->pDbPage);
6690 }else{
6691 pPage = btreePageLookup(pBt, iPage);
6694 /* Increment the free page count on pPage1 */
6695 rc = sqlite3PagerWrite(pPage1->pDbPage);
6696 if( rc ) goto freepage_out;
6697 nFree = get4byte(&pPage1->aData[36]);
6698 put4byte(&pPage1->aData[36], nFree+1);
6700 if( pBt->btsFlags & BTS_SECURE_DELETE ){
6701 /* If the secure_delete option is enabled, then
6702 ** always fully overwrite deleted information with zeros.
6704 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
6705 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
6707 goto freepage_out;
6709 memset(pPage->aData, 0, pPage->pBt->pageSize);
6712 /* If the database supports auto-vacuum, write an entry in the pointer-map
6713 ** to indicate that the page is free.
6715 if( ISAUTOVACUUM(pBt) ){
6716 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
6717 if( rc ) goto freepage_out;
6720 /* Now manipulate the actual database free-list structure. There are two
6721 ** possibilities. If the free-list is currently empty, or if the first
6722 ** trunk page in the free-list is full, then this page will become a
6723 ** new free-list trunk page. Otherwise, it will become a leaf of the
6724 ** first trunk page in the current free-list. This block tests if it
6725 ** is possible to add the page as a new free-list leaf.
6727 if( nFree!=0 ){
6728 u32 nLeaf; /* Initial number of leaf cells on trunk page */
6730 iTrunk = get4byte(&pPage1->aData[32]);
6731 if( iTrunk>btreePagecount(pBt) ){
6732 rc = SQLITE_CORRUPT_BKPT;
6733 goto freepage_out;
6735 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
6736 if( rc!=SQLITE_OK ){
6737 goto freepage_out;
6740 nLeaf = get4byte(&pTrunk->aData[4]);
6741 assert( pBt->usableSize>32 );
6742 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
6743 rc = SQLITE_CORRUPT_BKPT;
6744 goto freepage_out;
6746 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
6747 /* In this case there is room on the trunk page to insert the page
6748 ** being freed as a new leaf.
6750 ** Note that the trunk page is not really full until it contains
6751 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
6752 ** coded. But due to a coding error in versions of SQLite prior to
6753 ** 3.6.0, databases with freelist trunk pages holding more than
6754 ** usableSize/4 - 8 entries will be reported as corrupt. In order
6755 ** to maintain backwards compatibility with older versions of SQLite,
6756 ** we will continue to restrict the number of entries to usableSize/4 - 8
6757 ** for now. At some point in the future (once everyone has upgraded
6758 ** to 3.6.0 or later) we should consider fixing the conditional above
6759 ** to read "usableSize/4-2" instead of "usableSize/4-8".
6761 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
6762 ** avoid using the last six entries in the freelist trunk page array in
6763 ** order that database files created by newer versions of SQLite can be
6764 ** read by older versions of SQLite.
6766 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6767 if( rc==SQLITE_OK ){
6768 put4byte(&pTrunk->aData[4], nLeaf+1);
6769 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
6770 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
6771 sqlite3PagerDontWrite(pPage->pDbPage);
6773 rc = btreeSetHasContent(pBt, iPage);
6775 TRACE(("FREE-PAGE: %u leaf on trunk page %u\n",pPage->pgno,pTrunk->pgno));
6776 goto freepage_out;
6780 /* If control flows to this point, then it was not possible to add the
6781 ** the page being freed as a leaf page of the first trunk in the free-list.
6782 ** Possibly because the free-list is empty, or possibly because the
6783 ** first trunk in the free-list is full. Either way, the page being freed
6784 ** will become the new first trunk page in the free-list.
6786 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
6787 goto freepage_out;
6789 rc = sqlite3PagerWrite(pPage->pDbPage);
6790 if( rc!=SQLITE_OK ){
6791 goto freepage_out;
6793 put4byte(pPage->aData, iTrunk);
6794 put4byte(&pPage->aData[4], 0);
6795 put4byte(&pPage1->aData[32], iPage);
6796 TRACE(("FREE-PAGE: %u new trunk page replacing %u\n", pPage->pgno, iTrunk));
6798 freepage_out:
6799 if( pPage ){
6800 pPage->isInit = 0;
6802 releasePage(pPage);
6803 releasePage(pTrunk);
6804 return rc;
6806 static void freePage(MemPage *pPage, int *pRC){
6807 if( (*pRC)==SQLITE_OK ){
6808 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
6813 ** Free the overflow pages associated with the given Cell.
6815 static SQLITE_NOINLINE int clearCellOverflow(
6816 MemPage *pPage, /* The page that contains the Cell */
6817 unsigned char *pCell, /* First byte of the Cell */
6818 CellInfo *pInfo /* Size information about the cell */
6820 BtShared *pBt;
6821 Pgno ovflPgno;
6822 int rc;
6823 int nOvfl;
6824 u32 ovflPageSize;
6826 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6827 assert( pInfo->nLocal!=pInfo->nPayload );
6828 testcase( pCell + pInfo->nSize == pPage->aDataEnd );
6829 testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
6830 if( pCell + pInfo->nSize > pPage->aDataEnd ){
6831 /* Cell extends past end of page */
6832 return SQLITE_CORRUPT_PAGE(pPage);
6834 ovflPgno = get4byte(pCell + pInfo->nSize - 4);
6835 pBt = pPage->pBt;
6836 assert( pBt->usableSize > 4 );
6837 ovflPageSize = pBt->usableSize - 4;
6838 nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
6839 assert( nOvfl>0 ||
6840 (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
6842 while( nOvfl-- ){
6843 Pgno iNext = 0;
6844 MemPage *pOvfl = 0;
6845 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
6846 /* 0 is not a legal page number and page 1 cannot be an
6847 ** overflow page. Therefore if ovflPgno<2 or past the end of the
6848 ** file the database must be corrupt. */
6849 return SQLITE_CORRUPT_BKPT;
6851 if( nOvfl ){
6852 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
6853 if( rc ) return rc;
6856 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
6857 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
6859 /* There is no reason any cursor should have an outstanding reference
6860 ** to an overflow page belonging to a cell that is being deleted/updated.
6861 ** So if there exists more than one reference to this page, then it
6862 ** must not really be an overflow page and the database must be corrupt.
6863 ** It is helpful to detect this before calling freePage2(), as
6864 ** freePage2() may zero the page contents if secure-delete mode is
6865 ** enabled. If this 'overflow' page happens to be a page that the
6866 ** caller is iterating through or using in some other way, this
6867 ** can be problematic.
6869 rc = SQLITE_CORRUPT_BKPT;
6870 }else{
6871 rc = freePage2(pBt, pOvfl, ovflPgno);
6874 if( pOvfl ){
6875 sqlite3PagerUnref(pOvfl->pDbPage);
6877 if( rc ) return rc;
6878 ovflPgno = iNext;
6880 return SQLITE_OK;
6883 /* Call xParseCell to compute the size of a cell. If the cell contains
6884 ** overflow, then invoke cellClearOverflow to clear out that overflow.
6885 ** Store the result code (SQLITE_OK or some error code) in rc.
6887 ** Implemented as macro to force inlining for performance.
6889 #define BTREE_CLEAR_CELL(rc, pPage, pCell, sInfo) \
6890 pPage->xParseCell(pPage, pCell, &sInfo); \
6891 if( sInfo.nLocal!=sInfo.nPayload ){ \
6892 rc = clearCellOverflow(pPage, pCell, &sInfo); \
6893 }else{ \
6894 rc = SQLITE_OK; \
6899 ** Create the byte sequence used to represent a cell on page pPage
6900 ** and write that byte sequence into pCell[]. Overflow pages are
6901 ** allocated and filled in as necessary. The calling procedure
6902 ** is responsible for making sure sufficient space has been allocated
6903 ** for pCell[].
6905 ** Note that pCell does not necessary need to point to the pPage->aData
6906 ** area. pCell might point to some temporary storage. The cell will
6907 ** be constructed in this temporary area then copied into pPage->aData
6908 ** later.
6910 static int fillInCell(
6911 MemPage *pPage, /* The page that contains the cell */
6912 unsigned char *pCell, /* Complete text of the cell */
6913 const BtreePayload *pX, /* Payload with which to construct the cell */
6914 int *pnSize /* Write cell size here */
6916 int nPayload;
6917 const u8 *pSrc;
6918 int nSrc, n, rc, mn;
6919 int spaceLeft;
6920 MemPage *pToRelease;
6921 unsigned char *pPrior;
6922 unsigned char *pPayload;
6923 BtShared *pBt;
6924 Pgno pgnoOvfl;
6925 int nHeader;
6927 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6929 /* pPage is not necessarily writeable since pCell might be auxiliary
6930 ** buffer space that is separate from the pPage buffer area */
6931 assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
6932 || sqlite3PagerIswriteable(pPage->pDbPage) );
6934 /* Fill in the header. */
6935 nHeader = pPage->childPtrSize;
6936 if( pPage->intKey ){
6937 nPayload = pX->nData + pX->nZero;
6938 pSrc = pX->pData;
6939 nSrc = pX->nData;
6940 assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
6941 nHeader += putVarint32(&pCell[nHeader], nPayload);
6942 nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
6943 }else{
6944 assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
6945 nSrc = nPayload = (int)pX->nKey;
6946 pSrc = pX->pKey;
6947 nHeader += putVarint32(&pCell[nHeader], nPayload);
6950 /* Fill in the payload */
6951 pPayload = &pCell[nHeader];
6952 if( nPayload<=pPage->maxLocal ){
6953 /* This is the common case where everything fits on the btree page
6954 ** and no overflow pages are required. */
6955 n = nHeader + nPayload;
6956 testcase( n==3 );
6957 testcase( n==4 );
6958 if( n<4 ) n = 4;
6959 *pnSize = n;
6960 assert( nSrc<=nPayload );
6961 testcase( nSrc<nPayload );
6962 memcpy(pPayload, pSrc, nSrc);
6963 memset(pPayload+nSrc, 0, nPayload-nSrc);
6964 return SQLITE_OK;
6967 /* If we reach this point, it means that some of the content will need
6968 ** to spill onto overflow pages.
6970 mn = pPage->minLocal;
6971 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
6972 testcase( n==pPage->maxLocal );
6973 testcase( n==pPage->maxLocal+1 );
6974 if( n > pPage->maxLocal ) n = mn;
6975 spaceLeft = n;
6976 *pnSize = n + nHeader + 4;
6977 pPrior = &pCell[nHeader+n];
6978 pToRelease = 0;
6979 pgnoOvfl = 0;
6980 pBt = pPage->pBt;
6982 /* At this point variables should be set as follows:
6984 ** nPayload Total payload size in bytes
6985 ** pPayload Begin writing payload here
6986 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
6987 ** that means content must spill into overflow pages.
6988 ** *pnSize Size of the local cell (not counting overflow pages)
6989 ** pPrior Where to write the pgno of the first overflow page
6991 ** Use a call to btreeParseCellPtr() to verify that the values above
6992 ** were computed correctly.
6994 #ifdef SQLITE_DEBUG
6996 CellInfo info;
6997 pPage->xParseCell(pPage, pCell, &info);
6998 assert( nHeader==(int)(info.pPayload - pCell) );
6999 assert( info.nKey==pX->nKey );
7000 assert( *pnSize == info.nSize );
7001 assert( spaceLeft == info.nLocal );
7003 #endif
7005 /* Write the payload into the local Cell and any extra into overflow pages */
7006 while( 1 ){
7007 n = nPayload;
7008 if( n>spaceLeft ) n = spaceLeft;
7010 /* If pToRelease is not zero than pPayload points into the data area
7011 ** of pToRelease. Make sure pToRelease is still writeable. */
7012 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
7014 /* If pPayload is part of the data area of pPage, then make sure pPage
7015 ** is still writeable */
7016 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
7017 || sqlite3PagerIswriteable(pPage->pDbPage) );
7019 if( nSrc>=n ){
7020 memcpy(pPayload, pSrc, n);
7021 }else if( nSrc>0 ){
7022 n = nSrc;
7023 memcpy(pPayload, pSrc, n);
7024 }else{
7025 memset(pPayload, 0, n);
7027 nPayload -= n;
7028 if( nPayload<=0 ) break;
7029 pPayload += n;
7030 pSrc += n;
7031 nSrc -= n;
7032 spaceLeft -= n;
7033 if( spaceLeft==0 ){
7034 MemPage *pOvfl = 0;
7035 #ifndef SQLITE_OMIT_AUTOVACUUM
7036 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
7037 if( pBt->autoVacuum ){
7039 pgnoOvfl++;
7040 } while(
7041 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
7044 #endif
7045 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
7046 #ifndef SQLITE_OMIT_AUTOVACUUM
7047 /* If the database supports auto-vacuum, and the second or subsequent
7048 ** overflow page is being allocated, add an entry to the pointer-map
7049 ** for that page now.
7051 ** If this is the first overflow page, then write a partial entry
7052 ** to the pointer-map. If we write nothing to this pointer-map slot,
7053 ** then the optimistic overflow chain processing in clearCell()
7054 ** may misinterpret the uninitialized values and delete the
7055 ** wrong pages from the database.
7057 if( pBt->autoVacuum && rc==SQLITE_OK ){
7058 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
7059 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
7060 if( rc ){
7061 releasePage(pOvfl);
7064 #endif
7065 if( rc ){
7066 releasePage(pToRelease);
7067 return rc;
7070 /* If pToRelease is not zero than pPrior points into the data area
7071 ** of pToRelease. Make sure pToRelease is still writeable. */
7072 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
7074 /* If pPrior is part of the data area of pPage, then make sure pPage
7075 ** is still writeable */
7076 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
7077 || sqlite3PagerIswriteable(pPage->pDbPage) );
7079 put4byte(pPrior, pgnoOvfl);
7080 releasePage(pToRelease);
7081 pToRelease = pOvfl;
7082 pPrior = pOvfl->aData;
7083 put4byte(pPrior, 0);
7084 pPayload = &pOvfl->aData[4];
7085 spaceLeft = pBt->usableSize - 4;
7088 releasePage(pToRelease);
7089 return SQLITE_OK;
7093 ** Remove the i-th cell from pPage. This routine effects pPage only.
7094 ** The cell content is not freed or deallocated. It is assumed that
7095 ** the cell content has been copied someplace else. This routine just
7096 ** removes the reference to the cell from pPage.
7098 ** "sz" must be the number of bytes in the cell.
7100 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
7101 u32 pc; /* Offset to cell content of cell being deleted */
7102 u8 *data; /* pPage->aData */
7103 u8 *ptr; /* Used to move bytes around within data[] */
7104 int rc; /* The return code */
7105 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
7107 if( *pRC ) return;
7108 assert( idx>=0 );
7109 assert( idx<pPage->nCell );
7110 assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
7111 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
7112 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7113 assert( pPage->nFree>=0 );
7114 data = pPage->aData;
7115 ptr = &pPage->aCellIdx[2*idx];
7116 assert( pPage->pBt->usableSize > (u32)(ptr-data) );
7117 pc = get2byte(ptr);
7118 hdr = pPage->hdrOffset;
7119 testcase( pc==(u32)get2byte(&data[hdr+5]) );
7120 testcase( pc+sz==pPage->pBt->usableSize );
7121 if( pc+sz > pPage->pBt->usableSize ){
7122 *pRC = SQLITE_CORRUPT_BKPT;
7123 return;
7125 rc = freeSpace(pPage, pc, sz);
7126 if( rc ){
7127 *pRC = rc;
7128 return;
7130 pPage->nCell--;
7131 if( pPage->nCell==0 ){
7132 memset(&data[hdr+1], 0, 4);
7133 data[hdr+7] = 0;
7134 put2byte(&data[hdr+5], pPage->pBt->usableSize);
7135 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
7136 - pPage->childPtrSize - 8;
7137 }else{
7138 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
7139 put2byte(&data[hdr+3], pPage->nCell);
7140 pPage->nFree += 2;
7145 ** Insert a new cell on pPage at cell index "i". pCell points to the
7146 ** content of the cell.
7148 ** If the cell content will fit on the page, then put it there. If it
7149 ** will not fit, then make a copy of the cell content into pTemp if
7150 ** pTemp is not null. Regardless of pTemp, allocate a new entry
7151 ** in pPage->apOvfl[] and make it point to the cell content (either
7152 ** in pTemp or the original pCell) and also record its index.
7153 ** Allocating a new entry in pPage->aCell[] implies that
7154 ** pPage->nOverflow is incremented.
7156 ** The insertCellFast() routine below works exactly the same as
7157 ** insertCell() except that it lacks the pTemp and iChild parameters
7158 ** which are assumed zero. Other than that, the two routines are the
7159 ** same.
7161 ** Fixes or enhancements to this routine should be reflected in
7162 ** insertCellFast()!
7164 static int insertCell(
7165 MemPage *pPage, /* Page into which we are copying */
7166 int i, /* New cell becomes the i-th cell of the page */
7167 u8 *pCell, /* Content of the new cell */
7168 int sz, /* Bytes of content in pCell */
7169 u8 *pTemp, /* Temp storage space for pCell, if needed */
7170 Pgno iChild /* If non-zero, replace first 4 bytes with this value */
7172 int idx = 0; /* Where to write new cell content in data[] */
7173 int j; /* Loop counter */
7174 u8 *data; /* The content of the whole page */
7175 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
7177 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
7178 assert( MX_CELL(pPage->pBt)<=10921 );
7179 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
7180 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
7181 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
7182 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7183 assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
7184 assert( pPage->nFree>=0 );
7185 assert( iChild>0 );
7186 if( pPage->nOverflow || sz+2>pPage->nFree ){
7187 if( pTemp ){
7188 memcpy(pTemp, pCell, sz);
7189 pCell = pTemp;
7191 put4byte(pCell, iChild);
7192 j = pPage->nOverflow++;
7193 /* Comparison against ArraySize-1 since we hold back one extra slot
7194 ** as a contingency. In other words, never need more than 3 overflow
7195 ** slots but 4 are allocated, just to be safe. */
7196 assert( j < ArraySize(pPage->apOvfl)-1 );
7197 pPage->apOvfl[j] = pCell;
7198 pPage->aiOvfl[j] = (u16)i;
7200 /* When multiple overflows occur, they are always sequential and in
7201 ** sorted order. This invariants arise because multiple overflows can
7202 ** only occur when inserting divider cells into the parent page during
7203 ** balancing, and the dividers are adjacent and sorted.
7205 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
7206 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
7207 }else{
7208 int rc = sqlite3PagerWrite(pPage->pDbPage);
7209 if( NEVER(rc!=SQLITE_OK) ){
7210 return rc;
7212 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
7213 data = pPage->aData;
7214 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
7215 rc = allocateSpace(pPage, sz, &idx);
7216 if( rc ){ return rc; }
7217 /* The allocateSpace() routine guarantees the following properties
7218 ** if it returns successfully */
7219 assert( idx >= 0 );
7220 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
7221 assert( idx+sz <= (int)pPage->pBt->usableSize );
7222 pPage->nFree -= (u16)(2 + sz);
7223 /* In a corrupt database where an entry in the cell index section of
7224 ** a btree page has a value of 3 or less, the pCell value might point
7225 ** as many as 4 bytes in front of the start of the aData buffer for
7226 ** the source page. Make sure this does not cause problems by not
7227 ** reading the first 4 bytes */
7228 memcpy(&data[idx+4], pCell+4, sz-4);
7229 put4byte(&data[idx], iChild);
7230 pIns = pPage->aCellIdx + i*2;
7231 memmove(pIns+2, pIns, 2*(pPage->nCell - i));
7232 put2byte(pIns, idx);
7233 pPage->nCell++;
7234 /* increment the cell count */
7235 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
7236 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
7237 #ifndef SQLITE_OMIT_AUTOVACUUM
7238 if( pPage->pBt->autoVacuum ){
7239 int rc2 = SQLITE_OK;
7240 /* The cell may contain a pointer to an overflow page. If so, write
7241 ** the entry for the overflow page into the pointer map.
7243 ptrmapPutOvflPtr(pPage, pPage, pCell, &rc2);
7244 if( rc2 ) return rc2;
7246 #endif
7248 return SQLITE_OK;
7252 ** This variant of insertCell() assumes that the pTemp and iChild
7253 ** parameters are both zero. Use this variant in sqlite3BtreeInsert()
7254 ** for performance improvement, and also so that this variant is only
7255 ** called from that one place, and is thus inlined, and thus runs must
7256 ** faster.
7258 ** Fixes or enhancements to this routine should be reflected into
7259 ** the insertCell() routine.
7261 static int insertCellFast(
7262 MemPage *pPage, /* Page into which we are copying */
7263 int i, /* New cell becomes the i-th cell of the page */
7264 u8 *pCell, /* Content of the new cell */
7265 int sz /* Bytes of content in pCell */
7267 int idx = 0; /* Where to write new cell content in data[] */
7268 int j; /* Loop counter */
7269 u8 *data; /* The content of the whole page */
7270 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
7272 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
7273 assert( MX_CELL(pPage->pBt)<=10921 );
7274 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
7275 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
7276 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
7277 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7278 assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
7279 assert( pPage->nFree>=0 );
7280 assert( pPage->nOverflow==0 );
7281 if( sz+2>pPage->nFree ){
7282 j = pPage->nOverflow++;
7283 /* Comparison against ArraySize-1 since we hold back one extra slot
7284 ** as a contingency. In other words, never need more than 3 overflow
7285 ** slots but 4 are allocated, just to be safe. */
7286 assert( j < ArraySize(pPage->apOvfl)-1 );
7287 pPage->apOvfl[j] = pCell;
7288 pPage->aiOvfl[j] = (u16)i;
7290 /* When multiple overflows occur, they are always sequential and in
7291 ** sorted order. This invariants arise because multiple overflows can
7292 ** only occur when inserting divider cells into the parent page during
7293 ** balancing, and the dividers are adjacent and sorted.
7295 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
7296 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
7297 }else{
7298 int rc = sqlite3PagerWrite(pPage->pDbPage);
7299 if( rc!=SQLITE_OK ){
7300 return rc;
7302 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
7303 data = pPage->aData;
7304 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
7305 rc = allocateSpace(pPage, sz, &idx);
7306 if( rc ){ return rc; }
7307 /* The allocateSpace() routine guarantees the following properties
7308 ** if it returns successfully */
7309 assert( idx >= 0 );
7310 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
7311 assert( idx+sz <= (int)pPage->pBt->usableSize );
7312 pPage->nFree -= (u16)(2 + sz);
7313 memcpy(&data[idx], pCell, sz);
7314 pIns = pPage->aCellIdx + i*2;
7315 memmove(pIns+2, pIns, 2*(pPage->nCell - i));
7316 put2byte(pIns, idx);
7317 pPage->nCell++;
7318 /* increment the cell count */
7319 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
7320 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
7321 #ifndef SQLITE_OMIT_AUTOVACUUM
7322 if( pPage->pBt->autoVacuum ){
7323 int rc2 = SQLITE_OK;
7324 /* The cell may contain a pointer to an overflow page. If so, write
7325 ** the entry for the overflow page into the pointer map.
7327 ptrmapPutOvflPtr(pPage, pPage, pCell, &rc2);
7328 if( rc2 ) return rc2;
7330 #endif
7332 return SQLITE_OK;
7336 ** The following parameters determine how many adjacent pages get involved
7337 ** in a balancing operation. NN is the number of neighbors on either side
7338 ** of the page that participate in the balancing operation. NB is the
7339 ** total number of pages that participate, including the target page and
7340 ** NN neighbors on either side.
7342 ** The minimum value of NN is 1 (of course). Increasing NN above 1
7343 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
7344 ** in exchange for a larger degradation in INSERT and UPDATE performance.
7345 ** The value of NN appears to give the best results overall.
7347 ** (Later:) The description above makes it seem as if these values are
7348 ** tunable - as if you could change them and recompile and it would all work.
7349 ** But that is unlikely. NB has been 3 since the inception of SQLite and
7350 ** we have never tested any other value.
7352 #define NN 1 /* Number of neighbors on either side of pPage */
7353 #define NB 3 /* (NN*2+1): Total pages involved in the balance */
7356 ** A CellArray object contains a cache of pointers and sizes for a
7357 ** consecutive sequence of cells that might be held on multiple pages.
7359 ** The cells in this array are the divider cell or cells from the pParent
7360 ** page plus up to three child pages. There are a total of nCell cells.
7362 ** pRef is a pointer to one of the pages that contributes cells. This is
7363 ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
7364 ** which should be common to all pages that contribute cells to this array.
7366 ** apCell[] and szCell[] hold, respectively, pointers to the start of each
7367 ** cell and the size of each cell. Some of the apCell[] pointers might refer
7368 ** to overflow cells. In other words, some apCel[] pointers might not point
7369 ** to content area of the pages.
7371 ** A szCell[] of zero means the size of that cell has not yet been computed.
7373 ** The cells come from as many as four different pages:
7375 ** -----------
7376 ** | Parent |
7377 ** -----------
7378 ** / | \
7379 ** / | \
7380 ** --------- --------- ---------
7381 ** |Child-1| |Child-2| |Child-3|
7382 ** --------- --------- ---------
7384 ** The order of cells is in the array is for an index btree is:
7386 ** 1. All cells from Child-1 in order
7387 ** 2. The first divider cell from Parent
7388 ** 3. All cells from Child-2 in order
7389 ** 4. The second divider cell from Parent
7390 ** 5. All cells from Child-3 in order
7392 ** For a table-btree (with rowids) the items 2 and 4 are empty because
7393 ** content exists only in leaves and there are no divider cells.
7395 ** For an index btree, the apEnd[] array holds pointer to the end of page
7396 ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
7397 ** respectively. The ixNx[] array holds the number of cells contained in
7398 ** each of these 5 stages, and all stages to the left. Hence:
7400 ** ixNx[0] = Number of cells in Child-1.
7401 ** ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
7402 ** ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
7403 ** ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
7404 ** ixNx[4] = Total number of cells.
7406 ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
7407 ** are used and they point to the leaf pages only, and the ixNx value are:
7409 ** ixNx[0] = Number of cells in Child-1.
7410 ** ixNx[1] = Number of cells in Child-1 and Child-2.
7411 ** ixNx[2] = Total number of cells.
7413 ** Sometimes when deleting, a child page can have zero cells. In those
7414 ** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[]
7415 ** entries, shift down. The end result is that each ixNx[] entry should
7416 ** be larger than the previous
7418 typedef struct CellArray CellArray;
7419 struct CellArray {
7420 int nCell; /* Number of cells in apCell[] */
7421 MemPage *pRef; /* Reference page */
7422 u8 **apCell; /* All cells begin balanced */
7423 u16 *szCell; /* Local size of all cells in apCell[] */
7424 u8 *apEnd[NB*2]; /* MemPage.aDataEnd values */
7425 int ixNx[NB*2]; /* Index of at which we move to the next apEnd[] */
7429 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
7430 ** computed.
7432 static void populateCellCache(CellArray *p, int idx, int N){
7433 MemPage *pRef = p->pRef;
7434 u16 *szCell = p->szCell;
7435 assert( idx>=0 && idx+N<=p->nCell );
7436 while( N>0 ){
7437 assert( p->apCell[idx]!=0 );
7438 if( szCell[idx]==0 ){
7439 szCell[idx] = pRef->xCellSize(pRef, p->apCell[idx]);
7440 }else{
7441 assert( CORRUPT_DB ||
7442 szCell[idx]==pRef->xCellSize(pRef, p->apCell[idx]) );
7444 idx++;
7445 N--;
7450 ** Return the size of the Nth element of the cell array
7452 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
7453 assert( N>=0 && N<p->nCell );
7454 assert( p->szCell[N]==0 );
7455 p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
7456 return p->szCell[N];
7458 static u16 cachedCellSize(CellArray *p, int N){
7459 assert( N>=0 && N<p->nCell );
7460 if( p->szCell[N] ) return p->szCell[N];
7461 return computeCellSize(p, N);
7465 ** Array apCell[] contains pointers to nCell b-tree page cells. The
7466 ** szCell[] array contains the size in bytes of each cell. This function
7467 ** replaces the current contents of page pPg with the contents of the cell
7468 ** array.
7470 ** Some of the cells in apCell[] may currently be stored in pPg. This
7471 ** function works around problems caused by this by making a copy of any
7472 ** such cells before overwriting the page data.
7474 ** The MemPage.nFree field is invalidated by this function. It is the
7475 ** responsibility of the caller to set it correctly.
7477 static int rebuildPage(
7478 CellArray *pCArray, /* Content to be added to page pPg */
7479 int iFirst, /* First cell in pCArray to use */
7480 int nCell, /* Final number of cells on page */
7481 MemPage *pPg /* The page to be reconstructed */
7483 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
7484 u8 * const aData = pPg->aData; /* Pointer to data for pPg */
7485 const int usableSize = pPg->pBt->usableSize;
7486 u8 * const pEnd = &aData[usableSize];
7487 int i = iFirst; /* Which cell to copy from pCArray*/
7488 u32 j; /* Start of cell content area */
7489 int iEnd = i+nCell; /* Loop terminator */
7490 u8 *pCellptr = pPg->aCellIdx;
7491 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7492 u8 *pData;
7493 int k; /* Current slot in pCArray->apEnd[] */
7494 u8 *pSrcEnd; /* Current pCArray->apEnd[k] value */
7496 assert( nCell>0 );
7497 assert( i<iEnd );
7498 j = get2byte(&aData[hdr+5]);
7499 if( NEVER(j>(u32)usableSize) ){ j = 0; }
7500 memcpy(&pTmp[j], &aData[j], usableSize - j);
7502 for(k=0; ALWAYS(k<NB*2) && pCArray->ixNx[k]<=i; k++){}
7503 pSrcEnd = pCArray->apEnd[k];
7505 pData = pEnd;
7506 while( 1/*exit by break*/ ){
7507 u8 *pCell = pCArray->apCell[i];
7508 u16 sz = pCArray->szCell[i];
7509 assert( sz>0 );
7510 if( SQLITE_WITHIN(pCell,aData+j,pEnd) ){
7511 if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
7512 pCell = &pTmp[pCell - aData];
7513 }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
7514 && (uptr)(pCell)<(uptr)pSrcEnd
7516 return SQLITE_CORRUPT_BKPT;
7519 pData -= sz;
7520 put2byte(pCellptr, (pData - aData));
7521 pCellptr += 2;
7522 if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
7523 memmove(pData, pCell, sz);
7524 assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
7525 i++;
7526 if( i>=iEnd ) break;
7527 if( pCArray->ixNx[k]<=i ){
7528 k++;
7529 pSrcEnd = pCArray->apEnd[k];
7533 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
7534 pPg->nCell = nCell;
7535 pPg->nOverflow = 0;
7537 put2byte(&aData[hdr+1], 0);
7538 put2byte(&aData[hdr+3], pPg->nCell);
7539 put2byte(&aData[hdr+5], pData - aData);
7540 aData[hdr+7] = 0x00;
7541 return SQLITE_OK;
7545 ** The pCArray objects contains pointers to b-tree cells and the cell sizes.
7546 ** This function attempts to add the cells stored in the array to page pPg.
7547 ** If it cannot (because the page needs to be defragmented before the cells
7548 ** will fit), non-zero is returned. Otherwise, if the cells are added
7549 ** successfully, zero is returned.
7551 ** Argument pCellptr points to the first entry in the cell-pointer array
7552 ** (part of page pPg) to populate. After cell apCell[0] is written to the
7553 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
7554 ** cell in the array. It is the responsibility of the caller to ensure
7555 ** that it is safe to overwrite this part of the cell-pointer array.
7557 ** When this function is called, *ppData points to the start of the
7558 ** content area on page pPg. If the size of the content area is extended,
7559 ** *ppData is updated to point to the new start of the content area
7560 ** before returning.
7562 ** Finally, argument pBegin points to the byte immediately following the
7563 ** end of the space required by this page for the cell-pointer area (for
7564 ** all cells - not just those inserted by the current call). If the content
7565 ** area must be extended to before this point in order to accommodate all
7566 ** cells in apCell[], then the cells do not fit and non-zero is returned.
7568 static int pageInsertArray(
7569 MemPage *pPg, /* Page to add cells to */
7570 u8 *pBegin, /* End of cell-pointer array */
7571 u8 **ppData, /* IN/OUT: Page content-area pointer */
7572 u8 *pCellptr, /* Pointer to cell-pointer area */
7573 int iFirst, /* Index of first cell to add */
7574 int nCell, /* Number of cells to add to pPg */
7575 CellArray *pCArray /* Array of cells */
7577 int i = iFirst; /* Loop counter - cell index to insert */
7578 u8 *aData = pPg->aData; /* Complete page */
7579 u8 *pData = *ppData; /* Content area. A subset of aData[] */
7580 int iEnd = iFirst + nCell; /* End of loop. One past last cell to ins */
7581 int k; /* Current slot in pCArray->apEnd[] */
7582 u8 *pEnd; /* Maximum extent of cell data */
7583 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
7584 if( iEnd<=iFirst ) return 0;
7585 for(k=0; ALWAYS(k<NB*2) && pCArray->ixNx[k]<=i ; k++){}
7586 pEnd = pCArray->apEnd[k];
7587 while( 1 /*Exit by break*/ ){
7588 int sz, rc;
7589 u8 *pSlot;
7590 assert( pCArray->szCell[i]!=0 );
7591 sz = pCArray->szCell[i];
7592 if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
7593 if( (pData - pBegin)<sz ) return 1;
7594 pData -= sz;
7595 pSlot = pData;
7597 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
7598 ** database. But they might for a corrupt database. Hence use memmove()
7599 ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
7600 assert( (pSlot+sz)<=pCArray->apCell[i]
7601 || pSlot>=(pCArray->apCell[i]+sz)
7602 || CORRUPT_DB );
7603 if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
7604 && (uptr)(pCArray->apCell[i])<(uptr)pEnd
7606 assert( CORRUPT_DB );
7607 (void)SQLITE_CORRUPT_BKPT;
7608 return 1;
7610 memmove(pSlot, pCArray->apCell[i], sz);
7611 put2byte(pCellptr, (pSlot - aData));
7612 pCellptr += 2;
7613 i++;
7614 if( i>=iEnd ) break;
7615 if( pCArray->ixNx[k]<=i ){
7616 k++;
7617 pEnd = pCArray->apEnd[k];
7620 *ppData = pData;
7621 return 0;
7625 ** The pCArray object contains pointers to b-tree cells and their sizes.
7627 ** This function adds the space associated with each cell in the array
7628 ** that is currently stored within the body of pPg to the pPg free-list.
7629 ** The cell-pointers and other fields of the page are not updated.
7631 ** This function returns the total number of cells added to the free-list.
7633 static int pageFreeArray(
7634 MemPage *pPg, /* Page to edit */
7635 int iFirst, /* First cell to delete */
7636 int nCell, /* Cells to delete */
7637 CellArray *pCArray /* Array of cells */
7639 u8 * const aData = pPg->aData;
7640 u8 * const pEnd = &aData[pPg->pBt->usableSize];
7641 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
7642 int nRet = 0;
7643 int i, j;
7644 int iEnd = iFirst + nCell;
7645 int nFree = 0;
7646 int aOfst[10];
7647 int aAfter[10];
7649 for(i=iFirst; i<iEnd; i++){
7650 u8 *pCell = pCArray->apCell[i];
7651 if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
7652 int sz;
7653 int iAfter;
7654 int iOfst;
7655 /* No need to use cachedCellSize() here. The sizes of all cells that
7656 ** are to be freed have already been computing while deciding which
7657 ** cells need freeing */
7658 sz = pCArray->szCell[i]; assert( sz>0 );
7659 iOfst = (u16)(pCell - aData);
7660 iAfter = iOfst+sz;
7661 for(j=0; j<nFree; j++){
7662 if( aOfst[j]==iAfter ){
7663 aOfst[j] = iOfst;
7664 break;
7665 }else if( aAfter[j]==iOfst ){
7666 aAfter[j] = iAfter;
7667 break;
7670 if( j>=nFree ){
7671 if( nFree>=(int)(sizeof(aOfst)/sizeof(aOfst[0])) ){
7672 for(j=0; j<nFree; j++){
7673 freeSpace(pPg, aOfst[j], aAfter[j]-aOfst[j]);
7675 nFree = 0;
7677 aOfst[nFree] = iOfst;
7678 aAfter[nFree] = iAfter;
7679 if( &aData[iAfter]>pEnd ) return 0;
7680 nFree++;
7682 nRet++;
7685 for(j=0; j<nFree; j++){
7686 freeSpace(pPg, aOfst[j], aAfter[j]-aOfst[j]);
7688 return nRet;
7692 ** pCArray contains pointers to and sizes of all cells in the page being
7693 ** balanced. The current page, pPg, has pPg->nCell cells starting with
7694 ** pCArray->apCell[iOld]. After balancing, this page should hold nNew cells
7695 ** starting at apCell[iNew].
7697 ** This routine makes the necessary adjustments to pPg so that it contains
7698 ** the correct cells after being balanced.
7700 ** The pPg->nFree field is invalid when this function returns. It is the
7701 ** responsibility of the caller to set it correctly.
7703 static int editPage(
7704 MemPage *pPg, /* Edit this page */
7705 int iOld, /* Index of first cell currently on page */
7706 int iNew, /* Index of new first cell on page */
7707 int nNew, /* Final number of cells on page */
7708 CellArray *pCArray /* Array of cells and sizes */
7710 u8 * const aData = pPg->aData;
7711 const int hdr = pPg->hdrOffset;
7712 u8 *pBegin = &pPg->aCellIdx[nNew * 2];
7713 int nCell = pPg->nCell; /* Cells stored on pPg */
7714 u8 *pData;
7715 u8 *pCellptr;
7716 int i;
7717 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
7718 int iNewEnd = iNew + nNew;
7720 #ifdef SQLITE_DEBUG
7721 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7722 memcpy(pTmp, aData, pPg->pBt->usableSize);
7723 #endif
7725 /* Remove cells from the start and end of the page */
7726 assert( nCell>=0 );
7727 if( iOld<iNew ){
7728 int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
7729 if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT;
7730 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
7731 nCell -= nShift;
7733 if( iNewEnd < iOldEnd ){
7734 int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
7735 assert( nCell>=nTail );
7736 nCell -= nTail;
7739 pData = &aData[get2byte(&aData[hdr+5])];
7740 if( pData<pBegin ) goto editpage_fail;
7741 if( NEVER(pData>pPg->aDataEnd) ) goto editpage_fail;
7743 /* Add cells to the start of the page */
7744 if( iNew<iOld ){
7745 int nAdd = MIN(nNew,iOld-iNew);
7746 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
7747 assert( nAdd>=0 );
7748 pCellptr = pPg->aCellIdx;
7749 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
7750 if( pageInsertArray(
7751 pPg, pBegin, &pData, pCellptr,
7752 iNew, nAdd, pCArray
7753 ) ) goto editpage_fail;
7754 nCell += nAdd;
7757 /* Add any overflow cells */
7758 for(i=0; i<pPg->nOverflow; i++){
7759 int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
7760 if( iCell>=0 && iCell<nNew ){
7761 pCellptr = &pPg->aCellIdx[iCell * 2];
7762 if( nCell>iCell ){
7763 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
7765 nCell++;
7766 cachedCellSize(pCArray, iCell+iNew);
7767 if( pageInsertArray(
7768 pPg, pBegin, &pData, pCellptr,
7769 iCell+iNew, 1, pCArray
7770 ) ) goto editpage_fail;
7774 /* Append cells to the end of the page */
7775 assert( nCell>=0 );
7776 pCellptr = &pPg->aCellIdx[nCell*2];
7777 if( pageInsertArray(
7778 pPg, pBegin, &pData, pCellptr,
7779 iNew+nCell, nNew-nCell, pCArray
7780 ) ) goto editpage_fail;
7782 pPg->nCell = nNew;
7783 pPg->nOverflow = 0;
7785 put2byte(&aData[hdr+3], pPg->nCell);
7786 put2byte(&aData[hdr+5], pData - aData);
7788 #ifdef SQLITE_DEBUG
7789 for(i=0; i<nNew && !CORRUPT_DB; i++){
7790 u8 *pCell = pCArray->apCell[i+iNew];
7791 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
7792 if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
7793 pCell = &pTmp[pCell - aData];
7795 assert( 0==memcmp(pCell, &aData[iOff],
7796 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
7798 #endif
7800 return SQLITE_OK;
7801 editpage_fail:
7802 /* Unable to edit this page. Rebuild it from scratch instead. */
7803 if( nNew<1 ) return SQLITE_CORRUPT_BKPT;
7804 populateCellCache(pCArray, iNew, nNew);
7805 return rebuildPage(pCArray, iNew, nNew, pPg);
7809 #ifndef SQLITE_OMIT_QUICKBALANCE
7811 ** This version of balance() handles the common special case where
7812 ** a new entry is being inserted on the extreme right-end of the
7813 ** tree, in other words, when the new entry will become the largest
7814 ** entry in the tree.
7816 ** Instead of trying to balance the 3 right-most leaf pages, just add
7817 ** a new page to the right-hand side and put the one new entry in
7818 ** that page. This leaves the right side of the tree somewhat
7819 ** unbalanced. But odds are that we will be inserting new entries
7820 ** at the end soon afterwards so the nearly empty page will quickly
7821 ** fill up. On average.
7823 ** pPage is the leaf page which is the right-most page in the tree.
7824 ** pParent is its parent. pPage must have a single overflow entry
7825 ** which is also the right-most entry on the page.
7827 ** The pSpace buffer is used to store a temporary copy of the divider
7828 ** cell that will be inserted into pParent. Such a cell consists of a 4
7829 ** byte page number followed by a variable length integer. In other
7830 ** words, at most 13 bytes. Hence the pSpace buffer must be at
7831 ** least 13 bytes in size.
7833 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
7834 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
7835 MemPage *pNew; /* Newly allocated page */
7836 int rc; /* Return Code */
7837 Pgno pgnoNew; /* Page number of pNew */
7839 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7840 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7841 assert( pPage->nOverflow==1 );
7843 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; /* dbfuzz001.test */
7844 assert( pPage->nFree>=0 );
7845 assert( pParent->nFree>=0 );
7847 /* Allocate a new page. This page will become the right-sibling of
7848 ** pPage. Make the parent page writable, so that the new divider cell
7849 ** may be inserted. If both these operations are successful, proceed.
7851 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
7853 if( rc==SQLITE_OK ){
7855 u8 *pOut = &pSpace[4];
7856 u8 *pCell = pPage->apOvfl[0];
7857 u16 szCell = pPage->xCellSize(pPage, pCell);
7858 u8 *pStop;
7859 CellArray b;
7861 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
7862 assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
7863 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
7864 b.nCell = 1;
7865 b.pRef = pPage;
7866 b.apCell = &pCell;
7867 b.szCell = &szCell;
7868 b.apEnd[0] = pPage->aDataEnd;
7869 b.ixNx[0] = 2;
7870 rc = rebuildPage(&b, 0, 1, pNew);
7871 if( NEVER(rc) ){
7872 releasePage(pNew);
7873 return rc;
7875 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
7877 /* If this is an auto-vacuum database, update the pointer map
7878 ** with entries for the new page, and any pointer from the
7879 ** cell on the page to an overflow page. If either of these
7880 ** operations fails, the return code is set, but the contents
7881 ** of the parent page are still manipulated by the code below.
7882 ** That is Ok, at this point the parent page is guaranteed to
7883 ** be marked as dirty. Returning an error code will cause a
7884 ** rollback, undoing any changes made to the parent page.
7886 if( ISAUTOVACUUM(pBt) ){
7887 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
7888 if( szCell>pNew->minLocal ){
7889 ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
7893 /* Create a divider cell to insert into pParent. The divider cell
7894 ** consists of a 4-byte page number (the page number of pPage) and
7895 ** a variable length key value (which must be the same value as the
7896 ** largest key on pPage).
7898 ** To find the largest key value on pPage, first find the right-most
7899 ** cell on pPage. The first two fields of this cell are the
7900 ** record-length (a variable length integer at most 32-bits in size)
7901 ** and the key value (a variable length integer, may have any value).
7902 ** The first of the while(...) loops below skips over the record-length
7903 ** field. The second while(...) loop copies the key value from the
7904 ** cell on pPage into the pSpace buffer.
7906 pCell = findCell(pPage, pPage->nCell-1);
7907 pStop = &pCell[9];
7908 while( (*(pCell++)&0x80) && pCell<pStop );
7909 pStop = &pCell[9];
7910 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
7912 /* Insert the new divider cell into pParent. */
7913 if( rc==SQLITE_OK ){
7914 rc = insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
7915 0, pPage->pgno);
7918 /* Set the right-child pointer of pParent to point to the new page. */
7919 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
7921 /* Release the reference to the new page. */
7922 releasePage(pNew);
7925 return rc;
7927 #endif /* SQLITE_OMIT_QUICKBALANCE */
7929 #if 0
7931 ** This function does not contribute anything to the operation of SQLite.
7932 ** it is sometimes activated temporarily while debugging code responsible
7933 ** for setting pointer-map entries.
7935 static int ptrmapCheckPages(MemPage **apPage, int nPage){
7936 int i, j;
7937 for(i=0; i<nPage; i++){
7938 Pgno n;
7939 u8 e;
7940 MemPage *pPage = apPage[i];
7941 BtShared *pBt = pPage->pBt;
7942 assert( pPage->isInit );
7944 for(j=0; j<pPage->nCell; j++){
7945 CellInfo info;
7946 u8 *z;
7948 z = findCell(pPage, j);
7949 pPage->xParseCell(pPage, z, &info);
7950 if( info.nLocal<info.nPayload ){
7951 Pgno ovfl = get4byte(&z[info.nSize-4]);
7952 ptrmapGet(pBt, ovfl, &e, &n);
7953 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
7955 if( !pPage->leaf ){
7956 Pgno child = get4byte(z);
7957 ptrmapGet(pBt, child, &e, &n);
7958 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7961 if( !pPage->leaf ){
7962 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
7963 ptrmapGet(pBt, child, &e, &n);
7964 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7967 return 1;
7969 #endif
7972 ** This function is used to copy the contents of the b-tree node stored
7973 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
7974 ** the pointer-map entries for each child page are updated so that the
7975 ** parent page stored in the pointer map is page pTo. If pFrom contained
7976 ** any cells with overflow page pointers, then the corresponding pointer
7977 ** map entries are also updated so that the parent page is page pTo.
7979 ** If pFrom is currently carrying any overflow cells (entries in the
7980 ** MemPage.apOvfl[] array), they are not copied to pTo.
7982 ** Before returning, page pTo is reinitialized using btreeInitPage().
7984 ** The performance of this function is not critical. It is only used by
7985 ** the balance_shallower() and balance_deeper() procedures, neither of
7986 ** which are called often under normal circumstances.
7988 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
7989 if( (*pRC)==SQLITE_OK ){
7990 BtShared * const pBt = pFrom->pBt;
7991 u8 * const aFrom = pFrom->aData;
7992 u8 * const aTo = pTo->aData;
7993 int const iFromHdr = pFrom->hdrOffset;
7994 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
7995 int rc;
7996 int iData;
7999 assert( pFrom->isInit );
8000 assert( pFrom->nFree>=iToHdr );
8001 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
8003 /* Copy the b-tree node content from page pFrom to page pTo. */
8004 iData = get2byte(&aFrom[iFromHdr+5]);
8005 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
8006 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
8008 /* Reinitialize page pTo so that the contents of the MemPage structure
8009 ** match the new data. The initialization of pTo can actually fail under
8010 ** fairly obscure circumstances, even though it is a copy of initialized
8011 ** page pFrom.
8013 pTo->isInit = 0;
8014 rc = btreeInitPage(pTo);
8015 if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo);
8016 if( rc!=SQLITE_OK ){
8017 *pRC = rc;
8018 return;
8021 /* If this is an auto-vacuum database, update the pointer-map entries
8022 ** for any b-tree or overflow pages that pTo now contains the pointers to.
8024 if( ISAUTOVACUUM(pBt) ){
8025 *pRC = setChildPtrmaps(pTo);
8031 ** This routine redistributes cells on the iParentIdx'th child of pParent
8032 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
8033 ** same amount of free space. Usually a single sibling on either side of the
8034 ** page are used in the balancing, though both siblings might come from one
8035 ** side if the page is the first or last child of its parent. If the page
8036 ** has fewer than 2 siblings (something which can only happen if the page
8037 ** is a root page or a child of a root page) then all available siblings
8038 ** participate in the balancing.
8040 ** The number of siblings of the page might be increased or decreased by
8041 ** one or two in an effort to keep pages nearly full but not over full.
8043 ** Note that when this routine is called, some of the cells on the page
8044 ** might not actually be stored in MemPage.aData[]. This can happen
8045 ** if the page is overfull. This routine ensures that all cells allocated
8046 ** to the page and its siblings fit into MemPage.aData[] before returning.
8048 ** In the course of balancing the page and its siblings, cells may be
8049 ** inserted into or removed from the parent page (pParent). Doing so
8050 ** may cause the parent page to become overfull or underfull. If this
8051 ** happens, it is the responsibility of the caller to invoke the correct
8052 ** balancing routine to fix this problem (see the balance() routine).
8054 ** If this routine fails for any reason, it might leave the database
8055 ** in a corrupted state. So if this routine fails, the database should
8056 ** be rolled back.
8058 ** The third argument to this function, aOvflSpace, is a pointer to a
8059 ** buffer big enough to hold one page. If while inserting cells into the parent
8060 ** page (pParent) the parent page becomes overfull, this buffer is
8061 ** used to store the parent's overflow cells. Because this function inserts
8062 ** a maximum of four divider cells into the parent page, and the maximum
8063 ** size of a cell stored within an internal node is always less than 1/4
8064 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
8065 ** enough for all overflow cells.
8067 ** If aOvflSpace is set to a null pointer, this function returns
8068 ** SQLITE_NOMEM.
8070 static int balance_nonroot(
8071 MemPage *pParent, /* Parent page of siblings being balanced */
8072 int iParentIdx, /* Index of "the page" in pParent */
8073 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
8074 int isRoot, /* True if pParent is a root-page */
8075 int bBulk /* True if this call is part of a bulk load */
8077 BtShared *pBt; /* The whole database */
8078 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
8079 int nNew = 0; /* Number of pages in apNew[] */
8080 int nOld; /* Number of pages in apOld[] */
8081 int i, j, k; /* Loop counters */
8082 int nxDiv; /* Next divider slot in pParent->aCell[] */
8083 int rc = SQLITE_OK; /* The return code */
8084 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
8085 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
8086 int usableSpace; /* Bytes in pPage beyond the header */
8087 int pageFlags; /* Value of pPage->aData[0] */
8088 int iSpace1 = 0; /* First unused byte of aSpace1[] */
8089 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
8090 int szScratch; /* Size of scratch memory requested */
8091 MemPage *apOld[NB]; /* pPage and up to two siblings */
8092 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
8093 u8 *pRight; /* Location in parent of right-sibling pointer */
8094 u8 *apDiv[NB-1]; /* Divider cells in pParent */
8095 int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
8096 int cntOld[NB+2]; /* Old index in b.apCell[] */
8097 int szNew[NB+2]; /* Combined size of cells placed on i-th page */
8098 u8 *aSpace1; /* Space for copies of dividers cells */
8099 Pgno pgno; /* Temp var to store a page number in */
8100 u8 abDone[NB+2]; /* True after i'th new page is populated */
8101 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
8102 CellArray b; /* Parsed information on cells being balanced */
8104 memset(abDone, 0, sizeof(abDone));
8105 memset(&b, 0, sizeof(b));
8106 pBt = pParent->pBt;
8107 assert( sqlite3_mutex_held(pBt->mutex) );
8108 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8110 /* At this point pParent may have at most one overflow cell. And if
8111 ** this overflow cell is present, it must be the cell with
8112 ** index iParentIdx. This scenario comes about when this function
8113 ** is called (indirectly) from sqlite3BtreeDelete().
8115 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
8116 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
8118 if( !aOvflSpace ){
8119 return SQLITE_NOMEM_BKPT;
8121 assert( pParent->nFree>=0 );
8123 /* Find the sibling pages to balance. Also locate the cells in pParent
8124 ** that divide the siblings. An attempt is made to find NN siblings on
8125 ** either side of pPage. More siblings are taken from one side, however,
8126 ** if there are fewer than NN siblings on the other side. If pParent
8127 ** has NB or fewer children then all children of pParent are taken.
8129 ** This loop also drops the divider cells from the parent page. This
8130 ** way, the remainder of the function does not have to deal with any
8131 ** overflow cells in the parent page, since if any existed they will
8132 ** have already been removed.
8134 i = pParent->nOverflow + pParent->nCell;
8135 if( i<2 ){
8136 nxDiv = 0;
8137 }else{
8138 assert( bBulk==0 || bBulk==1 );
8139 if( iParentIdx==0 ){
8140 nxDiv = 0;
8141 }else if( iParentIdx==i ){
8142 nxDiv = i-2+bBulk;
8143 }else{
8144 nxDiv = iParentIdx-1;
8146 i = 2-bBulk;
8148 nOld = i+1;
8149 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
8150 pRight = &pParent->aData[pParent->hdrOffset+8];
8151 }else{
8152 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
8154 pgno = get4byte(pRight);
8155 while( 1 ){
8156 if( rc==SQLITE_OK ){
8157 rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
8159 if( rc ){
8160 memset(apOld, 0, (i+1)*sizeof(MemPage*));
8161 goto balance_cleanup;
8163 if( apOld[i]->nFree<0 ){
8164 rc = btreeComputeFreeSpace(apOld[i]);
8165 if( rc ){
8166 memset(apOld, 0, (i)*sizeof(MemPage*));
8167 goto balance_cleanup;
8170 nMaxCells += apOld[i]->nCell + ArraySize(pParent->apOvfl);
8171 if( (i--)==0 ) break;
8173 if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
8174 apDiv[i] = pParent->apOvfl[0];
8175 pgno = get4byte(apDiv[i]);
8176 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
8177 pParent->nOverflow = 0;
8178 }else{
8179 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
8180 pgno = get4byte(apDiv[i]);
8181 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
8183 /* Drop the cell from the parent page. apDiv[i] still points to
8184 ** the cell within the parent, even though it has been dropped.
8185 ** This is safe because dropping a cell only overwrites the first
8186 ** four bytes of it, and this function does not need the first
8187 ** four bytes of the divider cell. So the pointer is safe to use
8188 ** later on.
8190 ** But not if we are in secure-delete mode. In secure-delete mode,
8191 ** the dropCell() routine will overwrite the entire cell with zeroes.
8192 ** In this case, temporarily copy the cell into the aOvflSpace[]
8193 ** buffer. It will be copied out again as soon as the aSpace[] buffer
8194 ** is allocated. */
8195 if( pBt->btsFlags & BTS_FAST_SECURE ){
8196 int iOff;
8198 /* If the following if() condition is not true, the db is corrupted.
8199 ** The call to dropCell() below will detect this. */
8200 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
8201 if( (iOff+szNew[i])<=(int)pBt->usableSize ){
8202 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
8203 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
8206 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
8210 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
8211 ** alignment */
8212 nMaxCells = (nMaxCells + 3)&~3;
8215 ** Allocate space for memory structures
8217 szScratch =
8218 nMaxCells*sizeof(u8*) /* b.apCell */
8219 + nMaxCells*sizeof(u16) /* b.szCell */
8220 + pBt->pageSize; /* aSpace1 */
8222 assert( szScratch<=7*(int)pBt->pageSize );
8223 b.apCell = sqlite3StackAllocRaw(0, szScratch );
8224 if( b.apCell==0 ){
8225 rc = SQLITE_NOMEM_BKPT;
8226 goto balance_cleanup;
8228 b.szCell = (u16*)&b.apCell[nMaxCells];
8229 aSpace1 = (u8*)&b.szCell[nMaxCells];
8230 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
8233 ** Load pointers to all cells on sibling pages and the divider cells
8234 ** into the local b.apCell[] array. Make copies of the divider cells
8235 ** into space obtained from aSpace1[]. The divider cells have already
8236 ** been removed from pParent.
8238 ** If the siblings are on leaf pages, then the child pointers of the
8239 ** divider cells are stripped from the cells before they are copied
8240 ** into aSpace1[]. In this way, all cells in b.apCell[] are without
8241 ** child pointers. If siblings are not leaves, then all cell in
8242 ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
8243 ** are alike.
8245 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
8246 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
8248 b.pRef = apOld[0];
8249 leafCorrection = b.pRef->leaf*4;
8250 leafData = b.pRef->intKeyLeaf;
8251 for(i=0; i<nOld; i++){
8252 MemPage *pOld = apOld[i];
8253 int limit = pOld->nCell;
8254 u8 *aData = pOld->aData;
8255 u16 maskPage = pOld->maskPage;
8256 u8 *piCell = aData + pOld->cellOffset;
8257 u8 *piEnd;
8258 VVA_ONLY( int nCellAtStart = b.nCell; )
8260 /* Verify that all sibling pages are of the same "type" (table-leaf,
8261 ** table-interior, index-leaf, or index-interior).
8263 if( pOld->aData[0]!=apOld[0]->aData[0] ){
8264 rc = SQLITE_CORRUPT_BKPT;
8265 goto balance_cleanup;
8268 /* Load b.apCell[] with pointers to all cells in pOld. If pOld
8269 ** contains overflow cells, include them in the b.apCell[] array
8270 ** in the correct spot.
8272 ** Note that when there are multiple overflow cells, it is always the
8273 ** case that they are sequential and adjacent. This invariant arises
8274 ** because multiple overflows can only occurs when inserting divider
8275 ** cells into a parent on a prior balance, and divider cells are always
8276 ** adjacent and are inserted in order. There is an assert() tagged
8277 ** with "NOTE 1" in the overflow cell insertion loop to prove this
8278 ** invariant.
8280 ** This must be done in advance. Once the balance starts, the cell
8281 ** offset section of the btree page will be overwritten and we will no
8282 ** long be able to find the cells if a pointer to each cell is not saved
8283 ** first.
8285 memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
8286 if( pOld->nOverflow>0 ){
8287 if( NEVER(limit<pOld->aiOvfl[0]) ){
8288 rc = SQLITE_CORRUPT_BKPT;
8289 goto balance_cleanup;
8291 limit = pOld->aiOvfl[0];
8292 for(j=0; j<limit; j++){
8293 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
8294 piCell += 2;
8295 b.nCell++;
8297 for(k=0; k<pOld->nOverflow; k++){
8298 assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
8299 b.apCell[b.nCell] = pOld->apOvfl[k];
8300 b.nCell++;
8303 piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
8304 while( piCell<piEnd ){
8305 assert( b.nCell<nMaxCells );
8306 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
8307 piCell += 2;
8308 b.nCell++;
8310 assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );
8312 cntOld[i] = b.nCell;
8313 if( i<nOld-1 && !leafData){
8314 u16 sz = (u16)szNew[i];
8315 u8 *pTemp;
8316 assert( b.nCell<nMaxCells );
8317 b.szCell[b.nCell] = sz;
8318 pTemp = &aSpace1[iSpace1];
8319 iSpace1 += sz;
8320 assert( sz<=pBt->maxLocal+23 );
8321 assert( iSpace1 <= (int)pBt->pageSize );
8322 memcpy(pTemp, apDiv[i], sz);
8323 b.apCell[b.nCell] = pTemp+leafCorrection;
8324 assert( leafCorrection==0 || leafCorrection==4 );
8325 b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
8326 if( !pOld->leaf ){
8327 assert( leafCorrection==0 );
8328 assert( pOld->hdrOffset==0 || CORRUPT_DB );
8329 /* The right pointer of the child page pOld becomes the left
8330 ** pointer of the divider cell */
8331 memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
8332 }else{
8333 assert( leafCorrection==4 );
8334 while( b.szCell[b.nCell]<4 ){
8335 /* Do not allow any cells smaller than 4 bytes. If a smaller cell
8336 ** does exist, pad it with 0x00 bytes. */
8337 assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
8338 assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
8339 aSpace1[iSpace1++] = 0x00;
8340 b.szCell[b.nCell]++;
8343 b.nCell++;
8348 ** Figure out the number of pages needed to hold all b.nCell cells.
8349 ** Store this number in "k". Also compute szNew[] which is the total
8350 ** size of all cells on the i-th page and cntNew[] which is the index
8351 ** in b.apCell[] of the cell that divides page i from page i+1.
8352 ** cntNew[k] should equal b.nCell.
8354 ** Values computed by this block:
8356 ** k: The total number of sibling pages
8357 ** szNew[i]: Spaced used on the i-th sibling page.
8358 ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
8359 ** the right of the i-th sibling page.
8360 ** usableSpace: Number of bytes of space available on each sibling.
8363 usableSpace = pBt->usableSize - 12 + leafCorrection;
8364 for(i=k=0; i<nOld; i++, k++){
8365 MemPage *p = apOld[i];
8366 b.apEnd[k] = p->aDataEnd;
8367 b.ixNx[k] = cntOld[i];
8368 if( k && b.ixNx[k]==b.ixNx[k-1] ){
8369 k--; /* Omit b.ixNx[] entry for child pages with no cells */
8371 if( !leafData ){
8372 k++;
8373 b.apEnd[k] = pParent->aDataEnd;
8374 b.ixNx[k] = cntOld[i]+1;
8376 assert( p->nFree>=0 );
8377 szNew[i] = usableSpace - p->nFree;
8378 for(j=0; j<p->nOverflow; j++){
8379 szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
8381 cntNew[i] = cntOld[i];
8383 k = nOld;
8384 for(i=0; i<k; i++){
8385 int sz;
8386 while( szNew[i]>usableSpace ){
8387 if( i+1>=k ){
8388 k = i+2;
8389 if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
8390 szNew[k-1] = 0;
8391 cntNew[k-1] = b.nCell;
8393 sz = 2 + cachedCellSize(&b, cntNew[i]-1);
8394 szNew[i] -= sz;
8395 if( !leafData ){
8396 if( cntNew[i]<b.nCell ){
8397 sz = 2 + cachedCellSize(&b, cntNew[i]);
8398 }else{
8399 sz = 0;
8402 szNew[i+1] += sz;
8403 cntNew[i]--;
8405 while( cntNew[i]<b.nCell ){
8406 sz = 2 + cachedCellSize(&b, cntNew[i]);
8407 if( szNew[i]+sz>usableSpace ) break;
8408 szNew[i] += sz;
8409 cntNew[i]++;
8410 if( !leafData ){
8411 if( cntNew[i]<b.nCell ){
8412 sz = 2 + cachedCellSize(&b, cntNew[i]);
8413 }else{
8414 sz = 0;
8417 szNew[i+1] -= sz;
8419 if( cntNew[i]>=b.nCell ){
8420 k = i+1;
8421 }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
8422 rc = SQLITE_CORRUPT_BKPT;
8423 goto balance_cleanup;
8428 ** The packing computed by the previous block is biased toward the siblings
8429 ** on the left side (siblings with smaller keys). The left siblings are
8430 ** always nearly full, while the right-most sibling might be nearly empty.
8431 ** The next block of code attempts to adjust the packing of siblings to
8432 ** get a better balance.
8434 ** This adjustment is more than an optimization. The packing above might
8435 ** be so out of balance as to be illegal. For example, the right-most
8436 ** sibling might be completely empty. This adjustment is not optional.
8438 for(i=k-1; i>0; i--){
8439 int szRight = szNew[i]; /* Size of sibling on the right */
8440 int szLeft = szNew[i-1]; /* Size of sibling on the left */
8441 int r; /* Index of right-most cell in left sibling */
8442 int d; /* Index of first cell to the left of right sibling */
8444 r = cntNew[i-1] - 1;
8445 d = r + 1 - leafData;
8446 (void)cachedCellSize(&b, d);
8448 int szR, szD;
8449 assert( d<nMaxCells );
8450 assert( r<nMaxCells );
8451 szR = cachedCellSize(&b, r);
8452 szD = b.szCell[d];
8453 if( szRight!=0
8454 && (bBulk || szRight+szD+2 > szLeft-(szR+(i==k-1?0:2)))){
8455 break;
8457 szRight += szD + 2;
8458 szLeft -= szR + 2;
8459 cntNew[i-1] = r;
8460 r--;
8461 d--;
8462 }while( r>=0 );
8463 szNew[i] = szRight;
8464 szNew[i-1] = szLeft;
8465 if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
8466 rc = SQLITE_CORRUPT_BKPT;
8467 goto balance_cleanup;
8471 /* Sanity check: For a non-corrupt database file one of the following
8472 ** must be true:
8473 ** (1) We found one or more cells (cntNew[0])>0), or
8474 ** (2) pPage is a virtual root page. A virtual root page is when
8475 ** the real root page is page 1 and we are the only child of
8476 ** that page.
8478 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
8479 TRACE(("BALANCE: old: %u(nc=%u) %u(nc=%u) %u(nc=%u)\n",
8480 apOld[0]->pgno, apOld[0]->nCell,
8481 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
8482 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
8486 ** Allocate k new pages. Reuse old pages where possible.
8488 pageFlags = apOld[0]->aData[0];
8489 for(i=0; i<k; i++){
8490 MemPage *pNew;
8491 if( i<nOld ){
8492 pNew = apNew[i] = apOld[i];
8493 apOld[i] = 0;
8494 rc = sqlite3PagerWrite(pNew->pDbPage);
8495 nNew++;
8496 if( sqlite3PagerPageRefcount(pNew->pDbPage)!=1+(i==(iParentIdx-nxDiv))
8497 && rc==SQLITE_OK
8499 rc = SQLITE_CORRUPT_BKPT;
8501 if( rc ) goto balance_cleanup;
8502 }else{
8503 assert( i>0 );
8504 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
8505 if( rc ) goto balance_cleanup;
8506 zeroPage(pNew, pageFlags);
8507 apNew[i] = pNew;
8508 nNew++;
8509 cntOld[i] = b.nCell;
8511 /* Set the pointer-map entry for the new sibling page. */
8512 if( ISAUTOVACUUM(pBt) ){
8513 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
8514 if( rc!=SQLITE_OK ){
8515 goto balance_cleanup;
8522 ** Reassign page numbers so that the new pages are in ascending order.
8523 ** This helps to keep entries in the disk file in order so that a scan
8524 ** of the table is closer to a linear scan through the file. That in turn
8525 ** helps the operating system to deliver pages from the disk more rapidly.
8527 ** An O(N*N) sort algorithm is used, but since N is never more than NB+2
8528 ** (5), that is not a performance concern.
8530 ** When NB==3, this one optimization makes the database about 25% faster
8531 ** for large insertions and deletions.
8533 for(i=0; i<nNew; i++){
8534 aPgno[i] = apNew[i]->pgno;
8535 assert( apNew[i]->pDbPage->flags & PGHDR_WRITEABLE );
8536 assert( apNew[i]->pDbPage->flags & PGHDR_DIRTY );
8538 for(i=0; i<nNew-1; i++){
8539 int iB = i;
8540 for(j=i+1; j<nNew; j++){
8541 if( apNew[j]->pgno < apNew[iB]->pgno ) iB = j;
8544 /* If apNew[i] has a page number that is bigger than any of the
8545 ** subsequence apNew[i] entries, then swap apNew[i] with the subsequent
8546 ** entry that has the smallest page number (which we know to be
8547 ** entry apNew[iB]).
8549 if( iB!=i ){
8550 Pgno pgnoA = apNew[i]->pgno;
8551 Pgno pgnoB = apNew[iB]->pgno;
8552 Pgno pgnoTemp = (PENDING_BYTE/pBt->pageSize)+1;
8553 u16 fgA = apNew[i]->pDbPage->flags;
8554 u16 fgB = apNew[iB]->pDbPage->flags;
8555 sqlite3PagerRekey(apNew[i]->pDbPage, pgnoTemp, fgB);
8556 sqlite3PagerRekey(apNew[iB]->pDbPage, pgnoA, fgA);
8557 sqlite3PagerRekey(apNew[i]->pDbPage, pgnoB, fgB);
8558 apNew[i]->pgno = pgnoB;
8559 apNew[iB]->pgno = pgnoA;
8563 TRACE(("BALANCE: new: %u(%u nc=%u) %u(%u nc=%u) %u(%u nc=%u) "
8564 "%u(%u nc=%u) %u(%u nc=%u)\n",
8565 apNew[0]->pgno, szNew[0], cntNew[0],
8566 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
8567 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
8568 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
8569 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
8570 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
8571 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
8572 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
8573 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
8576 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8577 assert( nNew>=1 && nNew<=ArraySize(apNew) );
8578 assert( apNew[nNew-1]!=0 );
8579 put4byte(pRight, apNew[nNew-1]->pgno);
8581 /* If the sibling pages are not leaves, ensure that the right-child pointer
8582 ** of the right-most new sibling page is set to the value that was
8583 ** originally in the same field of the right-most old sibling page. */
8584 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
8585 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
8586 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
8589 /* Make any required updates to pointer map entries associated with
8590 ** cells stored on sibling pages following the balance operation. Pointer
8591 ** map entries associated with divider cells are set by the insertCell()
8592 ** routine. The associated pointer map entries are:
8594 ** a) if the cell contains a reference to an overflow chain, the
8595 ** entry associated with the first page in the overflow chain, and
8597 ** b) if the sibling pages are not leaves, the child page associated
8598 ** with the cell.
8600 ** If the sibling pages are not leaves, then the pointer map entry
8601 ** associated with the right-child of each sibling may also need to be
8602 ** updated. This happens below, after the sibling pages have been
8603 ** populated, not here.
8605 if( ISAUTOVACUUM(pBt) ){
8606 MemPage *pOld;
8607 MemPage *pNew = pOld = apNew[0];
8608 int cntOldNext = pNew->nCell + pNew->nOverflow;
8609 int iNew = 0;
8610 int iOld = 0;
8612 for(i=0; i<b.nCell; i++){
8613 u8 *pCell = b.apCell[i];
8614 while( i==cntOldNext ){
8615 iOld++;
8616 assert( iOld<nNew || iOld<nOld );
8617 assert( iOld>=0 && iOld<NB );
8618 pOld = iOld<nNew ? apNew[iOld] : apOld[iOld];
8619 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
8621 if( i==cntNew[iNew] ){
8622 pNew = apNew[++iNew];
8623 if( !leafData ) continue;
8626 /* Cell pCell is destined for new sibling page pNew. Originally, it
8627 ** was either part of sibling page iOld (possibly an overflow cell),
8628 ** or else the divider cell to the left of sibling page iOld. So,
8629 ** if sibling page iOld had the same page number as pNew, and if
8630 ** pCell really was a part of sibling page iOld (not a divider or
8631 ** overflow cell), we can skip updating the pointer map entries. */
8632 if( iOld>=nNew
8633 || pNew->pgno!=aPgno[iOld]
8634 || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
8636 if( !leafCorrection ){
8637 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
8639 if( cachedCellSize(&b,i)>pNew->minLocal ){
8640 ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);
8642 if( rc ) goto balance_cleanup;
8647 /* Insert new divider cells into pParent. */
8648 for(i=0; i<nNew-1; i++){
8649 u8 *pCell;
8650 u8 *pTemp;
8651 int sz;
8652 u8 *pSrcEnd;
8653 MemPage *pNew = apNew[i];
8654 j = cntNew[i];
8656 assert( j<nMaxCells );
8657 assert( b.apCell[j]!=0 );
8658 pCell = b.apCell[j];
8659 sz = b.szCell[j] + leafCorrection;
8660 pTemp = &aOvflSpace[iOvflSpace];
8661 if( !pNew->leaf ){
8662 memcpy(&pNew->aData[8], pCell, 4);
8663 }else if( leafData ){
8664 /* If the tree is a leaf-data tree, and the siblings are leaves,
8665 ** then there is no divider cell in b.apCell[]. Instead, the divider
8666 ** cell consists of the integer key for the right-most cell of
8667 ** the sibling-page assembled above only.
8669 CellInfo info;
8670 j--;
8671 pNew->xParseCell(pNew, b.apCell[j], &info);
8672 pCell = pTemp;
8673 sz = 4 + putVarint(&pCell[4], info.nKey);
8674 pTemp = 0;
8675 }else{
8676 pCell -= 4;
8677 /* Obscure case for non-leaf-data trees: If the cell at pCell was
8678 ** previously stored on a leaf node, and its reported size was 4
8679 ** bytes, then it may actually be smaller than this
8680 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
8681 ** any cell). But it is important to pass the correct size to
8682 ** insertCell(), so reparse the cell now.
8684 ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
8685 ** and WITHOUT ROWID tables with exactly one column which is the
8686 ** primary key.
8688 if( b.szCell[j]==4 ){
8689 assert(leafCorrection==4);
8690 sz = pParent->xCellSize(pParent, pCell);
8693 iOvflSpace += sz;
8694 assert( sz<=pBt->maxLocal+23 );
8695 assert( iOvflSpace <= (int)pBt->pageSize );
8696 for(k=0; ALWAYS(k<NB*2) && b.ixNx[k]<=j; k++){}
8697 pSrcEnd = b.apEnd[k];
8698 if( SQLITE_OVERFLOW(pSrcEnd, pCell, pCell+sz) ){
8699 rc = SQLITE_CORRUPT_BKPT;
8700 goto balance_cleanup;
8702 rc = insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno);
8703 if( rc!=SQLITE_OK ) goto balance_cleanup;
8704 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8707 /* Now update the actual sibling pages. The order in which they are updated
8708 ** is important, as this code needs to avoid disrupting any page from which
8709 ** cells may still to be read. In practice, this means:
8711 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
8712 ** then it is not safe to update page apNew[iPg] until after
8713 ** the left-hand sibling apNew[iPg-1] has been updated.
8715 ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
8716 ** then it is not safe to update page apNew[iPg] until after
8717 ** the right-hand sibling apNew[iPg+1] has been updated.
8719 ** If neither of the above apply, the page is safe to update.
8721 ** The iPg value in the following loop starts at nNew-1 goes down
8722 ** to 0, then back up to nNew-1 again, thus making two passes over
8723 ** the pages. On the initial downward pass, only condition (1) above
8724 ** needs to be tested because (2) will always be true from the previous
8725 ** step. On the upward pass, both conditions are always true, so the
8726 ** upwards pass simply processes pages that were missed on the downward
8727 ** pass.
8729 for(i=1-nNew; i<nNew; i++){
8730 int iPg = i<0 ? -i : i;
8731 assert( iPg>=0 && iPg<nNew );
8732 assert( iPg>=1 || i>=0 );
8733 assert( iPg<ArraySize(cntOld) );
8734 if( abDone[iPg] ) continue; /* Skip pages already processed */
8735 if( i>=0 /* On the upwards pass, or... */
8736 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
8738 int iNew;
8739 int iOld;
8740 int nNewCell;
8742 /* Verify condition (1): If cells are moving left, update iPg
8743 ** only after iPg-1 has already been updated. */
8744 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
8746 /* Verify condition (2): If cells are moving right, update iPg
8747 ** only after iPg+1 has already been updated. */
8748 assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
8750 if( iPg==0 ){
8751 iNew = iOld = 0;
8752 nNewCell = cntNew[0];
8753 }else{
8754 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
8755 iNew = cntNew[iPg-1] + !leafData;
8756 nNewCell = cntNew[iPg] - iNew;
8759 rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
8760 if( rc ) goto balance_cleanup;
8761 abDone[iPg]++;
8762 apNew[iPg]->nFree = usableSpace-szNew[iPg];
8763 assert( apNew[iPg]->nOverflow==0 );
8764 assert( apNew[iPg]->nCell==nNewCell );
8768 /* All pages have been processed exactly once */
8769 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
8771 assert( nOld>0 );
8772 assert( nNew>0 );
8774 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
8775 /* The root page of the b-tree now contains no cells. The only sibling
8776 ** page is the right-child of the parent. Copy the contents of the
8777 ** child page into the parent, decreasing the overall height of the
8778 ** b-tree structure by one. This is described as the "balance-shallower"
8779 ** sub-algorithm in some documentation.
8781 ** If this is an auto-vacuum database, the call to copyNodeContent()
8782 ** sets all pointer-map entries corresponding to database image pages
8783 ** for which the pointer is stored within the content being copied.
8785 ** It is critical that the child page be defragmented before being
8786 ** copied into the parent, because if the parent is page 1 then it will
8787 ** by smaller than the child due to the database header, and so all the
8788 ** free space needs to be up front.
8790 assert( nNew==1 || CORRUPT_DB );
8791 rc = defragmentPage(apNew[0], -1);
8792 testcase( rc!=SQLITE_OK );
8793 assert( apNew[0]->nFree ==
8794 (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
8795 - apNew[0]->nCell*2)
8796 || rc!=SQLITE_OK
8798 copyNodeContent(apNew[0], pParent, &rc);
8799 freePage(apNew[0], &rc);
8800 }else if( ISAUTOVACUUM(pBt) && !leafCorrection ){
8801 /* Fix the pointer map entries associated with the right-child of each
8802 ** sibling page. All other pointer map entries have already been taken
8803 ** care of. */
8804 for(i=0; i<nNew; i++){
8805 u32 key = get4byte(&apNew[i]->aData[8]);
8806 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
8810 assert( pParent->isInit );
8811 TRACE(("BALANCE: finished: old=%u new=%u cells=%u\n",
8812 nOld, nNew, b.nCell));
8814 /* Free any old pages that were not reused as new pages.
8816 for(i=nNew; i<nOld; i++){
8817 freePage(apOld[i], &rc);
8820 #if 0
8821 if( ISAUTOVACUUM(pBt) && rc==SQLITE_OK && apNew[0]->isInit ){
8822 /* The ptrmapCheckPages() contains assert() statements that verify that
8823 ** all pointer map pages are set correctly. This is helpful while
8824 ** debugging. This is usually disabled because a corrupt database may
8825 ** cause an assert() statement to fail. */
8826 ptrmapCheckPages(apNew, nNew);
8827 ptrmapCheckPages(&pParent, 1);
8829 #endif
8832 ** Cleanup before returning.
8834 balance_cleanup:
8835 sqlite3StackFree(0, b.apCell);
8836 for(i=0; i<nOld; i++){
8837 releasePage(apOld[i]);
8839 for(i=0; i<nNew; i++){
8840 releasePage(apNew[i]);
8843 return rc;
8848 ** This function is called when the root page of a b-tree structure is
8849 ** overfull (has one or more overflow pages).
8851 ** A new child page is allocated and the contents of the current root
8852 ** page, including overflow cells, are copied into the child. The root
8853 ** page is then overwritten to make it an empty page with the right-child
8854 ** pointer pointing to the new page.
8856 ** Before returning, all pointer-map entries corresponding to pages
8857 ** that the new child-page now contains pointers to are updated. The
8858 ** entry corresponding to the new right-child pointer of the root
8859 ** page is also updated.
8861 ** If successful, *ppChild is set to contain a reference to the child
8862 ** page and SQLITE_OK is returned. In this case the caller is required
8863 ** to call releasePage() on *ppChild exactly once. If an error occurs,
8864 ** an error code is returned and *ppChild is set to 0.
8866 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
8867 int rc; /* Return value from subprocedures */
8868 MemPage *pChild = 0; /* Pointer to a new child page */
8869 Pgno pgnoChild = 0; /* Page number of the new child page */
8870 BtShared *pBt = pRoot->pBt; /* The BTree */
8872 assert( pRoot->nOverflow>0 );
8873 assert( sqlite3_mutex_held(pBt->mutex) );
8875 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
8876 ** page that will become the new right-child of pPage. Copy the contents
8877 ** of the node stored on pRoot into the new child page.
8879 rc = sqlite3PagerWrite(pRoot->pDbPage);
8880 if( rc==SQLITE_OK ){
8881 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
8882 copyNodeContent(pRoot, pChild, &rc);
8883 if( ISAUTOVACUUM(pBt) ){
8884 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
8887 if( rc ){
8888 *ppChild = 0;
8889 releasePage(pChild);
8890 return rc;
8892 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
8893 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
8894 assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
8896 TRACE(("BALANCE: copy root %u into %u\n", pRoot->pgno, pChild->pgno));
8898 /* Copy the overflow cells from pRoot to pChild */
8899 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
8900 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
8901 memcpy(pChild->apOvfl, pRoot->apOvfl,
8902 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
8903 pChild->nOverflow = pRoot->nOverflow;
8905 /* Zero the contents of pRoot. Then install pChild as the right-child. */
8906 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
8907 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
8909 *ppChild = pChild;
8910 return SQLITE_OK;
8914 ** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid
8915 ** on the same B-tree as pCur.
8917 ** This can occur if a database is corrupt with two or more SQL tables
8918 ** pointing to the same b-tree. If an insert occurs on one SQL table
8919 ** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL
8920 ** table linked to the same b-tree. If the secondary insert causes a
8921 ** rebalance, that can change content out from under the cursor on the
8922 ** first SQL table, violating invariants on the first insert.
8924 static int anotherValidCursor(BtCursor *pCur){
8925 BtCursor *pOther;
8926 for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){
8927 if( pOther!=pCur
8928 && pOther->eState==CURSOR_VALID
8929 && pOther->pPage==pCur->pPage
8931 return SQLITE_CORRUPT_BKPT;
8934 return SQLITE_OK;
8938 ** The page that pCur currently points to has just been modified in
8939 ** some way. This function figures out if this modification means the
8940 ** tree needs to be balanced, and if so calls the appropriate balancing
8941 ** routine. Balancing routines are:
8943 ** balance_quick()
8944 ** balance_deeper()
8945 ** balance_nonroot()
8947 static int balance(BtCursor *pCur){
8948 int rc = SQLITE_OK;
8949 u8 aBalanceQuickSpace[13];
8950 u8 *pFree = 0;
8952 VVA_ONLY( int balance_quick_called = 0 );
8953 VVA_ONLY( int balance_deeper_called = 0 );
8955 do {
8956 int iPage;
8957 MemPage *pPage = pCur->pPage;
8959 if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
8960 if( pPage->nOverflow==0 && pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){
8961 /* No rebalance required as long as:
8962 ** (1) There are no overflow cells
8963 ** (2) The amount of free space on the page is less than 2/3rds of
8964 ** the total usable space on the page. */
8965 break;
8966 }else if( (iPage = pCur->iPage)==0 ){
8967 if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){
8968 /* The root page of the b-tree is overfull. In this case call the
8969 ** balance_deeper() function to create a new child for the root-page
8970 ** and copy the current contents of the root-page to it. The
8971 ** next iteration of the do-loop will balance the child page.
8973 assert( balance_deeper_called==0 );
8974 VVA_ONLY( balance_deeper_called++ );
8975 rc = balance_deeper(pPage, &pCur->apPage[1]);
8976 if( rc==SQLITE_OK ){
8977 pCur->iPage = 1;
8978 pCur->ix = 0;
8979 pCur->aiIdx[0] = 0;
8980 pCur->apPage[0] = pPage;
8981 pCur->pPage = pCur->apPage[1];
8982 assert( pCur->pPage->nOverflow );
8984 }else{
8985 break;
8987 }else if( sqlite3PagerPageRefcount(pPage->pDbPage)>1 ){
8988 /* The page being written is not a root page, and there is currently
8989 ** more than one reference to it. This only happens if the page is one
8990 ** of its own ancestor pages. Corruption. */
8991 rc = SQLITE_CORRUPT_BKPT;
8992 }else{
8993 MemPage * const pParent = pCur->apPage[iPage-1];
8994 int const iIdx = pCur->aiIdx[iPage-1];
8996 rc = sqlite3PagerWrite(pParent->pDbPage);
8997 if( rc==SQLITE_OK && pParent->nFree<0 ){
8998 rc = btreeComputeFreeSpace(pParent);
9000 if( rc==SQLITE_OK ){
9001 #ifndef SQLITE_OMIT_QUICKBALANCE
9002 if( pPage->intKeyLeaf
9003 && pPage->nOverflow==1
9004 && pPage->aiOvfl[0]==pPage->nCell
9005 && pParent->pgno!=1
9006 && pParent->nCell==iIdx
9008 /* Call balance_quick() to create a new sibling of pPage on which
9009 ** to store the overflow cell. balance_quick() inserts a new cell
9010 ** into pParent, which may cause pParent overflow. If this
9011 ** happens, the next iteration of the do-loop will balance pParent
9012 ** use either balance_nonroot() or balance_deeper(). Until this
9013 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
9014 ** buffer.
9016 ** The purpose of the following assert() is to check that only a
9017 ** single call to balance_quick() is made for each call to this
9018 ** function. If this were not verified, a subtle bug involving reuse
9019 ** of the aBalanceQuickSpace[] might sneak in.
9021 assert( balance_quick_called==0 );
9022 VVA_ONLY( balance_quick_called++ );
9023 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
9024 }else
9025 #endif
9027 /* In this case, call balance_nonroot() to redistribute cells
9028 ** between pPage and up to 2 of its sibling pages. This involves
9029 ** modifying the contents of pParent, which may cause pParent to
9030 ** become overfull or underfull. The next iteration of the do-loop
9031 ** will balance the parent page to correct this.
9033 ** If the parent page becomes overfull, the overflow cell or cells
9034 ** are stored in the pSpace buffer allocated immediately below.
9035 ** A subsequent iteration of the do-loop will deal with this by
9036 ** calling balance_nonroot() (balance_deeper() may be called first,
9037 ** but it doesn't deal with overflow cells - just moves them to a
9038 ** different page). Once this subsequent call to balance_nonroot()
9039 ** has completed, it is safe to release the pSpace buffer used by
9040 ** the previous call, as the overflow cell data will have been
9041 ** copied either into the body of a database page or into the new
9042 ** pSpace buffer passed to the latter call to balance_nonroot().
9044 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
9045 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
9046 pCur->hints&BTREE_BULKLOAD);
9047 if( pFree ){
9048 /* If pFree is not NULL, it points to the pSpace buffer used
9049 ** by a previous call to balance_nonroot(). Its contents are
9050 ** now stored either on real database pages or within the
9051 ** new pSpace buffer, so it may be safely freed here. */
9052 sqlite3PageFree(pFree);
9055 /* The pSpace buffer will be freed after the next call to
9056 ** balance_nonroot(), or just before this function returns, whichever
9057 ** comes first. */
9058 pFree = pSpace;
9062 pPage->nOverflow = 0;
9064 /* The next iteration of the do-loop balances the parent page. */
9065 releasePage(pPage);
9066 pCur->iPage--;
9067 assert( pCur->iPage>=0 );
9068 pCur->pPage = pCur->apPage[pCur->iPage];
9070 }while( rc==SQLITE_OK );
9072 if( pFree ){
9073 sqlite3PageFree(pFree);
9075 return rc;
9078 /* Overwrite content from pX into pDest. Only do the write if the
9079 ** content is different from what is already there.
9081 static int btreeOverwriteContent(
9082 MemPage *pPage, /* MemPage on which writing will occur */
9083 u8 *pDest, /* Pointer to the place to start writing */
9084 const BtreePayload *pX, /* Source of data to write */
9085 int iOffset, /* Offset of first byte to write */
9086 int iAmt /* Number of bytes to be written */
9088 int nData = pX->nData - iOffset;
9089 if( nData<=0 ){
9090 /* Overwriting with zeros */
9091 int i;
9092 for(i=0; i<iAmt && pDest[i]==0; i++){}
9093 if( i<iAmt ){
9094 int rc = sqlite3PagerWrite(pPage->pDbPage);
9095 if( rc ) return rc;
9096 memset(pDest + i, 0, iAmt - i);
9098 }else{
9099 if( nData<iAmt ){
9100 /* Mixed read data and zeros at the end. Make a recursive call
9101 ** to write the zeros then fall through to write the real data */
9102 int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
9103 iAmt-nData);
9104 if( rc ) return rc;
9105 iAmt = nData;
9107 if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
9108 int rc = sqlite3PagerWrite(pPage->pDbPage);
9109 if( rc ) return rc;
9110 /* In a corrupt database, it is possible for the source and destination
9111 ** buffers to overlap. This is harmless since the database is already
9112 ** corrupt but it does cause valgrind and ASAN warnings. So use
9113 ** memmove(). */
9114 memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
9117 return SQLITE_OK;
9121 ** Overwrite the cell that cursor pCur is pointing to with fresh content
9122 ** contained in pX. In this variant, pCur is pointing to an overflow
9123 ** cell.
9125 static SQLITE_NOINLINE int btreeOverwriteOverflowCell(
9126 BtCursor *pCur, /* Cursor pointing to cell to overwrite */
9127 const BtreePayload *pX /* Content to write into the cell */
9129 int iOffset; /* Next byte of pX->pData to write */
9130 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
9131 int rc; /* Return code */
9132 MemPage *pPage = pCur->pPage; /* Page being written */
9133 BtShared *pBt; /* Btree */
9134 Pgno ovflPgno; /* Next overflow page to write */
9135 u32 ovflPageSize; /* Size to write on overflow page */
9137 assert( pCur->info.nLocal<nTotal ); /* pCur is an overflow cell */
9139 /* Overwrite the local portion first */
9140 rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
9141 0, pCur->info.nLocal);
9142 if( rc ) return rc;
9144 /* Now overwrite the overflow pages */
9145 iOffset = pCur->info.nLocal;
9146 assert( nTotal>=0 );
9147 assert( iOffset>=0 );
9148 ovflPgno = get4byte(pCur->info.pPayload + iOffset);
9149 pBt = pPage->pBt;
9150 ovflPageSize = pBt->usableSize - 4;
9152 rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
9153 if( rc ) return rc;
9154 if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 || pPage->isInit ){
9155 rc = SQLITE_CORRUPT_BKPT;
9156 }else{
9157 if( iOffset+ovflPageSize<(u32)nTotal ){
9158 ovflPgno = get4byte(pPage->aData);
9159 }else{
9160 ovflPageSize = nTotal - iOffset;
9162 rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
9163 iOffset, ovflPageSize);
9165 sqlite3PagerUnref(pPage->pDbPage);
9166 if( rc ) return rc;
9167 iOffset += ovflPageSize;
9168 }while( iOffset<nTotal );
9169 return SQLITE_OK;
9173 ** Overwrite the cell that cursor pCur is pointing to with fresh content
9174 ** contained in pX.
9176 static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
9177 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
9178 MemPage *pPage = pCur->pPage; /* Page being written */
9180 if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd
9181 || pCur->info.pPayload < pPage->aData + pPage->cellOffset
9183 return SQLITE_CORRUPT_BKPT;
9185 if( pCur->info.nLocal==nTotal ){
9186 /* The entire cell is local */
9187 return btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
9188 0, pCur->info.nLocal);
9189 }else{
9190 /* The cell contains overflow content */
9191 return btreeOverwriteOverflowCell(pCur, pX);
9197 ** Insert a new record into the BTree. The content of the new record
9198 ** is described by the pX object. The pCur cursor is used only to
9199 ** define what table the record should be inserted into, and is left
9200 ** pointing at a random location.
9202 ** For a table btree (used for rowid tables), only the pX.nKey value of
9203 ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
9204 ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
9205 ** hold the content of the row.
9207 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
9208 ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
9209 ** pX.pData,nData,nZero fields must be zero.
9211 ** If the seekResult parameter is non-zero, then a successful call to
9212 ** sqlite3BtreeIndexMoveto() to seek cursor pCur to (pKey,nKey) has already
9213 ** been performed. In other words, if seekResult!=0 then the cursor
9214 ** is currently pointing to a cell that will be adjacent to the cell
9215 ** to be inserted. If seekResult<0 then pCur points to a cell that is
9216 ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
9217 ** that is larger than (pKey,nKey).
9219 ** If seekResult==0, that means pCur is pointing at some unknown location.
9220 ** In that case, this routine must seek the cursor to the correct insertion
9221 ** point for (pKey,nKey) before doing the insertion. For index btrees,
9222 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
9223 ** key values and pX->aMem can be used instead of pX->pKey to avoid having
9224 ** to decode the key.
9226 int sqlite3BtreeInsert(
9227 BtCursor *pCur, /* Insert data into the table of this cursor */
9228 const BtreePayload *pX, /* Content of the row to be inserted */
9229 int flags, /* True if this is likely an append */
9230 int seekResult /* Result of prior IndexMoveto() call */
9232 int rc;
9233 int loc = seekResult; /* -1: before desired location +1: after */
9234 int szNew = 0;
9235 int idx;
9236 MemPage *pPage;
9237 Btree *p = pCur->pBtree;
9238 unsigned char *oldCell;
9239 unsigned char *newCell = 0;
9241 assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND|BTREE_PREFORMAT))==flags );
9242 assert( (flags & BTREE_PREFORMAT)==0 || seekResult || pCur->pKeyInfo==0 );
9244 /* Save the positions of any other cursors open on this table.
9246 ** In some cases, the call to btreeMoveto() below is a no-op. For
9247 ** example, when inserting data into a table with auto-generated integer
9248 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
9249 ** integer key to use. It then calls this function to actually insert the
9250 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
9251 ** that the cursor is already where it needs to be and returns without
9252 ** doing any work. To avoid thwarting these optimizations, it is important
9253 ** not to clear the cursor here.
9255 if( pCur->curFlags & BTCF_Multiple ){
9256 rc = saveAllCursors(p->pBt, pCur->pgnoRoot, pCur);
9257 if( rc ) return rc;
9258 if( loc && pCur->iPage<0 ){
9259 /* This can only happen if the schema is corrupt such that there is more
9260 ** than one table or index with the same root page as used by the cursor.
9261 ** Which can only happen if the SQLITE_NoSchemaError flag was set when
9262 ** the schema was loaded. This cannot be asserted though, as a user might
9263 ** set the flag, load the schema, and then unset the flag. */
9264 return SQLITE_CORRUPT_BKPT;
9268 /* Ensure that the cursor is not in the CURSOR_FAULT state and that it
9269 ** points to a valid cell.
9271 if( pCur->eState>=CURSOR_REQUIRESEEK ){
9272 testcase( pCur->eState==CURSOR_REQUIRESEEK );
9273 testcase( pCur->eState==CURSOR_FAULT );
9274 rc = moveToRoot(pCur);
9275 if( rc && rc!=SQLITE_EMPTY ) return rc;
9278 assert( cursorOwnsBtShared(pCur) );
9279 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
9280 && p->pBt->inTransaction==TRANS_WRITE
9281 && (p->pBt->btsFlags & BTS_READ_ONLY)==0 );
9282 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
9284 /* Assert that the caller has been consistent. If this cursor was opened
9285 ** expecting an index b-tree, then the caller should be inserting blob
9286 ** keys with no associated data. If the cursor was opened expecting an
9287 ** intkey table, the caller should be inserting integer keys with a
9288 ** blob of associated data. */
9289 assert( (flags & BTREE_PREFORMAT) || (pX->pKey==0)==(pCur->pKeyInfo==0) );
9291 if( pCur->pKeyInfo==0 ){
9292 assert( pX->pKey==0 );
9293 /* If this is an insert into a table b-tree, invalidate any incrblob
9294 ** cursors open on the row being replaced */
9295 if( p->hasIncrblobCur ){
9296 invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
9299 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
9300 ** to a row with the same key as the new entry being inserted.
9302 #ifdef SQLITE_DEBUG
9303 if( flags & BTREE_SAVEPOSITION ){
9304 assert( pCur->curFlags & BTCF_ValidNKey );
9305 assert( pX->nKey==pCur->info.nKey );
9306 assert( loc==0 );
9308 #endif
9310 /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
9311 ** that the cursor is not pointing to a row to be overwritten.
9312 ** So do a complete check.
9314 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
9315 /* The cursor is pointing to the entry that is to be
9316 ** overwritten */
9317 assert( pX->nData>=0 && pX->nZero>=0 );
9318 if( pCur->info.nSize!=0
9319 && pCur->info.nPayload==(u32)pX->nData+pX->nZero
9321 /* New entry is the same size as the old. Do an overwrite */
9322 return btreeOverwriteCell(pCur, pX);
9324 assert( loc==0 );
9325 }else if( loc==0 ){
9326 /* The cursor is *not* pointing to the cell to be overwritten, nor
9327 ** to an adjacent cell. Move the cursor so that it is pointing either
9328 ** to the cell to be overwritten or an adjacent cell.
9330 rc = sqlite3BtreeTableMoveto(pCur, pX->nKey,
9331 (flags & BTREE_APPEND)!=0, &loc);
9332 if( rc ) return rc;
9334 }else{
9335 /* This is an index or a WITHOUT ROWID table */
9337 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
9338 ** to a row with the same key as the new entry being inserted.
9340 assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
9342 /* If the cursor is not already pointing either to the cell to be
9343 ** overwritten, or if a new cell is being inserted, if the cursor is
9344 ** not pointing to an immediately adjacent cell, then move the cursor
9345 ** so that it does.
9347 if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
9348 if( pX->nMem ){
9349 UnpackedRecord r;
9350 r.pKeyInfo = pCur->pKeyInfo;
9351 r.aMem = pX->aMem;
9352 r.nField = pX->nMem;
9353 r.default_rc = 0;
9354 r.eqSeen = 0;
9355 rc = sqlite3BtreeIndexMoveto(pCur, &r, &loc);
9356 }else{
9357 rc = btreeMoveto(pCur, pX->pKey, pX->nKey,
9358 (flags & BTREE_APPEND)!=0, &loc);
9360 if( rc ) return rc;
9363 /* If the cursor is currently pointing to an entry to be overwritten
9364 ** and the new content is the same as as the old, then use the
9365 ** overwrite optimization.
9367 if( loc==0 ){
9368 getCellInfo(pCur);
9369 if( pCur->info.nKey==pX->nKey ){
9370 BtreePayload x2;
9371 x2.pData = pX->pKey;
9372 x2.nData = pX->nKey;
9373 x2.nZero = 0;
9374 return btreeOverwriteCell(pCur, &x2);
9378 assert( pCur->eState==CURSOR_VALID
9379 || (pCur->eState==CURSOR_INVALID && loc) || CORRUPT_DB );
9381 pPage = pCur->pPage;
9382 assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) );
9383 assert( pPage->leaf || !pPage->intKey );
9384 if( pPage->nFree<0 ){
9385 if( NEVER(pCur->eState>CURSOR_INVALID) ){
9386 /* ^^^^^--- due to the moveToRoot() call above */
9387 rc = SQLITE_CORRUPT_BKPT;
9388 }else{
9389 rc = btreeComputeFreeSpace(pPage);
9391 if( rc ) return rc;
9394 TRACE(("INSERT: table=%u nkey=%lld ndata=%u page=%u %s\n",
9395 pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
9396 loc==0 ? "overwrite" : "new entry"));
9397 assert( pPage->isInit || CORRUPT_DB );
9398 newCell = p->pBt->pTmpSpace;
9399 assert( newCell!=0 );
9400 assert( BTREE_PREFORMAT==OPFLAG_PREFORMAT );
9401 if( flags & BTREE_PREFORMAT ){
9402 rc = SQLITE_OK;
9403 szNew = p->pBt->nPreformatSize;
9404 if( szNew<4 ) szNew = 4;
9405 if( ISAUTOVACUUM(p->pBt) && szNew>pPage->maxLocal ){
9406 CellInfo info;
9407 pPage->xParseCell(pPage, newCell, &info);
9408 if( info.nPayload!=info.nLocal ){
9409 Pgno ovfl = get4byte(&newCell[szNew-4]);
9410 ptrmapPut(p->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, &rc);
9411 if( NEVER(rc) ) goto end_insert;
9414 }else{
9415 rc = fillInCell(pPage, newCell, pX, &szNew);
9416 if( rc ) goto end_insert;
9418 assert( szNew==pPage->xCellSize(pPage, newCell) );
9419 assert( szNew <= MX_CELL_SIZE(p->pBt) );
9420 idx = pCur->ix;
9421 pCur->info.nSize = 0;
9422 if( loc==0 ){
9423 CellInfo info;
9424 assert( idx>=0 );
9425 if( idx>=pPage->nCell ){
9426 return SQLITE_CORRUPT_BKPT;
9428 rc = sqlite3PagerWrite(pPage->pDbPage);
9429 if( rc ){
9430 goto end_insert;
9432 oldCell = findCell(pPage, idx);
9433 if( !pPage->leaf ){
9434 memcpy(newCell, oldCell, 4);
9436 BTREE_CLEAR_CELL(rc, pPage, oldCell, info);
9437 testcase( pCur->curFlags & BTCF_ValidOvfl );
9438 invalidateOverflowCache(pCur);
9439 if( info.nSize==szNew && info.nLocal==info.nPayload
9440 && (!ISAUTOVACUUM(p->pBt) || szNew<pPage->minLocal)
9442 /* Overwrite the old cell with the new if they are the same size.
9443 ** We could also try to do this if the old cell is smaller, then add
9444 ** the leftover space to the free list. But experiments show that
9445 ** doing that is no faster then skipping this optimization and just
9446 ** calling dropCell() and insertCell().
9448 ** This optimization cannot be used on an autovacuum database if the
9449 ** new entry uses overflow pages, as the insertCell() call below is
9450 ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
9451 assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
9452 if( oldCell < pPage->aData+pPage->hdrOffset+10 ){
9453 return SQLITE_CORRUPT_BKPT;
9455 if( oldCell+szNew > pPage->aDataEnd ){
9456 return SQLITE_CORRUPT_BKPT;
9458 memcpy(oldCell, newCell, szNew);
9459 return SQLITE_OK;
9461 dropCell(pPage, idx, info.nSize, &rc);
9462 if( rc ) goto end_insert;
9463 }else if( loc<0 && pPage->nCell>0 ){
9464 assert( pPage->leaf );
9465 idx = ++pCur->ix;
9466 pCur->curFlags &= ~BTCF_ValidNKey;
9467 }else{
9468 assert( pPage->leaf );
9470 rc = insertCellFast(pPage, idx, newCell, szNew);
9471 assert( pPage->nOverflow==0 || rc==SQLITE_OK );
9472 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
9474 /* If no error has occurred and pPage has an overflow cell, call balance()
9475 ** to redistribute the cells within the tree. Since balance() may move
9476 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
9477 ** variables.
9479 ** Previous versions of SQLite called moveToRoot() to move the cursor
9480 ** back to the root page as balance() used to invalidate the contents
9481 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
9482 ** set the cursor state to "invalid". This makes common insert operations
9483 ** slightly faster.
9485 ** There is a subtle but important optimization here too. When inserting
9486 ** multiple records into an intkey b-tree using a single cursor (as can
9487 ** happen while processing an "INSERT INTO ... SELECT" statement), it
9488 ** is advantageous to leave the cursor pointing to the last entry in
9489 ** the b-tree if possible. If the cursor is left pointing to the last
9490 ** entry in the table, and the next row inserted has an integer key
9491 ** larger than the largest existing key, it is possible to insert the
9492 ** row without seeking the cursor. This can be a big performance boost.
9494 if( pPage->nOverflow ){
9495 assert( rc==SQLITE_OK );
9496 pCur->curFlags &= ~(BTCF_ValidNKey);
9497 rc = balance(pCur);
9499 /* Must make sure nOverflow is reset to zero even if the balance()
9500 ** fails. Internal data structure corruption will result otherwise.
9501 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
9502 ** from trying to save the current position of the cursor. */
9503 pCur->pPage->nOverflow = 0;
9504 pCur->eState = CURSOR_INVALID;
9505 if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
9506 btreeReleaseAllCursorPages(pCur);
9507 if( pCur->pKeyInfo ){
9508 assert( pCur->pKey==0 );
9509 pCur->pKey = sqlite3Malloc( pX->nKey );
9510 if( pCur->pKey==0 ){
9511 rc = SQLITE_NOMEM;
9512 }else{
9513 memcpy(pCur->pKey, pX->pKey, pX->nKey);
9516 pCur->eState = CURSOR_REQUIRESEEK;
9517 pCur->nKey = pX->nKey;
9520 assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
9522 end_insert:
9523 return rc;
9527 ** This function is used as part of copying the current row from cursor
9528 ** pSrc into cursor pDest. If the cursors are open on intkey tables, then
9529 ** parameter iKey is used as the rowid value when the record is copied
9530 ** into pDest. Otherwise, the record is copied verbatim.
9532 ** This function does not actually write the new value to cursor pDest.
9533 ** Instead, it creates and populates any required overflow pages and
9534 ** writes the data for the new cell into the BtShared.pTmpSpace buffer
9535 ** for the destination database. The size of the cell, in bytes, is left
9536 ** in BtShared.nPreformatSize. The caller completes the insertion by
9537 ** calling sqlite3BtreeInsert() with the BTREE_PREFORMAT flag specified.
9539 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
9541 int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 iKey){
9542 BtShared *pBt = pDest->pBt;
9543 u8 *aOut = pBt->pTmpSpace; /* Pointer to next output buffer */
9544 const u8 *aIn; /* Pointer to next input buffer */
9545 u32 nIn; /* Size of input buffer aIn[] */
9546 u32 nRem; /* Bytes of data still to copy */
9548 getCellInfo(pSrc);
9549 if( pSrc->info.nPayload<0x80 ){
9550 *(aOut++) = pSrc->info.nPayload;
9551 }else{
9552 aOut += sqlite3PutVarint(aOut, pSrc->info.nPayload);
9554 if( pDest->pKeyInfo==0 ) aOut += putVarint(aOut, iKey);
9555 nIn = pSrc->info.nLocal;
9556 aIn = pSrc->info.pPayload;
9557 if( aIn+nIn>pSrc->pPage->aDataEnd ){
9558 return SQLITE_CORRUPT_BKPT;
9560 nRem = pSrc->info.nPayload;
9561 if( nIn==nRem && nIn<pDest->pPage->maxLocal ){
9562 memcpy(aOut, aIn, nIn);
9563 pBt->nPreformatSize = nIn + (aOut - pBt->pTmpSpace);
9564 return SQLITE_OK;
9565 }else{
9566 int rc = SQLITE_OK;
9567 Pager *pSrcPager = pSrc->pBt->pPager;
9568 u8 *pPgnoOut = 0;
9569 Pgno ovflIn = 0;
9570 DbPage *pPageIn = 0;
9571 MemPage *pPageOut = 0;
9572 u32 nOut; /* Size of output buffer aOut[] */
9574 nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload);
9575 pBt->nPreformatSize = nOut + (aOut - pBt->pTmpSpace);
9576 if( nOut<pSrc->info.nPayload ){
9577 pPgnoOut = &aOut[nOut];
9578 pBt->nPreformatSize += 4;
9581 if( nRem>nIn ){
9582 if( aIn+nIn+4>pSrc->pPage->aDataEnd ){
9583 return SQLITE_CORRUPT_BKPT;
9585 ovflIn = get4byte(&pSrc->info.pPayload[nIn]);
9588 do {
9589 nRem -= nOut;
9591 assert( nOut>0 );
9592 if( nIn>0 ){
9593 int nCopy = MIN(nOut, nIn);
9594 memcpy(aOut, aIn, nCopy);
9595 nOut -= nCopy;
9596 nIn -= nCopy;
9597 aOut += nCopy;
9598 aIn += nCopy;
9600 if( nOut>0 ){
9601 sqlite3PagerUnref(pPageIn);
9602 pPageIn = 0;
9603 rc = sqlite3PagerGet(pSrcPager, ovflIn, &pPageIn, PAGER_GET_READONLY);
9604 if( rc==SQLITE_OK ){
9605 aIn = (const u8*)sqlite3PagerGetData(pPageIn);
9606 ovflIn = get4byte(aIn);
9607 aIn += 4;
9608 nIn = pSrc->pBt->usableSize - 4;
9611 }while( rc==SQLITE_OK && nOut>0 );
9613 if( rc==SQLITE_OK && nRem>0 && ALWAYS(pPgnoOut) ){
9614 Pgno pgnoNew;
9615 MemPage *pNew = 0;
9616 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
9617 put4byte(pPgnoOut, pgnoNew);
9618 if( ISAUTOVACUUM(pBt) && pPageOut ){
9619 ptrmapPut(pBt, pgnoNew, PTRMAP_OVERFLOW2, pPageOut->pgno, &rc);
9621 releasePage(pPageOut);
9622 pPageOut = pNew;
9623 if( pPageOut ){
9624 pPgnoOut = pPageOut->aData;
9625 put4byte(pPgnoOut, 0);
9626 aOut = &pPgnoOut[4];
9627 nOut = MIN(pBt->usableSize - 4, nRem);
9630 }while( nRem>0 && rc==SQLITE_OK );
9632 releasePage(pPageOut);
9633 sqlite3PagerUnref(pPageIn);
9634 return rc;
9639 ** Delete the entry that the cursor is pointing to.
9641 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
9642 ** the cursor is left pointing at an arbitrary location after the delete.
9643 ** But if that bit is set, then the cursor is left in a state such that
9644 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
9645 ** as it would have been on if the call to BtreeDelete() had been omitted.
9647 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
9648 ** associated with a single table entry and its indexes. Only one of those
9649 ** deletes is considered the "primary" delete. The primary delete occurs
9650 ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
9651 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
9652 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
9653 ** but which might be used by alternative storage engines.
9655 int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
9656 Btree *p = pCur->pBtree;
9657 BtShared *pBt = p->pBt;
9658 int rc; /* Return code */
9659 MemPage *pPage; /* Page to delete cell from */
9660 unsigned char *pCell; /* Pointer to cell to delete */
9661 int iCellIdx; /* Index of cell to delete */
9662 int iCellDepth; /* Depth of node containing pCell */
9663 CellInfo info; /* Size of the cell being deleted */
9664 u8 bPreserve; /* Keep cursor valid. 2 for CURSOR_SKIPNEXT */
9666 assert( cursorOwnsBtShared(pCur) );
9667 assert( pBt->inTransaction==TRANS_WRITE );
9668 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9669 assert( pCur->curFlags & BTCF_WriteFlag );
9670 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
9671 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
9672 assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
9673 if( pCur->eState!=CURSOR_VALID ){
9674 if( pCur->eState>=CURSOR_REQUIRESEEK ){
9675 rc = btreeRestoreCursorPosition(pCur);
9676 assert( rc!=SQLITE_OK || CORRUPT_DB || pCur->eState==CURSOR_VALID );
9677 if( rc || pCur->eState!=CURSOR_VALID ) return rc;
9678 }else{
9679 return SQLITE_CORRUPT_BKPT;
9682 assert( pCur->eState==CURSOR_VALID );
9684 iCellDepth = pCur->iPage;
9685 iCellIdx = pCur->ix;
9686 pPage = pCur->pPage;
9687 if( pPage->nCell<=iCellIdx ){
9688 return SQLITE_CORRUPT_BKPT;
9690 pCell = findCell(pPage, iCellIdx);
9691 if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ){
9692 return SQLITE_CORRUPT_BKPT;
9694 if( pCell<&pPage->aCellIdx[pPage->nCell] ){
9695 return SQLITE_CORRUPT_BKPT;
9698 /* If the BTREE_SAVEPOSITION bit is on, then the cursor position must
9699 ** be preserved following this delete operation. If the current delete
9700 ** will cause a b-tree rebalance, then this is done by saving the cursor
9701 ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
9702 ** returning.
9704 ** If the current delete will not cause a rebalance, then the cursor
9705 ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
9706 ** before or after the deleted entry.
9708 ** The bPreserve value records which path is required:
9710 ** bPreserve==0 Not necessary to save the cursor position
9711 ** bPreserve==1 Use CURSOR_REQUIRESEEK to save the cursor position
9712 ** bPreserve==2 Cursor won't move. Set CURSOR_SKIPNEXT.
9714 bPreserve = (flags & BTREE_SAVEPOSITION)!=0;
9715 if( bPreserve ){
9716 if( !pPage->leaf
9717 || (pPage->nFree+pPage->xCellSize(pPage,pCell)+2) >
9718 (int)(pBt->usableSize*2/3)
9719 || pPage->nCell==1 /* See dbfuzz001.test for a test case */
9721 /* A b-tree rebalance will be required after deleting this entry.
9722 ** Save the cursor key. */
9723 rc = saveCursorKey(pCur);
9724 if( rc ) return rc;
9725 }else{
9726 bPreserve = 2;
9730 /* If the page containing the entry to delete is not a leaf page, move
9731 ** the cursor to the largest entry in the tree that is smaller than
9732 ** the entry being deleted. This cell will replace the cell being deleted
9733 ** from the internal node. The 'previous' entry is used for this instead
9734 ** of the 'next' entry, as the previous entry is always a part of the
9735 ** sub-tree headed by the child page of the cell being deleted. This makes
9736 ** balancing the tree following the delete operation easier. */
9737 if( !pPage->leaf ){
9738 rc = sqlite3BtreePrevious(pCur, 0);
9739 assert( rc!=SQLITE_DONE );
9740 if( rc ) return rc;
9743 /* Save the positions of any other cursors open on this table before
9744 ** making any modifications. */
9745 if( pCur->curFlags & BTCF_Multiple ){
9746 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
9747 if( rc ) return rc;
9750 /* If this is a delete operation to remove a row from a table b-tree,
9751 ** invalidate any incrblob cursors open on the row being deleted. */
9752 if( pCur->pKeyInfo==0 && p->hasIncrblobCur ){
9753 invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
9756 /* Make the page containing the entry to be deleted writable. Then free any
9757 ** overflow pages associated with the entry and finally remove the cell
9758 ** itself from within the page. */
9759 rc = sqlite3PagerWrite(pPage->pDbPage);
9760 if( rc ) return rc;
9761 BTREE_CLEAR_CELL(rc, pPage, pCell, info);
9762 dropCell(pPage, iCellIdx, info.nSize, &rc);
9763 if( rc ) return rc;
9765 /* If the cell deleted was not located on a leaf page, then the cursor
9766 ** is currently pointing to the largest entry in the sub-tree headed
9767 ** by the child-page of the cell that was just deleted from an internal
9768 ** node. The cell from the leaf node needs to be moved to the internal
9769 ** node to replace the deleted cell. */
9770 if( !pPage->leaf ){
9771 MemPage *pLeaf = pCur->pPage;
9772 int nCell;
9773 Pgno n;
9774 unsigned char *pTmp;
9776 if( pLeaf->nFree<0 ){
9777 rc = btreeComputeFreeSpace(pLeaf);
9778 if( rc ) return rc;
9780 if( iCellDepth<pCur->iPage-1 ){
9781 n = pCur->apPage[iCellDepth+1]->pgno;
9782 }else{
9783 n = pCur->pPage->pgno;
9785 pCell = findCell(pLeaf, pLeaf->nCell-1);
9786 if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
9787 nCell = pLeaf->xCellSize(pLeaf, pCell);
9788 assert( MX_CELL_SIZE(pBt) >= nCell );
9789 pTmp = pBt->pTmpSpace;
9790 assert( pTmp!=0 );
9791 rc = sqlite3PagerWrite(pLeaf->pDbPage);
9792 if( rc==SQLITE_OK ){
9793 rc = insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n);
9795 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
9796 if( rc ) return rc;
9799 /* Balance the tree. If the entry deleted was located on a leaf page,
9800 ** then the cursor still points to that page. In this case the first
9801 ** call to balance() repairs the tree, and the if(...) condition is
9802 ** never true.
9804 ** Otherwise, if the entry deleted was on an internal node page, then
9805 ** pCur is pointing to the leaf page from which a cell was removed to
9806 ** replace the cell deleted from the internal node. This is slightly
9807 ** tricky as the leaf node may be underfull, and the internal node may
9808 ** be either under or overfull. In this case run the balancing algorithm
9809 ** on the leaf node first. If the balance proceeds far enough up the
9810 ** tree that we can be sure that any problem in the internal node has
9811 ** been corrected, so be it. Otherwise, after balancing the leaf node,
9812 ** walk the cursor up the tree to the internal node and balance it as
9813 ** well. */
9814 assert( pCur->pPage->nOverflow==0 );
9815 assert( pCur->pPage->nFree>=0 );
9816 if( pCur->pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){
9817 /* Optimization: If the free space is less than 2/3rds of the page,
9818 ** then balance() will always be a no-op. No need to invoke it. */
9819 rc = SQLITE_OK;
9820 }else{
9821 rc = balance(pCur);
9823 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
9824 releasePageNotNull(pCur->pPage);
9825 pCur->iPage--;
9826 while( pCur->iPage>iCellDepth ){
9827 releasePage(pCur->apPage[pCur->iPage--]);
9829 pCur->pPage = pCur->apPage[pCur->iPage];
9830 rc = balance(pCur);
9833 if( rc==SQLITE_OK ){
9834 if( bPreserve>1 ){
9835 assert( (pCur->iPage==iCellDepth || CORRUPT_DB) );
9836 assert( pPage==pCur->pPage || CORRUPT_DB );
9837 assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
9838 pCur->eState = CURSOR_SKIPNEXT;
9839 if( iCellIdx>=pPage->nCell ){
9840 pCur->skipNext = -1;
9841 pCur->ix = pPage->nCell-1;
9842 }else{
9843 pCur->skipNext = 1;
9845 }else{
9846 rc = moveToRoot(pCur);
9847 if( bPreserve ){
9848 btreeReleaseAllCursorPages(pCur);
9849 pCur->eState = CURSOR_REQUIRESEEK;
9851 if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
9854 return rc;
9858 ** Create a new BTree table. Write into *piTable the page
9859 ** number for the root page of the new table.
9861 ** The type of type is determined by the flags parameter. Only the
9862 ** following values of flags are currently in use. Other values for
9863 ** flags might not work:
9865 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
9866 ** BTREE_ZERODATA Used for SQL indices
9868 static int btreeCreateTable(Btree *p, Pgno *piTable, int createTabFlags){
9869 BtShared *pBt = p->pBt;
9870 MemPage *pRoot;
9871 Pgno pgnoRoot;
9872 int rc;
9873 int ptfFlags; /* Page-type flags for the root page of new table */
9875 assert( sqlite3BtreeHoldsMutex(p) );
9876 assert( pBt->inTransaction==TRANS_WRITE );
9877 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9879 #ifdef SQLITE_OMIT_AUTOVACUUM
9880 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9881 if( rc ){
9882 return rc;
9884 #else
9885 if( pBt->autoVacuum ){
9886 Pgno pgnoMove; /* Move a page here to make room for the root-page */
9887 MemPage *pPageMove; /* The page to move to. */
9889 /* Creating a new table may probably require moving an existing database
9890 ** to make room for the new tables root page. In case this page turns
9891 ** out to be an overflow page, delete all overflow page-map caches
9892 ** held by open cursors.
9894 invalidateAllOverflowCache(pBt);
9896 /* Read the value of meta[3] from the database to determine where the
9897 ** root page of the new table should go. meta[3] is the largest root-page
9898 ** created so far, so the new root-page is (meta[3]+1).
9900 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
9901 if( pgnoRoot>btreePagecount(pBt) ){
9902 return SQLITE_CORRUPT_BKPT;
9904 pgnoRoot++;
9906 /* The new root-page may not be allocated on a pointer-map page, or the
9907 ** PENDING_BYTE page.
9909 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
9910 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
9911 pgnoRoot++;
9913 assert( pgnoRoot>=3 );
9915 /* Allocate a page. The page that currently resides at pgnoRoot will
9916 ** be moved to the allocated page (unless the allocated page happens
9917 ** to reside at pgnoRoot).
9919 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
9920 if( rc!=SQLITE_OK ){
9921 return rc;
9924 if( pgnoMove!=pgnoRoot ){
9925 /* pgnoRoot is the page that will be used for the root-page of
9926 ** the new table (assuming an error did not occur). But we were
9927 ** allocated pgnoMove. If required (i.e. if it was not allocated
9928 ** by extending the file), the current page at position pgnoMove
9929 ** is already journaled.
9931 u8 eType = 0;
9932 Pgno iPtrPage = 0;
9934 /* Save the positions of any open cursors. This is required in
9935 ** case they are holding a reference to an xFetch reference
9936 ** corresponding to page pgnoRoot. */
9937 rc = saveAllCursors(pBt, 0, 0);
9938 releasePage(pPageMove);
9939 if( rc!=SQLITE_OK ){
9940 return rc;
9943 /* Move the page currently at pgnoRoot to pgnoMove. */
9944 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9945 if( rc!=SQLITE_OK ){
9946 return rc;
9948 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
9949 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
9950 rc = SQLITE_CORRUPT_BKPT;
9952 if( rc!=SQLITE_OK ){
9953 releasePage(pRoot);
9954 return rc;
9956 assert( eType!=PTRMAP_ROOTPAGE );
9957 assert( eType!=PTRMAP_FREEPAGE );
9958 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
9959 releasePage(pRoot);
9961 /* Obtain the page at pgnoRoot */
9962 if( rc!=SQLITE_OK ){
9963 return rc;
9965 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9966 if( rc!=SQLITE_OK ){
9967 return rc;
9969 rc = sqlite3PagerWrite(pRoot->pDbPage);
9970 if( rc!=SQLITE_OK ){
9971 releasePage(pRoot);
9972 return rc;
9974 }else{
9975 pRoot = pPageMove;
9978 /* Update the pointer-map and meta-data with the new root-page number. */
9979 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
9980 if( rc ){
9981 releasePage(pRoot);
9982 return rc;
9985 /* When the new root page was allocated, page 1 was made writable in
9986 ** order either to increase the database filesize, or to decrement the
9987 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
9989 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
9990 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
9991 if( NEVER(rc) ){
9992 releasePage(pRoot);
9993 return rc;
9996 }else{
9997 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9998 if( rc ) return rc;
10000 #endif
10001 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
10002 if( createTabFlags & BTREE_INTKEY ){
10003 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
10004 }else{
10005 ptfFlags = PTF_ZERODATA | PTF_LEAF;
10007 zeroPage(pRoot, ptfFlags);
10008 sqlite3PagerUnref(pRoot->pDbPage);
10009 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
10010 *piTable = pgnoRoot;
10011 return SQLITE_OK;
10013 int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){
10014 int rc;
10015 sqlite3BtreeEnter(p);
10016 rc = btreeCreateTable(p, piTable, flags);
10017 sqlite3BtreeLeave(p);
10018 return rc;
10022 ** Erase the given database page and all its children. Return
10023 ** the page to the freelist.
10025 static int clearDatabasePage(
10026 BtShared *pBt, /* The BTree that contains the table */
10027 Pgno pgno, /* Page number to clear */
10028 int freePageFlag, /* Deallocate page if true */
10029 i64 *pnChange /* Add number of Cells freed to this counter */
10031 MemPage *pPage;
10032 int rc;
10033 unsigned char *pCell;
10034 int i;
10035 int hdr;
10036 CellInfo info;
10038 assert( sqlite3_mutex_held(pBt->mutex) );
10039 if( pgno>btreePagecount(pBt) ){
10040 return SQLITE_CORRUPT_BKPT;
10042 rc = getAndInitPage(pBt, pgno, &pPage, 0);
10043 if( rc ) return rc;
10044 if( (pBt->openFlags & BTREE_SINGLE)==0
10045 && sqlite3PagerPageRefcount(pPage->pDbPage) != (1 + (pgno==1))
10047 rc = SQLITE_CORRUPT_BKPT;
10048 goto cleardatabasepage_out;
10050 hdr = pPage->hdrOffset;
10051 for(i=0; i<pPage->nCell; i++){
10052 pCell = findCell(pPage, i);
10053 if( !pPage->leaf ){
10054 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
10055 if( rc ) goto cleardatabasepage_out;
10057 BTREE_CLEAR_CELL(rc, pPage, pCell, info);
10058 if( rc ) goto cleardatabasepage_out;
10060 if( !pPage->leaf ){
10061 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
10062 if( rc ) goto cleardatabasepage_out;
10063 if( pPage->intKey ) pnChange = 0;
10065 if( pnChange ){
10066 testcase( !pPage->intKey );
10067 *pnChange += pPage->nCell;
10069 if( freePageFlag ){
10070 freePage(pPage, &rc);
10071 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
10072 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
10075 cleardatabasepage_out:
10076 releasePage(pPage);
10077 return rc;
10081 ** Delete all information from a single table in the database. iTable is
10082 ** the page number of the root of the table. After this routine returns,
10083 ** the root page is empty, but still exists.
10085 ** This routine will fail with SQLITE_LOCKED if there are any open
10086 ** read cursors on the table. Open write cursors are moved to the
10087 ** root of the table.
10089 ** If pnChange is not NULL, then the integer value pointed to by pnChange
10090 ** is incremented by the number of entries in the table.
10092 int sqlite3BtreeClearTable(Btree *p, int iTable, i64 *pnChange){
10093 int rc;
10094 BtShared *pBt = p->pBt;
10095 sqlite3BtreeEnter(p);
10096 assert( p->inTrans==TRANS_WRITE );
10098 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
10100 if( SQLITE_OK==rc ){
10101 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
10102 ** is the root of a table b-tree - if it is not, the following call is
10103 ** a no-op). */
10104 if( p->hasIncrblobCur ){
10105 invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
10107 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
10109 sqlite3BtreeLeave(p);
10110 return rc;
10114 ** Delete all information from the single table that pCur is open on.
10116 ** This routine only work for pCur on an ephemeral table.
10118 int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
10119 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
10123 ** Erase all information in a table and add the root of the table to
10124 ** the freelist. Except, the root of the principle table (the one on
10125 ** page 1) is never added to the freelist.
10127 ** This routine will fail with SQLITE_LOCKED if there are any open
10128 ** cursors on the table.
10130 ** If AUTOVACUUM is enabled and the page at iTable is not the last
10131 ** root page in the database file, then the last root page
10132 ** in the database file is moved into the slot formerly occupied by
10133 ** iTable and that last slot formerly occupied by the last root page
10134 ** is added to the freelist instead of iTable. In this say, all
10135 ** root pages are kept at the beginning of the database file, which
10136 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
10137 ** page number that used to be the last root page in the file before
10138 ** the move. If no page gets moved, *piMoved is set to 0.
10139 ** The last root page is recorded in meta[3] and the value of
10140 ** meta[3] is updated by this procedure.
10142 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
10143 int rc;
10144 MemPage *pPage = 0;
10145 BtShared *pBt = p->pBt;
10147 assert( sqlite3BtreeHoldsMutex(p) );
10148 assert( p->inTrans==TRANS_WRITE );
10149 assert( iTable>=2 );
10150 if( iTable>btreePagecount(pBt) ){
10151 return SQLITE_CORRUPT_BKPT;
10154 rc = sqlite3BtreeClearTable(p, iTable, 0);
10155 if( rc ) return rc;
10156 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
10157 if( NEVER(rc) ){
10158 releasePage(pPage);
10159 return rc;
10162 *piMoved = 0;
10164 #ifdef SQLITE_OMIT_AUTOVACUUM
10165 freePage(pPage, &rc);
10166 releasePage(pPage);
10167 #else
10168 if( pBt->autoVacuum ){
10169 Pgno maxRootPgno;
10170 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
10172 if( iTable==maxRootPgno ){
10173 /* If the table being dropped is the table with the largest root-page
10174 ** number in the database, put the root page on the free list.
10176 freePage(pPage, &rc);
10177 releasePage(pPage);
10178 if( rc!=SQLITE_OK ){
10179 return rc;
10181 }else{
10182 /* The table being dropped does not have the largest root-page
10183 ** number in the database. So move the page that does into the
10184 ** gap left by the deleted root-page.
10186 MemPage *pMove;
10187 releasePage(pPage);
10188 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
10189 if( rc!=SQLITE_OK ){
10190 return rc;
10192 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
10193 releasePage(pMove);
10194 if( rc!=SQLITE_OK ){
10195 return rc;
10197 pMove = 0;
10198 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
10199 freePage(pMove, &rc);
10200 releasePage(pMove);
10201 if( rc!=SQLITE_OK ){
10202 return rc;
10204 *piMoved = maxRootPgno;
10207 /* Set the new 'max-root-page' value in the database header. This
10208 ** is the old value less one, less one more if that happens to
10209 ** be a root-page number, less one again if that is the
10210 ** PENDING_BYTE_PAGE.
10212 maxRootPgno--;
10213 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
10214 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
10215 maxRootPgno--;
10217 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
10219 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
10220 }else{
10221 freePage(pPage, &rc);
10222 releasePage(pPage);
10224 #endif
10225 return rc;
10227 int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
10228 int rc;
10229 sqlite3BtreeEnter(p);
10230 rc = btreeDropTable(p, iTable, piMoved);
10231 sqlite3BtreeLeave(p);
10232 return rc;
10237 ** This function may only be called if the b-tree connection already
10238 ** has a read or write transaction open on the database.
10240 ** Read the meta-information out of a database file. Meta[0]
10241 ** is the number of free pages currently in the database. Meta[1]
10242 ** through meta[15] are available for use by higher layers. Meta[0]
10243 ** is read-only, the others are read/write.
10245 ** The schema layer numbers meta values differently. At the schema
10246 ** layer (and the SetCookie and ReadCookie opcodes) the number of
10247 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
10249 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
10250 ** of reading the value out of the header, it instead loads the "DataVersion"
10251 ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
10252 ** database file. It is a number computed by the pager. But its access
10253 ** pattern is the same as header meta values, and so it is convenient to
10254 ** read it from this routine.
10256 void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
10257 BtShared *pBt = p->pBt;
10259 sqlite3BtreeEnter(p);
10260 assert( p->inTrans>TRANS_NONE );
10261 assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) );
10262 assert( pBt->pPage1 );
10263 assert( idx>=0 && idx<=15 );
10265 if( idx==BTREE_DATA_VERSION ){
10266 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iBDataVersion;
10267 }else{
10268 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
10271 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
10272 ** database, mark the database as read-only. */
10273 #ifdef SQLITE_OMIT_AUTOVACUUM
10274 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
10275 pBt->btsFlags |= BTS_READ_ONLY;
10277 #endif
10279 sqlite3BtreeLeave(p);
10283 ** Write meta-information back into the database. Meta[0] is
10284 ** read-only and may not be written.
10286 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
10287 BtShared *pBt = p->pBt;
10288 unsigned char *pP1;
10289 int rc;
10290 assert( idx>=1 && idx<=15 );
10291 sqlite3BtreeEnter(p);
10292 assert( p->inTrans==TRANS_WRITE );
10293 assert( pBt->pPage1!=0 );
10294 pP1 = pBt->pPage1->aData;
10295 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
10296 if( rc==SQLITE_OK ){
10297 put4byte(&pP1[36 + idx*4], iMeta);
10298 #ifndef SQLITE_OMIT_AUTOVACUUM
10299 if( idx==BTREE_INCR_VACUUM ){
10300 assert( pBt->autoVacuum || iMeta==0 );
10301 assert( iMeta==0 || iMeta==1 );
10302 pBt->incrVacuum = (u8)iMeta;
10304 #endif
10306 sqlite3BtreeLeave(p);
10307 return rc;
10311 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
10312 ** number of entries in the b-tree and write the result to *pnEntry.
10314 ** SQLITE_OK is returned if the operation is successfully executed.
10315 ** Otherwise, if an error is encountered (i.e. an IO error or database
10316 ** corruption) an SQLite error code is returned.
10318 int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){
10319 i64 nEntry = 0; /* Value to return in *pnEntry */
10320 int rc; /* Return code */
10322 rc = moveToRoot(pCur);
10323 if( rc==SQLITE_EMPTY ){
10324 *pnEntry = 0;
10325 return SQLITE_OK;
10328 /* Unless an error occurs, the following loop runs one iteration for each
10329 ** page in the B-Tree structure (not including overflow pages).
10331 while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){
10332 int iIdx; /* Index of child node in parent */
10333 MemPage *pPage; /* Current page of the b-tree */
10335 /* If this is a leaf page or the tree is not an int-key tree, then
10336 ** this page contains countable entries. Increment the entry counter
10337 ** accordingly.
10339 pPage = pCur->pPage;
10340 if( pPage->leaf || !pPage->intKey ){
10341 nEntry += pPage->nCell;
10344 /* pPage is a leaf node. This loop navigates the cursor so that it
10345 ** points to the first interior cell that it points to the parent of
10346 ** the next page in the tree that has not yet been visited. The
10347 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
10348 ** of the page, or to the number of cells in the page if the next page
10349 ** to visit is the right-child of its parent.
10351 ** If all pages in the tree have been visited, return SQLITE_OK to the
10352 ** caller.
10354 if( pPage->leaf ){
10355 do {
10356 if( pCur->iPage==0 ){
10357 /* All pages of the b-tree have been visited. Return successfully. */
10358 *pnEntry = nEntry;
10359 return moveToRoot(pCur);
10361 moveToParent(pCur);
10362 }while ( pCur->ix>=pCur->pPage->nCell );
10364 pCur->ix++;
10365 pPage = pCur->pPage;
10368 /* Descend to the child node of the cell that the cursor currently
10369 ** points at. This is the right-child if (iIdx==pPage->nCell).
10371 iIdx = pCur->ix;
10372 if( iIdx==pPage->nCell ){
10373 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
10374 }else{
10375 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
10379 /* An error has occurred. Return an error code. */
10380 return rc;
10384 ** Return the pager associated with a BTree. This routine is used for
10385 ** testing and debugging only.
10387 Pager *sqlite3BtreePager(Btree *p){
10388 return p->pBt->pPager;
10391 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10393 ** Record an OOM error during integrity_check
10395 static void checkOom(IntegrityCk *pCheck){
10396 pCheck->rc = SQLITE_NOMEM;
10397 pCheck->mxErr = 0; /* Causes integrity_check processing to stop */
10398 if( pCheck->nErr==0 ) pCheck->nErr++;
10402 ** Invoke the progress handler, if appropriate. Also check for an
10403 ** interrupt.
10405 static void checkProgress(IntegrityCk *pCheck){
10406 sqlite3 *db = pCheck->db;
10407 if( AtomicLoad(&db->u1.isInterrupted) ){
10408 pCheck->rc = SQLITE_INTERRUPT;
10409 pCheck->nErr++;
10410 pCheck->mxErr = 0;
10412 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
10413 if( db->xProgress ){
10414 assert( db->nProgressOps>0 );
10415 pCheck->nStep++;
10416 if( (pCheck->nStep % db->nProgressOps)==0
10417 && db->xProgress(db->pProgressArg)
10419 pCheck->rc = SQLITE_INTERRUPT;
10420 pCheck->nErr++;
10421 pCheck->mxErr = 0;
10424 #endif
10428 ** Append a message to the error message string.
10430 static void checkAppendMsg(
10431 IntegrityCk *pCheck,
10432 const char *zFormat,
10435 va_list ap;
10436 checkProgress(pCheck);
10437 if( !pCheck->mxErr ) return;
10438 pCheck->mxErr--;
10439 pCheck->nErr++;
10440 va_start(ap, zFormat);
10441 if( pCheck->errMsg.nChar ){
10442 sqlite3_str_append(&pCheck->errMsg, "\n", 1);
10444 if( pCheck->zPfx ){
10445 sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx,
10446 pCheck->v0, pCheck->v1, pCheck->v2);
10448 sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
10449 va_end(ap);
10450 if( pCheck->errMsg.accError==SQLITE_NOMEM ){
10451 checkOom(pCheck);
10454 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10456 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10459 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
10460 ** corresponds to page iPg is already set.
10462 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
10463 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
10464 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
10468 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
10470 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
10471 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
10472 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
10477 ** Add 1 to the reference count for page iPage. If this is the second
10478 ** reference to the page, add an error message to pCheck->zErrMsg.
10479 ** Return 1 if there are 2 or more references to the page and 0 if
10480 ** if this is the first reference to the page.
10482 ** Also check that the page number is in bounds.
10484 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
10485 if( iPage>pCheck->nPage || iPage==0 ){
10486 checkAppendMsg(pCheck, "invalid page number %u", iPage);
10487 return 1;
10489 if( getPageReferenced(pCheck, iPage) ){
10490 checkAppendMsg(pCheck, "2nd reference to page %u", iPage);
10491 return 1;
10493 setPageReferenced(pCheck, iPage);
10494 return 0;
10497 #ifndef SQLITE_OMIT_AUTOVACUUM
10499 ** Check that the entry in the pointer-map for page iChild maps to
10500 ** page iParent, pointer type ptrType. If not, append an error message
10501 ** to pCheck.
10503 static void checkPtrmap(
10504 IntegrityCk *pCheck, /* Integrity check context */
10505 Pgno iChild, /* Child page number */
10506 u8 eType, /* Expected pointer map type */
10507 Pgno iParent /* Expected pointer map parent page number */
10509 int rc;
10510 u8 ePtrmapType;
10511 Pgno iPtrmapParent;
10513 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
10514 if( rc!=SQLITE_OK ){
10515 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) checkOom(pCheck);
10516 checkAppendMsg(pCheck, "Failed to read ptrmap key=%u", iChild);
10517 return;
10520 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
10521 checkAppendMsg(pCheck,
10522 "Bad ptr map entry key=%u expected=(%u,%u) got=(%u,%u)",
10523 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
10526 #endif
10529 ** Check the integrity of the freelist or of an overflow page list.
10530 ** Verify that the number of pages on the list is N.
10532 static void checkList(
10533 IntegrityCk *pCheck, /* Integrity checking context */
10534 int isFreeList, /* True for a freelist. False for overflow page list */
10535 Pgno iPage, /* Page number for first page in the list */
10536 u32 N /* Expected number of pages in the list */
10538 int i;
10539 u32 expected = N;
10540 int nErrAtStart = pCheck->nErr;
10541 while( iPage!=0 && pCheck->mxErr ){
10542 DbPage *pOvflPage;
10543 unsigned char *pOvflData;
10544 if( checkRef(pCheck, iPage) ) break;
10545 N--;
10546 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
10547 checkAppendMsg(pCheck, "failed to get page %u", iPage);
10548 break;
10550 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
10551 if( isFreeList ){
10552 u32 n = (u32)get4byte(&pOvflData[4]);
10553 #ifndef SQLITE_OMIT_AUTOVACUUM
10554 if( pCheck->pBt->autoVacuum ){
10555 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
10557 #endif
10558 if( n>pCheck->pBt->usableSize/4-2 ){
10559 checkAppendMsg(pCheck,
10560 "freelist leaf count too big on page %u", iPage);
10561 N--;
10562 }else{
10563 for(i=0; i<(int)n; i++){
10564 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
10565 #ifndef SQLITE_OMIT_AUTOVACUUM
10566 if( pCheck->pBt->autoVacuum ){
10567 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
10569 #endif
10570 checkRef(pCheck, iFreePage);
10572 N -= n;
10575 #ifndef SQLITE_OMIT_AUTOVACUUM
10576 else{
10577 /* If this database supports auto-vacuum and iPage is not the last
10578 ** page in this overflow list, check that the pointer-map entry for
10579 ** the following page matches iPage.
10581 if( pCheck->pBt->autoVacuum && N>0 ){
10582 i = get4byte(pOvflData);
10583 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
10586 #endif
10587 iPage = get4byte(pOvflData);
10588 sqlite3PagerUnref(pOvflPage);
10590 if( N && nErrAtStart==pCheck->nErr ){
10591 checkAppendMsg(pCheck,
10592 "%s is %u but should be %u",
10593 isFreeList ? "size" : "overflow list length",
10594 expected-N, expected);
10597 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10600 ** An implementation of a min-heap.
10602 ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
10603 ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
10604 ** and aHeap[N*2+1].
10606 ** The heap property is this: Every node is less than or equal to both
10607 ** of its daughter nodes. A consequence of the heap property is that the
10608 ** root node aHeap[1] is always the minimum value currently in the heap.
10610 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
10611 ** the heap, preserving the heap property. The btreeHeapPull() routine
10612 ** removes the root element from the heap (the minimum value in the heap)
10613 ** and then moves other nodes around as necessary to preserve the heap
10614 ** property.
10616 ** This heap is used for cell overlap and coverage testing. Each u32
10617 ** entry represents the span of a cell or freeblock on a btree page.
10618 ** The upper 16 bits are the index of the first byte of a range and the
10619 ** lower 16 bits are the index of the last byte of that range.
10621 static void btreeHeapInsert(u32 *aHeap, u32 x){
10622 u32 j, i;
10623 assert( aHeap!=0 );
10624 i = ++aHeap[0];
10625 aHeap[i] = x;
10626 while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
10627 x = aHeap[j];
10628 aHeap[j] = aHeap[i];
10629 aHeap[i] = x;
10630 i = j;
10633 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
10634 u32 j, i, x;
10635 if( (x = aHeap[0])==0 ) return 0;
10636 *pOut = aHeap[1];
10637 aHeap[1] = aHeap[x];
10638 aHeap[x] = 0xffffffff;
10639 aHeap[0]--;
10640 i = 1;
10641 while( (j = i*2)<=aHeap[0] ){
10642 if( aHeap[j]>aHeap[j+1] ) j++;
10643 if( aHeap[i]<aHeap[j] ) break;
10644 x = aHeap[i];
10645 aHeap[i] = aHeap[j];
10646 aHeap[j] = x;
10647 i = j;
10649 return 1;
10652 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10654 ** Do various sanity checks on a single page of a tree. Return
10655 ** the tree depth. Root pages return 0. Parents of root pages
10656 ** return 1, and so forth.
10658 ** These checks are done:
10660 ** 1. Make sure that cells and freeblocks do not overlap
10661 ** but combine to completely cover the page.
10662 ** 2. Make sure integer cell keys are in order.
10663 ** 3. Check the integrity of overflow pages.
10664 ** 4. Recursively call checkTreePage on all children.
10665 ** 5. Verify that the depth of all children is the same.
10667 static int checkTreePage(
10668 IntegrityCk *pCheck, /* Context for the sanity check */
10669 Pgno iPage, /* Page number of the page to check */
10670 i64 *piMinKey, /* Write minimum integer primary key here */
10671 i64 maxKey /* Error if integer primary key greater than this */
10673 MemPage *pPage = 0; /* The page being analyzed */
10674 int i; /* Loop counter */
10675 int rc; /* Result code from subroutine call */
10676 int depth = -1, d2; /* Depth of a subtree */
10677 int pgno; /* Page number */
10678 int nFrag; /* Number of fragmented bytes on the page */
10679 int hdr; /* Offset to the page header */
10680 int cellStart; /* Offset to the start of the cell pointer array */
10681 int nCell; /* Number of cells */
10682 int doCoverageCheck = 1; /* True if cell coverage checking should be done */
10683 int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
10684 ** False if IPK must be strictly less than maxKey */
10685 u8 *data; /* Page content */
10686 u8 *pCell; /* Cell content */
10687 u8 *pCellIdx; /* Next element of the cell pointer array */
10688 BtShared *pBt; /* The BtShared object that owns pPage */
10689 u32 pc; /* Address of a cell */
10690 u32 usableSize; /* Usable size of the page */
10691 u32 contentOffset; /* Offset to the start of the cell content area */
10692 u32 *heap = 0; /* Min-heap used for checking cell coverage */
10693 u32 x, prev = 0; /* Next and previous entry on the min-heap */
10694 const char *saved_zPfx = pCheck->zPfx;
10695 int saved_v1 = pCheck->v1;
10696 int saved_v2 = pCheck->v2;
10697 u8 savedIsInit = 0;
10699 /* Check that the page exists
10701 checkProgress(pCheck);
10702 if( pCheck->mxErr==0 ) goto end_of_check;
10703 pBt = pCheck->pBt;
10704 usableSize = pBt->usableSize;
10705 if( iPage==0 ) return 0;
10706 if( checkRef(pCheck, iPage) ) return 0;
10707 pCheck->zPfx = "Tree %u page %u: ";
10708 pCheck->v1 = iPage;
10709 if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){
10710 checkAppendMsg(pCheck,
10711 "unable to get the page. error code=%d", rc);
10712 goto end_of_check;
10715 /* Clear MemPage.isInit to make sure the corruption detection code in
10716 ** btreeInitPage() is executed. */
10717 savedIsInit = pPage->isInit;
10718 pPage->isInit = 0;
10719 if( (rc = btreeInitPage(pPage))!=0 ){
10720 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
10721 checkAppendMsg(pCheck,
10722 "btreeInitPage() returns error code %d", rc);
10723 goto end_of_check;
10725 if( (rc = btreeComputeFreeSpace(pPage))!=0 ){
10726 assert( rc==SQLITE_CORRUPT );
10727 checkAppendMsg(pCheck, "free space corruption", rc);
10728 goto end_of_check;
10730 data = pPage->aData;
10731 hdr = pPage->hdrOffset;
10733 /* Set up for cell analysis */
10734 pCheck->zPfx = "Tree %u page %u cell %u: ";
10735 contentOffset = get2byteNotZero(&data[hdr+5]);
10736 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
10738 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
10739 ** number of cells on the page. */
10740 nCell = get2byte(&data[hdr+3]);
10741 assert( pPage->nCell==nCell );
10743 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
10744 ** immediately follows the b-tree page header. */
10745 cellStart = hdr + 12 - 4*pPage->leaf;
10746 assert( pPage->aCellIdx==&data[cellStart] );
10747 pCellIdx = &data[cellStart + 2*(nCell-1)];
10749 if( !pPage->leaf ){
10750 /* Analyze the right-child page of internal pages */
10751 pgno = get4byte(&data[hdr+8]);
10752 #ifndef SQLITE_OMIT_AUTOVACUUM
10753 if( pBt->autoVacuum ){
10754 pCheck->zPfx = "Tree %u page %u right child: ";
10755 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10757 #endif
10758 depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10759 keyCanBeEqual = 0;
10760 }else{
10761 /* For leaf pages, the coverage check will occur in the same loop
10762 ** as the other cell checks, so initialize the heap. */
10763 heap = pCheck->heap;
10764 heap[0] = 0;
10767 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
10768 ** integer offsets to the cell contents. */
10769 for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
10770 CellInfo info;
10772 /* Check cell size */
10773 pCheck->v2 = i;
10774 assert( pCellIdx==&data[cellStart + i*2] );
10775 pc = get2byteAligned(pCellIdx);
10776 pCellIdx -= 2;
10777 if( pc<contentOffset || pc>usableSize-4 ){
10778 checkAppendMsg(pCheck, "Offset %u out of range %u..%u",
10779 pc, contentOffset, usableSize-4);
10780 doCoverageCheck = 0;
10781 continue;
10783 pCell = &data[pc];
10784 pPage->xParseCell(pPage, pCell, &info);
10785 if( pc+info.nSize>usableSize ){
10786 checkAppendMsg(pCheck, "Extends off end of page");
10787 doCoverageCheck = 0;
10788 continue;
10791 /* Check for integer primary key out of range */
10792 if( pPage->intKey ){
10793 if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
10794 checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
10796 maxKey = info.nKey;
10797 keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
10800 /* Check the content overflow list */
10801 if( info.nPayload>info.nLocal ){
10802 u32 nPage; /* Number of pages on the overflow chain */
10803 Pgno pgnoOvfl; /* First page of the overflow chain */
10804 assert( pc + info.nSize - 4 <= usableSize );
10805 nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
10806 pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
10807 #ifndef SQLITE_OMIT_AUTOVACUUM
10808 if( pBt->autoVacuum ){
10809 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
10811 #endif
10812 checkList(pCheck, 0, pgnoOvfl, nPage);
10815 if( !pPage->leaf ){
10816 /* Check sanity of left child page for internal pages */
10817 pgno = get4byte(pCell);
10818 #ifndef SQLITE_OMIT_AUTOVACUUM
10819 if( pBt->autoVacuum ){
10820 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10822 #endif
10823 d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10824 keyCanBeEqual = 0;
10825 if( d2!=depth ){
10826 checkAppendMsg(pCheck, "Child page depth differs");
10827 depth = d2;
10829 }else{
10830 /* Populate the coverage-checking heap for leaf pages */
10831 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
10834 *piMinKey = maxKey;
10836 /* Check for complete coverage of the page
10838 pCheck->zPfx = 0;
10839 if( doCoverageCheck && pCheck->mxErr>0 ){
10840 /* For leaf pages, the min-heap has already been initialized and the
10841 ** cells have already been inserted. But for internal pages, that has
10842 ** not yet been done, so do it now */
10843 if( !pPage->leaf ){
10844 heap = pCheck->heap;
10845 heap[0] = 0;
10846 for(i=nCell-1; i>=0; i--){
10847 u32 size;
10848 pc = get2byteAligned(&data[cellStart+i*2]);
10849 size = pPage->xCellSize(pPage, &data[pc]);
10850 btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
10853 /* Add the freeblocks to the min-heap
10855 ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
10856 ** is the offset of the first freeblock, or zero if there are no
10857 ** freeblocks on the page.
10859 i = get2byte(&data[hdr+1]);
10860 while( i>0 ){
10861 int size, j;
10862 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10863 size = get2byte(&data[i+2]);
10864 assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
10865 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
10866 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
10867 ** big-endian integer which is the offset in the b-tree page of the next
10868 ** freeblock in the chain, or zero if the freeblock is the last on the
10869 ** chain. */
10870 j = get2byte(&data[i]);
10871 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
10872 ** increasing offset. */
10873 assert( j==0 || j>i+size ); /* Enforced by btreeComputeFreeSpace() */
10874 assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10875 i = j;
10877 /* Analyze the min-heap looking for overlap between cells and/or
10878 ** freeblocks, and counting the number of untracked bytes in nFrag.
10880 ** Each min-heap entry is of the form: (start_address<<16)|end_address.
10881 ** There is an implied first entry the covers the page header, the cell
10882 ** pointer index, and the gap between the cell pointer index and the start
10883 ** of cell content.
10885 ** The loop below pulls entries from the min-heap in order and compares
10886 ** the start_address against the previous end_address. If there is an
10887 ** overlap, that means bytes are used multiple times. If there is a gap,
10888 ** that gap is added to the fragmentation count.
10890 nFrag = 0;
10891 prev = contentOffset - 1; /* Implied first min-heap entry */
10892 while( btreeHeapPull(heap,&x) ){
10893 if( (prev&0xffff)>=(x>>16) ){
10894 checkAppendMsg(pCheck,
10895 "Multiple uses for byte %u of page %u", x>>16, iPage);
10896 break;
10897 }else{
10898 nFrag += (x>>16) - (prev&0xffff) - 1;
10899 prev = x;
10902 nFrag += usableSize - (prev&0xffff) - 1;
10903 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
10904 ** is stored in the fifth field of the b-tree page header.
10905 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
10906 ** number of fragmented free bytes within the cell content area.
10908 if( heap[0]==0 && nFrag!=data[hdr+7] ){
10909 checkAppendMsg(pCheck,
10910 "Fragmentation of %u bytes reported as %u on page %u",
10911 nFrag, data[hdr+7], iPage);
10915 end_of_check:
10916 if( !doCoverageCheck ) pPage->isInit = savedIsInit;
10917 releasePage(pPage);
10918 pCheck->zPfx = saved_zPfx;
10919 pCheck->v1 = saved_v1;
10920 pCheck->v2 = saved_v2;
10921 return depth+1;
10923 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10925 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10927 ** This routine does a complete check of the given BTree file. aRoot[] is
10928 ** an array of pages numbers were each page number is the root page of
10929 ** a table. nRoot is the number of entries in aRoot.
10931 ** A read-only or read-write transaction must be opened before calling
10932 ** this function.
10934 ** Write the number of error seen in *pnErr. Except for some memory
10935 ** allocation errors, an error message held in memory obtained from
10936 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
10937 ** returned. If a memory allocation error occurs, NULL is returned.
10939 ** If the first entry in aRoot[] is 0, that indicates that the list of
10940 ** root pages is incomplete. This is a "partial integrity-check". This
10941 ** happens when performing an integrity check on a single table. The
10942 ** zero is skipped, of course. But in addition, the freelist checks
10943 ** and the checks to make sure every page is referenced are also skipped,
10944 ** since obviously it is not possible to know which pages are covered by
10945 ** the unverified btrees. Except, if aRoot[1] is 1, then the freelist
10946 ** checks are still performed.
10948 int sqlite3BtreeIntegrityCheck(
10949 sqlite3 *db, /* Database connection that is running the check */
10950 Btree *p, /* The btree to be checked */
10951 Pgno *aRoot, /* An array of root pages numbers for individual trees */
10952 int nRoot, /* Number of entries in aRoot[] */
10953 int mxErr, /* Stop reporting errors after this many */
10954 int *pnErr, /* OUT: Write number of errors seen to this variable */
10955 char **pzOut /* OUT: Write the error message string here */
10957 Pgno i;
10958 IntegrityCk sCheck;
10959 BtShared *pBt = p->pBt;
10960 u64 savedDbFlags = pBt->db->flags;
10961 char zErr[100];
10962 int bPartial = 0; /* True if not checking all btrees */
10963 int bCkFreelist = 1; /* True to scan the freelist */
10964 VVA_ONLY( int nRef );
10965 assert( nRoot>0 );
10967 /* aRoot[0]==0 means this is a partial check */
10968 if( aRoot[0]==0 ){
10969 assert( nRoot>1 );
10970 bPartial = 1;
10971 if( aRoot[1]!=1 ) bCkFreelist = 0;
10974 sqlite3BtreeEnter(p);
10975 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
10976 VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
10977 assert( nRef>=0 );
10978 memset(&sCheck, 0, sizeof(sCheck));
10979 sCheck.db = db;
10980 sCheck.pBt = pBt;
10981 sCheck.pPager = pBt->pPager;
10982 sCheck.nPage = btreePagecount(sCheck.pBt);
10983 sCheck.mxErr = mxErr;
10984 sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
10985 sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
10986 if( sCheck.nPage==0 ){
10987 goto integrity_ck_cleanup;
10990 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
10991 if( !sCheck.aPgRef ){
10992 checkOom(&sCheck);
10993 goto integrity_ck_cleanup;
10995 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
10996 if( sCheck.heap==0 ){
10997 checkOom(&sCheck);
10998 goto integrity_ck_cleanup;
11001 i = PENDING_BYTE_PAGE(pBt);
11002 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
11004 /* Check the integrity of the freelist
11006 if( bCkFreelist ){
11007 sCheck.zPfx = "Freelist: ";
11008 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
11009 get4byte(&pBt->pPage1->aData[36]));
11010 sCheck.zPfx = 0;
11013 /* Check all the tables.
11015 #ifndef SQLITE_OMIT_AUTOVACUUM
11016 if( !bPartial ){
11017 if( pBt->autoVacuum ){
11018 Pgno mx = 0;
11019 Pgno mxInHdr;
11020 for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
11021 mxInHdr = get4byte(&pBt->pPage1->aData[52]);
11022 if( mx!=mxInHdr ){
11023 checkAppendMsg(&sCheck,
11024 "max rootpage (%u) disagrees with header (%u)",
11025 mx, mxInHdr
11028 }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
11029 checkAppendMsg(&sCheck,
11030 "incremental_vacuum enabled with a max rootpage of zero"
11034 #endif
11035 testcase( pBt->db->flags & SQLITE_CellSizeCk );
11036 pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
11037 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
11038 i64 notUsed;
11039 if( aRoot[i]==0 ) continue;
11040 #ifndef SQLITE_OMIT_AUTOVACUUM
11041 if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){
11042 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
11044 #endif
11045 sCheck.v0 = aRoot[i];
11046 checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
11048 pBt->db->flags = savedDbFlags;
11050 /* Make sure every page in the file is referenced
11052 if( !bPartial ){
11053 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
11054 #ifdef SQLITE_OMIT_AUTOVACUUM
11055 if( getPageReferenced(&sCheck, i)==0 ){
11056 checkAppendMsg(&sCheck, "Page %u: never used", i);
11058 #else
11059 /* If the database supports auto-vacuum, make sure no tables contain
11060 ** references to pointer-map pages.
11062 if( getPageReferenced(&sCheck, i)==0 &&
11063 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
11064 checkAppendMsg(&sCheck, "Page %u: never used", i);
11066 if( getPageReferenced(&sCheck, i)!=0 &&
11067 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
11068 checkAppendMsg(&sCheck, "Page %u: pointer map referenced", i);
11070 #endif
11074 /* Clean up and report errors.
11076 integrity_ck_cleanup:
11077 sqlite3PageFree(sCheck.heap);
11078 sqlite3_free(sCheck.aPgRef);
11079 *pnErr = sCheck.nErr;
11080 if( sCheck.nErr==0 ){
11081 sqlite3_str_reset(&sCheck.errMsg);
11082 *pzOut = 0;
11083 }else{
11084 *pzOut = sqlite3StrAccumFinish(&sCheck.errMsg);
11086 /* Make sure this analysis did not leave any unref() pages. */
11087 assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
11088 sqlite3BtreeLeave(p);
11089 return sCheck.rc;
11091 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
11094 ** Return the full pathname of the underlying database file. Return
11095 ** an empty string if the database is in-memory or a TEMP database.
11097 ** The pager filename is invariant as long as the pager is
11098 ** open so it is safe to access without the BtShared mutex.
11100 const char *sqlite3BtreeGetFilename(Btree *p){
11101 assert( p->pBt->pPager!=0 );
11102 return sqlite3PagerFilename(p->pBt->pPager, 1);
11106 ** Return the pathname of the journal file for this database. The return
11107 ** value of this routine is the same regardless of whether the journal file
11108 ** has been created or not.
11110 ** The pager journal filename is invariant as long as the pager is
11111 ** open so it is safe to access without the BtShared mutex.
11113 const char *sqlite3BtreeGetJournalname(Btree *p){
11114 assert( p->pBt->pPager!=0 );
11115 return sqlite3PagerJournalname(p->pBt->pPager);
11119 ** Return one of SQLITE_TXN_NONE, SQLITE_TXN_READ, or SQLITE_TXN_WRITE
11120 ** to describe the current transaction state of Btree p.
11122 int sqlite3BtreeTxnState(Btree *p){
11123 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
11124 return p ? p->inTrans : 0;
11127 #ifndef SQLITE_OMIT_WAL
11129 ** Run a checkpoint on the Btree passed as the first argument.
11131 ** Return SQLITE_LOCKED if this or any other connection has an open
11132 ** transaction on the shared-cache the argument Btree is connected to.
11134 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
11136 int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
11137 int rc = SQLITE_OK;
11138 if( p ){
11139 BtShared *pBt = p->pBt;
11140 sqlite3BtreeEnter(p);
11141 if( pBt->inTransaction!=TRANS_NONE ){
11142 rc = SQLITE_LOCKED;
11143 }else{
11144 rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
11146 sqlite3BtreeLeave(p);
11148 return rc;
11150 #endif
11153 ** Return true if there is currently a backup running on Btree p.
11155 int sqlite3BtreeIsInBackup(Btree *p){
11156 assert( p );
11157 assert( sqlite3_mutex_held(p->db->mutex) );
11158 return p->nBackup!=0;
11162 ** This function returns a pointer to a blob of memory associated with
11163 ** a single shared-btree. The memory is used by client code for its own
11164 ** purposes (for example, to store a high-level schema associated with
11165 ** the shared-btree). The btree layer manages reference counting issues.
11167 ** The first time this is called on a shared-btree, nBytes bytes of memory
11168 ** are allocated, zeroed, and returned to the caller. For each subsequent
11169 ** call the nBytes parameter is ignored and a pointer to the same blob
11170 ** of memory returned.
11172 ** If the nBytes parameter is 0 and the blob of memory has not yet been
11173 ** allocated, a null pointer is returned. If the blob has already been
11174 ** allocated, it is returned as normal.
11176 ** Just before the shared-btree is closed, the function passed as the
11177 ** xFree argument when the memory allocation was made is invoked on the
11178 ** blob of allocated memory. The xFree function should not call sqlite3_free()
11179 ** on the memory, the btree layer does that.
11181 void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
11182 BtShared *pBt = p->pBt;
11183 sqlite3BtreeEnter(p);
11184 if( !pBt->pSchema && nBytes ){
11185 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
11186 pBt->xFreeSchema = xFree;
11188 sqlite3BtreeLeave(p);
11189 return pBt->pSchema;
11193 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
11194 ** btree as the argument handle holds an exclusive lock on the
11195 ** sqlite_schema table. Otherwise SQLITE_OK.
11197 int sqlite3BtreeSchemaLocked(Btree *p){
11198 int rc;
11199 assert( sqlite3_mutex_held(p->db->mutex) );
11200 sqlite3BtreeEnter(p);
11201 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
11202 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
11203 sqlite3BtreeLeave(p);
11204 return rc;
11208 #ifndef SQLITE_OMIT_SHARED_CACHE
11210 ** Obtain a lock on the table whose root page is iTab. The
11211 ** lock is a write lock if isWritelock is true or a read lock
11212 ** if it is false.
11214 int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
11215 int rc = SQLITE_OK;
11216 assert( p->inTrans!=TRANS_NONE );
11217 if( p->sharable ){
11218 u8 lockType = READ_LOCK + isWriteLock;
11219 assert( READ_LOCK+1==WRITE_LOCK );
11220 assert( isWriteLock==0 || isWriteLock==1 );
11222 sqlite3BtreeEnter(p);
11223 rc = querySharedCacheTableLock(p, iTab, lockType);
11224 if( rc==SQLITE_OK ){
11225 rc = setSharedCacheTableLock(p, iTab, lockType);
11227 sqlite3BtreeLeave(p);
11229 return rc;
11231 #endif
11233 #ifndef SQLITE_OMIT_INCRBLOB
11235 ** Argument pCsr must be a cursor opened for writing on an
11236 ** INTKEY table currently pointing at a valid table entry.
11237 ** This function modifies the data stored as part of that entry.
11239 ** Only the data content may only be modified, it is not possible to
11240 ** change the length of the data stored. If this function is called with
11241 ** parameters that attempt to write past the end of the existing data,
11242 ** no modifications are made and SQLITE_CORRUPT is returned.
11244 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
11245 int rc;
11246 assert( cursorOwnsBtShared(pCsr) );
11247 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
11248 assert( pCsr->curFlags & BTCF_Incrblob );
11250 rc = restoreCursorPosition(pCsr);
11251 if( rc!=SQLITE_OK ){
11252 return rc;
11254 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
11255 if( pCsr->eState!=CURSOR_VALID ){
11256 return SQLITE_ABORT;
11259 /* Save the positions of all other cursors open on this table. This is
11260 ** required in case any of them are holding references to an xFetch
11261 ** version of the b-tree page modified by the accessPayload call below.
11263 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
11264 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
11265 ** saveAllCursors can only return SQLITE_OK.
11267 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
11268 assert( rc==SQLITE_OK );
11270 /* Check some assumptions:
11271 ** (a) the cursor is open for writing,
11272 ** (b) there is a read/write transaction open,
11273 ** (c) the connection holds a write-lock on the table (if required),
11274 ** (d) there are no conflicting read-locks, and
11275 ** (e) the cursor points at a valid row of an intKey table.
11277 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
11278 return SQLITE_READONLY;
11280 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
11281 && pCsr->pBt->inTransaction==TRANS_WRITE );
11282 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
11283 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
11284 assert( pCsr->pPage->intKey );
11286 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
11290 ** Mark this cursor as an incremental blob cursor.
11292 void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
11293 pCur->curFlags |= BTCF_Incrblob;
11294 pCur->pBtree->hasIncrblobCur = 1;
11296 #endif
11299 ** Set both the "read version" (single byte at byte offset 18) and
11300 ** "write version" (single byte at byte offset 19) fields in the database
11301 ** header to iVersion.
11303 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
11304 BtShared *pBt = pBtree->pBt;
11305 int rc; /* Return code */
11307 assert( iVersion==1 || iVersion==2 );
11309 /* If setting the version fields to 1, do not automatically open the
11310 ** WAL connection, even if the version fields are currently set to 2.
11312 pBt->btsFlags &= ~BTS_NO_WAL;
11313 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
11315 rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
11316 if( rc==SQLITE_OK ){
11317 u8 *aData = pBt->pPage1->aData;
11318 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
11319 rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
11320 if( rc==SQLITE_OK ){
11321 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
11322 if( rc==SQLITE_OK ){
11323 aData[18] = (u8)iVersion;
11324 aData[19] = (u8)iVersion;
11330 pBt->btsFlags &= ~BTS_NO_WAL;
11331 return rc;
11335 ** Return true if the cursor has a hint specified. This routine is
11336 ** only used from within assert() statements
11338 int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
11339 return (pCsr->hints & mask)!=0;
11343 ** Return true if the given Btree is read-only.
11345 int sqlite3BtreeIsReadonly(Btree *p){
11346 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
11350 ** Return the size of the header added to each page by this module.
11352 int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
11355 ** If no transaction is active and the database is not a temp-db, clear
11356 ** the in-memory pager cache.
11358 void sqlite3BtreeClearCache(Btree *p){
11359 BtShared *pBt = p->pBt;
11360 if( pBt->inTransaction==TRANS_NONE ){
11361 sqlite3PagerClearCache(pBt->pPager);
11365 #if !defined(SQLITE_OMIT_SHARED_CACHE)
11367 ** Return true if the Btree passed as the only argument is sharable.
11369 int sqlite3BtreeSharable(Btree *p){
11370 return p->sharable;
11374 ** Return the number of connections to the BtShared object accessed by
11375 ** the Btree handle passed as the only argument. For private caches
11376 ** this is always 1. For shared caches it may be 1 or greater.
11378 int sqlite3BtreeConnectionCount(Btree *p){
11379 testcase( p->sharable );
11380 return p->pBt->nRef;
11382 #endif