Snapshot of upstream SQLite 3.42.0
[sqlcipher.git] / src / btree.c
blob87bc0058bb8566e96c1b70519a2e9d5b325ff55a
1 /*
2 ** 2004 April 6
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file implements an external (disk-based) database using BTrees.
13 ** See the header comment on "btreeInt.h" for additional information.
14 ** Including a description of file format and an overview of operation.
16 #include "btreeInt.h"
19 ** The header string that appears at the beginning of every
20 ** SQLite database.
22 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
25 ** Set this global variable to 1 to enable tracing using the TRACE
26 ** macro.
28 #if 0
29 int sqlite3BtreeTrace=1; /* True to enable tracing */
30 # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
31 #else
32 # define TRACE(X)
33 #endif
36 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
37 ** But if the value is zero, make it 65536.
39 ** This routine is used to extract the "offset to cell content area" value
40 ** from the header of a btree page. If the page size is 65536 and the page
41 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
42 ** This routine makes the necessary adjustment to 65536.
44 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
47 ** Values passed as the 5th argument to allocateBtreePage()
49 #define BTALLOC_ANY 0 /* Allocate any page */
50 #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
51 #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
54 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
55 ** defined, or 0 if it is. For example:
57 ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
59 #ifndef SQLITE_OMIT_AUTOVACUUM
60 #define IfNotOmitAV(expr) (expr)
61 #else
62 #define IfNotOmitAV(expr) 0
63 #endif
65 #ifndef SQLITE_OMIT_SHARED_CACHE
67 ** A list of BtShared objects that are eligible for participation
68 ** in shared cache. This variable has file scope during normal builds,
69 ** but the test harness needs to access it so we make it global for
70 ** test builds.
72 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MAIN.
74 #ifdef SQLITE_TEST
75 BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
76 #else
77 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
78 #endif
79 #endif /* SQLITE_OMIT_SHARED_CACHE */
81 #ifndef SQLITE_OMIT_SHARED_CACHE
83 ** Enable or disable the shared pager and schema features.
85 ** This routine has no effect on existing database connections.
86 ** The shared cache setting effects only future calls to
87 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
89 int sqlite3_enable_shared_cache(int enable){
90 sqlite3GlobalConfig.sharedCacheEnabled = enable;
91 return SQLITE_OK;
93 #endif
97 #ifdef SQLITE_OMIT_SHARED_CACHE
99 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
100 ** and clearAllSharedCacheTableLocks()
101 ** manipulate entries in the BtShared.pLock linked list used to store
102 ** shared-cache table level locks. If the library is compiled with the
103 ** shared-cache feature disabled, then there is only ever one user
104 ** of each BtShared structure and so this locking is not necessary.
105 ** So define the lock related functions as no-ops.
107 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
108 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
109 #define clearAllSharedCacheTableLocks(a)
110 #define downgradeAllSharedCacheTableLocks(a)
111 #define hasSharedCacheTableLock(a,b,c,d) 1
112 #define hasReadConflicts(a, b) 0
113 #endif
115 #ifdef SQLITE_DEBUG
117 ** Return and reset the seek counter for a Btree object.
119 sqlite3_uint64 sqlite3BtreeSeekCount(Btree *pBt){
120 u64 n = pBt->nSeek;
121 pBt->nSeek = 0;
122 return n;
124 #endif
127 ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
128 ** (MemPage*) as an argument. The (MemPage*) must not be NULL.
130 ** If SQLITE_DEBUG is not defined, then this macro is equivalent to
131 ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
132 ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
133 ** with the page number and filename associated with the (MemPage*).
135 #ifdef SQLITE_DEBUG
136 int corruptPageError(int lineno, MemPage *p){
137 char *zMsg;
138 sqlite3BeginBenignMalloc();
139 zMsg = sqlite3_mprintf("database corruption page %u of %s",
140 p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
142 sqlite3EndBenignMalloc();
143 if( zMsg ){
144 sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
146 sqlite3_free(zMsg);
147 return SQLITE_CORRUPT_BKPT;
149 # define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
150 #else
151 # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
152 #endif
154 #ifndef SQLITE_OMIT_SHARED_CACHE
156 #ifdef SQLITE_DEBUG
158 **** This function is only used as part of an assert() statement. ***
160 ** Check to see if pBtree holds the required locks to read or write to the
161 ** table with root page iRoot. Return 1 if it does and 0 if not.
163 ** For example, when writing to a table with root-page iRoot via
164 ** Btree connection pBtree:
166 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
168 ** When writing to an index that resides in a sharable database, the
169 ** caller should have first obtained a lock specifying the root page of
170 ** the corresponding table. This makes things a bit more complicated,
171 ** as this module treats each table as a separate structure. To determine
172 ** the table corresponding to the index being written, this
173 ** function has to search through the database schema.
175 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
176 ** hold a write-lock on the schema table (root page 1). This is also
177 ** acceptable.
179 static int hasSharedCacheTableLock(
180 Btree *pBtree, /* Handle that must hold lock */
181 Pgno iRoot, /* Root page of b-tree */
182 int isIndex, /* True if iRoot is the root of an index b-tree */
183 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
185 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
186 Pgno iTab = 0;
187 BtLock *pLock;
189 /* If this database is not shareable, or if the client is reading
190 ** and has the read-uncommitted flag set, then no lock is required.
191 ** Return true immediately.
193 if( (pBtree->sharable==0)
194 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
196 return 1;
199 /* If the client is reading or writing an index and the schema is
200 ** not loaded, then it is too difficult to actually check to see if
201 ** the correct locks are held. So do not bother - just return true.
202 ** This case does not come up very often anyhow.
204 if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
205 return 1;
208 /* Figure out the root-page that the lock should be held on. For table
209 ** b-trees, this is just the root page of the b-tree being read or
210 ** written. For index b-trees, it is the root page of the associated
211 ** table. */
212 if( isIndex ){
213 HashElem *p;
214 int bSeen = 0;
215 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
216 Index *pIdx = (Index *)sqliteHashData(p);
217 if( pIdx->tnum==iRoot ){
218 if( bSeen ){
219 /* Two or more indexes share the same root page. There must
220 ** be imposter tables. So just return true. The assert is not
221 ** useful in that case. */
222 return 1;
224 iTab = pIdx->pTable->tnum;
225 bSeen = 1;
228 }else{
229 iTab = iRoot;
232 /* Search for the required lock. Either a write-lock on root-page iTab, a
233 ** write-lock on the schema table, or (if the client is reading) a
234 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
235 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
236 if( pLock->pBtree==pBtree
237 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
238 && pLock->eLock>=eLockType
240 return 1;
244 /* Failed to find the required lock. */
245 return 0;
247 #endif /* SQLITE_DEBUG */
249 #ifdef SQLITE_DEBUG
251 **** This function may be used as part of assert() statements only. ****
253 ** Return true if it would be illegal for pBtree to write into the
254 ** table or index rooted at iRoot because other shared connections are
255 ** simultaneously reading that same table or index.
257 ** It is illegal for pBtree to write if some other Btree object that
258 ** shares the same BtShared object is currently reading or writing
259 ** the iRoot table. Except, if the other Btree object has the
260 ** read-uncommitted flag set, then it is OK for the other object to
261 ** have a read cursor.
263 ** For example, before writing to any part of the table or index
264 ** rooted at page iRoot, one should call:
266 ** assert( !hasReadConflicts(pBtree, iRoot) );
268 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
269 BtCursor *p;
270 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
271 if( p->pgnoRoot==iRoot
272 && p->pBtree!=pBtree
273 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
275 return 1;
278 return 0;
280 #endif /* #ifdef SQLITE_DEBUG */
283 ** Query to see if Btree handle p may obtain a lock of type eLock
284 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
285 ** SQLITE_OK if the lock may be obtained (by calling
286 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
288 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
289 BtShared *pBt = p->pBt;
290 BtLock *pIter;
292 assert( sqlite3BtreeHoldsMutex(p) );
293 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
294 assert( p->db!=0 );
295 assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
297 /* If requesting a write-lock, then the Btree must have an open write
298 ** transaction on this file. And, obviously, for this to be so there
299 ** must be an open write transaction on the file itself.
301 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
302 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
304 /* This routine is a no-op if the shared-cache is not enabled */
305 if( !p->sharable ){
306 return SQLITE_OK;
309 /* If some other connection is holding an exclusive lock, the
310 ** requested lock may not be obtained.
312 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
313 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
314 return SQLITE_LOCKED_SHAREDCACHE;
317 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
318 /* The condition (pIter->eLock!=eLock) in the following if(...)
319 ** statement is a simplification of:
321 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
323 ** since we know that if eLock==WRITE_LOCK, then no other connection
324 ** may hold a WRITE_LOCK on any table in this file (since there can
325 ** only be a single writer).
327 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
328 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
329 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
330 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
331 if( eLock==WRITE_LOCK ){
332 assert( p==pBt->pWriter );
333 pBt->btsFlags |= BTS_PENDING;
335 return SQLITE_LOCKED_SHAREDCACHE;
338 return SQLITE_OK;
340 #endif /* !SQLITE_OMIT_SHARED_CACHE */
342 #ifndef SQLITE_OMIT_SHARED_CACHE
344 ** Add a lock on the table with root-page iTable to the shared-btree used
345 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
346 ** WRITE_LOCK.
348 ** This function assumes the following:
350 ** (a) The specified Btree object p is connected to a sharable
351 ** database (one with the BtShared.sharable flag set), and
353 ** (b) No other Btree objects hold a lock that conflicts
354 ** with the requested lock (i.e. querySharedCacheTableLock() has
355 ** already been called and returned SQLITE_OK).
357 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
358 ** is returned if a malloc attempt fails.
360 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
361 BtShared *pBt = p->pBt;
362 BtLock *pLock = 0;
363 BtLock *pIter;
365 assert( sqlite3BtreeHoldsMutex(p) );
366 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
367 assert( p->db!=0 );
369 /* A connection with the read-uncommitted flag set will never try to
370 ** obtain a read-lock using this function. The only read-lock obtained
371 ** by a connection in read-uncommitted mode is on the sqlite_schema
372 ** table, and that lock is obtained in BtreeBeginTrans(). */
373 assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
375 /* This function should only be called on a sharable b-tree after it
376 ** has been determined that no other b-tree holds a conflicting lock. */
377 assert( p->sharable );
378 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
380 /* First search the list for an existing lock on this table. */
381 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
382 if( pIter->iTable==iTable && pIter->pBtree==p ){
383 pLock = pIter;
384 break;
388 /* If the above search did not find a BtLock struct associating Btree p
389 ** with table iTable, allocate one and link it into the list.
391 if( !pLock ){
392 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
393 if( !pLock ){
394 return SQLITE_NOMEM_BKPT;
396 pLock->iTable = iTable;
397 pLock->pBtree = p;
398 pLock->pNext = pBt->pLock;
399 pBt->pLock = pLock;
402 /* Set the BtLock.eLock variable to the maximum of the current lock
403 ** and the requested lock. This means if a write-lock was already held
404 ** and a read-lock requested, we don't incorrectly downgrade the lock.
406 assert( WRITE_LOCK>READ_LOCK );
407 if( eLock>pLock->eLock ){
408 pLock->eLock = eLock;
411 return SQLITE_OK;
413 #endif /* !SQLITE_OMIT_SHARED_CACHE */
415 #ifndef SQLITE_OMIT_SHARED_CACHE
417 ** Release all the table locks (locks obtained via calls to
418 ** the setSharedCacheTableLock() procedure) held by Btree object p.
420 ** This function assumes that Btree p has an open read or write
421 ** transaction. If it does not, then the BTS_PENDING flag
422 ** may be incorrectly cleared.
424 static void clearAllSharedCacheTableLocks(Btree *p){
425 BtShared *pBt = p->pBt;
426 BtLock **ppIter = &pBt->pLock;
428 assert( sqlite3BtreeHoldsMutex(p) );
429 assert( p->sharable || 0==*ppIter );
430 assert( p->inTrans>0 );
432 while( *ppIter ){
433 BtLock *pLock = *ppIter;
434 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
435 assert( pLock->pBtree->inTrans>=pLock->eLock );
436 if( pLock->pBtree==p ){
437 *ppIter = pLock->pNext;
438 assert( pLock->iTable!=1 || pLock==&p->lock );
439 if( pLock->iTable!=1 ){
440 sqlite3_free(pLock);
442 }else{
443 ppIter = &pLock->pNext;
447 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
448 if( pBt->pWriter==p ){
449 pBt->pWriter = 0;
450 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
451 }else if( pBt->nTransaction==2 ){
452 /* This function is called when Btree p is concluding its
453 ** transaction. If there currently exists a writer, and p is not
454 ** that writer, then the number of locks held by connections other
455 ** than the writer must be about to drop to zero. In this case
456 ** set the BTS_PENDING flag to 0.
458 ** If there is not currently a writer, then BTS_PENDING must
459 ** be zero already. So this next line is harmless in that case.
461 pBt->btsFlags &= ~BTS_PENDING;
466 ** This function changes all write-locks held by Btree p into read-locks.
468 static void downgradeAllSharedCacheTableLocks(Btree *p){
469 BtShared *pBt = p->pBt;
470 if( pBt->pWriter==p ){
471 BtLock *pLock;
472 pBt->pWriter = 0;
473 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
474 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
475 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
476 pLock->eLock = READ_LOCK;
481 #endif /* SQLITE_OMIT_SHARED_CACHE */
483 static void releasePage(MemPage *pPage); /* Forward reference */
484 static void releasePageOne(MemPage *pPage); /* Forward reference */
485 static void releasePageNotNull(MemPage *pPage); /* Forward reference */
488 ***** This routine is used inside of assert() only ****
490 ** Verify that the cursor holds the mutex on its BtShared
492 #ifdef SQLITE_DEBUG
493 static int cursorHoldsMutex(BtCursor *p){
494 return sqlite3_mutex_held(p->pBt->mutex);
497 /* Verify that the cursor and the BtShared agree about what is the current
498 ** database connetion. This is important in shared-cache mode. If the database
499 ** connection pointers get out-of-sync, it is possible for routines like
500 ** btreeInitPage() to reference an stale connection pointer that references a
501 ** a connection that has already closed. This routine is used inside assert()
502 ** statements only and for the purpose of double-checking that the btree code
503 ** does keep the database connection pointers up-to-date.
505 static int cursorOwnsBtShared(BtCursor *p){
506 assert( cursorHoldsMutex(p) );
507 return (p->pBtree->db==p->pBt->db);
509 #endif
512 ** Invalidate the overflow cache of the cursor passed as the first argument.
513 ** on the shared btree structure pBt.
515 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
518 ** Invalidate the overflow page-list cache for all cursors opened
519 ** on the shared btree structure pBt.
521 static void invalidateAllOverflowCache(BtShared *pBt){
522 BtCursor *p;
523 assert( sqlite3_mutex_held(pBt->mutex) );
524 for(p=pBt->pCursor; p; p=p->pNext){
525 invalidateOverflowCache(p);
529 #ifndef SQLITE_OMIT_INCRBLOB
531 ** This function is called before modifying the contents of a table
532 ** to invalidate any incrblob cursors that are open on the
533 ** row or one of the rows being modified.
535 ** If argument isClearTable is true, then the entire contents of the
536 ** table is about to be deleted. In this case invalidate all incrblob
537 ** cursors open on any row within the table with root-page pgnoRoot.
539 ** Otherwise, if argument isClearTable is false, then the row with
540 ** rowid iRow is being replaced or deleted. In this case invalidate
541 ** only those incrblob cursors open on that specific row.
543 static void invalidateIncrblobCursors(
544 Btree *pBtree, /* The database file to check */
545 Pgno pgnoRoot, /* The table that might be changing */
546 i64 iRow, /* The rowid that might be changing */
547 int isClearTable /* True if all rows are being deleted */
549 BtCursor *p;
550 assert( pBtree->hasIncrblobCur );
551 assert( sqlite3BtreeHoldsMutex(pBtree) );
552 pBtree->hasIncrblobCur = 0;
553 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
554 if( (p->curFlags & BTCF_Incrblob)!=0 ){
555 pBtree->hasIncrblobCur = 1;
556 if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
557 p->eState = CURSOR_INVALID;
563 #else
564 /* Stub function when INCRBLOB is omitted */
565 #define invalidateIncrblobCursors(w,x,y,z)
566 #endif /* SQLITE_OMIT_INCRBLOB */
569 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
570 ** when a page that previously contained data becomes a free-list leaf
571 ** page.
573 ** The BtShared.pHasContent bitvec exists to work around an obscure
574 ** bug caused by the interaction of two useful IO optimizations surrounding
575 ** free-list leaf pages:
577 ** 1) When all data is deleted from a page and the page becomes
578 ** a free-list leaf page, the page is not written to the database
579 ** (as free-list leaf pages contain no meaningful data). Sometimes
580 ** such a page is not even journalled (as it will not be modified,
581 ** why bother journalling it?).
583 ** 2) When a free-list leaf page is reused, its content is not read
584 ** from the database or written to the journal file (why should it
585 ** be, if it is not at all meaningful?).
587 ** By themselves, these optimizations work fine and provide a handy
588 ** performance boost to bulk delete or insert operations. However, if
589 ** a page is moved to the free-list and then reused within the same
590 ** transaction, a problem comes up. If the page is not journalled when
591 ** it is moved to the free-list and it is also not journalled when it
592 ** is extracted from the free-list and reused, then the original data
593 ** may be lost. In the event of a rollback, it may not be possible
594 ** to restore the database to its original configuration.
596 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
597 ** moved to become a free-list leaf page, the corresponding bit is
598 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
599 ** optimization 2 above is omitted if the corresponding bit is already
600 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
601 ** at the end of every transaction.
603 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
604 int rc = SQLITE_OK;
605 if( !pBt->pHasContent ){
606 assert( pgno<=pBt->nPage );
607 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
608 if( !pBt->pHasContent ){
609 rc = SQLITE_NOMEM_BKPT;
612 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
613 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
615 return rc;
619 ** Query the BtShared.pHasContent vector.
621 ** This function is called when a free-list leaf page is removed from the
622 ** free-list for reuse. It returns false if it is safe to retrieve the
623 ** page from the pager layer with the 'no-content' flag set. True otherwise.
625 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
626 Bitvec *p = pBt->pHasContent;
627 return p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTestNotNull(p, pgno));
631 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
632 ** invoked at the conclusion of each write-transaction.
634 static void btreeClearHasContent(BtShared *pBt){
635 sqlite3BitvecDestroy(pBt->pHasContent);
636 pBt->pHasContent = 0;
640 ** Release all of the apPage[] pages for a cursor.
642 static void btreeReleaseAllCursorPages(BtCursor *pCur){
643 int i;
644 if( pCur->iPage>=0 ){
645 for(i=0; i<pCur->iPage; i++){
646 releasePageNotNull(pCur->apPage[i]);
648 releasePageNotNull(pCur->pPage);
649 pCur->iPage = -1;
654 ** The cursor passed as the only argument must point to a valid entry
655 ** when this function is called (i.e. have eState==CURSOR_VALID). This
656 ** function saves the current cursor key in variables pCur->nKey and
657 ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
658 ** code otherwise.
660 ** If the cursor is open on an intkey table, then the integer key
661 ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
662 ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
663 ** set to point to a malloced buffer pCur->nKey bytes in size containing
664 ** the key.
666 static int saveCursorKey(BtCursor *pCur){
667 int rc = SQLITE_OK;
668 assert( CURSOR_VALID==pCur->eState );
669 assert( 0==pCur->pKey );
670 assert( cursorHoldsMutex(pCur) );
672 if( pCur->curIntKey ){
673 /* Only the rowid is required for a table btree */
674 pCur->nKey = sqlite3BtreeIntegerKey(pCur);
675 }else{
676 /* For an index btree, save the complete key content. It is possible
677 ** that the current key is corrupt. In that case, it is possible that
678 ** the sqlite3VdbeRecordUnpack() function may overread the buffer by
679 ** up to the size of 1 varint plus 1 8-byte value when the cursor
680 ** position is restored. Hence the 17 bytes of padding allocated
681 ** below. */
682 void *pKey;
683 pCur->nKey = sqlite3BtreePayloadSize(pCur);
684 pKey = sqlite3Malloc( pCur->nKey + 9 + 8 );
685 if( pKey ){
686 rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
687 if( rc==SQLITE_OK ){
688 memset(((u8*)pKey)+pCur->nKey, 0, 9+8);
689 pCur->pKey = pKey;
690 }else{
691 sqlite3_free(pKey);
693 }else{
694 rc = SQLITE_NOMEM_BKPT;
697 assert( !pCur->curIntKey || !pCur->pKey );
698 return rc;
702 ** Save the current cursor position in the variables BtCursor.nKey
703 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
705 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
706 ** prior to calling this routine.
708 static int saveCursorPosition(BtCursor *pCur){
709 int rc;
711 assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
712 assert( 0==pCur->pKey );
713 assert( cursorHoldsMutex(pCur) );
715 if( pCur->curFlags & BTCF_Pinned ){
716 return SQLITE_CONSTRAINT_PINNED;
718 if( pCur->eState==CURSOR_SKIPNEXT ){
719 pCur->eState = CURSOR_VALID;
720 }else{
721 pCur->skipNext = 0;
724 rc = saveCursorKey(pCur);
725 if( rc==SQLITE_OK ){
726 btreeReleaseAllCursorPages(pCur);
727 pCur->eState = CURSOR_REQUIRESEEK;
730 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
731 return rc;
734 /* Forward reference */
735 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
738 ** Save the positions of all cursors (except pExcept) that are open on
739 ** the table with root-page iRoot. "Saving the cursor position" means that
740 ** the location in the btree is remembered in such a way that it can be
741 ** moved back to the same spot after the btree has been modified. This
742 ** routine is called just before cursor pExcept is used to modify the
743 ** table, for example in BtreeDelete() or BtreeInsert().
745 ** If there are two or more cursors on the same btree, then all such
746 ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
747 ** routine enforces that rule. This routine only needs to be called in
748 ** the uncommon case when pExpect has the BTCF_Multiple flag set.
750 ** If pExpect!=NULL and if no other cursors are found on the same root-page,
751 ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
752 ** pointless call to this routine.
754 ** Implementation note: This routine merely checks to see if any cursors
755 ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
756 ** event that cursors are in need to being saved.
758 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
759 BtCursor *p;
760 assert( sqlite3_mutex_held(pBt->mutex) );
761 assert( pExcept==0 || pExcept->pBt==pBt );
762 for(p=pBt->pCursor; p; p=p->pNext){
763 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
765 if( p ) return saveCursorsOnList(p, iRoot, pExcept);
766 if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
767 return SQLITE_OK;
770 /* This helper routine to saveAllCursors does the actual work of saving
771 ** the cursors if and when a cursor is found that actually requires saving.
772 ** The common case is that no cursors need to be saved, so this routine is
773 ** broken out from its caller to avoid unnecessary stack pointer movement.
775 static int SQLITE_NOINLINE saveCursorsOnList(
776 BtCursor *p, /* The first cursor that needs saving */
777 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
778 BtCursor *pExcept /* Do not save this cursor */
781 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
782 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
783 int rc = saveCursorPosition(p);
784 if( SQLITE_OK!=rc ){
785 return rc;
787 }else{
788 testcase( p->iPage>=0 );
789 btreeReleaseAllCursorPages(p);
792 p = p->pNext;
793 }while( p );
794 return SQLITE_OK;
798 ** Clear the current cursor position.
800 void sqlite3BtreeClearCursor(BtCursor *pCur){
801 assert( cursorHoldsMutex(pCur) );
802 sqlite3_free(pCur->pKey);
803 pCur->pKey = 0;
804 pCur->eState = CURSOR_INVALID;
808 ** In this version of BtreeMoveto, pKey is a packed index record
809 ** such as is generated by the OP_MakeRecord opcode. Unpack the
810 ** record and then call sqlite3BtreeIndexMoveto() to do the work.
812 static int btreeMoveto(
813 BtCursor *pCur, /* Cursor open on the btree to be searched */
814 const void *pKey, /* Packed key if the btree is an index */
815 i64 nKey, /* Integer key for tables. Size of pKey for indices */
816 int bias, /* Bias search to the high end */
817 int *pRes /* Write search results here */
819 int rc; /* Status code */
820 UnpackedRecord *pIdxKey; /* Unpacked index key */
822 if( pKey ){
823 KeyInfo *pKeyInfo = pCur->pKeyInfo;
824 assert( nKey==(i64)(int)nKey );
825 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
826 if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
827 sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey);
828 if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){
829 rc = SQLITE_CORRUPT_BKPT;
830 }else{
831 rc = sqlite3BtreeIndexMoveto(pCur, pIdxKey, pRes);
833 sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
834 }else{
835 pIdxKey = 0;
836 rc = sqlite3BtreeTableMoveto(pCur, nKey, bias, pRes);
838 return rc;
842 ** Restore the cursor to the position it was in (or as close to as possible)
843 ** when saveCursorPosition() was called. Note that this call deletes the
844 ** saved position info stored by saveCursorPosition(), so there can be
845 ** at most one effective restoreCursorPosition() call after each
846 ** saveCursorPosition().
848 static int btreeRestoreCursorPosition(BtCursor *pCur){
849 int rc;
850 int skipNext = 0;
851 assert( cursorOwnsBtShared(pCur) );
852 assert( pCur->eState>=CURSOR_REQUIRESEEK );
853 if( pCur->eState==CURSOR_FAULT ){
854 return pCur->skipNext;
856 pCur->eState = CURSOR_INVALID;
857 if( sqlite3FaultSim(410) ){
858 rc = SQLITE_IOERR;
859 }else{
860 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
862 if( rc==SQLITE_OK ){
863 sqlite3_free(pCur->pKey);
864 pCur->pKey = 0;
865 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
866 if( skipNext ) pCur->skipNext = skipNext;
867 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
868 pCur->eState = CURSOR_SKIPNEXT;
871 return rc;
874 #define restoreCursorPosition(p) \
875 (p->eState>=CURSOR_REQUIRESEEK ? \
876 btreeRestoreCursorPosition(p) : \
877 SQLITE_OK)
880 ** Determine whether or not a cursor has moved from the position where
881 ** it was last placed, or has been invalidated for any other reason.
882 ** Cursors can move when the row they are pointing at is deleted out
883 ** from under them, for example. Cursor might also move if a btree
884 ** is rebalanced.
886 ** Calling this routine with a NULL cursor pointer returns false.
888 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
889 ** back to where it ought to be if this routine returns true.
891 int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
892 assert( EIGHT_BYTE_ALIGNMENT(pCur)
893 || pCur==sqlite3BtreeFakeValidCursor() );
894 assert( offsetof(BtCursor, eState)==0 );
895 assert( sizeof(pCur->eState)==1 );
896 return CURSOR_VALID != *(u8*)pCur;
900 ** Return a pointer to a fake BtCursor object that will always answer
901 ** false to the sqlite3BtreeCursorHasMoved() routine above. The fake
902 ** cursor returned must not be used with any other Btree interface.
904 BtCursor *sqlite3BtreeFakeValidCursor(void){
905 static u8 fakeCursor = CURSOR_VALID;
906 assert( offsetof(BtCursor, eState)==0 );
907 return (BtCursor*)&fakeCursor;
911 ** This routine restores a cursor back to its original position after it
912 ** has been moved by some outside activity (such as a btree rebalance or
913 ** a row having been deleted out from under the cursor).
915 ** On success, the *pDifferentRow parameter is false if the cursor is left
916 ** pointing at exactly the same row. *pDifferntRow is the row the cursor
917 ** was pointing to has been deleted, forcing the cursor to point to some
918 ** nearby row.
920 ** This routine should only be called for a cursor that just returned
921 ** TRUE from sqlite3BtreeCursorHasMoved().
923 int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
924 int rc;
926 assert( pCur!=0 );
927 assert( pCur->eState!=CURSOR_VALID );
928 rc = restoreCursorPosition(pCur);
929 if( rc ){
930 *pDifferentRow = 1;
931 return rc;
933 if( pCur->eState!=CURSOR_VALID ){
934 *pDifferentRow = 1;
935 }else{
936 *pDifferentRow = 0;
938 return SQLITE_OK;
941 #ifdef SQLITE_ENABLE_CURSOR_HINTS
943 ** Provide hints to the cursor. The particular hint given (and the type
944 ** and number of the varargs parameters) is determined by the eHintType
945 ** parameter. See the definitions of the BTREE_HINT_* macros for details.
947 void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
948 /* Used only by system that substitute their own storage engine */
949 #ifdef SQLITE_DEBUG
950 if( ALWAYS(eHintType==BTREE_HINT_RANGE) ){
951 va_list ap;
952 Expr *pExpr;
953 Walker w;
954 memset(&w, 0, sizeof(w));
955 w.xExprCallback = sqlite3CursorRangeHintExprCheck;
956 va_start(ap, eHintType);
957 pExpr = va_arg(ap, Expr*);
958 w.u.aMem = va_arg(ap, Mem*);
959 va_end(ap);
960 assert( pExpr!=0 );
961 assert( w.u.aMem!=0 );
962 sqlite3WalkExpr(&w, pExpr);
964 #endif /* SQLITE_DEBUG */
966 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
970 ** Provide flag hints to the cursor.
972 void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
973 assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
974 pCur->hints = x;
978 #ifndef SQLITE_OMIT_AUTOVACUUM
980 ** Given a page number of a regular database page, return the page
981 ** number for the pointer-map page that contains the entry for the
982 ** input page number.
984 ** Return 0 (not a valid page) for pgno==1 since there is
985 ** no pointer map associated with page 1. The integrity_check logic
986 ** requires that ptrmapPageno(*,1)!=1.
988 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
989 int nPagesPerMapPage;
990 Pgno iPtrMap, ret;
991 assert( sqlite3_mutex_held(pBt->mutex) );
992 if( pgno<2 ) return 0;
993 nPagesPerMapPage = (pBt->usableSize/5)+1;
994 iPtrMap = (pgno-2)/nPagesPerMapPage;
995 ret = (iPtrMap*nPagesPerMapPage) + 2;
996 if( ret==PENDING_BYTE_PAGE(pBt) ){
997 ret++;
999 return ret;
1003 ** Write an entry into the pointer map.
1005 ** This routine updates the pointer map entry for page number 'key'
1006 ** so that it maps to type 'eType' and parent page number 'pgno'.
1008 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
1009 ** a no-op. If an error occurs, the appropriate error code is written
1010 ** into *pRC.
1012 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
1013 DbPage *pDbPage; /* The pointer map page */
1014 u8 *pPtrmap; /* The pointer map data */
1015 Pgno iPtrmap; /* The pointer map page number */
1016 int offset; /* Offset in pointer map page */
1017 int rc; /* Return code from subfunctions */
1019 if( *pRC ) return;
1021 assert( sqlite3_mutex_held(pBt->mutex) );
1022 /* The super-journal page number must never be used as a pointer map page */
1023 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
1025 assert( pBt->autoVacuum );
1026 if( key==0 ){
1027 *pRC = SQLITE_CORRUPT_BKPT;
1028 return;
1030 iPtrmap = PTRMAP_PAGENO(pBt, key);
1031 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
1032 if( rc!=SQLITE_OK ){
1033 *pRC = rc;
1034 return;
1036 if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){
1037 /* The first byte of the extra data is the MemPage.isInit byte.
1038 ** If that byte is set, it means this page is also being used
1039 ** as a btree page. */
1040 *pRC = SQLITE_CORRUPT_BKPT;
1041 goto ptrmap_exit;
1043 offset = PTRMAP_PTROFFSET(iPtrmap, key);
1044 if( offset<0 ){
1045 *pRC = SQLITE_CORRUPT_BKPT;
1046 goto ptrmap_exit;
1048 assert( offset <= (int)pBt->usableSize-5 );
1049 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1051 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
1052 TRACE(("PTRMAP_UPDATE: %u->(%u,%u)\n", key, eType, parent));
1053 *pRC= rc = sqlite3PagerWrite(pDbPage);
1054 if( rc==SQLITE_OK ){
1055 pPtrmap[offset] = eType;
1056 put4byte(&pPtrmap[offset+1], parent);
1060 ptrmap_exit:
1061 sqlite3PagerUnref(pDbPage);
1065 ** Read an entry from the pointer map.
1067 ** This routine retrieves the pointer map entry for page 'key', writing
1068 ** the type and parent page number to *pEType and *pPgno respectively.
1069 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
1071 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
1072 DbPage *pDbPage; /* The pointer map page */
1073 int iPtrmap; /* Pointer map page index */
1074 u8 *pPtrmap; /* Pointer map page data */
1075 int offset; /* Offset of entry in pointer map */
1076 int rc;
1078 assert( sqlite3_mutex_held(pBt->mutex) );
1080 iPtrmap = PTRMAP_PAGENO(pBt, key);
1081 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
1082 if( rc!=0 ){
1083 return rc;
1085 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1087 offset = PTRMAP_PTROFFSET(iPtrmap, key);
1088 if( offset<0 ){
1089 sqlite3PagerUnref(pDbPage);
1090 return SQLITE_CORRUPT_BKPT;
1092 assert( offset <= (int)pBt->usableSize-5 );
1093 assert( pEType!=0 );
1094 *pEType = pPtrmap[offset];
1095 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
1097 sqlite3PagerUnref(pDbPage);
1098 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
1099 return SQLITE_OK;
1102 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
1103 #define ptrmapPut(w,x,y,z,rc)
1104 #define ptrmapGet(w,x,y,z) SQLITE_OK
1105 #define ptrmapPutOvflPtr(x, y, z, rc)
1106 #endif
1109 ** Given a btree page and a cell index (0 means the first cell on
1110 ** the page, 1 means the second cell, and so forth) return a pointer
1111 ** to the cell content.
1113 ** findCellPastPtr() does the same except it skips past the initial
1114 ** 4-byte child pointer found on interior pages, if there is one.
1116 ** This routine works only for pages that do not contain overflow cells.
1118 #define findCell(P,I) \
1119 ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1120 #define findCellPastPtr(P,I) \
1121 ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1125 ** This is common tail processing for btreeParseCellPtr() and
1126 ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
1127 ** on a single B-tree page. Make necessary adjustments to the CellInfo
1128 ** structure.
1130 static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
1131 MemPage *pPage, /* Page containing the cell */
1132 u8 *pCell, /* Pointer to the cell text. */
1133 CellInfo *pInfo /* Fill in this structure */
1135 /* If the payload will not fit completely on the local page, we have
1136 ** to decide how much to store locally and how much to spill onto
1137 ** overflow pages. The strategy is to minimize the amount of unused
1138 ** space on overflow pages while keeping the amount of local storage
1139 ** in between minLocal and maxLocal.
1141 ** Warning: changing the way overflow payload is distributed in any
1142 ** way will result in an incompatible file format.
1144 int minLocal; /* Minimum amount of payload held locally */
1145 int maxLocal; /* Maximum amount of payload held locally */
1146 int surplus; /* Overflow payload available for local storage */
1148 minLocal = pPage->minLocal;
1149 maxLocal = pPage->maxLocal;
1150 surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
1151 testcase( surplus==maxLocal );
1152 testcase( surplus==maxLocal+1 );
1153 if( surplus <= maxLocal ){
1154 pInfo->nLocal = (u16)surplus;
1155 }else{
1156 pInfo->nLocal = (u16)minLocal;
1158 pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
1162 ** Given a record with nPayload bytes of payload stored within btree
1163 ** page pPage, return the number of bytes of payload stored locally.
1165 static int btreePayloadToLocal(MemPage *pPage, i64 nPayload){
1166 int maxLocal; /* Maximum amount of payload held locally */
1167 maxLocal = pPage->maxLocal;
1168 if( nPayload<=maxLocal ){
1169 return nPayload;
1170 }else{
1171 int minLocal; /* Minimum amount of payload held locally */
1172 int surplus; /* Overflow payload available for local storage */
1173 minLocal = pPage->minLocal;
1174 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize-4);
1175 return ( surplus <= maxLocal ) ? surplus : minLocal;
1180 ** The following routines are implementations of the MemPage.xParseCell()
1181 ** method.
1183 ** Parse a cell content block and fill in the CellInfo structure.
1185 ** btreeParseCellPtr() => table btree leaf nodes
1186 ** btreeParseCellNoPayload() => table btree internal nodes
1187 ** btreeParseCellPtrIndex() => index btree nodes
1189 ** There is also a wrapper function btreeParseCell() that works for
1190 ** all MemPage types and that references the cell by index rather than
1191 ** by pointer.
1193 static void btreeParseCellPtrNoPayload(
1194 MemPage *pPage, /* Page containing the cell */
1195 u8 *pCell, /* Pointer to the cell text. */
1196 CellInfo *pInfo /* Fill in this structure */
1198 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1199 assert( pPage->leaf==0 );
1200 assert( pPage->childPtrSize==4 );
1201 #ifndef SQLITE_DEBUG
1202 UNUSED_PARAMETER(pPage);
1203 #endif
1204 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
1205 pInfo->nPayload = 0;
1206 pInfo->nLocal = 0;
1207 pInfo->pPayload = 0;
1208 return;
1210 static void btreeParseCellPtr(
1211 MemPage *pPage, /* Page containing the cell */
1212 u8 *pCell, /* Pointer to the cell text. */
1213 CellInfo *pInfo /* Fill in this structure */
1215 u8 *pIter; /* For scanning through pCell */
1216 u32 nPayload; /* Number of bytes of cell payload */
1217 u64 iKey; /* Extracted Key value */
1219 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1220 assert( pPage->leaf==0 || pPage->leaf==1 );
1221 assert( pPage->intKeyLeaf );
1222 assert( pPage->childPtrSize==0 );
1223 pIter = pCell;
1225 /* The next block of code is equivalent to:
1227 ** pIter += getVarint32(pIter, nPayload);
1229 ** The code is inlined to avoid a function call.
1231 nPayload = *pIter;
1232 if( nPayload>=0x80 ){
1233 u8 *pEnd = &pIter[8];
1234 nPayload &= 0x7f;
1236 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1237 }while( (*pIter)>=0x80 && pIter<pEnd );
1239 pIter++;
1241 /* The next block of code is equivalent to:
1243 ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
1245 ** The code is inlined and the loop is unrolled for performance.
1246 ** This routine is a high-runner.
1248 iKey = *pIter;
1249 if( iKey>=0x80 ){
1250 u8 x;
1251 iKey = (iKey<<7) ^ (x = *++pIter);
1252 if( x>=0x80 ){
1253 iKey = (iKey<<7) ^ (x = *++pIter);
1254 if( x>=0x80 ){
1255 iKey = (iKey<<7) ^ 0x10204000 ^ (x = *++pIter);
1256 if( x>=0x80 ){
1257 iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
1258 if( x>=0x80 ){
1259 iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
1260 if( x>=0x80 ){
1261 iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
1262 if( x>=0x80 ){
1263 iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
1264 if( x>=0x80 ){
1265 iKey = (iKey<<8) ^ 0x8000 ^ (*++pIter);
1271 }else{
1272 iKey ^= 0x204000;
1274 }else{
1275 iKey ^= 0x4000;
1278 pIter++;
1280 pInfo->nKey = *(i64*)&iKey;
1281 pInfo->nPayload = nPayload;
1282 pInfo->pPayload = pIter;
1283 testcase( nPayload==pPage->maxLocal );
1284 testcase( nPayload==(u32)pPage->maxLocal+1 );
1285 if( nPayload<=pPage->maxLocal ){
1286 /* This is the (easy) common case where the entire payload fits
1287 ** on the local page. No overflow is required.
1289 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1290 if( pInfo->nSize<4 ) pInfo->nSize = 4;
1291 pInfo->nLocal = (u16)nPayload;
1292 }else{
1293 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1296 static void btreeParseCellPtrIndex(
1297 MemPage *pPage, /* Page containing the cell */
1298 u8 *pCell, /* Pointer to the cell text. */
1299 CellInfo *pInfo /* Fill in this structure */
1301 u8 *pIter; /* For scanning through pCell */
1302 u32 nPayload; /* Number of bytes of cell payload */
1304 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1305 assert( pPage->leaf==0 || pPage->leaf==1 );
1306 assert( pPage->intKeyLeaf==0 );
1307 pIter = pCell + pPage->childPtrSize;
1308 nPayload = *pIter;
1309 if( nPayload>=0x80 ){
1310 u8 *pEnd = &pIter[8];
1311 nPayload &= 0x7f;
1313 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1314 }while( *(pIter)>=0x80 && pIter<pEnd );
1316 pIter++;
1317 pInfo->nKey = nPayload;
1318 pInfo->nPayload = nPayload;
1319 pInfo->pPayload = pIter;
1320 testcase( nPayload==pPage->maxLocal );
1321 testcase( nPayload==(u32)pPage->maxLocal+1 );
1322 if( nPayload<=pPage->maxLocal ){
1323 /* This is the (easy) common case where the entire payload fits
1324 ** on the local page. No overflow is required.
1326 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1327 if( pInfo->nSize<4 ) pInfo->nSize = 4;
1328 pInfo->nLocal = (u16)nPayload;
1329 }else{
1330 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1333 static void btreeParseCell(
1334 MemPage *pPage, /* Page containing the cell */
1335 int iCell, /* The cell index. First cell is 0 */
1336 CellInfo *pInfo /* Fill in this structure */
1338 pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
1342 ** The following routines are implementations of the MemPage.xCellSize
1343 ** method.
1345 ** Compute the total number of bytes that a Cell needs in the cell
1346 ** data area of the btree-page. The return number includes the cell
1347 ** data header and the local payload, but not any overflow page or
1348 ** the space used by the cell pointer.
1350 ** cellSizePtrNoPayload() => table internal nodes
1351 ** cellSizePtrTableLeaf() => table leaf nodes
1352 ** cellSizePtr() => index internal nodes
1353 ** cellSizeIdxLeaf() => index leaf nodes
1355 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
1356 u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
1357 u8 *pEnd; /* End mark for a varint */
1358 u32 nSize; /* Size value to return */
1360 #ifdef SQLITE_DEBUG
1361 /* The value returned by this function should always be the same as
1362 ** the (CellInfo.nSize) value found by doing a full parse of the
1363 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1364 ** this function verifies that this invariant is not violated. */
1365 CellInfo debuginfo;
1366 pPage->xParseCell(pPage, pCell, &debuginfo);
1367 #endif
1369 assert( pPage->childPtrSize==4 );
1370 nSize = *pIter;
1371 if( nSize>=0x80 ){
1372 pEnd = &pIter[8];
1373 nSize &= 0x7f;
1375 nSize = (nSize<<7) | (*++pIter & 0x7f);
1376 }while( *(pIter)>=0x80 && pIter<pEnd );
1378 pIter++;
1379 testcase( nSize==pPage->maxLocal );
1380 testcase( nSize==(u32)pPage->maxLocal+1 );
1381 if( nSize<=pPage->maxLocal ){
1382 nSize += (u32)(pIter - pCell);
1383 assert( nSize>4 );
1384 }else{
1385 int minLocal = pPage->minLocal;
1386 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1387 testcase( nSize==pPage->maxLocal );
1388 testcase( nSize==(u32)pPage->maxLocal+1 );
1389 if( nSize>pPage->maxLocal ){
1390 nSize = minLocal;
1392 nSize += 4 + (u16)(pIter - pCell);
1394 assert( nSize==debuginfo.nSize || CORRUPT_DB );
1395 return (u16)nSize;
1397 static u16 cellSizePtrIdxLeaf(MemPage *pPage, u8 *pCell){
1398 u8 *pIter = pCell; /* For looping over bytes of pCell */
1399 u8 *pEnd; /* End mark for a varint */
1400 u32 nSize; /* Size value to return */
1402 #ifdef SQLITE_DEBUG
1403 /* The value returned by this function should always be the same as
1404 ** the (CellInfo.nSize) value found by doing a full parse of the
1405 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1406 ** this function verifies that this invariant is not violated. */
1407 CellInfo debuginfo;
1408 pPage->xParseCell(pPage, pCell, &debuginfo);
1409 #endif
1411 assert( pPage->childPtrSize==0 );
1412 nSize = *pIter;
1413 if( nSize>=0x80 ){
1414 pEnd = &pIter[8];
1415 nSize &= 0x7f;
1417 nSize = (nSize<<7) | (*++pIter & 0x7f);
1418 }while( *(pIter)>=0x80 && pIter<pEnd );
1420 pIter++;
1421 testcase( nSize==pPage->maxLocal );
1422 testcase( nSize==(u32)pPage->maxLocal+1 );
1423 if( nSize<=pPage->maxLocal ){
1424 nSize += (u32)(pIter - pCell);
1425 if( nSize<4 ) nSize = 4;
1426 }else{
1427 int minLocal = pPage->minLocal;
1428 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1429 testcase( nSize==pPage->maxLocal );
1430 testcase( nSize==(u32)pPage->maxLocal+1 );
1431 if( nSize>pPage->maxLocal ){
1432 nSize = minLocal;
1434 nSize += 4 + (u16)(pIter - pCell);
1436 assert( nSize==debuginfo.nSize || CORRUPT_DB );
1437 return (u16)nSize;
1439 static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
1440 u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
1441 u8 *pEnd; /* End mark for a varint */
1443 #ifdef SQLITE_DEBUG
1444 /* The value returned by this function should always be the same as
1445 ** the (CellInfo.nSize) value found by doing a full parse of the
1446 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1447 ** this function verifies that this invariant is not violated. */
1448 CellInfo debuginfo;
1449 pPage->xParseCell(pPage, pCell, &debuginfo);
1450 #else
1451 UNUSED_PARAMETER(pPage);
1452 #endif
1454 assert( pPage->childPtrSize==4 );
1455 pEnd = pIter + 9;
1456 while( (*pIter++)&0x80 && pIter<pEnd );
1457 assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
1458 return (u16)(pIter - pCell);
1460 static u16 cellSizePtrTableLeaf(MemPage *pPage, u8 *pCell){
1461 u8 *pIter = pCell; /* For looping over bytes of pCell */
1462 u8 *pEnd; /* End mark for a varint */
1463 u32 nSize; /* Size value to return */
1465 #ifdef SQLITE_DEBUG
1466 /* The value returned by this function should always be the same as
1467 ** the (CellInfo.nSize) value found by doing a full parse of the
1468 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1469 ** this function verifies that this invariant is not violated. */
1470 CellInfo debuginfo;
1471 pPage->xParseCell(pPage, pCell, &debuginfo);
1472 #endif
1474 nSize = *pIter;
1475 if( nSize>=0x80 ){
1476 pEnd = &pIter[8];
1477 nSize &= 0x7f;
1479 nSize = (nSize<<7) | (*++pIter & 0x7f);
1480 }while( *(pIter)>=0x80 && pIter<pEnd );
1482 pIter++;
1483 /* pIter now points at the 64-bit integer key value, a variable length
1484 ** integer. The following block moves pIter to point at the first byte
1485 ** past the end of the key value. */
1486 if( (*pIter++)&0x80
1487 && (*pIter++)&0x80
1488 && (*pIter++)&0x80
1489 && (*pIter++)&0x80
1490 && (*pIter++)&0x80
1491 && (*pIter++)&0x80
1492 && (*pIter++)&0x80
1493 && (*pIter++)&0x80 ){ pIter++; }
1494 testcase( nSize==pPage->maxLocal );
1495 testcase( nSize==(u32)pPage->maxLocal+1 );
1496 if( nSize<=pPage->maxLocal ){
1497 nSize += (u32)(pIter - pCell);
1498 if( nSize<4 ) nSize = 4;
1499 }else{
1500 int minLocal = pPage->minLocal;
1501 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1502 testcase( nSize==pPage->maxLocal );
1503 testcase( nSize==(u32)pPage->maxLocal+1 );
1504 if( nSize>pPage->maxLocal ){
1505 nSize = minLocal;
1507 nSize += 4 + (u16)(pIter - pCell);
1509 assert( nSize==debuginfo.nSize || CORRUPT_DB );
1510 return (u16)nSize;
1514 #ifdef SQLITE_DEBUG
1515 /* This variation on cellSizePtr() is used inside of assert() statements
1516 ** only. */
1517 static u16 cellSize(MemPage *pPage, int iCell){
1518 return pPage->xCellSize(pPage, findCell(pPage, iCell));
1520 #endif
1522 #ifndef SQLITE_OMIT_AUTOVACUUM
1524 ** The cell pCell is currently part of page pSrc but will ultimately be part
1525 ** of pPage. (pSrc and pPage are often the same.) If pCell contains a
1526 ** pointer to an overflow page, insert an entry into the pointer-map for
1527 ** the overflow page that will be valid after pCell has been moved to pPage.
1529 static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){
1530 CellInfo info;
1531 if( *pRC ) return;
1532 assert( pCell!=0 );
1533 pPage->xParseCell(pPage, pCell, &info);
1534 if( info.nLocal<info.nPayload ){
1535 Pgno ovfl;
1536 if( SQLITE_WITHIN(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){
1537 testcase( pSrc!=pPage );
1538 *pRC = SQLITE_CORRUPT_BKPT;
1539 return;
1541 ovfl = get4byte(&pCell[info.nSize-4]);
1542 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
1545 #endif
1549 ** Defragment the page given. This routine reorganizes cells within the
1550 ** page so that there are no free-blocks on the free-block list.
1552 ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
1553 ** present in the page after this routine returns.
1555 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
1556 ** b-tree page so that there are no freeblocks or fragment bytes, all
1557 ** unused bytes are contained in the unallocated space region, and all
1558 ** cells are packed tightly at the end of the page.
1560 static int defragmentPage(MemPage *pPage, int nMaxFrag){
1561 int i; /* Loop counter */
1562 int pc; /* Address of the i-th cell */
1563 int hdr; /* Offset to the page header */
1564 int size; /* Size of a cell */
1565 int usableSize; /* Number of usable bytes on a page */
1566 int cellOffset; /* Offset to the cell pointer array */
1567 int cbrk; /* Offset to the cell content area */
1568 int nCell; /* Number of cells on the page */
1569 unsigned char *data; /* The page data */
1570 unsigned char *temp; /* Temp area for cell content */
1571 unsigned char *src; /* Source of content */
1572 int iCellFirst; /* First allowable cell index */
1573 int iCellLast; /* Last possible cell index */
1574 int iCellStart; /* First cell offset in input */
1576 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1577 assert( pPage->pBt!=0 );
1578 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
1579 assert( pPage->nOverflow==0 );
1580 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1581 data = pPage->aData;
1582 hdr = pPage->hdrOffset;
1583 cellOffset = pPage->cellOffset;
1584 nCell = pPage->nCell;
1585 assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB );
1586 iCellFirst = cellOffset + 2*nCell;
1587 usableSize = pPage->pBt->usableSize;
1589 /* This block handles pages with two or fewer free blocks and nMaxFrag
1590 ** or fewer fragmented bytes. In this case it is faster to move the
1591 ** two (or one) blocks of cells using memmove() and add the required
1592 ** offsets to each pointer in the cell-pointer array than it is to
1593 ** reconstruct the entire page. */
1594 if( (int)data[hdr+7]<=nMaxFrag ){
1595 int iFree = get2byte(&data[hdr+1]);
1596 if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1597 if( iFree ){
1598 int iFree2 = get2byte(&data[iFree]);
1599 if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1600 if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
1601 u8 *pEnd = &data[cellOffset + nCell*2];
1602 u8 *pAddr;
1603 int sz2 = 0;
1604 int sz = get2byte(&data[iFree+2]);
1605 int top = get2byte(&data[hdr+5]);
1606 if( top>=iFree ){
1607 return SQLITE_CORRUPT_PAGE(pPage);
1609 if( iFree2 ){
1610 if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage);
1611 sz2 = get2byte(&data[iFree2+2]);
1612 if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage);
1613 memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
1614 sz += sz2;
1615 }else if( iFree+sz>usableSize ){
1616 return SQLITE_CORRUPT_PAGE(pPage);
1619 cbrk = top+sz;
1620 assert( cbrk+(iFree-top) <= usableSize );
1621 memmove(&data[cbrk], &data[top], iFree-top);
1622 for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
1623 pc = get2byte(pAddr);
1624 if( pc<iFree ){ put2byte(pAddr, pc+sz); }
1625 else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
1627 goto defragment_out;
1632 cbrk = usableSize;
1633 iCellLast = usableSize - 4;
1634 iCellStart = get2byte(&data[hdr+5]);
1635 if( nCell>0 ){
1636 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
1637 memcpy(&temp[iCellStart], &data[iCellStart], usableSize - iCellStart);
1638 src = temp;
1639 for(i=0; i<nCell; i++){
1640 u8 *pAddr; /* The i-th cell pointer */
1641 pAddr = &data[cellOffset + i*2];
1642 pc = get2byte(pAddr);
1643 testcase( pc==iCellFirst );
1644 testcase( pc==iCellLast );
1645 /* These conditions have already been verified in btreeInitPage()
1646 ** if PRAGMA cell_size_check=ON.
1648 if( pc>iCellLast ){
1649 return SQLITE_CORRUPT_PAGE(pPage);
1651 assert( pc>=0 && pc<=iCellLast );
1652 size = pPage->xCellSize(pPage, &src[pc]);
1653 cbrk -= size;
1654 if( cbrk<iCellStart || pc+size>usableSize ){
1655 return SQLITE_CORRUPT_PAGE(pPage);
1657 assert( cbrk+size<=usableSize && cbrk>=iCellStart );
1658 testcase( cbrk+size==usableSize );
1659 testcase( pc+size==usableSize );
1660 put2byte(pAddr, cbrk);
1661 memcpy(&data[cbrk], &src[pc], size);
1664 data[hdr+7] = 0;
1666 defragment_out:
1667 assert( pPage->nFree>=0 );
1668 if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
1669 return SQLITE_CORRUPT_PAGE(pPage);
1671 assert( cbrk>=iCellFirst );
1672 put2byte(&data[hdr+5], cbrk);
1673 data[hdr+1] = 0;
1674 data[hdr+2] = 0;
1675 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
1676 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1677 return SQLITE_OK;
1681 ** Search the free-list on page pPg for space to store a cell nByte bytes in
1682 ** size. If one can be found, return a pointer to the space and remove it
1683 ** from the free-list.
1685 ** If no suitable space can be found on the free-list, return NULL.
1687 ** This function may detect corruption within pPg. If corruption is
1688 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
1690 ** Slots on the free list that are between 1 and 3 bytes larger than nByte
1691 ** will be ignored if adding the extra space to the fragmentation count
1692 ** causes the fragmentation count to exceed 60.
1694 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
1695 const int hdr = pPg->hdrOffset; /* Offset to page header */
1696 u8 * const aData = pPg->aData; /* Page data */
1697 int iAddr = hdr + 1; /* Address of ptr to pc */
1698 u8 *pTmp = &aData[iAddr]; /* Temporary ptr into aData[] */
1699 int pc = get2byte(pTmp); /* Address of a free slot */
1700 int x; /* Excess size of the slot */
1701 int maxPC = pPg->pBt->usableSize - nByte; /* Max address for a usable slot */
1702 int size; /* Size of the free slot */
1704 assert( pc>0 );
1705 while( pc<=maxPC ){
1706 /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
1707 ** freeblock form a big-endian integer which is the size of the freeblock
1708 ** in bytes, including the 4-byte header. */
1709 pTmp = &aData[pc+2];
1710 size = get2byte(pTmp);
1711 if( (x = size - nByte)>=0 ){
1712 testcase( x==4 );
1713 testcase( x==3 );
1714 if( x<4 ){
1715 /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
1716 ** number of bytes in fragments may not exceed 60. */
1717 if( aData[hdr+7]>57 ) return 0;
1719 /* Remove the slot from the free-list. Update the number of
1720 ** fragmented bytes within the page. */
1721 memcpy(&aData[iAddr], &aData[pc], 2);
1722 aData[hdr+7] += (u8)x;
1723 return &aData[pc];
1724 }else if( x+pc > maxPC ){
1725 /* This slot extends off the end of the usable part of the page */
1726 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1727 return 0;
1728 }else{
1729 /* The slot remains on the free-list. Reduce its size to account
1730 ** for the portion used by the new allocation. */
1731 put2byte(&aData[pc+2], x);
1733 return &aData[pc + x];
1735 iAddr = pc;
1736 pTmp = &aData[pc];
1737 pc = get2byte(pTmp);
1738 if( pc<=iAddr ){
1739 if( pc ){
1740 /* The next slot in the chain comes before the current slot */
1741 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1743 return 0;
1746 if( pc>maxPC+nByte-4 ){
1747 /* The free slot chain extends off the end of the page */
1748 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1750 return 0;
1754 ** Allocate nByte bytes of space from within the B-Tree page passed
1755 ** as the first argument. Write into *pIdx the index into pPage->aData[]
1756 ** of the first byte of allocated space. Return either SQLITE_OK or
1757 ** an error code (usually SQLITE_CORRUPT).
1759 ** The caller guarantees that there is sufficient space to make the
1760 ** allocation. This routine might need to defragment in order to bring
1761 ** all the space together, however. This routine will avoid using
1762 ** the first two bytes past the cell pointer area since presumably this
1763 ** allocation is being made in order to insert a new cell, so we will
1764 ** also end up needing a new cell pointer.
1766 static SQLITE_INLINE int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
1767 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1768 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
1769 int top; /* First byte of cell content area */
1770 int rc = SQLITE_OK; /* Integer return code */
1771 u8 *pTmp; /* Temp ptr into data[] */
1772 int gap; /* First byte of gap between cell pointers and cell content */
1774 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1775 assert( pPage->pBt );
1776 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1777 assert( nByte>=0 ); /* Minimum cell size is 4 */
1778 assert( pPage->nFree>=nByte );
1779 assert( pPage->nOverflow==0 );
1780 assert( nByte < (int)(pPage->pBt->usableSize-8) );
1782 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1783 gap = pPage->cellOffset + 2*pPage->nCell;
1784 assert( gap<=65536 );
1785 /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
1786 ** and the reserved space is zero (the usual value for reserved space)
1787 ** then the cell content offset of an empty page wants to be 65536.
1788 ** However, that integer is too large to be stored in a 2-byte unsigned
1789 ** integer, so a value of 0 is used in its place. */
1790 pTmp = &data[hdr+5];
1791 top = get2byte(pTmp);
1792 if( gap>top ){
1793 if( top==0 && pPage->pBt->usableSize==65536 ){
1794 top = 65536;
1795 }else{
1796 return SQLITE_CORRUPT_PAGE(pPage);
1798 }else if( top>(int)pPage->pBt->usableSize ){
1799 return SQLITE_CORRUPT_PAGE(pPage);
1802 /* If there is enough space between gap and top for one more cell pointer,
1803 ** and if the freelist is not empty, then search the
1804 ** freelist looking for a slot big enough to satisfy the request.
1806 testcase( gap+2==top );
1807 testcase( gap+1==top );
1808 testcase( gap==top );
1809 if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
1810 u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
1811 if( pSpace ){
1812 int g2;
1813 assert( pSpace+nByte<=data+pPage->pBt->usableSize );
1814 *pIdx = g2 = (int)(pSpace-data);
1815 if( g2<=gap ){
1816 return SQLITE_CORRUPT_PAGE(pPage);
1817 }else{
1818 return SQLITE_OK;
1820 }else if( rc ){
1821 return rc;
1825 /* The request could not be fulfilled using a freelist slot. Check
1826 ** to see if defragmentation is necessary.
1828 testcase( gap+2+nByte==top );
1829 if( gap+2+nByte>top ){
1830 assert( pPage->nCell>0 || CORRUPT_DB );
1831 assert( pPage->nFree>=0 );
1832 rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
1833 if( rc ) return rc;
1834 top = get2byteNotZero(&data[hdr+5]);
1835 assert( gap+2+nByte<=top );
1839 /* Allocate memory from the gap in between the cell pointer array
1840 ** and the cell content area. The btreeComputeFreeSpace() call has already
1841 ** validated the freelist. Given that the freelist is valid, there
1842 ** is no way that the allocation can extend off the end of the page.
1843 ** The assert() below verifies the previous sentence.
1845 top -= nByte;
1846 put2byte(&data[hdr+5], top);
1847 assert( top+nByte <= (int)pPage->pBt->usableSize );
1848 *pIdx = top;
1849 return SQLITE_OK;
1853 ** Return a section of the pPage->aData to the freelist.
1854 ** The first byte of the new free block is pPage->aData[iStart]
1855 ** and the size of the block is iSize bytes.
1857 ** Adjacent freeblocks are coalesced.
1859 ** Even though the freeblock list was checked by btreeComputeFreeSpace(),
1860 ** that routine will not detect overlap between cells or freeblocks. Nor
1861 ** does it detect cells or freeblocks that encrouch into the reserved bytes
1862 ** at the end of the page. So do additional corruption checks inside this
1863 ** routine and return SQLITE_CORRUPT if any problems are found.
1865 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
1866 u16 iPtr; /* Address of ptr to next freeblock */
1867 u16 iFreeBlk; /* Address of the next freeblock */
1868 u8 hdr; /* Page header size. 0 or 100 */
1869 u8 nFrag = 0; /* Reduction in fragmentation */
1870 u16 iOrigSize = iSize; /* Original value of iSize */
1871 u16 x; /* Offset to cell content area */
1872 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
1873 unsigned char *data = pPage->aData; /* Page content */
1874 u8 *pTmp; /* Temporary ptr into data[] */
1876 assert( pPage->pBt!=0 );
1877 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1878 assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
1879 assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
1880 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1881 assert( iSize>=4 ); /* Minimum cell size is 4 */
1882 assert( CORRUPT_DB || iStart<=pPage->pBt->usableSize-4 );
1884 /* The list of freeblocks must be in ascending order. Find the
1885 ** spot on the list where iStart should be inserted.
1887 hdr = pPage->hdrOffset;
1888 iPtr = hdr + 1;
1889 if( data[iPtr+1]==0 && data[iPtr]==0 ){
1890 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
1891 }else{
1892 while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
1893 if( iFreeBlk<=iPtr ){
1894 if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */
1895 return SQLITE_CORRUPT_PAGE(pPage);
1897 iPtr = iFreeBlk;
1899 if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */
1900 return SQLITE_CORRUPT_PAGE(pPage);
1902 assert( iFreeBlk>iPtr || iFreeBlk==0 || CORRUPT_DB );
1904 /* At this point:
1905 ** iFreeBlk: First freeblock after iStart, or zero if none
1906 ** iPtr: The address of a pointer to iFreeBlk
1908 ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
1910 if( iFreeBlk && iEnd+3>=iFreeBlk ){
1911 nFrag = iFreeBlk - iEnd;
1912 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
1913 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
1914 if( iEnd > pPage->pBt->usableSize ){
1915 return SQLITE_CORRUPT_PAGE(pPage);
1917 iSize = iEnd - iStart;
1918 iFreeBlk = get2byte(&data[iFreeBlk]);
1921 /* If iPtr is another freeblock (that is, if iPtr is not the freelist
1922 ** pointer in the page header) then check to see if iStart should be
1923 ** coalesced onto the end of iPtr.
1925 if( iPtr>hdr+1 ){
1926 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
1927 if( iPtrEnd+3>=iStart ){
1928 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
1929 nFrag += iStart - iPtrEnd;
1930 iSize = iEnd - iPtr;
1931 iStart = iPtr;
1934 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
1935 data[hdr+7] -= nFrag;
1937 pTmp = &data[hdr+5];
1938 x = get2byte(pTmp);
1939 if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
1940 /* Overwrite deleted information with zeros when the secure_delete
1941 ** option is enabled */
1942 memset(&data[iStart], 0, iSize);
1944 if( iStart<=x ){
1945 /* The new freeblock is at the beginning of the cell content area,
1946 ** so just extend the cell content area rather than create another
1947 ** freelist entry */
1948 if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage);
1949 if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
1950 put2byte(&data[hdr+1], iFreeBlk);
1951 put2byte(&data[hdr+5], iEnd);
1952 }else{
1953 /* Insert the new freeblock into the freelist */
1954 put2byte(&data[iPtr], iStart);
1955 put2byte(&data[iStart], iFreeBlk);
1956 put2byte(&data[iStart+2], iSize);
1958 pPage->nFree += iOrigSize;
1959 return SQLITE_OK;
1963 ** Decode the flags byte (the first byte of the header) for a page
1964 ** and initialize fields of the MemPage structure accordingly.
1966 ** Only the following combinations are supported. Anything different
1967 ** indicates a corrupt database files:
1969 ** PTF_ZERODATA (0x02, 2)
1970 ** PTF_LEAFDATA | PTF_INTKEY (0x05, 5)
1971 ** PTF_ZERODATA | PTF_LEAF (0x0a, 10)
1972 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF (0x0d, 13)
1974 static int decodeFlags(MemPage *pPage, int flagByte){
1975 BtShared *pBt; /* A copy of pPage->pBt */
1977 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
1978 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1979 pBt = pPage->pBt;
1980 pPage->max1bytePayload = pBt->max1bytePayload;
1981 if( flagByte>=(PTF_ZERODATA | PTF_LEAF) ){
1982 pPage->childPtrSize = 0;
1983 pPage->leaf = 1;
1984 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF) ){
1985 pPage->intKeyLeaf = 1;
1986 pPage->xCellSize = cellSizePtrTableLeaf;
1987 pPage->xParseCell = btreeParseCellPtr;
1988 pPage->intKey = 1;
1989 pPage->maxLocal = pBt->maxLeaf;
1990 pPage->minLocal = pBt->minLeaf;
1991 }else if( flagByte==(PTF_ZERODATA | PTF_LEAF) ){
1992 pPage->intKey = 0;
1993 pPage->intKeyLeaf = 0;
1994 pPage->xCellSize = cellSizePtrIdxLeaf;
1995 pPage->xParseCell = btreeParseCellPtrIndex;
1996 pPage->maxLocal = pBt->maxLocal;
1997 pPage->minLocal = pBt->minLocal;
1998 }else{
1999 pPage->intKey = 0;
2000 pPage->intKeyLeaf = 0;
2001 pPage->xCellSize = cellSizePtrIdxLeaf;
2002 pPage->xParseCell = btreeParseCellPtrIndex;
2003 return SQLITE_CORRUPT_PAGE(pPage);
2005 }else{
2006 pPage->childPtrSize = 4;
2007 pPage->leaf = 0;
2008 if( flagByte==(PTF_ZERODATA) ){
2009 pPage->intKey = 0;
2010 pPage->intKeyLeaf = 0;
2011 pPage->xCellSize = cellSizePtr;
2012 pPage->xParseCell = btreeParseCellPtrIndex;
2013 pPage->maxLocal = pBt->maxLocal;
2014 pPage->minLocal = pBt->minLocal;
2015 }else if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
2016 pPage->intKeyLeaf = 0;
2017 pPage->xCellSize = cellSizePtrNoPayload;
2018 pPage->xParseCell = btreeParseCellPtrNoPayload;
2019 pPage->intKey = 1;
2020 pPage->maxLocal = pBt->maxLeaf;
2021 pPage->minLocal = pBt->minLeaf;
2022 }else{
2023 pPage->intKey = 0;
2024 pPage->intKeyLeaf = 0;
2025 pPage->xCellSize = cellSizePtr;
2026 pPage->xParseCell = btreeParseCellPtrIndex;
2027 return SQLITE_CORRUPT_PAGE(pPage);
2030 return SQLITE_OK;
2034 ** Compute the amount of freespace on the page. In other words, fill
2035 ** in the pPage->nFree field.
2037 static int btreeComputeFreeSpace(MemPage *pPage){
2038 int pc; /* Address of a freeblock within pPage->aData[] */
2039 u8 hdr; /* Offset to beginning of page header */
2040 u8 *data; /* Equal to pPage->aData */
2041 int usableSize; /* Amount of usable space on each page */
2042 int nFree; /* Number of unused bytes on the page */
2043 int top; /* First byte of the cell content area */
2044 int iCellFirst; /* First allowable cell or freeblock offset */
2045 int iCellLast; /* Last possible cell or freeblock offset */
2047 assert( pPage->pBt!=0 );
2048 assert( pPage->pBt->db!=0 );
2049 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2050 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
2051 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
2052 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
2053 assert( pPage->isInit==1 );
2054 assert( pPage->nFree<0 );
2056 usableSize = pPage->pBt->usableSize;
2057 hdr = pPage->hdrOffset;
2058 data = pPage->aData;
2059 /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
2060 ** the start of the cell content area. A zero value for this integer is
2061 ** interpreted as 65536. */
2062 top = get2byteNotZero(&data[hdr+5]);
2063 iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell;
2064 iCellLast = usableSize - 4;
2066 /* Compute the total free space on the page
2067 ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
2068 ** start of the first freeblock on the page, or is zero if there are no
2069 ** freeblocks. */
2070 pc = get2byte(&data[hdr+1]);
2071 nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
2072 if( pc>0 ){
2073 u32 next, size;
2074 if( pc<top ){
2075 /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
2076 ** always be at least one cell before the first freeblock.
2078 return SQLITE_CORRUPT_PAGE(pPage);
2080 while( 1 ){
2081 if( pc>iCellLast ){
2082 /* Freeblock off the end of the page */
2083 return SQLITE_CORRUPT_PAGE(pPage);
2085 next = get2byte(&data[pc]);
2086 size = get2byte(&data[pc+2]);
2087 nFree = nFree + size;
2088 if( next<=pc+size+3 ) break;
2089 pc = next;
2091 if( next>0 ){
2092 /* Freeblock not in ascending order */
2093 return SQLITE_CORRUPT_PAGE(pPage);
2095 if( pc+size>(unsigned int)usableSize ){
2096 /* Last freeblock extends past page end */
2097 return SQLITE_CORRUPT_PAGE(pPage);
2101 /* At this point, nFree contains the sum of the offset to the start
2102 ** of the cell-content area plus the number of free bytes within
2103 ** the cell-content area. If this is greater than the usable-size
2104 ** of the page, then the page must be corrupted. This check also
2105 ** serves to verify that the offset to the start of the cell-content
2106 ** area, according to the page header, lies within the page.
2108 if( nFree>usableSize || nFree<iCellFirst ){
2109 return SQLITE_CORRUPT_PAGE(pPage);
2111 pPage->nFree = (u16)(nFree - iCellFirst);
2112 return SQLITE_OK;
2116 ** Do additional sanity check after btreeInitPage() if
2117 ** PRAGMA cell_size_check=ON
2119 static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){
2120 int iCellFirst; /* First allowable cell or freeblock offset */
2121 int iCellLast; /* Last possible cell or freeblock offset */
2122 int i; /* Index into the cell pointer array */
2123 int sz; /* Size of a cell */
2124 int pc; /* Address of a freeblock within pPage->aData[] */
2125 u8 *data; /* Equal to pPage->aData */
2126 int usableSize; /* Maximum usable space on the page */
2127 int cellOffset; /* Start of cell content area */
2129 iCellFirst = pPage->cellOffset + 2*pPage->nCell;
2130 usableSize = pPage->pBt->usableSize;
2131 iCellLast = usableSize - 4;
2132 data = pPage->aData;
2133 cellOffset = pPage->cellOffset;
2134 if( !pPage->leaf ) iCellLast--;
2135 for(i=0; i<pPage->nCell; i++){
2136 pc = get2byteAligned(&data[cellOffset+i*2]);
2137 testcase( pc==iCellFirst );
2138 testcase( pc==iCellLast );
2139 if( pc<iCellFirst || pc>iCellLast ){
2140 return SQLITE_CORRUPT_PAGE(pPage);
2142 sz = pPage->xCellSize(pPage, &data[pc]);
2143 testcase( pc+sz==usableSize );
2144 if( pc+sz>usableSize ){
2145 return SQLITE_CORRUPT_PAGE(pPage);
2148 return SQLITE_OK;
2152 ** Initialize the auxiliary information for a disk block.
2154 ** Return SQLITE_OK on success. If we see that the page does
2155 ** not contain a well-formed database page, then return
2156 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
2157 ** guarantee that the page is well-formed. It only shows that
2158 ** we failed to detect any corruption.
2160 static int btreeInitPage(MemPage *pPage){
2161 u8 *data; /* Equal to pPage->aData */
2162 BtShared *pBt; /* The main btree structure */
2164 assert( pPage->pBt!=0 );
2165 assert( pPage->pBt->db!=0 );
2166 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2167 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
2168 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
2169 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
2170 assert( pPage->isInit==0 );
2172 pBt = pPage->pBt;
2173 data = pPage->aData + pPage->hdrOffset;
2174 /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
2175 ** the b-tree page type. */
2176 if( decodeFlags(pPage, data[0]) ){
2177 return SQLITE_CORRUPT_PAGE(pPage);
2179 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2180 pPage->maskPage = (u16)(pBt->pageSize - 1);
2181 pPage->nOverflow = 0;
2182 pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize;
2183 pPage->aCellIdx = data + pPage->childPtrSize + 8;
2184 pPage->aDataEnd = pPage->aData + pBt->pageSize;
2185 pPage->aDataOfst = pPage->aData + pPage->childPtrSize;
2186 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
2187 ** number of cells on the page. */
2188 pPage->nCell = get2byte(&data[3]);
2189 if( pPage->nCell>MX_CELL(pBt) ){
2190 /* To many cells for a single page. The page must be corrupt */
2191 return SQLITE_CORRUPT_PAGE(pPage);
2193 testcase( pPage->nCell==MX_CELL(pBt) );
2194 /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
2195 ** possible for a root page of a table that contains no rows) then the
2196 ** offset to the cell content area will equal the page size minus the
2197 ** bytes of reserved space. */
2198 assert( pPage->nCell>0
2199 || get2byteNotZero(&data[5])==(int)pBt->usableSize
2200 || CORRUPT_DB );
2201 pPage->nFree = -1; /* Indicate that this value is yet uncomputed */
2202 pPage->isInit = 1;
2203 if( pBt->db->flags & SQLITE_CellSizeCk ){
2204 return btreeCellSizeCheck(pPage);
2206 return SQLITE_OK;
2210 ** Set up a raw page so that it looks like a database page holding
2211 ** no entries.
2213 static void zeroPage(MemPage *pPage, int flags){
2214 unsigned char *data = pPage->aData;
2215 BtShared *pBt = pPage->pBt;
2216 u8 hdr = pPage->hdrOffset;
2217 u16 first;
2219 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno || CORRUPT_DB );
2220 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2221 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
2222 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
2223 assert( sqlite3_mutex_held(pBt->mutex) );
2224 if( pBt->btsFlags & BTS_FAST_SECURE ){
2225 memset(&data[hdr], 0, pBt->usableSize - hdr);
2227 data[hdr] = (char)flags;
2228 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
2229 memset(&data[hdr+1], 0, 4);
2230 data[hdr+7] = 0;
2231 put2byte(&data[hdr+5], pBt->usableSize);
2232 pPage->nFree = (u16)(pBt->usableSize - first);
2233 decodeFlags(pPage, flags);
2234 pPage->cellOffset = first;
2235 pPage->aDataEnd = &data[pBt->pageSize];
2236 pPage->aCellIdx = &data[first];
2237 pPage->aDataOfst = &data[pPage->childPtrSize];
2238 pPage->nOverflow = 0;
2239 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2240 pPage->maskPage = (u16)(pBt->pageSize - 1);
2241 pPage->nCell = 0;
2242 pPage->isInit = 1;
2247 ** Convert a DbPage obtained from the pager into a MemPage used by
2248 ** the btree layer.
2250 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
2251 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2252 if( pgno!=pPage->pgno ){
2253 pPage->aData = sqlite3PagerGetData(pDbPage);
2254 pPage->pDbPage = pDbPage;
2255 pPage->pBt = pBt;
2256 pPage->pgno = pgno;
2257 pPage->hdrOffset = pgno==1 ? 100 : 0;
2259 assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
2260 return pPage;
2264 ** Get a page from the pager. Initialize the MemPage.pBt and
2265 ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
2267 ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
2268 ** about the content of the page at this time. So do not go to the disk
2269 ** to fetch the content. Just fill in the content with zeros for now.
2270 ** If in the future we call sqlite3PagerWrite() on this page, that
2271 ** means we have started to be concerned about content and the disk
2272 ** read should occur at that point.
2274 static int btreeGetPage(
2275 BtShared *pBt, /* The btree */
2276 Pgno pgno, /* Number of the page to fetch */
2277 MemPage **ppPage, /* Return the page in this parameter */
2278 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2280 int rc;
2281 DbPage *pDbPage;
2283 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
2284 assert( sqlite3_mutex_held(pBt->mutex) );
2285 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
2286 if( rc ) return rc;
2287 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
2288 return SQLITE_OK;
2292 ** Retrieve a page from the pager cache. If the requested page is not
2293 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
2294 ** MemPage.aData elements if needed.
2296 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
2297 DbPage *pDbPage;
2298 assert( sqlite3_mutex_held(pBt->mutex) );
2299 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
2300 if( pDbPage ){
2301 return btreePageFromDbPage(pDbPage, pgno, pBt);
2303 return 0;
2307 ** Return the size of the database file in pages. If there is any kind of
2308 ** error, return ((unsigned int)-1).
2310 static Pgno btreePagecount(BtShared *pBt){
2311 return pBt->nPage;
2313 Pgno sqlite3BtreeLastPage(Btree *p){
2314 assert( sqlite3BtreeHoldsMutex(p) );
2315 return btreePagecount(p->pBt);
2319 ** Get a page from the pager and initialize it.
2321 ** If pCur!=0 then the page is being fetched as part of a moveToChild()
2322 ** call. Do additional sanity checking on the page in this case.
2323 ** And if the fetch fails, this routine must decrement pCur->iPage.
2325 ** The page is fetched as read-write unless pCur is not NULL and is
2326 ** a read-only cursor.
2328 ** If an error occurs, then *ppPage is undefined. It
2329 ** may remain unchanged, or it may be set to an invalid value.
2331 static int getAndInitPage(
2332 BtShared *pBt, /* The database file */
2333 Pgno pgno, /* Number of the page to get */
2334 MemPage **ppPage, /* Write the page pointer here */
2335 BtCursor *pCur, /* Cursor to receive the page, or NULL */
2336 int bReadOnly /* True for a read-only page */
2338 int rc;
2339 DbPage *pDbPage;
2340 assert( sqlite3_mutex_held(pBt->mutex) );
2341 assert( pCur==0 || ppPage==&pCur->pPage );
2342 assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
2343 assert( pCur==0 || pCur->iPage>0 );
2345 if( pgno>btreePagecount(pBt) ){
2346 rc = SQLITE_CORRUPT_BKPT;
2347 goto getAndInitPage_error1;
2349 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
2350 if( rc ){
2351 goto getAndInitPage_error1;
2353 *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2354 if( (*ppPage)->isInit==0 ){
2355 btreePageFromDbPage(pDbPage, pgno, pBt);
2356 rc = btreeInitPage(*ppPage);
2357 if( rc!=SQLITE_OK ){
2358 goto getAndInitPage_error2;
2361 assert( (*ppPage)->pgno==pgno || CORRUPT_DB );
2362 assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
2364 /* If obtaining a child page for a cursor, we must verify that the page is
2365 ** compatible with the root page. */
2366 if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
2367 rc = SQLITE_CORRUPT_PGNO(pgno);
2368 goto getAndInitPage_error2;
2370 return SQLITE_OK;
2372 getAndInitPage_error2:
2373 releasePage(*ppPage);
2374 getAndInitPage_error1:
2375 if( pCur ){
2376 pCur->iPage--;
2377 pCur->pPage = pCur->apPage[pCur->iPage];
2379 testcase( pgno==0 );
2380 assert( pgno!=0 || rc!=SQLITE_OK );
2381 return rc;
2385 ** Release a MemPage. This should be called once for each prior
2386 ** call to btreeGetPage.
2388 ** Page1 is a special case and must be released using releasePageOne().
2390 static void releasePageNotNull(MemPage *pPage){
2391 assert( pPage->aData );
2392 assert( pPage->pBt );
2393 assert( pPage->pDbPage!=0 );
2394 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2395 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2396 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2397 sqlite3PagerUnrefNotNull(pPage->pDbPage);
2399 static void releasePage(MemPage *pPage){
2400 if( pPage ) releasePageNotNull(pPage);
2402 static void releasePageOne(MemPage *pPage){
2403 assert( pPage!=0 );
2404 assert( pPage->aData );
2405 assert( pPage->pBt );
2406 assert( pPage->pDbPage!=0 );
2407 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2408 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2409 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2410 sqlite3PagerUnrefPageOne(pPage->pDbPage);
2414 ** Get an unused page.
2416 ** This works just like btreeGetPage() with the addition:
2418 ** * If the page is already in use for some other purpose, immediately
2419 ** release it and return an SQLITE_CURRUPT error.
2420 ** * Make sure the isInit flag is clear
2422 static int btreeGetUnusedPage(
2423 BtShared *pBt, /* The btree */
2424 Pgno pgno, /* Number of the page to fetch */
2425 MemPage **ppPage, /* Return the page in this parameter */
2426 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2428 int rc = btreeGetPage(pBt, pgno, ppPage, flags);
2429 if( rc==SQLITE_OK ){
2430 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
2431 releasePage(*ppPage);
2432 *ppPage = 0;
2433 return SQLITE_CORRUPT_BKPT;
2435 (*ppPage)->isInit = 0;
2436 }else{
2437 *ppPage = 0;
2439 return rc;
2444 ** During a rollback, when the pager reloads information into the cache
2445 ** so that the cache is restored to its original state at the start of
2446 ** the transaction, for each page restored this routine is called.
2448 ** This routine needs to reset the extra data section at the end of the
2449 ** page to agree with the restored data.
2451 static void pageReinit(DbPage *pData){
2452 MemPage *pPage;
2453 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
2454 assert( sqlite3PagerPageRefcount(pData)>0 );
2455 if( pPage->isInit ){
2456 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2457 pPage->isInit = 0;
2458 if( sqlite3PagerPageRefcount(pData)>1 ){
2459 /* pPage might not be a btree page; it might be an overflow page
2460 ** or ptrmap page or a free page. In those cases, the following
2461 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
2462 ** But no harm is done by this. And it is very important that
2463 ** btreeInitPage() be called on every btree page so we make
2464 ** the call for every page that comes in for re-initing. */
2465 btreeInitPage(pPage);
2471 ** Invoke the busy handler for a btree.
2473 static int btreeInvokeBusyHandler(void *pArg){
2474 BtShared *pBt = (BtShared*)pArg;
2475 assert( pBt->db );
2476 assert( sqlite3_mutex_held(pBt->db->mutex) );
2477 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
2481 ** Open a database file.
2483 ** zFilename is the name of the database file. If zFilename is NULL
2484 ** then an ephemeral database is created. The ephemeral database might
2485 ** be exclusively in memory, or it might use a disk-based memory cache.
2486 ** Either way, the ephemeral database will be automatically deleted
2487 ** when sqlite3BtreeClose() is called.
2489 ** If zFilename is ":memory:" then an in-memory database is created
2490 ** that is automatically destroyed when it is closed.
2492 ** The "flags" parameter is a bitmask that might contain bits like
2493 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
2495 ** If the database is already opened in the same database connection
2496 ** and we are in shared cache mode, then the open will fail with an
2497 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
2498 ** objects in the same database connection since doing so will lead
2499 ** to problems with locking.
2501 int sqlite3BtreeOpen(
2502 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
2503 const char *zFilename, /* Name of the file containing the BTree database */
2504 sqlite3 *db, /* Associated database handle */
2505 Btree **ppBtree, /* Pointer to new Btree object written here */
2506 int flags, /* Options */
2507 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
2509 BtShared *pBt = 0; /* Shared part of btree structure */
2510 Btree *p; /* Handle to return */
2511 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
2512 int rc = SQLITE_OK; /* Result code from this function */
2513 u8 nReserve; /* Byte of unused space on each page */
2514 unsigned char zDbHeader[100]; /* Database header content */
2516 /* True if opening an ephemeral, temporary database */
2517 const int isTempDb = zFilename==0 || zFilename[0]==0;
2519 /* Set the variable isMemdb to true for an in-memory database, or
2520 ** false for a file-based database.
2522 #ifdef SQLITE_OMIT_MEMORYDB
2523 const int isMemdb = 0;
2524 #else
2525 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
2526 || (isTempDb && sqlite3TempInMemory(db))
2527 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
2528 #endif
2530 assert( db!=0 );
2531 assert( pVfs!=0 );
2532 assert( sqlite3_mutex_held(db->mutex) );
2533 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
2535 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
2536 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
2538 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
2539 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
2541 if( isMemdb ){
2542 flags |= BTREE_MEMORY;
2544 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
2545 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
2547 p = sqlite3MallocZero(sizeof(Btree));
2548 if( !p ){
2549 return SQLITE_NOMEM_BKPT;
2551 p->inTrans = TRANS_NONE;
2552 p->db = db;
2553 #ifndef SQLITE_OMIT_SHARED_CACHE
2554 p->lock.pBtree = p;
2555 p->lock.iTable = 1;
2556 #endif
2558 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2560 ** If this Btree is a candidate for shared cache, try to find an
2561 ** existing BtShared object that we can share with
2563 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
2564 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
2565 int nFilename = sqlite3Strlen30(zFilename)+1;
2566 int nFullPathname = pVfs->mxPathname+1;
2567 char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
2568 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2570 p->sharable = 1;
2571 if( !zFullPathname ){
2572 sqlite3_free(p);
2573 return SQLITE_NOMEM_BKPT;
2575 if( isMemdb ){
2576 memcpy(zFullPathname, zFilename, nFilename);
2577 }else{
2578 rc = sqlite3OsFullPathname(pVfs, zFilename,
2579 nFullPathname, zFullPathname);
2580 if( rc ){
2581 if( rc==SQLITE_OK_SYMLINK ){
2582 rc = SQLITE_OK;
2583 }else{
2584 sqlite3_free(zFullPathname);
2585 sqlite3_free(p);
2586 return rc;
2590 #if SQLITE_THREADSAFE
2591 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
2592 sqlite3_mutex_enter(mutexOpen);
2593 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
2594 sqlite3_mutex_enter(mutexShared);
2595 #endif
2596 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
2597 assert( pBt->nRef>0 );
2598 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
2599 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
2600 int iDb;
2601 for(iDb=db->nDb-1; iDb>=0; iDb--){
2602 Btree *pExisting = db->aDb[iDb].pBt;
2603 if( pExisting && pExisting->pBt==pBt ){
2604 sqlite3_mutex_leave(mutexShared);
2605 sqlite3_mutex_leave(mutexOpen);
2606 sqlite3_free(zFullPathname);
2607 sqlite3_free(p);
2608 return SQLITE_CONSTRAINT;
2611 p->pBt = pBt;
2612 pBt->nRef++;
2613 break;
2616 sqlite3_mutex_leave(mutexShared);
2617 sqlite3_free(zFullPathname);
2619 #ifdef SQLITE_DEBUG
2620 else{
2621 /* In debug mode, we mark all persistent databases as sharable
2622 ** even when they are not. This exercises the locking code and
2623 ** gives more opportunity for asserts(sqlite3_mutex_held())
2624 ** statements to find locking problems.
2626 p->sharable = 1;
2628 #endif
2630 #endif
2631 if( pBt==0 ){
2633 ** The following asserts make sure that structures used by the btree are
2634 ** the right size. This is to guard against size changes that result
2635 ** when compiling on a different architecture.
2637 assert( sizeof(i64)==8 );
2638 assert( sizeof(u64)==8 );
2639 assert( sizeof(u32)==4 );
2640 assert( sizeof(u16)==2 );
2641 assert( sizeof(Pgno)==4 );
2643 pBt = sqlite3MallocZero( sizeof(*pBt) );
2644 if( pBt==0 ){
2645 rc = SQLITE_NOMEM_BKPT;
2646 goto btree_open_out;
2648 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
2649 sizeof(MemPage), flags, vfsFlags, pageReinit);
2650 if( rc==SQLITE_OK ){
2651 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
2652 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
2654 if( rc!=SQLITE_OK ){
2655 goto btree_open_out;
2657 pBt->openFlags = (u8)flags;
2658 pBt->db = db;
2659 sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
2660 p->pBt = pBt;
2662 pBt->pCursor = 0;
2663 pBt->pPage1 = 0;
2664 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
2665 #if defined(SQLITE_SECURE_DELETE)
2666 pBt->btsFlags |= BTS_SECURE_DELETE;
2667 #elif defined(SQLITE_FAST_SECURE_DELETE)
2668 pBt->btsFlags |= BTS_OVERWRITE;
2669 #endif
2670 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2671 ** determined by the 2-byte integer located at an offset of 16 bytes from
2672 ** the beginning of the database file. */
2673 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
2674 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
2675 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
2676 pBt->pageSize = 0;
2677 #ifndef SQLITE_OMIT_AUTOVACUUM
2678 /* If the magic name ":memory:" will create an in-memory database, then
2679 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
2680 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
2681 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
2682 ** regular file-name. In this case the auto-vacuum applies as per normal.
2684 if( zFilename && !isMemdb ){
2685 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
2686 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
2688 #endif
2689 nReserve = 0;
2690 }else{
2691 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2692 ** determined by the one-byte unsigned integer found at an offset of 20
2693 ** into the database file header. */
2694 nReserve = zDbHeader[20];
2695 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2696 #ifndef SQLITE_OMIT_AUTOVACUUM
2697 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
2698 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
2699 #endif
2701 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2702 if( rc ) goto btree_open_out;
2703 pBt->usableSize = pBt->pageSize - nReserve;
2704 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
2706 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2707 /* Add the new BtShared object to the linked list sharable BtShareds.
2709 pBt->nRef = 1;
2710 if( p->sharable ){
2711 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2712 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);)
2713 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
2714 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
2715 if( pBt->mutex==0 ){
2716 rc = SQLITE_NOMEM_BKPT;
2717 goto btree_open_out;
2720 sqlite3_mutex_enter(mutexShared);
2721 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2722 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
2723 sqlite3_mutex_leave(mutexShared);
2725 #endif
2728 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2729 /* If the new Btree uses a sharable pBtShared, then link the new
2730 ** Btree into the list of all sharable Btrees for the same connection.
2731 ** The list is kept in ascending order by pBt address.
2733 if( p->sharable ){
2734 int i;
2735 Btree *pSib;
2736 for(i=0; i<db->nDb; i++){
2737 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
2738 while( pSib->pPrev ){ pSib = pSib->pPrev; }
2739 if( (uptr)p->pBt<(uptr)pSib->pBt ){
2740 p->pNext = pSib;
2741 p->pPrev = 0;
2742 pSib->pPrev = p;
2743 }else{
2744 while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
2745 pSib = pSib->pNext;
2747 p->pNext = pSib->pNext;
2748 p->pPrev = pSib;
2749 if( p->pNext ){
2750 p->pNext->pPrev = p;
2752 pSib->pNext = p;
2754 break;
2758 #endif
2759 *ppBtree = p;
2761 btree_open_out:
2762 if( rc!=SQLITE_OK ){
2763 if( pBt && pBt->pPager ){
2764 sqlite3PagerClose(pBt->pPager, 0);
2766 sqlite3_free(pBt);
2767 sqlite3_free(p);
2768 *ppBtree = 0;
2769 }else{
2770 sqlite3_file *pFile;
2772 /* If the B-Tree was successfully opened, set the pager-cache size to the
2773 ** default value. Except, when opening on an existing shared pager-cache,
2774 ** do not change the pager-cache size.
2776 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
2777 sqlite3BtreeSetCacheSize(p, SQLITE_DEFAULT_CACHE_SIZE);
2780 pFile = sqlite3PagerFile(pBt->pPager);
2781 if( pFile->pMethods ){
2782 sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
2785 if( mutexOpen ){
2786 assert( sqlite3_mutex_held(mutexOpen) );
2787 sqlite3_mutex_leave(mutexOpen);
2789 assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
2790 return rc;
2794 ** Decrement the BtShared.nRef counter. When it reaches zero,
2795 ** remove the BtShared structure from the sharing list. Return
2796 ** true if the BtShared.nRef counter reaches zero and return
2797 ** false if it is still positive.
2799 static int removeFromSharingList(BtShared *pBt){
2800 #ifndef SQLITE_OMIT_SHARED_CACHE
2801 MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )
2802 BtShared *pList;
2803 int removed = 0;
2805 assert( sqlite3_mutex_notheld(pBt->mutex) );
2806 MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
2807 sqlite3_mutex_enter(pMainMtx);
2808 pBt->nRef--;
2809 if( pBt->nRef<=0 ){
2810 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2811 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
2812 }else{
2813 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
2814 while( ALWAYS(pList) && pList->pNext!=pBt ){
2815 pList=pList->pNext;
2817 if( ALWAYS(pList) ){
2818 pList->pNext = pBt->pNext;
2821 if( SQLITE_THREADSAFE ){
2822 sqlite3_mutex_free(pBt->mutex);
2824 removed = 1;
2826 sqlite3_mutex_leave(pMainMtx);
2827 return removed;
2828 #else
2829 return 1;
2830 #endif
2834 ** Make sure pBt->pTmpSpace points to an allocation of
2835 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
2836 ** pointer.
2838 static SQLITE_NOINLINE int allocateTempSpace(BtShared *pBt){
2839 assert( pBt!=0 );
2840 assert( pBt->pTmpSpace==0 );
2841 /* This routine is called only by btreeCursor() when allocating the
2842 ** first write cursor for the BtShared object */
2843 assert( pBt->pCursor!=0 && (pBt->pCursor->curFlags & BTCF_WriteFlag)!=0 );
2844 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
2845 if( pBt->pTmpSpace==0 ){
2846 BtCursor *pCur = pBt->pCursor;
2847 pBt->pCursor = pCur->pNext; /* Unlink the cursor */
2848 memset(pCur, 0, sizeof(*pCur));
2849 return SQLITE_NOMEM_BKPT;
2852 /* One of the uses of pBt->pTmpSpace is to format cells before
2853 ** inserting them into a leaf page (function fillInCell()). If
2854 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
2855 ** by the various routines that manipulate binary cells. Which
2856 ** can mean that fillInCell() only initializes the first 2 or 3
2857 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
2858 ** it into a database page. This is not actually a problem, but it
2859 ** does cause a valgrind error when the 1 or 2 bytes of unitialized
2860 ** data is passed to system call write(). So to avoid this error,
2861 ** zero the first 4 bytes of temp space here.
2863 ** Also: Provide four bytes of initialized space before the
2864 ** beginning of pTmpSpace as an area available to prepend the
2865 ** left-child pointer to the beginning of a cell.
2867 memset(pBt->pTmpSpace, 0, 8);
2868 pBt->pTmpSpace += 4;
2869 return SQLITE_OK;
2873 ** Free the pBt->pTmpSpace allocation
2875 static void freeTempSpace(BtShared *pBt){
2876 if( pBt->pTmpSpace ){
2877 pBt->pTmpSpace -= 4;
2878 sqlite3PageFree(pBt->pTmpSpace);
2879 pBt->pTmpSpace = 0;
2884 ** Close an open database and invalidate all cursors.
2886 int sqlite3BtreeClose(Btree *p){
2887 BtShared *pBt = p->pBt;
2889 /* Close all cursors opened via this handle. */
2890 assert( sqlite3_mutex_held(p->db->mutex) );
2891 sqlite3BtreeEnter(p);
2893 /* Verify that no other cursors have this Btree open */
2894 #ifdef SQLITE_DEBUG
2896 BtCursor *pCur = pBt->pCursor;
2897 while( pCur ){
2898 BtCursor *pTmp = pCur;
2899 pCur = pCur->pNext;
2900 assert( pTmp->pBtree!=p );
2904 #endif
2906 /* Rollback any active transaction and free the handle structure.
2907 ** The call to sqlite3BtreeRollback() drops any table-locks held by
2908 ** this handle.
2910 sqlite3BtreeRollback(p, SQLITE_OK, 0);
2911 sqlite3BtreeLeave(p);
2913 /* If there are still other outstanding references to the shared-btree
2914 ** structure, return now. The remainder of this procedure cleans
2915 ** up the shared-btree.
2917 assert( p->wantToLock==0 && p->locked==0 );
2918 if( !p->sharable || removeFromSharingList(pBt) ){
2919 /* The pBt is no longer on the sharing list, so we can access
2920 ** it without having to hold the mutex.
2922 ** Clean out and delete the BtShared object.
2924 assert( !pBt->pCursor );
2925 sqlite3PagerClose(pBt->pPager, p->db);
2926 if( pBt->xFreeSchema && pBt->pSchema ){
2927 pBt->xFreeSchema(pBt->pSchema);
2929 sqlite3DbFree(0, pBt->pSchema);
2930 freeTempSpace(pBt);
2931 sqlite3_free(pBt);
2934 #ifndef SQLITE_OMIT_SHARED_CACHE
2935 assert( p->wantToLock==0 );
2936 assert( p->locked==0 );
2937 if( p->pPrev ) p->pPrev->pNext = p->pNext;
2938 if( p->pNext ) p->pNext->pPrev = p->pPrev;
2939 #endif
2941 sqlite3_free(p);
2942 return SQLITE_OK;
2946 ** Change the "soft" limit on the number of pages in the cache.
2947 ** Unused and unmodified pages will be recycled when the number of
2948 ** pages in the cache exceeds this soft limit. But the size of the
2949 ** cache is allowed to grow larger than this limit if it contains
2950 ** dirty pages or pages still in active use.
2952 int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2953 BtShared *pBt = p->pBt;
2954 assert( sqlite3_mutex_held(p->db->mutex) );
2955 sqlite3BtreeEnter(p);
2956 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
2957 sqlite3BtreeLeave(p);
2958 return SQLITE_OK;
2962 ** Change the "spill" limit on the number of pages in the cache.
2963 ** If the number of pages exceeds this limit during a write transaction,
2964 ** the pager might attempt to "spill" pages to the journal early in
2965 ** order to free up memory.
2967 ** The value returned is the current spill size. If zero is passed
2968 ** as an argument, no changes are made to the spill size setting, so
2969 ** using mxPage of 0 is a way to query the current spill size.
2971 int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
2972 BtShared *pBt = p->pBt;
2973 int res;
2974 assert( sqlite3_mutex_held(p->db->mutex) );
2975 sqlite3BtreeEnter(p);
2976 res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
2977 sqlite3BtreeLeave(p);
2978 return res;
2981 #if SQLITE_MAX_MMAP_SIZE>0
2983 ** Change the limit on the amount of the database file that may be
2984 ** memory mapped.
2986 int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
2987 BtShared *pBt = p->pBt;
2988 assert( sqlite3_mutex_held(p->db->mutex) );
2989 sqlite3BtreeEnter(p);
2990 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
2991 sqlite3BtreeLeave(p);
2992 return SQLITE_OK;
2994 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
2997 ** Change the way data is synced to disk in order to increase or decrease
2998 ** how well the database resists damage due to OS crashes and power
2999 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
3000 ** there is a high probability of damage) Level 2 is the default. There
3001 ** is a very low but non-zero probability of damage. Level 3 reduces the
3002 ** probability of damage to near zero but with a write performance reduction.
3004 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
3005 int sqlite3BtreeSetPagerFlags(
3006 Btree *p, /* The btree to set the safety level on */
3007 unsigned pgFlags /* Various PAGER_* flags */
3009 BtShared *pBt = p->pBt;
3010 assert( sqlite3_mutex_held(p->db->mutex) );
3011 sqlite3BtreeEnter(p);
3012 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
3013 sqlite3BtreeLeave(p);
3014 return SQLITE_OK;
3016 #endif
3019 ** Change the default pages size and the number of reserved bytes per page.
3020 ** Or, if the page size has already been fixed, return SQLITE_READONLY
3021 ** without changing anything.
3023 ** The page size must be a power of 2 between 512 and 65536. If the page
3024 ** size supplied does not meet this constraint then the page size is not
3025 ** changed.
3027 ** Page sizes are constrained to be a power of two so that the region
3028 ** of the database file used for locking (beginning at PENDING_BYTE,
3029 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
3030 ** at the beginning of a page.
3032 ** If parameter nReserve is less than zero, then the number of reserved
3033 ** bytes per page is left unchanged.
3035 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
3036 ** and autovacuum mode can no longer be changed.
3038 int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
3039 int rc = SQLITE_OK;
3040 int x;
3041 BtShared *pBt = p->pBt;
3042 assert( nReserve>=0 && nReserve<=255 );
3043 sqlite3BtreeEnter(p);
3044 pBt->nReserveWanted = nReserve;
3045 x = pBt->pageSize - pBt->usableSize;
3046 if( nReserve<x ) nReserve = x;
3047 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
3048 sqlite3BtreeLeave(p);
3049 return SQLITE_READONLY;
3051 assert( nReserve>=0 && nReserve<=255 );
3052 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
3053 ((pageSize-1)&pageSize)==0 ){
3054 assert( (pageSize & 7)==0 );
3055 assert( !pBt->pCursor );
3056 if( nReserve>32 && pageSize==512 ) pageSize = 1024;
3057 pBt->pageSize = (u32)pageSize;
3058 freeTempSpace(pBt);
3060 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
3061 pBt->usableSize = pBt->pageSize - (u16)nReserve;
3062 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3063 sqlite3BtreeLeave(p);
3064 return rc;
3068 ** Return the currently defined page size
3070 int sqlite3BtreeGetPageSize(Btree *p){
3071 return p->pBt->pageSize;
3075 ** This function is similar to sqlite3BtreeGetReserve(), except that it
3076 ** may only be called if it is guaranteed that the b-tree mutex is already
3077 ** held.
3079 ** This is useful in one special case in the backup API code where it is
3080 ** known that the shared b-tree mutex is held, but the mutex on the
3081 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
3082 ** were to be called, it might collide with some other operation on the
3083 ** database handle that owns *p, causing undefined behavior.
3085 int sqlite3BtreeGetReserveNoMutex(Btree *p){
3086 int n;
3087 assert( sqlite3_mutex_held(p->pBt->mutex) );
3088 n = p->pBt->pageSize - p->pBt->usableSize;
3089 return n;
3093 ** Return the number of bytes of space at the end of every page that
3094 ** are intentually left unused. This is the "reserved" space that is
3095 ** sometimes used by extensions.
3097 ** The value returned is the larger of the current reserve size and
3098 ** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES.
3099 ** The amount of reserve can only grow - never shrink.
3101 int sqlite3BtreeGetRequestedReserve(Btree *p){
3102 int n1, n2;
3103 sqlite3BtreeEnter(p);
3104 n1 = (int)p->pBt->nReserveWanted;
3105 n2 = sqlite3BtreeGetReserveNoMutex(p);
3106 sqlite3BtreeLeave(p);
3107 return n1>n2 ? n1 : n2;
3112 ** Set the maximum page count for a database if mxPage is positive.
3113 ** No changes are made if mxPage is 0 or negative.
3114 ** Regardless of the value of mxPage, return the maximum page count.
3116 Pgno sqlite3BtreeMaxPageCount(Btree *p, Pgno mxPage){
3117 Pgno n;
3118 sqlite3BtreeEnter(p);
3119 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
3120 sqlite3BtreeLeave(p);
3121 return n;
3125 ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
3127 ** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
3128 ** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
3129 ** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
3130 ** newFlag==(-1) No changes
3132 ** This routine acts as a query if newFlag is less than zero
3134 ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
3135 ** freelist leaf pages are not written back to the database. Thus in-page
3136 ** deleted content is cleared, but freelist deleted content is not.
3138 ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
3139 ** that freelist leaf pages are written back into the database, increasing
3140 ** the amount of disk I/O.
3142 int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
3143 int b;
3144 if( p==0 ) return 0;
3145 sqlite3BtreeEnter(p);
3146 assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
3147 assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
3148 if( newFlag>=0 ){
3149 p->pBt->btsFlags &= ~BTS_FAST_SECURE;
3150 p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
3152 b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
3153 sqlite3BtreeLeave(p);
3154 return b;
3158 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
3159 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
3160 ** is disabled. The default value for the auto-vacuum property is
3161 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
3163 int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
3164 #ifdef SQLITE_OMIT_AUTOVACUUM
3165 return SQLITE_READONLY;
3166 #else
3167 BtShared *pBt = p->pBt;
3168 int rc = SQLITE_OK;
3169 u8 av = (u8)autoVacuum;
3171 sqlite3BtreeEnter(p);
3172 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
3173 rc = SQLITE_READONLY;
3174 }else{
3175 pBt->autoVacuum = av ?1:0;
3176 pBt->incrVacuum = av==2 ?1:0;
3178 sqlite3BtreeLeave(p);
3179 return rc;
3180 #endif
3184 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
3185 ** enabled 1 is returned. Otherwise 0.
3187 int sqlite3BtreeGetAutoVacuum(Btree *p){
3188 #ifdef SQLITE_OMIT_AUTOVACUUM
3189 return BTREE_AUTOVACUUM_NONE;
3190 #else
3191 int rc;
3192 sqlite3BtreeEnter(p);
3193 rc = (
3194 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
3195 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
3196 BTREE_AUTOVACUUM_INCR
3198 sqlite3BtreeLeave(p);
3199 return rc;
3200 #endif
3204 ** If the user has not set the safety-level for this database connection
3205 ** using "PRAGMA synchronous", and if the safety-level is not already
3206 ** set to the value passed to this function as the second parameter,
3207 ** set it so.
3209 #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
3210 && !defined(SQLITE_OMIT_WAL)
3211 static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
3212 sqlite3 *db;
3213 Db *pDb;
3214 if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
3215 while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
3216 if( pDb->bSyncSet==0
3217 && pDb->safety_level!=safety_level
3218 && pDb!=&db->aDb[1]
3220 pDb->safety_level = safety_level;
3221 sqlite3PagerSetFlags(pBt->pPager,
3222 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
3226 #else
3227 # define setDefaultSyncFlag(pBt,safety_level)
3228 #endif
3230 /* Forward declaration */
3231 static int newDatabase(BtShared*);
3235 ** Get a reference to pPage1 of the database file. This will
3236 ** also acquire a readlock on that file.
3238 ** SQLITE_OK is returned on success. If the file is not a
3239 ** well-formed database file, then SQLITE_CORRUPT is returned.
3240 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
3241 ** is returned if we run out of memory.
3243 static int lockBtree(BtShared *pBt){
3244 int rc; /* Result code from subfunctions */
3245 MemPage *pPage1; /* Page 1 of the database file */
3246 u32 nPage; /* Number of pages in the database */
3247 u32 nPageFile = 0; /* Number of pages in the database file */
3249 assert( sqlite3_mutex_held(pBt->mutex) );
3250 assert( pBt->pPage1==0 );
3251 rc = sqlite3PagerSharedLock(pBt->pPager);
3252 if( rc!=SQLITE_OK ) return rc;
3253 rc = btreeGetPage(pBt, 1, &pPage1, 0);
3254 if( rc!=SQLITE_OK ) return rc;
3256 /* Do some checking to help insure the file we opened really is
3257 ** a valid database file.
3259 nPage = get4byte(28+(u8*)pPage1->aData);
3260 sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
3261 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
3262 nPage = nPageFile;
3264 if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
3265 nPage = 0;
3267 if( nPage>0 ){
3268 u32 pageSize;
3269 u32 usableSize;
3270 u8 *page1 = pPage1->aData;
3271 rc = SQLITE_NOTADB;
3272 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
3273 ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
3274 ** 61 74 20 33 00. */
3275 if( memcmp(page1, zMagicHeader, 16)!=0 ){
3276 goto page1_init_failed;
3279 #ifdef SQLITE_OMIT_WAL
3280 if( page1[18]>1 ){
3281 pBt->btsFlags |= BTS_READ_ONLY;
3283 if( page1[19]>1 ){
3284 goto page1_init_failed;
3286 #else
3287 if( page1[18]>2 ){
3288 pBt->btsFlags |= BTS_READ_ONLY;
3290 if( page1[19]>2 ){
3291 goto page1_init_failed;
3294 /* If the read version is set to 2, this database should be accessed
3295 ** in WAL mode. If the log is not already open, open it now. Then
3296 ** return SQLITE_OK and return without populating BtShared.pPage1.
3297 ** The caller detects this and calls this function again. This is
3298 ** required as the version of page 1 currently in the page1 buffer
3299 ** may not be the latest version - there may be a newer one in the log
3300 ** file.
3302 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
3303 int isOpen = 0;
3304 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
3305 if( rc!=SQLITE_OK ){
3306 goto page1_init_failed;
3307 }else{
3308 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
3309 if( isOpen==0 ){
3310 releasePageOne(pPage1);
3311 return SQLITE_OK;
3314 rc = SQLITE_NOTADB;
3315 }else{
3316 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
3318 #endif
3320 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
3321 ** fractions and the leaf payload fraction values must be 64, 32, and 32.
3323 ** The original design allowed these amounts to vary, but as of
3324 ** version 3.6.0, we require them to be fixed.
3326 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
3327 goto page1_init_failed;
3329 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
3330 ** determined by the 2-byte integer located at an offset of 16 bytes from
3331 ** the beginning of the database file. */
3332 pageSize = (page1[16]<<8) | (page1[17]<<16);
3333 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
3334 ** between 512 and 65536 inclusive. */
3335 if( ((pageSize-1)&pageSize)!=0
3336 || pageSize>SQLITE_MAX_PAGE_SIZE
3337 || pageSize<=256
3339 goto page1_init_failed;
3341 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3342 assert( (pageSize & 7)==0 );
3343 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
3344 ** integer at offset 20 is the number of bytes of space at the end of
3345 ** each page to reserve for extensions.
3347 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
3348 ** determined by the one-byte unsigned integer found at an offset of 20
3349 ** into the database file header. */
3350 usableSize = pageSize - page1[20];
3351 if( (u32)pageSize!=pBt->pageSize ){
3352 /* After reading the first page of the database assuming a page size
3353 ** of BtShared.pageSize, we have discovered that the page-size is
3354 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
3355 ** zero and return SQLITE_OK. The caller will call this function
3356 ** again with the correct page-size.
3358 releasePageOne(pPage1);
3359 pBt->usableSize = usableSize;
3360 pBt->pageSize = pageSize;
3361 freeTempSpace(pBt);
3362 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
3363 pageSize-usableSize);
3364 return rc;
3366 if( nPage>nPageFile ){
3367 if( sqlite3WritableSchema(pBt->db)==0 ){
3368 rc = SQLITE_CORRUPT_BKPT;
3369 goto page1_init_failed;
3370 }else{
3371 nPage = nPageFile;
3374 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
3375 ** be less than 480. In other words, if the page size is 512, then the
3376 ** reserved space size cannot exceed 32. */
3377 if( usableSize<480 ){
3378 goto page1_init_failed;
3380 pBt->pageSize = pageSize;
3381 pBt->usableSize = usableSize;
3382 #ifndef SQLITE_OMIT_AUTOVACUUM
3383 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
3384 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
3385 #endif
3388 /* maxLocal is the maximum amount of payload to store locally for
3389 ** a cell. Make sure it is small enough so that at least minFanout
3390 ** cells can will fit on one page. We assume a 10-byte page header.
3391 ** Besides the payload, the cell must store:
3392 ** 2-byte pointer to the cell
3393 ** 4-byte child pointer
3394 ** 9-byte nKey value
3395 ** 4-byte nData value
3396 ** 4-byte overflow page pointer
3397 ** So a cell consists of a 2-byte pointer, a header which is as much as
3398 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
3399 ** page pointer.
3401 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
3402 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
3403 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
3404 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
3405 if( pBt->maxLocal>127 ){
3406 pBt->max1bytePayload = 127;
3407 }else{
3408 pBt->max1bytePayload = (u8)pBt->maxLocal;
3410 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
3411 pBt->pPage1 = pPage1;
3412 pBt->nPage = nPage;
3413 return SQLITE_OK;
3415 page1_init_failed:
3416 releasePageOne(pPage1);
3417 pBt->pPage1 = 0;
3418 return rc;
3421 #ifndef NDEBUG
3423 ** Return the number of cursors open on pBt. This is for use
3424 ** in assert() expressions, so it is only compiled if NDEBUG is not
3425 ** defined.
3427 ** Only write cursors are counted if wrOnly is true. If wrOnly is
3428 ** false then all cursors are counted.
3430 ** For the purposes of this routine, a cursor is any cursor that
3431 ** is capable of reading or writing to the database. Cursors that
3432 ** have been tripped into the CURSOR_FAULT state are not counted.
3434 static int countValidCursors(BtShared *pBt, int wrOnly){
3435 BtCursor *pCur;
3436 int r = 0;
3437 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3438 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
3439 && pCur->eState!=CURSOR_FAULT ) r++;
3441 return r;
3443 #endif
3446 ** If there are no outstanding cursors and we are not in the middle
3447 ** of a transaction but there is a read lock on the database, then
3448 ** this routine unrefs the first page of the database file which
3449 ** has the effect of releasing the read lock.
3451 ** If there is a transaction in progress, this routine is a no-op.
3453 static void unlockBtreeIfUnused(BtShared *pBt){
3454 assert( sqlite3_mutex_held(pBt->mutex) );
3455 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
3456 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
3457 MemPage *pPage1 = pBt->pPage1;
3458 assert( pPage1->aData );
3459 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
3460 pBt->pPage1 = 0;
3461 releasePageOne(pPage1);
3466 ** If pBt points to an empty file then convert that empty file
3467 ** into a new empty database by initializing the first page of
3468 ** the database.
3470 static int newDatabase(BtShared *pBt){
3471 MemPage *pP1;
3472 unsigned char *data;
3473 int rc;
3475 assert( sqlite3_mutex_held(pBt->mutex) );
3476 if( pBt->nPage>0 ){
3477 return SQLITE_OK;
3479 pP1 = pBt->pPage1;
3480 assert( pP1!=0 );
3481 data = pP1->aData;
3482 rc = sqlite3PagerWrite(pP1->pDbPage);
3483 if( rc ) return rc;
3484 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
3485 assert( sizeof(zMagicHeader)==16 );
3486 data[16] = (u8)((pBt->pageSize>>8)&0xff);
3487 data[17] = (u8)((pBt->pageSize>>16)&0xff);
3488 data[18] = 1;
3489 data[19] = 1;
3490 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
3491 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
3492 data[21] = 64;
3493 data[22] = 32;
3494 data[23] = 32;
3495 memset(&data[24], 0, 100-24);
3496 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
3497 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3498 #ifndef SQLITE_OMIT_AUTOVACUUM
3499 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
3500 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
3501 put4byte(&data[36 + 4*4], pBt->autoVacuum);
3502 put4byte(&data[36 + 7*4], pBt->incrVacuum);
3503 #endif
3504 pBt->nPage = 1;
3505 data[31] = 1;
3506 return SQLITE_OK;
3510 ** Initialize the first page of the database file (creating a database
3511 ** consisting of a single page and no schema objects). Return SQLITE_OK
3512 ** if successful, or an SQLite error code otherwise.
3514 int sqlite3BtreeNewDb(Btree *p){
3515 int rc;
3516 sqlite3BtreeEnter(p);
3517 p->pBt->nPage = 0;
3518 rc = newDatabase(p->pBt);
3519 sqlite3BtreeLeave(p);
3520 return rc;
3524 ** Attempt to start a new transaction. A write-transaction
3525 ** is started if the second argument is nonzero, otherwise a read-
3526 ** transaction. If the second argument is 2 or more and exclusive
3527 ** transaction is started, meaning that no other process is allowed
3528 ** to access the database. A preexisting transaction may not be
3529 ** upgraded to exclusive by calling this routine a second time - the
3530 ** exclusivity flag only works for a new transaction.
3532 ** A write-transaction must be started before attempting any
3533 ** changes to the database. None of the following routines
3534 ** will work unless a transaction is started first:
3536 ** sqlite3BtreeCreateTable()
3537 ** sqlite3BtreeCreateIndex()
3538 ** sqlite3BtreeClearTable()
3539 ** sqlite3BtreeDropTable()
3540 ** sqlite3BtreeInsert()
3541 ** sqlite3BtreeDelete()
3542 ** sqlite3BtreeUpdateMeta()
3544 ** If an initial attempt to acquire the lock fails because of lock contention
3545 ** and the database was previously unlocked, then invoke the busy handler
3546 ** if there is one. But if there was previously a read-lock, do not
3547 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
3548 ** returned when there is already a read-lock in order to avoid a deadlock.
3550 ** Suppose there are two processes A and B. A has a read lock and B has
3551 ** a reserved lock. B tries to promote to exclusive but is blocked because
3552 ** of A's read lock. A tries to promote to reserved but is blocked by B.
3553 ** One or the other of the two processes must give way or there can be
3554 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
3555 ** when A already has a read lock, we encourage A to give up and let B
3556 ** proceed.
3558 int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
3559 BtShared *pBt = p->pBt;
3560 Pager *pPager = pBt->pPager;
3561 int rc = SQLITE_OK;
3563 sqlite3BtreeEnter(p);
3564 btreeIntegrity(p);
3566 /* If the btree is already in a write-transaction, or it
3567 ** is already in a read-transaction and a read-transaction
3568 ** is requested, this is a no-op.
3570 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
3571 goto trans_begun;
3573 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
3575 if( (p->db->flags & SQLITE_ResetDatabase)
3576 && sqlite3PagerIsreadonly(pPager)==0
3578 pBt->btsFlags &= ~BTS_READ_ONLY;
3581 /* Write transactions are not possible on a read-only database */
3582 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
3583 rc = SQLITE_READONLY;
3584 goto trans_begun;
3587 #ifndef SQLITE_OMIT_SHARED_CACHE
3589 sqlite3 *pBlock = 0;
3590 /* If another database handle has already opened a write transaction
3591 ** on this shared-btree structure and a second write transaction is
3592 ** requested, return SQLITE_LOCKED.
3594 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
3595 || (pBt->btsFlags & BTS_PENDING)!=0
3597 pBlock = pBt->pWriter->db;
3598 }else if( wrflag>1 ){
3599 BtLock *pIter;
3600 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
3601 if( pIter->pBtree!=p ){
3602 pBlock = pIter->pBtree->db;
3603 break;
3607 if( pBlock ){
3608 sqlite3ConnectionBlocked(p->db, pBlock);
3609 rc = SQLITE_LOCKED_SHAREDCACHE;
3610 goto trans_begun;
3613 #endif
3615 /* Any read-only or read-write transaction implies a read-lock on
3616 ** page 1. So if some other shared-cache client already has a write-lock
3617 ** on page 1, the transaction cannot be opened. */
3618 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
3619 if( SQLITE_OK!=rc ) goto trans_begun;
3621 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
3622 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
3623 do {
3624 sqlite3PagerWalDb(pPager, p->db);
3626 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3627 /* If transitioning from no transaction directly to a write transaction,
3628 ** block for the WRITER lock first if possible. */
3629 if( pBt->pPage1==0 && wrflag ){
3630 assert( pBt->inTransaction==TRANS_NONE );
3631 rc = sqlite3PagerWalWriteLock(pPager, 1);
3632 if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break;
3634 #endif
3636 /* Call lockBtree() until either pBt->pPage1 is populated or
3637 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
3638 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
3639 ** reading page 1 it discovers that the page-size of the database
3640 ** file is not pBt->pageSize. In this case lockBtree() will update
3641 ** pBt->pageSize to the page-size of the file on disk.
3643 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
3645 if( rc==SQLITE_OK && wrflag ){
3646 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
3647 rc = SQLITE_READONLY;
3648 }else{
3649 rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db));
3650 if( rc==SQLITE_OK ){
3651 rc = newDatabase(pBt);
3652 }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
3653 /* if there was no transaction opened when this function was
3654 ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
3655 ** code to SQLITE_BUSY. */
3656 rc = SQLITE_BUSY;
3661 if( rc!=SQLITE_OK ){
3662 (void)sqlite3PagerWalWriteLock(pPager, 0);
3663 unlockBtreeIfUnused(pBt);
3665 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
3666 btreeInvokeBusyHandler(pBt) );
3667 sqlite3PagerWalDb(pPager, 0);
3668 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3669 if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
3670 #endif
3672 if( rc==SQLITE_OK ){
3673 if( p->inTrans==TRANS_NONE ){
3674 pBt->nTransaction++;
3675 #ifndef SQLITE_OMIT_SHARED_CACHE
3676 if( p->sharable ){
3677 assert( p->lock.pBtree==p && p->lock.iTable==1 );
3678 p->lock.eLock = READ_LOCK;
3679 p->lock.pNext = pBt->pLock;
3680 pBt->pLock = &p->lock;
3682 #endif
3684 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
3685 if( p->inTrans>pBt->inTransaction ){
3686 pBt->inTransaction = p->inTrans;
3688 if( wrflag ){
3689 MemPage *pPage1 = pBt->pPage1;
3690 #ifndef SQLITE_OMIT_SHARED_CACHE
3691 assert( !pBt->pWriter );
3692 pBt->pWriter = p;
3693 pBt->btsFlags &= ~BTS_EXCLUSIVE;
3694 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
3695 #endif
3697 /* If the db-size header field is incorrect (as it may be if an old
3698 ** client has been writing the database file), update it now. Doing
3699 ** this sooner rather than later means the database size can safely
3700 ** re-read the database size from page 1 if a savepoint or transaction
3701 ** rollback occurs within the transaction.
3703 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
3704 rc = sqlite3PagerWrite(pPage1->pDbPage);
3705 if( rc==SQLITE_OK ){
3706 put4byte(&pPage1->aData[28], pBt->nPage);
3712 trans_begun:
3713 if( rc==SQLITE_OK ){
3714 if( pSchemaVersion ){
3715 *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
3717 if( wrflag ){
3718 /* This call makes sure that the pager has the correct number of
3719 ** open savepoints. If the second parameter is greater than 0 and
3720 ** the sub-journal is not already open, then it will be opened here.
3722 rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint);
3726 btreeIntegrity(p);
3727 sqlite3BtreeLeave(p);
3728 return rc;
3731 #ifndef SQLITE_OMIT_AUTOVACUUM
3734 ** Set the pointer-map entries for all children of page pPage. Also, if
3735 ** pPage contains cells that point to overflow pages, set the pointer
3736 ** map entries for the overflow pages as well.
3738 static int setChildPtrmaps(MemPage *pPage){
3739 int i; /* Counter variable */
3740 int nCell; /* Number of cells in page pPage */
3741 int rc; /* Return code */
3742 BtShared *pBt = pPage->pBt;
3743 Pgno pgno = pPage->pgno;
3745 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3746 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3747 if( rc!=SQLITE_OK ) return rc;
3748 nCell = pPage->nCell;
3750 for(i=0; i<nCell; i++){
3751 u8 *pCell = findCell(pPage, i);
3753 ptrmapPutOvflPtr(pPage, pPage, pCell, &rc);
3755 if( !pPage->leaf ){
3756 Pgno childPgno = get4byte(pCell);
3757 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3761 if( !pPage->leaf ){
3762 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
3763 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3766 return rc;
3770 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
3771 ** that it points to iTo. Parameter eType describes the type of pointer to
3772 ** be modified, as follows:
3774 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
3775 ** page of pPage.
3777 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3778 ** page pointed to by one of the cells on pPage.
3780 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3781 ** overflow page in the list.
3783 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
3784 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3785 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
3786 if( eType==PTRMAP_OVERFLOW2 ){
3787 /* The pointer is always the first 4 bytes of the page in this case. */
3788 if( get4byte(pPage->aData)!=iFrom ){
3789 return SQLITE_CORRUPT_PAGE(pPage);
3791 put4byte(pPage->aData, iTo);
3792 }else{
3793 int i;
3794 int nCell;
3795 int rc;
3797 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3798 if( rc ) return rc;
3799 nCell = pPage->nCell;
3801 for(i=0; i<nCell; i++){
3802 u8 *pCell = findCell(pPage, i);
3803 if( eType==PTRMAP_OVERFLOW1 ){
3804 CellInfo info;
3805 pPage->xParseCell(pPage, pCell, &info);
3806 if( info.nLocal<info.nPayload ){
3807 if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
3808 return SQLITE_CORRUPT_PAGE(pPage);
3810 if( iFrom==get4byte(pCell+info.nSize-4) ){
3811 put4byte(pCell+info.nSize-4, iTo);
3812 break;
3815 }else{
3816 if( pCell+4 > pPage->aData+pPage->pBt->usableSize ){
3817 return SQLITE_CORRUPT_PAGE(pPage);
3819 if( get4byte(pCell)==iFrom ){
3820 put4byte(pCell, iTo);
3821 break;
3826 if( i==nCell ){
3827 if( eType!=PTRMAP_BTREE ||
3828 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
3829 return SQLITE_CORRUPT_PAGE(pPage);
3831 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3834 return SQLITE_OK;
3839 ** Move the open database page pDbPage to location iFreePage in the
3840 ** database. The pDbPage reference remains valid.
3842 ** The isCommit flag indicates that there is no need to remember that
3843 ** the journal needs to be sync()ed before database page pDbPage->pgno
3844 ** can be written to. The caller has already promised not to write to that
3845 ** page.
3847 static int relocatePage(
3848 BtShared *pBt, /* Btree */
3849 MemPage *pDbPage, /* Open page to move */
3850 u8 eType, /* Pointer map 'type' entry for pDbPage */
3851 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
3852 Pgno iFreePage, /* The location to move pDbPage to */
3853 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
3855 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
3856 Pgno iDbPage = pDbPage->pgno;
3857 Pager *pPager = pBt->pPager;
3858 int rc;
3860 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3861 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
3862 assert( sqlite3_mutex_held(pBt->mutex) );
3863 assert( pDbPage->pBt==pBt );
3864 if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
3866 /* Move page iDbPage from its current location to page number iFreePage */
3867 TRACE(("AUTOVACUUM: Moving %u to free page %u (ptr page %u type %u)\n",
3868 iDbPage, iFreePage, iPtrPage, eType));
3869 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
3870 if( rc!=SQLITE_OK ){
3871 return rc;
3873 pDbPage->pgno = iFreePage;
3875 /* If pDbPage was a btree-page, then it may have child pages and/or cells
3876 ** that point to overflow pages. The pointer map entries for all these
3877 ** pages need to be changed.
3879 ** If pDbPage is an overflow page, then the first 4 bytes may store a
3880 ** pointer to a subsequent overflow page. If this is the case, then
3881 ** the pointer map needs to be updated for the subsequent overflow page.
3883 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
3884 rc = setChildPtrmaps(pDbPage);
3885 if( rc!=SQLITE_OK ){
3886 return rc;
3888 }else{
3889 Pgno nextOvfl = get4byte(pDbPage->aData);
3890 if( nextOvfl!=0 ){
3891 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
3892 if( rc!=SQLITE_OK ){
3893 return rc;
3898 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3899 ** that it points at iFreePage. Also fix the pointer map entry for
3900 ** iPtrPage.
3902 if( eType!=PTRMAP_ROOTPAGE ){
3903 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
3904 if( rc!=SQLITE_OK ){
3905 return rc;
3907 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
3908 if( rc!=SQLITE_OK ){
3909 releasePage(pPtrPage);
3910 return rc;
3912 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
3913 releasePage(pPtrPage);
3914 if( rc==SQLITE_OK ){
3915 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
3918 return rc;
3921 /* Forward declaration required by incrVacuumStep(). */
3922 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
3925 ** Perform a single step of an incremental-vacuum. If successful, return
3926 ** SQLITE_OK. If there is no work to do (and therefore no point in
3927 ** calling this function again), return SQLITE_DONE. Or, if an error
3928 ** occurs, return some other error code.
3930 ** More specifically, this function attempts to re-organize the database so
3931 ** that the last page of the file currently in use is no longer in use.
3933 ** Parameter nFin is the number of pages that this database would contain
3934 ** were this function called until it returns SQLITE_DONE.
3936 ** If the bCommit parameter is non-zero, this function assumes that the
3937 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
3938 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
3939 ** operation, or false for an incremental vacuum.
3941 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
3942 Pgno nFreeList; /* Number of pages still on the free-list */
3943 int rc;
3945 assert( sqlite3_mutex_held(pBt->mutex) );
3946 assert( iLastPg>nFin );
3948 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
3949 u8 eType;
3950 Pgno iPtrPage;
3952 nFreeList = get4byte(&pBt->pPage1->aData[36]);
3953 if( nFreeList==0 ){
3954 return SQLITE_DONE;
3957 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3958 if( rc!=SQLITE_OK ){
3959 return rc;
3961 if( eType==PTRMAP_ROOTPAGE ){
3962 return SQLITE_CORRUPT_BKPT;
3965 if( eType==PTRMAP_FREEPAGE ){
3966 if( bCommit==0 ){
3967 /* Remove the page from the files free-list. This is not required
3968 ** if bCommit is non-zero. In that case, the free-list will be
3969 ** truncated to zero after this function returns, so it doesn't
3970 ** matter if it still contains some garbage entries.
3972 Pgno iFreePg;
3973 MemPage *pFreePg;
3974 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
3975 if( rc!=SQLITE_OK ){
3976 return rc;
3978 assert( iFreePg==iLastPg );
3979 releasePage(pFreePg);
3981 } else {
3982 Pgno iFreePg; /* Index of free page to move pLastPg to */
3983 MemPage *pLastPg;
3984 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
3985 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
3987 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
3988 if( rc!=SQLITE_OK ){
3989 return rc;
3992 /* If bCommit is zero, this loop runs exactly once and page pLastPg
3993 ** is swapped with the first free page pulled off the free list.
3995 ** On the other hand, if bCommit is greater than zero, then keep
3996 ** looping until a free-page located within the first nFin pages
3997 ** of the file is found.
3999 if( bCommit==0 ){
4000 eMode = BTALLOC_LE;
4001 iNear = nFin;
4003 do {
4004 MemPage *pFreePg;
4005 Pgno dbSize = btreePagecount(pBt);
4006 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
4007 if( rc!=SQLITE_OK ){
4008 releasePage(pLastPg);
4009 return rc;
4011 releasePage(pFreePg);
4012 if( iFreePg>dbSize ){
4013 releasePage(pLastPg);
4014 return SQLITE_CORRUPT_BKPT;
4016 }while( bCommit && iFreePg>nFin );
4017 assert( iFreePg<iLastPg );
4019 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
4020 releasePage(pLastPg);
4021 if( rc!=SQLITE_OK ){
4022 return rc;
4027 if( bCommit==0 ){
4028 do {
4029 iLastPg--;
4030 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
4031 pBt->bDoTruncate = 1;
4032 pBt->nPage = iLastPg;
4034 return SQLITE_OK;
4038 ** The database opened by the first argument is an auto-vacuum database
4039 ** nOrig pages in size containing nFree free pages. Return the expected
4040 ** size of the database in pages following an auto-vacuum operation.
4042 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
4043 int nEntry; /* Number of entries on one ptrmap page */
4044 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
4045 Pgno nFin; /* Return value */
4047 nEntry = pBt->usableSize/5;
4048 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
4049 nFin = nOrig - nFree - nPtrmap;
4050 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
4051 nFin--;
4053 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
4054 nFin--;
4057 return nFin;
4061 ** A write-transaction must be opened before calling this function.
4062 ** It performs a single unit of work towards an incremental vacuum.
4064 ** If the incremental vacuum is finished after this function has run,
4065 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
4066 ** SQLITE_OK is returned. Otherwise an SQLite error code.
4068 int sqlite3BtreeIncrVacuum(Btree *p){
4069 int rc;
4070 BtShared *pBt = p->pBt;
4072 sqlite3BtreeEnter(p);
4073 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
4074 if( !pBt->autoVacuum ){
4075 rc = SQLITE_DONE;
4076 }else{
4077 Pgno nOrig = btreePagecount(pBt);
4078 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
4079 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
4081 if( nOrig<nFin || nFree>=nOrig ){
4082 rc = SQLITE_CORRUPT_BKPT;
4083 }else if( nFree>0 ){
4084 rc = saveAllCursors(pBt, 0, 0);
4085 if( rc==SQLITE_OK ){
4086 invalidateAllOverflowCache(pBt);
4087 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
4089 if( rc==SQLITE_OK ){
4090 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
4091 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
4093 }else{
4094 rc = SQLITE_DONE;
4097 sqlite3BtreeLeave(p);
4098 return rc;
4102 ** This routine is called prior to sqlite3PagerCommit when a transaction
4103 ** is committed for an auto-vacuum database.
4105 static int autoVacuumCommit(Btree *p){
4106 int rc = SQLITE_OK;
4107 Pager *pPager;
4108 BtShared *pBt;
4109 sqlite3 *db;
4110 VVA_ONLY( int nRef );
4112 assert( p!=0 );
4113 pBt = p->pBt;
4114 pPager = pBt->pPager;
4115 VVA_ONLY( nRef = sqlite3PagerRefcount(pPager); )
4117 assert( sqlite3_mutex_held(pBt->mutex) );
4118 invalidateAllOverflowCache(pBt);
4119 assert(pBt->autoVacuum);
4120 if( !pBt->incrVacuum ){
4121 Pgno nFin; /* Number of pages in database after autovacuuming */
4122 Pgno nFree; /* Number of pages on the freelist initially */
4123 Pgno nVac; /* Number of pages to vacuum */
4124 Pgno iFree; /* The next page to be freed */
4125 Pgno nOrig; /* Database size before freeing */
4127 nOrig = btreePagecount(pBt);
4128 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
4129 /* It is not possible to create a database for which the final page
4130 ** is either a pointer-map page or the pending-byte page. If one
4131 ** is encountered, this indicates corruption.
4133 return SQLITE_CORRUPT_BKPT;
4136 nFree = get4byte(&pBt->pPage1->aData[36]);
4137 db = p->db;
4138 if( db->xAutovacPages ){
4139 int iDb;
4140 for(iDb=0; ALWAYS(iDb<db->nDb); iDb++){
4141 if( db->aDb[iDb].pBt==p ) break;
4143 nVac = db->xAutovacPages(
4144 db->pAutovacPagesArg,
4145 db->aDb[iDb].zDbSName,
4146 nOrig,
4147 nFree,
4148 pBt->pageSize
4150 if( nVac>nFree ){
4151 nVac = nFree;
4153 if( nVac==0 ){
4154 return SQLITE_OK;
4156 }else{
4157 nVac = nFree;
4159 nFin = finalDbSize(pBt, nOrig, nVac);
4160 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
4161 if( nFin<nOrig ){
4162 rc = saveAllCursors(pBt, 0, 0);
4164 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
4165 rc = incrVacuumStep(pBt, nFin, iFree, nVac==nFree);
4167 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
4168 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
4169 if( nVac==nFree ){
4170 put4byte(&pBt->pPage1->aData[32], 0);
4171 put4byte(&pBt->pPage1->aData[36], 0);
4173 put4byte(&pBt->pPage1->aData[28], nFin);
4174 pBt->bDoTruncate = 1;
4175 pBt->nPage = nFin;
4177 if( rc!=SQLITE_OK ){
4178 sqlite3PagerRollback(pPager);
4182 assert( nRef>=sqlite3PagerRefcount(pPager) );
4183 return rc;
4186 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
4187 # define setChildPtrmaps(x) SQLITE_OK
4188 #endif
4191 ** This routine does the first phase of a two-phase commit. This routine
4192 ** causes a rollback journal to be created (if it does not already exist)
4193 ** and populated with enough information so that if a power loss occurs
4194 ** the database can be restored to its original state by playing back
4195 ** the journal. Then the contents of the journal are flushed out to
4196 ** the disk. After the journal is safely on oxide, the changes to the
4197 ** database are written into the database file and flushed to oxide.
4198 ** At the end of this call, the rollback journal still exists on the
4199 ** disk and we are still holding all locks, so the transaction has not
4200 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
4201 ** commit process.
4203 ** This call is a no-op if no write-transaction is currently active on pBt.
4205 ** Otherwise, sync the database file for the btree pBt. zSuperJrnl points to
4206 ** the name of a super-journal file that should be written into the
4207 ** individual journal file, or is NULL, indicating no super-journal file
4208 ** (single database transaction).
4210 ** When this is called, the super-journal should already have been
4211 ** created, populated with this journal pointer and synced to disk.
4213 ** Once this is routine has returned, the only thing required to commit
4214 ** the write-transaction for this database file is to delete the journal.
4216 int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zSuperJrnl){
4217 int rc = SQLITE_OK;
4218 if( p->inTrans==TRANS_WRITE ){
4219 BtShared *pBt = p->pBt;
4220 sqlite3BtreeEnter(p);
4221 #ifndef SQLITE_OMIT_AUTOVACUUM
4222 if( pBt->autoVacuum ){
4223 rc = autoVacuumCommit(p);
4224 if( rc!=SQLITE_OK ){
4225 sqlite3BtreeLeave(p);
4226 return rc;
4229 if( pBt->bDoTruncate ){
4230 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
4232 #endif
4233 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0);
4234 sqlite3BtreeLeave(p);
4236 return rc;
4240 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
4241 ** at the conclusion of a transaction.
4243 static void btreeEndTransaction(Btree *p){
4244 BtShared *pBt = p->pBt;
4245 sqlite3 *db = p->db;
4246 assert( sqlite3BtreeHoldsMutex(p) );
4248 #ifndef SQLITE_OMIT_AUTOVACUUM
4249 pBt->bDoTruncate = 0;
4250 #endif
4251 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
4252 /* If there are other active statements that belong to this database
4253 ** handle, downgrade to a read-only transaction. The other statements
4254 ** may still be reading from the database. */
4255 downgradeAllSharedCacheTableLocks(p);
4256 p->inTrans = TRANS_READ;
4257 }else{
4258 /* If the handle had any kind of transaction open, decrement the
4259 ** transaction count of the shared btree. If the transaction count
4260 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
4261 ** call below will unlock the pager. */
4262 if( p->inTrans!=TRANS_NONE ){
4263 clearAllSharedCacheTableLocks(p);
4264 pBt->nTransaction--;
4265 if( 0==pBt->nTransaction ){
4266 pBt->inTransaction = TRANS_NONE;
4270 /* Set the current transaction state to TRANS_NONE and unlock the
4271 ** pager if this call closed the only read or write transaction. */
4272 p->inTrans = TRANS_NONE;
4273 unlockBtreeIfUnused(pBt);
4276 btreeIntegrity(p);
4280 ** Commit the transaction currently in progress.
4282 ** This routine implements the second phase of a 2-phase commit. The
4283 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
4284 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
4285 ** routine did all the work of writing information out to disk and flushing the
4286 ** contents so that they are written onto the disk platter. All this
4287 ** routine has to do is delete or truncate or zero the header in the
4288 ** the rollback journal (which causes the transaction to commit) and
4289 ** drop locks.
4291 ** Normally, if an error occurs while the pager layer is attempting to
4292 ** finalize the underlying journal file, this function returns an error and
4293 ** the upper layer will attempt a rollback. However, if the second argument
4294 ** is non-zero then this b-tree transaction is part of a multi-file
4295 ** transaction. In this case, the transaction has already been committed
4296 ** (by deleting a super-journal file) and the caller will ignore this
4297 ** functions return code. So, even if an error occurs in the pager layer,
4298 ** reset the b-tree objects internal state to indicate that the write
4299 ** transaction has been closed. This is quite safe, as the pager will have
4300 ** transitioned to the error state.
4302 ** This will release the write lock on the database file. If there
4303 ** are no active cursors, it also releases the read lock.
4305 int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
4307 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
4308 sqlite3BtreeEnter(p);
4309 btreeIntegrity(p);
4311 /* If the handle has a write-transaction open, commit the shared-btrees
4312 ** transaction and set the shared state to TRANS_READ.
4314 if( p->inTrans==TRANS_WRITE ){
4315 int rc;
4316 BtShared *pBt = p->pBt;
4317 assert( pBt->inTransaction==TRANS_WRITE );
4318 assert( pBt->nTransaction>0 );
4319 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
4320 if( rc!=SQLITE_OK && bCleanup==0 ){
4321 sqlite3BtreeLeave(p);
4322 return rc;
4324 p->iBDataVersion--; /* Compensate for pPager->iDataVersion++; */
4325 pBt->inTransaction = TRANS_READ;
4326 btreeClearHasContent(pBt);
4329 btreeEndTransaction(p);
4330 sqlite3BtreeLeave(p);
4331 return SQLITE_OK;
4335 ** Do both phases of a commit.
4337 int sqlite3BtreeCommit(Btree *p){
4338 int rc;
4339 sqlite3BtreeEnter(p);
4340 rc = sqlite3BtreeCommitPhaseOne(p, 0);
4341 if( rc==SQLITE_OK ){
4342 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
4344 sqlite3BtreeLeave(p);
4345 return rc;
4349 ** This routine sets the state to CURSOR_FAULT and the error
4350 ** code to errCode for every cursor on any BtShared that pBtree
4351 ** references. Or if the writeOnly flag is set to 1, then only
4352 ** trip write cursors and leave read cursors unchanged.
4354 ** Every cursor is a candidate to be tripped, including cursors
4355 ** that belong to other database connections that happen to be
4356 ** sharing the cache with pBtree.
4358 ** This routine gets called when a rollback occurs. If the writeOnly
4359 ** flag is true, then only write-cursors need be tripped - read-only
4360 ** cursors save their current positions so that they may continue
4361 ** following the rollback. Or, if writeOnly is false, all cursors are
4362 ** tripped. In general, writeOnly is false if the transaction being
4363 ** rolled back modified the database schema. In this case b-tree root
4364 ** pages may be moved or deleted from the database altogether, making
4365 ** it unsafe for read cursors to continue.
4367 ** If the writeOnly flag is true and an error is encountered while
4368 ** saving the current position of a read-only cursor, all cursors,
4369 ** including all read-cursors are tripped.
4371 ** SQLITE_OK is returned if successful, or if an error occurs while
4372 ** saving a cursor position, an SQLite error code.
4374 int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
4375 BtCursor *p;
4376 int rc = SQLITE_OK;
4378 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
4379 if( pBtree ){
4380 sqlite3BtreeEnter(pBtree);
4381 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
4382 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
4383 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
4384 rc = saveCursorPosition(p);
4385 if( rc!=SQLITE_OK ){
4386 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
4387 break;
4390 }else{
4391 sqlite3BtreeClearCursor(p);
4392 p->eState = CURSOR_FAULT;
4393 p->skipNext = errCode;
4395 btreeReleaseAllCursorPages(p);
4397 sqlite3BtreeLeave(pBtree);
4399 return rc;
4403 ** Set the pBt->nPage field correctly, according to the current
4404 ** state of the database. Assume pBt->pPage1 is valid.
4406 static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){
4407 int nPage = get4byte(&pPage1->aData[28]);
4408 testcase( nPage==0 );
4409 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
4410 testcase( pBt->nPage!=(u32)nPage );
4411 pBt->nPage = nPage;
4415 ** Rollback the transaction in progress.
4417 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
4418 ** Only write cursors are tripped if writeOnly is true but all cursors are
4419 ** tripped if writeOnly is false. Any attempt to use
4420 ** a tripped cursor will result in an error.
4422 ** This will release the write lock on the database file. If there
4423 ** are no active cursors, it also releases the read lock.
4425 int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
4426 int rc;
4427 BtShared *pBt = p->pBt;
4428 MemPage *pPage1;
4430 assert( writeOnly==1 || writeOnly==0 );
4431 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
4432 sqlite3BtreeEnter(p);
4433 if( tripCode==SQLITE_OK ){
4434 rc = tripCode = saveAllCursors(pBt, 0, 0);
4435 if( rc ) writeOnly = 0;
4436 }else{
4437 rc = SQLITE_OK;
4439 if( tripCode ){
4440 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
4441 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
4442 if( rc2!=SQLITE_OK ) rc = rc2;
4444 btreeIntegrity(p);
4446 if( p->inTrans==TRANS_WRITE ){
4447 int rc2;
4449 assert( TRANS_WRITE==pBt->inTransaction );
4450 rc2 = sqlite3PagerRollback(pBt->pPager);
4451 if( rc2!=SQLITE_OK ){
4452 rc = rc2;
4455 /* The rollback may have destroyed the pPage1->aData value. So
4456 ** call btreeGetPage() on page 1 again to make
4457 ** sure pPage1->aData is set correctly. */
4458 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
4459 btreeSetNPage(pBt, pPage1);
4460 releasePageOne(pPage1);
4462 assert( countValidCursors(pBt, 1)==0 );
4463 pBt->inTransaction = TRANS_READ;
4464 btreeClearHasContent(pBt);
4467 btreeEndTransaction(p);
4468 sqlite3BtreeLeave(p);
4469 return rc;
4473 ** Start a statement subtransaction. The subtransaction can be rolled
4474 ** back independently of the main transaction. You must start a transaction
4475 ** before starting a subtransaction. The subtransaction is ended automatically
4476 ** if the main transaction commits or rolls back.
4478 ** Statement subtransactions are used around individual SQL statements
4479 ** that are contained within a BEGIN...COMMIT block. If a constraint
4480 ** error occurs within the statement, the effect of that one statement
4481 ** can be rolled back without having to rollback the entire transaction.
4483 ** A statement sub-transaction is implemented as an anonymous savepoint. The
4484 ** value passed as the second parameter is the total number of savepoints,
4485 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
4486 ** are no active savepoints and no other statement-transactions open,
4487 ** iStatement is 1. This anonymous savepoint can be released or rolled back
4488 ** using the sqlite3BtreeSavepoint() function.
4490 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
4491 int rc;
4492 BtShared *pBt = p->pBt;
4493 sqlite3BtreeEnter(p);
4494 assert( p->inTrans==TRANS_WRITE );
4495 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
4496 assert( iStatement>0 );
4497 assert( iStatement>p->db->nSavepoint );
4498 assert( pBt->inTransaction==TRANS_WRITE );
4499 /* At the pager level, a statement transaction is a savepoint with
4500 ** an index greater than all savepoints created explicitly using
4501 ** SQL statements. It is illegal to open, release or rollback any
4502 ** such savepoints while the statement transaction savepoint is active.
4504 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
4505 sqlite3BtreeLeave(p);
4506 return rc;
4510 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
4511 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
4512 ** savepoint identified by parameter iSavepoint, depending on the value
4513 ** of op.
4515 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
4516 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
4517 ** contents of the entire transaction are rolled back. This is different
4518 ** from a normal transaction rollback, as no locks are released and the
4519 ** transaction remains open.
4521 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
4522 int rc = SQLITE_OK;
4523 if( p && p->inTrans==TRANS_WRITE ){
4524 BtShared *pBt = p->pBt;
4525 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
4526 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
4527 sqlite3BtreeEnter(p);
4528 if( op==SAVEPOINT_ROLLBACK ){
4529 rc = saveAllCursors(pBt, 0, 0);
4531 if( rc==SQLITE_OK ){
4532 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
4534 if( rc==SQLITE_OK ){
4535 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
4536 pBt->nPage = 0;
4538 rc = newDatabase(pBt);
4539 btreeSetNPage(pBt, pBt->pPage1);
4541 /* pBt->nPage might be zero if the database was corrupt when
4542 ** the transaction was started. Otherwise, it must be at least 1. */
4543 assert( CORRUPT_DB || pBt->nPage>0 );
4545 sqlite3BtreeLeave(p);
4547 return rc;
4551 ** Create a new cursor for the BTree whose root is on the page
4552 ** iTable. If a read-only cursor is requested, it is assumed that
4553 ** the caller already has at least a read-only transaction open
4554 ** on the database already. If a write-cursor is requested, then
4555 ** the caller is assumed to have an open write transaction.
4557 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
4558 ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
4559 ** can be used for reading or for writing if other conditions for writing
4560 ** are also met. These are the conditions that must be met in order
4561 ** for writing to be allowed:
4563 ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
4565 ** 2: Other database connections that share the same pager cache
4566 ** but which are not in the READ_UNCOMMITTED state may not have
4567 ** cursors open with wrFlag==0 on the same table. Otherwise
4568 ** the changes made by this write cursor would be visible to
4569 ** the read cursors in the other database connection.
4571 ** 3: The database must be writable (not on read-only media)
4573 ** 4: There must be an active transaction.
4575 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
4576 ** is set. If FORDELETE is set, that is a hint to the implementation that
4577 ** this cursor will only be used to seek to and delete entries of an index
4578 ** as part of a larger DELETE statement. The FORDELETE hint is not used by
4579 ** this implementation. But in a hypothetical alternative storage engine
4580 ** in which index entries are automatically deleted when corresponding table
4581 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
4582 ** operations on this cursor can be no-ops and all READ operations can
4583 ** return a null row (2-bytes: 0x01 0x00).
4585 ** No checking is done to make sure that page iTable really is the
4586 ** root page of a b-tree. If it is not, then the cursor acquired
4587 ** will not work correctly.
4589 ** It is assumed that the sqlite3BtreeCursorZero() has been called
4590 ** on pCur to initialize the memory space prior to invoking this routine.
4592 static int btreeCursor(
4593 Btree *p, /* The btree */
4594 Pgno iTable, /* Root page of table to open */
4595 int wrFlag, /* 1 to write. 0 read-only */
4596 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4597 BtCursor *pCur /* Space for new cursor */
4599 BtShared *pBt = p->pBt; /* Shared b-tree handle */
4600 BtCursor *pX; /* Looping over other all cursors */
4602 assert( sqlite3BtreeHoldsMutex(p) );
4603 assert( wrFlag==0
4604 || wrFlag==BTREE_WRCSR
4605 || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
4608 /* The following assert statements verify that if this is a sharable
4609 ** b-tree database, the connection is holding the required table locks,
4610 ** and that no other connection has any open cursor that conflicts with
4611 ** this lock. The iTable<1 term disables the check for corrupt schemas. */
4612 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1))
4613 || iTable<1 );
4614 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
4616 /* Assert that the caller has opened the required transaction. */
4617 assert( p->inTrans>TRANS_NONE );
4618 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
4619 assert( pBt->pPage1 && pBt->pPage1->aData );
4620 assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
4622 if( iTable<=1 ){
4623 if( iTable<1 ){
4624 return SQLITE_CORRUPT_BKPT;
4625 }else if( btreePagecount(pBt)==0 ){
4626 assert( wrFlag==0 );
4627 iTable = 0;
4631 /* Now that no other errors can occur, finish filling in the BtCursor
4632 ** variables and link the cursor into the BtShared list. */
4633 pCur->pgnoRoot = iTable;
4634 pCur->iPage = -1;
4635 pCur->pKeyInfo = pKeyInfo;
4636 pCur->pBtree = p;
4637 pCur->pBt = pBt;
4638 pCur->curFlags = 0;
4639 /* If there are two or more cursors on the same btree, then all such
4640 ** cursors *must* have the BTCF_Multiple flag set. */
4641 for(pX=pBt->pCursor; pX; pX=pX->pNext){
4642 if( pX->pgnoRoot==iTable ){
4643 pX->curFlags |= BTCF_Multiple;
4644 pCur->curFlags = BTCF_Multiple;
4647 pCur->eState = CURSOR_INVALID;
4648 pCur->pNext = pBt->pCursor;
4649 pBt->pCursor = pCur;
4650 if( wrFlag ){
4651 pCur->curFlags |= BTCF_WriteFlag;
4652 pCur->curPagerFlags = 0;
4653 if( pBt->pTmpSpace==0 ) return allocateTempSpace(pBt);
4654 }else{
4655 pCur->curPagerFlags = PAGER_GET_READONLY;
4657 return SQLITE_OK;
4659 static int btreeCursorWithLock(
4660 Btree *p, /* The btree */
4661 Pgno iTable, /* Root page of table to open */
4662 int wrFlag, /* 1 to write. 0 read-only */
4663 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4664 BtCursor *pCur /* Space for new cursor */
4666 int rc;
4667 sqlite3BtreeEnter(p);
4668 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4669 sqlite3BtreeLeave(p);
4670 return rc;
4672 int sqlite3BtreeCursor(
4673 Btree *p, /* The btree */
4674 Pgno iTable, /* Root page of table to open */
4675 int wrFlag, /* 1 to write. 0 read-only */
4676 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
4677 BtCursor *pCur /* Write new cursor here */
4679 if( p->sharable ){
4680 return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur);
4681 }else{
4682 return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4687 ** Return the size of a BtCursor object in bytes.
4689 ** This interfaces is needed so that users of cursors can preallocate
4690 ** sufficient storage to hold a cursor. The BtCursor object is opaque
4691 ** to users so they cannot do the sizeof() themselves - they must call
4692 ** this routine.
4694 int sqlite3BtreeCursorSize(void){
4695 return ROUND8(sizeof(BtCursor));
4699 ** Initialize memory that will be converted into a BtCursor object.
4701 ** The simple approach here would be to memset() the entire object
4702 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
4703 ** do not need to be zeroed and they are large, so we can save a lot
4704 ** of run-time by skipping the initialization of those elements.
4706 void sqlite3BtreeCursorZero(BtCursor *p){
4707 memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
4711 ** Close a cursor. The read lock on the database file is released
4712 ** when the last cursor is closed.
4714 int sqlite3BtreeCloseCursor(BtCursor *pCur){
4715 Btree *pBtree = pCur->pBtree;
4716 if( pBtree ){
4717 BtShared *pBt = pCur->pBt;
4718 sqlite3BtreeEnter(pBtree);
4719 assert( pBt->pCursor!=0 );
4720 if( pBt->pCursor==pCur ){
4721 pBt->pCursor = pCur->pNext;
4722 }else{
4723 BtCursor *pPrev = pBt->pCursor;
4725 if( pPrev->pNext==pCur ){
4726 pPrev->pNext = pCur->pNext;
4727 break;
4729 pPrev = pPrev->pNext;
4730 }while( ALWAYS(pPrev) );
4732 btreeReleaseAllCursorPages(pCur);
4733 unlockBtreeIfUnused(pBt);
4734 sqlite3_free(pCur->aOverflow);
4735 sqlite3_free(pCur->pKey);
4736 if( (pBt->openFlags & BTREE_SINGLE) && pBt->pCursor==0 ){
4737 /* Since the BtShared is not sharable, there is no need to
4738 ** worry about the missing sqlite3BtreeLeave() call here. */
4739 assert( pBtree->sharable==0 );
4740 sqlite3BtreeClose(pBtree);
4741 }else{
4742 sqlite3BtreeLeave(pBtree);
4744 pCur->pBtree = 0;
4746 return SQLITE_OK;
4750 ** Make sure the BtCursor* given in the argument has a valid
4751 ** BtCursor.info structure. If it is not already valid, call
4752 ** btreeParseCell() to fill it in.
4754 ** BtCursor.info is a cache of the information in the current cell.
4755 ** Using this cache reduces the number of calls to btreeParseCell().
4757 #ifndef NDEBUG
4758 static int cellInfoEqual(CellInfo *a, CellInfo *b){
4759 if( a->nKey!=b->nKey ) return 0;
4760 if( a->pPayload!=b->pPayload ) return 0;
4761 if( a->nPayload!=b->nPayload ) return 0;
4762 if( a->nLocal!=b->nLocal ) return 0;
4763 if( a->nSize!=b->nSize ) return 0;
4764 return 1;
4766 static void assertCellInfo(BtCursor *pCur){
4767 CellInfo info;
4768 memset(&info, 0, sizeof(info));
4769 btreeParseCell(pCur->pPage, pCur->ix, &info);
4770 assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
4772 #else
4773 #define assertCellInfo(x)
4774 #endif
4775 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
4776 if( pCur->info.nSize==0 ){
4777 pCur->curFlags |= BTCF_ValidNKey;
4778 btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
4779 }else{
4780 assertCellInfo(pCur);
4784 #ifndef NDEBUG /* The next routine used only within assert() statements */
4786 ** Return true if the given BtCursor is valid. A valid cursor is one
4787 ** that is currently pointing to a row in a (non-empty) table.
4788 ** This is a verification routine is used only within assert() statements.
4790 int sqlite3BtreeCursorIsValid(BtCursor *pCur){
4791 return pCur && pCur->eState==CURSOR_VALID;
4793 #endif /* NDEBUG */
4794 int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
4795 assert( pCur!=0 );
4796 return pCur->eState==CURSOR_VALID;
4800 ** Return the value of the integer key or "rowid" for a table btree.
4801 ** This routine is only valid for a cursor that is pointing into a
4802 ** ordinary table btree. If the cursor points to an index btree or
4803 ** is invalid, the result of this routine is undefined.
4805 i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
4806 assert( cursorHoldsMutex(pCur) );
4807 assert( pCur->eState==CURSOR_VALID );
4808 assert( pCur->curIntKey );
4809 getCellInfo(pCur);
4810 return pCur->info.nKey;
4814 ** Pin or unpin a cursor.
4816 void sqlite3BtreeCursorPin(BtCursor *pCur){
4817 assert( (pCur->curFlags & BTCF_Pinned)==0 );
4818 pCur->curFlags |= BTCF_Pinned;
4820 void sqlite3BtreeCursorUnpin(BtCursor *pCur){
4821 assert( (pCur->curFlags & BTCF_Pinned)!=0 );
4822 pCur->curFlags &= ~BTCF_Pinned;
4825 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4827 ** Return the offset into the database file for the start of the
4828 ** payload to which the cursor is pointing.
4830 i64 sqlite3BtreeOffset(BtCursor *pCur){
4831 assert( cursorHoldsMutex(pCur) );
4832 assert( pCur->eState==CURSOR_VALID );
4833 getCellInfo(pCur);
4834 return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
4835 (i64)(pCur->info.pPayload - pCur->pPage->aData);
4837 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
4840 ** Return the number of bytes of payload for the entry that pCur is
4841 ** currently pointing to. For table btrees, this will be the amount
4842 ** of data. For index btrees, this will be the size of the key.
4844 ** The caller must guarantee that the cursor is pointing to a non-NULL
4845 ** valid entry. In other words, the calling procedure must guarantee
4846 ** that the cursor has Cursor.eState==CURSOR_VALID.
4848 u32 sqlite3BtreePayloadSize(BtCursor *pCur){
4849 assert( cursorHoldsMutex(pCur) );
4850 assert( pCur->eState==CURSOR_VALID );
4851 getCellInfo(pCur);
4852 return pCur->info.nPayload;
4856 ** Return an upper bound on the size of any record for the table
4857 ** that the cursor is pointing into.
4859 ** This is an optimization. Everything will still work if this
4860 ** routine always returns 2147483647 (which is the largest record
4861 ** that SQLite can handle) or more. But returning a smaller value might
4862 ** prevent large memory allocations when trying to interpret a
4863 ** corrupt datrabase.
4865 ** The current implementation merely returns the size of the underlying
4866 ** database file.
4868 sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){
4869 assert( cursorHoldsMutex(pCur) );
4870 assert( pCur->eState==CURSOR_VALID );
4871 return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
4875 ** Given the page number of an overflow page in the database (parameter
4876 ** ovfl), this function finds the page number of the next page in the
4877 ** linked list of overflow pages. If possible, it uses the auto-vacuum
4878 ** pointer-map data instead of reading the content of page ovfl to do so.
4880 ** If an error occurs an SQLite error code is returned. Otherwise:
4882 ** The page number of the next overflow page in the linked list is
4883 ** written to *pPgnoNext. If page ovfl is the last page in its linked
4884 ** list, *pPgnoNext is set to zero.
4886 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
4887 ** to page number pOvfl was obtained, then *ppPage is set to point to that
4888 ** reference. It is the responsibility of the caller to call releasePage()
4889 ** on *ppPage to free the reference. In no reference was obtained (because
4890 ** the pointer-map was used to obtain the value for *pPgnoNext), then
4891 ** *ppPage is set to zero.
4893 static int getOverflowPage(
4894 BtShared *pBt, /* The database file */
4895 Pgno ovfl, /* Current overflow page number */
4896 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
4897 Pgno *pPgnoNext /* OUT: Next overflow page number */
4899 Pgno next = 0;
4900 MemPage *pPage = 0;
4901 int rc = SQLITE_OK;
4903 assert( sqlite3_mutex_held(pBt->mutex) );
4904 assert(pPgnoNext);
4906 #ifndef SQLITE_OMIT_AUTOVACUUM
4907 /* Try to find the next page in the overflow list using the
4908 ** autovacuum pointer-map pages. Guess that the next page in
4909 ** the overflow list is page number (ovfl+1). If that guess turns
4910 ** out to be wrong, fall back to loading the data of page
4911 ** number ovfl to determine the next page number.
4913 if( pBt->autoVacuum ){
4914 Pgno pgno;
4915 Pgno iGuess = ovfl+1;
4916 u8 eType;
4918 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
4919 iGuess++;
4922 if( iGuess<=btreePagecount(pBt) ){
4923 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
4924 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
4925 next = iGuess;
4926 rc = SQLITE_DONE;
4930 #endif
4932 assert( next==0 || rc==SQLITE_DONE );
4933 if( rc==SQLITE_OK ){
4934 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
4935 assert( rc==SQLITE_OK || pPage==0 );
4936 if( rc==SQLITE_OK ){
4937 next = get4byte(pPage->aData);
4941 *pPgnoNext = next;
4942 if( ppPage ){
4943 *ppPage = pPage;
4944 }else{
4945 releasePage(pPage);
4947 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
4951 ** Copy data from a buffer to a page, or from a page to a buffer.
4953 ** pPayload is a pointer to data stored on database page pDbPage.
4954 ** If argument eOp is false, then nByte bytes of data are copied
4955 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4956 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4957 ** of data are copied from the buffer pBuf to pPayload.
4959 ** SQLITE_OK is returned on success, otherwise an error code.
4961 static int copyPayload(
4962 void *pPayload, /* Pointer to page data */
4963 void *pBuf, /* Pointer to buffer */
4964 int nByte, /* Number of bytes to copy */
4965 int eOp, /* 0 -> copy from page, 1 -> copy to page */
4966 DbPage *pDbPage /* Page containing pPayload */
4968 if( eOp ){
4969 /* Copy data from buffer to page (a write operation) */
4970 int rc = sqlite3PagerWrite(pDbPage);
4971 if( rc!=SQLITE_OK ){
4972 return rc;
4974 memcpy(pPayload, pBuf, nByte);
4975 }else{
4976 /* Copy data from page to buffer (a read operation) */
4977 memcpy(pBuf, pPayload, nByte);
4979 return SQLITE_OK;
4983 ** This function is used to read or overwrite payload information
4984 ** for the entry that the pCur cursor is pointing to. The eOp
4985 ** argument is interpreted as follows:
4987 ** 0: The operation is a read. Populate the overflow cache.
4988 ** 1: The operation is a write. Populate the overflow cache.
4990 ** A total of "amt" bytes are read or written beginning at "offset".
4991 ** Data is read to or from the buffer pBuf.
4993 ** The content being read or written might appear on the main page
4994 ** or be scattered out on multiple overflow pages.
4996 ** If the current cursor entry uses one or more overflow pages
4997 ** this function may allocate space for and lazily populate
4998 ** the overflow page-list cache array (BtCursor.aOverflow).
4999 ** Subsequent calls use this cache to make seeking to the supplied offset
5000 ** more efficient.
5002 ** Once an overflow page-list cache has been allocated, it must be
5003 ** invalidated if some other cursor writes to the same table, or if
5004 ** the cursor is moved to a different row. Additionally, in auto-vacuum
5005 ** mode, the following events may invalidate an overflow page-list cache.
5007 ** * An incremental vacuum,
5008 ** * A commit in auto_vacuum="full" mode,
5009 ** * Creating a table (may require moving an overflow page).
5011 static int accessPayload(
5012 BtCursor *pCur, /* Cursor pointing to entry to read from */
5013 u32 offset, /* Begin reading this far into payload */
5014 u32 amt, /* Read this many bytes */
5015 unsigned char *pBuf, /* Write the bytes into this buffer */
5016 int eOp /* zero to read. non-zero to write. */
5018 unsigned char *aPayload;
5019 int rc = SQLITE_OK;
5020 int iIdx = 0;
5021 MemPage *pPage = pCur->pPage; /* Btree page of current entry */
5022 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
5023 #ifdef SQLITE_DIRECT_OVERFLOW_READ
5024 unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
5025 #endif
5027 assert( pPage );
5028 assert( eOp==0 || eOp==1 );
5029 assert( pCur->eState==CURSOR_VALID );
5030 if( pCur->ix>=pPage->nCell ){
5031 return SQLITE_CORRUPT_PAGE(pPage);
5033 assert( cursorHoldsMutex(pCur) );
5035 getCellInfo(pCur);
5036 aPayload = pCur->info.pPayload;
5037 assert( offset+amt <= pCur->info.nPayload );
5039 assert( aPayload > pPage->aData );
5040 if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
5041 /* Trying to read or write past the end of the data is an error. The
5042 ** conditional above is really:
5043 ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
5044 ** but is recast into its current form to avoid integer overflow problems
5046 return SQLITE_CORRUPT_PAGE(pPage);
5049 /* Check if data must be read/written to/from the btree page itself. */
5050 if( offset<pCur->info.nLocal ){
5051 int a = amt;
5052 if( a+offset>pCur->info.nLocal ){
5053 a = pCur->info.nLocal - offset;
5055 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
5056 offset = 0;
5057 pBuf += a;
5058 amt -= a;
5059 }else{
5060 offset -= pCur->info.nLocal;
5064 if( rc==SQLITE_OK && amt>0 ){
5065 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
5066 Pgno nextPage;
5068 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
5070 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
5072 ** The aOverflow[] array is sized at one entry for each overflow page
5073 ** in the overflow chain. The page number of the first overflow page is
5074 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
5075 ** means "not yet known" (the cache is lazily populated).
5077 if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
5078 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
5079 if( pCur->aOverflow==0
5080 || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
5082 Pgno *aNew = (Pgno*)sqlite3Realloc(
5083 pCur->aOverflow, nOvfl*2*sizeof(Pgno)
5085 if( aNew==0 ){
5086 return SQLITE_NOMEM_BKPT;
5087 }else{
5088 pCur->aOverflow = aNew;
5091 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
5092 pCur->curFlags |= BTCF_ValidOvfl;
5093 }else{
5094 /* If the overflow page-list cache has been allocated and the
5095 ** entry for the first required overflow page is valid, skip
5096 ** directly to it.
5098 if( pCur->aOverflow[offset/ovflSize] ){
5099 iIdx = (offset/ovflSize);
5100 nextPage = pCur->aOverflow[iIdx];
5101 offset = (offset%ovflSize);
5105 assert( rc==SQLITE_OK && amt>0 );
5106 while( nextPage ){
5107 /* If required, populate the overflow page-list cache. */
5108 if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPT;
5109 assert( pCur->aOverflow[iIdx]==0
5110 || pCur->aOverflow[iIdx]==nextPage
5111 || CORRUPT_DB );
5112 pCur->aOverflow[iIdx] = nextPage;
5114 if( offset>=ovflSize ){
5115 /* The only reason to read this page is to obtain the page
5116 ** number for the next page in the overflow chain. The page
5117 ** data is not required. So first try to lookup the overflow
5118 ** page-list cache, if any, then fall back to the getOverflowPage()
5119 ** function.
5121 assert( pCur->curFlags & BTCF_ValidOvfl );
5122 assert( pCur->pBtree->db==pBt->db );
5123 if( pCur->aOverflow[iIdx+1] ){
5124 nextPage = pCur->aOverflow[iIdx+1];
5125 }else{
5126 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
5128 offset -= ovflSize;
5129 }else{
5130 /* Need to read this page properly. It contains some of the
5131 ** range of data that is being read (eOp==0) or written (eOp!=0).
5133 int a = amt;
5134 if( a + offset > ovflSize ){
5135 a = ovflSize - offset;
5138 #ifdef SQLITE_DIRECT_OVERFLOW_READ
5139 /* If all the following are true:
5141 ** 1) this is a read operation, and
5142 ** 2) data is required from the start of this overflow page, and
5143 ** 3) there are no dirty pages in the page-cache
5144 ** 4) the database is file-backed, and
5145 ** 5) the page is not in the WAL file
5146 ** 6) at least 4 bytes have already been read into the output buffer
5148 ** then data can be read directly from the database file into the
5149 ** output buffer, bypassing the page-cache altogether. This speeds
5150 ** up loading large records that span many overflow pages.
5152 if( eOp==0 /* (1) */
5153 && offset==0 /* (2) */
5154 && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */
5155 && &pBuf[-4]>=pBufStart /* (6) */
5157 sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
5158 u8 aSave[4];
5159 u8 *aWrite = &pBuf[-4];
5160 assert( aWrite>=pBufStart ); /* due to (6) */
5161 memcpy(aSave, aWrite, 4);
5162 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
5163 if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT;
5164 nextPage = get4byte(aWrite);
5165 memcpy(aWrite, aSave, 4);
5166 }else
5167 #endif
5170 DbPage *pDbPage;
5171 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
5172 (eOp==0 ? PAGER_GET_READONLY : 0)
5174 if( rc==SQLITE_OK ){
5175 aPayload = sqlite3PagerGetData(pDbPage);
5176 nextPage = get4byte(aPayload);
5177 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
5178 sqlite3PagerUnref(pDbPage);
5179 offset = 0;
5182 amt -= a;
5183 if( amt==0 ) return rc;
5184 pBuf += a;
5186 if( rc ) break;
5187 iIdx++;
5191 if( rc==SQLITE_OK && amt>0 ){
5192 /* Overflow chain ends prematurely */
5193 return SQLITE_CORRUPT_PAGE(pPage);
5195 return rc;
5199 ** Read part of the payload for the row at which that cursor pCur is currently
5200 ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
5201 ** begins at "offset".
5203 ** pCur can be pointing to either a table or an index b-tree.
5204 ** If pointing to a table btree, then the content section is read. If
5205 ** pCur is pointing to an index b-tree then the key section is read.
5207 ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
5208 ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
5209 ** cursor might be invalid or might need to be restored before being read.
5211 ** Return SQLITE_OK on success or an error code if anything goes
5212 ** wrong. An error is returned if "offset+amt" is larger than
5213 ** the available payload.
5215 int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5216 assert( cursorHoldsMutex(pCur) );
5217 assert( pCur->eState==CURSOR_VALID );
5218 assert( pCur->iPage>=0 && pCur->pPage );
5219 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
5223 ** This variant of sqlite3BtreePayload() works even if the cursor has not
5224 ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
5225 ** interface.
5227 #ifndef SQLITE_OMIT_INCRBLOB
5228 static SQLITE_NOINLINE int accessPayloadChecked(
5229 BtCursor *pCur,
5230 u32 offset,
5231 u32 amt,
5232 void *pBuf
5234 int rc;
5235 if ( pCur->eState==CURSOR_INVALID ){
5236 return SQLITE_ABORT;
5238 assert( cursorOwnsBtShared(pCur) );
5239 rc = btreeRestoreCursorPosition(pCur);
5240 return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
5242 int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5243 if( pCur->eState==CURSOR_VALID ){
5244 assert( cursorOwnsBtShared(pCur) );
5245 return accessPayload(pCur, offset, amt, pBuf, 0);
5246 }else{
5247 return accessPayloadChecked(pCur, offset, amt, pBuf);
5250 #endif /* SQLITE_OMIT_INCRBLOB */
5253 ** Return a pointer to payload information from the entry that the
5254 ** pCur cursor is pointing to. The pointer is to the beginning of
5255 ** the key if index btrees (pPage->intKey==0) and is the data for
5256 ** table btrees (pPage->intKey==1). The number of bytes of available
5257 ** key/data is written into *pAmt. If *pAmt==0, then the value
5258 ** returned will not be a valid pointer.
5260 ** This routine is an optimization. It is common for the entire key
5261 ** and data to fit on the local page and for there to be no overflow
5262 ** pages. When that is so, this routine can be used to access the
5263 ** key and data without making a copy. If the key and/or data spills
5264 ** onto overflow pages, then accessPayload() must be used to reassemble
5265 ** the key/data and copy it into a preallocated buffer.
5267 ** The pointer returned by this routine looks directly into the cached
5268 ** page of the database. The data might change or move the next time
5269 ** any btree routine is called.
5271 static const void *fetchPayload(
5272 BtCursor *pCur, /* Cursor pointing to entry to read from */
5273 u32 *pAmt /* Write the number of available bytes here */
5275 int amt;
5276 assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
5277 assert( pCur->eState==CURSOR_VALID );
5278 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5279 assert( cursorOwnsBtShared(pCur) );
5280 assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
5281 assert( pCur->info.nSize>0 );
5282 assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
5283 assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
5284 amt = pCur->info.nLocal;
5285 if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
5286 /* There is too little space on the page for the expected amount
5287 ** of local content. Database must be corrupt. */
5288 assert( CORRUPT_DB );
5289 amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
5291 *pAmt = (u32)amt;
5292 return (void*)pCur->info.pPayload;
5297 ** For the entry that cursor pCur is point to, return as
5298 ** many bytes of the key or data as are available on the local
5299 ** b-tree page. Write the number of available bytes into *pAmt.
5301 ** The pointer returned is ephemeral. The key/data may move
5302 ** or be destroyed on the next call to any Btree routine,
5303 ** including calls from other threads against the same cache.
5304 ** Hence, a mutex on the BtShared should be held prior to calling
5305 ** this routine.
5307 ** These routines is used to get quick access to key and data
5308 ** in the common case where no overflow pages are used.
5310 const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
5311 return fetchPayload(pCur, pAmt);
5316 ** Move the cursor down to a new child page. The newPgno argument is the
5317 ** page number of the child page to move to.
5319 ** This function returns SQLITE_CORRUPT if the page-header flags field of
5320 ** the new child page does not match the flags field of the parent (i.e.
5321 ** if an intkey page appears to be the parent of a non-intkey page, or
5322 ** vice-versa).
5324 static int moveToChild(BtCursor *pCur, u32 newPgno){
5325 assert( cursorOwnsBtShared(pCur) );
5326 assert( pCur->eState==CURSOR_VALID );
5327 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
5328 assert( pCur->iPage>=0 );
5329 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
5330 return SQLITE_CORRUPT_BKPT;
5332 pCur->info.nSize = 0;
5333 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5334 pCur->aiIdx[pCur->iPage] = pCur->ix;
5335 pCur->apPage[pCur->iPage] = pCur->pPage;
5336 pCur->ix = 0;
5337 pCur->iPage++;
5338 return getAndInitPage(pCur->pBt, newPgno, &pCur->pPage, pCur,
5339 pCur->curPagerFlags);
5342 #ifdef SQLITE_DEBUG
5344 ** Page pParent is an internal (non-leaf) tree page. This function
5345 ** asserts that page number iChild is the left-child if the iIdx'th
5346 ** cell in page pParent. Or, if iIdx is equal to the total number of
5347 ** cells in pParent, that page number iChild is the right-child of
5348 ** the page.
5350 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
5351 if( CORRUPT_DB ) return; /* The conditions tested below might not be true
5352 ** in a corrupt database */
5353 assert( iIdx<=pParent->nCell );
5354 if( iIdx==pParent->nCell ){
5355 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
5356 }else{
5357 assert( get4byte(findCell(pParent, iIdx))==iChild );
5360 #else
5361 # define assertParentIndex(x,y,z)
5362 #endif
5365 ** Move the cursor up to the parent page.
5367 ** pCur->idx is set to the cell index that contains the pointer
5368 ** to the page we are coming from. If we are coming from the
5369 ** right-most child page then pCur->idx is set to one more than
5370 ** the largest cell index.
5372 static void moveToParent(BtCursor *pCur){
5373 MemPage *pLeaf;
5374 assert( cursorOwnsBtShared(pCur) );
5375 assert( pCur->eState==CURSOR_VALID );
5376 assert( pCur->iPage>0 );
5377 assert( pCur->pPage );
5378 assertParentIndex(
5379 pCur->apPage[pCur->iPage-1],
5380 pCur->aiIdx[pCur->iPage-1],
5381 pCur->pPage->pgno
5383 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
5384 pCur->info.nSize = 0;
5385 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5386 pCur->ix = pCur->aiIdx[pCur->iPage-1];
5387 pLeaf = pCur->pPage;
5388 pCur->pPage = pCur->apPage[--pCur->iPage];
5389 releasePageNotNull(pLeaf);
5393 ** Move the cursor to point to the root page of its b-tree structure.
5395 ** If the table has a virtual root page, then the cursor is moved to point
5396 ** to the virtual root page instead of the actual root page. A table has a
5397 ** virtual root page when the actual root page contains no cells and a
5398 ** single child page. This can only happen with the table rooted at page 1.
5400 ** If the b-tree structure is empty, the cursor state is set to
5401 ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
5402 ** the cursor is set to point to the first cell located on the root
5403 ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
5405 ** If this function returns successfully, it may be assumed that the
5406 ** page-header flags indicate that the [virtual] root-page is the expected
5407 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
5408 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
5409 ** indicating a table b-tree, or if the caller did specify a KeyInfo
5410 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
5411 ** b-tree).
5413 static int moveToRoot(BtCursor *pCur){
5414 MemPage *pRoot;
5415 int rc = SQLITE_OK;
5417 assert( cursorOwnsBtShared(pCur) );
5418 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
5419 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
5420 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
5421 assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
5422 assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
5424 if( pCur->iPage>=0 ){
5425 if( pCur->iPage ){
5426 releasePageNotNull(pCur->pPage);
5427 while( --pCur->iPage ){
5428 releasePageNotNull(pCur->apPage[pCur->iPage]);
5430 pRoot = pCur->pPage = pCur->apPage[0];
5431 goto skip_init;
5433 }else if( pCur->pgnoRoot==0 ){
5434 pCur->eState = CURSOR_INVALID;
5435 return SQLITE_EMPTY;
5436 }else{
5437 assert( pCur->iPage==(-1) );
5438 if( pCur->eState>=CURSOR_REQUIRESEEK ){
5439 if( pCur->eState==CURSOR_FAULT ){
5440 assert( pCur->skipNext!=SQLITE_OK );
5441 return pCur->skipNext;
5443 sqlite3BtreeClearCursor(pCur);
5445 rc = getAndInitPage(pCur->pBt, pCur->pgnoRoot, &pCur->pPage,
5446 0, pCur->curPagerFlags);
5447 if( rc!=SQLITE_OK ){
5448 pCur->eState = CURSOR_INVALID;
5449 return rc;
5451 pCur->iPage = 0;
5452 pCur->curIntKey = pCur->pPage->intKey;
5454 pRoot = pCur->pPage;
5455 assert( pRoot->pgno==pCur->pgnoRoot || CORRUPT_DB );
5457 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
5458 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
5459 ** NULL, the caller expects a table b-tree. If this is not the case,
5460 ** return an SQLITE_CORRUPT error.
5462 ** Earlier versions of SQLite assumed that this test could not fail
5463 ** if the root page was already loaded when this function was called (i.e.
5464 ** if pCur->iPage>=0). But this is not so if the database is corrupted
5465 ** in such a way that page pRoot is linked into a second b-tree table
5466 ** (or the freelist). */
5467 assert( pRoot->intKey==1 || pRoot->intKey==0 );
5468 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
5469 return SQLITE_CORRUPT_PAGE(pCur->pPage);
5472 skip_init:
5473 pCur->ix = 0;
5474 pCur->info.nSize = 0;
5475 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
5477 if( pRoot->nCell>0 ){
5478 pCur->eState = CURSOR_VALID;
5479 }else if( !pRoot->leaf ){
5480 Pgno subpage;
5481 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
5482 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
5483 pCur->eState = CURSOR_VALID;
5484 rc = moveToChild(pCur, subpage);
5485 }else{
5486 pCur->eState = CURSOR_INVALID;
5487 rc = SQLITE_EMPTY;
5489 return rc;
5493 ** Move the cursor down to the left-most leaf entry beneath the
5494 ** entry to which it is currently pointing.
5496 ** The left-most leaf is the one with the smallest key - the first
5497 ** in ascending order.
5499 static int moveToLeftmost(BtCursor *pCur){
5500 Pgno pgno;
5501 int rc = SQLITE_OK;
5502 MemPage *pPage;
5504 assert( cursorOwnsBtShared(pCur) );
5505 assert( pCur->eState==CURSOR_VALID );
5506 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
5507 assert( pCur->ix<pPage->nCell );
5508 pgno = get4byte(findCell(pPage, pCur->ix));
5509 rc = moveToChild(pCur, pgno);
5511 return rc;
5515 ** Move the cursor down to the right-most leaf entry beneath the
5516 ** page to which it is currently pointing. Notice the difference
5517 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
5518 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
5519 ** finds the right-most entry beneath the *page*.
5521 ** The right-most entry is the one with the largest key - the last
5522 ** key in ascending order.
5524 static int moveToRightmost(BtCursor *pCur){
5525 Pgno pgno;
5526 int rc = SQLITE_OK;
5527 MemPage *pPage = 0;
5529 assert( cursorOwnsBtShared(pCur) );
5530 assert( pCur->eState==CURSOR_VALID );
5531 while( !(pPage = pCur->pPage)->leaf ){
5532 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5533 pCur->ix = pPage->nCell;
5534 rc = moveToChild(pCur, pgno);
5535 if( rc ) return rc;
5537 pCur->ix = pPage->nCell-1;
5538 assert( pCur->info.nSize==0 );
5539 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
5540 return SQLITE_OK;
5543 /* Move the cursor to the first entry in the table. Return SQLITE_OK
5544 ** on success. Set *pRes to 0 if the cursor actually points to something
5545 ** or set *pRes to 1 if the table is empty.
5547 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
5548 int rc;
5550 assert( cursorOwnsBtShared(pCur) );
5551 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5552 rc = moveToRoot(pCur);
5553 if( rc==SQLITE_OK ){
5554 assert( pCur->pPage->nCell>0 );
5555 *pRes = 0;
5556 rc = moveToLeftmost(pCur);
5557 }else if( rc==SQLITE_EMPTY ){
5558 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5559 *pRes = 1;
5560 rc = SQLITE_OK;
5562 return rc;
5565 /* Move the cursor to the last entry in the table. Return SQLITE_OK
5566 ** on success. Set *pRes to 0 if the cursor actually points to something
5567 ** or set *pRes to 1 if the table is empty.
5569 static SQLITE_NOINLINE int btreeLast(BtCursor *pCur, int *pRes){
5570 int rc = moveToRoot(pCur);
5571 if( rc==SQLITE_OK ){
5572 assert( pCur->eState==CURSOR_VALID );
5573 *pRes = 0;
5574 rc = moveToRightmost(pCur);
5575 if( rc==SQLITE_OK ){
5576 pCur->curFlags |= BTCF_AtLast;
5577 }else{
5578 pCur->curFlags &= ~BTCF_AtLast;
5580 }else if( rc==SQLITE_EMPTY ){
5581 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5582 *pRes = 1;
5583 rc = SQLITE_OK;
5585 return rc;
5587 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
5588 assert( cursorOwnsBtShared(pCur) );
5589 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5591 /* If the cursor already points to the last entry, this is a no-op. */
5592 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
5593 #ifdef SQLITE_DEBUG
5594 /* This block serves to assert() that the cursor really does point
5595 ** to the last entry in the b-tree. */
5596 int ii;
5597 for(ii=0; ii<pCur->iPage; ii++){
5598 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
5600 assert( pCur->ix==pCur->pPage->nCell-1 || CORRUPT_DB );
5601 testcase( pCur->ix!=pCur->pPage->nCell-1 );
5602 /* ^-- dbsqlfuzz b92b72e4de80b5140c30ab71372ca719b8feb618 */
5603 assert( pCur->pPage->leaf );
5604 #endif
5605 *pRes = 0;
5606 return SQLITE_OK;
5608 return btreeLast(pCur, pRes);
5611 /* Move the cursor so that it points to an entry in a table (a.k.a INTKEY)
5612 ** table near the key intKey. Return a success code.
5614 ** If an exact match is not found, then the cursor is always
5615 ** left pointing at a leaf page which would hold the entry if it
5616 ** were present. The cursor might point to an entry that comes
5617 ** before or after the key.
5619 ** An integer is written into *pRes which is the result of
5620 ** comparing the key with the entry to which the cursor is
5621 ** pointing. The meaning of the integer written into
5622 ** *pRes is as follows:
5624 ** *pRes<0 The cursor is left pointing at an entry that
5625 ** is smaller than intKey or if the table is empty
5626 ** and the cursor is therefore left point to nothing.
5628 ** *pRes==0 The cursor is left pointing at an entry that
5629 ** exactly matches intKey.
5631 ** *pRes>0 The cursor is left pointing at an entry that
5632 ** is larger than intKey.
5634 int sqlite3BtreeTableMoveto(
5635 BtCursor *pCur, /* The cursor to be moved */
5636 i64 intKey, /* The table key */
5637 int biasRight, /* If true, bias the search to the high end */
5638 int *pRes /* Write search results here */
5640 int rc;
5642 assert( cursorOwnsBtShared(pCur) );
5643 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5644 assert( pRes );
5645 assert( pCur->pKeyInfo==0 );
5646 assert( pCur->eState!=CURSOR_VALID || pCur->curIntKey!=0 );
5648 /* If the cursor is already positioned at the point we are trying
5649 ** to move to, then just return without doing any work */
5650 if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0 ){
5651 if( pCur->info.nKey==intKey ){
5652 *pRes = 0;
5653 return SQLITE_OK;
5655 if( pCur->info.nKey<intKey ){
5656 if( (pCur->curFlags & BTCF_AtLast)!=0 ){
5657 *pRes = -1;
5658 return SQLITE_OK;
5660 /* If the requested key is one more than the previous key, then
5661 ** try to get there using sqlite3BtreeNext() rather than a full
5662 ** binary search. This is an optimization only. The correct answer
5663 ** is still obtained without this case, only a little more slowely */
5664 if( pCur->info.nKey+1==intKey ){
5665 *pRes = 0;
5666 rc = sqlite3BtreeNext(pCur, 0);
5667 if( rc==SQLITE_OK ){
5668 getCellInfo(pCur);
5669 if( pCur->info.nKey==intKey ){
5670 return SQLITE_OK;
5672 }else if( rc!=SQLITE_DONE ){
5673 return rc;
5679 #ifdef SQLITE_DEBUG
5680 pCur->pBtree->nSeek++; /* Performance measurement during testing */
5681 #endif
5683 rc = moveToRoot(pCur);
5684 if( rc ){
5685 if( rc==SQLITE_EMPTY ){
5686 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5687 *pRes = -1;
5688 return SQLITE_OK;
5690 return rc;
5692 assert( pCur->pPage );
5693 assert( pCur->pPage->isInit );
5694 assert( pCur->eState==CURSOR_VALID );
5695 assert( pCur->pPage->nCell > 0 );
5696 assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
5697 assert( pCur->curIntKey );
5699 for(;;){
5700 int lwr, upr, idx, c;
5701 Pgno chldPg;
5702 MemPage *pPage = pCur->pPage;
5703 u8 *pCell; /* Pointer to current cell in pPage */
5705 /* pPage->nCell must be greater than zero. If this is the root-page
5706 ** the cursor would have been INVALID above and this for(;;) loop
5707 ** not run. If this is not the root-page, then the moveToChild() routine
5708 ** would have already detected db corruption. Similarly, pPage must
5709 ** be the right kind (index or table) of b-tree page. Otherwise
5710 ** a moveToChild() or moveToRoot() call would have detected corruption. */
5711 assert( pPage->nCell>0 );
5712 assert( pPage->intKey );
5713 lwr = 0;
5714 upr = pPage->nCell-1;
5715 assert( biasRight==0 || biasRight==1 );
5716 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
5717 for(;;){
5718 i64 nCellKey;
5719 pCell = findCellPastPtr(pPage, idx);
5720 if( pPage->intKeyLeaf ){
5721 while( 0x80 <= *(pCell++) ){
5722 if( pCell>=pPage->aDataEnd ){
5723 return SQLITE_CORRUPT_PAGE(pPage);
5727 getVarint(pCell, (u64*)&nCellKey);
5728 if( nCellKey<intKey ){
5729 lwr = idx+1;
5730 if( lwr>upr ){ c = -1; break; }
5731 }else if( nCellKey>intKey ){
5732 upr = idx-1;
5733 if( lwr>upr ){ c = +1; break; }
5734 }else{
5735 assert( nCellKey==intKey );
5736 pCur->ix = (u16)idx;
5737 if( !pPage->leaf ){
5738 lwr = idx;
5739 goto moveto_table_next_layer;
5740 }else{
5741 pCur->curFlags |= BTCF_ValidNKey;
5742 pCur->info.nKey = nCellKey;
5743 pCur->info.nSize = 0;
5744 *pRes = 0;
5745 return SQLITE_OK;
5748 assert( lwr+upr>=0 );
5749 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
5751 assert( lwr==upr+1 || !pPage->leaf );
5752 assert( pPage->isInit );
5753 if( pPage->leaf ){
5754 assert( pCur->ix<pCur->pPage->nCell );
5755 pCur->ix = (u16)idx;
5756 *pRes = c;
5757 rc = SQLITE_OK;
5758 goto moveto_table_finish;
5760 moveto_table_next_layer:
5761 if( lwr>=pPage->nCell ){
5762 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5763 }else{
5764 chldPg = get4byte(findCell(pPage, lwr));
5766 pCur->ix = (u16)lwr;
5767 rc = moveToChild(pCur, chldPg);
5768 if( rc ) break;
5770 moveto_table_finish:
5771 pCur->info.nSize = 0;
5772 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5773 return rc;
5777 ** Compare the "idx"-th cell on the page the cursor pCur is currently
5778 ** pointing to to pIdxKey using xRecordCompare. Return negative or
5779 ** zero if the cell is less than or equal pIdxKey. Return positive
5780 ** if unknown.
5782 ** Return value negative: Cell at pCur[idx] less than pIdxKey
5784 ** Return value is zero: Cell at pCur[idx] equals pIdxKey
5786 ** Return value positive: Nothing is known about the relationship
5787 ** of the cell at pCur[idx] and pIdxKey.
5789 ** This routine is part of an optimization. It is always safe to return
5790 ** a positive value as that will cause the optimization to be skipped.
5792 static int indexCellCompare(
5793 BtCursor *pCur,
5794 int idx,
5795 UnpackedRecord *pIdxKey,
5796 RecordCompare xRecordCompare
5798 MemPage *pPage = pCur->pPage;
5799 int c;
5800 int nCell; /* Size of the pCell cell in bytes */
5801 u8 *pCell = findCellPastPtr(pPage, idx);
5803 nCell = pCell[0];
5804 if( nCell<=pPage->max1bytePayload ){
5805 /* This branch runs if the record-size field of the cell is a
5806 ** single byte varint and the record fits entirely on the main
5807 ** b-tree page. */
5808 testcase( pCell+nCell+1==pPage->aDataEnd );
5809 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
5810 }else if( !(pCell[1] & 0x80)
5811 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5813 /* The record-size field is a 2 byte varint and the record
5814 ** fits entirely on the main b-tree page. */
5815 testcase( pCell+nCell+2==pPage->aDataEnd );
5816 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
5817 }else{
5818 /* If the record extends into overflow pages, do not attempt
5819 ** the optimization. */
5820 c = 99;
5822 return c;
5826 ** Return true (non-zero) if pCur is current pointing to the last
5827 ** page of a table.
5829 static int cursorOnLastPage(BtCursor *pCur){
5830 int i;
5831 assert( pCur->eState==CURSOR_VALID );
5832 for(i=0; i<pCur->iPage; i++){
5833 MemPage *pPage = pCur->apPage[i];
5834 if( pCur->aiIdx[i]<pPage->nCell ) return 0;
5836 return 1;
5839 /* Move the cursor so that it points to an entry in an index table
5840 ** near the key pIdxKey. Return a success code.
5842 ** If an exact match is not found, then the cursor is always
5843 ** left pointing at a leaf page which would hold the entry if it
5844 ** were present. The cursor might point to an entry that comes
5845 ** before or after the key.
5847 ** An integer is written into *pRes which is the result of
5848 ** comparing the key with the entry to which the cursor is
5849 ** pointing. The meaning of the integer written into
5850 ** *pRes is as follows:
5852 ** *pRes<0 The cursor is left pointing at an entry that
5853 ** is smaller than pIdxKey or if the table is empty
5854 ** and the cursor is therefore left point to nothing.
5856 ** *pRes==0 The cursor is left pointing at an entry that
5857 ** exactly matches pIdxKey.
5859 ** *pRes>0 The cursor is left pointing at an entry that
5860 ** is larger than pIdxKey.
5862 ** The pIdxKey->eqSeen field is set to 1 if there
5863 ** exists an entry in the table that exactly matches pIdxKey.
5865 int sqlite3BtreeIndexMoveto(
5866 BtCursor *pCur, /* The cursor to be moved */
5867 UnpackedRecord *pIdxKey, /* Unpacked index key */
5868 int *pRes /* Write search results here */
5870 int rc;
5871 RecordCompare xRecordCompare;
5873 assert( cursorOwnsBtShared(pCur) );
5874 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5875 assert( pRes );
5876 assert( pCur->pKeyInfo!=0 );
5878 #ifdef SQLITE_DEBUG
5879 pCur->pBtree->nSeek++; /* Performance measurement during testing */
5880 #endif
5882 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
5883 pIdxKey->errCode = 0;
5884 assert( pIdxKey->default_rc==1
5885 || pIdxKey->default_rc==0
5886 || pIdxKey->default_rc==-1
5890 /* Check to see if we can skip a lot of work. Two cases:
5892 ** (1) If the cursor is already pointing to the very last cell
5893 ** in the table and the pIdxKey search key is greater than or
5894 ** equal to that last cell, then no movement is required.
5896 ** (2) If the cursor is on the last page of the table and the first
5897 ** cell on that last page is less than or equal to the pIdxKey
5898 ** search key, then we can start the search on the current page
5899 ** without needing to go back to root.
5901 if( pCur->eState==CURSOR_VALID
5902 && pCur->pPage->leaf
5903 && cursorOnLastPage(pCur)
5905 int c;
5906 if( pCur->ix==pCur->pPage->nCell-1
5907 && (c = indexCellCompare(pCur, pCur->ix, pIdxKey, xRecordCompare))<=0
5908 && pIdxKey->errCode==SQLITE_OK
5910 *pRes = c;
5911 return SQLITE_OK; /* Cursor already pointing at the correct spot */
5913 if( pCur->iPage>0
5914 && indexCellCompare(pCur, 0, pIdxKey, xRecordCompare)<=0
5915 && pIdxKey->errCode==SQLITE_OK
5917 pCur->curFlags &= ~BTCF_ValidOvfl;
5918 if( !pCur->pPage->isInit ){
5919 return SQLITE_CORRUPT_BKPT;
5921 goto bypass_moveto_root; /* Start search on the current page */
5923 pIdxKey->errCode = SQLITE_OK;
5926 rc = moveToRoot(pCur);
5927 if( rc ){
5928 if( rc==SQLITE_EMPTY ){
5929 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5930 *pRes = -1;
5931 return SQLITE_OK;
5933 return rc;
5936 bypass_moveto_root:
5937 assert( pCur->pPage );
5938 assert( pCur->pPage->isInit );
5939 assert( pCur->eState==CURSOR_VALID );
5940 assert( pCur->pPage->nCell > 0 );
5941 assert( pCur->curIntKey==0 );
5942 assert( pIdxKey!=0 );
5943 for(;;){
5944 int lwr, upr, idx, c;
5945 Pgno chldPg;
5946 MemPage *pPage = pCur->pPage;
5947 u8 *pCell; /* Pointer to current cell in pPage */
5949 /* pPage->nCell must be greater than zero. If this is the root-page
5950 ** the cursor would have been INVALID above and this for(;;) loop
5951 ** not run. If this is not the root-page, then the moveToChild() routine
5952 ** would have already detected db corruption. Similarly, pPage must
5953 ** be the right kind (index or table) of b-tree page. Otherwise
5954 ** a moveToChild() or moveToRoot() call would have detected corruption. */
5955 assert( pPage->nCell>0 );
5956 assert( pPage->intKey==0 );
5957 lwr = 0;
5958 upr = pPage->nCell-1;
5959 idx = upr>>1; /* idx = (lwr+upr)/2; */
5960 for(;;){
5961 int nCell; /* Size of the pCell cell in bytes */
5962 pCell = findCellPastPtr(pPage, idx);
5964 /* The maximum supported page-size is 65536 bytes. This means that
5965 ** the maximum number of record bytes stored on an index B-Tree
5966 ** page is less than 16384 bytes and may be stored as a 2-byte
5967 ** varint. This information is used to attempt to avoid parsing
5968 ** the entire cell by checking for the cases where the record is
5969 ** stored entirely within the b-tree page by inspecting the first
5970 ** 2 bytes of the cell.
5972 nCell = pCell[0];
5973 if( nCell<=pPage->max1bytePayload ){
5974 /* This branch runs if the record-size field of the cell is a
5975 ** single byte varint and the record fits entirely on the main
5976 ** b-tree page. */
5977 testcase( pCell+nCell+1==pPage->aDataEnd );
5978 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
5979 }else if( !(pCell[1] & 0x80)
5980 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5982 /* The record-size field is a 2 byte varint and the record
5983 ** fits entirely on the main b-tree page. */
5984 testcase( pCell+nCell+2==pPage->aDataEnd );
5985 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
5986 }else{
5987 /* The record flows over onto one or more overflow pages. In
5988 ** this case the whole cell needs to be parsed, a buffer allocated
5989 ** and accessPayload() used to retrieve the record into the
5990 ** buffer before VdbeRecordCompare() can be called.
5992 ** If the record is corrupt, the xRecordCompare routine may read
5993 ** up to two varints past the end of the buffer. An extra 18
5994 ** bytes of padding is allocated at the end of the buffer in
5995 ** case this happens. */
5996 void *pCellKey;
5997 u8 * const pCellBody = pCell - pPage->childPtrSize;
5998 const int nOverrun = 18; /* Size of the overrun padding */
5999 pPage->xParseCell(pPage, pCellBody, &pCur->info);
6000 nCell = (int)pCur->info.nKey;
6001 testcase( nCell<0 ); /* True if key size is 2^32 or more */
6002 testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
6003 testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
6004 testcase( nCell==2 ); /* Minimum legal index key size */
6005 if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
6006 rc = SQLITE_CORRUPT_PAGE(pPage);
6007 goto moveto_index_finish;
6009 pCellKey = sqlite3Malloc( nCell+nOverrun );
6010 if( pCellKey==0 ){
6011 rc = SQLITE_NOMEM_BKPT;
6012 goto moveto_index_finish;
6014 pCur->ix = (u16)idx;
6015 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
6016 memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */
6017 pCur->curFlags &= ~BTCF_ValidOvfl;
6018 if( rc ){
6019 sqlite3_free(pCellKey);
6020 goto moveto_index_finish;
6022 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
6023 sqlite3_free(pCellKey);
6025 assert(
6026 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
6027 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
6029 if( c<0 ){
6030 lwr = idx+1;
6031 }else if( c>0 ){
6032 upr = idx-1;
6033 }else{
6034 assert( c==0 );
6035 *pRes = 0;
6036 rc = SQLITE_OK;
6037 pCur->ix = (u16)idx;
6038 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
6039 goto moveto_index_finish;
6041 if( lwr>upr ) break;
6042 assert( lwr+upr>=0 );
6043 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
6045 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
6046 assert( pPage->isInit );
6047 if( pPage->leaf ){
6048 assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
6049 pCur->ix = (u16)idx;
6050 *pRes = c;
6051 rc = SQLITE_OK;
6052 goto moveto_index_finish;
6054 if( lwr>=pPage->nCell ){
6055 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
6056 }else{
6057 chldPg = get4byte(findCell(pPage, lwr));
6059 pCur->ix = (u16)lwr;
6060 rc = moveToChild(pCur, chldPg);
6061 if( rc ) break;
6063 moveto_index_finish:
6064 pCur->info.nSize = 0;
6065 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
6066 return rc;
6071 ** Return TRUE if the cursor is not pointing at an entry of the table.
6073 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
6074 ** past the last entry in the table or sqlite3BtreePrev() moves past
6075 ** the first entry. TRUE is also returned if the table is empty.
6077 int sqlite3BtreeEof(BtCursor *pCur){
6078 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
6079 ** have been deleted? This API will need to change to return an error code
6080 ** as well as the boolean result value.
6082 return (CURSOR_VALID!=pCur->eState);
6086 ** Return an estimate for the number of rows in the table that pCur is
6087 ** pointing to. Return a negative number if no estimate is currently
6088 ** available.
6090 i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
6091 i64 n;
6092 u8 i;
6094 assert( cursorOwnsBtShared(pCur) );
6095 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
6097 /* Currently this interface is only called by the OP_IfSmaller
6098 ** opcode, and it that case the cursor will always be valid and
6099 ** will always point to a leaf node. */
6100 if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
6101 if( NEVER(pCur->pPage->leaf==0) ) return -1;
6103 n = pCur->pPage->nCell;
6104 for(i=0; i<pCur->iPage; i++){
6105 n *= pCur->apPage[i]->nCell;
6107 return n;
6111 ** Advance the cursor to the next entry in the database.
6112 ** Return value:
6114 ** SQLITE_OK success
6115 ** SQLITE_DONE cursor is already pointing at the last element
6116 ** otherwise some kind of error occurred
6118 ** The main entry point is sqlite3BtreeNext(). That routine is optimized
6119 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
6120 ** to the next cell on the current page. The (slower) btreeNext() helper
6121 ** routine is called when it is necessary to move to a different page or
6122 ** to restore the cursor.
6124 ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
6125 ** cursor corresponds to an SQL index and this routine could have been
6126 ** skipped if the SQL index had been a unique index. The F argument
6127 ** is a hint to the implement. SQLite btree implementation does not use
6128 ** this hint, but COMDB2 does.
6130 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
6131 int rc;
6132 int idx;
6133 MemPage *pPage;
6135 assert( cursorOwnsBtShared(pCur) );
6136 if( pCur->eState!=CURSOR_VALID ){
6137 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
6138 rc = restoreCursorPosition(pCur);
6139 if( rc!=SQLITE_OK ){
6140 return rc;
6142 if( CURSOR_INVALID==pCur->eState ){
6143 return SQLITE_DONE;
6145 if( pCur->eState==CURSOR_SKIPNEXT ){
6146 pCur->eState = CURSOR_VALID;
6147 if( pCur->skipNext>0 ) return SQLITE_OK;
6151 pPage = pCur->pPage;
6152 idx = ++pCur->ix;
6153 if( sqlite3FaultSim(412) ) pPage->isInit = 0;
6154 if( !pPage->isInit ){
6155 return SQLITE_CORRUPT_BKPT;
6158 if( idx>=pPage->nCell ){
6159 if( !pPage->leaf ){
6160 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
6161 if( rc ) return rc;
6162 return moveToLeftmost(pCur);
6165 if( pCur->iPage==0 ){
6166 pCur->eState = CURSOR_INVALID;
6167 return SQLITE_DONE;
6169 moveToParent(pCur);
6170 pPage = pCur->pPage;
6171 }while( pCur->ix>=pPage->nCell );
6172 if( pPage->intKey ){
6173 return sqlite3BtreeNext(pCur, 0);
6174 }else{
6175 return SQLITE_OK;
6178 if( pPage->leaf ){
6179 return SQLITE_OK;
6180 }else{
6181 return moveToLeftmost(pCur);
6184 int sqlite3BtreeNext(BtCursor *pCur, int flags){
6185 MemPage *pPage;
6186 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
6187 assert( cursorOwnsBtShared(pCur) );
6188 assert( flags==0 || flags==1 );
6189 pCur->info.nSize = 0;
6190 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
6191 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
6192 pPage = pCur->pPage;
6193 if( (++pCur->ix)>=pPage->nCell ){
6194 pCur->ix--;
6195 return btreeNext(pCur);
6197 if( pPage->leaf ){
6198 return SQLITE_OK;
6199 }else{
6200 return moveToLeftmost(pCur);
6205 ** Step the cursor to the back to the previous entry in the database.
6206 ** Return values:
6208 ** SQLITE_OK success
6209 ** SQLITE_DONE the cursor is already on the first element of the table
6210 ** otherwise some kind of error occurred
6212 ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
6213 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
6214 ** to the previous cell on the current page. The (slower) btreePrevious()
6215 ** helper routine is called when it is necessary to move to a different page
6216 ** or to restore the cursor.
6218 ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
6219 ** the cursor corresponds to an SQL index and this routine could have been
6220 ** skipped if the SQL index had been a unique index. The F argument is a
6221 ** hint to the implement. The native SQLite btree implementation does not
6222 ** use this hint, but COMDB2 does.
6224 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
6225 int rc;
6226 MemPage *pPage;
6228 assert( cursorOwnsBtShared(pCur) );
6229 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
6230 assert( pCur->info.nSize==0 );
6231 if( pCur->eState!=CURSOR_VALID ){
6232 rc = restoreCursorPosition(pCur);
6233 if( rc!=SQLITE_OK ){
6234 return rc;
6236 if( CURSOR_INVALID==pCur->eState ){
6237 return SQLITE_DONE;
6239 if( CURSOR_SKIPNEXT==pCur->eState ){
6240 pCur->eState = CURSOR_VALID;
6241 if( pCur->skipNext<0 ) return SQLITE_OK;
6245 pPage = pCur->pPage;
6246 assert( pPage->isInit );
6247 if( !pPage->leaf ){
6248 int idx = pCur->ix;
6249 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
6250 if( rc ) return rc;
6251 rc = moveToRightmost(pCur);
6252 }else{
6253 while( pCur->ix==0 ){
6254 if( pCur->iPage==0 ){
6255 pCur->eState = CURSOR_INVALID;
6256 return SQLITE_DONE;
6258 moveToParent(pCur);
6260 assert( pCur->info.nSize==0 );
6261 assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
6263 pCur->ix--;
6264 pPage = pCur->pPage;
6265 if( pPage->intKey && !pPage->leaf ){
6266 rc = sqlite3BtreePrevious(pCur, 0);
6267 }else{
6268 rc = SQLITE_OK;
6271 return rc;
6273 int sqlite3BtreePrevious(BtCursor *pCur, int flags){
6274 assert( cursorOwnsBtShared(pCur) );
6275 assert( flags==0 || flags==1 );
6276 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
6277 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
6278 pCur->info.nSize = 0;
6279 if( pCur->eState!=CURSOR_VALID
6280 || pCur->ix==0
6281 || pCur->pPage->leaf==0
6283 return btreePrevious(pCur);
6285 pCur->ix--;
6286 return SQLITE_OK;
6290 ** Allocate a new page from the database file.
6292 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
6293 ** has already been called on the new page.) The new page has also
6294 ** been referenced and the calling routine is responsible for calling
6295 ** sqlite3PagerUnref() on the new page when it is done.
6297 ** SQLITE_OK is returned on success. Any other return value indicates
6298 ** an error. *ppPage is set to NULL in the event of an error.
6300 ** If the "nearby" parameter is not 0, then an effort is made to
6301 ** locate a page close to the page number "nearby". This can be used in an
6302 ** attempt to keep related pages close to each other in the database file,
6303 ** which in turn can make database access faster.
6305 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
6306 ** anywhere on the free-list, then it is guaranteed to be returned. If
6307 ** eMode is BTALLOC_LT then the page returned will be less than or equal
6308 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
6309 ** are no restrictions on which page is returned.
6311 static int allocateBtreePage(
6312 BtShared *pBt, /* The btree */
6313 MemPage **ppPage, /* Store pointer to the allocated page here */
6314 Pgno *pPgno, /* Store the page number here */
6315 Pgno nearby, /* Search for a page near this one */
6316 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
6318 MemPage *pPage1;
6319 int rc;
6320 u32 n; /* Number of pages on the freelist */
6321 u32 k; /* Number of leaves on the trunk of the freelist */
6322 MemPage *pTrunk = 0;
6323 MemPage *pPrevTrunk = 0;
6324 Pgno mxPage; /* Total size of the database file */
6326 assert( sqlite3_mutex_held(pBt->mutex) );
6327 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
6328 pPage1 = pBt->pPage1;
6329 mxPage = btreePagecount(pBt);
6330 /* EVIDENCE-OF: R-21003-45125 The 4-byte big-endian integer at offset 36
6331 ** stores the total number of pages on the freelist. */
6332 n = get4byte(&pPage1->aData[36]);
6333 testcase( n==mxPage-1 );
6334 if( n>=mxPage ){
6335 return SQLITE_CORRUPT_BKPT;
6337 if( n>0 ){
6338 /* There are pages on the freelist. Reuse one of those pages. */
6339 Pgno iTrunk;
6340 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
6341 u32 nSearch = 0; /* Count of the number of search attempts */
6343 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
6344 ** shows that the page 'nearby' is somewhere on the free-list, then
6345 ** the entire-list will be searched for that page.
6347 #ifndef SQLITE_OMIT_AUTOVACUUM
6348 if( eMode==BTALLOC_EXACT ){
6349 if( nearby<=mxPage ){
6350 u8 eType;
6351 assert( nearby>0 );
6352 assert( pBt->autoVacuum );
6353 rc = ptrmapGet(pBt, nearby, &eType, 0);
6354 if( rc ) return rc;
6355 if( eType==PTRMAP_FREEPAGE ){
6356 searchList = 1;
6359 }else if( eMode==BTALLOC_LE ){
6360 searchList = 1;
6362 #endif
6364 /* Decrement the free-list count by 1. Set iTrunk to the index of the
6365 ** first free-list trunk page. iPrevTrunk is initially 1.
6367 rc = sqlite3PagerWrite(pPage1->pDbPage);
6368 if( rc ) return rc;
6369 put4byte(&pPage1->aData[36], n-1);
6371 /* The code within this loop is run only once if the 'searchList' variable
6372 ** is not true. Otherwise, it runs once for each trunk-page on the
6373 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
6374 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
6376 do {
6377 pPrevTrunk = pTrunk;
6378 if( pPrevTrunk ){
6379 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
6380 ** is the page number of the next freelist trunk page in the list or
6381 ** zero if this is the last freelist trunk page. */
6382 iTrunk = get4byte(&pPrevTrunk->aData[0]);
6383 }else{
6384 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
6385 ** stores the page number of the first page of the freelist, or zero if
6386 ** the freelist is empty. */
6387 iTrunk = get4byte(&pPage1->aData[32]);
6389 testcase( iTrunk==mxPage );
6390 if( iTrunk>mxPage || nSearch++ > n ){
6391 rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
6392 }else{
6393 rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
6395 if( rc ){
6396 pTrunk = 0;
6397 goto end_allocate_page;
6399 assert( pTrunk!=0 );
6400 assert( pTrunk->aData!=0 );
6401 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
6402 ** is the number of leaf page pointers to follow. */
6403 k = get4byte(&pTrunk->aData[4]);
6404 if( k==0 && !searchList ){
6405 /* The trunk has no leaves and the list is not being searched.
6406 ** So extract the trunk page itself and use it as the newly
6407 ** allocated page */
6408 assert( pPrevTrunk==0 );
6409 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6410 if( rc ){
6411 goto end_allocate_page;
6413 *pPgno = iTrunk;
6414 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6415 *ppPage = pTrunk;
6416 pTrunk = 0;
6417 TRACE(("ALLOCATE: %u trunk - %u free pages left\n", *pPgno, n-1));
6418 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
6419 /* Value of k is out of range. Database corruption */
6420 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6421 goto end_allocate_page;
6422 #ifndef SQLITE_OMIT_AUTOVACUUM
6423 }else if( searchList
6424 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
6426 /* The list is being searched and this trunk page is the page
6427 ** to allocate, regardless of whether it has leaves.
6429 *pPgno = iTrunk;
6430 *ppPage = pTrunk;
6431 searchList = 0;
6432 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6433 if( rc ){
6434 goto end_allocate_page;
6436 if( k==0 ){
6437 if( !pPrevTrunk ){
6438 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6439 }else{
6440 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6441 if( rc!=SQLITE_OK ){
6442 goto end_allocate_page;
6444 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
6446 }else{
6447 /* The trunk page is required by the caller but it contains
6448 ** pointers to free-list leaves. The first leaf becomes a trunk
6449 ** page in this case.
6451 MemPage *pNewTrunk;
6452 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
6453 if( iNewTrunk>mxPage ){
6454 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6455 goto end_allocate_page;
6457 testcase( iNewTrunk==mxPage );
6458 rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
6459 if( rc!=SQLITE_OK ){
6460 goto end_allocate_page;
6462 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
6463 if( rc!=SQLITE_OK ){
6464 releasePage(pNewTrunk);
6465 goto end_allocate_page;
6467 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
6468 put4byte(&pNewTrunk->aData[4], k-1);
6469 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
6470 releasePage(pNewTrunk);
6471 if( !pPrevTrunk ){
6472 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
6473 put4byte(&pPage1->aData[32], iNewTrunk);
6474 }else{
6475 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6476 if( rc ){
6477 goto end_allocate_page;
6479 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
6482 pTrunk = 0;
6483 TRACE(("ALLOCATE: %u trunk - %u free pages left\n", *pPgno, n-1));
6484 #endif
6485 }else if( k>0 ){
6486 /* Extract a leaf from the trunk */
6487 u32 closest;
6488 Pgno iPage;
6489 unsigned char *aData = pTrunk->aData;
6490 if( nearby>0 ){
6491 u32 i;
6492 closest = 0;
6493 if( eMode==BTALLOC_LE ){
6494 for(i=0; i<k; i++){
6495 iPage = get4byte(&aData[8+i*4]);
6496 if( iPage<=nearby ){
6497 closest = i;
6498 break;
6501 }else{
6502 int dist;
6503 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
6504 for(i=1; i<k; i++){
6505 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
6506 if( d2<dist ){
6507 closest = i;
6508 dist = d2;
6512 }else{
6513 closest = 0;
6516 iPage = get4byte(&aData[8+closest*4]);
6517 testcase( iPage==mxPage );
6518 if( iPage>mxPage || iPage<2 ){
6519 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6520 goto end_allocate_page;
6522 testcase( iPage==mxPage );
6523 if( !searchList
6524 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
6526 int noContent;
6527 *pPgno = iPage;
6528 TRACE(("ALLOCATE: %u was leaf %u of %u on trunk %u"
6529 ": %u more free pages\n",
6530 *pPgno, closest+1, k, pTrunk->pgno, n-1));
6531 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6532 if( rc ) goto end_allocate_page;
6533 if( closest<k-1 ){
6534 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
6536 put4byte(&aData[4], k-1);
6537 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
6538 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
6539 if( rc==SQLITE_OK ){
6540 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6541 if( rc!=SQLITE_OK ){
6542 releasePage(*ppPage);
6543 *ppPage = 0;
6546 searchList = 0;
6549 releasePage(pPrevTrunk);
6550 pPrevTrunk = 0;
6551 }while( searchList );
6552 }else{
6553 /* There are no pages on the freelist, so append a new page to the
6554 ** database image.
6556 ** Normally, new pages allocated by this block can be requested from the
6557 ** pager layer with the 'no-content' flag set. This prevents the pager
6558 ** from trying to read the pages content from disk. However, if the
6559 ** current transaction has already run one or more incremental-vacuum
6560 ** steps, then the page we are about to allocate may contain content
6561 ** that is required in the event of a rollback. In this case, do
6562 ** not set the no-content flag. This causes the pager to load and journal
6563 ** the current page content before overwriting it.
6565 ** Note that the pager will not actually attempt to load or journal
6566 ** content for any page that really does lie past the end of the database
6567 ** file on disk. So the effects of disabling the no-content optimization
6568 ** here are confined to those pages that lie between the end of the
6569 ** database image and the end of the database file.
6571 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
6573 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6574 if( rc ) return rc;
6575 pBt->nPage++;
6576 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
6578 #ifndef SQLITE_OMIT_AUTOVACUUM
6579 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
6580 /* If *pPgno refers to a pointer-map page, allocate two new pages
6581 ** at the end of the file instead of one. The first allocated page
6582 ** becomes a new pointer-map page, the second is used by the caller.
6584 MemPage *pPg = 0;
6585 TRACE(("ALLOCATE: %u from end of file (pointer-map page)\n", pBt->nPage));
6586 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
6587 rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
6588 if( rc==SQLITE_OK ){
6589 rc = sqlite3PagerWrite(pPg->pDbPage);
6590 releasePage(pPg);
6592 if( rc ) return rc;
6593 pBt->nPage++;
6594 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
6596 #endif
6597 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
6598 *pPgno = pBt->nPage;
6600 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
6601 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
6602 if( rc ) return rc;
6603 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6604 if( rc!=SQLITE_OK ){
6605 releasePage(*ppPage);
6606 *ppPage = 0;
6608 TRACE(("ALLOCATE: %u from end of file\n", *pPgno));
6611 assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );
6613 end_allocate_page:
6614 releasePage(pTrunk);
6615 releasePage(pPrevTrunk);
6616 assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
6617 assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
6618 return rc;
6622 ** This function is used to add page iPage to the database file free-list.
6623 ** It is assumed that the page is not already a part of the free-list.
6625 ** The value passed as the second argument to this function is optional.
6626 ** If the caller happens to have a pointer to the MemPage object
6627 ** corresponding to page iPage handy, it may pass it as the second value.
6628 ** Otherwise, it may pass NULL.
6630 ** If a pointer to a MemPage object is passed as the second argument,
6631 ** its reference count is not altered by this function.
6633 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
6634 MemPage *pTrunk = 0; /* Free-list trunk page */
6635 Pgno iTrunk = 0; /* Page number of free-list trunk page */
6636 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
6637 MemPage *pPage; /* Page being freed. May be NULL. */
6638 int rc; /* Return Code */
6639 u32 nFree; /* Initial number of pages on free-list */
6641 assert( sqlite3_mutex_held(pBt->mutex) );
6642 assert( CORRUPT_DB || iPage>1 );
6643 assert( !pMemPage || pMemPage->pgno==iPage );
6645 if( iPage<2 || iPage>pBt->nPage ){
6646 return SQLITE_CORRUPT_BKPT;
6648 if( pMemPage ){
6649 pPage = pMemPage;
6650 sqlite3PagerRef(pPage->pDbPage);
6651 }else{
6652 pPage = btreePageLookup(pBt, iPage);
6655 /* Increment the free page count on pPage1 */
6656 rc = sqlite3PagerWrite(pPage1->pDbPage);
6657 if( rc ) goto freepage_out;
6658 nFree = get4byte(&pPage1->aData[36]);
6659 put4byte(&pPage1->aData[36], nFree+1);
6661 if( pBt->btsFlags & BTS_SECURE_DELETE ){
6662 /* If the secure_delete option is enabled, then
6663 ** always fully overwrite deleted information with zeros.
6665 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
6666 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
6668 goto freepage_out;
6670 memset(pPage->aData, 0, pPage->pBt->pageSize);
6673 /* If the database supports auto-vacuum, write an entry in the pointer-map
6674 ** to indicate that the page is free.
6676 if( ISAUTOVACUUM(pBt) ){
6677 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
6678 if( rc ) goto freepage_out;
6681 /* Now manipulate the actual database free-list structure. There are two
6682 ** possibilities. If the free-list is currently empty, or if the first
6683 ** trunk page in the free-list is full, then this page will become a
6684 ** new free-list trunk page. Otherwise, it will become a leaf of the
6685 ** first trunk page in the current free-list. This block tests if it
6686 ** is possible to add the page as a new free-list leaf.
6688 if( nFree!=0 ){
6689 u32 nLeaf; /* Initial number of leaf cells on trunk page */
6691 iTrunk = get4byte(&pPage1->aData[32]);
6692 if( iTrunk>btreePagecount(pBt) ){
6693 rc = SQLITE_CORRUPT_BKPT;
6694 goto freepage_out;
6696 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
6697 if( rc!=SQLITE_OK ){
6698 goto freepage_out;
6701 nLeaf = get4byte(&pTrunk->aData[4]);
6702 assert( pBt->usableSize>32 );
6703 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
6704 rc = SQLITE_CORRUPT_BKPT;
6705 goto freepage_out;
6707 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
6708 /* In this case there is room on the trunk page to insert the page
6709 ** being freed as a new leaf.
6711 ** Note that the trunk page is not really full until it contains
6712 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
6713 ** coded. But due to a coding error in versions of SQLite prior to
6714 ** 3.6.0, databases with freelist trunk pages holding more than
6715 ** usableSize/4 - 8 entries will be reported as corrupt. In order
6716 ** to maintain backwards compatibility with older versions of SQLite,
6717 ** we will continue to restrict the number of entries to usableSize/4 - 8
6718 ** for now. At some point in the future (once everyone has upgraded
6719 ** to 3.6.0 or later) we should consider fixing the conditional above
6720 ** to read "usableSize/4-2" instead of "usableSize/4-8".
6722 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
6723 ** avoid using the last six entries in the freelist trunk page array in
6724 ** order that database files created by newer versions of SQLite can be
6725 ** read by older versions of SQLite.
6727 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6728 if( rc==SQLITE_OK ){
6729 put4byte(&pTrunk->aData[4], nLeaf+1);
6730 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
6731 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
6732 sqlite3PagerDontWrite(pPage->pDbPage);
6734 rc = btreeSetHasContent(pBt, iPage);
6736 TRACE(("FREE-PAGE: %u leaf on trunk page %u\n",pPage->pgno,pTrunk->pgno));
6737 goto freepage_out;
6741 /* If control flows to this point, then it was not possible to add the
6742 ** the page being freed as a leaf page of the first trunk in the free-list.
6743 ** Possibly because the free-list is empty, or possibly because the
6744 ** first trunk in the free-list is full. Either way, the page being freed
6745 ** will become the new first trunk page in the free-list.
6747 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
6748 goto freepage_out;
6750 rc = sqlite3PagerWrite(pPage->pDbPage);
6751 if( rc!=SQLITE_OK ){
6752 goto freepage_out;
6754 put4byte(pPage->aData, iTrunk);
6755 put4byte(&pPage->aData[4], 0);
6756 put4byte(&pPage1->aData[32], iPage);
6757 TRACE(("FREE-PAGE: %u new trunk page replacing %u\n", pPage->pgno, iTrunk));
6759 freepage_out:
6760 if( pPage ){
6761 pPage->isInit = 0;
6763 releasePage(pPage);
6764 releasePage(pTrunk);
6765 return rc;
6767 static void freePage(MemPage *pPage, int *pRC){
6768 if( (*pRC)==SQLITE_OK ){
6769 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
6774 ** Free the overflow pages associated with the given Cell.
6776 static SQLITE_NOINLINE int clearCellOverflow(
6777 MemPage *pPage, /* The page that contains the Cell */
6778 unsigned char *pCell, /* First byte of the Cell */
6779 CellInfo *pInfo /* Size information about the cell */
6781 BtShared *pBt;
6782 Pgno ovflPgno;
6783 int rc;
6784 int nOvfl;
6785 u32 ovflPageSize;
6787 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6788 assert( pInfo->nLocal!=pInfo->nPayload );
6789 testcase( pCell + pInfo->nSize == pPage->aDataEnd );
6790 testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
6791 if( pCell + pInfo->nSize > pPage->aDataEnd ){
6792 /* Cell extends past end of page */
6793 return SQLITE_CORRUPT_PAGE(pPage);
6795 ovflPgno = get4byte(pCell + pInfo->nSize - 4);
6796 pBt = pPage->pBt;
6797 assert( pBt->usableSize > 4 );
6798 ovflPageSize = pBt->usableSize - 4;
6799 nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
6800 assert( nOvfl>0 ||
6801 (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
6803 while( nOvfl-- ){
6804 Pgno iNext = 0;
6805 MemPage *pOvfl = 0;
6806 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
6807 /* 0 is not a legal page number and page 1 cannot be an
6808 ** overflow page. Therefore if ovflPgno<2 or past the end of the
6809 ** file the database must be corrupt. */
6810 return SQLITE_CORRUPT_BKPT;
6812 if( nOvfl ){
6813 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
6814 if( rc ) return rc;
6817 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
6818 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
6820 /* There is no reason any cursor should have an outstanding reference
6821 ** to an overflow page belonging to a cell that is being deleted/updated.
6822 ** So if there exists more than one reference to this page, then it
6823 ** must not really be an overflow page and the database must be corrupt.
6824 ** It is helpful to detect this before calling freePage2(), as
6825 ** freePage2() may zero the page contents if secure-delete mode is
6826 ** enabled. If this 'overflow' page happens to be a page that the
6827 ** caller is iterating through or using in some other way, this
6828 ** can be problematic.
6830 rc = SQLITE_CORRUPT_BKPT;
6831 }else{
6832 rc = freePage2(pBt, pOvfl, ovflPgno);
6835 if( pOvfl ){
6836 sqlite3PagerUnref(pOvfl->pDbPage);
6838 if( rc ) return rc;
6839 ovflPgno = iNext;
6841 return SQLITE_OK;
6844 /* Call xParseCell to compute the size of a cell. If the cell contains
6845 ** overflow, then invoke cellClearOverflow to clear out that overflow.
6846 ** STore the result code (SQLITE_OK or some error code) in rc.
6848 ** Implemented as macro to force inlining for performance.
6850 #define BTREE_CLEAR_CELL(rc, pPage, pCell, sInfo) \
6851 pPage->xParseCell(pPage, pCell, &sInfo); \
6852 if( sInfo.nLocal!=sInfo.nPayload ){ \
6853 rc = clearCellOverflow(pPage, pCell, &sInfo); \
6854 }else{ \
6855 rc = SQLITE_OK; \
6860 ** Create the byte sequence used to represent a cell on page pPage
6861 ** and write that byte sequence into pCell[]. Overflow pages are
6862 ** allocated and filled in as necessary. The calling procedure
6863 ** is responsible for making sure sufficient space has been allocated
6864 ** for pCell[].
6866 ** Note that pCell does not necessary need to point to the pPage->aData
6867 ** area. pCell might point to some temporary storage. The cell will
6868 ** be constructed in this temporary area then copied into pPage->aData
6869 ** later.
6871 static int fillInCell(
6872 MemPage *pPage, /* The page that contains the cell */
6873 unsigned char *pCell, /* Complete text of the cell */
6874 const BtreePayload *pX, /* Payload with which to construct the cell */
6875 int *pnSize /* Write cell size here */
6877 int nPayload;
6878 const u8 *pSrc;
6879 int nSrc, n, rc, mn;
6880 int spaceLeft;
6881 MemPage *pToRelease;
6882 unsigned char *pPrior;
6883 unsigned char *pPayload;
6884 BtShared *pBt;
6885 Pgno pgnoOvfl;
6886 int nHeader;
6888 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6890 /* pPage is not necessarily writeable since pCell might be auxiliary
6891 ** buffer space that is separate from the pPage buffer area */
6892 assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
6893 || sqlite3PagerIswriteable(pPage->pDbPage) );
6895 /* Fill in the header. */
6896 nHeader = pPage->childPtrSize;
6897 if( pPage->intKey ){
6898 nPayload = pX->nData + pX->nZero;
6899 pSrc = pX->pData;
6900 nSrc = pX->nData;
6901 assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
6902 nHeader += putVarint32(&pCell[nHeader], nPayload);
6903 nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
6904 }else{
6905 assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
6906 nSrc = nPayload = (int)pX->nKey;
6907 pSrc = pX->pKey;
6908 nHeader += putVarint32(&pCell[nHeader], nPayload);
6911 /* Fill in the payload */
6912 pPayload = &pCell[nHeader];
6913 if( nPayload<=pPage->maxLocal ){
6914 /* This is the common case where everything fits on the btree page
6915 ** and no overflow pages are required. */
6916 n = nHeader + nPayload;
6917 testcase( n==3 );
6918 testcase( n==4 );
6919 if( n<4 ) n = 4;
6920 *pnSize = n;
6921 assert( nSrc<=nPayload );
6922 testcase( nSrc<nPayload );
6923 memcpy(pPayload, pSrc, nSrc);
6924 memset(pPayload+nSrc, 0, nPayload-nSrc);
6925 return SQLITE_OK;
6928 /* If we reach this point, it means that some of the content will need
6929 ** to spill onto overflow pages.
6931 mn = pPage->minLocal;
6932 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
6933 testcase( n==pPage->maxLocal );
6934 testcase( n==pPage->maxLocal+1 );
6935 if( n > pPage->maxLocal ) n = mn;
6936 spaceLeft = n;
6937 *pnSize = n + nHeader + 4;
6938 pPrior = &pCell[nHeader+n];
6939 pToRelease = 0;
6940 pgnoOvfl = 0;
6941 pBt = pPage->pBt;
6943 /* At this point variables should be set as follows:
6945 ** nPayload Total payload size in bytes
6946 ** pPayload Begin writing payload here
6947 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
6948 ** that means content must spill into overflow pages.
6949 ** *pnSize Size of the local cell (not counting overflow pages)
6950 ** pPrior Where to write the pgno of the first overflow page
6952 ** Use a call to btreeParseCellPtr() to verify that the values above
6953 ** were computed correctly.
6955 #ifdef SQLITE_DEBUG
6957 CellInfo info;
6958 pPage->xParseCell(pPage, pCell, &info);
6959 assert( nHeader==(int)(info.pPayload - pCell) );
6960 assert( info.nKey==pX->nKey );
6961 assert( *pnSize == info.nSize );
6962 assert( spaceLeft == info.nLocal );
6964 #endif
6966 /* Write the payload into the local Cell and any extra into overflow pages */
6967 while( 1 ){
6968 n = nPayload;
6969 if( n>spaceLeft ) n = spaceLeft;
6971 /* If pToRelease is not zero than pPayload points into the data area
6972 ** of pToRelease. Make sure pToRelease is still writeable. */
6973 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6975 /* If pPayload is part of the data area of pPage, then make sure pPage
6976 ** is still writeable */
6977 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
6978 || sqlite3PagerIswriteable(pPage->pDbPage) );
6980 if( nSrc>=n ){
6981 memcpy(pPayload, pSrc, n);
6982 }else if( nSrc>0 ){
6983 n = nSrc;
6984 memcpy(pPayload, pSrc, n);
6985 }else{
6986 memset(pPayload, 0, n);
6988 nPayload -= n;
6989 if( nPayload<=0 ) break;
6990 pPayload += n;
6991 pSrc += n;
6992 nSrc -= n;
6993 spaceLeft -= n;
6994 if( spaceLeft==0 ){
6995 MemPage *pOvfl = 0;
6996 #ifndef SQLITE_OMIT_AUTOVACUUM
6997 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
6998 if( pBt->autoVacuum ){
7000 pgnoOvfl++;
7001 } while(
7002 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
7005 #endif
7006 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
7007 #ifndef SQLITE_OMIT_AUTOVACUUM
7008 /* If the database supports auto-vacuum, and the second or subsequent
7009 ** overflow page is being allocated, add an entry to the pointer-map
7010 ** for that page now.
7012 ** If this is the first overflow page, then write a partial entry
7013 ** to the pointer-map. If we write nothing to this pointer-map slot,
7014 ** then the optimistic overflow chain processing in clearCell()
7015 ** may misinterpret the uninitialized values and delete the
7016 ** wrong pages from the database.
7018 if( pBt->autoVacuum && rc==SQLITE_OK ){
7019 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
7020 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
7021 if( rc ){
7022 releasePage(pOvfl);
7025 #endif
7026 if( rc ){
7027 releasePage(pToRelease);
7028 return rc;
7031 /* If pToRelease is not zero than pPrior points into the data area
7032 ** of pToRelease. Make sure pToRelease is still writeable. */
7033 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
7035 /* If pPrior is part of the data area of pPage, then make sure pPage
7036 ** is still writeable */
7037 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
7038 || sqlite3PagerIswriteable(pPage->pDbPage) );
7040 put4byte(pPrior, pgnoOvfl);
7041 releasePage(pToRelease);
7042 pToRelease = pOvfl;
7043 pPrior = pOvfl->aData;
7044 put4byte(pPrior, 0);
7045 pPayload = &pOvfl->aData[4];
7046 spaceLeft = pBt->usableSize - 4;
7049 releasePage(pToRelease);
7050 return SQLITE_OK;
7054 ** Remove the i-th cell from pPage. This routine effects pPage only.
7055 ** The cell content is not freed or deallocated. It is assumed that
7056 ** the cell content has been copied someplace else. This routine just
7057 ** removes the reference to the cell from pPage.
7059 ** "sz" must be the number of bytes in the cell.
7061 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
7062 u32 pc; /* Offset to cell content of cell being deleted */
7063 u8 *data; /* pPage->aData */
7064 u8 *ptr; /* Used to move bytes around within data[] */
7065 int rc; /* The return code */
7066 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
7068 if( *pRC ) return;
7069 assert( idx>=0 );
7070 assert( idx<pPage->nCell );
7071 assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
7072 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
7073 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7074 assert( pPage->nFree>=0 );
7075 data = pPage->aData;
7076 ptr = &pPage->aCellIdx[2*idx];
7077 assert( pPage->pBt->usableSize > (u32)(ptr-data) );
7078 pc = get2byte(ptr);
7079 hdr = pPage->hdrOffset;
7080 testcase( pc==(u32)get2byte(&data[hdr+5]) );
7081 testcase( pc+sz==pPage->pBt->usableSize );
7082 if( pc+sz > pPage->pBt->usableSize ){
7083 *pRC = SQLITE_CORRUPT_BKPT;
7084 return;
7086 rc = freeSpace(pPage, pc, sz);
7087 if( rc ){
7088 *pRC = rc;
7089 return;
7091 pPage->nCell--;
7092 if( pPage->nCell==0 ){
7093 memset(&data[hdr+1], 0, 4);
7094 data[hdr+7] = 0;
7095 put2byte(&data[hdr+5], pPage->pBt->usableSize);
7096 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
7097 - pPage->childPtrSize - 8;
7098 }else{
7099 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
7100 put2byte(&data[hdr+3], pPage->nCell);
7101 pPage->nFree += 2;
7106 ** Insert a new cell on pPage at cell index "i". pCell points to the
7107 ** content of the cell.
7109 ** If the cell content will fit on the page, then put it there. If it
7110 ** will not fit, then make a copy of the cell content into pTemp if
7111 ** pTemp is not null. Regardless of pTemp, allocate a new entry
7112 ** in pPage->apOvfl[] and make it point to the cell content (either
7113 ** in pTemp or the original pCell) and also record its index.
7114 ** Allocating a new entry in pPage->aCell[] implies that
7115 ** pPage->nOverflow is incremented.
7117 ** The insertCellFast() routine below works exactly the same as
7118 ** insertCell() except that it lacks the pTemp and iChild parameters
7119 ** which are assumed zero. Other than that, the two routines are the
7120 ** same.
7122 ** Fixes or enhancements to this routine should be reflected in
7123 ** insertCellFast()!
7125 static int insertCell(
7126 MemPage *pPage, /* Page into which we are copying */
7127 int i, /* New cell becomes the i-th cell of the page */
7128 u8 *pCell, /* Content of the new cell */
7129 int sz, /* Bytes of content in pCell */
7130 u8 *pTemp, /* Temp storage space for pCell, if needed */
7131 Pgno iChild /* If non-zero, replace first 4 bytes with this value */
7133 int idx = 0; /* Where to write new cell content in data[] */
7134 int j; /* Loop counter */
7135 u8 *data; /* The content of the whole page */
7136 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
7138 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
7139 assert( MX_CELL(pPage->pBt)<=10921 );
7140 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
7141 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
7142 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
7143 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7144 assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
7145 assert( pPage->nFree>=0 );
7146 assert( iChild>0 );
7147 if( pPage->nOverflow || sz+2>pPage->nFree ){
7148 if( pTemp ){
7149 memcpy(pTemp, pCell, sz);
7150 pCell = pTemp;
7152 put4byte(pCell, iChild);
7153 j = pPage->nOverflow++;
7154 /* Comparison against ArraySize-1 since we hold back one extra slot
7155 ** as a contingency. In other words, never need more than 3 overflow
7156 ** slots but 4 are allocated, just to be safe. */
7157 assert( j < ArraySize(pPage->apOvfl)-1 );
7158 pPage->apOvfl[j] = pCell;
7159 pPage->aiOvfl[j] = (u16)i;
7161 /* When multiple overflows occur, they are always sequential and in
7162 ** sorted order. This invariants arise because multiple overflows can
7163 ** only occur when inserting divider cells into the parent page during
7164 ** balancing, and the dividers are adjacent and sorted.
7166 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
7167 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
7168 }else{
7169 int rc = sqlite3PagerWrite(pPage->pDbPage);
7170 if( NEVER(rc!=SQLITE_OK) ){
7171 return rc;
7173 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
7174 data = pPage->aData;
7175 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
7176 rc = allocateSpace(pPage, sz, &idx);
7177 if( rc ){ return rc; }
7178 /* The allocateSpace() routine guarantees the following properties
7179 ** if it returns successfully */
7180 assert( idx >= 0 );
7181 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
7182 assert( idx+sz <= (int)pPage->pBt->usableSize );
7183 pPage->nFree -= (u16)(2 + sz);
7184 /* In a corrupt database where an entry in the cell index section of
7185 ** a btree page has a value of 3 or less, the pCell value might point
7186 ** as many as 4 bytes in front of the start of the aData buffer for
7187 ** the source page. Make sure this does not cause problems by not
7188 ** reading the first 4 bytes */
7189 memcpy(&data[idx+4], pCell+4, sz-4);
7190 put4byte(&data[idx], iChild);
7191 pIns = pPage->aCellIdx + i*2;
7192 memmove(pIns+2, pIns, 2*(pPage->nCell - i));
7193 put2byte(pIns, idx);
7194 pPage->nCell++;
7195 /* increment the cell count */
7196 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
7197 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
7198 #ifndef SQLITE_OMIT_AUTOVACUUM
7199 if( pPage->pBt->autoVacuum ){
7200 int rc2 = SQLITE_OK;
7201 /* The cell may contain a pointer to an overflow page. If so, write
7202 ** the entry for the overflow page into the pointer map.
7204 ptrmapPutOvflPtr(pPage, pPage, pCell, &rc2);
7205 if( rc2 ) return rc2;
7207 #endif
7209 return SQLITE_OK;
7213 ** This variant of insertCell() assumes that the pTemp and iChild
7214 ** parameters are both zero. Use this variant in sqlite3BtreeInsert()
7215 ** for performance improvement, and also so that this variant is only
7216 ** called from that one place, and is thus inlined, and thus runs must
7217 ** faster.
7219 ** Fixes or enhancements to this routine should be reflected into
7220 ** the insertCell() routine.
7222 static int insertCellFast(
7223 MemPage *pPage, /* Page into which we are copying */
7224 int i, /* New cell becomes the i-th cell of the page */
7225 u8 *pCell, /* Content of the new cell */
7226 int sz /* Bytes of content in pCell */
7228 int idx = 0; /* Where to write new cell content in data[] */
7229 int j; /* Loop counter */
7230 u8 *data; /* The content of the whole page */
7231 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
7233 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
7234 assert( MX_CELL(pPage->pBt)<=10921 );
7235 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
7236 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
7237 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
7238 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7239 assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
7240 assert( pPage->nFree>=0 );
7241 assert( pPage->nOverflow==0 );
7242 if( sz+2>pPage->nFree ){
7243 j = pPage->nOverflow++;
7244 /* Comparison against ArraySize-1 since we hold back one extra slot
7245 ** as a contingency. In other words, never need more than 3 overflow
7246 ** slots but 4 are allocated, just to be safe. */
7247 assert( j < ArraySize(pPage->apOvfl)-1 );
7248 pPage->apOvfl[j] = pCell;
7249 pPage->aiOvfl[j] = (u16)i;
7251 /* When multiple overflows occur, they are always sequential and in
7252 ** sorted order. This invariants arise because multiple overflows can
7253 ** only occur when inserting divider cells into the parent page during
7254 ** balancing, and the dividers are adjacent and sorted.
7256 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
7257 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
7258 }else{
7259 int rc = sqlite3PagerWrite(pPage->pDbPage);
7260 if( rc!=SQLITE_OK ){
7261 return rc;
7263 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
7264 data = pPage->aData;
7265 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
7266 rc = allocateSpace(pPage, sz, &idx);
7267 if( rc ){ return rc; }
7268 /* The allocateSpace() routine guarantees the following properties
7269 ** if it returns successfully */
7270 assert( idx >= 0 );
7271 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
7272 assert( idx+sz <= (int)pPage->pBt->usableSize );
7273 pPage->nFree -= (u16)(2 + sz);
7274 memcpy(&data[idx], pCell, sz);
7275 pIns = pPage->aCellIdx + i*2;
7276 memmove(pIns+2, pIns, 2*(pPage->nCell - i));
7277 put2byte(pIns, idx);
7278 pPage->nCell++;
7279 /* increment the cell count */
7280 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
7281 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
7282 #ifndef SQLITE_OMIT_AUTOVACUUM
7283 if( pPage->pBt->autoVacuum ){
7284 int rc2 = SQLITE_OK;
7285 /* The cell may contain a pointer to an overflow page. If so, write
7286 ** the entry for the overflow page into the pointer map.
7288 ptrmapPutOvflPtr(pPage, pPage, pCell, &rc2);
7289 if( rc2 ) return rc2;
7291 #endif
7293 return SQLITE_OK;
7297 ** The following parameters determine how many adjacent pages get involved
7298 ** in a balancing operation. NN is the number of neighbors on either side
7299 ** of the page that participate in the balancing operation. NB is the
7300 ** total number of pages that participate, including the target page and
7301 ** NN neighbors on either side.
7303 ** The minimum value of NN is 1 (of course). Increasing NN above 1
7304 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
7305 ** in exchange for a larger degradation in INSERT and UPDATE performance.
7306 ** The value of NN appears to give the best results overall.
7308 ** (Later:) The description above makes it seem as if these values are
7309 ** tunable - as if you could change them and recompile and it would all work.
7310 ** But that is unlikely. NB has been 3 since the inception of SQLite and
7311 ** we have never tested any other value.
7313 #define NN 1 /* Number of neighbors on either side of pPage */
7314 #define NB 3 /* (NN*2+1): Total pages involved in the balance */
7317 ** A CellArray object contains a cache of pointers and sizes for a
7318 ** consecutive sequence of cells that might be held on multiple pages.
7320 ** The cells in this array are the divider cell or cells from the pParent
7321 ** page plus up to three child pages. There are a total of nCell cells.
7323 ** pRef is a pointer to one of the pages that contributes cells. This is
7324 ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
7325 ** which should be common to all pages that contribute cells to this array.
7327 ** apCell[] and szCell[] hold, respectively, pointers to the start of each
7328 ** cell and the size of each cell. Some of the apCell[] pointers might refer
7329 ** to overflow cells. In other words, some apCel[] pointers might not point
7330 ** to content area of the pages.
7332 ** A szCell[] of zero means the size of that cell has not yet been computed.
7334 ** The cells come from as many as four different pages:
7336 ** -----------
7337 ** | Parent |
7338 ** -----------
7339 ** / | \
7340 ** / | \
7341 ** --------- --------- ---------
7342 ** |Child-1| |Child-2| |Child-3|
7343 ** --------- --------- ---------
7345 ** The order of cells is in the array is for an index btree is:
7347 ** 1. All cells from Child-1 in order
7348 ** 2. The first divider cell from Parent
7349 ** 3. All cells from Child-2 in order
7350 ** 4. The second divider cell from Parent
7351 ** 5. All cells from Child-3 in order
7353 ** For a table-btree (with rowids) the items 2 and 4 are empty because
7354 ** content exists only in leaves and there are no divider cells.
7356 ** For an index btree, the apEnd[] array holds pointer to the end of page
7357 ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
7358 ** respectively. The ixNx[] array holds the number of cells contained in
7359 ** each of these 5 stages, and all stages to the left. Hence:
7361 ** ixNx[0] = Number of cells in Child-1.
7362 ** ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
7363 ** ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
7364 ** ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
7365 ** ixNx[4] = Total number of cells.
7367 ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
7368 ** are used and they point to the leaf pages only, and the ixNx value are:
7370 ** ixNx[0] = Number of cells in Child-1.
7371 ** ixNx[1] = Number of cells in Child-1 and Child-2.
7372 ** ixNx[2] = Total number of cells.
7374 ** Sometimes when deleting, a child page can have zero cells. In those
7375 ** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[]
7376 ** entries, shift down. The end result is that each ixNx[] entry should
7377 ** be larger than the previous
7379 typedef struct CellArray CellArray;
7380 struct CellArray {
7381 int nCell; /* Number of cells in apCell[] */
7382 MemPage *pRef; /* Reference page */
7383 u8 **apCell; /* All cells begin balanced */
7384 u16 *szCell; /* Local size of all cells in apCell[] */
7385 u8 *apEnd[NB*2]; /* MemPage.aDataEnd values */
7386 int ixNx[NB*2]; /* Index of at which we move to the next apEnd[] */
7390 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
7391 ** computed.
7393 static void populateCellCache(CellArray *p, int idx, int N){
7394 MemPage *pRef = p->pRef;
7395 u16 *szCell = p->szCell;
7396 assert( idx>=0 && idx+N<=p->nCell );
7397 while( N>0 ){
7398 assert( p->apCell[idx]!=0 );
7399 if( szCell[idx]==0 ){
7400 szCell[idx] = pRef->xCellSize(pRef, p->apCell[idx]);
7401 }else{
7402 assert( CORRUPT_DB ||
7403 szCell[idx]==pRef->xCellSize(pRef, p->apCell[idx]) );
7405 idx++;
7406 N--;
7411 ** Return the size of the Nth element of the cell array
7413 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
7414 assert( N>=0 && N<p->nCell );
7415 assert( p->szCell[N]==0 );
7416 p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
7417 return p->szCell[N];
7419 static u16 cachedCellSize(CellArray *p, int N){
7420 assert( N>=0 && N<p->nCell );
7421 if( p->szCell[N] ) return p->szCell[N];
7422 return computeCellSize(p, N);
7426 ** Array apCell[] contains pointers to nCell b-tree page cells. The
7427 ** szCell[] array contains the size in bytes of each cell. This function
7428 ** replaces the current contents of page pPg with the contents of the cell
7429 ** array.
7431 ** Some of the cells in apCell[] may currently be stored in pPg. This
7432 ** function works around problems caused by this by making a copy of any
7433 ** such cells before overwriting the page data.
7435 ** The MemPage.nFree field is invalidated by this function. It is the
7436 ** responsibility of the caller to set it correctly.
7438 static int rebuildPage(
7439 CellArray *pCArray, /* Content to be added to page pPg */
7440 int iFirst, /* First cell in pCArray to use */
7441 int nCell, /* Final number of cells on page */
7442 MemPage *pPg /* The page to be reconstructed */
7444 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
7445 u8 * const aData = pPg->aData; /* Pointer to data for pPg */
7446 const int usableSize = pPg->pBt->usableSize;
7447 u8 * const pEnd = &aData[usableSize];
7448 int i = iFirst; /* Which cell to copy from pCArray*/
7449 u32 j; /* Start of cell content area */
7450 int iEnd = i+nCell; /* Loop terminator */
7451 u8 *pCellptr = pPg->aCellIdx;
7452 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7453 u8 *pData;
7454 int k; /* Current slot in pCArray->apEnd[] */
7455 u8 *pSrcEnd; /* Current pCArray->apEnd[k] value */
7457 assert( i<iEnd );
7458 j = get2byte(&aData[hdr+5]);
7459 if( NEVER(j>(u32)usableSize) ){ j = 0; }
7460 memcpy(&pTmp[j], &aData[j], usableSize - j);
7462 for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
7463 pSrcEnd = pCArray->apEnd[k];
7465 pData = pEnd;
7466 while( 1/*exit by break*/ ){
7467 u8 *pCell = pCArray->apCell[i];
7468 u16 sz = pCArray->szCell[i];
7469 assert( sz>0 );
7470 if( SQLITE_WITHIN(pCell,aData+j,pEnd) ){
7471 if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
7472 pCell = &pTmp[pCell - aData];
7473 }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
7474 && (uptr)(pCell)<(uptr)pSrcEnd
7476 return SQLITE_CORRUPT_BKPT;
7479 pData -= sz;
7480 put2byte(pCellptr, (pData - aData));
7481 pCellptr += 2;
7482 if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
7483 memmove(pData, pCell, sz);
7484 assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
7485 i++;
7486 if( i>=iEnd ) break;
7487 if( pCArray->ixNx[k]<=i ){
7488 k++;
7489 pSrcEnd = pCArray->apEnd[k];
7493 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
7494 pPg->nCell = nCell;
7495 pPg->nOverflow = 0;
7497 put2byte(&aData[hdr+1], 0);
7498 put2byte(&aData[hdr+3], pPg->nCell);
7499 put2byte(&aData[hdr+5], pData - aData);
7500 aData[hdr+7] = 0x00;
7501 return SQLITE_OK;
7505 ** The pCArray objects contains pointers to b-tree cells and the cell sizes.
7506 ** This function attempts to add the cells stored in the array to page pPg.
7507 ** If it cannot (because the page needs to be defragmented before the cells
7508 ** will fit), non-zero is returned. Otherwise, if the cells are added
7509 ** successfully, zero is returned.
7511 ** Argument pCellptr points to the first entry in the cell-pointer array
7512 ** (part of page pPg) to populate. After cell apCell[0] is written to the
7513 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
7514 ** cell in the array. It is the responsibility of the caller to ensure
7515 ** that it is safe to overwrite this part of the cell-pointer array.
7517 ** When this function is called, *ppData points to the start of the
7518 ** content area on page pPg. If the size of the content area is extended,
7519 ** *ppData is updated to point to the new start of the content area
7520 ** before returning.
7522 ** Finally, argument pBegin points to the byte immediately following the
7523 ** end of the space required by this page for the cell-pointer area (for
7524 ** all cells - not just those inserted by the current call). If the content
7525 ** area must be extended to before this point in order to accomodate all
7526 ** cells in apCell[], then the cells do not fit and non-zero is returned.
7528 static int pageInsertArray(
7529 MemPage *pPg, /* Page to add cells to */
7530 u8 *pBegin, /* End of cell-pointer array */
7531 u8 **ppData, /* IN/OUT: Page content-area pointer */
7532 u8 *pCellptr, /* Pointer to cell-pointer area */
7533 int iFirst, /* Index of first cell to add */
7534 int nCell, /* Number of cells to add to pPg */
7535 CellArray *pCArray /* Array of cells */
7537 int i = iFirst; /* Loop counter - cell index to insert */
7538 u8 *aData = pPg->aData; /* Complete page */
7539 u8 *pData = *ppData; /* Content area. A subset of aData[] */
7540 int iEnd = iFirst + nCell; /* End of loop. One past last cell to ins */
7541 int k; /* Current slot in pCArray->apEnd[] */
7542 u8 *pEnd; /* Maximum extent of cell data */
7543 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
7544 if( iEnd<=iFirst ) return 0;
7545 for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
7546 pEnd = pCArray->apEnd[k];
7547 while( 1 /*Exit by break*/ ){
7548 int sz, rc;
7549 u8 *pSlot;
7550 assert( pCArray->szCell[i]!=0 );
7551 sz = pCArray->szCell[i];
7552 if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
7553 if( (pData - pBegin)<sz ) return 1;
7554 pData -= sz;
7555 pSlot = pData;
7557 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
7558 ** database. But they might for a corrupt database. Hence use memmove()
7559 ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
7560 assert( (pSlot+sz)<=pCArray->apCell[i]
7561 || pSlot>=(pCArray->apCell[i]+sz)
7562 || CORRUPT_DB );
7563 if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
7564 && (uptr)(pCArray->apCell[i])<(uptr)pEnd
7566 assert( CORRUPT_DB );
7567 (void)SQLITE_CORRUPT_BKPT;
7568 return 1;
7570 memmove(pSlot, pCArray->apCell[i], sz);
7571 put2byte(pCellptr, (pSlot - aData));
7572 pCellptr += 2;
7573 i++;
7574 if( i>=iEnd ) break;
7575 if( pCArray->ixNx[k]<=i ){
7576 k++;
7577 pEnd = pCArray->apEnd[k];
7580 *ppData = pData;
7581 return 0;
7585 ** The pCArray object contains pointers to b-tree cells and their sizes.
7587 ** This function adds the space associated with each cell in the array
7588 ** that is currently stored within the body of pPg to the pPg free-list.
7589 ** The cell-pointers and other fields of the page are not updated.
7591 ** This function returns the total number of cells added to the free-list.
7593 static int pageFreeArray(
7594 MemPage *pPg, /* Page to edit */
7595 int iFirst, /* First cell to delete */
7596 int nCell, /* Cells to delete */
7597 CellArray *pCArray /* Array of cells */
7599 u8 * const aData = pPg->aData;
7600 u8 * const pEnd = &aData[pPg->pBt->usableSize];
7601 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
7602 int nRet = 0;
7603 int i, j;
7604 int iEnd = iFirst + nCell;
7605 int nFree = 0;
7606 int aOfst[10];
7607 int aAfter[10];
7609 for(i=iFirst; i<iEnd; i++){
7610 u8 *pCell = pCArray->apCell[i];
7611 if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
7612 int sz;
7613 int iAfter;
7614 int iOfst;
7615 /* No need to use cachedCellSize() here. The sizes of all cells that
7616 ** are to be freed have already been computing while deciding which
7617 ** cells need freeing */
7618 sz = pCArray->szCell[i]; assert( sz>0 );
7619 iOfst = (u16)(pCell - aData);
7620 iAfter = iOfst+sz;
7621 for(j=0; j<nFree; j++){
7622 if( aOfst[j]==iAfter ){
7623 aOfst[j] = iOfst;
7624 break;
7625 }else if( aAfter[j]==iOfst ){
7626 aAfter[j] = iAfter;
7627 break;
7630 if( j>=nFree ){
7631 if( nFree>=(int)(sizeof(aOfst)/sizeof(aOfst[0])) ){
7632 for(j=0; j<nFree; j++){
7633 freeSpace(pPg, aOfst[j], aAfter[j]-aOfst[j]);
7635 nFree = 0;
7637 aOfst[nFree] = iOfst;
7638 aAfter[nFree] = iAfter;
7639 if( &aData[iAfter]>pEnd ) return 0;
7640 nFree++;
7642 nRet++;
7645 for(j=0; j<nFree; j++){
7646 freeSpace(pPg, aOfst[j], aAfter[j]-aOfst[j]);
7648 return nRet;
7652 ** pCArray contains pointers to and sizes of all cells in the page being
7653 ** balanced. The current page, pPg, has pPg->nCell cells starting with
7654 ** pCArray->apCell[iOld]. After balancing, this page should hold nNew cells
7655 ** starting at apCell[iNew].
7657 ** This routine makes the necessary adjustments to pPg so that it contains
7658 ** the correct cells after being balanced.
7660 ** The pPg->nFree field is invalid when this function returns. It is the
7661 ** responsibility of the caller to set it correctly.
7663 static int editPage(
7664 MemPage *pPg, /* Edit this page */
7665 int iOld, /* Index of first cell currently on page */
7666 int iNew, /* Index of new first cell on page */
7667 int nNew, /* Final number of cells on page */
7668 CellArray *pCArray /* Array of cells and sizes */
7670 u8 * const aData = pPg->aData;
7671 const int hdr = pPg->hdrOffset;
7672 u8 *pBegin = &pPg->aCellIdx[nNew * 2];
7673 int nCell = pPg->nCell; /* Cells stored on pPg */
7674 u8 *pData;
7675 u8 *pCellptr;
7676 int i;
7677 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
7678 int iNewEnd = iNew + nNew;
7680 #ifdef SQLITE_DEBUG
7681 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7682 memcpy(pTmp, aData, pPg->pBt->usableSize);
7683 #endif
7685 /* Remove cells from the start and end of the page */
7686 assert( nCell>=0 );
7687 if( iOld<iNew ){
7688 int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
7689 if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT;
7690 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
7691 nCell -= nShift;
7693 if( iNewEnd < iOldEnd ){
7694 int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
7695 assert( nCell>=nTail );
7696 nCell -= nTail;
7699 pData = &aData[get2byte(&aData[hdr+5])];
7700 if( pData<pBegin ) goto editpage_fail;
7701 if( NEVER(pData>pPg->aDataEnd) ) goto editpage_fail;
7703 /* Add cells to the start of the page */
7704 if( iNew<iOld ){
7705 int nAdd = MIN(nNew,iOld-iNew);
7706 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
7707 assert( nAdd>=0 );
7708 pCellptr = pPg->aCellIdx;
7709 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
7710 if( pageInsertArray(
7711 pPg, pBegin, &pData, pCellptr,
7712 iNew, nAdd, pCArray
7713 ) ) goto editpage_fail;
7714 nCell += nAdd;
7717 /* Add any overflow cells */
7718 for(i=0; i<pPg->nOverflow; i++){
7719 int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
7720 if( iCell>=0 && iCell<nNew ){
7721 pCellptr = &pPg->aCellIdx[iCell * 2];
7722 if( nCell>iCell ){
7723 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
7725 nCell++;
7726 cachedCellSize(pCArray, iCell+iNew);
7727 if( pageInsertArray(
7728 pPg, pBegin, &pData, pCellptr,
7729 iCell+iNew, 1, pCArray
7730 ) ) goto editpage_fail;
7734 /* Append cells to the end of the page */
7735 assert( nCell>=0 );
7736 pCellptr = &pPg->aCellIdx[nCell*2];
7737 if( pageInsertArray(
7738 pPg, pBegin, &pData, pCellptr,
7739 iNew+nCell, nNew-nCell, pCArray
7740 ) ) goto editpage_fail;
7742 pPg->nCell = nNew;
7743 pPg->nOverflow = 0;
7745 put2byte(&aData[hdr+3], pPg->nCell);
7746 put2byte(&aData[hdr+5], pData - aData);
7748 #ifdef SQLITE_DEBUG
7749 for(i=0; i<nNew && !CORRUPT_DB; i++){
7750 u8 *pCell = pCArray->apCell[i+iNew];
7751 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
7752 if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
7753 pCell = &pTmp[pCell - aData];
7755 assert( 0==memcmp(pCell, &aData[iOff],
7756 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
7758 #endif
7760 return SQLITE_OK;
7761 editpage_fail:
7762 /* Unable to edit this page. Rebuild it from scratch instead. */
7763 populateCellCache(pCArray, iNew, nNew);
7764 return rebuildPage(pCArray, iNew, nNew, pPg);
7768 #ifndef SQLITE_OMIT_QUICKBALANCE
7770 ** This version of balance() handles the common special case where
7771 ** a new entry is being inserted on the extreme right-end of the
7772 ** tree, in other words, when the new entry will become the largest
7773 ** entry in the tree.
7775 ** Instead of trying to balance the 3 right-most leaf pages, just add
7776 ** a new page to the right-hand side and put the one new entry in
7777 ** that page. This leaves the right side of the tree somewhat
7778 ** unbalanced. But odds are that we will be inserting new entries
7779 ** at the end soon afterwards so the nearly empty page will quickly
7780 ** fill up. On average.
7782 ** pPage is the leaf page which is the right-most page in the tree.
7783 ** pParent is its parent. pPage must have a single overflow entry
7784 ** which is also the right-most entry on the page.
7786 ** The pSpace buffer is used to store a temporary copy of the divider
7787 ** cell that will be inserted into pParent. Such a cell consists of a 4
7788 ** byte page number followed by a variable length integer. In other
7789 ** words, at most 13 bytes. Hence the pSpace buffer must be at
7790 ** least 13 bytes in size.
7792 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
7793 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
7794 MemPage *pNew; /* Newly allocated page */
7795 int rc; /* Return Code */
7796 Pgno pgnoNew; /* Page number of pNew */
7798 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7799 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7800 assert( pPage->nOverflow==1 );
7802 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; /* dbfuzz001.test */
7803 assert( pPage->nFree>=0 );
7804 assert( pParent->nFree>=0 );
7806 /* Allocate a new page. This page will become the right-sibling of
7807 ** pPage. Make the parent page writable, so that the new divider cell
7808 ** may be inserted. If both these operations are successful, proceed.
7810 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
7812 if( rc==SQLITE_OK ){
7814 u8 *pOut = &pSpace[4];
7815 u8 *pCell = pPage->apOvfl[0];
7816 u16 szCell = pPage->xCellSize(pPage, pCell);
7817 u8 *pStop;
7818 CellArray b;
7820 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
7821 assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
7822 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
7823 b.nCell = 1;
7824 b.pRef = pPage;
7825 b.apCell = &pCell;
7826 b.szCell = &szCell;
7827 b.apEnd[0] = pPage->aDataEnd;
7828 b.ixNx[0] = 2;
7829 rc = rebuildPage(&b, 0, 1, pNew);
7830 if( NEVER(rc) ){
7831 releasePage(pNew);
7832 return rc;
7834 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
7836 /* If this is an auto-vacuum database, update the pointer map
7837 ** with entries for the new page, and any pointer from the
7838 ** cell on the page to an overflow page. If either of these
7839 ** operations fails, the return code is set, but the contents
7840 ** of the parent page are still manipulated by thh code below.
7841 ** That is Ok, at this point the parent page is guaranteed to
7842 ** be marked as dirty. Returning an error code will cause a
7843 ** rollback, undoing any changes made to the parent page.
7845 if( ISAUTOVACUUM(pBt) ){
7846 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
7847 if( szCell>pNew->minLocal ){
7848 ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
7852 /* Create a divider cell to insert into pParent. The divider cell
7853 ** consists of a 4-byte page number (the page number of pPage) and
7854 ** a variable length key value (which must be the same value as the
7855 ** largest key on pPage).
7857 ** To find the largest key value on pPage, first find the right-most
7858 ** cell on pPage. The first two fields of this cell are the
7859 ** record-length (a variable length integer at most 32-bits in size)
7860 ** and the key value (a variable length integer, may have any value).
7861 ** The first of the while(...) loops below skips over the record-length
7862 ** field. The second while(...) loop copies the key value from the
7863 ** cell on pPage into the pSpace buffer.
7865 pCell = findCell(pPage, pPage->nCell-1);
7866 pStop = &pCell[9];
7867 while( (*(pCell++)&0x80) && pCell<pStop );
7868 pStop = &pCell[9];
7869 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
7871 /* Insert the new divider cell into pParent. */
7872 if( rc==SQLITE_OK ){
7873 rc = insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
7874 0, pPage->pgno);
7877 /* Set the right-child pointer of pParent to point to the new page. */
7878 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
7880 /* Release the reference to the new page. */
7881 releasePage(pNew);
7884 return rc;
7886 #endif /* SQLITE_OMIT_QUICKBALANCE */
7888 #if 0
7890 ** This function does not contribute anything to the operation of SQLite.
7891 ** it is sometimes activated temporarily while debugging code responsible
7892 ** for setting pointer-map entries.
7894 static int ptrmapCheckPages(MemPage **apPage, int nPage){
7895 int i, j;
7896 for(i=0; i<nPage; i++){
7897 Pgno n;
7898 u8 e;
7899 MemPage *pPage = apPage[i];
7900 BtShared *pBt = pPage->pBt;
7901 assert( pPage->isInit );
7903 for(j=0; j<pPage->nCell; j++){
7904 CellInfo info;
7905 u8 *z;
7907 z = findCell(pPage, j);
7908 pPage->xParseCell(pPage, z, &info);
7909 if( info.nLocal<info.nPayload ){
7910 Pgno ovfl = get4byte(&z[info.nSize-4]);
7911 ptrmapGet(pBt, ovfl, &e, &n);
7912 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
7914 if( !pPage->leaf ){
7915 Pgno child = get4byte(z);
7916 ptrmapGet(pBt, child, &e, &n);
7917 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7920 if( !pPage->leaf ){
7921 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
7922 ptrmapGet(pBt, child, &e, &n);
7923 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7926 return 1;
7928 #endif
7931 ** This function is used to copy the contents of the b-tree node stored
7932 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
7933 ** the pointer-map entries for each child page are updated so that the
7934 ** parent page stored in the pointer map is page pTo. If pFrom contained
7935 ** any cells with overflow page pointers, then the corresponding pointer
7936 ** map entries are also updated so that the parent page is page pTo.
7938 ** If pFrom is currently carrying any overflow cells (entries in the
7939 ** MemPage.apOvfl[] array), they are not copied to pTo.
7941 ** Before returning, page pTo is reinitialized using btreeInitPage().
7943 ** The performance of this function is not critical. It is only used by
7944 ** the balance_shallower() and balance_deeper() procedures, neither of
7945 ** which are called often under normal circumstances.
7947 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
7948 if( (*pRC)==SQLITE_OK ){
7949 BtShared * const pBt = pFrom->pBt;
7950 u8 * const aFrom = pFrom->aData;
7951 u8 * const aTo = pTo->aData;
7952 int const iFromHdr = pFrom->hdrOffset;
7953 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
7954 int rc;
7955 int iData;
7958 assert( pFrom->isInit );
7959 assert( pFrom->nFree>=iToHdr );
7960 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
7962 /* Copy the b-tree node content from page pFrom to page pTo. */
7963 iData = get2byte(&aFrom[iFromHdr+5]);
7964 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
7965 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
7967 /* Reinitialize page pTo so that the contents of the MemPage structure
7968 ** match the new data. The initialization of pTo can actually fail under
7969 ** fairly obscure circumstances, even though it is a copy of initialized
7970 ** page pFrom.
7972 pTo->isInit = 0;
7973 rc = btreeInitPage(pTo);
7974 if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo);
7975 if( rc!=SQLITE_OK ){
7976 *pRC = rc;
7977 return;
7980 /* If this is an auto-vacuum database, update the pointer-map entries
7981 ** for any b-tree or overflow pages that pTo now contains the pointers to.
7983 if( ISAUTOVACUUM(pBt) ){
7984 *pRC = setChildPtrmaps(pTo);
7990 ** This routine redistributes cells on the iParentIdx'th child of pParent
7991 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
7992 ** same amount of free space. Usually a single sibling on either side of the
7993 ** page are used in the balancing, though both siblings might come from one
7994 ** side if the page is the first or last child of its parent. If the page
7995 ** has fewer than 2 siblings (something which can only happen if the page
7996 ** is a root page or a child of a root page) then all available siblings
7997 ** participate in the balancing.
7999 ** The number of siblings of the page might be increased or decreased by
8000 ** one or two in an effort to keep pages nearly full but not over full.
8002 ** Note that when this routine is called, some of the cells on the page
8003 ** might not actually be stored in MemPage.aData[]. This can happen
8004 ** if the page is overfull. This routine ensures that all cells allocated
8005 ** to the page and its siblings fit into MemPage.aData[] before returning.
8007 ** In the course of balancing the page and its siblings, cells may be
8008 ** inserted into or removed from the parent page (pParent). Doing so
8009 ** may cause the parent page to become overfull or underfull. If this
8010 ** happens, it is the responsibility of the caller to invoke the correct
8011 ** balancing routine to fix this problem (see the balance() routine).
8013 ** If this routine fails for any reason, it might leave the database
8014 ** in a corrupted state. So if this routine fails, the database should
8015 ** be rolled back.
8017 ** The third argument to this function, aOvflSpace, is a pointer to a
8018 ** buffer big enough to hold one page. If while inserting cells into the parent
8019 ** page (pParent) the parent page becomes overfull, this buffer is
8020 ** used to store the parent's overflow cells. Because this function inserts
8021 ** a maximum of four divider cells into the parent page, and the maximum
8022 ** size of a cell stored within an internal node is always less than 1/4
8023 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
8024 ** enough for all overflow cells.
8026 ** If aOvflSpace is set to a null pointer, this function returns
8027 ** SQLITE_NOMEM.
8029 static int balance_nonroot(
8030 MemPage *pParent, /* Parent page of siblings being balanced */
8031 int iParentIdx, /* Index of "the page" in pParent */
8032 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
8033 int isRoot, /* True if pParent is a root-page */
8034 int bBulk /* True if this call is part of a bulk load */
8036 BtShared *pBt; /* The whole database */
8037 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
8038 int nNew = 0; /* Number of pages in apNew[] */
8039 int nOld; /* Number of pages in apOld[] */
8040 int i, j, k; /* Loop counters */
8041 int nxDiv; /* Next divider slot in pParent->aCell[] */
8042 int rc = SQLITE_OK; /* The return code */
8043 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
8044 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
8045 int usableSpace; /* Bytes in pPage beyond the header */
8046 int pageFlags; /* Value of pPage->aData[0] */
8047 int iSpace1 = 0; /* First unused byte of aSpace1[] */
8048 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
8049 int szScratch; /* Size of scratch memory requested */
8050 MemPage *apOld[NB]; /* pPage and up to two siblings */
8051 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
8052 u8 *pRight; /* Location in parent of right-sibling pointer */
8053 u8 *apDiv[NB-1]; /* Divider cells in pParent */
8054 int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
8055 int cntOld[NB+2]; /* Old index in b.apCell[] */
8056 int szNew[NB+2]; /* Combined size of cells placed on i-th page */
8057 u8 *aSpace1; /* Space for copies of dividers cells */
8058 Pgno pgno; /* Temp var to store a page number in */
8059 u8 abDone[NB+2]; /* True after i'th new page is populated */
8060 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
8061 CellArray b; /* Parsed information on cells being balanced */
8063 memset(abDone, 0, sizeof(abDone));
8064 memset(&b, 0, sizeof(b));
8065 pBt = pParent->pBt;
8066 assert( sqlite3_mutex_held(pBt->mutex) );
8067 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8069 /* At this point pParent may have at most one overflow cell. And if
8070 ** this overflow cell is present, it must be the cell with
8071 ** index iParentIdx. This scenario comes about when this function
8072 ** is called (indirectly) from sqlite3BtreeDelete().
8074 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
8075 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
8077 if( !aOvflSpace ){
8078 return SQLITE_NOMEM_BKPT;
8080 assert( pParent->nFree>=0 );
8082 /* Find the sibling pages to balance. Also locate the cells in pParent
8083 ** that divide the siblings. An attempt is made to find NN siblings on
8084 ** either side of pPage. More siblings are taken from one side, however,
8085 ** if there are fewer than NN siblings on the other side. If pParent
8086 ** has NB or fewer children then all children of pParent are taken.
8088 ** This loop also drops the divider cells from the parent page. This
8089 ** way, the remainder of the function does not have to deal with any
8090 ** overflow cells in the parent page, since if any existed they will
8091 ** have already been removed.
8093 i = pParent->nOverflow + pParent->nCell;
8094 if( i<2 ){
8095 nxDiv = 0;
8096 }else{
8097 assert( bBulk==0 || bBulk==1 );
8098 if( iParentIdx==0 ){
8099 nxDiv = 0;
8100 }else if( iParentIdx==i ){
8101 nxDiv = i-2+bBulk;
8102 }else{
8103 nxDiv = iParentIdx-1;
8105 i = 2-bBulk;
8107 nOld = i+1;
8108 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
8109 pRight = &pParent->aData[pParent->hdrOffset+8];
8110 }else{
8111 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
8113 pgno = get4byte(pRight);
8114 while( 1 ){
8115 if( rc==SQLITE_OK ){
8116 rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
8118 if( rc ){
8119 memset(apOld, 0, (i+1)*sizeof(MemPage*));
8120 goto balance_cleanup;
8122 if( apOld[i]->nFree<0 ){
8123 rc = btreeComputeFreeSpace(apOld[i]);
8124 if( rc ){
8125 memset(apOld, 0, (i)*sizeof(MemPage*));
8126 goto balance_cleanup;
8129 nMaxCells += apOld[i]->nCell + ArraySize(pParent->apOvfl);
8130 if( (i--)==0 ) break;
8132 if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
8133 apDiv[i] = pParent->apOvfl[0];
8134 pgno = get4byte(apDiv[i]);
8135 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
8136 pParent->nOverflow = 0;
8137 }else{
8138 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
8139 pgno = get4byte(apDiv[i]);
8140 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
8142 /* Drop the cell from the parent page. apDiv[i] still points to
8143 ** the cell within the parent, even though it has been dropped.
8144 ** This is safe because dropping a cell only overwrites the first
8145 ** four bytes of it, and this function does not need the first
8146 ** four bytes of the divider cell. So the pointer is safe to use
8147 ** later on.
8149 ** But not if we are in secure-delete mode. In secure-delete mode,
8150 ** the dropCell() routine will overwrite the entire cell with zeroes.
8151 ** In this case, temporarily copy the cell into the aOvflSpace[]
8152 ** buffer. It will be copied out again as soon as the aSpace[] buffer
8153 ** is allocated. */
8154 if( pBt->btsFlags & BTS_FAST_SECURE ){
8155 int iOff;
8157 /* If the following if() condition is not true, the db is corrupted.
8158 ** The call to dropCell() below will detect this. */
8159 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
8160 if( (iOff+szNew[i])<=(int)pBt->usableSize ){
8161 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
8162 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
8165 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
8169 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
8170 ** alignment */
8171 nMaxCells = (nMaxCells + 3)&~3;
8174 ** Allocate space for memory structures
8176 szScratch =
8177 nMaxCells*sizeof(u8*) /* b.apCell */
8178 + nMaxCells*sizeof(u16) /* b.szCell */
8179 + pBt->pageSize; /* aSpace1 */
8181 assert( szScratch<=7*(int)pBt->pageSize );
8182 b.apCell = sqlite3StackAllocRaw(0, szScratch );
8183 if( b.apCell==0 ){
8184 rc = SQLITE_NOMEM_BKPT;
8185 goto balance_cleanup;
8187 b.szCell = (u16*)&b.apCell[nMaxCells];
8188 aSpace1 = (u8*)&b.szCell[nMaxCells];
8189 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
8192 ** Load pointers to all cells on sibling pages and the divider cells
8193 ** into the local b.apCell[] array. Make copies of the divider cells
8194 ** into space obtained from aSpace1[]. The divider cells have already
8195 ** been removed from pParent.
8197 ** If the siblings are on leaf pages, then the child pointers of the
8198 ** divider cells are stripped from the cells before they are copied
8199 ** into aSpace1[]. In this way, all cells in b.apCell[] are without
8200 ** child pointers. If siblings are not leaves, then all cell in
8201 ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
8202 ** are alike.
8204 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
8205 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
8207 b.pRef = apOld[0];
8208 leafCorrection = b.pRef->leaf*4;
8209 leafData = b.pRef->intKeyLeaf;
8210 for(i=0; i<nOld; i++){
8211 MemPage *pOld = apOld[i];
8212 int limit = pOld->nCell;
8213 u8 *aData = pOld->aData;
8214 u16 maskPage = pOld->maskPage;
8215 u8 *piCell = aData + pOld->cellOffset;
8216 u8 *piEnd;
8217 VVA_ONLY( int nCellAtStart = b.nCell; )
8219 /* Verify that all sibling pages are of the same "type" (table-leaf,
8220 ** table-interior, index-leaf, or index-interior).
8222 if( pOld->aData[0]!=apOld[0]->aData[0] ){
8223 rc = SQLITE_CORRUPT_BKPT;
8224 goto balance_cleanup;
8227 /* Load b.apCell[] with pointers to all cells in pOld. If pOld
8228 ** contains overflow cells, include them in the b.apCell[] array
8229 ** in the correct spot.
8231 ** Note that when there are multiple overflow cells, it is always the
8232 ** case that they are sequential and adjacent. This invariant arises
8233 ** because multiple overflows can only occurs when inserting divider
8234 ** cells into a parent on a prior balance, and divider cells are always
8235 ** adjacent and are inserted in order. There is an assert() tagged
8236 ** with "NOTE 1" in the overflow cell insertion loop to prove this
8237 ** invariant.
8239 ** This must be done in advance. Once the balance starts, the cell
8240 ** offset section of the btree page will be overwritten and we will no
8241 ** long be able to find the cells if a pointer to each cell is not saved
8242 ** first.
8244 memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
8245 if( pOld->nOverflow>0 ){
8246 if( NEVER(limit<pOld->aiOvfl[0]) ){
8247 rc = SQLITE_CORRUPT_BKPT;
8248 goto balance_cleanup;
8250 limit = pOld->aiOvfl[0];
8251 for(j=0; j<limit; j++){
8252 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
8253 piCell += 2;
8254 b.nCell++;
8256 for(k=0; k<pOld->nOverflow; k++){
8257 assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
8258 b.apCell[b.nCell] = pOld->apOvfl[k];
8259 b.nCell++;
8262 piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
8263 while( piCell<piEnd ){
8264 assert( b.nCell<nMaxCells );
8265 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
8266 piCell += 2;
8267 b.nCell++;
8269 assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );
8271 cntOld[i] = b.nCell;
8272 if( i<nOld-1 && !leafData){
8273 u16 sz = (u16)szNew[i];
8274 u8 *pTemp;
8275 assert( b.nCell<nMaxCells );
8276 b.szCell[b.nCell] = sz;
8277 pTemp = &aSpace1[iSpace1];
8278 iSpace1 += sz;
8279 assert( sz<=pBt->maxLocal+23 );
8280 assert( iSpace1 <= (int)pBt->pageSize );
8281 memcpy(pTemp, apDiv[i], sz);
8282 b.apCell[b.nCell] = pTemp+leafCorrection;
8283 assert( leafCorrection==0 || leafCorrection==4 );
8284 b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
8285 if( !pOld->leaf ){
8286 assert( leafCorrection==0 );
8287 assert( pOld->hdrOffset==0 || CORRUPT_DB );
8288 /* The right pointer of the child page pOld becomes the left
8289 ** pointer of the divider cell */
8290 memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
8291 }else{
8292 assert( leafCorrection==4 );
8293 while( b.szCell[b.nCell]<4 ){
8294 /* Do not allow any cells smaller than 4 bytes. If a smaller cell
8295 ** does exist, pad it with 0x00 bytes. */
8296 assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
8297 assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
8298 aSpace1[iSpace1++] = 0x00;
8299 b.szCell[b.nCell]++;
8302 b.nCell++;
8307 ** Figure out the number of pages needed to hold all b.nCell cells.
8308 ** Store this number in "k". Also compute szNew[] which is the total
8309 ** size of all cells on the i-th page and cntNew[] which is the index
8310 ** in b.apCell[] of the cell that divides page i from page i+1.
8311 ** cntNew[k] should equal b.nCell.
8313 ** Values computed by this block:
8315 ** k: The total number of sibling pages
8316 ** szNew[i]: Spaced used on the i-th sibling page.
8317 ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
8318 ** the right of the i-th sibling page.
8319 ** usableSpace: Number of bytes of space available on each sibling.
8322 usableSpace = pBt->usableSize - 12 + leafCorrection;
8323 for(i=k=0; i<nOld; i++, k++){
8324 MemPage *p = apOld[i];
8325 b.apEnd[k] = p->aDataEnd;
8326 b.ixNx[k] = cntOld[i];
8327 if( k && b.ixNx[k]==b.ixNx[k-1] ){
8328 k--; /* Omit b.ixNx[] entry for child pages with no cells */
8330 if( !leafData ){
8331 k++;
8332 b.apEnd[k] = pParent->aDataEnd;
8333 b.ixNx[k] = cntOld[i]+1;
8335 assert( p->nFree>=0 );
8336 szNew[i] = usableSpace - p->nFree;
8337 for(j=0; j<p->nOverflow; j++){
8338 szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
8340 cntNew[i] = cntOld[i];
8342 k = nOld;
8343 for(i=0; i<k; i++){
8344 int sz;
8345 while( szNew[i]>usableSpace ){
8346 if( i+1>=k ){
8347 k = i+2;
8348 if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
8349 szNew[k-1] = 0;
8350 cntNew[k-1] = b.nCell;
8352 sz = 2 + cachedCellSize(&b, cntNew[i]-1);
8353 szNew[i] -= sz;
8354 if( !leafData ){
8355 if( cntNew[i]<b.nCell ){
8356 sz = 2 + cachedCellSize(&b, cntNew[i]);
8357 }else{
8358 sz = 0;
8361 szNew[i+1] += sz;
8362 cntNew[i]--;
8364 while( cntNew[i]<b.nCell ){
8365 sz = 2 + cachedCellSize(&b, cntNew[i]);
8366 if( szNew[i]+sz>usableSpace ) break;
8367 szNew[i] += sz;
8368 cntNew[i]++;
8369 if( !leafData ){
8370 if( cntNew[i]<b.nCell ){
8371 sz = 2 + cachedCellSize(&b, cntNew[i]);
8372 }else{
8373 sz = 0;
8376 szNew[i+1] -= sz;
8378 if( cntNew[i]>=b.nCell ){
8379 k = i+1;
8380 }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
8381 rc = SQLITE_CORRUPT_BKPT;
8382 goto balance_cleanup;
8387 ** The packing computed by the previous block is biased toward the siblings
8388 ** on the left side (siblings with smaller keys). The left siblings are
8389 ** always nearly full, while the right-most sibling might be nearly empty.
8390 ** The next block of code attempts to adjust the packing of siblings to
8391 ** get a better balance.
8393 ** This adjustment is more than an optimization. The packing above might
8394 ** be so out of balance as to be illegal. For example, the right-most
8395 ** sibling might be completely empty. This adjustment is not optional.
8397 for(i=k-1; i>0; i--){
8398 int szRight = szNew[i]; /* Size of sibling on the right */
8399 int szLeft = szNew[i-1]; /* Size of sibling on the left */
8400 int r; /* Index of right-most cell in left sibling */
8401 int d; /* Index of first cell to the left of right sibling */
8403 r = cntNew[i-1] - 1;
8404 d = r + 1 - leafData;
8405 (void)cachedCellSize(&b, d);
8407 int szR, szD;
8408 assert( d<nMaxCells );
8409 assert( r<nMaxCells );
8410 szR = cachedCellSize(&b, r);
8411 szD = b.szCell[d];
8412 if( szRight!=0
8413 && (bBulk || szRight+szD+2 > szLeft-(szR+(i==k-1?0:2)))){
8414 break;
8416 szRight += szD + 2;
8417 szLeft -= szR + 2;
8418 cntNew[i-1] = r;
8419 r--;
8420 d--;
8421 }while( r>=0 );
8422 szNew[i] = szRight;
8423 szNew[i-1] = szLeft;
8424 if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
8425 rc = SQLITE_CORRUPT_BKPT;
8426 goto balance_cleanup;
8430 /* Sanity check: For a non-corrupt database file one of the follwing
8431 ** must be true:
8432 ** (1) We found one or more cells (cntNew[0])>0), or
8433 ** (2) pPage is a virtual root page. A virtual root page is when
8434 ** the real root page is page 1 and we are the only child of
8435 ** that page.
8437 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
8438 TRACE(("BALANCE: old: %u(nc=%u) %u(nc=%u) %u(nc=%u)\n",
8439 apOld[0]->pgno, apOld[0]->nCell,
8440 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
8441 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
8445 ** Allocate k new pages. Reuse old pages where possible.
8447 pageFlags = apOld[0]->aData[0];
8448 for(i=0; i<k; i++){
8449 MemPage *pNew;
8450 if( i<nOld ){
8451 pNew = apNew[i] = apOld[i];
8452 apOld[i] = 0;
8453 rc = sqlite3PagerWrite(pNew->pDbPage);
8454 nNew++;
8455 if( sqlite3PagerPageRefcount(pNew->pDbPage)!=1+(i==(iParentIdx-nxDiv))
8456 && rc==SQLITE_OK
8458 rc = SQLITE_CORRUPT_BKPT;
8460 if( rc ) goto balance_cleanup;
8461 }else{
8462 assert( i>0 );
8463 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
8464 if( rc ) goto balance_cleanup;
8465 zeroPage(pNew, pageFlags);
8466 apNew[i] = pNew;
8467 nNew++;
8468 cntOld[i] = b.nCell;
8470 /* Set the pointer-map entry for the new sibling page. */
8471 if( ISAUTOVACUUM(pBt) ){
8472 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
8473 if( rc!=SQLITE_OK ){
8474 goto balance_cleanup;
8481 ** Reassign page numbers so that the new pages are in ascending order.
8482 ** This helps to keep entries in the disk file in order so that a scan
8483 ** of the table is closer to a linear scan through the file. That in turn
8484 ** helps the operating system to deliver pages from the disk more rapidly.
8486 ** An O(N*N) sort algorithm is used, but since N is never more than NB+2
8487 ** (5), that is not a performance concern.
8489 ** When NB==3, this one optimization makes the database about 25% faster
8490 ** for large insertions and deletions.
8492 for(i=0; i<nNew; i++){
8493 aPgno[i] = apNew[i]->pgno;
8494 assert( apNew[i]->pDbPage->flags & PGHDR_WRITEABLE );
8495 assert( apNew[i]->pDbPage->flags & PGHDR_DIRTY );
8497 for(i=0; i<nNew-1; i++){
8498 int iB = i;
8499 for(j=i+1; j<nNew; j++){
8500 if( apNew[j]->pgno < apNew[iB]->pgno ) iB = j;
8503 /* If apNew[i] has a page number that is bigger than any of the
8504 ** subsequence apNew[i] entries, then swap apNew[i] with the subsequent
8505 ** entry that has the smallest page number (which we know to be
8506 ** entry apNew[iB]).
8508 if( iB!=i ){
8509 Pgno pgnoA = apNew[i]->pgno;
8510 Pgno pgnoB = apNew[iB]->pgno;
8511 Pgno pgnoTemp = (PENDING_BYTE/pBt->pageSize)+1;
8512 u16 fgA = apNew[i]->pDbPage->flags;
8513 u16 fgB = apNew[iB]->pDbPage->flags;
8514 sqlite3PagerRekey(apNew[i]->pDbPage, pgnoTemp, fgB);
8515 sqlite3PagerRekey(apNew[iB]->pDbPage, pgnoA, fgA);
8516 sqlite3PagerRekey(apNew[i]->pDbPage, pgnoB, fgB);
8517 apNew[i]->pgno = pgnoB;
8518 apNew[iB]->pgno = pgnoA;
8522 TRACE(("BALANCE: new: %u(%u nc=%u) %u(%u nc=%u) %u(%u nc=%u) "
8523 "%u(%u nc=%u) %u(%u nc=%u)\n",
8524 apNew[0]->pgno, szNew[0], cntNew[0],
8525 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
8526 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
8527 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
8528 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
8529 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
8530 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
8531 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
8532 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
8535 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8536 assert( nNew>=1 && nNew<=ArraySize(apNew) );
8537 assert( apNew[nNew-1]!=0 );
8538 put4byte(pRight, apNew[nNew-1]->pgno);
8540 /* If the sibling pages are not leaves, ensure that the right-child pointer
8541 ** of the right-most new sibling page is set to the value that was
8542 ** originally in the same field of the right-most old sibling page. */
8543 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
8544 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
8545 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
8548 /* Make any required updates to pointer map entries associated with
8549 ** cells stored on sibling pages following the balance operation. Pointer
8550 ** map entries associated with divider cells are set by the insertCell()
8551 ** routine. The associated pointer map entries are:
8553 ** a) if the cell contains a reference to an overflow chain, the
8554 ** entry associated with the first page in the overflow chain, and
8556 ** b) if the sibling pages are not leaves, the child page associated
8557 ** with the cell.
8559 ** If the sibling pages are not leaves, then the pointer map entry
8560 ** associated with the right-child of each sibling may also need to be
8561 ** updated. This happens below, after the sibling pages have been
8562 ** populated, not here.
8564 if( ISAUTOVACUUM(pBt) ){
8565 MemPage *pOld;
8566 MemPage *pNew = pOld = apNew[0];
8567 int cntOldNext = pNew->nCell + pNew->nOverflow;
8568 int iNew = 0;
8569 int iOld = 0;
8571 for(i=0; i<b.nCell; i++){
8572 u8 *pCell = b.apCell[i];
8573 while( i==cntOldNext ){
8574 iOld++;
8575 assert( iOld<nNew || iOld<nOld );
8576 assert( iOld>=0 && iOld<NB );
8577 pOld = iOld<nNew ? apNew[iOld] : apOld[iOld];
8578 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
8580 if( i==cntNew[iNew] ){
8581 pNew = apNew[++iNew];
8582 if( !leafData ) continue;
8585 /* Cell pCell is destined for new sibling page pNew. Originally, it
8586 ** was either part of sibling page iOld (possibly an overflow cell),
8587 ** or else the divider cell to the left of sibling page iOld. So,
8588 ** if sibling page iOld had the same page number as pNew, and if
8589 ** pCell really was a part of sibling page iOld (not a divider or
8590 ** overflow cell), we can skip updating the pointer map entries. */
8591 if( iOld>=nNew
8592 || pNew->pgno!=aPgno[iOld]
8593 || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
8595 if( !leafCorrection ){
8596 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
8598 if( cachedCellSize(&b,i)>pNew->minLocal ){
8599 ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);
8601 if( rc ) goto balance_cleanup;
8606 /* Insert new divider cells into pParent. */
8607 for(i=0; i<nNew-1; i++){
8608 u8 *pCell;
8609 u8 *pTemp;
8610 int sz;
8611 u8 *pSrcEnd;
8612 MemPage *pNew = apNew[i];
8613 j = cntNew[i];
8615 assert( j<nMaxCells );
8616 assert( b.apCell[j]!=0 );
8617 pCell = b.apCell[j];
8618 sz = b.szCell[j] + leafCorrection;
8619 pTemp = &aOvflSpace[iOvflSpace];
8620 if( !pNew->leaf ){
8621 memcpy(&pNew->aData[8], pCell, 4);
8622 }else if( leafData ){
8623 /* If the tree is a leaf-data tree, and the siblings are leaves,
8624 ** then there is no divider cell in b.apCell[]. Instead, the divider
8625 ** cell consists of the integer key for the right-most cell of
8626 ** the sibling-page assembled above only.
8628 CellInfo info;
8629 j--;
8630 pNew->xParseCell(pNew, b.apCell[j], &info);
8631 pCell = pTemp;
8632 sz = 4 + putVarint(&pCell[4], info.nKey);
8633 pTemp = 0;
8634 }else{
8635 pCell -= 4;
8636 /* Obscure case for non-leaf-data trees: If the cell at pCell was
8637 ** previously stored on a leaf node, and its reported size was 4
8638 ** bytes, then it may actually be smaller than this
8639 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
8640 ** any cell). But it is important to pass the correct size to
8641 ** insertCell(), so reparse the cell now.
8643 ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
8644 ** and WITHOUT ROWID tables with exactly one column which is the
8645 ** primary key.
8647 if( b.szCell[j]==4 ){
8648 assert(leafCorrection==4);
8649 sz = pParent->xCellSize(pParent, pCell);
8652 iOvflSpace += sz;
8653 assert( sz<=pBt->maxLocal+23 );
8654 assert( iOvflSpace <= (int)pBt->pageSize );
8655 for(k=0; b.ixNx[k]<=j && ALWAYS(k<NB*2); k++){}
8656 pSrcEnd = b.apEnd[k];
8657 if( SQLITE_WITHIN(pSrcEnd, pCell, pCell+sz) ){
8658 rc = SQLITE_CORRUPT_BKPT;
8659 goto balance_cleanup;
8661 rc = insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno);
8662 if( rc!=SQLITE_OK ) goto balance_cleanup;
8663 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8666 /* Now update the actual sibling pages. The order in which they are updated
8667 ** is important, as this code needs to avoid disrupting any page from which
8668 ** cells may still to be read. In practice, this means:
8670 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
8671 ** then it is not safe to update page apNew[iPg] until after
8672 ** the left-hand sibling apNew[iPg-1] has been updated.
8674 ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
8675 ** then it is not safe to update page apNew[iPg] until after
8676 ** the right-hand sibling apNew[iPg+1] has been updated.
8678 ** If neither of the above apply, the page is safe to update.
8680 ** The iPg value in the following loop starts at nNew-1 goes down
8681 ** to 0, then back up to nNew-1 again, thus making two passes over
8682 ** the pages. On the initial downward pass, only condition (1) above
8683 ** needs to be tested because (2) will always be true from the previous
8684 ** step. On the upward pass, both conditions are always true, so the
8685 ** upwards pass simply processes pages that were missed on the downward
8686 ** pass.
8688 for(i=1-nNew; i<nNew; i++){
8689 int iPg = i<0 ? -i : i;
8690 assert( iPg>=0 && iPg<nNew );
8691 if( abDone[iPg] ) continue; /* Skip pages already processed */
8692 if( i>=0 /* On the upwards pass, or... */
8693 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
8695 int iNew;
8696 int iOld;
8697 int nNewCell;
8699 /* Verify condition (1): If cells are moving left, update iPg
8700 ** only after iPg-1 has already been updated. */
8701 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
8703 /* Verify condition (2): If cells are moving right, update iPg
8704 ** only after iPg+1 has already been updated. */
8705 assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
8707 if( iPg==0 ){
8708 iNew = iOld = 0;
8709 nNewCell = cntNew[0];
8710 }else{
8711 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
8712 iNew = cntNew[iPg-1] + !leafData;
8713 nNewCell = cntNew[iPg] - iNew;
8716 rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
8717 if( rc ) goto balance_cleanup;
8718 abDone[iPg]++;
8719 apNew[iPg]->nFree = usableSpace-szNew[iPg];
8720 assert( apNew[iPg]->nOverflow==0 );
8721 assert( apNew[iPg]->nCell==nNewCell );
8725 /* All pages have been processed exactly once */
8726 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
8728 assert( nOld>0 );
8729 assert( nNew>0 );
8731 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
8732 /* The root page of the b-tree now contains no cells. The only sibling
8733 ** page is the right-child of the parent. Copy the contents of the
8734 ** child page into the parent, decreasing the overall height of the
8735 ** b-tree structure by one. This is described as the "balance-shallower"
8736 ** sub-algorithm in some documentation.
8738 ** If this is an auto-vacuum database, the call to copyNodeContent()
8739 ** sets all pointer-map entries corresponding to database image pages
8740 ** for which the pointer is stored within the content being copied.
8742 ** It is critical that the child page be defragmented before being
8743 ** copied into the parent, because if the parent is page 1 then it will
8744 ** by smaller than the child due to the database header, and so all the
8745 ** free space needs to be up front.
8747 assert( nNew==1 || CORRUPT_DB );
8748 rc = defragmentPage(apNew[0], -1);
8749 testcase( rc!=SQLITE_OK );
8750 assert( apNew[0]->nFree ==
8751 (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
8752 - apNew[0]->nCell*2)
8753 || rc!=SQLITE_OK
8755 copyNodeContent(apNew[0], pParent, &rc);
8756 freePage(apNew[0], &rc);
8757 }else if( ISAUTOVACUUM(pBt) && !leafCorrection ){
8758 /* Fix the pointer map entries associated with the right-child of each
8759 ** sibling page. All other pointer map entries have already been taken
8760 ** care of. */
8761 for(i=0; i<nNew; i++){
8762 u32 key = get4byte(&apNew[i]->aData[8]);
8763 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
8767 assert( pParent->isInit );
8768 TRACE(("BALANCE: finished: old=%u new=%u cells=%u\n",
8769 nOld, nNew, b.nCell));
8771 /* Free any old pages that were not reused as new pages.
8773 for(i=nNew; i<nOld; i++){
8774 freePage(apOld[i], &rc);
8777 #if 0
8778 if( ISAUTOVACUUM(pBt) && rc==SQLITE_OK && apNew[0]->isInit ){
8779 /* The ptrmapCheckPages() contains assert() statements that verify that
8780 ** all pointer map pages are set correctly. This is helpful while
8781 ** debugging. This is usually disabled because a corrupt database may
8782 ** cause an assert() statement to fail. */
8783 ptrmapCheckPages(apNew, nNew);
8784 ptrmapCheckPages(&pParent, 1);
8786 #endif
8789 ** Cleanup before returning.
8791 balance_cleanup:
8792 sqlite3StackFree(0, b.apCell);
8793 for(i=0; i<nOld; i++){
8794 releasePage(apOld[i]);
8796 for(i=0; i<nNew; i++){
8797 releasePage(apNew[i]);
8800 return rc;
8805 ** This function is called when the root page of a b-tree structure is
8806 ** overfull (has one or more overflow pages).
8808 ** A new child page is allocated and the contents of the current root
8809 ** page, including overflow cells, are copied into the child. The root
8810 ** page is then overwritten to make it an empty page with the right-child
8811 ** pointer pointing to the new page.
8813 ** Before returning, all pointer-map entries corresponding to pages
8814 ** that the new child-page now contains pointers to are updated. The
8815 ** entry corresponding to the new right-child pointer of the root
8816 ** page is also updated.
8818 ** If successful, *ppChild is set to contain a reference to the child
8819 ** page and SQLITE_OK is returned. In this case the caller is required
8820 ** to call releasePage() on *ppChild exactly once. If an error occurs,
8821 ** an error code is returned and *ppChild is set to 0.
8823 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
8824 int rc; /* Return value from subprocedures */
8825 MemPage *pChild = 0; /* Pointer to a new child page */
8826 Pgno pgnoChild = 0; /* Page number of the new child page */
8827 BtShared *pBt = pRoot->pBt; /* The BTree */
8829 assert( pRoot->nOverflow>0 );
8830 assert( sqlite3_mutex_held(pBt->mutex) );
8832 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
8833 ** page that will become the new right-child of pPage. Copy the contents
8834 ** of the node stored on pRoot into the new child page.
8836 rc = sqlite3PagerWrite(pRoot->pDbPage);
8837 if( rc==SQLITE_OK ){
8838 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
8839 copyNodeContent(pRoot, pChild, &rc);
8840 if( ISAUTOVACUUM(pBt) ){
8841 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
8844 if( rc ){
8845 *ppChild = 0;
8846 releasePage(pChild);
8847 return rc;
8849 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
8850 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
8851 assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
8853 TRACE(("BALANCE: copy root %u into %u\n", pRoot->pgno, pChild->pgno));
8855 /* Copy the overflow cells from pRoot to pChild */
8856 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
8857 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
8858 memcpy(pChild->apOvfl, pRoot->apOvfl,
8859 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
8860 pChild->nOverflow = pRoot->nOverflow;
8862 /* Zero the contents of pRoot. Then install pChild as the right-child. */
8863 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
8864 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
8866 *ppChild = pChild;
8867 return SQLITE_OK;
8871 ** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid
8872 ** on the same B-tree as pCur.
8874 ** This can occur if a database is corrupt with two or more SQL tables
8875 ** pointing to the same b-tree. If an insert occurs on one SQL table
8876 ** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL
8877 ** table linked to the same b-tree. If the secondary insert causes a
8878 ** rebalance, that can change content out from under the cursor on the
8879 ** first SQL table, violating invariants on the first insert.
8881 static int anotherValidCursor(BtCursor *pCur){
8882 BtCursor *pOther;
8883 for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){
8884 if( pOther!=pCur
8885 && pOther->eState==CURSOR_VALID
8886 && pOther->pPage==pCur->pPage
8888 return SQLITE_CORRUPT_BKPT;
8891 return SQLITE_OK;
8895 ** The page that pCur currently points to has just been modified in
8896 ** some way. This function figures out if this modification means the
8897 ** tree needs to be balanced, and if so calls the appropriate balancing
8898 ** routine. Balancing routines are:
8900 ** balance_quick()
8901 ** balance_deeper()
8902 ** balance_nonroot()
8904 static int balance(BtCursor *pCur){
8905 int rc = SQLITE_OK;
8906 u8 aBalanceQuickSpace[13];
8907 u8 *pFree = 0;
8909 VVA_ONLY( int balance_quick_called = 0 );
8910 VVA_ONLY( int balance_deeper_called = 0 );
8912 do {
8913 int iPage;
8914 MemPage *pPage = pCur->pPage;
8916 if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
8917 if( pPage->nOverflow==0 && pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){
8918 /* No rebalance required as long as:
8919 ** (1) There are no overflow cells
8920 ** (2) The amount of free space on the page is less than 2/3rds of
8921 ** the total usable space on the page. */
8922 break;
8923 }else if( (iPage = pCur->iPage)==0 ){
8924 if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){
8925 /* The root page of the b-tree is overfull. In this case call the
8926 ** balance_deeper() function to create a new child for the root-page
8927 ** and copy the current contents of the root-page to it. The
8928 ** next iteration of the do-loop will balance the child page.
8930 assert( balance_deeper_called==0 );
8931 VVA_ONLY( balance_deeper_called++ );
8932 rc = balance_deeper(pPage, &pCur->apPage[1]);
8933 if( rc==SQLITE_OK ){
8934 pCur->iPage = 1;
8935 pCur->ix = 0;
8936 pCur->aiIdx[0] = 0;
8937 pCur->apPage[0] = pPage;
8938 pCur->pPage = pCur->apPage[1];
8939 assert( pCur->pPage->nOverflow );
8941 }else{
8942 break;
8944 }else if( sqlite3PagerPageRefcount(pPage->pDbPage)>1 ){
8945 /* The page being written is not a root page, and there is currently
8946 ** more than one reference to it. This only happens if the page is one
8947 ** of its own ancestor pages. Corruption. */
8948 rc = SQLITE_CORRUPT_BKPT;
8949 }else{
8950 MemPage * const pParent = pCur->apPage[iPage-1];
8951 int const iIdx = pCur->aiIdx[iPage-1];
8953 rc = sqlite3PagerWrite(pParent->pDbPage);
8954 if( rc==SQLITE_OK && pParent->nFree<0 ){
8955 rc = btreeComputeFreeSpace(pParent);
8957 if( rc==SQLITE_OK ){
8958 #ifndef SQLITE_OMIT_QUICKBALANCE
8959 if( pPage->intKeyLeaf
8960 && pPage->nOverflow==1
8961 && pPage->aiOvfl[0]==pPage->nCell
8962 && pParent->pgno!=1
8963 && pParent->nCell==iIdx
8965 /* Call balance_quick() to create a new sibling of pPage on which
8966 ** to store the overflow cell. balance_quick() inserts a new cell
8967 ** into pParent, which may cause pParent overflow. If this
8968 ** happens, the next iteration of the do-loop will balance pParent
8969 ** use either balance_nonroot() or balance_deeper(). Until this
8970 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
8971 ** buffer.
8973 ** The purpose of the following assert() is to check that only a
8974 ** single call to balance_quick() is made for each call to this
8975 ** function. If this were not verified, a subtle bug involving reuse
8976 ** of the aBalanceQuickSpace[] might sneak in.
8978 assert( balance_quick_called==0 );
8979 VVA_ONLY( balance_quick_called++ );
8980 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
8981 }else
8982 #endif
8984 /* In this case, call balance_nonroot() to redistribute cells
8985 ** between pPage and up to 2 of its sibling pages. This involves
8986 ** modifying the contents of pParent, which may cause pParent to
8987 ** become overfull or underfull. The next iteration of the do-loop
8988 ** will balance the parent page to correct this.
8990 ** If the parent page becomes overfull, the overflow cell or cells
8991 ** are stored in the pSpace buffer allocated immediately below.
8992 ** A subsequent iteration of the do-loop will deal with this by
8993 ** calling balance_nonroot() (balance_deeper() may be called first,
8994 ** but it doesn't deal with overflow cells - just moves them to a
8995 ** different page). Once this subsequent call to balance_nonroot()
8996 ** has completed, it is safe to release the pSpace buffer used by
8997 ** the previous call, as the overflow cell data will have been
8998 ** copied either into the body of a database page or into the new
8999 ** pSpace buffer passed to the latter call to balance_nonroot().
9001 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
9002 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
9003 pCur->hints&BTREE_BULKLOAD);
9004 if( pFree ){
9005 /* If pFree is not NULL, it points to the pSpace buffer used
9006 ** by a previous call to balance_nonroot(). Its contents are
9007 ** now stored either on real database pages or within the
9008 ** new pSpace buffer, so it may be safely freed here. */
9009 sqlite3PageFree(pFree);
9012 /* The pSpace buffer will be freed after the next call to
9013 ** balance_nonroot(), or just before this function returns, whichever
9014 ** comes first. */
9015 pFree = pSpace;
9019 pPage->nOverflow = 0;
9021 /* The next iteration of the do-loop balances the parent page. */
9022 releasePage(pPage);
9023 pCur->iPage--;
9024 assert( pCur->iPage>=0 );
9025 pCur->pPage = pCur->apPage[pCur->iPage];
9027 }while( rc==SQLITE_OK );
9029 if( pFree ){
9030 sqlite3PageFree(pFree);
9032 return rc;
9035 /* Overwrite content from pX into pDest. Only do the write if the
9036 ** content is different from what is already there.
9038 static int btreeOverwriteContent(
9039 MemPage *pPage, /* MemPage on which writing will occur */
9040 u8 *pDest, /* Pointer to the place to start writing */
9041 const BtreePayload *pX, /* Source of data to write */
9042 int iOffset, /* Offset of first byte to write */
9043 int iAmt /* Number of bytes to be written */
9045 int nData = pX->nData - iOffset;
9046 if( nData<=0 ){
9047 /* Overwritting with zeros */
9048 int i;
9049 for(i=0; i<iAmt && pDest[i]==0; i++){}
9050 if( i<iAmt ){
9051 int rc = sqlite3PagerWrite(pPage->pDbPage);
9052 if( rc ) return rc;
9053 memset(pDest + i, 0, iAmt - i);
9055 }else{
9056 if( nData<iAmt ){
9057 /* Mixed read data and zeros at the end. Make a recursive call
9058 ** to write the zeros then fall through to write the real data */
9059 int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
9060 iAmt-nData);
9061 if( rc ) return rc;
9062 iAmt = nData;
9064 if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
9065 int rc = sqlite3PagerWrite(pPage->pDbPage);
9066 if( rc ) return rc;
9067 /* In a corrupt database, it is possible for the source and destination
9068 ** buffers to overlap. This is harmless since the database is already
9069 ** corrupt but it does cause valgrind and ASAN warnings. So use
9070 ** memmove(). */
9071 memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
9074 return SQLITE_OK;
9078 ** Overwrite the cell that cursor pCur is pointing to with fresh content
9079 ** contained in pX. In this variant, pCur is pointing to an overflow
9080 ** cell.
9082 static SQLITE_NOINLINE int btreeOverwriteOverflowCell(
9083 BtCursor *pCur, /* Cursor pointing to cell to ovewrite */
9084 const BtreePayload *pX /* Content to write into the cell */
9086 int iOffset; /* Next byte of pX->pData to write */
9087 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
9088 int rc; /* Return code */
9089 MemPage *pPage = pCur->pPage; /* Page being written */
9090 BtShared *pBt; /* Btree */
9091 Pgno ovflPgno; /* Next overflow page to write */
9092 u32 ovflPageSize; /* Size to write on overflow page */
9094 assert( pCur->info.nLocal<nTotal ); /* pCur is an overflow cell */
9096 /* Overwrite the local portion first */
9097 rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
9098 0, pCur->info.nLocal);
9099 if( rc ) return rc;
9101 /* Now overwrite the overflow pages */
9102 iOffset = pCur->info.nLocal;
9103 assert( nTotal>=0 );
9104 assert( iOffset>=0 );
9105 ovflPgno = get4byte(pCur->info.pPayload + iOffset);
9106 pBt = pPage->pBt;
9107 ovflPageSize = pBt->usableSize - 4;
9109 rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
9110 if( rc ) return rc;
9111 if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 || pPage->isInit ){
9112 rc = SQLITE_CORRUPT_BKPT;
9113 }else{
9114 if( iOffset+ovflPageSize<(u32)nTotal ){
9115 ovflPgno = get4byte(pPage->aData);
9116 }else{
9117 ovflPageSize = nTotal - iOffset;
9119 rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
9120 iOffset, ovflPageSize);
9122 sqlite3PagerUnref(pPage->pDbPage);
9123 if( rc ) return rc;
9124 iOffset += ovflPageSize;
9125 }while( iOffset<nTotal );
9126 return SQLITE_OK;
9130 ** Overwrite the cell that cursor pCur is pointing to with fresh content
9131 ** contained in pX.
9133 static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
9134 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
9135 MemPage *pPage = pCur->pPage; /* Page being written */
9137 if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd
9138 || pCur->info.pPayload < pPage->aData + pPage->cellOffset
9140 return SQLITE_CORRUPT_BKPT;
9142 if( pCur->info.nLocal==nTotal ){
9143 /* The entire cell is local */
9144 return btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
9145 0, pCur->info.nLocal);
9146 }else{
9147 /* The cell contains overflow content */
9148 return btreeOverwriteOverflowCell(pCur, pX);
9154 ** Insert a new record into the BTree. The content of the new record
9155 ** is described by the pX object. The pCur cursor is used only to
9156 ** define what table the record should be inserted into, and is left
9157 ** pointing at a random location.
9159 ** For a table btree (used for rowid tables), only the pX.nKey value of
9160 ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
9161 ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
9162 ** hold the content of the row.
9164 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
9165 ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
9166 ** pX.pData,nData,nZero fields must be zero.
9168 ** If the seekResult parameter is non-zero, then a successful call to
9169 ** sqlite3BtreeIndexMoveto() to seek cursor pCur to (pKey,nKey) has already
9170 ** been performed. In other words, if seekResult!=0 then the cursor
9171 ** is currently pointing to a cell that will be adjacent to the cell
9172 ** to be inserted. If seekResult<0 then pCur points to a cell that is
9173 ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
9174 ** that is larger than (pKey,nKey).
9176 ** If seekResult==0, that means pCur is pointing at some unknown location.
9177 ** In that case, this routine must seek the cursor to the correct insertion
9178 ** point for (pKey,nKey) before doing the insertion. For index btrees,
9179 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
9180 ** key values and pX->aMem can be used instead of pX->pKey to avoid having
9181 ** to decode the key.
9183 int sqlite3BtreeInsert(
9184 BtCursor *pCur, /* Insert data into the table of this cursor */
9185 const BtreePayload *pX, /* Content of the row to be inserted */
9186 int flags, /* True if this is likely an append */
9187 int seekResult /* Result of prior IndexMoveto() call */
9189 int rc;
9190 int loc = seekResult; /* -1: before desired location +1: after */
9191 int szNew = 0;
9192 int idx;
9193 MemPage *pPage;
9194 Btree *p = pCur->pBtree;
9195 unsigned char *oldCell;
9196 unsigned char *newCell = 0;
9198 assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND|BTREE_PREFORMAT))==flags );
9199 assert( (flags & BTREE_PREFORMAT)==0 || seekResult || pCur->pKeyInfo==0 );
9201 /* Save the positions of any other cursors open on this table.
9203 ** In some cases, the call to btreeMoveto() below is a no-op. For
9204 ** example, when inserting data into a table with auto-generated integer
9205 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
9206 ** integer key to use. It then calls this function to actually insert the
9207 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
9208 ** that the cursor is already where it needs to be and returns without
9209 ** doing any work. To avoid thwarting these optimizations, it is important
9210 ** not to clear the cursor here.
9212 if( pCur->curFlags & BTCF_Multiple ){
9213 rc = saveAllCursors(p->pBt, pCur->pgnoRoot, pCur);
9214 if( rc ) return rc;
9215 if( loc && pCur->iPage<0 ){
9216 /* This can only happen if the schema is corrupt such that there is more
9217 ** than one table or index with the same root page as used by the cursor.
9218 ** Which can only happen if the SQLITE_NoSchemaError flag was set when
9219 ** the schema was loaded. This cannot be asserted though, as a user might
9220 ** set the flag, load the schema, and then unset the flag. */
9221 return SQLITE_CORRUPT_BKPT;
9225 /* Ensure that the cursor is not in the CURSOR_FAULT state and that it
9226 ** points to a valid cell.
9228 if( pCur->eState>=CURSOR_REQUIRESEEK ){
9229 testcase( pCur->eState==CURSOR_REQUIRESEEK );
9230 testcase( pCur->eState==CURSOR_FAULT );
9231 rc = moveToRoot(pCur);
9232 if( rc && rc!=SQLITE_EMPTY ) return rc;
9235 assert( cursorOwnsBtShared(pCur) );
9236 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
9237 && p->pBt->inTransaction==TRANS_WRITE
9238 && (p->pBt->btsFlags & BTS_READ_ONLY)==0 );
9239 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
9241 /* Assert that the caller has been consistent. If this cursor was opened
9242 ** expecting an index b-tree, then the caller should be inserting blob
9243 ** keys with no associated data. If the cursor was opened expecting an
9244 ** intkey table, the caller should be inserting integer keys with a
9245 ** blob of associated data. */
9246 assert( (flags & BTREE_PREFORMAT) || (pX->pKey==0)==(pCur->pKeyInfo==0) );
9248 if( pCur->pKeyInfo==0 ){
9249 assert( pX->pKey==0 );
9250 /* If this is an insert into a table b-tree, invalidate any incrblob
9251 ** cursors open on the row being replaced */
9252 if( p->hasIncrblobCur ){
9253 invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
9256 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
9257 ** to a row with the same key as the new entry being inserted.
9259 #ifdef SQLITE_DEBUG
9260 if( flags & BTREE_SAVEPOSITION ){
9261 assert( pCur->curFlags & BTCF_ValidNKey );
9262 assert( pX->nKey==pCur->info.nKey );
9263 assert( loc==0 );
9265 #endif
9267 /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
9268 ** that the cursor is not pointing to a row to be overwritten.
9269 ** So do a complete check.
9271 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
9272 /* The cursor is pointing to the entry that is to be
9273 ** overwritten */
9274 assert( pX->nData>=0 && pX->nZero>=0 );
9275 if( pCur->info.nSize!=0
9276 && pCur->info.nPayload==(u32)pX->nData+pX->nZero
9278 /* New entry is the same size as the old. Do an overwrite */
9279 return btreeOverwriteCell(pCur, pX);
9281 assert( loc==0 );
9282 }else if( loc==0 ){
9283 /* The cursor is *not* pointing to the cell to be overwritten, nor
9284 ** to an adjacent cell. Move the cursor so that it is pointing either
9285 ** to the cell to be overwritten or an adjacent cell.
9287 rc = sqlite3BtreeTableMoveto(pCur, pX->nKey,
9288 (flags & BTREE_APPEND)!=0, &loc);
9289 if( rc ) return rc;
9291 }else{
9292 /* This is an index or a WITHOUT ROWID table */
9294 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
9295 ** to a row with the same key as the new entry being inserted.
9297 assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
9299 /* If the cursor is not already pointing either to the cell to be
9300 ** overwritten, or if a new cell is being inserted, if the cursor is
9301 ** not pointing to an immediately adjacent cell, then move the cursor
9302 ** so that it does.
9304 if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
9305 if( pX->nMem ){
9306 UnpackedRecord r;
9307 r.pKeyInfo = pCur->pKeyInfo;
9308 r.aMem = pX->aMem;
9309 r.nField = pX->nMem;
9310 r.default_rc = 0;
9311 r.eqSeen = 0;
9312 rc = sqlite3BtreeIndexMoveto(pCur, &r, &loc);
9313 }else{
9314 rc = btreeMoveto(pCur, pX->pKey, pX->nKey,
9315 (flags & BTREE_APPEND)!=0, &loc);
9317 if( rc ) return rc;
9320 /* If the cursor is currently pointing to an entry to be overwritten
9321 ** and the new content is the same as as the old, then use the
9322 ** overwrite optimization.
9324 if( loc==0 ){
9325 getCellInfo(pCur);
9326 if( pCur->info.nKey==pX->nKey ){
9327 BtreePayload x2;
9328 x2.pData = pX->pKey;
9329 x2.nData = pX->nKey;
9330 x2.nZero = 0;
9331 return btreeOverwriteCell(pCur, &x2);
9335 assert( pCur->eState==CURSOR_VALID
9336 || (pCur->eState==CURSOR_INVALID && loc) || CORRUPT_DB );
9338 pPage = pCur->pPage;
9339 assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) );
9340 assert( pPage->leaf || !pPage->intKey );
9341 if( pPage->nFree<0 ){
9342 if( NEVER(pCur->eState>CURSOR_INVALID) ){
9343 /* ^^^^^--- due to the moveToRoot() call above */
9344 rc = SQLITE_CORRUPT_BKPT;
9345 }else{
9346 rc = btreeComputeFreeSpace(pPage);
9348 if( rc ) return rc;
9351 TRACE(("INSERT: table=%u nkey=%lld ndata=%u page=%u %s\n",
9352 pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
9353 loc==0 ? "overwrite" : "new entry"));
9354 assert( pPage->isInit || CORRUPT_DB );
9355 newCell = p->pBt->pTmpSpace;
9356 assert( newCell!=0 );
9357 assert( BTREE_PREFORMAT==OPFLAG_PREFORMAT );
9358 if( flags & BTREE_PREFORMAT ){
9359 rc = SQLITE_OK;
9360 szNew = p->pBt->nPreformatSize;
9361 if( szNew<4 ) szNew = 4;
9362 if( ISAUTOVACUUM(p->pBt) && szNew>pPage->maxLocal ){
9363 CellInfo info;
9364 pPage->xParseCell(pPage, newCell, &info);
9365 if( info.nPayload!=info.nLocal ){
9366 Pgno ovfl = get4byte(&newCell[szNew-4]);
9367 ptrmapPut(p->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, &rc);
9368 if( NEVER(rc) ) goto end_insert;
9371 }else{
9372 rc = fillInCell(pPage, newCell, pX, &szNew);
9373 if( rc ) goto end_insert;
9375 assert( szNew==pPage->xCellSize(pPage, newCell) );
9376 assert( szNew <= MX_CELL_SIZE(p->pBt) );
9377 idx = pCur->ix;
9378 pCur->info.nSize = 0;
9379 if( loc==0 ){
9380 CellInfo info;
9381 assert( idx>=0 );
9382 if( idx>=pPage->nCell ){
9383 return SQLITE_CORRUPT_BKPT;
9385 rc = sqlite3PagerWrite(pPage->pDbPage);
9386 if( rc ){
9387 goto end_insert;
9389 oldCell = findCell(pPage, idx);
9390 if( !pPage->leaf ){
9391 memcpy(newCell, oldCell, 4);
9393 BTREE_CLEAR_CELL(rc, pPage, oldCell, info);
9394 testcase( pCur->curFlags & BTCF_ValidOvfl );
9395 invalidateOverflowCache(pCur);
9396 if( info.nSize==szNew && info.nLocal==info.nPayload
9397 && (!ISAUTOVACUUM(p->pBt) || szNew<pPage->minLocal)
9399 /* Overwrite the old cell with the new if they are the same size.
9400 ** We could also try to do this if the old cell is smaller, then add
9401 ** the leftover space to the free list. But experiments show that
9402 ** doing that is no faster then skipping this optimization and just
9403 ** calling dropCell() and insertCell().
9405 ** This optimization cannot be used on an autovacuum database if the
9406 ** new entry uses overflow pages, as the insertCell() call below is
9407 ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
9408 assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
9409 if( oldCell < pPage->aData+pPage->hdrOffset+10 ){
9410 return SQLITE_CORRUPT_BKPT;
9412 if( oldCell+szNew > pPage->aDataEnd ){
9413 return SQLITE_CORRUPT_BKPT;
9415 memcpy(oldCell, newCell, szNew);
9416 return SQLITE_OK;
9418 dropCell(pPage, idx, info.nSize, &rc);
9419 if( rc ) goto end_insert;
9420 }else if( loc<0 && pPage->nCell>0 ){
9421 assert( pPage->leaf );
9422 idx = ++pCur->ix;
9423 pCur->curFlags &= ~BTCF_ValidNKey;
9424 }else{
9425 assert( pPage->leaf );
9427 rc = insertCellFast(pPage, idx, newCell, szNew);
9428 assert( pPage->nOverflow==0 || rc==SQLITE_OK );
9429 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
9431 /* If no error has occurred and pPage has an overflow cell, call balance()
9432 ** to redistribute the cells within the tree. Since balance() may move
9433 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
9434 ** variables.
9436 ** Previous versions of SQLite called moveToRoot() to move the cursor
9437 ** back to the root page as balance() used to invalidate the contents
9438 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
9439 ** set the cursor state to "invalid". This makes common insert operations
9440 ** slightly faster.
9442 ** There is a subtle but important optimization here too. When inserting
9443 ** multiple records into an intkey b-tree using a single cursor (as can
9444 ** happen while processing an "INSERT INTO ... SELECT" statement), it
9445 ** is advantageous to leave the cursor pointing to the last entry in
9446 ** the b-tree if possible. If the cursor is left pointing to the last
9447 ** entry in the table, and the next row inserted has an integer key
9448 ** larger than the largest existing key, it is possible to insert the
9449 ** row without seeking the cursor. This can be a big performance boost.
9451 if( pPage->nOverflow ){
9452 assert( rc==SQLITE_OK );
9453 pCur->curFlags &= ~(BTCF_ValidNKey);
9454 rc = balance(pCur);
9456 /* Must make sure nOverflow is reset to zero even if the balance()
9457 ** fails. Internal data structure corruption will result otherwise.
9458 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
9459 ** from trying to save the current position of the cursor. */
9460 pCur->pPage->nOverflow = 0;
9461 pCur->eState = CURSOR_INVALID;
9462 if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
9463 btreeReleaseAllCursorPages(pCur);
9464 if( pCur->pKeyInfo ){
9465 assert( pCur->pKey==0 );
9466 pCur->pKey = sqlite3Malloc( pX->nKey );
9467 if( pCur->pKey==0 ){
9468 rc = SQLITE_NOMEM;
9469 }else{
9470 memcpy(pCur->pKey, pX->pKey, pX->nKey);
9473 pCur->eState = CURSOR_REQUIRESEEK;
9474 pCur->nKey = pX->nKey;
9477 assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
9479 end_insert:
9480 return rc;
9484 ** This function is used as part of copying the current row from cursor
9485 ** pSrc into cursor pDest. If the cursors are open on intkey tables, then
9486 ** parameter iKey is used as the rowid value when the record is copied
9487 ** into pDest. Otherwise, the record is copied verbatim.
9489 ** This function does not actually write the new value to cursor pDest.
9490 ** Instead, it creates and populates any required overflow pages and
9491 ** writes the data for the new cell into the BtShared.pTmpSpace buffer
9492 ** for the destination database. The size of the cell, in bytes, is left
9493 ** in BtShared.nPreformatSize. The caller completes the insertion by
9494 ** calling sqlite3BtreeInsert() with the BTREE_PREFORMAT flag specified.
9496 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
9498 int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 iKey){
9499 BtShared *pBt = pDest->pBt;
9500 u8 *aOut = pBt->pTmpSpace; /* Pointer to next output buffer */
9501 const u8 *aIn; /* Pointer to next input buffer */
9502 u32 nIn; /* Size of input buffer aIn[] */
9503 u32 nRem; /* Bytes of data still to copy */
9505 getCellInfo(pSrc);
9506 if( pSrc->info.nPayload<0x80 ){
9507 *(aOut++) = pSrc->info.nPayload;
9508 }else{
9509 aOut += sqlite3PutVarint(aOut, pSrc->info.nPayload);
9511 if( pDest->pKeyInfo==0 ) aOut += putVarint(aOut, iKey);
9512 nIn = pSrc->info.nLocal;
9513 aIn = pSrc->info.pPayload;
9514 if( aIn+nIn>pSrc->pPage->aDataEnd ){
9515 return SQLITE_CORRUPT_BKPT;
9517 nRem = pSrc->info.nPayload;
9518 if( nIn==nRem && nIn<pDest->pPage->maxLocal ){
9519 memcpy(aOut, aIn, nIn);
9520 pBt->nPreformatSize = nIn + (aOut - pBt->pTmpSpace);
9521 return SQLITE_OK;
9522 }else{
9523 int rc = SQLITE_OK;
9524 Pager *pSrcPager = pSrc->pBt->pPager;
9525 u8 *pPgnoOut = 0;
9526 Pgno ovflIn = 0;
9527 DbPage *pPageIn = 0;
9528 MemPage *pPageOut = 0;
9529 u32 nOut; /* Size of output buffer aOut[] */
9531 nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload);
9532 pBt->nPreformatSize = nOut + (aOut - pBt->pTmpSpace);
9533 if( nOut<pSrc->info.nPayload ){
9534 pPgnoOut = &aOut[nOut];
9535 pBt->nPreformatSize += 4;
9538 if( nRem>nIn ){
9539 if( aIn+nIn+4>pSrc->pPage->aDataEnd ){
9540 return SQLITE_CORRUPT_BKPT;
9542 ovflIn = get4byte(&pSrc->info.pPayload[nIn]);
9545 do {
9546 nRem -= nOut;
9548 assert( nOut>0 );
9549 if( nIn>0 ){
9550 int nCopy = MIN(nOut, nIn);
9551 memcpy(aOut, aIn, nCopy);
9552 nOut -= nCopy;
9553 nIn -= nCopy;
9554 aOut += nCopy;
9555 aIn += nCopy;
9557 if( nOut>0 ){
9558 sqlite3PagerUnref(pPageIn);
9559 pPageIn = 0;
9560 rc = sqlite3PagerGet(pSrcPager, ovflIn, &pPageIn, PAGER_GET_READONLY);
9561 if( rc==SQLITE_OK ){
9562 aIn = (const u8*)sqlite3PagerGetData(pPageIn);
9563 ovflIn = get4byte(aIn);
9564 aIn += 4;
9565 nIn = pSrc->pBt->usableSize - 4;
9568 }while( rc==SQLITE_OK && nOut>0 );
9570 if( rc==SQLITE_OK && nRem>0 && ALWAYS(pPgnoOut) ){
9571 Pgno pgnoNew;
9572 MemPage *pNew = 0;
9573 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
9574 put4byte(pPgnoOut, pgnoNew);
9575 if( ISAUTOVACUUM(pBt) && pPageOut ){
9576 ptrmapPut(pBt, pgnoNew, PTRMAP_OVERFLOW2, pPageOut->pgno, &rc);
9578 releasePage(pPageOut);
9579 pPageOut = pNew;
9580 if( pPageOut ){
9581 pPgnoOut = pPageOut->aData;
9582 put4byte(pPgnoOut, 0);
9583 aOut = &pPgnoOut[4];
9584 nOut = MIN(pBt->usableSize - 4, nRem);
9587 }while( nRem>0 && rc==SQLITE_OK );
9589 releasePage(pPageOut);
9590 sqlite3PagerUnref(pPageIn);
9591 return rc;
9596 ** Delete the entry that the cursor is pointing to.
9598 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
9599 ** the cursor is left pointing at an arbitrary location after the delete.
9600 ** But if that bit is set, then the cursor is left in a state such that
9601 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
9602 ** as it would have been on if the call to BtreeDelete() had been omitted.
9604 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
9605 ** associated with a single table entry and its indexes. Only one of those
9606 ** deletes is considered the "primary" delete. The primary delete occurs
9607 ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
9608 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
9609 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
9610 ** but which might be used by alternative storage engines.
9612 int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
9613 Btree *p = pCur->pBtree;
9614 BtShared *pBt = p->pBt;
9615 int rc; /* Return code */
9616 MemPage *pPage; /* Page to delete cell from */
9617 unsigned char *pCell; /* Pointer to cell to delete */
9618 int iCellIdx; /* Index of cell to delete */
9619 int iCellDepth; /* Depth of node containing pCell */
9620 CellInfo info; /* Size of the cell being deleted */
9621 u8 bPreserve; /* Keep cursor valid. 2 for CURSOR_SKIPNEXT */
9623 assert( cursorOwnsBtShared(pCur) );
9624 assert( pBt->inTransaction==TRANS_WRITE );
9625 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9626 assert( pCur->curFlags & BTCF_WriteFlag );
9627 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
9628 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
9629 assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
9630 if( pCur->eState!=CURSOR_VALID ){
9631 if( pCur->eState>=CURSOR_REQUIRESEEK ){
9632 rc = btreeRestoreCursorPosition(pCur);
9633 assert( rc!=SQLITE_OK || CORRUPT_DB || pCur->eState==CURSOR_VALID );
9634 if( rc || pCur->eState!=CURSOR_VALID ) return rc;
9635 }else{
9636 return SQLITE_CORRUPT_BKPT;
9639 assert( pCur->eState==CURSOR_VALID );
9641 iCellDepth = pCur->iPage;
9642 iCellIdx = pCur->ix;
9643 pPage = pCur->pPage;
9644 if( pPage->nCell<=iCellIdx ){
9645 return SQLITE_CORRUPT_BKPT;
9647 pCell = findCell(pPage, iCellIdx);
9648 if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ){
9649 return SQLITE_CORRUPT_BKPT;
9651 if( pCell<&pPage->aCellIdx[pPage->nCell] ){
9652 return SQLITE_CORRUPT_BKPT;
9655 /* If the BTREE_SAVEPOSITION bit is on, then the cursor position must
9656 ** be preserved following this delete operation. If the current delete
9657 ** will cause a b-tree rebalance, then this is done by saving the cursor
9658 ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
9659 ** returning.
9661 ** If the current delete will not cause a rebalance, then the cursor
9662 ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
9663 ** before or after the deleted entry.
9665 ** The bPreserve value records which path is required:
9667 ** bPreserve==0 Not necessary to save the cursor position
9668 ** bPreserve==1 Use CURSOR_REQUIRESEEK to save the cursor position
9669 ** bPreserve==2 Cursor won't move. Set CURSOR_SKIPNEXT.
9671 bPreserve = (flags & BTREE_SAVEPOSITION)!=0;
9672 if( bPreserve ){
9673 if( !pPage->leaf
9674 || (pPage->nFree+pPage->xCellSize(pPage,pCell)+2) >
9675 (int)(pBt->usableSize*2/3)
9676 || pPage->nCell==1 /* See dbfuzz001.test for a test case */
9678 /* A b-tree rebalance will be required after deleting this entry.
9679 ** Save the cursor key. */
9680 rc = saveCursorKey(pCur);
9681 if( rc ) return rc;
9682 }else{
9683 bPreserve = 2;
9687 /* If the page containing the entry to delete is not a leaf page, move
9688 ** the cursor to the largest entry in the tree that is smaller than
9689 ** the entry being deleted. This cell will replace the cell being deleted
9690 ** from the internal node. The 'previous' entry is used for this instead
9691 ** of the 'next' entry, as the previous entry is always a part of the
9692 ** sub-tree headed by the child page of the cell being deleted. This makes
9693 ** balancing the tree following the delete operation easier. */
9694 if( !pPage->leaf ){
9695 rc = sqlite3BtreePrevious(pCur, 0);
9696 assert( rc!=SQLITE_DONE );
9697 if( rc ) return rc;
9700 /* Save the positions of any other cursors open on this table before
9701 ** making any modifications. */
9702 if( pCur->curFlags & BTCF_Multiple ){
9703 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
9704 if( rc ) return rc;
9707 /* If this is a delete operation to remove a row from a table b-tree,
9708 ** invalidate any incrblob cursors open on the row being deleted. */
9709 if( pCur->pKeyInfo==0 && p->hasIncrblobCur ){
9710 invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
9713 /* Make the page containing the entry to be deleted writable. Then free any
9714 ** overflow pages associated with the entry and finally remove the cell
9715 ** itself from within the page. */
9716 rc = sqlite3PagerWrite(pPage->pDbPage);
9717 if( rc ) return rc;
9718 BTREE_CLEAR_CELL(rc, pPage, pCell, info);
9719 dropCell(pPage, iCellIdx, info.nSize, &rc);
9720 if( rc ) return rc;
9722 /* If the cell deleted was not located on a leaf page, then the cursor
9723 ** is currently pointing to the largest entry in the sub-tree headed
9724 ** by the child-page of the cell that was just deleted from an internal
9725 ** node. The cell from the leaf node needs to be moved to the internal
9726 ** node to replace the deleted cell. */
9727 if( !pPage->leaf ){
9728 MemPage *pLeaf = pCur->pPage;
9729 int nCell;
9730 Pgno n;
9731 unsigned char *pTmp;
9733 if( pLeaf->nFree<0 ){
9734 rc = btreeComputeFreeSpace(pLeaf);
9735 if( rc ) return rc;
9737 if( iCellDepth<pCur->iPage-1 ){
9738 n = pCur->apPage[iCellDepth+1]->pgno;
9739 }else{
9740 n = pCur->pPage->pgno;
9742 pCell = findCell(pLeaf, pLeaf->nCell-1);
9743 if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
9744 nCell = pLeaf->xCellSize(pLeaf, pCell);
9745 assert( MX_CELL_SIZE(pBt) >= nCell );
9746 pTmp = pBt->pTmpSpace;
9747 assert( pTmp!=0 );
9748 rc = sqlite3PagerWrite(pLeaf->pDbPage);
9749 if( rc==SQLITE_OK ){
9750 rc = insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n);
9752 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
9753 if( rc ) return rc;
9756 /* Balance the tree. If the entry deleted was located on a leaf page,
9757 ** then the cursor still points to that page. In this case the first
9758 ** call to balance() repairs the tree, and the if(...) condition is
9759 ** never true.
9761 ** Otherwise, if the entry deleted was on an internal node page, then
9762 ** pCur is pointing to the leaf page from which a cell was removed to
9763 ** replace the cell deleted from the internal node. This is slightly
9764 ** tricky as the leaf node may be underfull, and the internal node may
9765 ** be either under or overfull. In this case run the balancing algorithm
9766 ** on the leaf node first. If the balance proceeds far enough up the
9767 ** tree that we can be sure that any problem in the internal node has
9768 ** been corrected, so be it. Otherwise, after balancing the leaf node,
9769 ** walk the cursor up the tree to the internal node and balance it as
9770 ** well. */
9771 assert( pCur->pPage->nOverflow==0 );
9772 assert( pCur->pPage->nFree>=0 );
9773 if( pCur->pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){
9774 /* Optimization: If the free space is less than 2/3rds of the page,
9775 ** then balance() will always be a no-op. No need to invoke it. */
9776 rc = SQLITE_OK;
9777 }else{
9778 rc = balance(pCur);
9780 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
9781 releasePageNotNull(pCur->pPage);
9782 pCur->iPage--;
9783 while( pCur->iPage>iCellDepth ){
9784 releasePage(pCur->apPage[pCur->iPage--]);
9786 pCur->pPage = pCur->apPage[pCur->iPage];
9787 rc = balance(pCur);
9790 if( rc==SQLITE_OK ){
9791 if( bPreserve>1 ){
9792 assert( (pCur->iPage==iCellDepth || CORRUPT_DB) );
9793 assert( pPage==pCur->pPage || CORRUPT_DB );
9794 assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
9795 pCur->eState = CURSOR_SKIPNEXT;
9796 if( iCellIdx>=pPage->nCell ){
9797 pCur->skipNext = -1;
9798 pCur->ix = pPage->nCell-1;
9799 }else{
9800 pCur->skipNext = 1;
9802 }else{
9803 rc = moveToRoot(pCur);
9804 if( bPreserve ){
9805 btreeReleaseAllCursorPages(pCur);
9806 pCur->eState = CURSOR_REQUIRESEEK;
9808 if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
9811 return rc;
9815 ** Create a new BTree table. Write into *piTable the page
9816 ** number for the root page of the new table.
9818 ** The type of type is determined by the flags parameter. Only the
9819 ** following values of flags are currently in use. Other values for
9820 ** flags might not work:
9822 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
9823 ** BTREE_ZERODATA Used for SQL indices
9825 static int btreeCreateTable(Btree *p, Pgno *piTable, int createTabFlags){
9826 BtShared *pBt = p->pBt;
9827 MemPage *pRoot;
9828 Pgno pgnoRoot;
9829 int rc;
9830 int ptfFlags; /* Page-type flage for the root page of new table */
9832 assert( sqlite3BtreeHoldsMutex(p) );
9833 assert( pBt->inTransaction==TRANS_WRITE );
9834 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9836 #ifdef SQLITE_OMIT_AUTOVACUUM
9837 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9838 if( rc ){
9839 return rc;
9841 #else
9842 if( pBt->autoVacuum ){
9843 Pgno pgnoMove; /* Move a page here to make room for the root-page */
9844 MemPage *pPageMove; /* The page to move to. */
9846 /* Creating a new table may probably require moving an existing database
9847 ** to make room for the new tables root page. In case this page turns
9848 ** out to be an overflow page, delete all overflow page-map caches
9849 ** held by open cursors.
9851 invalidateAllOverflowCache(pBt);
9853 /* Read the value of meta[3] from the database to determine where the
9854 ** root page of the new table should go. meta[3] is the largest root-page
9855 ** created so far, so the new root-page is (meta[3]+1).
9857 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
9858 if( pgnoRoot>btreePagecount(pBt) ){
9859 return SQLITE_CORRUPT_BKPT;
9861 pgnoRoot++;
9863 /* The new root-page may not be allocated on a pointer-map page, or the
9864 ** PENDING_BYTE page.
9866 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
9867 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
9868 pgnoRoot++;
9870 assert( pgnoRoot>=3 );
9872 /* Allocate a page. The page that currently resides at pgnoRoot will
9873 ** be moved to the allocated page (unless the allocated page happens
9874 ** to reside at pgnoRoot).
9876 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
9877 if( rc!=SQLITE_OK ){
9878 return rc;
9881 if( pgnoMove!=pgnoRoot ){
9882 /* pgnoRoot is the page that will be used for the root-page of
9883 ** the new table (assuming an error did not occur). But we were
9884 ** allocated pgnoMove. If required (i.e. if it was not allocated
9885 ** by extending the file), the current page at position pgnoMove
9886 ** is already journaled.
9888 u8 eType = 0;
9889 Pgno iPtrPage = 0;
9891 /* Save the positions of any open cursors. This is required in
9892 ** case they are holding a reference to an xFetch reference
9893 ** corresponding to page pgnoRoot. */
9894 rc = saveAllCursors(pBt, 0, 0);
9895 releasePage(pPageMove);
9896 if( rc!=SQLITE_OK ){
9897 return rc;
9900 /* Move the page currently at pgnoRoot to pgnoMove. */
9901 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9902 if( rc!=SQLITE_OK ){
9903 return rc;
9905 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
9906 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
9907 rc = SQLITE_CORRUPT_BKPT;
9909 if( rc!=SQLITE_OK ){
9910 releasePage(pRoot);
9911 return rc;
9913 assert( eType!=PTRMAP_ROOTPAGE );
9914 assert( eType!=PTRMAP_FREEPAGE );
9915 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
9916 releasePage(pRoot);
9918 /* Obtain the page at pgnoRoot */
9919 if( rc!=SQLITE_OK ){
9920 return rc;
9922 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9923 if( rc!=SQLITE_OK ){
9924 return rc;
9926 rc = sqlite3PagerWrite(pRoot->pDbPage);
9927 if( rc!=SQLITE_OK ){
9928 releasePage(pRoot);
9929 return rc;
9931 }else{
9932 pRoot = pPageMove;
9935 /* Update the pointer-map and meta-data with the new root-page number. */
9936 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
9937 if( rc ){
9938 releasePage(pRoot);
9939 return rc;
9942 /* When the new root page was allocated, page 1 was made writable in
9943 ** order either to increase the database filesize, or to decrement the
9944 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
9946 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
9947 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
9948 if( NEVER(rc) ){
9949 releasePage(pRoot);
9950 return rc;
9953 }else{
9954 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9955 if( rc ) return rc;
9957 #endif
9958 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
9959 if( createTabFlags & BTREE_INTKEY ){
9960 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
9961 }else{
9962 ptfFlags = PTF_ZERODATA | PTF_LEAF;
9964 zeroPage(pRoot, ptfFlags);
9965 sqlite3PagerUnref(pRoot->pDbPage);
9966 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
9967 *piTable = pgnoRoot;
9968 return SQLITE_OK;
9970 int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){
9971 int rc;
9972 sqlite3BtreeEnter(p);
9973 rc = btreeCreateTable(p, piTable, flags);
9974 sqlite3BtreeLeave(p);
9975 return rc;
9979 ** Erase the given database page and all its children. Return
9980 ** the page to the freelist.
9982 static int clearDatabasePage(
9983 BtShared *pBt, /* The BTree that contains the table */
9984 Pgno pgno, /* Page number to clear */
9985 int freePageFlag, /* Deallocate page if true */
9986 i64 *pnChange /* Add number of Cells freed to this counter */
9988 MemPage *pPage;
9989 int rc;
9990 unsigned char *pCell;
9991 int i;
9992 int hdr;
9993 CellInfo info;
9995 assert( sqlite3_mutex_held(pBt->mutex) );
9996 if( pgno>btreePagecount(pBt) ){
9997 return SQLITE_CORRUPT_BKPT;
9999 rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
10000 if( rc ) return rc;
10001 if( (pBt->openFlags & BTREE_SINGLE)==0
10002 && sqlite3PagerPageRefcount(pPage->pDbPage) != (1 + (pgno==1))
10004 rc = SQLITE_CORRUPT_BKPT;
10005 goto cleardatabasepage_out;
10007 hdr = pPage->hdrOffset;
10008 for(i=0; i<pPage->nCell; i++){
10009 pCell = findCell(pPage, i);
10010 if( !pPage->leaf ){
10011 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
10012 if( rc ) goto cleardatabasepage_out;
10014 BTREE_CLEAR_CELL(rc, pPage, pCell, info);
10015 if( rc ) goto cleardatabasepage_out;
10017 if( !pPage->leaf ){
10018 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
10019 if( rc ) goto cleardatabasepage_out;
10020 if( pPage->intKey ) pnChange = 0;
10022 if( pnChange ){
10023 testcase( !pPage->intKey );
10024 *pnChange += pPage->nCell;
10026 if( freePageFlag ){
10027 freePage(pPage, &rc);
10028 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
10029 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
10032 cleardatabasepage_out:
10033 releasePage(pPage);
10034 return rc;
10038 ** Delete all information from a single table in the database. iTable is
10039 ** the page number of the root of the table. After this routine returns,
10040 ** the root page is empty, but still exists.
10042 ** This routine will fail with SQLITE_LOCKED if there are any open
10043 ** read cursors on the table. Open write cursors are moved to the
10044 ** root of the table.
10046 ** If pnChange is not NULL, then the integer value pointed to by pnChange
10047 ** is incremented by the number of entries in the table.
10049 int sqlite3BtreeClearTable(Btree *p, int iTable, i64 *pnChange){
10050 int rc;
10051 BtShared *pBt = p->pBt;
10052 sqlite3BtreeEnter(p);
10053 assert( p->inTrans==TRANS_WRITE );
10055 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
10057 if( SQLITE_OK==rc ){
10058 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
10059 ** is the root of a table b-tree - if it is not, the following call is
10060 ** a no-op). */
10061 if( p->hasIncrblobCur ){
10062 invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
10064 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
10066 sqlite3BtreeLeave(p);
10067 return rc;
10071 ** Delete all information from the single table that pCur is open on.
10073 ** This routine only work for pCur on an ephemeral table.
10075 int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
10076 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
10080 ** Erase all information in a table and add the root of the table to
10081 ** the freelist. Except, the root of the principle table (the one on
10082 ** page 1) is never added to the freelist.
10084 ** This routine will fail with SQLITE_LOCKED if there are any open
10085 ** cursors on the table.
10087 ** If AUTOVACUUM is enabled and the page at iTable is not the last
10088 ** root page in the database file, then the last root page
10089 ** in the database file is moved into the slot formerly occupied by
10090 ** iTable and that last slot formerly occupied by the last root page
10091 ** is added to the freelist instead of iTable. In this say, all
10092 ** root pages are kept at the beginning of the database file, which
10093 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
10094 ** page number that used to be the last root page in the file before
10095 ** the move. If no page gets moved, *piMoved is set to 0.
10096 ** The last root page is recorded in meta[3] and the value of
10097 ** meta[3] is updated by this procedure.
10099 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
10100 int rc;
10101 MemPage *pPage = 0;
10102 BtShared *pBt = p->pBt;
10104 assert( sqlite3BtreeHoldsMutex(p) );
10105 assert( p->inTrans==TRANS_WRITE );
10106 assert( iTable>=2 );
10107 if( iTable>btreePagecount(pBt) ){
10108 return SQLITE_CORRUPT_BKPT;
10111 rc = sqlite3BtreeClearTable(p, iTable, 0);
10112 if( rc ) return rc;
10113 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
10114 if( NEVER(rc) ){
10115 releasePage(pPage);
10116 return rc;
10119 *piMoved = 0;
10121 #ifdef SQLITE_OMIT_AUTOVACUUM
10122 freePage(pPage, &rc);
10123 releasePage(pPage);
10124 #else
10125 if( pBt->autoVacuum ){
10126 Pgno maxRootPgno;
10127 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
10129 if( iTable==maxRootPgno ){
10130 /* If the table being dropped is the table with the largest root-page
10131 ** number in the database, put the root page on the free list.
10133 freePage(pPage, &rc);
10134 releasePage(pPage);
10135 if( rc!=SQLITE_OK ){
10136 return rc;
10138 }else{
10139 /* The table being dropped does not have the largest root-page
10140 ** number in the database. So move the page that does into the
10141 ** gap left by the deleted root-page.
10143 MemPage *pMove;
10144 releasePage(pPage);
10145 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
10146 if( rc!=SQLITE_OK ){
10147 return rc;
10149 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
10150 releasePage(pMove);
10151 if( rc!=SQLITE_OK ){
10152 return rc;
10154 pMove = 0;
10155 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
10156 freePage(pMove, &rc);
10157 releasePage(pMove);
10158 if( rc!=SQLITE_OK ){
10159 return rc;
10161 *piMoved = maxRootPgno;
10164 /* Set the new 'max-root-page' value in the database header. This
10165 ** is the old value less one, less one more if that happens to
10166 ** be a root-page number, less one again if that is the
10167 ** PENDING_BYTE_PAGE.
10169 maxRootPgno--;
10170 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
10171 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
10172 maxRootPgno--;
10174 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
10176 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
10177 }else{
10178 freePage(pPage, &rc);
10179 releasePage(pPage);
10181 #endif
10182 return rc;
10184 int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
10185 int rc;
10186 sqlite3BtreeEnter(p);
10187 rc = btreeDropTable(p, iTable, piMoved);
10188 sqlite3BtreeLeave(p);
10189 return rc;
10194 ** This function may only be called if the b-tree connection already
10195 ** has a read or write transaction open on the database.
10197 ** Read the meta-information out of a database file. Meta[0]
10198 ** is the number of free pages currently in the database. Meta[1]
10199 ** through meta[15] are available for use by higher layers. Meta[0]
10200 ** is read-only, the others are read/write.
10202 ** The schema layer numbers meta values differently. At the schema
10203 ** layer (and the SetCookie and ReadCookie opcodes) the number of
10204 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
10206 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
10207 ** of reading the value out of the header, it instead loads the "DataVersion"
10208 ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
10209 ** database file. It is a number computed by the pager. But its access
10210 ** pattern is the same as header meta values, and so it is convenient to
10211 ** read it from this routine.
10213 void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
10214 BtShared *pBt = p->pBt;
10216 sqlite3BtreeEnter(p);
10217 assert( p->inTrans>TRANS_NONE );
10218 assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) );
10219 assert( pBt->pPage1 );
10220 assert( idx>=0 && idx<=15 );
10222 if( idx==BTREE_DATA_VERSION ){
10223 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iBDataVersion;
10224 }else{
10225 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
10228 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
10229 ** database, mark the database as read-only. */
10230 #ifdef SQLITE_OMIT_AUTOVACUUM
10231 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
10232 pBt->btsFlags |= BTS_READ_ONLY;
10234 #endif
10236 sqlite3BtreeLeave(p);
10240 ** Write meta-information back into the database. Meta[0] is
10241 ** read-only and may not be written.
10243 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
10244 BtShared *pBt = p->pBt;
10245 unsigned char *pP1;
10246 int rc;
10247 assert( idx>=1 && idx<=15 );
10248 sqlite3BtreeEnter(p);
10249 assert( p->inTrans==TRANS_WRITE );
10250 assert( pBt->pPage1!=0 );
10251 pP1 = pBt->pPage1->aData;
10252 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
10253 if( rc==SQLITE_OK ){
10254 put4byte(&pP1[36 + idx*4], iMeta);
10255 #ifndef SQLITE_OMIT_AUTOVACUUM
10256 if( idx==BTREE_INCR_VACUUM ){
10257 assert( pBt->autoVacuum || iMeta==0 );
10258 assert( iMeta==0 || iMeta==1 );
10259 pBt->incrVacuum = (u8)iMeta;
10261 #endif
10263 sqlite3BtreeLeave(p);
10264 return rc;
10268 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
10269 ** number of entries in the b-tree and write the result to *pnEntry.
10271 ** SQLITE_OK is returned if the operation is successfully executed.
10272 ** Otherwise, if an error is encountered (i.e. an IO error or database
10273 ** corruption) an SQLite error code is returned.
10275 int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){
10276 i64 nEntry = 0; /* Value to return in *pnEntry */
10277 int rc; /* Return code */
10279 rc = moveToRoot(pCur);
10280 if( rc==SQLITE_EMPTY ){
10281 *pnEntry = 0;
10282 return SQLITE_OK;
10285 /* Unless an error occurs, the following loop runs one iteration for each
10286 ** page in the B-Tree structure (not including overflow pages).
10288 while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){
10289 int iIdx; /* Index of child node in parent */
10290 MemPage *pPage; /* Current page of the b-tree */
10292 /* If this is a leaf page or the tree is not an int-key tree, then
10293 ** this page contains countable entries. Increment the entry counter
10294 ** accordingly.
10296 pPage = pCur->pPage;
10297 if( pPage->leaf || !pPage->intKey ){
10298 nEntry += pPage->nCell;
10301 /* pPage is a leaf node. This loop navigates the cursor so that it
10302 ** points to the first interior cell that it points to the parent of
10303 ** the next page in the tree that has not yet been visited. The
10304 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
10305 ** of the page, or to the number of cells in the page if the next page
10306 ** to visit is the right-child of its parent.
10308 ** If all pages in the tree have been visited, return SQLITE_OK to the
10309 ** caller.
10311 if( pPage->leaf ){
10312 do {
10313 if( pCur->iPage==0 ){
10314 /* All pages of the b-tree have been visited. Return successfully. */
10315 *pnEntry = nEntry;
10316 return moveToRoot(pCur);
10318 moveToParent(pCur);
10319 }while ( pCur->ix>=pCur->pPage->nCell );
10321 pCur->ix++;
10322 pPage = pCur->pPage;
10325 /* Descend to the child node of the cell that the cursor currently
10326 ** points at. This is the right-child if (iIdx==pPage->nCell).
10328 iIdx = pCur->ix;
10329 if( iIdx==pPage->nCell ){
10330 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
10331 }else{
10332 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
10336 /* An error has occurred. Return an error code. */
10337 return rc;
10341 ** Return the pager associated with a BTree. This routine is used for
10342 ** testing and debugging only.
10344 Pager *sqlite3BtreePager(Btree *p){
10345 return p->pBt->pPager;
10348 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10350 ** Record an OOM error during integrity_check
10352 static void checkOom(IntegrityCk *pCheck){
10353 pCheck->rc = SQLITE_NOMEM;
10354 pCheck->mxErr = 0; /* Causes integrity_check processing to stop */
10355 if( pCheck->nErr==0 ) pCheck->nErr++;
10359 ** Invoke the progress handler, if appropriate. Also check for an
10360 ** interrupt.
10362 static void checkProgress(IntegrityCk *pCheck){
10363 sqlite3 *db = pCheck->db;
10364 if( AtomicLoad(&db->u1.isInterrupted) ){
10365 pCheck->rc = SQLITE_INTERRUPT;
10366 pCheck->nErr++;
10367 pCheck->mxErr = 0;
10369 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
10370 if( db->xProgress ){
10371 assert( db->nProgressOps>0 );
10372 pCheck->nStep++;
10373 if( (pCheck->nStep % db->nProgressOps)==0
10374 && db->xProgress(db->pProgressArg)
10376 pCheck->rc = SQLITE_INTERRUPT;
10377 pCheck->nErr++;
10378 pCheck->mxErr = 0;
10381 #endif
10385 ** Append a message to the error message string.
10387 static void checkAppendMsg(
10388 IntegrityCk *pCheck,
10389 const char *zFormat,
10392 va_list ap;
10393 checkProgress(pCheck);
10394 if( !pCheck->mxErr ) return;
10395 pCheck->mxErr--;
10396 pCheck->nErr++;
10397 va_start(ap, zFormat);
10398 if( pCheck->errMsg.nChar ){
10399 sqlite3_str_append(&pCheck->errMsg, "\n", 1);
10401 if( pCheck->zPfx ){
10402 sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx,
10403 pCheck->v0, pCheck->v1, pCheck->v2);
10405 sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
10406 va_end(ap);
10407 if( pCheck->errMsg.accError==SQLITE_NOMEM ){
10408 checkOom(pCheck);
10411 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10413 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10416 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
10417 ** corresponds to page iPg is already set.
10419 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
10420 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
10421 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
10425 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
10427 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
10428 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
10429 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
10434 ** Add 1 to the reference count for page iPage. If this is the second
10435 ** reference to the page, add an error message to pCheck->zErrMsg.
10436 ** Return 1 if there are 2 or more references to the page and 0 if
10437 ** if this is the first reference to the page.
10439 ** Also check that the page number is in bounds.
10441 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
10442 if( iPage>pCheck->nPage || iPage==0 ){
10443 checkAppendMsg(pCheck, "invalid page number %u", iPage);
10444 return 1;
10446 if( getPageReferenced(pCheck, iPage) ){
10447 checkAppendMsg(pCheck, "2nd reference to page %u", iPage);
10448 return 1;
10450 setPageReferenced(pCheck, iPage);
10451 return 0;
10454 #ifndef SQLITE_OMIT_AUTOVACUUM
10456 ** Check that the entry in the pointer-map for page iChild maps to
10457 ** page iParent, pointer type ptrType. If not, append an error message
10458 ** to pCheck.
10460 static void checkPtrmap(
10461 IntegrityCk *pCheck, /* Integrity check context */
10462 Pgno iChild, /* Child page number */
10463 u8 eType, /* Expected pointer map type */
10464 Pgno iParent /* Expected pointer map parent page number */
10466 int rc;
10467 u8 ePtrmapType;
10468 Pgno iPtrmapParent;
10470 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
10471 if( rc!=SQLITE_OK ){
10472 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) checkOom(pCheck);
10473 checkAppendMsg(pCheck, "Failed to read ptrmap key=%u", iChild);
10474 return;
10477 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
10478 checkAppendMsg(pCheck,
10479 "Bad ptr map entry key=%u expected=(%u,%u) got=(%u,%u)",
10480 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
10483 #endif
10486 ** Check the integrity of the freelist or of an overflow page list.
10487 ** Verify that the number of pages on the list is N.
10489 static void checkList(
10490 IntegrityCk *pCheck, /* Integrity checking context */
10491 int isFreeList, /* True for a freelist. False for overflow page list */
10492 Pgno iPage, /* Page number for first page in the list */
10493 u32 N /* Expected number of pages in the list */
10495 int i;
10496 u32 expected = N;
10497 int nErrAtStart = pCheck->nErr;
10498 while( iPage!=0 && pCheck->mxErr ){
10499 DbPage *pOvflPage;
10500 unsigned char *pOvflData;
10501 if( checkRef(pCheck, iPage) ) break;
10502 N--;
10503 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
10504 checkAppendMsg(pCheck, "failed to get page %u", iPage);
10505 break;
10507 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
10508 if( isFreeList ){
10509 u32 n = (u32)get4byte(&pOvflData[4]);
10510 #ifndef SQLITE_OMIT_AUTOVACUUM
10511 if( pCheck->pBt->autoVacuum ){
10512 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
10514 #endif
10515 if( n>pCheck->pBt->usableSize/4-2 ){
10516 checkAppendMsg(pCheck,
10517 "freelist leaf count too big on page %u", iPage);
10518 N--;
10519 }else{
10520 for(i=0; i<(int)n; i++){
10521 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
10522 #ifndef SQLITE_OMIT_AUTOVACUUM
10523 if( pCheck->pBt->autoVacuum ){
10524 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
10526 #endif
10527 checkRef(pCheck, iFreePage);
10529 N -= n;
10532 #ifndef SQLITE_OMIT_AUTOVACUUM
10533 else{
10534 /* If this database supports auto-vacuum and iPage is not the last
10535 ** page in this overflow list, check that the pointer-map entry for
10536 ** the following page matches iPage.
10538 if( pCheck->pBt->autoVacuum && N>0 ){
10539 i = get4byte(pOvflData);
10540 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
10543 #endif
10544 iPage = get4byte(pOvflData);
10545 sqlite3PagerUnref(pOvflPage);
10547 if( N && nErrAtStart==pCheck->nErr ){
10548 checkAppendMsg(pCheck,
10549 "%s is %u but should be %u",
10550 isFreeList ? "size" : "overflow list length",
10551 expected-N, expected);
10554 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10557 ** An implementation of a min-heap.
10559 ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
10560 ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
10561 ** and aHeap[N*2+1].
10563 ** The heap property is this: Every node is less than or equal to both
10564 ** of its daughter nodes. A consequence of the heap property is that the
10565 ** root node aHeap[1] is always the minimum value currently in the heap.
10567 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
10568 ** the heap, preserving the heap property. The btreeHeapPull() routine
10569 ** removes the root element from the heap (the minimum value in the heap)
10570 ** and then moves other nodes around as necessary to preserve the heap
10571 ** property.
10573 ** This heap is used for cell overlap and coverage testing. Each u32
10574 ** entry represents the span of a cell or freeblock on a btree page.
10575 ** The upper 16 bits are the index of the first byte of a range and the
10576 ** lower 16 bits are the index of the last byte of that range.
10578 static void btreeHeapInsert(u32 *aHeap, u32 x){
10579 u32 j, i;
10580 assert( aHeap!=0 );
10581 i = ++aHeap[0];
10582 aHeap[i] = x;
10583 while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
10584 x = aHeap[j];
10585 aHeap[j] = aHeap[i];
10586 aHeap[i] = x;
10587 i = j;
10590 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
10591 u32 j, i, x;
10592 if( (x = aHeap[0])==0 ) return 0;
10593 *pOut = aHeap[1];
10594 aHeap[1] = aHeap[x];
10595 aHeap[x] = 0xffffffff;
10596 aHeap[0]--;
10597 i = 1;
10598 while( (j = i*2)<=aHeap[0] ){
10599 if( aHeap[j]>aHeap[j+1] ) j++;
10600 if( aHeap[i]<aHeap[j] ) break;
10601 x = aHeap[i];
10602 aHeap[i] = aHeap[j];
10603 aHeap[j] = x;
10604 i = j;
10606 return 1;
10609 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10611 ** Do various sanity checks on a single page of a tree. Return
10612 ** the tree depth. Root pages return 0. Parents of root pages
10613 ** return 1, and so forth.
10615 ** These checks are done:
10617 ** 1. Make sure that cells and freeblocks do not overlap
10618 ** but combine to completely cover the page.
10619 ** 2. Make sure integer cell keys are in order.
10620 ** 3. Check the integrity of overflow pages.
10621 ** 4. Recursively call checkTreePage on all children.
10622 ** 5. Verify that the depth of all children is the same.
10624 static int checkTreePage(
10625 IntegrityCk *pCheck, /* Context for the sanity check */
10626 Pgno iPage, /* Page number of the page to check */
10627 i64 *piMinKey, /* Write minimum integer primary key here */
10628 i64 maxKey /* Error if integer primary key greater than this */
10630 MemPage *pPage = 0; /* The page being analyzed */
10631 int i; /* Loop counter */
10632 int rc; /* Result code from subroutine call */
10633 int depth = -1, d2; /* Depth of a subtree */
10634 int pgno; /* Page number */
10635 int nFrag; /* Number of fragmented bytes on the page */
10636 int hdr; /* Offset to the page header */
10637 int cellStart; /* Offset to the start of the cell pointer array */
10638 int nCell; /* Number of cells */
10639 int doCoverageCheck = 1; /* True if cell coverage checking should be done */
10640 int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
10641 ** False if IPK must be strictly less than maxKey */
10642 u8 *data; /* Page content */
10643 u8 *pCell; /* Cell content */
10644 u8 *pCellIdx; /* Next element of the cell pointer array */
10645 BtShared *pBt; /* The BtShared object that owns pPage */
10646 u32 pc; /* Address of a cell */
10647 u32 usableSize; /* Usable size of the page */
10648 u32 contentOffset; /* Offset to the start of the cell content area */
10649 u32 *heap = 0; /* Min-heap used for checking cell coverage */
10650 u32 x, prev = 0; /* Next and previous entry on the min-heap */
10651 const char *saved_zPfx = pCheck->zPfx;
10652 int saved_v1 = pCheck->v1;
10653 int saved_v2 = pCheck->v2;
10654 u8 savedIsInit = 0;
10656 /* Check that the page exists
10658 checkProgress(pCheck);
10659 if( pCheck->mxErr==0 ) goto end_of_check;
10660 pBt = pCheck->pBt;
10661 usableSize = pBt->usableSize;
10662 if( iPage==0 ) return 0;
10663 if( checkRef(pCheck, iPage) ) return 0;
10664 pCheck->zPfx = "Tree %u page %u: ";
10665 pCheck->v0 = pCheck->v1 = iPage;
10666 if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){
10667 checkAppendMsg(pCheck,
10668 "unable to get the page. error code=%d", rc);
10669 goto end_of_check;
10672 /* Clear MemPage.isInit to make sure the corruption detection code in
10673 ** btreeInitPage() is executed. */
10674 savedIsInit = pPage->isInit;
10675 pPage->isInit = 0;
10676 if( (rc = btreeInitPage(pPage))!=0 ){
10677 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
10678 checkAppendMsg(pCheck,
10679 "btreeInitPage() returns error code %d", rc);
10680 goto end_of_check;
10682 if( (rc = btreeComputeFreeSpace(pPage))!=0 ){
10683 assert( rc==SQLITE_CORRUPT );
10684 checkAppendMsg(pCheck, "free space corruption", rc);
10685 goto end_of_check;
10687 data = pPage->aData;
10688 hdr = pPage->hdrOffset;
10690 /* Set up for cell analysis */
10691 pCheck->zPfx = "Tree %u page %u cell %u: ";
10692 contentOffset = get2byteNotZero(&data[hdr+5]);
10693 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
10695 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
10696 ** number of cells on the page. */
10697 nCell = get2byte(&data[hdr+3]);
10698 assert( pPage->nCell==nCell );
10700 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
10701 ** immediately follows the b-tree page header. */
10702 cellStart = hdr + 12 - 4*pPage->leaf;
10703 assert( pPage->aCellIdx==&data[cellStart] );
10704 pCellIdx = &data[cellStart + 2*(nCell-1)];
10706 if( !pPage->leaf ){
10707 /* Analyze the right-child page of internal pages */
10708 pgno = get4byte(&data[hdr+8]);
10709 #ifndef SQLITE_OMIT_AUTOVACUUM
10710 if( pBt->autoVacuum ){
10711 pCheck->zPfx = "Tree %u page %u right child: ";
10712 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10714 #endif
10715 depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10716 keyCanBeEqual = 0;
10717 }else{
10718 /* For leaf pages, the coverage check will occur in the same loop
10719 ** as the other cell checks, so initialize the heap. */
10720 heap = pCheck->heap;
10721 heap[0] = 0;
10724 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
10725 ** integer offsets to the cell contents. */
10726 for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
10727 CellInfo info;
10729 /* Check cell size */
10730 pCheck->v2 = i;
10731 assert( pCellIdx==&data[cellStart + i*2] );
10732 pc = get2byteAligned(pCellIdx);
10733 pCellIdx -= 2;
10734 if( pc<contentOffset || pc>usableSize-4 ){
10735 checkAppendMsg(pCheck, "Offset %u out of range %u..%u",
10736 pc, contentOffset, usableSize-4);
10737 doCoverageCheck = 0;
10738 continue;
10740 pCell = &data[pc];
10741 pPage->xParseCell(pPage, pCell, &info);
10742 if( pc+info.nSize>usableSize ){
10743 checkAppendMsg(pCheck, "Extends off end of page");
10744 doCoverageCheck = 0;
10745 continue;
10748 /* Check for integer primary key out of range */
10749 if( pPage->intKey ){
10750 if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
10751 checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
10753 maxKey = info.nKey;
10754 keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
10757 /* Check the content overflow list */
10758 if( info.nPayload>info.nLocal ){
10759 u32 nPage; /* Number of pages on the overflow chain */
10760 Pgno pgnoOvfl; /* First page of the overflow chain */
10761 assert( pc + info.nSize - 4 <= usableSize );
10762 nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
10763 pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
10764 #ifndef SQLITE_OMIT_AUTOVACUUM
10765 if( pBt->autoVacuum ){
10766 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
10768 #endif
10769 checkList(pCheck, 0, pgnoOvfl, nPage);
10772 if( !pPage->leaf ){
10773 /* Check sanity of left child page for internal pages */
10774 pgno = get4byte(pCell);
10775 #ifndef SQLITE_OMIT_AUTOVACUUM
10776 if( pBt->autoVacuum ){
10777 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10779 #endif
10780 d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10781 keyCanBeEqual = 0;
10782 if( d2!=depth ){
10783 checkAppendMsg(pCheck, "Child page depth differs");
10784 depth = d2;
10786 }else{
10787 /* Populate the coverage-checking heap for leaf pages */
10788 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
10791 *piMinKey = maxKey;
10793 /* Check for complete coverage of the page
10795 pCheck->zPfx = 0;
10796 if( doCoverageCheck && pCheck->mxErr>0 ){
10797 /* For leaf pages, the min-heap has already been initialized and the
10798 ** cells have already been inserted. But for internal pages, that has
10799 ** not yet been done, so do it now */
10800 if( !pPage->leaf ){
10801 heap = pCheck->heap;
10802 heap[0] = 0;
10803 for(i=nCell-1; i>=0; i--){
10804 u32 size;
10805 pc = get2byteAligned(&data[cellStart+i*2]);
10806 size = pPage->xCellSize(pPage, &data[pc]);
10807 btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
10810 /* Add the freeblocks to the min-heap
10812 ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
10813 ** is the offset of the first freeblock, or zero if there are no
10814 ** freeblocks on the page.
10816 i = get2byte(&data[hdr+1]);
10817 while( i>0 ){
10818 int size, j;
10819 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10820 size = get2byte(&data[i+2]);
10821 assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
10822 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
10823 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
10824 ** big-endian integer which is the offset in the b-tree page of the next
10825 ** freeblock in the chain, or zero if the freeblock is the last on the
10826 ** chain. */
10827 j = get2byte(&data[i]);
10828 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
10829 ** increasing offset. */
10830 assert( j==0 || j>i+size ); /* Enforced by btreeComputeFreeSpace() */
10831 assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10832 i = j;
10834 /* Analyze the min-heap looking for overlap between cells and/or
10835 ** freeblocks, and counting the number of untracked bytes in nFrag.
10837 ** Each min-heap entry is of the form: (start_address<<16)|end_address.
10838 ** There is an implied first entry the covers the page header, the cell
10839 ** pointer index, and the gap between the cell pointer index and the start
10840 ** of cell content.
10842 ** The loop below pulls entries from the min-heap in order and compares
10843 ** the start_address against the previous end_address. If there is an
10844 ** overlap, that means bytes are used multiple times. If there is a gap,
10845 ** that gap is added to the fragmentation count.
10847 nFrag = 0;
10848 prev = contentOffset - 1; /* Implied first min-heap entry */
10849 while( btreeHeapPull(heap,&x) ){
10850 if( (prev&0xffff)>=(x>>16) ){
10851 checkAppendMsg(pCheck,
10852 "Multiple uses for byte %u of page %u", x>>16, iPage);
10853 break;
10854 }else{
10855 nFrag += (x>>16) - (prev&0xffff) - 1;
10856 prev = x;
10859 nFrag += usableSize - (prev&0xffff) - 1;
10860 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
10861 ** is stored in the fifth field of the b-tree page header.
10862 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
10863 ** number of fragmented free bytes within the cell content area.
10865 if( heap[0]==0 && nFrag!=data[hdr+7] ){
10866 checkAppendMsg(pCheck,
10867 "Fragmentation of %u bytes reported as %u on page %u",
10868 nFrag, data[hdr+7], iPage);
10872 end_of_check:
10873 if( !doCoverageCheck ) pPage->isInit = savedIsInit;
10874 releasePage(pPage);
10875 pCheck->zPfx = saved_zPfx;
10876 pCheck->v1 = saved_v1;
10877 pCheck->v2 = saved_v2;
10878 return depth+1;
10880 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10882 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10884 ** This routine does a complete check of the given BTree file. aRoot[] is
10885 ** an array of pages numbers were each page number is the root page of
10886 ** a table. nRoot is the number of entries in aRoot.
10888 ** A read-only or read-write transaction must be opened before calling
10889 ** this function.
10891 ** Write the number of error seen in *pnErr. Except for some memory
10892 ** allocation errors, an error message held in memory obtained from
10893 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
10894 ** returned. If a memory allocation error occurs, NULL is returned.
10896 ** If the first entry in aRoot[] is 0, that indicates that the list of
10897 ** root pages is incomplete. This is a "partial integrity-check". This
10898 ** happens when performing an integrity check on a single table. The
10899 ** zero is skipped, of course. But in addition, the freelist checks
10900 ** and the checks to make sure every page is referenced are also skipped,
10901 ** since obviously it is not possible to know which pages are covered by
10902 ** the unverified btrees. Except, if aRoot[1] is 1, then the freelist
10903 ** checks are still performed.
10905 int sqlite3BtreeIntegrityCheck(
10906 sqlite3 *db, /* Database connection that is running the check */
10907 Btree *p, /* The btree to be checked */
10908 Pgno *aRoot, /* An array of root pages numbers for individual trees */
10909 int nRoot, /* Number of entries in aRoot[] */
10910 int mxErr, /* Stop reporting errors after this many */
10911 int *pnErr, /* OUT: Write number of errors seen to this variable */
10912 char **pzOut /* OUT: Write the error message string here */
10914 Pgno i;
10915 IntegrityCk sCheck;
10916 BtShared *pBt = p->pBt;
10917 u64 savedDbFlags = pBt->db->flags;
10918 char zErr[100];
10919 int bPartial = 0; /* True if not checking all btrees */
10920 int bCkFreelist = 1; /* True to scan the freelist */
10921 VVA_ONLY( int nRef );
10922 assert( nRoot>0 );
10924 /* aRoot[0]==0 means this is a partial check */
10925 if( aRoot[0]==0 ){
10926 assert( nRoot>1 );
10927 bPartial = 1;
10928 if( aRoot[1]!=1 ) bCkFreelist = 0;
10931 sqlite3BtreeEnter(p);
10932 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
10933 VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
10934 assert( nRef>=0 );
10935 memset(&sCheck, 0, sizeof(sCheck));
10936 sCheck.db = db;
10937 sCheck.pBt = pBt;
10938 sCheck.pPager = pBt->pPager;
10939 sCheck.nPage = btreePagecount(sCheck.pBt);
10940 sCheck.mxErr = mxErr;
10941 sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
10942 sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
10943 if( sCheck.nPage==0 ){
10944 goto integrity_ck_cleanup;
10947 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
10948 if( !sCheck.aPgRef ){
10949 checkOom(&sCheck);
10950 goto integrity_ck_cleanup;
10952 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
10953 if( sCheck.heap==0 ){
10954 checkOom(&sCheck);
10955 goto integrity_ck_cleanup;
10958 i = PENDING_BYTE_PAGE(pBt);
10959 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
10961 /* Check the integrity of the freelist
10963 if( bCkFreelist ){
10964 sCheck.zPfx = "Freelist: ";
10965 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
10966 get4byte(&pBt->pPage1->aData[36]));
10967 sCheck.zPfx = 0;
10970 /* Check all the tables.
10972 #ifndef SQLITE_OMIT_AUTOVACUUM
10973 if( !bPartial ){
10974 if( pBt->autoVacuum ){
10975 Pgno mx = 0;
10976 Pgno mxInHdr;
10977 for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
10978 mxInHdr = get4byte(&pBt->pPage1->aData[52]);
10979 if( mx!=mxInHdr ){
10980 checkAppendMsg(&sCheck,
10981 "max rootpage (%u) disagrees with header (%u)",
10982 mx, mxInHdr
10985 }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
10986 checkAppendMsg(&sCheck,
10987 "incremental_vacuum enabled with a max rootpage of zero"
10991 #endif
10992 testcase( pBt->db->flags & SQLITE_CellSizeCk );
10993 pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
10994 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
10995 i64 notUsed;
10996 if( aRoot[i]==0 ) continue;
10997 #ifndef SQLITE_OMIT_AUTOVACUUM
10998 if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){
10999 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
11001 #endif
11002 checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
11004 pBt->db->flags = savedDbFlags;
11006 /* Make sure every page in the file is referenced
11008 if( !bPartial ){
11009 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
11010 #ifdef SQLITE_OMIT_AUTOVACUUM
11011 if( getPageReferenced(&sCheck, i)==0 ){
11012 checkAppendMsg(&sCheck, "Page %u: never used", i);
11014 #else
11015 /* If the database supports auto-vacuum, make sure no tables contain
11016 ** references to pointer-map pages.
11018 if( getPageReferenced(&sCheck, i)==0 &&
11019 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
11020 checkAppendMsg(&sCheck, "Page %u: never used", i);
11022 if( getPageReferenced(&sCheck, i)!=0 &&
11023 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
11024 checkAppendMsg(&sCheck, "Page %u: pointer map referenced", i);
11026 #endif
11030 /* Clean up and report errors.
11032 integrity_ck_cleanup:
11033 sqlite3PageFree(sCheck.heap);
11034 sqlite3_free(sCheck.aPgRef);
11035 *pnErr = sCheck.nErr;
11036 if( sCheck.nErr==0 ){
11037 sqlite3_str_reset(&sCheck.errMsg);
11038 *pzOut = 0;
11039 }else{
11040 *pzOut = sqlite3StrAccumFinish(&sCheck.errMsg);
11042 /* Make sure this analysis did not leave any unref() pages. */
11043 assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
11044 sqlite3BtreeLeave(p);
11045 return sCheck.rc;
11047 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
11050 ** Return the full pathname of the underlying database file. Return
11051 ** an empty string if the database is in-memory or a TEMP database.
11053 ** The pager filename is invariant as long as the pager is
11054 ** open so it is safe to access without the BtShared mutex.
11056 const char *sqlite3BtreeGetFilename(Btree *p){
11057 assert( p->pBt->pPager!=0 );
11058 return sqlite3PagerFilename(p->pBt->pPager, 1);
11062 ** Return the pathname of the journal file for this database. The return
11063 ** value of this routine is the same regardless of whether the journal file
11064 ** has been created or not.
11066 ** The pager journal filename is invariant as long as the pager is
11067 ** open so it is safe to access without the BtShared mutex.
11069 const char *sqlite3BtreeGetJournalname(Btree *p){
11070 assert( p->pBt->pPager!=0 );
11071 return sqlite3PagerJournalname(p->pBt->pPager);
11075 ** Return one of SQLITE_TXN_NONE, SQLITE_TXN_READ, or SQLITE_TXN_WRITE
11076 ** to describe the current transaction state of Btree p.
11078 int sqlite3BtreeTxnState(Btree *p){
11079 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
11080 return p ? p->inTrans : 0;
11083 #ifndef SQLITE_OMIT_WAL
11085 ** Run a checkpoint on the Btree passed as the first argument.
11087 ** Return SQLITE_LOCKED if this or any other connection has an open
11088 ** transaction on the shared-cache the argument Btree is connected to.
11090 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
11092 int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
11093 int rc = SQLITE_OK;
11094 if( p ){
11095 BtShared *pBt = p->pBt;
11096 sqlite3BtreeEnter(p);
11097 if( pBt->inTransaction!=TRANS_NONE ){
11098 rc = SQLITE_LOCKED;
11099 }else{
11100 rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
11102 sqlite3BtreeLeave(p);
11104 return rc;
11106 #endif
11109 ** Return true if there is currently a backup running on Btree p.
11111 int sqlite3BtreeIsInBackup(Btree *p){
11112 assert( p );
11113 assert( sqlite3_mutex_held(p->db->mutex) );
11114 return p->nBackup!=0;
11118 ** This function returns a pointer to a blob of memory associated with
11119 ** a single shared-btree. The memory is used by client code for its own
11120 ** purposes (for example, to store a high-level schema associated with
11121 ** the shared-btree). The btree layer manages reference counting issues.
11123 ** The first time this is called on a shared-btree, nBytes bytes of memory
11124 ** are allocated, zeroed, and returned to the caller. For each subsequent
11125 ** call the nBytes parameter is ignored and a pointer to the same blob
11126 ** of memory returned.
11128 ** If the nBytes parameter is 0 and the blob of memory has not yet been
11129 ** allocated, a null pointer is returned. If the blob has already been
11130 ** allocated, it is returned as normal.
11132 ** Just before the shared-btree is closed, the function passed as the
11133 ** xFree argument when the memory allocation was made is invoked on the
11134 ** blob of allocated memory. The xFree function should not call sqlite3_free()
11135 ** on the memory, the btree layer does that.
11137 void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
11138 BtShared *pBt = p->pBt;
11139 sqlite3BtreeEnter(p);
11140 if( !pBt->pSchema && nBytes ){
11141 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
11142 pBt->xFreeSchema = xFree;
11144 sqlite3BtreeLeave(p);
11145 return pBt->pSchema;
11149 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
11150 ** btree as the argument handle holds an exclusive lock on the
11151 ** sqlite_schema table. Otherwise SQLITE_OK.
11153 int sqlite3BtreeSchemaLocked(Btree *p){
11154 int rc;
11155 assert( sqlite3_mutex_held(p->db->mutex) );
11156 sqlite3BtreeEnter(p);
11157 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
11158 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
11159 sqlite3BtreeLeave(p);
11160 return rc;
11164 #ifndef SQLITE_OMIT_SHARED_CACHE
11166 ** Obtain a lock on the table whose root page is iTab. The
11167 ** lock is a write lock if isWritelock is true or a read lock
11168 ** if it is false.
11170 int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
11171 int rc = SQLITE_OK;
11172 assert( p->inTrans!=TRANS_NONE );
11173 if( p->sharable ){
11174 u8 lockType = READ_LOCK + isWriteLock;
11175 assert( READ_LOCK+1==WRITE_LOCK );
11176 assert( isWriteLock==0 || isWriteLock==1 );
11178 sqlite3BtreeEnter(p);
11179 rc = querySharedCacheTableLock(p, iTab, lockType);
11180 if( rc==SQLITE_OK ){
11181 rc = setSharedCacheTableLock(p, iTab, lockType);
11183 sqlite3BtreeLeave(p);
11185 return rc;
11187 #endif
11189 #ifndef SQLITE_OMIT_INCRBLOB
11191 ** Argument pCsr must be a cursor opened for writing on an
11192 ** INTKEY table currently pointing at a valid table entry.
11193 ** This function modifies the data stored as part of that entry.
11195 ** Only the data content may only be modified, it is not possible to
11196 ** change the length of the data stored. If this function is called with
11197 ** parameters that attempt to write past the end of the existing data,
11198 ** no modifications are made and SQLITE_CORRUPT is returned.
11200 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
11201 int rc;
11202 assert( cursorOwnsBtShared(pCsr) );
11203 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
11204 assert( pCsr->curFlags & BTCF_Incrblob );
11206 rc = restoreCursorPosition(pCsr);
11207 if( rc!=SQLITE_OK ){
11208 return rc;
11210 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
11211 if( pCsr->eState!=CURSOR_VALID ){
11212 return SQLITE_ABORT;
11215 /* Save the positions of all other cursors open on this table. This is
11216 ** required in case any of them are holding references to an xFetch
11217 ** version of the b-tree page modified by the accessPayload call below.
11219 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
11220 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
11221 ** saveAllCursors can only return SQLITE_OK.
11223 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
11224 assert( rc==SQLITE_OK );
11226 /* Check some assumptions:
11227 ** (a) the cursor is open for writing,
11228 ** (b) there is a read/write transaction open,
11229 ** (c) the connection holds a write-lock on the table (if required),
11230 ** (d) there are no conflicting read-locks, and
11231 ** (e) the cursor points at a valid row of an intKey table.
11233 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
11234 return SQLITE_READONLY;
11236 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
11237 && pCsr->pBt->inTransaction==TRANS_WRITE );
11238 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
11239 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
11240 assert( pCsr->pPage->intKey );
11242 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
11246 ** Mark this cursor as an incremental blob cursor.
11248 void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
11249 pCur->curFlags |= BTCF_Incrblob;
11250 pCur->pBtree->hasIncrblobCur = 1;
11252 #endif
11255 ** Set both the "read version" (single byte at byte offset 18) and
11256 ** "write version" (single byte at byte offset 19) fields in the database
11257 ** header to iVersion.
11259 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
11260 BtShared *pBt = pBtree->pBt;
11261 int rc; /* Return code */
11263 assert( iVersion==1 || iVersion==2 );
11265 /* If setting the version fields to 1, do not automatically open the
11266 ** WAL connection, even if the version fields are currently set to 2.
11268 pBt->btsFlags &= ~BTS_NO_WAL;
11269 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
11271 rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
11272 if( rc==SQLITE_OK ){
11273 u8 *aData = pBt->pPage1->aData;
11274 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
11275 rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
11276 if( rc==SQLITE_OK ){
11277 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
11278 if( rc==SQLITE_OK ){
11279 aData[18] = (u8)iVersion;
11280 aData[19] = (u8)iVersion;
11286 pBt->btsFlags &= ~BTS_NO_WAL;
11287 return rc;
11291 ** Return true if the cursor has a hint specified. This routine is
11292 ** only used from within assert() statements
11294 int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
11295 return (pCsr->hints & mask)!=0;
11299 ** Return true if the given Btree is read-only.
11301 int sqlite3BtreeIsReadonly(Btree *p){
11302 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
11306 ** Return the size of the header added to each page by this module.
11308 int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
11311 ** If no transaction is active and the database is not a temp-db, clear
11312 ** the in-memory pager cache.
11314 void sqlite3BtreeClearCache(Btree *p){
11315 BtShared *pBt = p->pBt;
11316 if( pBt->inTransaction==TRANS_NONE ){
11317 sqlite3PagerClearCache(pBt->pPager);
11321 #if !defined(SQLITE_OMIT_SHARED_CACHE)
11323 ** Return true if the Btree passed as the only argument is sharable.
11325 int sqlite3BtreeSharable(Btree *p){
11326 return p->sharable;
11330 ** Return the number of connections to the BtShared object accessed by
11331 ** the Btree handle passed as the only argument. For private caches
11332 ** this is always 1. For shared caches it may be 1 or greater.
11334 int sqlite3BtreeConnectionCount(Btree *p){
11335 testcase( p->sharable );
11336 return p->pBt->nRef;
11338 #endif