Merge sqlite-release(3.44.2) into prerelease-integration
[sqlcipher.git] / src / btree.c
blob5be30d562c7259bb819bea57861e4d59d4c4640a
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_OVERFLOW(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, data, usableSize);
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 encroach 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 static int getAndInitPage(
2322 BtShared *pBt, /* The database file */
2323 Pgno pgno, /* Number of the page to get */
2324 MemPage **ppPage, /* Write the page pointer here */
2325 int bReadOnly /* True for a read-only page */
2327 int rc;
2328 DbPage *pDbPage;
2329 MemPage *pPage;
2330 assert( sqlite3_mutex_held(pBt->mutex) );
2332 if( pgno>btreePagecount(pBt) ){
2333 *ppPage = 0;
2334 return SQLITE_CORRUPT_BKPT;
2336 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
2337 if( rc ){
2338 *ppPage = 0;
2339 return rc;
2341 pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2342 if( pPage->isInit==0 ){
2343 btreePageFromDbPage(pDbPage, pgno, pBt);
2344 rc = btreeInitPage(pPage);
2345 if( rc!=SQLITE_OK ){
2346 releasePage(pPage);
2347 *ppPage = 0;
2348 return rc;
2351 assert( pPage->pgno==pgno || CORRUPT_DB );
2352 assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
2353 *ppPage = pPage;
2354 return SQLITE_OK;
2358 ** Release a MemPage. This should be called once for each prior
2359 ** call to btreeGetPage.
2361 ** Page1 is a special case and must be released using releasePageOne().
2363 static void releasePageNotNull(MemPage *pPage){
2364 assert( pPage->aData );
2365 assert( pPage->pBt );
2366 assert( pPage->pDbPage!=0 );
2367 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2368 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2369 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2370 sqlite3PagerUnrefNotNull(pPage->pDbPage);
2372 static void releasePage(MemPage *pPage){
2373 if( pPage ) releasePageNotNull(pPage);
2375 static void releasePageOne(MemPage *pPage){
2376 assert( pPage!=0 );
2377 assert( pPage->aData );
2378 assert( pPage->pBt );
2379 assert( pPage->pDbPage!=0 );
2380 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2381 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2382 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2383 sqlite3PagerUnrefPageOne(pPage->pDbPage);
2387 ** Get an unused page.
2389 ** This works just like btreeGetPage() with the addition:
2391 ** * If the page is already in use for some other purpose, immediately
2392 ** release it and return an SQLITE_CURRUPT error.
2393 ** * Make sure the isInit flag is clear
2395 static int btreeGetUnusedPage(
2396 BtShared *pBt, /* The btree */
2397 Pgno pgno, /* Number of the page to fetch */
2398 MemPage **ppPage, /* Return the page in this parameter */
2399 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2401 int rc = btreeGetPage(pBt, pgno, ppPage, flags);
2402 if( rc==SQLITE_OK ){
2403 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
2404 releasePage(*ppPage);
2405 *ppPage = 0;
2406 return SQLITE_CORRUPT_BKPT;
2408 (*ppPage)->isInit = 0;
2409 }else{
2410 *ppPage = 0;
2412 return rc;
2417 ** During a rollback, when the pager reloads information into the cache
2418 ** so that the cache is restored to its original state at the start of
2419 ** the transaction, for each page restored this routine is called.
2421 ** This routine needs to reset the extra data section at the end of the
2422 ** page to agree with the restored data.
2424 static void pageReinit(DbPage *pData){
2425 MemPage *pPage;
2426 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
2427 assert( sqlite3PagerPageRefcount(pData)>0 );
2428 if( pPage->isInit ){
2429 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2430 pPage->isInit = 0;
2431 if( sqlite3PagerPageRefcount(pData)>1 ){
2432 /* pPage might not be a btree page; it might be an overflow page
2433 ** or ptrmap page or a free page. In those cases, the following
2434 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
2435 ** But no harm is done by this. And it is very important that
2436 ** btreeInitPage() be called on every btree page so we make
2437 ** the call for every page that comes in for re-initializing. */
2438 btreeInitPage(pPage);
2444 ** Invoke the busy handler for a btree.
2446 static int btreeInvokeBusyHandler(void *pArg){
2447 BtShared *pBt = (BtShared*)pArg;
2448 assert( pBt->db );
2449 assert( sqlite3_mutex_held(pBt->db->mutex) );
2450 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
2454 ** Open a database file.
2456 ** zFilename is the name of the database file. If zFilename is NULL
2457 ** then an ephemeral database is created. The ephemeral database might
2458 ** be exclusively in memory, or it might use a disk-based memory cache.
2459 ** Either way, the ephemeral database will be automatically deleted
2460 ** when sqlite3BtreeClose() is called.
2462 ** If zFilename is ":memory:" then an in-memory database is created
2463 ** that is automatically destroyed when it is closed.
2465 ** The "flags" parameter is a bitmask that might contain bits like
2466 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
2468 ** If the database is already opened in the same database connection
2469 ** and we are in shared cache mode, then the open will fail with an
2470 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
2471 ** objects in the same database connection since doing so will lead
2472 ** to problems with locking.
2474 int sqlite3BtreeOpen(
2475 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
2476 const char *zFilename, /* Name of the file containing the BTree database */
2477 sqlite3 *db, /* Associated database handle */
2478 Btree **ppBtree, /* Pointer to new Btree object written here */
2479 int flags, /* Options */
2480 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
2482 BtShared *pBt = 0; /* Shared part of btree structure */
2483 Btree *p; /* Handle to return */
2484 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
2485 int rc = SQLITE_OK; /* Result code from this function */
2486 u8 nReserve; /* Byte of unused space on each page */
2487 unsigned char zDbHeader[100]; /* Database header content */
2489 /* True if opening an ephemeral, temporary database */
2490 const int isTempDb = zFilename==0 || zFilename[0]==0;
2492 /* Set the variable isMemdb to true for an in-memory database, or
2493 ** false for a file-based database.
2495 #ifdef SQLITE_OMIT_MEMORYDB
2496 const int isMemdb = 0;
2497 #else
2498 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
2499 || (isTempDb && sqlite3TempInMemory(db))
2500 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
2501 #endif
2503 assert( db!=0 );
2504 assert( pVfs!=0 );
2505 assert( sqlite3_mutex_held(db->mutex) );
2506 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
2508 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
2509 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
2511 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
2512 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
2514 if( isMemdb ){
2515 flags |= BTREE_MEMORY;
2517 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
2518 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
2520 p = sqlite3MallocZero(sizeof(Btree));
2521 if( !p ){
2522 return SQLITE_NOMEM_BKPT;
2524 p->inTrans = TRANS_NONE;
2525 p->db = db;
2526 #ifndef SQLITE_OMIT_SHARED_CACHE
2527 p->lock.pBtree = p;
2528 p->lock.iTable = 1;
2529 #endif
2531 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2533 ** If this Btree is a candidate for shared cache, try to find an
2534 ** existing BtShared object that we can share with
2536 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
2537 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
2538 int nFilename = sqlite3Strlen30(zFilename)+1;
2539 int nFullPathname = pVfs->mxPathname+1;
2540 char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
2541 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2543 p->sharable = 1;
2544 if( !zFullPathname ){
2545 sqlite3_free(p);
2546 return SQLITE_NOMEM_BKPT;
2548 if( isMemdb ){
2549 memcpy(zFullPathname, zFilename, nFilename);
2550 }else{
2551 rc = sqlite3OsFullPathname(pVfs, zFilename,
2552 nFullPathname, zFullPathname);
2553 if( rc ){
2554 if( rc==SQLITE_OK_SYMLINK ){
2555 rc = SQLITE_OK;
2556 }else{
2557 sqlite3_free(zFullPathname);
2558 sqlite3_free(p);
2559 return rc;
2563 #if SQLITE_THREADSAFE
2564 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
2565 sqlite3_mutex_enter(mutexOpen);
2566 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
2567 sqlite3_mutex_enter(mutexShared);
2568 #endif
2569 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
2570 assert( pBt->nRef>0 );
2571 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
2572 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
2573 int iDb;
2574 for(iDb=db->nDb-1; iDb>=0; iDb--){
2575 Btree *pExisting = db->aDb[iDb].pBt;
2576 if( pExisting && pExisting->pBt==pBt ){
2577 sqlite3_mutex_leave(mutexShared);
2578 sqlite3_mutex_leave(mutexOpen);
2579 sqlite3_free(zFullPathname);
2580 sqlite3_free(p);
2581 return SQLITE_CONSTRAINT;
2584 p->pBt = pBt;
2585 pBt->nRef++;
2586 break;
2589 sqlite3_mutex_leave(mutexShared);
2590 sqlite3_free(zFullPathname);
2592 #ifdef SQLITE_DEBUG
2593 else{
2594 /* In debug mode, we mark all persistent databases as sharable
2595 ** even when they are not. This exercises the locking code and
2596 ** gives more opportunity for asserts(sqlite3_mutex_held())
2597 ** statements to find locking problems.
2599 p->sharable = 1;
2601 #endif
2603 #endif
2604 if( pBt==0 ){
2606 ** The following asserts make sure that structures used by the btree are
2607 ** the right size. This is to guard against size changes that result
2608 ** when compiling on a different architecture.
2610 assert( sizeof(i64)==8 );
2611 assert( sizeof(u64)==8 );
2612 assert( sizeof(u32)==4 );
2613 assert( sizeof(u16)==2 );
2614 assert( sizeof(Pgno)==4 );
2616 /* Suppress false-positive compiler warning from PVS-Studio */
2617 memset(&zDbHeader[16], 0, 8);
2619 pBt = sqlite3MallocZero( sizeof(*pBt) );
2620 if( pBt==0 ){
2621 rc = SQLITE_NOMEM_BKPT;
2622 goto btree_open_out;
2624 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
2625 sizeof(MemPage), flags, vfsFlags, pageReinit);
2626 if( rc==SQLITE_OK ){
2627 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
2628 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
2630 if( rc!=SQLITE_OK ){
2631 goto btree_open_out;
2633 pBt->openFlags = (u8)flags;
2634 pBt->db = db;
2635 sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
2636 p->pBt = pBt;
2638 pBt->pCursor = 0;
2639 pBt->pPage1 = 0;
2640 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
2641 #if defined(SQLITE_SECURE_DELETE)
2642 pBt->btsFlags |= BTS_SECURE_DELETE;
2643 #elif defined(SQLITE_FAST_SECURE_DELETE)
2644 pBt->btsFlags |= BTS_OVERWRITE;
2645 #endif
2646 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2647 ** determined by the 2-byte integer located at an offset of 16 bytes from
2648 ** the beginning of the database file. */
2649 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
2650 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
2651 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
2652 pBt->pageSize = 0;
2653 #ifndef SQLITE_OMIT_AUTOVACUUM
2654 /* If the magic name ":memory:" will create an in-memory database, then
2655 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
2656 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
2657 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
2658 ** regular file-name. In this case the auto-vacuum applies as per normal.
2660 if( zFilename && !isMemdb ){
2661 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
2662 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
2664 #endif
2665 nReserve = 0;
2666 }else{
2667 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2668 ** determined by the one-byte unsigned integer found at an offset of 20
2669 ** into the database file header. */
2670 nReserve = zDbHeader[20];
2671 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2672 #ifndef SQLITE_OMIT_AUTOVACUUM
2673 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
2674 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
2675 #endif
2677 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2678 if( rc ) goto btree_open_out;
2679 pBt->usableSize = pBt->pageSize - nReserve;
2680 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
2682 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2683 /* Add the new BtShared object to the linked list sharable BtShareds.
2685 pBt->nRef = 1;
2686 if( p->sharable ){
2687 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2688 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);)
2689 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
2690 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
2691 if( pBt->mutex==0 ){
2692 rc = SQLITE_NOMEM_BKPT;
2693 goto btree_open_out;
2696 sqlite3_mutex_enter(mutexShared);
2697 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2698 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
2699 sqlite3_mutex_leave(mutexShared);
2701 #endif
2704 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2705 /* If the new Btree uses a sharable pBtShared, then link the new
2706 ** Btree into the list of all sharable Btrees for the same connection.
2707 ** The list is kept in ascending order by pBt address.
2709 if( p->sharable ){
2710 int i;
2711 Btree *pSib;
2712 for(i=0; i<db->nDb; i++){
2713 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
2714 while( pSib->pPrev ){ pSib = pSib->pPrev; }
2715 if( (uptr)p->pBt<(uptr)pSib->pBt ){
2716 p->pNext = pSib;
2717 p->pPrev = 0;
2718 pSib->pPrev = p;
2719 }else{
2720 while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
2721 pSib = pSib->pNext;
2723 p->pNext = pSib->pNext;
2724 p->pPrev = pSib;
2725 if( p->pNext ){
2726 p->pNext->pPrev = p;
2728 pSib->pNext = p;
2730 break;
2734 #endif
2735 *ppBtree = p;
2737 btree_open_out:
2738 if( rc!=SQLITE_OK ){
2739 if( pBt && pBt->pPager ){
2740 sqlite3PagerClose(pBt->pPager, 0);
2742 sqlite3_free(pBt);
2743 sqlite3_free(p);
2744 *ppBtree = 0;
2745 }else{
2746 sqlite3_file *pFile;
2748 /* If the B-Tree was successfully opened, set the pager-cache size to the
2749 ** default value. Except, when opening on an existing shared pager-cache,
2750 ** do not change the pager-cache size.
2752 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
2753 sqlite3BtreeSetCacheSize(p, SQLITE_DEFAULT_CACHE_SIZE);
2756 pFile = sqlite3PagerFile(pBt->pPager);
2757 if( pFile->pMethods ){
2758 sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
2761 if( mutexOpen ){
2762 assert( sqlite3_mutex_held(mutexOpen) );
2763 sqlite3_mutex_leave(mutexOpen);
2765 assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
2766 return rc;
2770 ** Decrement the BtShared.nRef counter. When it reaches zero,
2771 ** remove the BtShared structure from the sharing list. Return
2772 ** true if the BtShared.nRef counter reaches zero and return
2773 ** false if it is still positive.
2775 static int removeFromSharingList(BtShared *pBt){
2776 #ifndef SQLITE_OMIT_SHARED_CACHE
2777 MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )
2778 BtShared *pList;
2779 int removed = 0;
2781 assert( sqlite3_mutex_notheld(pBt->mutex) );
2782 MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
2783 sqlite3_mutex_enter(pMainMtx);
2784 pBt->nRef--;
2785 if( pBt->nRef<=0 ){
2786 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2787 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
2788 }else{
2789 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
2790 while( ALWAYS(pList) && pList->pNext!=pBt ){
2791 pList=pList->pNext;
2793 if( ALWAYS(pList) ){
2794 pList->pNext = pBt->pNext;
2797 if( SQLITE_THREADSAFE ){
2798 sqlite3_mutex_free(pBt->mutex);
2800 removed = 1;
2802 sqlite3_mutex_leave(pMainMtx);
2803 return removed;
2804 #else
2805 return 1;
2806 #endif
2810 ** Make sure pBt->pTmpSpace points to an allocation of
2811 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
2812 ** pointer.
2814 static SQLITE_NOINLINE int allocateTempSpace(BtShared *pBt){
2815 assert( pBt!=0 );
2816 assert( pBt->pTmpSpace==0 );
2817 /* This routine is called only by btreeCursor() when allocating the
2818 ** first write cursor for the BtShared object */
2819 assert( pBt->pCursor!=0 && (pBt->pCursor->curFlags & BTCF_WriteFlag)!=0 );
2820 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
2821 if( pBt->pTmpSpace==0 ){
2822 BtCursor *pCur = pBt->pCursor;
2823 pBt->pCursor = pCur->pNext; /* Unlink the cursor */
2824 memset(pCur, 0, sizeof(*pCur));
2825 return SQLITE_NOMEM_BKPT;
2828 /* One of the uses of pBt->pTmpSpace is to format cells before
2829 ** inserting them into a leaf page (function fillInCell()). If
2830 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
2831 ** by the various routines that manipulate binary cells. Which
2832 ** can mean that fillInCell() only initializes the first 2 or 3
2833 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
2834 ** it into a database page. This is not actually a problem, but it
2835 ** does cause a valgrind error when the 1 or 2 bytes of uninitialized
2836 ** data is passed to system call write(). So to avoid this error,
2837 ** zero the first 4 bytes of temp space here.
2839 ** Also: Provide four bytes of initialized space before the
2840 ** beginning of pTmpSpace as an area available to prepend the
2841 ** left-child pointer to the beginning of a cell.
2843 memset(pBt->pTmpSpace, 0, 8);
2844 pBt->pTmpSpace += 4;
2845 return SQLITE_OK;
2849 ** Free the pBt->pTmpSpace allocation
2851 static void freeTempSpace(BtShared *pBt){
2852 if( pBt->pTmpSpace ){
2853 pBt->pTmpSpace -= 4;
2854 sqlite3PageFree(pBt->pTmpSpace);
2855 pBt->pTmpSpace = 0;
2860 ** Close an open database and invalidate all cursors.
2862 int sqlite3BtreeClose(Btree *p){
2863 BtShared *pBt = p->pBt;
2865 /* Close all cursors opened via this handle. */
2866 assert( sqlite3_mutex_held(p->db->mutex) );
2867 sqlite3BtreeEnter(p);
2869 /* Verify that no other cursors have this Btree open */
2870 #ifdef SQLITE_DEBUG
2872 BtCursor *pCur = pBt->pCursor;
2873 while( pCur ){
2874 BtCursor *pTmp = pCur;
2875 pCur = pCur->pNext;
2876 assert( pTmp->pBtree!=p );
2880 #endif
2882 /* Rollback any active transaction and free the handle structure.
2883 ** The call to sqlite3BtreeRollback() drops any table-locks held by
2884 ** this handle.
2886 sqlite3BtreeRollback(p, SQLITE_OK, 0);
2887 sqlite3BtreeLeave(p);
2889 /* If there are still other outstanding references to the shared-btree
2890 ** structure, return now. The remainder of this procedure cleans
2891 ** up the shared-btree.
2893 assert( p->wantToLock==0 && p->locked==0 );
2894 if( !p->sharable || removeFromSharingList(pBt) ){
2895 /* The pBt is no longer on the sharing list, so we can access
2896 ** it without having to hold the mutex.
2898 ** Clean out and delete the BtShared object.
2900 assert( !pBt->pCursor );
2901 sqlite3PagerClose(pBt->pPager, p->db);
2902 if( pBt->xFreeSchema && pBt->pSchema ){
2903 pBt->xFreeSchema(pBt->pSchema);
2905 sqlite3DbFree(0, pBt->pSchema);
2906 freeTempSpace(pBt);
2907 sqlite3_free(pBt);
2910 #ifndef SQLITE_OMIT_SHARED_CACHE
2911 assert( p->wantToLock==0 );
2912 assert( p->locked==0 );
2913 if( p->pPrev ) p->pPrev->pNext = p->pNext;
2914 if( p->pNext ) p->pNext->pPrev = p->pPrev;
2915 #endif
2917 sqlite3_free(p);
2918 return SQLITE_OK;
2922 ** Change the "soft" limit on the number of pages in the cache.
2923 ** Unused and unmodified pages will be recycled when the number of
2924 ** pages in the cache exceeds this soft limit. But the size of the
2925 ** cache is allowed to grow larger than this limit if it contains
2926 ** dirty pages or pages still in active use.
2928 int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2929 BtShared *pBt = p->pBt;
2930 assert( sqlite3_mutex_held(p->db->mutex) );
2931 sqlite3BtreeEnter(p);
2932 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
2933 sqlite3BtreeLeave(p);
2934 return SQLITE_OK;
2938 ** Change the "spill" limit on the number of pages in the cache.
2939 ** If the number of pages exceeds this limit during a write transaction,
2940 ** the pager might attempt to "spill" pages to the journal early in
2941 ** order to free up memory.
2943 ** The value returned is the current spill size. If zero is passed
2944 ** as an argument, no changes are made to the spill size setting, so
2945 ** using mxPage of 0 is a way to query the current spill size.
2947 int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
2948 BtShared *pBt = p->pBt;
2949 int res;
2950 assert( sqlite3_mutex_held(p->db->mutex) );
2951 sqlite3BtreeEnter(p);
2952 res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
2953 sqlite3BtreeLeave(p);
2954 return res;
2957 #if SQLITE_MAX_MMAP_SIZE>0
2959 ** Change the limit on the amount of the database file that may be
2960 ** memory mapped.
2962 int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
2963 BtShared *pBt = p->pBt;
2964 assert( sqlite3_mutex_held(p->db->mutex) );
2965 sqlite3BtreeEnter(p);
2966 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
2967 sqlite3BtreeLeave(p);
2968 return SQLITE_OK;
2970 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
2973 ** Change the way data is synced to disk in order to increase or decrease
2974 ** how well the database resists damage due to OS crashes and power
2975 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
2976 ** there is a high probability of damage) Level 2 is the default. There
2977 ** is a very low but non-zero probability of damage. Level 3 reduces the
2978 ** probability of damage to near zero but with a write performance reduction.
2980 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
2981 int sqlite3BtreeSetPagerFlags(
2982 Btree *p, /* The btree to set the safety level on */
2983 unsigned pgFlags /* Various PAGER_* flags */
2985 BtShared *pBt = p->pBt;
2986 assert( sqlite3_mutex_held(p->db->mutex) );
2987 sqlite3BtreeEnter(p);
2988 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
2989 sqlite3BtreeLeave(p);
2990 return SQLITE_OK;
2992 #endif
2995 ** Change the default pages size and the number of reserved bytes per page.
2996 ** Or, if the page size has already been fixed, return SQLITE_READONLY
2997 ** without changing anything.
2999 ** The page size must be a power of 2 between 512 and 65536. If the page
3000 ** size supplied does not meet this constraint then the page size is not
3001 ** changed.
3003 ** Page sizes are constrained to be a power of two so that the region
3004 ** of the database file used for locking (beginning at PENDING_BYTE,
3005 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
3006 ** at the beginning of a page.
3008 ** If parameter nReserve is less than zero, then the number of reserved
3009 ** bytes per page is left unchanged.
3011 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
3012 ** and autovacuum mode can no longer be changed.
3014 int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
3015 int rc = SQLITE_OK;
3016 int x;
3017 BtShared *pBt = p->pBt;
3018 assert( nReserve>=0 && nReserve<=255 );
3019 sqlite3BtreeEnter(p);
3020 pBt->nReserveWanted = nReserve;
3021 x = pBt->pageSize - pBt->usableSize;
3022 if( nReserve<x ) nReserve = x;
3023 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
3024 sqlite3BtreeLeave(p);
3025 return SQLITE_READONLY;
3027 assert( nReserve>=0 && nReserve<=255 );
3028 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
3029 ((pageSize-1)&pageSize)==0 ){
3030 assert( (pageSize & 7)==0 );
3031 assert( !pBt->pCursor );
3032 if( nReserve>32 && pageSize==512 ) pageSize = 1024;
3033 pBt->pageSize = (u32)pageSize;
3034 freeTempSpace(pBt);
3036 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
3037 pBt->usableSize = pBt->pageSize - (u16)nReserve;
3038 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3039 sqlite3BtreeLeave(p);
3040 return rc;
3044 ** Return the currently defined page size
3046 int sqlite3BtreeGetPageSize(Btree *p){
3047 return p->pBt->pageSize;
3051 ** This function is similar to sqlite3BtreeGetReserve(), except that it
3052 ** may only be called if it is guaranteed that the b-tree mutex is already
3053 ** held.
3055 ** This is useful in one special case in the backup API code where it is
3056 ** known that the shared b-tree mutex is held, but the mutex on the
3057 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
3058 ** were to be called, it might collide with some other operation on the
3059 ** database handle that owns *p, causing undefined behavior.
3061 int sqlite3BtreeGetReserveNoMutex(Btree *p){
3062 int n;
3063 assert( sqlite3_mutex_held(p->pBt->mutex) );
3064 n = p->pBt->pageSize - p->pBt->usableSize;
3065 return n;
3069 ** Return the number of bytes of space at the end of every page that
3070 ** are intentionally left unused. This is the "reserved" space that is
3071 ** sometimes used by extensions.
3073 ** The value returned is the larger of the current reserve size and
3074 ** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES.
3075 ** The amount of reserve can only grow - never shrink.
3077 int sqlite3BtreeGetRequestedReserve(Btree *p){
3078 int n1, n2;
3079 sqlite3BtreeEnter(p);
3080 n1 = (int)p->pBt->nReserveWanted;
3081 n2 = sqlite3BtreeGetReserveNoMutex(p);
3082 sqlite3BtreeLeave(p);
3083 return n1>n2 ? n1 : n2;
3088 ** Set the maximum page count for a database if mxPage is positive.
3089 ** No changes are made if mxPage is 0 or negative.
3090 ** Regardless of the value of mxPage, return the maximum page count.
3092 Pgno sqlite3BtreeMaxPageCount(Btree *p, Pgno mxPage){
3093 Pgno n;
3094 sqlite3BtreeEnter(p);
3095 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
3096 sqlite3BtreeLeave(p);
3097 return n;
3101 ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
3103 ** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
3104 ** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
3105 ** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
3106 ** newFlag==(-1) No changes
3108 ** This routine acts as a query if newFlag is less than zero
3110 ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
3111 ** freelist leaf pages are not written back to the database. Thus in-page
3112 ** deleted content is cleared, but freelist deleted content is not.
3114 ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
3115 ** that freelist leaf pages are written back into the database, increasing
3116 ** the amount of disk I/O.
3118 int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
3119 int b;
3120 if( p==0 ) return 0;
3121 sqlite3BtreeEnter(p);
3122 assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
3123 assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
3124 if( newFlag>=0 ){
3125 p->pBt->btsFlags &= ~BTS_FAST_SECURE;
3126 p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
3128 b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
3129 sqlite3BtreeLeave(p);
3130 return b;
3134 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
3135 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
3136 ** is disabled. The default value for the auto-vacuum property is
3137 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
3139 int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
3140 #ifdef SQLITE_OMIT_AUTOVACUUM
3141 return SQLITE_READONLY;
3142 #else
3143 BtShared *pBt = p->pBt;
3144 int rc = SQLITE_OK;
3145 u8 av = (u8)autoVacuum;
3147 sqlite3BtreeEnter(p);
3148 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
3149 rc = SQLITE_READONLY;
3150 }else{
3151 pBt->autoVacuum = av ?1:0;
3152 pBt->incrVacuum = av==2 ?1:0;
3154 sqlite3BtreeLeave(p);
3155 return rc;
3156 #endif
3160 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
3161 ** enabled 1 is returned. Otherwise 0.
3163 int sqlite3BtreeGetAutoVacuum(Btree *p){
3164 #ifdef SQLITE_OMIT_AUTOVACUUM
3165 return BTREE_AUTOVACUUM_NONE;
3166 #else
3167 int rc;
3168 sqlite3BtreeEnter(p);
3169 rc = (
3170 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
3171 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
3172 BTREE_AUTOVACUUM_INCR
3174 sqlite3BtreeLeave(p);
3175 return rc;
3176 #endif
3180 ** If the user has not set the safety-level for this database connection
3181 ** using "PRAGMA synchronous", and if the safety-level is not already
3182 ** set to the value passed to this function as the second parameter,
3183 ** set it so.
3185 #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
3186 && !defined(SQLITE_OMIT_WAL)
3187 static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
3188 sqlite3 *db;
3189 Db *pDb;
3190 if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
3191 while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
3192 if( pDb->bSyncSet==0
3193 && pDb->safety_level!=safety_level
3194 && pDb!=&db->aDb[1]
3196 pDb->safety_level = safety_level;
3197 sqlite3PagerSetFlags(pBt->pPager,
3198 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
3202 #else
3203 # define setDefaultSyncFlag(pBt,safety_level)
3204 #endif
3206 /* Forward declaration */
3207 static int newDatabase(BtShared*);
3211 ** Get a reference to pPage1 of the database file. This will
3212 ** also acquire a readlock on that file.
3214 ** SQLITE_OK is returned on success. If the file is not a
3215 ** well-formed database file, then SQLITE_CORRUPT is returned.
3216 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
3217 ** is returned if we run out of memory.
3219 static int lockBtree(BtShared *pBt){
3220 int rc; /* Result code from subfunctions */
3221 MemPage *pPage1; /* Page 1 of the database file */
3222 u32 nPage; /* Number of pages in the database */
3223 u32 nPageFile = 0; /* Number of pages in the database file */
3225 assert( sqlite3_mutex_held(pBt->mutex) );
3226 assert( pBt->pPage1==0 );
3227 rc = sqlite3PagerSharedLock(pBt->pPager);
3228 if( rc!=SQLITE_OK ) return rc;
3229 rc = btreeGetPage(pBt, 1, &pPage1, 0);
3230 if( rc!=SQLITE_OK ) return rc;
3232 /* Do some checking to help insure the file we opened really is
3233 ** a valid database file.
3235 nPage = get4byte(28+(u8*)pPage1->aData);
3236 sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
3237 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
3238 nPage = nPageFile;
3240 if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
3241 nPage = 0;
3243 if( nPage>0 ){
3244 u32 pageSize;
3245 u32 usableSize;
3246 u8 *page1 = pPage1->aData;
3247 rc = SQLITE_NOTADB;
3248 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
3249 ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
3250 ** 61 74 20 33 00. */
3251 if( memcmp(page1, zMagicHeader, 16)!=0 ){
3252 goto page1_init_failed;
3255 #ifdef SQLITE_OMIT_WAL
3256 if( page1[18]>1 ){
3257 pBt->btsFlags |= BTS_READ_ONLY;
3259 if( page1[19]>1 ){
3260 goto page1_init_failed;
3262 #else
3263 if( page1[18]>2 ){
3264 pBt->btsFlags |= BTS_READ_ONLY;
3266 if( page1[19]>2 ){
3267 goto page1_init_failed;
3270 /* If the read version is set to 2, this database should be accessed
3271 ** in WAL mode. If the log is not already open, open it now. Then
3272 ** return SQLITE_OK and return without populating BtShared.pPage1.
3273 ** The caller detects this and calls this function again. This is
3274 ** required as the version of page 1 currently in the page1 buffer
3275 ** may not be the latest version - there may be a newer one in the log
3276 ** file.
3278 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
3279 int isOpen = 0;
3280 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
3281 if( rc!=SQLITE_OK ){
3282 goto page1_init_failed;
3283 }else{
3284 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
3285 if( isOpen==0 ){
3286 releasePageOne(pPage1);
3287 return SQLITE_OK;
3290 rc = SQLITE_NOTADB;
3291 }else{
3292 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
3294 #endif
3296 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
3297 ** fractions and the leaf payload fraction values must be 64, 32, and 32.
3299 ** The original design allowed these amounts to vary, but as of
3300 ** version 3.6.0, we require them to be fixed.
3302 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
3303 goto page1_init_failed;
3305 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
3306 ** determined by the 2-byte integer located at an offset of 16 bytes from
3307 ** the beginning of the database file. */
3308 pageSize = (page1[16]<<8) | (page1[17]<<16);
3309 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
3310 ** between 512 and 65536 inclusive. */
3311 if( ((pageSize-1)&pageSize)!=0
3312 || pageSize>SQLITE_MAX_PAGE_SIZE
3313 || pageSize<=256
3315 goto page1_init_failed;
3317 assert( (pageSize & 7)==0 );
3318 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
3319 ** integer at offset 20 is the number of bytes of space at the end of
3320 ** each page to reserve for extensions.
3322 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
3323 ** determined by the one-byte unsigned integer found at an offset of 20
3324 ** into the database file header. */
3325 usableSize = pageSize - page1[20];
3326 if( (u32)pageSize!=pBt->pageSize ){
3327 /* After reading the first page of the database assuming a page size
3328 ** of BtShared.pageSize, we have discovered that the page-size is
3329 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
3330 ** zero and return SQLITE_OK. The caller will call this function
3331 ** again with the correct page-size.
3333 releasePageOne(pPage1);
3334 pBt->usableSize = usableSize;
3335 pBt->pageSize = pageSize;
3336 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3337 freeTempSpace(pBt);
3338 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
3339 pageSize-usableSize);
3340 return rc;
3342 if( nPage>nPageFile ){
3343 if( sqlite3WritableSchema(pBt->db)==0 ){
3344 rc = SQLITE_CORRUPT_BKPT;
3345 goto page1_init_failed;
3346 }else{
3347 nPage = nPageFile;
3350 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
3351 ** be less than 480. In other words, if the page size is 512, then the
3352 ** reserved space size cannot exceed 32. */
3353 if( usableSize<480 ){
3354 goto page1_init_failed;
3356 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3357 pBt->pageSize = pageSize;
3358 pBt->usableSize = usableSize;
3359 #ifndef SQLITE_OMIT_AUTOVACUUM
3360 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
3361 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
3362 #endif
3365 /* maxLocal is the maximum amount of payload to store locally for
3366 ** a cell. Make sure it is small enough so that at least minFanout
3367 ** cells can will fit on one page. We assume a 10-byte page header.
3368 ** Besides the payload, the cell must store:
3369 ** 2-byte pointer to the cell
3370 ** 4-byte child pointer
3371 ** 9-byte nKey value
3372 ** 4-byte nData value
3373 ** 4-byte overflow page pointer
3374 ** So a cell consists of a 2-byte pointer, a header which is as much as
3375 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
3376 ** page pointer.
3378 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
3379 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
3380 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
3381 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
3382 if( pBt->maxLocal>127 ){
3383 pBt->max1bytePayload = 127;
3384 }else{
3385 pBt->max1bytePayload = (u8)pBt->maxLocal;
3387 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
3388 pBt->pPage1 = pPage1;
3389 pBt->nPage = nPage;
3390 return SQLITE_OK;
3392 page1_init_failed:
3393 releasePageOne(pPage1);
3394 pBt->pPage1 = 0;
3395 return rc;
3398 #ifndef NDEBUG
3400 ** Return the number of cursors open on pBt. This is for use
3401 ** in assert() expressions, so it is only compiled if NDEBUG is not
3402 ** defined.
3404 ** Only write cursors are counted if wrOnly is true. If wrOnly is
3405 ** false then all cursors are counted.
3407 ** For the purposes of this routine, a cursor is any cursor that
3408 ** is capable of reading or writing to the database. Cursors that
3409 ** have been tripped into the CURSOR_FAULT state are not counted.
3411 static int countValidCursors(BtShared *pBt, int wrOnly){
3412 BtCursor *pCur;
3413 int r = 0;
3414 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3415 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
3416 && pCur->eState!=CURSOR_FAULT ) r++;
3418 return r;
3420 #endif
3423 ** If there are no outstanding cursors and we are not in the middle
3424 ** of a transaction but there is a read lock on the database, then
3425 ** this routine unrefs the first page of the database file which
3426 ** has the effect of releasing the read lock.
3428 ** If there is a transaction in progress, this routine is a no-op.
3430 static void unlockBtreeIfUnused(BtShared *pBt){
3431 assert( sqlite3_mutex_held(pBt->mutex) );
3432 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
3433 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
3434 MemPage *pPage1 = pBt->pPage1;
3435 assert( pPage1->aData );
3436 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
3437 pBt->pPage1 = 0;
3438 releasePageOne(pPage1);
3443 ** If pBt points to an empty file then convert that empty file
3444 ** into a new empty database by initializing the first page of
3445 ** the database.
3447 static int newDatabase(BtShared *pBt){
3448 MemPage *pP1;
3449 unsigned char *data;
3450 int rc;
3452 assert( sqlite3_mutex_held(pBt->mutex) );
3453 if( pBt->nPage>0 ){
3454 return SQLITE_OK;
3456 pP1 = pBt->pPage1;
3457 assert( pP1!=0 );
3458 data = pP1->aData;
3459 rc = sqlite3PagerWrite(pP1->pDbPage);
3460 if( rc ) return rc;
3461 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
3462 assert( sizeof(zMagicHeader)==16 );
3463 data[16] = (u8)((pBt->pageSize>>8)&0xff);
3464 data[17] = (u8)((pBt->pageSize>>16)&0xff);
3465 data[18] = 1;
3466 data[19] = 1;
3467 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
3468 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
3469 data[21] = 64;
3470 data[22] = 32;
3471 data[23] = 32;
3472 memset(&data[24], 0, 100-24);
3473 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
3474 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3475 #ifndef SQLITE_OMIT_AUTOVACUUM
3476 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
3477 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
3478 put4byte(&data[36 + 4*4], pBt->autoVacuum);
3479 put4byte(&data[36 + 7*4], pBt->incrVacuum);
3480 #endif
3481 pBt->nPage = 1;
3482 data[31] = 1;
3483 return SQLITE_OK;
3487 ** Initialize the first page of the database file (creating a database
3488 ** consisting of a single page and no schema objects). Return SQLITE_OK
3489 ** if successful, or an SQLite error code otherwise.
3491 int sqlite3BtreeNewDb(Btree *p){
3492 int rc;
3493 sqlite3BtreeEnter(p);
3494 p->pBt->nPage = 0;
3495 rc = newDatabase(p->pBt);
3496 sqlite3BtreeLeave(p);
3497 return rc;
3501 ** Attempt to start a new transaction. A write-transaction
3502 ** is started if the second argument is nonzero, otherwise a read-
3503 ** transaction. If the second argument is 2 or more and exclusive
3504 ** transaction is started, meaning that no other process is allowed
3505 ** to access the database. A preexisting transaction may not be
3506 ** upgraded to exclusive by calling this routine a second time - the
3507 ** exclusivity flag only works for a new transaction.
3509 ** A write-transaction must be started before attempting any
3510 ** changes to the database. None of the following routines
3511 ** will work unless a transaction is started first:
3513 ** sqlite3BtreeCreateTable()
3514 ** sqlite3BtreeCreateIndex()
3515 ** sqlite3BtreeClearTable()
3516 ** sqlite3BtreeDropTable()
3517 ** sqlite3BtreeInsert()
3518 ** sqlite3BtreeDelete()
3519 ** sqlite3BtreeUpdateMeta()
3521 ** If an initial attempt to acquire the lock fails because of lock contention
3522 ** and the database was previously unlocked, then invoke the busy handler
3523 ** if there is one. But if there was previously a read-lock, do not
3524 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
3525 ** returned when there is already a read-lock in order to avoid a deadlock.
3527 ** Suppose there are two processes A and B. A has a read lock and B has
3528 ** a reserved lock. B tries to promote to exclusive but is blocked because
3529 ** of A's read lock. A tries to promote to reserved but is blocked by B.
3530 ** One or the other of the two processes must give way or there can be
3531 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
3532 ** when A already has a read lock, we encourage A to give up and let B
3533 ** proceed.
3535 static SQLITE_NOINLINE int btreeBeginTrans(
3536 Btree *p, /* The btree in which to start the transaction */
3537 int wrflag, /* True to start a write transaction */
3538 int *pSchemaVersion /* Put schema version number here, if not NULL */
3540 BtShared *pBt = p->pBt;
3541 Pager *pPager = pBt->pPager;
3542 int rc = SQLITE_OK;
3544 sqlite3BtreeEnter(p);
3545 btreeIntegrity(p);
3547 /* If the btree is already in a write-transaction, or it
3548 ** is already in a read-transaction and a read-transaction
3549 ** is requested, this is a no-op.
3551 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
3552 goto trans_begun;
3554 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
3556 if( (p->db->flags & SQLITE_ResetDatabase)
3557 && sqlite3PagerIsreadonly(pPager)==0
3559 pBt->btsFlags &= ~BTS_READ_ONLY;
3562 /* Write transactions are not possible on a read-only database */
3563 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
3564 rc = SQLITE_READONLY;
3565 goto trans_begun;
3568 #ifndef SQLITE_OMIT_SHARED_CACHE
3570 sqlite3 *pBlock = 0;
3571 /* If another database handle has already opened a write transaction
3572 ** on this shared-btree structure and a second write transaction is
3573 ** requested, return SQLITE_LOCKED.
3575 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
3576 || (pBt->btsFlags & BTS_PENDING)!=0
3578 pBlock = pBt->pWriter->db;
3579 }else if( wrflag>1 ){
3580 BtLock *pIter;
3581 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
3582 if( pIter->pBtree!=p ){
3583 pBlock = pIter->pBtree->db;
3584 break;
3588 if( pBlock ){
3589 sqlite3ConnectionBlocked(p->db, pBlock);
3590 rc = SQLITE_LOCKED_SHAREDCACHE;
3591 goto trans_begun;
3594 #endif
3596 /* Any read-only or read-write transaction implies a read-lock on
3597 ** page 1. So if some other shared-cache client already has a write-lock
3598 ** on page 1, the transaction cannot be opened. */
3599 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
3600 if( SQLITE_OK!=rc ) goto trans_begun;
3602 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
3603 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
3604 do {
3605 sqlite3PagerWalDb(pPager, p->db);
3607 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3608 /* If transitioning from no transaction directly to a write transaction,
3609 ** block for the WRITER lock first if possible. */
3610 if( pBt->pPage1==0 && wrflag ){
3611 assert( pBt->inTransaction==TRANS_NONE );
3612 rc = sqlite3PagerWalWriteLock(pPager, 1);
3613 if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break;
3615 #endif
3617 /* Call lockBtree() until either pBt->pPage1 is populated or
3618 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
3619 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
3620 ** reading page 1 it discovers that the page-size of the database
3621 ** file is not pBt->pageSize. In this case lockBtree() will update
3622 ** pBt->pageSize to the page-size of the file on disk.
3624 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
3626 if( rc==SQLITE_OK && wrflag ){
3627 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
3628 rc = SQLITE_READONLY;
3629 }else{
3630 rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db));
3631 if( rc==SQLITE_OK ){
3632 rc = newDatabase(pBt);
3633 }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
3634 /* if there was no transaction opened when this function was
3635 ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
3636 ** code to SQLITE_BUSY. */
3637 rc = SQLITE_BUSY;
3642 if( rc!=SQLITE_OK ){
3643 (void)sqlite3PagerWalWriteLock(pPager, 0);
3644 unlockBtreeIfUnused(pBt);
3646 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
3647 btreeInvokeBusyHandler(pBt) );
3648 sqlite3PagerWalDb(pPager, 0);
3649 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3650 if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
3651 #endif
3653 if( rc==SQLITE_OK ){
3654 if( p->inTrans==TRANS_NONE ){
3655 pBt->nTransaction++;
3656 #ifndef SQLITE_OMIT_SHARED_CACHE
3657 if( p->sharable ){
3658 assert( p->lock.pBtree==p && p->lock.iTable==1 );
3659 p->lock.eLock = READ_LOCK;
3660 p->lock.pNext = pBt->pLock;
3661 pBt->pLock = &p->lock;
3663 #endif
3665 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
3666 if( p->inTrans>pBt->inTransaction ){
3667 pBt->inTransaction = p->inTrans;
3669 if( wrflag ){
3670 MemPage *pPage1 = pBt->pPage1;
3671 #ifndef SQLITE_OMIT_SHARED_CACHE
3672 assert( !pBt->pWriter );
3673 pBt->pWriter = p;
3674 pBt->btsFlags &= ~BTS_EXCLUSIVE;
3675 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
3676 #endif
3678 /* If the db-size header field is incorrect (as it may be if an old
3679 ** client has been writing the database file), update it now. Doing
3680 ** this sooner rather than later means the database size can safely
3681 ** re-read the database size from page 1 if a savepoint or transaction
3682 ** rollback occurs within the transaction.
3684 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
3685 rc = sqlite3PagerWrite(pPage1->pDbPage);
3686 if( rc==SQLITE_OK ){
3687 put4byte(&pPage1->aData[28], pBt->nPage);
3693 trans_begun:
3694 if( rc==SQLITE_OK ){
3695 if( pSchemaVersion ){
3696 *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
3698 if( wrflag ){
3699 /* This call makes sure that the pager has the correct number of
3700 ** open savepoints. If the second parameter is greater than 0 and
3701 ** the sub-journal is not already open, then it will be opened here.
3703 rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint);
3707 btreeIntegrity(p);
3708 sqlite3BtreeLeave(p);
3709 return rc;
3711 int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
3712 BtShared *pBt;
3713 if( p->sharable
3714 || p->inTrans==TRANS_NONE
3715 || (p->inTrans==TRANS_READ && wrflag!=0)
3717 return btreeBeginTrans(p,wrflag,pSchemaVersion);
3719 pBt = p->pBt;
3720 if( pSchemaVersion ){
3721 *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
3723 if( wrflag ){
3724 /* This call makes sure that the pager has the correct number of
3725 ** open savepoints. If the second parameter is greater than 0 and
3726 ** the sub-journal is not already open, then it will be opened here.
3728 return sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
3729 }else{
3730 return SQLITE_OK;
3734 #ifndef SQLITE_OMIT_AUTOVACUUM
3737 ** Set the pointer-map entries for all children of page pPage. Also, if
3738 ** pPage contains cells that point to overflow pages, set the pointer
3739 ** map entries for the overflow pages as well.
3741 static int setChildPtrmaps(MemPage *pPage){
3742 int i; /* Counter variable */
3743 int nCell; /* Number of cells in page pPage */
3744 int rc; /* Return code */
3745 BtShared *pBt = pPage->pBt;
3746 Pgno pgno = pPage->pgno;
3748 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3749 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3750 if( rc!=SQLITE_OK ) return rc;
3751 nCell = pPage->nCell;
3753 for(i=0; i<nCell; i++){
3754 u8 *pCell = findCell(pPage, i);
3756 ptrmapPutOvflPtr(pPage, pPage, pCell, &rc);
3758 if( !pPage->leaf ){
3759 Pgno childPgno = get4byte(pCell);
3760 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3764 if( !pPage->leaf ){
3765 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
3766 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3769 return rc;
3773 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
3774 ** that it points to iTo. Parameter eType describes the type of pointer to
3775 ** be modified, as follows:
3777 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
3778 ** page of pPage.
3780 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3781 ** page pointed to by one of the cells on pPage.
3783 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3784 ** overflow page in the list.
3786 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
3787 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3788 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
3789 if( eType==PTRMAP_OVERFLOW2 ){
3790 /* The pointer is always the first 4 bytes of the page in this case. */
3791 if( get4byte(pPage->aData)!=iFrom ){
3792 return SQLITE_CORRUPT_PAGE(pPage);
3794 put4byte(pPage->aData, iTo);
3795 }else{
3796 int i;
3797 int nCell;
3798 int rc;
3800 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3801 if( rc ) return rc;
3802 nCell = pPage->nCell;
3804 for(i=0; i<nCell; i++){
3805 u8 *pCell = findCell(pPage, i);
3806 if( eType==PTRMAP_OVERFLOW1 ){
3807 CellInfo info;
3808 pPage->xParseCell(pPage, pCell, &info);
3809 if( info.nLocal<info.nPayload ){
3810 if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
3811 return SQLITE_CORRUPT_PAGE(pPage);
3813 if( iFrom==get4byte(pCell+info.nSize-4) ){
3814 put4byte(pCell+info.nSize-4, iTo);
3815 break;
3818 }else{
3819 if( pCell+4 > pPage->aData+pPage->pBt->usableSize ){
3820 return SQLITE_CORRUPT_PAGE(pPage);
3822 if( get4byte(pCell)==iFrom ){
3823 put4byte(pCell, iTo);
3824 break;
3829 if( i==nCell ){
3830 if( eType!=PTRMAP_BTREE ||
3831 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
3832 return SQLITE_CORRUPT_PAGE(pPage);
3834 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3837 return SQLITE_OK;
3842 ** Move the open database page pDbPage to location iFreePage in the
3843 ** database. The pDbPage reference remains valid.
3845 ** The isCommit flag indicates that there is no need to remember that
3846 ** the journal needs to be sync()ed before database page pDbPage->pgno
3847 ** can be written to. The caller has already promised not to write to that
3848 ** page.
3850 static int relocatePage(
3851 BtShared *pBt, /* Btree */
3852 MemPage *pDbPage, /* Open page to move */
3853 u8 eType, /* Pointer map 'type' entry for pDbPage */
3854 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
3855 Pgno iFreePage, /* The location to move pDbPage to */
3856 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
3858 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
3859 Pgno iDbPage = pDbPage->pgno;
3860 Pager *pPager = pBt->pPager;
3861 int rc;
3863 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3864 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
3865 assert( sqlite3_mutex_held(pBt->mutex) );
3866 assert( pDbPage->pBt==pBt );
3867 if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
3869 /* Move page iDbPage from its current location to page number iFreePage */
3870 TRACE(("AUTOVACUUM: Moving %u to free page %u (ptr page %u type %u)\n",
3871 iDbPage, iFreePage, iPtrPage, eType));
3872 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
3873 if( rc!=SQLITE_OK ){
3874 return rc;
3876 pDbPage->pgno = iFreePage;
3878 /* If pDbPage was a btree-page, then it may have child pages and/or cells
3879 ** that point to overflow pages. The pointer map entries for all these
3880 ** pages need to be changed.
3882 ** If pDbPage is an overflow page, then the first 4 bytes may store a
3883 ** pointer to a subsequent overflow page. If this is the case, then
3884 ** the pointer map needs to be updated for the subsequent overflow page.
3886 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
3887 rc = setChildPtrmaps(pDbPage);
3888 if( rc!=SQLITE_OK ){
3889 return rc;
3891 }else{
3892 Pgno nextOvfl = get4byte(pDbPage->aData);
3893 if( nextOvfl!=0 ){
3894 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
3895 if( rc!=SQLITE_OK ){
3896 return rc;
3901 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3902 ** that it points at iFreePage. Also fix the pointer map entry for
3903 ** iPtrPage.
3905 if( eType!=PTRMAP_ROOTPAGE ){
3906 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
3907 if( rc!=SQLITE_OK ){
3908 return rc;
3910 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
3911 if( rc!=SQLITE_OK ){
3912 releasePage(pPtrPage);
3913 return rc;
3915 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
3916 releasePage(pPtrPage);
3917 if( rc==SQLITE_OK ){
3918 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
3921 return rc;
3924 /* Forward declaration required by incrVacuumStep(). */
3925 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
3928 ** Perform a single step of an incremental-vacuum. If successful, return
3929 ** SQLITE_OK. If there is no work to do (and therefore no point in
3930 ** calling this function again), return SQLITE_DONE. Or, if an error
3931 ** occurs, return some other error code.
3933 ** More specifically, this function attempts to re-organize the database so
3934 ** that the last page of the file currently in use is no longer in use.
3936 ** Parameter nFin is the number of pages that this database would contain
3937 ** were this function called until it returns SQLITE_DONE.
3939 ** If the bCommit parameter is non-zero, this function assumes that the
3940 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
3941 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
3942 ** operation, or false for an incremental vacuum.
3944 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
3945 Pgno nFreeList; /* Number of pages still on the free-list */
3946 int rc;
3948 assert( sqlite3_mutex_held(pBt->mutex) );
3949 assert( iLastPg>nFin );
3951 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
3952 u8 eType;
3953 Pgno iPtrPage;
3955 nFreeList = get4byte(&pBt->pPage1->aData[36]);
3956 if( nFreeList==0 ){
3957 return SQLITE_DONE;
3960 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3961 if( rc!=SQLITE_OK ){
3962 return rc;
3964 if( eType==PTRMAP_ROOTPAGE ){
3965 return SQLITE_CORRUPT_BKPT;
3968 if( eType==PTRMAP_FREEPAGE ){
3969 if( bCommit==0 ){
3970 /* Remove the page from the files free-list. This is not required
3971 ** if bCommit is non-zero. In that case, the free-list will be
3972 ** truncated to zero after this function returns, so it doesn't
3973 ** matter if it still contains some garbage entries.
3975 Pgno iFreePg;
3976 MemPage *pFreePg;
3977 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
3978 if( rc!=SQLITE_OK ){
3979 return rc;
3981 assert( iFreePg==iLastPg );
3982 releasePage(pFreePg);
3984 } else {
3985 Pgno iFreePg; /* Index of free page to move pLastPg to */
3986 MemPage *pLastPg;
3987 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
3988 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
3990 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
3991 if( rc!=SQLITE_OK ){
3992 return rc;
3995 /* If bCommit is zero, this loop runs exactly once and page pLastPg
3996 ** is swapped with the first free page pulled off the free list.
3998 ** On the other hand, if bCommit is greater than zero, then keep
3999 ** looping until a free-page located within the first nFin pages
4000 ** of the file is found.
4002 if( bCommit==0 ){
4003 eMode = BTALLOC_LE;
4004 iNear = nFin;
4006 do {
4007 MemPage *pFreePg;
4008 Pgno dbSize = btreePagecount(pBt);
4009 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
4010 if( rc!=SQLITE_OK ){
4011 releasePage(pLastPg);
4012 return rc;
4014 releasePage(pFreePg);
4015 if( iFreePg>dbSize ){
4016 releasePage(pLastPg);
4017 return SQLITE_CORRUPT_BKPT;
4019 }while( bCommit && iFreePg>nFin );
4020 assert( iFreePg<iLastPg );
4022 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
4023 releasePage(pLastPg);
4024 if( rc!=SQLITE_OK ){
4025 return rc;
4030 if( bCommit==0 ){
4031 do {
4032 iLastPg--;
4033 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
4034 pBt->bDoTruncate = 1;
4035 pBt->nPage = iLastPg;
4037 return SQLITE_OK;
4041 ** The database opened by the first argument is an auto-vacuum database
4042 ** nOrig pages in size containing nFree free pages. Return the expected
4043 ** size of the database in pages following an auto-vacuum operation.
4045 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
4046 int nEntry; /* Number of entries on one ptrmap page */
4047 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
4048 Pgno nFin; /* Return value */
4050 nEntry = pBt->usableSize/5;
4051 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
4052 nFin = nOrig - nFree - nPtrmap;
4053 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
4054 nFin--;
4056 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
4057 nFin--;
4060 return nFin;
4064 ** A write-transaction must be opened before calling this function.
4065 ** It performs a single unit of work towards an incremental vacuum.
4067 ** If the incremental vacuum is finished after this function has run,
4068 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
4069 ** SQLITE_OK is returned. Otherwise an SQLite error code.
4071 int sqlite3BtreeIncrVacuum(Btree *p){
4072 int rc;
4073 BtShared *pBt = p->pBt;
4075 sqlite3BtreeEnter(p);
4076 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
4077 if( !pBt->autoVacuum ){
4078 rc = SQLITE_DONE;
4079 }else{
4080 Pgno nOrig = btreePagecount(pBt);
4081 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
4082 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
4084 if( nOrig<nFin || nFree>=nOrig ){
4085 rc = SQLITE_CORRUPT_BKPT;
4086 }else if( nFree>0 ){
4087 rc = saveAllCursors(pBt, 0, 0);
4088 if( rc==SQLITE_OK ){
4089 invalidateAllOverflowCache(pBt);
4090 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
4092 if( rc==SQLITE_OK ){
4093 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
4094 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
4096 }else{
4097 rc = SQLITE_DONE;
4100 sqlite3BtreeLeave(p);
4101 return rc;
4105 ** This routine is called prior to sqlite3PagerCommit when a transaction
4106 ** is committed for an auto-vacuum database.
4108 static int autoVacuumCommit(Btree *p){
4109 int rc = SQLITE_OK;
4110 Pager *pPager;
4111 BtShared *pBt;
4112 sqlite3 *db;
4113 VVA_ONLY( int nRef );
4115 assert( p!=0 );
4116 pBt = p->pBt;
4117 pPager = pBt->pPager;
4118 VVA_ONLY( nRef = sqlite3PagerRefcount(pPager); )
4120 assert( sqlite3_mutex_held(pBt->mutex) );
4121 invalidateAllOverflowCache(pBt);
4122 assert(pBt->autoVacuum);
4123 if( !pBt->incrVacuum ){
4124 Pgno nFin; /* Number of pages in database after autovacuuming */
4125 Pgno nFree; /* Number of pages on the freelist initially */
4126 Pgno nVac; /* Number of pages to vacuum */
4127 Pgno iFree; /* The next page to be freed */
4128 Pgno nOrig; /* Database size before freeing */
4130 nOrig = btreePagecount(pBt);
4131 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
4132 /* It is not possible to create a database for which the final page
4133 ** is either a pointer-map page or the pending-byte page. If one
4134 ** is encountered, this indicates corruption.
4136 return SQLITE_CORRUPT_BKPT;
4139 nFree = get4byte(&pBt->pPage1->aData[36]);
4140 db = p->db;
4141 if( db->xAutovacPages ){
4142 int iDb;
4143 for(iDb=0; ALWAYS(iDb<db->nDb); iDb++){
4144 if( db->aDb[iDb].pBt==p ) break;
4146 nVac = db->xAutovacPages(
4147 db->pAutovacPagesArg,
4148 db->aDb[iDb].zDbSName,
4149 nOrig,
4150 nFree,
4151 pBt->pageSize
4153 if( nVac>nFree ){
4154 nVac = nFree;
4156 if( nVac==0 ){
4157 return SQLITE_OK;
4159 }else{
4160 nVac = nFree;
4162 nFin = finalDbSize(pBt, nOrig, nVac);
4163 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
4164 if( nFin<nOrig ){
4165 rc = saveAllCursors(pBt, 0, 0);
4167 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
4168 rc = incrVacuumStep(pBt, nFin, iFree, nVac==nFree);
4170 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
4171 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
4172 if( nVac==nFree ){
4173 put4byte(&pBt->pPage1->aData[32], 0);
4174 put4byte(&pBt->pPage1->aData[36], 0);
4176 put4byte(&pBt->pPage1->aData[28], nFin);
4177 pBt->bDoTruncate = 1;
4178 pBt->nPage = nFin;
4180 if( rc!=SQLITE_OK ){
4181 sqlite3PagerRollback(pPager);
4185 assert( nRef>=sqlite3PagerRefcount(pPager) );
4186 return rc;
4189 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
4190 # define setChildPtrmaps(x) SQLITE_OK
4191 #endif
4194 ** This routine does the first phase of a two-phase commit. This routine
4195 ** causes a rollback journal to be created (if it does not already exist)
4196 ** and populated with enough information so that if a power loss occurs
4197 ** the database can be restored to its original state by playing back
4198 ** the journal. Then the contents of the journal are flushed out to
4199 ** the disk. After the journal is safely on oxide, the changes to the
4200 ** database are written into the database file and flushed to oxide.
4201 ** At the end of this call, the rollback journal still exists on the
4202 ** disk and we are still holding all locks, so the transaction has not
4203 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
4204 ** commit process.
4206 ** This call is a no-op if no write-transaction is currently active on pBt.
4208 ** Otherwise, sync the database file for the btree pBt. zSuperJrnl points to
4209 ** the name of a super-journal file that should be written into the
4210 ** individual journal file, or is NULL, indicating no super-journal file
4211 ** (single database transaction).
4213 ** When this is called, the super-journal should already have been
4214 ** created, populated with this journal pointer and synced to disk.
4216 ** Once this is routine has returned, the only thing required to commit
4217 ** the write-transaction for this database file is to delete the journal.
4219 int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zSuperJrnl){
4220 int rc = SQLITE_OK;
4221 if( p->inTrans==TRANS_WRITE ){
4222 BtShared *pBt = p->pBt;
4223 sqlite3BtreeEnter(p);
4224 #ifndef SQLITE_OMIT_AUTOVACUUM
4225 if( pBt->autoVacuum ){
4226 rc = autoVacuumCommit(p);
4227 if( rc!=SQLITE_OK ){
4228 sqlite3BtreeLeave(p);
4229 return rc;
4232 if( pBt->bDoTruncate ){
4233 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
4235 #endif
4236 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0);
4237 sqlite3BtreeLeave(p);
4239 return rc;
4243 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
4244 ** at the conclusion of a transaction.
4246 static void btreeEndTransaction(Btree *p){
4247 BtShared *pBt = p->pBt;
4248 sqlite3 *db = p->db;
4249 assert( sqlite3BtreeHoldsMutex(p) );
4251 #ifndef SQLITE_OMIT_AUTOVACUUM
4252 pBt->bDoTruncate = 0;
4253 #endif
4254 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
4255 /* If there are other active statements that belong to this database
4256 ** handle, downgrade to a read-only transaction. The other statements
4257 ** may still be reading from the database. */
4258 downgradeAllSharedCacheTableLocks(p);
4259 p->inTrans = TRANS_READ;
4260 }else{
4261 /* If the handle had any kind of transaction open, decrement the
4262 ** transaction count of the shared btree. If the transaction count
4263 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
4264 ** call below will unlock the pager. */
4265 if( p->inTrans!=TRANS_NONE ){
4266 clearAllSharedCacheTableLocks(p);
4267 pBt->nTransaction--;
4268 if( 0==pBt->nTransaction ){
4269 pBt->inTransaction = TRANS_NONE;
4273 /* Set the current transaction state to TRANS_NONE and unlock the
4274 ** pager if this call closed the only read or write transaction. */
4275 p->inTrans = TRANS_NONE;
4276 unlockBtreeIfUnused(pBt);
4279 btreeIntegrity(p);
4283 ** Commit the transaction currently in progress.
4285 ** This routine implements the second phase of a 2-phase commit. The
4286 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
4287 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
4288 ** routine did all the work of writing information out to disk and flushing the
4289 ** contents so that they are written onto the disk platter. All this
4290 ** routine has to do is delete or truncate or zero the header in the
4291 ** the rollback journal (which causes the transaction to commit) and
4292 ** drop locks.
4294 ** Normally, if an error occurs while the pager layer is attempting to
4295 ** finalize the underlying journal file, this function returns an error and
4296 ** the upper layer will attempt a rollback. However, if the second argument
4297 ** is non-zero then this b-tree transaction is part of a multi-file
4298 ** transaction. In this case, the transaction has already been committed
4299 ** (by deleting a super-journal file) and the caller will ignore this
4300 ** functions return code. So, even if an error occurs in the pager layer,
4301 ** reset the b-tree objects internal state to indicate that the write
4302 ** transaction has been closed. This is quite safe, as the pager will have
4303 ** transitioned to the error state.
4305 ** This will release the write lock on the database file. If there
4306 ** are no active cursors, it also releases the read lock.
4308 int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
4310 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
4311 sqlite3BtreeEnter(p);
4312 btreeIntegrity(p);
4314 /* If the handle has a write-transaction open, commit the shared-btrees
4315 ** transaction and set the shared state to TRANS_READ.
4317 if( p->inTrans==TRANS_WRITE ){
4318 int rc;
4319 BtShared *pBt = p->pBt;
4320 assert( pBt->inTransaction==TRANS_WRITE );
4321 assert( pBt->nTransaction>0 );
4322 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
4323 if( rc!=SQLITE_OK && bCleanup==0 ){
4324 sqlite3BtreeLeave(p);
4325 return rc;
4327 p->iBDataVersion--; /* Compensate for pPager->iDataVersion++; */
4328 pBt->inTransaction = TRANS_READ;
4329 btreeClearHasContent(pBt);
4332 btreeEndTransaction(p);
4333 sqlite3BtreeLeave(p);
4334 return SQLITE_OK;
4338 ** Do both phases of a commit.
4340 int sqlite3BtreeCommit(Btree *p){
4341 int rc;
4342 sqlite3BtreeEnter(p);
4343 rc = sqlite3BtreeCommitPhaseOne(p, 0);
4344 if( rc==SQLITE_OK ){
4345 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
4347 sqlite3BtreeLeave(p);
4348 return rc;
4352 ** This routine sets the state to CURSOR_FAULT and the error
4353 ** code to errCode for every cursor on any BtShared that pBtree
4354 ** references. Or if the writeOnly flag is set to 1, then only
4355 ** trip write cursors and leave read cursors unchanged.
4357 ** Every cursor is a candidate to be tripped, including cursors
4358 ** that belong to other database connections that happen to be
4359 ** sharing the cache with pBtree.
4361 ** This routine gets called when a rollback occurs. If the writeOnly
4362 ** flag is true, then only write-cursors need be tripped - read-only
4363 ** cursors save their current positions so that they may continue
4364 ** following the rollback. Or, if writeOnly is false, all cursors are
4365 ** tripped. In general, writeOnly is false if the transaction being
4366 ** rolled back modified the database schema. In this case b-tree root
4367 ** pages may be moved or deleted from the database altogether, making
4368 ** it unsafe for read cursors to continue.
4370 ** If the writeOnly flag is true and an error is encountered while
4371 ** saving the current position of a read-only cursor, all cursors,
4372 ** including all read-cursors are tripped.
4374 ** SQLITE_OK is returned if successful, or if an error occurs while
4375 ** saving a cursor position, an SQLite error code.
4377 int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
4378 BtCursor *p;
4379 int rc = SQLITE_OK;
4381 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
4382 if( pBtree ){
4383 sqlite3BtreeEnter(pBtree);
4384 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
4385 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
4386 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
4387 rc = saveCursorPosition(p);
4388 if( rc!=SQLITE_OK ){
4389 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
4390 break;
4393 }else{
4394 sqlite3BtreeClearCursor(p);
4395 p->eState = CURSOR_FAULT;
4396 p->skipNext = errCode;
4398 btreeReleaseAllCursorPages(p);
4400 sqlite3BtreeLeave(pBtree);
4402 return rc;
4406 ** Set the pBt->nPage field correctly, according to the current
4407 ** state of the database. Assume pBt->pPage1 is valid.
4409 static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){
4410 int nPage = get4byte(&pPage1->aData[28]);
4411 testcase( nPage==0 );
4412 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
4413 testcase( pBt->nPage!=(u32)nPage );
4414 pBt->nPage = nPage;
4418 ** Rollback the transaction in progress.
4420 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
4421 ** Only write cursors are tripped if writeOnly is true but all cursors are
4422 ** tripped if writeOnly is false. Any attempt to use
4423 ** a tripped cursor will result in an error.
4425 ** This will release the write lock on the database file. If there
4426 ** are no active cursors, it also releases the read lock.
4428 int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
4429 int rc;
4430 BtShared *pBt = p->pBt;
4431 MemPage *pPage1;
4433 assert( writeOnly==1 || writeOnly==0 );
4434 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
4435 sqlite3BtreeEnter(p);
4436 if( tripCode==SQLITE_OK ){
4437 rc = tripCode = saveAllCursors(pBt, 0, 0);
4438 if( rc ) writeOnly = 0;
4439 }else{
4440 rc = SQLITE_OK;
4442 if( tripCode ){
4443 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
4444 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
4445 if( rc2!=SQLITE_OK ) rc = rc2;
4447 btreeIntegrity(p);
4449 if( p->inTrans==TRANS_WRITE ){
4450 int rc2;
4452 assert( TRANS_WRITE==pBt->inTransaction );
4453 rc2 = sqlite3PagerRollback(pBt->pPager);
4454 if( rc2!=SQLITE_OK ){
4455 rc = rc2;
4458 /* The rollback may have destroyed the pPage1->aData value. So
4459 ** call btreeGetPage() on page 1 again to make
4460 ** sure pPage1->aData is set correctly. */
4461 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
4462 btreeSetNPage(pBt, pPage1);
4463 releasePageOne(pPage1);
4465 assert( countValidCursors(pBt, 1)==0 );
4466 pBt->inTransaction = TRANS_READ;
4467 btreeClearHasContent(pBt);
4470 btreeEndTransaction(p);
4471 sqlite3BtreeLeave(p);
4472 return rc;
4476 ** Start a statement subtransaction. The subtransaction can be rolled
4477 ** back independently of the main transaction. You must start a transaction
4478 ** before starting a subtransaction. The subtransaction is ended automatically
4479 ** if the main transaction commits or rolls back.
4481 ** Statement subtransactions are used around individual SQL statements
4482 ** that are contained within a BEGIN...COMMIT block. If a constraint
4483 ** error occurs within the statement, the effect of that one statement
4484 ** can be rolled back without having to rollback the entire transaction.
4486 ** A statement sub-transaction is implemented as an anonymous savepoint. The
4487 ** value passed as the second parameter is the total number of savepoints,
4488 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
4489 ** are no active savepoints and no other statement-transactions open,
4490 ** iStatement is 1. This anonymous savepoint can be released or rolled back
4491 ** using the sqlite3BtreeSavepoint() function.
4493 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
4494 int rc;
4495 BtShared *pBt = p->pBt;
4496 sqlite3BtreeEnter(p);
4497 assert( p->inTrans==TRANS_WRITE );
4498 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
4499 assert( iStatement>0 );
4500 assert( iStatement>p->db->nSavepoint );
4501 assert( pBt->inTransaction==TRANS_WRITE );
4502 /* At the pager level, a statement transaction is a savepoint with
4503 ** an index greater than all savepoints created explicitly using
4504 ** SQL statements. It is illegal to open, release or rollback any
4505 ** such savepoints while the statement transaction savepoint is active.
4507 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
4508 sqlite3BtreeLeave(p);
4509 return rc;
4513 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
4514 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
4515 ** savepoint identified by parameter iSavepoint, depending on the value
4516 ** of op.
4518 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
4519 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
4520 ** contents of the entire transaction are rolled back. This is different
4521 ** from a normal transaction rollback, as no locks are released and the
4522 ** transaction remains open.
4524 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
4525 int rc = SQLITE_OK;
4526 if( p && p->inTrans==TRANS_WRITE ){
4527 BtShared *pBt = p->pBt;
4528 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
4529 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
4530 sqlite3BtreeEnter(p);
4531 if( op==SAVEPOINT_ROLLBACK ){
4532 rc = saveAllCursors(pBt, 0, 0);
4534 if( rc==SQLITE_OK ){
4535 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
4537 if( rc==SQLITE_OK ){
4538 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
4539 pBt->nPage = 0;
4541 rc = newDatabase(pBt);
4542 btreeSetNPage(pBt, pBt->pPage1);
4544 /* pBt->nPage might be zero if the database was corrupt when
4545 ** the transaction was started. Otherwise, it must be at least 1. */
4546 assert( CORRUPT_DB || pBt->nPage>0 );
4548 sqlite3BtreeLeave(p);
4550 return rc;
4554 ** Create a new cursor for the BTree whose root is on the page
4555 ** iTable. If a read-only cursor is requested, it is assumed that
4556 ** the caller already has at least a read-only transaction open
4557 ** on the database already. If a write-cursor is requested, then
4558 ** the caller is assumed to have an open write transaction.
4560 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
4561 ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
4562 ** can be used for reading or for writing if other conditions for writing
4563 ** are also met. These are the conditions that must be met in order
4564 ** for writing to be allowed:
4566 ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
4568 ** 2: Other database connections that share the same pager cache
4569 ** but which are not in the READ_UNCOMMITTED state may not have
4570 ** cursors open with wrFlag==0 on the same table. Otherwise
4571 ** the changes made by this write cursor would be visible to
4572 ** the read cursors in the other database connection.
4574 ** 3: The database must be writable (not on read-only media)
4576 ** 4: There must be an active transaction.
4578 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
4579 ** is set. If FORDELETE is set, that is a hint to the implementation that
4580 ** this cursor will only be used to seek to and delete entries of an index
4581 ** as part of a larger DELETE statement. The FORDELETE hint is not used by
4582 ** this implementation. But in a hypothetical alternative storage engine
4583 ** in which index entries are automatically deleted when corresponding table
4584 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
4585 ** operations on this cursor can be no-ops and all READ operations can
4586 ** return a null row (2-bytes: 0x01 0x00).
4588 ** No checking is done to make sure that page iTable really is the
4589 ** root page of a b-tree. If it is not, then the cursor acquired
4590 ** will not work correctly.
4592 ** It is assumed that the sqlite3BtreeCursorZero() has been called
4593 ** on pCur to initialize the memory space prior to invoking this routine.
4595 static int btreeCursor(
4596 Btree *p, /* The btree */
4597 Pgno iTable, /* Root page of table to open */
4598 int wrFlag, /* 1 to write. 0 read-only */
4599 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4600 BtCursor *pCur /* Space for new cursor */
4602 BtShared *pBt = p->pBt; /* Shared b-tree handle */
4603 BtCursor *pX; /* Looping over other all cursors */
4605 assert( sqlite3BtreeHoldsMutex(p) );
4606 assert( wrFlag==0
4607 || wrFlag==BTREE_WRCSR
4608 || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
4611 /* The following assert statements verify that if this is a sharable
4612 ** b-tree database, the connection is holding the required table locks,
4613 ** and that no other connection has any open cursor that conflicts with
4614 ** this lock. The iTable<1 term disables the check for corrupt schemas. */
4615 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1))
4616 || iTable<1 );
4617 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
4619 /* Assert that the caller has opened the required transaction. */
4620 assert( p->inTrans>TRANS_NONE );
4621 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
4622 assert( pBt->pPage1 && pBt->pPage1->aData );
4623 assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
4625 if( iTable<=1 ){
4626 if( iTable<1 ){
4627 return SQLITE_CORRUPT_BKPT;
4628 }else if( btreePagecount(pBt)==0 ){
4629 assert( wrFlag==0 );
4630 iTable = 0;
4634 /* Now that no other errors can occur, finish filling in the BtCursor
4635 ** variables and link the cursor into the BtShared list. */
4636 pCur->pgnoRoot = iTable;
4637 pCur->iPage = -1;
4638 pCur->pKeyInfo = pKeyInfo;
4639 pCur->pBtree = p;
4640 pCur->pBt = pBt;
4641 pCur->curFlags = 0;
4642 /* If there are two or more cursors on the same btree, then all such
4643 ** cursors *must* have the BTCF_Multiple flag set. */
4644 for(pX=pBt->pCursor; pX; pX=pX->pNext){
4645 if( pX->pgnoRoot==iTable ){
4646 pX->curFlags |= BTCF_Multiple;
4647 pCur->curFlags = BTCF_Multiple;
4650 pCur->eState = CURSOR_INVALID;
4651 pCur->pNext = pBt->pCursor;
4652 pBt->pCursor = pCur;
4653 if( wrFlag ){
4654 pCur->curFlags |= BTCF_WriteFlag;
4655 pCur->curPagerFlags = 0;
4656 if( pBt->pTmpSpace==0 ) return allocateTempSpace(pBt);
4657 }else{
4658 pCur->curPagerFlags = PAGER_GET_READONLY;
4660 return SQLITE_OK;
4662 static int btreeCursorWithLock(
4663 Btree *p, /* The btree */
4664 Pgno iTable, /* Root page of table to open */
4665 int wrFlag, /* 1 to write. 0 read-only */
4666 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4667 BtCursor *pCur /* Space for new cursor */
4669 int rc;
4670 sqlite3BtreeEnter(p);
4671 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4672 sqlite3BtreeLeave(p);
4673 return rc;
4675 int sqlite3BtreeCursor(
4676 Btree *p, /* The btree */
4677 Pgno iTable, /* Root page of table to open */
4678 int wrFlag, /* 1 to write. 0 read-only */
4679 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
4680 BtCursor *pCur /* Write new cursor here */
4682 if( p->sharable ){
4683 return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur);
4684 }else{
4685 return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4690 ** Return the size of a BtCursor object in bytes.
4692 ** This interfaces is needed so that users of cursors can preallocate
4693 ** sufficient storage to hold a cursor. The BtCursor object is opaque
4694 ** to users so they cannot do the sizeof() themselves - they must call
4695 ** this routine.
4697 int sqlite3BtreeCursorSize(void){
4698 return ROUND8(sizeof(BtCursor));
4702 ** Initialize memory that will be converted into a BtCursor object.
4704 ** The simple approach here would be to memset() the entire object
4705 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
4706 ** do not need to be zeroed and they are large, so we can save a lot
4707 ** of run-time by skipping the initialization of those elements.
4709 void sqlite3BtreeCursorZero(BtCursor *p){
4710 memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
4714 ** Close a cursor. The read lock on the database file is released
4715 ** when the last cursor is closed.
4717 int sqlite3BtreeCloseCursor(BtCursor *pCur){
4718 Btree *pBtree = pCur->pBtree;
4719 if( pBtree ){
4720 BtShared *pBt = pCur->pBt;
4721 sqlite3BtreeEnter(pBtree);
4722 assert( pBt->pCursor!=0 );
4723 if( pBt->pCursor==pCur ){
4724 pBt->pCursor = pCur->pNext;
4725 }else{
4726 BtCursor *pPrev = pBt->pCursor;
4728 if( pPrev->pNext==pCur ){
4729 pPrev->pNext = pCur->pNext;
4730 break;
4732 pPrev = pPrev->pNext;
4733 }while( ALWAYS(pPrev) );
4735 btreeReleaseAllCursorPages(pCur);
4736 unlockBtreeIfUnused(pBt);
4737 sqlite3_free(pCur->aOverflow);
4738 sqlite3_free(pCur->pKey);
4739 if( (pBt->openFlags & BTREE_SINGLE) && pBt->pCursor==0 ){
4740 /* Since the BtShared is not sharable, there is no need to
4741 ** worry about the missing sqlite3BtreeLeave() call here. */
4742 assert( pBtree->sharable==0 );
4743 sqlite3BtreeClose(pBtree);
4744 }else{
4745 sqlite3BtreeLeave(pBtree);
4747 pCur->pBtree = 0;
4749 return SQLITE_OK;
4753 ** Make sure the BtCursor* given in the argument has a valid
4754 ** BtCursor.info structure. If it is not already valid, call
4755 ** btreeParseCell() to fill it in.
4757 ** BtCursor.info is a cache of the information in the current cell.
4758 ** Using this cache reduces the number of calls to btreeParseCell().
4760 #ifndef NDEBUG
4761 static int cellInfoEqual(CellInfo *a, CellInfo *b){
4762 if( a->nKey!=b->nKey ) return 0;
4763 if( a->pPayload!=b->pPayload ) return 0;
4764 if( a->nPayload!=b->nPayload ) return 0;
4765 if( a->nLocal!=b->nLocal ) return 0;
4766 if( a->nSize!=b->nSize ) return 0;
4767 return 1;
4769 static void assertCellInfo(BtCursor *pCur){
4770 CellInfo info;
4771 memset(&info, 0, sizeof(info));
4772 btreeParseCell(pCur->pPage, pCur->ix, &info);
4773 assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
4775 #else
4776 #define assertCellInfo(x)
4777 #endif
4778 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
4779 if( pCur->info.nSize==0 ){
4780 pCur->curFlags |= BTCF_ValidNKey;
4781 btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
4782 }else{
4783 assertCellInfo(pCur);
4787 #ifndef NDEBUG /* The next routine used only within assert() statements */
4789 ** Return true if the given BtCursor is valid. A valid cursor is one
4790 ** that is currently pointing to a row in a (non-empty) table.
4791 ** This is a verification routine is used only within assert() statements.
4793 int sqlite3BtreeCursorIsValid(BtCursor *pCur){
4794 return pCur && pCur->eState==CURSOR_VALID;
4796 #endif /* NDEBUG */
4797 int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
4798 assert( pCur!=0 );
4799 return pCur->eState==CURSOR_VALID;
4803 ** Return the value of the integer key or "rowid" for a table btree.
4804 ** This routine is only valid for a cursor that is pointing into a
4805 ** ordinary table btree. If the cursor points to an index btree or
4806 ** is invalid, the result of this routine is undefined.
4808 i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
4809 assert( cursorHoldsMutex(pCur) );
4810 assert( pCur->eState==CURSOR_VALID );
4811 assert( pCur->curIntKey );
4812 getCellInfo(pCur);
4813 return pCur->info.nKey;
4817 ** Pin or unpin a cursor.
4819 void sqlite3BtreeCursorPin(BtCursor *pCur){
4820 assert( (pCur->curFlags & BTCF_Pinned)==0 );
4821 pCur->curFlags |= BTCF_Pinned;
4823 void sqlite3BtreeCursorUnpin(BtCursor *pCur){
4824 assert( (pCur->curFlags & BTCF_Pinned)!=0 );
4825 pCur->curFlags &= ~BTCF_Pinned;
4829 ** Return the offset into the database file for the start of the
4830 ** payload to which the cursor is pointing.
4832 i64 sqlite3BtreeOffset(BtCursor *pCur){
4833 assert( cursorHoldsMutex(pCur) );
4834 assert( pCur->eState==CURSOR_VALID );
4835 getCellInfo(pCur);
4836 return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
4837 (i64)(pCur->info.pPayload - pCur->pPage->aData);
4841 ** Return the number of bytes of payload for the entry that pCur is
4842 ** currently pointing to. For table btrees, this will be the amount
4843 ** of data. For index btrees, this will be the size of the key.
4845 ** The caller must guarantee that the cursor is pointing to a non-NULL
4846 ** valid entry. In other words, the calling procedure must guarantee
4847 ** that the cursor has Cursor.eState==CURSOR_VALID.
4849 u32 sqlite3BtreePayloadSize(BtCursor *pCur){
4850 assert( cursorHoldsMutex(pCur) );
4851 assert( pCur->eState==CURSOR_VALID );
4852 getCellInfo(pCur);
4853 return pCur->info.nPayload;
4857 ** Return an upper bound on the size of any record for the table
4858 ** that the cursor is pointing into.
4860 ** This is an optimization. Everything will still work if this
4861 ** routine always returns 2147483647 (which is the largest record
4862 ** that SQLite can handle) or more. But returning a smaller value might
4863 ** prevent large memory allocations when trying to interpret a
4864 ** corrupt database.
4866 ** The current implementation merely returns the size of the underlying
4867 ** database file.
4869 sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){
4870 assert( cursorHoldsMutex(pCur) );
4871 assert( pCur->eState==CURSOR_VALID );
4872 return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
4876 ** Given the page number of an overflow page in the database (parameter
4877 ** ovfl), this function finds the page number of the next page in the
4878 ** linked list of overflow pages. If possible, it uses the auto-vacuum
4879 ** pointer-map data instead of reading the content of page ovfl to do so.
4881 ** If an error occurs an SQLite error code is returned. Otherwise:
4883 ** The page number of the next overflow page in the linked list is
4884 ** written to *pPgnoNext. If page ovfl is the last page in its linked
4885 ** list, *pPgnoNext is set to zero.
4887 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
4888 ** to page number pOvfl was obtained, then *ppPage is set to point to that
4889 ** reference. It is the responsibility of the caller to call releasePage()
4890 ** on *ppPage to free the reference. In no reference was obtained (because
4891 ** the pointer-map was used to obtain the value for *pPgnoNext), then
4892 ** *ppPage is set to zero.
4894 static int getOverflowPage(
4895 BtShared *pBt, /* The database file */
4896 Pgno ovfl, /* Current overflow page number */
4897 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
4898 Pgno *pPgnoNext /* OUT: Next overflow page number */
4900 Pgno next = 0;
4901 MemPage *pPage = 0;
4902 int rc = SQLITE_OK;
4904 assert( sqlite3_mutex_held(pBt->mutex) );
4905 assert(pPgnoNext);
4907 #ifndef SQLITE_OMIT_AUTOVACUUM
4908 /* Try to find the next page in the overflow list using the
4909 ** autovacuum pointer-map pages. Guess that the next page in
4910 ** the overflow list is page number (ovfl+1). If that guess turns
4911 ** out to be wrong, fall back to loading the data of page
4912 ** number ovfl to determine the next page number.
4914 if( pBt->autoVacuum ){
4915 Pgno pgno;
4916 Pgno iGuess = ovfl+1;
4917 u8 eType;
4919 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
4920 iGuess++;
4923 if( iGuess<=btreePagecount(pBt) ){
4924 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
4925 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
4926 next = iGuess;
4927 rc = SQLITE_DONE;
4931 #endif
4933 assert( next==0 || rc==SQLITE_DONE );
4934 if( rc==SQLITE_OK ){
4935 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
4936 assert( rc==SQLITE_OK || pPage==0 );
4937 if( rc==SQLITE_OK ){
4938 next = get4byte(pPage->aData);
4942 *pPgnoNext = next;
4943 if( ppPage ){
4944 *ppPage = pPage;
4945 }else{
4946 releasePage(pPage);
4948 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
4952 ** Copy data from a buffer to a page, or from a page to a buffer.
4954 ** pPayload is a pointer to data stored on database page pDbPage.
4955 ** If argument eOp is false, then nByte bytes of data are copied
4956 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4957 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4958 ** of data are copied from the buffer pBuf to pPayload.
4960 ** SQLITE_OK is returned on success, otherwise an error code.
4962 static int copyPayload(
4963 void *pPayload, /* Pointer to page data */
4964 void *pBuf, /* Pointer to buffer */
4965 int nByte, /* Number of bytes to copy */
4966 int eOp, /* 0 -> copy from page, 1 -> copy to page */
4967 DbPage *pDbPage /* Page containing pPayload */
4969 if( eOp ){
4970 /* Copy data from buffer to page (a write operation) */
4971 int rc = sqlite3PagerWrite(pDbPage);
4972 if( rc!=SQLITE_OK ){
4973 return rc;
4975 memcpy(pPayload, pBuf, nByte);
4976 }else{
4977 /* Copy data from page to buffer (a read operation) */
4978 memcpy(pBuf, pPayload, nByte);
4980 return SQLITE_OK;
4984 ** This function is used to read or overwrite payload information
4985 ** for the entry that the pCur cursor is pointing to. The eOp
4986 ** argument is interpreted as follows:
4988 ** 0: The operation is a read. Populate the overflow cache.
4989 ** 1: The operation is a write. Populate the overflow cache.
4991 ** A total of "amt" bytes are read or written beginning at "offset".
4992 ** Data is read to or from the buffer pBuf.
4994 ** The content being read or written might appear on the main page
4995 ** or be scattered out on multiple overflow pages.
4997 ** If the current cursor entry uses one or more overflow pages
4998 ** this function may allocate space for and lazily populate
4999 ** the overflow page-list cache array (BtCursor.aOverflow).
5000 ** Subsequent calls use this cache to make seeking to the supplied offset
5001 ** more efficient.
5003 ** Once an overflow page-list cache has been allocated, it must be
5004 ** invalidated if some other cursor writes to the same table, or if
5005 ** the cursor is moved to a different row. Additionally, in auto-vacuum
5006 ** mode, the following events may invalidate an overflow page-list cache.
5008 ** * An incremental vacuum,
5009 ** * A commit in auto_vacuum="full" mode,
5010 ** * Creating a table (may require moving an overflow page).
5012 static int accessPayload(
5013 BtCursor *pCur, /* Cursor pointing to entry to read from */
5014 u32 offset, /* Begin reading this far into payload */
5015 u32 amt, /* Read this many bytes */
5016 unsigned char *pBuf, /* Write the bytes into this buffer */
5017 int eOp /* zero to read. non-zero to write. */
5019 unsigned char *aPayload;
5020 int rc = SQLITE_OK;
5021 int iIdx = 0;
5022 MemPage *pPage = pCur->pPage; /* Btree page of current entry */
5023 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
5024 #ifdef SQLITE_DIRECT_OVERFLOW_READ
5025 unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
5026 #endif
5028 assert( pPage );
5029 assert( eOp==0 || eOp==1 );
5030 assert( pCur->eState==CURSOR_VALID );
5031 if( pCur->ix>=pPage->nCell ){
5032 return SQLITE_CORRUPT_PAGE(pPage);
5034 assert( cursorHoldsMutex(pCur) );
5036 getCellInfo(pCur);
5037 aPayload = pCur->info.pPayload;
5038 assert( offset+amt <= pCur->info.nPayload );
5040 assert( aPayload > pPage->aData );
5041 if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
5042 /* Trying to read or write past the end of the data is an error. The
5043 ** conditional above is really:
5044 ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
5045 ** but is recast into its current form to avoid integer overflow problems
5047 return SQLITE_CORRUPT_PAGE(pPage);
5050 /* Check if data must be read/written to/from the btree page itself. */
5051 if( offset<pCur->info.nLocal ){
5052 int a = amt;
5053 if( a+offset>pCur->info.nLocal ){
5054 a = pCur->info.nLocal - offset;
5056 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
5057 offset = 0;
5058 pBuf += a;
5059 amt -= a;
5060 }else{
5061 offset -= pCur->info.nLocal;
5065 if( rc==SQLITE_OK && amt>0 ){
5066 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
5067 Pgno nextPage;
5069 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
5071 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
5073 ** The aOverflow[] array is sized at one entry for each overflow page
5074 ** in the overflow chain. The page number of the first overflow page is
5075 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
5076 ** means "not yet known" (the cache is lazily populated).
5078 if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
5079 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
5080 if( pCur->aOverflow==0
5081 || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
5083 Pgno *aNew = (Pgno*)sqlite3Realloc(
5084 pCur->aOverflow, nOvfl*2*sizeof(Pgno)
5086 if( aNew==0 ){
5087 return SQLITE_NOMEM_BKPT;
5088 }else{
5089 pCur->aOverflow = aNew;
5092 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
5093 pCur->curFlags |= BTCF_ValidOvfl;
5094 }else{
5095 /* If the overflow page-list cache has been allocated and the
5096 ** entry for the first required overflow page is valid, skip
5097 ** directly to it.
5099 if( pCur->aOverflow[offset/ovflSize] ){
5100 iIdx = (offset/ovflSize);
5101 nextPage = pCur->aOverflow[iIdx];
5102 offset = (offset%ovflSize);
5106 assert( rc==SQLITE_OK && amt>0 );
5107 while( nextPage ){
5108 /* If required, populate the overflow page-list cache. */
5109 if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPT;
5110 assert( pCur->aOverflow[iIdx]==0
5111 || pCur->aOverflow[iIdx]==nextPage
5112 || CORRUPT_DB );
5113 pCur->aOverflow[iIdx] = nextPage;
5115 if( offset>=ovflSize ){
5116 /* The only reason to read this page is to obtain the page
5117 ** number for the next page in the overflow chain. The page
5118 ** data is not required. So first try to lookup the overflow
5119 ** page-list cache, if any, then fall back to the getOverflowPage()
5120 ** function.
5122 assert( pCur->curFlags & BTCF_ValidOvfl );
5123 assert( pCur->pBtree->db==pBt->db );
5124 if( pCur->aOverflow[iIdx+1] ){
5125 nextPage = pCur->aOverflow[iIdx+1];
5126 }else{
5127 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
5129 offset -= ovflSize;
5130 }else{
5131 /* Need to read this page properly. It contains some of the
5132 ** range of data that is being read (eOp==0) or written (eOp!=0).
5134 int a = amt;
5135 if( a + offset > ovflSize ){
5136 a = ovflSize - offset;
5139 #ifdef SQLITE_DIRECT_OVERFLOW_READ
5140 /* If all the following are true:
5142 ** 1) this is a read operation, and
5143 ** 2) data is required from the start of this overflow page, and
5144 ** 3) there are no dirty pages in the page-cache
5145 ** 4) the database is file-backed, and
5146 ** 5) the page is not in the WAL file
5147 ** 6) at least 4 bytes have already been read into the output buffer
5149 ** then data can be read directly from the database file into the
5150 ** output buffer, bypassing the page-cache altogether. This speeds
5151 ** up loading large records that span many overflow pages.
5153 if( eOp==0 /* (1) */
5154 && offset==0 /* (2) */
5155 && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */
5156 && &pBuf[-4]>=pBufStart /* (6) */
5158 sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
5159 u8 aSave[4];
5160 u8 *aWrite = &pBuf[-4];
5161 assert( aWrite>=pBufStart ); /* due to (6) */
5162 memcpy(aSave, aWrite, 4);
5163 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
5164 if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT;
5165 nextPage = get4byte(aWrite);
5166 memcpy(aWrite, aSave, 4);
5167 }else
5168 #endif
5171 DbPage *pDbPage;
5172 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
5173 (eOp==0 ? PAGER_GET_READONLY : 0)
5175 if( rc==SQLITE_OK ){
5176 aPayload = sqlite3PagerGetData(pDbPage);
5177 nextPage = get4byte(aPayload);
5178 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
5179 sqlite3PagerUnref(pDbPage);
5180 offset = 0;
5183 amt -= a;
5184 if( amt==0 ) return rc;
5185 pBuf += a;
5187 if( rc ) break;
5188 iIdx++;
5192 if( rc==SQLITE_OK && amt>0 ){
5193 /* Overflow chain ends prematurely */
5194 return SQLITE_CORRUPT_PAGE(pPage);
5196 return rc;
5200 ** Read part of the payload for the row at which that cursor pCur is currently
5201 ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
5202 ** begins at "offset".
5204 ** pCur can be pointing to either a table or an index b-tree.
5205 ** If pointing to a table btree, then the content section is read. If
5206 ** pCur is pointing to an index b-tree then the key section is read.
5208 ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
5209 ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
5210 ** cursor might be invalid or might need to be restored before being read.
5212 ** Return SQLITE_OK on success or an error code if anything goes
5213 ** wrong. An error is returned if "offset+amt" is larger than
5214 ** the available payload.
5216 int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5217 assert( cursorHoldsMutex(pCur) );
5218 assert( pCur->eState==CURSOR_VALID );
5219 assert( pCur->iPage>=0 && pCur->pPage );
5220 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
5224 ** This variant of sqlite3BtreePayload() works even if the cursor has not
5225 ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
5226 ** interface.
5228 #ifndef SQLITE_OMIT_INCRBLOB
5229 static SQLITE_NOINLINE int accessPayloadChecked(
5230 BtCursor *pCur,
5231 u32 offset,
5232 u32 amt,
5233 void *pBuf
5235 int rc;
5236 if ( pCur->eState==CURSOR_INVALID ){
5237 return SQLITE_ABORT;
5239 assert( cursorOwnsBtShared(pCur) );
5240 rc = btreeRestoreCursorPosition(pCur);
5241 return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
5243 int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5244 if( pCur->eState==CURSOR_VALID ){
5245 assert( cursorOwnsBtShared(pCur) );
5246 return accessPayload(pCur, offset, amt, pBuf, 0);
5247 }else{
5248 return accessPayloadChecked(pCur, offset, amt, pBuf);
5251 #endif /* SQLITE_OMIT_INCRBLOB */
5254 ** Return a pointer to payload information from the entry that the
5255 ** pCur cursor is pointing to. The pointer is to the beginning of
5256 ** the key if index btrees (pPage->intKey==0) and is the data for
5257 ** table btrees (pPage->intKey==1). The number of bytes of available
5258 ** key/data is written into *pAmt. If *pAmt==0, then the value
5259 ** returned will not be a valid pointer.
5261 ** This routine is an optimization. It is common for the entire key
5262 ** and data to fit on the local page and for there to be no overflow
5263 ** pages. When that is so, this routine can be used to access the
5264 ** key and data without making a copy. If the key and/or data spills
5265 ** onto overflow pages, then accessPayload() must be used to reassemble
5266 ** the key/data and copy it into a preallocated buffer.
5268 ** The pointer returned by this routine looks directly into the cached
5269 ** page of the database. The data might change or move the next time
5270 ** any btree routine is called.
5272 static const void *fetchPayload(
5273 BtCursor *pCur, /* Cursor pointing to entry to read from */
5274 u32 *pAmt /* Write the number of available bytes here */
5276 int amt;
5277 assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
5278 assert( pCur->eState==CURSOR_VALID );
5279 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5280 assert( cursorOwnsBtShared(pCur) );
5281 assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
5282 assert( pCur->info.nSize>0 );
5283 assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
5284 assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
5285 amt = pCur->info.nLocal;
5286 if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
5287 /* There is too little space on the page for the expected amount
5288 ** of local content. Database must be corrupt. */
5289 assert( CORRUPT_DB );
5290 amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
5292 *pAmt = (u32)amt;
5293 return (void*)pCur->info.pPayload;
5298 ** For the entry that cursor pCur is point to, return as
5299 ** many bytes of the key or data as are available on the local
5300 ** b-tree page. Write the number of available bytes into *pAmt.
5302 ** The pointer returned is ephemeral. The key/data may move
5303 ** or be destroyed on the next call to any Btree routine,
5304 ** including calls from other threads against the same cache.
5305 ** Hence, a mutex on the BtShared should be held prior to calling
5306 ** this routine.
5308 ** These routines is used to get quick access to key and data
5309 ** in the common case where no overflow pages are used.
5311 const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
5312 return fetchPayload(pCur, pAmt);
5317 ** Move the cursor down to a new child page. The newPgno argument is the
5318 ** page number of the child page to move to.
5320 ** This function returns SQLITE_CORRUPT if the page-header flags field of
5321 ** the new child page does not match the flags field of the parent (i.e.
5322 ** if an intkey page appears to be the parent of a non-intkey page, or
5323 ** vice-versa).
5325 static int moveToChild(BtCursor *pCur, u32 newPgno){
5326 int rc;
5327 assert( cursorOwnsBtShared(pCur) );
5328 assert( pCur->eState==CURSOR_VALID );
5329 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
5330 assert( pCur->iPage>=0 );
5331 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
5332 return SQLITE_CORRUPT_BKPT;
5334 pCur->info.nSize = 0;
5335 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5336 pCur->aiIdx[pCur->iPage] = pCur->ix;
5337 pCur->apPage[pCur->iPage] = pCur->pPage;
5338 pCur->ix = 0;
5339 pCur->iPage++;
5340 rc = getAndInitPage(pCur->pBt, newPgno, &pCur->pPage, pCur->curPagerFlags);
5341 assert( pCur->pPage!=0 || rc!=SQLITE_OK );
5342 if( rc==SQLITE_OK
5343 && (pCur->pPage->nCell<1 || pCur->pPage->intKey!=pCur->curIntKey)
5345 releasePage(pCur->pPage);
5346 rc = SQLITE_CORRUPT_PGNO(newPgno);
5348 if( rc ){
5349 pCur->pPage = pCur->apPage[--pCur->iPage];
5351 return rc;
5354 #ifdef SQLITE_DEBUG
5356 ** Page pParent is an internal (non-leaf) tree page. This function
5357 ** asserts that page number iChild is the left-child if the iIdx'th
5358 ** cell in page pParent. Or, if iIdx is equal to the total number of
5359 ** cells in pParent, that page number iChild is the right-child of
5360 ** the page.
5362 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
5363 if( CORRUPT_DB ) return; /* The conditions tested below might not be true
5364 ** in a corrupt database */
5365 assert( iIdx<=pParent->nCell );
5366 if( iIdx==pParent->nCell ){
5367 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
5368 }else{
5369 assert( get4byte(findCell(pParent, iIdx))==iChild );
5372 #else
5373 # define assertParentIndex(x,y,z)
5374 #endif
5377 ** Move the cursor up to the parent page.
5379 ** pCur->idx is set to the cell index that contains the pointer
5380 ** to the page we are coming from. If we are coming from the
5381 ** right-most child page then pCur->idx is set to one more than
5382 ** the largest cell index.
5384 static void moveToParent(BtCursor *pCur){
5385 MemPage *pLeaf;
5386 assert( cursorOwnsBtShared(pCur) );
5387 assert( pCur->eState==CURSOR_VALID );
5388 assert( pCur->iPage>0 );
5389 assert( pCur->pPage );
5390 assertParentIndex(
5391 pCur->apPage[pCur->iPage-1],
5392 pCur->aiIdx[pCur->iPage-1],
5393 pCur->pPage->pgno
5395 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
5396 pCur->info.nSize = 0;
5397 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5398 pCur->ix = pCur->aiIdx[pCur->iPage-1];
5399 pLeaf = pCur->pPage;
5400 pCur->pPage = pCur->apPage[--pCur->iPage];
5401 releasePageNotNull(pLeaf);
5405 ** Move the cursor to point to the root page of its b-tree structure.
5407 ** If the table has a virtual root page, then the cursor is moved to point
5408 ** to the virtual root page instead of the actual root page. A table has a
5409 ** virtual root page when the actual root page contains no cells and a
5410 ** single child page. This can only happen with the table rooted at page 1.
5412 ** If the b-tree structure is empty, the cursor state is set to
5413 ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
5414 ** the cursor is set to point to the first cell located on the root
5415 ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
5417 ** If this function returns successfully, it may be assumed that the
5418 ** page-header flags indicate that the [virtual] root-page is the expected
5419 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
5420 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
5421 ** indicating a table b-tree, or if the caller did specify a KeyInfo
5422 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
5423 ** b-tree).
5425 static int moveToRoot(BtCursor *pCur){
5426 MemPage *pRoot;
5427 int rc = SQLITE_OK;
5429 assert( cursorOwnsBtShared(pCur) );
5430 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
5431 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
5432 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
5433 assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
5434 assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
5436 if( pCur->iPage>=0 ){
5437 if( pCur->iPage ){
5438 releasePageNotNull(pCur->pPage);
5439 while( --pCur->iPage ){
5440 releasePageNotNull(pCur->apPage[pCur->iPage]);
5442 pRoot = pCur->pPage = pCur->apPage[0];
5443 goto skip_init;
5445 }else if( pCur->pgnoRoot==0 ){
5446 pCur->eState = CURSOR_INVALID;
5447 return SQLITE_EMPTY;
5448 }else{
5449 assert( pCur->iPage==(-1) );
5450 if( pCur->eState>=CURSOR_REQUIRESEEK ){
5451 if( pCur->eState==CURSOR_FAULT ){
5452 assert( pCur->skipNext!=SQLITE_OK );
5453 return pCur->skipNext;
5455 sqlite3BtreeClearCursor(pCur);
5457 rc = getAndInitPage(pCur->pBt, pCur->pgnoRoot, &pCur->pPage,
5458 pCur->curPagerFlags);
5459 if( rc!=SQLITE_OK ){
5460 pCur->eState = CURSOR_INVALID;
5461 return rc;
5463 pCur->iPage = 0;
5464 pCur->curIntKey = pCur->pPage->intKey;
5466 pRoot = pCur->pPage;
5467 assert( pRoot->pgno==pCur->pgnoRoot || CORRUPT_DB );
5469 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
5470 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
5471 ** NULL, the caller expects a table b-tree. If this is not the case,
5472 ** return an SQLITE_CORRUPT error.
5474 ** Earlier versions of SQLite assumed that this test could not fail
5475 ** if the root page was already loaded when this function was called (i.e.
5476 ** if pCur->iPage>=0). But this is not so if the database is corrupted
5477 ** in such a way that page pRoot is linked into a second b-tree table
5478 ** (or the freelist). */
5479 assert( pRoot->intKey==1 || pRoot->intKey==0 );
5480 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
5481 return SQLITE_CORRUPT_PAGE(pCur->pPage);
5484 skip_init:
5485 pCur->ix = 0;
5486 pCur->info.nSize = 0;
5487 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
5489 if( pRoot->nCell>0 ){
5490 pCur->eState = CURSOR_VALID;
5491 }else if( !pRoot->leaf ){
5492 Pgno subpage;
5493 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
5494 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
5495 pCur->eState = CURSOR_VALID;
5496 rc = moveToChild(pCur, subpage);
5497 }else{
5498 pCur->eState = CURSOR_INVALID;
5499 rc = SQLITE_EMPTY;
5501 return rc;
5505 ** Move the cursor down to the left-most leaf entry beneath the
5506 ** entry to which it is currently pointing.
5508 ** The left-most leaf is the one with the smallest key - the first
5509 ** in ascending order.
5511 static int moveToLeftmost(BtCursor *pCur){
5512 Pgno pgno;
5513 int rc = SQLITE_OK;
5514 MemPage *pPage;
5516 assert( cursorOwnsBtShared(pCur) );
5517 assert( pCur->eState==CURSOR_VALID );
5518 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
5519 assert( pCur->ix<pPage->nCell );
5520 pgno = get4byte(findCell(pPage, pCur->ix));
5521 rc = moveToChild(pCur, pgno);
5523 return rc;
5527 ** Move the cursor down to the right-most leaf entry beneath the
5528 ** page to which it is currently pointing. Notice the difference
5529 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
5530 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
5531 ** finds the right-most entry beneath the *page*.
5533 ** The right-most entry is the one with the largest key - the last
5534 ** key in ascending order.
5536 static int moveToRightmost(BtCursor *pCur){
5537 Pgno pgno;
5538 int rc = SQLITE_OK;
5539 MemPage *pPage = 0;
5541 assert( cursorOwnsBtShared(pCur) );
5542 assert( pCur->eState==CURSOR_VALID );
5543 while( !(pPage = pCur->pPage)->leaf ){
5544 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5545 pCur->ix = pPage->nCell;
5546 rc = moveToChild(pCur, pgno);
5547 if( rc ) return rc;
5549 pCur->ix = pPage->nCell-1;
5550 assert( pCur->info.nSize==0 );
5551 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
5552 return SQLITE_OK;
5555 /* Move the cursor to the first entry in the table. Return SQLITE_OK
5556 ** on success. Set *pRes to 0 if the cursor actually points to something
5557 ** or set *pRes to 1 if the table is empty.
5559 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
5560 int rc;
5562 assert( cursorOwnsBtShared(pCur) );
5563 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5564 rc = moveToRoot(pCur);
5565 if( rc==SQLITE_OK ){
5566 assert( pCur->pPage->nCell>0 );
5567 *pRes = 0;
5568 rc = moveToLeftmost(pCur);
5569 }else if( rc==SQLITE_EMPTY ){
5570 assert( pCur->pgnoRoot==0 || (pCur->pPage!=0 && pCur->pPage->nCell==0) );
5571 *pRes = 1;
5572 rc = SQLITE_OK;
5574 return rc;
5577 /* Move the cursor to the last entry in the table. Return SQLITE_OK
5578 ** on success. Set *pRes to 0 if the cursor actually points to something
5579 ** or set *pRes to 1 if the table is empty.
5581 static SQLITE_NOINLINE int btreeLast(BtCursor *pCur, int *pRes){
5582 int rc = moveToRoot(pCur);
5583 if( rc==SQLITE_OK ){
5584 assert( pCur->eState==CURSOR_VALID );
5585 *pRes = 0;
5586 rc = moveToRightmost(pCur);
5587 if( rc==SQLITE_OK ){
5588 pCur->curFlags |= BTCF_AtLast;
5589 }else{
5590 pCur->curFlags &= ~BTCF_AtLast;
5592 }else if( rc==SQLITE_EMPTY ){
5593 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5594 *pRes = 1;
5595 rc = SQLITE_OK;
5597 return rc;
5599 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
5600 assert( cursorOwnsBtShared(pCur) );
5601 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5603 /* If the cursor already points to the last entry, this is a no-op. */
5604 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
5605 #ifdef SQLITE_DEBUG
5606 /* This block serves to assert() that the cursor really does point
5607 ** to the last entry in the b-tree. */
5608 int ii;
5609 for(ii=0; ii<pCur->iPage; ii++){
5610 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
5612 assert( pCur->ix==pCur->pPage->nCell-1 || CORRUPT_DB );
5613 testcase( pCur->ix!=pCur->pPage->nCell-1 );
5614 /* ^-- dbsqlfuzz b92b72e4de80b5140c30ab71372ca719b8feb618 */
5615 assert( pCur->pPage->leaf );
5616 #endif
5617 *pRes = 0;
5618 return SQLITE_OK;
5620 return btreeLast(pCur, pRes);
5623 /* Move the cursor so that it points to an entry in a table (a.k.a INTKEY)
5624 ** table near the key intKey. Return a success code.
5626 ** If an exact match is not found, then the cursor is always
5627 ** left pointing at a leaf page which would hold the entry if it
5628 ** were present. The cursor might point to an entry that comes
5629 ** before or after the key.
5631 ** An integer is written into *pRes which is the result of
5632 ** comparing the key with the entry to which the cursor is
5633 ** pointing. The meaning of the integer written into
5634 ** *pRes is as follows:
5636 ** *pRes<0 The cursor is left pointing at an entry that
5637 ** is smaller than intKey or if the table is empty
5638 ** and the cursor is therefore left point to nothing.
5640 ** *pRes==0 The cursor is left pointing at an entry that
5641 ** exactly matches intKey.
5643 ** *pRes>0 The cursor is left pointing at an entry that
5644 ** is larger than intKey.
5646 int sqlite3BtreeTableMoveto(
5647 BtCursor *pCur, /* The cursor to be moved */
5648 i64 intKey, /* The table key */
5649 int biasRight, /* If true, bias the search to the high end */
5650 int *pRes /* Write search results here */
5652 int rc;
5654 assert( cursorOwnsBtShared(pCur) );
5655 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5656 assert( pRes );
5657 assert( pCur->pKeyInfo==0 );
5658 assert( pCur->eState!=CURSOR_VALID || pCur->curIntKey!=0 );
5660 /* If the cursor is already positioned at the point we are trying
5661 ** to move to, then just return without doing any work */
5662 if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0 ){
5663 if( pCur->info.nKey==intKey ){
5664 *pRes = 0;
5665 return SQLITE_OK;
5667 if( pCur->info.nKey<intKey ){
5668 if( (pCur->curFlags & BTCF_AtLast)!=0 ){
5669 *pRes = -1;
5670 return SQLITE_OK;
5672 /* If the requested key is one more than the previous key, then
5673 ** try to get there using sqlite3BtreeNext() rather than a full
5674 ** binary search. This is an optimization only. The correct answer
5675 ** is still obtained without this case, only a little more slowly. */
5676 if( pCur->info.nKey+1==intKey ){
5677 *pRes = 0;
5678 rc = sqlite3BtreeNext(pCur, 0);
5679 if( rc==SQLITE_OK ){
5680 getCellInfo(pCur);
5681 if( pCur->info.nKey==intKey ){
5682 return SQLITE_OK;
5684 }else if( rc!=SQLITE_DONE ){
5685 return rc;
5691 #ifdef SQLITE_DEBUG
5692 pCur->pBtree->nSeek++; /* Performance measurement during testing */
5693 #endif
5695 rc = moveToRoot(pCur);
5696 if( rc ){
5697 if( rc==SQLITE_EMPTY ){
5698 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5699 *pRes = -1;
5700 return SQLITE_OK;
5702 return rc;
5704 assert( pCur->pPage );
5705 assert( pCur->pPage->isInit );
5706 assert( pCur->eState==CURSOR_VALID );
5707 assert( pCur->pPage->nCell > 0 );
5708 assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
5709 assert( pCur->curIntKey );
5711 for(;;){
5712 int lwr, upr, idx, c;
5713 Pgno chldPg;
5714 MemPage *pPage = pCur->pPage;
5715 u8 *pCell; /* Pointer to current cell in pPage */
5717 /* pPage->nCell must be greater than zero. If this is the root-page
5718 ** the cursor would have been INVALID above and this for(;;) loop
5719 ** not run. If this is not the root-page, then the moveToChild() routine
5720 ** would have already detected db corruption. Similarly, pPage must
5721 ** be the right kind (index or table) of b-tree page. Otherwise
5722 ** a moveToChild() or moveToRoot() call would have detected corruption. */
5723 assert( pPage->nCell>0 );
5724 assert( pPage->intKey );
5725 lwr = 0;
5726 upr = pPage->nCell-1;
5727 assert( biasRight==0 || biasRight==1 );
5728 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
5729 for(;;){
5730 i64 nCellKey;
5731 pCell = findCellPastPtr(pPage, idx);
5732 if( pPage->intKeyLeaf ){
5733 while( 0x80 <= *(pCell++) ){
5734 if( pCell>=pPage->aDataEnd ){
5735 return SQLITE_CORRUPT_PAGE(pPage);
5739 getVarint(pCell, (u64*)&nCellKey);
5740 if( nCellKey<intKey ){
5741 lwr = idx+1;
5742 if( lwr>upr ){ c = -1; break; }
5743 }else if( nCellKey>intKey ){
5744 upr = idx-1;
5745 if( lwr>upr ){ c = +1; break; }
5746 }else{
5747 assert( nCellKey==intKey );
5748 pCur->ix = (u16)idx;
5749 if( !pPage->leaf ){
5750 lwr = idx;
5751 goto moveto_table_next_layer;
5752 }else{
5753 pCur->curFlags |= BTCF_ValidNKey;
5754 pCur->info.nKey = nCellKey;
5755 pCur->info.nSize = 0;
5756 *pRes = 0;
5757 return SQLITE_OK;
5760 assert( lwr+upr>=0 );
5761 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
5763 assert( lwr==upr+1 || !pPage->leaf );
5764 assert( pPage->isInit );
5765 if( pPage->leaf ){
5766 assert( pCur->ix<pCur->pPage->nCell );
5767 pCur->ix = (u16)idx;
5768 *pRes = c;
5769 rc = SQLITE_OK;
5770 goto moveto_table_finish;
5772 moveto_table_next_layer:
5773 if( lwr>=pPage->nCell ){
5774 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5775 }else{
5776 chldPg = get4byte(findCell(pPage, lwr));
5778 pCur->ix = (u16)lwr;
5779 rc = moveToChild(pCur, chldPg);
5780 if( rc ) break;
5782 moveto_table_finish:
5783 pCur->info.nSize = 0;
5784 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5785 return rc;
5789 ** Compare the "idx"-th cell on the page the cursor pCur is currently
5790 ** pointing to to pIdxKey using xRecordCompare. Return negative or
5791 ** zero if the cell is less than or equal pIdxKey. Return positive
5792 ** if unknown.
5794 ** Return value negative: Cell at pCur[idx] less than pIdxKey
5796 ** Return value is zero: Cell at pCur[idx] equals pIdxKey
5798 ** Return value positive: Nothing is known about the relationship
5799 ** of the cell at pCur[idx] and pIdxKey.
5801 ** This routine is part of an optimization. It is always safe to return
5802 ** a positive value as that will cause the optimization to be skipped.
5804 static int indexCellCompare(
5805 BtCursor *pCur,
5806 int idx,
5807 UnpackedRecord *pIdxKey,
5808 RecordCompare xRecordCompare
5810 MemPage *pPage = pCur->pPage;
5811 int c;
5812 int nCell; /* Size of the pCell cell in bytes */
5813 u8 *pCell = findCellPastPtr(pPage, idx);
5815 nCell = pCell[0];
5816 if( nCell<=pPage->max1bytePayload ){
5817 /* This branch runs if the record-size field of the cell is a
5818 ** single byte varint and the record fits entirely on the main
5819 ** b-tree page. */
5820 testcase( pCell+nCell+1==pPage->aDataEnd );
5821 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
5822 }else if( !(pCell[1] & 0x80)
5823 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5825 /* The record-size field is a 2 byte varint and the record
5826 ** fits entirely on the main b-tree page. */
5827 testcase( pCell+nCell+2==pPage->aDataEnd );
5828 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
5829 }else{
5830 /* If the record extends into overflow pages, do not attempt
5831 ** the optimization. */
5832 c = 99;
5834 return c;
5838 ** Return true (non-zero) if pCur is current pointing to the last
5839 ** page of a table.
5841 static int cursorOnLastPage(BtCursor *pCur){
5842 int i;
5843 assert( pCur->eState==CURSOR_VALID );
5844 for(i=0; i<pCur->iPage; i++){
5845 MemPage *pPage = pCur->apPage[i];
5846 if( pCur->aiIdx[i]<pPage->nCell ) return 0;
5848 return 1;
5851 /* Move the cursor so that it points to an entry in an index table
5852 ** near the key pIdxKey. Return a success code.
5854 ** If an exact match is not found, then the cursor is always
5855 ** left pointing at a leaf page which would hold the entry if it
5856 ** were present. The cursor might point to an entry that comes
5857 ** before or after the key.
5859 ** An integer is written into *pRes which is the result of
5860 ** comparing the key with the entry to which the cursor is
5861 ** pointing. The meaning of the integer written into
5862 ** *pRes is as follows:
5864 ** *pRes<0 The cursor is left pointing at an entry that
5865 ** is smaller than pIdxKey or if the table is empty
5866 ** and the cursor is therefore left point to nothing.
5868 ** *pRes==0 The cursor is left pointing at an entry that
5869 ** exactly matches pIdxKey.
5871 ** *pRes>0 The cursor is left pointing at an entry that
5872 ** is larger than pIdxKey.
5874 ** The pIdxKey->eqSeen field is set to 1 if there
5875 ** exists an entry in the table that exactly matches pIdxKey.
5877 int sqlite3BtreeIndexMoveto(
5878 BtCursor *pCur, /* The cursor to be moved */
5879 UnpackedRecord *pIdxKey, /* Unpacked index key */
5880 int *pRes /* Write search results here */
5882 int rc;
5883 RecordCompare xRecordCompare;
5885 assert( cursorOwnsBtShared(pCur) );
5886 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5887 assert( pRes );
5888 assert( pCur->pKeyInfo!=0 );
5890 #ifdef SQLITE_DEBUG
5891 pCur->pBtree->nSeek++; /* Performance measurement during testing */
5892 #endif
5894 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
5895 pIdxKey->errCode = 0;
5896 assert( pIdxKey->default_rc==1
5897 || pIdxKey->default_rc==0
5898 || pIdxKey->default_rc==-1
5902 /* Check to see if we can skip a lot of work. Two cases:
5904 ** (1) If the cursor is already pointing to the very last cell
5905 ** in the table and the pIdxKey search key is greater than or
5906 ** equal to that last cell, then no movement is required.
5908 ** (2) If the cursor is on the last page of the table and the first
5909 ** cell on that last page is less than or equal to the pIdxKey
5910 ** search key, then we can start the search on the current page
5911 ** without needing to go back to root.
5913 if( pCur->eState==CURSOR_VALID
5914 && pCur->pPage->leaf
5915 && cursorOnLastPage(pCur)
5917 int c;
5918 if( pCur->ix==pCur->pPage->nCell-1
5919 && (c = indexCellCompare(pCur, pCur->ix, pIdxKey, xRecordCompare))<=0
5920 && pIdxKey->errCode==SQLITE_OK
5922 *pRes = c;
5923 return SQLITE_OK; /* Cursor already pointing at the correct spot */
5925 if( pCur->iPage>0
5926 && indexCellCompare(pCur, 0, pIdxKey, xRecordCompare)<=0
5927 && pIdxKey->errCode==SQLITE_OK
5929 pCur->curFlags &= ~BTCF_ValidOvfl;
5930 if( !pCur->pPage->isInit ){
5931 return SQLITE_CORRUPT_BKPT;
5933 goto bypass_moveto_root; /* Start search on the current page */
5935 pIdxKey->errCode = SQLITE_OK;
5938 rc = moveToRoot(pCur);
5939 if( rc ){
5940 if( rc==SQLITE_EMPTY ){
5941 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5942 *pRes = -1;
5943 return SQLITE_OK;
5945 return rc;
5948 bypass_moveto_root:
5949 assert( pCur->pPage );
5950 assert( pCur->pPage->isInit );
5951 assert( pCur->eState==CURSOR_VALID );
5952 assert( pCur->pPage->nCell > 0 );
5953 assert( pCur->curIntKey==0 );
5954 assert( pIdxKey!=0 );
5955 for(;;){
5956 int lwr, upr, idx, c;
5957 Pgno chldPg;
5958 MemPage *pPage = pCur->pPage;
5959 u8 *pCell; /* Pointer to current cell in pPage */
5961 /* pPage->nCell must be greater than zero. If this is the root-page
5962 ** the cursor would have been INVALID above and this for(;;) loop
5963 ** not run. If this is not the root-page, then the moveToChild() routine
5964 ** would have already detected db corruption. Similarly, pPage must
5965 ** be the right kind (index or table) of b-tree page. Otherwise
5966 ** a moveToChild() or moveToRoot() call would have detected corruption. */
5967 assert( pPage->nCell>0 );
5968 assert( pPage->intKey==0 );
5969 lwr = 0;
5970 upr = pPage->nCell-1;
5971 idx = upr>>1; /* idx = (lwr+upr)/2; */
5972 for(;;){
5973 int nCell; /* Size of the pCell cell in bytes */
5974 pCell = findCellPastPtr(pPage, idx);
5976 /* The maximum supported page-size is 65536 bytes. This means that
5977 ** the maximum number of record bytes stored on an index B-Tree
5978 ** page is less than 16384 bytes and may be stored as a 2-byte
5979 ** varint. This information is used to attempt to avoid parsing
5980 ** the entire cell by checking for the cases where the record is
5981 ** stored entirely within the b-tree page by inspecting the first
5982 ** 2 bytes of the cell.
5984 nCell = pCell[0];
5985 if( nCell<=pPage->max1bytePayload ){
5986 /* This branch runs if the record-size field of the cell is a
5987 ** single byte varint and the record fits entirely on the main
5988 ** b-tree page. */
5989 testcase( pCell+nCell+1==pPage->aDataEnd );
5990 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
5991 }else if( !(pCell[1] & 0x80)
5992 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5994 /* The record-size field is a 2 byte varint and the record
5995 ** fits entirely on the main b-tree page. */
5996 testcase( pCell+nCell+2==pPage->aDataEnd );
5997 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
5998 }else{
5999 /* The record flows over onto one or more overflow pages. In
6000 ** this case the whole cell needs to be parsed, a buffer allocated
6001 ** and accessPayload() used to retrieve the record into the
6002 ** buffer before VdbeRecordCompare() can be called.
6004 ** If the record is corrupt, the xRecordCompare routine may read
6005 ** up to two varints past the end of the buffer. An extra 18
6006 ** bytes of padding is allocated at the end of the buffer in
6007 ** case this happens. */
6008 void *pCellKey;
6009 u8 * const pCellBody = pCell - pPage->childPtrSize;
6010 const int nOverrun = 18; /* Size of the overrun padding */
6011 pPage->xParseCell(pPage, pCellBody, &pCur->info);
6012 nCell = (int)pCur->info.nKey;
6013 testcase( nCell<0 ); /* True if key size is 2^32 or more */
6014 testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
6015 testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
6016 testcase( nCell==2 ); /* Minimum legal index key size */
6017 if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
6018 rc = SQLITE_CORRUPT_PAGE(pPage);
6019 goto moveto_index_finish;
6021 pCellKey = sqlite3Malloc( nCell+nOverrun );
6022 if( pCellKey==0 ){
6023 rc = SQLITE_NOMEM_BKPT;
6024 goto moveto_index_finish;
6026 pCur->ix = (u16)idx;
6027 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
6028 memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */
6029 pCur->curFlags &= ~BTCF_ValidOvfl;
6030 if( rc ){
6031 sqlite3_free(pCellKey);
6032 goto moveto_index_finish;
6034 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
6035 sqlite3_free(pCellKey);
6037 assert(
6038 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
6039 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
6041 if( c<0 ){
6042 lwr = idx+1;
6043 }else if( c>0 ){
6044 upr = idx-1;
6045 }else{
6046 assert( c==0 );
6047 *pRes = 0;
6048 rc = SQLITE_OK;
6049 pCur->ix = (u16)idx;
6050 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
6051 goto moveto_index_finish;
6053 if( lwr>upr ) break;
6054 assert( lwr+upr>=0 );
6055 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
6057 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
6058 assert( pPage->isInit );
6059 if( pPage->leaf ){
6060 assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
6061 pCur->ix = (u16)idx;
6062 *pRes = c;
6063 rc = SQLITE_OK;
6064 goto moveto_index_finish;
6066 if( lwr>=pPage->nCell ){
6067 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
6068 }else{
6069 chldPg = get4byte(findCell(pPage, lwr));
6072 /* This block is similar to an in-lined version of:
6074 ** pCur->ix = (u16)lwr;
6075 ** rc = moveToChild(pCur, chldPg);
6076 ** if( rc ) break;
6078 pCur->info.nSize = 0;
6079 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
6080 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
6081 return SQLITE_CORRUPT_BKPT;
6083 pCur->aiIdx[pCur->iPage] = (u16)lwr;
6084 pCur->apPage[pCur->iPage] = pCur->pPage;
6085 pCur->ix = 0;
6086 pCur->iPage++;
6087 rc = getAndInitPage(pCur->pBt, chldPg, &pCur->pPage, pCur->curPagerFlags);
6088 if( rc==SQLITE_OK
6089 && (pCur->pPage->nCell<1 || pCur->pPage->intKey!=pCur->curIntKey)
6091 releasePage(pCur->pPage);
6092 rc = SQLITE_CORRUPT_PGNO(chldPg);
6094 if( rc ){
6095 pCur->pPage = pCur->apPage[--pCur->iPage];
6096 break;
6099 ***** End of in-lined moveToChild() call */
6101 moveto_index_finish:
6102 pCur->info.nSize = 0;
6103 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
6104 return rc;
6109 ** Return TRUE if the cursor is not pointing at an entry of the table.
6111 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
6112 ** past the last entry in the table or sqlite3BtreePrev() moves past
6113 ** the first entry. TRUE is also returned if the table is empty.
6115 int sqlite3BtreeEof(BtCursor *pCur){
6116 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
6117 ** have been deleted? This API will need to change to return an error code
6118 ** as well as the boolean result value.
6120 return (CURSOR_VALID!=pCur->eState);
6124 ** Return an estimate for the number of rows in the table that pCur is
6125 ** pointing to. Return a negative number if no estimate is currently
6126 ** available.
6128 i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
6129 i64 n;
6130 u8 i;
6132 assert( cursorOwnsBtShared(pCur) );
6133 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
6135 /* Currently this interface is only called by the OP_IfSmaller
6136 ** opcode, and it that case the cursor will always be valid and
6137 ** will always point to a leaf node. */
6138 if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
6139 if( NEVER(pCur->pPage->leaf==0) ) return -1;
6141 n = pCur->pPage->nCell;
6142 for(i=0; i<pCur->iPage; i++){
6143 n *= pCur->apPage[i]->nCell;
6145 return n;
6149 ** Advance the cursor to the next entry in the database.
6150 ** Return value:
6152 ** SQLITE_OK success
6153 ** SQLITE_DONE cursor is already pointing at the last element
6154 ** otherwise some kind of error occurred
6156 ** The main entry point is sqlite3BtreeNext(). That routine is optimized
6157 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
6158 ** to the next cell on the current page. The (slower) btreeNext() helper
6159 ** routine is called when it is necessary to move to a different page or
6160 ** to restore the cursor.
6162 ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
6163 ** cursor corresponds to an SQL index and this routine could have been
6164 ** skipped if the SQL index had been a unique index. The F argument
6165 ** is a hint to the implement. SQLite btree implementation does not use
6166 ** this hint, but COMDB2 does.
6168 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
6169 int rc;
6170 int idx;
6171 MemPage *pPage;
6173 assert( cursorOwnsBtShared(pCur) );
6174 if( pCur->eState!=CURSOR_VALID ){
6175 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
6176 rc = restoreCursorPosition(pCur);
6177 if( rc!=SQLITE_OK ){
6178 return rc;
6180 if( CURSOR_INVALID==pCur->eState ){
6181 return SQLITE_DONE;
6183 if( pCur->eState==CURSOR_SKIPNEXT ){
6184 pCur->eState = CURSOR_VALID;
6185 if( pCur->skipNext>0 ) return SQLITE_OK;
6189 pPage = pCur->pPage;
6190 idx = ++pCur->ix;
6191 if( sqlite3FaultSim(412) ) pPage->isInit = 0;
6192 if( !pPage->isInit ){
6193 return SQLITE_CORRUPT_BKPT;
6196 if( idx>=pPage->nCell ){
6197 if( !pPage->leaf ){
6198 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
6199 if( rc ) return rc;
6200 return moveToLeftmost(pCur);
6203 if( pCur->iPage==0 ){
6204 pCur->eState = CURSOR_INVALID;
6205 return SQLITE_DONE;
6207 moveToParent(pCur);
6208 pPage = pCur->pPage;
6209 }while( pCur->ix>=pPage->nCell );
6210 if( pPage->intKey ){
6211 return sqlite3BtreeNext(pCur, 0);
6212 }else{
6213 return SQLITE_OK;
6216 if( pPage->leaf ){
6217 return SQLITE_OK;
6218 }else{
6219 return moveToLeftmost(pCur);
6222 int sqlite3BtreeNext(BtCursor *pCur, int flags){
6223 MemPage *pPage;
6224 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
6225 assert( cursorOwnsBtShared(pCur) );
6226 assert( flags==0 || flags==1 );
6227 pCur->info.nSize = 0;
6228 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
6229 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
6230 pPage = pCur->pPage;
6231 if( (++pCur->ix)>=pPage->nCell ){
6232 pCur->ix--;
6233 return btreeNext(pCur);
6235 if( pPage->leaf ){
6236 return SQLITE_OK;
6237 }else{
6238 return moveToLeftmost(pCur);
6243 ** Step the cursor to the back to the previous entry in the database.
6244 ** Return values:
6246 ** SQLITE_OK success
6247 ** SQLITE_DONE the cursor is already on the first element of the table
6248 ** otherwise some kind of error occurred
6250 ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
6251 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
6252 ** to the previous cell on the current page. The (slower) btreePrevious()
6253 ** helper routine is called when it is necessary to move to a different page
6254 ** or to restore the cursor.
6256 ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
6257 ** the cursor corresponds to an SQL index and this routine could have been
6258 ** skipped if the SQL index had been a unique index. The F argument is a
6259 ** hint to the implement. The native SQLite btree implementation does not
6260 ** use this hint, but COMDB2 does.
6262 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
6263 int rc;
6264 MemPage *pPage;
6266 assert( cursorOwnsBtShared(pCur) );
6267 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
6268 assert( pCur->info.nSize==0 );
6269 if( pCur->eState!=CURSOR_VALID ){
6270 rc = restoreCursorPosition(pCur);
6271 if( rc!=SQLITE_OK ){
6272 return rc;
6274 if( CURSOR_INVALID==pCur->eState ){
6275 return SQLITE_DONE;
6277 if( CURSOR_SKIPNEXT==pCur->eState ){
6278 pCur->eState = CURSOR_VALID;
6279 if( pCur->skipNext<0 ) return SQLITE_OK;
6283 pPage = pCur->pPage;
6284 assert( pPage->isInit );
6285 if( !pPage->leaf ){
6286 int idx = pCur->ix;
6287 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
6288 if( rc ) return rc;
6289 rc = moveToRightmost(pCur);
6290 }else{
6291 while( pCur->ix==0 ){
6292 if( pCur->iPage==0 ){
6293 pCur->eState = CURSOR_INVALID;
6294 return SQLITE_DONE;
6296 moveToParent(pCur);
6298 assert( pCur->info.nSize==0 );
6299 assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
6301 pCur->ix--;
6302 pPage = pCur->pPage;
6303 if( pPage->intKey && !pPage->leaf ){
6304 rc = sqlite3BtreePrevious(pCur, 0);
6305 }else{
6306 rc = SQLITE_OK;
6309 return rc;
6311 int sqlite3BtreePrevious(BtCursor *pCur, int flags){
6312 assert( cursorOwnsBtShared(pCur) );
6313 assert( flags==0 || flags==1 );
6314 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
6315 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
6316 pCur->info.nSize = 0;
6317 if( pCur->eState!=CURSOR_VALID
6318 || pCur->ix==0
6319 || pCur->pPage->leaf==0
6321 return btreePrevious(pCur);
6323 pCur->ix--;
6324 return SQLITE_OK;
6328 ** Allocate a new page from the database file.
6330 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
6331 ** has already been called on the new page.) The new page has also
6332 ** been referenced and the calling routine is responsible for calling
6333 ** sqlite3PagerUnref() on the new page when it is done.
6335 ** SQLITE_OK is returned on success. Any other return value indicates
6336 ** an error. *ppPage is set to NULL in the event of an error.
6338 ** If the "nearby" parameter is not 0, then an effort is made to
6339 ** locate a page close to the page number "nearby". This can be used in an
6340 ** attempt to keep related pages close to each other in the database file,
6341 ** which in turn can make database access faster.
6343 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
6344 ** anywhere on the free-list, then it is guaranteed to be returned. If
6345 ** eMode is BTALLOC_LT then the page returned will be less than or equal
6346 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
6347 ** are no restrictions on which page is returned.
6349 static int allocateBtreePage(
6350 BtShared *pBt, /* The btree */
6351 MemPage **ppPage, /* Store pointer to the allocated page here */
6352 Pgno *pPgno, /* Store the page number here */
6353 Pgno nearby, /* Search for a page near this one */
6354 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
6356 MemPage *pPage1;
6357 int rc;
6358 u32 n; /* Number of pages on the freelist */
6359 u32 k; /* Number of leaves on the trunk of the freelist */
6360 MemPage *pTrunk = 0;
6361 MemPage *pPrevTrunk = 0;
6362 Pgno mxPage; /* Total size of the database file */
6364 assert( sqlite3_mutex_held(pBt->mutex) );
6365 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
6366 pPage1 = pBt->pPage1;
6367 mxPage = btreePagecount(pBt);
6368 /* EVIDENCE-OF: R-21003-45125 The 4-byte big-endian integer at offset 36
6369 ** stores the total number of pages on the freelist. */
6370 n = get4byte(&pPage1->aData[36]);
6371 testcase( n==mxPage-1 );
6372 if( n>=mxPage ){
6373 return SQLITE_CORRUPT_BKPT;
6375 if( n>0 ){
6376 /* There are pages on the freelist. Reuse one of those pages. */
6377 Pgno iTrunk;
6378 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
6379 u32 nSearch = 0; /* Count of the number of search attempts */
6381 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
6382 ** shows that the page 'nearby' is somewhere on the free-list, then
6383 ** the entire-list will be searched for that page.
6385 #ifndef SQLITE_OMIT_AUTOVACUUM
6386 if( eMode==BTALLOC_EXACT ){
6387 if( nearby<=mxPage ){
6388 u8 eType;
6389 assert( nearby>0 );
6390 assert( pBt->autoVacuum );
6391 rc = ptrmapGet(pBt, nearby, &eType, 0);
6392 if( rc ) return rc;
6393 if( eType==PTRMAP_FREEPAGE ){
6394 searchList = 1;
6397 }else if( eMode==BTALLOC_LE ){
6398 searchList = 1;
6400 #endif
6402 /* Decrement the free-list count by 1. Set iTrunk to the index of the
6403 ** first free-list trunk page. iPrevTrunk is initially 1.
6405 rc = sqlite3PagerWrite(pPage1->pDbPage);
6406 if( rc ) return rc;
6407 put4byte(&pPage1->aData[36], n-1);
6409 /* The code within this loop is run only once if the 'searchList' variable
6410 ** is not true. Otherwise, it runs once for each trunk-page on the
6411 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
6412 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
6414 do {
6415 pPrevTrunk = pTrunk;
6416 if( pPrevTrunk ){
6417 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
6418 ** is the page number of the next freelist trunk page in the list or
6419 ** zero if this is the last freelist trunk page. */
6420 iTrunk = get4byte(&pPrevTrunk->aData[0]);
6421 }else{
6422 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
6423 ** stores the page number of the first page of the freelist, or zero if
6424 ** the freelist is empty. */
6425 iTrunk = get4byte(&pPage1->aData[32]);
6427 testcase( iTrunk==mxPage );
6428 if( iTrunk>mxPage || nSearch++ > n ){
6429 rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
6430 }else{
6431 rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
6433 if( rc ){
6434 pTrunk = 0;
6435 goto end_allocate_page;
6437 assert( pTrunk!=0 );
6438 assert( pTrunk->aData!=0 );
6439 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
6440 ** is the number of leaf page pointers to follow. */
6441 k = get4byte(&pTrunk->aData[4]);
6442 if( k==0 && !searchList ){
6443 /* The trunk has no leaves and the list is not being searched.
6444 ** So extract the trunk page itself and use it as the newly
6445 ** allocated page */
6446 assert( pPrevTrunk==0 );
6447 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6448 if( rc ){
6449 goto end_allocate_page;
6451 *pPgno = iTrunk;
6452 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6453 *ppPage = pTrunk;
6454 pTrunk = 0;
6455 TRACE(("ALLOCATE: %u trunk - %u free pages left\n", *pPgno, n-1));
6456 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
6457 /* Value of k is out of range. Database corruption */
6458 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6459 goto end_allocate_page;
6460 #ifndef SQLITE_OMIT_AUTOVACUUM
6461 }else if( searchList
6462 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
6464 /* The list is being searched and this trunk page is the page
6465 ** to allocate, regardless of whether it has leaves.
6467 *pPgno = iTrunk;
6468 *ppPage = pTrunk;
6469 searchList = 0;
6470 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6471 if( rc ){
6472 goto end_allocate_page;
6474 if( k==0 ){
6475 if( !pPrevTrunk ){
6476 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6477 }else{
6478 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6479 if( rc!=SQLITE_OK ){
6480 goto end_allocate_page;
6482 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
6484 }else{
6485 /* The trunk page is required by the caller but it contains
6486 ** pointers to free-list leaves. The first leaf becomes a trunk
6487 ** page in this case.
6489 MemPage *pNewTrunk;
6490 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
6491 if( iNewTrunk>mxPage ){
6492 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6493 goto end_allocate_page;
6495 testcase( iNewTrunk==mxPage );
6496 rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
6497 if( rc!=SQLITE_OK ){
6498 goto end_allocate_page;
6500 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
6501 if( rc!=SQLITE_OK ){
6502 releasePage(pNewTrunk);
6503 goto end_allocate_page;
6505 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
6506 put4byte(&pNewTrunk->aData[4], k-1);
6507 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
6508 releasePage(pNewTrunk);
6509 if( !pPrevTrunk ){
6510 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
6511 put4byte(&pPage1->aData[32], iNewTrunk);
6512 }else{
6513 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6514 if( rc ){
6515 goto end_allocate_page;
6517 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
6520 pTrunk = 0;
6521 TRACE(("ALLOCATE: %u trunk - %u free pages left\n", *pPgno, n-1));
6522 #endif
6523 }else if( k>0 ){
6524 /* Extract a leaf from the trunk */
6525 u32 closest;
6526 Pgno iPage;
6527 unsigned char *aData = pTrunk->aData;
6528 if( nearby>0 ){
6529 u32 i;
6530 closest = 0;
6531 if( eMode==BTALLOC_LE ){
6532 for(i=0; i<k; i++){
6533 iPage = get4byte(&aData[8+i*4]);
6534 if( iPage<=nearby ){
6535 closest = i;
6536 break;
6539 }else{
6540 int dist;
6541 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
6542 for(i=1; i<k; i++){
6543 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
6544 if( d2<dist ){
6545 closest = i;
6546 dist = d2;
6550 }else{
6551 closest = 0;
6554 iPage = get4byte(&aData[8+closest*4]);
6555 testcase( iPage==mxPage );
6556 if( iPage>mxPage || iPage<2 ){
6557 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6558 goto end_allocate_page;
6560 testcase( iPage==mxPage );
6561 if( !searchList
6562 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
6564 int noContent;
6565 *pPgno = iPage;
6566 TRACE(("ALLOCATE: %u was leaf %u of %u on trunk %u"
6567 ": %u more free pages\n",
6568 *pPgno, closest+1, k, pTrunk->pgno, n-1));
6569 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6570 if( rc ) goto end_allocate_page;
6571 if( closest<k-1 ){
6572 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
6574 put4byte(&aData[4], k-1);
6575 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
6576 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
6577 if( rc==SQLITE_OK ){
6578 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6579 if( rc!=SQLITE_OK ){
6580 releasePage(*ppPage);
6581 *ppPage = 0;
6584 searchList = 0;
6587 releasePage(pPrevTrunk);
6588 pPrevTrunk = 0;
6589 }while( searchList );
6590 }else{
6591 /* There are no pages on the freelist, so append a new page to the
6592 ** database image.
6594 ** Normally, new pages allocated by this block can be requested from the
6595 ** pager layer with the 'no-content' flag set. This prevents the pager
6596 ** from trying to read the pages content from disk. However, if the
6597 ** current transaction has already run one or more incremental-vacuum
6598 ** steps, then the page we are about to allocate may contain content
6599 ** that is required in the event of a rollback. In this case, do
6600 ** not set the no-content flag. This causes the pager to load and journal
6601 ** the current page content before overwriting it.
6603 ** Note that the pager will not actually attempt to load or journal
6604 ** content for any page that really does lie past the end of the database
6605 ** file on disk. So the effects of disabling the no-content optimization
6606 ** here are confined to those pages that lie between the end of the
6607 ** database image and the end of the database file.
6609 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
6611 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6612 if( rc ) return rc;
6613 pBt->nPage++;
6614 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
6616 #ifndef SQLITE_OMIT_AUTOVACUUM
6617 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
6618 /* If *pPgno refers to a pointer-map page, allocate two new pages
6619 ** at the end of the file instead of one. The first allocated page
6620 ** becomes a new pointer-map page, the second is used by the caller.
6622 MemPage *pPg = 0;
6623 TRACE(("ALLOCATE: %u from end of file (pointer-map page)\n", pBt->nPage));
6624 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
6625 rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
6626 if( rc==SQLITE_OK ){
6627 rc = sqlite3PagerWrite(pPg->pDbPage);
6628 releasePage(pPg);
6630 if( rc ) return rc;
6631 pBt->nPage++;
6632 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
6634 #endif
6635 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
6636 *pPgno = pBt->nPage;
6638 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
6639 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
6640 if( rc ) return rc;
6641 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6642 if( rc!=SQLITE_OK ){
6643 releasePage(*ppPage);
6644 *ppPage = 0;
6646 TRACE(("ALLOCATE: %u from end of file\n", *pPgno));
6649 assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );
6651 end_allocate_page:
6652 releasePage(pTrunk);
6653 releasePage(pPrevTrunk);
6654 assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
6655 assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
6656 return rc;
6660 ** This function is used to add page iPage to the database file free-list.
6661 ** It is assumed that the page is not already a part of the free-list.
6663 ** The value passed as the second argument to this function is optional.
6664 ** If the caller happens to have a pointer to the MemPage object
6665 ** corresponding to page iPage handy, it may pass it as the second value.
6666 ** Otherwise, it may pass NULL.
6668 ** If a pointer to a MemPage object is passed as the second argument,
6669 ** its reference count is not altered by this function.
6671 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
6672 MemPage *pTrunk = 0; /* Free-list trunk page */
6673 Pgno iTrunk = 0; /* Page number of free-list trunk page */
6674 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
6675 MemPage *pPage; /* Page being freed. May be NULL. */
6676 int rc; /* Return Code */
6677 u32 nFree; /* Initial number of pages on free-list */
6679 assert( sqlite3_mutex_held(pBt->mutex) );
6680 assert( CORRUPT_DB || iPage>1 );
6681 assert( !pMemPage || pMemPage->pgno==iPage );
6683 if( iPage<2 || iPage>pBt->nPage ){
6684 return SQLITE_CORRUPT_BKPT;
6686 if( pMemPage ){
6687 pPage = pMemPage;
6688 sqlite3PagerRef(pPage->pDbPage);
6689 }else{
6690 pPage = btreePageLookup(pBt, iPage);
6693 /* Increment the free page count on pPage1 */
6694 rc = sqlite3PagerWrite(pPage1->pDbPage);
6695 if( rc ) goto freepage_out;
6696 nFree = get4byte(&pPage1->aData[36]);
6697 put4byte(&pPage1->aData[36], nFree+1);
6699 if( pBt->btsFlags & BTS_SECURE_DELETE ){
6700 /* If the secure_delete option is enabled, then
6701 ** always fully overwrite deleted information with zeros.
6703 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
6704 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
6706 goto freepage_out;
6708 memset(pPage->aData, 0, pPage->pBt->pageSize);
6711 /* If the database supports auto-vacuum, write an entry in the pointer-map
6712 ** to indicate that the page is free.
6714 if( ISAUTOVACUUM(pBt) ){
6715 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
6716 if( rc ) goto freepage_out;
6719 /* Now manipulate the actual database free-list structure. There are two
6720 ** possibilities. If the free-list is currently empty, or if the first
6721 ** trunk page in the free-list is full, then this page will become a
6722 ** new free-list trunk page. Otherwise, it will become a leaf of the
6723 ** first trunk page in the current free-list. This block tests if it
6724 ** is possible to add the page as a new free-list leaf.
6726 if( nFree!=0 ){
6727 u32 nLeaf; /* Initial number of leaf cells on trunk page */
6729 iTrunk = get4byte(&pPage1->aData[32]);
6730 if( iTrunk>btreePagecount(pBt) ){
6731 rc = SQLITE_CORRUPT_BKPT;
6732 goto freepage_out;
6734 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
6735 if( rc!=SQLITE_OK ){
6736 goto freepage_out;
6739 nLeaf = get4byte(&pTrunk->aData[4]);
6740 assert( pBt->usableSize>32 );
6741 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
6742 rc = SQLITE_CORRUPT_BKPT;
6743 goto freepage_out;
6745 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
6746 /* In this case there is room on the trunk page to insert the page
6747 ** being freed as a new leaf.
6749 ** Note that the trunk page is not really full until it contains
6750 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
6751 ** coded. But due to a coding error in versions of SQLite prior to
6752 ** 3.6.0, databases with freelist trunk pages holding more than
6753 ** usableSize/4 - 8 entries will be reported as corrupt. In order
6754 ** to maintain backwards compatibility with older versions of SQLite,
6755 ** we will continue to restrict the number of entries to usableSize/4 - 8
6756 ** for now. At some point in the future (once everyone has upgraded
6757 ** to 3.6.0 or later) we should consider fixing the conditional above
6758 ** to read "usableSize/4-2" instead of "usableSize/4-8".
6760 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
6761 ** avoid using the last six entries in the freelist trunk page array in
6762 ** order that database files created by newer versions of SQLite can be
6763 ** read by older versions of SQLite.
6765 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6766 if( rc==SQLITE_OK ){
6767 put4byte(&pTrunk->aData[4], nLeaf+1);
6768 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
6769 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
6770 sqlite3PagerDontWrite(pPage->pDbPage);
6772 rc = btreeSetHasContent(pBt, iPage);
6774 TRACE(("FREE-PAGE: %u leaf on trunk page %u\n",pPage->pgno,pTrunk->pgno));
6775 goto freepage_out;
6779 /* If control flows to this point, then it was not possible to add the
6780 ** the page being freed as a leaf page of the first trunk in the free-list.
6781 ** Possibly because the free-list is empty, or possibly because the
6782 ** first trunk in the free-list is full. Either way, the page being freed
6783 ** will become the new first trunk page in the free-list.
6785 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
6786 goto freepage_out;
6788 rc = sqlite3PagerWrite(pPage->pDbPage);
6789 if( rc!=SQLITE_OK ){
6790 goto freepage_out;
6792 put4byte(pPage->aData, iTrunk);
6793 put4byte(&pPage->aData[4], 0);
6794 put4byte(&pPage1->aData[32], iPage);
6795 TRACE(("FREE-PAGE: %u new trunk page replacing %u\n", pPage->pgno, iTrunk));
6797 freepage_out:
6798 if( pPage ){
6799 pPage->isInit = 0;
6801 releasePage(pPage);
6802 releasePage(pTrunk);
6803 return rc;
6805 static void freePage(MemPage *pPage, int *pRC){
6806 if( (*pRC)==SQLITE_OK ){
6807 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
6812 ** Free the overflow pages associated with the given Cell.
6814 static SQLITE_NOINLINE int clearCellOverflow(
6815 MemPage *pPage, /* The page that contains the Cell */
6816 unsigned char *pCell, /* First byte of the Cell */
6817 CellInfo *pInfo /* Size information about the cell */
6819 BtShared *pBt;
6820 Pgno ovflPgno;
6821 int rc;
6822 int nOvfl;
6823 u32 ovflPageSize;
6825 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6826 assert( pInfo->nLocal!=pInfo->nPayload );
6827 testcase( pCell + pInfo->nSize == pPage->aDataEnd );
6828 testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
6829 if( pCell + pInfo->nSize > pPage->aDataEnd ){
6830 /* Cell extends past end of page */
6831 return SQLITE_CORRUPT_PAGE(pPage);
6833 ovflPgno = get4byte(pCell + pInfo->nSize - 4);
6834 pBt = pPage->pBt;
6835 assert( pBt->usableSize > 4 );
6836 ovflPageSize = pBt->usableSize - 4;
6837 nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
6838 assert( nOvfl>0 ||
6839 (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
6841 while( nOvfl-- ){
6842 Pgno iNext = 0;
6843 MemPage *pOvfl = 0;
6844 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
6845 /* 0 is not a legal page number and page 1 cannot be an
6846 ** overflow page. Therefore if ovflPgno<2 or past the end of the
6847 ** file the database must be corrupt. */
6848 return SQLITE_CORRUPT_BKPT;
6850 if( nOvfl ){
6851 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
6852 if( rc ) return rc;
6855 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
6856 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
6858 /* There is no reason any cursor should have an outstanding reference
6859 ** to an overflow page belonging to a cell that is being deleted/updated.
6860 ** So if there exists more than one reference to this page, then it
6861 ** must not really be an overflow page and the database must be corrupt.
6862 ** It is helpful to detect this before calling freePage2(), as
6863 ** freePage2() may zero the page contents if secure-delete mode is
6864 ** enabled. If this 'overflow' page happens to be a page that the
6865 ** caller is iterating through or using in some other way, this
6866 ** can be problematic.
6868 rc = SQLITE_CORRUPT_BKPT;
6869 }else{
6870 rc = freePage2(pBt, pOvfl, ovflPgno);
6873 if( pOvfl ){
6874 sqlite3PagerUnref(pOvfl->pDbPage);
6876 if( rc ) return rc;
6877 ovflPgno = iNext;
6879 return SQLITE_OK;
6882 /* Call xParseCell to compute the size of a cell. If the cell contains
6883 ** overflow, then invoke cellClearOverflow to clear out that overflow.
6884 ** Store the result code (SQLITE_OK or some error code) in rc.
6886 ** Implemented as macro to force inlining for performance.
6888 #define BTREE_CLEAR_CELL(rc, pPage, pCell, sInfo) \
6889 pPage->xParseCell(pPage, pCell, &sInfo); \
6890 if( sInfo.nLocal!=sInfo.nPayload ){ \
6891 rc = clearCellOverflow(pPage, pCell, &sInfo); \
6892 }else{ \
6893 rc = SQLITE_OK; \
6898 ** Create the byte sequence used to represent a cell on page pPage
6899 ** and write that byte sequence into pCell[]. Overflow pages are
6900 ** allocated and filled in as necessary. The calling procedure
6901 ** is responsible for making sure sufficient space has been allocated
6902 ** for pCell[].
6904 ** Note that pCell does not necessary need to point to the pPage->aData
6905 ** area. pCell might point to some temporary storage. The cell will
6906 ** be constructed in this temporary area then copied into pPage->aData
6907 ** later.
6909 static int fillInCell(
6910 MemPage *pPage, /* The page that contains the cell */
6911 unsigned char *pCell, /* Complete text of the cell */
6912 const BtreePayload *pX, /* Payload with which to construct the cell */
6913 int *pnSize /* Write cell size here */
6915 int nPayload;
6916 const u8 *pSrc;
6917 int nSrc, n, rc, mn;
6918 int spaceLeft;
6919 MemPage *pToRelease;
6920 unsigned char *pPrior;
6921 unsigned char *pPayload;
6922 BtShared *pBt;
6923 Pgno pgnoOvfl;
6924 int nHeader;
6926 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6928 /* pPage is not necessarily writeable since pCell might be auxiliary
6929 ** buffer space that is separate from the pPage buffer area */
6930 assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
6931 || sqlite3PagerIswriteable(pPage->pDbPage) );
6933 /* Fill in the header. */
6934 nHeader = pPage->childPtrSize;
6935 if( pPage->intKey ){
6936 nPayload = pX->nData + pX->nZero;
6937 pSrc = pX->pData;
6938 nSrc = pX->nData;
6939 assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
6940 nHeader += putVarint32(&pCell[nHeader], nPayload);
6941 nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
6942 }else{
6943 assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
6944 nSrc = nPayload = (int)pX->nKey;
6945 pSrc = pX->pKey;
6946 nHeader += putVarint32(&pCell[nHeader], nPayload);
6949 /* Fill in the payload */
6950 pPayload = &pCell[nHeader];
6951 if( nPayload<=pPage->maxLocal ){
6952 /* This is the common case where everything fits on the btree page
6953 ** and no overflow pages are required. */
6954 n = nHeader + nPayload;
6955 testcase( n==3 );
6956 testcase( n==4 );
6957 if( n<4 ) n = 4;
6958 *pnSize = n;
6959 assert( nSrc<=nPayload );
6960 testcase( nSrc<nPayload );
6961 memcpy(pPayload, pSrc, nSrc);
6962 memset(pPayload+nSrc, 0, nPayload-nSrc);
6963 return SQLITE_OK;
6966 /* If we reach this point, it means that some of the content will need
6967 ** to spill onto overflow pages.
6969 mn = pPage->minLocal;
6970 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
6971 testcase( n==pPage->maxLocal );
6972 testcase( n==pPage->maxLocal+1 );
6973 if( n > pPage->maxLocal ) n = mn;
6974 spaceLeft = n;
6975 *pnSize = n + nHeader + 4;
6976 pPrior = &pCell[nHeader+n];
6977 pToRelease = 0;
6978 pgnoOvfl = 0;
6979 pBt = pPage->pBt;
6981 /* At this point variables should be set as follows:
6983 ** nPayload Total payload size in bytes
6984 ** pPayload Begin writing payload here
6985 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
6986 ** that means content must spill into overflow pages.
6987 ** *pnSize Size of the local cell (not counting overflow pages)
6988 ** pPrior Where to write the pgno of the first overflow page
6990 ** Use a call to btreeParseCellPtr() to verify that the values above
6991 ** were computed correctly.
6993 #ifdef SQLITE_DEBUG
6995 CellInfo info;
6996 pPage->xParseCell(pPage, pCell, &info);
6997 assert( nHeader==(int)(info.pPayload - pCell) );
6998 assert( info.nKey==pX->nKey );
6999 assert( *pnSize == info.nSize );
7000 assert( spaceLeft == info.nLocal );
7002 #endif
7004 /* Write the payload into the local Cell and any extra into overflow pages */
7005 while( 1 ){
7006 n = nPayload;
7007 if( n>spaceLeft ) n = spaceLeft;
7009 /* If pToRelease is not zero than pPayload points into the data area
7010 ** of pToRelease. Make sure pToRelease is still writeable. */
7011 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
7013 /* If pPayload is part of the data area of pPage, then make sure pPage
7014 ** is still writeable */
7015 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
7016 || sqlite3PagerIswriteable(pPage->pDbPage) );
7018 if( nSrc>=n ){
7019 memcpy(pPayload, pSrc, n);
7020 }else if( nSrc>0 ){
7021 n = nSrc;
7022 memcpy(pPayload, pSrc, n);
7023 }else{
7024 memset(pPayload, 0, n);
7026 nPayload -= n;
7027 if( nPayload<=0 ) break;
7028 pPayload += n;
7029 pSrc += n;
7030 nSrc -= n;
7031 spaceLeft -= n;
7032 if( spaceLeft==0 ){
7033 MemPage *pOvfl = 0;
7034 #ifndef SQLITE_OMIT_AUTOVACUUM
7035 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
7036 if( pBt->autoVacuum ){
7038 pgnoOvfl++;
7039 } while(
7040 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
7043 #endif
7044 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
7045 #ifndef SQLITE_OMIT_AUTOVACUUM
7046 /* If the database supports auto-vacuum, and the second or subsequent
7047 ** overflow page is being allocated, add an entry to the pointer-map
7048 ** for that page now.
7050 ** If this is the first overflow page, then write a partial entry
7051 ** to the pointer-map. If we write nothing to this pointer-map slot,
7052 ** then the optimistic overflow chain processing in clearCell()
7053 ** may misinterpret the uninitialized values and delete the
7054 ** wrong pages from the database.
7056 if( pBt->autoVacuum && rc==SQLITE_OK ){
7057 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
7058 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
7059 if( rc ){
7060 releasePage(pOvfl);
7063 #endif
7064 if( rc ){
7065 releasePage(pToRelease);
7066 return rc;
7069 /* If pToRelease is not zero than pPrior points into the data area
7070 ** of pToRelease. Make sure pToRelease is still writeable. */
7071 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
7073 /* If pPrior is part of the data area of pPage, then make sure pPage
7074 ** is still writeable */
7075 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
7076 || sqlite3PagerIswriteable(pPage->pDbPage) );
7078 put4byte(pPrior, pgnoOvfl);
7079 releasePage(pToRelease);
7080 pToRelease = pOvfl;
7081 pPrior = pOvfl->aData;
7082 put4byte(pPrior, 0);
7083 pPayload = &pOvfl->aData[4];
7084 spaceLeft = pBt->usableSize - 4;
7087 releasePage(pToRelease);
7088 return SQLITE_OK;
7092 ** Remove the i-th cell from pPage. This routine effects pPage only.
7093 ** The cell content is not freed or deallocated. It is assumed that
7094 ** the cell content has been copied someplace else. This routine just
7095 ** removes the reference to the cell from pPage.
7097 ** "sz" must be the number of bytes in the cell.
7099 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
7100 u32 pc; /* Offset to cell content of cell being deleted */
7101 u8 *data; /* pPage->aData */
7102 u8 *ptr; /* Used to move bytes around within data[] */
7103 int rc; /* The return code */
7104 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
7106 if( *pRC ) return;
7107 assert( idx>=0 );
7108 assert( idx<pPage->nCell );
7109 assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
7110 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
7111 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7112 assert( pPage->nFree>=0 );
7113 data = pPage->aData;
7114 ptr = &pPage->aCellIdx[2*idx];
7115 assert( pPage->pBt->usableSize > (u32)(ptr-data) );
7116 pc = get2byte(ptr);
7117 hdr = pPage->hdrOffset;
7118 testcase( pc==(u32)get2byte(&data[hdr+5]) );
7119 testcase( pc+sz==pPage->pBt->usableSize );
7120 if( pc+sz > pPage->pBt->usableSize ){
7121 *pRC = SQLITE_CORRUPT_BKPT;
7122 return;
7124 rc = freeSpace(pPage, pc, sz);
7125 if( rc ){
7126 *pRC = rc;
7127 return;
7129 pPage->nCell--;
7130 if( pPage->nCell==0 ){
7131 memset(&data[hdr+1], 0, 4);
7132 data[hdr+7] = 0;
7133 put2byte(&data[hdr+5], pPage->pBt->usableSize);
7134 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
7135 - pPage->childPtrSize - 8;
7136 }else{
7137 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
7138 put2byte(&data[hdr+3], pPage->nCell);
7139 pPage->nFree += 2;
7144 ** Insert a new cell on pPage at cell index "i". pCell points to the
7145 ** content of the cell.
7147 ** If the cell content will fit on the page, then put it there. If it
7148 ** will not fit, then make a copy of the cell content into pTemp if
7149 ** pTemp is not null. Regardless of pTemp, allocate a new entry
7150 ** in pPage->apOvfl[] and make it point to the cell content (either
7151 ** in pTemp or the original pCell) and also record its index.
7152 ** Allocating a new entry in pPage->aCell[] implies that
7153 ** pPage->nOverflow is incremented.
7155 ** The insertCellFast() routine below works exactly the same as
7156 ** insertCell() except that it lacks the pTemp and iChild parameters
7157 ** which are assumed zero. Other than that, the two routines are the
7158 ** same.
7160 ** Fixes or enhancements to this routine should be reflected in
7161 ** insertCellFast()!
7163 static int insertCell(
7164 MemPage *pPage, /* Page into which we are copying */
7165 int i, /* New cell becomes the i-th cell of the page */
7166 u8 *pCell, /* Content of the new cell */
7167 int sz, /* Bytes of content in pCell */
7168 u8 *pTemp, /* Temp storage space for pCell, if needed */
7169 Pgno iChild /* If non-zero, replace first 4 bytes with this value */
7171 int idx = 0; /* Where to write new cell content in data[] */
7172 int j; /* Loop counter */
7173 u8 *data; /* The content of the whole page */
7174 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
7176 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
7177 assert( MX_CELL(pPage->pBt)<=10921 );
7178 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
7179 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
7180 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
7181 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7182 assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
7183 assert( pPage->nFree>=0 );
7184 assert( iChild>0 );
7185 if( pPage->nOverflow || sz+2>pPage->nFree ){
7186 if( pTemp ){
7187 memcpy(pTemp, pCell, sz);
7188 pCell = pTemp;
7190 put4byte(pCell, iChild);
7191 j = pPage->nOverflow++;
7192 /* Comparison against ArraySize-1 since we hold back one extra slot
7193 ** as a contingency. In other words, never need more than 3 overflow
7194 ** slots but 4 are allocated, just to be safe. */
7195 assert( j < ArraySize(pPage->apOvfl)-1 );
7196 pPage->apOvfl[j] = pCell;
7197 pPage->aiOvfl[j] = (u16)i;
7199 /* When multiple overflows occur, they are always sequential and in
7200 ** sorted order. This invariants arise because multiple overflows can
7201 ** only occur when inserting divider cells into the parent page during
7202 ** balancing, and the dividers are adjacent and sorted.
7204 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
7205 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
7206 }else{
7207 int rc = sqlite3PagerWrite(pPage->pDbPage);
7208 if( NEVER(rc!=SQLITE_OK) ){
7209 return rc;
7211 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
7212 data = pPage->aData;
7213 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
7214 rc = allocateSpace(pPage, sz, &idx);
7215 if( rc ){ return rc; }
7216 /* The allocateSpace() routine guarantees the following properties
7217 ** if it returns successfully */
7218 assert( idx >= 0 );
7219 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
7220 assert( idx+sz <= (int)pPage->pBt->usableSize );
7221 pPage->nFree -= (u16)(2 + sz);
7222 /* In a corrupt database where an entry in the cell index section of
7223 ** a btree page has a value of 3 or less, the pCell value might point
7224 ** as many as 4 bytes in front of the start of the aData buffer for
7225 ** the source page. Make sure this does not cause problems by not
7226 ** reading the first 4 bytes */
7227 memcpy(&data[idx+4], pCell+4, sz-4);
7228 put4byte(&data[idx], iChild);
7229 pIns = pPage->aCellIdx + i*2;
7230 memmove(pIns+2, pIns, 2*(pPage->nCell - i));
7231 put2byte(pIns, idx);
7232 pPage->nCell++;
7233 /* increment the cell count */
7234 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
7235 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
7236 #ifndef SQLITE_OMIT_AUTOVACUUM
7237 if( pPage->pBt->autoVacuum ){
7238 int rc2 = SQLITE_OK;
7239 /* The cell may contain a pointer to an overflow page. If so, write
7240 ** the entry for the overflow page into the pointer map.
7242 ptrmapPutOvflPtr(pPage, pPage, pCell, &rc2);
7243 if( rc2 ) return rc2;
7245 #endif
7247 return SQLITE_OK;
7251 ** This variant of insertCell() assumes that the pTemp and iChild
7252 ** parameters are both zero. Use this variant in sqlite3BtreeInsert()
7253 ** for performance improvement, and also so that this variant is only
7254 ** called from that one place, and is thus inlined, and thus runs must
7255 ** faster.
7257 ** Fixes or enhancements to this routine should be reflected into
7258 ** the insertCell() routine.
7260 static int insertCellFast(
7261 MemPage *pPage, /* Page into which we are copying */
7262 int i, /* New cell becomes the i-th cell of the page */
7263 u8 *pCell, /* Content of the new cell */
7264 int sz /* Bytes of content in pCell */
7266 int idx = 0; /* Where to write new cell content in data[] */
7267 int j; /* Loop counter */
7268 u8 *data; /* The content of the whole page */
7269 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
7271 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
7272 assert( MX_CELL(pPage->pBt)<=10921 );
7273 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
7274 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
7275 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
7276 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7277 assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
7278 assert( pPage->nFree>=0 );
7279 assert( pPage->nOverflow==0 );
7280 if( sz+2>pPage->nFree ){
7281 j = pPage->nOverflow++;
7282 /* Comparison against ArraySize-1 since we hold back one extra slot
7283 ** as a contingency. In other words, never need more than 3 overflow
7284 ** slots but 4 are allocated, just to be safe. */
7285 assert( j < ArraySize(pPage->apOvfl)-1 );
7286 pPage->apOvfl[j] = pCell;
7287 pPage->aiOvfl[j] = (u16)i;
7289 /* When multiple overflows occur, they are always sequential and in
7290 ** sorted order. This invariants arise because multiple overflows can
7291 ** only occur when inserting divider cells into the parent page during
7292 ** balancing, and the dividers are adjacent and sorted.
7294 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
7295 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
7296 }else{
7297 int rc = sqlite3PagerWrite(pPage->pDbPage);
7298 if( rc!=SQLITE_OK ){
7299 return rc;
7301 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
7302 data = pPage->aData;
7303 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
7304 rc = allocateSpace(pPage, sz, &idx);
7305 if( rc ){ return rc; }
7306 /* The allocateSpace() routine guarantees the following properties
7307 ** if it returns successfully */
7308 assert( idx >= 0 );
7309 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
7310 assert( idx+sz <= (int)pPage->pBt->usableSize );
7311 pPage->nFree -= (u16)(2 + sz);
7312 memcpy(&data[idx], pCell, sz);
7313 pIns = pPage->aCellIdx + i*2;
7314 memmove(pIns+2, pIns, 2*(pPage->nCell - i));
7315 put2byte(pIns, idx);
7316 pPage->nCell++;
7317 /* increment the cell count */
7318 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
7319 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
7320 #ifndef SQLITE_OMIT_AUTOVACUUM
7321 if( pPage->pBt->autoVacuum ){
7322 int rc2 = SQLITE_OK;
7323 /* The cell may contain a pointer to an overflow page. If so, write
7324 ** the entry for the overflow page into the pointer map.
7326 ptrmapPutOvflPtr(pPage, pPage, pCell, &rc2);
7327 if( rc2 ) return rc2;
7329 #endif
7331 return SQLITE_OK;
7335 ** The following parameters determine how many adjacent pages get involved
7336 ** in a balancing operation. NN is the number of neighbors on either side
7337 ** of the page that participate in the balancing operation. NB is the
7338 ** total number of pages that participate, including the target page and
7339 ** NN neighbors on either side.
7341 ** The minimum value of NN is 1 (of course). Increasing NN above 1
7342 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
7343 ** in exchange for a larger degradation in INSERT and UPDATE performance.
7344 ** The value of NN appears to give the best results overall.
7346 ** (Later:) The description above makes it seem as if these values are
7347 ** tunable - as if you could change them and recompile and it would all work.
7348 ** But that is unlikely. NB has been 3 since the inception of SQLite and
7349 ** we have never tested any other value.
7351 #define NN 1 /* Number of neighbors on either side of pPage */
7352 #define NB 3 /* (NN*2+1): Total pages involved in the balance */
7355 ** A CellArray object contains a cache of pointers and sizes for a
7356 ** consecutive sequence of cells that might be held on multiple pages.
7358 ** The cells in this array are the divider cell or cells from the pParent
7359 ** page plus up to three child pages. There are a total of nCell cells.
7361 ** pRef is a pointer to one of the pages that contributes cells. This is
7362 ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
7363 ** which should be common to all pages that contribute cells to this array.
7365 ** apCell[] and szCell[] hold, respectively, pointers to the start of each
7366 ** cell and the size of each cell. Some of the apCell[] pointers might refer
7367 ** to overflow cells. In other words, some apCel[] pointers might not point
7368 ** to content area of the pages.
7370 ** A szCell[] of zero means the size of that cell has not yet been computed.
7372 ** The cells come from as many as four different pages:
7374 ** -----------
7375 ** | Parent |
7376 ** -----------
7377 ** / | \
7378 ** / | \
7379 ** --------- --------- ---------
7380 ** |Child-1| |Child-2| |Child-3|
7381 ** --------- --------- ---------
7383 ** The order of cells is in the array is for an index btree is:
7385 ** 1. All cells from Child-1 in order
7386 ** 2. The first divider cell from Parent
7387 ** 3. All cells from Child-2 in order
7388 ** 4. The second divider cell from Parent
7389 ** 5. All cells from Child-3 in order
7391 ** For a table-btree (with rowids) the items 2 and 4 are empty because
7392 ** content exists only in leaves and there are no divider cells.
7394 ** For an index btree, the apEnd[] array holds pointer to the end of page
7395 ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
7396 ** respectively. The ixNx[] array holds the number of cells contained in
7397 ** each of these 5 stages, and all stages to the left. Hence:
7399 ** ixNx[0] = Number of cells in Child-1.
7400 ** ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
7401 ** ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
7402 ** ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
7403 ** ixNx[4] = Total number of cells.
7405 ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
7406 ** are used and they point to the leaf pages only, and the ixNx value are:
7408 ** ixNx[0] = Number of cells in Child-1.
7409 ** ixNx[1] = Number of cells in Child-1 and Child-2.
7410 ** ixNx[2] = Total number of cells.
7412 ** Sometimes when deleting, a child page can have zero cells. In those
7413 ** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[]
7414 ** entries, shift down. The end result is that each ixNx[] entry should
7415 ** be larger than the previous
7417 typedef struct CellArray CellArray;
7418 struct CellArray {
7419 int nCell; /* Number of cells in apCell[] */
7420 MemPage *pRef; /* Reference page */
7421 u8 **apCell; /* All cells begin balanced */
7422 u16 *szCell; /* Local size of all cells in apCell[] */
7423 u8 *apEnd[NB*2]; /* MemPage.aDataEnd values */
7424 int ixNx[NB*2]; /* Index of at which we move to the next apEnd[] */
7428 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
7429 ** computed.
7431 static void populateCellCache(CellArray *p, int idx, int N){
7432 MemPage *pRef = p->pRef;
7433 u16 *szCell = p->szCell;
7434 assert( idx>=0 && idx+N<=p->nCell );
7435 while( N>0 ){
7436 assert( p->apCell[idx]!=0 );
7437 if( szCell[idx]==0 ){
7438 szCell[idx] = pRef->xCellSize(pRef, p->apCell[idx]);
7439 }else{
7440 assert( CORRUPT_DB ||
7441 szCell[idx]==pRef->xCellSize(pRef, p->apCell[idx]) );
7443 idx++;
7444 N--;
7449 ** Return the size of the Nth element of the cell array
7451 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
7452 assert( N>=0 && N<p->nCell );
7453 assert( p->szCell[N]==0 );
7454 p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
7455 return p->szCell[N];
7457 static u16 cachedCellSize(CellArray *p, int N){
7458 assert( N>=0 && N<p->nCell );
7459 if( p->szCell[N] ) return p->szCell[N];
7460 return computeCellSize(p, N);
7464 ** Array apCell[] contains pointers to nCell b-tree page cells. The
7465 ** szCell[] array contains the size in bytes of each cell. This function
7466 ** replaces the current contents of page pPg with the contents of the cell
7467 ** array.
7469 ** Some of the cells in apCell[] may currently be stored in pPg. This
7470 ** function works around problems caused by this by making a copy of any
7471 ** such cells before overwriting the page data.
7473 ** The MemPage.nFree field is invalidated by this function. It is the
7474 ** responsibility of the caller to set it correctly.
7476 static int rebuildPage(
7477 CellArray *pCArray, /* Content to be added to page pPg */
7478 int iFirst, /* First cell in pCArray to use */
7479 int nCell, /* Final number of cells on page */
7480 MemPage *pPg /* The page to be reconstructed */
7482 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
7483 u8 * const aData = pPg->aData; /* Pointer to data for pPg */
7484 const int usableSize = pPg->pBt->usableSize;
7485 u8 * const pEnd = &aData[usableSize];
7486 int i = iFirst; /* Which cell to copy from pCArray*/
7487 u32 j; /* Start of cell content area */
7488 int iEnd = i+nCell; /* Loop terminator */
7489 u8 *pCellptr = pPg->aCellIdx;
7490 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7491 u8 *pData;
7492 int k; /* Current slot in pCArray->apEnd[] */
7493 u8 *pSrcEnd; /* Current pCArray->apEnd[k] value */
7495 assert( nCell>0 );
7496 assert( i<iEnd );
7497 j = get2byte(&aData[hdr+5]);
7498 if( j>(u32)usableSize ){ j = 0; }
7499 memcpy(&pTmp[j], &aData[j], usableSize - j);
7501 for(k=0; ALWAYS(k<NB*2) && pCArray->ixNx[k]<=i; k++){}
7502 pSrcEnd = pCArray->apEnd[k];
7504 pData = pEnd;
7505 while( 1/*exit by break*/ ){
7506 u8 *pCell = pCArray->apCell[i];
7507 u16 sz = pCArray->szCell[i];
7508 assert( sz>0 );
7509 if( SQLITE_WITHIN(pCell,aData+j,pEnd) ){
7510 if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
7511 pCell = &pTmp[pCell - aData];
7512 }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
7513 && (uptr)(pCell)<(uptr)pSrcEnd
7515 return SQLITE_CORRUPT_BKPT;
7518 pData -= sz;
7519 put2byte(pCellptr, (pData - aData));
7520 pCellptr += 2;
7521 if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
7522 memmove(pData, pCell, sz);
7523 assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
7524 i++;
7525 if( i>=iEnd ) break;
7526 if( pCArray->ixNx[k]<=i ){
7527 k++;
7528 pSrcEnd = pCArray->apEnd[k];
7532 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
7533 pPg->nCell = nCell;
7534 pPg->nOverflow = 0;
7536 put2byte(&aData[hdr+1], 0);
7537 put2byte(&aData[hdr+3], pPg->nCell);
7538 put2byte(&aData[hdr+5], pData - aData);
7539 aData[hdr+7] = 0x00;
7540 return SQLITE_OK;
7544 ** The pCArray objects contains pointers to b-tree cells and the cell sizes.
7545 ** This function attempts to add the cells stored in the array to page pPg.
7546 ** If it cannot (because the page needs to be defragmented before the cells
7547 ** will fit), non-zero is returned. Otherwise, if the cells are added
7548 ** successfully, zero is returned.
7550 ** Argument pCellptr points to the first entry in the cell-pointer array
7551 ** (part of page pPg) to populate. After cell apCell[0] is written to the
7552 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
7553 ** cell in the array. It is the responsibility of the caller to ensure
7554 ** that it is safe to overwrite this part of the cell-pointer array.
7556 ** When this function is called, *ppData points to the start of the
7557 ** content area on page pPg. If the size of the content area is extended,
7558 ** *ppData is updated to point to the new start of the content area
7559 ** before returning.
7561 ** Finally, argument pBegin points to the byte immediately following the
7562 ** end of the space required by this page for the cell-pointer area (for
7563 ** all cells - not just those inserted by the current call). If the content
7564 ** area must be extended to before this point in order to accommodate all
7565 ** cells in apCell[], then the cells do not fit and non-zero is returned.
7567 static int pageInsertArray(
7568 MemPage *pPg, /* Page to add cells to */
7569 u8 *pBegin, /* End of cell-pointer array */
7570 u8 **ppData, /* IN/OUT: Page content-area pointer */
7571 u8 *pCellptr, /* Pointer to cell-pointer area */
7572 int iFirst, /* Index of first cell to add */
7573 int nCell, /* Number of cells to add to pPg */
7574 CellArray *pCArray /* Array of cells */
7576 int i = iFirst; /* Loop counter - cell index to insert */
7577 u8 *aData = pPg->aData; /* Complete page */
7578 u8 *pData = *ppData; /* Content area. A subset of aData[] */
7579 int iEnd = iFirst + nCell; /* End of loop. One past last cell to ins */
7580 int k; /* Current slot in pCArray->apEnd[] */
7581 u8 *pEnd; /* Maximum extent of cell data */
7582 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
7583 if( iEnd<=iFirst ) return 0;
7584 for(k=0; ALWAYS(k<NB*2) && pCArray->ixNx[k]<=i ; k++){}
7585 pEnd = pCArray->apEnd[k];
7586 while( 1 /*Exit by break*/ ){
7587 int sz, rc;
7588 u8 *pSlot;
7589 assert( pCArray->szCell[i]!=0 );
7590 sz = pCArray->szCell[i];
7591 if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
7592 if( (pData - pBegin)<sz ) return 1;
7593 pData -= sz;
7594 pSlot = pData;
7596 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
7597 ** database. But they might for a corrupt database. Hence use memmove()
7598 ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
7599 assert( (pSlot+sz)<=pCArray->apCell[i]
7600 || pSlot>=(pCArray->apCell[i]+sz)
7601 || CORRUPT_DB );
7602 if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
7603 && (uptr)(pCArray->apCell[i])<(uptr)pEnd
7605 assert( CORRUPT_DB );
7606 (void)SQLITE_CORRUPT_BKPT;
7607 return 1;
7609 memmove(pSlot, pCArray->apCell[i], sz);
7610 put2byte(pCellptr, (pSlot - aData));
7611 pCellptr += 2;
7612 i++;
7613 if( i>=iEnd ) break;
7614 if( pCArray->ixNx[k]<=i ){
7615 k++;
7616 pEnd = pCArray->apEnd[k];
7619 *ppData = pData;
7620 return 0;
7624 ** The pCArray object contains pointers to b-tree cells and their sizes.
7626 ** This function adds the space associated with each cell in the array
7627 ** that is currently stored within the body of pPg to the pPg free-list.
7628 ** The cell-pointers and other fields of the page are not updated.
7630 ** This function returns the total number of cells added to the free-list.
7632 static int pageFreeArray(
7633 MemPage *pPg, /* Page to edit */
7634 int iFirst, /* First cell to delete */
7635 int nCell, /* Cells to delete */
7636 CellArray *pCArray /* Array of cells */
7638 u8 * const aData = pPg->aData;
7639 u8 * const pEnd = &aData[pPg->pBt->usableSize];
7640 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
7641 int nRet = 0;
7642 int i, j;
7643 int iEnd = iFirst + nCell;
7644 int nFree = 0;
7645 int aOfst[10];
7646 int aAfter[10];
7648 for(i=iFirst; i<iEnd; i++){
7649 u8 *pCell = pCArray->apCell[i];
7650 if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
7651 int sz;
7652 int iAfter;
7653 int iOfst;
7654 /* No need to use cachedCellSize() here. The sizes of all cells that
7655 ** are to be freed have already been computing while deciding which
7656 ** cells need freeing */
7657 sz = pCArray->szCell[i]; assert( sz>0 );
7658 iOfst = (u16)(pCell - aData);
7659 iAfter = iOfst+sz;
7660 for(j=0; j<nFree; j++){
7661 if( aOfst[j]==iAfter ){
7662 aOfst[j] = iOfst;
7663 break;
7664 }else if( aAfter[j]==iOfst ){
7665 aAfter[j] = iAfter;
7666 break;
7669 if( j>=nFree ){
7670 if( nFree>=(int)(sizeof(aOfst)/sizeof(aOfst[0])) ){
7671 for(j=0; j<nFree; j++){
7672 freeSpace(pPg, aOfst[j], aAfter[j]-aOfst[j]);
7674 nFree = 0;
7676 aOfst[nFree] = iOfst;
7677 aAfter[nFree] = iAfter;
7678 if( &aData[iAfter]>pEnd ) return 0;
7679 nFree++;
7681 nRet++;
7684 for(j=0; j<nFree; j++){
7685 freeSpace(pPg, aOfst[j], aAfter[j]-aOfst[j]);
7687 return nRet;
7691 ** pCArray contains pointers to and sizes of all cells in the page being
7692 ** balanced. The current page, pPg, has pPg->nCell cells starting with
7693 ** pCArray->apCell[iOld]. After balancing, this page should hold nNew cells
7694 ** starting at apCell[iNew].
7696 ** This routine makes the necessary adjustments to pPg so that it contains
7697 ** the correct cells after being balanced.
7699 ** The pPg->nFree field is invalid when this function returns. It is the
7700 ** responsibility of the caller to set it correctly.
7702 static int editPage(
7703 MemPage *pPg, /* Edit this page */
7704 int iOld, /* Index of first cell currently on page */
7705 int iNew, /* Index of new first cell on page */
7706 int nNew, /* Final number of cells on page */
7707 CellArray *pCArray /* Array of cells and sizes */
7709 u8 * const aData = pPg->aData;
7710 const int hdr = pPg->hdrOffset;
7711 u8 *pBegin = &pPg->aCellIdx[nNew * 2];
7712 int nCell = pPg->nCell; /* Cells stored on pPg */
7713 u8 *pData;
7714 u8 *pCellptr;
7715 int i;
7716 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
7717 int iNewEnd = iNew + nNew;
7719 #ifdef SQLITE_DEBUG
7720 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7721 memcpy(pTmp, aData, pPg->pBt->usableSize);
7722 #endif
7724 /* Remove cells from the start and end of the page */
7725 assert( nCell>=0 );
7726 if( iOld<iNew ){
7727 int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
7728 if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT;
7729 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
7730 nCell -= nShift;
7732 if( iNewEnd < iOldEnd ){
7733 int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
7734 assert( nCell>=nTail );
7735 nCell -= nTail;
7738 pData = &aData[get2byte(&aData[hdr+5])];
7739 if( pData<pBegin ) goto editpage_fail;
7740 if( NEVER(pData>pPg->aDataEnd) ) goto editpage_fail;
7742 /* Add cells to the start of the page */
7743 if( iNew<iOld ){
7744 int nAdd = MIN(nNew,iOld-iNew);
7745 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
7746 assert( nAdd>=0 );
7747 pCellptr = pPg->aCellIdx;
7748 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
7749 if( pageInsertArray(
7750 pPg, pBegin, &pData, pCellptr,
7751 iNew, nAdd, pCArray
7752 ) ) goto editpage_fail;
7753 nCell += nAdd;
7756 /* Add any overflow cells */
7757 for(i=0; i<pPg->nOverflow; i++){
7758 int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
7759 if( iCell>=0 && iCell<nNew ){
7760 pCellptr = &pPg->aCellIdx[iCell * 2];
7761 if( nCell>iCell ){
7762 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
7764 nCell++;
7765 cachedCellSize(pCArray, iCell+iNew);
7766 if( pageInsertArray(
7767 pPg, pBegin, &pData, pCellptr,
7768 iCell+iNew, 1, pCArray
7769 ) ) goto editpage_fail;
7773 /* Append cells to the end of the page */
7774 assert( nCell>=0 );
7775 pCellptr = &pPg->aCellIdx[nCell*2];
7776 if( pageInsertArray(
7777 pPg, pBegin, &pData, pCellptr,
7778 iNew+nCell, nNew-nCell, pCArray
7779 ) ) goto editpage_fail;
7781 pPg->nCell = nNew;
7782 pPg->nOverflow = 0;
7784 put2byte(&aData[hdr+3], pPg->nCell);
7785 put2byte(&aData[hdr+5], pData - aData);
7787 #ifdef SQLITE_DEBUG
7788 for(i=0; i<nNew && !CORRUPT_DB; i++){
7789 u8 *pCell = pCArray->apCell[i+iNew];
7790 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
7791 if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
7792 pCell = &pTmp[pCell - aData];
7794 assert( 0==memcmp(pCell, &aData[iOff],
7795 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
7797 #endif
7799 return SQLITE_OK;
7800 editpage_fail:
7801 /* Unable to edit this page. Rebuild it from scratch instead. */
7802 if( nNew<1 ) return SQLITE_CORRUPT_BKPT;
7803 populateCellCache(pCArray, iNew, nNew);
7804 return rebuildPage(pCArray, iNew, nNew, pPg);
7808 #ifndef SQLITE_OMIT_QUICKBALANCE
7810 ** This version of balance() handles the common special case where
7811 ** a new entry is being inserted on the extreme right-end of the
7812 ** tree, in other words, when the new entry will become the largest
7813 ** entry in the tree.
7815 ** Instead of trying to balance the 3 right-most leaf pages, just add
7816 ** a new page to the right-hand side and put the one new entry in
7817 ** that page. This leaves the right side of the tree somewhat
7818 ** unbalanced. But odds are that we will be inserting new entries
7819 ** at the end soon afterwards so the nearly empty page will quickly
7820 ** fill up. On average.
7822 ** pPage is the leaf page which is the right-most page in the tree.
7823 ** pParent is its parent. pPage must have a single overflow entry
7824 ** which is also the right-most entry on the page.
7826 ** The pSpace buffer is used to store a temporary copy of the divider
7827 ** cell that will be inserted into pParent. Such a cell consists of a 4
7828 ** byte page number followed by a variable length integer. In other
7829 ** words, at most 13 bytes. Hence the pSpace buffer must be at
7830 ** least 13 bytes in size.
7832 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
7833 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
7834 MemPage *pNew; /* Newly allocated page */
7835 int rc; /* Return Code */
7836 Pgno pgnoNew; /* Page number of pNew */
7838 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7839 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7840 assert( pPage->nOverflow==1 );
7842 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; /* dbfuzz001.test */
7843 assert( pPage->nFree>=0 );
7844 assert( pParent->nFree>=0 );
7846 /* Allocate a new page. This page will become the right-sibling of
7847 ** pPage. Make the parent page writable, so that the new divider cell
7848 ** may be inserted. If both these operations are successful, proceed.
7850 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
7852 if( rc==SQLITE_OK ){
7854 u8 *pOut = &pSpace[4];
7855 u8 *pCell = pPage->apOvfl[0];
7856 u16 szCell = pPage->xCellSize(pPage, pCell);
7857 u8 *pStop;
7858 CellArray b;
7860 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
7861 assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
7862 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
7863 b.nCell = 1;
7864 b.pRef = pPage;
7865 b.apCell = &pCell;
7866 b.szCell = &szCell;
7867 b.apEnd[0] = pPage->aDataEnd;
7868 b.ixNx[0] = 2;
7869 rc = rebuildPage(&b, 0, 1, pNew);
7870 if( NEVER(rc) ){
7871 releasePage(pNew);
7872 return rc;
7874 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
7876 /* If this is an auto-vacuum database, update the pointer map
7877 ** with entries for the new page, and any pointer from the
7878 ** cell on the page to an overflow page. If either of these
7879 ** operations fails, the return code is set, but the contents
7880 ** of the parent page are still manipulated by the code below.
7881 ** That is Ok, at this point the parent page is guaranteed to
7882 ** be marked as dirty. Returning an error code will cause a
7883 ** rollback, undoing any changes made to the parent page.
7885 if( ISAUTOVACUUM(pBt) ){
7886 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
7887 if( szCell>pNew->minLocal ){
7888 ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
7892 /* Create a divider cell to insert into pParent. The divider cell
7893 ** consists of a 4-byte page number (the page number of pPage) and
7894 ** a variable length key value (which must be the same value as the
7895 ** largest key on pPage).
7897 ** To find the largest key value on pPage, first find the right-most
7898 ** cell on pPage. The first two fields of this cell are the
7899 ** record-length (a variable length integer at most 32-bits in size)
7900 ** and the key value (a variable length integer, may have any value).
7901 ** The first of the while(...) loops below skips over the record-length
7902 ** field. The second while(...) loop copies the key value from the
7903 ** cell on pPage into the pSpace buffer.
7905 pCell = findCell(pPage, pPage->nCell-1);
7906 pStop = &pCell[9];
7907 while( (*(pCell++)&0x80) && pCell<pStop );
7908 pStop = &pCell[9];
7909 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
7911 /* Insert the new divider cell into pParent. */
7912 if( rc==SQLITE_OK ){
7913 rc = insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
7914 0, pPage->pgno);
7917 /* Set the right-child pointer of pParent to point to the new page. */
7918 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
7920 /* Release the reference to the new page. */
7921 releasePage(pNew);
7924 return rc;
7926 #endif /* SQLITE_OMIT_QUICKBALANCE */
7928 #if 0
7930 ** This function does not contribute anything to the operation of SQLite.
7931 ** it is sometimes activated temporarily while debugging code responsible
7932 ** for setting pointer-map entries.
7934 static int ptrmapCheckPages(MemPage **apPage, int nPage){
7935 int i, j;
7936 for(i=0; i<nPage; i++){
7937 Pgno n;
7938 u8 e;
7939 MemPage *pPage = apPage[i];
7940 BtShared *pBt = pPage->pBt;
7941 assert( pPage->isInit );
7943 for(j=0; j<pPage->nCell; j++){
7944 CellInfo info;
7945 u8 *z;
7947 z = findCell(pPage, j);
7948 pPage->xParseCell(pPage, z, &info);
7949 if( info.nLocal<info.nPayload ){
7950 Pgno ovfl = get4byte(&z[info.nSize-4]);
7951 ptrmapGet(pBt, ovfl, &e, &n);
7952 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
7954 if( !pPage->leaf ){
7955 Pgno child = get4byte(z);
7956 ptrmapGet(pBt, child, &e, &n);
7957 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7960 if( !pPage->leaf ){
7961 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
7962 ptrmapGet(pBt, child, &e, &n);
7963 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7966 return 1;
7968 #endif
7971 ** This function is used to copy the contents of the b-tree node stored
7972 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
7973 ** the pointer-map entries for each child page are updated so that the
7974 ** parent page stored in the pointer map is page pTo. If pFrom contained
7975 ** any cells with overflow page pointers, then the corresponding pointer
7976 ** map entries are also updated so that the parent page is page pTo.
7978 ** If pFrom is currently carrying any overflow cells (entries in the
7979 ** MemPage.apOvfl[] array), they are not copied to pTo.
7981 ** Before returning, page pTo is reinitialized using btreeInitPage().
7983 ** The performance of this function is not critical. It is only used by
7984 ** the balance_shallower() and balance_deeper() procedures, neither of
7985 ** which are called often under normal circumstances.
7987 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
7988 if( (*pRC)==SQLITE_OK ){
7989 BtShared * const pBt = pFrom->pBt;
7990 u8 * const aFrom = pFrom->aData;
7991 u8 * const aTo = pTo->aData;
7992 int const iFromHdr = pFrom->hdrOffset;
7993 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
7994 int rc;
7995 int iData;
7998 assert( pFrom->isInit );
7999 assert( pFrom->nFree>=iToHdr );
8000 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
8002 /* Copy the b-tree node content from page pFrom to page pTo. */
8003 iData = get2byte(&aFrom[iFromHdr+5]);
8004 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
8005 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
8007 /* Reinitialize page pTo so that the contents of the MemPage structure
8008 ** match the new data. The initialization of pTo can actually fail under
8009 ** fairly obscure circumstances, even though it is a copy of initialized
8010 ** page pFrom.
8012 pTo->isInit = 0;
8013 rc = btreeInitPage(pTo);
8014 if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo);
8015 if( rc!=SQLITE_OK ){
8016 *pRC = rc;
8017 return;
8020 /* If this is an auto-vacuum database, update the pointer-map entries
8021 ** for any b-tree or overflow pages that pTo now contains the pointers to.
8023 if( ISAUTOVACUUM(pBt) ){
8024 *pRC = setChildPtrmaps(pTo);
8030 ** This routine redistributes cells on the iParentIdx'th child of pParent
8031 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
8032 ** same amount of free space. Usually a single sibling on either side of the
8033 ** page are used in the balancing, though both siblings might come from one
8034 ** side if the page is the first or last child of its parent. If the page
8035 ** has fewer than 2 siblings (something which can only happen if the page
8036 ** is a root page or a child of a root page) then all available siblings
8037 ** participate in the balancing.
8039 ** The number of siblings of the page might be increased or decreased by
8040 ** one or two in an effort to keep pages nearly full but not over full.
8042 ** Note that when this routine is called, some of the cells on the page
8043 ** might not actually be stored in MemPage.aData[]. This can happen
8044 ** if the page is overfull. This routine ensures that all cells allocated
8045 ** to the page and its siblings fit into MemPage.aData[] before returning.
8047 ** In the course of balancing the page and its siblings, cells may be
8048 ** inserted into or removed from the parent page (pParent). Doing so
8049 ** may cause the parent page to become overfull or underfull. If this
8050 ** happens, it is the responsibility of the caller to invoke the correct
8051 ** balancing routine to fix this problem (see the balance() routine).
8053 ** If this routine fails for any reason, it might leave the database
8054 ** in a corrupted state. So if this routine fails, the database should
8055 ** be rolled back.
8057 ** The third argument to this function, aOvflSpace, is a pointer to a
8058 ** buffer big enough to hold one page. If while inserting cells into the parent
8059 ** page (pParent) the parent page becomes overfull, this buffer is
8060 ** used to store the parent's overflow cells. Because this function inserts
8061 ** a maximum of four divider cells into the parent page, and the maximum
8062 ** size of a cell stored within an internal node is always less than 1/4
8063 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
8064 ** enough for all overflow cells.
8066 ** If aOvflSpace is set to a null pointer, this function returns
8067 ** SQLITE_NOMEM.
8069 static int balance_nonroot(
8070 MemPage *pParent, /* Parent page of siblings being balanced */
8071 int iParentIdx, /* Index of "the page" in pParent */
8072 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
8073 int isRoot, /* True if pParent is a root-page */
8074 int bBulk /* True if this call is part of a bulk load */
8076 BtShared *pBt; /* The whole database */
8077 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
8078 int nNew = 0; /* Number of pages in apNew[] */
8079 int nOld; /* Number of pages in apOld[] */
8080 int i, j, k; /* Loop counters */
8081 int nxDiv; /* Next divider slot in pParent->aCell[] */
8082 int rc = SQLITE_OK; /* The return code */
8083 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
8084 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
8085 int usableSpace; /* Bytes in pPage beyond the header */
8086 int pageFlags; /* Value of pPage->aData[0] */
8087 int iSpace1 = 0; /* First unused byte of aSpace1[] */
8088 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
8089 int szScratch; /* Size of scratch memory requested */
8090 MemPage *apOld[NB]; /* pPage and up to two siblings */
8091 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
8092 u8 *pRight; /* Location in parent of right-sibling pointer */
8093 u8 *apDiv[NB-1]; /* Divider cells in pParent */
8094 int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
8095 int cntOld[NB+2]; /* Old index in b.apCell[] */
8096 int szNew[NB+2]; /* Combined size of cells placed on i-th page */
8097 u8 *aSpace1; /* Space for copies of dividers cells */
8098 Pgno pgno; /* Temp var to store a page number in */
8099 u8 abDone[NB+2]; /* True after i'th new page is populated */
8100 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
8101 CellArray b; /* Parsed information on cells being balanced */
8103 memset(abDone, 0, sizeof(abDone));
8104 memset(&b, 0, sizeof(b));
8105 pBt = pParent->pBt;
8106 assert( sqlite3_mutex_held(pBt->mutex) );
8107 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8109 /* At this point pParent may have at most one overflow cell. And if
8110 ** this overflow cell is present, it must be the cell with
8111 ** index iParentIdx. This scenario comes about when this function
8112 ** is called (indirectly) from sqlite3BtreeDelete().
8114 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
8115 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
8117 if( !aOvflSpace ){
8118 return SQLITE_NOMEM_BKPT;
8120 assert( pParent->nFree>=0 );
8122 /* Find the sibling pages to balance. Also locate the cells in pParent
8123 ** that divide the siblings. An attempt is made to find NN siblings on
8124 ** either side of pPage. More siblings are taken from one side, however,
8125 ** if there are fewer than NN siblings on the other side. If pParent
8126 ** has NB or fewer children then all children of pParent are taken.
8128 ** This loop also drops the divider cells from the parent page. This
8129 ** way, the remainder of the function does not have to deal with any
8130 ** overflow cells in the parent page, since if any existed they will
8131 ** have already been removed.
8133 i = pParent->nOverflow + pParent->nCell;
8134 if( i<2 ){
8135 nxDiv = 0;
8136 }else{
8137 assert( bBulk==0 || bBulk==1 );
8138 if( iParentIdx==0 ){
8139 nxDiv = 0;
8140 }else if( iParentIdx==i ){
8141 nxDiv = i-2+bBulk;
8142 }else{
8143 nxDiv = iParentIdx-1;
8145 i = 2-bBulk;
8147 nOld = i+1;
8148 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
8149 pRight = &pParent->aData[pParent->hdrOffset+8];
8150 }else{
8151 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
8153 pgno = get4byte(pRight);
8154 while( 1 ){
8155 if( rc==SQLITE_OK ){
8156 rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
8158 if( rc ){
8159 memset(apOld, 0, (i+1)*sizeof(MemPage*));
8160 goto balance_cleanup;
8162 if( apOld[i]->nFree<0 ){
8163 rc = btreeComputeFreeSpace(apOld[i]);
8164 if( rc ){
8165 memset(apOld, 0, (i)*sizeof(MemPage*));
8166 goto balance_cleanup;
8169 nMaxCells += apOld[i]->nCell + ArraySize(pParent->apOvfl);
8170 if( (i--)==0 ) break;
8172 if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
8173 apDiv[i] = pParent->apOvfl[0];
8174 pgno = get4byte(apDiv[i]);
8175 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
8176 pParent->nOverflow = 0;
8177 }else{
8178 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
8179 pgno = get4byte(apDiv[i]);
8180 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
8182 /* Drop the cell from the parent page. apDiv[i] still points to
8183 ** the cell within the parent, even though it has been dropped.
8184 ** This is safe because dropping a cell only overwrites the first
8185 ** four bytes of it, and this function does not need the first
8186 ** four bytes of the divider cell. So the pointer is safe to use
8187 ** later on.
8189 ** But not if we are in secure-delete mode. In secure-delete mode,
8190 ** the dropCell() routine will overwrite the entire cell with zeroes.
8191 ** In this case, temporarily copy the cell into the aOvflSpace[]
8192 ** buffer. It will be copied out again as soon as the aSpace[] buffer
8193 ** is allocated. */
8194 if( pBt->btsFlags & BTS_FAST_SECURE ){
8195 int iOff;
8197 /* If the following if() condition is not true, the db is corrupted.
8198 ** The call to dropCell() below will detect this. */
8199 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
8200 if( (iOff+szNew[i])<=(int)pBt->usableSize ){
8201 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
8202 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
8205 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
8209 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
8210 ** alignment */
8211 nMaxCells = (nMaxCells + 3)&~3;
8214 ** Allocate space for memory structures
8216 szScratch =
8217 nMaxCells*sizeof(u8*) /* b.apCell */
8218 + nMaxCells*sizeof(u16) /* b.szCell */
8219 + pBt->pageSize; /* aSpace1 */
8221 assert( szScratch<=7*(int)pBt->pageSize );
8222 b.apCell = sqlite3StackAllocRaw(0, szScratch );
8223 if( b.apCell==0 ){
8224 rc = SQLITE_NOMEM_BKPT;
8225 goto balance_cleanup;
8227 b.szCell = (u16*)&b.apCell[nMaxCells];
8228 aSpace1 = (u8*)&b.szCell[nMaxCells];
8229 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
8232 ** Load pointers to all cells on sibling pages and the divider cells
8233 ** into the local b.apCell[] array. Make copies of the divider cells
8234 ** into space obtained from aSpace1[]. The divider cells have already
8235 ** been removed from pParent.
8237 ** If the siblings are on leaf pages, then the child pointers of the
8238 ** divider cells are stripped from the cells before they are copied
8239 ** into aSpace1[]. In this way, all cells in b.apCell[] are without
8240 ** child pointers. If siblings are not leaves, then all cell in
8241 ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
8242 ** are alike.
8244 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
8245 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
8247 b.pRef = apOld[0];
8248 leafCorrection = b.pRef->leaf*4;
8249 leafData = b.pRef->intKeyLeaf;
8250 for(i=0; i<nOld; i++){
8251 MemPage *pOld = apOld[i];
8252 int limit = pOld->nCell;
8253 u8 *aData = pOld->aData;
8254 u16 maskPage = pOld->maskPage;
8255 u8 *piCell = aData + pOld->cellOffset;
8256 u8 *piEnd;
8257 VVA_ONLY( int nCellAtStart = b.nCell; )
8259 /* Verify that all sibling pages are of the same "type" (table-leaf,
8260 ** table-interior, index-leaf, or index-interior).
8262 if( pOld->aData[0]!=apOld[0]->aData[0] ){
8263 rc = SQLITE_CORRUPT_BKPT;
8264 goto balance_cleanup;
8267 /* Load b.apCell[] with pointers to all cells in pOld. If pOld
8268 ** contains overflow cells, include them in the b.apCell[] array
8269 ** in the correct spot.
8271 ** Note that when there are multiple overflow cells, it is always the
8272 ** case that they are sequential and adjacent. This invariant arises
8273 ** because multiple overflows can only occurs when inserting divider
8274 ** cells into a parent on a prior balance, and divider cells are always
8275 ** adjacent and are inserted in order. There is an assert() tagged
8276 ** with "NOTE 1" in the overflow cell insertion loop to prove this
8277 ** invariant.
8279 ** This must be done in advance. Once the balance starts, the cell
8280 ** offset section of the btree page will be overwritten and we will no
8281 ** long be able to find the cells if a pointer to each cell is not saved
8282 ** first.
8284 memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
8285 if( pOld->nOverflow>0 ){
8286 if( NEVER(limit<pOld->aiOvfl[0]) ){
8287 rc = SQLITE_CORRUPT_BKPT;
8288 goto balance_cleanup;
8290 limit = pOld->aiOvfl[0];
8291 for(j=0; j<limit; j++){
8292 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
8293 piCell += 2;
8294 b.nCell++;
8296 for(k=0; k<pOld->nOverflow; k++){
8297 assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
8298 b.apCell[b.nCell] = pOld->apOvfl[k];
8299 b.nCell++;
8302 piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
8303 while( piCell<piEnd ){
8304 assert( b.nCell<nMaxCells );
8305 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
8306 piCell += 2;
8307 b.nCell++;
8309 assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );
8311 cntOld[i] = b.nCell;
8312 if( i<nOld-1 && !leafData){
8313 u16 sz = (u16)szNew[i];
8314 u8 *pTemp;
8315 assert( b.nCell<nMaxCells );
8316 b.szCell[b.nCell] = sz;
8317 pTemp = &aSpace1[iSpace1];
8318 iSpace1 += sz;
8319 assert( sz<=pBt->maxLocal+23 );
8320 assert( iSpace1 <= (int)pBt->pageSize );
8321 memcpy(pTemp, apDiv[i], sz);
8322 b.apCell[b.nCell] = pTemp+leafCorrection;
8323 assert( leafCorrection==0 || leafCorrection==4 );
8324 b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
8325 if( !pOld->leaf ){
8326 assert( leafCorrection==0 );
8327 assert( pOld->hdrOffset==0 || CORRUPT_DB );
8328 /* The right pointer of the child page pOld becomes the left
8329 ** pointer of the divider cell */
8330 memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
8331 }else{
8332 assert( leafCorrection==4 );
8333 while( b.szCell[b.nCell]<4 ){
8334 /* Do not allow any cells smaller than 4 bytes. If a smaller cell
8335 ** does exist, pad it with 0x00 bytes. */
8336 assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
8337 assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
8338 aSpace1[iSpace1++] = 0x00;
8339 b.szCell[b.nCell]++;
8342 b.nCell++;
8347 ** Figure out the number of pages needed to hold all b.nCell cells.
8348 ** Store this number in "k". Also compute szNew[] which is the total
8349 ** size of all cells on the i-th page and cntNew[] which is the index
8350 ** in b.apCell[] of the cell that divides page i from page i+1.
8351 ** cntNew[k] should equal b.nCell.
8353 ** Values computed by this block:
8355 ** k: The total number of sibling pages
8356 ** szNew[i]: Spaced used on the i-th sibling page.
8357 ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
8358 ** the right of the i-th sibling page.
8359 ** usableSpace: Number of bytes of space available on each sibling.
8362 usableSpace = pBt->usableSize - 12 + leafCorrection;
8363 for(i=k=0; i<nOld; i++, k++){
8364 MemPage *p = apOld[i];
8365 b.apEnd[k] = p->aDataEnd;
8366 b.ixNx[k] = cntOld[i];
8367 if( k && b.ixNx[k]==b.ixNx[k-1] ){
8368 k--; /* Omit b.ixNx[] entry for child pages with no cells */
8370 if( !leafData ){
8371 k++;
8372 b.apEnd[k] = pParent->aDataEnd;
8373 b.ixNx[k] = cntOld[i]+1;
8375 assert( p->nFree>=0 );
8376 szNew[i] = usableSpace - p->nFree;
8377 for(j=0; j<p->nOverflow; j++){
8378 szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
8380 cntNew[i] = cntOld[i];
8382 k = nOld;
8383 for(i=0; i<k; i++){
8384 int sz;
8385 while( szNew[i]>usableSpace ){
8386 if( i+1>=k ){
8387 k = i+2;
8388 if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
8389 szNew[k-1] = 0;
8390 cntNew[k-1] = b.nCell;
8392 sz = 2 + cachedCellSize(&b, cntNew[i]-1);
8393 szNew[i] -= sz;
8394 if( !leafData ){
8395 if( cntNew[i]<b.nCell ){
8396 sz = 2 + cachedCellSize(&b, cntNew[i]);
8397 }else{
8398 sz = 0;
8401 szNew[i+1] += sz;
8402 cntNew[i]--;
8404 while( cntNew[i]<b.nCell ){
8405 sz = 2 + cachedCellSize(&b, cntNew[i]);
8406 if( szNew[i]+sz>usableSpace ) break;
8407 szNew[i] += sz;
8408 cntNew[i]++;
8409 if( !leafData ){
8410 if( cntNew[i]<b.nCell ){
8411 sz = 2 + cachedCellSize(&b, cntNew[i]);
8412 }else{
8413 sz = 0;
8416 szNew[i+1] -= sz;
8418 if( cntNew[i]>=b.nCell ){
8419 k = i+1;
8420 }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
8421 rc = SQLITE_CORRUPT_BKPT;
8422 goto balance_cleanup;
8427 ** The packing computed by the previous block is biased toward the siblings
8428 ** on the left side (siblings with smaller keys). The left siblings are
8429 ** always nearly full, while the right-most sibling might be nearly empty.
8430 ** The next block of code attempts to adjust the packing of siblings to
8431 ** get a better balance.
8433 ** This adjustment is more than an optimization. The packing above might
8434 ** be so out of balance as to be illegal. For example, the right-most
8435 ** sibling might be completely empty. This adjustment is not optional.
8437 for(i=k-1; i>0; i--){
8438 int szRight = szNew[i]; /* Size of sibling on the right */
8439 int szLeft = szNew[i-1]; /* Size of sibling on the left */
8440 int r; /* Index of right-most cell in left sibling */
8441 int d; /* Index of first cell to the left of right sibling */
8443 r = cntNew[i-1] - 1;
8444 d = r + 1 - leafData;
8445 (void)cachedCellSize(&b, d);
8447 int szR, szD;
8448 assert( d<nMaxCells );
8449 assert( r<nMaxCells );
8450 szR = cachedCellSize(&b, r);
8451 szD = b.szCell[d];
8452 if( szRight!=0
8453 && (bBulk || szRight+szD+2 > szLeft-(szR+(i==k-1?0:2)))){
8454 break;
8456 szRight += szD + 2;
8457 szLeft -= szR + 2;
8458 cntNew[i-1] = r;
8459 r--;
8460 d--;
8461 }while( r>=0 );
8462 szNew[i] = szRight;
8463 szNew[i-1] = szLeft;
8464 if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
8465 rc = SQLITE_CORRUPT_BKPT;
8466 goto balance_cleanup;
8470 /* Sanity check: For a non-corrupt database file one of the following
8471 ** must be true:
8472 ** (1) We found one or more cells (cntNew[0])>0), or
8473 ** (2) pPage is a virtual root page. A virtual root page is when
8474 ** the real root page is page 1 and we are the only child of
8475 ** that page.
8477 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
8478 TRACE(("BALANCE: old: %u(nc=%u) %u(nc=%u) %u(nc=%u)\n",
8479 apOld[0]->pgno, apOld[0]->nCell,
8480 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
8481 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
8485 ** Allocate k new pages. Reuse old pages where possible.
8487 pageFlags = apOld[0]->aData[0];
8488 for(i=0; i<k; i++){
8489 MemPage *pNew;
8490 if( i<nOld ){
8491 pNew = apNew[i] = apOld[i];
8492 apOld[i] = 0;
8493 rc = sqlite3PagerWrite(pNew->pDbPage);
8494 nNew++;
8495 if( sqlite3PagerPageRefcount(pNew->pDbPage)!=1+(i==(iParentIdx-nxDiv))
8496 && rc==SQLITE_OK
8498 rc = SQLITE_CORRUPT_BKPT;
8500 if( rc ) goto balance_cleanup;
8501 }else{
8502 assert( i>0 );
8503 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
8504 if( rc ) goto balance_cleanup;
8505 zeroPage(pNew, pageFlags);
8506 apNew[i] = pNew;
8507 nNew++;
8508 cntOld[i] = b.nCell;
8510 /* Set the pointer-map entry for the new sibling page. */
8511 if( ISAUTOVACUUM(pBt) ){
8512 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
8513 if( rc!=SQLITE_OK ){
8514 goto balance_cleanup;
8521 ** Reassign page numbers so that the new pages are in ascending order.
8522 ** This helps to keep entries in the disk file in order so that a scan
8523 ** of the table is closer to a linear scan through the file. That in turn
8524 ** helps the operating system to deliver pages from the disk more rapidly.
8526 ** An O(N*N) sort algorithm is used, but since N is never more than NB+2
8527 ** (5), that is not a performance concern.
8529 ** When NB==3, this one optimization makes the database about 25% faster
8530 ** for large insertions and deletions.
8532 for(i=0; i<nNew; i++){
8533 aPgno[i] = apNew[i]->pgno;
8534 assert( apNew[i]->pDbPage->flags & PGHDR_WRITEABLE );
8535 assert( apNew[i]->pDbPage->flags & PGHDR_DIRTY );
8537 for(i=0; i<nNew-1; i++){
8538 int iB = i;
8539 for(j=i+1; j<nNew; j++){
8540 if( apNew[j]->pgno < apNew[iB]->pgno ) iB = j;
8543 /* If apNew[i] has a page number that is bigger than any of the
8544 ** subsequence apNew[i] entries, then swap apNew[i] with the subsequent
8545 ** entry that has the smallest page number (which we know to be
8546 ** entry apNew[iB]).
8548 if( iB!=i ){
8549 Pgno pgnoA = apNew[i]->pgno;
8550 Pgno pgnoB = apNew[iB]->pgno;
8551 Pgno pgnoTemp = (PENDING_BYTE/pBt->pageSize)+1;
8552 u16 fgA = apNew[i]->pDbPage->flags;
8553 u16 fgB = apNew[iB]->pDbPage->flags;
8554 sqlite3PagerRekey(apNew[i]->pDbPage, pgnoTemp, fgB);
8555 sqlite3PagerRekey(apNew[iB]->pDbPage, pgnoA, fgA);
8556 sqlite3PagerRekey(apNew[i]->pDbPage, pgnoB, fgB);
8557 apNew[i]->pgno = pgnoB;
8558 apNew[iB]->pgno = pgnoA;
8562 TRACE(("BALANCE: new: %u(%u nc=%u) %u(%u nc=%u) %u(%u nc=%u) "
8563 "%u(%u nc=%u) %u(%u nc=%u)\n",
8564 apNew[0]->pgno, szNew[0], cntNew[0],
8565 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
8566 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
8567 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
8568 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
8569 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
8570 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
8571 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
8572 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
8575 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8576 assert( nNew>=1 && nNew<=ArraySize(apNew) );
8577 assert( apNew[nNew-1]!=0 );
8578 put4byte(pRight, apNew[nNew-1]->pgno);
8580 /* If the sibling pages are not leaves, ensure that the right-child pointer
8581 ** of the right-most new sibling page is set to the value that was
8582 ** originally in the same field of the right-most old sibling page. */
8583 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
8584 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
8585 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
8588 /* Make any required updates to pointer map entries associated with
8589 ** cells stored on sibling pages following the balance operation. Pointer
8590 ** map entries associated with divider cells are set by the insertCell()
8591 ** routine. The associated pointer map entries are:
8593 ** a) if the cell contains a reference to an overflow chain, the
8594 ** entry associated with the first page in the overflow chain, and
8596 ** b) if the sibling pages are not leaves, the child page associated
8597 ** with the cell.
8599 ** If the sibling pages are not leaves, then the pointer map entry
8600 ** associated with the right-child of each sibling may also need to be
8601 ** updated. This happens below, after the sibling pages have been
8602 ** populated, not here.
8604 if( ISAUTOVACUUM(pBt) ){
8605 MemPage *pOld;
8606 MemPage *pNew = pOld = apNew[0];
8607 int cntOldNext = pNew->nCell + pNew->nOverflow;
8608 int iNew = 0;
8609 int iOld = 0;
8611 for(i=0; i<b.nCell; i++){
8612 u8 *pCell = b.apCell[i];
8613 while( i==cntOldNext ){
8614 iOld++;
8615 assert( iOld<nNew || iOld<nOld );
8616 assert( iOld>=0 && iOld<NB );
8617 pOld = iOld<nNew ? apNew[iOld] : apOld[iOld];
8618 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
8620 if( i==cntNew[iNew] ){
8621 pNew = apNew[++iNew];
8622 if( !leafData ) continue;
8625 /* Cell pCell is destined for new sibling page pNew. Originally, it
8626 ** was either part of sibling page iOld (possibly an overflow cell),
8627 ** or else the divider cell to the left of sibling page iOld. So,
8628 ** if sibling page iOld had the same page number as pNew, and if
8629 ** pCell really was a part of sibling page iOld (not a divider or
8630 ** overflow cell), we can skip updating the pointer map entries. */
8631 if( iOld>=nNew
8632 || pNew->pgno!=aPgno[iOld]
8633 || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
8635 if( !leafCorrection ){
8636 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
8638 if( cachedCellSize(&b,i)>pNew->minLocal ){
8639 ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);
8641 if( rc ) goto balance_cleanup;
8646 /* Insert new divider cells into pParent. */
8647 for(i=0; i<nNew-1; i++){
8648 u8 *pCell;
8649 u8 *pTemp;
8650 int sz;
8651 u8 *pSrcEnd;
8652 MemPage *pNew = apNew[i];
8653 j = cntNew[i];
8655 assert( j<nMaxCells );
8656 assert( b.apCell[j]!=0 );
8657 pCell = b.apCell[j];
8658 sz = b.szCell[j] + leafCorrection;
8659 pTemp = &aOvflSpace[iOvflSpace];
8660 if( !pNew->leaf ){
8661 memcpy(&pNew->aData[8], pCell, 4);
8662 }else if( leafData ){
8663 /* If the tree is a leaf-data tree, and the siblings are leaves,
8664 ** then there is no divider cell in b.apCell[]. Instead, the divider
8665 ** cell consists of the integer key for the right-most cell of
8666 ** the sibling-page assembled above only.
8668 CellInfo info;
8669 j--;
8670 pNew->xParseCell(pNew, b.apCell[j], &info);
8671 pCell = pTemp;
8672 sz = 4 + putVarint(&pCell[4], info.nKey);
8673 pTemp = 0;
8674 }else{
8675 pCell -= 4;
8676 /* Obscure case for non-leaf-data trees: If the cell at pCell was
8677 ** previously stored on a leaf node, and its reported size was 4
8678 ** bytes, then it may actually be smaller than this
8679 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
8680 ** any cell). But it is important to pass the correct size to
8681 ** insertCell(), so reparse the cell now.
8683 ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
8684 ** and WITHOUT ROWID tables with exactly one column which is the
8685 ** primary key.
8687 if( b.szCell[j]==4 ){
8688 assert(leafCorrection==4);
8689 sz = pParent->xCellSize(pParent, pCell);
8692 iOvflSpace += sz;
8693 assert( sz<=pBt->maxLocal+23 );
8694 assert( iOvflSpace <= (int)pBt->pageSize );
8695 for(k=0; ALWAYS(k<NB*2) && b.ixNx[k]<=j; k++){}
8696 pSrcEnd = b.apEnd[k];
8697 if( SQLITE_OVERFLOW(pSrcEnd, pCell, pCell+sz) ){
8698 rc = SQLITE_CORRUPT_BKPT;
8699 goto balance_cleanup;
8701 rc = insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno);
8702 if( rc!=SQLITE_OK ) goto balance_cleanup;
8703 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8706 /* Now update the actual sibling pages. The order in which they are updated
8707 ** is important, as this code needs to avoid disrupting any page from which
8708 ** cells may still to be read. In practice, this means:
8710 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
8711 ** then it is not safe to update page apNew[iPg] until after
8712 ** the left-hand sibling apNew[iPg-1] has been updated.
8714 ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
8715 ** then it is not safe to update page apNew[iPg] until after
8716 ** the right-hand sibling apNew[iPg+1] has been updated.
8718 ** If neither of the above apply, the page is safe to update.
8720 ** The iPg value in the following loop starts at nNew-1 goes down
8721 ** to 0, then back up to nNew-1 again, thus making two passes over
8722 ** the pages. On the initial downward pass, only condition (1) above
8723 ** needs to be tested because (2) will always be true from the previous
8724 ** step. On the upward pass, both conditions are always true, so the
8725 ** upwards pass simply processes pages that were missed on the downward
8726 ** pass.
8728 for(i=1-nNew; i<nNew; i++){
8729 int iPg = i<0 ? -i : i;
8730 assert( iPg>=0 && iPg<nNew );
8731 assert( iPg>=1 || i>=0 );
8732 assert( iPg<ArraySize(cntOld) );
8733 if( abDone[iPg] ) continue; /* Skip pages already processed */
8734 if( i>=0 /* On the upwards pass, or... */
8735 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
8737 int iNew;
8738 int iOld;
8739 int nNewCell;
8741 /* Verify condition (1): If cells are moving left, update iPg
8742 ** only after iPg-1 has already been updated. */
8743 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
8745 /* Verify condition (2): If cells are moving right, update iPg
8746 ** only after iPg+1 has already been updated. */
8747 assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
8749 if( iPg==0 ){
8750 iNew = iOld = 0;
8751 nNewCell = cntNew[0];
8752 }else{
8753 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
8754 iNew = cntNew[iPg-1] + !leafData;
8755 nNewCell = cntNew[iPg] - iNew;
8758 rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
8759 if( rc ) goto balance_cleanup;
8760 abDone[iPg]++;
8761 apNew[iPg]->nFree = usableSpace-szNew[iPg];
8762 assert( apNew[iPg]->nOverflow==0 );
8763 assert( apNew[iPg]->nCell==nNewCell );
8767 /* All pages have been processed exactly once */
8768 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
8770 assert( nOld>0 );
8771 assert( nNew>0 );
8773 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
8774 /* The root page of the b-tree now contains no cells. The only sibling
8775 ** page is the right-child of the parent. Copy the contents of the
8776 ** child page into the parent, decreasing the overall height of the
8777 ** b-tree structure by one. This is described as the "balance-shallower"
8778 ** sub-algorithm in some documentation.
8780 ** If this is an auto-vacuum database, the call to copyNodeContent()
8781 ** sets all pointer-map entries corresponding to database image pages
8782 ** for which the pointer is stored within the content being copied.
8784 ** It is critical that the child page be defragmented before being
8785 ** copied into the parent, because if the parent is page 1 then it will
8786 ** by smaller than the child due to the database header, and so all the
8787 ** free space needs to be up front.
8789 assert( nNew==1 || CORRUPT_DB );
8790 rc = defragmentPage(apNew[0], -1);
8791 testcase( rc!=SQLITE_OK );
8792 assert( apNew[0]->nFree ==
8793 (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
8794 - apNew[0]->nCell*2)
8795 || rc!=SQLITE_OK
8797 copyNodeContent(apNew[0], pParent, &rc);
8798 freePage(apNew[0], &rc);
8799 }else if( ISAUTOVACUUM(pBt) && !leafCorrection ){
8800 /* Fix the pointer map entries associated with the right-child of each
8801 ** sibling page. All other pointer map entries have already been taken
8802 ** care of. */
8803 for(i=0; i<nNew; i++){
8804 u32 key = get4byte(&apNew[i]->aData[8]);
8805 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
8809 assert( pParent->isInit );
8810 TRACE(("BALANCE: finished: old=%u new=%u cells=%u\n",
8811 nOld, nNew, b.nCell));
8813 /* Free any old pages that were not reused as new pages.
8815 for(i=nNew; i<nOld; i++){
8816 freePage(apOld[i], &rc);
8819 #if 0
8820 if( ISAUTOVACUUM(pBt) && rc==SQLITE_OK && apNew[0]->isInit ){
8821 /* The ptrmapCheckPages() contains assert() statements that verify that
8822 ** all pointer map pages are set correctly. This is helpful while
8823 ** debugging. This is usually disabled because a corrupt database may
8824 ** cause an assert() statement to fail. */
8825 ptrmapCheckPages(apNew, nNew);
8826 ptrmapCheckPages(&pParent, 1);
8828 #endif
8831 ** Cleanup before returning.
8833 balance_cleanup:
8834 sqlite3StackFree(0, b.apCell);
8835 for(i=0; i<nOld; i++){
8836 releasePage(apOld[i]);
8838 for(i=0; i<nNew; i++){
8839 releasePage(apNew[i]);
8842 return rc;
8847 ** This function is called when the root page of a b-tree structure is
8848 ** overfull (has one or more overflow pages).
8850 ** A new child page is allocated and the contents of the current root
8851 ** page, including overflow cells, are copied into the child. The root
8852 ** page is then overwritten to make it an empty page with the right-child
8853 ** pointer pointing to the new page.
8855 ** Before returning, all pointer-map entries corresponding to pages
8856 ** that the new child-page now contains pointers to are updated. The
8857 ** entry corresponding to the new right-child pointer of the root
8858 ** page is also updated.
8860 ** If successful, *ppChild is set to contain a reference to the child
8861 ** page and SQLITE_OK is returned. In this case the caller is required
8862 ** to call releasePage() on *ppChild exactly once. If an error occurs,
8863 ** an error code is returned and *ppChild is set to 0.
8865 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
8866 int rc; /* Return value from subprocedures */
8867 MemPage *pChild = 0; /* Pointer to a new child page */
8868 Pgno pgnoChild = 0; /* Page number of the new child page */
8869 BtShared *pBt = pRoot->pBt; /* The BTree */
8871 assert( pRoot->nOverflow>0 );
8872 assert( sqlite3_mutex_held(pBt->mutex) );
8874 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
8875 ** page that will become the new right-child of pPage. Copy the contents
8876 ** of the node stored on pRoot into the new child page.
8878 rc = sqlite3PagerWrite(pRoot->pDbPage);
8879 if( rc==SQLITE_OK ){
8880 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
8881 copyNodeContent(pRoot, pChild, &rc);
8882 if( ISAUTOVACUUM(pBt) ){
8883 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
8886 if( rc ){
8887 *ppChild = 0;
8888 releasePage(pChild);
8889 return rc;
8891 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
8892 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
8893 assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
8895 TRACE(("BALANCE: copy root %u into %u\n", pRoot->pgno, pChild->pgno));
8897 /* Copy the overflow cells from pRoot to pChild */
8898 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
8899 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
8900 memcpy(pChild->apOvfl, pRoot->apOvfl,
8901 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
8902 pChild->nOverflow = pRoot->nOverflow;
8904 /* Zero the contents of pRoot. Then install pChild as the right-child. */
8905 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
8906 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
8908 *ppChild = pChild;
8909 return SQLITE_OK;
8913 ** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid
8914 ** on the same B-tree as pCur.
8916 ** This can occur if a database is corrupt with two or more SQL tables
8917 ** pointing to the same b-tree. If an insert occurs on one SQL table
8918 ** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL
8919 ** table linked to the same b-tree. If the secondary insert causes a
8920 ** rebalance, that can change content out from under the cursor on the
8921 ** first SQL table, violating invariants on the first insert.
8923 static int anotherValidCursor(BtCursor *pCur){
8924 BtCursor *pOther;
8925 for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){
8926 if( pOther!=pCur
8927 && pOther->eState==CURSOR_VALID
8928 && pOther->pPage==pCur->pPage
8930 return SQLITE_CORRUPT_BKPT;
8933 return SQLITE_OK;
8937 ** The page that pCur currently points to has just been modified in
8938 ** some way. This function figures out if this modification means the
8939 ** tree needs to be balanced, and if so calls the appropriate balancing
8940 ** routine. Balancing routines are:
8942 ** balance_quick()
8943 ** balance_deeper()
8944 ** balance_nonroot()
8946 static int balance(BtCursor *pCur){
8947 int rc = SQLITE_OK;
8948 u8 aBalanceQuickSpace[13];
8949 u8 *pFree = 0;
8951 VVA_ONLY( int balance_quick_called = 0 );
8952 VVA_ONLY( int balance_deeper_called = 0 );
8954 do {
8955 int iPage;
8956 MemPage *pPage = pCur->pPage;
8958 if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
8959 if( pPage->nOverflow==0 && pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){
8960 /* No rebalance required as long as:
8961 ** (1) There are no overflow cells
8962 ** (2) The amount of free space on the page is less than 2/3rds of
8963 ** the total usable space on the page. */
8964 break;
8965 }else if( (iPage = pCur->iPage)==0 ){
8966 if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){
8967 /* The root page of the b-tree is overfull. In this case call the
8968 ** balance_deeper() function to create a new child for the root-page
8969 ** and copy the current contents of the root-page to it. The
8970 ** next iteration of the do-loop will balance the child page.
8972 assert( balance_deeper_called==0 );
8973 VVA_ONLY( balance_deeper_called++ );
8974 rc = balance_deeper(pPage, &pCur->apPage[1]);
8975 if( rc==SQLITE_OK ){
8976 pCur->iPage = 1;
8977 pCur->ix = 0;
8978 pCur->aiIdx[0] = 0;
8979 pCur->apPage[0] = pPage;
8980 pCur->pPage = pCur->apPage[1];
8981 assert( pCur->pPage->nOverflow );
8983 }else{
8984 break;
8986 }else if( sqlite3PagerPageRefcount(pPage->pDbPage)>1 ){
8987 /* The page being written is not a root page, and there is currently
8988 ** more than one reference to it. This only happens if the page is one
8989 ** of its own ancestor pages. Corruption. */
8990 rc = SQLITE_CORRUPT_BKPT;
8991 }else{
8992 MemPage * const pParent = pCur->apPage[iPage-1];
8993 int const iIdx = pCur->aiIdx[iPage-1];
8995 rc = sqlite3PagerWrite(pParent->pDbPage);
8996 if( rc==SQLITE_OK && pParent->nFree<0 ){
8997 rc = btreeComputeFreeSpace(pParent);
8999 if( rc==SQLITE_OK ){
9000 #ifndef SQLITE_OMIT_QUICKBALANCE
9001 if( pPage->intKeyLeaf
9002 && pPage->nOverflow==1
9003 && pPage->aiOvfl[0]==pPage->nCell
9004 && pParent->pgno!=1
9005 && pParent->nCell==iIdx
9007 /* Call balance_quick() to create a new sibling of pPage on which
9008 ** to store the overflow cell. balance_quick() inserts a new cell
9009 ** into pParent, which may cause pParent overflow. If this
9010 ** happens, the next iteration of the do-loop will balance pParent
9011 ** use either balance_nonroot() or balance_deeper(). Until this
9012 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
9013 ** buffer.
9015 ** The purpose of the following assert() is to check that only a
9016 ** single call to balance_quick() is made for each call to this
9017 ** function. If this were not verified, a subtle bug involving reuse
9018 ** of the aBalanceQuickSpace[] might sneak in.
9020 assert( balance_quick_called==0 );
9021 VVA_ONLY( balance_quick_called++ );
9022 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
9023 }else
9024 #endif
9026 /* In this case, call balance_nonroot() to redistribute cells
9027 ** between pPage and up to 2 of its sibling pages. This involves
9028 ** modifying the contents of pParent, which may cause pParent to
9029 ** become overfull or underfull. The next iteration of the do-loop
9030 ** will balance the parent page to correct this.
9032 ** If the parent page becomes overfull, the overflow cell or cells
9033 ** are stored in the pSpace buffer allocated immediately below.
9034 ** A subsequent iteration of the do-loop will deal with this by
9035 ** calling balance_nonroot() (balance_deeper() may be called first,
9036 ** but it doesn't deal with overflow cells - just moves them to a
9037 ** different page). Once this subsequent call to balance_nonroot()
9038 ** has completed, it is safe to release the pSpace buffer used by
9039 ** the previous call, as the overflow cell data will have been
9040 ** copied either into the body of a database page or into the new
9041 ** pSpace buffer passed to the latter call to balance_nonroot().
9043 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
9044 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
9045 pCur->hints&BTREE_BULKLOAD);
9046 if( pFree ){
9047 /* If pFree is not NULL, it points to the pSpace buffer used
9048 ** by a previous call to balance_nonroot(). Its contents are
9049 ** now stored either on real database pages or within the
9050 ** new pSpace buffer, so it may be safely freed here. */
9051 sqlite3PageFree(pFree);
9054 /* The pSpace buffer will be freed after the next call to
9055 ** balance_nonroot(), or just before this function returns, whichever
9056 ** comes first. */
9057 pFree = pSpace;
9061 pPage->nOverflow = 0;
9063 /* The next iteration of the do-loop balances the parent page. */
9064 releasePage(pPage);
9065 pCur->iPage--;
9066 assert( pCur->iPage>=0 );
9067 pCur->pPage = pCur->apPage[pCur->iPage];
9069 }while( rc==SQLITE_OK );
9071 if( pFree ){
9072 sqlite3PageFree(pFree);
9074 return rc;
9077 /* Overwrite content from pX into pDest. Only do the write if the
9078 ** content is different from what is already there.
9080 static int btreeOverwriteContent(
9081 MemPage *pPage, /* MemPage on which writing will occur */
9082 u8 *pDest, /* Pointer to the place to start writing */
9083 const BtreePayload *pX, /* Source of data to write */
9084 int iOffset, /* Offset of first byte to write */
9085 int iAmt /* Number of bytes to be written */
9087 int nData = pX->nData - iOffset;
9088 if( nData<=0 ){
9089 /* Overwriting with zeros */
9090 int i;
9091 for(i=0; i<iAmt && pDest[i]==0; i++){}
9092 if( i<iAmt ){
9093 int rc = sqlite3PagerWrite(pPage->pDbPage);
9094 if( rc ) return rc;
9095 memset(pDest + i, 0, iAmt - i);
9097 }else{
9098 if( nData<iAmt ){
9099 /* Mixed read data and zeros at the end. Make a recursive call
9100 ** to write the zeros then fall through to write the real data */
9101 int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
9102 iAmt-nData);
9103 if( rc ) return rc;
9104 iAmt = nData;
9106 if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
9107 int rc = sqlite3PagerWrite(pPage->pDbPage);
9108 if( rc ) return rc;
9109 /* In a corrupt database, it is possible for the source and destination
9110 ** buffers to overlap. This is harmless since the database is already
9111 ** corrupt but it does cause valgrind and ASAN warnings. So use
9112 ** memmove(). */
9113 memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
9116 return SQLITE_OK;
9120 ** Overwrite the cell that cursor pCur is pointing to with fresh content
9121 ** contained in pX. In this variant, pCur is pointing to an overflow
9122 ** cell.
9124 static SQLITE_NOINLINE int btreeOverwriteOverflowCell(
9125 BtCursor *pCur, /* Cursor pointing to cell to overwrite */
9126 const BtreePayload *pX /* Content to write into the cell */
9128 int iOffset; /* Next byte of pX->pData to write */
9129 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
9130 int rc; /* Return code */
9131 MemPage *pPage = pCur->pPage; /* Page being written */
9132 BtShared *pBt; /* Btree */
9133 Pgno ovflPgno; /* Next overflow page to write */
9134 u32 ovflPageSize; /* Size to write on overflow page */
9136 assert( pCur->info.nLocal<nTotal ); /* pCur is an overflow cell */
9138 /* Overwrite the local portion first */
9139 rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
9140 0, pCur->info.nLocal);
9141 if( rc ) return rc;
9143 /* Now overwrite the overflow pages */
9144 iOffset = pCur->info.nLocal;
9145 assert( nTotal>=0 );
9146 assert( iOffset>=0 );
9147 ovflPgno = get4byte(pCur->info.pPayload + iOffset);
9148 pBt = pPage->pBt;
9149 ovflPageSize = pBt->usableSize - 4;
9151 rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
9152 if( rc ) return rc;
9153 if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 || pPage->isInit ){
9154 rc = SQLITE_CORRUPT_BKPT;
9155 }else{
9156 if( iOffset+ovflPageSize<(u32)nTotal ){
9157 ovflPgno = get4byte(pPage->aData);
9158 }else{
9159 ovflPageSize = nTotal - iOffset;
9161 rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
9162 iOffset, ovflPageSize);
9164 sqlite3PagerUnref(pPage->pDbPage);
9165 if( rc ) return rc;
9166 iOffset += ovflPageSize;
9167 }while( iOffset<nTotal );
9168 return SQLITE_OK;
9172 ** Overwrite the cell that cursor pCur is pointing to with fresh content
9173 ** contained in pX.
9175 static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
9176 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
9177 MemPage *pPage = pCur->pPage; /* Page being written */
9179 if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd
9180 || pCur->info.pPayload < pPage->aData + pPage->cellOffset
9182 return SQLITE_CORRUPT_BKPT;
9184 if( pCur->info.nLocal==nTotal ){
9185 /* The entire cell is local */
9186 return btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
9187 0, pCur->info.nLocal);
9188 }else{
9189 /* The cell contains overflow content */
9190 return btreeOverwriteOverflowCell(pCur, pX);
9196 ** Insert a new record into the BTree. The content of the new record
9197 ** is described by the pX object. The pCur cursor is used only to
9198 ** define what table the record should be inserted into, and is left
9199 ** pointing at a random location.
9201 ** For a table btree (used for rowid tables), only the pX.nKey value of
9202 ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
9203 ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
9204 ** hold the content of the row.
9206 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
9207 ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
9208 ** pX.pData,nData,nZero fields must be zero.
9210 ** If the seekResult parameter is non-zero, then a successful call to
9211 ** sqlite3BtreeIndexMoveto() to seek cursor pCur to (pKey,nKey) has already
9212 ** been performed. In other words, if seekResult!=0 then the cursor
9213 ** is currently pointing to a cell that will be adjacent to the cell
9214 ** to be inserted. If seekResult<0 then pCur points to a cell that is
9215 ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
9216 ** that is larger than (pKey,nKey).
9218 ** If seekResult==0, that means pCur is pointing at some unknown location.
9219 ** In that case, this routine must seek the cursor to the correct insertion
9220 ** point for (pKey,nKey) before doing the insertion. For index btrees,
9221 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
9222 ** key values and pX->aMem can be used instead of pX->pKey to avoid having
9223 ** to decode the key.
9225 int sqlite3BtreeInsert(
9226 BtCursor *pCur, /* Insert data into the table of this cursor */
9227 const BtreePayload *pX, /* Content of the row to be inserted */
9228 int flags, /* True if this is likely an append */
9229 int seekResult /* Result of prior IndexMoveto() call */
9231 int rc;
9232 int loc = seekResult; /* -1: before desired location +1: after */
9233 int szNew = 0;
9234 int idx;
9235 MemPage *pPage;
9236 Btree *p = pCur->pBtree;
9237 unsigned char *oldCell;
9238 unsigned char *newCell = 0;
9240 assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND|BTREE_PREFORMAT))==flags );
9241 assert( (flags & BTREE_PREFORMAT)==0 || seekResult || pCur->pKeyInfo==0 );
9243 /* Save the positions of any other cursors open on this table.
9245 ** In some cases, the call to btreeMoveto() below is a no-op. For
9246 ** example, when inserting data into a table with auto-generated integer
9247 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
9248 ** integer key to use. It then calls this function to actually insert the
9249 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
9250 ** that the cursor is already where it needs to be and returns without
9251 ** doing any work. To avoid thwarting these optimizations, it is important
9252 ** not to clear the cursor here.
9254 if( pCur->curFlags & BTCF_Multiple ){
9255 rc = saveAllCursors(p->pBt, pCur->pgnoRoot, pCur);
9256 if( rc ) return rc;
9257 if( loc && pCur->iPage<0 ){
9258 /* This can only happen if the schema is corrupt such that there is more
9259 ** than one table or index with the same root page as used by the cursor.
9260 ** Which can only happen if the SQLITE_NoSchemaError flag was set when
9261 ** the schema was loaded. This cannot be asserted though, as a user might
9262 ** set the flag, load the schema, and then unset the flag. */
9263 return SQLITE_CORRUPT_BKPT;
9267 /* Ensure that the cursor is not in the CURSOR_FAULT state and that it
9268 ** points to a valid cell.
9270 if( pCur->eState>=CURSOR_REQUIRESEEK ){
9271 testcase( pCur->eState==CURSOR_REQUIRESEEK );
9272 testcase( pCur->eState==CURSOR_FAULT );
9273 rc = moveToRoot(pCur);
9274 if( rc && rc!=SQLITE_EMPTY ) return rc;
9277 assert( cursorOwnsBtShared(pCur) );
9278 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
9279 && p->pBt->inTransaction==TRANS_WRITE
9280 && (p->pBt->btsFlags & BTS_READ_ONLY)==0 );
9281 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
9283 /* Assert that the caller has been consistent. If this cursor was opened
9284 ** expecting an index b-tree, then the caller should be inserting blob
9285 ** keys with no associated data. If the cursor was opened expecting an
9286 ** intkey table, the caller should be inserting integer keys with a
9287 ** blob of associated data. */
9288 assert( (flags & BTREE_PREFORMAT) || (pX->pKey==0)==(pCur->pKeyInfo==0) );
9290 if( pCur->pKeyInfo==0 ){
9291 assert( pX->pKey==0 );
9292 /* If this is an insert into a table b-tree, invalidate any incrblob
9293 ** cursors open on the row being replaced */
9294 if( p->hasIncrblobCur ){
9295 invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
9298 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
9299 ** to a row with the same key as the new entry being inserted.
9301 #ifdef SQLITE_DEBUG
9302 if( flags & BTREE_SAVEPOSITION ){
9303 assert( pCur->curFlags & BTCF_ValidNKey );
9304 assert( pX->nKey==pCur->info.nKey );
9305 assert( loc==0 );
9307 #endif
9309 /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
9310 ** that the cursor is not pointing to a row to be overwritten.
9311 ** So do a complete check.
9313 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
9314 /* The cursor is pointing to the entry that is to be
9315 ** overwritten */
9316 assert( pX->nData>=0 && pX->nZero>=0 );
9317 if( pCur->info.nSize!=0
9318 && pCur->info.nPayload==(u32)pX->nData+pX->nZero
9320 /* New entry is the same size as the old. Do an overwrite */
9321 return btreeOverwriteCell(pCur, pX);
9323 assert( loc==0 );
9324 }else if( loc==0 ){
9325 /* The cursor is *not* pointing to the cell to be overwritten, nor
9326 ** to an adjacent cell. Move the cursor so that it is pointing either
9327 ** to the cell to be overwritten or an adjacent cell.
9329 rc = sqlite3BtreeTableMoveto(pCur, pX->nKey,
9330 (flags & BTREE_APPEND)!=0, &loc);
9331 if( rc ) return rc;
9333 }else{
9334 /* This is an index or a WITHOUT ROWID table */
9336 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
9337 ** to a row with the same key as the new entry being inserted.
9339 assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
9341 /* If the cursor is not already pointing either to the cell to be
9342 ** overwritten, or if a new cell is being inserted, if the cursor is
9343 ** not pointing to an immediately adjacent cell, then move the cursor
9344 ** so that it does.
9346 if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
9347 if( pX->nMem ){
9348 UnpackedRecord r;
9349 r.pKeyInfo = pCur->pKeyInfo;
9350 r.aMem = pX->aMem;
9351 r.nField = pX->nMem;
9352 r.default_rc = 0;
9353 r.eqSeen = 0;
9354 rc = sqlite3BtreeIndexMoveto(pCur, &r, &loc);
9355 }else{
9356 rc = btreeMoveto(pCur, pX->pKey, pX->nKey,
9357 (flags & BTREE_APPEND)!=0, &loc);
9359 if( rc ) return rc;
9362 /* If the cursor is currently pointing to an entry to be overwritten
9363 ** and the new content is the same as as the old, then use the
9364 ** overwrite optimization.
9366 if( loc==0 ){
9367 getCellInfo(pCur);
9368 if( pCur->info.nKey==pX->nKey ){
9369 BtreePayload x2;
9370 x2.pData = pX->pKey;
9371 x2.nData = pX->nKey;
9372 x2.nZero = 0;
9373 return btreeOverwriteCell(pCur, &x2);
9377 assert( pCur->eState==CURSOR_VALID
9378 || (pCur->eState==CURSOR_INVALID && loc) || CORRUPT_DB );
9380 pPage = pCur->pPage;
9381 assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) );
9382 assert( pPage->leaf || !pPage->intKey );
9383 if( pPage->nFree<0 ){
9384 if( NEVER(pCur->eState>CURSOR_INVALID) ){
9385 /* ^^^^^--- due to the moveToRoot() call above */
9386 rc = SQLITE_CORRUPT_BKPT;
9387 }else{
9388 rc = btreeComputeFreeSpace(pPage);
9390 if( rc ) return rc;
9393 TRACE(("INSERT: table=%u nkey=%lld ndata=%u page=%u %s\n",
9394 pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
9395 loc==0 ? "overwrite" : "new entry"));
9396 assert( pPage->isInit || CORRUPT_DB );
9397 newCell = p->pBt->pTmpSpace;
9398 assert( newCell!=0 );
9399 assert( BTREE_PREFORMAT==OPFLAG_PREFORMAT );
9400 if( flags & BTREE_PREFORMAT ){
9401 rc = SQLITE_OK;
9402 szNew = p->pBt->nPreformatSize;
9403 if( szNew<4 ) szNew = 4;
9404 if( ISAUTOVACUUM(p->pBt) && szNew>pPage->maxLocal ){
9405 CellInfo info;
9406 pPage->xParseCell(pPage, newCell, &info);
9407 if( info.nPayload!=info.nLocal ){
9408 Pgno ovfl = get4byte(&newCell[szNew-4]);
9409 ptrmapPut(p->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, &rc);
9410 if( NEVER(rc) ) goto end_insert;
9413 }else{
9414 rc = fillInCell(pPage, newCell, pX, &szNew);
9415 if( rc ) goto end_insert;
9417 assert( szNew==pPage->xCellSize(pPage, newCell) );
9418 assert( szNew <= MX_CELL_SIZE(p->pBt) );
9419 idx = pCur->ix;
9420 pCur->info.nSize = 0;
9421 if( loc==0 ){
9422 CellInfo info;
9423 assert( idx>=0 );
9424 if( idx>=pPage->nCell ){
9425 return SQLITE_CORRUPT_BKPT;
9427 rc = sqlite3PagerWrite(pPage->pDbPage);
9428 if( rc ){
9429 goto end_insert;
9431 oldCell = findCell(pPage, idx);
9432 if( !pPage->leaf ){
9433 memcpy(newCell, oldCell, 4);
9435 BTREE_CLEAR_CELL(rc, pPage, oldCell, info);
9436 testcase( pCur->curFlags & BTCF_ValidOvfl );
9437 invalidateOverflowCache(pCur);
9438 if( info.nSize==szNew && info.nLocal==info.nPayload
9439 && (!ISAUTOVACUUM(p->pBt) || szNew<pPage->minLocal)
9441 /* Overwrite the old cell with the new if they are the same size.
9442 ** We could also try to do this if the old cell is smaller, then add
9443 ** the leftover space to the free list. But experiments show that
9444 ** doing that is no faster then skipping this optimization and just
9445 ** calling dropCell() and insertCell().
9447 ** This optimization cannot be used on an autovacuum database if the
9448 ** new entry uses overflow pages, as the insertCell() call below is
9449 ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
9450 assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
9451 if( oldCell < pPage->aData+pPage->hdrOffset+10 ){
9452 return SQLITE_CORRUPT_BKPT;
9454 if( oldCell+szNew > pPage->aDataEnd ){
9455 return SQLITE_CORRUPT_BKPT;
9457 memcpy(oldCell, newCell, szNew);
9458 return SQLITE_OK;
9460 dropCell(pPage, idx, info.nSize, &rc);
9461 if( rc ) goto end_insert;
9462 }else if( loc<0 && pPage->nCell>0 ){
9463 assert( pPage->leaf );
9464 idx = ++pCur->ix;
9465 pCur->curFlags &= ~BTCF_ValidNKey;
9466 }else{
9467 assert( pPage->leaf );
9469 rc = insertCellFast(pPage, idx, newCell, szNew);
9470 assert( pPage->nOverflow==0 || rc==SQLITE_OK );
9471 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
9473 /* If no error has occurred and pPage has an overflow cell, call balance()
9474 ** to redistribute the cells within the tree. Since balance() may move
9475 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
9476 ** variables.
9478 ** Previous versions of SQLite called moveToRoot() to move the cursor
9479 ** back to the root page as balance() used to invalidate the contents
9480 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
9481 ** set the cursor state to "invalid". This makes common insert operations
9482 ** slightly faster.
9484 ** There is a subtle but important optimization here too. When inserting
9485 ** multiple records into an intkey b-tree using a single cursor (as can
9486 ** happen while processing an "INSERT INTO ... SELECT" statement), it
9487 ** is advantageous to leave the cursor pointing to the last entry in
9488 ** the b-tree if possible. If the cursor is left pointing to the last
9489 ** entry in the table, and the next row inserted has an integer key
9490 ** larger than the largest existing key, it is possible to insert the
9491 ** row without seeking the cursor. This can be a big performance boost.
9493 if( pPage->nOverflow ){
9494 assert( rc==SQLITE_OK );
9495 pCur->curFlags &= ~(BTCF_ValidNKey);
9496 rc = balance(pCur);
9498 /* Must make sure nOverflow is reset to zero even if the balance()
9499 ** fails. Internal data structure corruption will result otherwise.
9500 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
9501 ** from trying to save the current position of the cursor. */
9502 pCur->pPage->nOverflow = 0;
9503 pCur->eState = CURSOR_INVALID;
9504 if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
9505 btreeReleaseAllCursorPages(pCur);
9506 if( pCur->pKeyInfo ){
9507 assert( pCur->pKey==0 );
9508 pCur->pKey = sqlite3Malloc( pX->nKey );
9509 if( pCur->pKey==0 ){
9510 rc = SQLITE_NOMEM;
9511 }else{
9512 memcpy(pCur->pKey, pX->pKey, pX->nKey);
9515 pCur->eState = CURSOR_REQUIRESEEK;
9516 pCur->nKey = pX->nKey;
9519 assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
9521 end_insert:
9522 return rc;
9526 ** This function is used as part of copying the current row from cursor
9527 ** pSrc into cursor pDest. If the cursors are open on intkey tables, then
9528 ** parameter iKey is used as the rowid value when the record is copied
9529 ** into pDest. Otherwise, the record is copied verbatim.
9531 ** This function does not actually write the new value to cursor pDest.
9532 ** Instead, it creates and populates any required overflow pages and
9533 ** writes the data for the new cell into the BtShared.pTmpSpace buffer
9534 ** for the destination database. The size of the cell, in bytes, is left
9535 ** in BtShared.nPreformatSize. The caller completes the insertion by
9536 ** calling sqlite3BtreeInsert() with the BTREE_PREFORMAT flag specified.
9538 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
9540 int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 iKey){
9541 BtShared *pBt = pDest->pBt;
9542 u8 *aOut = pBt->pTmpSpace; /* Pointer to next output buffer */
9543 const u8 *aIn; /* Pointer to next input buffer */
9544 u32 nIn; /* Size of input buffer aIn[] */
9545 u32 nRem; /* Bytes of data still to copy */
9547 getCellInfo(pSrc);
9548 if( pSrc->info.nPayload<0x80 ){
9549 *(aOut++) = pSrc->info.nPayload;
9550 }else{
9551 aOut += sqlite3PutVarint(aOut, pSrc->info.nPayload);
9553 if( pDest->pKeyInfo==0 ) aOut += putVarint(aOut, iKey);
9554 nIn = pSrc->info.nLocal;
9555 aIn = pSrc->info.pPayload;
9556 if( aIn+nIn>pSrc->pPage->aDataEnd ){
9557 return SQLITE_CORRUPT_BKPT;
9559 nRem = pSrc->info.nPayload;
9560 if( nIn==nRem && nIn<pDest->pPage->maxLocal ){
9561 memcpy(aOut, aIn, nIn);
9562 pBt->nPreformatSize = nIn + (aOut - pBt->pTmpSpace);
9563 return SQLITE_OK;
9564 }else{
9565 int rc = SQLITE_OK;
9566 Pager *pSrcPager = pSrc->pBt->pPager;
9567 u8 *pPgnoOut = 0;
9568 Pgno ovflIn = 0;
9569 DbPage *pPageIn = 0;
9570 MemPage *pPageOut = 0;
9571 u32 nOut; /* Size of output buffer aOut[] */
9573 nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload);
9574 pBt->nPreformatSize = nOut + (aOut - pBt->pTmpSpace);
9575 if( nOut<pSrc->info.nPayload ){
9576 pPgnoOut = &aOut[nOut];
9577 pBt->nPreformatSize += 4;
9580 if( nRem>nIn ){
9581 if( aIn+nIn+4>pSrc->pPage->aDataEnd ){
9582 return SQLITE_CORRUPT_BKPT;
9584 ovflIn = get4byte(&pSrc->info.pPayload[nIn]);
9587 do {
9588 nRem -= nOut;
9590 assert( nOut>0 );
9591 if( nIn>0 ){
9592 int nCopy = MIN(nOut, nIn);
9593 memcpy(aOut, aIn, nCopy);
9594 nOut -= nCopy;
9595 nIn -= nCopy;
9596 aOut += nCopy;
9597 aIn += nCopy;
9599 if( nOut>0 ){
9600 sqlite3PagerUnref(pPageIn);
9601 pPageIn = 0;
9602 rc = sqlite3PagerGet(pSrcPager, ovflIn, &pPageIn, PAGER_GET_READONLY);
9603 if( rc==SQLITE_OK ){
9604 aIn = (const u8*)sqlite3PagerGetData(pPageIn);
9605 ovflIn = get4byte(aIn);
9606 aIn += 4;
9607 nIn = pSrc->pBt->usableSize - 4;
9610 }while( rc==SQLITE_OK && nOut>0 );
9612 if( rc==SQLITE_OK && nRem>0 && ALWAYS(pPgnoOut) ){
9613 Pgno pgnoNew;
9614 MemPage *pNew = 0;
9615 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
9616 put4byte(pPgnoOut, pgnoNew);
9617 if( ISAUTOVACUUM(pBt) && pPageOut ){
9618 ptrmapPut(pBt, pgnoNew, PTRMAP_OVERFLOW2, pPageOut->pgno, &rc);
9620 releasePage(pPageOut);
9621 pPageOut = pNew;
9622 if( pPageOut ){
9623 pPgnoOut = pPageOut->aData;
9624 put4byte(pPgnoOut, 0);
9625 aOut = &pPgnoOut[4];
9626 nOut = MIN(pBt->usableSize - 4, nRem);
9629 }while( nRem>0 && rc==SQLITE_OK );
9631 releasePage(pPageOut);
9632 sqlite3PagerUnref(pPageIn);
9633 return rc;
9638 ** Delete the entry that the cursor is pointing to.
9640 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
9641 ** the cursor is left pointing at an arbitrary location after the delete.
9642 ** But if that bit is set, then the cursor is left in a state such that
9643 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
9644 ** as it would have been on if the call to BtreeDelete() had been omitted.
9646 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
9647 ** associated with a single table entry and its indexes. Only one of those
9648 ** deletes is considered the "primary" delete. The primary delete occurs
9649 ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
9650 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
9651 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
9652 ** but which might be used by alternative storage engines.
9654 int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
9655 Btree *p = pCur->pBtree;
9656 BtShared *pBt = p->pBt;
9657 int rc; /* Return code */
9658 MemPage *pPage; /* Page to delete cell from */
9659 unsigned char *pCell; /* Pointer to cell to delete */
9660 int iCellIdx; /* Index of cell to delete */
9661 int iCellDepth; /* Depth of node containing pCell */
9662 CellInfo info; /* Size of the cell being deleted */
9663 u8 bPreserve; /* Keep cursor valid. 2 for CURSOR_SKIPNEXT */
9665 assert( cursorOwnsBtShared(pCur) );
9666 assert( pBt->inTransaction==TRANS_WRITE );
9667 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9668 assert( pCur->curFlags & BTCF_WriteFlag );
9669 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
9670 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
9671 assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
9672 if( pCur->eState!=CURSOR_VALID ){
9673 if( pCur->eState>=CURSOR_REQUIRESEEK ){
9674 rc = btreeRestoreCursorPosition(pCur);
9675 assert( rc!=SQLITE_OK || CORRUPT_DB || pCur->eState==CURSOR_VALID );
9676 if( rc || pCur->eState!=CURSOR_VALID ) return rc;
9677 }else{
9678 return SQLITE_CORRUPT_BKPT;
9681 assert( pCur->eState==CURSOR_VALID );
9683 iCellDepth = pCur->iPage;
9684 iCellIdx = pCur->ix;
9685 pPage = pCur->pPage;
9686 if( pPage->nCell<=iCellIdx ){
9687 return SQLITE_CORRUPT_BKPT;
9689 pCell = findCell(pPage, iCellIdx);
9690 if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ){
9691 return SQLITE_CORRUPT_BKPT;
9693 if( pCell<&pPage->aCellIdx[pPage->nCell] ){
9694 return SQLITE_CORRUPT_BKPT;
9697 /* If the BTREE_SAVEPOSITION bit is on, then the cursor position must
9698 ** be preserved following this delete operation. If the current delete
9699 ** will cause a b-tree rebalance, then this is done by saving the cursor
9700 ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
9701 ** returning.
9703 ** If the current delete will not cause a rebalance, then the cursor
9704 ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
9705 ** before or after the deleted entry.
9707 ** The bPreserve value records which path is required:
9709 ** bPreserve==0 Not necessary to save the cursor position
9710 ** bPreserve==1 Use CURSOR_REQUIRESEEK to save the cursor position
9711 ** bPreserve==2 Cursor won't move. Set CURSOR_SKIPNEXT.
9713 bPreserve = (flags & BTREE_SAVEPOSITION)!=0;
9714 if( bPreserve ){
9715 if( !pPage->leaf
9716 || (pPage->nFree+pPage->xCellSize(pPage,pCell)+2) >
9717 (int)(pBt->usableSize*2/3)
9718 || pPage->nCell==1 /* See dbfuzz001.test for a test case */
9720 /* A b-tree rebalance will be required after deleting this entry.
9721 ** Save the cursor key. */
9722 rc = saveCursorKey(pCur);
9723 if( rc ) return rc;
9724 }else{
9725 bPreserve = 2;
9729 /* If the page containing the entry to delete is not a leaf page, move
9730 ** the cursor to the largest entry in the tree that is smaller than
9731 ** the entry being deleted. This cell will replace the cell being deleted
9732 ** from the internal node. The 'previous' entry is used for this instead
9733 ** of the 'next' entry, as the previous entry is always a part of the
9734 ** sub-tree headed by the child page of the cell being deleted. This makes
9735 ** balancing the tree following the delete operation easier. */
9736 if( !pPage->leaf ){
9737 rc = sqlite3BtreePrevious(pCur, 0);
9738 assert( rc!=SQLITE_DONE );
9739 if( rc ) return rc;
9742 /* Save the positions of any other cursors open on this table before
9743 ** making any modifications. */
9744 if( pCur->curFlags & BTCF_Multiple ){
9745 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
9746 if( rc ) return rc;
9749 /* If this is a delete operation to remove a row from a table b-tree,
9750 ** invalidate any incrblob cursors open on the row being deleted. */
9751 if( pCur->pKeyInfo==0 && p->hasIncrblobCur ){
9752 invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
9755 /* Make the page containing the entry to be deleted writable. Then free any
9756 ** overflow pages associated with the entry and finally remove the cell
9757 ** itself from within the page. */
9758 rc = sqlite3PagerWrite(pPage->pDbPage);
9759 if( rc ) return rc;
9760 BTREE_CLEAR_CELL(rc, pPage, pCell, info);
9761 dropCell(pPage, iCellIdx, info.nSize, &rc);
9762 if( rc ) return rc;
9764 /* If the cell deleted was not located on a leaf page, then the cursor
9765 ** is currently pointing to the largest entry in the sub-tree headed
9766 ** by the child-page of the cell that was just deleted from an internal
9767 ** node. The cell from the leaf node needs to be moved to the internal
9768 ** node to replace the deleted cell. */
9769 if( !pPage->leaf ){
9770 MemPage *pLeaf = pCur->pPage;
9771 int nCell;
9772 Pgno n;
9773 unsigned char *pTmp;
9775 if( pLeaf->nFree<0 ){
9776 rc = btreeComputeFreeSpace(pLeaf);
9777 if( rc ) return rc;
9779 if( iCellDepth<pCur->iPage-1 ){
9780 n = pCur->apPage[iCellDepth+1]->pgno;
9781 }else{
9782 n = pCur->pPage->pgno;
9784 pCell = findCell(pLeaf, pLeaf->nCell-1);
9785 if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
9786 nCell = pLeaf->xCellSize(pLeaf, pCell);
9787 assert( MX_CELL_SIZE(pBt) >= nCell );
9788 pTmp = pBt->pTmpSpace;
9789 assert( pTmp!=0 );
9790 rc = sqlite3PagerWrite(pLeaf->pDbPage);
9791 if( rc==SQLITE_OK ){
9792 rc = insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n);
9794 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
9795 if( rc ) return rc;
9798 /* Balance the tree. If the entry deleted was located on a leaf page,
9799 ** then the cursor still points to that page. In this case the first
9800 ** call to balance() repairs the tree, and the if(...) condition is
9801 ** never true.
9803 ** Otherwise, if the entry deleted was on an internal node page, then
9804 ** pCur is pointing to the leaf page from which a cell was removed to
9805 ** replace the cell deleted from the internal node. This is slightly
9806 ** tricky as the leaf node may be underfull, and the internal node may
9807 ** be either under or overfull. In this case run the balancing algorithm
9808 ** on the leaf node first. If the balance proceeds far enough up the
9809 ** tree that we can be sure that any problem in the internal node has
9810 ** been corrected, so be it. Otherwise, after balancing the leaf node,
9811 ** walk the cursor up the tree to the internal node and balance it as
9812 ** well. */
9813 assert( pCur->pPage->nOverflow==0 );
9814 assert( pCur->pPage->nFree>=0 );
9815 if( pCur->pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){
9816 /* Optimization: If the free space is less than 2/3rds of the page,
9817 ** then balance() will always be a no-op. No need to invoke it. */
9818 rc = SQLITE_OK;
9819 }else{
9820 rc = balance(pCur);
9822 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
9823 releasePageNotNull(pCur->pPage);
9824 pCur->iPage--;
9825 while( pCur->iPage>iCellDepth ){
9826 releasePage(pCur->apPage[pCur->iPage--]);
9828 pCur->pPage = pCur->apPage[pCur->iPage];
9829 rc = balance(pCur);
9832 if( rc==SQLITE_OK ){
9833 if( bPreserve>1 ){
9834 assert( (pCur->iPage==iCellDepth || CORRUPT_DB) );
9835 assert( pPage==pCur->pPage || CORRUPT_DB );
9836 assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
9837 pCur->eState = CURSOR_SKIPNEXT;
9838 if( iCellIdx>=pPage->nCell ){
9839 pCur->skipNext = -1;
9840 pCur->ix = pPage->nCell-1;
9841 }else{
9842 pCur->skipNext = 1;
9844 }else{
9845 rc = moveToRoot(pCur);
9846 if( bPreserve ){
9847 btreeReleaseAllCursorPages(pCur);
9848 pCur->eState = CURSOR_REQUIRESEEK;
9850 if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
9853 return rc;
9857 ** Create a new BTree table. Write into *piTable the page
9858 ** number for the root page of the new table.
9860 ** The type of type is determined by the flags parameter. Only the
9861 ** following values of flags are currently in use. Other values for
9862 ** flags might not work:
9864 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
9865 ** BTREE_ZERODATA Used for SQL indices
9867 static int btreeCreateTable(Btree *p, Pgno *piTable, int createTabFlags){
9868 BtShared *pBt = p->pBt;
9869 MemPage *pRoot;
9870 Pgno pgnoRoot;
9871 int rc;
9872 int ptfFlags; /* Page-type flags for the root page of new table */
9874 assert( sqlite3BtreeHoldsMutex(p) );
9875 assert( pBt->inTransaction==TRANS_WRITE );
9876 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9878 #ifdef SQLITE_OMIT_AUTOVACUUM
9879 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9880 if( rc ){
9881 return rc;
9883 #else
9884 if( pBt->autoVacuum ){
9885 Pgno pgnoMove; /* Move a page here to make room for the root-page */
9886 MemPage *pPageMove; /* The page to move to. */
9888 /* Creating a new table may probably require moving an existing database
9889 ** to make room for the new tables root page. In case this page turns
9890 ** out to be an overflow page, delete all overflow page-map caches
9891 ** held by open cursors.
9893 invalidateAllOverflowCache(pBt);
9895 /* Read the value of meta[3] from the database to determine where the
9896 ** root page of the new table should go. meta[3] is the largest root-page
9897 ** created so far, so the new root-page is (meta[3]+1).
9899 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
9900 if( pgnoRoot>btreePagecount(pBt) ){
9901 return SQLITE_CORRUPT_BKPT;
9903 pgnoRoot++;
9905 /* The new root-page may not be allocated on a pointer-map page, or the
9906 ** PENDING_BYTE page.
9908 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
9909 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
9910 pgnoRoot++;
9912 assert( pgnoRoot>=3 );
9914 /* Allocate a page. The page that currently resides at pgnoRoot will
9915 ** be moved to the allocated page (unless the allocated page happens
9916 ** to reside at pgnoRoot).
9918 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
9919 if( rc!=SQLITE_OK ){
9920 return rc;
9923 if( pgnoMove!=pgnoRoot ){
9924 /* pgnoRoot is the page that will be used for the root-page of
9925 ** the new table (assuming an error did not occur). But we were
9926 ** allocated pgnoMove. If required (i.e. if it was not allocated
9927 ** by extending the file), the current page at position pgnoMove
9928 ** is already journaled.
9930 u8 eType = 0;
9931 Pgno iPtrPage = 0;
9933 /* Save the positions of any open cursors. This is required in
9934 ** case they are holding a reference to an xFetch reference
9935 ** corresponding to page pgnoRoot. */
9936 rc = saveAllCursors(pBt, 0, 0);
9937 releasePage(pPageMove);
9938 if( rc!=SQLITE_OK ){
9939 return rc;
9942 /* Move the page currently at pgnoRoot to pgnoMove. */
9943 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9944 if( rc!=SQLITE_OK ){
9945 return rc;
9947 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
9948 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
9949 rc = SQLITE_CORRUPT_BKPT;
9951 if( rc!=SQLITE_OK ){
9952 releasePage(pRoot);
9953 return rc;
9955 assert( eType!=PTRMAP_ROOTPAGE );
9956 assert( eType!=PTRMAP_FREEPAGE );
9957 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
9958 releasePage(pRoot);
9960 /* Obtain the page at pgnoRoot */
9961 if( rc!=SQLITE_OK ){
9962 return rc;
9964 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9965 if( rc!=SQLITE_OK ){
9966 return rc;
9968 rc = sqlite3PagerWrite(pRoot->pDbPage);
9969 if( rc!=SQLITE_OK ){
9970 releasePage(pRoot);
9971 return rc;
9973 }else{
9974 pRoot = pPageMove;
9977 /* Update the pointer-map and meta-data with the new root-page number. */
9978 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
9979 if( rc ){
9980 releasePage(pRoot);
9981 return rc;
9984 /* When the new root page was allocated, page 1 was made writable in
9985 ** order either to increase the database filesize, or to decrement the
9986 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
9988 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
9989 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
9990 if( NEVER(rc) ){
9991 releasePage(pRoot);
9992 return rc;
9995 }else{
9996 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9997 if( rc ) return rc;
9999 #endif
10000 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
10001 if( createTabFlags & BTREE_INTKEY ){
10002 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
10003 }else{
10004 ptfFlags = PTF_ZERODATA | PTF_LEAF;
10006 zeroPage(pRoot, ptfFlags);
10007 sqlite3PagerUnref(pRoot->pDbPage);
10008 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
10009 *piTable = pgnoRoot;
10010 return SQLITE_OK;
10012 int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){
10013 int rc;
10014 sqlite3BtreeEnter(p);
10015 rc = btreeCreateTable(p, piTable, flags);
10016 sqlite3BtreeLeave(p);
10017 return rc;
10021 ** Erase the given database page and all its children. Return
10022 ** the page to the freelist.
10024 static int clearDatabasePage(
10025 BtShared *pBt, /* The BTree that contains the table */
10026 Pgno pgno, /* Page number to clear */
10027 int freePageFlag, /* Deallocate page if true */
10028 i64 *pnChange /* Add number of Cells freed to this counter */
10030 MemPage *pPage;
10031 int rc;
10032 unsigned char *pCell;
10033 int i;
10034 int hdr;
10035 CellInfo info;
10037 assert( sqlite3_mutex_held(pBt->mutex) );
10038 if( pgno>btreePagecount(pBt) ){
10039 return SQLITE_CORRUPT_BKPT;
10041 rc = getAndInitPage(pBt, pgno, &pPage, 0);
10042 if( rc ) return rc;
10043 if( (pBt->openFlags & BTREE_SINGLE)==0
10044 && sqlite3PagerPageRefcount(pPage->pDbPage) != (1 + (pgno==1))
10046 rc = SQLITE_CORRUPT_BKPT;
10047 goto cleardatabasepage_out;
10049 hdr = pPage->hdrOffset;
10050 for(i=0; i<pPage->nCell; i++){
10051 pCell = findCell(pPage, i);
10052 if( !pPage->leaf ){
10053 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
10054 if( rc ) goto cleardatabasepage_out;
10056 BTREE_CLEAR_CELL(rc, pPage, pCell, info);
10057 if( rc ) goto cleardatabasepage_out;
10059 if( !pPage->leaf ){
10060 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
10061 if( rc ) goto cleardatabasepage_out;
10062 if( pPage->intKey ) pnChange = 0;
10064 if( pnChange ){
10065 testcase( !pPage->intKey );
10066 *pnChange += pPage->nCell;
10068 if( freePageFlag ){
10069 freePage(pPage, &rc);
10070 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
10071 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
10074 cleardatabasepage_out:
10075 releasePage(pPage);
10076 return rc;
10080 ** Delete all information from a single table in the database. iTable is
10081 ** the page number of the root of the table. After this routine returns,
10082 ** the root page is empty, but still exists.
10084 ** This routine will fail with SQLITE_LOCKED if there are any open
10085 ** read cursors on the table. Open write cursors are moved to the
10086 ** root of the table.
10088 ** If pnChange is not NULL, then the integer value pointed to by pnChange
10089 ** is incremented by the number of entries in the table.
10091 int sqlite3BtreeClearTable(Btree *p, int iTable, i64 *pnChange){
10092 int rc;
10093 BtShared *pBt = p->pBt;
10094 sqlite3BtreeEnter(p);
10095 assert( p->inTrans==TRANS_WRITE );
10097 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
10099 if( SQLITE_OK==rc ){
10100 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
10101 ** is the root of a table b-tree - if it is not, the following call is
10102 ** a no-op). */
10103 if( p->hasIncrblobCur ){
10104 invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
10106 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
10108 sqlite3BtreeLeave(p);
10109 return rc;
10113 ** Delete all information from the single table that pCur is open on.
10115 ** This routine only work for pCur on an ephemeral table.
10117 int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
10118 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
10122 ** Erase all information in a table and add the root of the table to
10123 ** the freelist. Except, the root of the principle table (the one on
10124 ** page 1) is never added to the freelist.
10126 ** This routine will fail with SQLITE_LOCKED if there are any open
10127 ** cursors on the table.
10129 ** If AUTOVACUUM is enabled and the page at iTable is not the last
10130 ** root page in the database file, then the last root page
10131 ** in the database file is moved into the slot formerly occupied by
10132 ** iTable and that last slot formerly occupied by the last root page
10133 ** is added to the freelist instead of iTable. In this say, all
10134 ** root pages are kept at the beginning of the database file, which
10135 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
10136 ** page number that used to be the last root page in the file before
10137 ** the move. If no page gets moved, *piMoved is set to 0.
10138 ** The last root page is recorded in meta[3] and the value of
10139 ** meta[3] is updated by this procedure.
10141 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
10142 int rc;
10143 MemPage *pPage = 0;
10144 BtShared *pBt = p->pBt;
10146 assert( sqlite3BtreeHoldsMutex(p) );
10147 assert( p->inTrans==TRANS_WRITE );
10148 assert( iTable>=2 );
10149 if( iTable>btreePagecount(pBt) ){
10150 return SQLITE_CORRUPT_BKPT;
10153 rc = sqlite3BtreeClearTable(p, iTable, 0);
10154 if( rc ) return rc;
10155 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
10156 if( NEVER(rc) ){
10157 releasePage(pPage);
10158 return rc;
10161 *piMoved = 0;
10163 #ifdef SQLITE_OMIT_AUTOVACUUM
10164 freePage(pPage, &rc);
10165 releasePage(pPage);
10166 #else
10167 if( pBt->autoVacuum ){
10168 Pgno maxRootPgno;
10169 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
10171 if( iTable==maxRootPgno ){
10172 /* If the table being dropped is the table with the largest root-page
10173 ** number in the database, put the root page on the free list.
10175 freePage(pPage, &rc);
10176 releasePage(pPage);
10177 if( rc!=SQLITE_OK ){
10178 return rc;
10180 }else{
10181 /* The table being dropped does not have the largest root-page
10182 ** number in the database. So move the page that does into the
10183 ** gap left by the deleted root-page.
10185 MemPage *pMove;
10186 releasePage(pPage);
10187 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
10188 if( rc!=SQLITE_OK ){
10189 return rc;
10191 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
10192 releasePage(pMove);
10193 if( rc!=SQLITE_OK ){
10194 return rc;
10196 pMove = 0;
10197 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
10198 freePage(pMove, &rc);
10199 releasePage(pMove);
10200 if( rc!=SQLITE_OK ){
10201 return rc;
10203 *piMoved = maxRootPgno;
10206 /* Set the new 'max-root-page' value in the database header. This
10207 ** is the old value less one, less one more if that happens to
10208 ** be a root-page number, less one again if that is the
10209 ** PENDING_BYTE_PAGE.
10211 maxRootPgno--;
10212 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
10213 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
10214 maxRootPgno--;
10216 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
10218 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
10219 }else{
10220 freePage(pPage, &rc);
10221 releasePage(pPage);
10223 #endif
10224 return rc;
10226 int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
10227 int rc;
10228 sqlite3BtreeEnter(p);
10229 rc = btreeDropTable(p, iTable, piMoved);
10230 sqlite3BtreeLeave(p);
10231 return rc;
10236 ** This function may only be called if the b-tree connection already
10237 ** has a read or write transaction open on the database.
10239 ** Read the meta-information out of a database file. Meta[0]
10240 ** is the number of free pages currently in the database. Meta[1]
10241 ** through meta[15] are available for use by higher layers. Meta[0]
10242 ** is read-only, the others are read/write.
10244 ** The schema layer numbers meta values differently. At the schema
10245 ** layer (and the SetCookie and ReadCookie opcodes) the number of
10246 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
10248 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
10249 ** of reading the value out of the header, it instead loads the "DataVersion"
10250 ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
10251 ** database file. It is a number computed by the pager. But its access
10252 ** pattern is the same as header meta values, and so it is convenient to
10253 ** read it from this routine.
10255 void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
10256 BtShared *pBt = p->pBt;
10258 sqlite3BtreeEnter(p);
10259 assert( p->inTrans>TRANS_NONE );
10260 assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) );
10261 assert( pBt->pPage1 );
10262 assert( idx>=0 && idx<=15 );
10264 if( idx==BTREE_DATA_VERSION ){
10265 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iBDataVersion;
10266 }else{
10267 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
10270 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
10271 ** database, mark the database as read-only. */
10272 #ifdef SQLITE_OMIT_AUTOVACUUM
10273 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
10274 pBt->btsFlags |= BTS_READ_ONLY;
10276 #endif
10278 sqlite3BtreeLeave(p);
10282 ** Write meta-information back into the database. Meta[0] is
10283 ** read-only and may not be written.
10285 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
10286 BtShared *pBt = p->pBt;
10287 unsigned char *pP1;
10288 int rc;
10289 assert( idx>=1 && idx<=15 );
10290 sqlite3BtreeEnter(p);
10291 assert( p->inTrans==TRANS_WRITE );
10292 assert( pBt->pPage1!=0 );
10293 pP1 = pBt->pPage1->aData;
10294 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
10295 if( rc==SQLITE_OK ){
10296 put4byte(&pP1[36 + idx*4], iMeta);
10297 #ifndef SQLITE_OMIT_AUTOVACUUM
10298 if( idx==BTREE_INCR_VACUUM ){
10299 assert( pBt->autoVacuum || iMeta==0 );
10300 assert( iMeta==0 || iMeta==1 );
10301 pBt->incrVacuum = (u8)iMeta;
10303 #endif
10305 sqlite3BtreeLeave(p);
10306 return rc;
10310 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
10311 ** number of entries in the b-tree and write the result to *pnEntry.
10313 ** SQLITE_OK is returned if the operation is successfully executed.
10314 ** Otherwise, if an error is encountered (i.e. an IO error or database
10315 ** corruption) an SQLite error code is returned.
10317 int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){
10318 i64 nEntry = 0; /* Value to return in *pnEntry */
10319 int rc; /* Return code */
10321 rc = moveToRoot(pCur);
10322 if( rc==SQLITE_EMPTY ){
10323 *pnEntry = 0;
10324 return SQLITE_OK;
10327 /* Unless an error occurs, the following loop runs one iteration for each
10328 ** page in the B-Tree structure (not including overflow pages).
10330 while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){
10331 int iIdx; /* Index of child node in parent */
10332 MemPage *pPage; /* Current page of the b-tree */
10334 /* If this is a leaf page or the tree is not an int-key tree, then
10335 ** this page contains countable entries. Increment the entry counter
10336 ** accordingly.
10338 pPage = pCur->pPage;
10339 if( pPage->leaf || !pPage->intKey ){
10340 nEntry += pPage->nCell;
10343 /* pPage is a leaf node. This loop navigates the cursor so that it
10344 ** points to the first interior cell that it points to the parent of
10345 ** the next page in the tree that has not yet been visited. The
10346 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
10347 ** of the page, or to the number of cells in the page if the next page
10348 ** to visit is the right-child of its parent.
10350 ** If all pages in the tree have been visited, return SQLITE_OK to the
10351 ** caller.
10353 if( pPage->leaf ){
10354 do {
10355 if( pCur->iPage==0 ){
10356 /* All pages of the b-tree have been visited. Return successfully. */
10357 *pnEntry = nEntry;
10358 return moveToRoot(pCur);
10360 moveToParent(pCur);
10361 }while ( pCur->ix>=pCur->pPage->nCell );
10363 pCur->ix++;
10364 pPage = pCur->pPage;
10367 /* Descend to the child node of the cell that the cursor currently
10368 ** points at. This is the right-child if (iIdx==pPage->nCell).
10370 iIdx = pCur->ix;
10371 if( iIdx==pPage->nCell ){
10372 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
10373 }else{
10374 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
10378 /* An error has occurred. Return an error code. */
10379 return rc;
10383 ** Return the pager associated with a BTree. This routine is used for
10384 ** testing and debugging only.
10386 Pager *sqlite3BtreePager(Btree *p){
10387 return p->pBt->pPager;
10390 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10392 ** Record an OOM error during integrity_check
10394 static void checkOom(IntegrityCk *pCheck){
10395 pCheck->rc = SQLITE_NOMEM;
10396 pCheck->mxErr = 0; /* Causes integrity_check processing to stop */
10397 if( pCheck->nErr==0 ) pCheck->nErr++;
10401 ** Invoke the progress handler, if appropriate. Also check for an
10402 ** interrupt.
10404 static void checkProgress(IntegrityCk *pCheck){
10405 sqlite3 *db = pCheck->db;
10406 if( AtomicLoad(&db->u1.isInterrupted) ){
10407 pCheck->rc = SQLITE_INTERRUPT;
10408 pCheck->nErr++;
10409 pCheck->mxErr = 0;
10411 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
10412 if( db->xProgress ){
10413 assert( db->nProgressOps>0 );
10414 pCheck->nStep++;
10415 if( (pCheck->nStep % db->nProgressOps)==0
10416 && db->xProgress(db->pProgressArg)
10418 pCheck->rc = SQLITE_INTERRUPT;
10419 pCheck->nErr++;
10420 pCheck->mxErr = 0;
10423 #endif
10427 ** Append a message to the error message string.
10429 static void checkAppendMsg(
10430 IntegrityCk *pCheck,
10431 const char *zFormat,
10434 va_list ap;
10435 checkProgress(pCheck);
10436 if( !pCheck->mxErr ) return;
10437 pCheck->mxErr--;
10438 pCheck->nErr++;
10439 va_start(ap, zFormat);
10440 if( pCheck->errMsg.nChar ){
10441 sqlite3_str_append(&pCheck->errMsg, "\n", 1);
10443 if( pCheck->zPfx ){
10444 sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx,
10445 pCheck->v0, pCheck->v1, pCheck->v2);
10447 sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
10448 va_end(ap);
10449 if( pCheck->errMsg.accError==SQLITE_NOMEM ){
10450 checkOom(pCheck);
10453 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10455 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10458 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
10459 ** corresponds to page iPg is already set.
10461 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
10462 assert( pCheck->aPgRef!=0 );
10463 assert( iPg<=pCheck->nCkPage && sizeof(pCheck->aPgRef[0])==1 );
10464 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
10468 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
10470 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
10471 assert( pCheck->aPgRef!=0 );
10472 assert( iPg<=pCheck->nCkPage && sizeof(pCheck->aPgRef[0])==1 );
10473 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
10478 ** Add 1 to the reference count for page iPage. If this is the second
10479 ** reference to the page, add an error message to pCheck->zErrMsg.
10480 ** Return 1 if there are 2 or more references to the page and 0 if
10481 ** if this is the first reference to the page.
10483 ** Also check that the page number is in bounds.
10485 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
10486 if( iPage>pCheck->nCkPage || iPage==0 ){
10487 checkAppendMsg(pCheck, "invalid page number %u", iPage);
10488 return 1;
10490 if( getPageReferenced(pCheck, iPage) ){
10491 checkAppendMsg(pCheck, "2nd reference to page %u", iPage);
10492 return 1;
10494 setPageReferenced(pCheck, iPage);
10495 return 0;
10498 #ifndef SQLITE_OMIT_AUTOVACUUM
10500 ** Check that the entry in the pointer-map for page iChild maps to
10501 ** page iParent, pointer type ptrType. If not, append an error message
10502 ** to pCheck.
10504 static void checkPtrmap(
10505 IntegrityCk *pCheck, /* Integrity check context */
10506 Pgno iChild, /* Child page number */
10507 u8 eType, /* Expected pointer map type */
10508 Pgno iParent /* Expected pointer map parent page number */
10510 int rc;
10511 u8 ePtrmapType;
10512 Pgno iPtrmapParent;
10514 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
10515 if( rc!=SQLITE_OK ){
10516 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) checkOom(pCheck);
10517 checkAppendMsg(pCheck, "Failed to read ptrmap key=%u", iChild);
10518 return;
10521 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
10522 checkAppendMsg(pCheck,
10523 "Bad ptr map entry key=%u expected=(%u,%u) got=(%u,%u)",
10524 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
10527 #endif
10530 ** Check the integrity of the freelist or of an overflow page list.
10531 ** Verify that the number of pages on the list is N.
10533 static void checkList(
10534 IntegrityCk *pCheck, /* Integrity checking context */
10535 int isFreeList, /* True for a freelist. False for overflow page list */
10536 Pgno iPage, /* Page number for first page in the list */
10537 u32 N /* Expected number of pages in the list */
10539 int i;
10540 u32 expected = N;
10541 int nErrAtStart = pCheck->nErr;
10542 while( iPage!=0 && pCheck->mxErr ){
10543 DbPage *pOvflPage;
10544 unsigned char *pOvflData;
10545 if( checkRef(pCheck, iPage) ) break;
10546 N--;
10547 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
10548 checkAppendMsg(pCheck, "failed to get page %u", iPage);
10549 break;
10551 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
10552 if( isFreeList ){
10553 u32 n = (u32)get4byte(&pOvflData[4]);
10554 #ifndef SQLITE_OMIT_AUTOVACUUM
10555 if( pCheck->pBt->autoVacuum ){
10556 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
10558 #endif
10559 if( n>pCheck->pBt->usableSize/4-2 ){
10560 checkAppendMsg(pCheck,
10561 "freelist leaf count too big on page %u", iPage);
10562 N--;
10563 }else{
10564 for(i=0; i<(int)n; i++){
10565 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
10566 #ifndef SQLITE_OMIT_AUTOVACUUM
10567 if( pCheck->pBt->autoVacuum ){
10568 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
10570 #endif
10571 checkRef(pCheck, iFreePage);
10573 N -= n;
10576 #ifndef SQLITE_OMIT_AUTOVACUUM
10577 else{
10578 /* If this database supports auto-vacuum and iPage is not the last
10579 ** page in this overflow list, check that the pointer-map entry for
10580 ** the following page matches iPage.
10582 if( pCheck->pBt->autoVacuum && N>0 ){
10583 i = get4byte(pOvflData);
10584 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
10587 #endif
10588 iPage = get4byte(pOvflData);
10589 sqlite3PagerUnref(pOvflPage);
10591 if( N && nErrAtStart==pCheck->nErr ){
10592 checkAppendMsg(pCheck,
10593 "%s is %u but should be %u",
10594 isFreeList ? "size" : "overflow list length",
10595 expected-N, expected);
10598 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10601 ** An implementation of a min-heap.
10603 ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
10604 ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
10605 ** and aHeap[N*2+1].
10607 ** The heap property is this: Every node is less than or equal to both
10608 ** of its daughter nodes. A consequence of the heap property is that the
10609 ** root node aHeap[1] is always the minimum value currently in the heap.
10611 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
10612 ** the heap, preserving the heap property. The btreeHeapPull() routine
10613 ** removes the root element from the heap (the minimum value in the heap)
10614 ** and then moves other nodes around as necessary to preserve the heap
10615 ** property.
10617 ** This heap is used for cell overlap and coverage testing. Each u32
10618 ** entry represents the span of a cell or freeblock on a btree page.
10619 ** The upper 16 bits are the index of the first byte of a range and the
10620 ** lower 16 bits are the index of the last byte of that range.
10622 static void btreeHeapInsert(u32 *aHeap, u32 x){
10623 u32 j, i;
10624 assert( aHeap!=0 );
10625 i = ++aHeap[0];
10626 aHeap[i] = x;
10627 while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
10628 x = aHeap[j];
10629 aHeap[j] = aHeap[i];
10630 aHeap[i] = x;
10631 i = j;
10634 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
10635 u32 j, i, x;
10636 if( (x = aHeap[0])==0 ) return 0;
10637 *pOut = aHeap[1];
10638 aHeap[1] = aHeap[x];
10639 aHeap[x] = 0xffffffff;
10640 aHeap[0]--;
10641 i = 1;
10642 while( (j = i*2)<=aHeap[0] ){
10643 if( aHeap[j]>aHeap[j+1] ) j++;
10644 if( aHeap[i]<aHeap[j] ) break;
10645 x = aHeap[i];
10646 aHeap[i] = aHeap[j];
10647 aHeap[j] = x;
10648 i = j;
10650 return 1;
10653 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10655 ** Do various sanity checks on a single page of a tree. Return
10656 ** the tree depth. Root pages return 0. Parents of root pages
10657 ** return 1, and so forth.
10659 ** These checks are done:
10661 ** 1. Make sure that cells and freeblocks do not overlap
10662 ** but combine to completely cover the page.
10663 ** 2. Make sure integer cell keys are in order.
10664 ** 3. Check the integrity of overflow pages.
10665 ** 4. Recursively call checkTreePage on all children.
10666 ** 5. Verify that the depth of all children is the same.
10668 static int checkTreePage(
10669 IntegrityCk *pCheck, /* Context for the sanity check */
10670 Pgno iPage, /* Page number of the page to check */
10671 i64 *piMinKey, /* Write minimum integer primary key here */
10672 i64 maxKey /* Error if integer primary key greater than this */
10674 MemPage *pPage = 0; /* The page being analyzed */
10675 int i; /* Loop counter */
10676 int rc; /* Result code from subroutine call */
10677 int depth = -1, d2; /* Depth of a subtree */
10678 int pgno; /* Page number */
10679 int nFrag; /* Number of fragmented bytes on the page */
10680 int hdr; /* Offset to the page header */
10681 int cellStart; /* Offset to the start of the cell pointer array */
10682 int nCell; /* Number of cells */
10683 int doCoverageCheck = 1; /* True if cell coverage checking should be done */
10684 int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
10685 ** False if IPK must be strictly less than maxKey */
10686 u8 *data; /* Page content */
10687 u8 *pCell; /* Cell content */
10688 u8 *pCellIdx; /* Next element of the cell pointer array */
10689 BtShared *pBt; /* The BtShared object that owns pPage */
10690 u32 pc; /* Address of a cell */
10691 u32 usableSize; /* Usable size of the page */
10692 u32 contentOffset; /* Offset to the start of the cell content area */
10693 u32 *heap = 0; /* Min-heap used for checking cell coverage */
10694 u32 x, prev = 0; /* Next and previous entry on the min-heap */
10695 const char *saved_zPfx = pCheck->zPfx;
10696 int saved_v1 = pCheck->v1;
10697 int saved_v2 = pCheck->v2;
10698 u8 savedIsInit = 0;
10700 /* Check that the page exists
10702 checkProgress(pCheck);
10703 if( pCheck->mxErr==0 ) goto end_of_check;
10704 pBt = pCheck->pBt;
10705 usableSize = pBt->usableSize;
10706 if( iPage==0 ) return 0;
10707 if( checkRef(pCheck, iPage) ) return 0;
10708 pCheck->zPfx = "Tree %u page %u: ";
10709 pCheck->v1 = iPage;
10710 if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){
10711 checkAppendMsg(pCheck,
10712 "unable to get the page. error code=%d", rc);
10713 if( rc==SQLITE_IOERR_NOMEM ) pCheck->rc = SQLITE_NOMEM;
10714 goto end_of_check;
10717 /* Clear MemPage.isInit to make sure the corruption detection code in
10718 ** btreeInitPage() is executed. */
10719 savedIsInit = pPage->isInit;
10720 pPage->isInit = 0;
10721 if( (rc = btreeInitPage(pPage))!=0 ){
10722 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
10723 checkAppendMsg(pCheck,
10724 "btreeInitPage() returns error code %d", rc);
10725 goto end_of_check;
10727 if( (rc = btreeComputeFreeSpace(pPage))!=0 ){
10728 assert( rc==SQLITE_CORRUPT );
10729 checkAppendMsg(pCheck, "free space corruption", rc);
10730 goto end_of_check;
10732 data = pPage->aData;
10733 hdr = pPage->hdrOffset;
10735 /* Set up for cell analysis */
10736 pCheck->zPfx = "Tree %u page %u cell %u: ";
10737 contentOffset = get2byteNotZero(&data[hdr+5]);
10738 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
10740 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
10741 ** number of cells on the page. */
10742 nCell = get2byte(&data[hdr+3]);
10743 assert( pPage->nCell==nCell );
10745 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
10746 ** immediately follows the b-tree page header. */
10747 cellStart = hdr + 12 - 4*pPage->leaf;
10748 assert( pPage->aCellIdx==&data[cellStart] );
10749 pCellIdx = &data[cellStart + 2*(nCell-1)];
10751 if( !pPage->leaf ){
10752 /* Analyze the right-child page of internal pages */
10753 pgno = get4byte(&data[hdr+8]);
10754 #ifndef SQLITE_OMIT_AUTOVACUUM
10755 if( pBt->autoVacuum ){
10756 pCheck->zPfx = "Tree %u page %u right child: ";
10757 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10759 #endif
10760 depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10761 keyCanBeEqual = 0;
10762 }else{
10763 /* For leaf pages, the coverage check will occur in the same loop
10764 ** as the other cell checks, so initialize the heap. */
10765 heap = pCheck->heap;
10766 heap[0] = 0;
10769 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
10770 ** integer offsets to the cell contents. */
10771 for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
10772 CellInfo info;
10774 /* Check cell size */
10775 pCheck->v2 = i;
10776 assert( pCellIdx==&data[cellStart + i*2] );
10777 pc = get2byteAligned(pCellIdx);
10778 pCellIdx -= 2;
10779 if( pc<contentOffset || pc>usableSize-4 ){
10780 checkAppendMsg(pCheck, "Offset %u out of range %u..%u",
10781 pc, contentOffset, usableSize-4);
10782 doCoverageCheck = 0;
10783 continue;
10785 pCell = &data[pc];
10786 pPage->xParseCell(pPage, pCell, &info);
10787 if( pc+info.nSize>usableSize ){
10788 checkAppendMsg(pCheck, "Extends off end of page");
10789 doCoverageCheck = 0;
10790 continue;
10793 /* Check for integer primary key out of range */
10794 if( pPage->intKey ){
10795 if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
10796 checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
10798 maxKey = info.nKey;
10799 keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
10802 /* Check the content overflow list */
10803 if( info.nPayload>info.nLocal ){
10804 u32 nPage; /* Number of pages on the overflow chain */
10805 Pgno pgnoOvfl; /* First page of the overflow chain */
10806 assert( pc + info.nSize - 4 <= usableSize );
10807 nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
10808 pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
10809 #ifndef SQLITE_OMIT_AUTOVACUUM
10810 if( pBt->autoVacuum ){
10811 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
10813 #endif
10814 checkList(pCheck, 0, pgnoOvfl, nPage);
10817 if( !pPage->leaf ){
10818 /* Check sanity of left child page for internal pages */
10819 pgno = get4byte(pCell);
10820 #ifndef SQLITE_OMIT_AUTOVACUUM
10821 if( pBt->autoVacuum ){
10822 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10824 #endif
10825 d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10826 keyCanBeEqual = 0;
10827 if( d2!=depth ){
10828 checkAppendMsg(pCheck, "Child page depth differs");
10829 depth = d2;
10831 }else{
10832 /* Populate the coverage-checking heap for leaf pages */
10833 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
10836 *piMinKey = maxKey;
10838 /* Check for complete coverage of the page
10840 pCheck->zPfx = 0;
10841 if( doCoverageCheck && pCheck->mxErr>0 ){
10842 /* For leaf pages, the min-heap has already been initialized and the
10843 ** cells have already been inserted. But for internal pages, that has
10844 ** not yet been done, so do it now */
10845 if( !pPage->leaf ){
10846 heap = pCheck->heap;
10847 heap[0] = 0;
10848 for(i=nCell-1; i>=0; i--){
10849 u32 size;
10850 pc = get2byteAligned(&data[cellStart+i*2]);
10851 size = pPage->xCellSize(pPage, &data[pc]);
10852 btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
10855 /* Add the freeblocks to the min-heap
10857 ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
10858 ** is the offset of the first freeblock, or zero if there are no
10859 ** freeblocks on the page.
10861 i = get2byte(&data[hdr+1]);
10862 while( i>0 ){
10863 int size, j;
10864 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10865 size = get2byte(&data[i+2]);
10866 assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
10867 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
10868 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
10869 ** big-endian integer which is the offset in the b-tree page of the next
10870 ** freeblock in the chain, or zero if the freeblock is the last on the
10871 ** chain. */
10872 j = get2byte(&data[i]);
10873 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
10874 ** increasing offset. */
10875 assert( j==0 || j>i+size ); /* Enforced by btreeComputeFreeSpace() */
10876 assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10877 i = j;
10879 /* Analyze the min-heap looking for overlap between cells and/or
10880 ** freeblocks, and counting the number of untracked bytes in nFrag.
10882 ** Each min-heap entry is of the form: (start_address<<16)|end_address.
10883 ** There is an implied first entry the covers the page header, the cell
10884 ** pointer index, and the gap between the cell pointer index and the start
10885 ** of cell content.
10887 ** The loop below pulls entries from the min-heap in order and compares
10888 ** the start_address against the previous end_address. If there is an
10889 ** overlap, that means bytes are used multiple times. If there is a gap,
10890 ** that gap is added to the fragmentation count.
10892 nFrag = 0;
10893 prev = contentOffset - 1; /* Implied first min-heap entry */
10894 while( btreeHeapPull(heap,&x) ){
10895 if( (prev&0xffff)>=(x>>16) ){
10896 checkAppendMsg(pCheck,
10897 "Multiple uses for byte %u of page %u", x>>16, iPage);
10898 break;
10899 }else{
10900 nFrag += (x>>16) - (prev&0xffff) - 1;
10901 prev = x;
10904 nFrag += usableSize - (prev&0xffff) - 1;
10905 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
10906 ** is stored in the fifth field of the b-tree page header.
10907 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
10908 ** number of fragmented free bytes within the cell content area.
10910 if( heap[0]==0 && nFrag!=data[hdr+7] ){
10911 checkAppendMsg(pCheck,
10912 "Fragmentation of %u bytes reported as %u on page %u",
10913 nFrag, data[hdr+7], iPage);
10917 end_of_check:
10918 if( !doCoverageCheck ) pPage->isInit = savedIsInit;
10919 releasePage(pPage);
10920 pCheck->zPfx = saved_zPfx;
10921 pCheck->v1 = saved_v1;
10922 pCheck->v2 = saved_v2;
10923 return depth+1;
10925 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10927 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10929 ** This routine does a complete check of the given BTree file. aRoot[] is
10930 ** an array of pages numbers were each page number is the root page of
10931 ** a table. nRoot is the number of entries in aRoot.
10933 ** A read-only or read-write transaction must be opened before calling
10934 ** this function.
10936 ** Write the number of error seen in *pnErr. Except for some memory
10937 ** allocation errors, an error message held in memory obtained from
10938 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
10939 ** returned. If a memory allocation error occurs, NULL is returned.
10941 ** If the first entry in aRoot[] is 0, that indicates that the list of
10942 ** root pages is incomplete. This is a "partial integrity-check". This
10943 ** happens when performing an integrity check on a single table. The
10944 ** zero is skipped, of course. But in addition, the freelist checks
10945 ** and the checks to make sure every page is referenced are also skipped,
10946 ** since obviously it is not possible to know which pages are covered by
10947 ** the unverified btrees. Except, if aRoot[1] is 1, then the freelist
10948 ** checks are still performed.
10950 int sqlite3BtreeIntegrityCheck(
10951 sqlite3 *db, /* Database connection that is running the check */
10952 Btree *p, /* The btree to be checked */
10953 Pgno *aRoot, /* An array of root pages numbers for individual trees */
10954 int nRoot, /* Number of entries in aRoot[] */
10955 int mxErr, /* Stop reporting errors after this many */
10956 int *pnErr, /* OUT: Write number of errors seen to this variable */
10957 char **pzOut /* OUT: Write the error message string here */
10959 Pgno i;
10960 IntegrityCk sCheck;
10961 BtShared *pBt = p->pBt;
10962 u64 savedDbFlags = pBt->db->flags;
10963 char zErr[100];
10964 int bPartial = 0; /* True if not checking all btrees */
10965 int bCkFreelist = 1; /* True to scan the freelist */
10966 VVA_ONLY( int nRef );
10967 assert( nRoot>0 );
10969 /* aRoot[0]==0 means this is a partial check */
10970 if( aRoot[0]==0 ){
10971 assert( nRoot>1 );
10972 bPartial = 1;
10973 if( aRoot[1]!=1 ) bCkFreelist = 0;
10976 sqlite3BtreeEnter(p);
10977 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
10978 VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
10979 assert( nRef>=0 );
10980 memset(&sCheck, 0, sizeof(sCheck));
10981 sCheck.db = db;
10982 sCheck.pBt = pBt;
10983 sCheck.pPager = pBt->pPager;
10984 sCheck.nCkPage = btreePagecount(sCheck.pBt);
10985 sCheck.mxErr = mxErr;
10986 sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
10987 sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
10988 if( sCheck.nCkPage==0 ){
10989 goto integrity_ck_cleanup;
10992 sCheck.aPgRef = sqlite3MallocZero((sCheck.nCkPage / 8)+ 1);
10993 if( !sCheck.aPgRef ){
10994 checkOom(&sCheck);
10995 goto integrity_ck_cleanup;
10997 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
10998 if( sCheck.heap==0 ){
10999 checkOom(&sCheck);
11000 goto integrity_ck_cleanup;
11003 i = PENDING_BYTE_PAGE(pBt);
11004 if( i<=sCheck.nCkPage ) setPageReferenced(&sCheck, i);
11006 /* Check the integrity of the freelist
11008 if( bCkFreelist ){
11009 sCheck.zPfx = "Freelist: ";
11010 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
11011 get4byte(&pBt->pPage1->aData[36]));
11012 sCheck.zPfx = 0;
11015 /* Check all the tables.
11017 #ifndef SQLITE_OMIT_AUTOVACUUM
11018 if( !bPartial ){
11019 if( pBt->autoVacuum ){
11020 Pgno mx = 0;
11021 Pgno mxInHdr;
11022 for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
11023 mxInHdr = get4byte(&pBt->pPage1->aData[52]);
11024 if( mx!=mxInHdr ){
11025 checkAppendMsg(&sCheck,
11026 "max rootpage (%u) disagrees with header (%u)",
11027 mx, mxInHdr
11030 }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
11031 checkAppendMsg(&sCheck,
11032 "incremental_vacuum enabled with a max rootpage of zero"
11036 #endif
11037 testcase( pBt->db->flags & SQLITE_CellSizeCk );
11038 pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
11039 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
11040 i64 notUsed;
11041 if( aRoot[i]==0 ) continue;
11042 #ifndef SQLITE_OMIT_AUTOVACUUM
11043 if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){
11044 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
11046 #endif
11047 sCheck.v0 = aRoot[i];
11048 checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
11050 pBt->db->flags = savedDbFlags;
11052 /* Make sure every page in the file is referenced
11054 if( !bPartial ){
11055 for(i=1; i<=sCheck.nCkPage && sCheck.mxErr; i++){
11056 #ifdef SQLITE_OMIT_AUTOVACUUM
11057 if( getPageReferenced(&sCheck, i)==0 ){
11058 checkAppendMsg(&sCheck, "Page %u: never used", i);
11060 #else
11061 /* If the database supports auto-vacuum, make sure no tables contain
11062 ** references to pointer-map pages.
11064 if( getPageReferenced(&sCheck, i)==0 &&
11065 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
11066 checkAppendMsg(&sCheck, "Page %u: never used", i);
11068 if( getPageReferenced(&sCheck, i)!=0 &&
11069 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
11070 checkAppendMsg(&sCheck, "Page %u: pointer map referenced", i);
11072 #endif
11076 /* Clean up and report errors.
11078 integrity_ck_cleanup:
11079 sqlite3PageFree(sCheck.heap);
11080 sqlite3_free(sCheck.aPgRef);
11081 *pnErr = sCheck.nErr;
11082 if( sCheck.nErr==0 ){
11083 sqlite3_str_reset(&sCheck.errMsg);
11084 *pzOut = 0;
11085 }else{
11086 *pzOut = sqlite3StrAccumFinish(&sCheck.errMsg);
11088 /* Make sure this analysis did not leave any unref() pages. */
11089 assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
11090 sqlite3BtreeLeave(p);
11091 return sCheck.rc;
11093 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
11096 ** Return the full pathname of the underlying database file. Return
11097 ** an empty string if the database is in-memory or a TEMP database.
11099 ** The pager filename is invariant as long as the pager is
11100 ** open so it is safe to access without the BtShared mutex.
11102 const char *sqlite3BtreeGetFilename(Btree *p){
11103 assert( p->pBt->pPager!=0 );
11104 return sqlite3PagerFilename(p->pBt->pPager, 1);
11108 ** Return the pathname of the journal file for this database. The return
11109 ** value of this routine is the same regardless of whether the journal file
11110 ** has been created or not.
11112 ** The pager journal filename is invariant as long as the pager is
11113 ** open so it is safe to access without the BtShared mutex.
11115 const char *sqlite3BtreeGetJournalname(Btree *p){
11116 assert( p->pBt->pPager!=0 );
11117 return sqlite3PagerJournalname(p->pBt->pPager);
11121 ** Return one of SQLITE_TXN_NONE, SQLITE_TXN_READ, or SQLITE_TXN_WRITE
11122 ** to describe the current transaction state of Btree p.
11124 int sqlite3BtreeTxnState(Btree *p){
11125 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
11126 return p ? p->inTrans : 0;
11129 #ifndef SQLITE_OMIT_WAL
11131 ** Run a checkpoint on the Btree passed as the first argument.
11133 ** Return SQLITE_LOCKED if this or any other connection has an open
11134 ** transaction on the shared-cache the argument Btree is connected to.
11136 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
11138 int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
11139 int rc = SQLITE_OK;
11140 if( p ){
11141 BtShared *pBt = p->pBt;
11142 sqlite3BtreeEnter(p);
11143 if( pBt->inTransaction!=TRANS_NONE ){
11144 rc = SQLITE_LOCKED;
11145 }else{
11146 rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
11148 sqlite3BtreeLeave(p);
11150 return rc;
11152 #endif
11155 ** Return true if there is currently a backup running on Btree p.
11157 int sqlite3BtreeIsInBackup(Btree *p){
11158 assert( p );
11159 assert( sqlite3_mutex_held(p->db->mutex) );
11160 return p->nBackup!=0;
11164 ** This function returns a pointer to a blob of memory associated with
11165 ** a single shared-btree. The memory is used by client code for its own
11166 ** purposes (for example, to store a high-level schema associated with
11167 ** the shared-btree). The btree layer manages reference counting issues.
11169 ** The first time this is called on a shared-btree, nBytes bytes of memory
11170 ** are allocated, zeroed, and returned to the caller. For each subsequent
11171 ** call the nBytes parameter is ignored and a pointer to the same blob
11172 ** of memory returned.
11174 ** If the nBytes parameter is 0 and the blob of memory has not yet been
11175 ** allocated, a null pointer is returned. If the blob has already been
11176 ** allocated, it is returned as normal.
11178 ** Just before the shared-btree is closed, the function passed as the
11179 ** xFree argument when the memory allocation was made is invoked on the
11180 ** blob of allocated memory. The xFree function should not call sqlite3_free()
11181 ** on the memory, the btree layer does that.
11183 void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
11184 BtShared *pBt = p->pBt;
11185 sqlite3BtreeEnter(p);
11186 if( !pBt->pSchema && nBytes ){
11187 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
11188 pBt->xFreeSchema = xFree;
11190 sqlite3BtreeLeave(p);
11191 return pBt->pSchema;
11195 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
11196 ** btree as the argument handle holds an exclusive lock on the
11197 ** sqlite_schema table. Otherwise SQLITE_OK.
11199 int sqlite3BtreeSchemaLocked(Btree *p){
11200 int rc;
11201 assert( sqlite3_mutex_held(p->db->mutex) );
11202 sqlite3BtreeEnter(p);
11203 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
11204 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
11205 sqlite3BtreeLeave(p);
11206 return rc;
11210 #ifndef SQLITE_OMIT_SHARED_CACHE
11212 ** Obtain a lock on the table whose root page is iTab. The
11213 ** lock is a write lock if isWritelock is true or a read lock
11214 ** if it is false.
11216 int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
11217 int rc = SQLITE_OK;
11218 assert( p->inTrans!=TRANS_NONE );
11219 if( p->sharable ){
11220 u8 lockType = READ_LOCK + isWriteLock;
11221 assert( READ_LOCK+1==WRITE_LOCK );
11222 assert( isWriteLock==0 || isWriteLock==1 );
11224 sqlite3BtreeEnter(p);
11225 rc = querySharedCacheTableLock(p, iTab, lockType);
11226 if( rc==SQLITE_OK ){
11227 rc = setSharedCacheTableLock(p, iTab, lockType);
11229 sqlite3BtreeLeave(p);
11231 return rc;
11233 #endif
11235 #ifndef SQLITE_OMIT_INCRBLOB
11237 ** Argument pCsr must be a cursor opened for writing on an
11238 ** INTKEY table currently pointing at a valid table entry.
11239 ** This function modifies the data stored as part of that entry.
11241 ** Only the data content may only be modified, it is not possible to
11242 ** change the length of the data stored. If this function is called with
11243 ** parameters that attempt to write past the end of the existing data,
11244 ** no modifications are made and SQLITE_CORRUPT is returned.
11246 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
11247 int rc;
11248 assert( cursorOwnsBtShared(pCsr) );
11249 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
11250 assert( pCsr->curFlags & BTCF_Incrblob );
11252 rc = restoreCursorPosition(pCsr);
11253 if( rc!=SQLITE_OK ){
11254 return rc;
11256 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
11257 if( pCsr->eState!=CURSOR_VALID ){
11258 return SQLITE_ABORT;
11261 /* Save the positions of all other cursors open on this table. This is
11262 ** required in case any of them are holding references to an xFetch
11263 ** version of the b-tree page modified by the accessPayload call below.
11265 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
11266 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
11267 ** saveAllCursors can only return SQLITE_OK.
11269 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
11270 assert( rc==SQLITE_OK );
11272 /* Check some assumptions:
11273 ** (a) the cursor is open for writing,
11274 ** (b) there is a read/write transaction open,
11275 ** (c) the connection holds a write-lock on the table (if required),
11276 ** (d) there are no conflicting read-locks, and
11277 ** (e) the cursor points at a valid row of an intKey table.
11279 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
11280 return SQLITE_READONLY;
11282 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
11283 && pCsr->pBt->inTransaction==TRANS_WRITE );
11284 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
11285 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
11286 assert( pCsr->pPage->intKey );
11288 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
11292 ** Mark this cursor as an incremental blob cursor.
11294 void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
11295 pCur->curFlags |= BTCF_Incrblob;
11296 pCur->pBtree->hasIncrblobCur = 1;
11298 #endif
11301 ** Set both the "read version" (single byte at byte offset 18) and
11302 ** "write version" (single byte at byte offset 19) fields in the database
11303 ** header to iVersion.
11305 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
11306 BtShared *pBt = pBtree->pBt;
11307 int rc; /* Return code */
11309 assert( iVersion==1 || iVersion==2 );
11311 /* If setting the version fields to 1, do not automatically open the
11312 ** WAL connection, even if the version fields are currently set to 2.
11314 pBt->btsFlags &= ~BTS_NO_WAL;
11315 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
11317 rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
11318 if( rc==SQLITE_OK ){
11319 u8 *aData = pBt->pPage1->aData;
11320 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
11321 rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
11322 if( rc==SQLITE_OK ){
11323 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
11324 if( rc==SQLITE_OK ){
11325 aData[18] = (u8)iVersion;
11326 aData[19] = (u8)iVersion;
11332 pBt->btsFlags &= ~BTS_NO_WAL;
11333 return rc;
11337 ** Return true if the cursor has a hint specified. This routine is
11338 ** only used from within assert() statements
11340 int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
11341 return (pCsr->hints & mask)!=0;
11345 ** Return true if the given Btree is read-only.
11347 int sqlite3BtreeIsReadonly(Btree *p){
11348 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
11352 ** Return the size of the header added to each page by this module.
11354 int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
11357 ** If no transaction is active and the database is not a temp-db, clear
11358 ** the in-memory pager cache.
11360 void sqlite3BtreeClearCache(Btree *p){
11361 BtShared *pBt = p->pBt;
11362 if( pBt->inTransaction==TRANS_NONE ){
11363 sqlite3PagerClearCache(pBt->pPager);
11367 #if !defined(SQLITE_OMIT_SHARED_CACHE)
11369 ** Return true if the Btree passed as the only argument is sharable.
11371 int sqlite3BtreeSharable(Btree *p){
11372 return p->sharable;
11376 ** Return the number of connections to the BtShared object accessed by
11377 ** the Btree handle passed as the only argument. For private caches
11378 ** this is always 1. For shared caches it may be 1 or greater.
11380 int sqlite3BtreeConnectionCount(Btree *p){
11381 testcase( p->sharable );
11382 return p->pBt->nRef;
11384 #endif