add logcat option to PRAGMA cipher_profile
[sqlcipher.git] / src / btree.c
blobd1e84d0a604a1e769f1044eba631f40fdc75d18a
1 /*
2 ** 2004 April 6
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file implements an external (disk-based) database using BTrees.
13 ** See the header comment on "btreeInt.h" for additional information.
14 ** Including a description of file format and an overview of operation.
16 #include "btreeInt.h"
19 ** The header string that appears at the beginning of every
20 ** SQLite database.
22 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
25 ** Set this global variable to 1 to enable tracing using the TRACE
26 ** macro.
28 #if 0
29 int sqlite3BtreeTrace=1; /* True to enable tracing */
30 # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
31 #else
32 # define TRACE(X)
33 #endif
36 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
37 ** But if the value is zero, make it 65536.
39 ** This routine is used to extract the "offset to cell content area" value
40 ** from the header of a btree page. If the page size is 65536 and the page
41 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
42 ** This routine makes the necessary adjustment to 65536.
44 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
47 ** Values passed as the 5th argument to allocateBtreePage()
49 #define BTALLOC_ANY 0 /* Allocate any page */
50 #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
51 #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
54 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
55 ** defined, or 0 if it is. For example:
57 ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
59 #ifndef SQLITE_OMIT_AUTOVACUUM
60 #define IfNotOmitAV(expr) (expr)
61 #else
62 #define IfNotOmitAV(expr) 0
63 #endif
65 #ifndef SQLITE_OMIT_SHARED_CACHE
67 ** A list of BtShared objects that are eligible for participation
68 ** in shared cache. This variable has file scope during normal builds,
69 ** but the test harness needs to access it so we make it global for
70 ** test builds.
72 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MAIN.
74 #ifdef SQLITE_TEST
75 BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
76 #else
77 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
78 #endif
79 #endif /* SQLITE_OMIT_SHARED_CACHE */
81 #ifndef SQLITE_OMIT_SHARED_CACHE
83 ** Enable or disable the shared pager and schema features.
85 ** This routine has no effect on existing database connections.
86 ** The shared cache setting effects only future calls to
87 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
89 int sqlite3_enable_shared_cache(int enable){
90 sqlite3GlobalConfig.sharedCacheEnabled = enable;
91 return SQLITE_OK;
93 #endif
97 #ifdef SQLITE_OMIT_SHARED_CACHE
99 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
100 ** and clearAllSharedCacheTableLocks()
101 ** manipulate entries in the BtShared.pLock linked list used to store
102 ** shared-cache table level locks. If the library is compiled with the
103 ** shared-cache feature disabled, then there is only ever one user
104 ** of each BtShared structure and so this locking is not necessary.
105 ** So define the lock related functions as no-ops.
107 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
108 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
109 #define clearAllSharedCacheTableLocks(a)
110 #define downgradeAllSharedCacheTableLocks(a)
111 #define hasSharedCacheTableLock(a,b,c,d) 1
112 #define hasReadConflicts(a, b) 0
113 #endif
115 #ifdef SQLITE_DEBUG
117 ** Return and reset the seek counter for a Btree object.
119 sqlite3_uint64 sqlite3BtreeSeekCount(Btree *pBt){
120 u64 n = pBt->nSeek;
121 pBt->nSeek = 0;
122 return n;
124 #endif
127 ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
128 ** (MemPage*) as an argument. The (MemPage*) must not be NULL.
130 ** If SQLITE_DEBUG is not defined, then this macro is equivalent to
131 ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
132 ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
133 ** with the page number and filename associated with the (MemPage*).
135 #ifdef SQLITE_DEBUG
136 int corruptPageError(int lineno, MemPage *p){
137 char *zMsg;
138 sqlite3BeginBenignMalloc();
139 zMsg = sqlite3_mprintf("database corruption page %d of %s",
140 (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
142 sqlite3EndBenignMalloc();
143 if( zMsg ){
144 sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
146 sqlite3_free(zMsg);
147 return SQLITE_CORRUPT_BKPT;
149 # define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
150 #else
151 # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
152 #endif
154 #ifndef SQLITE_OMIT_SHARED_CACHE
156 #ifdef SQLITE_DEBUG
158 **** This function is only used as part of an assert() statement. ***
160 ** Check to see if pBtree holds the required locks to read or write to the
161 ** table with root page iRoot. Return 1 if it does and 0 if not.
163 ** For example, when writing to a table with root-page iRoot via
164 ** Btree connection pBtree:
166 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
168 ** When writing to an index that resides in a sharable database, the
169 ** caller should have first obtained a lock specifying the root page of
170 ** the corresponding table. This makes things a bit more complicated,
171 ** as this module treats each table as a separate structure. To determine
172 ** the table corresponding to the index being written, this
173 ** function has to search through the database schema.
175 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
176 ** hold a write-lock on the schema table (root page 1). This is also
177 ** acceptable.
179 static int hasSharedCacheTableLock(
180 Btree *pBtree, /* Handle that must hold lock */
181 Pgno iRoot, /* Root page of b-tree */
182 int isIndex, /* True if iRoot is the root of an index b-tree */
183 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
185 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
186 Pgno iTab = 0;
187 BtLock *pLock;
189 /* If this database is not shareable, or if the client is reading
190 ** and has the read-uncommitted flag set, then no lock is required.
191 ** Return true immediately.
193 if( (pBtree->sharable==0)
194 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
196 return 1;
199 /* If the client is reading or writing an index and the schema is
200 ** not loaded, then it is too difficult to actually check to see if
201 ** the correct locks are held. So do not bother - just return true.
202 ** This case does not come up very often anyhow.
204 if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
205 return 1;
208 /* Figure out the root-page that the lock should be held on. For table
209 ** b-trees, this is just the root page of the b-tree being read or
210 ** written. For index b-trees, it is the root page of the associated
211 ** table. */
212 if( isIndex ){
213 HashElem *p;
214 int bSeen = 0;
215 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
216 Index *pIdx = (Index *)sqliteHashData(p);
217 if( pIdx->tnum==(int)iRoot ){
218 if( bSeen ){
219 /* Two or more indexes share the same root page. There must
220 ** be imposter tables. So just return true. The assert is not
221 ** useful in that case. */
222 return 1;
224 iTab = pIdx->pTable->tnum;
225 bSeen = 1;
228 }else{
229 iTab = iRoot;
232 /* Search for the required lock. Either a write-lock on root-page iTab, a
233 ** write-lock on the schema table, or (if the client is reading) a
234 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
235 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
236 if( pLock->pBtree==pBtree
237 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
238 && pLock->eLock>=eLockType
240 return 1;
244 /* Failed to find the required lock. */
245 return 0;
247 #endif /* SQLITE_DEBUG */
249 #ifdef SQLITE_DEBUG
251 **** This function may be used as part of assert() statements only. ****
253 ** Return true if it would be illegal for pBtree to write into the
254 ** table or index rooted at iRoot because other shared connections are
255 ** simultaneously reading that same table or index.
257 ** It is illegal for pBtree to write if some other Btree object that
258 ** shares the same BtShared object is currently reading or writing
259 ** the iRoot table. Except, if the other Btree object has the
260 ** read-uncommitted flag set, then it is OK for the other object to
261 ** have a read cursor.
263 ** For example, before writing to any part of the table or index
264 ** rooted at page iRoot, one should call:
266 ** assert( !hasReadConflicts(pBtree, iRoot) );
268 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
269 BtCursor *p;
270 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
271 if( p->pgnoRoot==iRoot
272 && p->pBtree!=pBtree
273 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
275 return 1;
278 return 0;
280 #endif /* #ifdef SQLITE_DEBUG */
283 ** Query to see if Btree handle p may obtain a lock of type eLock
284 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
285 ** SQLITE_OK if the lock may be obtained (by calling
286 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
288 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
289 BtShared *pBt = p->pBt;
290 BtLock *pIter;
292 assert( sqlite3BtreeHoldsMutex(p) );
293 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
294 assert( p->db!=0 );
295 assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
297 /* If requesting a write-lock, then the Btree must have an open write
298 ** transaction on this file. And, obviously, for this to be so there
299 ** must be an open write transaction on the file itself.
301 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
302 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
304 /* This routine is a no-op if the shared-cache is not enabled */
305 if( !p->sharable ){
306 return SQLITE_OK;
309 /* If some other connection is holding an exclusive lock, the
310 ** requested lock may not be obtained.
312 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
313 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
314 return SQLITE_LOCKED_SHAREDCACHE;
317 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
318 /* The condition (pIter->eLock!=eLock) in the following if(...)
319 ** statement is a simplification of:
321 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
323 ** since we know that if eLock==WRITE_LOCK, then no other connection
324 ** may hold a WRITE_LOCK on any table in this file (since there can
325 ** only be a single writer).
327 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
328 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
329 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
330 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
331 if( eLock==WRITE_LOCK ){
332 assert( p==pBt->pWriter );
333 pBt->btsFlags |= BTS_PENDING;
335 return SQLITE_LOCKED_SHAREDCACHE;
338 return SQLITE_OK;
340 #endif /* !SQLITE_OMIT_SHARED_CACHE */
342 #ifndef SQLITE_OMIT_SHARED_CACHE
344 ** Add a lock on the table with root-page iTable to the shared-btree used
345 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
346 ** WRITE_LOCK.
348 ** This function assumes the following:
350 ** (a) The specified Btree object p is connected to a sharable
351 ** database (one with the BtShared.sharable flag set), and
353 ** (b) No other Btree objects hold a lock that conflicts
354 ** with the requested lock (i.e. querySharedCacheTableLock() has
355 ** already been called and returned SQLITE_OK).
357 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
358 ** is returned if a malloc attempt fails.
360 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
361 BtShared *pBt = p->pBt;
362 BtLock *pLock = 0;
363 BtLock *pIter;
365 assert( sqlite3BtreeHoldsMutex(p) );
366 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
367 assert( p->db!=0 );
369 /* A connection with the read-uncommitted flag set will never try to
370 ** obtain a read-lock using this function. The only read-lock obtained
371 ** by a connection in read-uncommitted mode is on the sqlite_schema
372 ** table, and that lock is obtained in BtreeBeginTrans(). */
373 assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
375 /* This function should only be called on a sharable b-tree after it
376 ** has been determined that no other b-tree holds a conflicting lock. */
377 assert( p->sharable );
378 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
380 /* First search the list for an existing lock on this table. */
381 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
382 if( pIter->iTable==iTable && pIter->pBtree==p ){
383 pLock = pIter;
384 break;
388 /* If the above search did not find a BtLock struct associating Btree p
389 ** with table iTable, allocate one and link it into the list.
391 if( !pLock ){
392 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
393 if( !pLock ){
394 return SQLITE_NOMEM_BKPT;
396 pLock->iTable = iTable;
397 pLock->pBtree = p;
398 pLock->pNext = pBt->pLock;
399 pBt->pLock = pLock;
402 /* Set the BtLock.eLock variable to the maximum of the current lock
403 ** and the requested lock. This means if a write-lock was already held
404 ** and a read-lock requested, we don't incorrectly downgrade the lock.
406 assert( WRITE_LOCK>READ_LOCK );
407 if( eLock>pLock->eLock ){
408 pLock->eLock = eLock;
411 return SQLITE_OK;
413 #endif /* !SQLITE_OMIT_SHARED_CACHE */
415 #ifndef SQLITE_OMIT_SHARED_CACHE
417 ** Release all the table locks (locks obtained via calls to
418 ** the setSharedCacheTableLock() procedure) held by Btree object p.
420 ** This function assumes that Btree p has an open read or write
421 ** transaction. If it does not, then the BTS_PENDING flag
422 ** may be incorrectly cleared.
424 static void clearAllSharedCacheTableLocks(Btree *p){
425 BtShared *pBt = p->pBt;
426 BtLock **ppIter = &pBt->pLock;
428 assert( sqlite3BtreeHoldsMutex(p) );
429 assert( p->sharable || 0==*ppIter );
430 assert( p->inTrans>0 );
432 while( *ppIter ){
433 BtLock *pLock = *ppIter;
434 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
435 assert( pLock->pBtree->inTrans>=pLock->eLock );
436 if( pLock->pBtree==p ){
437 *ppIter = pLock->pNext;
438 assert( pLock->iTable!=1 || pLock==&p->lock );
439 if( pLock->iTable!=1 ){
440 sqlite3_free(pLock);
442 }else{
443 ppIter = &pLock->pNext;
447 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
448 if( pBt->pWriter==p ){
449 pBt->pWriter = 0;
450 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
451 }else if( pBt->nTransaction==2 ){
452 /* This function is called when Btree p is concluding its
453 ** transaction. If there currently exists a writer, and p is not
454 ** that writer, then the number of locks held by connections other
455 ** than the writer must be about to drop to zero. In this case
456 ** set the BTS_PENDING flag to 0.
458 ** If there is not currently a writer, then BTS_PENDING must
459 ** be zero already. So this next line is harmless in that case.
461 pBt->btsFlags &= ~BTS_PENDING;
466 ** This function changes all write-locks held by Btree p into read-locks.
468 static void downgradeAllSharedCacheTableLocks(Btree *p){
469 BtShared *pBt = p->pBt;
470 if( pBt->pWriter==p ){
471 BtLock *pLock;
472 pBt->pWriter = 0;
473 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
474 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
475 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
476 pLock->eLock = READ_LOCK;
481 #endif /* SQLITE_OMIT_SHARED_CACHE */
483 static void releasePage(MemPage *pPage); /* Forward reference */
484 static void releasePageOne(MemPage *pPage); /* Forward reference */
485 static void releasePageNotNull(MemPage *pPage); /* Forward reference */
488 ***** This routine is used inside of assert() only ****
490 ** Verify that the cursor holds the mutex on its BtShared
492 #ifdef SQLITE_DEBUG
493 static int cursorHoldsMutex(BtCursor *p){
494 return sqlite3_mutex_held(p->pBt->mutex);
497 /* Verify that the cursor and the BtShared agree about what is the current
498 ** database connetion. This is important in shared-cache mode. If the database
499 ** connection pointers get out-of-sync, it is possible for routines like
500 ** btreeInitPage() to reference an stale connection pointer that references a
501 ** a connection that has already closed. This routine is used inside assert()
502 ** statements only and for the purpose of double-checking that the btree code
503 ** does keep the database connection pointers up-to-date.
505 static int cursorOwnsBtShared(BtCursor *p){
506 assert( cursorHoldsMutex(p) );
507 return (p->pBtree->db==p->pBt->db);
509 #endif
512 ** Invalidate the overflow cache of the cursor passed as the first argument.
513 ** on the shared btree structure pBt.
515 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
518 ** Invalidate the overflow page-list cache for all cursors opened
519 ** on the shared btree structure pBt.
521 static void invalidateAllOverflowCache(BtShared *pBt){
522 BtCursor *p;
523 assert( sqlite3_mutex_held(pBt->mutex) );
524 for(p=pBt->pCursor; p; p=p->pNext){
525 invalidateOverflowCache(p);
529 #ifndef SQLITE_OMIT_INCRBLOB
531 ** This function is called before modifying the contents of a table
532 ** to invalidate any incrblob cursors that are open on the
533 ** row or one of the rows being modified.
535 ** If argument isClearTable is true, then the entire contents of the
536 ** table is about to be deleted. In this case invalidate all incrblob
537 ** cursors open on any row within the table with root-page pgnoRoot.
539 ** Otherwise, if argument isClearTable is false, then the row with
540 ** rowid iRow is being replaced or deleted. In this case invalidate
541 ** only those incrblob cursors open on that specific row.
543 static void invalidateIncrblobCursors(
544 Btree *pBtree, /* The database file to check */
545 Pgno pgnoRoot, /* The table that might be changing */
546 i64 iRow, /* The rowid that might be changing */
547 int isClearTable /* True if all rows are being deleted */
549 BtCursor *p;
550 assert( pBtree->hasIncrblobCur );
551 assert( sqlite3BtreeHoldsMutex(pBtree) );
552 pBtree->hasIncrblobCur = 0;
553 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
554 if( (p->curFlags & BTCF_Incrblob)!=0 ){
555 pBtree->hasIncrblobCur = 1;
556 if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
557 p->eState = CURSOR_INVALID;
563 #else
564 /* Stub function when INCRBLOB is omitted */
565 #define invalidateIncrblobCursors(w,x,y,z)
566 #endif /* SQLITE_OMIT_INCRBLOB */
569 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
570 ** when a page that previously contained data becomes a free-list leaf
571 ** page.
573 ** The BtShared.pHasContent bitvec exists to work around an obscure
574 ** bug caused by the interaction of two useful IO optimizations surrounding
575 ** free-list leaf pages:
577 ** 1) When all data is deleted from a page and the page becomes
578 ** a free-list leaf page, the page is not written to the database
579 ** (as free-list leaf pages contain no meaningful data). Sometimes
580 ** such a page is not even journalled (as it will not be modified,
581 ** why bother journalling it?).
583 ** 2) When a free-list leaf page is reused, its content is not read
584 ** from the database or written to the journal file (why should it
585 ** be, if it is not at all meaningful?).
587 ** By themselves, these optimizations work fine and provide a handy
588 ** performance boost to bulk delete or insert operations. However, if
589 ** a page is moved to the free-list and then reused within the same
590 ** transaction, a problem comes up. If the page is not journalled when
591 ** it is moved to the free-list and it is also not journalled when it
592 ** is extracted from the free-list and reused, then the original data
593 ** may be lost. In the event of a rollback, it may not be possible
594 ** to restore the database to its original configuration.
596 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
597 ** moved to become a free-list leaf page, the corresponding bit is
598 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
599 ** optimization 2 above is omitted if the corresponding bit is already
600 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
601 ** at the end of every transaction.
603 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
604 int rc = SQLITE_OK;
605 if( !pBt->pHasContent ){
606 assert( pgno<=pBt->nPage );
607 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
608 if( !pBt->pHasContent ){
609 rc = SQLITE_NOMEM_BKPT;
612 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
613 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
615 return rc;
619 ** Query the BtShared.pHasContent vector.
621 ** This function is called when a free-list leaf page is removed from the
622 ** free-list for reuse. It returns false if it is safe to retrieve the
623 ** page from the pager layer with the 'no-content' flag set. True otherwise.
625 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
626 Bitvec *p = pBt->pHasContent;
627 return p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTestNotNull(p, pgno));
631 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
632 ** invoked at the conclusion of each write-transaction.
634 static void btreeClearHasContent(BtShared *pBt){
635 sqlite3BitvecDestroy(pBt->pHasContent);
636 pBt->pHasContent = 0;
640 ** Release all of the apPage[] pages for a cursor.
642 static void btreeReleaseAllCursorPages(BtCursor *pCur){
643 int i;
644 if( pCur->iPage>=0 ){
645 for(i=0; i<pCur->iPage; i++){
646 releasePageNotNull(pCur->apPage[i]);
648 releasePageNotNull(pCur->pPage);
649 pCur->iPage = -1;
654 ** The cursor passed as the only argument must point to a valid entry
655 ** when this function is called (i.e. have eState==CURSOR_VALID). This
656 ** function saves the current cursor key in variables pCur->nKey and
657 ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
658 ** code otherwise.
660 ** If the cursor is open on an intkey table, then the integer key
661 ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
662 ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
663 ** set to point to a malloced buffer pCur->nKey bytes in size containing
664 ** the key.
666 static int saveCursorKey(BtCursor *pCur){
667 int rc = SQLITE_OK;
668 assert( CURSOR_VALID==pCur->eState );
669 assert( 0==pCur->pKey );
670 assert( cursorHoldsMutex(pCur) );
672 if( pCur->curIntKey ){
673 /* Only the rowid is required for a table btree */
674 pCur->nKey = sqlite3BtreeIntegerKey(pCur);
675 }else{
676 /* For an index btree, save the complete key content. It is possible
677 ** that the current key is corrupt. In that case, it is possible that
678 ** the sqlite3VdbeRecordUnpack() function may overread the buffer by
679 ** up to the size of 1 varint plus 1 8-byte value when the cursor
680 ** position is restored. Hence the 17 bytes of padding allocated
681 ** below. */
682 void *pKey;
683 pCur->nKey = sqlite3BtreePayloadSize(pCur);
684 pKey = sqlite3Malloc( pCur->nKey + 9 + 8 );
685 if( pKey ){
686 rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
687 if( rc==SQLITE_OK ){
688 memset(((u8*)pKey)+pCur->nKey, 0, 9+8);
689 pCur->pKey = pKey;
690 }else{
691 sqlite3_free(pKey);
693 }else{
694 rc = SQLITE_NOMEM_BKPT;
697 assert( !pCur->curIntKey || !pCur->pKey );
698 return rc;
702 ** Save the current cursor position in the variables BtCursor.nKey
703 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
705 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
706 ** prior to calling this routine.
708 static int saveCursorPosition(BtCursor *pCur){
709 int rc;
711 assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
712 assert( 0==pCur->pKey );
713 assert( cursorHoldsMutex(pCur) );
715 if( pCur->curFlags & BTCF_Pinned ){
716 return SQLITE_CONSTRAINT_PINNED;
718 if( pCur->eState==CURSOR_SKIPNEXT ){
719 pCur->eState = CURSOR_VALID;
720 }else{
721 pCur->skipNext = 0;
724 rc = saveCursorKey(pCur);
725 if( rc==SQLITE_OK ){
726 btreeReleaseAllCursorPages(pCur);
727 pCur->eState = CURSOR_REQUIRESEEK;
730 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
731 return rc;
734 /* Forward reference */
735 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
738 ** Save the positions of all cursors (except pExcept) that are open on
739 ** the table with root-page iRoot. "Saving the cursor position" means that
740 ** the location in the btree is remembered in such a way that it can be
741 ** moved back to the same spot after the btree has been modified. This
742 ** routine is called just before cursor pExcept is used to modify the
743 ** table, for example in BtreeDelete() or BtreeInsert().
745 ** If there are two or more cursors on the same btree, then all such
746 ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
747 ** routine enforces that rule. This routine only needs to be called in
748 ** the uncommon case when pExpect has the BTCF_Multiple flag set.
750 ** If pExpect!=NULL and if no other cursors are found on the same root-page,
751 ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
752 ** pointless call to this routine.
754 ** Implementation note: This routine merely checks to see if any cursors
755 ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
756 ** event that cursors are in need to being saved.
758 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
759 BtCursor *p;
760 assert( sqlite3_mutex_held(pBt->mutex) );
761 assert( pExcept==0 || pExcept->pBt==pBt );
762 for(p=pBt->pCursor; p; p=p->pNext){
763 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
765 if( p ) return saveCursorsOnList(p, iRoot, pExcept);
766 if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
767 return SQLITE_OK;
770 /* This helper routine to saveAllCursors does the actual work of saving
771 ** the cursors if and when a cursor is found that actually requires saving.
772 ** The common case is that no cursors need to be saved, so this routine is
773 ** broken out from its caller to avoid unnecessary stack pointer movement.
775 static int SQLITE_NOINLINE saveCursorsOnList(
776 BtCursor *p, /* The first cursor that needs saving */
777 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
778 BtCursor *pExcept /* Do not save this cursor */
781 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
782 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
783 int rc = saveCursorPosition(p);
784 if( SQLITE_OK!=rc ){
785 return rc;
787 }else{
788 testcase( p->iPage>=0 );
789 btreeReleaseAllCursorPages(p);
792 p = p->pNext;
793 }while( p );
794 return SQLITE_OK;
798 ** Clear the current cursor position.
800 void sqlite3BtreeClearCursor(BtCursor *pCur){
801 assert( cursorHoldsMutex(pCur) );
802 sqlite3_free(pCur->pKey);
803 pCur->pKey = 0;
804 pCur->eState = CURSOR_INVALID;
808 ** In this version of BtreeMoveto, pKey is a packed index record
809 ** such as is generated by the OP_MakeRecord opcode. Unpack the
810 ** record and then call BtreeMovetoUnpacked() to do the work.
812 static int btreeMoveto(
813 BtCursor *pCur, /* Cursor open on the btree to be searched */
814 const void *pKey, /* Packed key if the btree is an index */
815 i64 nKey, /* Integer key for tables. Size of pKey for indices */
816 int bias, /* Bias search to the high end */
817 int *pRes /* Write search results here */
819 int rc; /* Status code */
820 UnpackedRecord *pIdxKey; /* Unpacked index key */
822 if( pKey ){
823 KeyInfo *pKeyInfo = pCur->pKeyInfo;
824 assert( nKey==(i64)(int)nKey );
825 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
826 if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
827 sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey);
828 if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){
829 rc = SQLITE_CORRUPT_BKPT;
830 goto moveto_done;
832 }else{
833 pIdxKey = 0;
835 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
836 moveto_done:
837 if( pIdxKey ){
838 sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
840 return rc;
844 ** Restore the cursor to the position it was in (or as close to as possible)
845 ** when saveCursorPosition() was called. Note that this call deletes the
846 ** saved position info stored by saveCursorPosition(), so there can be
847 ** at most one effective restoreCursorPosition() call after each
848 ** saveCursorPosition().
850 static int btreeRestoreCursorPosition(BtCursor *pCur){
851 int rc;
852 int skipNext = 0;
853 assert( cursorOwnsBtShared(pCur) );
854 assert( pCur->eState>=CURSOR_REQUIRESEEK );
855 if( pCur->eState==CURSOR_FAULT ){
856 return pCur->skipNext;
858 pCur->eState = CURSOR_INVALID;
859 if( sqlite3FaultSim(410) ){
860 rc = SQLITE_IOERR;
861 }else{
862 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
864 if( rc==SQLITE_OK ){
865 sqlite3_free(pCur->pKey);
866 pCur->pKey = 0;
867 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
868 if( skipNext ) pCur->skipNext = skipNext;
869 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
870 pCur->eState = CURSOR_SKIPNEXT;
873 return rc;
876 #define restoreCursorPosition(p) \
877 (p->eState>=CURSOR_REQUIRESEEK ? \
878 btreeRestoreCursorPosition(p) : \
879 SQLITE_OK)
882 ** Determine whether or not a cursor has moved from the position where
883 ** it was last placed, or has been invalidated for any other reason.
884 ** Cursors can move when the row they are pointing at is deleted out
885 ** from under them, for example. Cursor might also move if a btree
886 ** is rebalanced.
888 ** Calling this routine with a NULL cursor pointer returns false.
890 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
891 ** back to where it ought to be if this routine returns true.
893 int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
894 assert( EIGHT_BYTE_ALIGNMENT(pCur)
895 || pCur==sqlite3BtreeFakeValidCursor() );
896 assert( offsetof(BtCursor, eState)==0 );
897 assert( sizeof(pCur->eState)==1 );
898 return CURSOR_VALID != *(u8*)pCur;
902 ** Return a pointer to a fake BtCursor object that will always answer
903 ** false to the sqlite3BtreeCursorHasMoved() routine above. The fake
904 ** cursor returned must not be used with any other Btree interface.
906 BtCursor *sqlite3BtreeFakeValidCursor(void){
907 static u8 fakeCursor = CURSOR_VALID;
908 assert( offsetof(BtCursor, eState)==0 );
909 return (BtCursor*)&fakeCursor;
913 ** This routine restores a cursor back to its original position after it
914 ** has been moved by some outside activity (such as a btree rebalance or
915 ** a row having been deleted out from under the cursor).
917 ** On success, the *pDifferentRow parameter is false if the cursor is left
918 ** pointing at exactly the same row. *pDifferntRow is the row the cursor
919 ** was pointing to has been deleted, forcing the cursor to point to some
920 ** nearby row.
922 ** This routine should only be called for a cursor that just returned
923 ** TRUE from sqlite3BtreeCursorHasMoved().
925 int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
926 int rc;
928 assert( pCur!=0 );
929 assert( pCur->eState!=CURSOR_VALID );
930 rc = restoreCursorPosition(pCur);
931 if( rc ){
932 *pDifferentRow = 1;
933 return rc;
935 if( pCur->eState!=CURSOR_VALID ){
936 *pDifferentRow = 1;
937 }else{
938 *pDifferentRow = 0;
940 return SQLITE_OK;
943 #ifdef SQLITE_ENABLE_CURSOR_HINTS
945 ** Provide hints to the cursor. The particular hint given (and the type
946 ** and number of the varargs parameters) is determined by the eHintType
947 ** parameter. See the definitions of the BTREE_HINT_* macros for details.
949 void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
950 /* Used only by system that substitute their own storage engine */
952 #endif
955 ** Provide flag hints to the cursor.
957 void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
958 assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
959 pCur->hints = x;
963 #ifndef SQLITE_OMIT_AUTOVACUUM
965 ** Given a page number of a regular database page, return the page
966 ** number for the pointer-map page that contains the entry for the
967 ** input page number.
969 ** Return 0 (not a valid page) for pgno==1 since there is
970 ** no pointer map associated with page 1. The integrity_check logic
971 ** requires that ptrmapPageno(*,1)!=1.
973 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
974 int nPagesPerMapPage;
975 Pgno iPtrMap, ret;
976 assert( sqlite3_mutex_held(pBt->mutex) );
977 if( pgno<2 ) return 0;
978 nPagesPerMapPage = (pBt->usableSize/5)+1;
979 iPtrMap = (pgno-2)/nPagesPerMapPage;
980 ret = (iPtrMap*nPagesPerMapPage) + 2;
981 if( ret==PENDING_BYTE_PAGE(pBt) ){
982 ret++;
984 return ret;
988 ** Write an entry into the pointer map.
990 ** This routine updates the pointer map entry for page number 'key'
991 ** so that it maps to type 'eType' and parent page number 'pgno'.
993 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
994 ** a no-op. If an error occurs, the appropriate error code is written
995 ** into *pRC.
997 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
998 DbPage *pDbPage; /* The pointer map page */
999 u8 *pPtrmap; /* The pointer map data */
1000 Pgno iPtrmap; /* The pointer map page number */
1001 int offset; /* Offset in pointer map page */
1002 int rc; /* Return code from subfunctions */
1004 if( *pRC ) return;
1006 assert( sqlite3_mutex_held(pBt->mutex) );
1007 /* The super-journal page number must never be used as a pointer map page */
1008 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
1010 assert( pBt->autoVacuum );
1011 if( key==0 ){
1012 *pRC = SQLITE_CORRUPT_BKPT;
1013 return;
1015 iPtrmap = PTRMAP_PAGENO(pBt, key);
1016 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
1017 if( rc!=SQLITE_OK ){
1018 *pRC = rc;
1019 return;
1021 if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){
1022 /* The first byte of the extra data is the MemPage.isInit byte.
1023 ** If that byte is set, it means this page is also being used
1024 ** as a btree page. */
1025 *pRC = SQLITE_CORRUPT_BKPT;
1026 goto ptrmap_exit;
1028 offset = PTRMAP_PTROFFSET(iPtrmap, key);
1029 if( offset<0 ){
1030 *pRC = SQLITE_CORRUPT_BKPT;
1031 goto ptrmap_exit;
1033 assert( offset <= (int)pBt->usableSize-5 );
1034 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1036 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
1037 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
1038 *pRC= rc = sqlite3PagerWrite(pDbPage);
1039 if( rc==SQLITE_OK ){
1040 pPtrmap[offset] = eType;
1041 put4byte(&pPtrmap[offset+1], parent);
1045 ptrmap_exit:
1046 sqlite3PagerUnref(pDbPage);
1050 ** Read an entry from the pointer map.
1052 ** This routine retrieves the pointer map entry for page 'key', writing
1053 ** the type and parent page number to *pEType and *pPgno respectively.
1054 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
1056 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
1057 DbPage *pDbPage; /* The pointer map page */
1058 int iPtrmap; /* Pointer map page index */
1059 u8 *pPtrmap; /* Pointer map page data */
1060 int offset; /* Offset of entry in pointer map */
1061 int rc;
1063 assert( sqlite3_mutex_held(pBt->mutex) );
1065 iPtrmap = PTRMAP_PAGENO(pBt, key);
1066 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
1067 if( rc!=0 ){
1068 return rc;
1070 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1072 offset = PTRMAP_PTROFFSET(iPtrmap, key);
1073 if( offset<0 ){
1074 sqlite3PagerUnref(pDbPage);
1075 return SQLITE_CORRUPT_BKPT;
1077 assert( offset <= (int)pBt->usableSize-5 );
1078 assert( pEType!=0 );
1079 *pEType = pPtrmap[offset];
1080 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
1082 sqlite3PagerUnref(pDbPage);
1083 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
1084 return SQLITE_OK;
1087 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
1088 #define ptrmapPut(w,x,y,z,rc)
1089 #define ptrmapGet(w,x,y,z) SQLITE_OK
1090 #define ptrmapPutOvflPtr(x, y, z, rc)
1091 #endif
1094 ** Given a btree page and a cell index (0 means the first cell on
1095 ** the page, 1 means the second cell, and so forth) return a pointer
1096 ** to the cell content.
1098 ** findCellPastPtr() does the same except it skips past the initial
1099 ** 4-byte child pointer found on interior pages, if there is one.
1101 ** This routine works only for pages that do not contain overflow cells.
1103 #define findCell(P,I) \
1104 ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1105 #define findCellPastPtr(P,I) \
1106 ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1110 ** This is common tail processing for btreeParseCellPtr() and
1111 ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
1112 ** on a single B-tree page. Make necessary adjustments to the CellInfo
1113 ** structure.
1115 static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
1116 MemPage *pPage, /* Page containing the cell */
1117 u8 *pCell, /* Pointer to the cell text. */
1118 CellInfo *pInfo /* Fill in this structure */
1120 /* If the payload will not fit completely on the local page, we have
1121 ** to decide how much to store locally and how much to spill onto
1122 ** overflow pages. The strategy is to minimize the amount of unused
1123 ** space on overflow pages while keeping the amount of local storage
1124 ** in between minLocal and maxLocal.
1126 ** Warning: changing the way overflow payload is distributed in any
1127 ** way will result in an incompatible file format.
1129 int minLocal; /* Minimum amount of payload held locally */
1130 int maxLocal; /* Maximum amount of payload held locally */
1131 int surplus; /* Overflow payload available for local storage */
1133 minLocal = pPage->minLocal;
1134 maxLocal = pPage->maxLocal;
1135 surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
1136 testcase( surplus==maxLocal );
1137 testcase( surplus==maxLocal+1 );
1138 if( surplus <= maxLocal ){
1139 pInfo->nLocal = (u16)surplus;
1140 }else{
1141 pInfo->nLocal = (u16)minLocal;
1143 pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
1147 ** Given a record with nPayload bytes of payload stored within btree
1148 ** page pPage, return the number of bytes of payload stored locally.
1150 static int btreePayloadToLocal(MemPage *pPage, i64 nPayload){
1151 int maxLocal; /* Maximum amount of payload held locally */
1152 maxLocal = pPage->maxLocal;
1153 if( nPayload<=maxLocal ){
1154 return nPayload;
1155 }else{
1156 int minLocal; /* Minimum amount of payload held locally */
1157 int surplus; /* Overflow payload available for local storage */
1158 minLocal = pPage->minLocal;
1159 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize-4);
1160 return ( surplus <= maxLocal ) ? surplus : minLocal;
1165 ** The following routines are implementations of the MemPage.xParseCell()
1166 ** method.
1168 ** Parse a cell content block and fill in the CellInfo structure.
1170 ** btreeParseCellPtr() => table btree leaf nodes
1171 ** btreeParseCellNoPayload() => table btree internal nodes
1172 ** btreeParseCellPtrIndex() => index btree nodes
1174 ** There is also a wrapper function btreeParseCell() that works for
1175 ** all MemPage types and that references the cell by index rather than
1176 ** by pointer.
1178 static void btreeParseCellPtrNoPayload(
1179 MemPage *pPage, /* Page containing the cell */
1180 u8 *pCell, /* Pointer to the cell text. */
1181 CellInfo *pInfo /* Fill in this structure */
1183 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1184 assert( pPage->leaf==0 );
1185 assert( pPage->childPtrSize==4 );
1186 #ifndef SQLITE_DEBUG
1187 UNUSED_PARAMETER(pPage);
1188 #endif
1189 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
1190 pInfo->nPayload = 0;
1191 pInfo->nLocal = 0;
1192 pInfo->pPayload = 0;
1193 return;
1195 static void btreeParseCellPtr(
1196 MemPage *pPage, /* Page containing the cell */
1197 u8 *pCell, /* Pointer to the cell text. */
1198 CellInfo *pInfo /* Fill in this structure */
1200 u8 *pIter; /* For scanning through pCell */
1201 u32 nPayload; /* Number of bytes of cell payload */
1202 u64 iKey; /* Extracted Key value */
1204 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1205 assert( pPage->leaf==0 || pPage->leaf==1 );
1206 assert( pPage->intKeyLeaf );
1207 assert( pPage->childPtrSize==0 );
1208 pIter = pCell;
1210 /* The next block of code is equivalent to:
1212 ** pIter += getVarint32(pIter, nPayload);
1214 ** The code is inlined to avoid a function call.
1216 nPayload = *pIter;
1217 if( nPayload>=0x80 ){
1218 u8 *pEnd = &pIter[8];
1219 nPayload &= 0x7f;
1221 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1222 }while( (*pIter)>=0x80 && pIter<pEnd );
1224 pIter++;
1226 /* The next block of code is equivalent to:
1228 ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
1230 ** The code is inlined to avoid a function call.
1232 iKey = *pIter;
1233 if( iKey>=0x80 ){
1234 u8 *pEnd = &pIter[7];
1235 iKey &= 0x7f;
1236 while(1){
1237 iKey = (iKey<<7) | (*++pIter & 0x7f);
1238 if( (*pIter)<0x80 ) break;
1239 if( pIter>=pEnd ){
1240 iKey = (iKey<<8) | *++pIter;
1241 break;
1245 pIter++;
1247 pInfo->nKey = *(i64*)&iKey;
1248 pInfo->nPayload = nPayload;
1249 pInfo->pPayload = pIter;
1250 testcase( nPayload==pPage->maxLocal );
1251 testcase( nPayload==pPage->maxLocal+1 );
1252 if( nPayload<=pPage->maxLocal ){
1253 /* This is the (easy) common case where the entire payload fits
1254 ** on the local page. No overflow is required.
1256 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1257 if( pInfo->nSize<4 ) pInfo->nSize = 4;
1258 pInfo->nLocal = (u16)nPayload;
1259 }else{
1260 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1263 static void btreeParseCellPtrIndex(
1264 MemPage *pPage, /* Page containing the cell */
1265 u8 *pCell, /* Pointer to the cell text. */
1266 CellInfo *pInfo /* Fill in this structure */
1268 u8 *pIter; /* For scanning through pCell */
1269 u32 nPayload; /* Number of bytes of cell payload */
1271 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1272 assert( pPage->leaf==0 || pPage->leaf==1 );
1273 assert( pPage->intKeyLeaf==0 );
1274 pIter = pCell + pPage->childPtrSize;
1275 nPayload = *pIter;
1276 if( nPayload>=0x80 ){
1277 u8 *pEnd = &pIter[8];
1278 nPayload &= 0x7f;
1280 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1281 }while( *(pIter)>=0x80 && pIter<pEnd );
1283 pIter++;
1284 pInfo->nKey = nPayload;
1285 pInfo->nPayload = nPayload;
1286 pInfo->pPayload = pIter;
1287 testcase( nPayload==pPage->maxLocal );
1288 testcase( nPayload==pPage->maxLocal+1 );
1289 if( nPayload<=pPage->maxLocal ){
1290 /* This is the (easy) common case where the entire payload fits
1291 ** on the local page. No overflow is required.
1293 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1294 if( pInfo->nSize<4 ) pInfo->nSize = 4;
1295 pInfo->nLocal = (u16)nPayload;
1296 }else{
1297 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1300 static void btreeParseCell(
1301 MemPage *pPage, /* Page containing the cell */
1302 int iCell, /* The cell index. First cell is 0 */
1303 CellInfo *pInfo /* Fill in this structure */
1305 pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
1309 ** The following routines are implementations of the MemPage.xCellSize
1310 ** method.
1312 ** Compute the total number of bytes that a Cell needs in the cell
1313 ** data area of the btree-page. The return number includes the cell
1314 ** data header and the local payload, but not any overflow page or
1315 ** the space used by the cell pointer.
1317 ** cellSizePtrNoPayload() => table internal nodes
1318 ** cellSizePtr() => all index nodes & table leaf nodes
1320 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
1321 u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
1322 u8 *pEnd; /* End mark for a varint */
1323 u32 nSize; /* Size value to return */
1325 #ifdef SQLITE_DEBUG
1326 /* The value returned by this function should always be the same as
1327 ** the (CellInfo.nSize) value found by doing a full parse of the
1328 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1329 ** this function verifies that this invariant is not violated. */
1330 CellInfo debuginfo;
1331 pPage->xParseCell(pPage, pCell, &debuginfo);
1332 #endif
1334 nSize = *pIter;
1335 if( nSize>=0x80 ){
1336 pEnd = &pIter[8];
1337 nSize &= 0x7f;
1339 nSize = (nSize<<7) | (*++pIter & 0x7f);
1340 }while( *(pIter)>=0x80 && pIter<pEnd );
1342 pIter++;
1343 if( pPage->intKey ){
1344 /* pIter now points at the 64-bit integer key value, a variable length
1345 ** integer. The following block moves pIter to point at the first byte
1346 ** past the end of the key value. */
1347 pEnd = &pIter[9];
1348 while( (*pIter++)&0x80 && pIter<pEnd );
1350 testcase( nSize==pPage->maxLocal );
1351 testcase( nSize==pPage->maxLocal+1 );
1352 if( nSize<=pPage->maxLocal ){
1353 nSize += (u32)(pIter - pCell);
1354 if( nSize<4 ) nSize = 4;
1355 }else{
1356 int minLocal = pPage->minLocal;
1357 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1358 testcase( nSize==pPage->maxLocal );
1359 testcase( nSize==pPage->maxLocal+1 );
1360 if( nSize>pPage->maxLocal ){
1361 nSize = minLocal;
1363 nSize += 4 + (u16)(pIter - pCell);
1365 assert( nSize==debuginfo.nSize || CORRUPT_DB );
1366 return (u16)nSize;
1368 static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
1369 u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
1370 u8 *pEnd; /* End mark for a varint */
1372 #ifdef SQLITE_DEBUG
1373 /* The value returned by this function should always be the same as
1374 ** the (CellInfo.nSize) value found by doing a full parse of the
1375 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1376 ** this function verifies that this invariant is not violated. */
1377 CellInfo debuginfo;
1378 pPage->xParseCell(pPage, pCell, &debuginfo);
1379 #else
1380 UNUSED_PARAMETER(pPage);
1381 #endif
1383 assert( pPage->childPtrSize==4 );
1384 pEnd = pIter + 9;
1385 while( (*pIter++)&0x80 && pIter<pEnd );
1386 assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
1387 return (u16)(pIter - pCell);
1391 #ifdef SQLITE_DEBUG
1392 /* This variation on cellSizePtr() is used inside of assert() statements
1393 ** only. */
1394 static u16 cellSize(MemPage *pPage, int iCell){
1395 return pPage->xCellSize(pPage, findCell(pPage, iCell));
1397 #endif
1399 #ifndef SQLITE_OMIT_AUTOVACUUM
1401 ** The cell pCell is currently part of page pSrc but will ultimately be part
1402 ** of pPage. (pSrc and pPager are often the same.) If pCell contains a
1403 ** pointer to an overflow page, insert an entry into the pointer-map for
1404 ** the overflow page that will be valid after pCell has been moved to pPage.
1406 static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){
1407 CellInfo info;
1408 if( *pRC ) return;
1409 assert( pCell!=0 );
1410 pPage->xParseCell(pPage, pCell, &info);
1411 if( info.nLocal<info.nPayload ){
1412 Pgno ovfl;
1413 if( SQLITE_WITHIN(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){
1414 testcase( pSrc!=pPage );
1415 *pRC = SQLITE_CORRUPT_BKPT;
1416 return;
1418 ovfl = get4byte(&pCell[info.nSize-4]);
1419 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
1422 #endif
1426 ** Defragment the page given. This routine reorganizes cells within the
1427 ** page so that there are no free-blocks on the free-block list.
1429 ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
1430 ** present in the page after this routine returns.
1432 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
1433 ** b-tree page so that there are no freeblocks or fragment bytes, all
1434 ** unused bytes are contained in the unallocated space region, and all
1435 ** cells are packed tightly at the end of the page.
1437 static int defragmentPage(MemPage *pPage, int nMaxFrag){
1438 int i; /* Loop counter */
1439 int pc; /* Address of the i-th cell */
1440 int hdr; /* Offset to the page header */
1441 int size; /* Size of a cell */
1442 int usableSize; /* Number of usable bytes on a page */
1443 int cellOffset; /* Offset to the cell pointer array */
1444 int cbrk; /* Offset to the cell content area */
1445 int nCell; /* Number of cells on the page */
1446 unsigned char *data; /* The page data */
1447 unsigned char *temp; /* Temp area for cell content */
1448 unsigned char *src; /* Source of content */
1449 int iCellFirst; /* First allowable cell index */
1450 int iCellLast; /* Last possible cell index */
1451 int iCellStart; /* First cell offset in input */
1453 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1454 assert( pPage->pBt!=0 );
1455 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
1456 assert( pPage->nOverflow==0 );
1457 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1458 temp = 0;
1459 src = data = pPage->aData;
1460 hdr = pPage->hdrOffset;
1461 cellOffset = pPage->cellOffset;
1462 nCell = pPage->nCell;
1463 assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB );
1464 iCellFirst = cellOffset + 2*nCell;
1465 usableSize = pPage->pBt->usableSize;
1467 /* This block handles pages with two or fewer free blocks and nMaxFrag
1468 ** or fewer fragmented bytes. In this case it is faster to move the
1469 ** two (or one) blocks of cells using memmove() and add the required
1470 ** offsets to each pointer in the cell-pointer array than it is to
1471 ** reconstruct the entire page. */
1472 if( (int)data[hdr+7]<=nMaxFrag ){
1473 int iFree = get2byte(&data[hdr+1]);
1474 if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1475 if( iFree ){
1476 int iFree2 = get2byte(&data[iFree]);
1477 if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1478 if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
1479 u8 *pEnd = &data[cellOffset + nCell*2];
1480 u8 *pAddr;
1481 int sz2 = 0;
1482 int sz = get2byte(&data[iFree+2]);
1483 int top = get2byte(&data[hdr+5]);
1484 if( top>=iFree ){
1485 return SQLITE_CORRUPT_PAGE(pPage);
1487 if( iFree2 ){
1488 if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage);
1489 sz2 = get2byte(&data[iFree2+2]);
1490 if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage);
1491 memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
1492 sz += sz2;
1493 }else if( iFree+sz>usableSize ){
1494 return SQLITE_CORRUPT_PAGE(pPage);
1497 cbrk = top+sz;
1498 assert( cbrk+(iFree-top) <= usableSize );
1499 memmove(&data[cbrk], &data[top], iFree-top);
1500 for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
1501 pc = get2byte(pAddr);
1502 if( pc<iFree ){ put2byte(pAddr, pc+sz); }
1503 else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
1505 goto defragment_out;
1510 cbrk = usableSize;
1511 iCellLast = usableSize - 4;
1512 iCellStart = get2byte(&data[hdr+5]);
1513 for(i=0; i<nCell; i++){
1514 u8 *pAddr; /* The i-th cell pointer */
1515 pAddr = &data[cellOffset + i*2];
1516 pc = get2byte(pAddr);
1517 testcase( pc==iCellFirst );
1518 testcase( pc==iCellLast );
1519 /* These conditions have already been verified in btreeInitPage()
1520 ** if PRAGMA cell_size_check=ON.
1522 if( pc<iCellStart || pc>iCellLast ){
1523 return SQLITE_CORRUPT_PAGE(pPage);
1525 assert( pc>=iCellStart && pc<=iCellLast );
1526 size = pPage->xCellSize(pPage, &src[pc]);
1527 cbrk -= size;
1528 if( cbrk<iCellStart || pc+size>usableSize ){
1529 return SQLITE_CORRUPT_PAGE(pPage);
1531 assert( cbrk+size<=usableSize && cbrk>=iCellStart );
1532 testcase( cbrk+size==usableSize );
1533 testcase( pc+size==usableSize );
1534 put2byte(pAddr, cbrk);
1535 if( temp==0 ){
1536 if( cbrk==pc ) continue;
1537 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
1538 memcpy(&temp[iCellStart], &data[iCellStart], usableSize - iCellStart);
1539 src = temp;
1541 memcpy(&data[cbrk], &src[pc], size);
1543 data[hdr+7] = 0;
1545 defragment_out:
1546 assert( pPage->nFree>=0 );
1547 if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
1548 return SQLITE_CORRUPT_PAGE(pPage);
1550 assert( cbrk>=iCellFirst );
1551 put2byte(&data[hdr+5], cbrk);
1552 data[hdr+1] = 0;
1553 data[hdr+2] = 0;
1554 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
1555 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1556 return SQLITE_OK;
1560 ** Search the free-list on page pPg for space to store a cell nByte bytes in
1561 ** size. If one can be found, return a pointer to the space and remove it
1562 ** from the free-list.
1564 ** If no suitable space can be found on the free-list, return NULL.
1566 ** This function may detect corruption within pPg. If corruption is
1567 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
1569 ** Slots on the free list that are between 1 and 3 bytes larger than nByte
1570 ** will be ignored if adding the extra space to the fragmentation count
1571 ** causes the fragmentation count to exceed 60.
1573 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
1574 const int hdr = pPg->hdrOffset; /* Offset to page header */
1575 u8 * const aData = pPg->aData; /* Page data */
1576 int iAddr = hdr + 1; /* Address of ptr to pc */
1577 int pc = get2byte(&aData[iAddr]); /* Address of a free slot */
1578 int x; /* Excess size of the slot */
1579 int maxPC = pPg->pBt->usableSize - nByte; /* Max address for a usable slot */
1580 int size; /* Size of the free slot */
1582 assert( pc>0 );
1583 while( pc<=maxPC ){
1584 /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
1585 ** freeblock form a big-endian integer which is the size of the freeblock
1586 ** in bytes, including the 4-byte header. */
1587 size = get2byte(&aData[pc+2]);
1588 if( (x = size - nByte)>=0 ){
1589 testcase( x==4 );
1590 testcase( x==3 );
1591 if( x<4 ){
1592 /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
1593 ** number of bytes in fragments may not exceed 60. */
1594 if( aData[hdr+7]>57 ) return 0;
1596 /* Remove the slot from the free-list. Update the number of
1597 ** fragmented bytes within the page. */
1598 memcpy(&aData[iAddr], &aData[pc], 2);
1599 aData[hdr+7] += (u8)x;
1600 }else if( x+pc > maxPC ){
1601 /* This slot extends off the end of the usable part of the page */
1602 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1603 return 0;
1604 }else{
1605 /* The slot remains on the free-list. Reduce its size to account
1606 ** for the portion used by the new allocation. */
1607 put2byte(&aData[pc+2], x);
1609 return &aData[pc + x];
1611 iAddr = pc;
1612 pc = get2byte(&aData[pc]);
1613 if( pc<=iAddr+size ){
1614 if( pc ){
1615 /* The next slot in the chain is not past the end of the current slot */
1616 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1618 return 0;
1621 if( pc>maxPC+nByte-4 ){
1622 /* The free slot chain extends off the end of the page */
1623 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1625 return 0;
1629 ** Allocate nByte bytes of space from within the B-Tree page passed
1630 ** as the first argument. Write into *pIdx the index into pPage->aData[]
1631 ** of the first byte of allocated space. Return either SQLITE_OK or
1632 ** an error code (usually SQLITE_CORRUPT).
1634 ** The caller guarantees that there is sufficient space to make the
1635 ** allocation. This routine might need to defragment in order to bring
1636 ** all the space together, however. This routine will avoid using
1637 ** the first two bytes past the cell pointer area since presumably this
1638 ** allocation is being made in order to insert a new cell, so we will
1639 ** also end up needing a new cell pointer.
1641 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
1642 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1643 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
1644 int top; /* First byte of cell content area */
1645 int rc = SQLITE_OK; /* Integer return code */
1646 int gap; /* First byte of gap between cell pointers and cell content */
1648 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1649 assert( pPage->pBt );
1650 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1651 assert( nByte>=0 ); /* Minimum cell size is 4 */
1652 assert( pPage->nFree>=nByte );
1653 assert( pPage->nOverflow==0 );
1654 assert( nByte < (int)(pPage->pBt->usableSize-8) );
1656 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1657 gap = pPage->cellOffset + 2*pPage->nCell;
1658 assert( gap<=65536 );
1659 /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
1660 ** and the reserved space is zero (the usual value for reserved space)
1661 ** then the cell content offset of an empty page wants to be 65536.
1662 ** However, that integer is too large to be stored in a 2-byte unsigned
1663 ** integer, so a value of 0 is used in its place. */
1664 top = get2byte(&data[hdr+5]);
1665 assert( top<=(int)pPage->pBt->usableSize ); /* by btreeComputeFreeSpace() */
1666 if( gap>top ){
1667 if( top==0 && pPage->pBt->usableSize==65536 ){
1668 top = 65536;
1669 }else{
1670 return SQLITE_CORRUPT_PAGE(pPage);
1674 /* If there is enough space between gap and top for one more cell pointer,
1675 ** and if the freelist is not empty, then search the
1676 ** freelist looking for a slot big enough to satisfy the request.
1678 testcase( gap+2==top );
1679 testcase( gap+1==top );
1680 testcase( gap==top );
1681 if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
1682 u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
1683 if( pSpace ){
1684 int g2;
1685 assert( pSpace+nByte<=data+pPage->pBt->usableSize );
1686 *pIdx = g2 = (int)(pSpace-data);
1687 if( NEVER(g2<=gap) ){
1688 return SQLITE_CORRUPT_PAGE(pPage);
1689 }else{
1690 return SQLITE_OK;
1692 }else if( rc ){
1693 return rc;
1697 /* The request could not be fulfilled using a freelist slot. Check
1698 ** to see if defragmentation is necessary.
1700 testcase( gap+2+nByte==top );
1701 if( gap+2+nByte>top ){
1702 assert( pPage->nCell>0 || CORRUPT_DB );
1703 assert( pPage->nFree>=0 );
1704 rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
1705 if( rc ) return rc;
1706 top = get2byteNotZero(&data[hdr+5]);
1707 assert( gap+2+nByte<=top );
1711 /* Allocate memory from the gap in between the cell pointer array
1712 ** and the cell content area. The btreeComputeFreeSpace() call has already
1713 ** validated the freelist. Given that the freelist is valid, there
1714 ** is no way that the allocation can extend off the end of the page.
1715 ** The assert() below verifies the previous sentence.
1717 top -= nByte;
1718 put2byte(&data[hdr+5], top);
1719 assert( top+nByte <= (int)pPage->pBt->usableSize );
1720 *pIdx = top;
1721 return SQLITE_OK;
1725 ** Return a section of the pPage->aData to the freelist.
1726 ** The first byte of the new free block is pPage->aData[iStart]
1727 ** and the size of the block is iSize bytes.
1729 ** Adjacent freeblocks are coalesced.
1731 ** Even though the freeblock list was checked by btreeComputeFreeSpace(),
1732 ** that routine will not detect overlap between cells or freeblocks. Nor
1733 ** does it detect cells or freeblocks that encrouch into the reserved bytes
1734 ** at the end of the page. So do additional corruption checks inside this
1735 ** routine and return SQLITE_CORRUPT if any problems are found.
1737 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
1738 u16 iPtr; /* Address of ptr to next freeblock */
1739 u16 iFreeBlk; /* Address of the next freeblock */
1740 u8 hdr; /* Page header size. 0 or 100 */
1741 u8 nFrag = 0; /* Reduction in fragmentation */
1742 u16 iOrigSize = iSize; /* Original value of iSize */
1743 u16 x; /* Offset to cell content area */
1744 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
1745 unsigned char *data = pPage->aData; /* Page content */
1747 assert( pPage->pBt!=0 );
1748 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1749 assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
1750 assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
1751 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1752 assert( iSize>=4 ); /* Minimum cell size is 4 */
1753 assert( iStart<=pPage->pBt->usableSize-4 );
1755 /* The list of freeblocks must be in ascending order. Find the
1756 ** spot on the list where iStart should be inserted.
1758 hdr = pPage->hdrOffset;
1759 iPtr = hdr + 1;
1760 if( data[iPtr+1]==0 && data[iPtr]==0 ){
1761 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
1762 }else{
1763 while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
1764 if( iFreeBlk<iPtr+4 ){
1765 if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */
1766 return SQLITE_CORRUPT_PAGE(pPage);
1768 iPtr = iFreeBlk;
1770 if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */
1771 return SQLITE_CORRUPT_PAGE(pPage);
1773 assert( iFreeBlk>iPtr || iFreeBlk==0 );
1775 /* At this point:
1776 ** iFreeBlk: First freeblock after iStart, or zero if none
1777 ** iPtr: The address of a pointer to iFreeBlk
1779 ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
1781 if( iFreeBlk && iEnd+3>=iFreeBlk ){
1782 nFrag = iFreeBlk - iEnd;
1783 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
1784 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
1785 if( iEnd > pPage->pBt->usableSize ){
1786 return SQLITE_CORRUPT_PAGE(pPage);
1788 iSize = iEnd - iStart;
1789 iFreeBlk = get2byte(&data[iFreeBlk]);
1792 /* If iPtr is another freeblock (that is, if iPtr is not the freelist
1793 ** pointer in the page header) then check to see if iStart should be
1794 ** coalesced onto the end of iPtr.
1796 if( iPtr>hdr+1 ){
1797 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
1798 if( iPtrEnd+3>=iStart ){
1799 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
1800 nFrag += iStart - iPtrEnd;
1801 iSize = iEnd - iPtr;
1802 iStart = iPtr;
1805 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
1806 data[hdr+7] -= nFrag;
1808 x = get2byte(&data[hdr+5]);
1809 if( iStart<=x ){
1810 /* The new freeblock is at the beginning of the cell content area,
1811 ** so just extend the cell content area rather than create another
1812 ** freelist entry */
1813 if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage);
1814 if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
1815 put2byte(&data[hdr+1], iFreeBlk);
1816 put2byte(&data[hdr+5], iEnd);
1817 }else{
1818 /* Insert the new freeblock into the freelist */
1819 put2byte(&data[iPtr], iStart);
1821 if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
1822 /* Overwrite deleted information with zeros when the secure_delete
1823 ** option is enabled */
1824 memset(&data[iStart], 0, iSize);
1826 put2byte(&data[iStart], iFreeBlk);
1827 put2byte(&data[iStart+2], iSize);
1828 pPage->nFree += iOrigSize;
1829 return SQLITE_OK;
1833 ** Decode the flags byte (the first byte of the header) for a page
1834 ** and initialize fields of the MemPage structure accordingly.
1836 ** Only the following combinations are supported. Anything different
1837 ** indicates a corrupt database files:
1839 ** PTF_ZERODATA
1840 ** PTF_ZERODATA | PTF_LEAF
1841 ** PTF_LEAFDATA | PTF_INTKEY
1842 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
1844 static int decodeFlags(MemPage *pPage, int flagByte){
1845 BtShared *pBt; /* A copy of pPage->pBt */
1847 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
1848 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1849 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
1850 flagByte &= ~PTF_LEAF;
1851 pPage->childPtrSize = 4-4*pPage->leaf;
1852 pPage->xCellSize = cellSizePtr;
1853 pBt = pPage->pBt;
1854 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
1855 /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
1856 ** interior table b-tree page. */
1857 assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
1858 /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
1859 ** leaf table b-tree page. */
1860 assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
1861 pPage->intKey = 1;
1862 if( pPage->leaf ){
1863 pPage->intKeyLeaf = 1;
1864 pPage->xParseCell = btreeParseCellPtr;
1865 }else{
1866 pPage->intKeyLeaf = 0;
1867 pPage->xCellSize = cellSizePtrNoPayload;
1868 pPage->xParseCell = btreeParseCellPtrNoPayload;
1870 pPage->maxLocal = pBt->maxLeaf;
1871 pPage->minLocal = pBt->minLeaf;
1872 }else if( flagByte==PTF_ZERODATA ){
1873 /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
1874 ** interior index b-tree page. */
1875 assert( (PTF_ZERODATA)==2 );
1876 /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
1877 ** leaf index b-tree page. */
1878 assert( (PTF_ZERODATA|PTF_LEAF)==10 );
1879 pPage->intKey = 0;
1880 pPage->intKeyLeaf = 0;
1881 pPage->xParseCell = btreeParseCellPtrIndex;
1882 pPage->maxLocal = pBt->maxLocal;
1883 pPage->minLocal = pBt->minLocal;
1884 }else{
1885 /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
1886 ** an error. */
1887 return SQLITE_CORRUPT_PAGE(pPage);
1889 pPage->max1bytePayload = pBt->max1bytePayload;
1890 return SQLITE_OK;
1894 ** Compute the amount of freespace on the page. In other words, fill
1895 ** in the pPage->nFree field.
1897 static int btreeComputeFreeSpace(MemPage *pPage){
1898 int pc; /* Address of a freeblock within pPage->aData[] */
1899 u8 hdr; /* Offset to beginning of page header */
1900 u8 *data; /* Equal to pPage->aData */
1901 int usableSize; /* Amount of usable space on each page */
1902 int nFree; /* Number of unused bytes on the page */
1903 int top; /* First byte of the cell content area */
1904 int iCellFirst; /* First allowable cell or freeblock offset */
1905 int iCellLast; /* Last possible cell or freeblock offset */
1907 assert( pPage->pBt!=0 );
1908 assert( pPage->pBt->db!=0 );
1909 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1910 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
1911 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1912 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
1913 assert( pPage->isInit==1 );
1914 assert( pPage->nFree<0 );
1916 usableSize = pPage->pBt->usableSize;
1917 hdr = pPage->hdrOffset;
1918 data = pPage->aData;
1919 /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
1920 ** the start of the cell content area. A zero value for this integer is
1921 ** interpreted as 65536. */
1922 top = get2byteNotZero(&data[hdr+5]);
1923 iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell;
1924 iCellLast = usableSize - 4;
1926 /* Compute the total free space on the page
1927 ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
1928 ** start of the first freeblock on the page, or is zero if there are no
1929 ** freeblocks. */
1930 pc = get2byte(&data[hdr+1]);
1931 nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
1932 if( pc>0 ){
1933 u32 next, size;
1934 if( pc<top ){
1935 /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
1936 ** always be at least one cell before the first freeblock.
1938 return SQLITE_CORRUPT_PAGE(pPage);
1940 while( 1 ){
1941 if( pc>iCellLast ){
1942 /* Freeblock off the end of the page */
1943 return SQLITE_CORRUPT_PAGE(pPage);
1945 next = get2byte(&data[pc]);
1946 size = get2byte(&data[pc+2]);
1947 nFree = nFree + size;
1948 if( next<=pc+size+3 ) break;
1949 pc = next;
1951 if( next>0 ){
1952 /* Freeblock not in ascending order */
1953 return SQLITE_CORRUPT_PAGE(pPage);
1955 if( pc+size>(unsigned int)usableSize ){
1956 /* Last freeblock extends past page end */
1957 return SQLITE_CORRUPT_PAGE(pPage);
1961 /* At this point, nFree contains the sum of the offset to the start
1962 ** of the cell-content area plus the number of free bytes within
1963 ** the cell-content area. If this is greater than the usable-size
1964 ** of the page, then the page must be corrupted. This check also
1965 ** serves to verify that the offset to the start of the cell-content
1966 ** area, according to the page header, lies within the page.
1968 if( nFree>usableSize || nFree<iCellFirst ){
1969 return SQLITE_CORRUPT_PAGE(pPage);
1971 pPage->nFree = (u16)(nFree - iCellFirst);
1972 return SQLITE_OK;
1976 ** Do additional sanity check after btreeInitPage() if
1977 ** PRAGMA cell_size_check=ON
1979 static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){
1980 int iCellFirst; /* First allowable cell or freeblock offset */
1981 int iCellLast; /* Last possible cell or freeblock offset */
1982 int i; /* Index into the cell pointer array */
1983 int sz; /* Size of a cell */
1984 int pc; /* Address of a freeblock within pPage->aData[] */
1985 u8 *data; /* Equal to pPage->aData */
1986 int usableSize; /* Maximum usable space on the page */
1987 int cellOffset; /* Start of cell content area */
1989 iCellFirst = pPage->cellOffset + 2*pPage->nCell;
1990 usableSize = pPage->pBt->usableSize;
1991 iCellLast = usableSize - 4;
1992 data = pPage->aData;
1993 cellOffset = pPage->cellOffset;
1994 if( !pPage->leaf ) iCellLast--;
1995 for(i=0; i<pPage->nCell; i++){
1996 pc = get2byteAligned(&data[cellOffset+i*2]);
1997 testcase( pc==iCellFirst );
1998 testcase( pc==iCellLast );
1999 if( pc<iCellFirst || pc>iCellLast ){
2000 return SQLITE_CORRUPT_PAGE(pPage);
2002 sz = pPage->xCellSize(pPage, &data[pc]);
2003 testcase( pc+sz==usableSize );
2004 if( pc+sz>usableSize ){
2005 return SQLITE_CORRUPT_PAGE(pPage);
2008 return SQLITE_OK;
2012 ** Initialize the auxiliary information for a disk block.
2014 ** Return SQLITE_OK on success. If we see that the page does
2015 ** not contain a well-formed database page, then return
2016 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
2017 ** guarantee that the page is well-formed. It only shows that
2018 ** we failed to detect any corruption.
2020 static int btreeInitPage(MemPage *pPage){
2021 u8 *data; /* Equal to pPage->aData */
2022 BtShared *pBt; /* The main btree structure */
2024 assert( pPage->pBt!=0 );
2025 assert( pPage->pBt->db!=0 );
2026 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2027 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
2028 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
2029 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
2030 assert( pPage->isInit==0 );
2032 pBt = pPage->pBt;
2033 data = pPage->aData + pPage->hdrOffset;
2034 /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
2035 ** the b-tree page type. */
2036 if( decodeFlags(pPage, data[0]) ){
2037 return SQLITE_CORRUPT_PAGE(pPage);
2039 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2040 pPage->maskPage = (u16)(pBt->pageSize - 1);
2041 pPage->nOverflow = 0;
2042 pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize;
2043 pPage->aCellIdx = data + pPage->childPtrSize + 8;
2044 pPage->aDataEnd = pPage->aData + pBt->usableSize;
2045 pPage->aDataOfst = pPage->aData + pPage->childPtrSize;
2046 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
2047 ** number of cells on the page. */
2048 pPage->nCell = get2byte(&data[3]);
2049 if( pPage->nCell>MX_CELL(pBt) ){
2050 /* To many cells for a single page. The page must be corrupt */
2051 return SQLITE_CORRUPT_PAGE(pPage);
2053 testcase( pPage->nCell==MX_CELL(pBt) );
2054 /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
2055 ** possible for a root page of a table that contains no rows) then the
2056 ** offset to the cell content area will equal the page size minus the
2057 ** bytes of reserved space. */
2058 assert( pPage->nCell>0
2059 || get2byteNotZero(&data[5])==(int)pBt->usableSize
2060 || CORRUPT_DB );
2061 pPage->nFree = -1; /* Indicate that this value is yet uncomputed */
2062 pPage->isInit = 1;
2063 if( pBt->db->flags & SQLITE_CellSizeCk ){
2064 return btreeCellSizeCheck(pPage);
2066 return SQLITE_OK;
2070 ** Set up a raw page so that it looks like a database page holding
2071 ** no entries.
2073 static void zeroPage(MemPage *pPage, int flags){
2074 unsigned char *data = pPage->aData;
2075 BtShared *pBt = pPage->pBt;
2076 u8 hdr = pPage->hdrOffset;
2077 u16 first;
2079 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
2080 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2081 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
2082 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
2083 assert( sqlite3_mutex_held(pBt->mutex) );
2084 if( pBt->btsFlags & BTS_FAST_SECURE ){
2085 memset(&data[hdr], 0, pBt->usableSize - hdr);
2087 data[hdr] = (char)flags;
2088 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
2089 memset(&data[hdr+1], 0, 4);
2090 data[hdr+7] = 0;
2091 put2byte(&data[hdr+5], pBt->usableSize);
2092 pPage->nFree = (u16)(pBt->usableSize - first);
2093 decodeFlags(pPage, flags);
2094 pPage->cellOffset = first;
2095 pPage->aDataEnd = &data[pBt->usableSize];
2096 pPage->aCellIdx = &data[first];
2097 pPage->aDataOfst = &data[pPage->childPtrSize];
2098 pPage->nOverflow = 0;
2099 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2100 pPage->maskPage = (u16)(pBt->pageSize - 1);
2101 pPage->nCell = 0;
2102 pPage->isInit = 1;
2107 ** Convert a DbPage obtained from the pager into a MemPage used by
2108 ** the btree layer.
2110 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
2111 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2112 if( pgno!=pPage->pgno ){
2113 pPage->aData = sqlite3PagerGetData(pDbPage);
2114 pPage->pDbPage = pDbPage;
2115 pPage->pBt = pBt;
2116 pPage->pgno = pgno;
2117 pPage->hdrOffset = pgno==1 ? 100 : 0;
2119 assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
2120 return pPage;
2124 ** Get a page from the pager. Initialize the MemPage.pBt and
2125 ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
2127 ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
2128 ** about the content of the page at this time. So do not go to the disk
2129 ** to fetch the content. Just fill in the content with zeros for now.
2130 ** If in the future we call sqlite3PagerWrite() on this page, that
2131 ** means we have started to be concerned about content and the disk
2132 ** read should occur at that point.
2134 static int btreeGetPage(
2135 BtShared *pBt, /* The btree */
2136 Pgno pgno, /* Number of the page to fetch */
2137 MemPage **ppPage, /* Return the page in this parameter */
2138 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2140 int rc;
2141 DbPage *pDbPage;
2143 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
2144 assert( sqlite3_mutex_held(pBt->mutex) );
2145 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
2146 if( rc ) return rc;
2147 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
2148 return SQLITE_OK;
2152 ** Retrieve a page from the pager cache. If the requested page is not
2153 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
2154 ** MemPage.aData elements if needed.
2156 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
2157 DbPage *pDbPage;
2158 assert( sqlite3_mutex_held(pBt->mutex) );
2159 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
2160 if( pDbPage ){
2161 return btreePageFromDbPage(pDbPage, pgno, pBt);
2163 return 0;
2167 ** Return the size of the database file in pages. If there is any kind of
2168 ** error, return ((unsigned int)-1).
2170 static Pgno btreePagecount(BtShared *pBt){
2171 return pBt->nPage;
2173 Pgno sqlite3BtreeLastPage(Btree *p){
2174 assert( sqlite3BtreeHoldsMutex(p) );
2175 return btreePagecount(p->pBt);
2179 ** Get a page from the pager and initialize it.
2181 ** If pCur!=0 then the page is being fetched as part of a moveToChild()
2182 ** call. Do additional sanity checking on the page in this case.
2183 ** And if the fetch fails, this routine must decrement pCur->iPage.
2185 ** The page is fetched as read-write unless pCur is not NULL and is
2186 ** a read-only cursor.
2188 ** If an error occurs, then *ppPage is undefined. It
2189 ** may remain unchanged, or it may be set to an invalid value.
2191 static int getAndInitPage(
2192 BtShared *pBt, /* The database file */
2193 Pgno pgno, /* Number of the page to get */
2194 MemPage **ppPage, /* Write the page pointer here */
2195 BtCursor *pCur, /* Cursor to receive the page, or NULL */
2196 int bReadOnly /* True for a read-only page */
2198 int rc;
2199 DbPage *pDbPage;
2200 assert( sqlite3_mutex_held(pBt->mutex) );
2201 assert( pCur==0 || ppPage==&pCur->pPage );
2202 assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
2203 assert( pCur==0 || pCur->iPage>0 );
2205 if( pgno>btreePagecount(pBt) ){
2206 rc = SQLITE_CORRUPT_BKPT;
2207 goto getAndInitPage_error1;
2209 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
2210 if( rc ){
2211 goto getAndInitPage_error1;
2213 *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2214 if( (*ppPage)->isInit==0 ){
2215 btreePageFromDbPage(pDbPage, pgno, pBt);
2216 rc = btreeInitPage(*ppPage);
2217 if( rc!=SQLITE_OK ){
2218 goto getAndInitPage_error2;
2221 assert( (*ppPage)->pgno==pgno );
2222 assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
2224 /* If obtaining a child page for a cursor, we must verify that the page is
2225 ** compatible with the root page. */
2226 if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
2227 rc = SQLITE_CORRUPT_PGNO(pgno);
2228 goto getAndInitPage_error2;
2230 return SQLITE_OK;
2232 getAndInitPage_error2:
2233 releasePage(*ppPage);
2234 getAndInitPage_error1:
2235 if( pCur ){
2236 pCur->iPage--;
2237 pCur->pPage = pCur->apPage[pCur->iPage];
2239 testcase( pgno==0 );
2240 assert( pgno!=0 || rc==SQLITE_CORRUPT );
2241 return rc;
2245 ** Release a MemPage. This should be called once for each prior
2246 ** call to btreeGetPage.
2248 ** Page1 is a special case and must be released using releasePageOne().
2250 static void releasePageNotNull(MemPage *pPage){
2251 assert( pPage->aData );
2252 assert( pPage->pBt );
2253 assert( pPage->pDbPage!=0 );
2254 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2255 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2256 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2257 sqlite3PagerUnrefNotNull(pPage->pDbPage);
2259 static void releasePage(MemPage *pPage){
2260 if( pPage ) releasePageNotNull(pPage);
2262 static void releasePageOne(MemPage *pPage){
2263 assert( pPage!=0 );
2264 assert( pPage->aData );
2265 assert( pPage->pBt );
2266 assert( pPage->pDbPage!=0 );
2267 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2268 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2269 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2270 sqlite3PagerUnrefPageOne(pPage->pDbPage);
2274 ** Get an unused page.
2276 ** This works just like btreeGetPage() with the addition:
2278 ** * If the page is already in use for some other purpose, immediately
2279 ** release it and return an SQLITE_CURRUPT error.
2280 ** * Make sure the isInit flag is clear
2282 static int btreeGetUnusedPage(
2283 BtShared *pBt, /* The btree */
2284 Pgno pgno, /* Number of the page to fetch */
2285 MemPage **ppPage, /* Return the page in this parameter */
2286 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2288 int rc = btreeGetPage(pBt, pgno, ppPage, flags);
2289 if( rc==SQLITE_OK ){
2290 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
2291 releasePage(*ppPage);
2292 *ppPage = 0;
2293 return SQLITE_CORRUPT_BKPT;
2295 (*ppPage)->isInit = 0;
2296 }else{
2297 *ppPage = 0;
2299 return rc;
2304 ** During a rollback, when the pager reloads information into the cache
2305 ** so that the cache is restored to its original state at the start of
2306 ** the transaction, for each page restored this routine is called.
2308 ** This routine needs to reset the extra data section at the end of the
2309 ** page to agree with the restored data.
2311 static void pageReinit(DbPage *pData){
2312 MemPage *pPage;
2313 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
2314 assert( sqlite3PagerPageRefcount(pData)>0 );
2315 if( pPage->isInit ){
2316 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2317 pPage->isInit = 0;
2318 if( sqlite3PagerPageRefcount(pData)>1 ){
2319 /* pPage might not be a btree page; it might be an overflow page
2320 ** or ptrmap page or a free page. In those cases, the following
2321 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
2322 ** But no harm is done by this. And it is very important that
2323 ** btreeInitPage() be called on every btree page so we make
2324 ** the call for every page that comes in for re-initing. */
2325 btreeInitPage(pPage);
2331 ** Invoke the busy handler for a btree.
2333 static int btreeInvokeBusyHandler(void *pArg){
2334 BtShared *pBt = (BtShared*)pArg;
2335 assert( pBt->db );
2336 assert( sqlite3_mutex_held(pBt->db->mutex) );
2337 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
2341 ** Open a database file.
2343 ** zFilename is the name of the database file. If zFilename is NULL
2344 ** then an ephemeral database is created. The ephemeral database might
2345 ** be exclusively in memory, or it might use a disk-based memory cache.
2346 ** Either way, the ephemeral database will be automatically deleted
2347 ** when sqlite3BtreeClose() is called.
2349 ** If zFilename is ":memory:" then an in-memory database is created
2350 ** that is automatically destroyed when it is closed.
2352 ** The "flags" parameter is a bitmask that might contain bits like
2353 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
2355 ** If the database is already opened in the same database connection
2356 ** and we are in shared cache mode, then the open will fail with an
2357 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
2358 ** objects in the same database connection since doing so will lead
2359 ** to problems with locking.
2361 int sqlite3BtreeOpen(
2362 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
2363 const char *zFilename, /* Name of the file containing the BTree database */
2364 sqlite3 *db, /* Associated database handle */
2365 Btree **ppBtree, /* Pointer to new Btree object written here */
2366 int flags, /* Options */
2367 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
2369 BtShared *pBt = 0; /* Shared part of btree structure */
2370 Btree *p; /* Handle to return */
2371 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
2372 int rc = SQLITE_OK; /* Result code from this function */
2373 u8 nReserve; /* Byte of unused space on each page */
2374 unsigned char zDbHeader[100]; /* Database header content */
2376 /* True if opening an ephemeral, temporary database */
2377 const int isTempDb = zFilename==0 || zFilename[0]==0;
2379 /* Set the variable isMemdb to true for an in-memory database, or
2380 ** false for a file-based database.
2382 #ifdef SQLITE_OMIT_MEMORYDB
2383 const int isMemdb = 0;
2384 #else
2385 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
2386 || (isTempDb && sqlite3TempInMemory(db))
2387 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
2388 #endif
2390 assert( db!=0 );
2391 assert( pVfs!=0 );
2392 assert( sqlite3_mutex_held(db->mutex) );
2393 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
2395 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
2396 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
2398 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
2399 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
2401 if( isMemdb ){
2402 flags |= BTREE_MEMORY;
2404 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
2405 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
2407 p = sqlite3MallocZero(sizeof(Btree));
2408 if( !p ){
2409 return SQLITE_NOMEM_BKPT;
2411 p->inTrans = TRANS_NONE;
2412 p->db = db;
2413 #ifndef SQLITE_OMIT_SHARED_CACHE
2414 p->lock.pBtree = p;
2415 p->lock.iTable = 1;
2416 #endif
2418 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2420 ** If this Btree is a candidate for shared cache, try to find an
2421 ** existing BtShared object that we can share with
2423 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
2424 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
2425 int nFilename = sqlite3Strlen30(zFilename)+1;
2426 int nFullPathname = pVfs->mxPathname+1;
2427 char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
2428 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2430 p->sharable = 1;
2431 if( !zFullPathname ){
2432 sqlite3_free(p);
2433 return SQLITE_NOMEM_BKPT;
2435 if( isMemdb ){
2436 memcpy(zFullPathname, zFilename, nFilename);
2437 }else{
2438 rc = sqlite3OsFullPathname(pVfs, zFilename,
2439 nFullPathname, zFullPathname);
2440 if( rc ){
2441 if( rc==SQLITE_OK_SYMLINK ){
2442 rc = SQLITE_OK;
2443 }else{
2444 sqlite3_free(zFullPathname);
2445 sqlite3_free(p);
2446 return rc;
2450 #if SQLITE_THREADSAFE
2451 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
2452 sqlite3_mutex_enter(mutexOpen);
2453 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
2454 sqlite3_mutex_enter(mutexShared);
2455 #endif
2456 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
2457 assert( pBt->nRef>0 );
2458 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
2459 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
2460 int iDb;
2461 for(iDb=db->nDb-1; iDb>=0; iDb--){
2462 Btree *pExisting = db->aDb[iDb].pBt;
2463 if( pExisting && pExisting->pBt==pBt ){
2464 sqlite3_mutex_leave(mutexShared);
2465 sqlite3_mutex_leave(mutexOpen);
2466 sqlite3_free(zFullPathname);
2467 sqlite3_free(p);
2468 return SQLITE_CONSTRAINT;
2471 p->pBt = pBt;
2472 pBt->nRef++;
2473 break;
2476 sqlite3_mutex_leave(mutexShared);
2477 sqlite3_free(zFullPathname);
2479 #ifdef SQLITE_DEBUG
2480 else{
2481 /* In debug mode, we mark all persistent databases as sharable
2482 ** even when they are not. This exercises the locking code and
2483 ** gives more opportunity for asserts(sqlite3_mutex_held())
2484 ** statements to find locking problems.
2486 p->sharable = 1;
2488 #endif
2490 #endif
2491 if( pBt==0 ){
2493 ** The following asserts make sure that structures used by the btree are
2494 ** the right size. This is to guard against size changes that result
2495 ** when compiling on a different architecture.
2497 assert( sizeof(i64)==8 );
2498 assert( sizeof(u64)==8 );
2499 assert( sizeof(u32)==4 );
2500 assert( sizeof(u16)==2 );
2501 assert( sizeof(Pgno)==4 );
2503 pBt = sqlite3MallocZero( sizeof(*pBt) );
2504 if( pBt==0 ){
2505 rc = SQLITE_NOMEM_BKPT;
2506 goto btree_open_out;
2508 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
2509 sizeof(MemPage), flags, vfsFlags, pageReinit);
2510 if( rc==SQLITE_OK ){
2511 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
2512 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
2514 if( rc!=SQLITE_OK ){
2515 goto btree_open_out;
2517 pBt->openFlags = (u8)flags;
2518 pBt->db = db;
2519 sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
2520 p->pBt = pBt;
2522 pBt->pCursor = 0;
2523 pBt->pPage1 = 0;
2524 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
2525 #if defined(SQLITE_SECURE_DELETE)
2526 pBt->btsFlags |= BTS_SECURE_DELETE;
2527 #elif defined(SQLITE_FAST_SECURE_DELETE)
2528 pBt->btsFlags |= BTS_OVERWRITE;
2529 #endif
2530 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2531 ** determined by the 2-byte integer located at an offset of 16 bytes from
2532 ** the beginning of the database file. */
2533 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
2534 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
2535 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
2536 pBt->pageSize = 0;
2537 #ifndef SQLITE_OMIT_AUTOVACUUM
2538 /* If the magic name ":memory:" will create an in-memory database, then
2539 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
2540 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
2541 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
2542 ** regular file-name. In this case the auto-vacuum applies as per normal.
2544 if( zFilename && !isMemdb ){
2545 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
2546 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
2548 #endif
2549 nReserve = 0;
2550 }else{
2551 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2552 ** determined by the one-byte unsigned integer found at an offset of 20
2553 ** into the database file header. */
2554 nReserve = zDbHeader[20];
2555 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2556 #ifndef SQLITE_OMIT_AUTOVACUUM
2557 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
2558 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
2559 #endif
2561 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2562 if( rc ) goto btree_open_out;
2563 pBt->usableSize = pBt->pageSize - nReserve;
2564 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
2566 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2567 /* Add the new BtShared object to the linked list sharable BtShareds.
2569 pBt->nRef = 1;
2570 if( p->sharable ){
2571 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2572 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);)
2573 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
2574 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
2575 if( pBt->mutex==0 ){
2576 rc = SQLITE_NOMEM_BKPT;
2577 goto btree_open_out;
2580 sqlite3_mutex_enter(mutexShared);
2581 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2582 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
2583 sqlite3_mutex_leave(mutexShared);
2585 #endif
2588 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2589 /* If the new Btree uses a sharable pBtShared, then link the new
2590 ** Btree into the list of all sharable Btrees for the same connection.
2591 ** The list is kept in ascending order by pBt address.
2593 if( p->sharable ){
2594 int i;
2595 Btree *pSib;
2596 for(i=0; i<db->nDb; i++){
2597 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
2598 while( pSib->pPrev ){ pSib = pSib->pPrev; }
2599 if( (uptr)p->pBt<(uptr)pSib->pBt ){
2600 p->pNext = pSib;
2601 p->pPrev = 0;
2602 pSib->pPrev = p;
2603 }else{
2604 while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
2605 pSib = pSib->pNext;
2607 p->pNext = pSib->pNext;
2608 p->pPrev = pSib;
2609 if( p->pNext ){
2610 p->pNext->pPrev = p;
2612 pSib->pNext = p;
2614 break;
2618 #endif
2619 *ppBtree = p;
2621 btree_open_out:
2622 if( rc!=SQLITE_OK ){
2623 if( pBt && pBt->pPager ){
2624 sqlite3PagerClose(pBt->pPager, 0);
2626 sqlite3_free(pBt);
2627 sqlite3_free(p);
2628 *ppBtree = 0;
2629 }else{
2630 sqlite3_file *pFile;
2632 /* If the B-Tree was successfully opened, set the pager-cache size to the
2633 ** default value. Except, when opening on an existing shared pager-cache,
2634 ** do not change the pager-cache size.
2636 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
2637 sqlite3BtreeSetCacheSize(p, SQLITE_DEFAULT_CACHE_SIZE);
2640 pFile = sqlite3PagerFile(pBt->pPager);
2641 if( pFile->pMethods ){
2642 sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
2645 if( mutexOpen ){
2646 assert( sqlite3_mutex_held(mutexOpen) );
2647 sqlite3_mutex_leave(mutexOpen);
2649 assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
2650 return rc;
2654 ** Decrement the BtShared.nRef counter. When it reaches zero,
2655 ** remove the BtShared structure from the sharing list. Return
2656 ** true if the BtShared.nRef counter reaches zero and return
2657 ** false if it is still positive.
2659 static int removeFromSharingList(BtShared *pBt){
2660 #ifndef SQLITE_OMIT_SHARED_CACHE
2661 MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )
2662 BtShared *pList;
2663 int removed = 0;
2665 assert( sqlite3_mutex_notheld(pBt->mutex) );
2666 MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
2667 sqlite3_mutex_enter(pMainMtx);
2668 pBt->nRef--;
2669 if( pBt->nRef<=0 ){
2670 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2671 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
2672 }else{
2673 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
2674 while( ALWAYS(pList) && pList->pNext!=pBt ){
2675 pList=pList->pNext;
2677 if( ALWAYS(pList) ){
2678 pList->pNext = pBt->pNext;
2681 if( SQLITE_THREADSAFE ){
2682 sqlite3_mutex_free(pBt->mutex);
2684 removed = 1;
2686 sqlite3_mutex_leave(pMainMtx);
2687 return removed;
2688 #else
2689 return 1;
2690 #endif
2694 ** Make sure pBt->pTmpSpace points to an allocation of
2695 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
2696 ** pointer.
2698 static void allocateTempSpace(BtShared *pBt){
2699 if( !pBt->pTmpSpace ){
2700 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
2702 /* One of the uses of pBt->pTmpSpace is to format cells before
2703 ** inserting them into a leaf page (function fillInCell()). If
2704 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
2705 ** by the various routines that manipulate binary cells. Which
2706 ** can mean that fillInCell() only initializes the first 2 or 3
2707 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
2708 ** it into a database page. This is not actually a problem, but it
2709 ** does cause a valgrind error when the 1 or 2 bytes of unitialized
2710 ** data is passed to system call write(). So to avoid this error,
2711 ** zero the first 4 bytes of temp space here.
2713 ** Also: Provide four bytes of initialized space before the
2714 ** beginning of pTmpSpace as an area available to prepend the
2715 ** left-child pointer to the beginning of a cell.
2717 if( pBt->pTmpSpace ){
2718 memset(pBt->pTmpSpace, 0, 8);
2719 pBt->pTmpSpace += 4;
2725 ** Free the pBt->pTmpSpace allocation
2727 static void freeTempSpace(BtShared *pBt){
2728 if( pBt->pTmpSpace ){
2729 pBt->pTmpSpace -= 4;
2730 sqlite3PageFree(pBt->pTmpSpace);
2731 pBt->pTmpSpace = 0;
2736 ** Close an open database and invalidate all cursors.
2738 int sqlite3BtreeClose(Btree *p){
2739 BtShared *pBt = p->pBt;
2741 /* Close all cursors opened via this handle. */
2742 assert( sqlite3_mutex_held(p->db->mutex) );
2743 sqlite3BtreeEnter(p);
2745 /* Verify that no other cursors have this Btree open */
2746 #ifdef SQLITE_DEBUG
2748 BtCursor *pCur = pBt->pCursor;
2749 while( pCur ){
2750 BtCursor *pTmp = pCur;
2751 pCur = pCur->pNext;
2752 assert( pTmp->pBtree!=p );
2756 #endif
2758 /* Rollback any active transaction and free the handle structure.
2759 ** The call to sqlite3BtreeRollback() drops any table-locks held by
2760 ** this handle.
2762 sqlite3BtreeRollback(p, SQLITE_OK, 0);
2763 sqlite3BtreeLeave(p);
2765 /* If there are still other outstanding references to the shared-btree
2766 ** structure, return now. The remainder of this procedure cleans
2767 ** up the shared-btree.
2769 assert( p->wantToLock==0 && p->locked==0 );
2770 if( !p->sharable || removeFromSharingList(pBt) ){
2771 /* The pBt is no longer on the sharing list, so we can access
2772 ** it without having to hold the mutex.
2774 ** Clean out and delete the BtShared object.
2776 assert( !pBt->pCursor );
2777 sqlite3PagerClose(pBt->pPager, p->db);
2778 if( pBt->xFreeSchema && pBt->pSchema ){
2779 pBt->xFreeSchema(pBt->pSchema);
2781 sqlite3DbFree(0, pBt->pSchema);
2782 freeTempSpace(pBt);
2783 sqlite3_free(pBt);
2786 #ifndef SQLITE_OMIT_SHARED_CACHE
2787 assert( p->wantToLock==0 );
2788 assert( p->locked==0 );
2789 if( p->pPrev ) p->pPrev->pNext = p->pNext;
2790 if( p->pNext ) p->pNext->pPrev = p->pPrev;
2791 #endif
2793 sqlite3_free(p);
2794 return SQLITE_OK;
2798 ** Change the "soft" limit on the number of pages in the cache.
2799 ** Unused and unmodified pages will be recycled when the number of
2800 ** pages in the cache exceeds this soft limit. But the size of the
2801 ** cache is allowed to grow larger than this limit if it contains
2802 ** dirty pages or pages still in active use.
2804 int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2805 BtShared *pBt = p->pBt;
2806 assert( sqlite3_mutex_held(p->db->mutex) );
2807 sqlite3BtreeEnter(p);
2808 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
2809 sqlite3BtreeLeave(p);
2810 return SQLITE_OK;
2814 ** Change the "spill" limit on the number of pages in the cache.
2815 ** If the number of pages exceeds this limit during a write transaction,
2816 ** the pager might attempt to "spill" pages to the journal early in
2817 ** order to free up memory.
2819 ** The value returned is the current spill size. If zero is passed
2820 ** as an argument, no changes are made to the spill size setting, so
2821 ** using mxPage of 0 is a way to query the current spill size.
2823 int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
2824 BtShared *pBt = p->pBt;
2825 int res;
2826 assert( sqlite3_mutex_held(p->db->mutex) );
2827 sqlite3BtreeEnter(p);
2828 res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
2829 sqlite3BtreeLeave(p);
2830 return res;
2833 #if SQLITE_MAX_MMAP_SIZE>0
2835 ** Change the limit on the amount of the database file that may be
2836 ** memory mapped.
2838 int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
2839 BtShared *pBt = p->pBt;
2840 assert( sqlite3_mutex_held(p->db->mutex) );
2841 sqlite3BtreeEnter(p);
2842 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
2843 sqlite3BtreeLeave(p);
2844 return SQLITE_OK;
2846 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
2849 ** Change the way data is synced to disk in order to increase or decrease
2850 ** how well the database resists damage due to OS crashes and power
2851 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
2852 ** there is a high probability of damage) Level 2 is the default. There
2853 ** is a very low but non-zero probability of damage. Level 3 reduces the
2854 ** probability of damage to near zero but with a write performance reduction.
2856 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
2857 int sqlite3BtreeSetPagerFlags(
2858 Btree *p, /* The btree to set the safety level on */
2859 unsigned pgFlags /* Various PAGER_* flags */
2861 BtShared *pBt = p->pBt;
2862 assert( sqlite3_mutex_held(p->db->mutex) );
2863 sqlite3BtreeEnter(p);
2864 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
2865 sqlite3BtreeLeave(p);
2866 return SQLITE_OK;
2868 #endif
2871 ** Change the default pages size and the number of reserved bytes per page.
2872 ** Or, if the page size has already been fixed, return SQLITE_READONLY
2873 ** without changing anything.
2875 ** The page size must be a power of 2 between 512 and 65536. If the page
2876 ** size supplied does not meet this constraint then the page size is not
2877 ** changed.
2879 ** Page sizes are constrained to be a power of two so that the region
2880 ** of the database file used for locking (beginning at PENDING_BYTE,
2881 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
2882 ** at the beginning of a page.
2884 ** If parameter nReserve is less than zero, then the number of reserved
2885 ** bytes per page is left unchanged.
2887 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
2888 ** and autovacuum mode can no longer be changed.
2890 int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
2891 int rc = SQLITE_OK;
2892 int x;
2893 BtShared *pBt = p->pBt;
2894 assert( nReserve>=0 && nReserve<=255 );
2895 sqlite3BtreeEnter(p);
2896 pBt->nReserveWanted = nReserve;
2897 x = pBt->pageSize - pBt->usableSize;
2898 if( nReserve<x ) nReserve = x;
2899 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
2900 sqlite3BtreeLeave(p);
2901 return SQLITE_READONLY;
2903 assert( nReserve>=0 && nReserve<=255 );
2904 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2905 ((pageSize-1)&pageSize)==0 ){
2906 assert( (pageSize & 7)==0 );
2907 assert( !pBt->pCursor );
2908 if( nReserve>32 && pageSize==512 ) pageSize = 1024;
2909 pBt->pageSize = (u32)pageSize;
2910 freeTempSpace(pBt);
2912 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2913 pBt->usableSize = pBt->pageSize - (u16)nReserve;
2914 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2915 sqlite3BtreeLeave(p);
2916 return rc;
2920 ** Return the currently defined page size
2922 int sqlite3BtreeGetPageSize(Btree *p){
2923 return p->pBt->pageSize;
2927 ** This function is similar to sqlite3BtreeGetReserve(), except that it
2928 ** may only be called if it is guaranteed that the b-tree mutex is already
2929 ** held.
2931 ** This is useful in one special case in the backup API code where it is
2932 ** known that the shared b-tree mutex is held, but the mutex on the
2933 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
2934 ** were to be called, it might collide with some other operation on the
2935 ** database handle that owns *p, causing undefined behavior.
2937 int sqlite3BtreeGetReserveNoMutex(Btree *p){
2938 int n;
2939 assert( sqlite3_mutex_held(p->pBt->mutex) );
2940 n = p->pBt->pageSize - p->pBt->usableSize;
2941 return n;
2945 ** Return the number of bytes of space at the end of every page that
2946 ** are intentually left unused. This is the "reserved" space that is
2947 ** sometimes used by extensions.
2949 ** The value returned is the larger of the current reserve size and
2950 ** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES.
2951 ** The amount of reserve can only grow - never shrink.
2953 int sqlite3BtreeGetRequestedReserve(Btree *p){
2954 int n1, n2;
2955 sqlite3BtreeEnter(p);
2956 n1 = (int)p->pBt->nReserveWanted;
2957 n2 = sqlite3BtreeGetReserveNoMutex(p);
2958 sqlite3BtreeLeave(p);
2959 return n1>n2 ? n1 : n2;
2964 ** Set the maximum page count for a database if mxPage is positive.
2965 ** No changes are made if mxPage is 0 or negative.
2966 ** Regardless of the value of mxPage, return the maximum page count.
2968 Pgno sqlite3BtreeMaxPageCount(Btree *p, Pgno mxPage){
2969 Pgno n;
2970 sqlite3BtreeEnter(p);
2971 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
2972 sqlite3BtreeLeave(p);
2973 return n;
2977 ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
2979 ** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
2980 ** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
2981 ** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
2982 ** newFlag==(-1) No changes
2984 ** This routine acts as a query if newFlag is less than zero
2986 ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
2987 ** freelist leaf pages are not written back to the database. Thus in-page
2988 ** deleted content is cleared, but freelist deleted content is not.
2990 ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
2991 ** that freelist leaf pages are written back into the database, increasing
2992 ** the amount of disk I/O.
2994 int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
2995 int b;
2996 if( p==0 ) return 0;
2997 sqlite3BtreeEnter(p);
2998 assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
2999 assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
3000 if( newFlag>=0 ){
3001 p->pBt->btsFlags &= ~BTS_FAST_SECURE;
3002 p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
3004 b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
3005 sqlite3BtreeLeave(p);
3006 return b;
3010 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
3011 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
3012 ** is disabled. The default value for the auto-vacuum property is
3013 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
3015 int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
3016 #ifdef SQLITE_OMIT_AUTOVACUUM
3017 return SQLITE_READONLY;
3018 #else
3019 BtShared *pBt = p->pBt;
3020 int rc = SQLITE_OK;
3021 u8 av = (u8)autoVacuum;
3023 sqlite3BtreeEnter(p);
3024 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
3025 rc = SQLITE_READONLY;
3026 }else{
3027 pBt->autoVacuum = av ?1:0;
3028 pBt->incrVacuum = av==2 ?1:0;
3030 sqlite3BtreeLeave(p);
3031 return rc;
3032 #endif
3036 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
3037 ** enabled 1 is returned. Otherwise 0.
3039 int sqlite3BtreeGetAutoVacuum(Btree *p){
3040 #ifdef SQLITE_OMIT_AUTOVACUUM
3041 return BTREE_AUTOVACUUM_NONE;
3042 #else
3043 int rc;
3044 sqlite3BtreeEnter(p);
3045 rc = (
3046 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
3047 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
3048 BTREE_AUTOVACUUM_INCR
3050 sqlite3BtreeLeave(p);
3051 return rc;
3052 #endif
3056 ** If the user has not set the safety-level for this database connection
3057 ** using "PRAGMA synchronous", and if the safety-level is not already
3058 ** set to the value passed to this function as the second parameter,
3059 ** set it so.
3061 #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
3062 && !defined(SQLITE_OMIT_WAL)
3063 static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
3064 sqlite3 *db;
3065 Db *pDb;
3066 if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
3067 while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
3068 if( pDb->bSyncSet==0
3069 && pDb->safety_level!=safety_level
3070 && pDb!=&db->aDb[1]
3072 pDb->safety_level = safety_level;
3073 sqlite3PagerSetFlags(pBt->pPager,
3074 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
3078 #else
3079 # define setDefaultSyncFlag(pBt,safety_level)
3080 #endif
3082 /* Forward declaration */
3083 static int newDatabase(BtShared*);
3087 ** Get a reference to pPage1 of the database file. This will
3088 ** also acquire a readlock on that file.
3090 ** SQLITE_OK is returned on success. If the file is not a
3091 ** well-formed database file, then SQLITE_CORRUPT is returned.
3092 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
3093 ** is returned if we run out of memory.
3095 static int lockBtree(BtShared *pBt){
3096 int rc; /* Result code from subfunctions */
3097 MemPage *pPage1; /* Page 1 of the database file */
3098 u32 nPage; /* Number of pages in the database */
3099 u32 nPageFile = 0; /* Number of pages in the database file */
3100 u32 nPageHeader; /* Number of pages in the database according to hdr */
3102 assert( sqlite3_mutex_held(pBt->mutex) );
3103 assert( pBt->pPage1==0 );
3104 rc = sqlite3PagerSharedLock(pBt->pPager);
3105 if( rc!=SQLITE_OK ) return rc;
3106 rc = btreeGetPage(pBt, 1, &pPage1, 0);
3107 if( rc!=SQLITE_OK ) return rc;
3109 /* Do some checking to help insure the file we opened really is
3110 ** a valid database file.
3112 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
3113 sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
3114 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
3115 nPage = nPageFile;
3117 if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
3118 nPage = 0;
3120 if( nPage>0 ){
3121 u32 pageSize;
3122 u32 usableSize;
3123 u8 *page1 = pPage1->aData;
3124 rc = SQLITE_NOTADB;
3125 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
3126 ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
3127 ** 61 74 20 33 00. */
3128 if( memcmp(page1, zMagicHeader, 16)!=0 ){
3129 goto page1_init_failed;
3132 #ifdef SQLITE_OMIT_WAL
3133 if( page1[18]>1 ){
3134 pBt->btsFlags |= BTS_READ_ONLY;
3136 if( page1[19]>1 ){
3137 goto page1_init_failed;
3139 #else
3140 if( page1[18]>2 ){
3141 pBt->btsFlags |= BTS_READ_ONLY;
3143 if( page1[19]>2 ){
3144 goto page1_init_failed;
3147 /* If the write version is set to 2, this database should be accessed
3148 ** in WAL mode. If the log is not already open, open it now. Then
3149 ** return SQLITE_OK and return without populating BtShared.pPage1.
3150 ** The caller detects this and calls this function again. This is
3151 ** required as the version of page 1 currently in the page1 buffer
3152 ** may not be the latest version - there may be a newer one in the log
3153 ** file.
3155 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
3156 int isOpen = 0;
3157 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
3158 if( rc!=SQLITE_OK ){
3159 goto page1_init_failed;
3160 }else{
3161 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
3162 if( isOpen==0 ){
3163 releasePageOne(pPage1);
3164 return SQLITE_OK;
3167 rc = SQLITE_NOTADB;
3168 }else{
3169 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
3171 #endif
3173 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
3174 ** fractions and the leaf payload fraction values must be 64, 32, and 32.
3176 ** The original design allowed these amounts to vary, but as of
3177 ** version 3.6.0, we require them to be fixed.
3179 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
3180 goto page1_init_failed;
3182 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
3183 ** determined by the 2-byte integer located at an offset of 16 bytes from
3184 ** the beginning of the database file. */
3185 pageSize = (page1[16]<<8) | (page1[17]<<16);
3186 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
3187 ** between 512 and 65536 inclusive. */
3188 if( ((pageSize-1)&pageSize)!=0
3189 || pageSize>SQLITE_MAX_PAGE_SIZE
3190 || pageSize<=256
3192 goto page1_init_failed;
3194 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3195 assert( (pageSize & 7)==0 );
3196 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
3197 ** integer at offset 20 is the number of bytes of space at the end of
3198 ** each page to reserve for extensions.
3200 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
3201 ** determined by the one-byte unsigned integer found at an offset of 20
3202 ** into the database file header. */
3203 usableSize = pageSize - page1[20];
3204 if( (u32)pageSize!=pBt->pageSize ){
3205 /* After reading the first page of the database assuming a page size
3206 ** of BtShared.pageSize, we have discovered that the page-size is
3207 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
3208 ** zero and return SQLITE_OK. The caller will call this function
3209 ** again with the correct page-size.
3211 releasePageOne(pPage1);
3212 pBt->usableSize = usableSize;
3213 pBt->pageSize = pageSize;
3214 freeTempSpace(pBt);
3215 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
3216 pageSize-usableSize);
3217 return rc;
3219 if( sqlite3WritableSchema(pBt->db)==0 && nPage>nPageFile ){
3220 rc = SQLITE_CORRUPT_BKPT;
3221 goto page1_init_failed;
3223 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
3224 ** be less than 480. In other words, if the page size is 512, then the
3225 ** reserved space size cannot exceed 32. */
3226 if( usableSize<480 ){
3227 goto page1_init_failed;
3229 pBt->pageSize = pageSize;
3230 pBt->usableSize = usableSize;
3231 #ifndef SQLITE_OMIT_AUTOVACUUM
3232 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
3233 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
3234 #endif
3237 /* maxLocal is the maximum amount of payload to store locally for
3238 ** a cell. Make sure it is small enough so that at least minFanout
3239 ** cells can will fit on one page. We assume a 10-byte page header.
3240 ** Besides the payload, the cell must store:
3241 ** 2-byte pointer to the cell
3242 ** 4-byte child pointer
3243 ** 9-byte nKey value
3244 ** 4-byte nData value
3245 ** 4-byte overflow page pointer
3246 ** So a cell consists of a 2-byte pointer, a header which is as much as
3247 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
3248 ** page pointer.
3250 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
3251 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
3252 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
3253 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
3254 if( pBt->maxLocal>127 ){
3255 pBt->max1bytePayload = 127;
3256 }else{
3257 pBt->max1bytePayload = (u8)pBt->maxLocal;
3259 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
3260 pBt->pPage1 = pPage1;
3261 pBt->nPage = nPage;
3262 return SQLITE_OK;
3264 page1_init_failed:
3265 releasePageOne(pPage1);
3266 pBt->pPage1 = 0;
3267 return rc;
3270 #ifndef NDEBUG
3272 ** Return the number of cursors open on pBt. This is for use
3273 ** in assert() expressions, so it is only compiled if NDEBUG is not
3274 ** defined.
3276 ** Only write cursors are counted if wrOnly is true. If wrOnly is
3277 ** false then all cursors are counted.
3279 ** For the purposes of this routine, a cursor is any cursor that
3280 ** is capable of reading or writing to the database. Cursors that
3281 ** have been tripped into the CURSOR_FAULT state are not counted.
3283 static int countValidCursors(BtShared *pBt, int wrOnly){
3284 BtCursor *pCur;
3285 int r = 0;
3286 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3287 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
3288 && pCur->eState!=CURSOR_FAULT ) r++;
3290 return r;
3292 #endif
3295 ** If there are no outstanding cursors and we are not in the middle
3296 ** of a transaction but there is a read lock on the database, then
3297 ** this routine unrefs the first page of the database file which
3298 ** has the effect of releasing the read lock.
3300 ** If there is a transaction in progress, this routine is a no-op.
3302 static void unlockBtreeIfUnused(BtShared *pBt){
3303 assert( sqlite3_mutex_held(pBt->mutex) );
3304 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
3305 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
3306 MemPage *pPage1 = pBt->pPage1;
3307 assert( pPage1->aData );
3308 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
3309 pBt->pPage1 = 0;
3310 releasePageOne(pPage1);
3315 ** If pBt points to an empty file then convert that empty file
3316 ** into a new empty database by initializing the first page of
3317 ** the database.
3319 static int newDatabase(BtShared *pBt){
3320 MemPage *pP1;
3321 unsigned char *data;
3322 int rc;
3324 assert( sqlite3_mutex_held(pBt->mutex) );
3325 if( pBt->nPage>0 ){
3326 return SQLITE_OK;
3328 pP1 = pBt->pPage1;
3329 assert( pP1!=0 );
3330 data = pP1->aData;
3331 rc = sqlite3PagerWrite(pP1->pDbPage);
3332 if( rc ) return rc;
3333 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
3334 assert( sizeof(zMagicHeader)==16 );
3335 data[16] = (u8)((pBt->pageSize>>8)&0xff);
3336 data[17] = (u8)((pBt->pageSize>>16)&0xff);
3337 data[18] = 1;
3338 data[19] = 1;
3339 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
3340 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
3341 data[21] = 64;
3342 data[22] = 32;
3343 data[23] = 32;
3344 memset(&data[24], 0, 100-24);
3345 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
3346 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3347 #ifndef SQLITE_OMIT_AUTOVACUUM
3348 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
3349 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
3350 put4byte(&data[36 + 4*4], pBt->autoVacuum);
3351 put4byte(&data[36 + 7*4], pBt->incrVacuum);
3352 #endif
3353 pBt->nPage = 1;
3354 data[31] = 1;
3355 return SQLITE_OK;
3359 ** Initialize the first page of the database file (creating a database
3360 ** consisting of a single page and no schema objects). Return SQLITE_OK
3361 ** if successful, or an SQLite error code otherwise.
3363 int sqlite3BtreeNewDb(Btree *p){
3364 int rc;
3365 sqlite3BtreeEnter(p);
3366 p->pBt->nPage = 0;
3367 rc = newDatabase(p->pBt);
3368 sqlite3BtreeLeave(p);
3369 return rc;
3373 ** Attempt to start a new transaction. A write-transaction
3374 ** is started if the second argument is nonzero, otherwise a read-
3375 ** transaction. If the second argument is 2 or more and exclusive
3376 ** transaction is started, meaning that no other process is allowed
3377 ** to access the database. A preexisting transaction may not be
3378 ** upgraded to exclusive by calling this routine a second time - the
3379 ** exclusivity flag only works for a new transaction.
3381 ** A write-transaction must be started before attempting any
3382 ** changes to the database. None of the following routines
3383 ** will work unless a transaction is started first:
3385 ** sqlite3BtreeCreateTable()
3386 ** sqlite3BtreeCreateIndex()
3387 ** sqlite3BtreeClearTable()
3388 ** sqlite3BtreeDropTable()
3389 ** sqlite3BtreeInsert()
3390 ** sqlite3BtreeDelete()
3391 ** sqlite3BtreeUpdateMeta()
3393 ** If an initial attempt to acquire the lock fails because of lock contention
3394 ** and the database was previously unlocked, then invoke the busy handler
3395 ** if there is one. But if there was previously a read-lock, do not
3396 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
3397 ** returned when there is already a read-lock in order to avoid a deadlock.
3399 ** Suppose there are two processes A and B. A has a read lock and B has
3400 ** a reserved lock. B tries to promote to exclusive but is blocked because
3401 ** of A's read lock. A tries to promote to reserved but is blocked by B.
3402 ** One or the other of the two processes must give way or there can be
3403 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
3404 ** when A already has a read lock, we encourage A to give up and let B
3405 ** proceed.
3407 int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
3408 BtShared *pBt = p->pBt;
3409 Pager *pPager = pBt->pPager;
3410 int rc = SQLITE_OK;
3412 sqlite3BtreeEnter(p);
3413 btreeIntegrity(p);
3415 /* If the btree is already in a write-transaction, or it
3416 ** is already in a read-transaction and a read-transaction
3417 ** is requested, this is a no-op.
3419 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
3420 goto trans_begun;
3422 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
3424 if( (p->db->flags & SQLITE_ResetDatabase)
3425 && sqlite3PagerIsreadonly(pPager)==0
3427 pBt->btsFlags &= ~BTS_READ_ONLY;
3430 /* Write transactions are not possible on a read-only database */
3431 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
3432 rc = SQLITE_READONLY;
3433 goto trans_begun;
3436 #ifndef SQLITE_OMIT_SHARED_CACHE
3438 sqlite3 *pBlock = 0;
3439 /* If another database handle has already opened a write transaction
3440 ** on this shared-btree structure and a second write transaction is
3441 ** requested, return SQLITE_LOCKED.
3443 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
3444 || (pBt->btsFlags & BTS_PENDING)!=0
3446 pBlock = pBt->pWriter->db;
3447 }else if( wrflag>1 ){
3448 BtLock *pIter;
3449 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
3450 if( pIter->pBtree!=p ){
3451 pBlock = pIter->pBtree->db;
3452 break;
3456 if( pBlock ){
3457 sqlite3ConnectionBlocked(p->db, pBlock);
3458 rc = SQLITE_LOCKED_SHAREDCACHE;
3459 goto trans_begun;
3462 #endif
3464 /* Any read-only or read-write transaction implies a read-lock on
3465 ** page 1. So if some other shared-cache client already has a write-lock
3466 ** on page 1, the transaction cannot be opened. */
3467 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
3468 if( SQLITE_OK!=rc ) goto trans_begun;
3470 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
3471 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
3472 do {
3473 sqlite3PagerWalDb(pPager, p->db);
3475 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3476 /* If transitioning from no transaction directly to a write transaction,
3477 ** block for the WRITER lock first if possible. */
3478 if( pBt->pPage1==0 && wrflag ){
3479 assert( pBt->inTransaction==TRANS_NONE );
3480 rc = sqlite3PagerWalWriteLock(pPager, 1);
3481 if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break;
3483 #endif
3485 /* Call lockBtree() until either pBt->pPage1 is populated or
3486 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
3487 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
3488 ** reading page 1 it discovers that the page-size of the database
3489 ** file is not pBt->pageSize. In this case lockBtree() will update
3490 ** pBt->pageSize to the page-size of the file on disk.
3492 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
3494 if( rc==SQLITE_OK && wrflag ){
3495 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
3496 rc = SQLITE_READONLY;
3497 }else{
3498 rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db));
3499 if( rc==SQLITE_OK ){
3500 rc = newDatabase(pBt);
3501 }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
3502 /* if there was no transaction opened when this function was
3503 ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
3504 ** code to SQLITE_BUSY. */
3505 rc = SQLITE_BUSY;
3510 if( rc!=SQLITE_OK ){
3511 (void)sqlite3PagerWalWriteLock(pPager, 0);
3512 unlockBtreeIfUnused(pBt);
3514 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
3515 btreeInvokeBusyHandler(pBt) );
3516 sqlite3PagerWalDb(pPager, 0);
3517 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3518 if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
3519 #endif
3521 if( rc==SQLITE_OK ){
3522 if( p->inTrans==TRANS_NONE ){
3523 pBt->nTransaction++;
3524 #ifndef SQLITE_OMIT_SHARED_CACHE
3525 if( p->sharable ){
3526 assert( p->lock.pBtree==p && p->lock.iTable==1 );
3527 p->lock.eLock = READ_LOCK;
3528 p->lock.pNext = pBt->pLock;
3529 pBt->pLock = &p->lock;
3531 #endif
3533 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
3534 if( p->inTrans>pBt->inTransaction ){
3535 pBt->inTransaction = p->inTrans;
3537 if( wrflag ){
3538 MemPage *pPage1 = pBt->pPage1;
3539 #ifndef SQLITE_OMIT_SHARED_CACHE
3540 assert( !pBt->pWriter );
3541 pBt->pWriter = p;
3542 pBt->btsFlags &= ~BTS_EXCLUSIVE;
3543 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
3544 #endif
3546 /* If the db-size header field is incorrect (as it may be if an old
3547 ** client has been writing the database file), update it now. Doing
3548 ** this sooner rather than later means the database size can safely
3549 ** re-read the database size from page 1 if a savepoint or transaction
3550 ** rollback occurs within the transaction.
3552 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
3553 rc = sqlite3PagerWrite(pPage1->pDbPage);
3554 if( rc==SQLITE_OK ){
3555 put4byte(&pPage1->aData[28], pBt->nPage);
3561 trans_begun:
3562 if( rc==SQLITE_OK ){
3563 if( pSchemaVersion ){
3564 *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
3566 if( wrflag ){
3567 /* This call makes sure that the pager has the correct number of
3568 ** open savepoints. If the second parameter is greater than 0 and
3569 ** the sub-journal is not already open, then it will be opened here.
3571 rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint);
3575 btreeIntegrity(p);
3576 sqlite3BtreeLeave(p);
3577 return rc;
3580 #ifndef SQLITE_OMIT_AUTOVACUUM
3583 ** Set the pointer-map entries for all children of page pPage. Also, if
3584 ** pPage contains cells that point to overflow pages, set the pointer
3585 ** map entries for the overflow pages as well.
3587 static int setChildPtrmaps(MemPage *pPage){
3588 int i; /* Counter variable */
3589 int nCell; /* Number of cells in page pPage */
3590 int rc; /* Return code */
3591 BtShared *pBt = pPage->pBt;
3592 Pgno pgno = pPage->pgno;
3594 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3595 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3596 if( rc!=SQLITE_OK ) return rc;
3597 nCell = pPage->nCell;
3599 for(i=0; i<nCell; i++){
3600 u8 *pCell = findCell(pPage, i);
3602 ptrmapPutOvflPtr(pPage, pPage, pCell, &rc);
3604 if( !pPage->leaf ){
3605 Pgno childPgno = get4byte(pCell);
3606 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3610 if( !pPage->leaf ){
3611 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
3612 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3615 return rc;
3619 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
3620 ** that it points to iTo. Parameter eType describes the type of pointer to
3621 ** be modified, as follows:
3623 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
3624 ** page of pPage.
3626 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3627 ** page pointed to by one of the cells on pPage.
3629 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3630 ** overflow page in the list.
3632 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
3633 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3634 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
3635 if( eType==PTRMAP_OVERFLOW2 ){
3636 /* The pointer is always the first 4 bytes of the page in this case. */
3637 if( get4byte(pPage->aData)!=iFrom ){
3638 return SQLITE_CORRUPT_PAGE(pPage);
3640 put4byte(pPage->aData, iTo);
3641 }else{
3642 int i;
3643 int nCell;
3644 int rc;
3646 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3647 if( rc ) return rc;
3648 nCell = pPage->nCell;
3650 for(i=0; i<nCell; i++){
3651 u8 *pCell = findCell(pPage, i);
3652 if( eType==PTRMAP_OVERFLOW1 ){
3653 CellInfo info;
3654 pPage->xParseCell(pPage, pCell, &info);
3655 if( info.nLocal<info.nPayload ){
3656 if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
3657 return SQLITE_CORRUPT_PAGE(pPage);
3659 if( iFrom==get4byte(pCell+info.nSize-4) ){
3660 put4byte(pCell+info.nSize-4, iTo);
3661 break;
3664 }else{
3665 if( get4byte(pCell)==iFrom ){
3666 put4byte(pCell, iTo);
3667 break;
3672 if( i==nCell ){
3673 if( eType!=PTRMAP_BTREE ||
3674 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
3675 return SQLITE_CORRUPT_PAGE(pPage);
3677 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3680 return SQLITE_OK;
3685 ** Move the open database page pDbPage to location iFreePage in the
3686 ** database. The pDbPage reference remains valid.
3688 ** The isCommit flag indicates that there is no need to remember that
3689 ** the journal needs to be sync()ed before database page pDbPage->pgno
3690 ** can be written to. The caller has already promised not to write to that
3691 ** page.
3693 static int relocatePage(
3694 BtShared *pBt, /* Btree */
3695 MemPage *pDbPage, /* Open page to move */
3696 u8 eType, /* Pointer map 'type' entry for pDbPage */
3697 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
3698 Pgno iFreePage, /* The location to move pDbPage to */
3699 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
3701 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
3702 Pgno iDbPage = pDbPage->pgno;
3703 Pager *pPager = pBt->pPager;
3704 int rc;
3706 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3707 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
3708 assert( sqlite3_mutex_held(pBt->mutex) );
3709 assert( pDbPage->pBt==pBt );
3710 if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
3712 /* Move page iDbPage from its current location to page number iFreePage */
3713 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
3714 iDbPage, iFreePage, iPtrPage, eType));
3715 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
3716 if( rc!=SQLITE_OK ){
3717 return rc;
3719 pDbPage->pgno = iFreePage;
3721 /* If pDbPage was a btree-page, then it may have child pages and/or cells
3722 ** that point to overflow pages. The pointer map entries for all these
3723 ** pages need to be changed.
3725 ** If pDbPage is an overflow page, then the first 4 bytes may store a
3726 ** pointer to a subsequent overflow page. If this is the case, then
3727 ** the pointer map needs to be updated for the subsequent overflow page.
3729 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
3730 rc = setChildPtrmaps(pDbPage);
3731 if( rc!=SQLITE_OK ){
3732 return rc;
3734 }else{
3735 Pgno nextOvfl = get4byte(pDbPage->aData);
3736 if( nextOvfl!=0 ){
3737 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
3738 if( rc!=SQLITE_OK ){
3739 return rc;
3744 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3745 ** that it points at iFreePage. Also fix the pointer map entry for
3746 ** iPtrPage.
3748 if( eType!=PTRMAP_ROOTPAGE ){
3749 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
3750 if( rc!=SQLITE_OK ){
3751 return rc;
3753 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
3754 if( rc!=SQLITE_OK ){
3755 releasePage(pPtrPage);
3756 return rc;
3758 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
3759 releasePage(pPtrPage);
3760 if( rc==SQLITE_OK ){
3761 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
3764 return rc;
3767 /* Forward declaration required by incrVacuumStep(). */
3768 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
3771 ** Perform a single step of an incremental-vacuum. If successful, return
3772 ** SQLITE_OK. If there is no work to do (and therefore no point in
3773 ** calling this function again), return SQLITE_DONE. Or, if an error
3774 ** occurs, return some other error code.
3776 ** More specifically, this function attempts to re-organize the database so
3777 ** that the last page of the file currently in use is no longer in use.
3779 ** Parameter nFin is the number of pages that this database would contain
3780 ** were this function called until it returns SQLITE_DONE.
3782 ** If the bCommit parameter is non-zero, this function assumes that the
3783 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
3784 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
3785 ** operation, or false for an incremental vacuum.
3787 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
3788 Pgno nFreeList; /* Number of pages still on the free-list */
3789 int rc;
3791 assert( sqlite3_mutex_held(pBt->mutex) );
3792 assert( iLastPg>nFin );
3794 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
3795 u8 eType;
3796 Pgno iPtrPage;
3798 nFreeList = get4byte(&pBt->pPage1->aData[36]);
3799 if( nFreeList==0 ){
3800 return SQLITE_DONE;
3803 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3804 if( rc!=SQLITE_OK ){
3805 return rc;
3807 if( eType==PTRMAP_ROOTPAGE ){
3808 return SQLITE_CORRUPT_BKPT;
3811 if( eType==PTRMAP_FREEPAGE ){
3812 if( bCommit==0 ){
3813 /* Remove the page from the files free-list. This is not required
3814 ** if bCommit is non-zero. In that case, the free-list will be
3815 ** truncated to zero after this function returns, so it doesn't
3816 ** matter if it still contains some garbage entries.
3818 Pgno iFreePg;
3819 MemPage *pFreePg;
3820 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
3821 if( rc!=SQLITE_OK ){
3822 return rc;
3824 assert( iFreePg==iLastPg );
3825 releasePage(pFreePg);
3827 } else {
3828 Pgno iFreePg; /* Index of free page to move pLastPg to */
3829 MemPage *pLastPg;
3830 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
3831 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
3833 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
3834 if( rc!=SQLITE_OK ){
3835 return rc;
3838 /* If bCommit is zero, this loop runs exactly once and page pLastPg
3839 ** is swapped with the first free page pulled off the free list.
3841 ** On the other hand, if bCommit is greater than zero, then keep
3842 ** looping until a free-page located within the first nFin pages
3843 ** of the file is found.
3845 if( bCommit==0 ){
3846 eMode = BTALLOC_LE;
3847 iNear = nFin;
3849 do {
3850 MemPage *pFreePg;
3851 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
3852 if( rc!=SQLITE_OK ){
3853 releasePage(pLastPg);
3854 return rc;
3856 releasePage(pFreePg);
3857 }while( bCommit && iFreePg>nFin );
3858 assert( iFreePg<iLastPg );
3860 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
3861 releasePage(pLastPg);
3862 if( rc!=SQLITE_OK ){
3863 return rc;
3868 if( bCommit==0 ){
3869 do {
3870 iLastPg--;
3871 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
3872 pBt->bDoTruncate = 1;
3873 pBt->nPage = iLastPg;
3875 return SQLITE_OK;
3879 ** The database opened by the first argument is an auto-vacuum database
3880 ** nOrig pages in size containing nFree free pages. Return the expected
3881 ** size of the database in pages following an auto-vacuum operation.
3883 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
3884 int nEntry; /* Number of entries on one ptrmap page */
3885 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
3886 Pgno nFin; /* Return value */
3888 nEntry = pBt->usableSize/5;
3889 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
3890 nFin = nOrig - nFree - nPtrmap;
3891 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
3892 nFin--;
3894 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
3895 nFin--;
3898 return nFin;
3902 ** A write-transaction must be opened before calling this function.
3903 ** It performs a single unit of work towards an incremental vacuum.
3905 ** If the incremental vacuum is finished after this function has run,
3906 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
3907 ** SQLITE_OK is returned. Otherwise an SQLite error code.
3909 int sqlite3BtreeIncrVacuum(Btree *p){
3910 int rc;
3911 BtShared *pBt = p->pBt;
3913 sqlite3BtreeEnter(p);
3914 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
3915 if( !pBt->autoVacuum ){
3916 rc = SQLITE_DONE;
3917 }else{
3918 Pgno nOrig = btreePagecount(pBt);
3919 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
3920 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
3922 if( nOrig<nFin || nFree>=nOrig ){
3923 rc = SQLITE_CORRUPT_BKPT;
3924 }else if( nFree>0 ){
3925 rc = saveAllCursors(pBt, 0, 0);
3926 if( rc==SQLITE_OK ){
3927 invalidateAllOverflowCache(pBt);
3928 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
3930 if( rc==SQLITE_OK ){
3931 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3932 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
3934 }else{
3935 rc = SQLITE_DONE;
3938 sqlite3BtreeLeave(p);
3939 return rc;
3943 ** This routine is called prior to sqlite3PagerCommit when a transaction
3944 ** is committed for an auto-vacuum database.
3946 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
3947 ** the database file should be truncated to during the commit process.
3948 ** i.e. the database has been reorganized so that only the first *pnTrunc
3949 ** pages are in use.
3951 static int autoVacuumCommit(BtShared *pBt){
3952 int rc = SQLITE_OK;
3953 Pager *pPager = pBt->pPager;
3954 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
3956 assert( sqlite3_mutex_held(pBt->mutex) );
3957 invalidateAllOverflowCache(pBt);
3958 assert(pBt->autoVacuum);
3959 if( !pBt->incrVacuum ){
3960 Pgno nFin; /* Number of pages in database after autovacuuming */
3961 Pgno nFree; /* Number of pages on the freelist initially */
3962 Pgno iFree; /* The next page to be freed */
3963 Pgno nOrig; /* Database size before freeing */
3965 nOrig = btreePagecount(pBt);
3966 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
3967 /* It is not possible to create a database for which the final page
3968 ** is either a pointer-map page or the pending-byte page. If one
3969 ** is encountered, this indicates corruption.
3971 return SQLITE_CORRUPT_BKPT;
3974 nFree = get4byte(&pBt->pPage1->aData[36]);
3975 nFin = finalDbSize(pBt, nOrig, nFree);
3976 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
3977 if( nFin<nOrig ){
3978 rc = saveAllCursors(pBt, 0, 0);
3980 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
3981 rc = incrVacuumStep(pBt, nFin, iFree, 1);
3983 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
3984 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3985 put4byte(&pBt->pPage1->aData[32], 0);
3986 put4byte(&pBt->pPage1->aData[36], 0);
3987 put4byte(&pBt->pPage1->aData[28], nFin);
3988 pBt->bDoTruncate = 1;
3989 pBt->nPage = nFin;
3991 if( rc!=SQLITE_OK ){
3992 sqlite3PagerRollback(pPager);
3996 assert( nRef>=sqlite3PagerRefcount(pPager) );
3997 return rc;
4000 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
4001 # define setChildPtrmaps(x) SQLITE_OK
4002 #endif
4005 ** This routine does the first phase of a two-phase commit. This routine
4006 ** causes a rollback journal to be created (if it does not already exist)
4007 ** and populated with enough information so that if a power loss occurs
4008 ** the database can be restored to its original state by playing back
4009 ** the journal. Then the contents of the journal are flushed out to
4010 ** the disk. After the journal is safely on oxide, the changes to the
4011 ** database are written into the database file and flushed to oxide.
4012 ** At the end of this call, the rollback journal still exists on the
4013 ** disk and we are still holding all locks, so the transaction has not
4014 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
4015 ** commit process.
4017 ** This call is a no-op if no write-transaction is currently active on pBt.
4019 ** Otherwise, sync the database file for the btree pBt. zSuperJrnl points to
4020 ** the name of a super-journal file that should be written into the
4021 ** individual journal file, or is NULL, indicating no super-journal file
4022 ** (single database transaction).
4024 ** When this is called, the super-journal should already have been
4025 ** created, populated with this journal pointer and synced to disk.
4027 ** Once this is routine has returned, the only thing required to commit
4028 ** the write-transaction for this database file is to delete the journal.
4030 int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zSuperJrnl){
4031 int rc = SQLITE_OK;
4032 if( p->inTrans==TRANS_WRITE ){
4033 BtShared *pBt = p->pBt;
4034 sqlite3BtreeEnter(p);
4035 #ifndef SQLITE_OMIT_AUTOVACUUM
4036 if( pBt->autoVacuum ){
4037 rc = autoVacuumCommit(pBt);
4038 if( rc!=SQLITE_OK ){
4039 sqlite3BtreeLeave(p);
4040 return rc;
4043 if( pBt->bDoTruncate ){
4044 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
4046 #endif
4047 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0);
4048 sqlite3BtreeLeave(p);
4050 return rc;
4054 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
4055 ** at the conclusion of a transaction.
4057 static void btreeEndTransaction(Btree *p){
4058 BtShared *pBt = p->pBt;
4059 sqlite3 *db = p->db;
4060 assert( sqlite3BtreeHoldsMutex(p) );
4062 #ifndef SQLITE_OMIT_AUTOVACUUM
4063 pBt->bDoTruncate = 0;
4064 #endif
4065 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
4066 /* If there are other active statements that belong to this database
4067 ** handle, downgrade to a read-only transaction. The other statements
4068 ** may still be reading from the database. */
4069 downgradeAllSharedCacheTableLocks(p);
4070 p->inTrans = TRANS_READ;
4071 }else{
4072 /* If the handle had any kind of transaction open, decrement the
4073 ** transaction count of the shared btree. If the transaction count
4074 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
4075 ** call below will unlock the pager. */
4076 if( p->inTrans!=TRANS_NONE ){
4077 clearAllSharedCacheTableLocks(p);
4078 pBt->nTransaction--;
4079 if( 0==pBt->nTransaction ){
4080 pBt->inTransaction = TRANS_NONE;
4084 /* Set the current transaction state to TRANS_NONE and unlock the
4085 ** pager if this call closed the only read or write transaction. */
4086 p->inTrans = TRANS_NONE;
4087 unlockBtreeIfUnused(pBt);
4090 btreeIntegrity(p);
4094 ** Commit the transaction currently in progress.
4096 ** This routine implements the second phase of a 2-phase commit. The
4097 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
4098 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
4099 ** routine did all the work of writing information out to disk and flushing the
4100 ** contents so that they are written onto the disk platter. All this
4101 ** routine has to do is delete or truncate or zero the header in the
4102 ** the rollback journal (which causes the transaction to commit) and
4103 ** drop locks.
4105 ** Normally, if an error occurs while the pager layer is attempting to
4106 ** finalize the underlying journal file, this function returns an error and
4107 ** the upper layer will attempt a rollback. However, if the second argument
4108 ** is non-zero then this b-tree transaction is part of a multi-file
4109 ** transaction. In this case, the transaction has already been committed
4110 ** (by deleting a super-journal file) and the caller will ignore this
4111 ** functions return code. So, even if an error occurs in the pager layer,
4112 ** reset the b-tree objects internal state to indicate that the write
4113 ** transaction has been closed. This is quite safe, as the pager will have
4114 ** transitioned to the error state.
4116 ** This will release the write lock on the database file. If there
4117 ** are no active cursors, it also releases the read lock.
4119 int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
4121 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
4122 sqlite3BtreeEnter(p);
4123 btreeIntegrity(p);
4125 /* If the handle has a write-transaction open, commit the shared-btrees
4126 ** transaction and set the shared state to TRANS_READ.
4128 if( p->inTrans==TRANS_WRITE ){
4129 int rc;
4130 BtShared *pBt = p->pBt;
4131 assert( pBt->inTransaction==TRANS_WRITE );
4132 assert( pBt->nTransaction>0 );
4133 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
4134 if( rc!=SQLITE_OK && bCleanup==0 ){
4135 sqlite3BtreeLeave(p);
4136 return rc;
4138 p->iBDataVersion--; /* Compensate for pPager->iDataVersion++; */
4139 pBt->inTransaction = TRANS_READ;
4140 btreeClearHasContent(pBt);
4143 btreeEndTransaction(p);
4144 sqlite3BtreeLeave(p);
4145 return SQLITE_OK;
4149 ** Do both phases of a commit.
4151 int sqlite3BtreeCommit(Btree *p){
4152 int rc;
4153 sqlite3BtreeEnter(p);
4154 rc = sqlite3BtreeCommitPhaseOne(p, 0);
4155 if( rc==SQLITE_OK ){
4156 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
4158 sqlite3BtreeLeave(p);
4159 return rc;
4163 ** This routine sets the state to CURSOR_FAULT and the error
4164 ** code to errCode for every cursor on any BtShared that pBtree
4165 ** references. Or if the writeOnly flag is set to 1, then only
4166 ** trip write cursors and leave read cursors unchanged.
4168 ** Every cursor is a candidate to be tripped, including cursors
4169 ** that belong to other database connections that happen to be
4170 ** sharing the cache with pBtree.
4172 ** This routine gets called when a rollback occurs. If the writeOnly
4173 ** flag is true, then only write-cursors need be tripped - read-only
4174 ** cursors save their current positions so that they may continue
4175 ** following the rollback. Or, if writeOnly is false, all cursors are
4176 ** tripped. In general, writeOnly is false if the transaction being
4177 ** rolled back modified the database schema. In this case b-tree root
4178 ** pages may be moved or deleted from the database altogether, making
4179 ** it unsafe for read cursors to continue.
4181 ** If the writeOnly flag is true and an error is encountered while
4182 ** saving the current position of a read-only cursor, all cursors,
4183 ** including all read-cursors are tripped.
4185 ** SQLITE_OK is returned if successful, or if an error occurs while
4186 ** saving a cursor position, an SQLite error code.
4188 int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
4189 BtCursor *p;
4190 int rc = SQLITE_OK;
4192 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
4193 if( pBtree ){
4194 sqlite3BtreeEnter(pBtree);
4195 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
4196 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
4197 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
4198 rc = saveCursorPosition(p);
4199 if( rc!=SQLITE_OK ){
4200 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
4201 break;
4204 }else{
4205 sqlite3BtreeClearCursor(p);
4206 p->eState = CURSOR_FAULT;
4207 p->skipNext = errCode;
4209 btreeReleaseAllCursorPages(p);
4211 sqlite3BtreeLeave(pBtree);
4213 return rc;
4217 ** Set the pBt->nPage field correctly, according to the current
4218 ** state of the database. Assume pBt->pPage1 is valid.
4220 static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){
4221 int nPage = get4byte(&pPage1->aData[28]);
4222 testcase( nPage==0 );
4223 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
4224 testcase( pBt->nPage!=nPage );
4225 pBt->nPage = nPage;
4229 ** Rollback the transaction in progress.
4231 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
4232 ** Only write cursors are tripped if writeOnly is true but all cursors are
4233 ** tripped if writeOnly is false. Any attempt to use
4234 ** a tripped cursor will result in an error.
4236 ** This will release the write lock on the database file. If there
4237 ** are no active cursors, it also releases the read lock.
4239 int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
4240 int rc;
4241 BtShared *pBt = p->pBt;
4242 MemPage *pPage1;
4244 assert( writeOnly==1 || writeOnly==0 );
4245 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
4246 sqlite3BtreeEnter(p);
4247 if( tripCode==SQLITE_OK ){
4248 rc = tripCode = saveAllCursors(pBt, 0, 0);
4249 if( rc ) writeOnly = 0;
4250 }else{
4251 rc = SQLITE_OK;
4253 if( tripCode ){
4254 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
4255 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
4256 if( rc2!=SQLITE_OK ) rc = rc2;
4258 btreeIntegrity(p);
4260 if( p->inTrans==TRANS_WRITE ){
4261 int rc2;
4263 assert( TRANS_WRITE==pBt->inTransaction );
4264 rc2 = sqlite3PagerRollback(pBt->pPager);
4265 if( rc2!=SQLITE_OK ){
4266 rc = rc2;
4269 /* The rollback may have destroyed the pPage1->aData value. So
4270 ** call btreeGetPage() on page 1 again to make
4271 ** sure pPage1->aData is set correctly. */
4272 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
4273 btreeSetNPage(pBt, pPage1);
4274 releasePageOne(pPage1);
4276 assert( countValidCursors(pBt, 1)==0 );
4277 pBt->inTransaction = TRANS_READ;
4278 btreeClearHasContent(pBt);
4281 btreeEndTransaction(p);
4282 sqlite3BtreeLeave(p);
4283 return rc;
4287 ** Start a statement subtransaction. The subtransaction can be rolled
4288 ** back independently of the main transaction. You must start a transaction
4289 ** before starting a subtransaction. The subtransaction is ended automatically
4290 ** if the main transaction commits or rolls back.
4292 ** Statement subtransactions are used around individual SQL statements
4293 ** that are contained within a BEGIN...COMMIT block. If a constraint
4294 ** error occurs within the statement, the effect of that one statement
4295 ** can be rolled back without having to rollback the entire transaction.
4297 ** A statement sub-transaction is implemented as an anonymous savepoint. The
4298 ** value passed as the second parameter is the total number of savepoints,
4299 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
4300 ** are no active savepoints and no other statement-transactions open,
4301 ** iStatement is 1. This anonymous savepoint can be released or rolled back
4302 ** using the sqlite3BtreeSavepoint() function.
4304 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
4305 int rc;
4306 BtShared *pBt = p->pBt;
4307 sqlite3BtreeEnter(p);
4308 assert( p->inTrans==TRANS_WRITE );
4309 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
4310 assert( iStatement>0 );
4311 assert( iStatement>p->db->nSavepoint );
4312 assert( pBt->inTransaction==TRANS_WRITE );
4313 /* At the pager level, a statement transaction is a savepoint with
4314 ** an index greater than all savepoints created explicitly using
4315 ** SQL statements. It is illegal to open, release or rollback any
4316 ** such savepoints while the statement transaction savepoint is active.
4318 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
4319 sqlite3BtreeLeave(p);
4320 return rc;
4324 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
4325 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
4326 ** savepoint identified by parameter iSavepoint, depending on the value
4327 ** of op.
4329 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
4330 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
4331 ** contents of the entire transaction are rolled back. This is different
4332 ** from a normal transaction rollback, as no locks are released and the
4333 ** transaction remains open.
4335 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
4336 int rc = SQLITE_OK;
4337 if( p && p->inTrans==TRANS_WRITE ){
4338 BtShared *pBt = p->pBt;
4339 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
4340 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
4341 sqlite3BtreeEnter(p);
4342 if( op==SAVEPOINT_ROLLBACK ){
4343 rc = saveAllCursors(pBt, 0, 0);
4345 if( rc==SQLITE_OK ){
4346 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
4348 if( rc==SQLITE_OK ){
4349 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
4350 pBt->nPage = 0;
4352 rc = newDatabase(pBt);
4353 btreeSetNPage(pBt, pBt->pPage1);
4355 /* pBt->nPage might be zero if the database was corrupt when
4356 ** the transaction was started. Otherwise, it must be at least 1. */
4357 assert( CORRUPT_DB || pBt->nPage>0 );
4359 sqlite3BtreeLeave(p);
4361 return rc;
4365 ** Create a new cursor for the BTree whose root is on the page
4366 ** iTable. If a read-only cursor is requested, it is assumed that
4367 ** the caller already has at least a read-only transaction open
4368 ** on the database already. If a write-cursor is requested, then
4369 ** the caller is assumed to have an open write transaction.
4371 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
4372 ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
4373 ** can be used for reading or for writing if other conditions for writing
4374 ** are also met. These are the conditions that must be met in order
4375 ** for writing to be allowed:
4377 ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
4379 ** 2: Other database connections that share the same pager cache
4380 ** but which are not in the READ_UNCOMMITTED state may not have
4381 ** cursors open with wrFlag==0 on the same table. Otherwise
4382 ** the changes made by this write cursor would be visible to
4383 ** the read cursors in the other database connection.
4385 ** 3: The database must be writable (not on read-only media)
4387 ** 4: There must be an active transaction.
4389 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
4390 ** is set. If FORDELETE is set, that is a hint to the implementation that
4391 ** this cursor will only be used to seek to and delete entries of an index
4392 ** as part of a larger DELETE statement. The FORDELETE hint is not used by
4393 ** this implementation. But in a hypothetical alternative storage engine
4394 ** in which index entries are automatically deleted when corresponding table
4395 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
4396 ** operations on this cursor can be no-ops and all READ operations can
4397 ** return a null row (2-bytes: 0x01 0x00).
4399 ** No checking is done to make sure that page iTable really is the
4400 ** root page of a b-tree. If it is not, then the cursor acquired
4401 ** will not work correctly.
4403 ** It is assumed that the sqlite3BtreeCursorZero() has been called
4404 ** on pCur to initialize the memory space prior to invoking this routine.
4406 static int btreeCursor(
4407 Btree *p, /* The btree */
4408 Pgno iTable, /* Root page of table to open */
4409 int wrFlag, /* 1 to write. 0 read-only */
4410 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4411 BtCursor *pCur /* Space for new cursor */
4413 BtShared *pBt = p->pBt; /* Shared b-tree handle */
4414 BtCursor *pX; /* Looping over other all cursors */
4416 assert( sqlite3BtreeHoldsMutex(p) );
4417 assert( wrFlag==0
4418 || wrFlag==BTREE_WRCSR
4419 || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
4422 /* The following assert statements verify that if this is a sharable
4423 ** b-tree database, the connection is holding the required table locks,
4424 ** and that no other connection has any open cursor that conflicts with
4425 ** this lock. The iTable<1 term disables the check for corrupt schemas. */
4426 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1))
4427 || iTable<1 );
4428 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
4430 /* Assert that the caller has opened the required transaction. */
4431 assert( p->inTrans>TRANS_NONE );
4432 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
4433 assert( pBt->pPage1 && pBt->pPage1->aData );
4434 assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
4436 if( wrFlag ){
4437 allocateTempSpace(pBt);
4438 if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
4440 if( iTable<=1 ){
4441 if( iTable<1 ){
4442 return SQLITE_CORRUPT_BKPT;
4443 }else if( btreePagecount(pBt)==0 ){
4444 assert( wrFlag==0 );
4445 iTable = 0;
4449 /* Now that no other errors can occur, finish filling in the BtCursor
4450 ** variables and link the cursor into the BtShared list. */
4451 pCur->pgnoRoot = iTable;
4452 pCur->iPage = -1;
4453 pCur->pKeyInfo = pKeyInfo;
4454 pCur->pBtree = p;
4455 pCur->pBt = pBt;
4456 pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
4457 pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
4458 /* If there are two or more cursors on the same btree, then all such
4459 ** cursors *must* have the BTCF_Multiple flag set. */
4460 for(pX=pBt->pCursor; pX; pX=pX->pNext){
4461 if( pX->pgnoRoot==iTable ){
4462 pX->curFlags |= BTCF_Multiple;
4463 pCur->curFlags |= BTCF_Multiple;
4466 pCur->pNext = pBt->pCursor;
4467 pBt->pCursor = pCur;
4468 pCur->eState = CURSOR_INVALID;
4469 return SQLITE_OK;
4471 static int btreeCursorWithLock(
4472 Btree *p, /* The btree */
4473 Pgno iTable, /* Root page of table to open */
4474 int wrFlag, /* 1 to write. 0 read-only */
4475 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4476 BtCursor *pCur /* Space for new cursor */
4478 int rc;
4479 sqlite3BtreeEnter(p);
4480 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4481 sqlite3BtreeLeave(p);
4482 return rc;
4484 int sqlite3BtreeCursor(
4485 Btree *p, /* The btree */
4486 Pgno iTable, /* Root page of table to open */
4487 int wrFlag, /* 1 to write. 0 read-only */
4488 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
4489 BtCursor *pCur /* Write new cursor here */
4491 if( p->sharable ){
4492 return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur);
4493 }else{
4494 return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4499 ** Return the size of a BtCursor object in bytes.
4501 ** This interfaces is needed so that users of cursors can preallocate
4502 ** sufficient storage to hold a cursor. The BtCursor object is opaque
4503 ** to users so they cannot do the sizeof() themselves - they must call
4504 ** this routine.
4506 int sqlite3BtreeCursorSize(void){
4507 return ROUND8(sizeof(BtCursor));
4511 ** Initialize memory that will be converted into a BtCursor object.
4513 ** The simple approach here would be to memset() the entire object
4514 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
4515 ** do not need to be zeroed and they are large, so we can save a lot
4516 ** of run-time by skipping the initialization of those elements.
4518 void sqlite3BtreeCursorZero(BtCursor *p){
4519 memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
4523 ** Close a cursor. The read lock on the database file is released
4524 ** when the last cursor is closed.
4526 int sqlite3BtreeCloseCursor(BtCursor *pCur){
4527 Btree *pBtree = pCur->pBtree;
4528 if( pBtree ){
4529 BtShared *pBt = pCur->pBt;
4530 sqlite3BtreeEnter(pBtree);
4531 assert( pBt->pCursor!=0 );
4532 if( pBt->pCursor==pCur ){
4533 pBt->pCursor = pCur->pNext;
4534 }else{
4535 BtCursor *pPrev = pBt->pCursor;
4537 if( pPrev->pNext==pCur ){
4538 pPrev->pNext = pCur->pNext;
4539 break;
4541 pPrev = pPrev->pNext;
4542 }while( ALWAYS(pPrev) );
4544 btreeReleaseAllCursorPages(pCur);
4545 unlockBtreeIfUnused(pBt);
4546 sqlite3_free(pCur->aOverflow);
4547 sqlite3_free(pCur->pKey);
4548 if( (pBt->openFlags & BTREE_SINGLE) && pBt->pCursor==0 ){
4549 /* Since the BtShared is not sharable, there is no need to
4550 ** worry about the missing sqlite3BtreeLeave() call here. */
4551 assert( pBtree->sharable==0 );
4552 sqlite3BtreeClose(pBtree);
4553 }else{
4554 sqlite3BtreeLeave(pBtree);
4556 pCur->pBtree = 0;
4558 return SQLITE_OK;
4562 ** Make sure the BtCursor* given in the argument has a valid
4563 ** BtCursor.info structure. If it is not already valid, call
4564 ** btreeParseCell() to fill it in.
4566 ** BtCursor.info is a cache of the information in the current cell.
4567 ** Using this cache reduces the number of calls to btreeParseCell().
4569 #ifndef NDEBUG
4570 static int cellInfoEqual(CellInfo *a, CellInfo *b){
4571 if( a->nKey!=b->nKey ) return 0;
4572 if( a->pPayload!=b->pPayload ) return 0;
4573 if( a->nPayload!=b->nPayload ) return 0;
4574 if( a->nLocal!=b->nLocal ) return 0;
4575 if( a->nSize!=b->nSize ) return 0;
4576 return 1;
4578 static void assertCellInfo(BtCursor *pCur){
4579 CellInfo info;
4580 memset(&info, 0, sizeof(info));
4581 btreeParseCell(pCur->pPage, pCur->ix, &info);
4582 assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
4584 #else
4585 #define assertCellInfo(x)
4586 #endif
4587 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
4588 if( pCur->info.nSize==0 ){
4589 pCur->curFlags |= BTCF_ValidNKey;
4590 btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
4591 }else{
4592 assertCellInfo(pCur);
4596 #ifndef NDEBUG /* The next routine used only within assert() statements */
4598 ** Return true if the given BtCursor is valid. A valid cursor is one
4599 ** that is currently pointing to a row in a (non-empty) table.
4600 ** This is a verification routine is used only within assert() statements.
4602 int sqlite3BtreeCursorIsValid(BtCursor *pCur){
4603 return pCur && pCur->eState==CURSOR_VALID;
4605 #endif /* NDEBUG */
4606 int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
4607 assert( pCur!=0 );
4608 return pCur->eState==CURSOR_VALID;
4612 ** Return the value of the integer key or "rowid" for a table btree.
4613 ** This routine is only valid for a cursor that is pointing into a
4614 ** ordinary table btree. If the cursor points to an index btree or
4615 ** is invalid, the result of this routine is undefined.
4617 i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
4618 assert( cursorHoldsMutex(pCur) );
4619 assert( pCur->eState==CURSOR_VALID );
4620 assert( pCur->curIntKey );
4621 getCellInfo(pCur);
4622 return pCur->info.nKey;
4626 ** Pin or unpin a cursor.
4628 void sqlite3BtreeCursorPin(BtCursor *pCur){
4629 assert( (pCur->curFlags & BTCF_Pinned)==0 );
4630 pCur->curFlags |= BTCF_Pinned;
4632 void sqlite3BtreeCursorUnpin(BtCursor *pCur){
4633 assert( (pCur->curFlags & BTCF_Pinned)!=0 );
4634 pCur->curFlags &= ~BTCF_Pinned;
4637 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4639 ** Return the offset into the database file for the start of the
4640 ** payload to which the cursor is pointing.
4642 i64 sqlite3BtreeOffset(BtCursor *pCur){
4643 assert( cursorHoldsMutex(pCur) );
4644 assert( pCur->eState==CURSOR_VALID );
4645 getCellInfo(pCur);
4646 return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
4647 (i64)(pCur->info.pPayload - pCur->pPage->aData);
4649 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
4652 ** Return the number of bytes of payload for the entry that pCur is
4653 ** currently pointing to. For table btrees, this will be the amount
4654 ** of data. For index btrees, this will be the size of the key.
4656 ** The caller must guarantee that the cursor is pointing to a non-NULL
4657 ** valid entry. In other words, the calling procedure must guarantee
4658 ** that the cursor has Cursor.eState==CURSOR_VALID.
4660 u32 sqlite3BtreePayloadSize(BtCursor *pCur){
4661 assert( cursorHoldsMutex(pCur) );
4662 assert( pCur->eState==CURSOR_VALID );
4663 getCellInfo(pCur);
4664 return pCur->info.nPayload;
4668 ** Return an upper bound on the size of any record for the table
4669 ** that the cursor is pointing into.
4671 ** This is an optimization. Everything will still work if this
4672 ** routine always returns 2147483647 (which is the largest record
4673 ** that SQLite can handle) or more. But returning a smaller value might
4674 ** prevent large memory allocations when trying to interpret a
4675 ** corrupt datrabase.
4677 ** The current implementation merely returns the size of the underlying
4678 ** database file.
4680 sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){
4681 assert( cursorHoldsMutex(pCur) );
4682 assert( pCur->eState==CURSOR_VALID );
4683 return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
4687 ** Given the page number of an overflow page in the database (parameter
4688 ** ovfl), this function finds the page number of the next page in the
4689 ** linked list of overflow pages. If possible, it uses the auto-vacuum
4690 ** pointer-map data instead of reading the content of page ovfl to do so.
4692 ** If an error occurs an SQLite error code is returned. Otherwise:
4694 ** The page number of the next overflow page in the linked list is
4695 ** written to *pPgnoNext. If page ovfl is the last page in its linked
4696 ** list, *pPgnoNext is set to zero.
4698 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
4699 ** to page number pOvfl was obtained, then *ppPage is set to point to that
4700 ** reference. It is the responsibility of the caller to call releasePage()
4701 ** on *ppPage to free the reference. In no reference was obtained (because
4702 ** the pointer-map was used to obtain the value for *pPgnoNext), then
4703 ** *ppPage is set to zero.
4705 static int getOverflowPage(
4706 BtShared *pBt, /* The database file */
4707 Pgno ovfl, /* Current overflow page number */
4708 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
4709 Pgno *pPgnoNext /* OUT: Next overflow page number */
4711 Pgno next = 0;
4712 MemPage *pPage = 0;
4713 int rc = SQLITE_OK;
4715 assert( sqlite3_mutex_held(pBt->mutex) );
4716 assert(pPgnoNext);
4718 #ifndef SQLITE_OMIT_AUTOVACUUM
4719 /* Try to find the next page in the overflow list using the
4720 ** autovacuum pointer-map pages. Guess that the next page in
4721 ** the overflow list is page number (ovfl+1). If that guess turns
4722 ** out to be wrong, fall back to loading the data of page
4723 ** number ovfl to determine the next page number.
4725 if( pBt->autoVacuum ){
4726 Pgno pgno;
4727 Pgno iGuess = ovfl+1;
4728 u8 eType;
4730 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
4731 iGuess++;
4734 if( iGuess<=btreePagecount(pBt) ){
4735 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
4736 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
4737 next = iGuess;
4738 rc = SQLITE_DONE;
4742 #endif
4744 assert( next==0 || rc==SQLITE_DONE );
4745 if( rc==SQLITE_OK ){
4746 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
4747 assert( rc==SQLITE_OK || pPage==0 );
4748 if( rc==SQLITE_OK ){
4749 next = get4byte(pPage->aData);
4753 *pPgnoNext = next;
4754 if( ppPage ){
4755 *ppPage = pPage;
4756 }else{
4757 releasePage(pPage);
4759 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
4763 ** Copy data from a buffer to a page, or from a page to a buffer.
4765 ** pPayload is a pointer to data stored on database page pDbPage.
4766 ** If argument eOp is false, then nByte bytes of data are copied
4767 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4768 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4769 ** of data are copied from the buffer pBuf to pPayload.
4771 ** SQLITE_OK is returned on success, otherwise an error code.
4773 static int copyPayload(
4774 void *pPayload, /* Pointer to page data */
4775 void *pBuf, /* Pointer to buffer */
4776 int nByte, /* Number of bytes to copy */
4777 int eOp, /* 0 -> copy from page, 1 -> copy to page */
4778 DbPage *pDbPage /* Page containing pPayload */
4780 if( eOp ){
4781 /* Copy data from buffer to page (a write operation) */
4782 int rc = sqlite3PagerWrite(pDbPage);
4783 if( rc!=SQLITE_OK ){
4784 return rc;
4786 memcpy(pPayload, pBuf, nByte);
4787 }else{
4788 /* Copy data from page to buffer (a read operation) */
4789 memcpy(pBuf, pPayload, nByte);
4791 return SQLITE_OK;
4795 ** This function is used to read or overwrite payload information
4796 ** for the entry that the pCur cursor is pointing to. The eOp
4797 ** argument is interpreted as follows:
4799 ** 0: The operation is a read. Populate the overflow cache.
4800 ** 1: The operation is a write. Populate the overflow cache.
4802 ** A total of "amt" bytes are read or written beginning at "offset".
4803 ** Data is read to or from the buffer pBuf.
4805 ** The content being read or written might appear on the main page
4806 ** or be scattered out on multiple overflow pages.
4808 ** If the current cursor entry uses one or more overflow pages
4809 ** this function may allocate space for and lazily populate
4810 ** the overflow page-list cache array (BtCursor.aOverflow).
4811 ** Subsequent calls use this cache to make seeking to the supplied offset
4812 ** more efficient.
4814 ** Once an overflow page-list cache has been allocated, it must be
4815 ** invalidated if some other cursor writes to the same table, or if
4816 ** the cursor is moved to a different row. Additionally, in auto-vacuum
4817 ** mode, the following events may invalidate an overflow page-list cache.
4819 ** * An incremental vacuum,
4820 ** * A commit in auto_vacuum="full" mode,
4821 ** * Creating a table (may require moving an overflow page).
4823 static int accessPayload(
4824 BtCursor *pCur, /* Cursor pointing to entry to read from */
4825 u32 offset, /* Begin reading this far into payload */
4826 u32 amt, /* Read this many bytes */
4827 unsigned char *pBuf, /* Write the bytes into this buffer */
4828 int eOp /* zero to read. non-zero to write. */
4830 unsigned char *aPayload;
4831 int rc = SQLITE_OK;
4832 int iIdx = 0;
4833 MemPage *pPage = pCur->pPage; /* Btree page of current entry */
4834 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
4835 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4836 unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
4837 #endif
4839 assert( pPage );
4840 assert( eOp==0 || eOp==1 );
4841 assert( pCur->eState==CURSOR_VALID );
4842 assert( pCur->ix<pPage->nCell );
4843 assert( cursorHoldsMutex(pCur) );
4845 getCellInfo(pCur);
4846 aPayload = pCur->info.pPayload;
4847 assert( offset+amt <= pCur->info.nPayload );
4849 assert( aPayload > pPage->aData );
4850 if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
4851 /* Trying to read or write past the end of the data is an error. The
4852 ** conditional above is really:
4853 ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
4854 ** but is recast into its current form to avoid integer overflow problems
4856 return SQLITE_CORRUPT_PAGE(pPage);
4859 /* Check if data must be read/written to/from the btree page itself. */
4860 if( offset<pCur->info.nLocal ){
4861 int a = amt;
4862 if( a+offset>pCur->info.nLocal ){
4863 a = pCur->info.nLocal - offset;
4865 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
4866 offset = 0;
4867 pBuf += a;
4868 amt -= a;
4869 }else{
4870 offset -= pCur->info.nLocal;
4874 if( rc==SQLITE_OK && amt>0 ){
4875 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
4876 Pgno nextPage;
4878 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
4880 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
4882 ** The aOverflow[] array is sized at one entry for each overflow page
4883 ** in the overflow chain. The page number of the first overflow page is
4884 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
4885 ** means "not yet known" (the cache is lazily populated).
4887 if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
4888 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
4889 if( pCur->aOverflow==0
4890 || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
4892 Pgno *aNew = (Pgno*)sqlite3Realloc(
4893 pCur->aOverflow, nOvfl*2*sizeof(Pgno)
4895 if( aNew==0 ){
4896 return SQLITE_NOMEM_BKPT;
4897 }else{
4898 pCur->aOverflow = aNew;
4901 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
4902 pCur->curFlags |= BTCF_ValidOvfl;
4903 }else{
4904 /* If the overflow page-list cache has been allocated and the
4905 ** entry for the first required overflow page is valid, skip
4906 ** directly to it.
4908 if( pCur->aOverflow[offset/ovflSize] ){
4909 iIdx = (offset/ovflSize);
4910 nextPage = pCur->aOverflow[iIdx];
4911 offset = (offset%ovflSize);
4915 assert( rc==SQLITE_OK && amt>0 );
4916 while( nextPage ){
4917 /* If required, populate the overflow page-list cache. */
4918 if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPT;
4919 assert( pCur->aOverflow[iIdx]==0
4920 || pCur->aOverflow[iIdx]==nextPage
4921 || CORRUPT_DB );
4922 pCur->aOverflow[iIdx] = nextPage;
4924 if( offset>=ovflSize ){
4925 /* The only reason to read this page is to obtain the page
4926 ** number for the next page in the overflow chain. The page
4927 ** data is not required. So first try to lookup the overflow
4928 ** page-list cache, if any, then fall back to the getOverflowPage()
4929 ** function.
4931 assert( pCur->curFlags & BTCF_ValidOvfl );
4932 assert( pCur->pBtree->db==pBt->db );
4933 if( pCur->aOverflow[iIdx+1] ){
4934 nextPage = pCur->aOverflow[iIdx+1];
4935 }else{
4936 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
4938 offset -= ovflSize;
4939 }else{
4940 /* Need to read this page properly. It contains some of the
4941 ** range of data that is being read (eOp==0) or written (eOp!=0).
4943 int a = amt;
4944 if( a + offset > ovflSize ){
4945 a = ovflSize - offset;
4948 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4949 /* If all the following are true:
4951 ** 1) this is a read operation, and
4952 ** 2) data is required from the start of this overflow page, and
4953 ** 3) there are no dirty pages in the page-cache
4954 ** 4) the database is file-backed, and
4955 ** 5) the page is not in the WAL file
4956 ** 6) at least 4 bytes have already been read into the output buffer
4958 ** then data can be read directly from the database file into the
4959 ** output buffer, bypassing the page-cache altogether. This speeds
4960 ** up loading large records that span many overflow pages.
4962 if( eOp==0 /* (1) */
4963 && offset==0 /* (2) */
4964 && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */
4965 && &pBuf[-4]>=pBufStart /* (6) */
4967 sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
4968 u8 aSave[4];
4969 u8 *aWrite = &pBuf[-4];
4970 assert( aWrite>=pBufStart ); /* due to (6) */
4971 memcpy(aSave, aWrite, 4);
4972 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
4973 if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT;
4974 nextPage = get4byte(aWrite);
4975 memcpy(aWrite, aSave, 4);
4976 }else
4977 #endif
4980 DbPage *pDbPage;
4981 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
4982 (eOp==0 ? PAGER_GET_READONLY : 0)
4984 if( rc==SQLITE_OK ){
4985 aPayload = sqlite3PagerGetData(pDbPage);
4986 nextPage = get4byte(aPayload);
4987 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
4988 sqlite3PagerUnref(pDbPage);
4989 offset = 0;
4992 amt -= a;
4993 if( amt==0 ) return rc;
4994 pBuf += a;
4996 if( rc ) break;
4997 iIdx++;
5001 if( rc==SQLITE_OK && amt>0 ){
5002 /* Overflow chain ends prematurely */
5003 return SQLITE_CORRUPT_PAGE(pPage);
5005 return rc;
5009 ** Read part of the payload for the row at which that cursor pCur is currently
5010 ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
5011 ** begins at "offset".
5013 ** pCur can be pointing to either a table or an index b-tree.
5014 ** If pointing to a table btree, then the content section is read. If
5015 ** pCur is pointing to an index b-tree then the key section is read.
5017 ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
5018 ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
5019 ** cursor might be invalid or might need to be restored before being read.
5021 ** Return SQLITE_OK on success or an error code if anything goes
5022 ** wrong. An error is returned if "offset+amt" is larger than
5023 ** the available payload.
5025 int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5026 assert( cursorHoldsMutex(pCur) );
5027 assert( pCur->eState==CURSOR_VALID );
5028 assert( pCur->iPage>=0 && pCur->pPage );
5029 assert( pCur->ix<pCur->pPage->nCell );
5030 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
5034 ** This variant of sqlite3BtreePayload() works even if the cursor has not
5035 ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
5036 ** interface.
5038 #ifndef SQLITE_OMIT_INCRBLOB
5039 static SQLITE_NOINLINE int accessPayloadChecked(
5040 BtCursor *pCur,
5041 u32 offset,
5042 u32 amt,
5043 void *pBuf
5045 int rc;
5046 if ( pCur->eState==CURSOR_INVALID ){
5047 return SQLITE_ABORT;
5049 assert( cursorOwnsBtShared(pCur) );
5050 rc = btreeRestoreCursorPosition(pCur);
5051 return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
5053 int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5054 if( pCur->eState==CURSOR_VALID ){
5055 assert( cursorOwnsBtShared(pCur) );
5056 return accessPayload(pCur, offset, amt, pBuf, 0);
5057 }else{
5058 return accessPayloadChecked(pCur, offset, amt, pBuf);
5061 #endif /* SQLITE_OMIT_INCRBLOB */
5064 ** Return a pointer to payload information from the entry that the
5065 ** pCur cursor is pointing to. The pointer is to the beginning of
5066 ** the key if index btrees (pPage->intKey==0) and is the data for
5067 ** table btrees (pPage->intKey==1). The number of bytes of available
5068 ** key/data is written into *pAmt. If *pAmt==0, then the value
5069 ** returned will not be a valid pointer.
5071 ** This routine is an optimization. It is common for the entire key
5072 ** and data to fit on the local page and for there to be no overflow
5073 ** pages. When that is so, this routine can be used to access the
5074 ** key and data without making a copy. If the key and/or data spills
5075 ** onto overflow pages, then accessPayload() must be used to reassemble
5076 ** the key/data and copy it into a preallocated buffer.
5078 ** The pointer returned by this routine looks directly into the cached
5079 ** page of the database. The data might change or move the next time
5080 ** any btree routine is called.
5082 static const void *fetchPayload(
5083 BtCursor *pCur, /* Cursor pointing to entry to read from */
5084 u32 *pAmt /* Write the number of available bytes here */
5086 int amt;
5087 assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
5088 assert( pCur->eState==CURSOR_VALID );
5089 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5090 assert( cursorOwnsBtShared(pCur) );
5091 assert( pCur->ix<pCur->pPage->nCell );
5092 assert( pCur->info.nSize>0 );
5093 assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
5094 assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
5095 amt = pCur->info.nLocal;
5096 if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
5097 /* There is too little space on the page for the expected amount
5098 ** of local content. Database must be corrupt. */
5099 assert( CORRUPT_DB );
5100 amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
5102 *pAmt = (u32)amt;
5103 return (void*)pCur->info.pPayload;
5108 ** For the entry that cursor pCur is point to, return as
5109 ** many bytes of the key or data as are available on the local
5110 ** b-tree page. Write the number of available bytes into *pAmt.
5112 ** The pointer returned is ephemeral. The key/data may move
5113 ** or be destroyed on the next call to any Btree routine,
5114 ** including calls from other threads against the same cache.
5115 ** Hence, a mutex on the BtShared should be held prior to calling
5116 ** this routine.
5118 ** These routines is used to get quick access to key and data
5119 ** in the common case where no overflow pages are used.
5121 const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
5122 return fetchPayload(pCur, pAmt);
5127 ** Move the cursor down to a new child page. The newPgno argument is the
5128 ** page number of the child page to move to.
5130 ** This function returns SQLITE_CORRUPT if the page-header flags field of
5131 ** the new child page does not match the flags field of the parent (i.e.
5132 ** if an intkey page appears to be the parent of a non-intkey page, or
5133 ** vice-versa).
5135 static int moveToChild(BtCursor *pCur, u32 newPgno){
5136 BtShared *pBt = pCur->pBt;
5138 assert( cursorOwnsBtShared(pCur) );
5139 assert( pCur->eState==CURSOR_VALID );
5140 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
5141 assert( pCur->iPage>=0 );
5142 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
5143 return SQLITE_CORRUPT_BKPT;
5145 pCur->info.nSize = 0;
5146 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5147 pCur->aiIdx[pCur->iPage] = pCur->ix;
5148 pCur->apPage[pCur->iPage] = pCur->pPage;
5149 pCur->ix = 0;
5150 pCur->iPage++;
5151 return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
5154 #ifdef SQLITE_DEBUG
5156 ** Page pParent is an internal (non-leaf) tree page. This function
5157 ** asserts that page number iChild is the left-child if the iIdx'th
5158 ** cell in page pParent. Or, if iIdx is equal to the total number of
5159 ** cells in pParent, that page number iChild is the right-child of
5160 ** the page.
5162 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
5163 if( CORRUPT_DB ) return; /* The conditions tested below might not be true
5164 ** in a corrupt database */
5165 assert( iIdx<=pParent->nCell );
5166 if( iIdx==pParent->nCell ){
5167 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
5168 }else{
5169 assert( get4byte(findCell(pParent, iIdx))==iChild );
5172 #else
5173 # define assertParentIndex(x,y,z)
5174 #endif
5177 ** Move the cursor up to the parent page.
5179 ** pCur->idx is set to the cell index that contains the pointer
5180 ** to the page we are coming from. If we are coming from the
5181 ** right-most child page then pCur->idx is set to one more than
5182 ** the largest cell index.
5184 static void moveToParent(BtCursor *pCur){
5185 MemPage *pLeaf;
5186 assert( cursorOwnsBtShared(pCur) );
5187 assert( pCur->eState==CURSOR_VALID );
5188 assert( pCur->iPage>0 );
5189 assert( pCur->pPage );
5190 assertParentIndex(
5191 pCur->apPage[pCur->iPage-1],
5192 pCur->aiIdx[pCur->iPage-1],
5193 pCur->pPage->pgno
5195 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
5196 pCur->info.nSize = 0;
5197 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5198 pCur->ix = pCur->aiIdx[pCur->iPage-1];
5199 pLeaf = pCur->pPage;
5200 pCur->pPage = pCur->apPage[--pCur->iPage];
5201 releasePageNotNull(pLeaf);
5205 ** Move the cursor to point to the root page of its b-tree structure.
5207 ** If the table has a virtual root page, then the cursor is moved to point
5208 ** to the virtual root page instead of the actual root page. A table has a
5209 ** virtual root page when the actual root page contains no cells and a
5210 ** single child page. This can only happen with the table rooted at page 1.
5212 ** If the b-tree structure is empty, the cursor state is set to
5213 ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
5214 ** the cursor is set to point to the first cell located on the root
5215 ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
5217 ** If this function returns successfully, it may be assumed that the
5218 ** page-header flags indicate that the [virtual] root-page is the expected
5219 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
5220 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
5221 ** indicating a table b-tree, or if the caller did specify a KeyInfo
5222 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
5223 ** b-tree).
5225 static int moveToRoot(BtCursor *pCur){
5226 MemPage *pRoot;
5227 int rc = SQLITE_OK;
5229 assert( cursorOwnsBtShared(pCur) );
5230 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
5231 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
5232 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
5233 assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
5234 assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
5236 if( pCur->iPage>=0 ){
5237 if( pCur->iPage ){
5238 releasePageNotNull(pCur->pPage);
5239 while( --pCur->iPage ){
5240 releasePageNotNull(pCur->apPage[pCur->iPage]);
5242 pCur->pPage = pCur->apPage[0];
5243 goto skip_init;
5245 }else if( pCur->pgnoRoot==0 ){
5246 pCur->eState = CURSOR_INVALID;
5247 return SQLITE_EMPTY;
5248 }else{
5249 assert( pCur->iPage==(-1) );
5250 if( pCur->eState>=CURSOR_REQUIRESEEK ){
5251 if( pCur->eState==CURSOR_FAULT ){
5252 assert( pCur->skipNext!=SQLITE_OK );
5253 return pCur->skipNext;
5255 sqlite3BtreeClearCursor(pCur);
5257 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
5258 0, pCur->curPagerFlags);
5259 if( rc!=SQLITE_OK ){
5260 pCur->eState = CURSOR_INVALID;
5261 return rc;
5263 pCur->iPage = 0;
5264 pCur->curIntKey = pCur->pPage->intKey;
5266 pRoot = pCur->pPage;
5267 assert( pRoot->pgno==pCur->pgnoRoot );
5269 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
5270 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
5271 ** NULL, the caller expects a table b-tree. If this is not the case,
5272 ** return an SQLITE_CORRUPT error.
5274 ** Earlier versions of SQLite assumed that this test could not fail
5275 ** if the root page was already loaded when this function was called (i.e.
5276 ** if pCur->iPage>=0). But this is not so if the database is corrupted
5277 ** in such a way that page pRoot is linked into a second b-tree table
5278 ** (or the freelist). */
5279 assert( pRoot->intKey==1 || pRoot->intKey==0 );
5280 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
5281 return SQLITE_CORRUPT_PAGE(pCur->pPage);
5284 skip_init:
5285 pCur->ix = 0;
5286 pCur->info.nSize = 0;
5287 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
5289 pRoot = pCur->pPage;
5290 if( pRoot->nCell>0 ){
5291 pCur->eState = CURSOR_VALID;
5292 }else if( !pRoot->leaf ){
5293 Pgno subpage;
5294 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
5295 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
5296 pCur->eState = CURSOR_VALID;
5297 rc = moveToChild(pCur, subpage);
5298 }else{
5299 pCur->eState = CURSOR_INVALID;
5300 rc = SQLITE_EMPTY;
5302 return rc;
5306 ** Move the cursor down to the left-most leaf entry beneath the
5307 ** entry to which it is currently pointing.
5309 ** The left-most leaf is the one with the smallest key - the first
5310 ** in ascending order.
5312 static int moveToLeftmost(BtCursor *pCur){
5313 Pgno pgno;
5314 int rc = SQLITE_OK;
5315 MemPage *pPage;
5317 assert( cursorOwnsBtShared(pCur) );
5318 assert( pCur->eState==CURSOR_VALID );
5319 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
5320 assert( pCur->ix<pPage->nCell );
5321 pgno = get4byte(findCell(pPage, pCur->ix));
5322 rc = moveToChild(pCur, pgno);
5324 return rc;
5328 ** Move the cursor down to the right-most leaf entry beneath the
5329 ** page to which it is currently pointing. Notice the difference
5330 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
5331 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
5332 ** finds the right-most entry beneath the *page*.
5334 ** The right-most entry is the one with the largest key - the last
5335 ** key in ascending order.
5337 static int moveToRightmost(BtCursor *pCur){
5338 Pgno pgno;
5339 int rc = SQLITE_OK;
5340 MemPage *pPage = 0;
5342 assert( cursorOwnsBtShared(pCur) );
5343 assert( pCur->eState==CURSOR_VALID );
5344 while( !(pPage = pCur->pPage)->leaf ){
5345 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5346 pCur->ix = pPage->nCell;
5347 rc = moveToChild(pCur, pgno);
5348 if( rc ) return rc;
5350 pCur->ix = pPage->nCell-1;
5351 assert( pCur->info.nSize==0 );
5352 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
5353 return SQLITE_OK;
5356 /* Move the cursor to the first entry in the table. Return SQLITE_OK
5357 ** on success. Set *pRes to 0 if the cursor actually points to something
5358 ** or set *pRes to 1 if the table is empty.
5360 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
5361 int rc;
5363 assert( cursorOwnsBtShared(pCur) );
5364 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5365 rc = moveToRoot(pCur);
5366 if( rc==SQLITE_OK ){
5367 assert( pCur->pPage->nCell>0 );
5368 *pRes = 0;
5369 rc = moveToLeftmost(pCur);
5370 }else if( rc==SQLITE_EMPTY ){
5371 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5372 *pRes = 1;
5373 rc = SQLITE_OK;
5375 return rc;
5378 /* Move the cursor to the last entry in the table. Return SQLITE_OK
5379 ** on success. Set *pRes to 0 if the cursor actually points to something
5380 ** or set *pRes to 1 if the table is empty.
5382 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
5383 int rc;
5385 assert( cursorOwnsBtShared(pCur) );
5386 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5388 /* If the cursor already points to the last entry, this is a no-op. */
5389 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
5390 #ifdef SQLITE_DEBUG
5391 /* This block serves to assert() that the cursor really does point
5392 ** to the last entry in the b-tree. */
5393 int ii;
5394 for(ii=0; ii<pCur->iPage; ii++){
5395 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
5397 assert( pCur->ix==pCur->pPage->nCell-1 || CORRUPT_DB );
5398 testcase( pCur->ix!=pCur->pPage->nCell-1 );
5399 /* ^-- dbsqlfuzz b92b72e4de80b5140c30ab71372ca719b8feb618 */
5400 assert( pCur->pPage->leaf );
5401 #endif
5402 *pRes = 0;
5403 return SQLITE_OK;
5406 rc = moveToRoot(pCur);
5407 if( rc==SQLITE_OK ){
5408 assert( pCur->eState==CURSOR_VALID );
5409 *pRes = 0;
5410 rc = moveToRightmost(pCur);
5411 if( rc==SQLITE_OK ){
5412 pCur->curFlags |= BTCF_AtLast;
5413 }else{
5414 pCur->curFlags &= ~BTCF_AtLast;
5416 }else if( rc==SQLITE_EMPTY ){
5417 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5418 *pRes = 1;
5419 rc = SQLITE_OK;
5421 return rc;
5424 /* Move the cursor so that it points to an entry near the key
5425 ** specified by pIdxKey or intKey. Return a success code.
5427 ** For INTKEY tables, the intKey parameter is used. pIdxKey
5428 ** must be NULL. For index tables, pIdxKey is used and intKey
5429 ** is ignored.
5431 ** If an exact match is not found, then the cursor is always
5432 ** left pointing at a leaf page which would hold the entry if it
5433 ** were present. The cursor might point to an entry that comes
5434 ** before or after the key.
5436 ** An integer is written into *pRes which is the result of
5437 ** comparing the key with the entry to which the cursor is
5438 ** pointing. The meaning of the integer written into
5439 ** *pRes is as follows:
5441 ** *pRes<0 The cursor is left pointing at an entry that
5442 ** is smaller than intKey/pIdxKey or if the table is empty
5443 ** and the cursor is therefore left point to nothing.
5445 ** *pRes==0 The cursor is left pointing at an entry that
5446 ** exactly matches intKey/pIdxKey.
5448 ** *pRes>0 The cursor is left pointing at an entry that
5449 ** is larger than intKey/pIdxKey.
5451 ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
5452 ** exists an entry in the table that exactly matches pIdxKey.
5454 int sqlite3BtreeMovetoUnpacked(
5455 BtCursor *pCur, /* The cursor to be moved */
5456 UnpackedRecord *pIdxKey, /* Unpacked index key */
5457 i64 intKey, /* The table key */
5458 int biasRight, /* If true, bias the search to the high end */
5459 int *pRes /* Write search results here */
5461 int rc;
5462 RecordCompare xRecordCompare;
5464 assert( cursorOwnsBtShared(pCur) );
5465 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5466 assert( pRes );
5467 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
5468 assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
5470 /* If the cursor is already positioned at the point we are trying
5471 ** to move to, then just return without doing any work */
5472 if( pIdxKey==0
5473 && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
5475 if( pCur->info.nKey==intKey ){
5476 *pRes = 0;
5477 return SQLITE_OK;
5479 if( pCur->info.nKey<intKey ){
5480 if( (pCur->curFlags & BTCF_AtLast)!=0 ){
5481 *pRes = -1;
5482 return SQLITE_OK;
5484 /* If the requested key is one more than the previous key, then
5485 ** try to get there using sqlite3BtreeNext() rather than a full
5486 ** binary search. This is an optimization only. The correct answer
5487 ** is still obtained without this case, only a little more slowely */
5488 if( pCur->info.nKey+1==intKey ){
5489 *pRes = 0;
5490 rc = sqlite3BtreeNext(pCur, 0);
5491 if( rc==SQLITE_OK ){
5492 getCellInfo(pCur);
5493 if( pCur->info.nKey==intKey ){
5494 return SQLITE_OK;
5496 }else if( rc==SQLITE_DONE ){
5497 rc = SQLITE_OK;
5498 }else{
5499 return rc;
5505 #ifdef SQLITE_DEBUG
5506 pCur->pBtree->nSeek++; /* Performance measurement during testing */
5507 #endif
5509 if( pIdxKey ){
5510 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
5511 pIdxKey->errCode = 0;
5512 assert( pIdxKey->default_rc==1
5513 || pIdxKey->default_rc==0
5514 || pIdxKey->default_rc==-1
5516 }else{
5517 xRecordCompare = 0; /* All keys are integers */
5520 rc = moveToRoot(pCur);
5521 if( rc ){
5522 if( rc==SQLITE_EMPTY ){
5523 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5524 *pRes = -1;
5525 return SQLITE_OK;
5527 return rc;
5529 assert( pCur->pPage );
5530 assert( pCur->pPage->isInit );
5531 assert( pCur->eState==CURSOR_VALID );
5532 assert( pCur->pPage->nCell > 0 );
5533 assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
5534 assert( pCur->curIntKey || pIdxKey );
5535 for(;;){
5536 int lwr, upr, idx, c;
5537 Pgno chldPg;
5538 MemPage *pPage = pCur->pPage;
5539 u8 *pCell; /* Pointer to current cell in pPage */
5541 /* pPage->nCell must be greater than zero. If this is the root-page
5542 ** the cursor would have been INVALID above and this for(;;) loop
5543 ** not run. If this is not the root-page, then the moveToChild() routine
5544 ** would have already detected db corruption. Similarly, pPage must
5545 ** be the right kind (index or table) of b-tree page. Otherwise
5546 ** a moveToChild() or moveToRoot() call would have detected corruption. */
5547 assert( pPage->nCell>0 );
5548 assert( pPage->intKey==(pIdxKey==0) );
5549 lwr = 0;
5550 upr = pPage->nCell-1;
5551 assert( biasRight==0 || biasRight==1 );
5552 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
5553 pCur->ix = (u16)idx;
5554 if( xRecordCompare==0 ){
5555 for(;;){
5556 i64 nCellKey;
5557 pCell = findCellPastPtr(pPage, idx);
5558 if( pPage->intKeyLeaf ){
5559 while( 0x80 <= *(pCell++) ){
5560 if( pCell>=pPage->aDataEnd ){
5561 return SQLITE_CORRUPT_PAGE(pPage);
5565 getVarint(pCell, (u64*)&nCellKey);
5566 if( nCellKey<intKey ){
5567 lwr = idx+1;
5568 if( lwr>upr ){ c = -1; break; }
5569 }else if( nCellKey>intKey ){
5570 upr = idx-1;
5571 if( lwr>upr ){ c = +1; break; }
5572 }else{
5573 assert( nCellKey==intKey );
5574 pCur->ix = (u16)idx;
5575 if( !pPage->leaf ){
5576 lwr = idx;
5577 goto moveto_next_layer;
5578 }else{
5579 pCur->curFlags |= BTCF_ValidNKey;
5580 pCur->info.nKey = nCellKey;
5581 pCur->info.nSize = 0;
5582 *pRes = 0;
5583 return SQLITE_OK;
5586 assert( lwr+upr>=0 );
5587 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
5589 }else{
5590 for(;;){
5591 int nCell; /* Size of the pCell cell in bytes */
5592 pCell = findCellPastPtr(pPage, idx);
5594 /* The maximum supported page-size is 65536 bytes. This means that
5595 ** the maximum number of record bytes stored on an index B-Tree
5596 ** page is less than 16384 bytes and may be stored as a 2-byte
5597 ** varint. This information is used to attempt to avoid parsing
5598 ** the entire cell by checking for the cases where the record is
5599 ** stored entirely within the b-tree page by inspecting the first
5600 ** 2 bytes of the cell.
5602 nCell = pCell[0];
5603 if( nCell<=pPage->max1bytePayload ){
5604 /* This branch runs if the record-size field of the cell is a
5605 ** single byte varint and the record fits entirely on the main
5606 ** b-tree page. */
5607 testcase( pCell+nCell+1==pPage->aDataEnd );
5608 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
5609 }else if( !(pCell[1] & 0x80)
5610 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5612 /* The record-size field is a 2 byte varint and the record
5613 ** fits entirely on the main b-tree page. */
5614 testcase( pCell+nCell+2==pPage->aDataEnd );
5615 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
5616 }else{
5617 /* The record flows over onto one or more overflow pages. In
5618 ** this case the whole cell needs to be parsed, a buffer allocated
5619 ** and accessPayload() used to retrieve the record into the
5620 ** buffer before VdbeRecordCompare() can be called.
5622 ** If the record is corrupt, the xRecordCompare routine may read
5623 ** up to two varints past the end of the buffer. An extra 18
5624 ** bytes of padding is allocated at the end of the buffer in
5625 ** case this happens. */
5626 void *pCellKey;
5627 u8 * const pCellBody = pCell - pPage->childPtrSize;
5628 const int nOverrun = 18; /* Size of the overrun padding */
5629 pPage->xParseCell(pPage, pCellBody, &pCur->info);
5630 nCell = (int)pCur->info.nKey;
5631 testcase( nCell<0 ); /* True if key size is 2^32 or more */
5632 testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
5633 testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
5634 testcase( nCell==2 ); /* Minimum legal index key size */
5635 if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
5636 rc = SQLITE_CORRUPT_PAGE(pPage);
5637 goto moveto_finish;
5639 pCellKey = sqlite3Malloc( nCell+nOverrun );
5640 if( pCellKey==0 ){
5641 rc = SQLITE_NOMEM_BKPT;
5642 goto moveto_finish;
5644 pCur->ix = (u16)idx;
5645 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
5646 memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */
5647 pCur->curFlags &= ~BTCF_ValidOvfl;
5648 if( rc ){
5649 sqlite3_free(pCellKey);
5650 goto moveto_finish;
5652 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
5653 sqlite3_free(pCellKey);
5655 assert(
5656 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
5657 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
5659 if( c<0 ){
5660 lwr = idx+1;
5661 }else if( c>0 ){
5662 upr = idx-1;
5663 }else{
5664 assert( c==0 );
5665 *pRes = 0;
5666 rc = SQLITE_OK;
5667 pCur->ix = (u16)idx;
5668 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
5669 goto moveto_finish;
5671 if( lwr>upr ) break;
5672 assert( lwr+upr>=0 );
5673 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
5676 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
5677 assert( pPage->isInit );
5678 if( pPage->leaf ){
5679 assert( pCur->ix<pCur->pPage->nCell );
5680 pCur->ix = (u16)idx;
5681 *pRes = c;
5682 rc = SQLITE_OK;
5683 goto moveto_finish;
5685 moveto_next_layer:
5686 if( lwr>=pPage->nCell ){
5687 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5688 }else{
5689 chldPg = get4byte(findCell(pPage, lwr));
5691 pCur->ix = (u16)lwr;
5692 rc = moveToChild(pCur, chldPg);
5693 if( rc ) break;
5695 moveto_finish:
5696 pCur->info.nSize = 0;
5697 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5698 return rc;
5703 ** Return TRUE if the cursor is not pointing at an entry of the table.
5705 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
5706 ** past the last entry in the table or sqlite3BtreePrev() moves past
5707 ** the first entry. TRUE is also returned if the table is empty.
5709 int sqlite3BtreeEof(BtCursor *pCur){
5710 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
5711 ** have been deleted? This API will need to change to return an error code
5712 ** as well as the boolean result value.
5714 return (CURSOR_VALID!=pCur->eState);
5718 ** Return an estimate for the number of rows in the table that pCur is
5719 ** pointing to. Return a negative number if no estimate is currently
5720 ** available.
5722 i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
5723 i64 n;
5724 u8 i;
5726 assert( cursorOwnsBtShared(pCur) );
5727 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5729 /* Currently this interface is only called by the OP_IfSmaller
5730 ** opcode, and it that case the cursor will always be valid and
5731 ** will always point to a leaf node. */
5732 if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
5733 if( NEVER(pCur->pPage->leaf==0) ) return -1;
5735 n = pCur->pPage->nCell;
5736 for(i=0; i<pCur->iPage; i++){
5737 n *= pCur->apPage[i]->nCell;
5739 return n;
5743 ** Advance the cursor to the next entry in the database.
5744 ** Return value:
5746 ** SQLITE_OK success
5747 ** SQLITE_DONE cursor is already pointing at the last element
5748 ** otherwise some kind of error occurred
5750 ** The main entry point is sqlite3BtreeNext(). That routine is optimized
5751 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
5752 ** to the next cell on the current page. The (slower) btreeNext() helper
5753 ** routine is called when it is necessary to move to a different page or
5754 ** to restore the cursor.
5756 ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
5757 ** cursor corresponds to an SQL index and this routine could have been
5758 ** skipped if the SQL index had been a unique index. The F argument
5759 ** is a hint to the implement. SQLite btree implementation does not use
5760 ** this hint, but COMDB2 does.
5762 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
5763 int rc;
5764 int idx;
5765 MemPage *pPage;
5767 assert( cursorOwnsBtShared(pCur) );
5768 if( pCur->eState!=CURSOR_VALID ){
5769 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5770 rc = restoreCursorPosition(pCur);
5771 if( rc!=SQLITE_OK ){
5772 return rc;
5774 if( CURSOR_INVALID==pCur->eState ){
5775 return SQLITE_DONE;
5777 if( pCur->eState==CURSOR_SKIPNEXT ){
5778 pCur->eState = CURSOR_VALID;
5779 if( pCur->skipNext>0 ) return SQLITE_OK;
5783 pPage = pCur->pPage;
5784 idx = ++pCur->ix;
5785 if( !pPage->isInit || sqlite3FaultSim(412) ){
5786 /* The only known way for this to happen is for there to be a
5787 ** recursive SQL function that does a DELETE operation as part of a
5788 ** SELECT which deletes content out from under an active cursor
5789 ** in a corrupt database file where the table being DELETE-ed from
5790 ** has pages in common with the table being queried. See TH3
5791 ** module cov1/btree78.test testcase 220 (2018-06-08) for an
5792 ** example. */
5793 return SQLITE_CORRUPT_BKPT;
5796 /* If the database file is corrupt, it is possible for the value of idx
5797 ** to be invalid here. This can only occur if a second cursor modifies
5798 ** the page while cursor pCur is holding a reference to it. Which can
5799 ** only happen if the database is corrupt in such a way as to link the
5800 ** page into more than one b-tree structure.
5802 ** Update 2019-12-23: appears to long longer be possible after the
5803 ** addition of anotherValidCursor() condition on balance_deeper(). */
5804 harmless( idx>pPage->nCell );
5806 if( idx>=pPage->nCell ){
5807 if( !pPage->leaf ){
5808 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
5809 if( rc ) return rc;
5810 return moveToLeftmost(pCur);
5813 if( pCur->iPage==0 ){
5814 pCur->eState = CURSOR_INVALID;
5815 return SQLITE_DONE;
5817 moveToParent(pCur);
5818 pPage = pCur->pPage;
5819 }while( pCur->ix>=pPage->nCell );
5820 if( pPage->intKey ){
5821 return sqlite3BtreeNext(pCur, 0);
5822 }else{
5823 return SQLITE_OK;
5826 if( pPage->leaf ){
5827 return SQLITE_OK;
5828 }else{
5829 return moveToLeftmost(pCur);
5832 int sqlite3BtreeNext(BtCursor *pCur, int flags){
5833 MemPage *pPage;
5834 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
5835 assert( cursorOwnsBtShared(pCur) );
5836 assert( flags==0 || flags==1 );
5837 pCur->info.nSize = 0;
5838 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5839 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
5840 pPage = pCur->pPage;
5841 if( (++pCur->ix)>=pPage->nCell ){
5842 pCur->ix--;
5843 return btreeNext(pCur);
5845 if( pPage->leaf ){
5846 return SQLITE_OK;
5847 }else{
5848 return moveToLeftmost(pCur);
5853 ** Step the cursor to the back to the previous entry in the database.
5854 ** Return values:
5856 ** SQLITE_OK success
5857 ** SQLITE_DONE the cursor is already on the first element of the table
5858 ** otherwise some kind of error occurred
5860 ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
5861 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
5862 ** to the previous cell on the current page. The (slower) btreePrevious()
5863 ** helper routine is called when it is necessary to move to a different page
5864 ** or to restore the cursor.
5866 ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
5867 ** the cursor corresponds to an SQL index and this routine could have been
5868 ** skipped if the SQL index had been a unique index. The F argument is a
5869 ** hint to the implement. The native SQLite btree implementation does not
5870 ** use this hint, but COMDB2 does.
5872 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
5873 int rc;
5874 MemPage *pPage;
5876 assert( cursorOwnsBtShared(pCur) );
5877 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
5878 assert( pCur->info.nSize==0 );
5879 if( pCur->eState!=CURSOR_VALID ){
5880 rc = restoreCursorPosition(pCur);
5881 if( rc!=SQLITE_OK ){
5882 return rc;
5884 if( CURSOR_INVALID==pCur->eState ){
5885 return SQLITE_DONE;
5887 if( CURSOR_SKIPNEXT==pCur->eState ){
5888 pCur->eState = CURSOR_VALID;
5889 if( pCur->skipNext<0 ) return SQLITE_OK;
5893 pPage = pCur->pPage;
5894 assert( pPage->isInit );
5895 if( !pPage->leaf ){
5896 int idx = pCur->ix;
5897 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
5898 if( rc ) return rc;
5899 rc = moveToRightmost(pCur);
5900 }else{
5901 while( pCur->ix==0 ){
5902 if( pCur->iPage==0 ){
5903 pCur->eState = CURSOR_INVALID;
5904 return SQLITE_DONE;
5906 moveToParent(pCur);
5908 assert( pCur->info.nSize==0 );
5909 assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
5911 pCur->ix--;
5912 pPage = pCur->pPage;
5913 if( pPage->intKey && !pPage->leaf ){
5914 rc = sqlite3BtreePrevious(pCur, 0);
5915 }else{
5916 rc = SQLITE_OK;
5919 return rc;
5921 int sqlite3BtreePrevious(BtCursor *pCur, int flags){
5922 assert( cursorOwnsBtShared(pCur) );
5923 assert( flags==0 || flags==1 );
5924 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
5925 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
5926 pCur->info.nSize = 0;
5927 if( pCur->eState!=CURSOR_VALID
5928 || pCur->ix==0
5929 || pCur->pPage->leaf==0
5931 return btreePrevious(pCur);
5933 pCur->ix--;
5934 return SQLITE_OK;
5938 ** Allocate a new page from the database file.
5940 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
5941 ** has already been called on the new page.) The new page has also
5942 ** been referenced and the calling routine is responsible for calling
5943 ** sqlite3PagerUnref() on the new page when it is done.
5945 ** SQLITE_OK is returned on success. Any other return value indicates
5946 ** an error. *ppPage is set to NULL in the event of an error.
5948 ** If the "nearby" parameter is not 0, then an effort is made to
5949 ** locate a page close to the page number "nearby". This can be used in an
5950 ** attempt to keep related pages close to each other in the database file,
5951 ** which in turn can make database access faster.
5953 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
5954 ** anywhere on the free-list, then it is guaranteed to be returned. If
5955 ** eMode is BTALLOC_LT then the page returned will be less than or equal
5956 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
5957 ** are no restrictions on which page is returned.
5959 static int allocateBtreePage(
5960 BtShared *pBt, /* The btree */
5961 MemPage **ppPage, /* Store pointer to the allocated page here */
5962 Pgno *pPgno, /* Store the page number here */
5963 Pgno nearby, /* Search for a page near this one */
5964 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
5966 MemPage *pPage1;
5967 int rc;
5968 u32 n; /* Number of pages on the freelist */
5969 u32 k; /* Number of leaves on the trunk of the freelist */
5970 MemPage *pTrunk = 0;
5971 MemPage *pPrevTrunk = 0;
5972 Pgno mxPage; /* Total size of the database file */
5974 assert( sqlite3_mutex_held(pBt->mutex) );
5975 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
5976 pPage1 = pBt->pPage1;
5977 mxPage = btreePagecount(pBt);
5978 /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
5979 ** stores stores the total number of pages on the freelist. */
5980 n = get4byte(&pPage1->aData[36]);
5981 testcase( n==mxPage-1 );
5982 if( n>=mxPage ){
5983 return SQLITE_CORRUPT_BKPT;
5985 if( n>0 ){
5986 /* There are pages on the freelist. Reuse one of those pages. */
5987 Pgno iTrunk;
5988 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
5989 u32 nSearch = 0; /* Count of the number of search attempts */
5991 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
5992 ** shows that the page 'nearby' is somewhere on the free-list, then
5993 ** the entire-list will be searched for that page.
5995 #ifndef SQLITE_OMIT_AUTOVACUUM
5996 if( eMode==BTALLOC_EXACT ){
5997 if( nearby<=mxPage ){
5998 u8 eType;
5999 assert( nearby>0 );
6000 assert( pBt->autoVacuum );
6001 rc = ptrmapGet(pBt, nearby, &eType, 0);
6002 if( rc ) return rc;
6003 if( eType==PTRMAP_FREEPAGE ){
6004 searchList = 1;
6007 }else if( eMode==BTALLOC_LE ){
6008 searchList = 1;
6010 #endif
6012 /* Decrement the free-list count by 1. Set iTrunk to the index of the
6013 ** first free-list trunk page. iPrevTrunk is initially 1.
6015 rc = sqlite3PagerWrite(pPage1->pDbPage);
6016 if( rc ) return rc;
6017 put4byte(&pPage1->aData[36], n-1);
6019 /* The code within this loop is run only once if the 'searchList' variable
6020 ** is not true. Otherwise, it runs once for each trunk-page on the
6021 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
6022 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
6024 do {
6025 pPrevTrunk = pTrunk;
6026 if( pPrevTrunk ){
6027 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
6028 ** is the page number of the next freelist trunk page in the list or
6029 ** zero if this is the last freelist trunk page. */
6030 iTrunk = get4byte(&pPrevTrunk->aData[0]);
6031 }else{
6032 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
6033 ** stores the page number of the first page of the freelist, or zero if
6034 ** the freelist is empty. */
6035 iTrunk = get4byte(&pPage1->aData[32]);
6037 testcase( iTrunk==mxPage );
6038 if( iTrunk>mxPage || nSearch++ > n ){
6039 rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
6040 }else{
6041 rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
6043 if( rc ){
6044 pTrunk = 0;
6045 goto end_allocate_page;
6047 assert( pTrunk!=0 );
6048 assert( pTrunk->aData!=0 );
6049 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
6050 ** is the number of leaf page pointers to follow. */
6051 k = get4byte(&pTrunk->aData[4]);
6052 if( k==0 && !searchList ){
6053 /* The trunk has no leaves and the list is not being searched.
6054 ** So extract the trunk page itself and use it as the newly
6055 ** allocated page */
6056 assert( pPrevTrunk==0 );
6057 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6058 if( rc ){
6059 goto end_allocate_page;
6061 *pPgno = iTrunk;
6062 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6063 *ppPage = pTrunk;
6064 pTrunk = 0;
6065 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
6066 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
6067 /* Value of k is out of range. Database corruption */
6068 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6069 goto end_allocate_page;
6070 #ifndef SQLITE_OMIT_AUTOVACUUM
6071 }else if( searchList
6072 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
6074 /* The list is being searched and this trunk page is the page
6075 ** to allocate, regardless of whether it has leaves.
6077 *pPgno = iTrunk;
6078 *ppPage = pTrunk;
6079 searchList = 0;
6080 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6081 if( rc ){
6082 goto end_allocate_page;
6084 if( k==0 ){
6085 if( !pPrevTrunk ){
6086 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6087 }else{
6088 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6089 if( rc!=SQLITE_OK ){
6090 goto end_allocate_page;
6092 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
6094 }else{
6095 /* The trunk page is required by the caller but it contains
6096 ** pointers to free-list leaves. The first leaf becomes a trunk
6097 ** page in this case.
6099 MemPage *pNewTrunk;
6100 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
6101 if( iNewTrunk>mxPage ){
6102 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6103 goto end_allocate_page;
6105 testcase( iNewTrunk==mxPage );
6106 rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
6107 if( rc!=SQLITE_OK ){
6108 goto end_allocate_page;
6110 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
6111 if( rc!=SQLITE_OK ){
6112 releasePage(pNewTrunk);
6113 goto end_allocate_page;
6115 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
6116 put4byte(&pNewTrunk->aData[4], k-1);
6117 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
6118 releasePage(pNewTrunk);
6119 if( !pPrevTrunk ){
6120 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
6121 put4byte(&pPage1->aData[32], iNewTrunk);
6122 }else{
6123 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6124 if( rc ){
6125 goto end_allocate_page;
6127 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
6130 pTrunk = 0;
6131 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
6132 #endif
6133 }else if( k>0 ){
6134 /* Extract a leaf from the trunk */
6135 u32 closest;
6136 Pgno iPage;
6137 unsigned char *aData = pTrunk->aData;
6138 if( nearby>0 ){
6139 u32 i;
6140 closest = 0;
6141 if( eMode==BTALLOC_LE ){
6142 for(i=0; i<k; i++){
6143 iPage = get4byte(&aData[8+i*4]);
6144 if( iPage<=nearby ){
6145 closest = i;
6146 break;
6149 }else{
6150 int dist;
6151 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
6152 for(i=1; i<k; i++){
6153 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
6154 if( d2<dist ){
6155 closest = i;
6156 dist = d2;
6160 }else{
6161 closest = 0;
6164 iPage = get4byte(&aData[8+closest*4]);
6165 testcase( iPage==mxPage );
6166 if( iPage>mxPage || iPage<2 ){
6167 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6168 goto end_allocate_page;
6170 testcase( iPage==mxPage );
6171 if( !searchList
6172 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
6174 int noContent;
6175 *pPgno = iPage;
6176 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
6177 ": %d more free pages\n",
6178 *pPgno, closest+1, k, pTrunk->pgno, n-1));
6179 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6180 if( rc ) goto end_allocate_page;
6181 if( closest<k-1 ){
6182 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
6184 put4byte(&aData[4], k-1);
6185 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
6186 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
6187 if( rc==SQLITE_OK ){
6188 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6189 if( rc!=SQLITE_OK ){
6190 releasePage(*ppPage);
6191 *ppPage = 0;
6194 searchList = 0;
6197 releasePage(pPrevTrunk);
6198 pPrevTrunk = 0;
6199 }while( searchList );
6200 }else{
6201 /* There are no pages on the freelist, so append a new page to the
6202 ** database image.
6204 ** Normally, new pages allocated by this block can be requested from the
6205 ** pager layer with the 'no-content' flag set. This prevents the pager
6206 ** from trying to read the pages content from disk. However, if the
6207 ** current transaction has already run one or more incremental-vacuum
6208 ** steps, then the page we are about to allocate may contain content
6209 ** that is required in the event of a rollback. In this case, do
6210 ** not set the no-content flag. This causes the pager to load and journal
6211 ** the current page content before overwriting it.
6213 ** Note that the pager will not actually attempt to load or journal
6214 ** content for any page that really does lie past the end of the database
6215 ** file on disk. So the effects of disabling the no-content optimization
6216 ** here are confined to those pages that lie between the end of the
6217 ** database image and the end of the database file.
6219 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
6221 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6222 if( rc ) return rc;
6223 pBt->nPage++;
6224 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
6226 #ifndef SQLITE_OMIT_AUTOVACUUM
6227 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
6228 /* If *pPgno refers to a pointer-map page, allocate two new pages
6229 ** at the end of the file instead of one. The first allocated page
6230 ** becomes a new pointer-map page, the second is used by the caller.
6232 MemPage *pPg = 0;
6233 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
6234 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
6235 rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
6236 if( rc==SQLITE_OK ){
6237 rc = sqlite3PagerWrite(pPg->pDbPage);
6238 releasePage(pPg);
6240 if( rc ) return rc;
6241 pBt->nPage++;
6242 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
6244 #endif
6245 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
6246 *pPgno = pBt->nPage;
6248 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
6249 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
6250 if( rc ) return rc;
6251 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6252 if( rc!=SQLITE_OK ){
6253 releasePage(*ppPage);
6254 *ppPage = 0;
6256 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
6259 assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );
6261 end_allocate_page:
6262 releasePage(pTrunk);
6263 releasePage(pPrevTrunk);
6264 assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
6265 assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
6266 return rc;
6270 ** This function is used to add page iPage to the database file free-list.
6271 ** It is assumed that the page is not already a part of the free-list.
6273 ** The value passed as the second argument to this function is optional.
6274 ** If the caller happens to have a pointer to the MemPage object
6275 ** corresponding to page iPage handy, it may pass it as the second value.
6276 ** Otherwise, it may pass NULL.
6278 ** If a pointer to a MemPage object is passed as the second argument,
6279 ** its reference count is not altered by this function.
6281 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
6282 MemPage *pTrunk = 0; /* Free-list trunk page */
6283 Pgno iTrunk = 0; /* Page number of free-list trunk page */
6284 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
6285 MemPage *pPage; /* Page being freed. May be NULL. */
6286 int rc; /* Return Code */
6287 u32 nFree; /* Initial number of pages on free-list */
6289 assert( sqlite3_mutex_held(pBt->mutex) );
6290 assert( CORRUPT_DB || iPage>1 );
6291 assert( !pMemPage || pMemPage->pgno==iPage );
6293 if( iPage<2 || iPage>pBt->nPage ){
6294 return SQLITE_CORRUPT_BKPT;
6296 if( pMemPage ){
6297 pPage = pMemPage;
6298 sqlite3PagerRef(pPage->pDbPage);
6299 }else{
6300 pPage = btreePageLookup(pBt, iPage);
6303 /* Increment the free page count on pPage1 */
6304 rc = sqlite3PagerWrite(pPage1->pDbPage);
6305 if( rc ) goto freepage_out;
6306 nFree = get4byte(&pPage1->aData[36]);
6307 put4byte(&pPage1->aData[36], nFree+1);
6309 if( pBt->btsFlags & BTS_SECURE_DELETE ){
6310 /* If the secure_delete option is enabled, then
6311 ** always fully overwrite deleted information with zeros.
6313 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
6314 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
6316 goto freepage_out;
6318 memset(pPage->aData, 0, pPage->pBt->pageSize);
6321 /* If the database supports auto-vacuum, write an entry in the pointer-map
6322 ** to indicate that the page is free.
6324 if( ISAUTOVACUUM ){
6325 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
6326 if( rc ) goto freepage_out;
6329 /* Now manipulate the actual database free-list structure. There are two
6330 ** possibilities. If the free-list is currently empty, or if the first
6331 ** trunk page in the free-list is full, then this page will become a
6332 ** new free-list trunk page. Otherwise, it will become a leaf of the
6333 ** first trunk page in the current free-list. This block tests if it
6334 ** is possible to add the page as a new free-list leaf.
6336 if( nFree!=0 ){
6337 u32 nLeaf; /* Initial number of leaf cells on trunk page */
6339 iTrunk = get4byte(&pPage1->aData[32]);
6340 if( iTrunk>btreePagecount(pBt) ){
6341 rc = SQLITE_CORRUPT_BKPT;
6342 goto freepage_out;
6344 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
6345 if( rc!=SQLITE_OK ){
6346 goto freepage_out;
6349 nLeaf = get4byte(&pTrunk->aData[4]);
6350 assert( pBt->usableSize>32 );
6351 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
6352 rc = SQLITE_CORRUPT_BKPT;
6353 goto freepage_out;
6355 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
6356 /* In this case there is room on the trunk page to insert the page
6357 ** being freed as a new leaf.
6359 ** Note that the trunk page is not really full until it contains
6360 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
6361 ** coded. But due to a coding error in versions of SQLite prior to
6362 ** 3.6.0, databases with freelist trunk pages holding more than
6363 ** usableSize/4 - 8 entries will be reported as corrupt. In order
6364 ** to maintain backwards compatibility with older versions of SQLite,
6365 ** we will continue to restrict the number of entries to usableSize/4 - 8
6366 ** for now. At some point in the future (once everyone has upgraded
6367 ** to 3.6.0 or later) we should consider fixing the conditional above
6368 ** to read "usableSize/4-2" instead of "usableSize/4-8".
6370 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
6371 ** avoid using the last six entries in the freelist trunk page array in
6372 ** order that database files created by newer versions of SQLite can be
6373 ** read by older versions of SQLite.
6375 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6376 if( rc==SQLITE_OK ){
6377 put4byte(&pTrunk->aData[4], nLeaf+1);
6378 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
6379 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
6380 sqlite3PagerDontWrite(pPage->pDbPage);
6382 rc = btreeSetHasContent(pBt, iPage);
6384 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
6385 goto freepage_out;
6389 /* If control flows to this point, then it was not possible to add the
6390 ** the page being freed as a leaf page of the first trunk in the free-list.
6391 ** Possibly because the free-list is empty, or possibly because the
6392 ** first trunk in the free-list is full. Either way, the page being freed
6393 ** will become the new first trunk page in the free-list.
6395 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
6396 goto freepage_out;
6398 rc = sqlite3PagerWrite(pPage->pDbPage);
6399 if( rc!=SQLITE_OK ){
6400 goto freepage_out;
6402 put4byte(pPage->aData, iTrunk);
6403 put4byte(&pPage->aData[4], 0);
6404 put4byte(&pPage1->aData[32], iPage);
6405 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
6407 freepage_out:
6408 if( pPage ){
6409 pPage->isInit = 0;
6411 releasePage(pPage);
6412 releasePage(pTrunk);
6413 return rc;
6415 static void freePage(MemPage *pPage, int *pRC){
6416 if( (*pRC)==SQLITE_OK ){
6417 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
6422 ** Free the overflow pages associated with the given Cell.
6424 static SQLITE_NOINLINE int clearCellOverflow(
6425 MemPage *pPage, /* The page that contains the Cell */
6426 unsigned char *pCell, /* First byte of the Cell */
6427 CellInfo *pInfo /* Size information about the cell */
6429 BtShared *pBt;
6430 Pgno ovflPgno;
6431 int rc;
6432 int nOvfl;
6433 u32 ovflPageSize;
6435 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6436 assert( pInfo->nLocal!=pInfo->nPayload );
6437 testcase( pCell + pInfo->nSize == pPage->aDataEnd );
6438 testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
6439 if( pCell + pInfo->nSize > pPage->aDataEnd ){
6440 /* Cell extends past end of page */
6441 return SQLITE_CORRUPT_PAGE(pPage);
6443 ovflPgno = get4byte(pCell + pInfo->nSize - 4);
6444 pBt = pPage->pBt;
6445 assert( pBt->usableSize > 4 );
6446 ovflPageSize = pBt->usableSize - 4;
6447 nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
6448 assert( nOvfl>0 ||
6449 (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
6451 while( nOvfl-- ){
6452 Pgno iNext = 0;
6453 MemPage *pOvfl = 0;
6454 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
6455 /* 0 is not a legal page number and page 1 cannot be an
6456 ** overflow page. Therefore if ovflPgno<2 or past the end of the
6457 ** file the database must be corrupt. */
6458 return SQLITE_CORRUPT_BKPT;
6460 if( nOvfl ){
6461 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
6462 if( rc ) return rc;
6465 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
6466 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
6468 /* There is no reason any cursor should have an outstanding reference
6469 ** to an overflow page belonging to a cell that is being deleted/updated.
6470 ** So if there exists more than one reference to this page, then it
6471 ** must not really be an overflow page and the database must be corrupt.
6472 ** It is helpful to detect this before calling freePage2(), as
6473 ** freePage2() may zero the page contents if secure-delete mode is
6474 ** enabled. If this 'overflow' page happens to be a page that the
6475 ** caller is iterating through or using in some other way, this
6476 ** can be problematic.
6478 rc = SQLITE_CORRUPT_BKPT;
6479 }else{
6480 rc = freePage2(pBt, pOvfl, ovflPgno);
6483 if( pOvfl ){
6484 sqlite3PagerUnref(pOvfl->pDbPage);
6486 if( rc ) return rc;
6487 ovflPgno = iNext;
6489 return SQLITE_OK;
6492 /* Call xParseCell to compute the size of a cell. If the cell contains
6493 ** overflow, then invoke cellClearOverflow to clear out that overflow.
6494 ** STore the result code (SQLITE_OK or some error code) in rc.
6496 ** Implemented as macro to force inlining for performance.
6498 #define BTREE_CLEAR_CELL(rc, pPage, pCell, sInfo) \
6499 pPage->xParseCell(pPage, pCell, &sInfo); \
6500 if( sInfo.nLocal!=sInfo.nPayload ){ \
6501 rc = clearCellOverflow(pPage, pCell, &sInfo); \
6502 }else{ \
6503 rc = SQLITE_OK; \
6508 ** Create the byte sequence used to represent a cell on page pPage
6509 ** and write that byte sequence into pCell[]. Overflow pages are
6510 ** allocated and filled in as necessary. The calling procedure
6511 ** is responsible for making sure sufficient space has been allocated
6512 ** for pCell[].
6514 ** Note that pCell does not necessary need to point to the pPage->aData
6515 ** area. pCell might point to some temporary storage. The cell will
6516 ** be constructed in this temporary area then copied into pPage->aData
6517 ** later.
6519 static int fillInCell(
6520 MemPage *pPage, /* The page that contains the cell */
6521 unsigned char *pCell, /* Complete text of the cell */
6522 const BtreePayload *pX, /* Payload with which to construct the cell */
6523 int *pnSize /* Write cell size here */
6525 int nPayload;
6526 const u8 *pSrc;
6527 int nSrc, n, rc, mn;
6528 int spaceLeft;
6529 MemPage *pToRelease;
6530 unsigned char *pPrior;
6531 unsigned char *pPayload;
6532 BtShared *pBt;
6533 Pgno pgnoOvfl;
6534 int nHeader;
6536 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6538 /* pPage is not necessarily writeable since pCell might be auxiliary
6539 ** buffer space that is separate from the pPage buffer area */
6540 assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
6541 || sqlite3PagerIswriteable(pPage->pDbPage) );
6543 /* Fill in the header. */
6544 nHeader = pPage->childPtrSize;
6545 if( pPage->intKey ){
6546 nPayload = pX->nData + pX->nZero;
6547 pSrc = pX->pData;
6548 nSrc = pX->nData;
6549 assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
6550 nHeader += putVarint32(&pCell[nHeader], nPayload);
6551 nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
6552 }else{
6553 assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
6554 nSrc = nPayload = (int)pX->nKey;
6555 pSrc = pX->pKey;
6556 nHeader += putVarint32(&pCell[nHeader], nPayload);
6559 /* Fill in the payload */
6560 pPayload = &pCell[nHeader];
6561 if( nPayload<=pPage->maxLocal ){
6562 /* This is the common case where everything fits on the btree page
6563 ** and no overflow pages are required. */
6564 n = nHeader + nPayload;
6565 testcase( n==3 );
6566 testcase( n==4 );
6567 if( n<4 ) n = 4;
6568 *pnSize = n;
6569 assert( nSrc<=nPayload );
6570 testcase( nSrc<nPayload );
6571 memcpy(pPayload, pSrc, nSrc);
6572 memset(pPayload+nSrc, 0, nPayload-nSrc);
6573 return SQLITE_OK;
6576 /* If we reach this point, it means that some of the content will need
6577 ** to spill onto overflow pages.
6579 mn = pPage->minLocal;
6580 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
6581 testcase( n==pPage->maxLocal );
6582 testcase( n==pPage->maxLocal+1 );
6583 if( n > pPage->maxLocal ) n = mn;
6584 spaceLeft = n;
6585 *pnSize = n + nHeader + 4;
6586 pPrior = &pCell[nHeader+n];
6587 pToRelease = 0;
6588 pgnoOvfl = 0;
6589 pBt = pPage->pBt;
6591 /* At this point variables should be set as follows:
6593 ** nPayload Total payload size in bytes
6594 ** pPayload Begin writing payload here
6595 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
6596 ** that means content must spill into overflow pages.
6597 ** *pnSize Size of the local cell (not counting overflow pages)
6598 ** pPrior Where to write the pgno of the first overflow page
6600 ** Use a call to btreeParseCellPtr() to verify that the values above
6601 ** were computed correctly.
6603 #ifdef SQLITE_DEBUG
6605 CellInfo info;
6606 pPage->xParseCell(pPage, pCell, &info);
6607 assert( nHeader==(int)(info.pPayload - pCell) );
6608 assert( info.nKey==pX->nKey );
6609 assert( *pnSize == info.nSize );
6610 assert( spaceLeft == info.nLocal );
6612 #endif
6614 /* Write the payload into the local Cell and any extra into overflow pages */
6615 while( 1 ){
6616 n = nPayload;
6617 if( n>spaceLeft ) n = spaceLeft;
6619 /* If pToRelease is not zero than pPayload points into the data area
6620 ** of pToRelease. Make sure pToRelease is still writeable. */
6621 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6623 /* If pPayload is part of the data area of pPage, then make sure pPage
6624 ** is still writeable */
6625 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
6626 || sqlite3PagerIswriteable(pPage->pDbPage) );
6628 if( nSrc>=n ){
6629 memcpy(pPayload, pSrc, n);
6630 }else if( nSrc>0 ){
6631 n = nSrc;
6632 memcpy(pPayload, pSrc, n);
6633 }else{
6634 memset(pPayload, 0, n);
6636 nPayload -= n;
6637 if( nPayload<=0 ) break;
6638 pPayload += n;
6639 pSrc += n;
6640 nSrc -= n;
6641 spaceLeft -= n;
6642 if( spaceLeft==0 ){
6643 MemPage *pOvfl = 0;
6644 #ifndef SQLITE_OMIT_AUTOVACUUM
6645 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
6646 if( pBt->autoVacuum ){
6648 pgnoOvfl++;
6649 } while(
6650 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
6653 #endif
6654 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
6655 #ifndef SQLITE_OMIT_AUTOVACUUM
6656 /* If the database supports auto-vacuum, and the second or subsequent
6657 ** overflow page is being allocated, add an entry to the pointer-map
6658 ** for that page now.
6660 ** If this is the first overflow page, then write a partial entry
6661 ** to the pointer-map. If we write nothing to this pointer-map slot,
6662 ** then the optimistic overflow chain processing in clearCell()
6663 ** may misinterpret the uninitialized values and delete the
6664 ** wrong pages from the database.
6666 if( pBt->autoVacuum && rc==SQLITE_OK ){
6667 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
6668 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
6669 if( rc ){
6670 releasePage(pOvfl);
6673 #endif
6674 if( rc ){
6675 releasePage(pToRelease);
6676 return rc;
6679 /* If pToRelease is not zero than pPrior points into the data area
6680 ** of pToRelease. Make sure pToRelease is still writeable. */
6681 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6683 /* If pPrior is part of the data area of pPage, then make sure pPage
6684 ** is still writeable */
6685 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
6686 || sqlite3PagerIswriteable(pPage->pDbPage) );
6688 put4byte(pPrior, pgnoOvfl);
6689 releasePage(pToRelease);
6690 pToRelease = pOvfl;
6691 pPrior = pOvfl->aData;
6692 put4byte(pPrior, 0);
6693 pPayload = &pOvfl->aData[4];
6694 spaceLeft = pBt->usableSize - 4;
6697 releasePage(pToRelease);
6698 return SQLITE_OK;
6702 ** Remove the i-th cell from pPage. This routine effects pPage only.
6703 ** The cell content is not freed or deallocated. It is assumed that
6704 ** the cell content has been copied someplace else. This routine just
6705 ** removes the reference to the cell from pPage.
6707 ** "sz" must be the number of bytes in the cell.
6709 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
6710 u32 pc; /* Offset to cell content of cell being deleted */
6711 u8 *data; /* pPage->aData */
6712 u8 *ptr; /* Used to move bytes around within data[] */
6713 int rc; /* The return code */
6714 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
6716 if( *pRC ) return;
6717 assert( idx>=0 && idx<pPage->nCell );
6718 assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
6719 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6720 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6721 assert( pPage->nFree>=0 );
6722 data = pPage->aData;
6723 ptr = &pPage->aCellIdx[2*idx];
6724 pc = get2byte(ptr);
6725 hdr = pPage->hdrOffset;
6726 testcase( pc==get2byte(&data[hdr+5]) );
6727 testcase( pc+sz==pPage->pBt->usableSize );
6728 if( pc+sz > pPage->pBt->usableSize ){
6729 *pRC = SQLITE_CORRUPT_BKPT;
6730 return;
6732 rc = freeSpace(pPage, pc, sz);
6733 if( rc ){
6734 *pRC = rc;
6735 return;
6737 pPage->nCell--;
6738 if( pPage->nCell==0 ){
6739 memset(&data[hdr+1], 0, 4);
6740 data[hdr+7] = 0;
6741 put2byte(&data[hdr+5], pPage->pBt->usableSize);
6742 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
6743 - pPage->childPtrSize - 8;
6744 }else{
6745 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
6746 put2byte(&data[hdr+3], pPage->nCell);
6747 pPage->nFree += 2;
6752 ** Insert a new cell on pPage at cell index "i". pCell points to the
6753 ** content of the cell.
6755 ** If the cell content will fit on the page, then put it there. If it
6756 ** will not fit, then make a copy of the cell content into pTemp if
6757 ** pTemp is not null. Regardless of pTemp, allocate a new entry
6758 ** in pPage->apOvfl[] and make it point to the cell content (either
6759 ** in pTemp or the original pCell) and also record its index.
6760 ** Allocating a new entry in pPage->aCell[] implies that
6761 ** pPage->nOverflow is incremented.
6763 ** *pRC must be SQLITE_OK when this routine is called.
6765 static void insertCell(
6766 MemPage *pPage, /* Page into which we are copying */
6767 int i, /* New cell becomes the i-th cell of the page */
6768 u8 *pCell, /* Content of the new cell */
6769 int sz, /* Bytes of content in pCell */
6770 u8 *pTemp, /* Temp storage space for pCell, if needed */
6771 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
6772 int *pRC /* Read and write return code from here */
6774 int idx = 0; /* Where to write new cell content in data[] */
6775 int j; /* Loop counter */
6776 u8 *data; /* The content of the whole page */
6777 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
6779 assert( *pRC==SQLITE_OK );
6780 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
6781 assert( MX_CELL(pPage->pBt)<=10921 );
6782 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
6783 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
6784 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
6785 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6786 assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
6787 assert( pPage->nFree>=0 );
6788 if( pPage->nOverflow || sz+2>pPage->nFree ){
6789 if( pTemp ){
6790 memcpy(pTemp, pCell, sz);
6791 pCell = pTemp;
6793 if( iChild ){
6794 put4byte(pCell, iChild);
6796 j = pPage->nOverflow++;
6797 /* Comparison against ArraySize-1 since we hold back one extra slot
6798 ** as a contingency. In other words, never need more than 3 overflow
6799 ** slots but 4 are allocated, just to be safe. */
6800 assert( j < ArraySize(pPage->apOvfl)-1 );
6801 pPage->apOvfl[j] = pCell;
6802 pPage->aiOvfl[j] = (u16)i;
6804 /* When multiple overflows occur, they are always sequential and in
6805 ** sorted order. This invariants arise because multiple overflows can
6806 ** only occur when inserting divider cells into the parent page during
6807 ** balancing, and the dividers are adjacent and sorted.
6809 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
6810 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
6811 }else{
6812 int rc = sqlite3PagerWrite(pPage->pDbPage);
6813 if( rc!=SQLITE_OK ){
6814 *pRC = rc;
6815 return;
6817 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6818 data = pPage->aData;
6819 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
6820 rc = allocateSpace(pPage, sz, &idx);
6821 if( rc ){ *pRC = rc; return; }
6822 /* The allocateSpace() routine guarantees the following properties
6823 ** if it returns successfully */
6824 assert( idx >= 0 );
6825 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
6826 assert( idx+sz <= (int)pPage->pBt->usableSize );
6827 pPage->nFree -= (u16)(2 + sz);
6828 if( iChild ){
6829 /* In a corrupt database where an entry in the cell index section of
6830 ** a btree page has a value of 3 or less, the pCell value might point
6831 ** as many as 4 bytes in front of the start of the aData buffer for
6832 ** the source page. Make sure this does not cause problems by not
6833 ** reading the first 4 bytes */
6834 memcpy(&data[idx+4], pCell+4, sz-4);
6835 put4byte(&data[idx], iChild);
6836 }else{
6837 memcpy(&data[idx], pCell, sz);
6839 pIns = pPage->aCellIdx + i*2;
6840 memmove(pIns+2, pIns, 2*(pPage->nCell - i));
6841 put2byte(pIns, idx);
6842 pPage->nCell++;
6843 /* increment the cell count */
6844 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
6845 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
6846 #ifndef SQLITE_OMIT_AUTOVACUUM
6847 if( pPage->pBt->autoVacuum ){
6848 /* The cell may contain a pointer to an overflow page. If so, write
6849 ** the entry for the overflow page into the pointer map.
6851 ptrmapPutOvflPtr(pPage, pPage, pCell, pRC);
6853 #endif
6858 ** The following parameters determine how many adjacent pages get involved
6859 ** in a balancing operation. NN is the number of neighbors on either side
6860 ** of the page that participate in the balancing operation. NB is the
6861 ** total number of pages that participate, including the target page and
6862 ** NN neighbors on either side.
6864 ** The minimum value of NN is 1 (of course). Increasing NN above 1
6865 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
6866 ** in exchange for a larger degradation in INSERT and UPDATE performance.
6867 ** The value of NN appears to give the best results overall.
6869 ** (Later:) The description above makes it seem as if these values are
6870 ** tunable - as if you could change them and recompile and it would all work.
6871 ** But that is unlikely. NB has been 3 since the inception of SQLite and
6872 ** we have never tested any other value.
6874 #define NN 1 /* Number of neighbors on either side of pPage */
6875 #define NB 3 /* (NN*2+1): Total pages involved in the balance */
6878 ** A CellArray object contains a cache of pointers and sizes for a
6879 ** consecutive sequence of cells that might be held on multiple pages.
6881 ** The cells in this array are the divider cell or cells from the pParent
6882 ** page plus up to three child pages. There are a total of nCell cells.
6884 ** pRef is a pointer to one of the pages that contributes cells. This is
6885 ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
6886 ** which should be common to all pages that contribute cells to this array.
6888 ** apCell[] and szCell[] hold, respectively, pointers to the start of each
6889 ** cell and the size of each cell. Some of the apCell[] pointers might refer
6890 ** to overflow cells. In other words, some apCel[] pointers might not point
6891 ** to content area of the pages.
6893 ** A szCell[] of zero means the size of that cell has not yet been computed.
6895 ** The cells come from as many as four different pages:
6897 ** -----------
6898 ** | Parent |
6899 ** -----------
6900 ** / | \
6901 ** / | \
6902 ** --------- --------- ---------
6903 ** |Child-1| |Child-2| |Child-3|
6904 ** --------- --------- ---------
6906 ** The order of cells is in the array is for an index btree is:
6908 ** 1. All cells from Child-1 in order
6909 ** 2. The first divider cell from Parent
6910 ** 3. All cells from Child-2 in order
6911 ** 4. The second divider cell from Parent
6912 ** 5. All cells from Child-3 in order
6914 ** For a table-btree (with rowids) the items 2 and 4 are empty because
6915 ** content exists only in leaves and there are no divider cells.
6917 ** For an index btree, the apEnd[] array holds pointer to the end of page
6918 ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
6919 ** respectively. The ixNx[] array holds the number of cells contained in
6920 ** each of these 5 stages, and all stages to the left. Hence:
6922 ** ixNx[0] = Number of cells in Child-1.
6923 ** ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
6924 ** ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
6925 ** ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
6926 ** ixNx[4] = Total number of cells.
6928 ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
6929 ** are used and they point to the leaf pages only, and the ixNx value are:
6931 ** ixNx[0] = Number of cells in Child-1.
6932 ** ixNx[1] = Number of cells in Child-1 and Child-2.
6933 ** ixNx[2] = Total number of cells.
6935 ** Sometimes when deleting, a child page can have zero cells. In those
6936 ** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[]
6937 ** entries, shift down. The end result is that each ixNx[] entry should
6938 ** be larger than the previous
6940 typedef struct CellArray CellArray;
6941 struct CellArray {
6942 int nCell; /* Number of cells in apCell[] */
6943 MemPage *pRef; /* Reference page */
6944 u8 **apCell; /* All cells begin balanced */
6945 u16 *szCell; /* Local size of all cells in apCell[] */
6946 u8 *apEnd[NB*2]; /* MemPage.aDataEnd values */
6947 int ixNx[NB*2]; /* Index of at which we move to the next apEnd[] */
6951 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
6952 ** computed.
6954 static void populateCellCache(CellArray *p, int idx, int N){
6955 assert( idx>=0 && idx+N<=p->nCell );
6956 while( N>0 ){
6957 assert( p->apCell[idx]!=0 );
6958 if( p->szCell[idx]==0 ){
6959 p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
6960 }else{
6961 assert( CORRUPT_DB ||
6962 p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
6964 idx++;
6965 N--;
6970 ** Return the size of the Nth element of the cell array
6972 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
6973 assert( N>=0 && N<p->nCell );
6974 assert( p->szCell[N]==0 );
6975 p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
6976 return p->szCell[N];
6978 static u16 cachedCellSize(CellArray *p, int N){
6979 assert( N>=0 && N<p->nCell );
6980 if( p->szCell[N] ) return p->szCell[N];
6981 return computeCellSize(p, N);
6985 ** Array apCell[] contains pointers to nCell b-tree page cells. The
6986 ** szCell[] array contains the size in bytes of each cell. This function
6987 ** replaces the current contents of page pPg with the contents of the cell
6988 ** array.
6990 ** Some of the cells in apCell[] may currently be stored in pPg. This
6991 ** function works around problems caused by this by making a copy of any
6992 ** such cells before overwriting the page data.
6994 ** The MemPage.nFree field is invalidated by this function. It is the
6995 ** responsibility of the caller to set it correctly.
6997 static int rebuildPage(
6998 CellArray *pCArray, /* Content to be added to page pPg */
6999 int iFirst, /* First cell in pCArray to use */
7000 int nCell, /* Final number of cells on page */
7001 MemPage *pPg /* The page to be reconstructed */
7003 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
7004 u8 * const aData = pPg->aData; /* Pointer to data for pPg */
7005 const int usableSize = pPg->pBt->usableSize;
7006 u8 * const pEnd = &aData[usableSize];
7007 int i = iFirst; /* Which cell to copy from pCArray*/
7008 u32 j; /* Start of cell content area */
7009 int iEnd = i+nCell; /* Loop terminator */
7010 u8 *pCellptr = pPg->aCellIdx;
7011 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7012 u8 *pData;
7013 int k; /* Current slot in pCArray->apEnd[] */
7014 u8 *pSrcEnd; /* Current pCArray->apEnd[k] value */
7016 assert( i<iEnd );
7017 j = get2byte(&aData[hdr+5]);
7018 if( NEVER(j>(u32)usableSize) ){ j = 0; }
7019 memcpy(&pTmp[j], &aData[j], usableSize - j);
7021 for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
7022 pSrcEnd = pCArray->apEnd[k];
7024 pData = pEnd;
7025 while( 1/*exit by break*/ ){
7026 u8 *pCell = pCArray->apCell[i];
7027 u16 sz = pCArray->szCell[i];
7028 assert( sz>0 );
7029 if( SQLITE_WITHIN(pCell,aData+j,pEnd) ){
7030 if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
7031 pCell = &pTmp[pCell - aData];
7032 }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
7033 && (uptr)(pCell)<(uptr)pSrcEnd
7035 return SQLITE_CORRUPT_BKPT;
7038 pData -= sz;
7039 put2byte(pCellptr, (pData - aData));
7040 pCellptr += 2;
7041 if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
7042 memmove(pData, pCell, sz);
7043 assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
7044 i++;
7045 if( i>=iEnd ) break;
7046 if( pCArray->ixNx[k]<=i ){
7047 k++;
7048 pSrcEnd = pCArray->apEnd[k];
7052 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
7053 pPg->nCell = nCell;
7054 pPg->nOverflow = 0;
7056 put2byte(&aData[hdr+1], 0);
7057 put2byte(&aData[hdr+3], pPg->nCell);
7058 put2byte(&aData[hdr+5], pData - aData);
7059 aData[hdr+7] = 0x00;
7060 return SQLITE_OK;
7064 ** The pCArray objects contains pointers to b-tree cells and the cell sizes.
7065 ** This function attempts to add the cells stored in the array to page pPg.
7066 ** If it cannot (because the page needs to be defragmented before the cells
7067 ** will fit), non-zero is returned. Otherwise, if the cells are added
7068 ** successfully, zero is returned.
7070 ** Argument pCellptr points to the first entry in the cell-pointer array
7071 ** (part of page pPg) to populate. After cell apCell[0] is written to the
7072 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
7073 ** cell in the array. It is the responsibility of the caller to ensure
7074 ** that it is safe to overwrite this part of the cell-pointer array.
7076 ** When this function is called, *ppData points to the start of the
7077 ** content area on page pPg. If the size of the content area is extended,
7078 ** *ppData is updated to point to the new start of the content area
7079 ** before returning.
7081 ** Finally, argument pBegin points to the byte immediately following the
7082 ** end of the space required by this page for the cell-pointer area (for
7083 ** all cells - not just those inserted by the current call). If the content
7084 ** area must be extended to before this point in order to accomodate all
7085 ** cells in apCell[], then the cells do not fit and non-zero is returned.
7087 static int pageInsertArray(
7088 MemPage *pPg, /* Page to add cells to */
7089 u8 *pBegin, /* End of cell-pointer array */
7090 u8 **ppData, /* IN/OUT: Page content-area pointer */
7091 u8 *pCellptr, /* Pointer to cell-pointer area */
7092 int iFirst, /* Index of first cell to add */
7093 int nCell, /* Number of cells to add to pPg */
7094 CellArray *pCArray /* Array of cells */
7096 int i = iFirst; /* Loop counter - cell index to insert */
7097 u8 *aData = pPg->aData; /* Complete page */
7098 u8 *pData = *ppData; /* Content area. A subset of aData[] */
7099 int iEnd = iFirst + nCell; /* End of loop. One past last cell to ins */
7100 int k; /* Current slot in pCArray->apEnd[] */
7101 u8 *pEnd; /* Maximum extent of cell data */
7102 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
7103 if( iEnd<=iFirst ) return 0;
7104 for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
7105 pEnd = pCArray->apEnd[k];
7106 while( 1 /*Exit by break*/ ){
7107 int sz, rc;
7108 u8 *pSlot;
7109 assert( pCArray->szCell[i]!=0 );
7110 sz = pCArray->szCell[i];
7111 if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
7112 if( (pData - pBegin)<sz ) return 1;
7113 pData -= sz;
7114 pSlot = pData;
7116 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
7117 ** database. But they might for a corrupt database. Hence use memmove()
7118 ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
7119 assert( (pSlot+sz)<=pCArray->apCell[i]
7120 || pSlot>=(pCArray->apCell[i]+sz)
7121 || CORRUPT_DB );
7122 if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
7123 && (uptr)(pCArray->apCell[i])<(uptr)pEnd
7125 assert( CORRUPT_DB );
7126 (void)SQLITE_CORRUPT_BKPT;
7127 return 1;
7129 memmove(pSlot, pCArray->apCell[i], sz);
7130 put2byte(pCellptr, (pSlot - aData));
7131 pCellptr += 2;
7132 i++;
7133 if( i>=iEnd ) break;
7134 if( pCArray->ixNx[k]<=i ){
7135 k++;
7136 pEnd = pCArray->apEnd[k];
7139 *ppData = pData;
7140 return 0;
7144 ** The pCArray object contains pointers to b-tree cells and their sizes.
7146 ** This function adds the space associated with each cell in the array
7147 ** that is currently stored within the body of pPg to the pPg free-list.
7148 ** The cell-pointers and other fields of the page are not updated.
7150 ** This function returns the total number of cells added to the free-list.
7152 static int pageFreeArray(
7153 MemPage *pPg, /* Page to edit */
7154 int iFirst, /* First cell to delete */
7155 int nCell, /* Cells to delete */
7156 CellArray *pCArray /* Array of cells */
7158 u8 * const aData = pPg->aData;
7159 u8 * const pEnd = &aData[pPg->pBt->usableSize];
7160 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
7161 int nRet = 0;
7162 int i;
7163 int iEnd = iFirst + nCell;
7164 u8 *pFree = 0;
7165 int szFree = 0;
7167 for(i=iFirst; i<iEnd; i++){
7168 u8 *pCell = pCArray->apCell[i];
7169 if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
7170 int sz;
7171 /* No need to use cachedCellSize() here. The sizes of all cells that
7172 ** are to be freed have already been computing while deciding which
7173 ** cells need freeing */
7174 sz = pCArray->szCell[i]; assert( sz>0 );
7175 if( pFree!=(pCell + sz) ){
7176 if( pFree ){
7177 assert( pFree>aData && (pFree - aData)<65536 );
7178 freeSpace(pPg, (u16)(pFree - aData), szFree);
7180 pFree = pCell;
7181 szFree = sz;
7182 if( pFree+sz>pEnd ){
7183 return 0;
7185 }else{
7186 pFree = pCell;
7187 szFree += sz;
7189 nRet++;
7192 if( pFree ){
7193 assert( pFree>aData && (pFree - aData)<65536 );
7194 freeSpace(pPg, (u16)(pFree - aData), szFree);
7196 return nRet;
7200 ** pCArray contains pointers to and sizes of all cells in the page being
7201 ** balanced. The current page, pPg, has pPg->nCell cells starting with
7202 ** pCArray->apCell[iOld]. After balancing, this page should hold nNew cells
7203 ** starting at apCell[iNew].
7205 ** This routine makes the necessary adjustments to pPg so that it contains
7206 ** the correct cells after being balanced.
7208 ** The pPg->nFree field is invalid when this function returns. It is the
7209 ** responsibility of the caller to set it correctly.
7211 static int editPage(
7212 MemPage *pPg, /* Edit this page */
7213 int iOld, /* Index of first cell currently on page */
7214 int iNew, /* Index of new first cell on page */
7215 int nNew, /* Final number of cells on page */
7216 CellArray *pCArray /* Array of cells and sizes */
7218 u8 * const aData = pPg->aData;
7219 const int hdr = pPg->hdrOffset;
7220 u8 *pBegin = &pPg->aCellIdx[nNew * 2];
7221 int nCell = pPg->nCell; /* Cells stored on pPg */
7222 u8 *pData;
7223 u8 *pCellptr;
7224 int i;
7225 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
7226 int iNewEnd = iNew + nNew;
7228 #ifdef SQLITE_DEBUG
7229 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7230 memcpy(pTmp, aData, pPg->pBt->usableSize);
7231 #endif
7233 /* Remove cells from the start and end of the page */
7234 assert( nCell>=0 );
7235 if( iOld<iNew ){
7236 int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
7237 if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT;
7238 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
7239 nCell -= nShift;
7241 if( iNewEnd < iOldEnd ){
7242 int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
7243 assert( nCell>=nTail );
7244 nCell -= nTail;
7247 pData = &aData[get2byteNotZero(&aData[hdr+5])];
7248 if( pData<pBegin ) goto editpage_fail;
7250 /* Add cells to the start of the page */
7251 if( iNew<iOld ){
7252 int nAdd = MIN(nNew,iOld-iNew);
7253 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
7254 assert( nAdd>=0 );
7255 pCellptr = pPg->aCellIdx;
7256 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
7257 if( pageInsertArray(
7258 pPg, pBegin, &pData, pCellptr,
7259 iNew, nAdd, pCArray
7260 ) ) goto editpage_fail;
7261 nCell += nAdd;
7264 /* Add any overflow cells */
7265 for(i=0; i<pPg->nOverflow; i++){
7266 int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
7267 if( iCell>=0 && iCell<nNew ){
7268 pCellptr = &pPg->aCellIdx[iCell * 2];
7269 if( nCell>iCell ){
7270 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
7272 nCell++;
7273 cachedCellSize(pCArray, iCell+iNew);
7274 if( pageInsertArray(
7275 pPg, pBegin, &pData, pCellptr,
7276 iCell+iNew, 1, pCArray
7277 ) ) goto editpage_fail;
7281 /* Append cells to the end of the page */
7282 assert( nCell>=0 );
7283 pCellptr = &pPg->aCellIdx[nCell*2];
7284 if( pageInsertArray(
7285 pPg, pBegin, &pData, pCellptr,
7286 iNew+nCell, nNew-nCell, pCArray
7287 ) ) goto editpage_fail;
7289 pPg->nCell = nNew;
7290 pPg->nOverflow = 0;
7292 put2byte(&aData[hdr+3], pPg->nCell);
7293 put2byte(&aData[hdr+5], pData - aData);
7295 #ifdef SQLITE_DEBUG
7296 for(i=0; i<nNew && !CORRUPT_DB; i++){
7297 u8 *pCell = pCArray->apCell[i+iNew];
7298 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
7299 if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
7300 pCell = &pTmp[pCell - aData];
7302 assert( 0==memcmp(pCell, &aData[iOff],
7303 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
7305 #endif
7307 return SQLITE_OK;
7308 editpage_fail:
7309 /* Unable to edit this page. Rebuild it from scratch instead. */
7310 populateCellCache(pCArray, iNew, nNew);
7311 return rebuildPage(pCArray, iNew, nNew, pPg);
7315 #ifndef SQLITE_OMIT_QUICKBALANCE
7317 ** This version of balance() handles the common special case where
7318 ** a new entry is being inserted on the extreme right-end of the
7319 ** tree, in other words, when the new entry will become the largest
7320 ** entry in the tree.
7322 ** Instead of trying to balance the 3 right-most leaf pages, just add
7323 ** a new page to the right-hand side and put the one new entry in
7324 ** that page. This leaves the right side of the tree somewhat
7325 ** unbalanced. But odds are that we will be inserting new entries
7326 ** at the end soon afterwards so the nearly empty page will quickly
7327 ** fill up. On average.
7329 ** pPage is the leaf page which is the right-most page in the tree.
7330 ** pParent is its parent. pPage must have a single overflow entry
7331 ** which is also the right-most entry on the page.
7333 ** The pSpace buffer is used to store a temporary copy of the divider
7334 ** cell that will be inserted into pParent. Such a cell consists of a 4
7335 ** byte page number followed by a variable length integer. In other
7336 ** words, at most 13 bytes. Hence the pSpace buffer must be at
7337 ** least 13 bytes in size.
7339 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
7340 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
7341 MemPage *pNew; /* Newly allocated page */
7342 int rc; /* Return Code */
7343 Pgno pgnoNew; /* Page number of pNew */
7345 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7346 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7347 assert( pPage->nOverflow==1 );
7349 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; /* dbfuzz001.test */
7350 assert( pPage->nFree>=0 );
7351 assert( pParent->nFree>=0 );
7353 /* Allocate a new page. This page will become the right-sibling of
7354 ** pPage. Make the parent page writable, so that the new divider cell
7355 ** may be inserted. If both these operations are successful, proceed.
7357 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
7359 if( rc==SQLITE_OK ){
7361 u8 *pOut = &pSpace[4];
7362 u8 *pCell = pPage->apOvfl[0];
7363 u16 szCell = pPage->xCellSize(pPage, pCell);
7364 u8 *pStop;
7365 CellArray b;
7367 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
7368 assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
7369 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
7370 b.nCell = 1;
7371 b.pRef = pPage;
7372 b.apCell = &pCell;
7373 b.szCell = &szCell;
7374 b.apEnd[0] = pPage->aDataEnd;
7375 b.ixNx[0] = 2;
7376 rc = rebuildPage(&b, 0, 1, pNew);
7377 if( NEVER(rc) ){
7378 releasePage(pNew);
7379 return rc;
7381 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
7383 /* If this is an auto-vacuum database, update the pointer map
7384 ** with entries for the new page, and any pointer from the
7385 ** cell on the page to an overflow page. If either of these
7386 ** operations fails, the return code is set, but the contents
7387 ** of the parent page are still manipulated by thh code below.
7388 ** That is Ok, at this point the parent page is guaranteed to
7389 ** be marked as dirty. Returning an error code will cause a
7390 ** rollback, undoing any changes made to the parent page.
7392 if( ISAUTOVACUUM ){
7393 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
7394 if( szCell>pNew->minLocal ){
7395 ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
7399 /* Create a divider cell to insert into pParent. The divider cell
7400 ** consists of a 4-byte page number (the page number of pPage) and
7401 ** a variable length key value (which must be the same value as the
7402 ** largest key on pPage).
7404 ** To find the largest key value on pPage, first find the right-most
7405 ** cell on pPage. The first two fields of this cell are the
7406 ** record-length (a variable length integer at most 32-bits in size)
7407 ** and the key value (a variable length integer, may have any value).
7408 ** The first of the while(...) loops below skips over the record-length
7409 ** field. The second while(...) loop copies the key value from the
7410 ** cell on pPage into the pSpace buffer.
7412 pCell = findCell(pPage, pPage->nCell-1);
7413 pStop = &pCell[9];
7414 while( (*(pCell++)&0x80) && pCell<pStop );
7415 pStop = &pCell[9];
7416 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
7418 /* Insert the new divider cell into pParent. */
7419 if( rc==SQLITE_OK ){
7420 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
7421 0, pPage->pgno, &rc);
7424 /* Set the right-child pointer of pParent to point to the new page. */
7425 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
7427 /* Release the reference to the new page. */
7428 releasePage(pNew);
7431 return rc;
7433 #endif /* SQLITE_OMIT_QUICKBALANCE */
7435 #if 0
7437 ** This function does not contribute anything to the operation of SQLite.
7438 ** it is sometimes activated temporarily while debugging code responsible
7439 ** for setting pointer-map entries.
7441 static int ptrmapCheckPages(MemPage **apPage, int nPage){
7442 int i, j;
7443 for(i=0; i<nPage; i++){
7444 Pgno n;
7445 u8 e;
7446 MemPage *pPage = apPage[i];
7447 BtShared *pBt = pPage->pBt;
7448 assert( pPage->isInit );
7450 for(j=0; j<pPage->nCell; j++){
7451 CellInfo info;
7452 u8 *z;
7454 z = findCell(pPage, j);
7455 pPage->xParseCell(pPage, z, &info);
7456 if( info.nLocal<info.nPayload ){
7457 Pgno ovfl = get4byte(&z[info.nSize-4]);
7458 ptrmapGet(pBt, ovfl, &e, &n);
7459 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
7461 if( !pPage->leaf ){
7462 Pgno child = get4byte(z);
7463 ptrmapGet(pBt, child, &e, &n);
7464 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7467 if( !pPage->leaf ){
7468 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
7469 ptrmapGet(pBt, child, &e, &n);
7470 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7473 return 1;
7475 #endif
7478 ** This function is used to copy the contents of the b-tree node stored
7479 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
7480 ** the pointer-map entries for each child page are updated so that the
7481 ** parent page stored in the pointer map is page pTo. If pFrom contained
7482 ** any cells with overflow page pointers, then the corresponding pointer
7483 ** map entries are also updated so that the parent page is page pTo.
7485 ** If pFrom is currently carrying any overflow cells (entries in the
7486 ** MemPage.apOvfl[] array), they are not copied to pTo.
7488 ** Before returning, page pTo is reinitialized using btreeInitPage().
7490 ** The performance of this function is not critical. It is only used by
7491 ** the balance_shallower() and balance_deeper() procedures, neither of
7492 ** which are called often under normal circumstances.
7494 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
7495 if( (*pRC)==SQLITE_OK ){
7496 BtShared * const pBt = pFrom->pBt;
7497 u8 * const aFrom = pFrom->aData;
7498 u8 * const aTo = pTo->aData;
7499 int const iFromHdr = pFrom->hdrOffset;
7500 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
7501 int rc;
7502 int iData;
7505 assert( pFrom->isInit );
7506 assert( pFrom->nFree>=iToHdr );
7507 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
7509 /* Copy the b-tree node content from page pFrom to page pTo. */
7510 iData = get2byte(&aFrom[iFromHdr+5]);
7511 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
7512 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
7514 /* Reinitialize page pTo so that the contents of the MemPage structure
7515 ** match the new data. The initialization of pTo can actually fail under
7516 ** fairly obscure circumstances, even though it is a copy of initialized
7517 ** page pFrom.
7519 pTo->isInit = 0;
7520 rc = btreeInitPage(pTo);
7521 if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo);
7522 if( rc!=SQLITE_OK ){
7523 *pRC = rc;
7524 return;
7527 /* If this is an auto-vacuum database, update the pointer-map entries
7528 ** for any b-tree or overflow pages that pTo now contains the pointers to.
7530 if( ISAUTOVACUUM ){
7531 *pRC = setChildPtrmaps(pTo);
7537 ** This routine redistributes cells on the iParentIdx'th child of pParent
7538 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
7539 ** same amount of free space. Usually a single sibling on either side of the
7540 ** page are used in the balancing, though both siblings might come from one
7541 ** side if the page is the first or last child of its parent. If the page
7542 ** has fewer than 2 siblings (something which can only happen if the page
7543 ** is a root page or a child of a root page) then all available siblings
7544 ** participate in the balancing.
7546 ** The number of siblings of the page might be increased or decreased by
7547 ** one or two in an effort to keep pages nearly full but not over full.
7549 ** Note that when this routine is called, some of the cells on the page
7550 ** might not actually be stored in MemPage.aData[]. This can happen
7551 ** if the page is overfull. This routine ensures that all cells allocated
7552 ** to the page and its siblings fit into MemPage.aData[] before returning.
7554 ** In the course of balancing the page and its siblings, cells may be
7555 ** inserted into or removed from the parent page (pParent). Doing so
7556 ** may cause the parent page to become overfull or underfull. If this
7557 ** happens, it is the responsibility of the caller to invoke the correct
7558 ** balancing routine to fix this problem (see the balance() routine).
7560 ** If this routine fails for any reason, it might leave the database
7561 ** in a corrupted state. So if this routine fails, the database should
7562 ** be rolled back.
7564 ** The third argument to this function, aOvflSpace, is a pointer to a
7565 ** buffer big enough to hold one page. If while inserting cells into the parent
7566 ** page (pParent) the parent page becomes overfull, this buffer is
7567 ** used to store the parent's overflow cells. Because this function inserts
7568 ** a maximum of four divider cells into the parent page, and the maximum
7569 ** size of a cell stored within an internal node is always less than 1/4
7570 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
7571 ** enough for all overflow cells.
7573 ** If aOvflSpace is set to a null pointer, this function returns
7574 ** SQLITE_NOMEM.
7576 static int balance_nonroot(
7577 MemPage *pParent, /* Parent page of siblings being balanced */
7578 int iParentIdx, /* Index of "the page" in pParent */
7579 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
7580 int isRoot, /* True if pParent is a root-page */
7581 int bBulk /* True if this call is part of a bulk load */
7583 BtShared *pBt; /* The whole database */
7584 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
7585 int nNew = 0; /* Number of pages in apNew[] */
7586 int nOld; /* Number of pages in apOld[] */
7587 int i, j, k; /* Loop counters */
7588 int nxDiv; /* Next divider slot in pParent->aCell[] */
7589 int rc = SQLITE_OK; /* The return code */
7590 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
7591 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
7592 int usableSpace; /* Bytes in pPage beyond the header */
7593 int pageFlags; /* Value of pPage->aData[0] */
7594 int iSpace1 = 0; /* First unused byte of aSpace1[] */
7595 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
7596 int szScratch; /* Size of scratch memory requested */
7597 MemPage *apOld[NB]; /* pPage and up to two siblings */
7598 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
7599 u8 *pRight; /* Location in parent of right-sibling pointer */
7600 u8 *apDiv[NB-1]; /* Divider cells in pParent */
7601 int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
7602 int cntOld[NB+2]; /* Old index in b.apCell[] */
7603 int szNew[NB+2]; /* Combined size of cells placed on i-th page */
7604 u8 *aSpace1; /* Space for copies of dividers cells */
7605 Pgno pgno; /* Temp var to store a page number in */
7606 u8 abDone[NB+2]; /* True after i'th new page is populated */
7607 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
7608 Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
7609 u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
7610 CellArray b; /* Parsed information on cells being balanced */
7612 memset(abDone, 0, sizeof(abDone));
7613 b.nCell = 0;
7614 b.apCell = 0;
7615 pBt = pParent->pBt;
7616 assert( sqlite3_mutex_held(pBt->mutex) );
7617 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7619 /* At this point pParent may have at most one overflow cell. And if
7620 ** this overflow cell is present, it must be the cell with
7621 ** index iParentIdx. This scenario comes about when this function
7622 ** is called (indirectly) from sqlite3BtreeDelete().
7624 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
7625 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
7627 if( !aOvflSpace ){
7628 return SQLITE_NOMEM_BKPT;
7630 assert( pParent->nFree>=0 );
7632 /* Find the sibling pages to balance. Also locate the cells in pParent
7633 ** that divide the siblings. An attempt is made to find NN siblings on
7634 ** either side of pPage. More siblings are taken from one side, however,
7635 ** if there are fewer than NN siblings on the other side. If pParent
7636 ** has NB or fewer children then all children of pParent are taken.
7638 ** This loop also drops the divider cells from the parent page. This
7639 ** way, the remainder of the function does not have to deal with any
7640 ** overflow cells in the parent page, since if any existed they will
7641 ** have already been removed.
7643 i = pParent->nOverflow + pParent->nCell;
7644 if( i<2 ){
7645 nxDiv = 0;
7646 }else{
7647 assert( bBulk==0 || bBulk==1 );
7648 if( iParentIdx==0 ){
7649 nxDiv = 0;
7650 }else if( iParentIdx==i ){
7651 nxDiv = i-2+bBulk;
7652 }else{
7653 nxDiv = iParentIdx-1;
7655 i = 2-bBulk;
7657 nOld = i+1;
7658 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
7659 pRight = &pParent->aData[pParent->hdrOffset+8];
7660 }else{
7661 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
7663 pgno = get4byte(pRight);
7664 while( 1 ){
7665 if( rc==SQLITE_OK ){
7666 rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
7668 if( rc ){
7669 memset(apOld, 0, (i+1)*sizeof(MemPage*));
7670 goto balance_cleanup;
7672 if( apOld[i]->nFree<0 ){
7673 rc = btreeComputeFreeSpace(apOld[i]);
7674 if( rc ){
7675 memset(apOld, 0, (i)*sizeof(MemPage*));
7676 goto balance_cleanup;
7679 if( (i--)==0 ) break;
7681 if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
7682 apDiv[i] = pParent->apOvfl[0];
7683 pgno = get4byte(apDiv[i]);
7684 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7685 pParent->nOverflow = 0;
7686 }else{
7687 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
7688 pgno = get4byte(apDiv[i]);
7689 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7691 /* Drop the cell from the parent page. apDiv[i] still points to
7692 ** the cell within the parent, even though it has been dropped.
7693 ** This is safe because dropping a cell only overwrites the first
7694 ** four bytes of it, and this function does not need the first
7695 ** four bytes of the divider cell. So the pointer is safe to use
7696 ** later on.
7698 ** But not if we are in secure-delete mode. In secure-delete mode,
7699 ** the dropCell() routine will overwrite the entire cell with zeroes.
7700 ** In this case, temporarily copy the cell into the aOvflSpace[]
7701 ** buffer. It will be copied out again as soon as the aSpace[] buffer
7702 ** is allocated. */
7703 if( pBt->btsFlags & BTS_FAST_SECURE ){
7704 int iOff;
7706 /* If the following if() condition is not true, the db is corrupted.
7707 ** The call to dropCell() below will detect this. */
7708 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
7709 if( (iOff+szNew[i])<=(int)pBt->usableSize ){
7710 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
7711 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
7714 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
7718 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
7719 ** alignment */
7720 nMaxCells = nOld*(MX_CELL(pBt) + ArraySize(pParent->apOvfl));
7721 nMaxCells = (nMaxCells + 3)&~3;
7724 ** Allocate space for memory structures
7726 szScratch =
7727 nMaxCells*sizeof(u8*) /* b.apCell */
7728 + nMaxCells*sizeof(u16) /* b.szCell */
7729 + pBt->pageSize; /* aSpace1 */
7731 assert( szScratch<=7*(int)pBt->pageSize );
7732 b.apCell = sqlite3StackAllocRaw(0, szScratch );
7733 if( b.apCell==0 ){
7734 rc = SQLITE_NOMEM_BKPT;
7735 goto balance_cleanup;
7737 b.szCell = (u16*)&b.apCell[nMaxCells];
7738 aSpace1 = (u8*)&b.szCell[nMaxCells];
7739 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
7742 ** Load pointers to all cells on sibling pages and the divider cells
7743 ** into the local b.apCell[] array. Make copies of the divider cells
7744 ** into space obtained from aSpace1[]. The divider cells have already
7745 ** been removed from pParent.
7747 ** If the siblings are on leaf pages, then the child pointers of the
7748 ** divider cells are stripped from the cells before they are copied
7749 ** into aSpace1[]. In this way, all cells in b.apCell[] are without
7750 ** child pointers. If siblings are not leaves, then all cell in
7751 ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
7752 ** are alike.
7754 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
7755 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
7757 b.pRef = apOld[0];
7758 leafCorrection = b.pRef->leaf*4;
7759 leafData = b.pRef->intKeyLeaf;
7760 for(i=0; i<nOld; i++){
7761 MemPage *pOld = apOld[i];
7762 int limit = pOld->nCell;
7763 u8 *aData = pOld->aData;
7764 u16 maskPage = pOld->maskPage;
7765 u8 *piCell = aData + pOld->cellOffset;
7766 u8 *piEnd;
7767 VVA_ONLY( int nCellAtStart = b.nCell; )
7769 /* Verify that all sibling pages are of the same "type" (table-leaf,
7770 ** table-interior, index-leaf, or index-interior).
7772 if( pOld->aData[0]!=apOld[0]->aData[0] ){
7773 rc = SQLITE_CORRUPT_BKPT;
7774 goto balance_cleanup;
7777 /* Load b.apCell[] with pointers to all cells in pOld. If pOld
7778 ** contains overflow cells, include them in the b.apCell[] array
7779 ** in the correct spot.
7781 ** Note that when there are multiple overflow cells, it is always the
7782 ** case that they are sequential and adjacent. This invariant arises
7783 ** because multiple overflows can only occurs when inserting divider
7784 ** cells into a parent on a prior balance, and divider cells are always
7785 ** adjacent and are inserted in order. There is an assert() tagged
7786 ** with "NOTE 1" in the overflow cell insertion loop to prove this
7787 ** invariant.
7789 ** This must be done in advance. Once the balance starts, the cell
7790 ** offset section of the btree page will be overwritten and we will no
7791 ** long be able to find the cells if a pointer to each cell is not saved
7792 ** first.
7794 memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
7795 if( pOld->nOverflow>0 ){
7796 if( NEVER(limit<pOld->aiOvfl[0]) ){
7797 rc = SQLITE_CORRUPT_BKPT;
7798 goto balance_cleanup;
7800 limit = pOld->aiOvfl[0];
7801 for(j=0; j<limit; j++){
7802 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7803 piCell += 2;
7804 b.nCell++;
7806 for(k=0; k<pOld->nOverflow; k++){
7807 assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
7808 b.apCell[b.nCell] = pOld->apOvfl[k];
7809 b.nCell++;
7812 piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
7813 while( piCell<piEnd ){
7814 assert( b.nCell<nMaxCells );
7815 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7816 piCell += 2;
7817 b.nCell++;
7819 assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );
7821 cntOld[i] = b.nCell;
7822 if( i<nOld-1 && !leafData){
7823 u16 sz = (u16)szNew[i];
7824 u8 *pTemp;
7825 assert( b.nCell<nMaxCells );
7826 b.szCell[b.nCell] = sz;
7827 pTemp = &aSpace1[iSpace1];
7828 iSpace1 += sz;
7829 assert( sz<=pBt->maxLocal+23 );
7830 assert( iSpace1 <= (int)pBt->pageSize );
7831 memcpy(pTemp, apDiv[i], sz);
7832 b.apCell[b.nCell] = pTemp+leafCorrection;
7833 assert( leafCorrection==0 || leafCorrection==4 );
7834 b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
7835 if( !pOld->leaf ){
7836 assert( leafCorrection==0 );
7837 assert( pOld->hdrOffset==0 || CORRUPT_DB );
7838 /* The right pointer of the child page pOld becomes the left
7839 ** pointer of the divider cell */
7840 memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
7841 }else{
7842 assert( leafCorrection==4 );
7843 while( b.szCell[b.nCell]<4 ){
7844 /* Do not allow any cells smaller than 4 bytes. If a smaller cell
7845 ** does exist, pad it with 0x00 bytes. */
7846 assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
7847 assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
7848 aSpace1[iSpace1++] = 0x00;
7849 b.szCell[b.nCell]++;
7852 b.nCell++;
7857 ** Figure out the number of pages needed to hold all b.nCell cells.
7858 ** Store this number in "k". Also compute szNew[] which is the total
7859 ** size of all cells on the i-th page and cntNew[] which is the index
7860 ** in b.apCell[] of the cell that divides page i from page i+1.
7861 ** cntNew[k] should equal b.nCell.
7863 ** Values computed by this block:
7865 ** k: The total number of sibling pages
7866 ** szNew[i]: Spaced used on the i-th sibling page.
7867 ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
7868 ** the right of the i-th sibling page.
7869 ** usableSpace: Number of bytes of space available on each sibling.
7872 usableSpace = pBt->usableSize - 12 + leafCorrection;
7873 for(i=k=0; i<nOld; i++, k++){
7874 MemPage *p = apOld[i];
7875 b.apEnd[k] = p->aDataEnd;
7876 b.ixNx[k] = cntOld[i];
7877 if( k && b.ixNx[k]==b.ixNx[k-1] ){
7878 k--; /* Omit b.ixNx[] entry for child pages with no cells */
7880 if( !leafData ){
7881 k++;
7882 b.apEnd[k] = pParent->aDataEnd;
7883 b.ixNx[k] = cntOld[i]+1;
7885 assert( p->nFree>=0 );
7886 szNew[i] = usableSpace - p->nFree;
7887 for(j=0; j<p->nOverflow; j++){
7888 szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
7890 cntNew[i] = cntOld[i];
7892 k = nOld;
7893 for(i=0; i<k; i++){
7894 int sz;
7895 while( szNew[i]>usableSpace ){
7896 if( i+1>=k ){
7897 k = i+2;
7898 if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
7899 szNew[k-1] = 0;
7900 cntNew[k-1] = b.nCell;
7902 sz = 2 + cachedCellSize(&b, cntNew[i]-1);
7903 szNew[i] -= sz;
7904 if( !leafData ){
7905 if( cntNew[i]<b.nCell ){
7906 sz = 2 + cachedCellSize(&b, cntNew[i]);
7907 }else{
7908 sz = 0;
7911 szNew[i+1] += sz;
7912 cntNew[i]--;
7914 while( cntNew[i]<b.nCell ){
7915 sz = 2 + cachedCellSize(&b, cntNew[i]);
7916 if( szNew[i]+sz>usableSpace ) break;
7917 szNew[i] += sz;
7918 cntNew[i]++;
7919 if( !leafData ){
7920 if( cntNew[i]<b.nCell ){
7921 sz = 2 + cachedCellSize(&b, cntNew[i]);
7922 }else{
7923 sz = 0;
7926 szNew[i+1] -= sz;
7928 if( cntNew[i]>=b.nCell ){
7929 k = i+1;
7930 }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
7931 rc = SQLITE_CORRUPT_BKPT;
7932 goto balance_cleanup;
7937 ** The packing computed by the previous block is biased toward the siblings
7938 ** on the left side (siblings with smaller keys). The left siblings are
7939 ** always nearly full, while the right-most sibling might be nearly empty.
7940 ** The next block of code attempts to adjust the packing of siblings to
7941 ** get a better balance.
7943 ** This adjustment is more than an optimization. The packing above might
7944 ** be so out of balance as to be illegal. For example, the right-most
7945 ** sibling might be completely empty. This adjustment is not optional.
7947 for(i=k-1; i>0; i--){
7948 int szRight = szNew[i]; /* Size of sibling on the right */
7949 int szLeft = szNew[i-1]; /* Size of sibling on the left */
7950 int r; /* Index of right-most cell in left sibling */
7951 int d; /* Index of first cell to the left of right sibling */
7953 r = cntNew[i-1] - 1;
7954 d = r + 1 - leafData;
7955 (void)cachedCellSize(&b, d);
7957 assert( d<nMaxCells );
7958 assert( r<nMaxCells );
7959 (void)cachedCellSize(&b, r);
7960 if( szRight!=0
7961 && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
7962 break;
7964 szRight += b.szCell[d] + 2;
7965 szLeft -= b.szCell[r] + 2;
7966 cntNew[i-1] = r;
7967 r--;
7968 d--;
7969 }while( r>=0 );
7970 szNew[i] = szRight;
7971 szNew[i-1] = szLeft;
7972 if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
7973 rc = SQLITE_CORRUPT_BKPT;
7974 goto balance_cleanup;
7978 /* Sanity check: For a non-corrupt database file one of the follwing
7979 ** must be true:
7980 ** (1) We found one or more cells (cntNew[0])>0), or
7981 ** (2) pPage is a virtual root page. A virtual root page is when
7982 ** the real root page is page 1 and we are the only child of
7983 ** that page.
7985 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
7986 TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
7987 apOld[0]->pgno, apOld[0]->nCell,
7988 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
7989 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
7993 ** Allocate k new pages. Reuse old pages where possible.
7995 pageFlags = apOld[0]->aData[0];
7996 for(i=0; i<k; i++){
7997 MemPage *pNew;
7998 if( i<nOld ){
7999 pNew = apNew[i] = apOld[i];
8000 apOld[i] = 0;
8001 rc = sqlite3PagerWrite(pNew->pDbPage);
8002 nNew++;
8003 if( sqlite3PagerPageRefcount(pNew->pDbPage)!=1+(i==(iParentIdx-nxDiv)) ){
8004 rc = SQLITE_CORRUPT_BKPT;
8006 if( rc ) goto balance_cleanup;
8007 }else{
8008 assert( i>0 );
8009 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
8010 if( rc ) goto balance_cleanup;
8011 zeroPage(pNew, pageFlags);
8012 apNew[i] = pNew;
8013 nNew++;
8014 cntOld[i] = b.nCell;
8016 /* Set the pointer-map entry for the new sibling page. */
8017 if( ISAUTOVACUUM ){
8018 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
8019 if( rc!=SQLITE_OK ){
8020 goto balance_cleanup;
8027 ** Reassign page numbers so that the new pages are in ascending order.
8028 ** This helps to keep entries in the disk file in order so that a scan
8029 ** of the table is closer to a linear scan through the file. That in turn
8030 ** helps the operating system to deliver pages from the disk more rapidly.
8032 ** An O(n^2) insertion sort algorithm is used, but since n is never more
8033 ** than (NB+2) (a small constant), that should not be a problem.
8035 ** When NB==3, this one optimization makes the database about 25% faster
8036 ** for large insertions and deletions.
8038 for(i=0; i<nNew; i++){
8039 aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
8040 aPgFlags[i] = apNew[i]->pDbPage->flags;
8041 for(j=0; j<i; j++){
8042 if( NEVER(aPgno[j]==aPgno[i]) ){
8043 /* This branch is taken if the set of sibling pages somehow contains
8044 ** duplicate entries. This can happen if the database is corrupt.
8045 ** It would be simpler to detect this as part of the loop below, but
8046 ** we do the detection here in order to avoid populating the pager
8047 ** cache with two separate objects associated with the same
8048 ** page number. */
8049 assert( CORRUPT_DB );
8050 rc = SQLITE_CORRUPT_BKPT;
8051 goto balance_cleanup;
8055 for(i=0; i<nNew; i++){
8056 int iBest = 0; /* aPgno[] index of page number to use */
8057 for(j=1; j<nNew; j++){
8058 if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
8060 pgno = aPgOrder[iBest];
8061 aPgOrder[iBest] = 0xffffffff;
8062 if( iBest!=i ){
8063 if( iBest>i ){
8064 sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
8066 sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
8067 apNew[i]->pgno = pgno;
8071 TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
8072 "%d(%d nc=%d) %d(%d nc=%d)\n",
8073 apNew[0]->pgno, szNew[0], cntNew[0],
8074 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
8075 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
8076 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
8077 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
8078 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
8079 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
8080 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
8081 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
8084 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8085 assert( nNew>=1 && nNew<=ArraySize(apNew) );
8086 assert( apNew[nNew-1]!=0 );
8087 put4byte(pRight, apNew[nNew-1]->pgno);
8089 /* If the sibling pages are not leaves, ensure that the right-child pointer
8090 ** of the right-most new sibling page is set to the value that was
8091 ** originally in the same field of the right-most old sibling page. */
8092 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
8093 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
8094 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
8097 /* Make any required updates to pointer map entries associated with
8098 ** cells stored on sibling pages following the balance operation. Pointer
8099 ** map entries associated with divider cells are set by the insertCell()
8100 ** routine. The associated pointer map entries are:
8102 ** a) if the cell contains a reference to an overflow chain, the
8103 ** entry associated with the first page in the overflow chain, and
8105 ** b) if the sibling pages are not leaves, the child page associated
8106 ** with the cell.
8108 ** If the sibling pages are not leaves, then the pointer map entry
8109 ** associated with the right-child of each sibling may also need to be
8110 ** updated. This happens below, after the sibling pages have been
8111 ** populated, not here.
8113 if( ISAUTOVACUUM ){
8114 MemPage *pOld;
8115 MemPage *pNew = pOld = apNew[0];
8116 int cntOldNext = pNew->nCell + pNew->nOverflow;
8117 int iNew = 0;
8118 int iOld = 0;
8120 for(i=0; i<b.nCell; i++){
8121 u8 *pCell = b.apCell[i];
8122 while( i==cntOldNext ){
8123 iOld++;
8124 assert( iOld<nNew || iOld<nOld );
8125 assert( iOld>=0 && iOld<NB );
8126 pOld = iOld<nNew ? apNew[iOld] : apOld[iOld];
8127 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
8129 if( i==cntNew[iNew] ){
8130 pNew = apNew[++iNew];
8131 if( !leafData ) continue;
8134 /* Cell pCell is destined for new sibling page pNew. Originally, it
8135 ** was either part of sibling page iOld (possibly an overflow cell),
8136 ** or else the divider cell to the left of sibling page iOld. So,
8137 ** if sibling page iOld had the same page number as pNew, and if
8138 ** pCell really was a part of sibling page iOld (not a divider or
8139 ** overflow cell), we can skip updating the pointer map entries. */
8140 if( iOld>=nNew
8141 || pNew->pgno!=aPgno[iOld]
8142 || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
8144 if( !leafCorrection ){
8145 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
8147 if( cachedCellSize(&b,i)>pNew->minLocal ){
8148 ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);
8150 if( rc ) goto balance_cleanup;
8155 /* Insert new divider cells into pParent. */
8156 for(i=0; i<nNew-1; i++){
8157 u8 *pCell;
8158 u8 *pTemp;
8159 int sz;
8160 u8 *pSrcEnd;
8161 MemPage *pNew = apNew[i];
8162 j = cntNew[i];
8164 assert( j<nMaxCells );
8165 assert( b.apCell[j]!=0 );
8166 pCell = b.apCell[j];
8167 sz = b.szCell[j] + leafCorrection;
8168 pTemp = &aOvflSpace[iOvflSpace];
8169 if( !pNew->leaf ){
8170 memcpy(&pNew->aData[8], pCell, 4);
8171 }else if( leafData ){
8172 /* If the tree is a leaf-data tree, and the siblings are leaves,
8173 ** then there is no divider cell in b.apCell[]. Instead, the divider
8174 ** cell consists of the integer key for the right-most cell of
8175 ** the sibling-page assembled above only.
8177 CellInfo info;
8178 j--;
8179 pNew->xParseCell(pNew, b.apCell[j], &info);
8180 pCell = pTemp;
8181 sz = 4 + putVarint(&pCell[4], info.nKey);
8182 pTemp = 0;
8183 }else{
8184 pCell -= 4;
8185 /* Obscure case for non-leaf-data trees: If the cell at pCell was
8186 ** previously stored on a leaf node, and its reported size was 4
8187 ** bytes, then it may actually be smaller than this
8188 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
8189 ** any cell). But it is important to pass the correct size to
8190 ** insertCell(), so reparse the cell now.
8192 ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
8193 ** and WITHOUT ROWID tables with exactly one column which is the
8194 ** primary key.
8196 if( b.szCell[j]==4 ){
8197 assert(leafCorrection==4);
8198 sz = pParent->xCellSize(pParent, pCell);
8201 iOvflSpace += sz;
8202 assert( sz<=pBt->maxLocal+23 );
8203 assert( iOvflSpace <= (int)pBt->pageSize );
8204 for(k=0; b.ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
8205 pSrcEnd = b.apEnd[k];
8206 if( SQLITE_WITHIN(pSrcEnd, pCell, pCell+sz) ){
8207 rc = SQLITE_CORRUPT_BKPT;
8208 goto balance_cleanup;
8210 insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
8211 if( rc!=SQLITE_OK ) goto balance_cleanup;
8212 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8215 /* Now update the actual sibling pages. The order in which they are updated
8216 ** is important, as this code needs to avoid disrupting any page from which
8217 ** cells may still to be read. In practice, this means:
8219 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
8220 ** then it is not safe to update page apNew[iPg] until after
8221 ** the left-hand sibling apNew[iPg-1] has been updated.
8223 ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
8224 ** then it is not safe to update page apNew[iPg] until after
8225 ** the right-hand sibling apNew[iPg+1] has been updated.
8227 ** If neither of the above apply, the page is safe to update.
8229 ** The iPg value in the following loop starts at nNew-1 goes down
8230 ** to 0, then back up to nNew-1 again, thus making two passes over
8231 ** the pages. On the initial downward pass, only condition (1) above
8232 ** needs to be tested because (2) will always be true from the previous
8233 ** step. On the upward pass, both conditions are always true, so the
8234 ** upwards pass simply processes pages that were missed on the downward
8235 ** pass.
8237 for(i=1-nNew; i<nNew; i++){
8238 int iPg = i<0 ? -i : i;
8239 assert( iPg>=0 && iPg<nNew );
8240 if( abDone[iPg] ) continue; /* Skip pages already processed */
8241 if( i>=0 /* On the upwards pass, or... */
8242 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
8244 int iNew;
8245 int iOld;
8246 int nNewCell;
8248 /* Verify condition (1): If cells are moving left, update iPg
8249 ** only after iPg-1 has already been updated. */
8250 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
8252 /* Verify condition (2): If cells are moving right, update iPg
8253 ** only after iPg+1 has already been updated. */
8254 assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
8256 if( iPg==0 ){
8257 iNew = iOld = 0;
8258 nNewCell = cntNew[0];
8259 }else{
8260 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
8261 iNew = cntNew[iPg-1] + !leafData;
8262 nNewCell = cntNew[iPg] - iNew;
8265 rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
8266 if( rc ) goto balance_cleanup;
8267 abDone[iPg]++;
8268 apNew[iPg]->nFree = usableSpace-szNew[iPg];
8269 assert( apNew[iPg]->nOverflow==0 );
8270 assert( apNew[iPg]->nCell==nNewCell );
8274 /* All pages have been processed exactly once */
8275 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
8277 assert( nOld>0 );
8278 assert( nNew>0 );
8280 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
8281 /* The root page of the b-tree now contains no cells. The only sibling
8282 ** page is the right-child of the parent. Copy the contents of the
8283 ** child page into the parent, decreasing the overall height of the
8284 ** b-tree structure by one. This is described as the "balance-shallower"
8285 ** sub-algorithm in some documentation.
8287 ** If this is an auto-vacuum database, the call to copyNodeContent()
8288 ** sets all pointer-map entries corresponding to database image pages
8289 ** for which the pointer is stored within the content being copied.
8291 ** It is critical that the child page be defragmented before being
8292 ** copied into the parent, because if the parent is page 1 then it will
8293 ** by smaller than the child due to the database header, and so all the
8294 ** free space needs to be up front.
8296 assert( nNew==1 || CORRUPT_DB );
8297 rc = defragmentPage(apNew[0], -1);
8298 testcase( rc!=SQLITE_OK );
8299 assert( apNew[0]->nFree ==
8300 (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
8301 - apNew[0]->nCell*2)
8302 || rc!=SQLITE_OK
8304 copyNodeContent(apNew[0], pParent, &rc);
8305 freePage(apNew[0], &rc);
8306 }else if( ISAUTOVACUUM && !leafCorrection ){
8307 /* Fix the pointer map entries associated with the right-child of each
8308 ** sibling page. All other pointer map entries have already been taken
8309 ** care of. */
8310 for(i=0; i<nNew; i++){
8311 u32 key = get4byte(&apNew[i]->aData[8]);
8312 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
8316 assert( pParent->isInit );
8317 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
8318 nOld, nNew, b.nCell));
8320 /* Free any old pages that were not reused as new pages.
8322 for(i=nNew; i<nOld; i++){
8323 freePage(apOld[i], &rc);
8326 #if 0
8327 if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
8328 /* The ptrmapCheckPages() contains assert() statements that verify that
8329 ** all pointer map pages are set correctly. This is helpful while
8330 ** debugging. This is usually disabled because a corrupt database may
8331 ** cause an assert() statement to fail. */
8332 ptrmapCheckPages(apNew, nNew);
8333 ptrmapCheckPages(&pParent, 1);
8335 #endif
8338 ** Cleanup before returning.
8340 balance_cleanup:
8341 sqlite3StackFree(0, b.apCell);
8342 for(i=0; i<nOld; i++){
8343 releasePage(apOld[i]);
8345 for(i=0; i<nNew; i++){
8346 releasePage(apNew[i]);
8349 return rc;
8354 ** This function is called when the root page of a b-tree structure is
8355 ** overfull (has one or more overflow pages).
8357 ** A new child page is allocated and the contents of the current root
8358 ** page, including overflow cells, are copied into the child. The root
8359 ** page is then overwritten to make it an empty page with the right-child
8360 ** pointer pointing to the new page.
8362 ** Before returning, all pointer-map entries corresponding to pages
8363 ** that the new child-page now contains pointers to are updated. The
8364 ** entry corresponding to the new right-child pointer of the root
8365 ** page is also updated.
8367 ** If successful, *ppChild is set to contain a reference to the child
8368 ** page and SQLITE_OK is returned. In this case the caller is required
8369 ** to call releasePage() on *ppChild exactly once. If an error occurs,
8370 ** an error code is returned and *ppChild is set to 0.
8372 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
8373 int rc; /* Return value from subprocedures */
8374 MemPage *pChild = 0; /* Pointer to a new child page */
8375 Pgno pgnoChild = 0; /* Page number of the new child page */
8376 BtShared *pBt = pRoot->pBt; /* The BTree */
8378 assert( pRoot->nOverflow>0 );
8379 assert( sqlite3_mutex_held(pBt->mutex) );
8381 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
8382 ** page that will become the new right-child of pPage. Copy the contents
8383 ** of the node stored on pRoot into the new child page.
8385 rc = sqlite3PagerWrite(pRoot->pDbPage);
8386 if( rc==SQLITE_OK ){
8387 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
8388 copyNodeContent(pRoot, pChild, &rc);
8389 if( ISAUTOVACUUM ){
8390 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
8393 if( rc ){
8394 *ppChild = 0;
8395 releasePage(pChild);
8396 return rc;
8398 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
8399 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
8400 assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
8402 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
8404 /* Copy the overflow cells from pRoot to pChild */
8405 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
8406 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
8407 memcpy(pChild->apOvfl, pRoot->apOvfl,
8408 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
8409 pChild->nOverflow = pRoot->nOverflow;
8411 /* Zero the contents of pRoot. Then install pChild as the right-child. */
8412 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
8413 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
8415 *ppChild = pChild;
8416 return SQLITE_OK;
8420 ** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid
8421 ** on the same B-tree as pCur.
8423 ** This can if a database is corrupt with two or more SQL tables
8424 ** pointing to the same b-tree. If an insert occurs on one SQL table
8425 ** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL
8426 ** table linked to the same b-tree. If the secondary insert causes a
8427 ** rebalance, that can change content out from under the cursor on the
8428 ** first SQL table, violating invariants on the first insert.
8430 static int anotherValidCursor(BtCursor *pCur){
8431 BtCursor *pOther;
8432 for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){
8433 if( pOther!=pCur
8434 && pOther->eState==CURSOR_VALID
8435 && pOther->pPage==pCur->pPage
8437 return SQLITE_CORRUPT_BKPT;
8440 return SQLITE_OK;
8444 ** The page that pCur currently points to has just been modified in
8445 ** some way. This function figures out if this modification means the
8446 ** tree needs to be balanced, and if so calls the appropriate balancing
8447 ** routine. Balancing routines are:
8449 ** balance_quick()
8450 ** balance_deeper()
8451 ** balance_nonroot()
8453 static int balance(BtCursor *pCur){
8454 int rc = SQLITE_OK;
8455 const int nMin = pCur->pBt->usableSize * 2 / 3;
8456 u8 aBalanceQuickSpace[13];
8457 u8 *pFree = 0;
8459 VVA_ONLY( int balance_quick_called = 0 );
8460 VVA_ONLY( int balance_deeper_called = 0 );
8462 do {
8463 int iPage;
8464 MemPage *pPage = pCur->pPage;
8466 if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
8467 if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
8468 break;
8469 }else if( (iPage = pCur->iPage)==0 ){
8470 if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){
8471 /* The root page of the b-tree is overfull. In this case call the
8472 ** balance_deeper() function to create a new child for the root-page
8473 ** and copy the current contents of the root-page to it. The
8474 ** next iteration of the do-loop will balance the child page.
8476 assert( balance_deeper_called==0 );
8477 VVA_ONLY( balance_deeper_called++ );
8478 rc = balance_deeper(pPage, &pCur->apPage[1]);
8479 if( rc==SQLITE_OK ){
8480 pCur->iPage = 1;
8481 pCur->ix = 0;
8482 pCur->aiIdx[0] = 0;
8483 pCur->apPage[0] = pPage;
8484 pCur->pPage = pCur->apPage[1];
8485 assert( pCur->pPage->nOverflow );
8487 }else{
8488 break;
8490 }else{
8491 MemPage * const pParent = pCur->apPage[iPage-1];
8492 int const iIdx = pCur->aiIdx[iPage-1];
8494 rc = sqlite3PagerWrite(pParent->pDbPage);
8495 if( rc==SQLITE_OK && pParent->nFree<0 ){
8496 rc = btreeComputeFreeSpace(pParent);
8498 if( rc==SQLITE_OK ){
8499 #ifndef SQLITE_OMIT_QUICKBALANCE
8500 if( pPage->intKeyLeaf
8501 && pPage->nOverflow==1
8502 && pPage->aiOvfl[0]==pPage->nCell
8503 && pParent->pgno!=1
8504 && pParent->nCell==iIdx
8506 /* Call balance_quick() to create a new sibling of pPage on which
8507 ** to store the overflow cell. balance_quick() inserts a new cell
8508 ** into pParent, which may cause pParent overflow. If this
8509 ** happens, the next iteration of the do-loop will balance pParent
8510 ** use either balance_nonroot() or balance_deeper(). Until this
8511 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
8512 ** buffer.
8514 ** The purpose of the following assert() is to check that only a
8515 ** single call to balance_quick() is made for each call to this
8516 ** function. If this were not verified, a subtle bug involving reuse
8517 ** of the aBalanceQuickSpace[] might sneak in.
8519 assert( balance_quick_called==0 );
8520 VVA_ONLY( balance_quick_called++ );
8521 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
8522 }else
8523 #endif
8525 /* In this case, call balance_nonroot() to redistribute cells
8526 ** between pPage and up to 2 of its sibling pages. This involves
8527 ** modifying the contents of pParent, which may cause pParent to
8528 ** become overfull or underfull. The next iteration of the do-loop
8529 ** will balance the parent page to correct this.
8531 ** If the parent page becomes overfull, the overflow cell or cells
8532 ** are stored in the pSpace buffer allocated immediately below.
8533 ** A subsequent iteration of the do-loop will deal with this by
8534 ** calling balance_nonroot() (balance_deeper() may be called first,
8535 ** but it doesn't deal with overflow cells - just moves them to a
8536 ** different page). Once this subsequent call to balance_nonroot()
8537 ** has completed, it is safe to release the pSpace buffer used by
8538 ** the previous call, as the overflow cell data will have been
8539 ** copied either into the body of a database page or into the new
8540 ** pSpace buffer passed to the latter call to balance_nonroot().
8542 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
8543 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
8544 pCur->hints&BTREE_BULKLOAD);
8545 if( pFree ){
8546 /* If pFree is not NULL, it points to the pSpace buffer used
8547 ** by a previous call to balance_nonroot(). Its contents are
8548 ** now stored either on real database pages or within the
8549 ** new pSpace buffer, so it may be safely freed here. */
8550 sqlite3PageFree(pFree);
8553 /* The pSpace buffer will be freed after the next call to
8554 ** balance_nonroot(), or just before this function returns, whichever
8555 ** comes first. */
8556 pFree = pSpace;
8560 pPage->nOverflow = 0;
8562 /* The next iteration of the do-loop balances the parent page. */
8563 releasePage(pPage);
8564 pCur->iPage--;
8565 assert( pCur->iPage>=0 );
8566 pCur->pPage = pCur->apPage[pCur->iPage];
8568 }while( rc==SQLITE_OK );
8570 if( pFree ){
8571 sqlite3PageFree(pFree);
8573 return rc;
8576 /* Overwrite content from pX into pDest. Only do the write if the
8577 ** content is different from what is already there.
8579 static int btreeOverwriteContent(
8580 MemPage *pPage, /* MemPage on which writing will occur */
8581 u8 *pDest, /* Pointer to the place to start writing */
8582 const BtreePayload *pX, /* Source of data to write */
8583 int iOffset, /* Offset of first byte to write */
8584 int iAmt /* Number of bytes to be written */
8586 int nData = pX->nData - iOffset;
8587 if( nData<=0 ){
8588 /* Overwritting with zeros */
8589 int i;
8590 for(i=0; i<iAmt && pDest[i]==0; i++){}
8591 if( i<iAmt ){
8592 int rc = sqlite3PagerWrite(pPage->pDbPage);
8593 if( rc ) return rc;
8594 memset(pDest + i, 0, iAmt - i);
8596 }else{
8597 if( nData<iAmt ){
8598 /* Mixed read data and zeros at the end. Make a recursive call
8599 ** to write the zeros then fall through to write the real data */
8600 int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
8601 iAmt-nData);
8602 if( rc ) return rc;
8603 iAmt = nData;
8605 if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
8606 int rc = sqlite3PagerWrite(pPage->pDbPage);
8607 if( rc ) return rc;
8608 /* In a corrupt database, it is possible for the source and destination
8609 ** buffers to overlap. This is harmless since the database is already
8610 ** corrupt but it does cause valgrind and ASAN warnings. So use
8611 ** memmove(). */
8612 memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
8615 return SQLITE_OK;
8619 ** Overwrite the cell that cursor pCur is pointing to with fresh content
8620 ** contained in pX.
8622 static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
8623 int iOffset; /* Next byte of pX->pData to write */
8624 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
8625 int rc; /* Return code */
8626 MemPage *pPage = pCur->pPage; /* Page being written */
8627 BtShared *pBt; /* Btree */
8628 Pgno ovflPgno; /* Next overflow page to write */
8629 u32 ovflPageSize; /* Size to write on overflow page */
8631 if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd
8632 || pCur->info.pPayload < pPage->aData + pPage->cellOffset
8634 return SQLITE_CORRUPT_BKPT;
8636 /* Overwrite the local portion first */
8637 rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
8638 0, pCur->info.nLocal);
8639 if( rc ) return rc;
8640 if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
8642 /* Now overwrite the overflow pages */
8643 iOffset = pCur->info.nLocal;
8644 assert( nTotal>=0 );
8645 assert( iOffset>=0 );
8646 ovflPgno = get4byte(pCur->info.pPayload + iOffset);
8647 pBt = pPage->pBt;
8648 ovflPageSize = pBt->usableSize - 4;
8650 rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
8651 if( rc ) return rc;
8652 if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){
8653 rc = SQLITE_CORRUPT_BKPT;
8654 }else{
8655 if( iOffset+ovflPageSize<(u32)nTotal ){
8656 ovflPgno = get4byte(pPage->aData);
8657 }else{
8658 ovflPageSize = nTotal - iOffset;
8660 rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
8661 iOffset, ovflPageSize);
8663 sqlite3PagerUnref(pPage->pDbPage);
8664 if( rc ) return rc;
8665 iOffset += ovflPageSize;
8666 }while( iOffset<nTotal );
8667 return SQLITE_OK;
8672 ** Insert a new record into the BTree. The content of the new record
8673 ** is described by the pX object. The pCur cursor is used only to
8674 ** define what table the record should be inserted into, and is left
8675 ** pointing at a random location.
8677 ** For a table btree (used for rowid tables), only the pX.nKey value of
8678 ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
8679 ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
8680 ** hold the content of the row.
8682 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
8683 ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
8684 ** pX.pData,nData,nZero fields must be zero.
8686 ** If the seekResult parameter is non-zero, then a successful call to
8687 ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
8688 ** been performed. In other words, if seekResult!=0 then the cursor
8689 ** is currently pointing to a cell that will be adjacent to the cell
8690 ** to be inserted. If seekResult<0 then pCur points to a cell that is
8691 ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
8692 ** that is larger than (pKey,nKey).
8694 ** If seekResult==0, that means pCur is pointing at some unknown location.
8695 ** In that case, this routine must seek the cursor to the correct insertion
8696 ** point for (pKey,nKey) before doing the insertion. For index btrees,
8697 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
8698 ** key values and pX->aMem can be used instead of pX->pKey to avoid having
8699 ** to decode the key.
8701 int sqlite3BtreeInsert(
8702 BtCursor *pCur, /* Insert data into the table of this cursor */
8703 const BtreePayload *pX, /* Content of the row to be inserted */
8704 int flags, /* True if this is likely an append */
8705 int seekResult /* Result of prior MovetoUnpacked() call */
8707 int rc;
8708 int loc = seekResult; /* -1: before desired location +1: after */
8709 int szNew = 0;
8710 int idx;
8711 MemPage *pPage;
8712 Btree *p = pCur->pBtree;
8713 BtShared *pBt = p->pBt;
8714 unsigned char *oldCell;
8715 unsigned char *newCell = 0;
8717 assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND|BTREE_PREFORMAT))==flags );
8718 assert( (flags & BTREE_PREFORMAT)==0 || seekResult || pCur->pKeyInfo==0 );
8720 if( pCur->eState==CURSOR_FAULT ){
8721 assert( pCur->skipNext!=SQLITE_OK );
8722 return pCur->skipNext;
8725 assert( cursorOwnsBtShared(pCur) );
8726 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
8727 && pBt->inTransaction==TRANS_WRITE
8728 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
8729 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8731 /* Assert that the caller has been consistent. If this cursor was opened
8732 ** expecting an index b-tree, then the caller should be inserting blob
8733 ** keys with no associated data. If the cursor was opened expecting an
8734 ** intkey table, the caller should be inserting integer keys with a
8735 ** blob of associated data. */
8736 assert( (flags & BTREE_PREFORMAT) || (pX->pKey==0)==(pCur->pKeyInfo==0) );
8738 /* Save the positions of any other cursors open on this table.
8740 ** In some cases, the call to btreeMoveto() below is a no-op. For
8741 ** example, when inserting data into a table with auto-generated integer
8742 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
8743 ** integer key to use. It then calls this function to actually insert the
8744 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
8745 ** that the cursor is already where it needs to be and returns without
8746 ** doing any work. To avoid thwarting these optimizations, it is important
8747 ** not to clear the cursor here.
8749 if( pCur->curFlags & BTCF_Multiple ){
8750 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8751 if( rc ) return rc;
8752 if( loc && pCur->iPage<0 ){
8753 /* This can only happen if the schema is corrupt such that there is more
8754 ** than one table or index with the same root page as used by the cursor.
8755 ** Which can only happen if the SQLITE_NoSchemaError flag was set when
8756 ** the schema was loaded. This cannot be asserted though, as a user might
8757 ** set the flag, load the schema, and then unset the flag. */
8758 return SQLITE_CORRUPT_BKPT;
8762 if( pCur->pKeyInfo==0 ){
8763 assert( pX->pKey==0 );
8764 /* If this is an insert into a table b-tree, invalidate any incrblob
8765 ** cursors open on the row being replaced */
8766 if( p->hasIncrblobCur ){
8767 invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
8770 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8771 ** to a row with the same key as the new entry being inserted.
8773 #ifdef SQLITE_DEBUG
8774 if( flags & BTREE_SAVEPOSITION ){
8775 assert( pCur->curFlags & BTCF_ValidNKey );
8776 assert( pX->nKey==pCur->info.nKey );
8777 assert( loc==0 );
8779 #endif
8781 /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
8782 ** that the cursor is not pointing to a row to be overwritten.
8783 ** So do a complete check.
8785 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
8786 /* The cursor is pointing to the entry that is to be
8787 ** overwritten */
8788 assert( pX->nData>=0 && pX->nZero>=0 );
8789 if( pCur->info.nSize!=0
8790 && pCur->info.nPayload==(u32)pX->nData+pX->nZero
8792 /* New entry is the same size as the old. Do an overwrite */
8793 return btreeOverwriteCell(pCur, pX);
8795 assert( loc==0 );
8796 }else if( loc==0 ){
8797 /* The cursor is *not* pointing to the cell to be overwritten, nor
8798 ** to an adjacent cell. Move the cursor so that it is pointing either
8799 ** to the cell to be overwritten or an adjacent cell.
8801 rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
8802 if( rc ) return rc;
8804 }else{
8805 /* This is an index or a WITHOUT ROWID table */
8807 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8808 ** to a row with the same key as the new entry being inserted.
8810 assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
8812 /* If the cursor is not already pointing either to the cell to be
8813 ** overwritten, or if a new cell is being inserted, if the cursor is
8814 ** not pointing to an immediately adjacent cell, then move the cursor
8815 ** so that it does.
8817 if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
8818 if( pX->nMem ){
8819 UnpackedRecord r;
8820 r.pKeyInfo = pCur->pKeyInfo;
8821 r.aMem = pX->aMem;
8822 r.nField = pX->nMem;
8823 r.default_rc = 0;
8824 r.errCode = 0;
8825 r.r1 = 0;
8826 r.r2 = 0;
8827 r.eqSeen = 0;
8828 rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
8829 }else{
8830 rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
8832 if( rc ) return rc;
8835 /* If the cursor is currently pointing to an entry to be overwritten
8836 ** and the new content is the same as as the old, then use the
8837 ** overwrite optimization.
8839 if( loc==0 ){
8840 getCellInfo(pCur);
8841 if( pCur->info.nKey==pX->nKey ){
8842 BtreePayload x2;
8843 x2.pData = pX->pKey;
8844 x2.nData = pX->nKey;
8845 x2.nZero = 0;
8846 return btreeOverwriteCell(pCur, &x2);
8850 assert( pCur->eState==CURSOR_VALID
8851 || (pCur->eState==CURSOR_INVALID && loc)
8852 || CORRUPT_DB );
8854 pPage = pCur->pPage;
8855 assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) );
8856 assert( pPage->leaf || !pPage->intKey );
8857 if( pPage->nFree<0 ){
8858 if( NEVER(pCur->eState>CURSOR_INVALID) ){
8859 rc = SQLITE_CORRUPT_BKPT;
8860 }else{
8861 rc = btreeComputeFreeSpace(pPage);
8863 if( rc ) return rc;
8866 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
8867 pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
8868 loc==0 ? "overwrite" : "new entry"));
8869 assert( pPage->isInit );
8870 newCell = pBt->pTmpSpace;
8871 assert( newCell!=0 );
8872 if( flags & BTREE_PREFORMAT ){
8873 rc = SQLITE_OK;
8874 szNew = pBt->nPreformatSize;
8875 if( szNew<4 ) szNew = 4;
8876 if( ISAUTOVACUUM && szNew>pPage->maxLocal ){
8877 CellInfo info;
8878 pPage->xParseCell(pPage, newCell, &info);
8879 if( info.nPayload!=info.nLocal ){
8880 Pgno ovfl = get4byte(&newCell[szNew-4]);
8881 ptrmapPut(pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, &rc);
8884 }else{
8885 rc = fillInCell(pPage, newCell, pX, &szNew);
8887 if( rc ) goto end_insert;
8888 assert( szNew==pPage->xCellSize(pPage, newCell) );
8889 assert( szNew <= MX_CELL_SIZE(pBt) );
8890 idx = pCur->ix;
8891 if( loc==0 ){
8892 CellInfo info;
8893 assert( idx<pPage->nCell );
8894 rc = sqlite3PagerWrite(pPage->pDbPage);
8895 if( rc ){
8896 goto end_insert;
8898 oldCell = findCell(pPage, idx);
8899 if( !pPage->leaf ){
8900 memcpy(newCell, oldCell, 4);
8902 BTREE_CLEAR_CELL(rc, pPage, oldCell, info);
8903 testcase( pCur->curFlags & BTCF_ValidOvfl );
8904 invalidateOverflowCache(pCur);
8905 if( info.nSize==szNew && info.nLocal==info.nPayload
8906 && (!ISAUTOVACUUM || szNew<pPage->minLocal)
8908 /* Overwrite the old cell with the new if they are the same size.
8909 ** We could also try to do this if the old cell is smaller, then add
8910 ** the leftover space to the free list. But experiments show that
8911 ** doing that is no faster then skipping this optimization and just
8912 ** calling dropCell() and insertCell().
8914 ** This optimization cannot be used on an autovacuum database if the
8915 ** new entry uses overflow pages, as the insertCell() call below is
8916 ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
8917 assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
8918 if( oldCell < pPage->aData+pPage->hdrOffset+10 ){
8919 return SQLITE_CORRUPT_BKPT;
8921 if( oldCell+szNew > pPage->aDataEnd ){
8922 return SQLITE_CORRUPT_BKPT;
8924 memcpy(oldCell, newCell, szNew);
8925 return SQLITE_OK;
8927 dropCell(pPage, idx, info.nSize, &rc);
8928 if( rc ) goto end_insert;
8929 }else if( loc<0 && pPage->nCell>0 ){
8930 assert( pPage->leaf );
8931 idx = ++pCur->ix;
8932 pCur->curFlags &= ~BTCF_ValidNKey;
8933 }else{
8934 assert( pPage->leaf );
8936 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
8937 assert( pPage->nOverflow==0 || rc==SQLITE_OK );
8938 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
8940 /* If no error has occurred and pPage has an overflow cell, call balance()
8941 ** to redistribute the cells within the tree. Since balance() may move
8942 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
8943 ** variables.
8945 ** Previous versions of SQLite called moveToRoot() to move the cursor
8946 ** back to the root page as balance() used to invalidate the contents
8947 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
8948 ** set the cursor state to "invalid". This makes common insert operations
8949 ** slightly faster.
8951 ** There is a subtle but important optimization here too. When inserting
8952 ** multiple records into an intkey b-tree using a single cursor (as can
8953 ** happen while processing an "INSERT INTO ... SELECT" statement), it
8954 ** is advantageous to leave the cursor pointing to the last entry in
8955 ** the b-tree if possible. If the cursor is left pointing to the last
8956 ** entry in the table, and the next row inserted has an integer key
8957 ** larger than the largest existing key, it is possible to insert the
8958 ** row without seeking the cursor. This can be a big performance boost.
8960 pCur->info.nSize = 0;
8961 if( pPage->nOverflow ){
8962 assert( rc==SQLITE_OK );
8963 pCur->curFlags &= ~(BTCF_ValidNKey);
8964 rc = balance(pCur);
8966 /* Must make sure nOverflow is reset to zero even if the balance()
8967 ** fails. Internal data structure corruption will result otherwise.
8968 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
8969 ** from trying to save the current position of the cursor. */
8970 pCur->pPage->nOverflow = 0;
8971 pCur->eState = CURSOR_INVALID;
8972 if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
8973 btreeReleaseAllCursorPages(pCur);
8974 if( pCur->pKeyInfo ){
8975 assert( pCur->pKey==0 );
8976 pCur->pKey = sqlite3Malloc( pX->nKey );
8977 if( pCur->pKey==0 ){
8978 rc = SQLITE_NOMEM;
8979 }else{
8980 memcpy(pCur->pKey, pX->pKey, pX->nKey);
8983 pCur->eState = CURSOR_REQUIRESEEK;
8984 pCur->nKey = pX->nKey;
8987 assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
8989 end_insert:
8990 return rc;
8994 ** This function is used as part of copying the current row from cursor
8995 ** pSrc into cursor pDest. If the cursors are open on intkey tables, then
8996 ** parameter iKey is used as the rowid value when the record is copied
8997 ** into pDest. Otherwise, the record is copied verbatim.
8999 ** This function does not actually write the new value to cursor pDest.
9000 ** Instead, it creates and populates any required overflow pages and
9001 ** writes the data for the new cell into the BtShared.pTmpSpace buffer
9002 ** for the destination database. The size of the cell, in bytes, is left
9003 ** in BtShared.nPreformatSize. The caller completes the insertion by
9004 ** calling sqlite3BtreeInsert() with the BTREE_PREFORMAT flag specified.
9006 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
9008 int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 iKey){
9009 int rc = SQLITE_OK;
9010 BtShared *pBt = pDest->pBt;
9011 u8 *aOut = pBt->pTmpSpace; /* Pointer to next output buffer */
9012 const u8 *aIn; /* Pointer to next input buffer */
9013 u32 nIn; /* Size of input buffer aIn[] */
9014 u32 nRem; /* Bytes of data still to copy */
9016 getCellInfo(pSrc);
9017 aOut += putVarint32(aOut, pSrc->info.nPayload);
9018 if( pDest->pKeyInfo==0 ) aOut += putVarint(aOut, iKey);
9019 nIn = pSrc->info.nLocal;
9020 aIn = pSrc->info.pPayload;
9021 if( aIn+nIn>pSrc->pPage->aDataEnd ){
9022 return SQLITE_CORRUPT_BKPT;
9024 nRem = pSrc->info.nPayload;
9025 if( nIn==nRem && nIn<pDest->pPage->maxLocal ){
9026 memcpy(aOut, aIn, nIn);
9027 pBt->nPreformatSize = nIn + (aOut - pBt->pTmpSpace);
9028 }else{
9029 Pager *pSrcPager = pSrc->pBt->pPager;
9030 u8 *pPgnoOut = 0;
9031 Pgno ovflIn = 0;
9032 DbPage *pPageIn = 0;
9033 MemPage *pPageOut = 0;
9034 u32 nOut; /* Size of output buffer aOut[] */
9036 nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload);
9037 pBt->nPreformatSize = nOut + (aOut - pBt->pTmpSpace);
9038 if( nOut<pSrc->info.nPayload ){
9039 pPgnoOut = &aOut[nOut];
9040 pBt->nPreformatSize += 4;
9043 if( nRem>nIn ){
9044 if( aIn+nIn+4>pSrc->pPage->aDataEnd ){
9045 return SQLITE_CORRUPT_BKPT;
9047 ovflIn = get4byte(&pSrc->info.pPayload[nIn]);
9050 do {
9051 nRem -= nOut;
9053 assert( nOut>0 );
9054 if( nIn>0 ){
9055 int nCopy = MIN(nOut, nIn);
9056 memcpy(aOut, aIn, nCopy);
9057 nOut -= nCopy;
9058 nIn -= nCopy;
9059 aOut += nCopy;
9060 aIn += nCopy;
9062 if( nOut>0 ){
9063 sqlite3PagerUnref(pPageIn);
9064 pPageIn = 0;
9065 rc = sqlite3PagerGet(pSrcPager, ovflIn, &pPageIn, PAGER_GET_READONLY);
9066 if( rc==SQLITE_OK ){
9067 aIn = (const u8*)sqlite3PagerGetData(pPageIn);
9068 ovflIn = get4byte(aIn);
9069 aIn += 4;
9070 nIn = pSrc->pBt->usableSize - 4;
9073 }while( rc==SQLITE_OK && nOut>0 );
9075 if( rc==SQLITE_OK && nRem>0 ){
9076 Pgno pgnoNew;
9077 MemPage *pNew = 0;
9078 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
9079 put4byte(pPgnoOut, pgnoNew);
9080 if( ISAUTOVACUUM && pPageOut ){
9081 ptrmapPut(pBt, pgnoNew, PTRMAP_OVERFLOW2, pPageOut->pgno, &rc);
9083 releasePage(pPageOut);
9084 pPageOut = pNew;
9085 if( pPageOut ){
9086 pPgnoOut = pPageOut->aData;
9087 put4byte(pPgnoOut, 0);
9088 aOut = &pPgnoOut[4];
9089 nOut = MIN(pBt->usableSize - 4, nRem);
9092 }while( nRem>0 && rc==SQLITE_OK );
9094 releasePage(pPageOut);
9095 sqlite3PagerUnref(pPageIn);
9098 return rc;
9102 ** Delete the entry that the cursor is pointing to.
9104 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
9105 ** the cursor is left pointing at an arbitrary location after the delete.
9106 ** But if that bit is set, then the cursor is left in a state such that
9107 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
9108 ** as it would have been on if the call to BtreeDelete() had been omitted.
9110 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
9111 ** associated with a single table entry and its indexes. Only one of those
9112 ** deletes is considered the "primary" delete. The primary delete occurs
9113 ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
9114 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
9115 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
9116 ** but which might be used by alternative storage engines.
9118 int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
9119 Btree *p = pCur->pBtree;
9120 BtShared *pBt = p->pBt;
9121 int rc; /* Return code */
9122 MemPage *pPage; /* Page to delete cell from */
9123 unsigned char *pCell; /* Pointer to cell to delete */
9124 int iCellIdx; /* Index of cell to delete */
9125 int iCellDepth; /* Depth of node containing pCell */
9126 CellInfo info; /* Size of the cell being deleted */
9127 int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
9128 u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
9130 assert( cursorOwnsBtShared(pCur) );
9131 assert( pBt->inTransaction==TRANS_WRITE );
9132 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9133 assert( pCur->curFlags & BTCF_WriteFlag );
9134 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
9135 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
9136 assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
9137 if( pCur->eState==CURSOR_REQUIRESEEK ){
9138 rc = btreeRestoreCursorPosition(pCur);
9139 assert( rc!=SQLITE_OK || CORRUPT_DB || pCur->eState==CURSOR_VALID );
9140 if( rc || pCur->eState!=CURSOR_VALID ) return rc;
9142 assert( CORRUPT_DB || pCur->eState==CURSOR_VALID );
9144 iCellDepth = pCur->iPage;
9145 iCellIdx = pCur->ix;
9146 pPage = pCur->pPage;
9147 pCell = findCell(pPage, iCellIdx);
9148 if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ) return SQLITE_CORRUPT;
9150 /* If the bPreserve flag is set to true, then the cursor position must
9151 ** be preserved following this delete operation. If the current delete
9152 ** will cause a b-tree rebalance, then this is done by saving the cursor
9153 ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
9154 ** returning.
9156 ** Or, if the current delete will not cause a rebalance, then the cursor
9157 ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
9158 ** before or after the deleted entry. In this case set bSkipnext to true. */
9159 if( bPreserve ){
9160 if( !pPage->leaf
9161 || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
9162 || pPage->nCell==1 /* See dbfuzz001.test for a test case */
9164 /* A b-tree rebalance will be required after deleting this entry.
9165 ** Save the cursor key. */
9166 rc = saveCursorKey(pCur);
9167 if( rc ) return rc;
9168 }else{
9169 bSkipnext = 1;
9173 /* If the page containing the entry to delete is not a leaf page, move
9174 ** the cursor to the largest entry in the tree that is smaller than
9175 ** the entry being deleted. This cell will replace the cell being deleted
9176 ** from the internal node. The 'previous' entry is used for this instead
9177 ** of the 'next' entry, as the previous entry is always a part of the
9178 ** sub-tree headed by the child page of the cell being deleted. This makes
9179 ** balancing the tree following the delete operation easier. */
9180 if( !pPage->leaf ){
9181 rc = sqlite3BtreePrevious(pCur, 0);
9182 assert( rc!=SQLITE_DONE );
9183 if( rc ) return rc;
9186 /* Save the positions of any other cursors open on this table before
9187 ** making any modifications. */
9188 if( pCur->curFlags & BTCF_Multiple ){
9189 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
9190 if( rc ) return rc;
9193 /* If this is a delete operation to remove a row from a table b-tree,
9194 ** invalidate any incrblob cursors open on the row being deleted. */
9195 if( pCur->pKeyInfo==0 && p->hasIncrblobCur ){
9196 invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
9199 /* Make the page containing the entry to be deleted writable. Then free any
9200 ** overflow pages associated with the entry and finally remove the cell
9201 ** itself from within the page. */
9202 rc = sqlite3PagerWrite(pPage->pDbPage);
9203 if( rc ) return rc;
9204 BTREE_CLEAR_CELL(rc, pPage, pCell, info);
9205 dropCell(pPage, iCellIdx, info.nSize, &rc);
9206 if( rc ) return rc;
9208 /* If the cell deleted was not located on a leaf page, then the cursor
9209 ** is currently pointing to the largest entry in the sub-tree headed
9210 ** by the child-page of the cell that was just deleted from an internal
9211 ** node. The cell from the leaf node needs to be moved to the internal
9212 ** node to replace the deleted cell. */
9213 if( !pPage->leaf ){
9214 MemPage *pLeaf = pCur->pPage;
9215 int nCell;
9216 Pgno n;
9217 unsigned char *pTmp;
9219 if( pLeaf->nFree<0 ){
9220 rc = btreeComputeFreeSpace(pLeaf);
9221 if( rc ) return rc;
9223 if( iCellDepth<pCur->iPage-1 ){
9224 n = pCur->apPage[iCellDepth+1]->pgno;
9225 }else{
9226 n = pCur->pPage->pgno;
9228 pCell = findCell(pLeaf, pLeaf->nCell-1);
9229 if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
9230 nCell = pLeaf->xCellSize(pLeaf, pCell);
9231 assert( MX_CELL_SIZE(pBt) >= nCell );
9232 pTmp = pBt->pTmpSpace;
9233 assert( pTmp!=0 );
9234 rc = sqlite3PagerWrite(pLeaf->pDbPage);
9235 if( rc==SQLITE_OK ){
9236 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
9238 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
9239 if( rc ) return rc;
9242 /* Balance the tree. If the entry deleted was located on a leaf page,
9243 ** then the cursor still points to that page. In this case the first
9244 ** call to balance() repairs the tree, and the if(...) condition is
9245 ** never true.
9247 ** Otherwise, if the entry deleted was on an internal node page, then
9248 ** pCur is pointing to the leaf page from which a cell was removed to
9249 ** replace the cell deleted from the internal node. This is slightly
9250 ** tricky as the leaf node may be underfull, and the internal node may
9251 ** be either under or overfull. In this case run the balancing algorithm
9252 ** on the leaf node first. If the balance proceeds far enough up the
9253 ** tree that we can be sure that any problem in the internal node has
9254 ** been corrected, so be it. Otherwise, after balancing the leaf node,
9255 ** walk the cursor up the tree to the internal node and balance it as
9256 ** well. */
9257 rc = balance(pCur);
9258 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
9259 releasePageNotNull(pCur->pPage);
9260 pCur->iPage--;
9261 while( pCur->iPage>iCellDepth ){
9262 releasePage(pCur->apPage[pCur->iPage--]);
9264 pCur->pPage = pCur->apPage[pCur->iPage];
9265 rc = balance(pCur);
9268 if( rc==SQLITE_OK ){
9269 if( bSkipnext ){
9270 assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
9271 assert( pPage==pCur->pPage || CORRUPT_DB );
9272 assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
9273 pCur->eState = CURSOR_SKIPNEXT;
9274 if( iCellIdx>=pPage->nCell ){
9275 pCur->skipNext = -1;
9276 pCur->ix = pPage->nCell-1;
9277 }else{
9278 pCur->skipNext = 1;
9280 }else{
9281 rc = moveToRoot(pCur);
9282 if( bPreserve ){
9283 btreeReleaseAllCursorPages(pCur);
9284 pCur->eState = CURSOR_REQUIRESEEK;
9286 if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
9289 return rc;
9293 ** Create a new BTree table. Write into *piTable the page
9294 ** number for the root page of the new table.
9296 ** The type of type is determined by the flags parameter. Only the
9297 ** following values of flags are currently in use. Other values for
9298 ** flags might not work:
9300 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
9301 ** BTREE_ZERODATA Used for SQL indices
9303 static int btreeCreateTable(Btree *p, Pgno *piTable, int createTabFlags){
9304 BtShared *pBt = p->pBt;
9305 MemPage *pRoot;
9306 Pgno pgnoRoot;
9307 int rc;
9308 int ptfFlags; /* Page-type flage for the root page of new table */
9310 assert( sqlite3BtreeHoldsMutex(p) );
9311 assert( pBt->inTransaction==TRANS_WRITE );
9312 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9314 #ifdef SQLITE_OMIT_AUTOVACUUM
9315 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9316 if( rc ){
9317 return rc;
9319 #else
9320 if( pBt->autoVacuum ){
9321 Pgno pgnoMove; /* Move a page here to make room for the root-page */
9322 MemPage *pPageMove; /* The page to move to. */
9324 /* Creating a new table may probably require moving an existing database
9325 ** to make room for the new tables root page. In case this page turns
9326 ** out to be an overflow page, delete all overflow page-map caches
9327 ** held by open cursors.
9329 invalidateAllOverflowCache(pBt);
9331 /* Read the value of meta[3] from the database to determine where the
9332 ** root page of the new table should go. meta[3] is the largest root-page
9333 ** created so far, so the new root-page is (meta[3]+1).
9335 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
9336 if( pgnoRoot>btreePagecount(pBt) ){
9337 return SQLITE_CORRUPT_BKPT;
9339 pgnoRoot++;
9341 /* The new root-page may not be allocated on a pointer-map page, or the
9342 ** PENDING_BYTE page.
9344 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
9345 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
9346 pgnoRoot++;
9348 assert( pgnoRoot>=3 );
9350 /* Allocate a page. The page that currently resides at pgnoRoot will
9351 ** be moved to the allocated page (unless the allocated page happens
9352 ** to reside at pgnoRoot).
9354 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
9355 if( rc!=SQLITE_OK ){
9356 return rc;
9359 if( pgnoMove!=pgnoRoot ){
9360 /* pgnoRoot is the page that will be used for the root-page of
9361 ** the new table (assuming an error did not occur). But we were
9362 ** allocated pgnoMove. If required (i.e. if it was not allocated
9363 ** by extending the file), the current page at position pgnoMove
9364 ** is already journaled.
9366 u8 eType = 0;
9367 Pgno iPtrPage = 0;
9369 /* Save the positions of any open cursors. This is required in
9370 ** case they are holding a reference to an xFetch reference
9371 ** corresponding to page pgnoRoot. */
9372 rc = saveAllCursors(pBt, 0, 0);
9373 releasePage(pPageMove);
9374 if( rc!=SQLITE_OK ){
9375 return rc;
9378 /* Move the page currently at pgnoRoot to pgnoMove. */
9379 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9380 if( rc!=SQLITE_OK ){
9381 return rc;
9383 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
9384 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
9385 rc = SQLITE_CORRUPT_BKPT;
9387 if( rc!=SQLITE_OK ){
9388 releasePage(pRoot);
9389 return rc;
9391 assert( eType!=PTRMAP_ROOTPAGE );
9392 assert( eType!=PTRMAP_FREEPAGE );
9393 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
9394 releasePage(pRoot);
9396 /* Obtain the page at pgnoRoot */
9397 if( rc!=SQLITE_OK ){
9398 return rc;
9400 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9401 if( rc!=SQLITE_OK ){
9402 return rc;
9404 rc = sqlite3PagerWrite(pRoot->pDbPage);
9405 if( rc!=SQLITE_OK ){
9406 releasePage(pRoot);
9407 return rc;
9409 }else{
9410 pRoot = pPageMove;
9413 /* Update the pointer-map and meta-data with the new root-page number. */
9414 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
9415 if( rc ){
9416 releasePage(pRoot);
9417 return rc;
9420 /* When the new root page was allocated, page 1 was made writable in
9421 ** order either to increase the database filesize, or to decrement the
9422 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
9424 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
9425 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
9426 if( NEVER(rc) ){
9427 releasePage(pRoot);
9428 return rc;
9431 }else{
9432 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9433 if( rc ) return rc;
9435 #endif
9436 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
9437 if( createTabFlags & BTREE_INTKEY ){
9438 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
9439 }else{
9440 ptfFlags = PTF_ZERODATA | PTF_LEAF;
9442 zeroPage(pRoot, ptfFlags);
9443 sqlite3PagerUnref(pRoot->pDbPage);
9444 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
9445 *piTable = pgnoRoot;
9446 return SQLITE_OK;
9448 int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){
9449 int rc;
9450 sqlite3BtreeEnter(p);
9451 rc = btreeCreateTable(p, piTable, flags);
9452 sqlite3BtreeLeave(p);
9453 return rc;
9457 ** Erase the given database page and all its children. Return
9458 ** the page to the freelist.
9460 static int clearDatabasePage(
9461 BtShared *pBt, /* The BTree that contains the table */
9462 Pgno pgno, /* Page number to clear */
9463 int freePageFlag, /* Deallocate page if true */
9464 int *pnChange /* Add number of Cells freed to this counter */
9466 MemPage *pPage;
9467 int rc;
9468 unsigned char *pCell;
9469 int i;
9470 int hdr;
9471 CellInfo info;
9473 assert( sqlite3_mutex_held(pBt->mutex) );
9474 if( pgno>btreePagecount(pBt) ){
9475 return SQLITE_CORRUPT_BKPT;
9477 rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
9478 if( rc ) return rc;
9479 if( pPage->bBusy ){
9480 rc = SQLITE_CORRUPT_BKPT;
9481 goto cleardatabasepage_out;
9483 pPage->bBusy = 1;
9484 hdr = pPage->hdrOffset;
9485 for(i=0; i<pPage->nCell; i++){
9486 pCell = findCell(pPage, i);
9487 if( !pPage->leaf ){
9488 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
9489 if( rc ) goto cleardatabasepage_out;
9491 BTREE_CLEAR_CELL(rc, pPage, pCell, info);
9492 if( rc ) goto cleardatabasepage_out;
9494 if( !pPage->leaf ){
9495 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
9496 if( rc ) goto cleardatabasepage_out;
9498 if( pnChange ){
9499 testcase( !pPage->intKey );
9500 *pnChange += pPage->nCell;
9502 if( freePageFlag ){
9503 freePage(pPage, &rc);
9504 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
9505 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
9508 cleardatabasepage_out:
9509 pPage->bBusy = 0;
9510 releasePage(pPage);
9511 return rc;
9515 ** Delete all information from a single table in the database. iTable is
9516 ** the page number of the root of the table. After this routine returns,
9517 ** the root page is empty, but still exists.
9519 ** This routine will fail with SQLITE_LOCKED if there are any open
9520 ** read cursors on the table. Open write cursors are moved to the
9521 ** root of the table.
9523 ** If pnChange is not NULL, then the integer value pointed to by pnChange
9524 ** is incremented by the number of entries in the table.
9526 int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
9527 int rc;
9528 BtShared *pBt = p->pBt;
9529 sqlite3BtreeEnter(p);
9530 assert( p->inTrans==TRANS_WRITE );
9532 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
9534 if( SQLITE_OK==rc ){
9535 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
9536 ** is the root of a table b-tree - if it is not, the following call is
9537 ** a no-op). */
9538 if( p->hasIncrblobCur ){
9539 invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
9541 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
9543 sqlite3BtreeLeave(p);
9544 return rc;
9548 ** Delete all information from the single table that pCur is open on.
9550 ** This routine only work for pCur on an ephemeral table.
9552 int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
9553 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
9557 ** Erase all information in a table and add the root of the table to
9558 ** the freelist. Except, the root of the principle table (the one on
9559 ** page 1) is never added to the freelist.
9561 ** This routine will fail with SQLITE_LOCKED if there are any open
9562 ** cursors on the table.
9564 ** If AUTOVACUUM is enabled and the page at iTable is not the last
9565 ** root page in the database file, then the last root page
9566 ** in the database file is moved into the slot formerly occupied by
9567 ** iTable and that last slot formerly occupied by the last root page
9568 ** is added to the freelist instead of iTable. In this say, all
9569 ** root pages are kept at the beginning of the database file, which
9570 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
9571 ** page number that used to be the last root page in the file before
9572 ** the move. If no page gets moved, *piMoved is set to 0.
9573 ** The last root page is recorded in meta[3] and the value of
9574 ** meta[3] is updated by this procedure.
9576 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
9577 int rc;
9578 MemPage *pPage = 0;
9579 BtShared *pBt = p->pBt;
9581 assert( sqlite3BtreeHoldsMutex(p) );
9582 assert( p->inTrans==TRANS_WRITE );
9583 assert( iTable>=2 );
9584 if( iTable>btreePagecount(pBt) ){
9585 return SQLITE_CORRUPT_BKPT;
9588 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
9589 if( rc ) return rc;
9590 rc = sqlite3BtreeClearTable(p, iTable, 0);
9591 if( rc ){
9592 releasePage(pPage);
9593 return rc;
9596 *piMoved = 0;
9598 #ifdef SQLITE_OMIT_AUTOVACUUM
9599 freePage(pPage, &rc);
9600 releasePage(pPage);
9601 #else
9602 if( pBt->autoVacuum ){
9603 Pgno maxRootPgno;
9604 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
9606 if( iTable==maxRootPgno ){
9607 /* If the table being dropped is the table with the largest root-page
9608 ** number in the database, put the root page on the free list.
9610 freePage(pPage, &rc);
9611 releasePage(pPage);
9612 if( rc!=SQLITE_OK ){
9613 return rc;
9615 }else{
9616 /* The table being dropped does not have the largest root-page
9617 ** number in the database. So move the page that does into the
9618 ** gap left by the deleted root-page.
9620 MemPage *pMove;
9621 releasePage(pPage);
9622 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9623 if( rc!=SQLITE_OK ){
9624 return rc;
9626 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
9627 releasePage(pMove);
9628 if( rc!=SQLITE_OK ){
9629 return rc;
9631 pMove = 0;
9632 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9633 freePage(pMove, &rc);
9634 releasePage(pMove);
9635 if( rc!=SQLITE_OK ){
9636 return rc;
9638 *piMoved = maxRootPgno;
9641 /* Set the new 'max-root-page' value in the database header. This
9642 ** is the old value less one, less one more if that happens to
9643 ** be a root-page number, less one again if that is the
9644 ** PENDING_BYTE_PAGE.
9646 maxRootPgno--;
9647 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
9648 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
9649 maxRootPgno--;
9651 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
9653 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
9654 }else{
9655 freePage(pPage, &rc);
9656 releasePage(pPage);
9658 #endif
9659 return rc;
9661 int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
9662 int rc;
9663 sqlite3BtreeEnter(p);
9664 rc = btreeDropTable(p, iTable, piMoved);
9665 sqlite3BtreeLeave(p);
9666 return rc;
9671 ** This function may only be called if the b-tree connection already
9672 ** has a read or write transaction open on the database.
9674 ** Read the meta-information out of a database file. Meta[0]
9675 ** is the number of free pages currently in the database. Meta[1]
9676 ** through meta[15] are available for use by higher layers. Meta[0]
9677 ** is read-only, the others are read/write.
9679 ** The schema layer numbers meta values differently. At the schema
9680 ** layer (and the SetCookie and ReadCookie opcodes) the number of
9681 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
9683 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
9684 ** of reading the value out of the header, it instead loads the "DataVersion"
9685 ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
9686 ** database file. It is a number computed by the pager. But its access
9687 ** pattern is the same as header meta values, and so it is convenient to
9688 ** read it from this routine.
9690 void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
9691 BtShared *pBt = p->pBt;
9693 sqlite3BtreeEnter(p);
9694 assert( p->inTrans>TRANS_NONE );
9695 assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) );
9696 assert( pBt->pPage1 );
9697 assert( idx>=0 && idx<=15 );
9699 if( idx==BTREE_DATA_VERSION ){
9700 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iBDataVersion;
9701 }else{
9702 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
9705 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
9706 ** database, mark the database as read-only. */
9707 #ifdef SQLITE_OMIT_AUTOVACUUM
9708 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
9709 pBt->btsFlags |= BTS_READ_ONLY;
9711 #endif
9713 sqlite3BtreeLeave(p);
9717 ** Write meta-information back into the database. Meta[0] is
9718 ** read-only and may not be written.
9720 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
9721 BtShared *pBt = p->pBt;
9722 unsigned char *pP1;
9723 int rc;
9724 assert( idx>=1 && idx<=15 );
9725 sqlite3BtreeEnter(p);
9726 assert( p->inTrans==TRANS_WRITE );
9727 assert( pBt->pPage1!=0 );
9728 pP1 = pBt->pPage1->aData;
9729 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
9730 if( rc==SQLITE_OK ){
9731 put4byte(&pP1[36 + idx*4], iMeta);
9732 #ifndef SQLITE_OMIT_AUTOVACUUM
9733 if( idx==BTREE_INCR_VACUUM ){
9734 assert( pBt->autoVacuum || iMeta==0 );
9735 assert( iMeta==0 || iMeta==1 );
9736 pBt->incrVacuum = (u8)iMeta;
9738 #endif
9740 sqlite3BtreeLeave(p);
9741 return rc;
9745 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
9746 ** number of entries in the b-tree and write the result to *pnEntry.
9748 ** SQLITE_OK is returned if the operation is successfully executed.
9749 ** Otherwise, if an error is encountered (i.e. an IO error or database
9750 ** corruption) an SQLite error code is returned.
9752 int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){
9753 i64 nEntry = 0; /* Value to return in *pnEntry */
9754 int rc; /* Return code */
9756 rc = moveToRoot(pCur);
9757 if( rc==SQLITE_EMPTY ){
9758 *pnEntry = 0;
9759 return SQLITE_OK;
9762 /* Unless an error occurs, the following loop runs one iteration for each
9763 ** page in the B-Tree structure (not including overflow pages).
9765 while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){
9766 int iIdx; /* Index of child node in parent */
9767 MemPage *pPage; /* Current page of the b-tree */
9769 /* If this is a leaf page or the tree is not an int-key tree, then
9770 ** this page contains countable entries. Increment the entry counter
9771 ** accordingly.
9773 pPage = pCur->pPage;
9774 if( pPage->leaf || !pPage->intKey ){
9775 nEntry += pPage->nCell;
9778 /* pPage is a leaf node. This loop navigates the cursor so that it
9779 ** points to the first interior cell that it points to the parent of
9780 ** the next page in the tree that has not yet been visited. The
9781 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
9782 ** of the page, or to the number of cells in the page if the next page
9783 ** to visit is the right-child of its parent.
9785 ** If all pages in the tree have been visited, return SQLITE_OK to the
9786 ** caller.
9788 if( pPage->leaf ){
9789 do {
9790 if( pCur->iPage==0 ){
9791 /* All pages of the b-tree have been visited. Return successfully. */
9792 *pnEntry = nEntry;
9793 return moveToRoot(pCur);
9795 moveToParent(pCur);
9796 }while ( pCur->ix>=pCur->pPage->nCell );
9798 pCur->ix++;
9799 pPage = pCur->pPage;
9802 /* Descend to the child node of the cell that the cursor currently
9803 ** points at. This is the right-child if (iIdx==pPage->nCell).
9805 iIdx = pCur->ix;
9806 if( iIdx==pPage->nCell ){
9807 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
9808 }else{
9809 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
9813 /* An error has occurred. Return an error code. */
9814 return rc;
9818 ** Return the pager associated with a BTree. This routine is used for
9819 ** testing and debugging only.
9821 Pager *sqlite3BtreePager(Btree *p){
9822 return p->pBt->pPager;
9825 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9827 ** Append a message to the error message string.
9829 static void checkAppendMsg(
9830 IntegrityCk *pCheck,
9831 const char *zFormat,
9834 va_list ap;
9835 if( !pCheck->mxErr ) return;
9836 pCheck->mxErr--;
9837 pCheck->nErr++;
9838 va_start(ap, zFormat);
9839 if( pCheck->errMsg.nChar ){
9840 sqlite3_str_append(&pCheck->errMsg, "\n", 1);
9842 if( pCheck->zPfx ){
9843 sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
9845 sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
9846 va_end(ap);
9847 if( pCheck->errMsg.accError==SQLITE_NOMEM ){
9848 pCheck->bOomFault = 1;
9851 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9853 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9856 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
9857 ** corresponds to page iPg is already set.
9859 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9860 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9861 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
9865 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
9867 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9868 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9869 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
9874 ** Add 1 to the reference count for page iPage. If this is the second
9875 ** reference to the page, add an error message to pCheck->zErrMsg.
9876 ** Return 1 if there are 2 or more references to the page and 0 if
9877 ** if this is the first reference to the page.
9879 ** Also check that the page number is in bounds.
9881 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
9882 if( iPage>pCheck->nPage || iPage==0 ){
9883 checkAppendMsg(pCheck, "invalid page number %d", iPage);
9884 return 1;
9886 if( getPageReferenced(pCheck, iPage) ){
9887 checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
9888 return 1;
9890 if( AtomicLoad(&pCheck->db->u1.isInterrupted) ) return 1;
9891 setPageReferenced(pCheck, iPage);
9892 return 0;
9895 #ifndef SQLITE_OMIT_AUTOVACUUM
9897 ** Check that the entry in the pointer-map for page iChild maps to
9898 ** page iParent, pointer type ptrType. If not, append an error message
9899 ** to pCheck.
9901 static void checkPtrmap(
9902 IntegrityCk *pCheck, /* Integrity check context */
9903 Pgno iChild, /* Child page number */
9904 u8 eType, /* Expected pointer map type */
9905 Pgno iParent /* Expected pointer map parent page number */
9907 int rc;
9908 u8 ePtrmapType;
9909 Pgno iPtrmapParent;
9911 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
9912 if( rc!=SQLITE_OK ){
9913 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->bOomFault = 1;
9914 checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
9915 return;
9918 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
9919 checkAppendMsg(pCheck,
9920 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
9921 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
9924 #endif
9927 ** Check the integrity of the freelist or of an overflow page list.
9928 ** Verify that the number of pages on the list is N.
9930 static void checkList(
9931 IntegrityCk *pCheck, /* Integrity checking context */
9932 int isFreeList, /* True for a freelist. False for overflow page list */
9933 Pgno iPage, /* Page number for first page in the list */
9934 u32 N /* Expected number of pages in the list */
9936 int i;
9937 u32 expected = N;
9938 int nErrAtStart = pCheck->nErr;
9939 while( iPage!=0 && pCheck->mxErr ){
9940 DbPage *pOvflPage;
9941 unsigned char *pOvflData;
9942 if( checkRef(pCheck, iPage) ) break;
9943 N--;
9944 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
9945 checkAppendMsg(pCheck, "failed to get page %d", iPage);
9946 break;
9948 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
9949 if( isFreeList ){
9950 u32 n = (u32)get4byte(&pOvflData[4]);
9951 #ifndef SQLITE_OMIT_AUTOVACUUM
9952 if( pCheck->pBt->autoVacuum ){
9953 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
9955 #endif
9956 if( n>pCheck->pBt->usableSize/4-2 ){
9957 checkAppendMsg(pCheck,
9958 "freelist leaf count too big on page %d", iPage);
9959 N--;
9960 }else{
9961 for(i=0; i<(int)n; i++){
9962 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
9963 #ifndef SQLITE_OMIT_AUTOVACUUM
9964 if( pCheck->pBt->autoVacuum ){
9965 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
9967 #endif
9968 checkRef(pCheck, iFreePage);
9970 N -= n;
9973 #ifndef SQLITE_OMIT_AUTOVACUUM
9974 else{
9975 /* If this database supports auto-vacuum and iPage is not the last
9976 ** page in this overflow list, check that the pointer-map entry for
9977 ** the following page matches iPage.
9979 if( pCheck->pBt->autoVacuum && N>0 ){
9980 i = get4byte(pOvflData);
9981 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
9984 #endif
9985 iPage = get4byte(pOvflData);
9986 sqlite3PagerUnref(pOvflPage);
9988 if( N && nErrAtStart==pCheck->nErr ){
9989 checkAppendMsg(pCheck,
9990 "%s is %d but should be %d",
9991 isFreeList ? "size" : "overflow list length",
9992 expected-N, expected);
9995 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9998 ** An implementation of a min-heap.
10000 ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
10001 ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
10002 ** and aHeap[N*2+1].
10004 ** The heap property is this: Every node is less than or equal to both
10005 ** of its daughter nodes. A consequence of the heap property is that the
10006 ** root node aHeap[1] is always the minimum value currently in the heap.
10008 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
10009 ** the heap, preserving the heap property. The btreeHeapPull() routine
10010 ** removes the root element from the heap (the minimum value in the heap)
10011 ** and then moves other nodes around as necessary to preserve the heap
10012 ** property.
10014 ** This heap is used for cell overlap and coverage testing. Each u32
10015 ** entry represents the span of a cell or freeblock on a btree page.
10016 ** The upper 16 bits are the index of the first byte of a range and the
10017 ** lower 16 bits are the index of the last byte of that range.
10019 static void btreeHeapInsert(u32 *aHeap, u32 x){
10020 u32 j, i = ++aHeap[0];
10021 aHeap[i] = x;
10022 while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
10023 x = aHeap[j];
10024 aHeap[j] = aHeap[i];
10025 aHeap[i] = x;
10026 i = j;
10029 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
10030 u32 j, i, x;
10031 if( (x = aHeap[0])==0 ) return 0;
10032 *pOut = aHeap[1];
10033 aHeap[1] = aHeap[x];
10034 aHeap[x] = 0xffffffff;
10035 aHeap[0]--;
10036 i = 1;
10037 while( (j = i*2)<=aHeap[0] ){
10038 if( aHeap[j]>aHeap[j+1] ) j++;
10039 if( aHeap[i]<aHeap[j] ) break;
10040 x = aHeap[i];
10041 aHeap[i] = aHeap[j];
10042 aHeap[j] = x;
10043 i = j;
10045 return 1;
10048 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10050 ** Do various sanity checks on a single page of a tree. Return
10051 ** the tree depth. Root pages return 0. Parents of root pages
10052 ** return 1, and so forth.
10054 ** These checks are done:
10056 ** 1. Make sure that cells and freeblocks do not overlap
10057 ** but combine to completely cover the page.
10058 ** 2. Make sure integer cell keys are in order.
10059 ** 3. Check the integrity of overflow pages.
10060 ** 4. Recursively call checkTreePage on all children.
10061 ** 5. Verify that the depth of all children is the same.
10063 static int checkTreePage(
10064 IntegrityCk *pCheck, /* Context for the sanity check */
10065 Pgno iPage, /* Page number of the page to check */
10066 i64 *piMinKey, /* Write minimum integer primary key here */
10067 i64 maxKey /* Error if integer primary key greater than this */
10069 MemPage *pPage = 0; /* The page being analyzed */
10070 int i; /* Loop counter */
10071 int rc; /* Result code from subroutine call */
10072 int depth = -1, d2; /* Depth of a subtree */
10073 int pgno; /* Page number */
10074 int nFrag; /* Number of fragmented bytes on the page */
10075 int hdr; /* Offset to the page header */
10076 int cellStart; /* Offset to the start of the cell pointer array */
10077 int nCell; /* Number of cells */
10078 int doCoverageCheck = 1; /* True if cell coverage checking should be done */
10079 int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
10080 ** False if IPK must be strictly less than maxKey */
10081 u8 *data; /* Page content */
10082 u8 *pCell; /* Cell content */
10083 u8 *pCellIdx; /* Next element of the cell pointer array */
10084 BtShared *pBt; /* The BtShared object that owns pPage */
10085 u32 pc; /* Address of a cell */
10086 u32 usableSize; /* Usable size of the page */
10087 u32 contentOffset; /* Offset to the start of the cell content area */
10088 u32 *heap = 0; /* Min-heap used for checking cell coverage */
10089 u32 x, prev = 0; /* Next and previous entry on the min-heap */
10090 const char *saved_zPfx = pCheck->zPfx;
10091 int saved_v1 = pCheck->v1;
10092 int saved_v2 = pCheck->v2;
10093 u8 savedIsInit = 0;
10095 /* Check that the page exists
10097 pBt = pCheck->pBt;
10098 usableSize = pBt->usableSize;
10099 if( iPage==0 ) return 0;
10100 if( checkRef(pCheck, iPage) ) return 0;
10101 pCheck->zPfx = "Page %u: ";
10102 pCheck->v1 = iPage;
10103 if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){
10104 checkAppendMsg(pCheck,
10105 "unable to get the page. error code=%d", rc);
10106 goto end_of_check;
10109 /* Clear MemPage.isInit to make sure the corruption detection code in
10110 ** btreeInitPage() is executed. */
10111 savedIsInit = pPage->isInit;
10112 pPage->isInit = 0;
10113 if( (rc = btreeInitPage(pPage))!=0 ){
10114 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
10115 checkAppendMsg(pCheck,
10116 "btreeInitPage() returns error code %d", rc);
10117 goto end_of_check;
10119 if( (rc = btreeComputeFreeSpace(pPage))!=0 ){
10120 assert( rc==SQLITE_CORRUPT );
10121 checkAppendMsg(pCheck, "free space corruption", rc);
10122 goto end_of_check;
10124 data = pPage->aData;
10125 hdr = pPage->hdrOffset;
10127 /* Set up for cell analysis */
10128 pCheck->zPfx = "On tree page %u cell %d: ";
10129 contentOffset = get2byteNotZero(&data[hdr+5]);
10130 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
10132 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
10133 ** number of cells on the page. */
10134 nCell = get2byte(&data[hdr+3]);
10135 assert( pPage->nCell==nCell );
10137 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
10138 ** immediately follows the b-tree page header. */
10139 cellStart = hdr + 12 - 4*pPage->leaf;
10140 assert( pPage->aCellIdx==&data[cellStart] );
10141 pCellIdx = &data[cellStart + 2*(nCell-1)];
10143 if( !pPage->leaf ){
10144 /* Analyze the right-child page of internal pages */
10145 pgno = get4byte(&data[hdr+8]);
10146 #ifndef SQLITE_OMIT_AUTOVACUUM
10147 if( pBt->autoVacuum ){
10148 pCheck->zPfx = "On page %u at right child: ";
10149 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10151 #endif
10152 depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10153 keyCanBeEqual = 0;
10154 }else{
10155 /* For leaf pages, the coverage check will occur in the same loop
10156 ** as the other cell checks, so initialize the heap. */
10157 heap = pCheck->heap;
10158 heap[0] = 0;
10161 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
10162 ** integer offsets to the cell contents. */
10163 for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
10164 CellInfo info;
10166 /* Check cell size */
10167 pCheck->v2 = i;
10168 assert( pCellIdx==&data[cellStart + i*2] );
10169 pc = get2byteAligned(pCellIdx);
10170 pCellIdx -= 2;
10171 if( pc<contentOffset || pc>usableSize-4 ){
10172 checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
10173 pc, contentOffset, usableSize-4);
10174 doCoverageCheck = 0;
10175 continue;
10177 pCell = &data[pc];
10178 pPage->xParseCell(pPage, pCell, &info);
10179 if( pc+info.nSize>usableSize ){
10180 checkAppendMsg(pCheck, "Extends off end of page");
10181 doCoverageCheck = 0;
10182 continue;
10185 /* Check for integer primary key out of range */
10186 if( pPage->intKey ){
10187 if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
10188 checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
10190 maxKey = info.nKey;
10191 keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
10194 /* Check the content overflow list */
10195 if( info.nPayload>info.nLocal ){
10196 u32 nPage; /* Number of pages on the overflow chain */
10197 Pgno pgnoOvfl; /* First page of the overflow chain */
10198 assert( pc + info.nSize - 4 <= usableSize );
10199 nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
10200 pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
10201 #ifndef SQLITE_OMIT_AUTOVACUUM
10202 if( pBt->autoVacuum ){
10203 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
10205 #endif
10206 checkList(pCheck, 0, pgnoOvfl, nPage);
10209 if( !pPage->leaf ){
10210 /* Check sanity of left child page for internal pages */
10211 pgno = get4byte(pCell);
10212 #ifndef SQLITE_OMIT_AUTOVACUUM
10213 if( pBt->autoVacuum ){
10214 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10216 #endif
10217 d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10218 keyCanBeEqual = 0;
10219 if( d2!=depth ){
10220 checkAppendMsg(pCheck, "Child page depth differs");
10221 depth = d2;
10223 }else{
10224 /* Populate the coverage-checking heap for leaf pages */
10225 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
10228 *piMinKey = maxKey;
10230 /* Check for complete coverage of the page
10232 pCheck->zPfx = 0;
10233 if( doCoverageCheck && pCheck->mxErr>0 ){
10234 /* For leaf pages, the min-heap has already been initialized and the
10235 ** cells have already been inserted. But for internal pages, that has
10236 ** not yet been done, so do it now */
10237 if( !pPage->leaf ){
10238 heap = pCheck->heap;
10239 heap[0] = 0;
10240 for(i=nCell-1; i>=0; i--){
10241 u32 size;
10242 pc = get2byteAligned(&data[cellStart+i*2]);
10243 size = pPage->xCellSize(pPage, &data[pc]);
10244 btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
10247 /* Add the freeblocks to the min-heap
10249 ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
10250 ** is the offset of the first freeblock, or zero if there are no
10251 ** freeblocks on the page.
10253 i = get2byte(&data[hdr+1]);
10254 while( i>0 ){
10255 int size, j;
10256 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10257 size = get2byte(&data[i+2]);
10258 assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
10259 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
10260 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
10261 ** big-endian integer which is the offset in the b-tree page of the next
10262 ** freeblock in the chain, or zero if the freeblock is the last on the
10263 ** chain. */
10264 j = get2byte(&data[i]);
10265 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
10266 ** increasing offset. */
10267 assert( j==0 || j>i+size ); /* Enforced by btreeComputeFreeSpace() */
10268 assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10269 i = j;
10271 /* Analyze the min-heap looking for overlap between cells and/or
10272 ** freeblocks, and counting the number of untracked bytes in nFrag.
10274 ** Each min-heap entry is of the form: (start_address<<16)|end_address.
10275 ** There is an implied first entry the covers the page header, the cell
10276 ** pointer index, and the gap between the cell pointer index and the start
10277 ** of cell content.
10279 ** The loop below pulls entries from the min-heap in order and compares
10280 ** the start_address against the previous end_address. If there is an
10281 ** overlap, that means bytes are used multiple times. If there is a gap,
10282 ** that gap is added to the fragmentation count.
10284 nFrag = 0;
10285 prev = contentOffset - 1; /* Implied first min-heap entry */
10286 while( btreeHeapPull(heap,&x) ){
10287 if( (prev&0xffff)>=(x>>16) ){
10288 checkAppendMsg(pCheck,
10289 "Multiple uses for byte %u of page %u", x>>16, iPage);
10290 break;
10291 }else{
10292 nFrag += (x>>16) - (prev&0xffff) - 1;
10293 prev = x;
10296 nFrag += usableSize - (prev&0xffff) - 1;
10297 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
10298 ** is stored in the fifth field of the b-tree page header.
10299 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
10300 ** number of fragmented free bytes within the cell content area.
10302 if( heap[0]==0 && nFrag!=data[hdr+7] ){
10303 checkAppendMsg(pCheck,
10304 "Fragmentation of %d bytes reported as %d on page %u",
10305 nFrag, data[hdr+7], iPage);
10309 end_of_check:
10310 if( !doCoverageCheck ) pPage->isInit = savedIsInit;
10311 releasePage(pPage);
10312 pCheck->zPfx = saved_zPfx;
10313 pCheck->v1 = saved_v1;
10314 pCheck->v2 = saved_v2;
10315 return depth+1;
10317 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10319 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10321 ** This routine does a complete check of the given BTree file. aRoot[] is
10322 ** an array of pages numbers were each page number is the root page of
10323 ** a table. nRoot is the number of entries in aRoot.
10325 ** A read-only or read-write transaction must be opened before calling
10326 ** this function.
10328 ** Write the number of error seen in *pnErr. Except for some memory
10329 ** allocation errors, an error message held in memory obtained from
10330 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
10331 ** returned. If a memory allocation error occurs, NULL is returned.
10333 ** If the first entry in aRoot[] is 0, that indicates that the list of
10334 ** root pages is incomplete. This is a "partial integrity-check". This
10335 ** happens when performing an integrity check on a single table. The
10336 ** zero is skipped, of course. But in addition, the freelist checks
10337 ** and the checks to make sure every page is referenced are also skipped,
10338 ** since obviously it is not possible to know which pages are covered by
10339 ** the unverified btrees. Except, if aRoot[1] is 1, then the freelist
10340 ** checks are still performed.
10342 char *sqlite3BtreeIntegrityCheck(
10343 sqlite3 *db, /* Database connection that is running the check */
10344 Btree *p, /* The btree to be checked */
10345 Pgno *aRoot, /* An array of root pages numbers for individual trees */
10346 int nRoot, /* Number of entries in aRoot[] */
10347 int mxErr, /* Stop reporting errors after this many */
10348 int *pnErr /* Write number of errors seen to this variable */
10350 Pgno i;
10351 IntegrityCk sCheck;
10352 BtShared *pBt = p->pBt;
10353 u64 savedDbFlags = pBt->db->flags;
10354 char zErr[100];
10355 int bPartial = 0; /* True if not checking all btrees */
10356 int bCkFreelist = 1; /* True to scan the freelist */
10357 VVA_ONLY( int nRef );
10358 assert( nRoot>0 );
10360 /* aRoot[0]==0 means this is a partial check */
10361 if( aRoot[0]==0 ){
10362 assert( nRoot>1 );
10363 bPartial = 1;
10364 if( aRoot[1]!=1 ) bCkFreelist = 0;
10367 sqlite3BtreeEnter(p);
10368 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
10369 VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
10370 assert( nRef>=0 );
10371 sCheck.db = db;
10372 sCheck.pBt = pBt;
10373 sCheck.pPager = pBt->pPager;
10374 sCheck.nPage = btreePagecount(sCheck.pBt);
10375 sCheck.mxErr = mxErr;
10376 sCheck.nErr = 0;
10377 sCheck.bOomFault = 0;
10378 sCheck.zPfx = 0;
10379 sCheck.v1 = 0;
10380 sCheck.v2 = 0;
10381 sCheck.aPgRef = 0;
10382 sCheck.heap = 0;
10383 sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
10384 sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
10385 if( sCheck.nPage==0 ){
10386 goto integrity_ck_cleanup;
10389 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
10390 if( !sCheck.aPgRef ){
10391 sCheck.bOomFault = 1;
10392 goto integrity_ck_cleanup;
10394 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
10395 if( sCheck.heap==0 ){
10396 sCheck.bOomFault = 1;
10397 goto integrity_ck_cleanup;
10400 i = PENDING_BYTE_PAGE(pBt);
10401 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
10403 /* Check the integrity of the freelist
10405 if( bCkFreelist ){
10406 sCheck.zPfx = "Main freelist: ";
10407 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
10408 get4byte(&pBt->pPage1->aData[36]));
10409 sCheck.zPfx = 0;
10412 /* Check all the tables.
10414 #ifndef SQLITE_OMIT_AUTOVACUUM
10415 if( !bPartial ){
10416 if( pBt->autoVacuum ){
10417 Pgno mx = 0;
10418 Pgno mxInHdr;
10419 for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
10420 mxInHdr = get4byte(&pBt->pPage1->aData[52]);
10421 if( mx!=mxInHdr ){
10422 checkAppendMsg(&sCheck,
10423 "max rootpage (%d) disagrees with header (%d)",
10424 mx, mxInHdr
10427 }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
10428 checkAppendMsg(&sCheck,
10429 "incremental_vacuum enabled with a max rootpage of zero"
10433 #endif
10434 testcase( pBt->db->flags & SQLITE_CellSizeCk );
10435 pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
10436 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
10437 i64 notUsed;
10438 if( aRoot[i]==0 ) continue;
10439 #ifndef SQLITE_OMIT_AUTOVACUUM
10440 if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){
10441 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
10443 #endif
10444 checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
10446 pBt->db->flags = savedDbFlags;
10448 /* Make sure every page in the file is referenced
10450 if( !bPartial ){
10451 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
10452 #ifdef SQLITE_OMIT_AUTOVACUUM
10453 if( getPageReferenced(&sCheck, i)==0 ){
10454 checkAppendMsg(&sCheck, "Page %d is never used", i);
10456 #else
10457 /* If the database supports auto-vacuum, make sure no tables contain
10458 ** references to pointer-map pages.
10460 if( getPageReferenced(&sCheck, i)==0 &&
10461 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
10462 checkAppendMsg(&sCheck, "Page %d is never used", i);
10464 if( getPageReferenced(&sCheck, i)!=0 &&
10465 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
10466 checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
10468 #endif
10472 /* Clean up and report errors.
10474 integrity_ck_cleanup:
10475 sqlite3PageFree(sCheck.heap);
10476 sqlite3_free(sCheck.aPgRef);
10477 if( sCheck.bOomFault ){
10478 sqlite3_str_reset(&sCheck.errMsg);
10479 sCheck.nErr++;
10481 *pnErr = sCheck.nErr;
10482 if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
10483 /* Make sure this analysis did not leave any unref() pages. */
10484 assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
10485 sqlite3BtreeLeave(p);
10486 return sqlite3StrAccumFinish(&sCheck.errMsg);
10488 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10491 ** Return the full pathname of the underlying database file. Return
10492 ** an empty string if the database is in-memory or a TEMP database.
10494 ** The pager filename is invariant as long as the pager is
10495 ** open so it is safe to access without the BtShared mutex.
10497 const char *sqlite3BtreeGetFilename(Btree *p){
10498 assert( p->pBt->pPager!=0 );
10499 return sqlite3PagerFilename(p->pBt->pPager, 1);
10503 ** Return the pathname of the journal file for this database. The return
10504 ** value of this routine is the same regardless of whether the journal file
10505 ** has been created or not.
10507 ** The pager journal filename is invariant as long as the pager is
10508 ** open so it is safe to access without the BtShared mutex.
10510 const char *sqlite3BtreeGetJournalname(Btree *p){
10511 assert( p->pBt->pPager!=0 );
10512 return sqlite3PagerJournalname(p->pBt->pPager);
10516 ** Return one of SQLITE_TXN_NONE, SQLITE_TXN_READ, or SQLITE_TXN_WRITE
10517 ** to describe the current transaction state of Btree p.
10519 int sqlite3BtreeTxnState(Btree *p){
10520 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
10521 return p ? p->inTrans : 0;
10524 #ifndef SQLITE_OMIT_WAL
10526 ** Run a checkpoint on the Btree passed as the first argument.
10528 ** Return SQLITE_LOCKED if this or any other connection has an open
10529 ** transaction on the shared-cache the argument Btree is connected to.
10531 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
10533 int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
10534 int rc = SQLITE_OK;
10535 if( p ){
10536 BtShared *pBt = p->pBt;
10537 sqlite3BtreeEnter(p);
10538 if( pBt->inTransaction!=TRANS_NONE ){
10539 rc = SQLITE_LOCKED;
10540 }else{
10541 rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
10543 sqlite3BtreeLeave(p);
10545 return rc;
10547 #endif
10550 ** Return true if there is currently a backup running on Btree p.
10552 int sqlite3BtreeIsInBackup(Btree *p){
10553 assert( p );
10554 assert( sqlite3_mutex_held(p->db->mutex) );
10555 return p->nBackup!=0;
10559 ** This function returns a pointer to a blob of memory associated with
10560 ** a single shared-btree. The memory is used by client code for its own
10561 ** purposes (for example, to store a high-level schema associated with
10562 ** the shared-btree). The btree layer manages reference counting issues.
10564 ** The first time this is called on a shared-btree, nBytes bytes of memory
10565 ** are allocated, zeroed, and returned to the caller. For each subsequent
10566 ** call the nBytes parameter is ignored and a pointer to the same blob
10567 ** of memory returned.
10569 ** If the nBytes parameter is 0 and the blob of memory has not yet been
10570 ** allocated, a null pointer is returned. If the blob has already been
10571 ** allocated, it is returned as normal.
10573 ** Just before the shared-btree is closed, the function passed as the
10574 ** xFree argument when the memory allocation was made is invoked on the
10575 ** blob of allocated memory. The xFree function should not call sqlite3_free()
10576 ** on the memory, the btree layer does that.
10578 void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
10579 BtShared *pBt = p->pBt;
10580 sqlite3BtreeEnter(p);
10581 if( !pBt->pSchema && nBytes ){
10582 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
10583 pBt->xFreeSchema = xFree;
10585 sqlite3BtreeLeave(p);
10586 return pBt->pSchema;
10590 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
10591 ** btree as the argument handle holds an exclusive lock on the
10592 ** sqlite_schema table. Otherwise SQLITE_OK.
10594 int sqlite3BtreeSchemaLocked(Btree *p){
10595 int rc;
10596 assert( sqlite3_mutex_held(p->db->mutex) );
10597 sqlite3BtreeEnter(p);
10598 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
10599 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
10600 sqlite3BtreeLeave(p);
10601 return rc;
10605 #ifndef SQLITE_OMIT_SHARED_CACHE
10607 ** Obtain a lock on the table whose root page is iTab. The
10608 ** lock is a write lock if isWritelock is true or a read lock
10609 ** if it is false.
10611 int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
10612 int rc = SQLITE_OK;
10613 assert( p->inTrans!=TRANS_NONE );
10614 if( p->sharable ){
10615 u8 lockType = READ_LOCK + isWriteLock;
10616 assert( READ_LOCK+1==WRITE_LOCK );
10617 assert( isWriteLock==0 || isWriteLock==1 );
10619 sqlite3BtreeEnter(p);
10620 rc = querySharedCacheTableLock(p, iTab, lockType);
10621 if( rc==SQLITE_OK ){
10622 rc = setSharedCacheTableLock(p, iTab, lockType);
10624 sqlite3BtreeLeave(p);
10626 return rc;
10628 #endif
10630 #ifndef SQLITE_OMIT_INCRBLOB
10632 ** Argument pCsr must be a cursor opened for writing on an
10633 ** INTKEY table currently pointing at a valid table entry.
10634 ** This function modifies the data stored as part of that entry.
10636 ** Only the data content may only be modified, it is not possible to
10637 ** change the length of the data stored. If this function is called with
10638 ** parameters that attempt to write past the end of the existing data,
10639 ** no modifications are made and SQLITE_CORRUPT is returned.
10641 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
10642 int rc;
10643 assert( cursorOwnsBtShared(pCsr) );
10644 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
10645 assert( pCsr->curFlags & BTCF_Incrblob );
10647 rc = restoreCursorPosition(pCsr);
10648 if( rc!=SQLITE_OK ){
10649 return rc;
10651 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
10652 if( pCsr->eState!=CURSOR_VALID ){
10653 return SQLITE_ABORT;
10656 /* Save the positions of all other cursors open on this table. This is
10657 ** required in case any of them are holding references to an xFetch
10658 ** version of the b-tree page modified by the accessPayload call below.
10660 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
10661 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
10662 ** saveAllCursors can only return SQLITE_OK.
10664 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
10665 assert( rc==SQLITE_OK );
10667 /* Check some assumptions:
10668 ** (a) the cursor is open for writing,
10669 ** (b) there is a read/write transaction open,
10670 ** (c) the connection holds a write-lock on the table (if required),
10671 ** (d) there are no conflicting read-locks, and
10672 ** (e) the cursor points at a valid row of an intKey table.
10674 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
10675 return SQLITE_READONLY;
10677 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
10678 && pCsr->pBt->inTransaction==TRANS_WRITE );
10679 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
10680 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
10681 assert( pCsr->pPage->intKey );
10683 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
10687 ** Mark this cursor as an incremental blob cursor.
10689 void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
10690 pCur->curFlags |= BTCF_Incrblob;
10691 pCur->pBtree->hasIncrblobCur = 1;
10693 #endif
10696 ** Set both the "read version" (single byte at byte offset 18) and
10697 ** "write version" (single byte at byte offset 19) fields in the database
10698 ** header to iVersion.
10700 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
10701 BtShared *pBt = pBtree->pBt;
10702 int rc; /* Return code */
10704 assert( iVersion==1 || iVersion==2 );
10706 /* If setting the version fields to 1, do not automatically open the
10707 ** WAL connection, even if the version fields are currently set to 2.
10709 pBt->btsFlags &= ~BTS_NO_WAL;
10710 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
10712 rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
10713 if( rc==SQLITE_OK ){
10714 u8 *aData = pBt->pPage1->aData;
10715 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
10716 rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
10717 if( rc==SQLITE_OK ){
10718 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
10719 if( rc==SQLITE_OK ){
10720 aData[18] = (u8)iVersion;
10721 aData[19] = (u8)iVersion;
10727 pBt->btsFlags &= ~BTS_NO_WAL;
10728 return rc;
10732 ** Return true if the cursor has a hint specified. This routine is
10733 ** only used from within assert() statements
10735 int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
10736 return (pCsr->hints & mask)!=0;
10740 ** Return true if the given Btree is read-only.
10742 int sqlite3BtreeIsReadonly(Btree *p){
10743 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
10747 ** Return the size of the header added to each page by this module.
10749 int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
10751 #if !defined(SQLITE_OMIT_SHARED_CACHE)
10753 ** Return true if the Btree passed as the only argument is sharable.
10755 int sqlite3BtreeSharable(Btree *p){
10756 return p->sharable;
10760 ** Return the number of connections to the BtShared object accessed by
10761 ** the Btree handle passed as the only argument. For private caches
10762 ** this is always 1. For shared caches it may be 1 or greater.
10764 int sqlite3BtreeConnectionCount(Btree *p){
10765 testcase( p->sharable );
10766 return p->pBt->nRef;
10768 #endif