In wal mode, if a "BEGIN EXCLUSIVE" command (or any other command that
[sqlite.git] / src / btree.c
blobcb1044155deb6ebbdb96b104e5742995e331275d
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_MASTER.
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
116 ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
117 ** (MemPage*) as an argument. The (MemPage*) must not be NULL.
119 ** If SQLITE_DEBUG is not defined, then this macro is equivalent to
120 ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
121 ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
122 ** with the page number and filename associated with the (MemPage*).
124 #ifdef SQLITE_DEBUG
125 int corruptPageError(int lineno, MemPage *p){
126 char *zMsg;
127 sqlite3BeginBenignMalloc();
128 zMsg = sqlite3_mprintf("database corruption page %d of %s",
129 (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
131 sqlite3EndBenignMalloc();
132 if( zMsg ){
133 sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
135 sqlite3_free(zMsg);
136 return SQLITE_CORRUPT_BKPT;
138 # define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
139 #else
140 # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
141 #endif
143 #ifndef SQLITE_OMIT_SHARED_CACHE
145 #ifdef SQLITE_DEBUG
147 **** This function is only used as part of an assert() statement. ***
149 ** Check to see if pBtree holds the required locks to read or write to the
150 ** table with root page iRoot. Return 1 if it does and 0 if not.
152 ** For example, when writing to a table with root-page iRoot via
153 ** Btree connection pBtree:
155 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
157 ** When writing to an index that resides in a sharable database, the
158 ** caller should have first obtained a lock specifying the root page of
159 ** the corresponding table. This makes things a bit more complicated,
160 ** as this module treats each table as a separate structure. To determine
161 ** the table corresponding to the index being written, this
162 ** function has to search through the database schema.
164 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
165 ** hold a write-lock on the schema table (root page 1). This is also
166 ** acceptable.
168 static int hasSharedCacheTableLock(
169 Btree *pBtree, /* Handle that must hold lock */
170 Pgno iRoot, /* Root page of b-tree */
171 int isIndex, /* True if iRoot is the root of an index b-tree */
172 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
174 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
175 Pgno iTab = 0;
176 BtLock *pLock;
178 /* If this database is not shareable, or if the client is reading
179 ** and has the read-uncommitted flag set, then no lock is required.
180 ** Return true immediately.
182 if( (pBtree->sharable==0)
183 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
185 return 1;
188 /* If the client is reading or writing an index and the schema is
189 ** not loaded, then it is too difficult to actually check to see if
190 ** the correct locks are held. So do not bother - just return true.
191 ** This case does not come up very often anyhow.
193 if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
194 return 1;
197 /* Figure out the root-page that the lock should be held on. For table
198 ** b-trees, this is just the root page of the b-tree being read or
199 ** written. For index b-trees, it is the root page of the associated
200 ** table. */
201 if( isIndex ){
202 HashElem *p;
203 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
204 Index *pIdx = (Index *)sqliteHashData(p);
205 if( pIdx->tnum==(int)iRoot ){
206 if( iTab ){
207 /* Two or more indexes share the same root page. There must
208 ** be imposter tables. So just return true. The assert is not
209 ** useful in that case. */
210 return 1;
212 iTab = pIdx->pTable->tnum;
215 }else{
216 iTab = iRoot;
219 /* Search for the required lock. Either a write-lock on root-page iTab, a
220 ** write-lock on the schema table, or (if the client is reading) a
221 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
222 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
223 if( pLock->pBtree==pBtree
224 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
225 && pLock->eLock>=eLockType
227 return 1;
231 /* Failed to find the required lock. */
232 return 0;
234 #endif /* SQLITE_DEBUG */
236 #ifdef SQLITE_DEBUG
238 **** This function may be used as part of assert() statements only. ****
240 ** Return true if it would be illegal for pBtree to write into the
241 ** table or index rooted at iRoot because other shared connections are
242 ** simultaneously reading that same table or index.
244 ** It is illegal for pBtree to write if some other Btree object that
245 ** shares the same BtShared object is currently reading or writing
246 ** the iRoot table. Except, if the other Btree object has the
247 ** read-uncommitted flag set, then it is OK for the other object to
248 ** have a read cursor.
250 ** For example, before writing to any part of the table or index
251 ** rooted at page iRoot, one should call:
253 ** assert( !hasReadConflicts(pBtree, iRoot) );
255 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
256 BtCursor *p;
257 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
258 if( p->pgnoRoot==iRoot
259 && p->pBtree!=pBtree
260 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
262 return 1;
265 return 0;
267 #endif /* #ifdef SQLITE_DEBUG */
270 ** Query to see if Btree handle p may obtain a lock of type eLock
271 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
272 ** SQLITE_OK if the lock may be obtained (by calling
273 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
275 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
276 BtShared *pBt = p->pBt;
277 BtLock *pIter;
279 assert( sqlite3BtreeHoldsMutex(p) );
280 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
281 assert( p->db!=0 );
282 assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
284 /* If requesting a write-lock, then the Btree must have an open write
285 ** transaction on this file. And, obviously, for this to be so there
286 ** must be an open write transaction on the file itself.
288 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
289 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
291 /* This routine is a no-op if the shared-cache is not enabled */
292 if( !p->sharable ){
293 return SQLITE_OK;
296 /* If some other connection is holding an exclusive lock, the
297 ** requested lock may not be obtained.
299 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
300 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
301 return SQLITE_LOCKED_SHAREDCACHE;
304 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
305 /* The condition (pIter->eLock!=eLock) in the following if(...)
306 ** statement is a simplification of:
308 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
310 ** since we know that if eLock==WRITE_LOCK, then no other connection
311 ** may hold a WRITE_LOCK on any table in this file (since there can
312 ** only be a single writer).
314 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
315 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
316 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
317 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
318 if( eLock==WRITE_LOCK ){
319 assert( p==pBt->pWriter );
320 pBt->btsFlags |= BTS_PENDING;
322 return SQLITE_LOCKED_SHAREDCACHE;
325 return SQLITE_OK;
327 #endif /* !SQLITE_OMIT_SHARED_CACHE */
329 #ifndef SQLITE_OMIT_SHARED_CACHE
331 ** Add a lock on the table with root-page iTable to the shared-btree used
332 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
333 ** WRITE_LOCK.
335 ** This function assumes the following:
337 ** (a) The specified Btree object p is connected to a sharable
338 ** database (one with the BtShared.sharable flag set), and
340 ** (b) No other Btree objects hold a lock that conflicts
341 ** with the requested lock (i.e. querySharedCacheTableLock() has
342 ** already been called and returned SQLITE_OK).
344 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
345 ** is returned if a malloc attempt fails.
347 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
348 BtShared *pBt = p->pBt;
349 BtLock *pLock = 0;
350 BtLock *pIter;
352 assert( sqlite3BtreeHoldsMutex(p) );
353 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
354 assert( p->db!=0 );
356 /* A connection with the read-uncommitted flag set will never try to
357 ** obtain a read-lock using this function. The only read-lock obtained
358 ** by a connection in read-uncommitted mode is on the sqlite_master
359 ** table, and that lock is obtained in BtreeBeginTrans(). */
360 assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
362 /* This function should only be called on a sharable b-tree after it
363 ** has been determined that no other b-tree holds a conflicting lock. */
364 assert( p->sharable );
365 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
367 /* First search the list for an existing lock on this table. */
368 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
369 if( pIter->iTable==iTable && pIter->pBtree==p ){
370 pLock = pIter;
371 break;
375 /* If the above search did not find a BtLock struct associating Btree p
376 ** with table iTable, allocate one and link it into the list.
378 if( !pLock ){
379 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
380 if( !pLock ){
381 return SQLITE_NOMEM_BKPT;
383 pLock->iTable = iTable;
384 pLock->pBtree = p;
385 pLock->pNext = pBt->pLock;
386 pBt->pLock = pLock;
389 /* Set the BtLock.eLock variable to the maximum of the current lock
390 ** and the requested lock. This means if a write-lock was already held
391 ** and a read-lock requested, we don't incorrectly downgrade the lock.
393 assert( WRITE_LOCK>READ_LOCK );
394 if( eLock>pLock->eLock ){
395 pLock->eLock = eLock;
398 return SQLITE_OK;
400 #endif /* !SQLITE_OMIT_SHARED_CACHE */
402 #ifndef SQLITE_OMIT_SHARED_CACHE
404 ** Release all the table locks (locks obtained via calls to
405 ** the setSharedCacheTableLock() procedure) held by Btree object p.
407 ** This function assumes that Btree p has an open read or write
408 ** transaction. If it does not, then the BTS_PENDING flag
409 ** may be incorrectly cleared.
411 static void clearAllSharedCacheTableLocks(Btree *p){
412 BtShared *pBt = p->pBt;
413 BtLock **ppIter = &pBt->pLock;
415 assert( sqlite3BtreeHoldsMutex(p) );
416 assert( p->sharable || 0==*ppIter );
417 assert( p->inTrans>0 );
419 while( *ppIter ){
420 BtLock *pLock = *ppIter;
421 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
422 assert( pLock->pBtree->inTrans>=pLock->eLock );
423 if( pLock->pBtree==p ){
424 *ppIter = pLock->pNext;
425 assert( pLock->iTable!=1 || pLock==&p->lock );
426 if( pLock->iTable!=1 ){
427 sqlite3_free(pLock);
429 }else{
430 ppIter = &pLock->pNext;
434 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
435 if( pBt->pWriter==p ){
436 pBt->pWriter = 0;
437 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
438 }else if( pBt->nTransaction==2 ){
439 /* This function is called when Btree p is concluding its
440 ** transaction. If there currently exists a writer, and p is not
441 ** that writer, then the number of locks held by connections other
442 ** than the writer must be about to drop to zero. In this case
443 ** set the BTS_PENDING flag to 0.
445 ** If there is not currently a writer, then BTS_PENDING must
446 ** be zero already. So this next line is harmless in that case.
448 pBt->btsFlags &= ~BTS_PENDING;
453 ** This function changes all write-locks held by Btree p into read-locks.
455 static void downgradeAllSharedCacheTableLocks(Btree *p){
456 BtShared *pBt = p->pBt;
457 if( pBt->pWriter==p ){
458 BtLock *pLock;
459 pBt->pWriter = 0;
460 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
461 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
462 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
463 pLock->eLock = READ_LOCK;
468 #endif /* SQLITE_OMIT_SHARED_CACHE */
470 static void releasePage(MemPage *pPage); /* Forward reference */
471 static void releasePageOne(MemPage *pPage); /* Forward reference */
472 static void releasePageNotNull(MemPage *pPage); /* Forward reference */
475 ***** This routine is used inside of assert() only ****
477 ** Verify that the cursor holds the mutex on its BtShared
479 #ifdef SQLITE_DEBUG
480 static int cursorHoldsMutex(BtCursor *p){
481 return sqlite3_mutex_held(p->pBt->mutex);
484 /* Verify that the cursor and the BtShared agree about what is the current
485 ** database connetion. This is important in shared-cache mode. If the database
486 ** connection pointers get out-of-sync, it is possible for routines like
487 ** btreeInitPage() to reference an stale connection pointer that references a
488 ** a connection that has already closed. This routine is used inside assert()
489 ** statements only and for the purpose of double-checking that the btree code
490 ** does keep the database connection pointers up-to-date.
492 static int cursorOwnsBtShared(BtCursor *p){
493 assert( cursorHoldsMutex(p) );
494 return (p->pBtree->db==p->pBt->db);
496 #endif
499 ** Invalidate the overflow cache of the cursor passed as the first argument.
500 ** on the shared btree structure pBt.
502 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
505 ** Invalidate the overflow page-list cache for all cursors opened
506 ** on the shared btree structure pBt.
508 static void invalidateAllOverflowCache(BtShared *pBt){
509 BtCursor *p;
510 assert( sqlite3_mutex_held(pBt->mutex) );
511 for(p=pBt->pCursor; p; p=p->pNext){
512 invalidateOverflowCache(p);
516 #ifndef SQLITE_OMIT_INCRBLOB
518 ** This function is called before modifying the contents of a table
519 ** to invalidate any incrblob cursors that are open on the
520 ** row or one of the rows being modified.
522 ** If argument isClearTable is true, then the entire contents of the
523 ** table is about to be deleted. In this case invalidate all incrblob
524 ** cursors open on any row within the table with root-page pgnoRoot.
526 ** Otherwise, if argument isClearTable is false, then the row with
527 ** rowid iRow is being replaced or deleted. In this case invalidate
528 ** only those incrblob cursors open on that specific row.
530 static void invalidateIncrblobCursors(
531 Btree *pBtree, /* The database file to check */
532 Pgno pgnoRoot, /* The table that might be changing */
533 i64 iRow, /* The rowid that might be changing */
534 int isClearTable /* True if all rows are being deleted */
536 BtCursor *p;
537 if( pBtree->hasIncrblobCur==0 ) return;
538 assert( sqlite3BtreeHoldsMutex(pBtree) );
539 pBtree->hasIncrblobCur = 0;
540 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
541 if( (p->curFlags & BTCF_Incrblob)!=0 ){
542 pBtree->hasIncrblobCur = 1;
543 if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
544 p->eState = CURSOR_INVALID;
550 #else
551 /* Stub function when INCRBLOB is omitted */
552 #define invalidateIncrblobCursors(w,x,y,z)
553 #endif /* SQLITE_OMIT_INCRBLOB */
556 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
557 ** when a page that previously contained data becomes a free-list leaf
558 ** page.
560 ** The BtShared.pHasContent bitvec exists to work around an obscure
561 ** bug caused by the interaction of two useful IO optimizations surrounding
562 ** free-list leaf pages:
564 ** 1) When all data is deleted from a page and the page becomes
565 ** a free-list leaf page, the page is not written to the database
566 ** (as free-list leaf pages contain no meaningful data). Sometimes
567 ** such a page is not even journalled (as it will not be modified,
568 ** why bother journalling it?).
570 ** 2) When a free-list leaf page is reused, its content is not read
571 ** from the database or written to the journal file (why should it
572 ** be, if it is not at all meaningful?).
574 ** By themselves, these optimizations work fine and provide a handy
575 ** performance boost to bulk delete or insert operations. However, if
576 ** a page is moved to the free-list and then reused within the same
577 ** transaction, a problem comes up. If the page is not journalled when
578 ** it is moved to the free-list and it is also not journalled when it
579 ** is extracted from the free-list and reused, then the original data
580 ** may be lost. In the event of a rollback, it may not be possible
581 ** to restore the database to its original configuration.
583 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
584 ** moved to become a free-list leaf page, the corresponding bit is
585 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
586 ** optimization 2 above is omitted if the corresponding bit is already
587 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
588 ** at the end of every transaction.
590 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
591 int rc = SQLITE_OK;
592 if( !pBt->pHasContent ){
593 assert( pgno<=pBt->nPage );
594 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
595 if( !pBt->pHasContent ){
596 rc = SQLITE_NOMEM_BKPT;
599 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
600 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
602 return rc;
606 ** Query the BtShared.pHasContent vector.
608 ** This function is called when a free-list leaf page is removed from the
609 ** free-list for reuse. It returns false if it is safe to retrieve the
610 ** page from the pager layer with the 'no-content' flag set. True otherwise.
612 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
613 Bitvec *p = pBt->pHasContent;
614 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
618 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
619 ** invoked at the conclusion of each write-transaction.
621 static void btreeClearHasContent(BtShared *pBt){
622 sqlite3BitvecDestroy(pBt->pHasContent);
623 pBt->pHasContent = 0;
627 ** Release all of the apPage[] pages for a cursor.
629 static void btreeReleaseAllCursorPages(BtCursor *pCur){
630 int i;
631 if( pCur->iPage>=0 ){
632 for(i=0; i<pCur->iPage; i++){
633 releasePageNotNull(pCur->apPage[i]);
635 releasePageNotNull(pCur->pPage);
636 pCur->iPage = -1;
641 ** The cursor passed as the only argument must point to a valid entry
642 ** when this function is called (i.e. have eState==CURSOR_VALID). This
643 ** function saves the current cursor key in variables pCur->nKey and
644 ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
645 ** code otherwise.
647 ** If the cursor is open on an intkey table, then the integer key
648 ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
649 ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
650 ** set to point to a malloced buffer pCur->nKey bytes in size containing
651 ** the key.
653 static int saveCursorKey(BtCursor *pCur){
654 int rc = SQLITE_OK;
655 assert( CURSOR_VALID==pCur->eState );
656 assert( 0==pCur->pKey );
657 assert( cursorHoldsMutex(pCur) );
659 if( pCur->curIntKey ){
660 /* Only the rowid is required for a table btree */
661 pCur->nKey = sqlite3BtreeIntegerKey(pCur);
662 }else{
663 /* For an index btree, save the complete key content */
664 void *pKey;
665 pCur->nKey = sqlite3BtreePayloadSize(pCur);
666 pKey = sqlite3Malloc( pCur->nKey );
667 if( pKey ){
668 rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
669 if( rc==SQLITE_OK ){
670 pCur->pKey = pKey;
671 }else{
672 sqlite3_free(pKey);
674 }else{
675 rc = SQLITE_NOMEM_BKPT;
678 assert( !pCur->curIntKey || !pCur->pKey );
679 return rc;
683 ** Save the current cursor position in the variables BtCursor.nKey
684 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
686 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
687 ** prior to calling this routine.
689 static int saveCursorPosition(BtCursor *pCur){
690 int rc;
692 assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
693 assert( 0==pCur->pKey );
694 assert( cursorHoldsMutex(pCur) );
696 if( pCur->eState==CURSOR_SKIPNEXT ){
697 pCur->eState = CURSOR_VALID;
698 }else{
699 pCur->skipNext = 0;
702 rc = saveCursorKey(pCur);
703 if( rc==SQLITE_OK ){
704 btreeReleaseAllCursorPages(pCur);
705 pCur->eState = CURSOR_REQUIRESEEK;
708 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
709 return rc;
712 /* Forward reference */
713 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
716 ** Save the positions of all cursors (except pExcept) that are open on
717 ** the table with root-page iRoot. "Saving the cursor position" means that
718 ** the location in the btree is remembered in such a way that it can be
719 ** moved back to the same spot after the btree has been modified. This
720 ** routine is called just before cursor pExcept is used to modify the
721 ** table, for example in BtreeDelete() or BtreeInsert().
723 ** If there are two or more cursors on the same btree, then all such
724 ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
725 ** routine enforces that rule. This routine only needs to be called in
726 ** the uncommon case when pExpect has the BTCF_Multiple flag set.
728 ** If pExpect!=NULL and if no other cursors are found on the same root-page,
729 ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
730 ** pointless call to this routine.
732 ** Implementation note: This routine merely checks to see if any cursors
733 ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
734 ** event that cursors are in need to being saved.
736 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
737 BtCursor *p;
738 assert( sqlite3_mutex_held(pBt->mutex) );
739 assert( pExcept==0 || pExcept->pBt==pBt );
740 for(p=pBt->pCursor; p; p=p->pNext){
741 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
743 if( p ) return saveCursorsOnList(p, iRoot, pExcept);
744 if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
745 return SQLITE_OK;
748 /* This helper routine to saveAllCursors does the actual work of saving
749 ** the cursors if and when a cursor is found that actually requires saving.
750 ** The common case is that no cursors need to be saved, so this routine is
751 ** broken out from its caller to avoid unnecessary stack pointer movement.
753 static int SQLITE_NOINLINE saveCursorsOnList(
754 BtCursor *p, /* The first cursor that needs saving */
755 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
756 BtCursor *pExcept /* Do not save this cursor */
759 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
760 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
761 int rc = saveCursorPosition(p);
762 if( SQLITE_OK!=rc ){
763 return rc;
765 }else{
766 testcase( p->iPage>=0 );
767 btreeReleaseAllCursorPages(p);
770 p = p->pNext;
771 }while( p );
772 return SQLITE_OK;
776 ** Clear the current cursor position.
778 void sqlite3BtreeClearCursor(BtCursor *pCur){
779 assert( cursorHoldsMutex(pCur) );
780 sqlite3_free(pCur->pKey);
781 pCur->pKey = 0;
782 pCur->eState = CURSOR_INVALID;
786 ** In this version of BtreeMoveto, pKey is a packed index record
787 ** such as is generated by the OP_MakeRecord opcode. Unpack the
788 ** record and then call BtreeMovetoUnpacked() to do the work.
790 static int btreeMoveto(
791 BtCursor *pCur, /* Cursor open on the btree to be searched */
792 const void *pKey, /* Packed key if the btree is an index */
793 i64 nKey, /* Integer key for tables. Size of pKey for indices */
794 int bias, /* Bias search to the high end */
795 int *pRes /* Write search results here */
797 int rc; /* Status code */
798 UnpackedRecord *pIdxKey; /* Unpacked index key */
800 if( pKey ){
801 assert( nKey==(i64)(int)nKey );
802 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pCur->pKeyInfo);
803 if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
804 sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
805 if( pIdxKey->nField==0 ){
806 rc = SQLITE_CORRUPT_BKPT;
807 goto moveto_done;
809 }else{
810 pIdxKey = 0;
812 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
813 moveto_done:
814 if( pIdxKey ){
815 sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
817 return rc;
821 ** Restore the cursor to the position it was in (or as close to as possible)
822 ** when saveCursorPosition() was called. Note that this call deletes the
823 ** saved position info stored by saveCursorPosition(), so there can be
824 ** at most one effective restoreCursorPosition() call after each
825 ** saveCursorPosition().
827 static int btreeRestoreCursorPosition(BtCursor *pCur){
828 int rc;
829 int skipNext;
830 assert( cursorOwnsBtShared(pCur) );
831 assert( pCur->eState>=CURSOR_REQUIRESEEK );
832 if( pCur->eState==CURSOR_FAULT ){
833 return pCur->skipNext;
835 pCur->eState = CURSOR_INVALID;
836 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
837 if( rc==SQLITE_OK ){
838 sqlite3_free(pCur->pKey);
839 pCur->pKey = 0;
840 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
841 pCur->skipNext |= skipNext;
842 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
843 pCur->eState = CURSOR_SKIPNEXT;
846 return rc;
849 #define restoreCursorPosition(p) \
850 (p->eState>=CURSOR_REQUIRESEEK ? \
851 btreeRestoreCursorPosition(p) : \
852 SQLITE_OK)
855 ** Determine whether or not a cursor has moved from the position where
856 ** it was last placed, or has been invalidated for any other reason.
857 ** Cursors can move when the row they are pointing at is deleted out
858 ** from under them, for example. Cursor might also move if a btree
859 ** is rebalanced.
861 ** Calling this routine with a NULL cursor pointer returns false.
863 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
864 ** back to where it ought to be if this routine returns true.
866 int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
867 assert( EIGHT_BYTE_ALIGNMENT(pCur)
868 || pCur==sqlite3BtreeFakeValidCursor() );
869 assert( offsetof(BtCursor, eState)==0 );
870 assert( sizeof(pCur->eState)==1 );
871 return CURSOR_VALID != *(u8*)pCur;
875 ** Return a pointer to a fake BtCursor object that will always answer
876 ** false to the sqlite3BtreeCursorHasMoved() routine above. The fake
877 ** cursor returned must not be used with any other Btree interface.
879 BtCursor *sqlite3BtreeFakeValidCursor(void){
880 static u8 fakeCursor = CURSOR_VALID;
881 assert( offsetof(BtCursor, eState)==0 );
882 return (BtCursor*)&fakeCursor;
886 ** This routine restores a cursor back to its original position after it
887 ** has been moved by some outside activity (such as a btree rebalance or
888 ** a row having been deleted out from under the cursor).
890 ** On success, the *pDifferentRow parameter is false if the cursor is left
891 ** pointing at exactly the same row. *pDifferntRow is the row the cursor
892 ** was pointing to has been deleted, forcing the cursor to point to some
893 ** nearby row.
895 ** This routine should only be called for a cursor that just returned
896 ** TRUE from sqlite3BtreeCursorHasMoved().
898 int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
899 int rc;
901 assert( pCur!=0 );
902 assert( pCur->eState!=CURSOR_VALID );
903 rc = restoreCursorPosition(pCur);
904 if( rc ){
905 *pDifferentRow = 1;
906 return rc;
908 if( pCur->eState!=CURSOR_VALID ){
909 *pDifferentRow = 1;
910 }else{
911 assert( pCur->skipNext==0 );
912 *pDifferentRow = 0;
914 return SQLITE_OK;
917 #ifdef SQLITE_ENABLE_CURSOR_HINTS
919 ** Provide hints to the cursor. The particular hint given (and the type
920 ** and number of the varargs parameters) is determined by the eHintType
921 ** parameter. See the definitions of the BTREE_HINT_* macros for details.
923 void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
924 /* Used only by system that substitute their own storage engine */
926 #endif
929 ** Provide flag hints to the cursor.
931 void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
932 assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
933 pCur->hints = x;
937 #ifndef SQLITE_OMIT_AUTOVACUUM
939 ** Given a page number of a regular database page, return the page
940 ** number for the pointer-map page that contains the entry for the
941 ** input page number.
943 ** Return 0 (not a valid page) for pgno==1 since there is
944 ** no pointer map associated with page 1. The integrity_check logic
945 ** requires that ptrmapPageno(*,1)!=1.
947 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
948 int nPagesPerMapPage;
949 Pgno iPtrMap, ret;
950 assert( sqlite3_mutex_held(pBt->mutex) );
951 if( pgno<2 ) return 0;
952 nPagesPerMapPage = (pBt->usableSize/5)+1;
953 iPtrMap = (pgno-2)/nPagesPerMapPage;
954 ret = (iPtrMap*nPagesPerMapPage) + 2;
955 if( ret==PENDING_BYTE_PAGE(pBt) ){
956 ret++;
958 return ret;
962 ** Write an entry into the pointer map.
964 ** This routine updates the pointer map entry for page number 'key'
965 ** so that it maps to type 'eType' and parent page number 'pgno'.
967 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
968 ** a no-op. If an error occurs, the appropriate error code is written
969 ** into *pRC.
971 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
972 DbPage *pDbPage; /* The pointer map page */
973 u8 *pPtrmap; /* The pointer map data */
974 Pgno iPtrmap; /* The pointer map page number */
975 int offset; /* Offset in pointer map page */
976 int rc; /* Return code from subfunctions */
978 if( *pRC ) return;
980 assert( sqlite3_mutex_held(pBt->mutex) );
981 /* The master-journal page number must never be used as a pointer map page */
982 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
984 assert( pBt->autoVacuum );
985 if( key==0 ){
986 *pRC = SQLITE_CORRUPT_BKPT;
987 return;
989 iPtrmap = PTRMAP_PAGENO(pBt, key);
990 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
991 if( rc!=SQLITE_OK ){
992 *pRC = rc;
993 return;
995 offset = PTRMAP_PTROFFSET(iPtrmap, key);
996 if( offset<0 ){
997 *pRC = SQLITE_CORRUPT_BKPT;
998 goto ptrmap_exit;
1000 assert( offset <= (int)pBt->usableSize-5 );
1001 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1003 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
1004 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
1005 *pRC= rc = sqlite3PagerWrite(pDbPage);
1006 if( rc==SQLITE_OK ){
1007 pPtrmap[offset] = eType;
1008 put4byte(&pPtrmap[offset+1], parent);
1012 ptrmap_exit:
1013 sqlite3PagerUnref(pDbPage);
1017 ** Read an entry from the pointer map.
1019 ** This routine retrieves the pointer map entry for page 'key', writing
1020 ** the type and parent page number to *pEType and *pPgno respectively.
1021 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
1023 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
1024 DbPage *pDbPage; /* The pointer map page */
1025 int iPtrmap; /* Pointer map page index */
1026 u8 *pPtrmap; /* Pointer map page data */
1027 int offset; /* Offset of entry in pointer map */
1028 int rc;
1030 assert( sqlite3_mutex_held(pBt->mutex) );
1032 iPtrmap = PTRMAP_PAGENO(pBt, key);
1033 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
1034 if( rc!=0 ){
1035 return rc;
1037 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1039 offset = PTRMAP_PTROFFSET(iPtrmap, key);
1040 if( offset<0 ){
1041 sqlite3PagerUnref(pDbPage);
1042 return SQLITE_CORRUPT_BKPT;
1044 assert( offset <= (int)pBt->usableSize-5 );
1045 assert( pEType!=0 );
1046 *pEType = pPtrmap[offset];
1047 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
1049 sqlite3PagerUnref(pDbPage);
1050 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
1051 return SQLITE_OK;
1054 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
1055 #define ptrmapPut(w,x,y,z,rc)
1056 #define ptrmapGet(w,x,y,z) SQLITE_OK
1057 #define ptrmapPutOvflPtr(x, y, rc)
1058 #endif
1061 ** Given a btree page and a cell index (0 means the first cell on
1062 ** the page, 1 means the second cell, and so forth) return a pointer
1063 ** to the cell content.
1065 ** findCellPastPtr() does the same except it skips past the initial
1066 ** 4-byte child pointer found on interior pages, if there is one.
1068 ** This routine works only for pages that do not contain overflow cells.
1070 #define findCell(P,I) \
1071 ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1072 #define findCellPastPtr(P,I) \
1073 ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1077 ** This is common tail processing for btreeParseCellPtr() and
1078 ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
1079 ** on a single B-tree page. Make necessary adjustments to the CellInfo
1080 ** structure.
1082 static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
1083 MemPage *pPage, /* Page containing the cell */
1084 u8 *pCell, /* Pointer to the cell text. */
1085 CellInfo *pInfo /* Fill in this structure */
1087 /* If the payload will not fit completely on the local page, we have
1088 ** to decide how much to store locally and how much to spill onto
1089 ** overflow pages. The strategy is to minimize the amount of unused
1090 ** space on overflow pages while keeping the amount of local storage
1091 ** in between minLocal and maxLocal.
1093 ** Warning: changing the way overflow payload is distributed in any
1094 ** way will result in an incompatible file format.
1096 int minLocal; /* Minimum amount of payload held locally */
1097 int maxLocal; /* Maximum amount of payload held locally */
1098 int surplus; /* Overflow payload available for local storage */
1100 minLocal = pPage->minLocal;
1101 maxLocal = pPage->maxLocal;
1102 surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
1103 testcase( surplus==maxLocal );
1104 testcase( surplus==maxLocal+1 );
1105 if( surplus <= maxLocal ){
1106 pInfo->nLocal = (u16)surplus;
1107 }else{
1108 pInfo->nLocal = (u16)minLocal;
1110 pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
1114 ** The following routines are implementations of the MemPage.xParseCell()
1115 ** method.
1117 ** Parse a cell content block and fill in the CellInfo structure.
1119 ** btreeParseCellPtr() => table btree leaf nodes
1120 ** btreeParseCellNoPayload() => table btree internal nodes
1121 ** btreeParseCellPtrIndex() => index btree nodes
1123 ** There is also a wrapper function btreeParseCell() that works for
1124 ** all MemPage types and that references the cell by index rather than
1125 ** by pointer.
1127 static void btreeParseCellPtrNoPayload(
1128 MemPage *pPage, /* Page containing the cell */
1129 u8 *pCell, /* Pointer to the cell text. */
1130 CellInfo *pInfo /* Fill in this structure */
1132 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1133 assert( pPage->leaf==0 );
1134 assert( pPage->childPtrSize==4 );
1135 #ifndef SQLITE_DEBUG
1136 UNUSED_PARAMETER(pPage);
1137 #endif
1138 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
1139 pInfo->nPayload = 0;
1140 pInfo->nLocal = 0;
1141 pInfo->pPayload = 0;
1142 return;
1144 static void btreeParseCellPtr(
1145 MemPage *pPage, /* Page containing the cell */
1146 u8 *pCell, /* Pointer to the cell text. */
1147 CellInfo *pInfo /* Fill in this structure */
1149 u8 *pIter; /* For scanning through pCell */
1150 u32 nPayload; /* Number of bytes of cell payload */
1151 u64 iKey; /* Extracted Key value */
1153 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1154 assert( pPage->leaf==0 || pPage->leaf==1 );
1155 assert( pPage->intKeyLeaf );
1156 assert( pPage->childPtrSize==0 );
1157 pIter = pCell;
1159 /* The next block of code is equivalent to:
1161 ** pIter += getVarint32(pIter, nPayload);
1163 ** The code is inlined to avoid a function call.
1165 nPayload = *pIter;
1166 if( nPayload>=0x80 ){
1167 u8 *pEnd = &pIter[8];
1168 nPayload &= 0x7f;
1170 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1171 }while( (*pIter)>=0x80 && pIter<pEnd );
1173 pIter++;
1175 /* The next block of code is equivalent to:
1177 ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
1179 ** The code is inlined to avoid a function call.
1181 iKey = *pIter;
1182 if( iKey>=0x80 ){
1183 u8 *pEnd = &pIter[7];
1184 iKey &= 0x7f;
1185 while(1){
1186 iKey = (iKey<<7) | (*++pIter & 0x7f);
1187 if( (*pIter)<0x80 ) break;
1188 if( pIter>=pEnd ){
1189 iKey = (iKey<<8) | *++pIter;
1190 break;
1194 pIter++;
1196 pInfo->nKey = *(i64*)&iKey;
1197 pInfo->nPayload = nPayload;
1198 pInfo->pPayload = pIter;
1199 testcase( nPayload==pPage->maxLocal );
1200 testcase( nPayload==pPage->maxLocal+1 );
1201 if( nPayload<=pPage->maxLocal ){
1202 /* This is the (easy) common case where the entire payload fits
1203 ** on the local page. No overflow is required.
1205 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1206 if( pInfo->nSize<4 ) pInfo->nSize = 4;
1207 pInfo->nLocal = (u16)nPayload;
1208 }else{
1209 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1212 static void btreeParseCellPtrIndex(
1213 MemPage *pPage, /* Page containing the cell */
1214 u8 *pCell, /* Pointer to the cell text. */
1215 CellInfo *pInfo /* Fill in this structure */
1217 u8 *pIter; /* For scanning through pCell */
1218 u32 nPayload; /* Number of bytes of cell payload */
1220 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1221 assert( pPage->leaf==0 || pPage->leaf==1 );
1222 assert( pPage->intKeyLeaf==0 );
1223 pIter = pCell + pPage->childPtrSize;
1224 nPayload = *pIter;
1225 if( nPayload>=0x80 ){
1226 u8 *pEnd = &pIter[8];
1227 nPayload &= 0x7f;
1229 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1230 }while( *(pIter)>=0x80 && pIter<pEnd );
1232 pIter++;
1233 pInfo->nKey = nPayload;
1234 pInfo->nPayload = nPayload;
1235 pInfo->pPayload = pIter;
1236 testcase( nPayload==pPage->maxLocal );
1237 testcase( nPayload==pPage->maxLocal+1 );
1238 if( nPayload<=pPage->maxLocal ){
1239 /* This is the (easy) common case where the entire payload fits
1240 ** on the local page. No overflow is required.
1242 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1243 if( pInfo->nSize<4 ) pInfo->nSize = 4;
1244 pInfo->nLocal = (u16)nPayload;
1245 }else{
1246 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1249 static void btreeParseCell(
1250 MemPage *pPage, /* Page containing the cell */
1251 int iCell, /* The cell index. First cell is 0 */
1252 CellInfo *pInfo /* Fill in this structure */
1254 pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
1258 ** The following routines are implementations of the MemPage.xCellSize
1259 ** method.
1261 ** Compute the total number of bytes that a Cell needs in the cell
1262 ** data area of the btree-page. The return number includes the cell
1263 ** data header and the local payload, but not any overflow page or
1264 ** the space used by the cell pointer.
1266 ** cellSizePtrNoPayload() => table internal nodes
1267 ** cellSizePtr() => all index nodes & table leaf nodes
1269 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
1270 u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
1271 u8 *pEnd; /* End mark for a varint */
1272 u32 nSize; /* Size value to return */
1274 #ifdef SQLITE_DEBUG
1275 /* The value returned by this function should always be the same as
1276 ** the (CellInfo.nSize) value found by doing a full parse of the
1277 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1278 ** this function verifies that this invariant is not violated. */
1279 CellInfo debuginfo;
1280 pPage->xParseCell(pPage, pCell, &debuginfo);
1281 #endif
1283 nSize = *pIter;
1284 if( nSize>=0x80 ){
1285 pEnd = &pIter[8];
1286 nSize &= 0x7f;
1288 nSize = (nSize<<7) | (*++pIter & 0x7f);
1289 }while( *(pIter)>=0x80 && pIter<pEnd );
1291 pIter++;
1292 if( pPage->intKey ){
1293 /* pIter now points at the 64-bit integer key value, a variable length
1294 ** integer. The following block moves pIter to point at the first byte
1295 ** past the end of the key value. */
1296 pEnd = &pIter[9];
1297 while( (*pIter++)&0x80 && pIter<pEnd );
1299 testcase( nSize==pPage->maxLocal );
1300 testcase( nSize==pPage->maxLocal+1 );
1301 if( nSize<=pPage->maxLocal ){
1302 nSize += (u32)(pIter - pCell);
1303 if( nSize<4 ) nSize = 4;
1304 }else{
1305 int minLocal = pPage->minLocal;
1306 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1307 testcase( nSize==pPage->maxLocal );
1308 testcase( nSize==pPage->maxLocal+1 );
1309 if( nSize>pPage->maxLocal ){
1310 nSize = minLocal;
1312 nSize += 4 + (u16)(pIter - pCell);
1314 assert( nSize==debuginfo.nSize || CORRUPT_DB );
1315 return (u16)nSize;
1317 static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
1318 u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
1319 u8 *pEnd; /* End mark for a varint */
1321 #ifdef SQLITE_DEBUG
1322 /* The value returned by this function should always be the same as
1323 ** the (CellInfo.nSize) value found by doing a full parse of the
1324 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1325 ** this function verifies that this invariant is not violated. */
1326 CellInfo debuginfo;
1327 pPage->xParseCell(pPage, pCell, &debuginfo);
1328 #else
1329 UNUSED_PARAMETER(pPage);
1330 #endif
1332 assert( pPage->childPtrSize==4 );
1333 pEnd = pIter + 9;
1334 while( (*pIter++)&0x80 && pIter<pEnd );
1335 assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
1336 return (u16)(pIter - pCell);
1340 #ifdef SQLITE_DEBUG
1341 /* This variation on cellSizePtr() is used inside of assert() statements
1342 ** only. */
1343 static u16 cellSize(MemPage *pPage, int iCell){
1344 return pPage->xCellSize(pPage, findCell(pPage, iCell));
1346 #endif
1348 #ifndef SQLITE_OMIT_AUTOVACUUM
1350 ** If the cell pCell, part of page pPage contains a pointer
1351 ** to an overflow page, insert an entry into the pointer-map
1352 ** for the overflow page.
1354 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
1355 CellInfo info;
1356 if( *pRC ) return;
1357 assert( pCell!=0 );
1358 pPage->xParseCell(pPage, pCell, &info);
1359 if( info.nLocal<info.nPayload ){
1360 Pgno ovfl = get4byte(&pCell[info.nSize-4]);
1361 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
1364 #endif
1368 ** Defragment the page given. This routine reorganizes cells within the
1369 ** page so that there are no free-blocks on the free-block list.
1371 ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
1372 ** present in the page after this routine returns.
1374 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
1375 ** b-tree page so that there are no freeblocks or fragment bytes, all
1376 ** unused bytes are contained in the unallocated space region, and all
1377 ** cells are packed tightly at the end of the page.
1379 static int defragmentPage(MemPage *pPage, int nMaxFrag){
1380 int i; /* Loop counter */
1381 int pc; /* Address of the i-th cell */
1382 int hdr; /* Offset to the page header */
1383 int size; /* Size of a cell */
1384 int usableSize; /* Number of usable bytes on a page */
1385 int cellOffset; /* Offset to the cell pointer array */
1386 int cbrk; /* Offset to the cell content area */
1387 int nCell; /* Number of cells on the page */
1388 unsigned char *data; /* The page data */
1389 unsigned char *temp; /* Temp area for cell content */
1390 unsigned char *src; /* Source of content */
1391 int iCellFirst; /* First allowable cell index */
1392 int iCellLast; /* Last possible cell index */
1394 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1395 assert( pPage->pBt!=0 );
1396 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
1397 assert( pPage->nOverflow==0 );
1398 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1399 temp = 0;
1400 src = data = pPage->aData;
1401 hdr = pPage->hdrOffset;
1402 cellOffset = pPage->cellOffset;
1403 nCell = pPage->nCell;
1404 assert( nCell==get2byte(&data[hdr+3]) );
1405 iCellFirst = cellOffset + 2*nCell;
1406 usableSize = pPage->pBt->usableSize;
1408 /* This block handles pages with two or fewer free blocks and nMaxFrag
1409 ** or fewer fragmented bytes. In this case it is faster to move the
1410 ** two (or one) blocks of cells using memmove() and add the required
1411 ** offsets to each pointer in the cell-pointer array than it is to
1412 ** reconstruct the entire page. */
1413 if( (int)data[hdr+7]<=nMaxFrag ){
1414 int iFree = get2byte(&data[hdr+1]);
1415 if( iFree ){
1416 int iFree2 = get2byte(&data[iFree]);
1418 /* pageFindSlot() has already verified that free blocks are sorted
1419 ** in order of offset within the page, and that no block extends
1420 ** past the end of the page. Provided the two free slots do not
1421 ** overlap, this guarantees that the memmove() calls below will not
1422 ** overwrite the usableSize byte buffer, even if the database page
1423 ** is corrupt. */
1424 assert( iFree2==0 || iFree2>iFree );
1425 assert( iFree+get2byte(&data[iFree+2]) <= usableSize );
1426 assert( iFree2==0 || iFree2+get2byte(&data[iFree2+2]) <= usableSize );
1428 if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
1429 u8 *pEnd = &data[cellOffset + nCell*2];
1430 u8 *pAddr;
1431 int sz2 = 0;
1432 int sz = get2byte(&data[iFree+2]);
1433 int top = get2byte(&data[hdr+5]);
1434 if( top>=iFree ){
1435 return SQLITE_CORRUPT_PAGE(pPage);
1437 if( iFree2 ){
1438 assert( iFree+sz<=iFree2 ); /* Verified by pageFindSlot() */
1439 sz2 = get2byte(&data[iFree2+2]);
1440 assert( iFree+sz+sz2+iFree2-(iFree+sz) <= usableSize );
1441 memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
1442 sz += sz2;
1444 cbrk = top+sz;
1445 assert( cbrk+(iFree-top) <= usableSize );
1446 memmove(&data[cbrk], &data[top], iFree-top);
1447 for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
1448 pc = get2byte(pAddr);
1449 if( pc<iFree ){ put2byte(pAddr, pc+sz); }
1450 else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
1452 goto defragment_out;
1457 cbrk = usableSize;
1458 iCellLast = usableSize - 4;
1459 for(i=0; i<nCell; i++){
1460 u8 *pAddr; /* The i-th cell pointer */
1461 pAddr = &data[cellOffset + i*2];
1462 pc = get2byte(pAddr);
1463 testcase( pc==iCellFirst );
1464 testcase( pc==iCellLast );
1465 /* These conditions have already been verified in btreeInitPage()
1466 ** if PRAGMA cell_size_check=ON.
1468 if( pc<iCellFirst || pc>iCellLast ){
1469 return SQLITE_CORRUPT_PAGE(pPage);
1471 assert( pc>=iCellFirst && pc<=iCellLast );
1472 size = pPage->xCellSize(pPage, &src[pc]);
1473 cbrk -= size;
1474 if( cbrk<iCellFirst || pc+size>usableSize ){
1475 return SQLITE_CORRUPT_PAGE(pPage);
1477 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
1478 testcase( cbrk+size==usableSize );
1479 testcase( pc+size==usableSize );
1480 put2byte(pAddr, cbrk);
1481 if( temp==0 ){
1482 int x;
1483 if( cbrk==pc ) continue;
1484 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
1485 x = get2byte(&data[hdr+5]);
1486 memcpy(&temp[x], &data[x], (cbrk+size) - x);
1487 src = temp;
1489 memcpy(&data[cbrk], &src[pc], size);
1491 data[hdr+7] = 0;
1493 defragment_out:
1494 if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
1495 return SQLITE_CORRUPT_PAGE(pPage);
1497 assert( cbrk>=iCellFirst );
1498 put2byte(&data[hdr+5], cbrk);
1499 data[hdr+1] = 0;
1500 data[hdr+2] = 0;
1501 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
1502 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1503 return SQLITE_OK;
1507 ** Search the free-list on page pPg for space to store a cell nByte bytes in
1508 ** size. If one can be found, return a pointer to the space and remove it
1509 ** from the free-list.
1511 ** If no suitable space can be found on the free-list, return NULL.
1513 ** This function may detect corruption within pPg. If corruption is
1514 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
1516 ** Slots on the free list that are between 1 and 3 bytes larger than nByte
1517 ** will be ignored if adding the extra space to the fragmentation count
1518 ** causes the fragmentation count to exceed 60.
1520 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
1521 const int hdr = pPg->hdrOffset;
1522 u8 * const aData = pPg->aData;
1523 int iAddr = hdr + 1;
1524 int pc = get2byte(&aData[iAddr]);
1525 int x;
1526 int usableSize = pPg->pBt->usableSize;
1527 int size; /* Size of the free slot */
1529 assert( pc>0 );
1530 while( pc<=usableSize-4 ){
1531 /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
1532 ** freeblock form a big-endian integer which is the size of the freeblock
1533 ** in bytes, including the 4-byte header. */
1534 size = get2byte(&aData[pc+2]);
1535 if( (x = size - nByte)>=0 ){
1536 testcase( x==4 );
1537 testcase( x==3 );
1538 if( size+pc > usableSize ){
1539 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1540 return 0;
1541 }else if( x<4 ){
1542 /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
1543 ** number of bytes in fragments may not exceed 60. */
1544 if( aData[hdr+7]>57 ) return 0;
1546 /* Remove the slot from the free-list. Update the number of
1547 ** fragmented bytes within the page. */
1548 memcpy(&aData[iAddr], &aData[pc], 2);
1549 aData[hdr+7] += (u8)x;
1550 }else{
1551 /* The slot remains on the free-list. Reduce its size to account
1552 ** for the portion used by the new allocation. */
1553 put2byte(&aData[pc+2], x);
1555 return &aData[pc + x];
1557 iAddr = pc;
1558 pc = get2byte(&aData[pc]);
1559 if( pc<iAddr+size ) break;
1561 if( pc ){
1562 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1565 return 0;
1569 ** Allocate nByte bytes of space from within the B-Tree page passed
1570 ** as the first argument. Write into *pIdx the index into pPage->aData[]
1571 ** of the first byte of allocated space. Return either SQLITE_OK or
1572 ** an error code (usually SQLITE_CORRUPT).
1574 ** The caller guarantees that there is sufficient space to make the
1575 ** allocation. This routine might need to defragment in order to bring
1576 ** all the space together, however. This routine will avoid using
1577 ** the first two bytes past the cell pointer area since presumably this
1578 ** allocation is being made in order to insert a new cell, so we will
1579 ** also end up needing a new cell pointer.
1581 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
1582 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1583 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
1584 int top; /* First byte of cell content area */
1585 int rc = SQLITE_OK; /* Integer return code */
1586 int gap; /* First byte of gap between cell pointers and cell content */
1588 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1589 assert( pPage->pBt );
1590 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1591 assert( nByte>=0 ); /* Minimum cell size is 4 */
1592 assert( pPage->nFree>=nByte );
1593 assert( pPage->nOverflow==0 );
1594 assert( nByte < (int)(pPage->pBt->usableSize-8) );
1596 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1597 gap = pPage->cellOffset + 2*pPage->nCell;
1598 assert( gap<=65536 );
1599 /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
1600 ** and the reserved space is zero (the usual value for reserved space)
1601 ** then the cell content offset of an empty page wants to be 65536.
1602 ** However, that integer is too large to be stored in a 2-byte unsigned
1603 ** integer, so a value of 0 is used in its place. */
1604 top = get2byte(&data[hdr+5]);
1605 assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
1606 if( gap>top ){
1607 if( top==0 && pPage->pBt->usableSize==65536 ){
1608 top = 65536;
1609 }else{
1610 return SQLITE_CORRUPT_PAGE(pPage);
1614 /* If there is enough space between gap and top for one more cell pointer
1615 ** array entry offset, and if the freelist is not empty, then search the
1616 ** freelist looking for a free slot big enough to satisfy the request.
1618 testcase( gap+2==top );
1619 testcase( gap+1==top );
1620 testcase( gap==top );
1621 if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
1622 u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
1623 if( pSpace ){
1624 assert( pSpace>=data && (pSpace - data)<65536 );
1625 *pIdx = (int)(pSpace - data);
1626 return SQLITE_OK;
1627 }else if( rc ){
1628 return rc;
1632 /* The request could not be fulfilled using a freelist slot. Check
1633 ** to see if defragmentation is necessary.
1635 testcase( gap+2+nByte==top );
1636 if( gap+2+nByte>top ){
1637 assert( pPage->nCell>0 || CORRUPT_DB );
1638 rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
1639 if( rc ) return rc;
1640 top = get2byteNotZero(&data[hdr+5]);
1641 assert( gap+2+nByte<=top );
1645 /* Allocate memory from the gap in between the cell pointer array
1646 ** and the cell content area. The btreeInitPage() call has already
1647 ** validated the freelist. Given that the freelist is valid, there
1648 ** is no way that the allocation can extend off the end of the page.
1649 ** The assert() below verifies the previous sentence.
1651 top -= nByte;
1652 put2byte(&data[hdr+5], top);
1653 assert( top+nByte <= (int)pPage->pBt->usableSize );
1654 *pIdx = top;
1655 return SQLITE_OK;
1659 ** Return a section of the pPage->aData to the freelist.
1660 ** The first byte of the new free block is pPage->aData[iStart]
1661 ** and the size of the block is iSize bytes.
1663 ** Adjacent freeblocks are coalesced.
1665 ** Note that even though the freeblock list was checked by btreeInitPage(),
1666 ** that routine will not detect overlap between cells or freeblocks. Nor
1667 ** does it detect cells or freeblocks that encrouch into the reserved bytes
1668 ** at the end of the page. So do additional corruption checks inside this
1669 ** routine and return SQLITE_CORRUPT if any problems are found.
1671 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
1672 u16 iPtr; /* Address of ptr to next freeblock */
1673 u16 iFreeBlk; /* Address of the next freeblock */
1674 u8 hdr; /* Page header size. 0 or 100 */
1675 u8 nFrag = 0; /* Reduction in fragmentation */
1676 u16 iOrigSize = iSize; /* Original value of iSize */
1677 u16 x; /* Offset to cell content area */
1678 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
1679 unsigned char *data = pPage->aData; /* Page content */
1681 assert( pPage->pBt!=0 );
1682 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1683 assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
1684 assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
1685 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1686 assert( iSize>=4 ); /* Minimum cell size is 4 */
1687 assert( iStart<=pPage->pBt->usableSize-4 );
1689 /* The list of freeblocks must be in ascending order. Find the
1690 ** spot on the list where iStart should be inserted.
1692 hdr = pPage->hdrOffset;
1693 iPtr = hdr + 1;
1694 if( data[iPtr+1]==0 && data[iPtr]==0 ){
1695 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
1696 }else{
1697 while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
1698 if( iFreeBlk<iPtr+4 ){
1699 if( iFreeBlk==0 ) break;
1700 return SQLITE_CORRUPT_PAGE(pPage);
1702 iPtr = iFreeBlk;
1704 if( iFreeBlk>pPage->pBt->usableSize-4 ){
1705 return SQLITE_CORRUPT_PAGE(pPage);
1707 assert( iFreeBlk>iPtr || iFreeBlk==0 );
1709 /* At this point:
1710 ** iFreeBlk: First freeblock after iStart, or zero if none
1711 ** iPtr: The address of a pointer to iFreeBlk
1713 ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
1715 if( iFreeBlk && iEnd+3>=iFreeBlk ){
1716 nFrag = iFreeBlk - iEnd;
1717 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
1718 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
1719 if( iEnd > pPage->pBt->usableSize ){
1720 return SQLITE_CORRUPT_PAGE(pPage);
1722 iSize = iEnd - iStart;
1723 iFreeBlk = get2byte(&data[iFreeBlk]);
1726 /* If iPtr is another freeblock (that is, if iPtr is not the freelist
1727 ** pointer in the page header) then check to see if iStart should be
1728 ** coalesced onto the end of iPtr.
1730 if( iPtr>hdr+1 ){
1731 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
1732 if( iPtrEnd+3>=iStart ){
1733 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
1734 nFrag += iStart - iPtrEnd;
1735 iSize = iEnd - iPtr;
1736 iStart = iPtr;
1739 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
1740 data[hdr+7] -= nFrag;
1742 x = get2byte(&data[hdr+5]);
1743 if( iStart<=x ){
1744 /* The new freeblock is at the beginning of the cell content area,
1745 ** so just extend the cell content area rather than create another
1746 ** freelist entry */
1747 if( iStart<x || iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
1748 put2byte(&data[hdr+1], iFreeBlk);
1749 put2byte(&data[hdr+5], iEnd);
1750 }else{
1751 /* Insert the new freeblock into the freelist */
1752 put2byte(&data[iPtr], iStart);
1754 if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
1755 /* Overwrite deleted information with zeros when the secure_delete
1756 ** option is enabled */
1757 memset(&data[iStart], 0, iSize);
1759 put2byte(&data[iStart], iFreeBlk);
1760 put2byte(&data[iStart+2], iSize);
1761 pPage->nFree += iOrigSize;
1762 return SQLITE_OK;
1766 ** Decode the flags byte (the first byte of the header) for a page
1767 ** and initialize fields of the MemPage structure accordingly.
1769 ** Only the following combinations are supported. Anything different
1770 ** indicates a corrupt database files:
1772 ** PTF_ZERODATA
1773 ** PTF_ZERODATA | PTF_LEAF
1774 ** PTF_LEAFDATA | PTF_INTKEY
1775 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
1777 static int decodeFlags(MemPage *pPage, int flagByte){
1778 BtShared *pBt; /* A copy of pPage->pBt */
1780 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
1781 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1782 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
1783 flagByte &= ~PTF_LEAF;
1784 pPage->childPtrSize = 4-4*pPage->leaf;
1785 pPage->xCellSize = cellSizePtr;
1786 pBt = pPage->pBt;
1787 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
1788 /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
1789 ** interior table b-tree page. */
1790 assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
1791 /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
1792 ** leaf table b-tree page. */
1793 assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
1794 pPage->intKey = 1;
1795 if( pPage->leaf ){
1796 pPage->intKeyLeaf = 1;
1797 pPage->xParseCell = btreeParseCellPtr;
1798 }else{
1799 pPage->intKeyLeaf = 0;
1800 pPage->xCellSize = cellSizePtrNoPayload;
1801 pPage->xParseCell = btreeParseCellPtrNoPayload;
1803 pPage->maxLocal = pBt->maxLeaf;
1804 pPage->minLocal = pBt->minLeaf;
1805 }else if( flagByte==PTF_ZERODATA ){
1806 /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
1807 ** interior index b-tree page. */
1808 assert( (PTF_ZERODATA)==2 );
1809 /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
1810 ** leaf index b-tree page. */
1811 assert( (PTF_ZERODATA|PTF_LEAF)==10 );
1812 pPage->intKey = 0;
1813 pPage->intKeyLeaf = 0;
1814 pPage->xParseCell = btreeParseCellPtrIndex;
1815 pPage->maxLocal = pBt->maxLocal;
1816 pPage->minLocal = pBt->minLocal;
1817 }else{
1818 /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
1819 ** an error. */
1820 return SQLITE_CORRUPT_PAGE(pPage);
1822 pPage->max1bytePayload = pBt->max1bytePayload;
1823 return SQLITE_OK;
1827 ** Initialize the auxiliary information for a disk block.
1829 ** Return SQLITE_OK on success. If we see that the page does
1830 ** not contain a well-formed database page, then return
1831 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1832 ** guarantee that the page is well-formed. It only shows that
1833 ** we failed to detect any corruption.
1835 static int btreeInitPage(MemPage *pPage){
1836 int pc; /* Address of a freeblock within pPage->aData[] */
1837 u8 hdr; /* Offset to beginning of page header */
1838 u8 *data; /* Equal to pPage->aData */
1839 BtShared *pBt; /* The main btree structure */
1840 int usableSize; /* Amount of usable space on each page */
1841 u16 cellOffset; /* Offset from start of page to first cell pointer */
1842 int nFree; /* Number of unused bytes on the page */
1843 int top; /* First byte of the cell content area */
1844 int iCellFirst; /* First allowable cell or freeblock offset */
1845 int iCellLast; /* Last possible cell or freeblock offset */
1847 assert( pPage->pBt!=0 );
1848 assert( pPage->pBt->db!=0 );
1849 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1850 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
1851 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1852 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
1853 assert( pPage->isInit==0 );
1855 pBt = pPage->pBt;
1856 hdr = pPage->hdrOffset;
1857 data = pPage->aData;
1858 /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
1859 ** the b-tree page type. */
1860 if( decodeFlags(pPage, data[hdr]) ){
1861 return SQLITE_CORRUPT_PAGE(pPage);
1863 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
1864 pPage->maskPage = (u16)(pBt->pageSize - 1);
1865 pPage->nOverflow = 0;
1866 usableSize = pBt->usableSize;
1867 pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
1868 pPage->aDataEnd = &data[usableSize];
1869 pPage->aCellIdx = &data[cellOffset];
1870 pPage->aDataOfst = &data[pPage->childPtrSize];
1871 /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
1872 ** the start of the cell content area. A zero value for this integer is
1873 ** interpreted as 65536. */
1874 top = get2byteNotZero(&data[hdr+5]);
1875 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
1876 ** number of cells on the page. */
1877 pPage->nCell = get2byte(&data[hdr+3]);
1878 if( pPage->nCell>MX_CELL(pBt) ){
1879 /* To many cells for a single page. The page must be corrupt */
1880 return SQLITE_CORRUPT_PAGE(pPage);
1882 testcase( pPage->nCell==MX_CELL(pBt) );
1883 /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
1884 ** possible for a root page of a table that contains no rows) then the
1885 ** offset to the cell content area will equal the page size minus the
1886 ** bytes of reserved space. */
1887 assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
1889 /* A malformed database page might cause us to read past the end
1890 ** of page when parsing a cell.
1892 ** The following block of code checks early to see if a cell extends
1893 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
1894 ** returned if it does.
1896 iCellFirst = cellOffset + 2*pPage->nCell;
1897 iCellLast = usableSize - 4;
1898 if( pBt->db->flags & SQLITE_CellSizeCk ){
1899 int i; /* Index into the cell pointer array */
1900 int sz; /* Size of a cell */
1902 if( !pPage->leaf ) iCellLast--;
1903 for(i=0; i<pPage->nCell; i++){
1904 pc = get2byteAligned(&data[cellOffset+i*2]);
1905 testcase( pc==iCellFirst );
1906 testcase( pc==iCellLast );
1907 if( pc<iCellFirst || pc>iCellLast ){
1908 return SQLITE_CORRUPT_PAGE(pPage);
1910 sz = pPage->xCellSize(pPage, &data[pc]);
1911 testcase( pc+sz==usableSize );
1912 if( pc+sz>usableSize ){
1913 return SQLITE_CORRUPT_PAGE(pPage);
1916 if( !pPage->leaf ) iCellLast++;
1919 /* Compute the total free space on the page
1920 ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
1921 ** start of the first freeblock on the page, or is zero if there are no
1922 ** freeblocks. */
1923 pc = get2byte(&data[hdr+1]);
1924 nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
1925 if( pc>0 ){
1926 u32 next, size;
1927 if( pc<iCellFirst ){
1928 /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
1929 ** always be at least one cell before the first freeblock.
1931 return SQLITE_CORRUPT_PAGE(pPage);
1933 while( 1 ){
1934 if( pc>iCellLast ){
1935 /* Freeblock off the end of the page */
1936 return SQLITE_CORRUPT_PAGE(pPage);
1938 next = get2byte(&data[pc]);
1939 size = get2byte(&data[pc+2]);
1940 nFree = nFree + size;
1941 if( next<=pc+size+3 ) break;
1942 pc = next;
1944 if( next>0 ){
1945 /* Freeblock not in ascending order */
1946 return SQLITE_CORRUPT_PAGE(pPage);
1948 if( pc+size>(unsigned int)usableSize ){
1949 /* Last freeblock extends past page end */
1950 return SQLITE_CORRUPT_PAGE(pPage);
1954 /* At this point, nFree contains the sum of the offset to the start
1955 ** of the cell-content area plus the number of free bytes within
1956 ** the cell-content area. If this is greater than the usable-size
1957 ** of the page, then the page must be corrupted. This check also
1958 ** serves to verify that the offset to the start of the cell-content
1959 ** area, according to the page header, lies within the page.
1961 if( nFree>usableSize ){
1962 return SQLITE_CORRUPT_PAGE(pPage);
1964 pPage->nFree = (u16)(nFree - iCellFirst);
1965 pPage->isInit = 1;
1966 return SQLITE_OK;
1970 ** Set up a raw page so that it looks like a database page holding
1971 ** no entries.
1973 static void zeroPage(MemPage *pPage, int flags){
1974 unsigned char *data = pPage->aData;
1975 BtShared *pBt = pPage->pBt;
1976 u8 hdr = pPage->hdrOffset;
1977 u16 first;
1979 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
1980 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1981 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
1982 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1983 assert( sqlite3_mutex_held(pBt->mutex) );
1984 if( pBt->btsFlags & BTS_FAST_SECURE ){
1985 memset(&data[hdr], 0, pBt->usableSize - hdr);
1987 data[hdr] = (char)flags;
1988 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
1989 memset(&data[hdr+1], 0, 4);
1990 data[hdr+7] = 0;
1991 put2byte(&data[hdr+5], pBt->usableSize);
1992 pPage->nFree = (u16)(pBt->usableSize - first);
1993 decodeFlags(pPage, flags);
1994 pPage->cellOffset = first;
1995 pPage->aDataEnd = &data[pBt->usableSize];
1996 pPage->aCellIdx = &data[first];
1997 pPage->aDataOfst = &data[pPage->childPtrSize];
1998 pPage->nOverflow = 0;
1999 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2000 pPage->maskPage = (u16)(pBt->pageSize - 1);
2001 pPage->nCell = 0;
2002 pPage->isInit = 1;
2007 ** Convert a DbPage obtained from the pager into a MemPage used by
2008 ** the btree layer.
2010 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
2011 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2012 if( pgno!=pPage->pgno ){
2013 pPage->aData = sqlite3PagerGetData(pDbPage);
2014 pPage->pDbPage = pDbPage;
2015 pPage->pBt = pBt;
2016 pPage->pgno = pgno;
2017 pPage->hdrOffset = pgno==1 ? 100 : 0;
2019 assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
2020 return pPage;
2024 ** Get a page from the pager. Initialize the MemPage.pBt and
2025 ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
2027 ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
2028 ** about the content of the page at this time. So do not go to the disk
2029 ** to fetch the content. Just fill in the content with zeros for now.
2030 ** If in the future we call sqlite3PagerWrite() on this page, that
2031 ** means we have started to be concerned about content and the disk
2032 ** read should occur at that point.
2034 static int btreeGetPage(
2035 BtShared *pBt, /* The btree */
2036 Pgno pgno, /* Number of the page to fetch */
2037 MemPage **ppPage, /* Return the page in this parameter */
2038 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2040 int rc;
2041 DbPage *pDbPage;
2043 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
2044 assert( sqlite3_mutex_held(pBt->mutex) );
2045 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
2046 if( rc ) return rc;
2047 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
2048 return SQLITE_OK;
2052 ** Retrieve a page from the pager cache. If the requested page is not
2053 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
2054 ** MemPage.aData elements if needed.
2056 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
2057 DbPage *pDbPage;
2058 assert( sqlite3_mutex_held(pBt->mutex) );
2059 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
2060 if( pDbPage ){
2061 return btreePageFromDbPage(pDbPage, pgno, pBt);
2063 return 0;
2067 ** Return the size of the database file in pages. If there is any kind of
2068 ** error, return ((unsigned int)-1).
2070 static Pgno btreePagecount(BtShared *pBt){
2071 return pBt->nPage;
2073 u32 sqlite3BtreeLastPage(Btree *p){
2074 assert( sqlite3BtreeHoldsMutex(p) );
2075 assert( ((p->pBt->nPage)&0x80000000)==0 );
2076 return btreePagecount(p->pBt);
2080 ** Get a page from the pager and initialize it.
2082 ** If pCur!=0 then the page is being fetched as part of a moveToChild()
2083 ** call. Do additional sanity checking on the page in this case.
2084 ** And if the fetch fails, this routine must decrement pCur->iPage.
2086 ** The page is fetched as read-write unless pCur is not NULL and is
2087 ** a read-only cursor.
2089 ** If an error occurs, then *ppPage is undefined. It
2090 ** may remain unchanged, or it may be set to an invalid value.
2092 static int getAndInitPage(
2093 BtShared *pBt, /* The database file */
2094 Pgno pgno, /* Number of the page to get */
2095 MemPage **ppPage, /* Write the page pointer here */
2096 BtCursor *pCur, /* Cursor to receive the page, or NULL */
2097 int bReadOnly /* True for a read-only page */
2099 int rc;
2100 DbPage *pDbPage;
2101 assert( sqlite3_mutex_held(pBt->mutex) );
2102 assert( pCur==0 || ppPage==&pCur->pPage );
2103 assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
2104 assert( pCur==0 || pCur->iPage>0 );
2106 if( pgno>btreePagecount(pBt) ){
2107 rc = SQLITE_CORRUPT_BKPT;
2108 goto getAndInitPage_error;
2110 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
2111 if( rc ){
2112 goto getAndInitPage_error;
2114 *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2115 if( (*ppPage)->isInit==0 ){
2116 btreePageFromDbPage(pDbPage, pgno, pBt);
2117 rc = btreeInitPage(*ppPage);
2118 if( rc!=SQLITE_OK ){
2119 releasePage(*ppPage);
2120 goto getAndInitPage_error;
2123 assert( (*ppPage)->pgno==pgno );
2124 assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
2126 /* If obtaining a child page for a cursor, we must verify that the page is
2127 ** compatible with the root page. */
2128 if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
2129 rc = SQLITE_CORRUPT_PGNO(pgno);
2130 releasePage(*ppPage);
2131 goto getAndInitPage_error;
2133 return SQLITE_OK;
2135 getAndInitPage_error:
2136 if( pCur ){
2137 pCur->iPage--;
2138 pCur->pPage = pCur->apPage[pCur->iPage];
2140 testcase( pgno==0 );
2141 assert( pgno!=0 || rc==SQLITE_CORRUPT );
2142 return rc;
2146 ** Release a MemPage. This should be called once for each prior
2147 ** call to btreeGetPage.
2149 ** Page1 is a special case and must be released using releasePageOne().
2151 static void releasePageNotNull(MemPage *pPage){
2152 assert( pPage->aData );
2153 assert( pPage->pBt );
2154 assert( pPage->pDbPage!=0 );
2155 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2156 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2157 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2158 sqlite3PagerUnrefNotNull(pPage->pDbPage);
2160 static void releasePage(MemPage *pPage){
2161 if( pPage ) releasePageNotNull(pPage);
2163 static void releasePageOne(MemPage *pPage){
2164 assert( pPage!=0 );
2165 assert( pPage->aData );
2166 assert( pPage->pBt );
2167 assert( pPage->pDbPage!=0 );
2168 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2169 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2170 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2171 sqlite3PagerUnrefPageOne(pPage->pDbPage);
2175 ** Get an unused page.
2177 ** This works just like btreeGetPage() with the addition:
2179 ** * If the page is already in use for some other purpose, immediately
2180 ** release it and return an SQLITE_CURRUPT error.
2181 ** * Make sure the isInit flag is clear
2183 static int btreeGetUnusedPage(
2184 BtShared *pBt, /* The btree */
2185 Pgno pgno, /* Number of the page to fetch */
2186 MemPage **ppPage, /* Return the page in this parameter */
2187 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2189 int rc = btreeGetPage(pBt, pgno, ppPage, flags);
2190 if( rc==SQLITE_OK ){
2191 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
2192 releasePage(*ppPage);
2193 *ppPage = 0;
2194 return SQLITE_CORRUPT_BKPT;
2196 (*ppPage)->isInit = 0;
2197 }else{
2198 *ppPage = 0;
2200 return rc;
2205 ** During a rollback, when the pager reloads information into the cache
2206 ** so that the cache is restored to its original state at the start of
2207 ** the transaction, for each page restored this routine is called.
2209 ** This routine needs to reset the extra data section at the end of the
2210 ** page to agree with the restored data.
2212 static void pageReinit(DbPage *pData){
2213 MemPage *pPage;
2214 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
2215 assert( sqlite3PagerPageRefcount(pData)>0 );
2216 if( pPage->isInit ){
2217 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2218 pPage->isInit = 0;
2219 if( sqlite3PagerPageRefcount(pData)>1 ){
2220 /* pPage might not be a btree page; it might be an overflow page
2221 ** or ptrmap page or a free page. In those cases, the following
2222 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
2223 ** But no harm is done by this. And it is very important that
2224 ** btreeInitPage() be called on every btree page so we make
2225 ** the call for every page that comes in for re-initing. */
2226 btreeInitPage(pPage);
2232 ** Invoke the busy handler for a btree.
2234 static int btreeInvokeBusyHandler(void *pArg){
2235 BtShared *pBt = (BtShared*)pArg;
2236 assert( pBt->db );
2237 assert( sqlite3_mutex_held(pBt->db->mutex) );
2238 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler,
2239 sqlite3PagerFile(pBt->pPager));
2243 ** Open a database file.
2245 ** zFilename is the name of the database file. If zFilename is NULL
2246 ** then an ephemeral database is created. The ephemeral database might
2247 ** be exclusively in memory, or it might use a disk-based memory cache.
2248 ** Either way, the ephemeral database will be automatically deleted
2249 ** when sqlite3BtreeClose() is called.
2251 ** If zFilename is ":memory:" then an in-memory database is created
2252 ** that is automatically destroyed when it is closed.
2254 ** The "flags" parameter is a bitmask that might contain bits like
2255 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
2257 ** If the database is already opened in the same database connection
2258 ** and we are in shared cache mode, then the open will fail with an
2259 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
2260 ** objects in the same database connection since doing so will lead
2261 ** to problems with locking.
2263 int sqlite3BtreeOpen(
2264 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
2265 const char *zFilename, /* Name of the file containing the BTree database */
2266 sqlite3 *db, /* Associated database handle */
2267 Btree **ppBtree, /* Pointer to new Btree object written here */
2268 int flags, /* Options */
2269 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
2271 BtShared *pBt = 0; /* Shared part of btree structure */
2272 Btree *p; /* Handle to return */
2273 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
2274 int rc = SQLITE_OK; /* Result code from this function */
2275 u8 nReserve; /* Byte of unused space on each page */
2276 unsigned char zDbHeader[100]; /* Database header content */
2278 /* True if opening an ephemeral, temporary database */
2279 const int isTempDb = zFilename==0 || zFilename[0]==0;
2281 /* Set the variable isMemdb to true for an in-memory database, or
2282 ** false for a file-based database.
2284 #ifdef SQLITE_OMIT_MEMORYDB
2285 const int isMemdb = 0;
2286 #else
2287 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
2288 || (isTempDb && sqlite3TempInMemory(db))
2289 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
2290 #endif
2292 assert( db!=0 );
2293 assert( pVfs!=0 );
2294 assert( sqlite3_mutex_held(db->mutex) );
2295 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
2297 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
2298 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
2300 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
2301 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
2303 if( isMemdb ){
2304 flags |= BTREE_MEMORY;
2306 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
2307 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
2309 p = sqlite3MallocZero(sizeof(Btree));
2310 if( !p ){
2311 return SQLITE_NOMEM_BKPT;
2313 p->inTrans = TRANS_NONE;
2314 p->db = db;
2315 #ifndef SQLITE_OMIT_SHARED_CACHE
2316 p->lock.pBtree = p;
2317 p->lock.iTable = 1;
2318 #endif
2320 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2322 ** If this Btree is a candidate for shared cache, try to find an
2323 ** existing BtShared object that we can share with
2325 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
2326 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
2327 int nFilename = sqlite3Strlen30(zFilename)+1;
2328 int nFullPathname = pVfs->mxPathname+1;
2329 char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
2330 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2332 p->sharable = 1;
2333 if( !zFullPathname ){
2334 sqlite3_free(p);
2335 return SQLITE_NOMEM_BKPT;
2337 if( isMemdb ){
2338 memcpy(zFullPathname, zFilename, nFilename);
2339 }else{
2340 rc = sqlite3OsFullPathname(pVfs, zFilename,
2341 nFullPathname, zFullPathname);
2342 if( rc ){
2343 sqlite3_free(zFullPathname);
2344 sqlite3_free(p);
2345 return rc;
2348 #if SQLITE_THREADSAFE
2349 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
2350 sqlite3_mutex_enter(mutexOpen);
2351 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
2352 sqlite3_mutex_enter(mutexShared);
2353 #endif
2354 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
2355 assert( pBt->nRef>0 );
2356 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
2357 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
2358 int iDb;
2359 for(iDb=db->nDb-1; iDb>=0; iDb--){
2360 Btree *pExisting = db->aDb[iDb].pBt;
2361 if( pExisting && pExisting->pBt==pBt ){
2362 sqlite3_mutex_leave(mutexShared);
2363 sqlite3_mutex_leave(mutexOpen);
2364 sqlite3_free(zFullPathname);
2365 sqlite3_free(p);
2366 return SQLITE_CONSTRAINT;
2369 p->pBt = pBt;
2370 pBt->nRef++;
2371 break;
2374 sqlite3_mutex_leave(mutexShared);
2375 sqlite3_free(zFullPathname);
2377 #ifdef SQLITE_DEBUG
2378 else{
2379 /* In debug mode, we mark all persistent databases as sharable
2380 ** even when they are not. This exercises the locking code and
2381 ** gives more opportunity for asserts(sqlite3_mutex_held())
2382 ** statements to find locking problems.
2384 p->sharable = 1;
2386 #endif
2388 #endif
2389 if( pBt==0 ){
2391 ** The following asserts make sure that structures used by the btree are
2392 ** the right size. This is to guard against size changes that result
2393 ** when compiling on a different architecture.
2395 assert( sizeof(i64)==8 );
2396 assert( sizeof(u64)==8 );
2397 assert( sizeof(u32)==4 );
2398 assert( sizeof(u16)==2 );
2399 assert( sizeof(Pgno)==4 );
2401 pBt = sqlite3MallocZero( sizeof(*pBt) );
2402 if( pBt==0 ){
2403 rc = SQLITE_NOMEM_BKPT;
2404 goto btree_open_out;
2406 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
2407 sizeof(MemPage), flags, vfsFlags, pageReinit);
2408 if( rc==SQLITE_OK ){
2409 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
2410 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
2412 if( rc!=SQLITE_OK ){
2413 goto btree_open_out;
2415 pBt->openFlags = (u8)flags;
2416 pBt->db = db;
2417 sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
2418 p->pBt = pBt;
2420 pBt->pCursor = 0;
2421 pBt->pPage1 = 0;
2422 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
2423 #if defined(SQLITE_SECURE_DELETE)
2424 pBt->btsFlags |= BTS_SECURE_DELETE;
2425 #elif defined(SQLITE_FAST_SECURE_DELETE)
2426 pBt->btsFlags |= BTS_OVERWRITE;
2427 #endif
2428 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2429 ** determined by the 2-byte integer located at an offset of 16 bytes from
2430 ** the beginning of the database file. */
2431 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
2432 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
2433 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
2434 pBt->pageSize = 0;
2435 #ifndef SQLITE_OMIT_AUTOVACUUM
2436 /* If the magic name ":memory:" will create an in-memory database, then
2437 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
2438 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
2439 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
2440 ** regular file-name. In this case the auto-vacuum applies as per normal.
2442 if( zFilename && !isMemdb ){
2443 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
2444 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
2446 #endif
2447 nReserve = 0;
2448 }else{
2449 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2450 ** determined by the one-byte unsigned integer found at an offset of 20
2451 ** into the database file header. */
2452 nReserve = zDbHeader[20];
2453 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2454 #ifndef SQLITE_OMIT_AUTOVACUUM
2455 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
2456 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
2457 #endif
2459 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2460 if( rc ) goto btree_open_out;
2461 pBt->usableSize = pBt->pageSize - nReserve;
2462 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
2464 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2465 /* Add the new BtShared object to the linked list sharable BtShareds.
2467 pBt->nRef = 1;
2468 if( p->sharable ){
2469 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2470 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
2471 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
2472 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
2473 if( pBt->mutex==0 ){
2474 rc = SQLITE_NOMEM_BKPT;
2475 goto btree_open_out;
2478 sqlite3_mutex_enter(mutexShared);
2479 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2480 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
2481 sqlite3_mutex_leave(mutexShared);
2483 #endif
2486 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2487 /* If the new Btree uses a sharable pBtShared, then link the new
2488 ** Btree into the list of all sharable Btrees for the same connection.
2489 ** The list is kept in ascending order by pBt address.
2491 if( p->sharable ){
2492 int i;
2493 Btree *pSib;
2494 for(i=0; i<db->nDb; i++){
2495 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
2496 while( pSib->pPrev ){ pSib = pSib->pPrev; }
2497 if( (uptr)p->pBt<(uptr)pSib->pBt ){
2498 p->pNext = pSib;
2499 p->pPrev = 0;
2500 pSib->pPrev = p;
2501 }else{
2502 while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
2503 pSib = pSib->pNext;
2505 p->pNext = pSib->pNext;
2506 p->pPrev = pSib;
2507 if( p->pNext ){
2508 p->pNext->pPrev = p;
2510 pSib->pNext = p;
2512 break;
2516 #endif
2517 *ppBtree = p;
2519 btree_open_out:
2520 if( rc!=SQLITE_OK ){
2521 if( pBt && pBt->pPager ){
2522 sqlite3PagerClose(pBt->pPager, 0);
2524 sqlite3_free(pBt);
2525 sqlite3_free(p);
2526 *ppBtree = 0;
2527 }else{
2528 sqlite3_file *pFile;
2530 /* If the B-Tree was successfully opened, set the pager-cache size to the
2531 ** default value. Except, when opening on an existing shared pager-cache,
2532 ** do not change the pager-cache size.
2534 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
2535 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
2538 pFile = sqlite3PagerFile(pBt->pPager);
2539 if( pFile->pMethods ){
2540 sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
2543 if( mutexOpen ){
2544 assert( sqlite3_mutex_held(mutexOpen) );
2545 sqlite3_mutex_leave(mutexOpen);
2547 assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
2548 return rc;
2552 ** Decrement the BtShared.nRef counter. When it reaches zero,
2553 ** remove the BtShared structure from the sharing list. Return
2554 ** true if the BtShared.nRef counter reaches zero and return
2555 ** false if it is still positive.
2557 static int removeFromSharingList(BtShared *pBt){
2558 #ifndef SQLITE_OMIT_SHARED_CACHE
2559 MUTEX_LOGIC( sqlite3_mutex *pMaster; )
2560 BtShared *pList;
2561 int removed = 0;
2563 assert( sqlite3_mutex_notheld(pBt->mutex) );
2564 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
2565 sqlite3_mutex_enter(pMaster);
2566 pBt->nRef--;
2567 if( pBt->nRef<=0 ){
2568 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2569 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
2570 }else{
2571 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
2572 while( ALWAYS(pList) && pList->pNext!=pBt ){
2573 pList=pList->pNext;
2575 if( ALWAYS(pList) ){
2576 pList->pNext = pBt->pNext;
2579 if( SQLITE_THREADSAFE ){
2580 sqlite3_mutex_free(pBt->mutex);
2582 removed = 1;
2584 sqlite3_mutex_leave(pMaster);
2585 return removed;
2586 #else
2587 return 1;
2588 #endif
2592 ** Make sure pBt->pTmpSpace points to an allocation of
2593 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
2594 ** pointer.
2596 static void allocateTempSpace(BtShared *pBt){
2597 if( !pBt->pTmpSpace ){
2598 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
2600 /* One of the uses of pBt->pTmpSpace is to format cells before
2601 ** inserting them into a leaf page (function fillInCell()). If
2602 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
2603 ** by the various routines that manipulate binary cells. Which
2604 ** can mean that fillInCell() only initializes the first 2 or 3
2605 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
2606 ** it into a database page. This is not actually a problem, but it
2607 ** does cause a valgrind error when the 1 or 2 bytes of unitialized
2608 ** data is passed to system call write(). So to avoid this error,
2609 ** zero the first 4 bytes of temp space here.
2611 ** Also: Provide four bytes of initialized space before the
2612 ** beginning of pTmpSpace as an area available to prepend the
2613 ** left-child pointer to the beginning of a cell.
2615 if( pBt->pTmpSpace ){
2616 memset(pBt->pTmpSpace, 0, 8);
2617 pBt->pTmpSpace += 4;
2623 ** Free the pBt->pTmpSpace allocation
2625 static void freeTempSpace(BtShared *pBt){
2626 if( pBt->pTmpSpace ){
2627 pBt->pTmpSpace -= 4;
2628 sqlite3PageFree(pBt->pTmpSpace);
2629 pBt->pTmpSpace = 0;
2634 ** Close an open database and invalidate all cursors.
2636 int sqlite3BtreeClose(Btree *p){
2637 BtShared *pBt = p->pBt;
2638 BtCursor *pCur;
2640 /* Close all cursors opened via this handle. */
2641 assert( sqlite3_mutex_held(p->db->mutex) );
2642 sqlite3BtreeEnter(p);
2643 pCur = pBt->pCursor;
2644 while( pCur ){
2645 BtCursor *pTmp = pCur;
2646 pCur = pCur->pNext;
2647 if( pTmp->pBtree==p ){
2648 sqlite3BtreeCloseCursor(pTmp);
2652 /* Rollback any active transaction and free the handle structure.
2653 ** The call to sqlite3BtreeRollback() drops any table-locks held by
2654 ** this handle.
2656 sqlite3BtreeRollback(p, SQLITE_OK, 0);
2657 sqlite3BtreeLeave(p);
2659 /* If there are still other outstanding references to the shared-btree
2660 ** structure, return now. The remainder of this procedure cleans
2661 ** up the shared-btree.
2663 assert( p->wantToLock==0 && p->locked==0 );
2664 if( !p->sharable || removeFromSharingList(pBt) ){
2665 /* The pBt is no longer on the sharing list, so we can access
2666 ** it without having to hold the mutex.
2668 ** Clean out and delete the BtShared object.
2670 assert( !pBt->pCursor );
2671 sqlite3PagerClose(pBt->pPager, p->db);
2672 if( pBt->xFreeSchema && pBt->pSchema ){
2673 pBt->xFreeSchema(pBt->pSchema);
2675 sqlite3DbFree(0, pBt->pSchema);
2676 freeTempSpace(pBt);
2677 sqlite3_free(pBt);
2680 #ifndef SQLITE_OMIT_SHARED_CACHE
2681 assert( p->wantToLock==0 );
2682 assert( p->locked==0 );
2683 if( p->pPrev ) p->pPrev->pNext = p->pNext;
2684 if( p->pNext ) p->pNext->pPrev = p->pPrev;
2685 #endif
2687 sqlite3_free(p);
2688 return SQLITE_OK;
2692 ** Change the "soft" limit on the number of pages in the cache.
2693 ** Unused and unmodified pages will be recycled when the number of
2694 ** pages in the cache exceeds this soft limit. But the size of the
2695 ** cache is allowed to grow larger than this limit if it contains
2696 ** dirty pages or pages still in active use.
2698 int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2699 BtShared *pBt = p->pBt;
2700 assert( sqlite3_mutex_held(p->db->mutex) );
2701 sqlite3BtreeEnter(p);
2702 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
2703 sqlite3BtreeLeave(p);
2704 return SQLITE_OK;
2708 ** Change the "spill" limit on the number of pages in the cache.
2709 ** If the number of pages exceeds this limit during a write transaction,
2710 ** the pager might attempt to "spill" pages to the journal early in
2711 ** order to free up memory.
2713 ** The value returned is the current spill size. If zero is passed
2714 ** as an argument, no changes are made to the spill size setting, so
2715 ** using mxPage of 0 is a way to query the current spill size.
2717 int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
2718 BtShared *pBt = p->pBt;
2719 int res;
2720 assert( sqlite3_mutex_held(p->db->mutex) );
2721 sqlite3BtreeEnter(p);
2722 res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
2723 sqlite3BtreeLeave(p);
2724 return res;
2727 #if SQLITE_MAX_MMAP_SIZE>0
2729 ** Change the limit on the amount of the database file that may be
2730 ** memory mapped.
2732 int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
2733 BtShared *pBt = p->pBt;
2734 assert( sqlite3_mutex_held(p->db->mutex) );
2735 sqlite3BtreeEnter(p);
2736 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
2737 sqlite3BtreeLeave(p);
2738 return SQLITE_OK;
2740 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
2743 ** Change the way data is synced to disk in order to increase or decrease
2744 ** how well the database resists damage due to OS crashes and power
2745 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
2746 ** there is a high probability of damage) Level 2 is the default. There
2747 ** is a very low but non-zero probability of damage. Level 3 reduces the
2748 ** probability of damage to near zero but with a write performance reduction.
2750 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
2751 int sqlite3BtreeSetPagerFlags(
2752 Btree *p, /* The btree to set the safety level on */
2753 unsigned pgFlags /* Various PAGER_* flags */
2755 BtShared *pBt = p->pBt;
2756 assert( sqlite3_mutex_held(p->db->mutex) );
2757 sqlite3BtreeEnter(p);
2758 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
2759 sqlite3BtreeLeave(p);
2760 return SQLITE_OK;
2762 #endif
2765 ** Change the default pages size and the number of reserved bytes per page.
2766 ** Or, if the page size has already been fixed, return SQLITE_READONLY
2767 ** without changing anything.
2769 ** The page size must be a power of 2 between 512 and 65536. If the page
2770 ** size supplied does not meet this constraint then the page size is not
2771 ** changed.
2773 ** Page sizes are constrained to be a power of two so that the region
2774 ** of the database file used for locking (beginning at PENDING_BYTE,
2775 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
2776 ** at the beginning of a page.
2778 ** If parameter nReserve is less than zero, then the number of reserved
2779 ** bytes per page is left unchanged.
2781 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
2782 ** and autovacuum mode can no longer be changed.
2784 int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
2785 int rc = SQLITE_OK;
2786 BtShared *pBt = p->pBt;
2787 assert( nReserve>=-1 && nReserve<=255 );
2788 sqlite3BtreeEnter(p);
2789 #if SQLITE_HAS_CODEC
2790 if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
2791 #endif
2792 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
2793 sqlite3BtreeLeave(p);
2794 return SQLITE_READONLY;
2796 if( nReserve<0 ){
2797 nReserve = pBt->pageSize - pBt->usableSize;
2799 assert( nReserve>=0 && nReserve<=255 );
2800 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2801 ((pageSize-1)&pageSize)==0 ){
2802 assert( (pageSize & 7)==0 );
2803 assert( !pBt->pCursor );
2804 pBt->pageSize = (u32)pageSize;
2805 freeTempSpace(pBt);
2807 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2808 pBt->usableSize = pBt->pageSize - (u16)nReserve;
2809 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2810 sqlite3BtreeLeave(p);
2811 return rc;
2815 ** Return the currently defined page size
2817 int sqlite3BtreeGetPageSize(Btree *p){
2818 return p->pBt->pageSize;
2822 ** This function is similar to sqlite3BtreeGetReserve(), except that it
2823 ** may only be called if it is guaranteed that the b-tree mutex is already
2824 ** held.
2826 ** This is useful in one special case in the backup API code where it is
2827 ** known that the shared b-tree mutex is held, but the mutex on the
2828 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
2829 ** were to be called, it might collide with some other operation on the
2830 ** database handle that owns *p, causing undefined behavior.
2832 int sqlite3BtreeGetReserveNoMutex(Btree *p){
2833 int n;
2834 assert( sqlite3_mutex_held(p->pBt->mutex) );
2835 n = p->pBt->pageSize - p->pBt->usableSize;
2836 return n;
2840 ** Return the number of bytes of space at the end of every page that
2841 ** are intentually left unused. This is the "reserved" space that is
2842 ** sometimes used by extensions.
2844 ** If SQLITE_HAS_MUTEX is defined then the number returned is the
2845 ** greater of the current reserved space and the maximum requested
2846 ** reserve space.
2848 int sqlite3BtreeGetOptimalReserve(Btree *p){
2849 int n;
2850 sqlite3BtreeEnter(p);
2851 n = sqlite3BtreeGetReserveNoMutex(p);
2852 #ifdef SQLITE_HAS_CODEC
2853 if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
2854 #endif
2855 sqlite3BtreeLeave(p);
2856 return n;
2861 ** Set the maximum page count for a database if mxPage is positive.
2862 ** No changes are made if mxPage is 0 or negative.
2863 ** Regardless of the value of mxPage, return the maximum page count.
2865 int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
2866 int n;
2867 sqlite3BtreeEnter(p);
2868 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
2869 sqlite3BtreeLeave(p);
2870 return n;
2874 ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
2876 ** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
2877 ** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
2878 ** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
2879 ** newFlag==(-1) No changes
2881 ** This routine acts as a query if newFlag is less than zero
2883 ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
2884 ** freelist leaf pages are not written back to the database. Thus in-page
2885 ** deleted content is cleared, but freelist deleted content is not.
2887 ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
2888 ** that freelist leaf pages are written back into the database, increasing
2889 ** the amount of disk I/O.
2891 int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
2892 int b;
2893 if( p==0 ) return 0;
2894 sqlite3BtreeEnter(p);
2895 assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
2896 assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
2897 if( newFlag>=0 ){
2898 p->pBt->btsFlags &= ~BTS_FAST_SECURE;
2899 p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
2901 b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
2902 sqlite3BtreeLeave(p);
2903 return b;
2907 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
2908 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
2909 ** is disabled. The default value for the auto-vacuum property is
2910 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
2912 int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
2913 #ifdef SQLITE_OMIT_AUTOVACUUM
2914 return SQLITE_READONLY;
2915 #else
2916 BtShared *pBt = p->pBt;
2917 int rc = SQLITE_OK;
2918 u8 av = (u8)autoVacuum;
2920 sqlite3BtreeEnter(p);
2921 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
2922 rc = SQLITE_READONLY;
2923 }else{
2924 pBt->autoVacuum = av ?1:0;
2925 pBt->incrVacuum = av==2 ?1:0;
2927 sqlite3BtreeLeave(p);
2928 return rc;
2929 #endif
2933 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
2934 ** enabled 1 is returned. Otherwise 0.
2936 int sqlite3BtreeGetAutoVacuum(Btree *p){
2937 #ifdef SQLITE_OMIT_AUTOVACUUM
2938 return BTREE_AUTOVACUUM_NONE;
2939 #else
2940 int rc;
2941 sqlite3BtreeEnter(p);
2942 rc = (
2943 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
2944 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
2945 BTREE_AUTOVACUUM_INCR
2947 sqlite3BtreeLeave(p);
2948 return rc;
2949 #endif
2953 ** If the user has not set the safety-level for this database connection
2954 ** using "PRAGMA synchronous", and if the safety-level is not already
2955 ** set to the value passed to this function as the second parameter,
2956 ** set it so.
2958 #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
2959 && !defined(SQLITE_OMIT_WAL)
2960 static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
2961 sqlite3 *db;
2962 Db *pDb;
2963 if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
2964 while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
2965 if( pDb->bSyncSet==0
2966 && pDb->safety_level!=safety_level
2967 && pDb!=&db->aDb[1]
2969 pDb->safety_level = safety_level;
2970 sqlite3PagerSetFlags(pBt->pPager,
2971 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
2975 #else
2976 # define setDefaultSyncFlag(pBt,safety_level)
2977 #endif
2979 /* Forward declaration */
2980 static int newDatabase(BtShared*);
2984 ** Get a reference to pPage1 of the database file. This will
2985 ** also acquire a readlock on that file.
2987 ** SQLITE_OK is returned on success. If the file is not a
2988 ** well-formed database file, then SQLITE_CORRUPT is returned.
2989 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
2990 ** is returned if we run out of memory.
2992 static int lockBtree(BtShared *pBt){
2993 int rc; /* Result code from subfunctions */
2994 MemPage *pPage1; /* Page 1 of the database file */
2995 int nPage; /* Number of pages in the database */
2996 int nPageFile = 0; /* Number of pages in the database file */
2997 int nPageHeader; /* Number of pages in the database according to hdr */
2999 assert( sqlite3_mutex_held(pBt->mutex) );
3000 assert( pBt->pPage1==0 );
3001 rc = sqlite3PagerSharedLock(pBt->pPager);
3002 if( rc!=SQLITE_OK ) return rc;
3003 rc = btreeGetPage(pBt, 1, &pPage1, 0);
3004 if( rc!=SQLITE_OK ) return rc;
3006 /* Do some checking to help insure the file we opened really is
3007 ** a valid database file.
3009 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
3010 sqlite3PagerPagecount(pBt->pPager, &nPageFile);
3011 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
3012 nPage = nPageFile;
3014 if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
3015 nPage = 0;
3017 if( nPage>0 ){
3018 u32 pageSize;
3019 u32 usableSize;
3020 u8 *page1 = pPage1->aData;
3021 rc = SQLITE_NOTADB;
3022 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
3023 ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
3024 ** 61 74 20 33 00. */
3025 if( memcmp(page1, zMagicHeader, 16)!=0 ){
3026 goto page1_init_failed;
3029 #ifdef SQLITE_OMIT_WAL
3030 if( page1[18]>1 ){
3031 pBt->btsFlags |= BTS_READ_ONLY;
3033 if( page1[19]>1 ){
3034 goto page1_init_failed;
3036 #else
3037 if( page1[18]>2 ){
3038 pBt->btsFlags |= BTS_READ_ONLY;
3040 if( page1[19]>2 ){
3041 goto page1_init_failed;
3044 /* If the write version is set to 2, this database should be accessed
3045 ** in WAL mode. If the log is not already open, open it now. Then
3046 ** return SQLITE_OK and return without populating BtShared.pPage1.
3047 ** The caller detects this and calls this function again. This is
3048 ** required as the version of page 1 currently in the page1 buffer
3049 ** may not be the latest version - there may be a newer one in the log
3050 ** file.
3052 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
3053 int isOpen = 0;
3054 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
3055 if( rc!=SQLITE_OK ){
3056 goto page1_init_failed;
3057 }else{
3058 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
3059 if( isOpen==0 ){
3060 releasePageOne(pPage1);
3061 return SQLITE_OK;
3064 rc = SQLITE_NOTADB;
3065 }else{
3066 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
3068 #endif
3070 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
3071 ** fractions and the leaf payload fraction values must be 64, 32, and 32.
3073 ** The original design allowed these amounts to vary, but as of
3074 ** version 3.6.0, we require them to be fixed.
3076 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
3077 goto page1_init_failed;
3079 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
3080 ** determined by the 2-byte integer located at an offset of 16 bytes from
3081 ** the beginning of the database file. */
3082 pageSize = (page1[16]<<8) | (page1[17]<<16);
3083 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
3084 ** between 512 and 65536 inclusive. */
3085 if( ((pageSize-1)&pageSize)!=0
3086 || pageSize>SQLITE_MAX_PAGE_SIZE
3087 || pageSize<=256
3089 goto page1_init_failed;
3091 assert( (pageSize & 7)==0 );
3092 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
3093 ** integer at offset 20 is the number of bytes of space at the end of
3094 ** each page to reserve for extensions.
3096 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
3097 ** determined by the one-byte unsigned integer found at an offset of 20
3098 ** into the database file header. */
3099 usableSize = pageSize - page1[20];
3100 if( (u32)pageSize!=pBt->pageSize ){
3101 /* After reading the first page of the database assuming a page size
3102 ** of BtShared.pageSize, we have discovered that the page-size is
3103 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
3104 ** zero and return SQLITE_OK. The caller will call this function
3105 ** again with the correct page-size.
3107 releasePageOne(pPage1);
3108 pBt->usableSize = usableSize;
3109 pBt->pageSize = pageSize;
3110 freeTempSpace(pBt);
3111 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
3112 pageSize-usableSize);
3113 return rc;
3115 if( (pBt->db->flags & SQLITE_WriteSchema)==0 && nPage>nPageFile ){
3116 rc = SQLITE_CORRUPT_BKPT;
3117 goto page1_init_failed;
3119 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
3120 ** be less than 480. In other words, if the page size is 512, then the
3121 ** reserved space size cannot exceed 32. */
3122 if( usableSize<480 ){
3123 goto page1_init_failed;
3125 pBt->pageSize = pageSize;
3126 pBt->usableSize = usableSize;
3127 #ifndef SQLITE_OMIT_AUTOVACUUM
3128 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
3129 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
3130 #endif
3133 /* maxLocal is the maximum amount of payload to store locally for
3134 ** a cell. Make sure it is small enough so that at least minFanout
3135 ** cells can will fit on one page. We assume a 10-byte page header.
3136 ** Besides the payload, the cell must store:
3137 ** 2-byte pointer to the cell
3138 ** 4-byte child pointer
3139 ** 9-byte nKey value
3140 ** 4-byte nData value
3141 ** 4-byte overflow page pointer
3142 ** So a cell consists of a 2-byte pointer, a header which is as much as
3143 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
3144 ** page pointer.
3146 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
3147 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
3148 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
3149 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
3150 if( pBt->maxLocal>127 ){
3151 pBt->max1bytePayload = 127;
3152 }else{
3153 pBt->max1bytePayload = (u8)pBt->maxLocal;
3155 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
3156 pBt->pPage1 = pPage1;
3157 pBt->nPage = nPage;
3158 return SQLITE_OK;
3160 page1_init_failed:
3161 releasePageOne(pPage1);
3162 pBt->pPage1 = 0;
3163 return rc;
3166 #ifndef NDEBUG
3168 ** Return the number of cursors open on pBt. This is for use
3169 ** in assert() expressions, so it is only compiled if NDEBUG is not
3170 ** defined.
3172 ** Only write cursors are counted if wrOnly is true. If wrOnly is
3173 ** false then all cursors are counted.
3175 ** For the purposes of this routine, a cursor is any cursor that
3176 ** is capable of reading or writing to the database. Cursors that
3177 ** have been tripped into the CURSOR_FAULT state are not counted.
3179 static int countValidCursors(BtShared *pBt, int wrOnly){
3180 BtCursor *pCur;
3181 int r = 0;
3182 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3183 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
3184 && pCur->eState!=CURSOR_FAULT ) r++;
3186 return r;
3188 #endif
3191 ** If there are no outstanding cursors and we are not in the middle
3192 ** of a transaction but there is a read lock on the database, then
3193 ** this routine unrefs the first page of the database file which
3194 ** has the effect of releasing the read lock.
3196 ** If there is a transaction in progress, this routine is a no-op.
3198 static void unlockBtreeIfUnused(BtShared *pBt){
3199 assert( sqlite3_mutex_held(pBt->mutex) );
3200 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
3201 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
3202 MemPage *pPage1 = pBt->pPage1;
3203 assert( pPage1->aData );
3204 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
3205 pBt->pPage1 = 0;
3206 releasePageOne(pPage1);
3211 ** If pBt points to an empty file then convert that empty file
3212 ** into a new empty database by initializing the first page of
3213 ** the database.
3215 static int newDatabase(BtShared *pBt){
3216 MemPage *pP1;
3217 unsigned char *data;
3218 int rc;
3220 assert( sqlite3_mutex_held(pBt->mutex) );
3221 if( pBt->nPage>0 ){
3222 return SQLITE_OK;
3224 pP1 = pBt->pPage1;
3225 assert( pP1!=0 );
3226 data = pP1->aData;
3227 rc = sqlite3PagerWrite(pP1->pDbPage);
3228 if( rc ) return rc;
3229 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
3230 assert( sizeof(zMagicHeader)==16 );
3231 data[16] = (u8)((pBt->pageSize>>8)&0xff);
3232 data[17] = (u8)((pBt->pageSize>>16)&0xff);
3233 data[18] = 1;
3234 data[19] = 1;
3235 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
3236 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
3237 data[21] = 64;
3238 data[22] = 32;
3239 data[23] = 32;
3240 memset(&data[24], 0, 100-24);
3241 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
3242 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3243 #ifndef SQLITE_OMIT_AUTOVACUUM
3244 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
3245 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
3246 put4byte(&data[36 + 4*4], pBt->autoVacuum);
3247 put4byte(&data[36 + 7*4], pBt->incrVacuum);
3248 #endif
3249 pBt->nPage = 1;
3250 data[31] = 1;
3251 return SQLITE_OK;
3255 ** Initialize the first page of the database file (creating a database
3256 ** consisting of a single page and no schema objects). Return SQLITE_OK
3257 ** if successful, or an SQLite error code otherwise.
3259 int sqlite3BtreeNewDb(Btree *p){
3260 int rc;
3261 sqlite3BtreeEnter(p);
3262 p->pBt->nPage = 0;
3263 rc = newDatabase(p->pBt);
3264 sqlite3BtreeLeave(p);
3265 return rc;
3269 ** Attempt to start a new transaction. A write-transaction
3270 ** is started if the second argument is nonzero, otherwise a read-
3271 ** transaction. If the second argument is 2 or more and exclusive
3272 ** transaction is started, meaning that no other process is allowed
3273 ** to access the database. A preexisting transaction may not be
3274 ** upgraded to exclusive by calling this routine a second time - the
3275 ** exclusivity flag only works for a new transaction.
3277 ** A write-transaction must be started before attempting any
3278 ** changes to the database. None of the following routines
3279 ** will work unless a transaction is started first:
3281 ** sqlite3BtreeCreateTable()
3282 ** sqlite3BtreeCreateIndex()
3283 ** sqlite3BtreeClearTable()
3284 ** sqlite3BtreeDropTable()
3285 ** sqlite3BtreeInsert()
3286 ** sqlite3BtreeDelete()
3287 ** sqlite3BtreeUpdateMeta()
3289 ** If an initial attempt to acquire the lock fails because of lock contention
3290 ** and the database was previously unlocked, then invoke the busy handler
3291 ** if there is one. But if there was previously a read-lock, do not
3292 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
3293 ** returned when there is already a read-lock in order to avoid a deadlock.
3295 ** Suppose there are two processes A and B. A has a read lock and B has
3296 ** a reserved lock. B tries to promote to exclusive but is blocked because
3297 ** of A's read lock. A tries to promote to reserved but is blocked by B.
3298 ** One or the other of the two processes must give way or there can be
3299 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
3300 ** when A already has a read lock, we encourage A to give up and let B
3301 ** proceed.
3303 int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
3304 BtShared *pBt = p->pBt;
3305 int rc = SQLITE_OK;
3307 sqlite3BtreeEnter(p);
3308 btreeIntegrity(p);
3310 /* If the btree is already in a write-transaction, or it
3311 ** is already in a read-transaction and a read-transaction
3312 ** is requested, this is a no-op.
3314 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
3315 goto trans_begun;
3317 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
3319 /* Write transactions are not possible on a read-only database */
3320 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
3321 rc = SQLITE_READONLY;
3322 goto trans_begun;
3325 #ifndef SQLITE_OMIT_SHARED_CACHE
3327 sqlite3 *pBlock = 0;
3328 /* If another database handle has already opened a write transaction
3329 ** on this shared-btree structure and a second write transaction is
3330 ** requested, return SQLITE_LOCKED.
3332 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
3333 || (pBt->btsFlags & BTS_PENDING)!=0
3335 pBlock = pBt->pWriter->db;
3336 }else if( wrflag>1 ){
3337 BtLock *pIter;
3338 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
3339 if( pIter->pBtree!=p ){
3340 pBlock = pIter->pBtree->db;
3341 break;
3345 if( pBlock ){
3346 sqlite3ConnectionBlocked(p->db, pBlock);
3347 rc = SQLITE_LOCKED_SHAREDCACHE;
3348 goto trans_begun;
3351 #endif
3353 /* Any read-only or read-write transaction implies a read-lock on
3354 ** page 1. So if some other shared-cache client already has a write-lock
3355 ** on page 1, the transaction cannot be opened. */
3356 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
3357 if( SQLITE_OK!=rc ) goto trans_begun;
3359 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
3360 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
3361 do {
3362 /* Call lockBtree() until either pBt->pPage1 is populated or
3363 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
3364 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
3365 ** reading page 1 it discovers that the page-size of the database
3366 ** file is not pBt->pageSize. In this case lockBtree() will update
3367 ** pBt->pageSize to the page-size of the file on disk.
3369 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
3371 if( rc==SQLITE_OK && wrflag ){
3372 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
3373 rc = SQLITE_READONLY;
3374 }else{
3375 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
3376 if( rc==SQLITE_OK ){
3377 rc = newDatabase(pBt);
3382 if( rc!=SQLITE_OK ){
3383 unlockBtreeIfUnused(pBt);
3385 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
3386 btreeInvokeBusyHandler(pBt) );
3387 sqlite3PagerResetLockTimeout(pBt->pPager);
3389 if( rc==SQLITE_OK ){
3390 if( p->inTrans==TRANS_NONE ){
3391 pBt->nTransaction++;
3392 #ifndef SQLITE_OMIT_SHARED_CACHE
3393 if( p->sharable ){
3394 assert( p->lock.pBtree==p && p->lock.iTable==1 );
3395 p->lock.eLock = READ_LOCK;
3396 p->lock.pNext = pBt->pLock;
3397 pBt->pLock = &p->lock;
3399 #endif
3401 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
3402 if( p->inTrans>pBt->inTransaction ){
3403 pBt->inTransaction = p->inTrans;
3405 if( wrflag ){
3406 MemPage *pPage1 = pBt->pPage1;
3407 #ifndef SQLITE_OMIT_SHARED_CACHE
3408 assert( !pBt->pWriter );
3409 pBt->pWriter = p;
3410 pBt->btsFlags &= ~BTS_EXCLUSIVE;
3411 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
3412 #endif
3414 /* If the db-size header field is incorrect (as it may be if an old
3415 ** client has been writing the database file), update it now. Doing
3416 ** this sooner rather than later means the database size can safely
3417 ** re-read the database size from page 1 if a savepoint or transaction
3418 ** rollback occurs within the transaction.
3420 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
3421 rc = sqlite3PagerWrite(pPage1->pDbPage);
3422 if( rc==SQLITE_OK ){
3423 put4byte(&pPage1->aData[28], pBt->nPage);
3427 }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
3428 /* Even if there was no transaction opened when this function was
3429 ** called, a race condition may cause an SQLITE_BUSY_SNAPSHOT error
3430 ** in wal mode (since the code above opens a read-transaction and then
3431 ** upgrades it to a write-transaction - it does not take the write lock
3432 ** atomically). In this case change the error code to SQLITE_BUSY. */
3433 assert( wrFlag );
3434 rc = SQLITE_BUSY;
3438 trans_begun:
3439 if( rc==SQLITE_OK ){
3440 if( pSchemaVersion ){
3441 *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
3443 if( wrflag ){
3444 /* This call makes sure that the pager has the correct number of
3445 ** open savepoints. If the second parameter is greater than 0 and
3446 ** the sub-journal is not already open, then it will be opened here.
3448 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
3452 btreeIntegrity(p);
3453 sqlite3BtreeLeave(p);
3454 return rc;
3457 #ifndef SQLITE_OMIT_AUTOVACUUM
3460 ** Set the pointer-map entries for all children of page pPage. Also, if
3461 ** pPage contains cells that point to overflow pages, set the pointer
3462 ** map entries for the overflow pages as well.
3464 static int setChildPtrmaps(MemPage *pPage){
3465 int i; /* Counter variable */
3466 int nCell; /* Number of cells in page pPage */
3467 int rc; /* Return code */
3468 BtShared *pBt = pPage->pBt;
3469 Pgno pgno = pPage->pgno;
3471 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3472 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3473 if( rc!=SQLITE_OK ) return rc;
3474 nCell = pPage->nCell;
3476 for(i=0; i<nCell; i++){
3477 u8 *pCell = findCell(pPage, i);
3479 ptrmapPutOvflPtr(pPage, pCell, &rc);
3481 if( !pPage->leaf ){
3482 Pgno childPgno = get4byte(pCell);
3483 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3487 if( !pPage->leaf ){
3488 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
3489 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3492 return rc;
3496 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
3497 ** that it points to iTo. Parameter eType describes the type of pointer to
3498 ** be modified, as follows:
3500 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
3501 ** page of pPage.
3503 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3504 ** page pointed to by one of the cells on pPage.
3506 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3507 ** overflow page in the list.
3509 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
3510 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3511 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
3512 if( eType==PTRMAP_OVERFLOW2 ){
3513 /* The pointer is always the first 4 bytes of the page in this case. */
3514 if( get4byte(pPage->aData)!=iFrom ){
3515 return SQLITE_CORRUPT_PAGE(pPage);
3517 put4byte(pPage->aData, iTo);
3518 }else{
3519 int i;
3520 int nCell;
3521 int rc;
3523 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3524 if( rc ) return rc;
3525 nCell = pPage->nCell;
3527 for(i=0; i<nCell; i++){
3528 u8 *pCell = findCell(pPage, i);
3529 if( eType==PTRMAP_OVERFLOW1 ){
3530 CellInfo info;
3531 pPage->xParseCell(pPage, pCell, &info);
3532 if( info.nLocal<info.nPayload ){
3533 if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
3534 return SQLITE_CORRUPT_PAGE(pPage);
3536 if( iFrom==get4byte(pCell+info.nSize-4) ){
3537 put4byte(pCell+info.nSize-4, iTo);
3538 break;
3541 }else{
3542 if( get4byte(pCell)==iFrom ){
3543 put4byte(pCell, iTo);
3544 break;
3549 if( i==nCell ){
3550 if( eType!=PTRMAP_BTREE ||
3551 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
3552 return SQLITE_CORRUPT_PAGE(pPage);
3554 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3557 return SQLITE_OK;
3562 ** Move the open database page pDbPage to location iFreePage in the
3563 ** database. The pDbPage reference remains valid.
3565 ** The isCommit flag indicates that there is no need to remember that
3566 ** the journal needs to be sync()ed before database page pDbPage->pgno
3567 ** can be written to. The caller has already promised not to write to that
3568 ** page.
3570 static int relocatePage(
3571 BtShared *pBt, /* Btree */
3572 MemPage *pDbPage, /* Open page to move */
3573 u8 eType, /* Pointer map 'type' entry for pDbPage */
3574 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
3575 Pgno iFreePage, /* The location to move pDbPage to */
3576 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
3578 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
3579 Pgno iDbPage = pDbPage->pgno;
3580 Pager *pPager = pBt->pPager;
3581 int rc;
3583 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3584 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
3585 assert( sqlite3_mutex_held(pBt->mutex) );
3586 assert( pDbPage->pBt==pBt );
3588 /* Move page iDbPage from its current location to page number iFreePage */
3589 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
3590 iDbPage, iFreePage, iPtrPage, eType));
3591 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
3592 if( rc!=SQLITE_OK ){
3593 return rc;
3595 pDbPage->pgno = iFreePage;
3597 /* If pDbPage was a btree-page, then it may have child pages and/or cells
3598 ** that point to overflow pages. The pointer map entries for all these
3599 ** pages need to be changed.
3601 ** If pDbPage is an overflow page, then the first 4 bytes may store a
3602 ** pointer to a subsequent overflow page. If this is the case, then
3603 ** the pointer map needs to be updated for the subsequent overflow page.
3605 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
3606 rc = setChildPtrmaps(pDbPage);
3607 if( rc!=SQLITE_OK ){
3608 return rc;
3610 }else{
3611 Pgno nextOvfl = get4byte(pDbPage->aData);
3612 if( nextOvfl!=0 ){
3613 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
3614 if( rc!=SQLITE_OK ){
3615 return rc;
3620 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3621 ** that it points at iFreePage. Also fix the pointer map entry for
3622 ** iPtrPage.
3624 if( eType!=PTRMAP_ROOTPAGE ){
3625 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
3626 if( rc!=SQLITE_OK ){
3627 return rc;
3629 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
3630 if( rc!=SQLITE_OK ){
3631 releasePage(pPtrPage);
3632 return rc;
3634 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
3635 releasePage(pPtrPage);
3636 if( rc==SQLITE_OK ){
3637 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
3640 return rc;
3643 /* Forward declaration required by incrVacuumStep(). */
3644 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
3647 ** Perform a single step of an incremental-vacuum. If successful, return
3648 ** SQLITE_OK. If there is no work to do (and therefore no point in
3649 ** calling this function again), return SQLITE_DONE. Or, if an error
3650 ** occurs, return some other error code.
3652 ** More specifically, this function attempts to re-organize the database so
3653 ** that the last page of the file currently in use is no longer in use.
3655 ** Parameter nFin is the number of pages that this database would contain
3656 ** were this function called until it returns SQLITE_DONE.
3658 ** If the bCommit parameter is non-zero, this function assumes that the
3659 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
3660 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
3661 ** operation, or false for an incremental vacuum.
3663 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
3664 Pgno nFreeList; /* Number of pages still on the free-list */
3665 int rc;
3667 assert( sqlite3_mutex_held(pBt->mutex) );
3668 assert( iLastPg>nFin );
3670 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
3671 u8 eType;
3672 Pgno iPtrPage;
3674 nFreeList = get4byte(&pBt->pPage1->aData[36]);
3675 if( nFreeList==0 ){
3676 return SQLITE_DONE;
3679 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3680 if( rc!=SQLITE_OK ){
3681 return rc;
3683 if( eType==PTRMAP_ROOTPAGE ){
3684 return SQLITE_CORRUPT_BKPT;
3687 if( eType==PTRMAP_FREEPAGE ){
3688 if( bCommit==0 ){
3689 /* Remove the page from the files free-list. This is not required
3690 ** if bCommit is non-zero. In that case, the free-list will be
3691 ** truncated to zero after this function returns, so it doesn't
3692 ** matter if it still contains some garbage entries.
3694 Pgno iFreePg;
3695 MemPage *pFreePg;
3696 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
3697 if( rc!=SQLITE_OK ){
3698 return rc;
3700 assert( iFreePg==iLastPg );
3701 releasePage(pFreePg);
3703 } else {
3704 Pgno iFreePg; /* Index of free page to move pLastPg to */
3705 MemPage *pLastPg;
3706 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
3707 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
3709 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
3710 if( rc!=SQLITE_OK ){
3711 return rc;
3714 /* If bCommit is zero, this loop runs exactly once and page pLastPg
3715 ** is swapped with the first free page pulled off the free list.
3717 ** On the other hand, if bCommit is greater than zero, then keep
3718 ** looping until a free-page located within the first nFin pages
3719 ** of the file is found.
3721 if( bCommit==0 ){
3722 eMode = BTALLOC_LE;
3723 iNear = nFin;
3725 do {
3726 MemPage *pFreePg;
3727 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
3728 if( rc!=SQLITE_OK ){
3729 releasePage(pLastPg);
3730 return rc;
3732 releasePage(pFreePg);
3733 }while( bCommit && iFreePg>nFin );
3734 assert( iFreePg<iLastPg );
3736 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
3737 releasePage(pLastPg);
3738 if( rc!=SQLITE_OK ){
3739 return rc;
3744 if( bCommit==0 ){
3745 do {
3746 iLastPg--;
3747 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
3748 pBt->bDoTruncate = 1;
3749 pBt->nPage = iLastPg;
3751 return SQLITE_OK;
3755 ** The database opened by the first argument is an auto-vacuum database
3756 ** nOrig pages in size containing nFree free pages. Return the expected
3757 ** size of the database in pages following an auto-vacuum operation.
3759 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
3760 int nEntry; /* Number of entries on one ptrmap page */
3761 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
3762 Pgno nFin; /* Return value */
3764 nEntry = pBt->usableSize/5;
3765 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
3766 nFin = nOrig - nFree - nPtrmap;
3767 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
3768 nFin--;
3770 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
3771 nFin--;
3774 return nFin;
3778 ** A write-transaction must be opened before calling this function.
3779 ** It performs a single unit of work towards an incremental vacuum.
3781 ** If the incremental vacuum is finished after this function has run,
3782 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
3783 ** SQLITE_OK is returned. Otherwise an SQLite error code.
3785 int sqlite3BtreeIncrVacuum(Btree *p){
3786 int rc;
3787 BtShared *pBt = p->pBt;
3789 sqlite3BtreeEnter(p);
3790 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
3791 if( !pBt->autoVacuum ){
3792 rc = SQLITE_DONE;
3793 }else{
3794 Pgno nOrig = btreePagecount(pBt);
3795 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
3796 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
3798 if( nOrig<nFin ){
3799 rc = SQLITE_CORRUPT_BKPT;
3800 }else if( nFree>0 ){
3801 rc = saveAllCursors(pBt, 0, 0);
3802 if( rc==SQLITE_OK ){
3803 invalidateAllOverflowCache(pBt);
3804 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
3806 if( rc==SQLITE_OK ){
3807 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3808 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
3810 }else{
3811 rc = SQLITE_DONE;
3814 sqlite3BtreeLeave(p);
3815 return rc;
3819 ** This routine is called prior to sqlite3PagerCommit when a transaction
3820 ** is committed for an auto-vacuum database.
3822 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
3823 ** the database file should be truncated to during the commit process.
3824 ** i.e. the database has been reorganized so that only the first *pnTrunc
3825 ** pages are in use.
3827 static int autoVacuumCommit(BtShared *pBt){
3828 int rc = SQLITE_OK;
3829 Pager *pPager = pBt->pPager;
3830 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
3832 assert( sqlite3_mutex_held(pBt->mutex) );
3833 invalidateAllOverflowCache(pBt);
3834 assert(pBt->autoVacuum);
3835 if( !pBt->incrVacuum ){
3836 Pgno nFin; /* Number of pages in database after autovacuuming */
3837 Pgno nFree; /* Number of pages on the freelist initially */
3838 Pgno iFree; /* The next page to be freed */
3839 Pgno nOrig; /* Database size before freeing */
3841 nOrig = btreePagecount(pBt);
3842 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
3843 /* It is not possible to create a database for which the final page
3844 ** is either a pointer-map page or the pending-byte page. If one
3845 ** is encountered, this indicates corruption.
3847 return SQLITE_CORRUPT_BKPT;
3850 nFree = get4byte(&pBt->pPage1->aData[36]);
3851 nFin = finalDbSize(pBt, nOrig, nFree);
3852 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
3853 if( nFin<nOrig ){
3854 rc = saveAllCursors(pBt, 0, 0);
3856 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
3857 rc = incrVacuumStep(pBt, nFin, iFree, 1);
3859 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
3860 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3861 put4byte(&pBt->pPage1->aData[32], 0);
3862 put4byte(&pBt->pPage1->aData[36], 0);
3863 put4byte(&pBt->pPage1->aData[28], nFin);
3864 pBt->bDoTruncate = 1;
3865 pBt->nPage = nFin;
3867 if( rc!=SQLITE_OK ){
3868 sqlite3PagerRollback(pPager);
3872 assert( nRef>=sqlite3PagerRefcount(pPager) );
3873 return rc;
3876 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
3877 # define setChildPtrmaps(x) SQLITE_OK
3878 #endif
3881 ** This routine does the first phase of a two-phase commit. This routine
3882 ** causes a rollback journal to be created (if it does not already exist)
3883 ** and populated with enough information so that if a power loss occurs
3884 ** the database can be restored to its original state by playing back
3885 ** the journal. Then the contents of the journal are flushed out to
3886 ** the disk. After the journal is safely on oxide, the changes to the
3887 ** database are written into the database file and flushed to oxide.
3888 ** At the end of this call, the rollback journal still exists on the
3889 ** disk and we are still holding all locks, so the transaction has not
3890 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
3891 ** commit process.
3893 ** This call is a no-op if no write-transaction is currently active on pBt.
3895 ** Otherwise, sync the database file for the btree pBt. zMaster points to
3896 ** the name of a master journal file that should be written into the
3897 ** individual journal file, or is NULL, indicating no master journal file
3898 ** (single database transaction).
3900 ** When this is called, the master journal should already have been
3901 ** created, populated with this journal pointer and synced to disk.
3903 ** Once this is routine has returned, the only thing required to commit
3904 ** the write-transaction for this database file is to delete the journal.
3906 int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
3907 int rc = SQLITE_OK;
3908 if( p->inTrans==TRANS_WRITE ){
3909 BtShared *pBt = p->pBt;
3910 sqlite3BtreeEnter(p);
3911 #ifndef SQLITE_OMIT_AUTOVACUUM
3912 if( pBt->autoVacuum ){
3913 rc = autoVacuumCommit(pBt);
3914 if( rc!=SQLITE_OK ){
3915 sqlite3BtreeLeave(p);
3916 return rc;
3919 if( pBt->bDoTruncate ){
3920 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
3922 #endif
3923 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
3924 sqlite3BtreeLeave(p);
3926 return rc;
3930 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
3931 ** at the conclusion of a transaction.
3933 static void btreeEndTransaction(Btree *p){
3934 BtShared *pBt = p->pBt;
3935 sqlite3 *db = p->db;
3936 assert( sqlite3BtreeHoldsMutex(p) );
3938 #ifndef SQLITE_OMIT_AUTOVACUUM
3939 pBt->bDoTruncate = 0;
3940 #endif
3941 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
3942 /* If there are other active statements that belong to this database
3943 ** handle, downgrade to a read-only transaction. The other statements
3944 ** may still be reading from the database. */
3945 downgradeAllSharedCacheTableLocks(p);
3946 p->inTrans = TRANS_READ;
3947 }else{
3948 /* If the handle had any kind of transaction open, decrement the
3949 ** transaction count of the shared btree. If the transaction count
3950 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
3951 ** call below will unlock the pager. */
3952 if( p->inTrans!=TRANS_NONE ){
3953 clearAllSharedCacheTableLocks(p);
3954 pBt->nTransaction--;
3955 if( 0==pBt->nTransaction ){
3956 pBt->inTransaction = TRANS_NONE;
3960 /* Set the current transaction state to TRANS_NONE and unlock the
3961 ** pager if this call closed the only read or write transaction. */
3962 p->inTrans = TRANS_NONE;
3963 unlockBtreeIfUnused(pBt);
3966 btreeIntegrity(p);
3970 ** Commit the transaction currently in progress.
3972 ** This routine implements the second phase of a 2-phase commit. The
3973 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
3974 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
3975 ** routine did all the work of writing information out to disk and flushing the
3976 ** contents so that they are written onto the disk platter. All this
3977 ** routine has to do is delete or truncate or zero the header in the
3978 ** the rollback journal (which causes the transaction to commit) and
3979 ** drop locks.
3981 ** Normally, if an error occurs while the pager layer is attempting to
3982 ** finalize the underlying journal file, this function returns an error and
3983 ** the upper layer will attempt a rollback. However, if the second argument
3984 ** is non-zero then this b-tree transaction is part of a multi-file
3985 ** transaction. In this case, the transaction has already been committed
3986 ** (by deleting a master journal file) and the caller will ignore this
3987 ** functions return code. So, even if an error occurs in the pager layer,
3988 ** reset the b-tree objects internal state to indicate that the write
3989 ** transaction has been closed. This is quite safe, as the pager will have
3990 ** transitioned to the error state.
3992 ** This will release the write lock on the database file. If there
3993 ** are no active cursors, it also releases the read lock.
3995 int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
3997 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
3998 sqlite3BtreeEnter(p);
3999 btreeIntegrity(p);
4001 /* If the handle has a write-transaction open, commit the shared-btrees
4002 ** transaction and set the shared state to TRANS_READ.
4004 if( p->inTrans==TRANS_WRITE ){
4005 int rc;
4006 BtShared *pBt = p->pBt;
4007 assert( pBt->inTransaction==TRANS_WRITE );
4008 assert( pBt->nTransaction>0 );
4009 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
4010 if( rc!=SQLITE_OK && bCleanup==0 ){
4011 sqlite3BtreeLeave(p);
4012 return rc;
4014 p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
4015 pBt->inTransaction = TRANS_READ;
4016 btreeClearHasContent(pBt);
4019 btreeEndTransaction(p);
4020 sqlite3BtreeLeave(p);
4021 return SQLITE_OK;
4025 ** Do both phases of a commit.
4027 int sqlite3BtreeCommit(Btree *p){
4028 int rc;
4029 sqlite3BtreeEnter(p);
4030 rc = sqlite3BtreeCommitPhaseOne(p, 0);
4031 if( rc==SQLITE_OK ){
4032 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
4034 sqlite3BtreeLeave(p);
4035 return rc;
4039 ** This routine sets the state to CURSOR_FAULT and the error
4040 ** code to errCode for every cursor on any BtShared that pBtree
4041 ** references. Or if the writeOnly flag is set to 1, then only
4042 ** trip write cursors and leave read cursors unchanged.
4044 ** Every cursor is a candidate to be tripped, including cursors
4045 ** that belong to other database connections that happen to be
4046 ** sharing the cache with pBtree.
4048 ** This routine gets called when a rollback occurs. If the writeOnly
4049 ** flag is true, then only write-cursors need be tripped - read-only
4050 ** cursors save their current positions so that they may continue
4051 ** following the rollback. Or, if writeOnly is false, all cursors are
4052 ** tripped. In general, writeOnly is false if the transaction being
4053 ** rolled back modified the database schema. In this case b-tree root
4054 ** pages may be moved or deleted from the database altogether, making
4055 ** it unsafe for read cursors to continue.
4057 ** If the writeOnly flag is true and an error is encountered while
4058 ** saving the current position of a read-only cursor, all cursors,
4059 ** including all read-cursors are tripped.
4061 ** SQLITE_OK is returned if successful, or if an error occurs while
4062 ** saving a cursor position, an SQLite error code.
4064 int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
4065 BtCursor *p;
4066 int rc = SQLITE_OK;
4068 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
4069 if( pBtree ){
4070 sqlite3BtreeEnter(pBtree);
4071 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
4072 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
4073 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
4074 rc = saveCursorPosition(p);
4075 if( rc!=SQLITE_OK ){
4076 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
4077 break;
4080 }else{
4081 sqlite3BtreeClearCursor(p);
4082 p->eState = CURSOR_FAULT;
4083 p->skipNext = errCode;
4085 btreeReleaseAllCursorPages(p);
4087 sqlite3BtreeLeave(pBtree);
4089 return rc;
4093 ** Rollback the transaction in progress.
4095 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
4096 ** Only write cursors are tripped if writeOnly is true but all cursors are
4097 ** tripped if writeOnly is false. Any attempt to use
4098 ** a tripped cursor will result in an error.
4100 ** This will release the write lock on the database file. If there
4101 ** are no active cursors, it also releases the read lock.
4103 int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
4104 int rc;
4105 BtShared *pBt = p->pBt;
4106 MemPage *pPage1;
4108 assert( writeOnly==1 || writeOnly==0 );
4109 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
4110 sqlite3BtreeEnter(p);
4111 if( tripCode==SQLITE_OK ){
4112 rc = tripCode = saveAllCursors(pBt, 0, 0);
4113 if( rc ) writeOnly = 0;
4114 }else{
4115 rc = SQLITE_OK;
4117 if( tripCode ){
4118 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
4119 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
4120 if( rc2!=SQLITE_OK ) rc = rc2;
4122 btreeIntegrity(p);
4124 if( p->inTrans==TRANS_WRITE ){
4125 int rc2;
4127 assert( TRANS_WRITE==pBt->inTransaction );
4128 rc2 = sqlite3PagerRollback(pBt->pPager);
4129 if( rc2!=SQLITE_OK ){
4130 rc = rc2;
4133 /* The rollback may have destroyed the pPage1->aData value. So
4134 ** call btreeGetPage() on page 1 again to make
4135 ** sure pPage1->aData is set correctly. */
4136 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
4137 int nPage = get4byte(28+(u8*)pPage1->aData);
4138 testcase( nPage==0 );
4139 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
4140 testcase( pBt->nPage!=nPage );
4141 pBt->nPage = nPage;
4142 releasePageOne(pPage1);
4144 assert( countValidCursors(pBt, 1)==0 );
4145 pBt->inTransaction = TRANS_READ;
4146 btreeClearHasContent(pBt);
4149 btreeEndTransaction(p);
4150 sqlite3BtreeLeave(p);
4151 return rc;
4155 ** Start a statement subtransaction. The subtransaction can be rolled
4156 ** back independently of the main transaction. You must start a transaction
4157 ** before starting a subtransaction. The subtransaction is ended automatically
4158 ** if the main transaction commits or rolls back.
4160 ** Statement subtransactions are used around individual SQL statements
4161 ** that are contained within a BEGIN...COMMIT block. If a constraint
4162 ** error occurs within the statement, the effect of that one statement
4163 ** can be rolled back without having to rollback the entire transaction.
4165 ** A statement sub-transaction is implemented as an anonymous savepoint. The
4166 ** value passed as the second parameter is the total number of savepoints,
4167 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
4168 ** are no active savepoints and no other statement-transactions open,
4169 ** iStatement is 1. This anonymous savepoint can be released or rolled back
4170 ** using the sqlite3BtreeSavepoint() function.
4172 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
4173 int rc;
4174 BtShared *pBt = p->pBt;
4175 sqlite3BtreeEnter(p);
4176 assert( p->inTrans==TRANS_WRITE );
4177 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
4178 assert( iStatement>0 );
4179 assert( iStatement>p->db->nSavepoint );
4180 assert( pBt->inTransaction==TRANS_WRITE );
4181 /* At the pager level, a statement transaction is a savepoint with
4182 ** an index greater than all savepoints created explicitly using
4183 ** SQL statements. It is illegal to open, release or rollback any
4184 ** such savepoints while the statement transaction savepoint is active.
4186 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
4187 sqlite3BtreeLeave(p);
4188 return rc;
4192 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
4193 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
4194 ** savepoint identified by parameter iSavepoint, depending on the value
4195 ** of op.
4197 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
4198 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
4199 ** contents of the entire transaction are rolled back. This is different
4200 ** from a normal transaction rollback, as no locks are released and the
4201 ** transaction remains open.
4203 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
4204 int rc = SQLITE_OK;
4205 if( p && p->inTrans==TRANS_WRITE ){
4206 BtShared *pBt = p->pBt;
4207 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
4208 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
4209 sqlite3BtreeEnter(p);
4210 if( op==SAVEPOINT_ROLLBACK ){
4211 rc = saveAllCursors(pBt, 0, 0);
4213 if( rc==SQLITE_OK ){
4214 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
4216 if( rc==SQLITE_OK ){
4217 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
4218 pBt->nPage = 0;
4220 rc = newDatabase(pBt);
4221 pBt->nPage = get4byte(28 + pBt->pPage1->aData);
4223 /* The database size was written into the offset 28 of the header
4224 ** when the transaction started, so we know that the value at offset
4225 ** 28 is nonzero. */
4226 assert( pBt->nPage>0 );
4228 sqlite3BtreeLeave(p);
4230 return rc;
4234 ** Create a new cursor for the BTree whose root is on the page
4235 ** iTable. If a read-only cursor is requested, it is assumed that
4236 ** the caller already has at least a read-only transaction open
4237 ** on the database already. If a write-cursor is requested, then
4238 ** the caller is assumed to have an open write transaction.
4240 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
4241 ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
4242 ** can be used for reading or for writing if other conditions for writing
4243 ** are also met. These are the conditions that must be met in order
4244 ** for writing to be allowed:
4246 ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
4248 ** 2: Other database connections that share the same pager cache
4249 ** but which are not in the READ_UNCOMMITTED state may not have
4250 ** cursors open with wrFlag==0 on the same table. Otherwise
4251 ** the changes made by this write cursor would be visible to
4252 ** the read cursors in the other database connection.
4254 ** 3: The database must be writable (not on read-only media)
4256 ** 4: There must be an active transaction.
4258 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
4259 ** is set. If FORDELETE is set, that is a hint to the implementation that
4260 ** this cursor will only be used to seek to and delete entries of an index
4261 ** as part of a larger DELETE statement. The FORDELETE hint is not used by
4262 ** this implementation. But in a hypothetical alternative storage engine
4263 ** in which index entries are automatically deleted when corresponding table
4264 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
4265 ** operations on this cursor can be no-ops and all READ operations can
4266 ** return a null row (2-bytes: 0x01 0x00).
4268 ** No checking is done to make sure that page iTable really is the
4269 ** root page of a b-tree. If it is not, then the cursor acquired
4270 ** will not work correctly.
4272 ** It is assumed that the sqlite3BtreeCursorZero() has been called
4273 ** on pCur to initialize the memory space prior to invoking this routine.
4275 static int btreeCursor(
4276 Btree *p, /* The btree */
4277 int iTable, /* Root page of table to open */
4278 int wrFlag, /* 1 to write. 0 read-only */
4279 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4280 BtCursor *pCur /* Space for new cursor */
4282 BtShared *pBt = p->pBt; /* Shared b-tree handle */
4283 BtCursor *pX; /* Looping over other all cursors */
4285 assert( sqlite3BtreeHoldsMutex(p) );
4286 assert( wrFlag==0
4287 || wrFlag==BTREE_WRCSR
4288 || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
4291 /* The following assert statements verify that if this is a sharable
4292 ** b-tree database, the connection is holding the required table locks,
4293 ** and that no other connection has any open cursor that conflicts with
4294 ** this lock. */
4295 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
4296 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
4298 /* Assert that the caller has opened the required transaction. */
4299 assert( p->inTrans>TRANS_NONE );
4300 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
4301 assert( pBt->pPage1 && pBt->pPage1->aData );
4302 assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
4304 if( wrFlag ){
4305 allocateTempSpace(pBt);
4306 if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
4308 if( iTable==1 && btreePagecount(pBt)==0 ){
4309 assert( wrFlag==0 );
4310 iTable = 0;
4313 /* Now that no other errors can occur, finish filling in the BtCursor
4314 ** variables and link the cursor into the BtShared list. */
4315 pCur->pgnoRoot = (Pgno)iTable;
4316 pCur->iPage = -1;
4317 pCur->pKeyInfo = pKeyInfo;
4318 pCur->pBtree = p;
4319 pCur->pBt = pBt;
4320 pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
4321 pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
4322 /* If there are two or more cursors on the same btree, then all such
4323 ** cursors *must* have the BTCF_Multiple flag set. */
4324 for(pX=pBt->pCursor; pX; pX=pX->pNext){
4325 if( pX->pgnoRoot==(Pgno)iTable ){
4326 pX->curFlags |= BTCF_Multiple;
4327 pCur->curFlags |= BTCF_Multiple;
4330 pCur->pNext = pBt->pCursor;
4331 pBt->pCursor = pCur;
4332 pCur->eState = CURSOR_INVALID;
4333 return SQLITE_OK;
4335 int sqlite3BtreeCursor(
4336 Btree *p, /* The btree */
4337 int iTable, /* Root page of table to open */
4338 int wrFlag, /* 1 to write. 0 read-only */
4339 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
4340 BtCursor *pCur /* Write new cursor here */
4342 int rc;
4343 if( iTable<1 ){
4344 rc = SQLITE_CORRUPT_BKPT;
4345 }else{
4346 sqlite3BtreeEnter(p);
4347 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4348 sqlite3BtreeLeave(p);
4350 return rc;
4354 ** Return the size of a BtCursor object in bytes.
4356 ** This interfaces is needed so that users of cursors can preallocate
4357 ** sufficient storage to hold a cursor. The BtCursor object is opaque
4358 ** to users so they cannot do the sizeof() themselves - they must call
4359 ** this routine.
4361 int sqlite3BtreeCursorSize(void){
4362 return ROUND8(sizeof(BtCursor));
4366 ** Initialize memory that will be converted into a BtCursor object.
4368 ** The simple approach here would be to memset() the entire object
4369 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
4370 ** do not need to be zeroed and they are large, so we can save a lot
4371 ** of run-time by skipping the initialization of those elements.
4373 void sqlite3BtreeCursorZero(BtCursor *p){
4374 memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
4378 ** Close a cursor. The read lock on the database file is released
4379 ** when the last cursor is closed.
4381 int sqlite3BtreeCloseCursor(BtCursor *pCur){
4382 Btree *pBtree = pCur->pBtree;
4383 if( pBtree ){
4384 BtShared *pBt = pCur->pBt;
4385 sqlite3BtreeEnter(pBtree);
4386 assert( pBt->pCursor!=0 );
4387 if( pBt->pCursor==pCur ){
4388 pBt->pCursor = pCur->pNext;
4389 }else{
4390 BtCursor *pPrev = pBt->pCursor;
4392 if( pPrev->pNext==pCur ){
4393 pPrev->pNext = pCur->pNext;
4394 break;
4396 pPrev = pPrev->pNext;
4397 }while( ALWAYS(pPrev) );
4399 btreeReleaseAllCursorPages(pCur);
4400 unlockBtreeIfUnused(pBt);
4401 sqlite3_free(pCur->aOverflow);
4402 sqlite3_free(pCur->pKey);
4403 sqlite3BtreeLeave(pBtree);
4405 return SQLITE_OK;
4409 ** Make sure the BtCursor* given in the argument has a valid
4410 ** BtCursor.info structure. If it is not already valid, call
4411 ** btreeParseCell() to fill it in.
4413 ** BtCursor.info is a cache of the information in the current cell.
4414 ** Using this cache reduces the number of calls to btreeParseCell().
4416 #ifndef NDEBUG
4417 static int cellInfoEqual(CellInfo *a, CellInfo *b){
4418 if( a->nKey!=b->nKey ) return 0;
4419 if( a->pPayload!=b->pPayload ) return 0;
4420 if( a->nPayload!=b->nPayload ) return 0;
4421 if( a->nLocal!=b->nLocal ) return 0;
4422 if( a->nSize!=b->nSize ) return 0;
4423 return 1;
4425 static void assertCellInfo(BtCursor *pCur){
4426 CellInfo info;
4427 memset(&info, 0, sizeof(info));
4428 btreeParseCell(pCur->pPage, pCur->ix, &info);
4429 assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
4431 #else
4432 #define assertCellInfo(x)
4433 #endif
4434 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
4435 if( pCur->info.nSize==0 ){
4436 pCur->curFlags |= BTCF_ValidNKey;
4437 btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
4438 }else{
4439 assertCellInfo(pCur);
4443 #ifndef NDEBUG /* The next routine used only within assert() statements */
4445 ** Return true if the given BtCursor is valid. A valid cursor is one
4446 ** that is currently pointing to a row in a (non-empty) table.
4447 ** This is a verification routine is used only within assert() statements.
4449 int sqlite3BtreeCursorIsValid(BtCursor *pCur){
4450 return pCur && pCur->eState==CURSOR_VALID;
4452 #endif /* NDEBUG */
4453 int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
4454 assert( pCur!=0 );
4455 return pCur->eState==CURSOR_VALID;
4459 ** Return the value of the integer key or "rowid" for a table btree.
4460 ** This routine is only valid for a cursor that is pointing into a
4461 ** ordinary table btree. If the cursor points to an index btree or
4462 ** is invalid, the result of this routine is undefined.
4464 i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
4465 assert( cursorHoldsMutex(pCur) );
4466 assert( pCur->eState==CURSOR_VALID );
4467 assert( pCur->curIntKey );
4468 getCellInfo(pCur);
4469 return pCur->info.nKey;
4472 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4474 ** Return the offset into the database file for the start of the
4475 ** payload to which the cursor is pointing.
4477 i64 sqlite3BtreeOffset(BtCursor *pCur){
4478 assert( cursorHoldsMutex(pCur) );
4479 assert( pCur->eState==CURSOR_VALID );
4480 getCellInfo(pCur);
4481 return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
4482 (i64)(pCur->info.pPayload - pCur->pPage->aData);
4484 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
4487 ** Return the number of bytes of payload for the entry that pCur is
4488 ** currently pointing to. For table btrees, this will be the amount
4489 ** of data. For index btrees, this will be the size of the key.
4491 ** The caller must guarantee that the cursor is pointing to a non-NULL
4492 ** valid entry. In other words, the calling procedure must guarantee
4493 ** that the cursor has Cursor.eState==CURSOR_VALID.
4495 u32 sqlite3BtreePayloadSize(BtCursor *pCur){
4496 assert( cursorHoldsMutex(pCur) );
4497 assert( pCur->eState==CURSOR_VALID );
4498 getCellInfo(pCur);
4499 return pCur->info.nPayload;
4503 ** Given the page number of an overflow page in the database (parameter
4504 ** ovfl), this function finds the page number of the next page in the
4505 ** linked list of overflow pages. If possible, it uses the auto-vacuum
4506 ** pointer-map data instead of reading the content of page ovfl to do so.
4508 ** If an error occurs an SQLite error code is returned. Otherwise:
4510 ** The page number of the next overflow page in the linked list is
4511 ** written to *pPgnoNext. If page ovfl is the last page in its linked
4512 ** list, *pPgnoNext is set to zero.
4514 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
4515 ** to page number pOvfl was obtained, then *ppPage is set to point to that
4516 ** reference. It is the responsibility of the caller to call releasePage()
4517 ** on *ppPage to free the reference. In no reference was obtained (because
4518 ** the pointer-map was used to obtain the value for *pPgnoNext), then
4519 ** *ppPage is set to zero.
4521 static int getOverflowPage(
4522 BtShared *pBt, /* The database file */
4523 Pgno ovfl, /* Current overflow page number */
4524 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
4525 Pgno *pPgnoNext /* OUT: Next overflow page number */
4527 Pgno next = 0;
4528 MemPage *pPage = 0;
4529 int rc = SQLITE_OK;
4531 assert( sqlite3_mutex_held(pBt->mutex) );
4532 assert(pPgnoNext);
4534 #ifndef SQLITE_OMIT_AUTOVACUUM
4535 /* Try to find the next page in the overflow list using the
4536 ** autovacuum pointer-map pages. Guess that the next page in
4537 ** the overflow list is page number (ovfl+1). If that guess turns
4538 ** out to be wrong, fall back to loading the data of page
4539 ** number ovfl to determine the next page number.
4541 if( pBt->autoVacuum ){
4542 Pgno pgno;
4543 Pgno iGuess = ovfl+1;
4544 u8 eType;
4546 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
4547 iGuess++;
4550 if( iGuess<=btreePagecount(pBt) ){
4551 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
4552 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
4553 next = iGuess;
4554 rc = SQLITE_DONE;
4558 #endif
4560 assert( next==0 || rc==SQLITE_DONE );
4561 if( rc==SQLITE_OK ){
4562 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
4563 assert( rc==SQLITE_OK || pPage==0 );
4564 if( rc==SQLITE_OK ){
4565 next = get4byte(pPage->aData);
4569 *pPgnoNext = next;
4570 if( ppPage ){
4571 *ppPage = pPage;
4572 }else{
4573 releasePage(pPage);
4575 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
4579 ** Copy data from a buffer to a page, or from a page to a buffer.
4581 ** pPayload is a pointer to data stored on database page pDbPage.
4582 ** If argument eOp is false, then nByte bytes of data are copied
4583 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4584 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4585 ** of data are copied from the buffer pBuf to pPayload.
4587 ** SQLITE_OK is returned on success, otherwise an error code.
4589 static int copyPayload(
4590 void *pPayload, /* Pointer to page data */
4591 void *pBuf, /* Pointer to buffer */
4592 int nByte, /* Number of bytes to copy */
4593 int eOp, /* 0 -> copy from page, 1 -> copy to page */
4594 DbPage *pDbPage /* Page containing pPayload */
4596 if( eOp ){
4597 /* Copy data from buffer to page (a write operation) */
4598 int rc = sqlite3PagerWrite(pDbPage);
4599 if( rc!=SQLITE_OK ){
4600 return rc;
4602 memcpy(pPayload, pBuf, nByte);
4603 }else{
4604 /* Copy data from page to buffer (a read operation) */
4605 memcpy(pBuf, pPayload, nByte);
4607 return SQLITE_OK;
4611 ** This function is used to read or overwrite payload information
4612 ** for the entry that the pCur cursor is pointing to. The eOp
4613 ** argument is interpreted as follows:
4615 ** 0: The operation is a read. Populate the overflow cache.
4616 ** 1: The operation is a write. Populate the overflow cache.
4618 ** A total of "amt" bytes are read or written beginning at "offset".
4619 ** Data is read to or from the buffer pBuf.
4621 ** The content being read or written might appear on the main page
4622 ** or be scattered out on multiple overflow pages.
4624 ** If the current cursor entry uses one or more overflow pages
4625 ** this function may allocate space for and lazily populate
4626 ** the overflow page-list cache array (BtCursor.aOverflow).
4627 ** Subsequent calls use this cache to make seeking to the supplied offset
4628 ** more efficient.
4630 ** Once an overflow page-list cache has been allocated, it must be
4631 ** invalidated if some other cursor writes to the same table, or if
4632 ** the cursor is moved to a different row. Additionally, in auto-vacuum
4633 ** mode, the following events may invalidate an overflow page-list cache.
4635 ** * An incremental vacuum,
4636 ** * A commit in auto_vacuum="full" mode,
4637 ** * Creating a table (may require moving an overflow page).
4639 static int accessPayload(
4640 BtCursor *pCur, /* Cursor pointing to entry to read from */
4641 u32 offset, /* Begin reading this far into payload */
4642 u32 amt, /* Read this many bytes */
4643 unsigned char *pBuf, /* Write the bytes into this buffer */
4644 int eOp /* zero to read. non-zero to write. */
4646 unsigned char *aPayload;
4647 int rc = SQLITE_OK;
4648 int iIdx = 0;
4649 MemPage *pPage = pCur->pPage; /* Btree page of current entry */
4650 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
4651 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4652 unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
4653 #endif
4655 assert( pPage );
4656 assert( eOp==0 || eOp==1 );
4657 assert( pCur->eState==CURSOR_VALID );
4658 assert( pCur->ix<pPage->nCell );
4659 assert( cursorHoldsMutex(pCur) );
4661 getCellInfo(pCur);
4662 aPayload = pCur->info.pPayload;
4663 assert( offset+amt <= pCur->info.nPayload );
4665 assert( aPayload > pPage->aData );
4666 if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
4667 /* Trying to read or write past the end of the data is an error. The
4668 ** conditional above is really:
4669 ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
4670 ** but is recast into its current form to avoid integer overflow problems
4672 return SQLITE_CORRUPT_PAGE(pPage);
4675 /* Check if data must be read/written to/from the btree page itself. */
4676 if( offset<pCur->info.nLocal ){
4677 int a = amt;
4678 if( a+offset>pCur->info.nLocal ){
4679 a = pCur->info.nLocal - offset;
4681 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
4682 offset = 0;
4683 pBuf += a;
4684 amt -= a;
4685 }else{
4686 offset -= pCur->info.nLocal;
4690 if( rc==SQLITE_OK && amt>0 ){
4691 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
4692 Pgno nextPage;
4694 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
4696 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
4698 ** The aOverflow[] array is sized at one entry for each overflow page
4699 ** in the overflow chain. The page number of the first overflow page is
4700 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
4701 ** means "not yet known" (the cache is lazily populated).
4703 if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
4704 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
4705 if( pCur->aOverflow==0
4706 || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
4708 Pgno *aNew = (Pgno*)sqlite3Realloc(
4709 pCur->aOverflow, nOvfl*2*sizeof(Pgno)
4711 if( aNew==0 ){
4712 return SQLITE_NOMEM_BKPT;
4713 }else{
4714 pCur->aOverflow = aNew;
4717 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
4718 pCur->curFlags |= BTCF_ValidOvfl;
4719 }else{
4720 /* If the overflow page-list cache has been allocated and the
4721 ** entry for the first required overflow page is valid, skip
4722 ** directly to it.
4724 if( pCur->aOverflow[offset/ovflSize] ){
4725 iIdx = (offset/ovflSize);
4726 nextPage = pCur->aOverflow[iIdx];
4727 offset = (offset%ovflSize);
4731 assert( rc==SQLITE_OK && amt>0 );
4732 while( nextPage ){
4733 /* If required, populate the overflow page-list cache. */
4734 assert( pCur->aOverflow[iIdx]==0
4735 || pCur->aOverflow[iIdx]==nextPage
4736 || CORRUPT_DB );
4737 pCur->aOverflow[iIdx] = nextPage;
4739 if( offset>=ovflSize ){
4740 /* The only reason to read this page is to obtain the page
4741 ** number for the next page in the overflow chain. The page
4742 ** data is not required. So first try to lookup the overflow
4743 ** page-list cache, if any, then fall back to the getOverflowPage()
4744 ** function.
4746 assert( pCur->curFlags & BTCF_ValidOvfl );
4747 assert( pCur->pBtree->db==pBt->db );
4748 if( pCur->aOverflow[iIdx+1] ){
4749 nextPage = pCur->aOverflow[iIdx+1];
4750 }else{
4751 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
4753 offset -= ovflSize;
4754 }else{
4755 /* Need to read this page properly. It contains some of the
4756 ** range of data that is being read (eOp==0) or written (eOp!=0).
4758 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4759 sqlite3_file *fd; /* File from which to do direct overflow read */
4760 #endif
4761 int a = amt;
4762 if( a + offset > ovflSize ){
4763 a = ovflSize - offset;
4766 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4767 /* If all the following are true:
4769 ** 1) this is a read operation, and
4770 ** 2) data is required from the start of this overflow page, and
4771 ** 3) there is no open write-transaction, and
4772 ** 4) the database is file-backed, and
4773 ** 5) the page is not in the WAL file
4774 ** 6) at least 4 bytes have already been read into the output buffer
4776 ** then data can be read directly from the database file into the
4777 ** output buffer, bypassing the page-cache altogether. This speeds
4778 ** up loading large records that span many overflow pages.
4780 if( eOp==0 /* (1) */
4781 && offset==0 /* (2) */
4782 && pBt->inTransaction==TRANS_READ /* (3) */
4783 && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (4) */
4784 && 0==sqlite3PagerUseWal(pBt->pPager, nextPage) /* (5) */
4785 && &pBuf[-4]>=pBufStart /* (6) */
4787 u8 aSave[4];
4788 u8 *aWrite = &pBuf[-4];
4789 assert( aWrite>=pBufStart ); /* due to (6) */
4790 memcpy(aSave, aWrite, 4);
4791 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
4792 nextPage = get4byte(aWrite);
4793 memcpy(aWrite, aSave, 4);
4794 }else
4795 #endif
4798 DbPage *pDbPage;
4799 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
4800 (eOp==0 ? PAGER_GET_READONLY : 0)
4802 if( rc==SQLITE_OK ){
4803 aPayload = sqlite3PagerGetData(pDbPage);
4804 nextPage = get4byte(aPayload);
4805 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
4806 sqlite3PagerUnref(pDbPage);
4807 offset = 0;
4810 amt -= a;
4811 if( amt==0 ) return rc;
4812 pBuf += a;
4814 if( rc ) break;
4815 iIdx++;
4819 if( rc==SQLITE_OK && amt>0 ){
4820 /* Overflow chain ends prematurely */
4821 return SQLITE_CORRUPT_PAGE(pPage);
4823 return rc;
4827 ** Read part of the payload for the row at which that cursor pCur is currently
4828 ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
4829 ** begins at "offset".
4831 ** pCur can be pointing to either a table or an index b-tree.
4832 ** If pointing to a table btree, then the content section is read. If
4833 ** pCur is pointing to an index b-tree then the key section is read.
4835 ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
4836 ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
4837 ** cursor might be invalid or might need to be restored before being read.
4839 ** Return SQLITE_OK on success or an error code if anything goes
4840 ** wrong. An error is returned if "offset+amt" is larger than
4841 ** the available payload.
4843 int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
4844 assert( cursorHoldsMutex(pCur) );
4845 assert( pCur->eState==CURSOR_VALID );
4846 assert( pCur->iPage>=0 && pCur->pPage );
4847 assert( pCur->ix<pCur->pPage->nCell );
4848 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
4852 ** This variant of sqlite3BtreePayload() works even if the cursor has not
4853 ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
4854 ** interface.
4856 #ifndef SQLITE_OMIT_INCRBLOB
4857 static SQLITE_NOINLINE int accessPayloadChecked(
4858 BtCursor *pCur,
4859 u32 offset,
4860 u32 amt,
4861 void *pBuf
4863 int rc;
4864 if ( pCur->eState==CURSOR_INVALID ){
4865 return SQLITE_ABORT;
4867 assert( cursorOwnsBtShared(pCur) );
4868 rc = btreeRestoreCursorPosition(pCur);
4869 return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
4871 int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
4872 if( pCur->eState==CURSOR_VALID ){
4873 assert( cursorOwnsBtShared(pCur) );
4874 return accessPayload(pCur, offset, amt, pBuf, 0);
4875 }else{
4876 return accessPayloadChecked(pCur, offset, amt, pBuf);
4879 #endif /* SQLITE_OMIT_INCRBLOB */
4882 ** Return a pointer to payload information from the entry that the
4883 ** pCur cursor is pointing to. The pointer is to the beginning of
4884 ** the key if index btrees (pPage->intKey==0) and is the data for
4885 ** table btrees (pPage->intKey==1). The number of bytes of available
4886 ** key/data is written into *pAmt. If *pAmt==0, then the value
4887 ** returned will not be a valid pointer.
4889 ** This routine is an optimization. It is common for the entire key
4890 ** and data to fit on the local page and for there to be no overflow
4891 ** pages. When that is so, this routine can be used to access the
4892 ** key and data without making a copy. If the key and/or data spills
4893 ** onto overflow pages, then accessPayload() must be used to reassemble
4894 ** the key/data and copy it into a preallocated buffer.
4896 ** The pointer returned by this routine looks directly into the cached
4897 ** page of the database. The data might change or move the next time
4898 ** any btree routine is called.
4900 static const void *fetchPayload(
4901 BtCursor *pCur, /* Cursor pointing to entry to read from */
4902 u32 *pAmt /* Write the number of available bytes here */
4904 int amt;
4905 assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
4906 assert( pCur->eState==CURSOR_VALID );
4907 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
4908 assert( cursorOwnsBtShared(pCur) );
4909 assert( pCur->ix<pCur->pPage->nCell );
4910 assert( pCur->info.nSize>0 );
4911 assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
4912 assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
4913 amt = pCur->info.nLocal;
4914 if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
4915 /* There is too little space on the page for the expected amount
4916 ** of local content. Database must be corrupt. */
4917 assert( CORRUPT_DB );
4918 amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
4920 *pAmt = (u32)amt;
4921 return (void*)pCur->info.pPayload;
4926 ** For the entry that cursor pCur is point to, return as
4927 ** many bytes of the key or data as are available on the local
4928 ** b-tree page. Write the number of available bytes into *pAmt.
4930 ** The pointer returned is ephemeral. The key/data may move
4931 ** or be destroyed on the next call to any Btree routine,
4932 ** including calls from other threads against the same cache.
4933 ** Hence, a mutex on the BtShared should be held prior to calling
4934 ** this routine.
4936 ** These routines is used to get quick access to key and data
4937 ** in the common case where no overflow pages are used.
4939 const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
4940 return fetchPayload(pCur, pAmt);
4945 ** Move the cursor down to a new child page. The newPgno argument is the
4946 ** page number of the child page to move to.
4948 ** This function returns SQLITE_CORRUPT if the page-header flags field of
4949 ** the new child page does not match the flags field of the parent (i.e.
4950 ** if an intkey page appears to be the parent of a non-intkey page, or
4951 ** vice-versa).
4953 static int moveToChild(BtCursor *pCur, u32 newPgno){
4954 BtShared *pBt = pCur->pBt;
4956 assert( cursorOwnsBtShared(pCur) );
4957 assert( pCur->eState==CURSOR_VALID );
4958 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
4959 assert( pCur->iPage>=0 );
4960 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
4961 return SQLITE_CORRUPT_BKPT;
4963 pCur->info.nSize = 0;
4964 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
4965 pCur->aiIdx[pCur->iPage] = pCur->ix;
4966 pCur->apPage[pCur->iPage] = pCur->pPage;
4967 pCur->ix = 0;
4968 pCur->iPage++;
4969 return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
4972 #ifdef SQLITE_DEBUG
4974 ** Page pParent is an internal (non-leaf) tree page. This function
4975 ** asserts that page number iChild is the left-child if the iIdx'th
4976 ** cell in page pParent. Or, if iIdx is equal to the total number of
4977 ** cells in pParent, that page number iChild is the right-child of
4978 ** the page.
4980 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
4981 if( CORRUPT_DB ) return; /* The conditions tested below might not be true
4982 ** in a corrupt database */
4983 assert( iIdx<=pParent->nCell );
4984 if( iIdx==pParent->nCell ){
4985 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
4986 }else{
4987 assert( get4byte(findCell(pParent, iIdx))==iChild );
4990 #else
4991 # define assertParentIndex(x,y,z)
4992 #endif
4995 ** Move the cursor up to the parent page.
4997 ** pCur->idx is set to the cell index that contains the pointer
4998 ** to the page we are coming from. If we are coming from the
4999 ** right-most child page then pCur->idx is set to one more than
5000 ** the largest cell index.
5002 static void moveToParent(BtCursor *pCur){
5003 MemPage *pLeaf;
5004 assert( cursorOwnsBtShared(pCur) );
5005 assert( pCur->eState==CURSOR_VALID );
5006 assert( pCur->iPage>0 );
5007 assert( pCur->pPage );
5008 assertParentIndex(
5009 pCur->apPage[pCur->iPage-1],
5010 pCur->aiIdx[pCur->iPage-1],
5011 pCur->pPage->pgno
5013 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
5014 pCur->info.nSize = 0;
5015 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5016 pCur->ix = pCur->aiIdx[pCur->iPage-1];
5017 pLeaf = pCur->pPage;
5018 pCur->pPage = pCur->apPage[--pCur->iPage];
5019 releasePageNotNull(pLeaf);
5023 ** Move the cursor to point to the root page of its b-tree structure.
5025 ** If the table has a virtual root page, then the cursor is moved to point
5026 ** to the virtual root page instead of the actual root page. A table has a
5027 ** virtual root page when the actual root page contains no cells and a
5028 ** single child page. This can only happen with the table rooted at page 1.
5030 ** If the b-tree structure is empty, the cursor state is set to
5031 ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
5032 ** the cursor is set to point to the first cell located on the root
5033 ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
5035 ** If this function returns successfully, it may be assumed that the
5036 ** page-header flags indicate that the [virtual] root-page is the expected
5037 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
5038 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
5039 ** indicating a table b-tree, or if the caller did specify a KeyInfo
5040 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
5041 ** b-tree).
5043 static int moveToRoot(BtCursor *pCur){
5044 MemPage *pRoot;
5045 int rc = SQLITE_OK;
5047 assert( cursorOwnsBtShared(pCur) );
5048 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
5049 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
5050 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
5051 assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
5052 assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
5054 if( pCur->iPage>=0 ){
5055 if( pCur->iPage ){
5056 releasePageNotNull(pCur->pPage);
5057 while( --pCur->iPage ){
5058 releasePageNotNull(pCur->apPage[pCur->iPage]);
5060 pCur->pPage = pCur->apPage[0];
5061 goto skip_init;
5063 }else if( pCur->pgnoRoot==0 ){
5064 pCur->eState = CURSOR_INVALID;
5065 return SQLITE_EMPTY;
5066 }else{
5067 assert( pCur->iPage==(-1) );
5068 if( pCur->eState>=CURSOR_REQUIRESEEK ){
5069 if( pCur->eState==CURSOR_FAULT ){
5070 assert( pCur->skipNext!=SQLITE_OK );
5071 return pCur->skipNext;
5073 sqlite3BtreeClearCursor(pCur);
5075 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
5076 0, pCur->curPagerFlags);
5077 if( rc!=SQLITE_OK ){
5078 pCur->eState = CURSOR_INVALID;
5079 return rc;
5081 pCur->iPage = 0;
5082 pCur->curIntKey = pCur->pPage->intKey;
5084 pRoot = pCur->pPage;
5085 assert( pRoot->pgno==pCur->pgnoRoot );
5087 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
5088 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
5089 ** NULL, the caller expects a table b-tree. If this is not the case,
5090 ** return an SQLITE_CORRUPT error.
5092 ** Earlier versions of SQLite assumed that this test could not fail
5093 ** if the root page was already loaded when this function was called (i.e.
5094 ** if pCur->iPage>=0). But this is not so if the database is corrupted
5095 ** in such a way that page pRoot is linked into a second b-tree table
5096 ** (or the freelist). */
5097 assert( pRoot->intKey==1 || pRoot->intKey==0 );
5098 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
5099 return SQLITE_CORRUPT_PAGE(pCur->pPage);
5102 skip_init:
5103 pCur->ix = 0;
5104 pCur->info.nSize = 0;
5105 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
5107 pRoot = pCur->pPage;
5108 if( pRoot->nCell>0 ){
5109 pCur->eState = CURSOR_VALID;
5110 }else if( !pRoot->leaf ){
5111 Pgno subpage;
5112 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
5113 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
5114 pCur->eState = CURSOR_VALID;
5115 rc = moveToChild(pCur, subpage);
5116 }else{
5117 pCur->eState = CURSOR_INVALID;
5118 rc = SQLITE_EMPTY;
5120 return rc;
5124 ** Move the cursor down to the left-most leaf entry beneath the
5125 ** entry to which it is currently pointing.
5127 ** The left-most leaf is the one with the smallest key - the first
5128 ** in ascending order.
5130 static int moveToLeftmost(BtCursor *pCur){
5131 Pgno pgno;
5132 int rc = SQLITE_OK;
5133 MemPage *pPage;
5135 assert( cursorOwnsBtShared(pCur) );
5136 assert( pCur->eState==CURSOR_VALID );
5137 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
5138 assert( pCur->ix<pPage->nCell );
5139 pgno = get4byte(findCell(pPage, pCur->ix));
5140 rc = moveToChild(pCur, pgno);
5142 return rc;
5146 ** Move the cursor down to the right-most leaf entry beneath the
5147 ** page to which it is currently pointing. Notice the difference
5148 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
5149 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
5150 ** finds the right-most entry beneath the *page*.
5152 ** The right-most entry is the one with the largest key - the last
5153 ** key in ascending order.
5155 static int moveToRightmost(BtCursor *pCur){
5156 Pgno pgno;
5157 int rc = SQLITE_OK;
5158 MemPage *pPage = 0;
5160 assert( cursorOwnsBtShared(pCur) );
5161 assert( pCur->eState==CURSOR_VALID );
5162 while( !(pPage = pCur->pPage)->leaf ){
5163 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5164 pCur->ix = pPage->nCell;
5165 rc = moveToChild(pCur, pgno);
5166 if( rc ) return rc;
5168 pCur->ix = pPage->nCell-1;
5169 assert( pCur->info.nSize==0 );
5170 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
5171 return SQLITE_OK;
5174 /* Move the cursor to the first entry in the table. Return SQLITE_OK
5175 ** on success. Set *pRes to 0 if the cursor actually points to something
5176 ** or set *pRes to 1 if the table is empty.
5178 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
5179 int rc;
5181 assert( cursorOwnsBtShared(pCur) );
5182 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5183 rc = moveToRoot(pCur);
5184 if( rc==SQLITE_OK ){
5185 assert( pCur->pPage->nCell>0 );
5186 *pRes = 0;
5187 rc = moveToLeftmost(pCur);
5188 }else if( rc==SQLITE_EMPTY ){
5189 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5190 *pRes = 1;
5191 rc = SQLITE_OK;
5193 return rc;
5197 ** This function is a no-op if cursor pCur does not point to a valid row.
5198 ** Otherwise, if pCur is valid, configure it so that the next call to
5199 ** sqlite3BtreeNext() is a no-op.
5201 #ifndef SQLITE_OMIT_WINDOWFUNC
5202 void sqlite3BtreeSkipNext(BtCursor *pCur){
5203 if( pCur->eState==CURSOR_VALID ){
5204 pCur->eState = CURSOR_SKIPNEXT;
5205 pCur->skipNext = 1;
5208 #endif /* SQLITE_OMIT_WINDOWFUNC */
5210 /* Move the cursor to the last entry in the table. Return SQLITE_OK
5211 ** on success. Set *pRes to 0 if the cursor actually points to something
5212 ** or set *pRes to 1 if the table is empty.
5214 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
5215 int rc;
5217 assert( cursorOwnsBtShared(pCur) );
5218 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5220 /* If the cursor already points to the last entry, this is a no-op. */
5221 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
5222 #ifdef SQLITE_DEBUG
5223 /* This block serves to assert() that the cursor really does point
5224 ** to the last entry in the b-tree. */
5225 int ii;
5226 for(ii=0; ii<pCur->iPage; ii++){
5227 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
5229 assert( pCur->ix==pCur->pPage->nCell-1 );
5230 assert( pCur->pPage->leaf );
5231 #endif
5232 return SQLITE_OK;
5235 rc = moveToRoot(pCur);
5236 if( rc==SQLITE_OK ){
5237 assert( pCur->eState==CURSOR_VALID );
5238 *pRes = 0;
5239 rc = moveToRightmost(pCur);
5240 if( rc==SQLITE_OK ){
5241 pCur->curFlags |= BTCF_AtLast;
5242 }else{
5243 pCur->curFlags &= ~BTCF_AtLast;
5245 }else if( rc==SQLITE_EMPTY ){
5246 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5247 *pRes = 1;
5248 rc = SQLITE_OK;
5250 return rc;
5253 /* Move the cursor so that it points to an entry near the key
5254 ** specified by pIdxKey or intKey. Return a success code.
5256 ** For INTKEY tables, the intKey parameter is used. pIdxKey
5257 ** must be NULL. For index tables, pIdxKey is used and intKey
5258 ** is ignored.
5260 ** If an exact match is not found, then the cursor is always
5261 ** left pointing at a leaf page which would hold the entry if it
5262 ** were present. The cursor might point to an entry that comes
5263 ** before or after the key.
5265 ** An integer is written into *pRes which is the result of
5266 ** comparing the key with the entry to which the cursor is
5267 ** pointing. The meaning of the integer written into
5268 ** *pRes is as follows:
5270 ** *pRes<0 The cursor is left pointing at an entry that
5271 ** is smaller than intKey/pIdxKey or if the table is empty
5272 ** and the cursor is therefore left point to nothing.
5274 ** *pRes==0 The cursor is left pointing at an entry that
5275 ** exactly matches intKey/pIdxKey.
5277 ** *pRes>0 The cursor is left pointing at an entry that
5278 ** is larger than intKey/pIdxKey.
5280 ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
5281 ** exists an entry in the table that exactly matches pIdxKey.
5283 int sqlite3BtreeMovetoUnpacked(
5284 BtCursor *pCur, /* The cursor to be moved */
5285 UnpackedRecord *pIdxKey, /* Unpacked index key */
5286 i64 intKey, /* The table key */
5287 int biasRight, /* If true, bias the search to the high end */
5288 int *pRes /* Write search results here */
5290 int rc;
5291 RecordCompare xRecordCompare;
5293 assert( cursorOwnsBtShared(pCur) );
5294 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5295 assert( pRes );
5296 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
5297 assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
5299 /* If the cursor is already positioned at the point we are trying
5300 ** to move to, then just return without doing any work */
5301 if( pIdxKey==0
5302 && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
5304 if( pCur->info.nKey==intKey ){
5305 *pRes = 0;
5306 return SQLITE_OK;
5308 if( pCur->info.nKey<intKey ){
5309 if( (pCur->curFlags & BTCF_AtLast)!=0 ){
5310 *pRes = -1;
5311 return SQLITE_OK;
5313 /* If the requested key is one more than the previous key, then
5314 ** try to get there using sqlite3BtreeNext() rather than a full
5315 ** binary search. This is an optimization only. The correct answer
5316 ** is still obtained without this case, only a little more slowely */
5317 if( pCur->info.nKey+1==intKey && !pCur->skipNext ){
5318 *pRes = 0;
5319 rc = sqlite3BtreeNext(pCur, 0);
5320 if( rc==SQLITE_OK ){
5321 getCellInfo(pCur);
5322 if( pCur->info.nKey==intKey ){
5323 return SQLITE_OK;
5325 }else if( rc==SQLITE_DONE ){
5326 rc = SQLITE_OK;
5327 }else{
5328 return rc;
5334 if( pIdxKey ){
5335 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
5336 pIdxKey->errCode = 0;
5337 assert( pIdxKey->default_rc==1
5338 || pIdxKey->default_rc==0
5339 || pIdxKey->default_rc==-1
5341 }else{
5342 xRecordCompare = 0; /* All keys are integers */
5345 rc = moveToRoot(pCur);
5346 if( rc ){
5347 if( rc==SQLITE_EMPTY ){
5348 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5349 *pRes = -1;
5350 return SQLITE_OK;
5352 return rc;
5354 assert( pCur->pPage );
5355 assert( pCur->pPage->isInit );
5356 assert( pCur->eState==CURSOR_VALID );
5357 assert( pCur->pPage->nCell > 0 );
5358 assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
5359 assert( pCur->curIntKey || pIdxKey );
5360 for(;;){
5361 int lwr, upr, idx, c;
5362 Pgno chldPg;
5363 MemPage *pPage = pCur->pPage;
5364 u8 *pCell; /* Pointer to current cell in pPage */
5366 /* pPage->nCell must be greater than zero. If this is the root-page
5367 ** the cursor would have been INVALID above and this for(;;) loop
5368 ** not run. If this is not the root-page, then the moveToChild() routine
5369 ** would have already detected db corruption. Similarly, pPage must
5370 ** be the right kind (index or table) of b-tree page. Otherwise
5371 ** a moveToChild() or moveToRoot() call would have detected corruption. */
5372 assert( pPage->nCell>0 );
5373 assert( pPage->intKey==(pIdxKey==0) );
5374 lwr = 0;
5375 upr = pPage->nCell-1;
5376 assert( biasRight==0 || biasRight==1 );
5377 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
5378 pCur->ix = (u16)idx;
5379 if( xRecordCompare==0 ){
5380 for(;;){
5381 i64 nCellKey;
5382 pCell = findCellPastPtr(pPage, idx);
5383 if( pPage->intKeyLeaf ){
5384 while( 0x80 <= *(pCell++) ){
5385 if( pCell>=pPage->aDataEnd ){
5386 return SQLITE_CORRUPT_PAGE(pPage);
5390 getVarint(pCell, (u64*)&nCellKey);
5391 if( nCellKey<intKey ){
5392 lwr = idx+1;
5393 if( lwr>upr ){ c = -1; break; }
5394 }else if( nCellKey>intKey ){
5395 upr = idx-1;
5396 if( lwr>upr ){ c = +1; break; }
5397 }else{
5398 assert( nCellKey==intKey );
5399 pCur->ix = (u16)idx;
5400 if( !pPage->leaf ){
5401 lwr = idx;
5402 goto moveto_next_layer;
5403 }else{
5404 pCur->curFlags |= BTCF_ValidNKey;
5405 pCur->info.nKey = nCellKey;
5406 pCur->info.nSize = 0;
5407 *pRes = 0;
5408 return SQLITE_OK;
5411 assert( lwr+upr>=0 );
5412 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
5414 }else{
5415 for(;;){
5416 int nCell; /* Size of the pCell cell in bytes */
5417 pCell = findCellPastPtr(pPage, idx);
5419 /* The maximum supported page-size is 65536 bytes. This means that
5420 ** the maximum number of record bytes stored on an index B-Tree
5421 ** page is less than 16384 bytes and may be stored as a 2-byte
5422 ** varint. This information is used to attempt to avoid parsing
5423 ** the entire cell by checking for the cases where the record is
5424 ** stored entirely within the b-tree page by inspecting the first
5425 ** 2 bytes of the cell.
5427 nCell = pCell[0];
5428 if( nCell<=pPage->max1bytePayload ){
5429 /* This branch runs if the record-size field of the cell is a
5430 ** single byte varint and the record fits entirely on the main
5431 ** b-tree page. */
5432 testcase( pCell+nCell+1==pPage->aDataEnd );
5433 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
5434 }else if( !(pCell[1] & 0x80)
5435 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5437 /* The record-size field is a 2 byte varint and the record
5438 ** fits entirely on the main b-tree page. */
5439 testcase( pCell+nCell+2==pPage->aDataEnd );
5440 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
5441 }else{
5442 /* The record flows over onto one or more overflow pages. In
5443 ** this case the whole cell needs to be parsed, a buffer allocated
5444 ** and accessPayload() used to retrieve the record into the
5445 ** buffer before VdbeRecordCompare() can be called.
5447 ** If the record is corrupt, the xRecordCompare routine may read
5448 ** up to two varints past the end of the buffer. An extra 18
5449 ** bytes of padding is allocated at the end of the buffer in
5450 ** case this happens. */
5451 void *pCellKey;
5452 u8 * const pCellBody = pCell - pPage->childPtrSize;
5453 pPage->xParseCell(pPage, pCellBody, &pCur->info);
5454 nCell = (int)pCur->info.nKey;
5455 testcase( nCell<0 ); /* True if key size is 2^32 or more */
5456 testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
5457 testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
5458 testcase( nCell==2 ); /* Minimum legal index key size */
5459 if( nCell<2 ){
5460 rc = SQLITE_CORRUPT_PAGE(pPage);
5461 goto moveto_finish;
5463 pCellKey = sqlite3Malloc( nCell+18 );
5464 if( pCellKey==0 ){
5465 rc = SQLITE_NOMEM_BKPT;
5466 goto moveto_finish;
5468 pCur->ix = (u16)idx;
5469 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
5470 pCur->curFlags &= ~BTCF_ValidOvfl;
5471 if( rc ){
5472 sqlite3_free(pCellKey);
5473 goto moveto_finish;
5475 c = xRecordCompare(nCell, pCellKey, pIdxKey);
5476 sqlite3_free(pCellKey);
5478 assert(
5479 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
5480 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
5482 if( c<0 ){
5483 lwr = idx+1;
5484 }else if( c>0 ){
5485 upr = idx-1;
5486 }else{
5487 assert( c==0 );
5488 *pRes = 0;
5489 rc = SQLITE_OK;
5490 pCur->ix = (u16)idx;
5491 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
5492 goto moveto_finish;
5494 if( lwr>upr ) break;
5495 assert( lwr+upr>=0 );
5496 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
5499 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
5500 assert( pPage->isInit );
5501 if( pPage->leaf ){
5502 assert( pCur->ix<pCur->pPage->nCell );
5503 pCur->ix = (u16)idx;
5504 *pRes = c;
5505 rc = SQLITE_OK;
5506 goto moveto_finish;
5508 moveto_next_layer:
5509 if( lwr>=pPage->nCell ){
5510 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5511 }else{
5512 chldPg = get4byte(findCell(pPage, lwr));
5514 pCur->ix = (u16)lwr;
5515 rc = moveToChild(pCur, chldPg);
5516 if( rc ) break;
5518 moveto_finish:
5519 pCur->info.nSize = 0;
5520 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5521 return rc;
5526 ** Return TRUE if the cursor is not pointing at an entry of the table.
5528 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
5529 ** past the last entry in the table or sqlite3BtreePrev() moves past
5530 ** the first entry. TRUE is also returned if the table is empty.
5532 int sqlite3BtreeEof(BtCursor *pCur){
5533 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
5534 ** have been deleted? This API will need to change to return an error code
5535 ** as well as the boolean result value.
5537 return (CURSOR_VALID!=pCur->eState);
5541 ** Return an estimate for the number of rows in the table that pCur is
5542 ** pointing to. Return a negative number if no estimate is currently
5543 ** available.
5545 i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
5546 i64 n;
5547 u8 i;
5549 assert( cursorOwnsBtShared(pCur) );
5550 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5552 /* Currently this interface is only called by the OP_IfSmaller
5553 ** opcode, and it that case the cursor will always be valid and
5554 ** will always point to a leaf node. */
5555 if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
5556 if( NEVER(pCur->pPage->leaf==0) ) return -1;
5558 n = pCur->pPage->nCell;
5559 for(i=0; i<pCur->iPage; i++){
5560 n *= pCur->apPage[i]->nCell;
5562 return n;
5566 ** Advance the cursor to the next entry in the database.
5567 ** Return value:
5569 ** SQLITE_OK success
5570 ** SQLITE_DONE cursor is already pointing at the last element
5571 ** otherwise some kind of error occurred
5573 ** The main entry point is sqlite3BtreeNext(). That routine is optimized
5574 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
5575 ** to the next cell on the current page. The (slower) btreeNext() helper
5576 ** routine is called when it is necessary to move to a different page or
5577 ** to restore the cursor.
5579 ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
5580 ** cursor corresponds to an SQL index and this routine could have been
5581 ** skipped if the SQL index had been a unique index. The F argument
5582 ** is a hint to the implement. SQLite btree implementation does not use
5583 ** this hint, but COMDB2 does.
5585 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
5586 int rc;
5587 int idx;
5588 MemPage *pPage;
5590 assert( cursorOwnsBtShared(pCur) );
5591 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5592 if( pCur->eState!=CURSOR_VALID ){
5593 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5594 rc = restoreCursorPosition(pCur);
5595 if( rc!=SQLITE_OK ){
5596 return rc;
5598 if( CURSOR_INVALID==pCur->eState ){
5599 return SQLITE_DONE;
5601 if( pCur->skipNext ){
5602 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
5603 pCur->eState = CURSOR_VALID;
5604 if( pCur->skipNext>0 ){
5605 pCur->skipNext = 0;
5606 return SQLITE_OK;
5608 pCur->skipNext = 0;
5612 pPage = pCur->pPage;
5613 idx = ++pCur->ix;
5614 if( !pPage->isInit ){
5615 /* The only known way for this to happen is for there to be a
5616 ** recursive SQL function that does a DELETE operation as part of a
5617 ** SELECT which deletes content out from under an active cursor
5618 ** in a corrupt database file where the table being DELETE-ed from
5619 ** has pages in common with the table being queried. See TH3
5620 ** module cov1/btree78.test testcase 220 (2018-06-08) for an
5621 ** example. */
5622 return SQLITE_CORRUPT_BKPT;
5625 /* If the database file is corrupt, it is possible for the value of idx
5626 ** to be invalid here. This can only occur if a second cursor modifies
5627 ** the page while cursor pCur is holding a reference to it. Which can
5628 ** only happen if the database is corrupt in such a way as to link the
5629 ** page into more than one b-tree structure. */
5630 testcase( idx>pPage->nCell );
5632 if( idx>=pPage->nCell ){
5633 if( !pPage->leaf ){
5634 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
5635 if( rc ) return rc;
5636 return moveToLeftmost(pCur);
5639 if( pCur->iPage==0 ){
5640 pCur->eState = CURSOR_INVALID;
5641 return SQLITE_DONE;
5643 moveToParent(pCur);
5644 pPage = pCur->pPage;
5645 }while( pCur->ix>=pPage->nCell );
5646 if( pPage->intKey ){
5647 return sqlite3BtreeNext(pCur, 0);
5648 }else{
5649 return SQLITE_OK;
5652 if( pPage->leaf ){
5653 return SQLITE_OK;
5654 }else{
5655 return moveToLeftmost(pCur);
5658 int sqlite3BtreeNext(BtCursor *pCur, int flags){
5659 MemPage *pPage;
5660 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
5661 assert( cursorOwnsBtShared(pCur) );
5662 assert( flags==0 || flags==1 );
5663 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5664 pCur->info.nSize = 0;
5665 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5666 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
5667 pPage = pCur->pPage;
5668 if( (++pCur->ix)>=pPage->nCell ){
5669 pCur->ix--;
5670 return btreeNext(pCur);
5672 if( pPage->leaf ){
5673 return SQLITE_OK;
5674 }else{
5675 return moveToLeftmost(pCur);
5680 ** Step the cursor to the back to the previous entry in the database.
5681 ** Return values:
5683 ** SQLITE_OK success
5684 ** SQLITE_DONE the cursor is already on the first element of the table
5685 ** otherwise some kind of error occurred
5687 ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
5688 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
5689 ** to the previous cell on the current page. The (slower) btreePrevious()
5690 ** helper routine is called when it is necessary to move to a different page
5691 ** or to restore the cursor.
5693 ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
5694 ** the cursor corresponds to an SQL index and this routine could have been
5695 ** skipped if the SQL index had been a unique index. The F argument is a
5696 ** hint to the implement. The native SQLite btree implementation does not
5697 ** use this hint, but COMDB2 does.
5699 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
5700 int rc;
5701 MemPage *pPage;
5703 assert( cursorOwnsBtShared(pCur) );
5704 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5705 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
5706 assert( pCur->info.nSize==0 );
5707 if( pCur->eState!=CURSOR_VALID ){
5708 rc = restoreCursorPosition(pCur);
5709 if( rc!=SQLITE_OK ){
5710 return rc;
5712 if( CURSOR_INVALID==pCur->eState ){
5713 return SQLITE_DONE;
5715 if( pCur->skipNext ){
5716 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
5717 pCur->eState = CURSOR_VALID;
5718 if( pCur->skipNext<0 ){
5719 pCur->skipNext = 0;
5720 return SQLITE_OK;
5722 pCur->skipNext = 0;
5726 pPage = pCur->pPage;
5727 assert( pPage->isInit );
5728 if( !pPage->leaf ){
5729 int idx = pCur->ix;
5730 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
5731 if( rc ) return rc;
5732 rc = moveToRightmost(pCur);
5733 }else{
5734 while( pCur->ix==0 ){
5735 if( pCur->iPage==0 ){
5736 pCur->eState = CURSOR_INVALID;
5737 return SQLITE_DONE;
5739 moveToParent(pCur);
5741 assert( pCur->info.nSize==0 );
5742 assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
5744 pCur->ix--;
5745 pPage = pCur->pPage;
5746 if( pPage->intKey && !pPage->leaf ){
5747 rc = sqlite3BtreePrevious(pCur, 0);
5748 }else{
5749 rc = SQLITE_OK;
5752 return rc;
5754 int sqlite3BtreePrevious(BtCursor *pCur, int flags){
5755 assert( cursorOwnsBtShared(pCur) );
5756 assert( flags==0 || flags==1 );
5757 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5758 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
5759 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
5760 pCur->info.nSize = 0;
5761 if( pCur->eState!=CURSOR_VALID
5762 || pCur->ix==0
5763 || pCur->pPage->leaf==0
5765 return btreePrevious(pCur);
5767 pCur->ix--;
5768 return SQLITE_OK;
5772 ** Allocate a new page from the database file.
5774 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
5775 ** has already been called on the new page.) The new page has also
5776 ** been referenced and the calling routine is responsible for calling
5777 ** sqlite3PagerUnref() on the new page when it is done.
5779 ** SQLITE_OK is returned on success. Any other return value indicates
5780 ** an error. *ppPage is set to NULL in the event of an error.
5782 ** If the "nearby" parameter is not 0, then an effort is made to
5783 ** locate a page close to the page number "nearby". This can be used in an
5784 ** attempt to keep related pages close to each other in the database file,
5785 ** which in turn can make database access faster.
5787 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
5788 ** anywhere on the free-list, then it is guaranteed to be returned. If
5789 ** eMode is BTALLOC_LT then the page returned will be less than or equal
5790 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
5791 ** are no restrictions on which page is returned.
5793 static int allocateBtreePage(
5794 BtShared *pBt, /* The btree */
5795 MemPage **ppPage, /* Store pointer to the allocated page here */
5796 Pgno *pPgno, /* Store the page number here */
5797 Pgno nearby, /* Search for a page near this one */
5798 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
5800 MemPage *pPage1;
5801 int rc;
5802 u32 n; /* Number of pages on the freelist */
5803 u32 k; /* Number of leaves on the trunk of the freelist */
5804 MemPage *pTrunk = 0;
5805 MemPage *pPrevTrunk = 0;
5806 Pgno mxPage; /* Total size of the database file */
5808 assert( sqlite3_mutex_held(pBt->mutex) );
5809 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
5810 pPage1 = pBt->pPage1;
5811 mxPage = btreePagecount(pBt);
5812 /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
5813 ** stores stores the total number of pages on the freelist. */
5814 n = get4byte(&pPage1->aData[36]);
5815 testcase( n==mxPage-1 );
5816 if( n>=mxPage ){
5817 return SQLITE_CORRUPT_BKPT;
5819 if( n>0 ){
5820 /* There are pages on the freelist. Reuse one of those pages. */
5821 Pgno iTrunk;
5822 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
5823 u32 nSearch = 0; /* Count of the number of search attempts */
5825 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
5826 ** shows that the page 'nearby' is somewhere on the free-list, then
5827 ** the entire-list will be searched for that page.
5829 #ifndef SQLITE_OMIT_AUTOVACUUM
5830 if( eMode==BTALLOC_EXACT ){
5831 if( nearby<=mxPage ){
5832 u8 eType;
5833 assert( nearby>0 );
5834 assert( pBt->autoVacuum );
5835 rc = ptrmapGet(pBt, nearby, &eType, 0);
5836 if( rc ) return rc;
5837 if( eType==PTRMAP_FREEPAGE ){
5838 searchList = 1;
5841 }else if( eMode==BTALLOC_LE ){
5842 searchList = 1;
5844 #endif
5846 /* Decrement the free-list count by 1. Set iTrunk to the index of the
5847 ** first free-list trunk page. iPrevTrunk is initially 1.
5849 rc = sqlite3PagerWrite(pPage1->pDbPage);
5850 if( rc ) return rc;
5851 put4byte(&pPage1->aData[36], n-1);
5853 /* The code within this loop is run only once if the 'searchList' variable
5854 ** is not true. Otherwise, it runs once for each trunk-page on the
5855 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
5856 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
5858 do {
5859 pPrevTrunk = pTrunk;
5860 if( pPrevTrunk ){
5861 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
5862 ** is the page number of the next freelist trunk page in the list or
5863 ** zero if this is the last freelist trunk page. */
5864 iTrunk = get4byte(&pPrevTrunk->aData[0]);
5865 }else{
5866 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
5867 ** stores the page number of the first page of the freelist, or zero if
5868 ** the freelist is empty. */
5869 iTrunk = get4byte(&pPage1->aData[32]);
5871 testcase( iTrunk==mxPage );
5872 if( iTrunk>mxPage || nSearch++ > n ){
5873 rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
5874 }else{
5875 rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
5877 if( rc ){
5878 pTrunk = 0;
5879 goto end_allocate_page;
5881 assert( pTrunk!=0 );
5882 assert( pTrunk->aData!=0 );
5883 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
5884 ** is the number of leaf page pointers to follow. */
5885 k = get4byte(&pTrunk->aData[4]);
5886 if( k==0 && !searchList ){
5887 /* The trunk has no leaves and the list is not being searched.
5888 ** So extract the trunk page itself and use it as the newly
5889 ** allocated page */
5890 assert( pPrevTrunk==0 );
5891 rc = sqlite3PagerWrite(pTrunk->pDbPage);
5892 if( rc ){
5893 goto end_allocate_page;
5895 *pPgno = iTrunk;
5896 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5897 *ppPage = pTrunk;
5898 pTrunk = 0;
5899 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
5900 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
5901 /* Value of k is out of range. Database corruption */
5902 rc = SQLITE_CORRUPT_PGNO(iTrunk);
5903 goto end_allocate_page;
5904 #ifndef SQLITE_OMIT_AUTOVACUUM
5905 }else if( searchList
5906 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
5908 /* The list is being searched and this trunk page is the page
5909 ** to allocate, regardless of whether it has leaves.
5911 *pPgno = iTrunk;
5912 *ppPage = pTrunk;
5913 searchList = 0;
5914 rc = sqlite3PagerWrite(pTrunk->pDbPage);
5915 if( rc ){
5916 goto end_allocate_page;
5918 if( k==0 ){
5919 if( !pPrevTrunk ){
5920 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5921 }else{
5922 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
5923 if( rc!=SQLITE_OK ){
5924 goto end_allocate_page;
5926 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
5928 }else{
5929 /* The trunk page is required by the caller but it contains
5930 ** pointers to free-list leaves. The first leaf becomes a trunk
5931 ** page in this case.
5933 MemPage *pNewTrunk;
5934 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
5935 if( iNewTrunk>mxPage ){
5936 rc = SQLITE_CORRUPT_PGNO(iTrunk);
5937 goto end_allocate_page;
5939 testcase( iNewTrunk==mxPage );
5940 rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
5941 if( rc!=SQLITE_OK ){
5942 goto end_allocate_page;
5944 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
5945 if( rc!=SQLITE_OK ){
5946 releasePage(pNewTrunk);
5947 goto end_allocate_page;
5949 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
5950 put4byte(&pNewTrunk->aData[4], k-1);
5951 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
5952 releasePage(pNewTrunk);
5953 if( !pPrevTrunk ){
5954 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
5955 put4byte(&pPage1->aData[32], iNewTrunk);
5956 }else{
5957 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
5958 if( rc ){
5959 goto end_allocate_page;
5961 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
5964 pTrunk = 0;
5965 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
5966 #endif
5967 }else if( k>0 ){
5968 /* Extract a leaf from the trunk */
5969 u32 closest;
5970 Pgno iPage;
5971 unsigned char *aData = pTrunk->aData;
5972 if( nearby>0 ){
5973 u32 i;
5974 closest = 0;
5975 if( eMode==BTALLOC_LE ){
5976 for(i=0; i<k; i++){
5977 iPage = get4byte(&aData[8+i*4]);
5978 if( iPage<=nearby ){
5979 closest = i;
5980 break;
5983 }else{
5984 int dist;
5985 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
5986 for(i=1; i<k; i++){
5987 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
5988 if( d2<dist ){
5989 closest = i;
5990 dist = d2;
5994 }else{
5995 closest = 0;
5998 iPage = get4byte(&aData[8+closest*4]);
5999 testcase( iPage==mxPage );
6000 if( iPage>mxPage ){
6001 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6002 goto end_allocate_page;
6004 testcase( iPage==mxPage );
6005 if( !searchList
6006 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
6008 int noContent;
6009 *pPgno = iPage;
6010 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
6011 ": %d more free pages\n",
6012 *pPgno, closest+1, k, pTrunk->pgno, n-1));
6013 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6014 if( rc ) goto end_allocate_page;
6015 if( closest<k-1 ){
6016 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
6018 put4byte(&aData[4], k-1);
6019 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
6020 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
6021 if( rc==SQLITE_OK ){
6022 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6023 if( rc!=SQLITE_OK ){
6024 releasePage(*ppPage);
6025 *ppPage = 0;
6028 searchList = 0;
6031 releasePage(pPrevTrunk);
6032 pPrevTrunk = 0;
6033 }while( searchList );
6034 }else{
6035 /* There are no pages on the freelist, so append a new page to the
6036 ** database image.
6038 ** Normally, new pages allocated by this block can be requested from the
6039 ** pager layer with the 'no-content' flag set. This prevents the pager
6040 ** from trying to read the pages content from disk. However, if the
6041 ** current transaction has already run one or more incremental-vacuum
6042 ** steps, then the page we are about to allocate may contain content
6043 ** that is required in the event of a rollback. In this case, do
6044 ** not set the no-content flag. This causes the pager to load and journal
6045 ** the current page content before overwriting it.
6047 ** Note that the pager will not actually attempt to load or journal
6048 ** content for any page that really does lie past the end of the database
6049 ** file on disk. So the effects of disabling the no-content optimization
6050 ** here are confined to those pages that lie between the end of the
6051 ** database image and the end of the database file.
6053 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
6055 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6056 if( rc ) return rc;
6057 pBt->nPage++;
6058 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
6060 #ifndef SQLITE_OMIT_AUTOVACUUM
6061 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
6062 /* If *pPgno refers to a pointer-map page, allocate two new pages
6063 ** at the end of the file instead of one. The first allocated page
6064 ** becomes a new pointer-map page, the second is used by the caller.
6066 MemPage *pPg = 0;
6067 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
6068 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
6069 rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
6070 if( rc==SQLITE_OK ){
6071 rc = sqlite3PagerWrite(pPg->pDbPage);
6072 releasePage(pPg);
6074 if( rc ) return rc;
6075 pBt->nPage++;
6076 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
6078 #endif
6079 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
6080 *pPgno = pBt->nPage;
6082 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
6083 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
6084 if( rc ) return rc;
6085 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6086 if( rc!=SQLITE_OK ){
6087 releasePage(*ppPage);
6088 *ppPage = 0;
6090 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
6093 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
6095 end_allocate_page:
6096 releasePage(pTrunk);
6097 releasePage(pPrevTrunk);
6098 assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
6099 assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
6100 return rc;
6104 ** This function is used to add page iPage to the database file free-list.
6105 ** It is assumed that the page is not already a part of the free-list.
6107 ** The value passed as the second argument to this function is optional.
6108 ** If the caller happens to have a pointer to the MemPage object
6109 ** corresponding to page iPage handy, it may pass it as the second value.
6110 ** Otherwise, it may pass NULL.
6112 ** If a pointer to a MemPage object is passed as the second argument,
6113 ** its reference count is not altered by this function.
6115 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
6116 MemPage *pTrunk = 0; /* Free-list trunk page */
6117 Pgno iTrunk = 0; /* Page number of free-list trunk page */
6118 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
6119 MemPage *pPage; /* Page being freed. May be NULL. */
6120 int rc; /* Return Code */
6121 int nFree; /* Initial number of pages on free-list */
6123 assert( sqlite3_mutex_held(pBt->mutex) );
6124 assert( CORRUPT_DB || iPage>1 );
6125 assert( !pMemPage || pMemPage->pgno==iPage );
6127 if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
6128 if( pMemPage ){
6129 pPage = pMemPage;
6130 sqlite3PagerRef(pPage->pDbPage);
6131 }else{
6132 pPage = btreePageLookup(pBt, iPage);
6135 /* Increment the free page count on pPage1 */
6136 rc = sqlite3PagerWrite(pPage1->pDbPage);
6137 if( rc ) goto freepage_out;
6138 nFree = get4byte(&pPage1->aData[36]);
6139 put4byte(&pPage1->aData[36], nFree+1);
6141 if( pBt->btsFlags & BTS_SECURE_DELETE ){
6142 /* If the secure_delete option is enabled, then
6143 ** always fully overwrite deleted information with zeros.
6145 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
6146 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
6148 goto freepage_out;
6150 memset(pPage->aData, 0, pPage->pBt->pageSize);
6153 /* If the database supports auto-vacuum, write an entry in the pointer-map
6154 ** to indicate that the page is free.
6156 if( ISAUTOVACUUM ){
6157 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
6158 if( rc ) goto freepage_out;
6161 /* Now manipulate the actual database free-list structure. There are two
6162 ** possibilities. If the free-list is currently empty, or if the first
6163 ** trunk page in the free-list is full, then this page will become a
6164 ** new free-list trunk page. Otherwise, it will become a leaf of the
6165 ** first trunk page in the current free-list. This block tests if it
6166 ** is possible to add the page as a new free-list leaf.
6168 if( nFree!=0 ){
6169 u32 nLeaf; /* Initial number of leaf cells on trunk page */
6171 iTrunk = get4byte(&pPage1->aData[32]);
6172 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
6173 if( rc!=SQLITE_OK ){
6174 goto freepage_out;
6177 nLeaf = get4byte(&pTrunk->aData[4]);
6178 assert( pBt->usableSize>32 );
6179 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
6180 rc = SQLITE_CORRUPT_BKPT;
6181 goto freepage_out;
6183 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
6184 /* In this case there is room on the trunk page to insert the page
6185 ** being freed as a new leaf.
6187 ** Note that the trunk page is not really full until it contains
6188 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
6189 ** coded. But due to a coding error in versions of SQLite prior to
6190 ** 3.6.0, databases with freelist trunk pages holding more than
6191 ** usableSize/4 - 8 entries will be reported as corrupt. In order
6192 ** to maintain backwards compatibility with older versions of SQLite,
6193 ** we will continue to restrict the number of entries to usableSize/4 - 8
6194 ** for now. At some point in the future (once everyone has upgraded
6195 ** to 3.6.0 or later) we should consider fixing the conditional above
6196 ** to read "usableSize/4-2" instead of "usableSize/4-8".
6198 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
6199 ** avoid using the last six entries in the freelist trunk page array in
6200 ** order that database files created by newer versions of SQLite can be
6201 ** read by older versions of SQLite.
6203 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6204 if( rc==SQLITE_OK ){
6205 put4byte(&pTrunk->aData[4], nLeaf+1);
6206 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
6207 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
6208 sqlite3PagerDontWrite(pPage->pDbPage);
6210 rc = btreeSetHasContent(pBt, iPage);
6212 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
6213 goto freepage_out;
6217 /* If control flows to this point, then it was not possible to add the
6218 ** the page being freed as a leaf page of the first trunk in the free-list.
6219 ** Possibly because the free-list is empty, or possibly because the
6220 ** first trunk in the free-list is full. Either way, the page being freed
6221 ** will become the new first trunk page in the free-list.
6223 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
6224 goto freepage_out;
6226 rc = sqlite3PagerWrite(pPage->pDbPage);
6227 if( rc!=SQLITE_OK ){
6228 goto freepage_out;
6230 put4byte(pPage->aData, iTrunk);
6231 put4byte(&pPage->aData[4], 0);
6232 put4byte(&pPage1->aData[32], iPage);
6233 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
6235 freepage_out:
6236 if( pPage ){
6237 pPage->isInit = 0;
6239 releasePage(pPage);
6240 releasePage(pTrunk);
6241 return rc;
6243 static void freePage(MemPage *pPage, int *pRC){
6244 if( (*pRC)==SQLITE_OK ){
6245 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
6250 ** Free any overflow pages associated with the given Cell. Store
6251 ** size information about the cell in pInfo.
6253 static int clearCell(
6254 MemPage *pPage, /* The page that contains the Cell */
6255 unsigned char *pCell, /* First byte of the Cell */
6256 CellInfo *pInfo /* Size information about the cell */
6258 BtShared *pBt;
6259 Pgno ovflPgno;
6260 int rc;
6261 int nOvfl;
6262 u32 ovflPageSize;
6264 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6265 pPage->xParseCell(pPage, pCell, pInfo);
6266 if( pInfo->nLocal==pInfo->nPayload ){
6267 return SQLITE_OK; /* No overflow pages. Return without doing anything */
6269 testcase( pCell + pInfo->nSize == pPage->aDataEnd );
6270 testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
6271 if( pCell + pInfo->nSize > pPage->aDataEnd ){
6272 /* Cell extends past end of page */
6273 return SQLITE_CORRUPT_PAGE(pPage);
6275 ovflPgno = get4byte(pCell + pInfo->nSize - 4);
6276 pBt = pPage->pBt;
6277 assert( pBt->usableSize > 4 );
6278 ovflPageSize = pBt->usableSize - 4;
6279 nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
6280 assert( nOvfl>0 ||
6281 (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
6283 while( nOvfl-- ){
6284 Pgno iNext = 0;
6285 MemPage *pOvfl = 0;
6286 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
6287 /* 0 is not a legal page number and page 1 cannot be an
6288 ** overflow page. Therefore if ovflPgno<2 or past the end of the
6289 ** file the database must be corrupt. */
6290 return SQLITE_CORRUPT_BKPT;
6292 if( nOvfl ){
6293 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
6294 if( rc ) return rc;
6297 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
6298 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
6300 /* There is no reason any cursor should have an outstanding reference
6301 ** to an overflow page belonging to a cell that is being deleted/updated.
6302 ** So if there exists more than one reference to this page, then it
6303 ** must not really be an overflow page and the database must be corrupt.
6304 ** It is helpful to detect this before calling freePage2(), as
6305 ** freePage2() may zero the page contents if secure-delete mode is
6306 ** enabled. If this 'overflow' page happens to be a page that the
6307 ** caller is iterating through or using in some other way, this
6308 ** can be problematic.
6310 rc = SQLITE_CORRUPT_BKPT;
6311 }else{
6312 rc = freePage2(pBt, pOvfl, ovflPgno);
6315 if( pOvfl ){
6316 sqlite3PagerUnref(pOvfl->pDbPage);
6318 if( rc ) return rc;
6319 ovflPgno = iNext;
6321 return SQLITE_OK;
6325 ** Create the byte sequence used to represent a cell on page pPage
6326 ** and write that byte sequence into pCell[]. Overflow pages are
6327 ** allocated and filled in as necessary. The calling procedure
6328 ** is responsible for making sure sufficient space has been allocated
6329 ** for pCell[].
6331 ** Note that pCell does not necessary need to point to the pPage->aData
6332 ** area. pCell might point to some temporary storage. The cell will
6333 ** be constructed in this temporary area then copied into pPage->aData
6334 ** later.
6336 static int fillInCell(
6337 MemPage *pPage, /* The page that contains the cell */
6338 unsigned char *pCell, /* Complete text of the cell */
6339 const BtreePayload *pX, /* Payload with which to construct the cell */
6340 int *pnSize /* Write cell size here */
6342 int nPayload;
6343 const u8 *pSrc;
6344 int nSrc, n, rc, mn;
6345 int spaceLeft;
6346 MemPage *pToRelease;
6347 unsigned char *pPrior;
6348 unsigned char *pPayload;
6349 BtShared *pBt;
6350 Pgno pgnoOvfl;
6351 int nHeader;
6353 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6355 /* pPage is not necessarily writeable since pCell might be auxiliary
6356 ** buffer space that is separate from the pPage buffer area */
6357 assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
6358 || sqlite3PagerIswriteable(pPage->pDbPage) );
6360 /* Fill in the header. */
6361 nHeader = pPage->childPtrSize;
6362 if( pPage->intKey ){
6363 nPayload = pX->nData + pX->nZero;
6364 pSrc = pX->pData;
6365 nSrc = pX->nData;
6366 assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
6367 nHeader += putVarint32(&pCell[nHeader], nPayload);
6368 nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
6369 }else{
6370 assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
6371 nSrc = nPayload = (int)pX->nKey;
6372 pSrc = pX->pKey;
6373 nHeader += putVarint32(&pCell[nHeader], nPayload);
6376 /* Fill in the payload */
6377 pPayload = &pCell[nHeader];
6378 if( nPayload<=pPage->maxLocal ){
6379 /* This is the common case where everything fits on the btree page
6380 ** and no overflow pages are required. */
6381 n = nHeader + nPayload;
6382 testcase( n==3 );
6383 testcase( n==4 );
6384 if( n<4 ) n = 4;
6385 *pnSize = n;
6386 assert( nSrc<=nPayload );
6387 testcase( nSrc<nPayload );
6388 memcpy(pPayload, pSrc, nSrc);
6389 memset(pPayload+nSrc, 0, nPayload-nSrc);
6390 return SQLITE_OK;
6393 /* If we reach this point, it means that some of the content will need
6394 ** to spill onto overflow pages.
6396 mn = pPage->minLocal;
6397 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
6398 testcase( n==pPage->maxLocal );
6399 testcase( n==pPage->maxLocal+1 );
6400 if( n > pPage->maxLocal ) n = mn;
6401 spaceLeft = n;
6402 *pnSize = n + nHeader + 4;
6403 pPrior = &pCell[nHeader+n];
6404 pToRelease = 0;
6405 pgnoOvfl = 0;
6406 pBt = pPage->pBt;
6408 /* At this point variables should be set as follows:
6410 ** nPayload Total payload size in bytes
6411 ** pPayload Begin writing payload here
6412 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
6413 ** that means content must spill into overflow pages.
6414 ** *pnSize Size of the local cell (not counting overflow pages)
6415 ** pPrior Where to write the pgno of the first overflow page
6417 ** Use a call to btreeParseCellPtr() to verify that the values above
6418 ** were computed correctly.
6420 #ifdef SQLITE_DEBUG
6422 CellInfo info;
6423 pPage->xParseCell(pPage, pCell, &info);
6424 assert( nHeader==(int)(info.pPayload - pCell) );
6425 assert( info.nKey==pX->nKey );
6426 assert( *pnSize == info.nSize );
6427 assert( spaceLeft == info.nLocal );
6429 #endif
6431 /* Write the payload into the local Cell and any extra into overflow pages */
6432 while( 1 ){
6433 n = nPayload;
6434 if( n>spaceLeft ) n = spaceLeft;
6436 /* If pToRelease is not zero than pPayload points into the data area
6437 ** of pToRelease. Make sure pToRelease is still writeable. */
6438 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6440 /* If pPayload is part of the data area of pPage, then make sure pPage
6441 ** is still writeable */
6442 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
6443 || sqlite3PagerIswriteable(pPage->pDbPage) );
6445 if( nSrc>=n ){
6446 memcpy(pPayload, pSrc, n);
6447 }else if( nSrc>0 ){
6448 n = nSrc;
6449 memcpy(pPayload, pSrc, n);
6450 }else{
6451 memset(pPayload, 0, n);
6453 nPayload -= n;
6454 if( nPayload<=0 ) break;
6455 pPayload += n;
6456 pSrc += n;
6457 nSrc -= n;
6458 spaceLeft -= n;
6459 if( spaceLeft==0 ){
6460 MemPage *pOvfl = 0;
6461 #ifndef SQLITE_OMIT_AUTOVACUUM
6462 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
6463 if( pBt->autoVacuum ){
6465 pgnoOvfl++;
6466 } while(
6467 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
6470 #endif
6471 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
6472 #ifndef SQLITE_OMIT_AUTOVACUUM
6473 /* If the database supports auto-vacuum, and the second or subsequent
6474 ** overflow page is being allocated, add an entry to the pointer-map
6475 ** for that page now.
6477 ** If this is the first overflow page, then write a partial entry
6478 ** to the pointer-map. If we write nothing to this pointer-map slot,
6479 ** then the optimistic overflow chain processing in clearCell()
6480 ** may misinterpret the uninitialized values and delete the
6481 ** wrong pages from the database.
6483 if( pBt->autoVacuum && rc==SQLITE_OK ){
6484 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
6485 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
6486 if( rc ){
6487 releasePage(pOvfl);
6490 #endif
6491 if( rc ){
6492 releasePage(pToRelease);
6493 return rc;
6496 /* If pToRelease is not zero than pPrior points into the data area
6497 ** of pToRelease. Make sure pToRelease is still writeable. */
6498 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6500 /* If pPrior is part of the data area of pPage, then make sure pPage
6501 ** is still writeable */
6502 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
6503 || sqlite3PagerIswriteable(pPage->pDbPage) );
6505 put4byte(pPrior, pgnoOvfl);
6506 releasePage(pToRelease);
6507 pToRelease = pOvfl;
6508 pPrior = pOvfl->aData;
6509 put4byte(pPrior, 0);
6510 pPayload = &pOvfl->aData[4];
6511 spaceLeft = pBt->usableSize - 4;
6514 releasePage(pToRelease);
6515 return SQLITE_OK;
6519 ** Remove the i-th cell from pPage. This routine effects pPage only.
6520 ** The cell content is not freed or deallocated. It is assumed that
6521 ** the cell content has been copied someplace else. This routine just
6522 ** removes the reference to the cell from pPage.
6524 ** "sz" must be the number of bytes in the cell.
6526 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
6527 u32 pc; /* Offset to cell content of cell being deleted */
6528 u8 *data; /* pPage->aData */
6529 u8 *ptr; /* Used to move bytes around within data[] */
6530 int rc; /* The return code */
6531 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
6533 if( *pRC ) return;
6534 assert( idx>=0 && idx<pPage->nCell );
6535 assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
6536 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6537 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6538 data = pPage->aData;
6539 ptr = &pPage->aCellIdx[2*idx];
6540 pc = get2byte(ptr);
6541 hdr = pPage->hdrOffset;
6542 testcase( pc==get2byte(&data[hdr+5]) );
6543 testcase( pc+sz==pPage->pBt->usableSize );
6544 if( pc+sz > pPage->pBt->usableSize ){
6545 *pRC = SQLITE_CORRUPT_BKPT;
6546 return;
6548 rc = freeSpace(pPage, pc, sz);
6549 if( rc ){
6550 *pRC = rc;
6551 return;
6553 pPage->nCell--;
6554 if( pPage->nCell==0 ){
6555 memset(&data[hdr+1], 0, 4);
6556 data[hdr+7] = 0;
6557 put2byte(&data[hdr+5], pPage->pBt->usableSize);
6558 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
6559 - pPage->childPtrSize - 8;
6560 }else{
6561 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
6562 put2byte(&data[hdr+3], pPage->nCell);
6563 pPage->nFree += 2;
6568 ** Insert a new cell on pPage at cell index "i". pCell points to the
6569 ** content of the cell.
6571 ** If the cell content will fit on the page, then put it there. If it
6572 ** will not fit, then make a copy of the cell content into pTemp if
6573 ** pTemp is not null. Regardless of pTemp, allocate a new entry
6574 ** in pPage->apOvfl[] and make it point to the cell content (either
6575 ** in pTemp or the original pCell) and also record its index.
6576 ** Allocating a new entry in pPage->aCell[] implies that
6577 ** pPage->nOverflow is incremented.
6579 ** *pRC must be SQLITE_OK when this routine is called.
6581 static void insertCell(
6582 MemPage *pPage, /* Page into which we are copying */
6583 int i, /* New cell becomes the i-th cell of the page */
6584 u8 *pCell, /* Content of the new cell */
6585 int sz, /* Bytes of content in pCell */
6586 u8 *pTemp, /* Temp storage space for pCell, if needed */
6587 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
6588 int *pRC /* Read and write return code from here */
6590 int idx = 0; /* Where to write new cell content in data[] */
6591 int j; /* Loop counter */
6592 u8 *data; /* The content of the whole page */
6593 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
6595 assert( *pRC==SQLITE_OK );
6596 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
6597 assert( MX_CELL(pPage->pBt)<=10921 );
6598 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
6599 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
6600 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
6601 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6602 /* The cell should normally be sized correctly. However, when moving a
6603 ** malformed cell from a leaf page to an interior page, if the cell size
6604 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
6605 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
6606 ** the term after the || in the following assert(). */
6607 assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
6608 if( pPage->nOverflow || sz+2>pPage->nFree ){
6609 if( pTemp ){
6610 memcpy(pTemp, pCell, sz);
6611 pCell = pTemp;
6613 if( iChild ){
6614 put4byte(pCell, iChild);
6616 j = pPage->nOverflow++;
6617 /* Comparison against ArraySize-1 since we hold back one extra slot
6618 ** as a contingency. In other words, never need more than 3 overflow
6619 ** slots but 4 are allocated, just to be safe. */
6620 assert( j < ArraySize(pPage->apOvfl)-1 );
6621 pPage->apOvfl[j] = pCell;
6622 pPage->aiOvfl[j] = (u16)i;
6624 /* When multiple overflows occur, they are always sequential and in
6625 ** sorted order. This invariants arise because multiple overflows can
6626 ** only occur when inserting divider cells into the parent page during
6627 ** balancing, and the dividers are adjacent and sorted.
6629 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
6630 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
6631 }else{
6632 int rc = sqlite3PagerWrite(pPage->pDbPage);
6633 if( rc!=SQLITE_OK ){
6634 *pRC = rc;
6635 return;
6637 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6638 data = pPage->aData;
6639 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
6640 rc = allocateSpace(pPage, sz, &idx);
6641 if( rc ){ *pRC = rc; return; }
6642 /* The allocateSpace() routine guarantees the following properties
6643 ** if it returns successfully */
6644 assert( idx >= 0 );
6645 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
6646 assert( idx+sz <= (int)pPage->pBt->usableSize );
6647 pPage->nFree -= (u16)(2 + sz);
6648 memcpy(&data[idx], pCell, sz);
6649 if( iChild ){
6650 put4byte(&data[idx], iChild);
6652 pIns = pPage->aCellIdx + i*2;
6653 memmove(pIns+2, pIns, 2*(pPage->nCell - i));
6654 put2byte(pIns, idx);
6655 pPage->nCell++;
6656 /* increment the cell count */
6657 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
6658 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
6659 #ifndef SQLITE_OMIT_AUTOVACUUM
6660 if( pPage->pBt->autoVacuum ){
6661 /* The cell may contain a pointer to an overflow page. If so, write
6662 ** the entry for the overflow page into the pointer map.
6664 ptrmapPutOvflPtr(pPage, pCell, pRC);
6666 #endif
6671 ** A CellArray object contains a cache of pointers and sizes for a
6672 ** consecutive sequence of cells that might be held on multiple pages.
6674 typedef struct CellArray CellArray;
6675 struct CellArray {
6676 int nCell; /* Number of cells in apCell[] */
6677 MemPage *pRef; /* Reference page */
6678 u8 **apCell; /* All cells begin balanced */
6679 u16 *szCell; /* Local size of all cells in apCell[] */
6683 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
6684 ** computed.
6686 static void populateCellCache(CellArray *p, int idx, int N){
6687 assert( idx>=0 && idx+N<=p->nCell );
6688 while( N>0 ){
6689 assert( p->apCell[idx]!=0 );
6690 if( p->szCell[idx]==0 ){
6691 p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
6692 }else{
6693 assert( CORRUPT_DB ||
6694 p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
6696 idx++;
6697 N--;
6702 ** Return the size of the Nth element of the cell array
6704 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
6705 assert( N>=0 && N<p->nCell );
6706 assert( p->szCell[N]==0 );
6707 p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
6708 return p->szCell[N];
6710 static u16 cachedCellSize(CellArray *p, int N){
6711 assert( N>=0 && N<p->nCell );
6712 if( p->szCell[N] ) return p->szCell[N];
6713 return computeCellSize(p, N);
6717 ** Array apCell[] contains pointers to nCell b-tree page cells. The
6718 ** szCell[] array contains the size in bytes of each cell. This function
6719 ** replaces the current contents of page pPg with the contents of the cell
6720 ** array.
6722 ** Some of the cells in apCell[] may currently be stored in pPg. This
6723 ** function works around problems caused by this by making a copy of any
6724 ** such cells before overwriting the page data.
6726 ** The MemPage.nFree field is invalidated by this function. It is the
6727 ** responsibility of the caller to set it correctly.
6729 static int rebuildPage(
6730 MemPage *pPg, /* Edit this page */
6731 int nCell, /* Final number of cells on page */
6732 u8 **apCell, /* Array of cells */
6733 u16 *szCell /* Array of cell sizes */
6735 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
6736 u8 * const aData = pPg->aData; /* Pointer to data for pPg */
6737 const int usableSize = pPg->pBt->usableSize;
6738 u8 * const pEnd = &aData[usableSize];
6739 int i;
6740 u8 *pCellptr = pPg->aCellIdx;
6741 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6742 u8 *pData;
6744 i = get2byte(&aData[hdr+5]);
6745 memcpy(&pTmp[i], &aData[i], usableSize - i);
6747 pData = pEnd;
6748 for(i=0; i<nCell; i++){
6749 u8 *pCell = apCell[i];
6750 if( SQLITE_WITHIN(pCell,aData,pEnd) ){
6751 pCell = &pTmp[pCell - aData];
6753 pData -= szCell[i];
6754 put2byte(pCellptr, (pData - aData));
6755 pCellptr += 2;
6756 if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
6757 memcpy(pData, pCell, szCell[i]);
6758 assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
6759 testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
6762 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
6763 pPg->nCell = nCell;
6764 pPg->nOverflow = 0;
6766 put2byte(&aData[hdr+1], 0);
6767 put2byte(&aData[hdr+3], pPg->nCell);
6768 put2byte(&aData[hdr+5], pData - aData);
6769 aData[hdr+7] = 0x00;
6770 return SQLITE_OK;
6774 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
6775 ** contains the size in bytes of each such cell. This function attempts to
6776 ** add the cells stored in the array to page pPg. If it cannot (because
6777 ** the page needs to be defragmented before the cells will fit), non-zero
6778 ** is returned. Otherwise, if the cells are added successfully, zero is
6779 ** returned.
6781 ** Argument pCellptr points to the first entry in the cell-pointer array
6782 ** (part of page pPg) to populate. After cell apCell[0] is written to the
6783 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
6784 ** cell in the array. It is the responsibility of the caller to ensure
6785 ** that it is safe to overwrite this part of the cell-pointer array.
6787 ** When this function is called, *ppData points to the start of the
6788 ** content area on page pPg. If the size of the content area is extended,
6789 ** *ppData is updated to point to the new start of the content area
6790 ** before returning.
6792 ** Finally, argument pBegin points to the byte immediately following the
6793 ** end of the space required by this page for the cell-pointer area (for
6794 ** all cells - not just those inserted by the current call). If the content
6795 ** area must be extended to before this point in order to accomodate all
6796 ** cells in apCell[], then the cells do not fit and non-zero is returned.
6798 static int pageInsertArray(
6799 MemPage *pPg, /* Page to add cells to */
6800 u8 *pBegin, /* End of cell-pointer array */
6801 u8 **ppData, /* IN/OUT: Page content -area pointer */
6802 u8 *pCellptr, /* Pointer to cell-pointer area */
6803 int iFirst, /* Index of first cell to add */
6804 int nCell, /* Number of cells to add to pPg */
6805 CellArray *pCArray /* Array of cells */
6807 int i;
6808 u8 *aData = pPg->aData;
6809 u8 *pData = *ppData;
6810 int iEnd = iFirst + nCell;
6811 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
6812 for(i=iFirst; i<iEnd; i++){
6813 int sz, rc;
6814 u8 *pSlot;
6815 sz = cachedCellSize(pCArray, i);
6816 if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
6817 if( (pData - pBegin)<sz ) return 1;
6818 pData -= sz;
6819 pSlot = pData;
6821 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
6822 ** database. But they might for a corrupt database. Hence use memmove()
6823 ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
6824 assert( (pSlot+sz)<=pCArray->apCell[i]
6825 || pSlot>=(pCArray->apCell[i]+sz)
6826 || CORRUPT_DB );
6827 memmove(pSlot, pCArray->apCell[i], sz);
6828 put2byte(pCellptr, (pSlot - aData));
6829 pCellptr += 2;
6831 *ppData = pData;
6832 return 0;
6836 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
6837 ** contains the size in bytes of each such cell. This function adds the
6838 ** space associated with each cell in the array that is currently stored
6839 ** within the body of pPg to the pPg free-list. The cell-pointers and other
6840 ** fields of the page are not updated.
6842 ** This function returns the total number of cells added to the free-list.
6844 static int pageFreeArray(
6845 MemPage *pPg, /* Page to edit */
6846 int iFirst, /* First cell to delete */
6847 int nCell, /* Cells to delete */
6848 CellArray *pCArray /* Array of cells */
6850 u8 * const aData = pPg->aData;
6851 u8 * const pEnd = &aData[pPg->pBt->usableSize];
6852 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
6853 int nRet = 0;
6854 int i;
6855 int iEnd = iFirst + nCell;
6856 u8 *pFree = 0;
6857 int szFree = 0;
6859 for(i=iFirst; i<iEnd; i++){
6860 u8 *pCell = pCArray->apCell[i];
6861 if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
6862 int sz;
6863 /* No need to use cachedCellSize() here. The sizes of all cells that
6864 ** are to be freed have already been computing while deciding which
6865 ** cells need freeing */
6866 sz = pCArray->szCell[i]; assert( sz>0 );
6867 if( pFree!=(pCell + sz) ){
6868 if( pFree ){
6869 assert( pFree>aData && (pFree - aData)<65536 );
6870 freeSpace(pPg, (u16)(pFree - aData), szFree);
6872 pFree = pCell;
6873 szFree = sz;
6874 if( pFree+sz>pEnd ) return 0;
6875 }else{
6876 pFree = pCell;
6877 szFree += sz;
6879 nRet++;
6882 if( pFree ){
6883 assert( pFree>aData && (pFree - aData)<65536 );
6884 freeSpace(pPg, (u16)(pFree - aData), szFree);
6886 return nRet;
6890 ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
6891 ** pages being balanced. The current page, pPg, has pPg->nCell cells starting
6892 ** with apCell[iOld]. After balancing, this page should hold nNew cells
6893 ** starting at apCell[iNew].
6895 ** This routine makes the necessary adjustments to pPg so that it contains
6896 ** the correct cells after being balanced.
6898 ** The pPg->nFree field is invalid when this function returns. It is the
6899 ** responsibility of the caller to set it correctly.
6901 static int editPage(
6902 MemPage *pPg, /* Edit this page */
6903 int iOld, /* Index of first cell currently on page */
6904 int iNew, /* Index of new first cell on page */
6905 int nNew, /* Final number of cells on page */
6906 CellArray *pCArray /* Array of cells and sizes */
6908 u8 * const aData = pPg->aData;
6909 const int hdr = pPg->hdrOffset;
6910 u8 *pBegin = &pPg->aCellIdx[nNew * 2];
6911 int nCell = pPg->nCell; /* Cells stored on pPg */
6912 u8 *pData;
6913 u8 *pCellptr;
6914 int i;
6915 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
6916 int iNewEnd = iNew + nNew;
6918 #ifdef SQLITE_DEBUG
6919 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6920 memcpy(pTmp, aData, pPg->pBt->usableSize);
6921 #endif
6923 /* Remove cells from the start and end of the page */
6924 if( iOld<iNew ){
6925 int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
6926 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
6927 nCell -= nShift;
6929 if( iNewEnd < iOldEnd ){
6930 nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
6933 pData = &aData[get2byteNotZero(&aData[hdr+5])];
6934 if( pData<pBegin ) goto editpage_fail;
6936 /* Add cells to the start of the page */
6937 if( iNew<iOld ){
6938 int nAdd = MIN(nNew,iOld-iNew);
6939 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
6940 pCellptr = pPg->aCellIdx;
6941 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
6942 if( pageInsertArray(
6943 pPg, pBegin, &pData, pCellptr,
6944 iNew, nAdd, pCArray
6945 ) ) goto editpage_fail;
6946 nCell += nAdd;
6949 /* Add any overflow cells */
6950 for(i=0; i<pPg->nOverflow; i++){
6951 int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
6952 if( iCell>=0 && iCell<nNew ){
6953 pCellptr = &pPg->aCellIdx[iCell * 2];
6954 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
6955 nCell++;
6956 if( pageInsertArray(
6957 pPg, pBegin, &pData, pCellptr,
6958 iCell+iNew, 1, pCArray
6959 ) ) goto editpage_fail;
6963 /* Append cells to the end of the page */
6964 pCellptr = &pPg->aCellIdx[nCell*2];
6965 if( pageInsertArray(
6966 pPg, pBegin, &pData, pCellptr,
6967 iNew+nCell, nNew-nCell, pCArray
6968 ) ) goto editpage_fail;
6970 pPg->nCell = nNew;
6971 pPg->nOverflow = 0;
6973 put2byte(&aData[hdr+3], pPg->nCell);
6974 put2byte(&aData[hdr+5], pData - aData);
6976 #ifdef SQLITE_DEBUG
6977 for(i=0; i<nNew && !CORRUPT_DB; i++){
6978 u8 *pCell = pCArray->apCell[i+iNew];
6979 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
6980 if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
6981 pCell = &pTmp[pCell - aData];
6983 assert( 0==memcmp(pCell, &aData[iOff],
6984 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
6986 #endif
6988 return SQLITE_OK;
6989 editpage_fail:
6990 /* Unable to edit this page. Rebuild it from scratch instead. */
6991 populateCellCache(pCArray, iNew, nNew);
6992 return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
6996 ** The following parameters determine how many adjacent pages get involved
6997 ** in a balancing operation. NN is the number of neighbors on either side
6998 ** of the page that participate in the balancing operation. NB is the
6999 ** total number of pages that participate, including the target page and
7000 ** NN neighbors on either side.
7002 ** The minimum value of NN is 1 (of course). Increasing NN above 1
7003 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
7004 ** in exchange for a larger degradation in INSERT and UPDATE performance.
7005 ** The value of NN appears to give the best results overall.
7007 #define NN 1 /* Number of neighbors on either side of pPage */
7008 #define NB (NN*2+1) /* Total pages involved in the balance */
7011 #ifndef SQLITE_OMIT_QUICKBALANCE
7013 ** This version of balance() handles the common special case where
7014 ** a new entry is being inserted on the extreme right-end of the
7015 ** tree, in other words, when the new entry will become the largest
7016 ** entry in the tree.
7018 ** Instead of trying to balance the 3 right-most leaf pages, just add
7019 ** a new page to the right-hand side and put the one new entry in
7020 ** that page. This leaves the right side of the tree somewhat
7021 ** unbalanced. But odds are that we will be inserting new entries
7022 ** at the end soon afterwards so the nearly empty page will quickly
7023 ** fill up. On average.
7025 ** pPage is the leaf page which is the right-most page in the tree.
7026 ** pParent is its parent. pPage must have a single overflow entry
7027 ** which is also the right-most entry on the page.
7029 ** The pSpace buffer is used to store a temporary copy of the divider
7030 ** cell that will be inserted into pParent. Such a cell consists of a 4
7031 ** byte page number followed by a variable length integer. In other
7032 ** words, at most 13 bytes. Hence the pSpace buffer must be at
7033 ** least 13 bytes in size.
7035 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
7036 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
7037 MemPage *pNew; /* Newly allocated page */
7038 int rc; /* Return Code */
7039 Pgno pgnoNew; /* Page number of pNew */
7041 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7042 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7043 assert( pPage->nOverflow==1 );
7045 /* This error condition is now caught prior to reaching this function */
7046 if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
7048 /* Allocate a new page. This page will become the right-sibling of
7049 ** pPage. Make the parent page writable, so that the new divider cell
7050 ** may be inserted. If both these operations are successful, proceed.
7052 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
7054 if( rc==SQLITE_OK ){
7056 u8 *pOut = &pSpace[4];
7057 u8 *pCell = pPage->apOvfl[0];
7058 u16 szCell = pPage->xCellSize(pPage, pCell);
7059 u8 *pStop;
7061 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
7062 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
7063 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
7064 rc = rebuildPage(pNew, 1, &pCell, &szCell);
7065 if( NEVER(rc) ) return rc;
7066 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
7068 /* If this is an auto-vacuum database, update the pointer map
7069 ** with entries for the new page, and any pointer from the
7070 ** cell on the page to an overflow page. If either of these
7071 ** operations fails, the return code is set, but the contents
7072 ** of the parent page are still manipulated by thh code below.
7073 ** That is Ok, at this point the parent page is guaranteed to
7074 ** be marked as dirty. Returning an error code will cause a
7075 ** rollback, undoing any changes made to the parent page.
7077 if( ISAUTOVACUUM ){
7078 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
7079 if( szCell>pNew->minLocal ){
7080 ptrmapPutOvflPtr(pNew, pCell, &rc);
7084 /* Create a divider cell to insert into pParent. The divider cell
7085 ** consists of a 4-byte page number (the page number of pPage) and
7086 ** a variable length key value (which must be the same value as the
7087 ** largest key on pPage).
7089 ** To find the largest key value on pPage, first find the right-most
7090 ** cell on pPage. The first two fields of this cell are the
7091 ** record-length (a variable length integer at most 32-bits in size)
7092 ** and the key value (a variable length integer, may have any value).
7093 ** The first of the while(...) loops below skips over the record-length
7094 ** field. The second while(...) loop copies the key value from the
7095 ** cell on pPage into the pSpace buffer.
7097 pCell = findCell(pPage, pPage->nCell-1);
7098 pStop = &pCell[9];
7099 while( (*(pCell++)&0x80) && pCell<pStop );
7100 pStop = &pCell[9];
7101 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
7103 /* Insert the new divider cell into pParent. */
7104 if( rc==SQLITE_OK ){
7105 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
7106 0, pPage->pgno, &rc);
7109 /* Set the right-child pointer of pParent to point to the new page. */
7110 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
7112 /* Release the reference to the new page. */
7113 releasePage(pNew);
7116 return rc;
7118 #endif /* SQLITE_OMIT_QUICKBALANCE */
7120 #if 0
7122 ** This function does not contribute anything to the operation of SQLite.
7123 ** it is sometimes activated temporarily while debugging code responsible
7124 ** for setting pointer-map entries.
7126 static int ptrmapCheckPages(MemPage **apPage, int nPage){
7127 int i, j;
7128 for(i=0; i<nPage; i++){
7129 Pgno n;
7130 u8 e;
7131 MemPage *pPage = apPage[i];
7132 BtShared *pBt = pPage->pBt;
7133 assert( pPage->isInit );
7135 for(j=0; j<pPage->nCell; j++){
7136 CellInfo info;
7137 u8 *z;
7139 z = findCell(pPage, j);
7140 pPage->xParseCell(pPage, z, &info);
7141 if( info.nLocal<info.nPayload ){
7142 Pgno ovfl = get4byte(&z[info.nSize-4]);
7143 ptrmapGet(pBt, ovfl, &e, &n);
7144 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
7146 if( !pPage->leaf ){
7147 Pgno child = get4byte(z);
7148 ptrmapGet(pBt, child, &e, &n);
7149 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7152 if( !pPage->leaf ){
7153 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
7154 ptrmapGet(pBt, child, &e, &n);
7155 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7158 return 1;
7160 #endif
7163 ** This function is used to copy the contents of the b-tree node stored
7164 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
7165 ** the pointer-map entries for each child page are updated so that the
7166 ** parent page stored in the pointer map is page pTo. If pFrom contained
7167 ** any cells with overflow page pointers, then the corresponding pointer
7168 ** map entries are also updated so that the parent page is page pTo.
7170 ** If pFrom is currently carrying any overflow cells (entries in the
7171 ** MemPage.apOvfl[] array), they are not copied to pTo.
7173 ** Before returning, page pTo is reinitialized using btreeInitPage().
7175 ** The performance of this function is not critical. It is only used by
7176 ** the balance_shallower() and balance_deeper() procedures, neither of
7177 ** which are called often under normal circumstances.
7179 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
7180 if( (*pRC)==SQLITE_OK ){
7181 BtShared * const pBt = pFrom->pBt;
7182 u8 * const aFrom = pFrom->aData;
7183 u8 * const aTo = pTo->aData;
7184 int const iFromHdr = pFrom->hdrOffset;
7185 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
7186 int rc;
7187 int iData;
7190 assert( pFrom->isInit );
7191 assert( pFrom->nFree>=iToHdr );
7192 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
7194 /* Copy the b-tree node content from page pFrom to page pTo. */
7195 iData = get2byte(&aFrom[iFromHdr+5]);
7196 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
7197 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
7199 /* Reinitialize page pTo so that the contents of the MemPage structure
7200 ** match the new data. The initialization of pTo can actually fail under
7201 ** fairly obscure circumstances, even though it is a copy of initialized
7202 ** page pFrom.
7204 pTo->isInit = 0;
7205 rc = btreeInitPage(pTo);
7206 if( rc!=SQLITE_OK ){
7207 *pRC = rc;
7208 return;
7211 /* If this is an auto-vacuum database, update the pointer-map entries
7212 ** for any b-tree or overflow pages that pTo now contains the pointers to.
7214 if( ISAUTOVACUUM ){
7215 *pRC = setChildPtrmaps(pTo);
7221 ** This routine redistributes cells on the iParentIdx'th child of pParent
7222 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
7223 ** same amount of free space. Usually a single sibling on either side of the
7224 ** page are used in the balancing, though both siblings might come from one
7225 ** side if the page is the first or last child of its parent. If the page
7226 ** has fewer than 2 siblings (something which can only happen if the page
7227 ** is a root page or a child of a root page) then all available siblings
7228 ** participate in the balancing.
7230 ** The number of siblings of the page might be increased or decreased by
7231 ** one or two in an effort to keep pages nearly full but not over full.
7233 ** Note that when this routine is called, some of the cells on the page
7234 ** might not actually be stored in MemPage.aData[]. This can happen
7235 ** if the page is overfull. This routine ensures that all cells allocated
7236 ** to the page and its siblings fit into MemPage.aData[] before returning.
7238 ** In the course of balancing the page and its siblings, cells may be
7239 ** inserted into or removed from the parent page (pParent). Doing so
7240 ** may cause the parent page to become overfull or underfull. If this
7241 ** happens, it is the responsibility of the caller to invoke the correct
7242 ** balancing routine to fix this problem (see the balance() routine).
7244 ** If this routine fails for any reason, it might leave the database
7245 ** in a corrupted state. So if this routine fails, the database should
7246 ** be rolled back.
7248 ** The third argument to this function, aOvflSpace, is a pointer to a
7249 ** buffer big enough to hold one page. If while inserting cells into the parent
7250 ** page (pParent) the parent page becomes overfull, this buffer is
7251 ** used to store the parent's overflow cells. Because this function inserts
7252 ** a maximum of four divider cells into the parent page, and the maximum
7253 ** size of a cell stored within an internal node is always less than 1/4
7254 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
7255 ** enough for all overflow cells.
7257 ** If aOvflSpace is set to a null pointer, this function returns
7258 ** SQLITE_NOMEM.
7260 static int balance_nonroot(
7261 MemPage *pParent, /* Parent page of siblings being balanced */
7262 int iParentIdx, /* Index of "the page" in pParent */
7263 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
7264 int isRoot, /* True if pParent is a root-page */
7265 int bBulk /* True if this call is part of a bulk load */
7267 BtShared *pBt; /* The whole database */
7268 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
7269 int nNew = 0; /* Number of pages in apNew[] */
7270 int nOld; /* Number of pages in apOld[] */
7271 int i, j, k; /* Loop counters */
7272 int nxDiv; /* Next divider slot in pParent->aCell[] */
7273 int rc = SQLITE_OK; /* The return code */
7274 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
7275 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
7276 int usableSpace; /* Bytes in pPage beyond the header */
7277 int pageFlags; /* Value of pPage->aData[0] */
7278 int iSpace1 = 0; /* First unused byte of aSpace1[] */
7279 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
7280 int szScratch; /* Size of scratch memory requested */
7281 MemPage *apOld[NB]; /* pPage and up to two siblings */
7282 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
7283 u8 *pRight; /* Location in parent of right-sibling pointer */
7284 u8 *apDiv[NB-1]; /* Divider cells in pParent */
7285 int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
7286 int cntOld[NB+2]; /* Old index in b.apCell[] */
7287 int szNew[NB+2]; /* Combined size of cells placed on i-th page */
7288 u8 *aSpace1; /* Space for copies of dividers cells */
7289 Pgno pgno; /* Temp var to store a page number in */
7290 u8 abDone[NB+2]; /* True after i'th new page is populated */
7291 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
7292 Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
7293 u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
7294 CellArray b; /* Parsed information on cells being balanced */
7296 memset(abDone, 0, sizeof(abDone));
7297 b.nCell = 0;
7298 b.apCell = 0;
7299 pBt = pParent->pBt;
7300 assert( sqlite3_mutex_held(pBt->mutex) );
7301 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7303 #if 0
7304 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
7305 #endif
7307 /* At this point pParent may have at most one overflow cell. And if
7308 ** this overflow cell is present, it must be the cell with
7309 ** index iParentIdx. This scenario comes about when this function
7310 ** is called (indirectly) from sqlite3BtreeDelete().
7312 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
7313 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
7315 if( !aOvflSpace ){
7316 return SQLITE_NOMEM_BKPT;
7319 /* Find the sibling pages to balance. Also locate the cells in pParent
7320 ** that divide the siblings. An attempt is made to find NN siblings on
7321 ** either side of pPage. More siblings are taken from one side, however,
7322 ** if there are fewer than NN siblings on the other side. If pParent
7323 ** has NB or fewer children then all children of pParent are taken.
7325 ** This loop also drops the divider cells from the parent page. This
7326 ** way, the remainder of the function does not have to deal with any
7327 ** overflow cells in the parent page, since if any existed they will
7328 ** have already been removed.
7330 i = pParent->nOverflow + pParent->nCell;
7331 if( i<2 ){
7332 nxDiv = 0;
7333 }else{
7334 assert( bBulk==0 || bBulk==1 );
7335 if( iParentIdx==0 ){
7336 nxDiv = 0;
7337 }else if( iParentIdx==i ){
7338 nxDiv = i-2+bBulk;
7339 }else{
7340 nxDiv = iParentIdx-1;
7342 i = 2-bBulk;
7344 nOld = i+1;
7345 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
7346 pRight = &pParent->aData[pParent->hdrOffset+8];
7347 }else{
7348 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
7350 pgno = get4byte(pRight);
7351 while( 1 ){
7352 rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
7353 if( rc ){
7354 memset(apOld, 0, (i+1)*sizeof(MemPage*));
7355 goto balance_cleanup;
7357 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
7358 if( (i--)==0 ) break;
7360 if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
7361 apDiv[i] = pParent->apOvfl[0];
7362 pgno = get4byte(apDiv[i]);
7363 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7364 pParent->nOverflow = 0;
7365 }else{
7366 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
7367 pgno = get4byte(apDiv[i]);
7368 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7370 /* Drop the cell from the parent page. apDiv[i] still points to
7371 ** the cell within the parent, even though it has been dropped.
7372 ** This is safe because dropping a cell only overwrites the first
7373 ** four bytes of it, and this function does not need the first
7374 ** four bytes of the divider cell. So the pointer is safe to use
7375 ** later on.
7377 ** But not if we are in secure-delete mode. In secure-delete mode,
7378 ** the dropCell() routine will overwrite the entire cell with zeroes.
7379 ** In this case, temporarily copy the cell into the aOvflSpace[]
7380 ** buffer. It will be copied out again as soon as the aSpace[] buffer
7381 ** is allocated. */
7382 if( pBt->btsFlags & BTS_FAST_SECURE ){
7383 int iOff;
7385 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
7386 if( (iOff+szNew[i])>(int)pBt->usableSize ){
7387 rc = SQLITE_CORRUPT_BKPT;
7388 memset(apOld, 0, (i+1)*sizeof(MemPage*));
7389 goto balance_cleanup;
7390 }else{
7391 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
7392 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
7395 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
7399 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
7400 ** alignment */
7401 nMaxCells = (nMaxCells + 3)&~3;
7404 ** Allocate space for memory structures
7406 szScratch =
7407 nMaxCells*sizeof(u8*) /* b.apCell */
7408 + nMaxCells*sizeof(u16) /* b.szCell */
7409 + pBt->pageSize; /* aSpace1 */
7411 assert( szScratch<=6*(int)pBt->pageSize );
7412 b.apCell = sqlite3StackAllocRaw(0, szScratch );
7413 if( b.apCell==0 ){
7414 rc = SQLITE_NOMEM_BKPT;
7415 goto balance_cleanup;
7417 b.szCell = (u16*)&b.apCell[nMaxCells];
7418 aSpace1 = (u8*)&b.szCell[nMaxCells];
7419 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
7422 ** Load pointers to all cells on sibling pages and the divider cells
7423 ** into the local b.apCell[] array. Make copies of the divider cells
7424 ** into space obtained from aSpace1[]. The divider cells have already
7425 ** been removed from pParent.
7427 ** If the siblings are on leaf pages, then the child pointers of the
7428 ** divider cells are stripped from the cells before they are copied
7429 ** into aSpace1[]. In this way, all cells in b.apCell[] are without
7430 ** child pointers. If siblings are not leaves, then all cell in
7431 ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
7432 ** are alike.
7434 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
7435 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
7437 b.pRef = apOld[0];
7438 leafCorrection = b.pRef->leaf*4;
7439 leafData = b.pRef->intKeyLeaf;
7440 for(i=0; i<nOld; i++){
7441 MemPage *pOld = apOld[i];
7442 int limit = pOld->nCell;
7443 u8 *aData = pOld->aData;
7444 u16 maskPage = pOld->maskPage;
7445 u8 *piCell = aData + pOld->cellOffset;
7446 u8 *piEnd;
7448 /* Verify that all sibling pages are of the same "type" (table-leaf,
7449 ** table-interior, index-leaf, or index-interior).
7451 if( pOld->aData[0]!=apOld[0]->aData[0] ){
7452 rc = SQLITE_CORRUPT_BKPT;
7453 goto balance_cleanup;
7456 /* Load b.apCell[] with pointers to all cells in pOld. If pOld
7457 ** contains overflow cells, include them in the b.apCell[] array
7458 ** in the correct spot.
7460 ** Note that when there are multiple overflow cells, it is always the
7461 ** case that they are sequential and adjacent. This invariant arises
7462 ** because multiple overflows can only occurs when inserting divider
7463 ** cells into a parent on a prior balance, and divider cells are always
7464 ** adjacent and are inserted in order. There is an assert() tagged
7465 ** with "NOTE 1" in the overflow cell insertion loop to prove this
7466 ** invariant.
7468 ** This must be done in advance. Once the balance starts, the cell
7469 ** offset section of the btree page will be overwritten and we will no
7470 ** long be able to find the cells if a pointer to each cell is not saved
7471 ** first.
7473 memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
7474 if( pOld->nOverflow>0 ){
7475 limit = pOld->aiOvfl[0];
7476 for(j=0; j<limit; j++){
7477 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7478 piCell += 2;
7479 b.nCell++;
7481 for(k=0; k<pOld->nOverflow; k++){
7482 assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
7483 b.apCell[b.nCell] = pOld->apOvfl[k];
7484 b.nCell++;
7487 piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
7488 while( piCell<piEnd ){
7489 assert( b.nCell<nMaxCells );
7490 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7491 piCell += 2;
7492 b.nCell++;
7495 cntOld[i] = b.nCell;
7496 if( i<nOld-1 && !leafData){
7497 u16 sz = (u16)szNew[i];
7498 u8 *pTemp;
7499 assert( b.nCell<nMaxCells );
7500 b.szCell[b.nCell] = sz;
7501 pTemp = &aSpace1[iSpace1];
7502 iSpace1 += sz;
7503 assert( sz<=pBt->maxLocal+23 );
7504 assert( iSpace1 <= (int)pBt->pageSize );
7505 memcpy(pTemp, apDiv[i], sz);
7506 b.apCell[b.nCell] = pTemp+leafCorrection;
7507 assert( leafCorrection==0 || leafCorrection==4 );
7508 b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
7509 if( !pOld->leaf ){
7510 assert( leafCorrection==0 );
7511 assert( pOld->hdrOffset==0 );
7512 /* The right pointer of the child page pOld becomes the left
7513 ** pointer of the divider cell */
7514 memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
7515 }else{
7516 assert( leafCorrection==4 );
7517 while( b.szCell[b.nCell]<4 ){
7518 /* Do not allow any cells smaller than 4 bytes. If a smaller cell
7519 ** does exist, pad it with 0x00 bytes. */
7520 assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
7521 assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
7522 aSpace1[iSpace1++] = 0x00;
7523 b.szCell[b.nCell]++;
7526 b.nCell++;
7531 ** Figure out the number of pages needed to hold all b.nCell cells.
7532 ** Store this number in "k". Also compute szNew[] which is the total
7533 ** size of all cells on the i-th page and cntNew[] which is the index
7534 ** in b.apCell[] of the cell that divides page i from page i+1.
7535 ** cntNew[k] should equal b.nCell.
7537 ** Values computed by this block:
7539 ** k: The total number of sibling pages
7540 ** szNew[i]: Spaced used on the i-th sibling page.
7541 ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
7542 ** the right of the i-th sibling page.
7543 ** usableSpace: Number of bytes of space available on each sibling.
7546 usableSpace = pBt->usableSize - 12 + leafCorrection;
7547 for(i=0; i<nOld; i++){
7548 MemPage *p = apOld[i];
7549 szNew[i] = usableSpace - p->nFree;
7550 for(j=0; j<p->nOverflow; j++){
7551 szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
7553 cntNew[i] = cntOld[i];
7555 k = nOld;
7556 for(i=0; i<k; i++){
7557 int sz;
7558 while( szNew[i]>usableSpace ){
7559 if( i+1>=k ){
7560 k = i+2;
7561 if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
7562 szNew[k-1] = 0;
7563 cntNew[k-1] = b.nCell;
7565 sz = 2 + cachedCellSize(&b, cntNew[i]-1);
7566 szNew[i] -= sz;
7567 if( !leafData ){
7568 if( cntNew[i]<b.nCell ){
7569 sz = 2 + cachedCellSize(&b, cntNew[i]);
7570 }else{
7571 sz = 0;
7574 szNew[i+1] += sz;
7575 cntNew[i]--;
7577 while( cntNew[i]<b.nCell ){
7578 sz = 2 + cachedCellSize(&b, cntNew[i]);
7579 if( szNew[i]+sz>usableSpace ) break;
7580 szNew[i] += sz;
7581 cntNew[i]++;
7582 if( !leafData ){
7583 if( cntNew[i]<b.nCell ){
7584 sz = 2 + cachedCellSize(&b, cntNew[i]);
7585 }else{
7586 sz = 0;
7589 szNew[i+1] -= sz;
7591 if( cntNew[i]>=b.nCell ){
7592 k = i+1;
7593 }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
7594 rc = SQLITE_CORRUPT_BKPT;
7595 goto balance_cleanup;
7600 ** The packing computed by the previous block is biased toward the siblings
7601 ** on the left side (siblings with smaller keys). The left siblings are
7602 ** always nearly full, while the right-most sibling might be nearly empty.
7603 ** The next block of code attempts to adjust the packing of siblings to
7604 ** get a better balance.
7606 ** This adjustment is more than an optimization. The packing above might
7607 ** be so out of balance as to be illegal. For example, the right-most
7608 ** sibling might be completely empty. This adjustment is not optional.
7610 for(i=k-1; i>0; i--){
7611 int szRight = szNew[i]; /* Size of sibling on the right */
7612 int szLeft = szNew[i-1]; /* Size of sibling on the left */
7613 int r; /* Index of right-most cell in left sibling */
7614 int d; /* Index of first cell to the left of right sibling */
7616 r = cntNew[i-1] - 1;
7617 d = r + 1 - leafData;
7618 (void)cachedCellSize(&b, d);
7620 assert( d<nMaxCells );
7621 assert( r<nMaxCells );
7622 (void)cachedCellSize(&b, r);
7623 if( szRight!=0
7624 && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
7625 break;
7627 szRight += b.szCell[d] + 2;
7628 szLeft -= b.szCell[r] + 2;
7629 cntNew[i-1] = r;
7630 r--;
7631 d--;
7632 }while( r>=0 );
7633 szNew[i] = szRight;
7634 szNew[i-1] = szLeft;
7635 if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
7636 rc = SQLITE_CORRUPT_BKPT;
7637 goto balance_cleanup;
7641 /* Sanity check: For a non-corrupt database file one of the follwing
7642 ** must be true:
7643 ** (1) We found one or more cells (cntNew[0])>0), or
7644 ** (2) pPage is a virtual root page. A virtual root page is when
7645 ** the real root page is page 1 and we are the only child of
7646 ** that page.
7648 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
7649 TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
7650 apOld[0]->pgno, apOld[0]->nCell,
7651 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
7652 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
7656 ** Allocate k new pages. Reuse old pages where possible.
7658 pageFlags = apOld[0]->aData[0];
7659 for(i=0; i<k; i++){
7660 MemPage *pNew;
7661 if( i<nOld ){
7662 pNew = apNew[i] = apOld[i];
7663 apOld[i] = 0;
7664 rc = sqlite3PagerWrite(pNew->pDbPage);
7665 nNew++;
7666 if( rc ) goto balance_cleanup;
7667 }else{
7668 assert( i>0 );
7669 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
7670 if( rc ) goto balance_cleanup;
7671 zeroPage(pNew, pageFlags);
7672 apNew[i] = pNew;
7673 nNew++;
7674 cntOld[i] = b.nCell;
7676 /* Set the pointer-map entry for the new sibling page. */
7677 if( ISAUTOVACUUM ){
7678 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
7679 if( rc!=SQLITE_OK ){
7680 goto balance_cleanup;
7687 ** Reassign page numbers so that the new pages are in ascending order.
7688 ** This helps to keep entries in the disk file in order so that a scan
7689 ** of the table is closer to a linear scan through the file. That in turn
7690 ** helps the operating system to deliver pages from the disk more rapidly.
7692 ** An O(n^2) insertion sort algorithm is used, but since n is never more
7693 ** than (NB+2) (a small constant), that should not be a problem.
7695 ** When NB==3, this one optimization makes the database about 25% faster
7696 ** for large insertions and deletions.
7698 for(i=0; i<nNew; i++){
7699 aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
7700 aPgFlags[i] = apNew[i]->pDbPage->flags;
7701 for(j=0; j<i; j++){
7702 if( aPgno[j]==aPgno[i] ){
7703 /* This branch is taken if the set of sibling pages somehow contains
7704 ** duplicate entries. This can happen if the database is corrupt.
7705 ** It would be simpler to detect this as part of the loop below, but
7706 ** we do the detection here in order to avoid populating the pager
7707 ** cache with two separate objects associated with the same
7708 ** page number. */
7709 assert( CORRUPT_DB );
7710 rc = SQLITE_CORRUPT_BKPT;
7711 goto balance_cleanup;
7715 for(i=0; i<nNew; i++){
7716 int iBest = 0; /* aPgno[] index of page number to use */
7717 for(j=1; j<nNew; j++){
7718 if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
7720 pgno = aPgOrder[iBest];
7721 aPgOrder[iBest] = 0xffffffff;
7722 if( iBest!=i ){
7723 if( iBest>i ){
7724 sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
7726 sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
7727 apNew[i]->pgno = pgno;
7731 TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
7732 "%d(%d nc=%d) %d(%d nc=%d)\n",
7733 apNew[0]->pgno, szNew[0], cntNew[0],
7734 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
7735 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
7736 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
7737 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
7738 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
7739 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
7740 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
7741 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
7744 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7745 put4byte(pRight, apNew[nNew-1]->pgno);
7747 /* If the sibling pages are not leaves, ensure that the right-child pointer
7748 ** of the right-most new sibling page is set to the value that was
7749 ** originally in the same field of the right-most old sibling page. */
7750 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
7751 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
7752 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
7755 /* Make any required updates to pointer map entries associated with
7756 ** cells stored on sibling pages following the balance operation. Pointer
7757 ** map entries associated with divider cells are set by the insertCell()
7758 ** routine. The associated pointer map entries are:
7760 ** a) if the cell contains a reference to an overflow chain, the
7761 ** entry associated with the first page in the overflow chain, and
7763 ** b) if the sibling pages are not leaves, the child page associated
7764 ** with the cell.
7766 ** If the sibling pages are not leaves, then the pointer map entry
7767 ** associated with the right-child of each sibling may also need to be
7768 ** updated. This happens below, after the sibling pages have been
7769 ** populated, not here.
7771 if( ISAUTOVACUUM ){
7772 MemPage *pNew = apNew[0];
7773 u8 *aOld = pNew->aData;
7774 int cntOldNext = pNew->nCell + pNew->nOverflow;
7775 int usableSize = pBt->usableSize;
7776 int iNew = 0;
7777 int iOld = 0;
7779 for(i=0; i<b.nCell; i++){
7780 u8 *pCell = b.apCell[i];
7781 if( i==cntOldNext ){
7782 MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
7783 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
7784 aOld = pOld->aData;
7786 if( i==cntNew[iNew] ){
7787 pNew = apNew[++iNew];
7788 if( !leafData ) continue;
7791 /* Cell pCell is destined for new sibling page pNew. Originally, it
7792 ** was either part of sibling page iOld (possibly an overflow cell),
7793 ** or else the divider cell to the left of sibling page iOld. So,
7794 ** if sibling page iOld had the same page number as pNew, and if
7795 ** pCell really was a part of sibling page iOld (not a divider or
7796 ** overflow cell), we can skip updating the pointer map entries. */
7797 if( iOld>=nNew
7798 || pNew->pgno!=aPgno[iOld]
7799 || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
7801 if( !leafCorrection ){
7802 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
7804 if( cachedCellSize(&b,i)>pNew->minLocal ){
7805 ptrmapPutOvflPtr(pNew, pCell, &rc);
7807 if( rc ) goto balance_cleanup;
7812 /* Insert new divider cells into pParent. */
7813 for(i=0; i<nNew-1; i++){
7814 u8 *pCell;
7815 u8 *pTemp;
7816 int sz;
7817 MemPage *pNew = apNew[i];
7818 j = cntNew[i];
7820 assert( j<nMaxCells );
7821 assert( b.apCell[j]!=0 );
7822 pCell = b.apCell[j];
7823 sz = b.szCell[j] + leafCorrection;
7824 pTemp = &aOvflSpace[iOvflSpace];
7825 if( !pNew->leaf ){
7826 memcpy(&pNew->aData[8], pCell, 4);
7827 }else if( leafData ){
7828 /* If the tree is a leaf-data tree, and the siblings are leaves,
7829 ** then there is no divider cell in b.apCell[]. Instead, the divider
7830 ** cell consists of the integer key for the right-most cell of
7831 ** the sibling-page assembled above only.
7833 CellInfo info;
7834 j--;
7835 pNew->xParseCell(pNew, b.apCell[j], &info);
7836 pCell = pTemp;
7837 sz = 4 + putVarint(&pCell[4], info.nKey);
7838 pTemp = 0;
7839 }else{
7840 pCell -= 4;
7841 /* Obscure case for non-leaf-data trees: If the cell at pCell was
7842 ** previously stored on a leaf node, and its reported size was 4
7843 ** bytes, then it may actually be smaller than this
7844 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
7845 ** any cell). But it is important to pass the correct size to
7846 ** insertCell(), so reparse the cell now.
7848 ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
7849 ** and WITHOUT ROWID tables with exactly one column which is the
7850 ** primary key.
7852 if( b.szCell[j]==4 ){
7853 assert(leafCorrection==4);
7854 sz = pParent->xCellSize(pParent, pCell);
7857 iOvflSpace += sz;
7858 assert( sz<=pBt->maxLocal+23 );
7859 assert( iOvflSpace <= (int)pBt->pageSize );
7860 insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
7861 if( rc!=SQLITE_OK ) goto balance_cleanup;
7862 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7865 /* Now update the actual sibling pages. The order in which they are updated
7866 ** is important, as this code needs to avoid disrupting any page from which
7867 ** cells may still to be read. In practice, this means:
7869 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
7870 ** then it is not safe to update page apNew[iPg] until after
7871 ** the left-hand sibling apNew[iPg-1] has been updated.
7873 ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
7874 ** then it is not safe to update page apNew[iPg] until after
7875 ** the right-hand sibling apNew[iPg+1] has been updated.
7877 ** If neither of the above apply, the page is safe to update.
7879 ** The iPg value in the following loop starts at nNew-1 goes down
7880 ** to 0, then back up to nNew-1 again, thus making two passes over
7881 ** the pages. On the initial downward pass, only condition (1) above
7882 ** needs to be tested because (2) will always be true from the previous
7883 ** step. On the upward pass, both conditions are always true, so the
7884 ** upwards pass simply processes pages that were missed on the downward
7885 ** pass.
7887 for(i=1-nNew; i<nNew; i++){
7888 int iPg = i<0 ? -i : i;
7889 assert( iPg>=0 && iPg<nNew );
7890 if( abDone[iPg] ) continue; /* Skip pages already processed */
7891 if( i>=0 /* On the upwards pass, or... */
7892 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
7894 int iNew;
7895 int iOld;
7896 int nNewCell;
7898 /* Verify condition (1): If cells are moving left, update iPg
7899 ** only after iPg-1 has already been updated. */
7900 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
7902 /* Verify condition (2): If cells are moving right, update iPg
7903 ** only after iPg+1 has already been updated. */
7904 assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
7906 if( iPg==0 ){
7907 iNew = iOld = 0;
7908 nNewCell = cntNew[0];
7909 }else{
7910 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
7911 iNew = cntNew[iPg-1] + !leafData;
7912 nNewCell = cntNew[iPg] - iNew;
7915 rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
7916 if( rc ) goto balance_cleanup;
7917 abDone[iPg]++;
7918 apNew[iPg]->nFree = usableSpace-szNew[iPg];
7919 assert( apNew[iPg]->nOverflow==0 );
7920 assert( apNew[iPg]->nCell==nNewCell );
7924 /* All pages have been processed exactly once */
7925 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
7927 assert( nOld>0 );
7928 assert( nNew>0 );
7930 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
7931 /* The root page of the b-tree now contains no cells. The only sibling
7932 ** page is the right-child of the parent. Copy the contents of the
7933 ** child page into the parent, decreasing the overall height of the
7934 ** b-tree structure by one. This is described as the "balance-shallower"
7935 ** sub-algorithm in some documentation.
7937 ** If this is an auto-vacuum database, the call to copyNodeContent()
7938 ** sets all pointer-map entries corresponding to database image pages
7939 ** for which the pointer is stored within the content being copied.
7941 ** It is critical that the child page be defragmented before being
7942 ** copied into the parent, because if the parent is page 1 then it will
7943 ** by smaller than the child due to the database header, and so all the
7944 ** free space needs to be up front.
7946 assert( nNew==1 || CORRUPT_DB );
7947 rc = defragmentPage(apNew[0], -1);
7948 testcase( rc!=SQLITE_OK );
7949 assert( apNew[0]->nFree ==
7950 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
7951 || rc!=SQLITE_OK
7953 copyNodeContent(apNew[0], pParent, &rc);
7954 freePage(apNew[0], &rc);
7955 }else if( ISAUTOVACUUM && !leafCorrection ){
7956 /* Fix the pointer map entries associated with the right-child of each
7957 ** sibling page. All other pointer map entries have already been taken
7958 ** care of. */
7959 for(i=0; i<nNew; i++){
7960 u32 key = get4byte(&apNew[i]->aData[8]);
7961 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
7965 assert( pParent->isInit );
7966 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
7967 nOld, nNew, b.nCell));
7969 /* Free any old pages that were not reused as new pages.
7971 for(i=nNew; i<nOld; i++){
7972 freePage(apOld[i], &rc);
7975 #if 0
7976 if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
7977 /* The ptrmapCheckPages() contains assert() statements that verify that
7978 ** all pointer map pages are set correctly. This is helpful while
7979 ** debugging. This is usually disabled because a corrupt database may
7980 ** cause an assert() statement to fail. */
7981 ptrmapCheckPages(apNew, nNew);
7982 ptrmapCheckPages(&pParent, 1);
7984 #endif
7987 ** Cleanup before returning.
7989 balance_cleanup:
7990 sqlite3StackFree(0, b.apCell);
7991 for(i=0; i<nOld; i++){
7992 releasePage(apOld[i]);
7994 for(i=0; i<nNew; i++){
7995 releasePage(apNew[i]);
7998 return rc;
8003 ** This function is called when the root page of a b-tree structure is
8004 ** overfull (has one or more overflow pages).
8006 ** A new child page is allocated and the contents of the current root
8007 ** page, including overflow cells, are copied into the child. The root
8008 ** page is then overwritten to make it an empty page with the right-child
8009 ** pointer pointing to the new page.
8011 ** Before returning, all pointer-map entries corresponding to pages
8012 ** that the new child-page now contains pointers to are updated. The
8013 ** entry corresponding to the new right-child pointer of the root
8014 ** page is also updated.
8016 ** If successful, *ppChild is set to contain a reference to the child
8017 ** page and SQLITE_OK is returned. In this case the caller is required
8018 ** to call releasePage() on *ppChild exactly once. If an error occurs,
8019 ** an error code is returned and *ppChild is set to 0.
8021 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
8022 int rc; /* Return value from subprocedures */
8023 MemPage *pChild = 0; /* Pointer to a new child page */
8024 Pgno pgnoChild = 0; /* Page number of the new child page */
8025 BtShared *pBt = pRoot->pBt; /* The BTree */
8027 assert( pRoot->nOverflow>0 );
8028 assert( sqlite3_mutex_held(pBt->mutex) );
8030 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
8031 ** page that will become the new right-child of pPage. Copy the contents
8032 ** of the node stored on pRoot into the new child page.
8034 rc = sqlite3PagerWrite(pRoot->pDbPage);
8035 if( rc==SQLITE_OK ){
8036 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
8037 copyNodeContent(pRoot, pChild, &rc);
8038 if( ISAUTOVACUUM ){
8039 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
8042 if( rc ){
8043 *ppChild = 0;
8044 releasePage(pChild);
8045 return rc;
8047 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
8048 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
8049 assert( pChild->nCell==pRoot->nCell );
8051 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
8053 /* Copy the overflow cells from pRoot to pChild */
8054 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
8055 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
8056 memcpy(pChild->apOvfl, pRoot->apOvfl,
8057 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
8058 pChild->nOverflow = pRoot->nOverflow;
8060 /* Zero the contents of pRoot. Then install pChild as the right-child. */
8061 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
8062 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
8064 *ppChild = pChild;
8065 return SQLITE_OK;
8069 ** The page that pCur currently points to has just been modified in
8070 ** some way. This function figures out if this modification means the
8071 ** tree needs to be balanced, and if so calls the appropriate balancing
8072 ** routine. Balancing routines are:
8074 ** balance_quick()
8075 ** balance_deeper()
8076 ** balance_nonroot()
8078 static int balance(BtCursor *pCur){
8079 int rc = SQLITE_OK;
8080 const int nMin = pCur->pBt->usableSize * 2 / 3;
8081 u8 aBalanceQuickSpace[13];
8082 u8 *pFree = 0;
8084 VVA_ONLY( int balance_quick_called = 0 );
8085 VVA_ONLY( int balance_deeper_called = 0 );
8087 do {
8088 int iPage = pCur->iPage;
8089 MemPage *pPage = pCur->pPage;
8091 if( iPage==0 ){
8092 if( pPage->nOverflow ){
8093 /* The root page of the b-tree is overfull. In this case call the
8094 ** balance_deeper() function to create a new child for the root-page
8095 ** and copy the current contents of the root-page to it. The
8096 ** next iteration of the do-loop will balance the child page.
8098 assert( balance_deeper_called==0 );
8099 VVA_ONLY( balance_deeper_called++ );
8100 rc = balance_deeper(pPage, &pCur->apPage[1]);
8101 if( rc==SQLITE_OK ){
8102 pCur->iPage = 1;
8103 pCur->ix = 0;
8104 pCur->aiIdx[0] = 0;
8105 pCur->apPage[0] = pPage;
8106 pCur->pPage = pCur->apPage[1];
8107 assert( pCur->pPage->nOverflow );
8109 }else{
8110 break;
8112 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
8113 break;
8114 }else{
8115 MemPage * const pParent = pCur->apPage[iPage-1];
8116 int const iIdx = pCur->aiIdx[iPage-1];
8118 rc = sqlite3PagerWrite(pParent->pDbPage);
8119 if( rc==SQLITE_OK ){
8120 #ifndef SQLITE_OMIT_QUICKBALANCE
8121 if( pPage->intKeyLeaf
8122 && pPage->nOverflow==1
8123 && pPage->aiOvfl[0]==pPage->nCell
8124 && pParent->pgno!=1
8125 && pParent->nCell==iIdx
8127 /* Call balance_quick() to create a new sibling of pPage on which
8128 ** to store the overflow cell. balance_quick() inserts a new cell
8129 ** into pParent, which may cause pParent overflow. If this
8130 ** happens, the next iteration of the do-loop will balance pParent
8131 ** use either balance_nonroot() or balance_deeper(). Until this
8132 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
8133 ** buffer.
8135 ** The purpose of the following assert() is to check that only a
8136 ** single call to balance_quick() is made for each call to this
8137 ** function. If this were not verified, a subtle bug involving reuse
8138 ** of the aBalanceQuickSpace[] might sneak in.
8140 assert( balance_quick_called==0 );
8141 VVA_ONLY( balance_quick_called++ );
8142 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
8143 }else
8144 #endif
8146 /* In this case, call balance_nonroot() to redistribute cells
8147 ** between pPage and up to 2 of its sibling pages. This involves
8148 ** modifying the contents of pParent, which may cause pParent to
8149 ** become overfull or underfull. The next iteration of the do-loop
8150 ** will balance the parent page to correct this.
8152 ** If the parent page becomes overfull, the overflow cell or cells
8153 ** are stored in the pSpace buffer allocated immediately below.
8154 ** A subsequent iteration of the do-loop will deal with this by
8155 ** calling balance_nonroot() (balance_deeper() may be called first,
8156 ** but it doesn't deal with overflow cells - just moves them to a
8157 ** different page). Once this subsequent call to balance_nonroot()
8158 ** has completed, it is safe to release the pSpace buffer used by
8159 ** the previous call, as the overflow cell data will have been
8160 ** copied either into the body of a database page or into the new
8161 ** pSpace buffer passed to the latter call to balance_nonroot().
8163 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
8164 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
8165 pCur->hints&BTREE_BULKLOAD);
8166 if( pFree ){
8167 /* If pFree is not NULL, it points to the pSpace buffer used
8168 ** by a previous call to balance_nonroot(). Its contents are
8169 ** now stored either on real database pages or within the
8170 ** new pSpace buffer, so it may be safely freed here. */
8171 sqlite3PageFree(pFree);
8174 /* The pSpace buffer will be freed after the next call to
8175 ** balance_nonroot(), or just before this function returns, whichever
8176 ** comes first. */
8177 pFree = pSpace;
8181 pPage->nOverflow = 0;
8183 /* The next iteration of the do-loop balances the parent page. */
8184 releasePage(pPage);
8185 pCur->iPage--;
8186 assert( pCur->iPage>=0 );
8187 pCur->pPage = pCur->apPage[pCur->iPage];
8189 }while( rc==SQLITE_OK );
8191 if( pFree ){
8192 sqlite3PageFree(pFree);
8194 return rc;
8197 /* Overwrite content from pX into pDest. Only do the write if the
8198 ** content is different from what is already there.
8200 static int btreeOverwriteContent(
8201 MemPage *pPage, /* MemPage on which writing will occur */
8202 u8 *pDest, /* Pointer to the place to start writing */
8203 const BtreePayload *pX, /* Source of data to write */
8204 int iOffset, /* Offset of first byte to write */
8205 int iAmt /* Number of bytes to be written */
8207 int nData = pX->nData - iOffset;
8208 if( nData<=0 ){
8209 /* Overwritting with zeros */
8210 int i;
8211 for(i=0; i<iAmt && pDest[i]==0; i++){}
8212 if( i<iAmt ){
8213 int rc = sqlite3PagerWrite(pPage->pDbPage);
8214 if( rc ) return rc;
8215 memset(pDest + i, 0, iAmt - i);
8217 }else{
8218 if( nData<iAmt ){
8219 /* Mixed read data and zeros at the end. Make a recursive call
8220 ** to write the zeros then fall through to write the real data */
8221 int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
8222 iAmt-nData);
8223 if( rc ) return rc;
8224 iAmt = nData;
8226 if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
8227 int rc = sqlite3PagerWrite(pPage->pDbPage);
8228 if( rc ) return rc;
8229 memcpy(pDest, ((u8*)pX->pData) + iOffset, iAmt);
8232 return SQLITE_OK;
8236 ** Overwrite the cell that cursor pCur is pointing to with fresh content
8237 ** contained in pX.
8239 static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
8240 int iOffset; /* Next byte of pX->pData to write */
8241 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
8242 int rc; /* Return code */
8243 MemPage *pPage = pCur->pPage; /* Page being written */
8244 BtShared *pBt; /* Btree */
8245 Pgno ovflPgno; /* Next overflow page to write */
8246 u32 ovflPageSize; /* Size to write on overflow page */
8248 if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd ){
8249 return SQLITE_CORRUPT_BKPT;
8251 /* Overwrite the local portion first */
8252 rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
8253 0, pCur->info.nLocal);
8254 if( rc ) return rc;
8255 if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
8257 /* Now overwrite the overflow pages */
8258 iOffset = pCur->info.nLocal;
8259 assert( nTotal>=0 );
8260 assert( iOffset>=0 );
8261 ovflPgno = get4byte(pCur->info.pPayload + iOffset);
8262 pBt = pPage->pBt;
8263 ovflPageSize = pBt->usableSize - 4;
8265 rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
8266 if( rc ) return rc;
8267 if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){
8268 rc = SQLITE_CORRUPT_BKPT;
8269 }else{
8270 if( iOffset+ovflPageSize<(u32)nTotal ){
8271 ovflPgno = get4byte(pPage->aData);
8272 }else{
8273 ovflPageSize = nTotal - iOffset;
8275 rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
8276 iOffset, ovflPageSize);
8278 sqlite3PagerUnref(pPage->pDbPage);
8279 if( rc ) return rc;
8280 iOffset += ovflPageSize;
8281 }while( iOffset<nTotal );
8282 return SQLITE_OK;
8287 ** Insert a new record into the BTree. The content of the new record
8288 ** is described by the pX object. The pCur cursor is used only to
8289 ** define what table the record should be inserted into, and is left
8290 ** pointing at a random location.
8292 ** For a table btree (used for rowid tables), only the pX.nKey value of
8293 ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
8294 ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
8295 ** hold the content of the row.
8297 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
8298 ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
8299 ** pX.pData,nData,nZero fields must be zero.
8301 ** If the seekResult parameter is non-zero, then a successful call to
8302 ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
8303 ** been performed. In other words, if seekResult!=0 then the cursor
8304 ** is currently pointing to a cell that will be adjacent to the cell
8305 ** to be inserted. If seekResult<0 then pCur points to a cell that is
8306 ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
8307 ** that is larger than (pKey,nKey).
8309 ** If seekResult==0, that means pCur is pointing at some unknown location.
8310 ** In that case, this routine must seek the cursor to the correct insertion
8311 ** point for (pKey,nKey) before doing the insertion. For index btrees,
8312 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
8313 ** key values and pX->aMem can be used instead of pX->pKey to avoid having
8314 ** to decode the key.
8316 int sqlite3BtreeInsert(
8317 BtCursor *pCur, /* Insert data into the table of this cursor */
8318 const BtreePayload *pX, /* Content of the row to be inserted */
8319 int flags, /* True if this is likely an append */
8320 int seekResult /* Result of prior MovetoUnpacked() call */
8322 int rc;
8323 int loc = seekResult; /* -1: before desired location +1: after */
8324 int szNew = 0;
8325 int idx;
8326 MemPage *pPage;
8327 Btree *p = pCur->pBtree;
8328 BtShared *pBt = p->pBt;
8329 unsigned char *oldCell;
8330 unsigned char *newCell = 0;
8332 assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
8334 if( pCur->eState==CURSOR_FAULT ){
8335 assert( pCur->skipNext!=SQLITE_OK );
8336 return pCur->skipNext;
8339 assert( cursorOwnsBtShared(pCur) );
8340 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
8341 && pBt->inTransaction==TRANS_WRITE
8342 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
8343 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8345 /* Assert that the caller has been consistent. If this cursor was opened
8346 ** expecting an index b-tree, then the caller should be inserting blob
8347 ** keys with no associated data. If the cursor was opened expecting an
8348 ** intkey table, the caller should be inserting integer keys with a
8349 ** blob of associated data. */
8350 assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
8352 /* Save the positions of any other cursors open on this table.
8354 ** In some cases, the call to btreeMoveto() below is a no-op. For
8355 ** example, when inserting data into a table with auto-generated integer
8356 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
8357 ** integer key to use. It then calls this function to actually insert the
8358 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
8359 ** that the cursor is already where it needs to be and returns without
8360 ** doing any work. To avoid thwarting these optimizations, it is important
8361 ** not to clear the cursor here.
8363 if( pCur->curFlags & BTCF_Multiple ){
8364 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8365 if( rc ) return rc;
8368 if( pCur->pKeyInfo==0 ){
8369 assert( pX->pKey==0 );
8370 /* If this is an insert into a table b-tree, invalidate any incrblob
8371 ** cursors open on the row being replaced */
8372 invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
8374 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8375 ** to a row with the same key as the new entry being inserted.
8377 #ifdef SQLITE_DEBUG
8378 if( flags & BTREE_SAVEPOSITION ){
8379 assert( pCur->curFlags & BTCF_ValidNKey );
8380 assert( pX->nKey==pCur->info.nKey );
8381 assert( pCur->info.nSize!=0 );
8382 assert( loc==0 );
8384 #endif
8386 /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
8387 ** that the cursor is not pointing to a row to be overwritten.
8388 ** So do a complete check.
8390 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
8391 /* The cursor is pointing to the entry that is to be
8392 ** overwritten */
8393 assert( pX->nData>=0 && pX->nZero>=0 );
8394 if( pCur->info.nSize!=0
8395 && pCur->info.nPayload==(u32)pX->nData+pX->nZero
8397 /* New entry is the same size as the old. Do an overwrite */
8398 return btreeOverwriteCell(pCur, pX);
8400 assert( loc==0 );
8401 }else if( loc==0 ){
8402 /* The cursor is *not* pointing to the cell to be overwritten, nor
8403 ** to an adjacent cell. Move the cursor so that it is pointing either
8404 ** to the cell to be overwritten or an adjacent cell.
8406 rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
8407 if( rc ) return rc;
8409 }else{
8410 /* This is an index or a WITHOUT ROWID table */
8412 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8413 ** to a row with the same key as the new entry being inserted.
8415 assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
8417 /* If the cursor is not already pointing either to the cell to be
8418 ** overwritten, or if a new cell is being inserted, if the cursor is
8419 ** not pointing to an immediately adjacent cell, then move the cursor
8420 ** so that it does.
8422 if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
8423 if( pX->nMem ){
8424 UnpackedRecord r;
8425 r.pKeyInfo = pCur->pKeyInfo;
8426 r.aMem = pX->aMem;
8427 r.nField = pX->nMem;
8428 r.default_rc = 0;
8429 r.errCode = 0;
8430 r.r1 = 0;
8431 r.r2 = 0;
8432 r.eqSeen = 0;
8433 rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
8434 }else{
8435 rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
8437 if( rc ) return rc;
8440 /* If the cursor is currently pointing to an entry to be overwritten
8441 ** and the new content is the same as as the old, then use the
8442 ** overwrite optimization.
8444 if( loc==0 ){
8445 getCellInfo(pCur);
8446 if( pCur->info.nKey==pX->nKey ){
8447 BtreePayload x2;
8448 x2.pData = pX->pKey;
8449 x2.nData = pX->nKey;
8450 x2.nZero = 0;
8451 return btreeOverwriteCell(pCur, &x2);
8456 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
8458 pPage = pCur->pPage;
8459 assert( pPage->intKey || pX->nKey>=0 );
8460 assert( pPage->leaf || !pPage->intKey );
8462 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
8463 pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
8464 loc==0 ? "overwrite" : "new entry"));
8465 assert( pPage->isInit );
8466 newCell = pBt->pTmpSpace;
8467 assert( newCell!=0 );
8468 rc = fillInCell(pPage, newCell, pX, &szNew);
8469 if( rc ) goto end_insert;
8470 assert( szNew==pPage->xCellSize(pPage, newCell) );
8471 assert( szNew <= MX_CELL_SIZE(pBt) );
8472 idx = pCur->ix;
8473 if( loc==0 ){
8474 CellInfo info;
8475 assert( idx<pPage->nCell );
8476 rc = sqlite3PagerWrite(pPage->pDbPage);
8477 if( rc ){
8478 goto end_insert;
8480 oldCell = findCell(pPage, idx);
8481 if( !pPage->leaf ){
8482 memcpy(newCell, oldCell, 4);
8484 rc = clearCell(pPage, oldCell, &info);
8485 if( info.nSize==szNew && info.nLocal==info.nPayload
8486 && (!ISAUTOVACUUM || szNew<pPage->minLocal)
8488 /* Overwrite the old cell with the new if they are the same size.
8489 ** We could also try to do this if the old cell is smaller, then add
8490 ** the leftover space to the free list. But experiments show that
8491 ** doing that is no faster then skipping this optimization and just
8492 ** calling dropCell() and insertCell().
8494 ** This optimization cannot be used on an autovacuum database if the
8495 ** new entry uses overflow pages, as the insertCell() call below is
8496 ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
8497 assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
8498 if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
8499 memcpy(oldCell, newCell, szNew);
8500 return SQLITE_OK;
8502 dropCell(pPage, idx, info.nSize, &rc);
8503 if( rc ) goto end_insert;
8504 }else if( loc<0 && pPage->nCell>0 ){
8505 assert( pPage->leaf );
8506 idx = ++pCur->ix;
8507 pCur->curFlags &= ~BTCF_ValidNKey;
8508 }else{
8509 assert( pPage->leaf );
8511 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
8512 assert( pPage->nOverflow==0 || rc==SQLITE_OK );
8513 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
8515 /* If no error has occurred and pPage has an overflow cell, call balance()
8516 ** to redistribute the cells within the tree. Since balance() may move
8517 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
8518 ** variables.
8520 ** Previous versions of SQLite called moveToRoot() to move the cursor
8521 ** back to the root page as balance() used to invalidate the contents
8522 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
8523 ** set the cursor state to "invalid". This makes common insert operations
8524 ** slightly faster.
8526 ** There is a subtle but important optimization here too. When inserting
8527 ** multiple records into an intkey b-tree using a single cursor (as can
8528 ** happen while processing an "INSERT INTO ... SELECT" statement), it
8529 ** is advantageous to leave the cursor pointing to the last entry in
8530 ** the b-tree if possible. If the cursor is left pointing to the last
8531 ** entry in the table, and the next row inserted has an integer key
8532 ** larger than the largest existing key, it is possible to insert the
8533 ** row without seeking the cursor. This can be a big performance boost.
8535 pCur->info.nSize = 0;
8536 if( pPage->nOverflow ){
8537 assert( rc==SQLITE_OK );
8538 pCur->curFlags &= ~(BTCF_ValidNKey);
8539 rc = balance(pCur);
8541 /* Must make sure nOverflow is reset to zero even if the balance()
8542 ** fails. Internal data structure corruption will result otherwise.
8543 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
8544 ** from trying to save the current position of the cursor. */
8545 pCur->pPage->nOverflow = 0;
8546 pCur->eState = CURSOR_INVALID;
8547 if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
8548 btreeReleaseAllCursorPages(pCur);
8549 if( pCur->pKeyInfo ){
8550 assert( pCur->pKey==0 );
8551 pCur->pKey = sqlite3Malloc( pX->nKey );
8552 if( pCur->pKey==0 ){
8553 rc = SQLITE_NOMEM;
8554 }else{
8555 memcpy(pCur->pKey, pX->pKey, pX->nKey);
8558 pCur->eState = CURSOR_REQUIRESEEK;
8559 pCur->nKey = pX->nKey;
8562 assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
8564 end_insert:
8565 return rc;
8569 ** Delete the entry that the cursor is pointing to.
8571 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
8572 ** the cursor is left pointing at an arbitrary location after the delete.
8573 ** But if that bit is set, then the cursor is left in a state such that
8574 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
8575 ** as it would have been on if the call to BtreeDelete() had been omitted.
8577 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
8578 ** associated with a single table entry and its indexes. Only one of those
8579 ** deletes is considered the "primary" delete. The primary delete occurs
8580 ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
8581 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
8582 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
8583 ** but which might be used by alternative storage engines.
8585 int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
8586 Btree *p = pCur->pBtree;
8587 BtShared *pBt = p->pBt;
8588 int rc; /* Return code */
8589 MemPage *pPage; /* Page to delete cell from */
8590 unsigned char *pCell; /* Pointer to cell to delete */
8591 int iCellIdx; /* Index of cell to delete */
8592 int iCellDepth; /* Depth of node containing pCell */
8593 CellInfo info; /* Size of the cell being deleted */
8594 int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
8595 u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
8597 assert( cursorOwnsBtShared(pCur) );
8598 assert( pBt->inTransaction==TRANS_WRITE );
8599 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
8600 assert( pCur->curFlags & BTCF_WriteFlag );
8601 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8602 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
8603 assert( pCur->ix<pCur->pPage->nCell );
8604 assert( pCur->eState==CURSOR_VALID );
8605 assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
8607 iCellDepth = pCur->iPage;
8608 iCellIdx = pCur->ix;
8609 pPage = pCur->pPage;
8610 pCell = findCell(pPage, iCellIdx);
8612 /* If the bPreserve flag is set to true, then the cursor position must
8613 ** be preserved following this delete operation. If the current delete
8614 ** will cause a b-tree rebalance, then this is done by saving the cursor
8615 ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
8616 ** returning.
8618 ** Or, if the current delete will not cause a rebalance, then the cursor
8619 ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
8620 ** before or after the deleted entry. In this case set bSkipnext to true. */
8621 if( bPreserve ){
8622 if( !pPage->leaf
8623 || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
8625 /* A b-tree rebalance will be required after deleting this entry.
8626 ** Save the cursor key. */
8627 rc = saveCursorKey(pCur);
8628 if( rc ) return rc;
8629 }else{
8630 bSkipnext = 1;
8634 /* If the page containing the entry to delete is not a leaf page, move
8635 ** the cursor to the largest entry in the tree that is smaller than
8636 ** the entry being deleted. This cell will replace the cell being deleted
8637 ** from the internal node. The 'previous' entry is used for this instead
8638 ** of the 'next' entry, as the previous entry is always a part of the
8639 ** sub-tree headed by the child page of the cell being deleted. This makes
8640 ** balancing the tree following the delete operation easier. */
8641 if( !pPage->leaf ){
8642 rc = sqlite3BtreePrevious(pCur, 0);
8643 assert( rc!=SQLITE_DONE );
8644 if( rc ) return rc;
8647 /* Save the positions of any other cursors open on this table before
8648 ** making any modifications. */
8649 if( pCur->curFlags & BTCF_Multiple ){
8650 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8651 if( rc ) return rc;
8654 /* If this is a delete operation to remove a row from a table b-tree,
8655 ** invalidate any incrblob cursors open on the row being deleted. */
8656 if( pCur->pKeyInfo==0 ){
8657 invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
8660 /* Make the page containing the entry to be deleted writable. Then free any
8661 ** overflow pages associated with the entry and finally remove the cell
8662 ** itself from within the page. */
8663 rc = sqlite3PagerWrite(pPage->pDbPage);
8664 if( rc ) return rc;
8665 rc = clearCell(pPage, pCell, &info);
8666 dropCell(pPage, iCellIdx, info.nSize, &rc);
8667 if( rc ) return rc;
8669 /* If the cell deleted was not located on a leaf page, then the cursor
8670 ** is currently pointing to the largest entry in the sub-tree headed
8671 ** by the child-page of the cell that was just deleted from an internal
8672 ** node. The cell from the leaf node needs to be moved to the internal
8673 ** node to replace the deleted cell. */
8674 if( !pPage->leaf ){
8675 MemPage *pLeaf = pCur->pPage;
8676 int nCell;
8677 Pgno n;
8678 unsigned char *pTmp;
8680 if( iCellDepth<pCur->iPage-1 ){
8681 n = pCur->apPage[iCellDepth+1]->pgno;
8682 }else{
8683 n = pCur->pPage->pgno;
8685 pCell = findCell(pLeaf, pLeaf->nCell-1);
8686 if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
8687 nCell = pLeaf->xCellSize(pLeaf, pCell);
8688 assert( MX_CELL_SIZE(pBt) >= nCell );
8689 pTmp = pBt->pTmpSpace;
8690 assert( pTmp!=0 );
8691 rc = sqlite3PagerWrite(pLeaf->pDbPage);
8692 if( rc==SQLITE_OK ){
8693 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
8695 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
8696 if( rc ) return rc;
8699 /* Balance the tree. If the entry deleted was located on a leaf page,
8700 ** then the cursor still points to that page. In this case the first
8701 ** call to balance() repairs the tree, and the if(...) condition is
8702 ** never true.
8704 ** Otherwise, if the entry deleted was on an internal node page, then
8705 ** pCur is pointing to the leaf page from which a cell was removed to
8706 ** replace the cell deleted from the internal node. This is slightly
8707 ** tricky as the leaf node may be underfull, and the internal node may
8708 ** be either under or overfull. In this case run the balancing algorithm
8709 ** on the leaf node first. If the balance proceeds far enough up the
8710 ** tree that we can be sure that any problem in the internal node has
8711 ** been corrected, so be it. Otherwise, after balancing the leaf node,
8712 ** walk the cursor up the tree to the internal node and balance it as
8713 ** well. */
8714 rc = balance(pCur);
8715 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
8716 releasePageNotNull(pCur->pPage);
8717 pCur->iPage--;
8718 while( pCur->iPage>iCellDepth ){
8719 releasePage(pCur->apPage[pCur->iPage--]);
8721 pCur->pPage = pCur->apPage[pCur->iPage];
8722 rc = balance(pCur);
8725 if( rc==SQLITE_OK ){
8726 if( bSkipnext ){
8727 assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
8728 assert( pPage==pCur->pPage || CORRUPT_DB );
8729 assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
8730 pCur->eState = CURSOR_SKIPNEXT;
8731 if( iCellIdx>=pPage->nCell ){
8732 pCur->skipNext = -1;
8733 pCur->ix = pPage->nCell-1;
8734 }else{
8735 pCur->skipNext = 1;
8737 }else{
8738 rc = moveToRoot(pCur);
8739 if( bPreserve ){
8740 btreeReleaseAllCursorPages(pCur);
8741 pCur->eState = CURSOR_REQUIRESEEK;
8743 if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
8746 return rc;
8750 ** Create a new BTree table. Write into *piTable the page
8751 ** number for the root page of the new table.
8753 ** The type of type is determined by the flags parameter. Only the
8754 ** following values of flags are currently in use. Other values for
8755 ** flags might not work:
8757 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
8758 ** BTREE_ZERODATA Used for SQL indices
8760 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
8761 BtShared *pBt = p->pBt;
8762 MemPage *pRoot;
8763 Pgno pgnoRoot;
8764 int rc;
8765 int ptfFlags; /* Page-type flage for the root page of new table */
8767 assert( sqlite3BtreeHoldsMutex(p) );
8768 assert( pBt->inTransaction==TRANS_WRITE );
8769 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
8771 #ifdef SQLITE_OMIT_AUTOVACUUM
8772 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
8773 if( rc ){
8774 return rc;
8776 #else
8777 if( pBt->autoVacuum ){
8778 Pgno pgnoMove; /* Move a page here to make room for the root-page */
8779 MemPage *pPageMove; /* The page to move to. */
8781 /* Creating a new table may probably require moving an existing database
8782 ** to make room for the new tables root page. In case this page turns
8783 ** out to be an overflow page, delete all overflow page-map caches
8784 ** held by open cursors.
8786 invalidateAllOverflowCache(pBt);
8788 /* Read the value of meta[3] from the database to determine where the
8789 ** root page of the new table should go. meta[3] is the largest root-page
8790 ** created so far, so the new root-page is (meta[3]+1).
8792 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
8793 pgnoRoot++;
8795 /* The new root-page may not be allocated on a pointer-map page, or the
8796 ** PENDING_BYTE page.
8798 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
8799 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
8800 pgnoRoot++;
8802 assert( pgnoRoot>=3 || CORRUPT_DB );
8803 testcase( pgnoRoot<3 );
8805 /* Allocate a page. The page that currently resides at pgnoRoot will
8806 ** be moved to the allocated page (unless the allocated page happens
8807 ** to reside at pgnoRoot).
8809 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
8810 if( rc!=SQLITE_OK ){
8811 return rc;
8814 if( pgnoMove!=pgnoRoot ){
8815 /* pgnoRoot is the page that will be used for the root-page of
8816 ** the new table (assuming an error did not occur). But we were
8817 ** allocated pgnoMove. If required (i.e. if it was not allocated
8818 ** by extending the file), the current page at position pgnoMove
8819 ** is already journaled.
8821 u8 eType = 0;
8822 Pgno iPtrPage = 0;
8824 /* Save the positions of any open cursors. This is required in
8825 ** case they are holding a reference to an xFetch reference
8826 ** corresponding to page pgnoRoot. */
8827 rc = saveAllCursors(pBt, 0, 0);
8828 releasePage(pPageMove);
8829 if( rc!=SQLITE_OK ){
8830 return rc;
8833 /* Move the page currently at pgnoRoot to pgnoMove. */
8834 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
8835 if( rc!=SQLITE_OK ){
8836 return rc;
8838 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
8839 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
8840 rc = SQLITE_CORRUPT_BKPT;
8842 if( rc!=SQLITE_OK ){
8843 releasePage(pRoot);
8844 return rc;
8846 assert( eType!=PTRMAP_ROOTPAGE );
8847 assert( eType!=PTRMAP_FREEPAGE );
8848 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
8849 releasePage(pRoot);
8851 /* Obtain the page at pgnoRoot */
8852 if( rc!=SQLITE_OK ){
8853 return rc;
8855 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
8856 if( rc!=SQLITE_OK ){
8857 return rc;
8859 rc = sqlite3PagerWrite(pRoot->pDbPage);
8860 if( rc!=SQLITE_OK ){
8861 releasePage(pRoot);
8862 return rc;
8864 }else{
8865 pRoot = pPageMove;
8868 /* Update the pointer-map and meta-data with the new root-page number. */
8869 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
8870 if( rc ){
8871 releasePage(pRoot);
8872 return rc;
8875 /* When the new root page was allocated, page 1 was made writable in
8876 ** order either to increase the database filesize, or to decrement the
8877 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
8879 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
8880 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
8881 if( NEVER(rc) ){
8882 releasePage(pRoot);
8883 return rc;
8886 }else{
8887 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
8888 if( rc ) return rc;
8890 #endif
8891 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
8892 if( createTabFlags & BTREE_INTKEY ){
8893 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
8894 }else{
8895 ptfFlags = PTF_ZERODATA | PTF_LEAF;
8897 zeroPage(pRoot, ptfFlags);
8898 sqlite3PagerUnref(pRoot->pDbPage);
8899 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
8900 *piTable = (int)pgnoRoot;
8901 return SQLITE_OK;
8903 int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
8904 int rc;
8905 sqlite3BtreeEnter(p);
8906 rc = btreeCreateTable(p, piTable, flags);
8907 sqlite3BtreeLeave(p);
8908 return rc;
8912 ** Erase the given database page and all its children. Return
8913 ** the page to the freelist.
8915 static int clearDatabasePage(
8916 BtShared *pBt, /* The BTree that contains the table */
8917 Pgno pgno, /* Page number to clear */
8918 int freePageFlag, /* Deallocate page if true */
8919 int *pnChange /* Add number of Cells freed to this counter */
8921 MemPage *pPage;
8922 int rc;
8923 unsigned char *pCell;
8924 int i;
8925 int hdr;
8926 CellInfo info;
8928 assert( sqlite3_mutex_held(pBt->mutex) );
8929 if( pgno>btreePagecount(pBt) ){
8930 return SQLITE_CORRUPT_BKPT;
8932 rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
8933 if( rc ) return rc;
8934 if( pPage->bBusy ){
8935 rc = SQLITE_CORRUPT_BKPT;
8936 goto cleardatabasepage_out;
8938 pPage->bBusy = 1;
8939 hdr = pPage->hdrOffset;
8940 for(i=0; i<pPage->nCell; i++){
8941 pCell = findCell(pPage, i);
8942 if( !pPage->leaf ){
8943 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
8944 if( rc ) goto cleardatabasepage_out;
8946 rc = clearCell(pPage, pCell, &info);
8947 if( rc ) goto cleardatabasepage_out;
8949 if( !pPage->leaf ){
8950 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
8951 if( rc ) goto cleardatabasepage_out;
8952 }else if( pnChange ){
8953 assert( pPage->intKey || CORRUPT_DB );
8954 testcase( !pPage->intKey );
8955 *pnChange += pPage->nCell;
8957 if( freePageFlag ){
8958 freePage(pPage, &rc);
8959 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
8960 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
8963 cleardatabasepage_out:
8964 pPage->bBusy = 0;
8965 releasePage(pPage);
8966 return rc;
8970 ** Delete all information from a single table in the database. iTable is
8971 ** the page number of the root of the table. After this routine returns,
8972 ** the root page is empty, but still exists.
8974 ** This routine will fail with SQLITE_LOCKED if there are any open
8975 ** read cursors on the table. Open write cursors are moved to the
8976 ** root of the table.
8978 ** If pnChange is not NULL, then table iTable must be an intkey table. The
8979 ** integer value pointed to by pnChange is incremented by the number of
8980 ** entries in the table.
8982 int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
8983 int rc;
8984 BtShared *pBt = p->pBt;
8985 sqlite3BtreeEnter(p);
8986 assert( p->inTrans==TRANS_WRITE );
8988 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
8990 if( SQLITE_OK==rc ){
8991 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
8992 ** is the root of a table b-tree - if it is not, the following call is
8993 ** a no-op). */
8994 invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
8995 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
8997 sqlite3BtreeLeave(p);
8998 return rc;
9002 ** Delete all information from the single table that pCur is open on.
9004 ** This routine only work for pCur on an ephemeral table.
9006 int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
9007 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
9011 ** Erase all information in a table and add the root of the table to
9012 ** the freelist. Except, the root of the principle table (the one on
9013 ** page 1) is never added to the freelist.
9015 ** This routine will fail with SQLITE_LOCKED if there are any open
9016 ** cursors on the table.
9018 ** If AUTOVACUUM is enabled and the page at iTable is not the last
9019 ** root page in the database file, then the last root page
9020 ** in the database file is moved into the slot formerly occupied by
9021 ** iTable and that last slot formerly occupied by the last root page
9022 ** is added to the freelist instead of iTable. In this say, all
9023 ** root pages are kept at the beginning of the database file, which
9024 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
9025 ** page number that used to be the last root page in the file before
9026 ** the move. If no page gets moved, *piMoved is set to 0.
9027 ** The last root page is recorded in meta[3] and the value of
9028 ** meta[3] is updated by this procedure.
9030 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
9031 int rc;
9032 MemPage *pPage = 0;
9033 BtShared *pBt = p->pBt;
9035 assert( sqlite3BtreeHoldsMutex(p) );
9036 assert( p->inTrans==TRANS_WRITE );
9037 assert( iTable>=2 );
9039 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
9040 if( rc ) return rc;
9041 rc = sqlite3BtreeClearTable(p, iTable, 0);
9042 if( rc ){
9043 releasePage(pPage);
9044 return rc;
9047 *piMoved = 0;
9049 #ifdef SQLITE_OMIT_AUTOVACUUM
9050 freePage(pPage, &rc);
9051 releasePage(pPage);
9052 #else
9053 if( pBt->autoVacuum ){
9054 Pgno maxRootPgno;
9055 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
9057 if( iTable==maxRootPgno ){
9058 /* If the table being dropped is the table with the largest root-page
9059 ** number in the database, put the root page on the free list.
9061 freePage(pPage, &rc);
9062 releasePage(pPage);
9063 if( rc!=SQLITE_OK ){
9064 return rc;
9066 }else{
9067 /* The table being dropped does not have the largest root-page
9068 ** number in the database. So move the page that does into the
9069 ** gap left by the deleted root-page.
9071 MemPage *pMove;
9072 releasePage(pPage);
9073 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9074 if( rc!=SQLITE_OK ){
9075 return rc;
9077 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
9078 releasePage(pMove);
9079 if( rc!=SQLITE_OK ){
9080 return rc;
9082 pMove = 0;
9083 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9084 freePage(pMove, &rc);
9085 releasePage(pMove);
9086 if( rc!=SQLITE_OK ){
9087 return rc;
9089 *piMoved = maxRootPgno;
9092 /* Set the new 'max-root-page' value in the database header. This
9093 ** is the old value less one, less one more if that happens to
9094 ** be a root-page number, less one again if that is the
9095 ** PENDING_BYTE_PAGE.
9097 maxRootPgno--;
9098 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
9099 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
9100 maxRootPgno--;
9102 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
9104 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
9105 }else{
9106 freePage(pPage, &rc);
9107 releasePage(pPage);
9109 #endif
9110 return rc;
9112 int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
9113 int rc;
9114 sqlite3BtreeEnter(p);
9115 rc = btreeDropTable(p, iTable, piMoved);
9116 sqlite3BtreeLeave(p);
9117 return rc;
9122 ** This function may only be called if the b-tree connection already
9123 ** has a read or write transaction open on the database.
9125 ** Read the meta-information out of a database file. Meta[0]
9126 ** is the number of free pages currently in the database. Meta[1]
9127 ** through meta[15] are available for use by higher layers. Meta[0]
9128 ** is read-only, the others are read/write.
9130 ** The schema layer numbers meta values differently. At the schema
9131 ** layer (and the SetCookie and ReadCookie opcodes) the number of
9132 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
9134 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
9135 ** of reading the value out of the header, it instead loads the "DataVersion"
9136 ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
9137 ** database file. It is a number computed by the pager. But its access
9138 ** pattern is the same as header meta values, and so it is convenient to
9139 ** read it from this routine.
9141 void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
9142 BtShared *pBt = p->pBt;
9144 sqlite3BtreeEnter(p);
9145 assert( p->inTrans>TRANS_NONE );
9146 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
9147 assert( pBt->pPage1 );
9148 assert( idx>=0 && idx<=15 );
9150 if( idx==BTREE_DATA_VERSION ){
9151 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
9152 }else{
9153 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
9156 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
9157 ** database, mark the database as read-only. */
9158 #ifdef SQLITE_OMIT_AUTOVACUUM
9159 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
9160 pBt->btsFlags |= BTS_READ_ONLY;
9162 #endif
9164 sqlite3BtreeLeave(p);
9168 ** Write meta-information back into the database. Meta[0] is
9169 ** read-only and may not be written.
9171 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
9172 BtShared *pBt = p->pBt;
9173 unsigned char *pP1;
9174 int rc;
9175 assert( idx>=1 && idx<=15 );
9176 sqlite3BtreeEnter(p);
9177 assert( p->inTrans==TRANS_WRITE );
9178 assert( pBt->pPage1!=0 );
9179 pP1 = pBt->pPage1->aData;
9180 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
9181 if( rc==SQLITE_OK ){
9182 put4byte(&pP1[36 + idx*4], iMeta);
9183 #ifndef SQLITE_OMIT_AUTOVACUUM
9184 if( idx==BTREE_INCR_VACUUM ){
9185 assert( pBt->autoVacuum || iMeta==0 );
9186 assert( iMeta==0 || iMeta==1 );
9187 pBt->incrVacuum = (u8)iMeta;
9189 #endif
9191 sqlite3BtreeLeave(p);
9192 return rc;
9195 #ifndef SQLITE_OMIT_BTREECOUNT
9197 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
9198 ** number of entries in the b-tree and write the result to *pnEntry.
9200 ** SQLITE_OK is returned if the operation is successfully executed.
9201 ** Otherwise, if an error is encountered (i.e. an IO error or database
9202 ** corruption) an SQLite error code is returned.
9204 int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
9205 i64 nEntry = 0; /* Value to return in *pnEntry */
9206 int rc; /* Return code */
9208 rc = moveToRoot(pCur);
9209 if( rc==SQLITE_EMPTY ){
9210 *pnEntry = 0;
9211 return SQLITE_OK;
9214 /* Unless an error occurs, the following loop runs one iteration for each
9215 ** page in the B-Tree structure (not including overflow pages).
9217 while( rc==SQLITE_OK ){
9218 int iIdx; /* Index of child node in parent */
9219 MemPage *pPage; /* Current page of the b-tree */
9221 /* If this is a leaf page or the tree is not an int-key tree, then
9222 ** this page contains countable entries. Increment the entry counter
9223 ** accordingly.
9225 pPage = pCur->pPage;
9226 if( pPage->leaf || !pPage->intKey ){
9227 nEntry += pPage->nCell;
9230 /* pPage is a leaf node. This loop navigates the cursor so that it
9231 ** points to the first interior cell that it points to the parent of
9232 ** the next page in the tree that has not yet been visited. The
9233 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
9234 ** of the page, or to the number of cells in the page if the next page
9235 ** to visit is the right-child of its parent.
9237 ** If all pages in the tree have been visited, return SQLITE_OK to the
9238 ** caller.
9240 if( pPage->leaf ){
9241 do {
9242 if( pCur->iPage==0 ){
9243 /* All pages of the b-tree have been visited. Return successfully. */
9244 *pnEntry = nEntry;
9245 return moveToRoot(pCur);
9247 moveToParent(pCur);
9248 }while ( pCur->ix>=pCur->pPage->nCell );
9250 pCur->ix++;
9251 pPage = pCur->pPage;
9254 /* Descend to the child node of the cell that the cursor currently
9255 ** points at. This is the right-child if (iIdx==pPage->nCell).
9257 iIdx = pCur->ix;
9258 if( iIdx==pPage->nCell ){
9259 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
9260 }else{
9261 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
9265 /* An error has occurred. Return an error code. */
9266 return rc;
9268 #endif
9271 ** Return the pager associated with a BTree. This routine is used for
9272 ** testing and debugging only.
9274 Pager *sqlite3BtreePager(Btree *p){
9275 return p->pBt->pPager;
9278 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9280 ** Append a message to the error message string.
9282 static void checkAppendMsg(
9283 IntegrityCk *pCheck,
9284 const char *zFormat,
9287 va_list ap;
9288 if( !pCheck->mxErr ) return;
9289 pCheck->mxErr--;
9290 pCheck->nErr++;
9291 va_start(ap, zFormat);
9292 if( pCheck->errMsg.nChar ){
9293 sqlite3_str_append(&pCheck->errMsg, "\n", 1);
9295 if( pCheck->zPfx ){
9296 sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
9298 sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
9299 va_end(ap);
9300 if( pCheck->errMsg.accError==SQLITE_NOMEM ){
9301 pCheck->mallocFailed = 1;
9304 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9306 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9309 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
9310 ** corresponds to page iPg is already set.
9312 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9313 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9314 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
9318 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
9320 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9321 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9322 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
9327 ** Add 1 to the reference count for page iPage. If this is the second
9328 ** reference to the page, add an error message to pCheck->zErrMsg.
9329 ** Return 1 if there are 2 or more references to the page and 0 if
9330 ** if this is the first reference to the page.
9332 ** Also check that the page number is in bounds.
9334 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
9335 if( iPage==0 ) return 1;
9336 if( iPage>pCheck->nPage ){
9337 checkAppendMsg(pCheck, "invalid page number %d", iPage);
9338 return 1;
9340 if( getPageReferenced(pCheck, iPage) ){
9341 checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
9342 return 1;
9344 setPageReferenced(pCheck, iPage);
9345 return 0;
9348 #ifndef SQLITE_OMIT_AUTOVACUUM
9350 ** Check that the entry in the pointer-map for page iChild maps to
9351 ** page iParent, pointer type ptrType. If not, append an error message
9352 ** to pCheck.
9354 static void checkPtrmap(
9355 IntegrityCk *pCheck, /* Integrity check context */
9356 Pgno iChild, /* Child page number */
9357 u8 eType, /* Expected pointer map type */
9358 Pgno iParent /* Expected pointer map parent page number */
9360 int rc;
9361 u8 ePtrmapType;
9362 Pgno iPtrmapParent;
9364 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
9365 if( rc!=SQLITE_OK ){
9366 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
9367 checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
9368 return;
9371 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
9372 checkAppendMsg(pCheck,
9373 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
9374 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
9377 #endif
9380 ** Check the integrity of the freelist or of an overflow page list.
9381 ** Verify that the number of pages on the list is N.
9383 static void checkList(
9384 IntegrityCk *pCheck, /* Integrity checking context */
9385 int isFreeList, /* True for a freelist. False for overflow page list */
9386 int iPage, /* Page number for first page in the list */
9387 int N /* Expected number of pages in the list */
9389 int i;
9390 int expected = N;
9391 int iFirst = iPage;
9392 while( N-- > 0 && pCheck->mxErr ){
9393 DbPage *pOvflPage;
9394 unsigned char *pOvflData;
9395 if( iPage<1 ){
9396 checkAppendMsg(pCheck,
9397 "%d of %d pages missing from overflow list starting at %d",
9398 N+1, expected, iFirst);
9399 break;
9401 if( checkRef(pCheck, iPage) ) break;
9402 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
9403 checkAppendMsg(pCheck, "failed to get page %d", iPage);
9404 break;
9406 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
9407 if( isFreeList ){
9408 int n = get4byte(&pOvflData[4]);
9409 #ifndef SQLITE_OMIT_AUTOVACUUM
9410 if( pCheck->pBt->autoVacuum ){
9411 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
9413 #endif
9414 if( n>(int)pCheck->pBt->usableSize/4-2 ){
9415 checkAppendMsg(pCheck,
9416 "freelist leaf count too big on page %d", iPage);
9417 N--;
9418 }else{
9419 for(i=0; i<n; i++){
9420 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
9421 #ifndef SQLITE_OMIT_AUTOVACUUM
9422 if( pCheck->pBt->autoVacuum ){
9423 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
9425 #endif
9426 checkRef(pCheck, iFreePage);
9428 N -= n;
9431 #ifndef SQLITE_OMIT_AUTOVACUUM
9432 else{
9433 /* If this database supports auto-vacuum and iPage is not the last
9434 ** page in this overflow list, check that the pointer-map entry for
9435 ** the following page matches iPage.
9437 if( pCheck->pBt->autoVacuum && N>0 ){
9438 i = get4byte(pOvflData);
9439 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
9442 #endif
9443 iPage = get4byte(pOvflData);
9444 sqlite3PagerUnref(pOvflPage);
9446 if( isFreeList && N<(iPage!=0) ){
9447 checkAppendMsg(pCheck, "free-page count in header is too small");
9451 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9454 ** An implementation of a min-heap.
9456 ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
9457 ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
9458 ** and aHeap[N*2+1].
9460 ** The heap property is this: Every node is less than or equal to both
9461 ** of its daughter nodes. A consequence of the heap property is that the
9462 ** root node aHeap[1] is always the minimum value currently in the heap.
9464 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
9465 ** the heap, preserving the heap property. The btreeHeapPull() routine
9466 ** removes the root element from the heap (the minimum value in the heap)
9467 ** and then moves other nodes around as necessary to preserve the heap
9468 ** property.
9470 ** This heap is used for cell overlap and coverage testing. Each u32
9471 ** entry represents the span of a cell or freeblock on a btree page.
9472 ** The upper 16 bits are the index of the first byte of a range and the
9473 ** lower 16 bits are the index of the last byte of that range.
9475 static void btreeHeapInsert(u32 *aHeap, u32 x){
9476 u32 j, i = ++aHeap[0];
9477 aHeap[i] = x;
9478 while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
9479 x = aHeap[j];
9480 aHeap[j] = aHeap[i];
9481 aHeap[i] = x;
9482 i = j;
9485 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
9486 u32 j, i, x;
9487 if( (x = aHeap[0])==0 ) return 0;
9488 *pOut = aHeap[1];
9489 aHeap[1] = aHeap[x];
9490 aHeap[x] = 0xffffffff;
9491 aHeap[0]--;
9492 i = 1;
9493 while( (j = i*2)<=aHeap[0] ){
9494 if( aHeap[j]>aHeap[j+1] ) j++;
9495 if( aHeap[i]<aHeap[j] ) break;
9496 x = aHeap[i];
9497 aHeap[i] = aHeap[j];
9498 aHeap[j] = x;
9499 i = j;
9501 return 1;
9504 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9506 ** Do various sanity checks on a single page of a tree. Return
9507 ** the tree depth. Root pages return 0. Parents of root pages
9508 ** return 1, and so forth.
9510 ** These checks are done:
9512 ** 1. Make sure that cells and freeblocks do not overlap
9513 ** but combine to completely cover the page.
9514 ** 2. Make sure integer cell keys are in order.
9515 ** 3. Check the integrity of overflow pages.
9516 ** 4. Recursively call checkTreePage on all children.
9517 ** 5. Verify that the depth of all children is the same.
9519 static int checkTreePage(
9520 IntegrityCk *pCheck, /* Context for the sanity check */
9521 int iPage, /* Page number of the page to check */
9522 i64 *piMinKey, /* Write minimum integer primary key here */
9523 i64 maxKey /* Error if integer primary key greater than this */
9525 MemPage *pPage = 0; /* The page being analyzed */
9526 int i; /* Loop counter */
9527 int rc; /* Result code from subroutine call */
9528 int depth = -1, d2; /* Depth of a subtree */
9529 int pgno; /* Page number */
9530 int nFrag; /* Number of fragmented bytes on the page */
9531 int hdr; /* Offset to the page header */
9532 int cellStart; /* Offset to the start of the cell pointer array */
9533 int nCell; /* Number of cells */
9534 int doCoverageCheck = 1; /* True if cell coverage checking should be done */
9535 int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
9536 ** False if IPK must be strictly less than maxKey */
9537 u8 *data; /* Page content */
9538 u8 *pCell; /* Cell content */
9539 u8 *pCellIdx; /* Next element of the cell pointer array */
9540 BtShared *pBt; /* The BtShared object that owns pPage */
9541 u32 pc; /* Address of a cell */
9542 u32 usableSize; /* Usable size of the page */
9543 u32 contentOffset; /* Offset to the start of the cell content area */
9544 u32 *heap = 0; /* Min-heap used for checking cell coverage */
9545 u32 x, prev = 0; /* Next and previous entry on the min-heap */
9546 const char *saved_zPfx = pCheck->zPfx;
9547 int saved_v1 = pCheck->v1;
9548 int saved_v2 = pCheck->v2;
9549 u8 savedIsInit = 0;
9551 /* Check that the page exists
9553 pBt = pCheck->pBt;
9554 usableSize = pBt->usableSize;
9555 if( iPage==0 ) return 0;
9556 if( checkRef(pCheck, iPage) ) return 0;
9557 pCheck->zPfx = "Page %d: ";
9558 pCheck->v1 = iPage;
9559 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
9560 checkAppendMsg(pCheck,
9561 "unable to get the page. error code=%d", rc);
9562 goto end_of_check;
9565 /* Clear MemPage.isInit to make sure the corruption detection code in
9566 ** btreeInitPage() is executed. */
9567 savedIsInit = pPage->isInit;
9568 pPage->isInit = 0;
9569 if( (rc = btreeInitPage(pPage))!=0 ){
9570 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
9571 checkAppendMsg(pCheck,
9572 "btreeInitPage() returns error code %d", rc);
9573 goto end_of_check;
9575 data = pPage->aData;
9576 hdr = pPage->hdrOffset;
9578 /* Set up for cell analysis */
9579 pCheck->zPfx = "On tree page %d cell %d: ";
9580 contentOffset = get2byteNotZero(&data[hdr+5]);
9581 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
9583 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
9584 ** number of cells on the page. */
9585 nCell = get2byte(&data[hdr+3]);
9586 assert( pPage->nCell==nCell );
9588 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
9589 ** immediately follows the b-tree page header. */
9590 cellStart = hdr + 12 - 4*pPage->leaf;
9591 assert( pPage->aCellIdx==&data[cellStart] );
9592 pCellIdx = &data[cellStart + 2*(nCell-1)];
9594 if( !pPage->leaf ){
9595 /* Analyze the right-child page of internal pages */
9596 pgno = get4byte(&data[hdr+8]);
9597 #ifndef SQLITE_OMIT_AUTOVACUUM
9598 if( pBt->autoVacuum ){
9599 pCheck->zPfx = "On page %d at right child: ";
9600 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
9602 #endif
9603 depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
9604 keyCanBeEqual = 0;
9605 }else{
9606 /* For leaf pages, the coverage check will occur in the same loop
9607 ** as the other cell checks, so initialize the heap. */
9608 heap = pCheck->heap;
9609 heap[0] = 0;
9612 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
9613 ** integer offsets to the cell contents. */
9614 for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
9615 CellInfo info;
9617 /* Check cell size */
9618 pCheck->v2 = i;
9619 assert( pCellIdx==&data[cellStart + i*2] );
9620 pc = get2byteAligned(pCellIdx);
9621 pCellIdx -= 2;
9622 if( pc<contentOffset || pc>usableSize-4 ){
9623 checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
9624 pc, contentOffset, usableSize-4);
9625 doCoverageCheck = 0;
9626 continue;
9628 pCell = &data[pc];
9629 pPage->xParseCell(pPage, pCell, &info);
9630 if( pc+info.nSize>usableSize ){
9631 checkAppendMsg(pCheck, "Extends off end of page");
9632 doCoverageCheck = 0;
9633 continue;
9636 /* Check for integer primary key out of range */
9637 if( pPage->intKey ){
9638 if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
9639 checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
9641 maxKey = info.nKey;
9642 keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
9645 /* Check the content overflow list */
9646 if( info.nPayload>info.nLocal ){
9647 int nPage; /* Number of pages on the overflow chain */
9648 Pgno pgnoOvfl; /* First page of the overflow chain */
9649 assert( pc + info.nSize - 4 <= usableSize );
9650 nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
9651 pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
9652 #ifndef SQLITE_OMIT_AUTOVACUUM
9653 if( pBt->autoVacuum ){
9654 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
9656 #endif
9657 checkList(pCheck, 0, pgnoOvfl, nPage);
9660 if( !pPage->leaf ){
9661 /* Check sanity of left child page for internal pages */
9662 pgno = get4byte(pCell);
9663 #ifndef SQLITE_OMIT_AUTOVACUUM
9664 if( pBt->autoVacuum ){
9665 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
9667 #endif
9668 d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
9669 keyCanBeEqual = 0;
9670 if( d2!=depth ){
9671 checkAppendMsg(pCheck, "Child page depth differs");
9672 depth = d2;
9674 }else{
9675 /* Populate the coverage-checking heap for leaf pages */
9676 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
9679 *piMinKey = maxKey;
9681 /* Check for complete coverage of the page
9683 pCheck->zPfx = 0;
9684 if( doCoverageCheck && pCheck->mxErr>0 ){
9685 /* For leaf pages, the min-heap has already been initialized and the
9686 ** cells have already been inserted. But for internal pages, that has
9687 ** not yet been done, so do it now */
9688 if( !pPage->leaf ){
9689 heap = pCheck->heap;
9690 heap[0] = 0;
9691 for(i=nCell-1; i>=0; i--){
9692 u32 size;
9693 pc = get2byteAligned(&data[cellStart+i*2]);
9694 size = pPage->xCellSize(pPage, &data[pc]);
9695 btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
9698 /* Add the freeblocks to the min-heap
9700 ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
9701 ** is the offset of the first freeblock, or zero if there are no
9702 ** freeblocks on the page.
9704 i = get2byte(&data[hdr+1]);
9705 while( i>0 ){
9706 int size, j;
9707 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */
9708 size = get2byte(&data[i+2]);
9709 assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */
9710 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
9711 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
9712 ** big-endian integer which is the offset in the b-tree page of the next
9713 ** freeblock in the chain, or zero if the freeblock is the last on the
9714 ** chain. */
9715 j = get2byte(&data[i]);
9716 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
9717 ** increasing offset. */
9718 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
9719 assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */
9720 i = j;
9722 /* Analyze the min-heap looking for overlap between cells and/or
9723 ** freeblocks, and counting the number of untracked bytes in nFrag.
9725 ** Each min-heap entry is of the form: (start_address<<16)|end_address.
9726 ** There is an implied first entry the covers the page header, the cell
9727 ** pointer index, and the gap between the cell pointer index and the start
9728 ** of cell content.
9730 ** The loop below pulls entries from the min-heap in order and compares
9731 ** the start_address against the previous end_address. If there is an
9732 ** overlap, that means bytes are used multiple times. If there is a gap,
9733 ** that gap is added to the fragmentation count.
9735 nFrag = 0;
9736 prev = contentOffset - 1; /* Implied first min-heap entry */
9737 while( btreeHeapPull(heap,&x) ){
9738 if( (prev&0xffff)>=(x>>16) ){
9739 checkAppendMsg(pCheck,
9740 "Multiple uses for byte %u of page %d", x>>16, iPage);
9741 break;
9742 }else{
9743 nFrag += (x>>16) - (prev&0xffff) - 1;
9744 prev = x;
9747 nFrag += usableSize - (prev&0xffff) - 1;
9748 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
9749 ** is stored in the fifth field of the b-tree page header.
9750 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
9751 ** number of fragmented free bytes within the cell content area.
9753 if( heap[0]==0 && nFrag!=data[hdr+7] ){
9754 checkAppendMsg(pCheck,
9755 "Fragmentation of %d bytes reported as %d on page %d",
9756 nFrag, data[hdr+7], iPage);
9760 end_of_check:
9761 if( !doCoverageCheck ) pPage->isInit = savedIsInit;
9762 releasePage(pPage);
9763 pCheck->zPfx = saved_zPfx;
9764 pCheck->v1 = saved_v1;
9765 pCheck->v2 = saved_v2;
9766 return depth+1;
9768 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9770 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9772 ** This routine does a complete check of the given BTree file. aRoot[] is
9773 ** an array of pages numbers were each page number is the root page of
9774 ** a table. nRoot is the number of entries in aRoot.
9776 ** A read-only or read-write transaction must be opened before calling
9777 ** this function.
9779 ** Write the number of error seen in *pnErr. Except for some memory
9780 ** allocation errors, an error message held in memory obtained from
9781 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
9782 ** returned. If a memory allocation error occurs, NULL is returned.
9784 char *sqlite3BtreeIntegrityCheck(
9785 Btree *p, /* The btree to be checked */
9786 int *aRoot, /* An array of root pages numbers for individual trees */
9787 int nRoot, /* Number of entries in aRoot[] */
9788 int mxErr, /* Stop reporting errors after this many */
9789 int *pnErr /* Write number of errors seen to this variable */
9791 Pgno i;
9792 IntegrityCk sCheck;
9793 BtShared *pBt = p->pBt;
9794 int savedDbFlags = pBt->db->flags;
9795 char zErr[100];
9796 VVA_ONLY( int nRef );
9798 sqlite3BtreeEnter(p);
9799 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
9800 VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
9801 assert( nRef>=0 );
9802 sCheck.pBt = pBt;
9803 sCheck.pPager = pBt->pPager;
9804 sCheck.nPage = btreePagecount(sCheck.pBt);
9805 sCheck.mxErr = mxErr;
9806 sCheck.nErr = 0;
9807 sCheck.mallocFailed = 0;
9808 sCheck.zPfx = 0;
9809 sCheck.v1 = 0;
9810 sCheck.v2 = 0;
9811 sCheck.aPgRef = 0;
9812 sCheck.heap = 0;
9813 sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
9814 sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
9815 if( sCheck.nPage==0 ){
9816 goto integrity_ck_cleanup;
9819 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
9820 if( !sCheck.aPgRef ){
9821 sCheck.mallocFailed = 1;
9822 goto integrity_ck_cleanup;
9824 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
9825 if( sCheck.heap==0 ){
9826 sCheck.mallocFailed = 1;
9827 goto integrity_ck_cleanup;
9830 i = PENDING_BYTE_PAGE(pBt);
9831 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
9833 /* Check the integrity of the freelist
9835 sCheck.zPfx = "Main freelist: ";
9836 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
9837 get4byte(&pBt->pPage1->aData[36]));
9838 sCheck.zPfx = 0;
9840 /* Check all the tables.
9842 testcase( pBt->db->flags & SQLITE_CellSizeCk );
9843 pBt->db->flags &= ~SQLITE_CellSizeCk;
9844 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
9845 i64 notUsed;
9846 if( aRoot[i]==0 ) continue;
9847 #ifndef SQLITE_OMIT_AUTOVACUUM
9848 if( pBt->autoVacuum && aRoot[i]>1 ){
9849 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
9851 #endif
9852 checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
9854 pBt->db->flags = savedDbFlags;
9856 /* Make sure every page in the file is referenced
9858 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
9859 #ifdef SQLITE_OMIT_AUTOVACUUM
9860 if( getPageReferenced(&sCheck, i)==0 ){
9861 checkAppendMsg(&sCheck, "Page %d is never used", i);
9863 #else
9864 /* If the database supports auto-vacuum, make sure no tables contain
9865 ** references to pointer-map pages.
9867 if( getPageReferenced(&sCheck, i)==0 &&
9868 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
9869 checkAppendMsg(&sCheck, "Page %d is never used", i);
9871 if( getPageReferenced(&sCheck, i)!=0 &&
9872 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
9873 checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
9875 #endif
9878 /* Clean up and report errors.
9880 integrity_ck_cleanup:
9881 sqlite3PageFree(sCheck.heap);
9882 sqlite3_free(sCheck.aPgRef);
9883 if( sCheck.mallocFailed ){
9884 sqlite3_str_reset(&sCheck.errMsg);
9885 sCheck.nErr++;
9887 *pnErr = sCheck.nErr;
9888 if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
9889 /* Make sure this analysis did not leave any unref() pages. */
9890 assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
9891 sqlite3BtreeLeave(p);
9892 return sqlite3StrAccumFinish(&sCheck.errMsg);
9894 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9897 ** Return the full pathname of the underlying database file. Return
9898 ** an empty string if the database is in-memory or a TEMP database.
9900 ** The pager filename is invariant as long as the pager is
9901 ** open so it is safe to access without the BtShared mutex.
9903 const char *sqlite3BtreeGetFilename(Btree *p){
9904 assert( p->pBt->pPager!=0 );
9905 return sqlite3PagerFilename(p->pBt->pPager, 1);
9909 ** Return the pathname of the journal file for this database. The return
9910 ** value of this routine is the same regardless of whether the journal file
9911 ** has been created or not.
9913 ** The pager journal filename is invariant as long as the pager is
9914 ** open so it is safe to access without the BtShared mutex.
9916 const char *sqlite3BtreeGetJournalname(Btree *p){
9917 assert( p->pBt->pPager!=0 );
9918 return sqlite3PagerJournalname(p->pBt->pPager);
9922 ** Return non-zero if a transaction is active.
9924 int sqlite3BtreeIsInTrans(Btree *p){
9925 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
9926 return (p && (p->inTrans==TRANS_WRITE));
9929 #ifndef SQLITE_OMIT_WAL
9931 ** Run a checkpoint on the Btree passed as the first argument.
9933 ** Return SQLITE_LOCKED if this or any other connection has an open
9934 ** transaction on the shared-cache the argument Btree is connected to.
9936 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
9938 int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
9939 int rc = SQLITE_OK;
9940 if( p ){
9941 BtShared *pBt = p->pBt;
9942 sqlite3BtreeEnter(p);
9943 if( pBt->inTransaction!=TRANS_NONE ){
9944 rc = SQLITE_LOCKED;
9945 }else{
9946 rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
9948 sqlite3BtreeLeave(p);
9950 return rc;
9952 #endif
9955 ** Return non-zero if a read (or write) transaction is active.
9957 int sqlite3BtreeIsInReadTrans(Btree *p){
9958 assert( p );
9959 assert( sqlite3_mutex_held(p->db->mutex) );
9960 return p->inTrans!=TRANS_NONE;
9963 int sqlite3BtreeIsInBackup(Btree *p){
9964 assert( p );
9965 assert( sqlite3_mutex_held(p->db->mutex) );
9966 return p->nBackup!=0;
9970 ** This function returns a pointer to a blob of memory associated with
9971 ** a single shared-btree. The memory is used by client code for its own
9972 ** purposes (for example, to store a high-level schema associated with
9973 ** the shared-btree). The btree layer manages reference counting issues.
9975 ** The first time this is called on a shared-btree, nBytes bytes of memory
9976 ** are allocated, zeroed, and returned to the caller. For each subsequent
9977 ** call the nBytes parameter is ignored and a pointer to the same blob
9978 ** of memory returned.
9980 ** If the nBytes parameter is 0 and the blob of memory has not yet been
9981 ** allocated, a null pointer is returned. If the blob has already been
9982 ** allocated, it is returned as normal.
9984 ** Just before the shared-btree is closed, the function passed as the
9985 ** xFree argument when the memory allocation was made is invoked on the
9986 ** blob of allocated memory. The xFree function should not call sqlite3_free()
9987 ** on the memory, the btree layer does that.
9989 void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
9990 BtShared *pBt = p->pBt;
9991 sqlite3BtreeEnter(p);
9992 if( !pBt->pSchema && nBytes ){
9993 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
9994 pBt->xFreeSchema = xFree;
9996 sqlite3BtreeLeave(p);
9997 return pBt->pSchema;
10001 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
10002 ** btree as the argument handle holds an exclusive lock on the
10003 ** sqlite_master table. Otherwise SQLITE_OK.
10005 int sqlite3BtreeSchemaLocked(Btree *p){
10006 int rc;
10007 assert( sqlite3_mutex_held(p->db->mutex) );
10008 sqlite3BtreeEnter(p);
10009 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
10010 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
10011 sqlite3BtreeLeave(p);
10012 return rc;
10016 #ifndef SQLITE_OMIT_SHARED_CACHE
10018 ** Obtain a lock on the table whose root page is iTab. The
10019 ** lock is a write lock if isWritelock is true or a read lock
10020 ** if it is false.
10022 int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
10023 int rc = SQLITE_OK;
10024 assert( p->inTrans!=TRANS_NONE );
10025 if( p->sharable ){
10026 u8 lockType = READ_LOCK + isWriteLock;
10027 assert( READ_LOCK+1==WRITE_LOCK );
10028 assert( isWriteLock==0 || isWriteLock==1 );
10030 sqlite3BtreeEnter(p);
10031 rc = querySharedCacheTableLock(p, iTab, lockType);
10032 if( rc==SQLITE_OK ){
10033 rc = setSharedCacheTableLock(p, iTab, lockType);
10035 sqlite3BtreeLeave(p);
10037 return rc;
10039 #endif
10041 #ifndef SQLITE_OMIT_INCRBLOB
10043 ** Argument pCsr must be a cursor opened for writing on an
10044 ** INTKEY table currently pointing at a valid table entry.
10045 ** This function modifies the data stored as part of that entry.
10047 ** Only the data content may only be modified, it is not possible to
10048 ** change the length of the data stored. If this function is called with
10049 ** parameters that attempt to write past the end of the existing data,
10050 ** no modifications are made and SQLITE_CORRUPT is returned.
10052 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
10053 int rc;
10054 assert( cursorOwnsBtShared(pCsr) );
10055 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
10056 assert( pCsr->curFlags & BTCF_Incrblob );
10058 rc = restoreCursorPosition(pCsr);
10059 if( rc!=SQLITE_OK ){
10060 return rc;
10062 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
10063 if( pCsr->eState!=CURSOR_VALID ){
10064 return SQLITE_ABORT;
10067 /* Save the positions of all other cursors open on this table. This is
10068 ** required in case any of them are holding references to an xFetch
10069 ** version of the b-tree page modified by the accessPayload call below.
10071 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
10072 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
10073 ** saveAllCursors can only return SQLITE_OK.
10075 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
10076 assert( rc==SQLITE_OK );
10078 /* Check some assumptions:
10079 ** (a) the cursor is open for writing,
10080 ** (b) there is a read/write transaction open,
10081 ** (c) the connection holds a write-lock on the table (if required),
10082 ** (d) there are no conflicting read-locks, and
10083 ** (e) the cursor points at a valid row of an intKey table.
10085 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
10086 return SQLITE_READONLY;
10088 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
10089 && pCsr->pBt->inTransaction==TRANS_WRITE );
10090 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
10091 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
10092 assert( pCsr->pPage->intKey );
10094 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
10098 ** Mark this cursor as an incremental blob cursor.
10100 void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
10101 pCur->curFlags |= BTCF_Incrblob;
10102 pCur->pBtree->hasIncrblobCur = 1;
10104 #endif
10107 ** Set both the "read version" (single byte at byte offset 18) and
10108 ** "write version" (single byte at byte offset 19) fields in the database
10109 ** header to iVersion.
10111 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
10112 BtShared *pBt = pBtree->pBt;
10113 int rc; /* Return code */
10115 assert( iVersion==1 || iVersion==2 );
10117 /* If setting the version fields to 1, do not automatically open the
10118 ** WAL connection, even if the version fields are currently set to 2.
10120 pBt->btsFlags &= ~BTS_NO_WAL;
10121 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
10123 rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
10124 if( rc==SQLITE_OK ){
10125 u8 *aData = pBt->pPage1->aData;
10126 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
10127 rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
10128 if( rc==SQLITE_OK ){
10129 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
10130 if( rc==SQLITE_OK ){
10131 aData[18] = (u8)iVersion;
10132 aData[19] = (u8)iVersion;
10138 pBt->btsFlags &= ~BTS_NO_WAL;
10139 return rc;
10143 ** Return true if the cursor has a hint specified. This routine is
10144 ** only used from within assert() statements
10146 int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
10147 return (pCsr->hints & mask)!=0;
10151 ** Return true if the given Btree is read-only.
10153 int sqlite3BtreeIsReadonly(Btree *p){
10154 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
10158 ** Return the size of the header added to each page by this module.
10160 int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
10162 #if !defined(SQLITE_OMIT_SHARED_CACHE)
10164 ** Return true if the Btree passed as the only argument is sharable.
10166 int sqlite3BtreeSharable(Btree *p){
10167 return p->sharable;
10171 ** Return the number of connections to the BtShared object accessed by
10172 ** the Btree handle passed as the only argument. For private caches
10173 ** this is always 1. For shared caches it may be 1 or greater.
10175 int sqlite3BtreeConnectionCount(Btree *p){
10176 testcase( p->sharable );
10177 return p->pBt->nRef;
10179 #endif