Fix a segfault caused by having identical window functions in the select-list
[sqlite.git] / src / btree.c
blobd2c580d11d470a70099765bc9a17eaadc578f312
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);
3430 trans_begun:
3431 if( rc==SQLITE_OK ){
3432 if( pSchemaVersion ){
3433 *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
3435 if( wrflag ){
3436 /* This call makes sure that the pager has the correct number of
3437 ** open savepoints. If the second parameter is greater than 0 and
3438 ** the sub-journal is not already open, then it will be opened here.
3440 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
3444 btreeIntegrity(p);
3445 sqlite3BtreeLeave(p);
3446 return rc;
3449 #ifndef SQLITE_OMIT_AUTOVACUUM
3452 ** Set the pointer-map entries for all children of page pPage. Also, if
3453 ** pPage contains cells that point to overflow pages, set the pointer
3454 ** map entries for the overflow pages as well.
3456 static int setChildPtrmaps(MemPage *pPage){
3457 int i; /* Counter variable */
3458 int nCell; /* Number of cells in page pPage */
3459 int rc; /* Return code */
3460 BtShared *pBt = pPage->pBt;
3461 Pgno pgno = pPage->pgno;
3463 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3464 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3465 if( rc!=SQLITE_OK ) return rc;
3466 nCell = pPage->nCell;
3468 for(i=0; i<nCell; i++){
3469 u8 *pCell = findCell(pPage, i);
3471 ptrmapPutOvflPtr(pPage, pCell, &rc);
3473 if( !pPage->leaf ){
3474 Pgno childPgno = get4byte(pCell);
3475 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3479 if( !pPage->leaf ){
3480 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
3481 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3484 return rc;
3488 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
3489 ** that it points to iTo. Parameter eType describes the type of pointer to
3490 ** be modified, as follows:
3492 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
3493 ** page of pPage.
3495 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3496 ** page pointed to by one of the cells on pPage.
3498 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3499 ** overflow page in the list.
3501 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
3502 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3503 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
3504 if( eType==PTRMAP_OVERFLOW2 ){
3505 /* The pointer is always the first 4 bytes of the page in this case. */
3506 if( get4byte(pPage->aData)!=iFrom ){
3507 return SQLITE_CORRUPT_PAGE(pPage);
3509 put4byte(pPage->aData, iTo);
3510 }else{
3511 int i;
3512 int nCell;
3513 int rc;
3515 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3516 if( rc ) return rc;
3517 nCell = pPage->nCell;
3519 for(i=0; i<nCell; i++){
3520 u8 *pCell = findCell(pPage, i);
3521 if( eType==PTRMAP_OVERFLOW1 ){
3522 CellInfo info;
3523 pPage->xParseCell(pPage, pCell, &info);
3524 if( info.nLocal<info.nPayload ){
3525 if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
3526 return SQLITE_CORRUPT_PAGE(pPage);
3528 if( iFrom==get4byte(pCell+info.nSize-4) ){
3529 put4byte(pCell+info.nSize-4, iTo);
3530 break;
3533 }else{
3534 if( get4byte(pCell)==iFrom ){
3535 put4byte(pCell, iTo);
3536 break;
3541 if( i==nCell ){
3542 if( eType!=PTRMAP_BTREE ||
3543 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
3544 return SQLITE_CORRUPT_PAGE(pPage);
3546 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3549 return SQLITE_OK;
3554 ** Move the open database page pDbPage to location iFreePage in the
3555 ** database. The pDbPage reference remains valid.
3557 ** The isCommit flag indicates that there is no need to remember that
3558 ** the journal needs to be sync()ed before database page pDbPage->pgno
3559 ** can be written to. The caller has already promised not to write to that
3560 ** page.
3562 static int relocatePage(
3563 BtShared *pBt, /* Btree */
3564 MemPage *pDbPage, /* Open page to move */
3565 u8 eType, /* Pointer map 'type' entry for pDbPage */
3566 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
3567 Pgno iFreePage, /* The location to move pDbPage to */
3568 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
3570 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
3571 Pgno iDbPage = pDbPage->pgno;
3572 Pager *pPager = pBt->pPager;
3573 int rc;
3575 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3576 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
3577 assert( sqlite3_mutex_held(pBt->mutex) );
3578 assert( pDbPage->pBt==pBt );
3580 /* Move page iDbPage from its current location to page number iFreePage */
3581 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
3582 iDbPage, iFreePage, iPtrPage, eType));
3583 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
3584 if( rc!=SQLITE_OK ){
3585 return rc;
3587 pDbPage->pgno = iFreePage;
3589 /* If pDbPage was a btree-page, then it may have child pages and/or cells
3590 ** that point to overflow pages. The pointer map entries for all these
3591 ** pages need to be changed.
3593 ** If pDbPage is an overflow page, then the first 4 bytes may store a
3594 ** pointer to a subsequent overflow page. If this is the case, then
3595 ** the pointer map needs to be updated for the subsequent overflow page.
3597 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
3598 rc = setChildPtrmaps(pDbPage);
3599 if( rc!=SQLITE_OK ){
3600 return rc;
3602 }else{
3603 Pgno nextOvfl = get4byte(pDbPage->aData);
3604 if( nextOvfl!=0 ){
3605 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
3606 if( rc!=SQLITE_OK ){
3607 return rc;
3612 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3613 ** that it points at iFreePage. Also fix the pointer map entry for
3614 ** iPtrPage.
3616 if( eType!=PTRMAP_ROOTPAGE ){
3617 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
3618 if( rc!=SQLITE_OK ){
3619 return rc;
3621 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
3622 if( rc!=SQLITE_OK ){
3623 releasePage(pPtrPage);
3624 return rc;
3626 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
3627 releasePage(pPtrPage);
3628 if( rc==SQLITE_OK ){
3629 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
3632 return rc;
3635 /* Forward declaration required by incrVacuumStep(). */
3636 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
3639 ** Perform a single step of an incremental-vacuum. If successful, return
3640 ** SQLITE_OK. If there is no work to do (and therefore no point in
3641 ** calling this function again), return SQLITE_DONE. Or, if an error
3642 ** occurs, return some other error code.
3644 ** More specifically, this function attempts to re-organize the database so
3645 ** that the last page of the file currently in use is no longer in use.
3647 ** Parameter nFin is the number of pages that this database would contain
3648 ** were this function called until it returns SQLITE_DONE.
3650 ** If the bCommit parameter is non-zero, this function assumes that the
3651 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
3652 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
3653 ** operation, or false for an incremental vacuum.
3655 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
3656 Pgno nFreeList; /* Number of pages still on the free-list */
3657 int rc;
3659 assert( sqlite3_mutex_held(pBt->mutex) );
3660 assert( iLastPg>nFin );
3662 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
3663 u8 eType;
3664 Pgno iPtrPage;
3666 nFreeList = get4byte(&pBt->pPage1->aData[36]);
3667 if( nFreeList==0 ){
3668 return SQLITE_DONE;
3671 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3672 if( rc!=SQLITE_OK ){
3673 return rc;
3675 if( eType==PTRMAP_ROOTPAGE ){
3676 return SQLITE_CORRUPT_BKPT;
3679 if( eType==PTRMAP_FREEPAGE ){
3680 if( bCommit==0 ){
3681 /* Remove the page from the files free-list. This is not required
3682 ** if bCommit is non-zero. In that case, the free-list will be
3683 ** truncated to zero after this function returns, so it doesn't
3684 ** matter if it still contains some garbage entries.
3686 Pgno iFreePg;
3687 MemPage *pFreePg;
3688 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
3689 if( rc!=SQLITE_OK ){
3690 return rc;
3692 assert( iFreePg==iLastPg );
3693 releasePage(pFreePg);
3695 } else {
3696 Pgno iFreePg; /* Index of free page to move pLastPg to */
3697 MemPage *pLastPg;
3698 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
3699 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
3701 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
3702 if( rc!=SQLITE_OK ){
3703 return rc;
3706 /* If bCommit is zero, this loop runs exactly once and page pLastPg
3707 ** is swapped with the first free page pulled off the free list.
3709 ** On the other hand, if bCommit is greater than zero, then keep
3710 ** looping until a free-page located within the first nFin pages
3711 ** of the file is found.
3713 if( bCommit==0 ){
3714 eMode = BTALLOC_LE;
3715 iNear = nFin;
3717 do {
3718 MemPage *pFreePg;
3719 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
3720 if( rc!=SQLITE_OK ){
3721 releasePage(pLastPg);
3722 return rc;
3724 releasePage(pFreePg);
3725 }while( bCommit && iFreePg>nFin );
3726 assert( iFreePg<iLastPg );
3728 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
3729 releasePage(pLastPg);
3730 if( rc!=SQLITE_OK ){
3731 return rc;
3736 if( bCommit==0 ){
3737 do {
3738 iLastPg--;
3739 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
3740 pBt->bDoTruncate = 1;
3741 pBt->nPage = iLastPg;
3743 return SQLITE_OK;
3747 ** The database opened by the first argument is an auto-vacuum database
3748 ** nOrig pages in size containing nFree free pages. Return the expected
3749 ** size of the database in pages following an auto-vacuum operation.
3751 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
3752 int nEntry; /* Number of entries on one ptrmap page */
3753 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
3754 Pgno nFin; /* Return value */
3756 nEntry = pBt->usableSize/5;
3757 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
3758 nFin = nOrig - nFree - nPtrmap;
3759 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
3760 nFin--;
3762 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
3763 nFin--;
3766 return nFin;
3770 ** A write-transaction must be opened before calling this function.
3771 ** It performs a single unit of work towards an incremental vacuum.
3773 ** If the incremental vacuum is finished after this function has run,
3774 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
3775 ** SQLITE_OK is returned. Otherwise an SQLite error code.
3777 int sqlite3BtreeIncrVacuum(Btree *p){
3778 int rc;
3779 BtShared *pBt = p->pBt;
3781 sqlite3BtreeEnter(p);
3782 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
3783 if( !pBt->autoVacuum ){
3784 rc = SQLITE_DONE;
3785 }else{
3786 Pgno nOrig = btreePagecount(pBt);
3787 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
3788 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
3790 if( nOrig<nFin ){
3791 rc = SQLITE_CORRUPT_BKPT;
3792 }else if( nFree>0 ){
3793 rc = saveAllCursors(pBt, 0, 0);
3794 if( rc==SQLITE_OK ){
3795 invalidateAllOverflowCache(pBt);
3796 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
3798 if( rc==SQLITE_OK ){
3799 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3800 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
3802 }else{
3803 rc = SQLITE_DONE;
3806 sqlite3BtreeLeave(p);
3807 return rc;
3811 ** This routine is called prior to sqlite3PagerCommit when a transaction
3812 ** is committed for an auto-vacuum database.
3814 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
3815 ** the database file should be truncated to during the commit process.
3816 ** i.e. the database has been reorganized so that only the first *pnTrunc
3817 ** pages are in use.
3819 static int autoVacuumCommit(BtShared *pBt){
3820 int rc = SQLITE_OK;
3821 Pager *pPager = pBt->pPager;
3822 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
3824 assert( sqlite3_mutex_held(pBt->mutex) );
3825 invalidateAllOverflowCache(pBt);
3826 assert(pBt->autoVacuum);
3827 if( !pBt->incrVacuum ){
3828 Pgno nFin; /* Number of pages in database after autovacuuming */
3829 Pgno nFree; /* Number of pages on the freelist initially */
3830 Pgno iFree; /* The next page to be freed */
3831 Pgno nOrig; /* Database size before freeing */
3833 nOrig = btreePagecount(pBt);
3834 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
3835 /* It is not possible to create a database for which the final page
3836 ** is either a pointer-map page or the pending-byte page. If one
3837 ** is encountered, this indicates corruption.
3839 return SQLITE_CORRUPT_BKPT;
3842 nFree = get4byte(&pBt->pPage1->aData[36]);
3843 nFin = finalDbSize(pBt, nOrig, nFree);
3844 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
3845 if( nFin<nOrig ){
3846 rc = saveAllCursors(pBt, 0, 0);
3848 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
3849 rc = incrVacuumStep(pBt, nFin, iFree, 1);
3851 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
3852 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3853 put4byte(&pBt->pPage1->aData[32], 0);
3854 put4byte(&pBt->pPage1->aData[36], 0);
3855 put4byte(&pBt->pPage1->aData[28], nFin);
3856 pBt->bDoTruncate = 1;
3857 pBt->nPage = nFin;
3859 if( rc!=SQLITE_OK ){
3860 sqlite3PagerRollback(pPager);
3864 assert( nRef>=sqlite3PagerRefcount(pPager) );
3865 return rc;
3868 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
3869 # define setChildPtrmaps(x) SQLITE_OK
3870 #endif
3873 ** This routine does the first phase of a two-phase commit. This routine
3874 ** causes a rollback journal to be created (if it does not already exist)
3875 ** and populated with enough information so that if a power loss occurs
3876 ** the database can be restored to its original state by playing back
3877 ** the journal. Then the contents of the journal are flushed out to
3878 ** the disk. After the journal is safely on oxide, the changes to the
3879 ** database are written into the database file and flushed to oxide.
3880 ** At the end of this call, the rollback journal still exists on the
3881 ** disk and we are still holding all locks, so the transaction has not
3882 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
3883 ** commit process.
3885 ** This call is a no-op if no write-transaction is currently active on pBt.
3887 ** Otherwise, sync the database file for the btree pBt. zMaster points to
3888 ** the name of a master journal file that should be written into the
3889 ** individual journal file, or is NULL, indicating no master journal file
3890 ** (single database transaction).
3892 ** When this is called, the master journal should already have been
3893 ** created, populated with this journal pointer and synced to disk.
3895 ** Once this is routine has returned, the only thing required to commit
3896 ** the write-transaction for this database file is to delete the journal.
3898 int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
3899 int rc = SQLITE_OK;
3900 if( p->inTrans==TRANS_WRITE ){
3901 BtShared *pBt = p->pBt;
3902 sqlite3BtreeEnter(p);
3903 #ifndef SQLITE_OMIT_AUTOVACUUM
3904 if( pBt->autoVacuum ){
3905 rc = autoVacuumCommit(pBt);
3906 if( rc!=SQLITE_OK ){
3907 sqlite3BtreeLeave(p);
3908 return rc;
3911 if( pBt->bDoTruncate ){
3912 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
3914 #endif
3915 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
3916 sqlite3BtreeLeave(p);
3918 return rc;
3922 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
3923 ** at the conclusion of a transaction.
3925 static void btreeEndTransaction(Btree *p){
3926 BtShared *pBt = p->pBt;
3927 sqlite3 *db = p->db;
3928 assert( sqlite3BtreeHoldsMutex(p) );
3930 #ifndef SQLITE_OMIT_AUTOVACUUM
3931 pBt->bDoTruncate = 0;
3932 #endif
3933 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
3934 /* If there are other active statements that belong to this database
3935 ** handle, downgrade to a read-only transaction. The other statements
3936 ** may still be reading from the database. */
3937 downgradeAllSharedCacheTableLocks(p);
3938 p->inTrans = TRANS_READ;
3939 }else{
3940 /* If the handle had any kind of transaction open, decrement the
3941 ** transaction count of the shared btree. If the transaction count
3942 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
3943 ** call below will unlock the pager. */
3944 if( p->inTrans!=TRANS_NONE ){
3945 clearAllSharedCacheTableLocks(p);
3946 pBt->nTransaction--;
3947 if( 0==pBt->nTransaction ){
3948 pBt->inTransaction = TRANS_NONE;
3952 /* Set the current transaction state to TRANS_NONE and unlock the
3953 ** pager if this call closed the only read or write transaction. */
3954 p->inTrans = TRANS_NONE;
3955 unlockBtreeIfUnused(pBt);
3958 btreeIntegrity(p);
3962 ** Commit the transaction currently in progress.
3964 ** This routine implements the second phase of a 2-phase commit. The
3965 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
3966 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
3967 ** routine did all the work of writing information out to disk and flushing the
3968 ** contents so that they are written onto the disk platter. All this
3969 ** routine has to do is delete or truncate or zero the header in the
3970 ** the rollback journal (which causes the transaction to commit) and
3971 ** drop locks.
3973 ** Normally, if an error occurs while the pager layer is attempting to
3974 ** finalize the underlying journal file, this function returns an error and
3975 ** the upper layer will attempt a rollback. However, if the second argument
3976 ** is non-zero then this b-tree transaction is part of a multi-file
3977 ** transaction. In this case, the transaction has already been committed
3978 ** (by deleting a master journal file) and the caller will ignore this
3979 ** functions return code. So, even if an error occurs in the pager layer,
3980 ** reset the b-tree objects internal state to indicate that the write
3981 ** transaction has been closed. This is quite safe, as the pager will have
3982 ** transitioned to the error state.
3984 ** This will release the write lock on the database file. If there
3985 ** are no active cursors, it also releases the read lock.
3987 int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
3989 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
3990 sqlite3BtreeEnter(p);
3991 btreeIntegrity(p);
3993 /* If the handle has a write-transaction open, commit the shared-btrees
3994 ** transaction and set the shared state to TRANS_READ.
3996 if( p->inTrans==TRANS_WRITE ){
3997 int rc;
3998 BtShared *pBt = p->pBt;
3999 assert( pBt->inTransaction==TRANS_WRITE );
4000 assert( pBt->nTransaction>0 );
4001 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
4002 if( rc!=SQLITE_OK && bCleanup==0 ){
4003 sqlite3BtreeLeave(p);
4004 return rc;
4006 p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
4007 pBt->inTransaction = TRANS_READ;
4008 btreeClearHasContent(pBt);
4011 btreeEndTransaction(p);
4012 sqlite3BtreeLeave(p);
4013 return SQLITE_OK;
4017 ** Do both phases of a commit.
4019 int sqlite3BtreeCommit(Btree *p){
4020 int rc;
4021 sqlite3BtreeEnter(p);
4022 rc = sqlite3BtreeCommitPhaseOne(p, 0);
4023 if( rc==SQLITE_OK ){
4024 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
4026 sqlite3BtreeLeave(p);
4027 return rc;
4031 ** This routine sets the state to CURSOR_FAULT and the error
4032 ** code to errCode for every cursor on any BtShared that pBtree
4033 ** references. Or if the writeOnly flag is set to 1, then only
4034 ** trip write cursors and leave read cursors unchanged.
4036 ** Every cursor is a candidate to be tripped, including cursors
4037 ** that belong to other database connections that happen to be
4038 ** sharing the cache with pBtree.
4040 ** This routine gets called when a rollback occurs. If the writeOnly
4041 ** flag is true, then only write-cursors need be tripped - read-only
4042 ** cursors save their current positions so that they may continue
4043 ** following the rollback. Or, if writeOnly is false, all cursors are
4044 ** tripped. In general, writeOnly is false if the transaction being
4045 ** rolled back modified the database schema. In this case b-tree root
4046 ** pages may be moved or deleted from the database altogether, making
4047 ** it unsafe for read cursors to continue.
4049 ** If the writeOnly flag is true and an error is encountered while
4050 ** saving the current position of a read-only cursor, all cursors,
4051 ** including all read-cursors are tripped.
4053 ** SQLITE_OK is returned if successful, or if an error occurs while
4054 ** saving a cursor position, an SQLite error code.
4056 int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
4057 BtCursor *p;
4058 int rc = SQLITE_OK;
4060 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
4061 if( pBtree ){
4062 sqlite3BtreeEnter(pBtree);
4063 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
4064 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
4065 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
4066 rc = saveCursorPosition(p);
4067 if( rc!=SQLITE_OK ){
4068 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
4069 break;
4072 }else{
4073 sqlite3BtreeClearCursor(p);
4074 p->eState = CURSOR_FAULT;
4075 p->skipNext = errCode;
4077 btreeReleaseAllCursorPages(p);
4079 sqlite3BtreeLeave(pBtree);
4081 return rc;
4085 ** Rollback the transaction in progress.
4087 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
4088 ** Only write cursors are tripped if writeOnly is true but all cursors are
4089 ** tripped if writeOnly is false. Any attempt to use
4090 ** a tripped cursor will result in an error.
4092 ** This will release the write lock on the database file. If there
4093 ** are no active cursors, it also releases the read lock.
4095 int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
4096 int rc;
4097 BtShared *pBt = p->pBt;
4098 MemPage *pPage1;
4100 assert( writeOnly==1 || writeOnly==0 );
4101 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
4102 sqlite3BtreeEnter(p);
4103 if( tripCode==SQLITE_OK ){
4104 rc = tripCode = saveAllCursors(pBt, 0, 0);
4105 if( rc ) writeOnly = 0;
4106 }else{
4107 rc = SQLITE_OK;
4109 if( tripCode ){
4110 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
4111 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
4112 if( rc2!=SQLITE_OK ) rc = rc2;
4114 btreeIntegrity(p);
4116 if( p->inTrans==TRANS_WRITE ){
4117 int rc2;
4119 assert( TRANS_WRITE==pBt->inTransaction );
4120 rc2 = sqlite3PagerRollback(pBt->pPager);
4121 if( rc2!=SQLITE_OK ){
4122 rc = rc2;
4125 /* The rollback may have destroyed the pPage1->aData value. So
4126 ** call btreeGetPage() on page 1 again to make
4127 ** sure pPage1->aData is set correctly. */
4128 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
4129 int nPage = get4byte(28+(u8*)pPage1->aData);
4130 testcase( nPage==0 );
4131 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
4132 testcase( pBt->nPage!=nPage );
4133 pBt->nPage = nPage;
4134 releasePageOne(pPage1);
4136 assert( countValidCursors(pBt, 1)==0 );
4137 pBt->inTransaction = TRANS_READ;
4138 btreeClearHasContent(pBt);
4141 btreeEndTransaction(p);
4142 sqlite3BtreeLeave(p);
4143 return rc;
4147 ** Start a statement subtransaction. The subtransaction can be rolled
4148 ** back independently of the main transaction. You must start a transaction
4149 ** before starting a subtransaction. The subtransaction is ended automatically
4150 ** if the main transaction commits or rolls back.
4152 ** Statement subtransactions are used around individual SQL statements
4153 ** that are contained within a BEGIN...COMMIT block. If a constraint
4154 ** error occurs within the statement, the effect of that one statement
4155 ** can be rolled back without having to rollback the entire transaction.
4157 ** A statement sub-transaction is implemented as an anonymous savepoint. The
4158 ** value passed as the second parameter is the total number of savepoints,
4159 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
4160 ** are no active savepoints and no other statement-transactions open,
4161 ** iStatement is 1. This anonymous savepoint can be released or rolled back
4162 ** using the sqlite3BtreeSavepoint() function.
4164 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
4165 int rc;
4166 BtShared *pBt = p->pBt;
4167 sqlite3BtreeEnter(p);
4168 assert( p->inTrans==TRANS_WRITE );
4169 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
4170 assert( iStatement>0 );
4171 assert( iStatement>p->db->nSavepoint );
4172 assert( pBt->inTransaction==TRANS_WRITE );
4173 /* At the pager level, a statement transaction is a savepoint with
4174 ** an index greater than all savepoints created explicitly using
4175 ** SQL statements. It is illegal to open, release or rollback any
4176 ** such savepoints while the statement transaction savepoint is active.
4178 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
4179 sqlite3BtreeLeave(p);
4180 return rc;
4184 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
4185 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
4186 ** savepoint identified by parameter iSavepoint, depending on the value
4187 ** of op.
4189 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
4190 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
4191 ** contents of the entire transaction are rolled back. This is different
4192 ** from a normal transaction rollback, as no locks are released and the
4193 ** transaction remains open.
4195 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
4196 int rc = SQLITE_OK;
4197 if( p && p->inTrans==TRANS_WRITE ){
4198 BtShared *pBt = p->pBt;
4199 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
4200 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
4201 sqlite3BtreeEnter(p);
4202 if( op==SAVEPOINT_ROLLBACK ){
4203 rc = saveAllCursors(pBt, 0, 0);
4205 if( rc==SQLITE_OK ){
4206 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
4208 if( rc==SQLITE_OK ){
4209 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
4210 pBt->nPage = 0;
4212 rc = newDatabase(pBt);
4213 pBt->nPage = get4byte(28 + pBt->pPage1->aData);
4215 /* The database size was written into the offset 28 of the header
4216 ** when the transaction started, so we know that the value at offset
4217 ** 28 is nonzero. */
4218 assert( pBt->nPage>0 );
4220 sqlite3BtreeLeave(p);
4222 return rc;
4226 ** Create a new cursor for the BTree whose root is on the page
4227 ** iTable. If a read-only cursor is requested, it is assumed that
4228 ** the caller already has at least a read-only transaction open
4229 ** on the database already. If a write-cursor is requested, then
4230 ** the caller is assumed to have an open write transaction.
4232 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
4233 ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
4234 ** can be used for reading or for writing if other conditions for writing
4235 ** are also met. These are the conditions that must be met in order
4236 ** for writing to be allowed:
4238 ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
4240 ** 2: Other database connections that share the same pager cache
4241 ** but which are not in the READ_UNCOMMITTED state may not have
4242 ** cursors open with wrFlag==0 on the same table. Otherwise
4243 ** the changes made by this write cursor would be visible to
4244 ** the read cursors in the other database connection.
4246 ** 3: The database must be writable (not on read-only media)
4248 ** 4: There must be an active transaction.
4250 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
4251 ** is set. If FORDELETE is set, that is a hint to the implementation that
4252 ** this cursor will only be used to seek to and delete entries of an index
4253 ** as part of a larger DELETE statement. The FORDELETE hint is not used by
4254 ** this implementation. But in a hypothetical alternative storage engine
4255 ** in which index entries are automatically deleted when corresponding table
4256 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
4257 ** operations on this cursor can be no-ops and all READ operations can
4258 ** return a null row (2-bytes: 0x01 0x00).
4260 ** No checking is done to make sure that page iTable really is the
4261 ** root page of a b-tree. If it is not, then the cursor acquired
4262 ** will not work correctly.
4264 ** It is assumed that the sqlite3BtreeCursorZero() has been called
4265 ** on pCur to initialize the memory space prior to invoking this routine.
4267 static int btreeCursor(
4268 Btree *p, /* The btree */
4269 int iTable, /* Root page of table to open */
4270 int wrFlag, /* 1 to write. 0 read-only */
4271 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4272 BtCursor *pCur /* Space for new cursor */
4274 BtShared *pBt = p->pBt; /* Shared b-tree handle */
4275 BtCursor *pX; /* Looping over other all cursors */
4277 assert( sqlite3BtreeHoldsMutex(p) );
4278 assert( wrFlag==0
4279 || wrFlag==BTREE_WRCSR
4280 || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
4283 /* The following assert statements verify that if this is a sharable
4284 ** b-tree database, the connection is holding the required table locks,
4285 ** and that no other connection has any open cursor that conflicts with
4286 ** this lock. */
4287 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
4288 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
4290 /* Assert that the caller has opened the required transaction. */
4291 assert( p->inTrans>TRANS_NONE );
4292 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
4293 assert( pBt->pPage1 && pBt->pPage1->aData );
4294 assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
4296 if( wrFlag ){
4297 allocateTempSpace(pBt);
4298 if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
4300 if( iTable==1 && btreePagecount(pBt)==0 ){
4301 assert( wrFlag==0 );
4302 iTable = 0;
4305 /* Now that no other errors can occur, finish filling in the BtCursor
4306 ** variables and link the cursor into the BtShared list. */
4307 pCur->pgnoRoot = (Pgno)iTable;
4308 pCur->iPage = -1;
4309 pCur->pKeyInfo = pKeyInfo;
4310 pCur->pBtree = p;
4311 pCur->pBt = pBt;
4312 pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
4313 pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
4314 /* If there are two or more cursors on the same btree, then all such
4315 ** cursors *must* have the BTCF_Multiple flag set. */
4316 for(pX=pBt->pCursor; pX; pX=pX->pNext){
4317 if( pX->pgnoRoot==(Pgno)iTable ){
4318 pX->curFlags |= BTCF_Multiple;
4319 pCur->curFlags |= BTCF_Multiple;
4322 pCur->pNext = pBt->pCursor;
4323 pBt->pCursor = pCur;
4324 pCur->eState = CURSOR_INVALID;
4325 return SQLITE_OK;
4327 int sqlite3BtreeCursor(
4328 Btree *p, /* The btree */
4329 int iTable, /* Root page of table to open */
4330 int wrFlag, /* 1 to write. 0 read-only */
4331 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
4332 BtCursor *pCur /* Write new cursor here */
4334 int rc;
4335 if( iTable<1 ){
4336 rc = SQLITE_CORRUPT_BKPT;
4337 }else{
4338 sqlite3BtreeEnter(p);
4339 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4340 sqlite3BtreeLeave(p);
4342 return rc;
4346 ** Return the size of a BtCursor object in bytes.
4348 ** This interfaces is needed so that users of cursors can preallocate
4349 ** sufficient storage to hold a cursor. The BtCursor object is opaque
4350 ** to users so they cannot do the sizeof() themselves - they must call
4351 ** this routine.
4353 int sqlite3BtreeCursorSize(void){
4354 return ROUND8(sizeof(BtCursor));
4358 ** Initialize memory that will be converted into a BtCursor object.
4360 ** The simple approach here would be to memset() the entire object
4361 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
4362 ** do not need to be zeroed and they are large, so we can save a lot
4363 ** of run-time by skipping the initialization of those elements.
4365 void sqlite3BtreeCursorZero(BtCursor *p){
4366 memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
4370 ** Close a cursor. The read lock on the database file is released
4371 ** when the last cursor is closed.
4373 int sqlite3BtreeCloseCursor(BtCursor *pCur){
4374 Btree *pBtree = pCur->pBtree;
4375 if( pBtree ){
4376 BtShared *pBt = pCur->pBt;
4377 sqlite3BtreeEnter(pBtree);
4378 assert( pBt->pCursor!=0 );
4379 if( pBt->pCursor==pCur ){
4380 pBt->pCursor = pCur->pNext;
4381 }else{
4382 BtCursor *pPrev = pBt->pCursor;
4384 if( pPrev->pNext==pCur ){
4385 pPrev->pNext = pCur->pNext;
4386 break;
4388 pPrev = pPrev->pNext;
4389 }while( ALWAYS(pPrev) );
4391 btreeReleaseAllCursorPages(pCur);
4392 unlockBtreeIfUnused(pBt);
4393 sqlite3_free(pCur->aOverflow);
4394 sqlite3_free(pCur->pKey);
4395 sqlite3BtreeLeave(pBtree);
4397 return SQLITE_OK;
4401 ** Make sure the BtCursor* given in the argument has a valid
4402 ** BtCursor.info structure. If it is not already valid, call
4403 ** btreeParseCell() to fill it in.
4405 ** BtCursor.info is a cache of the information in the current cell.
4406 ** Using this cache reduces the number of calls to btreeParseCell().
4408 #ifndef NDEBUG
4409 static int cellInfoEqual(CellInfo *a, CellInfo *b){
4410 if( a->nKey!=b->nKey ) return 0;
4411 if( a->pPayload!=b->pPayload ) return 0;
4412 if( a->nPayload!=b->nPayload ) return 0;
4413 if( a->nLocal!=b->nLocal ) return 0;
4414 if( a->nSize!=b->nSize ) return 0;
4415 return 1;
4417 static void assertCellInfo(BtCursor *pCur){
4418 CellInfo info;
4419 memset(&info, 0, sizeof(info));
4420 btreeParseCell(pCur->pPage, pCur->ix, &info);
4421 assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
4423 #else
4424 #define assertCellInfo(x)
4425 #endif
4426 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
4427 if( pCur->info.nSize==0 ){
4428 pCur->curFlags |= BTCF_ValidNKey;
4429 btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
4430 }else{
4431 assertCellInfo(pCur);
4435 #ifndef NDEBUG /* The next routine used only within assert() statements */
4437 ** Return true if the given BtCursor is valid. A valid cursor is one
4438 ** that is currently pointing to a row in a (non-empty) table.
4439 ** This is a verification routine is used only within assert() statements.
4441 int sqlite3BtreeCursorIsValid(BtCursor *pCur){
4442 return pCur && pCur->eState==CURSOR_VALID;
4444 #endif /* NDEBUG */
4445 int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
4446 assert( pCur!=0 );
4447 return pCur->eState==CURSOR_VALID;
4451 ** Return the value of the integer key or "rowid" for a table btree.
4452 ** This routine is only valid for a cursor that is pointing into a
4453 ** ordinary table btree. If the cursor points to an index btree or
4454 ** is invalid, the result of this routine is undefined.
4456 i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
4457 assert( cursorHoldsMutex(pCur) );
4458 assert( pCur->eState==CURSOR_VALID );
4459 assert( pCur->curIntKey );
4460 getCellInfo(pCur);
4461 return pCur->info.nKey;
4464 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4466 ** Return the offset into the database file for the start of the
4467 ** payload to which the cursor is pointing.
4469 i64 sqlite3BtreeOffset(BtCursor *pCur){
4470 assert( cursorHoldsMutex(pCur) );
4471 assert( pCur->eState==CURSOR_VALID );
4472 getCellInfo(pCur);
4473 return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
4474 (i64)(pCur->info.pPayload - pCur->pPage->aData);
4476 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
4479 ** Return the number of bytes of payload for the entry that pCur is
4480 ** currently pointing to. For table btrees, this will be the amount
4481 ** of data. For index btrees, this will be the size of the key.
4483 ** The caller must guarantee that the cursor is pointing to a non-NULL
4484 ** valid entry. In other words, the calling procedure must guarantee
4485 ** that the cursor has Cursor.eState==CURSOR_VALID.
4487 u32 sqlite3BtreePayloadSize(BtCursor *pCur){
4488 assert( cursorHoldsMutex(pCur) );
4489 assert( pCur->eState==CURSOR_VALID );
4490 getCellInfo(pCur);
4491 return pCur->info.nPayload;
4495 ** Given the page number of an overflow page in the database (parameter
4496 ** ovfl), this function finds the page number of the next page in the
4497 ** linked list of overflow pages. If possible, it uses the auto-vacuum
4498 ** pointer-map data instead of reading the content of page ovfl to do so.
4500 ** If an error occurs an SQLite error code is returned. Otherwise:
4502 ** The page number of the next overflow page in the linked list is
4503 ** written to *pPgnoNext. If page ovfl is the last page in its linked
4504 ** list, *pPgnoNext is set to zero.
4506 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
4507 ** to page number pOvfl was obtained, then *ppPage is set to point to that
4508 ** reference. It is the responsibility of the caller to call releasePage()
4509 ** on *ppPage to free the reference. In no reference was obtained (because
4510 ** the pointer-map was used to obtain the value for *pPgnoNext), then
4511 ** *ppPage is set to zero.
4513 static int getOverflowPage(
4514 BtShared *pBt, /* The database file */
4515 Pgno ovfl, /* Current overflow page number */
4516 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
4517 Pgno *pPgnoNext /* OUT: Next overflow page number */
4519 Pgno next = 0;
4520 MemPage *pPage = 0;
4521 int rc = SQLITE_OK;
4523 assert( sqlite3_mutex_held(pBt->mutex) );
4524 assert(pPgnoNext);
4526 #ifndef SQLITE_OMIT_AUTOVACUUM
4527 /* Try to find the next page in the overflow list using the
4528 ** autovacuum pointer-map pages. Guess that the next page in
4529 ** the overflow list is page number (ovfl+1). If that guess turns
4530 ** out to be wrong, fall back to loading the data of page
4531 ** number ovfl to determine the next page number.
4533 if( pBt->autoVacuum ){
4534 Pgno pgno;
4535 Pgno iGuess = ovfl+1;
4536 u8 eType;
4538 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
4539 iGuess++;
4542 if( iGuess<=btreePagecount(pBt) ){
4543 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
4544 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
4545 next = iGuess;
4546 rc = SQLITE_DONE;
4550 #endif
4552 assert( next==0 || rc==SQLITE_DONE );
4553 if( rc==SQLITE_OK ){
4554 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
4555 assert( rc==SQLITE_OK || pPage==0 );
4556 if( rc==SQLITE_OK ){
4557 next = get4byte(pPage->aData);
4561 *pPgnoNext = next;
4562 if( ppPage ){
4563 *ppPage = pPage;
4564 }else{
4565 releasePage(pPage);
4567 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
4571 ** Copy data from a buffer to a page, or from a page to a buffer.
4573 ** pPayload is a pointer to data stored on database page pDbPage.
4574 ** If argument eOp is false, then nByte bytes of data are copied
4575 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4576 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4577 ** of data are copied from the buffer pBuf to pPayload.
4579 ** SQLITE_OK is returned on success, otherwise an error code.
4581 static int copyPayload(
4582 void *pPayload, /* Pointer to page data */
4583 void *pBuf, /* Pointer to buffer */
4584 int nByte, /* Number of bytes to copy */
4585 int eOp, /* 0 -> copy from page, 1 -> copy to page */
4586 DbPage *pDbPage /* Page containing pPayload */
4588 if( eOp ){
4589 /* Copy data from buffer to page (a write operation) */
4590 int rc = sqlite3PagerWrite(pDbPage);
4591 if( rc!=SQLITE_OK ){
4592 return rc;
4594 memcpy(pPayload, pBuf, nByte);
4595 }else{
4596 /* Copy data from page to buffer (a read operation) */
4597 memcpy(pBuf, pPayload, nByte);
4599 return SQLITE_OK;
4603 ** This function is used to read or overwrite payload information
4604 ** for the entry that the pCur cursor is pointing to. The eOp
4605 ** argument is interpreted as follows:
4607 ** 0: The operation is a read. Populate the overflow cache.
4608 ** 1: The operation is a write. Populate the overflow cache.
4610 ** A total of "amt" bytes are read or written beginning at "offset".
4611 ** Data is read to or from the buffer pBuf.
4613 ** The content being read or written might appear on the main page
4614 ** or be scattered out on multiple overflow pages.
4616 ** If the current cursor entry uses one or more overflow pages
4617 ** this function may allocate space for and lazily populate
4618 ** the overflow page-list cache array (BtCursor.aOverflow).
4619 ** Subsequent calls use this cache to make seeking to the supplied offset
4620 ** more efficient.
4622 ** Once an overflow page-list cache has been allocated, it must be
4623 ** invalidated if some other cursor writes to the same table, or if
4624 ** the cursor is moved to a different row. Additionally, in auto-vacuum
4625 ** mode, the following events may invalidate an overflow page-list cache.
4627 ** * An incremental vacuum,
4628 ** * A commit in auto_vacuum="full" mode,
4629 ** * Creating a table (may require moving an overflow page).
4631 static int accessPayload(
4632 BtCursor *pCur, /* Cursor pointing to entry to read from */
4633 u32 offset, /* Begin reading this far into payload */
4634 u32 amt, /* Read this many bytes */
4635 unsigned char *pBuf, /* Write the bytes into this buffer */
4636 int eOp /* zero to read. non-zero to write. */
4638 unsigned char *aPayload;
4639 int rc = SQLITE_OK;
4640 int iIdx = 0;
4641 MemPage *pPage = pCur->pPage; /* Btree page of current entry */
4642 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
4643 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4644 unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
4645 #endif
4647 assert( pPage );
4648 assert( eOp==0 || eOp==1 );
4649 assert( pCur->eState==CURSOR_VALID );
4650 assert( pCur->ix<pPage->nCell );
4651 assert( cursorHoldsMutex(pCur) );
4653 getCellInfo(pCur);
4654 aPayload = pCur->info.pPayload;
4655 assert( offset+amt <= pCur->info.nPayload );
4657 assert( aPayload > pPage->aData );
4658 if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
4659 /* Trying to read or write past the end of the data is an error. The
4660 ** conditional above is really:
4661 ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
4662 ** but is recast into its current form to avoid integer overflow problems
4664 return SQLITE_CORRUPT_PAGE(pPage);
4667 /* Check if data must be read/written to/from the btree page itself. */
4668 if( offset<pCur->info.nLocal ){
4669 int a = amt;
4670 if( a+offset>pCur->info.nLocal ){
4671 a = pCur->info.nLocal - offset;
4673 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
4674 offset = 0;
4675 pBuf += a;
4676 amt -= a;
4677 }else{
4678 offset -= pCur->info.nLocal;
4682 if( rc==SQLITE_OK && amt>0 ){
4683 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
4684 Pgno nextPage;
4686 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
4688 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
4690 ** The aOverflow[] array is sized at one entry for each overflow page
4691 ** in the overflow chain. The page number of the first overflow page is
4692 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
4693 ** means "not yet known" (the cache is lazily populated).
4695 if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
4696 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
4697 if( pCur->aOverflow==0
4698 || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
4700 Pgno *aNew = (Pgno*)sqlite3Realloc(
4701 pCur->aOverflow, nOvfl*2*sizeof(Pgno)
4703 if( aNew==0 ){
4704 return SQLITE_NOMEM_BKPT;
4705 }else{
4706 pCur->aOverflow = aNew;
4709 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
4710 pCur->curFlags |= BTCF_ValidOvfl;
4711 }else{
4712 /* If the overflow page-list cache has been allocated and the
4713 ** entry for the first required overflow page is valid, skip
4714 ** directly to it.
4716 if( pCur->aOverflow[offset/ovflSize] ){
4717 iIdx = (offset/ovflSize);
4718 nextPage = pCur->aOverflow[iIdx];
4719 offset = (offset%ovflSize);
4723 assert( rc==SQLITE_OK && amt>0 );
4724 while( nextPage ){
4725 /* If required, populate the overflow page-list cache. */
4726 assert( pCur->aOverflow[iIdx]==0
4727 || pCur->aOverflow[iIdx]==nextPage
4728 || CORRUPT_DB );
4729 pCur->aOverflow[iIdx] = nextPage;
4731 if( offset>=ovflSize ){
4732 /* The only reason to read this page is to obtain the page
4733 ** number for the next page in the overflow chain. The page
4734 ** data is not required. So first try to lookup the overflow
4735 ** page-list cache, if any, then fall back to the getOverflowPage()
4736 ** function.
4738 assert( pCur->curFlags & BTCF_ValidOvfl );
4739 assert( pCur->pBtree->db==pBt->db );
4740 if( pCur->aOverflow[iIdx+1] ){
4741 nextPage = pCur->aOverflow[iIdx+1];
4742 }else{
4743 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
4745 offset -= ovflSize;
4746 }else{
4747 /* Need to read this page properly. It contains some of the
4748 ** range of data that is being read (eOp==0) or written (eOp!=0).
4750 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4751 sqlite3_file *fd; /* File from which to do direct overflow read */
4752 #endif
4753 int a = amt;
4754 if( a + offset > ovflSize ){
4755 a = ovflSize - offset;
4758 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4759 /* If all the following are true:
4761 ** 1) this is a read operation, and
4762 ** 2) data is required from the start of this overflow page, and
4763 ** 3) there is no open write-transaction, and
4764 ** 4) the database is file-backed, and
4765 ** 5) the page is not in the WAL file
4766 ** 6) at least 4 bytes have already been read into the output buffer
4768 ** then data can be read directly from the database file into the
4769 ** output buffer, bypassing the page-cache altogether. This speeds
4770 ** up loading large records that span many overflow pages.
4772 if( eOp==0 /* (1) */
4773 && offset==0 /* (2) */
4774 && pBt->inTransaction==TRANS_READ /* (3) */
4775 && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (4) */
4776 && 0==sqlite3PagerUseWal(pBt->pPager, nextPage) /* (5) */
4777 && &pBuf[-4]>=pBufStart /* (6) */
4779 u8 aSave[4];
4780 u8 *aWrite = &pBuf[-4];
4781 assert( aWrite>=pBufStart ); /* due to (6) */
4782 memcpy(aSave, aWrite, 4);
4783 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
4784 nextPage = get4byte(aWrite);
4785 memcpy(aWrite, aSave, 4);
4786 }else
4787 #endif
4790 DbPage *pDbPage;
4791 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
4792 (eOp==0 ? PAGER_GET_READONLY : 0)
4794 if( rc==SQLITE_OK ){
4795 aPayload = sqlite3PagerGetData(pDbPage);
4796 nextPage = get4byte(aPayload);
4797 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
4798 sqlite3PagerUnref(pDbPage);
4799 offset = 0;
4802 amt -= a;
4803 if( amt==0 ) return rc;
4804 pBuf += a;
4806 if( rc ) break;
4807 iIdx++;
4811 if( rc==SQLITE_OK && amt>0 ){
4812 /* Overflow chain ends prematurely */
4813 return SQLITE_CORRUPT_PAGE(pPage);
4815 return rc;
4819 ** Read part of the payload for the row at which that cursor pCur is currently
4820 ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
4821 ** begins at "offset".
4823 ** pCur can be pointing to either a table or an index b-tree.
4824 ** If pointing to a table btree, then the content section is read. If
4825 ** pCur is pointing to an index b-tree then the key section is read.
4827 ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
4828 ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
4829 ** cursor might be invalid or might need to be restored before being read.
4831 ** Return SQLITE_OK on success or an error code if anything goes
4832 ** wrong. An error is returned if "offset+amt" is larger than
4833 ** the available payload.
4835 int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
4836 assert( cursorHoldsMutex(pCur) );
4837 assert( pCur->eState==CURSOR_VALID );
4838 assert( pCur->iPage>=0 && pCur->pPage );
4839 assert( pCur->ix<pCur->pPage->nCell );
4840 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
4844 ** This variant of sqlite3BtreePayload() works even if the cursor has not
4845 ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
4846 ** interface.
4848 #ifndef SQLITE_OMIT_INCRBLOB
4849 static SQLITE_NOINLINE int accessPayloadChecked(
4850 BtCursor *pCur,
4851 u32 offset,
4852 u32 amt,
4853 void *pBuf
4855 int rc;
4856 if ( pCur->eState==CURSOR_INVALID ){
4857 return SQLITE_ABORT;
4859 assert( cursorOwnsBtShared(pCur) );
4860 rc = btreeRestoreCursorPosition(pCur);
4861 return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
4863 int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
4864 if( pCur->eState==CURSOR_VALID ){
4865 assert( cursorOwnsBtShared(pCur) );
4866 return accessPayload(pCur, offset, amt, pBuf, 0);
4867 }else{
4868 return accessPayloadChecked(pCur, offset, amt, pBuf);
4871 #endif /* SQLITE_OMIT_INCRBLOB */
4874 ** Return a pointer to payload information from the entry that the
4875 ** pCur cursor is pointing to. The pointer is to the beginning of
4876 ** the key if index btrees (pPage->intKey==0) and is the data for
4877 ** table btrees (pPage->intKey==1). The number of bytes of available
4878 ** key/data is written into *pAmt. If *pAmt==0, then the value
4879 ** returned will not be a valid pointer.
4881 ** This routine is an optimization. It is common for the entire key
4882 ** and data to fit on the local page and for there to be no overflow
4883 ** pages. When that is so, this routine can be used to access the
4884 ** key and data without making a copy. If the key and/or data spills
4885 ** onto overflow pages, then accessPayload() must be used to reassemble
4886 ** the key/data and copy it into a preallocated buffer.
4888 ** The pointer returned by this routine looks directly into the cached
4889 ** page of the database. The data might change or move the next time
4890 ** any btree routine is called.
4892 static const void *fetchPayload(
4893 BtCursor *pCur, /* Cursor pointing to entry to read from */
4894 u32 *pAmt /* Write the number of available bytes here */
4896 int amt;
4897 assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
4898 assert( pCur->eState==CURSOR_VALID );
4899 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
4900 assert( cursorOwnsBtShared(pCur) );
4901 assert( pCur->ix<pCur->pPage->nCell );
4902 assert( pCur->info.nSize>0 );
4903 assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
4904 assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
4905 amt = pCur->info.nLocal;
4906 if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
4907 /* There is too little space on the page for the expected amount
4908 ** of local content. Database must be corrupt. */
4909 assert( CORRUPT_DB );
4910 amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
4912 *pAmt = (u32)amt;
4913 return (void*)pCur->info.pPayload;
4918 ** For the entry that cursor pCur is point to, return as
4919 ** many bytes of the key or data as are available on the local
4920 ** b-tree page. Write the number of available bytes into *pAmt.
4922 ** The pointer returned is ephemeral. The key/data may move
4923 ** or be destroyed on the next call to any Btree routine,
4924 ** including calls from other threads against the same cache.
4925 ** Hence, a mutex on the BtShared should be held prior to calling
4926 ** this routine.
4928 ** These routines is used to get quick access to key and data
4929 ** in the common case where no overflow pages are used.
4931 const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
4932 return fetchPayload(pCur, pAmt);
4937 ** Move the cursor down to a new child page. The newPgno argument is the
4938 ** page number of the child page to move to.
4940 ** This function returns SQLITE_CORRUPT if the page-header flags field of
4941 ** the new child page does not match the flags field of the parent (i.e.
4942 ** if an intkey page appears to be the parent of a non-intkey page, or
4943 ** vice-versa).
4945 static int moveToChild(BtCursor *pCur, u32 newPgno){
4946 BtShared *pBt = pCur->pBt;
4948 assert( cursorOwnsBtShared(pCur) );
4949 assert( pCur->eState==CURSOR_VALID );
4950 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
4951 assert( pCur->iPage>=0 );
4952 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
4953 return SQLITE_CORRUPT_BKPT;
4955 pCur->info.nSize = 0;
4956 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
4957 pCur->aiIdx[pCur->iPage] = pCur->ix;
4958 pCur->apPage[pCur->iPage] = pCur->pPage;
4959 pCur->ix = 0;
4960 pCur->iPage++;
4961 return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
4964 #ifdef SQLITE_DEBUG
4966 ** Page pParent is an internal (non-leaf) tree page. This function
4967 ** asserts that page number iChild is the left-child if the iIdx'th
4968 ** cell in page pParent. Or, if iIdx is equal to the total number of
4969 ** cells in pParent, that page number iChild is the right-child of
4970 ** the page.
4972 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
4973 if( CORRUPT_DB ) return; /* The conditions tested below might not be true
4974 ** in a corrupt database */
4975 assert( iIdx<=pParent->nCell );
4976 if( iIdx==pParent->nCell ){
4977 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
4978 }else{
4979 assert( get4byte(findCell(pParent, iIdx))==iChild );
4982 #else
4983 # define assertParentIndex(x,y,z)
4984 #endif
4987 ** Move the cursor up to the parent page.
4989 ** pCur->idx is set to the cell index that contains the pointer
4990 ** to the page we are coming from. If we are coming from the
4991 ** right-most child page then pCur->idx is set to one more than
4992 ** the largest cell index.
4994 static void moveToParent(BtCursor *pCur){
4995 MemPage *pLeaf;
4996 assert( cursorOwnsBtShared(pCur) );
4997 assert( pCur->eState==CURSOR_VALID );
4998 assert( pCur->iPage>0 );
4999 assert( pCur->pPage );
5000 assertParentIndex(
5001 pCur->apPage[pCur->iPage-1],
5002 pCur->aiIdx[pCur->iPage-1],
5003 pCur->pPage->pgno
5005 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
5006 pCur->info.nSize = 0;
5007 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5008 pCur->ix = pCur->aiIdx[pCur->iPage-1];
5009 pLeaf = pCur->pPage;
5010 pCur->pPage = pCur->apPage[--pCur->iPage];
5011 releasePageNotNull(pLeaf);
5015 ** Move the cursor to point to the root page of its b-tree structure.
5017 ** If the table has a virtual root page, then the cursor is moved to point
5018 ** to the virtual root page instead of the actual root page. A table has a
5019 ** virtual root page when the actual root page contains no cells and a
5020 ** single child page. This can only happen with the table rooted at page 1.
5022 ** If the b-tree structure is empty, the cursor state is set to
5023 ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
5024 ** the cursor is set to point to the first cell located on the root
5025 ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
5027 ** If this function returns successfully, it may be assumed that the
5028 ** page-header flags indicate that the [virtual] root-page is the expected
5029 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
5030 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
5031 ** indicating a table b-tree, or if the caller did specify a KeyInfo
5032 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
5033 ** b-tree).
5035 static int moveToRoot(BtCursor *pCur){
5036 MemPage *pRoot;
5037 int rc = SQLITE_OK;
5039 assert( cursorOwnsBtShared(pCur) );
5040 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
5041 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
5042 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
5043 assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
5044 assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
5046 if( pCur->iPage>=0 ){
5047 if( pCur->iPage ){
5048 releasePageNotNull(pCur->pPage);
5049 while( --pCur->iPage ){
5050 releasePageNotNull(pCur->apPage[pCur->iPage]);
5052 pCur->pPage = pCur->apPage[0];
5053 goto skip_init;
5055 }else if( pCur->pgnoRoot==0 ){
5056 pCur->eState = CURSOR_INVALID;
5057 return SQLITE_EMPTY;
5058 }else{
5059 assert( pCur->iPage==(-1) );
5060 if( pCur->eState>=CURSOR_REQUIRESEEK ){
5061 if( pCur->eState==CURSOR_FAULT ){
5062 assert( pCur->skipNext!=SQLITE_OK );
5063 return pCur->skipNext;
5065 sqlite3BtreeClearCursor(pCur);
5067 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
5068 0, pCur->curPagerFlags);
5069 if( rc!=SQLITE_OK ){
5070 pCur->eState = CURSOR_INVALID;
5071 return rc;
5073 pCur->iPage = 0;
5074 pCur->curIntKey = pCur->pPage->intKey;
5076 pRoot = pCur->pPage;
5077 assert( pRoot->pgno==pCur->pgnoRoot );
5079 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
5080 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
5081 ** NULL, the caller expects a table b-tree. If this is not the case,
5082 ** return an SQLITE_CORRUPT error.
5084 ** Earlier versions of SQLite assumed that this test could not fail
5085 ** if the root page was already loaded when this function was called (i.e.
5086 ** if pCur->iPage>=0). But this is not so if the database is corrupted
5087 ** in such a way that page pRoot is linked into a second b-tree table
5088 ** (or the freelist). */
5089 assert( pRoot->intKey==1 || pRoot->intKey==0 );
5090 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
5091 return SQLITE_CORRUPT_PAGE(pCur->pPage);
5094 skip_init:
5095 pCur->ix = 0;
5096 pCur->info.nSize = 0;
5097 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
5099 pRoot = pCur->pPage;
5100 if( pRoot->nCell>0 ){
5101 pCur->eState = CURSOR_VALID;
5102 }else if( !pRoot->leaf ){
5103 Pgno subpage;
5104 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
5105 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
5106 pCur->eState = CURSOR_VALID;
5107 rc = moveToChild(pCur, subpage);
5108 }else{
5109 pCur->eState = CURSOR_INVALID;
5110 rc = SQLITE_EMPTY;
5112 return rc;
5116 ** Move the cursor down to the left-most leaf entry beneath the
5117 ** entry to which it is currently pointing.
5119 ** The left-most leaf is the one with the smallest key - the first
5120 ** in ascending order.
5122 static int moveToLeftmost(BtCursor *pCur){
5123 Pgno pgno;
5124 int rc = SQLITE_OK;
5125 MemPage *pPage;
5127 assert( cursorOwnsBtShared(pCur) );
5128 assert( pCur->eState==CURSOR_VALID );
5129 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
5130 assert( pCur->ix<pPage->nCell );
5131 pgno = get4byte(findCell(pPage, pCur->ix));
5132 rc = moveToChild(pCur, pgno);
5134 return rc;
5138 ** Move the cursor down to the right-most leaf entry beneath the
5139 ** page to which it is currently pointing. Notice the difference
5140 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
5141 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
5142 ** finds the right-most entry beneath the *page*.
5144 ** The right-most entry is the one with the largest key - the last
5145 ** key in ascending order.
5147 static int moveToRightmost(BtCursor *pCur){
5148 Pgno pgno;
5149 int rc = SQLITE_OK;
5150 MemPage *pPage = 0;
5152 assert( cursorOwnsBtShared(pCur) );
5153 assert( pCur->eState==CURSOR_VALID );
5154 while( !(pPage = pCur->pPage)->leaf ){
5155 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5156 pCur->ix = pPage->nCell;
5157 rc = moveToChild(pCur, pgno);
5158 if( rc ) return rc;
5160 pCur->ix = pPage->nCell-1;
5161 assert( pCur->info.nSize==0 );
5162 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
5163 return SQLITE_OK;
5166 /* Move the cursor to the first entry in the table. Return SQLITE_OK
5167 ** on success. Set *pRes to 0 if the cursor actually points to something
5168 ** or set *pRes to 1 if the table is empty.
5170 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
5171 int rc;
5173 assert( cursorOwnsBtShared(pCur) );
5174 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5175 rc = moveToRoot(pCur);
5176 if( rc==SQLITE_OK ){
5177 assert( pCur->pPage->nCell>0 );
5178 *pRes = 0;
5179 rc = moveToLeftmost(pCur);
5180 }else if( rc==SQLITE_EMPTY ){
5181 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5182 *pRes = 1;
5183 rc = SQLITE_OK;
5185 return rc;
5189 ** This function is a no-op if cursor pCur does not point to a valid row.
5190 ** Otherwise, if pCur is valid, configure it so that the next call to
5191 ** sqlite3BtreeNext() is a no-op.
5193 #ifndef SQLITE_OMIT_WINDOWFUNC
5194 void sqlite3BtreeSkipNext(BtCursor *pCur){
5195 if( pCur->eState==CURSOR_VALID ){
5196 pCur->eState = CURSOR_SKIPNEXT;
5197 pCur->skipNext = 1;
5200 #endif /* SQLITE_OMIT_WINDOWFUNC */
5202 /* Move the cursor to the last entry in the table. Return SQLITE_OK
5203 ** on success. Set *pRes to 0 if the cursor actually points to something
5204 ** or set *pRes to 1 if the table is empty.
5206 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
5207 int rc;
5209 assert( cursorOwnsBtShared(pCur) );
5210 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5212 /* If the cursor already points to the last entry, this is a no-op. */
5213 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
5214 #ifdef SQLITE_DEBUG
5215 /* This block serves to assert() that the cursor really does point
5216 ** to the last entry in the b-tree. */
5217 int ii;
5218 for(ii=0; ii<pCur->iPage; ii++){
5219 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
5221 assert( pCur->ix==pCur->pPage->nCell-1 );
5222 assert( pCur->pPage->leaf );
5223 #endif
5224 return SQLITE_OK;
5227 rc = moveToRoot(pCur);
5228 if( rc==SQLITE_OK ){
5229 assert( pCur->eState==CURSOR_VALID );
5230 *pRes = 0;
5231 rc = moveToRightmost(pCur);
5232 if( rc==SQLITE_OK ){
5233 pCur->curFlags |= BTCF_AtLast;
5234 }else{
5235 pCur->curFlags &= ~BTCF_AtLast;
5237 }else if( rc==SQLITE_EMPTY ){
5238 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5239 *pRes = 1;
5240 rc = SQLITE_OK;
5242 return rc;
5245 /* Move the cursor so that it points to an entry near the key
5246 ** specified by pIdxKey or intKey. Return a success code.
5248 ** For INTKEY tables, the intKey parameter is used. pIdxKey
5249 ** must be NULL. For index tables, pIdxKey is used and intKey
5250 ** is ignored.
5252 ** If an exact match is not found, then the cursor is always
5253 ** left pointing at a leaf page which would hold the entry if it
5254 ** were present. The cursor might point to an entry that comes
5255 ** before or after the key.
5257 ** An integer is written into *pRes which is the result of
5258 ** comparing the key with the entry to which the cursor is
5259 ** pointing. The meaning of the integer written into
5260 ** *pRes is as follows:
5262 ** *pRes<0 The cursor is left pointing at an entry that
5263 ** is smaller than intKey/pIdxKey or if the table is empty
5264 ** and the cursor is therefore left point to nothing.
5266 ** *pRes==0 The cursor is left pointing at an entry that
5267 ** exactly matches intKey/pIdxKey.
5269 ** *pRes>0 The cursor is left pointing at an entry that
5270 ** is larger than intKey/pIdxKey.
5272 ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
5273 ** exists an entry in the table that exactly matches pIdxKey.
5275 int sqlite3BtreeMovetoUnpacked(
5276 BtCursor *pCur, /* The cursor to be moved */
5277 UnpackedRecord *pIdxKey, /* Unpacked index key */
5278 i64 intKey, /* The table key */
5279 int biasRight, /* If true, bias the search to the high end */
5280 int *pRes /* Write search results here */
5282 int rc;
5283 RecordCompare xRecordCompare;
5285 assert( cursorOwnsBtShared(pCur) );
5286 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5287 assert( pRes );
5288 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
5289 assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
5291 /* If the cursor is already positioned at the point we are trying
5292 ** to move to, then just return without doing any work */
5293 if( pIdxKey==0
5294 && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
5296 if( pCur->info.nKey==intKey ){
5297 *pRes = 0;
5298 return SQLITE_OK;
5300 if( pCur->info.nKey<intKey ){
5301 if( (pCur->curFlags & BTCF_AtLast)!=0 ){
5302 *pRes = -1;
5303 return SQLITE_OK;
5305 /* If the requested key is one more than the previous key, then
5306 ** try to get there using sqlite3BtreeNext() rather than a full
5307 ** binary search. This is an optimization only. The correct answer
5308 ** is still obtained without this case, only a little more slowely */
5309 if( pCur->info.nKey+1==intKey && !pCur->skipNext ){
5310 *pRes = 0;
5311 rc = sqlite3BtreeNext(pCur, 0);
5312 if( rc==SQLITE_OK ){
5313 getCellInfo(pCur);
5314 if( pCur->info.nKey==intKey ){
5315 return SQLITE_OK;
5317 }else if( rc==SQLITE_DONE ){
5318 rc = SQLITE_OK;
5319 }else{
5320 return rc;
5326 if( pIdxKey ){
5327 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
5328 pIdxKey->errCode = 0;
5329 assert( pIdxKey->default_rc==1
5330 || pIdxKey->default_rc==0
5331 || pIdxKey->default_rc==-1
5333 }else{
5334 xRecordCompare = 0; /* All keys are integers */
5337 rc = moveToRoot(pCur);
5338 if( rc ){
5339 if( rc==SQLITE_EMPTY ){
5340 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5341 *pRes = -1;
5342 return SQLITE_OK;
5344 return rc;
5346 assert( pCur->pPage );
5347 assert( pCur->pPage->isInit );
5348 assert( pCur->eState==CURSOR_VALID );
5349 assert( pCur->pPage->nCell > 0 );
5350 assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
5351 assert( pCur->curIntKey || pIdxKey );
5352 for(;;){
5353 int lwr, upr, idx, c;
5354 Pgno chldPg;
5355 MemPage *pPage = pCur->pPage;
5356 u8 *pCell; /* Pointer to current cell in pPage */
5358 /* pPage->nCell must be greater than zero. If this is the root-page
5359 ** the cursor would have been INVALID above and this for(;;) loop
5360 ** not run. If this is not the root-page, then the moveToChild() routine
5361 ** would have already detected db corruption. Similarly, pPage must
5362 ** be the right kind (index or table) of b-tree page. Otherwise
5363 ** a moveToChild() or moveToRoot() call would have detected corruption. */
5364 assert( pPage->nCell>0 );
5365 assert( pPage->intKey==(pIdxKey==0) );
5366 lwr = 0;
5367 upr = pPage->nCell-1;
5368 assert( biasRight==0 || biasRight==1 );
5369 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
5370 pCur->ix = (u16)idx;
5371 if( xRecordCompare==0 ){
5372 for(;;){
5373 i64 nCellKey;
5374 pCell = findCellPastPtr(pPage, idx);
5375 if( pPage->intKeyLeaf ){
5376 while( 0x80 <= *(pCell++) ){
5377 if( pCell>=pPage->aDataEnd ){
5378 return SQLITE_CORRUPT_PAGE(pPage);
5382 getVarint(pCell, (u64*)&nCellKey);
5383 if( nCellKey<intKey ){
5384 lwr = idx+1;
5385 if( lwr>upr ){ c = -1; break; }
5386 }else if( nCellKey>intKey ){
5387 upr = idx-1;
5388 if( lwr>upr ){ c = +1; break; }
5389 }else{
5390 assert( nCellKey==intKey );
5391 pCur->ix = (u16)idx;
5392 if( !pPage->leaf ){
5393 lwr = idx;
5394 goto moveto_next_layer;
5395 }else{
5396 pCur->curFlags |= BTCF_ValidNKey;
5397 pCur->info.nKey = nCellKey;
5398 pCur->info.nSize = 0;
5399 *pRes = 0;
5400 return SQLITE_OK;
5403 assert( lwr+upr>=0 );
5404 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
5406 }else{
5407 for(;;){
5408 int nCell; /* Size of the pCell cell in bytes */
5409 pCell = findCellPastPtr(pPage, idx);
5411 /* The maximum supported page-size is 65536 bytes. This means that
5412 ** the maximum number of record bytes stored on an index B-Tree
5413 ** page is less than 16384 bytes and may be stored as a 2-byte
5414 ** varint. This information is used to attempt to avoid parsing
5415 ** the entire cell by checking for the cases where the record is
5416 ** stored entirely within the b-tree page by inspecting the first
5417 ** 2 bytes of the cell.
5419 nCell = pCell[0];
5420 if( nCell<=pPage->max1bytePayload ){
5421 /* This branch runs if the record-size field of the cell is a
5422 ** single byte varint and the record fits entirely on the main
5423 ** b-tree page. */
5424 testcase( pCell+nCell+1==pPage->aDataEnd );
5425 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
5426 }else if( !(pCell[1] & 0x80)
5427 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5429 /* The record-size field is a 2 byte varint and the record
5430 ** fits entirely on the main b-tree page. */
5431 testcase( pCell+nCell+2==pPage->aDataEnd );
5432 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
5433 }else{
5434 /* The record flows over onto one or more overflow pages. In
5435 ** this case the whole cell needs to be parsed, a buffer allocated
5436 ** and accessPayload() used to retrieve the record into the
5437 ** buffer before VdbeRecordCompare() can be called.
5439 ** If the record is corrupt, the xRecordCompare routine may read
5440 ** up to two varints past the end of the buffer. An extra 18
5441 ** bytes of padding is allocated at the end of the buffer in
5442 ** case this happens. */
5443 void *pCellKey;
5444 u8 * const pCellBody = pCell - pPage->childPtrSize;
5445 pPage->xParseCell(pPage, pCellBody, &pCur->info);
5446 nCell = (int)pCur->info.nKey;
5447 testcase( nCell<0 ); /* True if key size is 2^32 or more */
5448 testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
5449 testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
5450 testcase( nCell==2 ); /* Minimum legal index key size */
5451 if( nCell<2 ){
5452 rc = SQLITE_CORRUPT_PAGE(pPage);
5453 goto moveto_finish;
5455 pCellKey = sqlite3Malloc( nCell+18 );
5456 if( pCellKey==0 ){
5457 rc = SQLITE_NOMEM_BKPT;
5458 goto moveto_finish;
5460 pCur->ix = (u16)idx;
5461 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
5462 pCur->curFlags &= ~BTCF_ValidOvfl;
5463 if( rc ){
5464 sqlite3_free(pCellKey);
5465 goto moveto_finish;
5467 c = xRecordCompare(nCell, pCellKey, pIdxKey);
5468 sqlite3_free(pCellKey);
5470 assert(
5471 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
5472 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
5474 if( c<0 ){
5475 lwr = idx+1;
5476 }else if( c>0 ){
5477 upr = idx-1;
5478 }else{
5479 assert( c==0 );
5480 *pRes = 0;
5481 rc = SQLITE_OK;
5482 pCur->ix = (u16)idx;
5483 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
5484 goto moveto_finish;
5486 if( lwr>upr ) break;
5487 assert( lwr+upr>=0 );
5488 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
5491 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
5492 assert( pPage->isInit );
5493 if( pPage->leaf ){
5494 assert( pCur->ix<pCur->pPage->nCell );
5495 pCur->ix = (u16)idx;
5496 *pRes = c;
5497 rc = SQLITE_OK;
5498 goto moveto_finish;
5500 moveto_next_layer:
5501 if( lwr>=pPage->nCell ){
5502 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5503 }else{
5504 chldPg = get4byte(findCell(pPage, lwr));
5506 pCur->ix = (u16)lwr;
5507 rc = moveToChild(pCur, chldPg);
5508 if( rc ) break;
5510 moveto_finish:
5511 pCur->info.nSize = 0;
5512 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5513 return rc;
5518 ** Return TRUE if the cursor is not pointing at an entry of the table.
5520 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
5521 ** past the last entry in the table or sqlite3BtreePrev() moves past
5522 ** the first entry. TRUE is also returned if the table is empty.
5524 int sqlite3BtreeEof(BtCursor *pCur){
5525 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
5526 ** have been deleted? This API will need to change to return an error code
5527 ** as well as the boolean result value.
5529 return (CURSOR_VALID!=pCur->eState);
5533 ** Return an estimate for the number of rows in the table that pCur is
5534 ** pointing to. Return a negative number if no estimate is currently
5535 ** available.
5537 i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
5538 i64 n;
5539 u8 i;
5541 assert( cursorOwnsBtShared(pCur) );
5542 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5544 /* Currently this interface is only called by the OP_IfSmaller
5545 ** opcode, and it that case the cursor will always be valid and
5546 ** will always point to a leaf node. */
5547 if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
5548 if( NEVER(pCur->pPage->leaf==0) ) return -1;
5550 n = pCur->pPage->nCell;
5551 for(i=0; i<pCur->iPage; i++){
5552 n *= pCur->apPage[i]->nCell;
5554 return n;
5558 ** Advance the cursor to the next entry in the database.
5559 ** Return value:
5561 ** SQLITE_OK success
5562 ** SQLITE_DONE cursor is already pointing at the last element
5563 ** otherwise some kind of error occurred
5565 ** The main entry point is sqlite3BtreeNext(). That routine is optimized
5566 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
5567 ** to the next cell on the current page. The (slower) btreeNext() helper
5568 ** routine is called when it is necessary to move to a different page or
5569 ** to restore the cursor.
5571 ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
5572 ** cursor corresponds to an SQL index and this routine could have been
5573 ** skipped if the SQL index had been a unique index. The F argument
5574 ** is a hint to the implement. SQLite btree implementation does not use
5575 ** this hint, but COMDB2 does.
5577 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
5578 int rc;
5579 int idx;
5580 MemPage *pPage;
5582 assert( cursorOwnsBtShared(pCur) );
5583 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5584 if( pCur->eState!=CURSOR_VALID ){
5585 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5586 rc = restoreCursorPosition(pCur);
5587 if( rc!=SQLITE_OK ){
5588 return rc;
5590 if( CURSOR_INVALID==pCur->eState ){
5591 return SQLITE_DONE;
5593 if( pCur->skipNext ){
5594 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
5595 pCur->eState = CURSOR_VALID;
5596 if( pCur->skipNext>0 ){
5597 pCur->skipNext = 0;
5598 return SQLITE_OK;
5600 pCur->skipNext = 0;
5604 pPage = pCur->pPage;
5605 idx = ++pCur->ix;
5606 if( !pPage->isInit ){
5607 /* The only known way for this to happen is for there to be a
5608 ** recursive SQL function that does a DELETE operation as part of a
5609 ** SELECT which deletes content out from under an active cursor
5610 ** in a corrupt database file where the table being DELETE-ed from
5611 ** has pages in common with the table being queried. See TH3
5612 ** module cov1/btree78.test testcase 220 (2018-06-08) for an
5613 ** example. */
5614 return SQLITE_CORRUPT_BKPT;
5617 /* If the database file is corrupt, it is possible for the value of idx
5618 ** to be invalid here. This can only occur if a second cursor modifies
5619 ** the page while cursor pCur is holding a reference to it. Which can
5620 ** only happen if the database is corrupt in such a way as to link the
5621 ** page into more than one b-tree structure. */
5622 testcase( idx>pPage->nCell );
5624 if( idx>=pPage->nCell ){
5625 if( !pPage->leaf ){
5626 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
5627 if( rc ) return rc;
5628 return moveToLeftmost(pCur);
5631 if( pCur->iPage==0 ){
5632 pCur->eState = CURSOR_INVALID;
5633 return SQLITE_DONE;
5635 moveToParent(pCur);
5636 pPage = pCur->pPage;
5637 }while( pCur->ix>=pPage->nCell );
5638 if( pPage->intKey ){
5639 return sqlite3BtreeNext(pCur, 0);
5640 }else{
5641 return SQLITE_OK;
5644 if( pPage->leaf ){
5645 return SQLITE_OK;
5646 }else{
5647 return moveToLeftmost(pCur);
5650 int sqlite3BtreeNext(BtCursor *pCur, int flags){
5651 MemPage *pPage;
5652 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
5653 assert( cursorOwnsBtShared(pCur) );
5654 assert( flags==0 || flags==1 );
5655 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5656 pCur->info.nSize = 0;
5657 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5658 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
5659 pPage = pCur->pPage;
5660 if( (++pCur->ix)>=pPage->nCell ){
5661 pCur->ix--;
5662 return btreeNext(pCur);
5664 if( pPage->leaf ){
5665 return SQLITE_OK;
5666 }else{
5667 return moveToLeftmost(pCur);
5672 ** Step the cursor to the back to the previous entry in the database.
5673 ** Return values:
5675 ** SQLITE_OK success
5676 ** SQLITE_DONE the cursor is already on the first element of the table
5677 ** otherwise some kind of error occurred
5679 ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
5680 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
5681 ** to the previous cell on the current page. The (slower) btreePrevious()
5682 ** helper routine is called when it is necessary to move to a different page
5683 ** or to restore the cursor.
5685 ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
5686 ** the cursor corresponds to an SQL index and this routine could have been
5687 ** skipped if the SQL index had been a unique index. The F argument is a
5688 ** hint to the implement. The native SQLite btree implementation does not
5689 ** use this hint, but COMDB2 does.
5691 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
5692 int rc;
5693 MemPage *pPage;
5695 assert( cursorOwnsBtShared(pCur) );
5696 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5697 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
5698 assert( pCur->info.nSize==0 );
5699 if( pCur->eState!=CURSOR_VALID ){
5700 rc = restoreCursorPosition(pCur);
5701 if( rc!=SQLITE_OK ){
5702 return rc;
5704 if( CURSOR_INVALID==pCur->eState ){
5705 return SQLITE_DONE;
5707 if( pCur->skipNext ){
5708 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
5709 pCur->eState = CURSOR_VALID;
5710 if( pCur->skipNext<0 ){
5711 pCur->skipNext = 0;
5712 return SQLITE_OK;
5714 pCur->skipNext = 0;
5718 pPage = pCur->pPage;
5719 assert( pPage->isInit );
5720 if( !pPage->leaf ){
5721 int idx = pCur->ix;
5722 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
5723 if( rc ) return rc;
5724 rc = moveToRightmost(pCur);
5725 }else{
5726 while( pCur->ix==0 ){
5727 if( pCur->iPage==0 ){
5728 pCur->eState = CURSOR_INVALID;
5729 return SQLITE_DONE;
5731 moveToParent(pCur);
5733 assert( pCur->info.nSize==0 );
5734 assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
5736 pCur->ix--;
5737 pPage = pCur->pPage;
5738 if( pPage->intKey && !pPage->leaf ){
5739 rc = sqlite3BtreePrevious(pCur, 0);
5740 }else{
5741 rc = SQLITE_OK;
5744 return rc;
5746 int sqlite3BtreePrevious(BtCursor *pCur, int flags){
5747 assert( cursorOwnsBtShared(pCur) );
5748 assert( flags==0 || flags==1 );
5749 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5750 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
5751 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
5752 pCur->info.nSize = 0;
5753 if( pCur->eState!=CURSOR_VALID
5754 || pCur->ix==0
5755 || pCur->pPage->leaf==0
5757 return btreePrevious(pCur);
5759 pCur->ix--;
5760 return SQLITE_OK;
5764 ** Allocate a new page from the database file.
5766 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
5767 ** has already been called on the new page.) The new page has also
5768 ** been referenced and the calling routine is responsible for calling
5769 ** sqlite3PagerUnref() on the new page when it is done.
5771 ** SQLITE_OK is returned on success. Any other return value indicates
5772 ** an error. *ppPage is set to NULL in the event of an error.
5774 ** If the "nearby" parameter is not 0, then an effort is made to
5775 ** locate a page close to the page number "nearby". This can be used in an
5776 ** attempt to keep related pages close to each other in the database file,
5777 ** which in turn can make database access faster.
5779 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
5780 ** anywhere on the free-list, then it is guaranteed to be returned. If
5781 ** eMode is BTALLOC_LT then the page returned will be less than or equal
5782 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
5783 ** are no restrictions on which page is returned.
5785 static int allocateBtreePage(
5786 BtShared *pBt, /* The btree */
5787 MemPage **ppPage, /* Store pointer to the allocated page here */
5788 Pgno *pPgno, /* Store the page number here */
5789 Pgno nearby, /* Search for a page near this one */
5790 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
5792 MemPage *pPage1;
5793 int rc;
5794 u32 n; /* Number of pages on the freelist */
5795 u32 k; /* Number of leaves on the trunk of the freelist */
5796 MemPage *pTrunk = 0;
5797 MemPage *pPrevTrunk = 0;
5798 Pgno mxPage; /* Total size of the database file */
5800 assert( sqlite3_mutex_held(pBt->mutex) );
5801 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
5802 pPage1 = pBt->pPage1;
5803 mxPage = btreePagecount(pBt);
5804 /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
5805 ** stores stores the total number of pages on the freelist. */
5806 n = get4byte(&pPage1->aData[36]);
5807 testcase( n==mxPage-1 );
5808 if( n>=mxPage ){
5809 return SQLITE_CORRUPT_BKPT;
5811 if( n>0 ){
5812 /* There are pages on the freelist. Reuse one of those pages. */
5813 Pgno iTrunk;
5814 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
5815 u32 nSearch = 0; /* Count of the number of search attempts */
5817 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
5818 ** shows that the page 'nearby' is somewhere on the free-list, then
5819 ** the entire-list will be searched for that page.
5821 #ifndef SQLITE_OMIT_AUTOVACUUM
5822 if( eMode==BTALLOC_EXACT ){
5823 if( nearby<=mxPage ){
5824 u8 eType;
5825 assert( nearby>0 );
5826 assert( pBt->autoVacuum );
5827 rc = ptrmapGet(pBt, nearby, &eType, 0);
5828 if( rc ) return rc;
5829 if( eType==PTRMAP_FREEPAGE ){
5830 searchList = 1;
5833 }else if( eMode==BTALLOC_LE ){
5834 searchList = 1;
5836 #endif
5838 /* Decrement the free-list count by 1. Set iTrunk to the index of the
5839 ** first free-list trunk page. iPrevTrunk is initially 1.
5841 rc = sqlite3PagerWrite(pPage1->pDbPage);
5842 if( rc ) return rc;
5843 put4byte(&pPage1->aData[36], n-1);
5845 /* The code within this loop is run only once if the 'searchList' variable
5846 ** is not true. Otherwise, it runs once for each trunk-page on the
5847 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
5848 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
5850 do {
5851 pPrevTrunk = pTrunk;
5852 if( pPrevTrunk ){
5853 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
5854 ** is the page number of the next freelist trunk page in the list or
5855 ** zero if this is the last freelist trunk page. */
5856 iTrunk = get4byte(&pPrevTrunk->aData[0]);
5857 }else{
5858 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
5859 ** stores the page number of the first page of the freelist, or zero if
5860 ** the freelist is empty. */
5861 iTrunk = get4byte(&pPage1->aData[32]);
5863 testcase( iTrunk==mxPage );
5864 if( iTrunk>mxPage || nSearch++ > n ){
5865 rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
5866 }else{
5867 rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
5869 if( rc ){
5870 pTrunk = 0;
5871 goto end_allocate_page;
5873 assert( pTrunk!=0 );
5874 assert( pTrunk->aData!=0 );
5875 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
5876 ** is the number of leaf page pointers to follow. */
5877 k = get4byte(&pTrunk->aData[4]);
5878 if( k==0 && !searchList ){
5879 /* The trunk has no leaves and the list is not being searched.
5880 ** So extract the trunk page itself and use it as the newly
5881 ** allocated page */
5882 assert( pPrevTrunk==0 );
5883 rc = sqlite3PagerWrite(pTrunk->pDbPage);
5884 if( rc ){
5885 goto end_allocate_page;
5887 *pPgno = iTrunk;
5888 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5889 *ppPage = pTrunk;
5890 pTrunk = 0;
5891 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
5892 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
5893 /* Value of k is out of range. Database corruption */
5894 rc = SQLITE_CORRUPT_PGNO(iTrunk);
5895 goto end_allocate_page;
5896 #ifndef SQLITE_OMIT_AUTOVACUUM
5897 }else if( searchList
5898 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
5900 /* The list is being searched and this trunk page is the page
5901 ** to allocate, regardless of whether it has leaves.
5903 *pPgno = iTrunk;
5904 *ppPage = pTrunk;
5905 searchList = 0;
5906 rc = sqlite3PagerWrite(pTrunk->pDbPage);
5907 if( rc ){
5908 goto end_allocate_page;
5910 if( k==0 ){
5911 if( !pPrevTrunk ){
5912 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5913 }else{
5914 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
5915 if( rc!=SQLITE_OK ){
5916 goto end_allocate_page;
5918 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
5920 }else{
5921 /* The trunk page is required by the caller but it contains
5922 ** pointers to free-list leaves. The first leaf becomes a trunk
5923 ** page in this case.
5925 MemPage *pNewTrunk;
5926 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
5927 if( iNewTrunk>mxPage ){
5928 rc = SQLITE_CORRUPT_PGNO(iTrunk);
5929 goto end_allocate_page;
5931 testcase( iNewTrunk==mxPage );
5932 rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
5933 if( rc!=SQLITE_OK ){
5934 goto end_allocate_page;
5936 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
5937 if( rc!=SQLITE_OK ){
5938 releasePage(pNewTrunk);
5939 goto end_allocate_page;
5941 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
5942 put4byte(&pNewTrunk->aData[4], k-1);
5943 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
5944 releasePage(pNewTrunk);
5945 if( !pPrevTrunk ){
5946 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
5947 put4byte(&pPage1->aData[32], iNewTrunk);
5948 }else{
5949 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
5950 if( rc ){
5951 goto end_allocate_page;
5953 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
5956 pTrunk = 0;
5957 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
5958 #endif
5959 }else if( k>0 ){
5960 /* Extract a leaf from the trunk */
5961 u32 closest;
5962 Pgno iPage;
5963 unsigned char *aData = pTrunk->aData;
5964 if( nearby>0 ){
5965 u32 i;
5966 closest = 0;
5967 if( eMode==BTALLOC_LE ){
5968 for(i=0; i<k; i++){
5969 iPage = get4byte(&aData[8+i*4]);
5970 if( iPage<=nearby ){
5971 closest = i;
5972 break;
5975 }else{
5976 int dist;
5977 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
5978 for(i=1; i<k; i++){
5979 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
5980 if( d2<dist ){
5981 closest = i;
5982 dist = d2;
5986 }else{
5987 closest = 0;
5990 iPage = get4byte(&aData[8+closest*4]);
5991 testcase( iPage==mxPage );
5992 if( iPage>mxPage ){
5993 rc = SQLITE_CORRUPT_PGNO(iTrunk);
5994 goto end_allocate_page;
5996 testcase( iPage==mxPage );
5997 if( !searchList
5998 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
6000 int noContent;
6001 *pPgno = iPage;
6002 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
6003 ": %d more free pages\n",
6004 *pPgno, closest+1, k, pTrunk->pgno, n-1));
6005 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6006 if( rc ) goto end_allocate_page;
6007 if( closest<k-1 ){
6008 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
6010 put4byte(&aData[4], k-1);
6011 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
6012 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
6013 if( rc==SQLITE_OK ){
6014 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6015 if( rc!=SQLITE_OK ){
6016 releasePage(*ppPage);
6017 *ppPage = 0;
6020 searchList = 0;
6023 releasePage(pPrevTrunk);
6024 pPrevTrunk = 0;
6025 }while( searchList );
6026 }else{
6027 /* There are no pages on the freelist, so append a new page to the
6028 ** database image.
6030 ** Normally, new pages allocated by this block can be requested from the
6031 ** pager layer with the 'no-content' flag set. This prevents the pager
6032 ** from trying to read the pages content from disk. However, if the
6033 ** current transaction has already run one or more incremental-vacuum
6034 ** steps, then the page we are about to allocate may contain content
6035 ** that is required in the event of a rollback. In this case, do
6036 ** not set the no-content flag. This causes the pager to load and journal
6037 ** the current page content before overwriting it.
6039 ** Note that the pager will not actually attempt to load or journal
6040 ** content for any page that really does lie past the end of the database
6041 ** file on disk. So the effects of disabling the no-content optimization
6042 ** here are confined to those pages that lie between the end of the
6043 ** database image and the end of the database file.
6045 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
6047 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6048 if( rc ) return rc;
6049 pBt->nPage++;
6050 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
6052 #ifndef SQLITE_OMIT_AUTOVACUUM
6053 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
6054 /* If *pPgno refers to a pointer-map page, allocate two new pages
6055 ** at the end of the file instead of one. The first allocated page
6056 ** becomes a new pointer-map page, the second is used by the caller.
6058 MemPage *pPg = 0;
6059 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
6060 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
6061 rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
6062 if( rc==SQLITE_OK ){
6063 rc = sqlite3PagerWrite(pPg->pDbPage);
6064 releasePage(pPg);
6066 if( rc ) return rc;
6067 pBt->nPage++;
6068 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
6070 #endif
6071 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
6072 *pPgno = pBt->nPage;
6074 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
6075 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
6076 if( rc ) return rc;
6077 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6078 if( rc!=SQLITE_OK ){
6079 releasePage(*ppPage);
6080 *ppPage = 0;
6082 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
6085 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
6087 end_allocate_page:
6088 releasePage(pTrunk);
6089 releasePage(pPrevTrunk);
6090 assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
6091 assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
6092 return rc;
6096 ** This function is used to add page iPage to the database file free-list.
6097 ** It is assumed that the page is not already a part of the free-list.
6099 ** The value passed as the second argument to this function is optional.
6100 ** If the caller happens to have a pointer to the MemPage object
6101 ** corresponding to page iPage handy, it may pass it as the second value.
6102 ** Otherwise, it may pass NULL.
6104 ** If a pointer to a MemPage object is passed as the second argument,
6105 ** its reference count is not altered by this function.
6107 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
6108 MemPage *pTrunk = 0; /* Free-list trunk page */
6109 Pgno iTrunk = 0; /* Page number of free-list trunk page */
6110 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
6111 MemPage *pPage; /* Page being freed. May be NULL. */
6112 int rc; /* Return Code */
6113 int nFree; /* Initial number of pages on free-list */
6115 assert( sqlite3_mutex_held(pBt->mutex) );
6116 assert( CORRUPT_DB || iPage>1 );
6117 assert( !pMemPage || pMemPage->pgno==iPage );
6119 if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
6120 if( pMemPage ){
6121 pPage = pMemPage;
6122 sqlite3PagerRef(pPage->pDbPage);
6123 }else{
6124 pPage = btreePageLookup(pBt, iPage);
6127 /* Increment the free page count on pPage1 */
6128 rc = sqlite3PagerWrite(pPage1->pDbPage);
6129 if( rc ) goto freepage_out;
6130 nFree = get4byte(&pPage1->aData[36]);
6131 put4byte(&pPage1->aData[36], nFree+1);
6133 if( pBt->btsFlags & BTS_SECURE_DELETE ){
6134 /* If the secure_delete option is enabled, then
6135 ** always fully overwrite deleted information with zeros.
6137 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
6138 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
6140 goto freepage_out;
6142 memset(pPage->aData, 0, pPage->pBt->pageSize);
6145 /* If the database supports auto-vacuum, write an entry in the pointer-map
6146 ** to indicate that the page is free.
6148 if( ISAUTOVACUUM ){
6149 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
6150 if( rc ) goto freepage_out;
6153 /* Now manipulate the actual database free-list structure. There are two
6154 ** possibilities. If the free-list is currently empty, or if the first
6155 ** trunk page in the free-list is full, then this page will become a
6156 ** new free-list trunk page. Otherwise, it will become a leaf of the
6157 ** first trunk page in the current free-list. This block tests if it
6158 ** is possible to add the page as a new free-list leaf.
6160 if( nFree!=0 ){
6161 u32 nLeaf; /* Initial number of leaf cells on trunk page */
6163 iTrunk = get4byte(&pPage1->aData[32]);
6164 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
6165 if( rc!=SQLITE_OK ){
6166 goto freepage_out;
6169 nLeaf = get4byte(&pTrunk->aData[4]);
6170 assert( pBt->usableSize>32 );
6171 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
6172 rc = SQLITE_CORRUPT_BKPT;
6173 goto freepage_out;
6175 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
6176 /* In this case there is room on the trunk page to insert the page
6177 ** being freed as a new leaf.
6179 ** Note that the trunk page is not really full until it contains
6180 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
6181 ** coded. But due to a coding error in versions of SQLite prior to
6182 ** 3.6.0, databases with freelist trunk pages holding more than
6183 ** usableSize/4 - 8 entries will be reported as corrupt. In order
6184 ** to maintain backwards compatibility with older versions of SQLite,
6185 ** we will continue to restrict the number of entries to usableSize/4 - 8
6186 ** for now. At some point in the future (once everyone has upgraded
6187 ** to 3.6.0 or later) we should consider fixing the conditional above
6188 ** to read "usableSize/4-2" instead of "usableSize/4-8".
6190 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
6191 ** avoid using the last six entries in the freelist trunk page array in
6192 ** order that database files created by newer versions of SQLite can be
6193 ** read by older versions of SQLite.
6195 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6196 if( rc==SQLITE_OK ){
6197 put4byte(&pTrunk->aData[4], nLeaf+1);
6198 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
6199 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
6200 sqlite3PagerDontWrite(pPage->pDbPage);
6202 rc = btreeSetHasContent(pBt, iPage);
6204 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
6205 goto freepage_out;
6209 /* If control flows to this point, then it was not possible to add the
6210 ** the page being freed as a leaf page of the first trunk in the free-list.
6211 ** Possibly because the free-list is empty, or possibly because the
6212 ** first trunk in the free-list is full. Either way, the page being freed
6213 ** will become the new first trunk page in the free-list.
6215 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
6216 goto freepage_out;
6218 rc = sqlite3PagerWrite(pPage->pDbPage);
6219 if( rc!=SQLITE_OK ){
6220 goto freepage_out;
6222 put4byte(pPage->aData, iTrunk);
6223 put4byte(&pPage->aData[4], 0);
6224 put4byte(&pPage1->aData[32], iPage);
6225 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
6227 freepage_out:
6228 if( pPage ){
6229 pPage->isInit = 0;
6231 releasePage(pPage);
6232 releasePage(pTrunk);
6233 return rc;
6235 static void freePage(MemPage *pPage, int *pRC){
6236 if( (*pRC)==SQLITE_OK ){
6237 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
6242 ** Free any overflow pages associated with the given Cell. Store
6243 ** size information about the cell in pInfo.
6245 static int clearCell(
6246 MemPage *pPage, /* The page that contains the Cell */
6247 unsigned char *pCell, /* First byte of the Cell */
6248 CellInfo *pInfo /* Size information about the cell */
6250 BtShared *pBt;
6251 Pgno ovflPgno;
6252 int rc;
6253 int nOvfl;
6254 u32 ovflPageSize;
6256 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6257 pPage->xParseCell(pPage, pCell, pInfo);
6258 if( pInfo->nLocal==pInfo->nPayload ){
6259 return SQLITE_OK; /* No overflow pages. Return without doing anything */
6261 testcase( pCell + pInfo->nSize == pPage->aDataEnd );
6262 testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
6263 if( pCell + pInfo->nSize > pPage->aDataEnd ){
6264 /* Cell extends past end of page */
6265 return SQLITE_CORRUPT_PAGE(pPage);
6267 ovflPgno = get4byte(pCell + pInfo->nSize - 4);
6268 pBt = pPage->pBt;
6269 assert( pBt->usableSize > 4 );
6270 ovflPageSize = pBt->usableSize - 4;
6271 nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
6272 assert( nOvfl>0 ||
6273 (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
6275 while( nOvfl-- ){
6276 Pgno iNext = 0;
6277 MemPage *pOvfl = 0;
6278 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
6279 /* 0 is not a legal page number and page 1 cannot be an
6280 ** overflow page. Therefore if ovflPgno<2 or past the end of the
6281 ** file the database must be corrupt. */
6282 return SQLITE_CORRUPT_BKPT;
6284 if( nOvfl ){
6285 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
6286 if( rc ) return rc;
6289 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
6290 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
6292 /* There is no reason any cursor should have an outstanding reference
6293 ** to an overflow page belonging to a cell that is being deleted/updated.
6294 ** So if there exists more than one reference to this page, then it
6295 ** must not really be an overflow page and the database must be corrupt.
6296 ** It is helpful to detect this before calling freePage2(), as
6297 ** freePage2() may zero the page contents if secure-delete mode is
6298 ** enabled. If this 'overflow' page happens to be a page that the
6299 ** caller is iterating through or using in some other way, this
6300 ** can be problematic.
6302 rc = SQLITE_CORRUPT_BKPT;
6303 }else{
6304 rc = freePage2(pBt, pOvfl, ovflPgno);
6307 if( pOvfl ){
6308 sqlite3PagerUnref(pOvfl->pDbPage);
6310 if( rc ) return rc;
6311 ovflPgno = iNext;
6313 return SQLITE_OK;
6317 ** Create the byte sequence used to represent a cell on page pPage
6318 ** and write that byte sequence into pCell[]. Overflow pages are
6319 ** allocated and filled in as necessary. The calling procedure
6320 ** is responsible for making sure sufficient space has been allocated
6321 ** for pCell[].
6323 ** Note that pCell does not necessary need to point to the pPage->aData
6324 ** area. pCell might point to some temporary storage. The cell will
6325 ** be constructed in this temporary area then copied into pPage->aData
6326 ** later.
6328 static int fillInCell(
6329 MemPage *pPage, /* The page that contains the cell */
6330 unsigned char *pCell, /* Complete text of the cell */
6331 const BtreePayload *pX, /* Payload with which to construct the cell */
6332 int *pnSize /* Write cell size here */
6334 int nPayload;
6335 const u8 *pSrc;
6336 int nSrc, n, rc, mn;
6337 int spaceLeft;
6338 MemPage *pToRelease;
6339 unsigned char *pPrior;
6340 unsigned char *pPayload;
6341 BtShared *pBt;
6342 Pgno pgnoOvfl;
6343 int nHeader;
6345 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6347 /* pPage is not necessarily writeable since pCell might be auxiliary
6348 ** buffer space that is separate from the pPage buffer area */
6349 assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
6350 || sqlite3PagerIswriteable(pPage->pDbPage) );
6352 /* Fill in the header. */
6353 nHeader = pPage->childPtrSize;
6354 if( pPage->intKey ){
6355 nPayload = pX->nData + pX->nZero;
6356 pSrc = pX->pData;
6357 nSrc = pX->nData;
6358 assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
6359 nHeader += putVarint32(&pCell[nHeader], nPayload);
6360 nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
6361 }else{
6362 assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
6363 nSrc = nPayload = (int)pX->nKey;
6364 pSrc = pX->pKey;
6365 nHeader += putVarint32(&pCell[nHeader], nPayload);
6368 /* Fill in the payload */
6369 pPayload = &pCell[nHeader];
6370 if( nPayload<=pPage->maxLocal ){
6371 /* This is the common case where everything fits on the btree page
6372 ** and no overflow pages are required. */
6373 n = nHeader + nPayload;
6374 testcase( n==3 );
6375 testcase( n==4 );
6376 if( n<4 ) n = 4;
6377 *pnSize = n;
6378 assert( nSrc<=nPayload );
6379 testcase( nSrc<nPayload );
6380 memcpy(pPayload, pSrc, nSrc);
6381 memset(pPayload+nSrc, 0, nPayload-nSrc);
6382 return SQLITE_OK;
6385 /* If we reach this point, it means that some of the content will need
6386 ** to spill onto overflow pages.
6388 mn = pPage->minLocal;
6389 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
6390 testcase( n==pPage->maxLocal );
6391 testcase( n==pPage->maxLocal+1 );
6392 if( n > pPage->maxLocal ) n = mn;
6393 spaceLeft = n;
6394 *pnSize = n + nHeader + 4;
6395 pPrior = &pCell[nHeader+n];
6396 pToRelease = 0;
6397 pgnoOvfl = 0;
6398 pBt = pPage->pBt;
6400 /* At this point variables should be set as follows:
6402 ** nPayload Total payload size in bytes
6403 ** pPayload Begin writing payload here
6404 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
6405 ** that means content must spill into overflow pages.
6406 ** *pnSize Size of the local cell (not counting overflow pages)
6407 ** pPrior Where to write the pgno of the first overflow page
6409 ** Use a call to btreeParseCellPtr() to verify that the values above
6410 ** were computed correctly.
6412 #ifdef SQLITE_DEBUG
6414 CellInfo info;
6415 pPage->xParseCell(pPage, pCell, &info);
6416 assert( nHeader==(int)(info.pPayload - pCell) );
6417 assert( info.nKey==pX->nKey );
6418 assert( *pnSize == info.nSize );
6419 assert( spaceLeft == info.nLocal );
6421 #endif
6423 /* Write the payload into the local Cell and any extra into overflow pages */
6424 while( 1 ){
6425 n = nPayload;
6426 if( n>spaceLeft ) n = spaceLeft;
6428 /* If pToRelease is not zero than pPayload points into the data area
6429 ** of pToRelease. Make sure pToRelease is still writeable. */
6430 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6432 /* If pPayload is part of the data area of pPage, then make sure pPage
6433 ** is still writeable */
6434 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
6435 || sqlite3PagerIswriteable(pPage->pDbPage) );
6437 if( nSrc>=n ){
6438 memcpy(pPayload, pSrc, n);
6439 }else if( nSrc>0 ){
6440 n = nSrc;
6441 memcpy(pPayload, pSrc, n);
6442 }else{
6443 memset(pPayload, 0, n);
6445 nPayload -= n;
6446 if( nPayload<=0 ) break;
6447 pPayload += n;
6448 pSrc += n;
6449 nSrc -= n;
6450 spaceLeft -= n;
6451 if( spaceLeft==0 ){
6452 MemPage *pOvfl = 0;
6453 #ifndef SQLITE_OMIT_AUTOVACUUM
6454 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
6455 if( pBt->autoVacuum ){
6457 pgnoOvfl++;
6458 } while(
6459 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
6462 #endif
6463 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
6464 #ifndef SQLITE_OMIT_AUTOVACUUM
6465 /* If the database supports auto-vacuum, and the second or subsequent
6466 ** overflow page is being allocated, add an entry to the pointer-map
6467 ** for that page now.
6469 ** If this is the first overflow page, then write a partial entry
6470 ** to the pointer-map. If we write nothing to this pointer-map slot,
6471 ** then the optimistic overflow chain processing in clearCell()
6472 ** may misinterpret the uninitialized values and delete the
6473 ** wrong pages from the database.
6475 if( pBt->autoVacuum && rc==SQLITE_OK ){
6476 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
6477 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
6478 if( rc ){
6479 releasePage(pOvfl);
6482 #endif
6483 if( rc ){
6484 releasePage(pToRelease);
6485 return rc;
6488 /* If pToRelease is not zero than pPrior points into the data area
6489 ** of pToRelease. Make sure pToRelease is still writeable. */
6490 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6492 /* If pPrior is part of the data area of pPage, then make sure pPage
6493 ** is still writeable */
6494 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
6495 || sqlite3PagerIswriteable(pPage->pDbPage) );
6497 put4byte(pPrior, pgnoOvfl);
6498 releasePage(pToRelease);
6499 pToRelease = pOvfl;
6500 pPrior = pOvfl->aData;
6501 put4byte(pPrior, 0);
6502 pPayload = &pOvfl->aData[4];
6503 spaceLeft = pBt->usableSize - 4;
6506 releasePage(pToRelease);
6507 return SQLITE_OK;
6511 ** Remove the i-th cell from pPage. This routine effects pPage only.
6512 ** The cell content is not freed or deallocated. It is assumed that
6513 ** the cell content has been copied someplace else. This routine just
6514 ** removes the reference to the cell from pPage.
6516 ** "sz" must be the number of bytes in the cell.
6518 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
6519 u32 pc; /* Offset to cell content of cell being deleted */
6520 u8 *data; /* pPage->aData */
6521 u8 *ptr; /* Used to move bytes around within data[] */
6522 int rc; /* The return code */
6523 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
6525 if( *pRC ) return;
6526 assert( idx>=0 && idx<pPage->nCell );
6527 assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
6528 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6529 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6530 data = pPage->aData;
6531 ptr = &pPage->aCellIdx[2*idx];
6532 pc = get2byte(ptr);
6533 hdr = pPage->hdrOffset;
6534 testcase( pc==get2byte(&data[hdr+5]) );
6535 testcase( pc+sz==pPage->pBt->usableSize );
6536 if( pc+sz > pPage->pBt->usableSize ){
6537 *pRC = SQLITE_CORRUPT_BKPT;
6538 return;
6540 rc = freeSpace(pPage, pc, sz);
6541 if( rc ){
6542 *pRC = rc;
6543 return;
6545 pPage->nCell--;
6546 if( pPage->nCell==0 ){
6547 memset(&data[hdr+1], 0, 4);
6548 data[hdr+7] = 0;
6549 put2byte(&data[hdr+5], pPage->pBt->usableSize);
6550 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
6551 - pPage->childPtrSize - 8;
6552 }else{
6553 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
6554 put2byte(&data[hdr+3], pPage->nCell);
6555 pPage->nFree += 2;
6560 ** Insert a new cell on pPage at cell index "i". pCell points to the
6561 ** content of the cell.
6563 ** If the cell content will fit on the page, then put it there. If it
6564 ** will not fit, then make a copy of the cell content into pTemp if
6565 ** pTemp is not null. Regardless of pTemp, allocate a new entry
6566 ** in pPage->apOvfl[] and make it point to the cell content (either
6567 ** in pTemp or the original pCell) and also record its index.
6568 ** Allocating a new entry in pPage->aCell[] implies that
6569 ** pPage->nOverflow is incremented.
6571 ** *pRC must be SQLITE_OK when this routine is called.
6573 static void insertCell(
6574 MemPage *pPage, /* Page into which we are copying */
6575 int i, /* New cell becomes the i-th cell of the page */
6576 u8 *pCell, /* Content of the new cell */
6577 int sz, /* Bytes of content in pCell */
6578 u8 *pTemp, /* Temp storage space for pCell, if needed */
6579 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
6580 int *pRC /* Read and write return code from here */
6582 int idx = 0; /* Where to write new cell content in data[] */
6583 int j; /* Loop counter */
6584 u8 *data; /* The content of the whole page */
6585 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
6587 assert( *pRC==SQLITE_OK );
6588 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
6589 assert( MX_CELL(pPage->pBt)<=10921 );
6590 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
6591 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
6592 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
6593 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6594 /* The cell should normally be sized correctly. However, when moving a
6595 ** malformed cell from a leaf page to an interior page, if the cell size
6596 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
6597 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
6598 ** the term after the || in the following assert(). */
6599 assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
6600 if( pPage->nOverflow || sz+2>pPage->nFree ){
6601 if( pTemp ){
6602 memcpy(pTemp, pCell, sz);
6603 pCell = pTemp;
6605 if( iChild ){
6606 put4byte(pCell, iChild);
6608 j = pPage->nOverflow++;
6609 /* Comparison against ArraySize-1 since we hold back one extra slot
6610 ** as a contingency. In other words, never need more than 3 overflow
6611 ** slots but 4 are allocated, just to be safe. */
6612 assert( j < ArraySize(pPage->apOvfl)-1 );
6613 pPage->apOvfl[j] = pCell;
6614 pPage->aiOvfl[j] = (u16)i;
6616 /* When multiple overflows occur, they are always sequential and in
6617 ** sorted order. This invariants arise because multiple overflows can
6618 ** only occur when inserting divider cells into the parent page during
6619 ** balancing, and the dividers are adjacent and sorted.
6621 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
6622 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
6623 }else{
6624 int rc = sqlite3PagerWrite(pPage->pDbPage);
6625 if( rc!=SQLITE_OK ){
6626 *pRC = rc;
6627 return;
6629 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6630 data = pPage->aData;
6631 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
6632 rc = allocateSpace(pPage, sz, &idx);
6633 if( rc ){ *pRC = rc; return; }
6634 /* The allocateSpace() routine guarantees the following properties
6635 ** if it returns successfully */
6636 assert( idx >= 0 );
6637 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
6638 assert( idx+sz <= (int)pPage->pBt->usableSize );
6639 pPage->nFree -= (u16)(2 + sz);
6640 memcpy(&data[idx], pCell, sz);
6641 if( iChild ){
6642 put4byte(&data[idx], iChild);
6644 pIns = pPage->aCellIdx + i*2;
6645 memmove(pIns+2, pIns, 2*(pPage->nCell - i));
6646 put2byte(pIns, idx);
6647 pPage->nCell++;
6648 /* increment the cell count */
6649 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
6650 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
6651 #ifndef SQLITE_OMIT_AUTOVACUUM
6652 if( pPage->pBt->autoVacuum ){
6653 /* The cell may contain a pointer to an overflow page. If so, write
6654 ** the entry for the overflow page into the pointer map.
6656 ptrmapPutOvflPtr(pPage, pCell, pRC);
6658 #endif
6663 ** A CellArray object contains a cache of pointers and sizes for a
6664 ** consecutive sequence of cells that might be held on multiple pages.
6666 typedef struct CellArray CellArray;
6667 struct CellArray {
6668 int nCell; /* Number of cells in apCell[] */
6669 MemPage *pRef; /* Reference page */
6670 u8 **apCell; /* All cells begin balanced */
6671 u16 *szCell; /* Local size of all cells in apCell[] */
6675 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
6676 ** computed.
6678 static void populateCellCache(CellArray *p, int idx, int N){
6679 assert( idx>=0 && idx+N<=p->nCell );
6680 while( N>0 ){
6681 assert( p->apCell[idx]!=0 );
6682 if( p->szCell[idx]==0 ){
6683 p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
6684 }else{
6685 assert( CORRUPT_DB ||
6686 p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
6688 idx++;
6689 N--;
6694 ** Return the size of the Nth element of the cell array
6696 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
6697 assert( N>=0 && N<p->nCell );
6698 assert( p->szCell[N]==0 );
6699 p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
6700 return p->szCell[N];
6702 static u16 cachedCellSize(CellArray *p, int N){
6703 assert( N>=0 && N<p->nCell );
6704 if( p->szCell[N] ) return p->szCell[N];
6705 return computeCellSize(p, N);
6709 ** Array apCell[] contains pointers to nCell b-tree page cells. The
6710 ** szCell[] array contains the size in bytes of each cell. This function
6711 ** replaces the current contents of page pPg with the contents of the cell
6712 ** array.
6714 ** Some of the cells in apCell[] may currently be stored in pPg. This
6715 ** function works around problems caused by this by making a copy of any
6716 ** such cells before overwriting the page data.
6718 ** The MemPage.nFree field is invalidated by this function. It is the
6719 ** responsibility of the caller to set it correctly.
6721 static int rebuildPage(
6722 MemPage *pPg, /* Edit this page */
6723 int nCell, /* Final number of cells on page */
6724 u8 **apCell, /* Array of cells */
6725 u16 *szCell /* Array of cell sizes */
6727 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
6728 u8 * const aData = pPg->aData; /* Pointer to data for pPg */
6729 const int usableSize = pPg->pBt->usableSize;
6730 u8 * const pEnd = &aData[usableSize];
6731 int i;
6732 u8 *pCellptr = pPg->aCellIdx;
6733 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6734 u8 *pData;
6736 i = get2byte(&aData[hdr+5]);
6737 memcpy(&pTmp[i], &aData[i], usableSize - i);
6739 pData = pEnd;
6740 for(i=0; i<nCell; i++){
6741 u8 *pCell = apCell[i];
6742 if( SQLITE_WITHIN(pCell,aData,pEnd) ){
6743 pCell = &pTmp[pCell - aData];
6745 pData -= szCell[i];
6746 put2byte(pCellptr, (pData - aData));
6747 pCellptr += 2;
6748 if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
6749 memcpy(pData, pCell, szCell[i]);
6750 assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
6751 testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
6754 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
6755 pPg->nCell = nCell;
6756 pPg->nOverflow = 0;
6758 put2byte(&aData[hdr+1], 0);
6759 put2byte(&aData[hdr+3], pPg->nCell);
6760 put2byte(&aData[hdr+5], pData - aData);
6761 aData[hdr+7] = 0x00;
6762 return SQLITE_OK;
6766 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
6767 ** contains the size in bytes of each such cell. This function attempts to
6768 ** add the cells stored in the array to page pPg. If it cannot (because
6769 ** the page needs to be defragmented before the cells will fit), non-zero
6770 ** is returned. Otherwise, if the cells are added successfully, zero is
6771 ** returned.
6773 ** Argument pCellptr points to the first entry in the cell-pointer array
6774 ** (part of page pPg) to populate. After cell apCell[0] is written to the
6775 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
6776 ** cell in the array. It is the responsibility of the caller to ensure
6777 ** that it is safe to overwrite this part of the cell-pointer array.
6779 ** When this function is called, *ppData points to the start of the
6780 ** content area on page pPg. If the size of the content area is extended,
6781 ** *ppData is updated to point to the new start of the content area
6782 ** before returning.
6784 ** Finally, argument pBegin points to the byte immediately following the
6785 ** end of the space required by this page for the cell-pointer area (for
6786 ** all cells - not just those inserted by the current call). If the content
6787 ** area must be extended to before this point in order to accomodate all
6788 ** cells in apCell[], then the cells do not fit and non-zero is returned.
6790 static int pageInsertArray(
6791 MemPage *pPg, /* Page to add cells to */
6792 u8 *pBegin, /* End of cell-pointer array */
6793 u8 **ppData, /* IN/OUT: Page content -area pointer */
6794 u8 *pCellptr, /* Pointer to cell-pointer area */
6795 int iFirst, /* Index of first cell to add */
6796 int nCell, /* Number of cells to add to pPg */
6797 CellArray *pCArray /* Array of cells */
6799 int i;
6800 u8 *aData = pPg->aData;
6801 u8 *pData = *ppData;
6802 int iEnd = iFirst + nCell;
6803 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
6804 for(i=iFirst; i<iEnd; i++){
6805 int sz, rc;
6806 u8 *pSlot;
6807 sz = cachedCellSize(pCArray, i);
6808 if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
6809 if( (pData - pBegin)<sz ) return 1;
6810 pData -= sz;
6811 pSlot = pData;
6813 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
6814 ** database. But they might for a corrupt database. Hence use memmove()
6815 ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
6816 assert( (pSlot+sz)<=pCArray->apCell[i]
6817 || pSlot>=(pCArray->apCell[i]+sz)
6818 || CORRUPT_DB );
6819 memmove(pSlot, pCArray->apCell[i], sz);
6820 put2byte(pCellptr, (pSlot - aData));
6821 pCellptr += 2;
6823 *ppData = pData;
6824 return 0;
6828 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
6829 ** contains the size in bytes of each such cell. This function adds the
6830 ** space associated with each cell in the array that is currently stored
6831 ** within the body of pPg to the pPg free-list. The cell-pointers and other
6832 ** fields of the page are not updated.
6834 ** This function returns the total number of cells added to the free-list.
6836 static int pageFreeArray(
6837 MemPage *pPg, /* Page to edit */
6838 int iFirst, /* First cell to delete */
6839 int nCell, /* Cells to delete */
6840 CellArray *pCArray /* Array of cells */
6842 u8 * const aData = pPg->aData;
6843 u8 * const pEnd = &aData[pPg->pBt->usableSize];
6844 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
6845 int nRet = 0;
6846 int i;
6847 int iEnd = iFirst + nCell;
6848 u8 *pFree = 0;
6849 int szFree = 0;
6851 for(i=iFirst; i<iEnd; i++){
6852 u8 *pCell = pCArray->apCell[i];
6853 if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
6854 int sz;
6855 /* No need to use cachedCellSize() here. The sizes of all cells that
6856 ** are to be freed have already been computing while deciding which
6857 ** cells need freeing */
6858 sz = pCArray->szCell[i]; assert( sz>0 );
6859 if( pFree!=(pCell + sz) ){
6860 if( pFree ){
6861 assert( pFree>aData && (pFree - aData)<65536 );
6862 freeSpace(pPg, (u16)(pFree - aData), szFree);
6864 pFree = pCell;
6865 szFree = sz;
6866 if( pFree+sz>pEnd ) return 0;
6867 }else{
6868 pFree = pCell;
6869 szFree += sz;
6871 nRet++;
6874 if( pFree ){
6875 assert( pFree>aData && (pFree - aData)<65536 );
6876 freeSpace(pPg, (u16)(pFree - aData), szFree);
6878 return nRet;
6882 ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
6883 ** pages being balanced. The current page, pPg, has pPg->nCell cells starting
6884 ** with apCell[iOld]. After balancing, this page should hold nNew cells
6885 ** starting at apCell[iNew].
6887 ** This routine makes the necessary adjustments to pPg so that it contains
6888 ** the correct cells after being balanced.
6890 ** The pPg->nFree field is invalid when this function returns. It is the
6891 ** responsibility of the caller to set it correctly.
6893 static int editPage(
6894 MemPage *pPg, /* Edit this page */
6895 int iOld, /* Index of first cell currently on page */
6896 int iNew, /* Index of new first cell on page */
6897 int nNew, /* Final number of cells on page */
6898 CellArray *pCArray /* Array of cells and sizes */
6900 u8 * const aData = pPg->aData;
6901 const int hdr = pPg->hdrOffset;
6902 u8 *pBegin = &pPg->aCellIdx[nNew * 2];
6903 int nCell = pPg->nCell; /* Cells stored on pPg */
6904 u8 *pData;
6905 u8 *pCellptr;
6906 int i;
6907 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
6908 int iNewEnd = iNew + nNew;
6910 #ifdef SQLITE_DEBUG
6911 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6912 memcpy(pTmp, aData, pPg->pBt->usableSize);
6913 #endif
6915 /* Remove cells from the start and end of the page */
6916 if( iOld<iNew ){
6917 int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
6918 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
6919 nCell -= nShift;
6921 if( iNewEnd < iOldEnd ){
6922 nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
6925 pData = &aData[get2byteNotZero(&aData[hdr+5])];
6926 if( pData<pBegin ) goto editpage_fail;
6928 /* Add cells to the start of the page */
6929 if( iNew<iOld ){
6930 int nAdd = MIN(nNew,iOld-iNew);
6931 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
6932 pCellptr = pPg->aCellIdx;
6933 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
6934 if( pageInsertArray(
6935 pPg, pBegin, &pData, pCellptr,
6936 iNew, nAdd, pCArray
6937 ) ) goto editpage_fail;
6938 nCell += nAdd;
6941 /* Add any overflow cells */
6942 for(i=0; i<pPg->nOverflow; i++){
6943 int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
6944 if( iCell>=0 && iCell<nNew ){
6945 pCellptr = &pPg->aCellIdx[iCell * 2];
6946 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
6947 nCell++;
6948 if( pageInsertArray(
6949 pPg, pBegin, &pData, pCellptr,
6950 iCell+iNew, 1, pCArray
6951 ) ) goto editpage_fail;
6955 /* Append cells to the end of the page */
6956 pCellptr = &pPg->aCellIdx[nCell*2];
6957 if( pageInsertArray(
6958 pPg, pBegin, &pData, pCellptr,
6959 iNew+nCell, nNew-nCell, pCArray
6960 ) ) goto editpage_fail;
6962 pPg->nCell = nNew;
6963 pPg->nOverflow = 0;
6965 put2byte(&aData[hdr+3], pPg->nCell);
6966 put2byte(&aData[hdr+5], pData - aData);
6968 #ifdef SQLITE_DEBUG
6969 for(i=0; i<nNew && !CORRUPT_DB; i++){
6970 u8 *pCell = pCArray->apCell[i+iNew];
6971 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
6972 if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
6973 pCell = &pTmp[pCell - aData];
6975 assert( 0==memcmp(pCell, &aData[iOff],
6976 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
6978 #endif
6980 return SQLITE_OK;
6981 editpage_fail:
6982 /* Unable to edit this page. Rebuild it from scratch instead. */
6983 populateCellCache(pCArray, iNew, nNew);
6984 return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
6988 ** The following parameters determine how many adjacent pages get involved
6989 ** in a balancing operation. NN is the number of neighbors on either side
6990 ** of the page that participate in the balancing operation. NB is the
6991 ** total number of pages that participate, including the target page and
6992 ** NN neighbors on either side.
6994 ** The minimum value of NN is 1 (of course). Increasing NN above 1
6995 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
6996 ** in exchange for a larger degradation in INSERT and UPDATE performance.
6997 ** The value of NN appears to give the best results overall.
6999 #define NN 1 /* Number of neighbors on either side of pPage */
7000 #define NB (NN*2+1) /* Total pages involved in the balance */
7003 #ifndef SQLITE_OMIT_QUICKBALANCE
7005 ** This version of balance() handles the common special case where
7006 ** a new entry is being inserted on the extreme right-end of the
7007 ** tree, in other words, when the new entry will become the largest
7008 ** entry in the tree.
7010 ** Instead of trying to balance the 3 right-most leaf pages, just add
7011 ** a new page to the right-hand side and put the one new entry in
7012 ** that page. This leaves the right side of the tree somewhat
7013 ** unbalanced. But odds are that we will be inserting new entries
7014 ** at the end soon afterwards so the nearly empty page will quickly
7015 ** fill up. On average.
7017 ** pPage is the leaf page which is the right-most page in the tree.
7018 ** pParent is its parent. pPage must have a single overflow entry
7019 ** which is also the right-most entry on the page.
7021 ** The pSpace buffer is used to store a temporary copy of the divider
7022 ** cell that will be inserted into pParent. Such a cell consists of a 4
7023 ** byte page number followed by a variable length integer. In other
7024 ** words, at most 13 bytes. Hence the pSpace buffer must be at
7025 ** least 13 bytes in size.
7027 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
7028 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
7029 MemPage *pNew; /* Newly allocated page */
7030 int rc; /* Return Code */
7031 Pgno pgnoNew; /* Page number of pNew */
7033 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7034 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7035 assert( pPage->nOverflow==1 );
7037 /* This error condition is now caught prior to reaching this function */
7038 if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
7040 /* Allocate a new page. This page will become the right-sibling of
7041 ** pPage. Make the parent page writable, so that the new divider cell
7042 ** may be inserted. If both these operations are successful, proceed.
7044 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
7046 if( rc==SQLITE_OK ){
7048 u8 *pOut = &pSpace[4];
7049 u8 *pCell = pPage->apOvfl[0];
7050 u16 szCell = pPage->xCellSize(pPage, pCell);
7051 u8 *pStop;
7053 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
7054 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
7055 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
7056 rc = rebuildPage(pNew, 1, &pCell, &szCell);
7057 if( NEVER(rc) ) return rc;
7058 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
7060 /* If this is an auto-vacuum database, update the pointer map
7061 ** with entries for the new page, and any pointer from the
7062 ** cell on the page to an overflow page. If either of these
7063 ** operations fails, the return code is set, but the contents
7064 ** of the parent page are still manipulated by thh code below.
7065 ** That is Ok, at this point the parent page is guaranteed to
7066 ** be marked as dirty. Returning an error code will cause a
7067 ** rollback, undoing any changes made to the parent page.
7069 if( ISAUTOVACUUM ){
7070 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
7071 if( szCell>pNew->minLocal ){
7072 ptrmapPutOvflPtr(pNew, pCell, &rc);
7076 /* Create a divider cell to insert into pParent. The divider cell
7077 ** consists of a 4-byte page number (the page number of pPage) and
7078 ** a variable length key value (which must be the same value as the
7079 ** largest key on pPage).
7081 ** To find the largest key value on pPage, first find the right-most
7082 ** cell on pPage. The first two fields of this cell are the
7083 ** record-length (a variable length integer at most 32-bits in size)
7084 ** and the key value (a variable length integer, may have any value).
7085 ** The first of the while(...) loops below skips over the record-length
7086 ** field. The second while(...) loop copies the key value from the
7087 ** cell on pPage into the pSpace buffer.
7089 pCell = findCell(pPage, pPage->nCell-1);
7090 pStop = &pCell[9];
7091 while( (*(pCell++)&0x80) && pCell<pStop );
7092 pStop = &pCell[9];
7093 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
7095 /* Insert the new divider cell into pParent. */
7096 if( rc==SQLITE_OK ){
7097 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
7098 0, pPage->pgno, &rc);
7101 /* Set the right-child pointer of pParent to point to the new page. */
7102 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
7104 /* Release the reference to the new page. */
7105 releasePage(pNew);
7108 return rc;
7110 #endif /* SQLITE_OMIT_QUICKBALANCE */
7112 #if 0
7114 ** This function does not contribute anything to the operation of SQLite.
7115 ** it is sometimes activated temporarily while debugging code responsible
7116 ** for setting pointer-map entries.
7118 static int ptrmapCheckPages(MemPage **apPage, int nPage){
7119 int i, j;
7120 for(i=0; i<nPage; i++){
7121 Pgno n;
7122 u8 e;
7123 MemPage *pPage = apPage[i];
7124 BtShared *pBt = pPage->pBt;
7125 assert( pPage->isInit );
7127 for(j=0; j<pPage->nCell; j++){
7128 CellInfo info;
7129 u8 *z;
7131 z = findCell(pPage, j);
7132 pPage->xParseCell(pPage, z, &info);
7133 if( info.nLocal<info.nPayload ){
7134 Pgno ovfl = get4byte(&z[info.nSize-4]);
7135 ptrmapGet(pBt, ovfl, &e, &n);
7136 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
7138 if( !pPage->leaf ){
7139 Pgno child = get4byte(z);
7140 ptrmapGet(pBt, child, &e, &n);
7141 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7144 if( !pPage->leaf ){
7145 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
7146 ptrmapGet(pBt, child, &e, &n);
7147 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7150 return 1;
7152 #endif
7155 ** This function is used to copy the contents of the b-tree node stored
7156 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
7157 ** the pointer-map entries for each child page are updated so that the
7158 ** parent page stored in the pointer map is page pTo. If pFrom contained
7159 ** any cells with overflow page pointers, then the corresponding pointer
7160 ** map entries are also updated so that the parent page is page pTo.
7162 ** If pFrom is currently carrying any overflow cells (entries in the
7163 ** MemPage.apOvfl[] array), they are not copied to pTo.
7165 ** Before returning, page pTo is reinitialized using btreeInitPage().
7167 ** The performance of this function is not critical. It is only used by
7168 ** the balance_shallower() and balance_deeper() procedures, neither of
7169 ** which are called often under normal circumstances.
7171 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
7172 if( (*pRC)==SQLITE_OK ){
7173 BtShared * const pBt = pFrom->pBt;
7174 u8 * const aFrom = pFrom->aData;
7175 u8 * const aTo = pTo->aData;
7176 int const iFromHdr = pFrom->hdrOffset;
7177 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
7178 int rc;
7179 int iData;
7182 assert( pFrom->isInit );
7183 assert( pFrom->nFree>=iToHdr );
7184 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
7186 /* Copy the b-tree node content from page pFrom to page pTo. */
7187 iData = get2byte(&aFrom[iFromHdr+5]);
7188 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
7189 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
7191 /* Reinitialize page pTo so that the contents of the MemPage structure
7192 ** match the new data. The initialization of pTo can actually fail under
7193 ** fairly obscure circumstances, even though it is a copy of initialized
7194 ** page pFrom.
7196 pTo->isInit = 0;
7197 rc = btreeInitPage(pTo);
7198 if( rc!=SQLITE_OK ){
7199 *pRC = rc;
7200 return;
7203 /* If this is an auto-vacuum database, update the pointer-map entries
7204 ** for any b-tree or overflow pages that pTo now contains the pointers to.
7206 if( ISAUTOVACUUM ){
7207 *pRC = setChildPtrmaps(pTo);
7213 ** This routine redistributes cells on the iParentIdx'th child of pParent
7214 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
7215 ** same amount of free space. Usually a single sibling on either side of the
7216 ** page are used in the balancing, though both siblings might come from one
7217 ** side if the page is the first or last child of its parent. If the page
7218 ** has fewer than 2 siblings (something which can only happen if the page
7219 ** is a root page or a child of a root page) then all available siblings
7220 ** participate in the balancing.
7222 ** The number of siblings of the page might be increased or decreased by
7223 ** one or two in an effort to keep pages nearly full but not over full.
7225 ** Note that when this routine is called, some of the cells on the page
7226 ** might not actually be stored in MemPage.aData[]. This can happen
7227 ** if the page is overfull. This routine ensures that all cells allocated
7228 ** to the page and its siblings fit into MemPage.aData[] before returning.
7230 ** In the course of balancing the page and its siblings, cells may be
7231 ** inserted into or removed from the parent page (pParent). Doing so
7232 ** may cause the parent page to become overfull or underfull. If this
7233 ** happens, it is the responsibility of the caller to invoke the correct
7234 ** balancing routine to fix this problem (see the balance() routine).
7236 ** If this routine fails for any reason, it might leave the database
7237 ** in a corrupted state. So if this routine fails, the database should
7238 ** be rolled back.
7240 ** The third argument to this function, aOvflSpace, is a pointer to a
7241 ** buffer big enough to hold one page. If while inserting cells into the parent
7242 ** page (pParent) the parent page becomes overfull, this buffer is
7243 ** used to store the parent's overflow cells. Because this function inserts
7244 ** a maximum of four divider cells into the parent page, and the maximum
7245 ** size of a cell stored within an internal node is always less than 1/4
7246 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
7247 ** enough for all overflow cells.
7249 ** If aOvflSpace is set to a null pointer, this function returns
7250 ** SQLITE_NOMEM.
7252 static int balance_nonroot(
7253 MemPage *pParent, /* Parent page of siblings being balanced */
7254 int iParentIdx, /* Index of "the page" in pParent */
7255 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
7256 int isRoot, /* True if pParent is a root-page */
7257 int bBulk /* True if this call is part of a bulk load */
7259 BtShared *pBt; /* The whole database */
7260 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
7261 int nNew = 0; /* Number of pages in apNew[] */
7262 int nOld; /* Number of pages in apOld[] */
7263 int i, j, k; /* Loop counters */
7264 int nxDiv; /* Next divider slot in pParent->aCell[] */
7265 int rc = SQLITE_OK; /* The return code */
7266 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
7267 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
7268 int usableSpace; /* Bytes in pPage beyond the header */
7269 int pageFlags; /* Value of pPage->aData[0] */
7270 int iSpace1 = 0; /* First unused byte of aSpace1[] */
7271 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
7272 int szScratch; /* Size of scratch memory requested */
7273 MemPage *apOld[NB]; /* pPage and up to two siblings */
7274 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
7275 u8 *pRight; /* Location in parent of right-sibling pointer */
7276 u8 *apDiv[NB-1]; /* Divider cells in pParent */
7277 int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
7278 int cntOld[NB+2]; /* Old index in b.apCell[] */
7279 int szNew[NB+2]; /* Combined size of cells placed on i-th page */
7280 u8 *aSpace1; /* Space for copies of dividers cells */
7281 Pgno pgno; /* Temp var to store a page number in */
7282 u8 abDone[NB+2]; /* True after i'th new page is populated */
7283 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
7284 Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
7285 u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
7286 CellArray b; /* Parsed information on cells being balanced */
7288 memset(abDone, 0, sizeof(abDone));
7289 b.nCell = 0;
7290 b.apCell = 0;
7291 pBt = pParent->pBt;
7292 assert( sqlite3_mutex_held(pBt->mutex) );
7293 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7295 #if 0
7296 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
7297 #endif
7299 /* At this point pParent may have at most one overflow cell. And if
7300 ** this overflow cell is present, it must be the cell with
7301 ** index iParentIdx. This scenario comes about when this function
7302 ** is called (indirectly) from sqlite3BtreeDelete().
7304 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
7305 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
7307 if( !aOvflSpace ){
7308 return SQLITE_NOMEM_BKPT;
7311 /* Find the sibling pages to balance. Also locate the cells in pParent
7312 ** that divide the siblings. An attempt is made to find NN siblings on
7313 ** either side of pPage. More siblings are taken from one side, however,
7314 ** if there are fewer than NN siblings on the other side. If pParent
7315 ** has NB or fewer children then all children of pParent are taken.
7317 ** This loop also drops the divider cells from the parent page. This
7318 ** way, the remainder of the function does not have to deal with any
7319 ** overflow cells in the parent page, since if any existed they will
7320 ** have already been removed.
7322 i = pParent->nOverflow + pParent->nCell;
7323 if( i<2 ){
7324 nxDiv = 0;
7325 }else{
7326 assert( bBulk==0 || bBulk==1 );
7327 if( iParentIdx==0 ){
7328 nxDiv = 0;
7329 }else if( iParentIdx==i ){
7330 nxDiv = i-2+bBulk;
7331 }else{
7332 nxDiv = iParentIdx-1;
7334 i = 2-bBulk;
7336 nOld = i+1;
7337 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
7338 pRight = &pParent->aData[pParent->hdrOffset+8];
7339 }else{
7340 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
7342 pgno = get4byte(pRight);
7343 while( 1 ){
7344 rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
7345 if( rc ){
7346 memset(apOld, 0, (i+1)*sizeof(MemPage*));
7347 goto balance_cleanup;
7349 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
7350 if( (i--)==0 ) break;
7352 if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
7353 apDiv[i] = pParent->apOvfl[0];
7354 pgno = get4byte(apDiv[i]);
7355 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7356 pParent->nOverflow = 0;
7357 }else{
7358 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
7359 pgno = get4byte(apDiv[i]);
7360 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7362 /* Drop the cell from the parent page. apDiv[i] still points to
7363 ** the cell within the parent, even though it has been dropped.
7364 ** This is safe because dropping a cell only overwrites the first
7365 ** four bytes of it, and this function does not need the first
7366 ** four bytes of the divider cell. So the pointer is safe to use
7367 ** later on.
7369 ** But not if we are in secure-delete mode. In secure-delete mode,
7370 ** the dropCell() routine will overwrite the entire cell with zeroes.
7371 ** In this case, temporarily copy the cell into the aOvflSpace[]
7372 ** buffer. It will be copied out again as soon as the aSpace[] buffer
7373 ** is allocated. */
7374 if( pBt->btsFlags & BTS_FAST_SECURE ){
7375 int iOff;
7377 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
7378 if( (iOff+szNew[i])>(int)pBt->usableSize ){
7379 rc = SQLITE_CORRUPT_BKPT;
7380 memset(apOld, 0, (i+1)*sizeof(MemPage*));
7381 goto balance_cleanup;
7382 }else{
7383 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
7384 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
7387 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
7391 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
7392 ** alignment */
7393 nMaxCells = (nMaxCells + 3)&~3;
7396 ** Allocate space for memory structures
7398 szScratch =
7399 nMaxCells*sizeof(u8*) /* b.apCell */
7400 + nMaxCells*sizeof(u16) /* b.szCell */
7401 + pBt->pageSize; /* aSpace1 */
7403 assert( szScratch<=6*(int)pBt->pageSize );
7404 b.apCell = sqlite3StackAllocRaw(0, szScratch );
7405 if( b.apCell==0 ){
7406 rc = SQLITE_NOMEM_BKPT;
7407 goto balance_cleanup;
7409 b.szCell = (u16*)&b.apCell[nMaxCells];
7410 aSpace1 = (u8*)&b.szCell[nMaxCells];
7411 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
7414 ** Load pointers to all cells on sibling pages and the divider cells
7415 ** into the local b.apCell[] array. Make copies of the divider cells
7416 ** into space obtained from aSpace1[]. The divider cells have already
7417 ** been removed from pParent.
7419 ** If the siblings are on leaf pages, then the child pointers of the
7420 ** divider cells are stripped from the cells before they are copied
7421 ** into aSpace1[]. In this way, all cells in b.apCell[] are without
7422 ** child pointers. If siblings are not leaves, then all cell in
7423 ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
7424 ** are alike.
7426 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
7427 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
7429 b.pRef = apOld[0];
7430 leafCorrection = b.pRef->leaf*4;
7431 leafData = b.pRef->intKeyLeaf;
7432 for(i=0; i<nOld; i++){
7433 MemPage *pOld = apOld[i];
7434 int limit = pOld->nCell;
7435 u8 *aData = pOld->aData;
7436 u16 maskPage = pOld->maskPage;
7437 u8 *piCell = aData + pOld->cellOffset;
7438 u8 *piEnd;
7440 /* Verify that all sibling pages are of the same "type" (table-leaf,
7441 ** table-interior, index-leaf, or index-interior).
7443 if( pOld->aData[0]!=apOld[0]->aData[0] ){
7444 rc = SQLITE_CORRUPT_BKPT;
7445 goto balance_cleanup;
7448 /* Load b.apCell[] with pointers to all cells in pOld. If pOld
7449 ** contains overflow cells, include them in the b.apCell[] array
7450 ** in the correct spot.
7452 ** Note that when there are multiple overflow cells, it is always the
7453 ** case that they are sequential and adjacent. This invariant arises
7454 ** because multiple overflows can only occurs when inserting divider
7455 ** cells into a parent on a prior balance, and divider cells are always
7456 ** adjacent and are inserted in order. There is an assert() tagged
7457 ** with "NOTE 1" in the overflow cell insertion loop to prove this
7458 ** invariant.
7460 ** This must be done in advance. Once the balance starts, the cell
7461 ** offset section of the btree page will be overwritten and we will no
7462 ** long be able to find the cells if a pointer to each cell is not saved
7463 ** first.
7465 memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
7466 if( pOld->nOverflow>0 ){
7467 limit = pOld->aiOvfl[0];
7468 for(j=0; j<limit; j++){
7469 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7470 piCell += 2;
7471 b.nCell++;
7473 for(k=0; k<pOld->nOverflow; k++){
7474 assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
7475 b.apCell[b.nCell] = pOld->apOvfl[k];
7476 b.nCell++;
7479 piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
7480 while( piCell<piEnd ){
7481 assert( b.nCell<nMaxCells );
7482 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7483 piCell += 2;
7484 b.nCell++;
7487 cntOld[i] = b.nCell;
7488 if( i<nOld-1 && !leafData){
7489 u16 sz = (u16)szNew[i];
7490 u8 *pTemp;
7491 assert( b.nCell<nMaxCells );
7492 b.szCell[b.nCell] = sz;
7493 pTemp = &aSpace1[iSpace1];
7494 iSpace1 += sz;
7495 assert( sz<=pBt->maxLocal+23 );
7496 assert( iSpace1 <= (int)pBt->pageSize );
7497 memcpy(pTemp, apDiv[i], sz);
7498 b.apCell[b.nCell] = pTemp+leafCorrection;
7499 assert( leafCorrection==0 || leafCorrection==4 );
7500 b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
7501 if( !pOld->leaf ){
7502 assert( leafCorrection==0 );
7503 assert( pOld->hdrOffset==0 );
7504 /* The right pointer of the child page pOld becomes the left
7505 ** pointer of the divider cell */
7506 memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
7507 }else{
7508 assert( leafCorrection==4 );
7509 while( b.szCell[b.nCell]<4 ){
7510 /* Do not allow any cells smaller than 4 bytes. If a smaller cell
7511 ** does exist, pad it with 0x00 bytes. */
7512 assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
7513 assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
7514 aSpace1[iSpace1++] = 0x00;
7515 b.szCell[b.nCell]++;
7518 b.nCell++;
7523 ** Figure out the number of pages needed to hold all b.nCell cells.
7524 ** Store this number in "k". Also compute szNew[] which is the total
7525 ** size of all cells on the i-th page and cntNew[] which is the index
7526 ** in b.apCell[] of the cell that divides page i from page i+1.
7527 ** cntNew[k] should equal b.nCell.
7529 ** Values computed by this block:
7531 ** k: The total number of sibling pages
7532 ** szNew[i]: Spaced used on the i-th sibling page.
7533 ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
7534 ** the right of the i-th sibling page.
7535 ** usableSpace: Number of bytes of space available on each sibling.
7538 usableSpace = pBt->usableSize - 12 + leafCorrection;
7539 for(i=0; i<nOld; i++){
7540 MemPage *p = apOld[i];
7541 szNew[i] = usableSpace - p->nFree;
7542 for(j=0; j<p->nOverflow; j++){
7543 szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
7545 cntNew[i] = cntOld[i];
7547 k = nOld;
7548 for(i=0; i<k; i++){
7549 int sz;
7550 while( szNew[i]>usableSpace ){
7551 if( i+1>=k ){
7552 k = i+2;
7553 if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
7554 szNew[k-1] = 0;
7555 cntNew[k-1] = b.nCell;
7557 sz = 2 + cachedCellSize(&b, cntNew[i]-1);
7558 szNew[i] -= sz;
7559 if( !leafData ){
7560 if( cntNew[i]<b.nCell ){
7561 sz = 2 + cachedCellSize(&b, cntNew[i]);
7562 }else{
7563 sz = 0;
7566 szNew[i+1] += sz;
7567 cntNew[i]--;
7569 while( cntNew[i]<b.nCell ){
7570 sz = 2 + cachedCellSize(&b, cntNew[i]);
7571 if( szNew[i]+sz>usableSpace ) break;
7572 szNew[i] += sz;
7573 cntNew[i]++;
7574 if( !leafData ){
7575 if( cntNew[i]<b.nCell ){
7576 sz = 2 + cachedCellSize(&b, cntNew[i]);
7577 }else{
7578 sz = 0;
7581 szNew[i+1] -= sz;
7583 if( cntNew[i]>=b.nCell ){
7584 k = i+1;
7585 }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
7586 rc = SQLITE_CORRUPT_BKPT;
7587 goto balance_cleanup;
7592 ** The packing computed by the previous block is biased toward the siblings
7593 ** on the left side (siblings with smaller keys). The left siblings are
7594 ** always nearly full, while the right-most sibling might be nearly empty.
7595 ** The next block of code attempts to adjust the packing of siblings to
7596 ** get a better balance.
7598 ** This adjustment is more than an optimization. The packing above might
7599 ** be so out of balance as to be illegal. For example, the right-most
7600 ** sibling might be completely empty. This adjustment is not optional.
7602 for(i=k-1; i>0; i--){
7603 int szRight = szNew[i]; /* Size of sibling on the right */
7604 int szLeft = szNew[i-1]; /* Size of sibling on the left */
7605 int r; /* Index of right-most cell in left sibling */
7606 int d; /* Index of first cell to the left of right sibling */
7608 r = cntNew[i-1] - 1;
7609 d = r + 1 - leafData;
7610 (void)cachedCellSize(&b, d);
7612 assert( d<nMaxCells );
7613 assert( r<nMaxCells );
7614 (void)cachedCellSize(&b, r);
7615 if( szRight!=0
7616 && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
7617 break;
7619 szRight += b.szCell[d] + 2;
7620 szLeft -= b.szCell[r] + 2;
7621 cntNew[i-1] = r;
7622 r--;
7623 d--;
7624 }while( r>=0 );
7625 szNew[i] = szRight;
7626 szNew[i-1] = szLeft;
7627 if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
7628 rc = SQLITE_CORRUPT_BKPT;
7629 goto balance_cleanup;
7633 /* Sanity check: For a non-corrupt database file one of the follwing
7634 ** must be true:
7635 ** (1) We found one or more cells (cntNew[0])>0), or
7636 ** (2) pPage is a virtual root page. A virtual root page is when
7637 ** the real root page is page 1 and we are the only child of
7638 ** that page.
7640 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
7641 TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
7642 apOld[0]->pgno, apOld[0]->nCell,
7643 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
7644 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
7648 ** Allocate k new pages. Reuse old pages where possible.
7650 pageFlags = apOld[0]->aData[0];
7651 for(i=0; i<k; i++){
7652 MemPage *pNew;
7653 if( i<nOld ){
7654 pNew = apNew[i] = apOld[i];
7655 apOld[i] = 0;
7656 rc = sqlite3PagerWrite(pNew->pDbPage);
7657 nNew++;
7658 if( rc ) goto balance_cleanup;
7659 }else{
7660 assert( i>0 );
7661 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
7662 if( rc ) goto balance_cleanup;
7663 zeroPage(pNew, pageFlags);
7664 apNew[i] = pNew;
7665 nNew++;
7666 cntOld[i] = b.nCell;
7668 /* Set the pointer-map entry for the new sibling page. */
7669 if( ISAUTOVACUUM ){
7670 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
7671 if( rc!=SQLITE_OK ){
7672 goto balance_cleanup;
7679 ** Reassign page numbers so that the new pages are in ascending order.
7680 ** This helps to keep entries in the disk file in order so that a scan
7681 ** of the table is closer to a linear scan through the file. That in turn
7682 ** helps the operating system to deliver pages from the disk more rapidly.
7684 ** An O(n^2) insertion sort algorithm is used, but since n is never more
7685 ** than (NB+2) (a small constant), that should not be a problem.
7687 ** When NB==3, this one optimization makes the database about 25% faster
7688 ** for large insertions and deletions.
7690 for(i=0; i<nNew; i++){
7691 aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
7692 aPgFlags[i] = apNew[i]->pDbPage->flags;
7693 for(j=0; j<i; j++){
7694 if( aPgno[j]==aPgno[i] ){
7695 /* This branch is taken if the set of sibling pages somehow contains
7696 ** duplicate entries. This can happen if the database is corrupt.
7697 ** It would be simpler to detect this as part of the loop below, but
7698 ** we do the detection here in order to avoid populating the pager
7699 ** cache with two separate objects associated with the same
7700 ** page number. */
7701 assert( CORRUPT_DB );
7702 rc = SQLITE_CORRUPT_BKPT;
7703 goto balance_cleanup;
7707 for(i=0; i<nNew; i++){
7708 int iBest = 0; /* aPgno[] index of page number to use */
7709 for(j=1; j<nNew; j++){
7710 if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
7712 pgno = aPgOrder[iBest];
7713 aPgOrder[iBest] = 0xffffffff;
7714 if( iBest!=i ){
7715 if( iBest>i ){
7716 sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
7718 sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
7719 apNew[i]->pgno = pgno;
7723 TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
7724 "%d(%d nc=%d) %d(%d nc=%d)\n",
7725 apNew[0]->pgno, szNew[0], cntNew[0],
7726 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
7727 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
7728 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
7729 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
7730 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
7731 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
7732 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
7733 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
7736 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7737 put4byte(pRight, apNew[nNew-1]->pgno);
7739 /* If the sibling pages are not leaves, ensure that the right-child pointer
7740 ** of the right-most new sibling page is set to the value that was
7741 ** originally in the same field of the right-most old sibling page. */
7742 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
7743 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
7744 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
7747 /* Make any required updates to pointer map entries associated with
7748 ** cells stored on sibling pages following the balance operation. Pointer
7749 ** map entries associated with divider cells are set by the insertCell()
7750 ** routine. The associated pointer map entries are:
7752 ** a) if the cell contains a reference to an overflow chain, the
7753 ** entry associated with the first page in the overflow chain, and
7755 ** b) if the sibling pages are not leaves, the child page associated
7756 ** with the cell.
7758 ** If the sibling pages are not leaves, then the pointer map entry
7759 ** associated with the right-child of each sibling may also need to be
7760 ** updated. This happens below, after the sibling pages have been
7761 ** populated, not here.
7763 if( ISAUTOVACUUM ){
7764 MemPage *pNew = apNew[0];
7765 u8 *aOld = pNew->aData;
7766 int cntOldNext = pNew->nCell + pNew->nOverflow;
7767 int usableSize = pBt->usableSize;
7768 int iNew = 0;
7769 int iOld = 0;
7771 for(i=0; i<b.nCell; i++){
7772 u8 *pCell = b.apCell[i];
7773 if( i==cntOldNext ){
7774 MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
7775 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
7776 aOld = pOld->aData;
7778 if( i==cntNew[iNew] ){
7779 pNew = apNew[++iNew];
7780 if( !leafData ) continue;
7783 /* Cell pCell is destined for new sibling page pNew. Originally, it
7784 ** was either part of sibling page iOld (possibly an overflow cell),
7785 ** or else the divider cell to the left of sibling page iOld. So,
7786 ** if sibling page iOld had the same page number as pNew, and if
7787 ** pCell really was a part of sibling page iOld (not a divider or
7788 ** overflow cell), we can skip updating the pointer map entries. */
7789 if( iOld>=nNew
7790 || pNew->pgno!=aPgno[iOld]
7791 || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
7793 if( !leafCorrection ){
7794 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
7796 if( cachedCellSize(&b,i)>pNew->minLocal ){
7797 ptrmapPutOvflPtr(pNew, pCell, &rc);
7799 if( rc ) goto balance_cleanup;
7804 /* Insert new divider cells into pParent. */
7805 for(i=0; i<nNew-1; i++){
7806 u8 *pCell;
7807 u8 *pTemp;
7808 int sz;
7809 MemPage *pNew = apNew[i];
7810 j = cntNew[i];
7812 assert( j<nMaxCells );
7813 assert( b.apCell[j]!=0 );
7814 pCell = b.apCell[j];
7815 sz = b.szCell[j] + leafCorrection;
7816 pTemp = &aOvflSpace[iOvflSpace];
7817 if( !pNew->leaf ){
7818 memcpy(&pNew->aData[8], pCell, 4);
7819 }else if( leafData ){
7820 /* If the tree is a leaf-data tree, and the siblings are leaves,
7821 ** then there is no divider cell in b.apCell[]. Instead, the divider
7822 ** cell consists of the integer key for the right-most cell of
7823 ** the sibling-page assembled above only.
7825 CellInfo info;
7826 j--;
7827 pNew->xParseCell(pNew, b.apCell[j], &info);
7828 pCell = pTemp;
7829 sz = 4 + putVarint(&pCell[4], info.nKey);
7830 pTemp = 0;
7831 }else{
7832 pCell -= 4;
7833 /* Obscure case for non-leaf-data trees: If the cell at pCell was
7834 ** previously stored on a leaf node, and its reported size was 4
7835 ** bytes, then it may actually be smaller than this
7836 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
7837 ** any cell). But it is important to pass the correct size to
7838 ** insertCell(), so reparse the cell now.
7840 ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
7841 ** and WITHOUT ROWID tables with exactly one column which is the
7842 ** primary key.
7844 if( b.szCell[j]==4 ){
7845 assert(leafCorrection==4);
7846 sz = pParent->xCellSize(pParent, pCell);
7849 iOvflSpace += sz;
7850 assert( sz<=pBt->maxLocal+23 );
7851 assert( iOvflSpace <= (int)pBt->pageSize );
7852 insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
7853 if( rc!=SQLITE_OK ) goto balance_cleanup;
7854 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7857 /* Now update the actual sibling pages. The order in which they are updated
7858 ** is important, as this code needs to avoid disrupting any page from which
7859 ** cells may still to be read. In practice, this means:
7861 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
7862 ** then it is not safe to update page apNew[iPg] until after
7863 ** the left-hand sibling apNew[iPg-1] has been updated.
7865 ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
7866 ** then it is not safe to update page apNew[iPg] until after
7867 ** the right-hand sibling apNew[iPg+1] has been updated.
7869 ** If neither of the above apply, the page is safe to update.
7871 ** The iPg value in the following loop starts at nNew-1 goes down
7872 ** to 0, then back up to nNew-1 again, thus making two passes over
7873 ** the pages. On the initial downward pass, only condition (1) above
7874 ** needs to be tested because (2) will always be true from the previous
7875 ** step. On the upward pass, both conditions are always true, so the
7876 ** upwards pass simply processes pages that were missed on the downward
7877 ** pass.
7879 for(i=1-nNew; i<nNew; i++){
7880 int iPg = i<0 ? -i : i;
7881 assert( iPg>=0 && iPg<nNew );
7882 if( abDone[iPg] ) continue; /* Skip pages already processed */
7883 if( i>=0 /* On the upwards pass, or... */
7884 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
7886 int iNew;
7887 int iOld;
7888 int nNewCell;
7890 /* Verify condition (1): If cells are moving left, update iPg
7891 ** only after iPg-1 has already been updated. */
7892 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
7894 /* Verify condition (2): If cells are moving right, update iPg
7895 ** only after iPg+1 has already been updated. */
7896 assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
7898 if( iPg==0 ){
7899 iNew = iOld = 0;
7900 nNewCell = cntNew[0];
7901 }else{
7902 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
7903 iNew = cntNew[iPg-1] + !leafData;
7904 nNewCell = cntNew[iPg] - iNew;
7907 rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
7908 if( rc ) goto balance_cleanup;
7909 abDone[iPg]++;
7910 apNew[iPg]->nFree = usableSpace-szNew[iPg];
7911 assert( apNew[iPg]->nOverflow==0 );
7912 assert( apNew[iPg]->nCell==nNewCell );
7916 /* All pages have been processed exactly once */
7917 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
7919 assert( nOld>0 );
7920 assert( nNew>0 );
7922 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
7923 /* The root page of the b-tree now contains no cells. The only sibling
7924 ** page is the right-child of the parent. Copy the contents of the
7925 ** child page into the parent, decreasing the overall height of the
7926 ** b-tree structure by one. This is described as the "balance-shallower"
7927 ** sub-algorithm in some documentation.
7929 ** If this is an auto-vacuum database, the call to copyNodeContent()
7930 ** sets all pointer-map entries corresponding to database image pages
7931 ** for which the pointer is stored within the content being copied.
7933 ** It is critical that the child page be defragmented before being
7934 ** copied into the parent, because if the parent is page 1 then it will
7935 ** by smaller than the child due to the database header, and so all the
7936 ** free space needs to be up front.
7938 assert( nNew==1 || CORRUPT_DB );
7939 rc = defragmentPage(apNew[0], -1);
7940 testcase( rc!=SQLITE_OK );
7941 assert( apNew[0]->nFree ==
7942 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
7943 || rc!=SQLITE_OK
7945 copyNodeContent(apNew[0], pParent, &rc);
7946 freePage(apNew[0], &rc);
7947 }else if( ISAUTOVACUUM && !leafCorrection ){
7948 /* Fix the pointer map entries associated with the right-child of each
7949 ** sibling page. All other pointer map entries have already been taken
7950 ** care of. */
7951 for(i=0; i<nNew; i++){
7952 u32 key = get4byte(&apNew[i]->aData[8]);
7953 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
7957 assert( pParent->isInit );
7958 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
7959 nOld, nNew, b.nCell));
7961 /* Free any old pages that were not reused as new pages.
7963 for(i=nNew; i<nOld; i++){
7964 freePage(apOld[i], &rc);
7967 #if 0
7968 if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
7969 /* The ptrmapCheckPages() contains assert() statements that verify that
7970 ** all pointer map pages are set correctly. This is helpful while
7971 ** debugging. This is usually disabled because a corrupt database may
7972 ** cause an assert() statement to fail. */
7973 ptrmapCheckPages(apNew, nNew);
7974 ptrmapCheckPages(&pParent, 1);
7976 #endif
7979 ** Cleanup before returning.
7981 balance_cleanup:
7982 sqlite3StackFree(0, b.apCell);
7983 for(i=0; i<nOld; i++){
7984 releasePage(apOld[i]);
7986 for(i=0; i<nNew; i++){
7987 releasePage(apNew[i]);
7990 return rc;
7995 ** This function is called when the root page of a b-tree structure is
7996 ** overfull (has one or more overflow pages).
7998 ** A new child page is allocated and the contents of the current root
7999 ** page, including overflow cells, are copied into the child. The root
8000 ** page is then overwritten to make it an empty page with the right-child
8001 ** pointer pointing to the new page.
8003 ** Before returning, all pointer-map entries corresponding to pages
8004 ** that the new child-page now contains pointers to are updated. The
8005 ** entry corresponding to the new right-child pointer of the root
8006 ** page is also updated.
8008 ** If successful, *ppChild is set to contain a reference to the child
8009 ** page and SQLITE_OK is returned. In this case the caller is required
8010 ** to call releasePage() on *ppChild exactly once. If an error occurs,
8011 ** an error code is returned and *ppChild is set to 0.
8013 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
8014 int rc; /* Return value from subprocedures */
8015 MemPage *pChild = 0; /* Pointer to a new child page */
8016 Pgno pgnoChild = 0; /* Page number of the new child page */
8017 BtShared *pBt = pRoot->pBt; /* The BTree */
8019 assert( pRoot->nOverflow>0 );
8020 assert( sqlite3_mutex_held(pBt->mutex) );
8022 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
8023 ** page that will become the new right-child of pPage. Copy the contents
8024 ** of the node stored on pRoot into the new child page.
8026 rc = sqlite3PagerWrite(pRoot->pDbPage);
8027 if( rc==SQLITE_OK ){
8028 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
8029 copyNodeContent(pRoot, pChild, &rc);
8030 if( ISAUTOVACUUM ){
8031 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
8034 if( rc ){
8035 *ppChild = 0;
8036 releasePage(pChild);
8037 return rc;
8039 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
8040 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
8041 assert( pChild->nCell==pRoot->nCell );
8043 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
8045 /* Copy the overflow cells from pRoot to pChild */
8046 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
8047 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
8048 memcpy(pChild->apOvfl, pRoot->apOvfl,
8049 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
8050 pChild->nOverflow = pRoot->nOverflow;
8052 /* Zero the contents of pRoot. Then install pChild as the right-child. */
8053 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
8054 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
8056 *ppChild = pChild;
8057 return SQLITE_OK;
8061 ** The page that pCur currently points to has just been modified in
8062 ** some way. This function figures out if this modification means the
8063 ** tree needs to be balanced, and if so calls the appropriate balancing
8064 ** routine. Balancing routines are:
8066 ** balance_quick()
8067 ** balance_deeper()
8068 ** balance_nonroot()
8070 static int balance(BtCursor *pCur){
8071 int rc = SQLITE_OK;
8072 const int nMin = pCur->pBt->usableSize * 2 / 3;
8073 u8 aBalanceQuickSpace[13];
8074 u8 *pFree = 0;
8076 VVA_ONLY( int balance_quick_called = 0 );
8077 VVA_ONLY( int balance_deeper_called = 0 );
8079 do {
8080 int iPage = pCur->iPage;
8081 MemPage *pPage = pCur->pPage;
8083 if( iPage==0 ){
8084 if( pPage->nOverflow ){
8085 /* The root page of the b-tree is overfull. In this case call the
8086 ** balance_deeper() function to create a new child for the root-page
8087 ** and copy the current contents of the root-page to it. The
8088 ** next iteration of the do-loop will balance the child page.
8090 assert( balance_deeper_called==0 );
8091 VVA_ONLY( balance_deeper_called++ );
8092 rc = balance_deeper(pPage, &pCur->apPage[1]);
8093 if( rc==SQLITE_OK ){
8094 pCur->iPage = 1;
8095 pCur->ix = 0;
8096 pCur->aiIdx[0] = 0;
8097 pCur->apPage[0] = pPage;
8098 pCur->pPage = pCur->apPage[1];
8099 assert( pCur->pPage->nOverflow );
8101 }else{
8102 break;
8104 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
8105 break;
8106 }else{
8107 MemPage * const pParent = pCur->apPage[iPage-1];
8108 int const iIdx = pCur->aiIdx[iPage-1];
8110 rc = sqlite3PagerWrite(pParent->pDbPage);
8111 if( rc==SQLITE_OK ){
8112 #ifndef SQLITE_OMIT_QUICKBALANCE
8113 if( pPage->intKeyLeaf
8114 && pPage->nOverflow==1
8115 && pPage->aiOvfl[0]==pPage->nCell
8116 && pParent->pgno!=1
8117 && pParent->nCell==iIdx
8119 /* Call balance_quick() to create a new sibling of pPage on which
8120 ** to store the overflow cell. balance_quick() inserts a new cell
8121 ** into pParent, which may cause pParent overflow. If this
8122 ** happens, the next iteration of the do-loop will balance pParent
8123 ** use either balance_nonroot() or balance_deeper(). Until this
8124 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
8125 ** buffer.
8127 ** The purpose of the following assert() is to check that only a
8128 ** single call to balance_quick() is made for each call to this
8129 ** function. If this were not verified, a subtle bug involving reuse
8130 ** of the aBalanceQuickSpace[] might sneak in.
8132 assert( balance_quick_called==0 );
8133 VVA_ONLY( balance_quick_called++ );
8134 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
8135 }else
8136 #endif
8138 /* In this case, call balance_nonroot() to redistribute cells
8139 ** between pPage and up to 2 of its sibling pages. This involves
8140 ** modifying the contents of pParent, which may cause pParent to
8141 ** become overfull or underfull. The next iteration of the do-loop
8142 ** will balance the parent page to correct this.
8144 ** If the parent page becomes overfull, the overflow cell or cells
8145 ** are stored in the pSpace buffer allocated immediately below.
8146 ** A subsequent iteration of the do-loop will deal with this by
8147 ** calling balance_nonroot() (balance_deeper() may be called first,
8148 ** but it doesn't deal with overflow cells - just moves them to a
8149 ** different page). Once this subsequent call to balance_nonroot()
8150 ** has completed, it is safe to release the pSpace buffer used by
8151 ** the previous call, as the overflow cell data will have been
8152 ** copied either into the body of a database page or into the new
8153 ** pSpace buffer passed to the latter call to balance_nonroot().
8155 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
8156 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
8157 pCur->hints&BTREE_BULKLOAD);
8158 if( pFree ){
8159 /* If pFree is not NULL, it points to the pSpace buffer used
8160 ** by a previous call to balance_nonroot(). Its contents are
8161 ** now stored either on real database pages or within the
8162 ** new pSpace buffer, so it may be safely freed here. */
8163 sqlite3PageFree(pFree);
8166 /* The pSpace buffer will be freed after the next call to
8167 ** balance_nonroot(), or just before this function returns, whichever
8168 ** comes first. */
8169 pFree = pSpace;
8173 pPage->nOverflow = 0;
8175 /* The next iteration of the do-loop balances the parent page. */
8176 releasePage(pPage);
8177 pCur->iPage--;
8178 assert( pCur->iPage>=0 );
8179 pCur->pPage = pCur->apPage[pCur->iPage];
8181 }while( rc==SQLITE_OK );
8183 if( pFree ){
8184 sqlite3PageFree(pFree);
8186 return rc;
8189 /* Overwrite content from pX into pDest. Only do the write if the
8190 ** content is different from what is already there.
8192 static int btreeOverwriteContent(
8193 MemPage *pPage, /* MemPage on which writing will occur */
8194 u8 *pDest, /* Pointer to the place to start writing */
8195 const BtreePayload *pX, /* Source of data to write */
8196 int iOffset, /* Offset of first byte to write */
8197 int iAmt /* Number of bytes to be written */
8199 int nData = pX->nData - iOffset;
8200 if( nData<=0 ){
8201 /* Overwritting with zeros */
8202 int i;
8203 for(i=0; i<iAmt && pDest[i]==0; i++){}
8204 if( i<iAmt ){
8205 int rc = sqlite3PagerWrite(pPage->pDbPage);
8206 if( rc ) return rc;
8207 memset(pDest + i, 0, iAmt - i);
8209 }else{
8210 if( nData<iAmt ){
8211 /* Mixed read data and zeros at the end. Make a recursive call
8212 ** to write the zeros then fall through to write the real data */
8213 int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
8214 iAmt-nData);
8215 if( rc ) return rc;
8216 iAmt = nData;
8218 if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
8219 int rc = sqlite3PagerWrite(pPage->pDbPage);
8220 if( rc ) return rc;
8221 memcpy(pDest, ((u8*)pX->pData) + iOffset, iAmt);
8224 return SQLITE_OK;
8228 ** Overwrite the cell that cursor pCur is pointing to with fresh content
8229 ** contained in pX.
8231 static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
8232 int iOffset; /* Next byte of pX->pData to write */
8233 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
8234 int rc; /* Return code */
8235 MemPage *pPage = pCur->pPage; /* Page being written */
8236 BtShared *pBt; /* Btree */
8237 Pgno ovflPgno; /* Next overflow page to write */
8238 u32 ovflPageSize; /* Size to write on overflow page */
8240 if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd ){
8241 return SQLITE_CORRUPT_BKPT;
8243 /* Overwrite the local portion first */
8244 rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
8245 0, pCur->info.nLocal);
8246 if( rc ) return rc;
8247 if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
8249 /* Now overwrite the overflow pages */
8250 iOffset = pCur->info.nLocal;
8251 assert( nTotal>=0 );
8252 assert( iOffset>=0 );
8253 ovflPgno = get4byte(pCur->info.pPayload + iOffset);
8254 pBt = pPage->pBt;
8255 ovflPageSize = pBt->usableSize - 4;
8257 rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
8258 if( rc ) return rc;
8259 if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){
8260 rc = SQLITE_CORRUPT_BKPT;
8261 }else{
8262 if( iOffset+ovflPageSize<(u32)nTotal ){
8263 ovflPgno = get4byte(pPage->aData);
8264 }else{
8265 ovflPageSize = nTotal - iOffset;
8267 rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
8268 iOffset, ovflPageSize);
8270 sqlite3PagerUnref(pPage->pDbPage);
8271 if( rc ) return rc;
8272 iOffset += ovflPageSize;
8273 }while( iOffset<nTotal );
8274 return SQLITE_OK;
8279 ** Insert a new record into the BTree. The content of the new record
8280 ** is described by the pX object. The pCur cursor is used only to
8281 ** define what table the record should be inserted into, and is left
8282 ** pointing at a random location.
8284 ** For a table btree (used for rowid tables), only the pX.nKey value of
8285 ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
8286 ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
8287 ** hold the content of the row.
8289 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
8290 ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
8291 ** pX.pData,nData,nZero fields must be zero.
8293 ** If the seekResult parameter is non-zero, then a successful call to
8294 ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
8295 ** been performed. In other words, if seekResult!=0 then the cursor
8296 ** is currently pointing to a cell that will be adjacent to the cell
8297 ** to be inserted. If seekResult<0 then pCur points to a cell that is
8298 ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
8299 ** that is larger than (pKey,nKey).
8301 ** If seekResult==0, that means pCur is pointing at some unknown location.
8302 ** In that case, this routine must seek the cursor to the correct insertion
8303 ** point for (pKey,nKey) before doing the insertion. For index btrees,
8304 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
8305 ** key values and pX->aMem can be used instead of pX->pKey to avoid having
8306 ** to decode the key.
8308 int sqlite3BtreeInsert(
8309 BtCursor *pCur, /* Insert data into the table of this cursor */
8310 const BtreePayload *pX, /* Content of the row to be inserted */
8311 int flags, /* True if this is likely an append */
8312 int seekResult /* Result of prior MovetoUnpacked() call */
8314 int rc;
8315 int loc = seekResult; /* -1: before desired location +1: after */
8316 int szNew = 0;
8317 int idx;
8318 MemPage *pPage;
8319 Btree *p = pCur->pBtree;
8320 BtShared *pBt = p->pBt;
8321 unsigned char *oldCell;
8322 unsigned char *newCell = 0;
8324 assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
8326 if( pCur->eState==CURSOR_FAULT ){
8327 assert( pCur->skipNext!=SQLITE_OK );
8328 return pCur->skipNext;
8331 assert( cursorOwnsBtShared(pCur) );
8332 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
8333 && pBt->inTransaction==TRANS_WRITE
8334 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
8335 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8337 /* Assert that the caller has been consistent. If this cursor was opened
8338 ** expecting an index b-tree, then the caller should be inserting blob
8339 ** keys with no associated data. If the cursor was opened expecting an
8340 ** intkey table, the caller should be inserting integer keys with a
8341 ** blob of associated data. */
8342 assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
8344 /* Save the positions of any other cursors open on this table.
8346 ** In some cases, the call to btreeMoveto() below is a no-op. For
8347 ** example, when inserting data into a table with auto-generated integer
8348 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
8349 ** integer key to use. It then calls this function to actually insert the
8350 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
8351 ** that the cursor is already where it needs to be and returns without
8352 ** doing any work. To avoid thwarting these optimizations, it is important
8353 ** not to clear the cursor here.
8355 if( pCur->curFlags & BTCF_Multiple ){
8356 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8357 if( rc ) return rc;
8360 if( pCur->pKeyInfo==0 ){
8361 assert( pX->pKey==0 );
8362 /* If this is an insert into a table b-tree, invalidate any incrblob
8363 ** cursors open on the row being replaced */
8364 invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
8366 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8367 ** to a row with the same key as the new entry being inserted.
8369 #ifdef SQLITE_DEBUG
8370 if( flags & BTREE_SAVEPOSITION ){
8371 assert( pCur->curFlags & BTCF_ValidNKey );
8372 assert( pX->nKey==pCur->info.nKey );
8373 assert( pCur->info.nSize!=0 );
8374 assert( loc==0 );
8376 #endif
8378 /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
8379 ** that the cursor is not pointing to a row to be overwritten.
8380 ** So do a complete check.
8382 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
8383 /* The cursor is pointing to the entry that is to be
8384 ** overwritten */
8385 assert( pX->nData>=0 && pX->nZero>=0 );
8386 if( pCur->info.nSize!=0
8387 && pCur->info.nPayload==(u32)pX->nData+pX->nZero
8389 /* New entry is the same size as the old. Do an overwrite */
8390 return btreeOverwriteCell(pCur, pX);
8392 assert( loc==0 );
8393 }else if( loc==0 ){
8394 /* The cursor is *not* pointing to the cell to be overwritten, nor
8395 ** to an adjacent cell. Move the cursor so that it is pointing either
8396 ** to the cell to be overwritten or an adjacent cell.
8398 rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
8399 if( rc ) return rc;
8401 }else{
8402 /* This is an index or a WITHOUT ROWID table */
8404 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8405 ** to a row with the same key as the new entry being inserted.
8407 assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
8409 /* If the cursor is not already pointing either to the cell to be
8410 ** overwritten, or if a new cell is being inserted, if the cursor is
8411 ** not pointing to an immediately adjacent cell, then move the cursor
8412 ** so that it does.
8414 if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
8415 if( pX->nMem ){
8416 UnpackedRecord r;
8417 r.pKeyInfo = pCur->pKeyInfo;
8418 r.aMem = pX->aMem;
8419 r.nField = pX->nMem;
8420 r.default_rc = 0;
8421 r.errCode = 0;
8422 r.r1 = 0;
8423 r.r2 = 0;
8424 r.eqSeen = 0;
8425 rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
8426 }else{
8427 rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
8429 if( rc ) return rc;
8432 /* If the cursor is currently pointing to an entry to be overwritten
8433 ** and the new content is the same as as the old, then use the
8434 ** overwrite optimization.
8436 if( loc==0 ){
8437 getCellInfo(pCur);
8438 if( pCur->info.nKey==pX->nKey ){
8439 BtreePayload x2;
8440 x2.pData = pX->pKey;
8441 x2.nData = pX->nKey;
8442 x2.nZero = 0;
8443 return btreeOverwriteCell(pCur, &x2);
8448 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
8450 pPage = pCur->pPage;
8451 assert( pPage->intKey || pX->nKey>=0 );
8452 assert( pPage->leaf || !pPage->intKey );
8454 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
8455 pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
8456 loc==0 ? "overwrite" : "new entry"));
8457 assert( pPage->isInit );
8458 newCell = pBt->pTmpSpace;
8459 assert( newCell!=0 );
8460 rc = fillInCell(pPage, newCell, pX, &szNew);
8461 if( rc ) goto end_insert;
8462 assert( szNew==pPage->xCellSize(pPage, newCell) );
8463 assert( szNew <= MX_CELL_SIZE(pBt) );
8464 idx = pCur->ix;
8465 if( loc==0 ){
8466 CellInfo info;
8467 assert( idx<pPage->nCell );
8468 rc = sqlite3PagerWrite(pPage->pDbPage);
8469 if( rc ){
8470 goto end_insert;
8472 oldCell = findCell(pPage, idx);
8473 if( !pPage->leaf ){
8474 memcpy(newCell, oldCell, 4);
8476 rc = clearCell(pPage, oldCell, &info);
8477 if( info.nSize==szNew && info.nLocal==info.nPayload
8478 && (!ISAUTOVACUUM || szNew<pPage->minLocal)
8480 /* Overwrite the old cell with the new if they are the same size.
8481 ** We could also try to do this if the old cell is smaller, then add
8482 ** the leftover space to the free list. But experiments show that
8483 ** doing that is no faster then skipping this optimization and just
8484 ** calling dropCell() and insertCell().
8486 ** This optimization cannot be used on an autovacuum database if the
8487 ** new entry uses overflow pages, as the insertCell() call below is
8488 ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
8489 assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
8490 if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
8491 memcpy(oldCell, newCell, szNew);
8492 return SQLITE_OK;
8494 dropCell(pPage, idx, info.nSize, &rc);
8495 if( rc ) goto end_insert;
8496 }else if( loc<0 && pPage->nCell>0 ){
8497 assert( pPage->leaf );
8498 idx = ++pCur->ix;
8499 pCur->curFlags &= ~BTCF_ValidNKey;
8500 }else{
8501 assert( pPage->leaf );
8503 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
8504 assert( pPage->nOverflow==0 || rc==SQLITE_OK );
8505 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
8507 /* If no error has occurred and pPage has an overflow cell, call balance()
8508 ** to redistribute the cells within the tree. Since balance() may move
8509 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
8510 ** variables.
8512 ** Previous versions of SQLite called moveToRoot() to move the cursor
8513 ** back to the root page as balance() used to invalidate the contents
8514 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
8515 ** set the cursor state to "invalid". This makes common insert operations
8516 ** slightly faster.
8518 ** There is a subtle but important optimization here too. When inserting
8519 ** multiple records into an intkey b-tree using a single cursor (as can
8520 ** happen while processing an "INSERT INTO ... SELECT" statement), it
8521 ** is advantageous to leave the cursor pointing to the last entry in
8522 ** the b-tree if possible. If the cursor is left pointing to the last
8523 ** entry in the table, and the next row inserted has an integer key
8524 ** larger than the largest existing key, it is possible to insert the
8525 ** row without seeking the cursor. This can be a big performance boost.
8527 pCur->info.nSize = 0;
8528 if( pPage->nOverflow ){
8529 assert( rc==SQLITE_OK );
8530 pCur->curFlags &= ~(BTCF_ValidNKey);
8531 rc = balance(pCur);
8533 /* Must make sure nOverflow is reset to zero even if the balance()
8534 ** fails. Internal data structure corruption will result otherwise.
8535 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
8536 ** from trying to save the current position of the cursor. */
8537 pCur->pPage->nOverflow = 0;
8538 pCur->eState = CURSOR_INVALID;
8539 if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
8540 btreeReleaseAllCursorPages(pCur);
8541 if( pCur->pKeyInfo ){
8542 assert( pCur->pKey==0 );
8543 pCur->pKey = sqlite3Malloc( pX->nKey );
8544 if( pCur->pKey==0 ){
8545 rc = SQLITE_NOMEM;
8546 }else{
8547 memcpy(pCur->pKey, pX->pKey, pX->nKey);
8550 pCur->eState = CURSOR_REQUIRESEEK;
8551 pCur->nKey = pX->nKey;
8554 assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
8556 end_insert:
8557 return rc;
8561 ** Delete the entry that the cursor is pointing to.
8563 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
8564 ** the cursor is left pointing at an arbitrary location after the delete.
8565 ** But if that bit is set, then the cursor is left in a state such that
8566 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
8567 ** as it would have been on if the call to BtreeDelete() had been omitted.
8569 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
8570 ** associated with a single table entry and its indexes. Only one of those
8571 ** deletes is considered the "primary" delete. The primary delete occurs
8572 ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
8573 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
8574 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
8575 ** but which might be used by alternative storage engines.
8577 int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
8578 Btree *p = pCur->pBtree;
8579 BtShared *pBt = p->pBt;
8580 int rc; /* Return code */
8581 MemPage *pPage; /* Page to delete cell from */
8582 unsigned char *pCell; /* Pointer to cell to delete */
8583 int iCellIdx; /* Index of cell to delete */
8584 int iCellDepth; /* Depth of node containing pCell */
8585 CellInfo info; /* Size of the cell being deleted */
8586 int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
8587 u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
8589 assert( cursorOwnsBtShared(pCur) );
8590 assert( pBt->inTransaction==TRANS_WRITE );
8591 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
8592 assert( pCur->curFlags & BTCF_WriteFlag );
8593 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8594 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
8595 assert( pCur->ix<pCur->pPage->nCell );
8596 assert( pCur->eState==CURSOR_VALID );
8597 assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
8599 iCellDepth = pCur->iPage;
8600 iCellIdx = pCur->ix;
8601 pPage = pCur->pPage;
8602 pCell = findCell(pPage, iCellIdx);
8604 /* If the bPreserve flag is set to true, then the cursor position must
8605 ** be preserved following this delete operation. If the current delete
8606 ** will cause a b-tree rebalance, then this is done by saving the cursor
8607 ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
8608 ** returning.
8610 ** Or, if the current delete will not cause a rebalance, then the cursor
8611 ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
8612 ** before or after the deleted entry. In this case set bSkipnext to true. */
8613 if( bPreserve ){
8614 if( !pPage->leaf
8615 || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
8617 /* A b-tree rebalance will be required after deleting this entry.
8618 ** Save the cursor key. */
8619 rc = saveCursorKey(pCur);
8620 if( rc ) return rc;
8621 }else{
8622 bSkipnext = 1;
8626 /* If the page containing the entry to delete is not a leaf page, move
8627 ** the cursor to the largest entry in the tree that is smaller than
8628 ** the entry being deleted. This cell will replace the cell being deleted
8629 ** from the internal node. The 'previous' entry is used for this instead
8630 ** of the 'next' entry, as the previous entry is always a part of the
8631 ** sub-tree headed by the child page of the cell being deleted. This makes
8632 ** balancing the tree following the delete operation easier. */
8633 if( !pPage->leaf ){
8634 rc = sqlite3BtreePrevious(pCur, 0);
8635 assert( rc!=SQLITE_DONE );
8636 if( rc ) return rc;
8639 /* Save the positions of any other cursors open on this table before
8640 ** making any modifications. */
8641 if( pCur->curFlags & BTCF_Multiple ){
8642 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8643 if( rc ) return rc;
8646 /* If this is a delete operation to remove a row from a table b-tree,
8647 ** invalidate any incrblob cursors open on the row being deleted. */
8648 if( pCur->pKeyInfo==0 ){
8649 invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
8652 /* Make the page containing the entry to be deleted writable. Then free any
8653 ** overflow pages associated with the entry and finally remove the cell
8654 ** itself from within the page. */
8655 rc = sqlite3PagerWrite(pPage->pDbPage);
8656 if( rc ) return rc;
8657 rc = clearCell(pPage, pCell, &info);
8658 dropCell(pPage, iCellIdx, info.nSize, &rc);
8659 if( rc ) return rc;
8661 /* If the cell deleted was not located on a leaf page, then the cursor
8662 ** is currently pointing to the largest entry in the sub-tree headed
8663 ** by the child-page of the cell that was just deleted from an internal
8664 ** node. The cell from the leaf node needs to be moved to the internal
8665 ** node to replace the deleted cell. */
8666 if( !pPage->leaf ){
8667 MemPage *pLeaf = pCur->pPage;
8668 int nCell;
8669 Pgno n;
8670 unsigned char *pTmp;
8672 if( iCellDepth<pCur->iPage-1 ){
8673 n = pCur->apPage[iCellDepth+1]->pgno;
8674 }else{
8675 n = pCur->pPage->pgno;
8677 pCell = findCell(pLeaf, pLeaf->nCell-1);
8678 if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
8679 nCell = pLeaf->xCellSize(pLeaf, pCell);
8680 assert( MX_CELL_SIZE(pBt) >= nCell );
8681 pTmp = pBt->pTmpSpace;
8682 assert( pTmp!=0 );
8683 rc = sqlite3PagerWrite(pLeaf->pDbPage);
8684 if( rc==SQLITE_OK ){
8685 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
8687 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
8688 if( rc ) return rc;
8691 /* Balance the tree. If the entry deleted was located on a leaf page,
8692 ** then the cursor still points to that page. In this case the first
8693 ** call to balance() repairs the tree, and the if(...) condition is
8694 ** never true.
8696 ** Otherwise, if the entry deleted was on an internal node page, then
8697 ** pCur is pointing to the leaf page from which a cell was removed to
8698 ** replace the cell deleted from the internal node. This is slightly
8699 ** tricky as the leaf node may be underfull, and the internal node may
8700 ** be either under or overfull. In this case run the balancing algorithm
8701 ** on the leaf node first. If the balance proceeds far enough up the
8702 ** tree that we can be sure that any problem in the internal node has
8703 ** been corrected, so be it. Otherwise, after balancing the leaf node,
8704 ** walk the cursor up the tree to the internal node and balance it as
8705 ** well. */
8706 rc = balance(pCur);
8707 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
8708 releasePageNotNull(pCur->pPage);
8709 pCur->iPage--;
8710 while( pCur->iPage>iCellDepth ){
8711 releasePage(pCur->apPage[pCur->iPage--]);
8713 pCur->pPage = pCur->apPage[pCur->iPage];
8714 rc = balance(pCur);
8717 if( rc==SQLITE_OK ){
8718 if( bSkipnext ){
8719 assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
8720 assert( pPage==pCur->pPage || CORRUPT_DB );
8721 assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
8722 pCur->eState = CURSOR_SKIPNEXT;
8723 if( iCellIdx>=pPage->nCell ){
8724 pCur->skipNext = -1;
8725 pCur->ix = pPage->nCell-1;
8726 }else{
8727 pCur->skipNext = 1;
8729 }else{
8730 rc = moveToRoot(pCur);
8731 if( bPreserve ){
8732 btreeReleaseAllCursorPages(pCur);
8733 pCur->eState = CURSOR_REQUIRESEEK;
8735 if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
8738 return rc;
8742 ** Create a new BTree table. Write into *piTable the page
8743 ** number for the root page of the new table.
8745 ** The type of type is determined by the flags parameter. Only the
8746 ** following values of flags are currently in use. Other values for
8747 ** flags might not work:
8749 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
8750 ** BTREE_ZERODATA Used for SQL indices
8752 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
8753 BtShared *pBt = p->pBt;
8754 MemPage *pRoot;
8755 Pgno pgnoRoot;
8756 int rc;
8757 int ptfFlags; /* Page-type flage for the root page of new table */
8759 assert( sqlite3BtreeHoldsMutex(p) );
8760 assert( pBt->inTransaction==TRANS_WRITE );
8761 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
8763 #ifdef SQLITE_OMIT_AUTOVACUUM
8764 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
8765 if( rc ){
8766 return rc;
8768 #else
8769 if( pBt->autoVacuum ){
8770 Pgno pgnoMove; /* Move a page here to make room for the root-page */
8771 MemPage *pPageMove; /* The page to move to. */
8773 /* Creating a new table may probably require moving an existing database
8774 ** to make room for the new tables root page. In case this page turns
8775 ** out to be an overflow page, delete all overflow page-map caches
8776 ** held by open cursors.
8778 invalidateAllOverflowCache(pBt);
8780 /* Read the value of meta[3] from the database to determine where the
8781 ** root page of the new table should go. meta[3] is the largest root-page
8782 ** created so far, so the new root-page is (meta[3]+1).
8784 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
8785 pgnoRoot++;
8787 /* The new root-page may not be allocated on a pointer-map page, or the
8788 ** PENDING_BYTE page.
8790 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
8791 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
8792 pgnoRoot++;
8794 assert( pgnoRoot>=3 || CORRUPT_DB );
8795 testcase( pgnoRoot<3 );
8797 /* Allocate a page. The page that currently resides at pgnoRoot will
8798 ** be moved to the allocated page (unless the allocated page happens
8799 ** to reside at pgnoRoot).
8801 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
8802 if( rc!=SQLITE_OK ){
8803 return rc;
8806 if( pgnoMove!=pgnoRoot ){
8807 /* pgnoRoot is the page that will be used for the root-page of
8808 ** the new table (assuming an error did not occur). But we were
8809 ** allocated pgnoMove. If required (i.e. if it was not allocated
8810 ** by extending the file), the current page at position pgnoMove
8811 ** is already journaled.
8813 u8 eType = 0;
8814 Pgno iPtrPage = 0;
8816 /* Save the positions of any open cursors. This is required in
8817 ** case they are holding a reference to an xFetch reference
8818 ** corresponding to page pgnoRoot. */
8819 rc = saveAllCursors(pBt, 0, 0);
8820 releasePage(pPageMove);
8821 if( rc!=SQLITE_OK ){
8822 return rc;
8825 /* Move the page currently at pgnoRoot to pgnoMove. */
8826 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
8827 if( rc!=SQLITE_OK ){
8828 return rc;
8830 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
8831 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
8832 rc = SQLITE_CORRUPT_BKPT;
8834 if( rc!=SQLITE_OK ){
8835 releasePage(pRoot);
8836 return rc;
8838 assert( eType!=PTRMAP_ROOTPAGE );
8839 assert( eType!=PTRMAP_FREEPAGE );
8840 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
8841 releasePage(pRoot);
8843 /* Obtain the page at pgnoRoot */
8844 if( rc!=SQLITE_OK ){
8845 return rc;
8847 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
8848 if( rc!=SQLITE_OK ){
8849 return rc;
8851 rc = sqlite3PagerWrite(pRoot->pDbPage);
8852 if( rc!=SQLITE_OK ){
8853 releasePage(pRoot);
8854 return rc;
8856 }else{
8857 pRoot = pPageMove;
8860 /* Update the pointer-map and meta-data with the new root-page number. */
8861 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
8862 if( rc ){
8863 releasePage(pRoot);
8864 return rc;
8867 /* When the new root page was allocated, page 1 was made writable in
8868 ** order either to increase the database filesize, or to decrement the
8869 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
8871 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
8872 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
8873 if( NEVER(rc) ){
8874 releasePage(pRoot);
8875 return rc;
8878 }else{
8879 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
8880 if( rc ) return rc;
8882 #endif
8883 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
8884 if( createTabFlags & BTREE_INTKEY ){
8885 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
8886 }else{
8887 ptfFlags = PTF_ZERODATA | PTF_LEAF;
8889 zeroPage(pRoot, ptfFlags);
8890 sqlite3PagerUnref(pRoot->pDbPage);
8891 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
8892 *piTable = (int)pgnoRoot;
8893 return SQLITE_OK;
8895 int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
8896 int rc;
8897 sqlite3BtreeEnter(p);
8898 rc = btreeCreateTable(p, piTable, flags);
8899 sqlite3BtreeLeave(p);
8900 return rc;
8904 ** Erase the given database page and all its children. Return
8905 ** the page to the freelist.
8907 static int clearDatabasePage(
8908 BtShared *pBt, /* The BTree that contains the table */
8909 Pgno pgno, /* Page number to clear */
8910 int freePageFlag, /* Deallocate page if true */
8911 int *pnChange /* Add number of Cells freed to this counter */
8913 MemPage *pPage;
8914 int rc;
8915 unsigned char *pCell;
8916 int i;
8917 int hdr;
8918 CellInfo info;
8920 assert( sqlite3_mutex_held(pBt->mutex) );
8921 if( pgno>btreePagecount(pBt) ){
8922 return SQLITE_CORRUPT_BKPT;
8924 rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
8925 if( rc ) return rc;
8926 if( pPage->bBusy ){
8927 rc = SQLITE_CORRUPT_BKPT;
8928 goto cleardatabasepage_out;
8930 pPage->bBusy = 1;
8931 hdr = pPage->hdrOffset;
8932 for(i=0; i<pPage->nCell; i++){
8933 pCell = findCell(pPage, i);
8934 if( !pPage->leaf ){
8935 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
8936 if( rc ) goto cleardatabasepage_out;
8938 rc = clearCell(pPage, pCell, &info);
8939 if( rc ) goto cleardatabasepage_out;
8941 if( !pPage->leaf ){
8942 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
8943 if( rc ) goto cleardatabasepage_out;
8944 }else if( pnChange ){
8945 assert( pPage->intKey || CORRUPT_DB );
8946 testcase( !pPage->intKey );
8947 *pnChange += pPage->nCell;
8949 if( freePageFlag ){
8950 freePage(pPage, &rc);
8951 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
8952 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
8955 cleardatabasepage_out:
8956 pPage->bBusy = 0;
8957 releasePage(pPage);
8958 return rc;
8962 ** Delete all information from a single table in the database. iTable is
8963 ** the page number of the root of the table. After this routine returns,
8964 ** the root page is empty, but still exists.
8966 ** This routine will fail with SQLITE_LOCKED if there are any open
8967 ** read cursors on the table. Open write cursors are moved to the
8968 ** root of the table.
8970 ** If pnChange is not NULL, then table iTable must be an intkey table. The
8971 ** integer value pointed to by pnChange is incremented by the number of
8972 ** entries in the table.
8974 int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
8975 int rc;
8976 BtShared *pBt = p->pBt;
8977 sqlite3BtreeEnter(p);
8978 assert( p->inTrans==TRANS_WRITE );
8980 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
8982 if( SQLITE_OK==rc ){
8983 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
8984 ** is the root of a table b-tree - if it is not, the following call is
8985 ** a no-op). */
8986 invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
8987 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
8989 sqlite3BtreeLeave(p);
8990 return rc;
8994 ** Delete all information from the single table that pCur is open on.
8996 ** This routine only work for pCur on an ephemeral table.
8998 int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
8999 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
9003 ** Erase all information in a table and add the root of the table to
9004 ** the freelist. Except, the root of the principle table (the one on
9005 ** page 1) is never added to the freelist.
9007 ** This routine will fail with SQLITE_LOCKED if there are any open
9008 ** cursors on the table.
9010 ** If AUTOVACUUM is enabled and the page at iTable is not the last
9011 ** root page in the database file, then the last root page
9012 ** in the database file is moved into the slot formerly occupied by
9013 ** iTable and that last slot formerly occupied by the last root page
9014 ** is added to the freelist instead of iTable. In this say, all
9015 ** root pages are kept at the beginning of the database file, which
9016 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
9017 ** page number that used to be the last root page in the file before
9018 ** the move. If no page gets moved, *piMoved is set to 0.
9019 ** The last root page is recorded in meta[3] and the value of
9020 ** meta[3] is updated by this procedure.
9022 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
9023 int rc;
9024 MemPage *pPage = 0;
9025 BtShared *pBt = p->pBt;
9027 assert( sqlite3BtreeHoldsMutex(p) );
9028 assert( p->inTrans==TRANS_WRITE );
9029 assert( iTable>=2 );
9031 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
9032 if( rc ) return rc;
9033 rc = sqlite3BtreeClearTable(p, iTable, 0);
9034 if( rc ){
9035 releasePage(pPage);
9036 return rc;
9039 *piMoved = 0;
9041 #ifdef SQLITE_OMIT_AUTOVACUUM
9042 freePage(pPage, &rc);
9043 releasePage(pPage);
9044 #else
9045 if( pBt->autoVacuum ){
9046 Pgno maxRootPgno;
9047 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
9049 if( iTable==maxRootPgno ){
9050 /* If the table being dropped is the table with the largest root-page
9051 ** number in the database, put the root page on the free list.
9053 freePage(pPage, &rc);
9054 releasePage(pPage);
9055 if( rc!=SQLITE_OK ){
9056 return rc;
9058 }else{
9059 /* The table being dropped does not have the largest root-page
9060 ** number in the database. So move the page that does into the
9061 ** gap left by the deleted root-page.
9063 MemPage *pMove;
9064 releasePage(pPage);
9065 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9066 if( rc!=SQLITE_OK ){
9067 return rc;
9069 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
9070 releasePage(pMove);
9071 if( rc!=SQLITE_OK ){
9072 return rc;
9074 pMove = 0;
9075 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9076 freePage(pMove, &rc);
9077 releasePage(pMove);
9078 if( rc!=SQLITE_OK ){
9079 return rc;
9081 *piMoved = maxRootPgno;
9084 /* Set the new 'max-root-page' value in the database header. This
9085 ** is the old value less one, less one more if that happens to
9086 ** be a root-page number, less one again if that is the
9087 ** PENDING_BYTE_PAGE.
9089 maxRootPgno--;
9090 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
9091 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
9092 maxRootPgno--;
9094 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
9096 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
9097 }else{
9098 freePage(pPage, &rc);
9099 releasePage(pPage);
9101 #endif
9102 return rc;
9104 int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
9105 int rc;
9106 sqlite3BtreeEnter(p);
9107 rc = btreeDropTable(p, iTable, piMoved);
9108 sqlite3BtreeLeave(p);
9109 return rc;
9114 ** This function may only be called if the b-tree connection already
9115 ** has a read or write transaction open on the database.
9117 ** Read the meta-information out of a database file. Meta[0]
9118 ** is the number of free pages currently in the database. Meta[1]
9119 ** through meta[15] are available for use by higher layers. Meta[0]
9120 ** is read-only, the others are read/write.
9122 ** The schema layer numbers meta values differently. At the schema
9123 ** layer (and the SetCookie and ReadCookie opcodes) the number of
9124 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
9126 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
9127 ** of reading the value out of the header, it instead loads the "DataVersion"
9128 ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
9129 ** database file. It is a number computed by the pager. But its access
9130 ** pattern is the same as header meta values, and so it is convenient to
9131 ** read it from this routine.
9133 void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
9134 BtShared *pBt = p->pBt;
9136 sqlite3BtreeEnter(p);
9137 assert( p->inTrans>TRANS_NONE );
9138 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
9139 assert( pBt->pPage1 );
9140 assert( idx>=0 && idx<=15 );
9142 if( idx==BTREE_DATA_VERSION ){
9143 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
9144 }else{
9145 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
9148 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
9149 ** database, mark the database as read-only. */
9150 #ifdef SQLITE_OMIT_AUTOVACUUM
9151 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
9152 pBt->btsFlags |= BTS_READ_ONLY;
9154 #endif
9156 sqlite3BtreeLeave(p);
9160 ** Write meta-information back into the database. Meta[0] is
9161 ** read-only and may not be written.
9163 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
9164 BtShared *pBt = p->pBt;
9165 unsigned char *pP1;
9166 int rc;
9167 assert( idx>=1 && idx<=15 );
9168 sqlite3BtreeEnter(p);
9169 assert( p->inTrans==TRANS_WRITE );
9170 assert( pBt->pPage1!=0 );
9171 pP1 = pBt->pPage1->aData;
9172 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
9173 if( rc==SQLITE_OK ){
9174 put4byte(&pP1[36 + idx*4], iMeta);
9175 #ifndef SQLITE_OMIT_AUTOVACUUM
9176 if( idx==BTREE_INCR_VACUUM ){
9177 assert( pBt->autoVacuum || iMeta==0 );
9178 assert( iMeta==0 || iMeta==1 );
9179 pBt->incrVacuum = (u8)iMeta;
9181 #endif
9183 sqlite3BtreeLeave(p);
9184 return rc;
9187 #ifndef SQLITE_OMIT_BTREECOUNT
9189 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
9190 ** number of entries in the b-tree and write the result to *pnEntry.
9192 ** SQLITE_OK is returned if the operation is successfully executed.
9193 ** Otherwise, if an error is encountered (i.e. an IO error or database
9194 ** corruption) an SQLite error code is returned.
9196 int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
9197 i64 nEntry = 0; /* Value to return in *pnEntry */
9198 int rc; /* Return code */
9200 rc = moveToRoot(pCur);
9201 if( rc==SQLITE_EMPTY ){
9202 *pnEntry = 0;
9203 return SQLITE_OK;
9206 /* Unless an error occurs, the following loop runs one iteration for each
9207 ** page in the B-Tree structure (not including overflow pages).
9209 while( rc==SQLITE_OK ){
9210 int iIdx; /* Index of child node in parent */
9211 MemPage *pPage; /* Current page of the b-tree */
9213 /* If this is a leaf page or the tree is not an int-key tree, then
9214 ** this page contains countable entries. Increment the entry counter
9215 ** accordingly.
9217 pPage = pCur->pPage;
9218 if( pPage->leaf || !pPage->intKey ){
9219 nEntry += pPage->nCell;
9222 /* pPage is a leaf node. This loop navigates the cursor so that it
9223 ** points to the first interior cell that it points to the parent of
9224 ** the next page in the tree that has not yet been visited. The
9225 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
9226 ** of the page, or to the number of cells in the page if the next page
9227 ** to visit is the right-child of its parent.
9229 ** If all pages in the tree have been visited, return SQLITE_OK to the
9230 ** caller.
9232 if( pPage->leaf ){
9233 do {
9234 if( pCur->iPage==0 ){
9235 /* All pages of the b-tree have been visited. Return successfully. */
9236 *pnEntry = nEntry;
9237 return moveToRoot(pCur);
9239 moveToParent(pCur);
9240 }while ( pCur->ix>=pCur->pPage->nCell );
9242 pCur->ix++;
9243 pPage = pCur->pPage;
9246 /* Descend to the child node of the cell that the cursor currently
9247 ** points at. This is the right-child if (iIdx==pPage->nCell).
9249 iIdx = pCur->ix;
9250 if( iIdx==pPage->nCell ){
9251 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
9252 }else{
9253 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
9257 /* An error has occurred. Return an error code. */
9258 return rc;
9260 #endif
9263 ** Return the pager associated with a BTree. This routine is used for
9264 ** testing and debugging only.
9266 Pager *sqlite3BtreePager(Btree *p){
9267 return p->pBt->pPager;
9270 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9272 ** Append a message to the error message string.
9274 static void checkAppendMsg(
9275 IntegrityCk *pCheck,
9276 const char *zFormat,
9279 va_list ap;
9280 if( !pCheck->mxErr ) return;
9281 pCheck->mxErr--;
9282 pCheck->nErr++;
9283 va_start(ap, zFormat);
9284 if( pCheck->errMsg.nChar ){
9285 sqlite3_str_append(&pCheck->errMsg, "\n", 1);
9287 if( pCheck->zPfx ){
9288 sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
9290 sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
9291 va_end(ap);
9292 if( pCheck->errMsg.accError==SQLITE_NOMEM ){
9293 pCheck->mallocFailed = 1;
9296 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9298 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9301 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
9302 ** corresponds to page iPg is already set.
9304 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9305 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9306 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
9310 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
9312 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9313 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9314 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
9319 ** Add 1 to the reference count for page iPage. If this is the second
9320 ** reference to the page, add an error message to pCheck->zErrMsg.
9321 ** Return 1 if there are 2 or more references to the page and 0 if
9322 ** if this is the first reference to the page.
9324 ** Also check that the page number is in bounds.
9326 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
9327 if( iPage==0 ) return 1;
9328 if( iPage>pCheck->nPage ){
9329 checkAppendMsg(pCheck, "invalid page number %d", iPage);
9330 return 1;
9332 if( getPageReferenced(pCheck, iPage) ){
9333 checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
9334 return 1;
9336 setPageReferenced(pCheck, iPage);
9337 return 0;
9340 #ifndef SQLITE_OMIT_AUTOVACUUM
9342 ** Check that the entry in the pointer-map for page iChild maps to
9343 ** page iParent, pointer type ptrType. If not, append an error message
9344 ** to pCheck.
9346 static void checkPtrmap(
9347 IntegrityCk *pCheck, /* Integrity check context */
9348 Pgno iChild, /* Child page number */
9349 u8 eType, /* Expected pointer map type */
9350 Pgno iParent /* Expected pointer map parent page number */
9352 int rc;
9353 u8 ePtrmapType;
9354 Pgno iPtrmapParent;
9356 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
9357 if( rc!=SQLITE_OK ){
9358 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
9359 checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
9360 return;
9363 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
9364 checkAppendMsg(pCheck,
9365 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
9366 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
9369 #endif
9372 ** Check the integrity of the freelist or of an overflow page list.
9373 ** Verify that the number of pages on the list is N.
9375 static void checkList(
9376 IntegrityCk *pCheck, /* Integrity checking context */
9377 int isFreeList, /* True for a freelist. False for overflow page list */
9378 int iPage, /* Page number for first page in the list */
9379 int N /* Expected number of pages in the list */
9381 int i;
9382 int expected = N;
9383 int iFirst = iPage;
9384 while( N-- > 0 && pCheck->mxErr ){
9385 DbPage *pOvflPage;
9386 unsigned char *pOvflData;
9387 if( iPage<1 ){
9388 checkAppendMsg(pCheck,
9389 "%d of %d pages missing from overflow list starting at %d",
9390 N+1, expected, iFirst);
9391 break;
9393 if( checkRef(pCheck, iPage) ) break;
9394 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
9395 checkAppendMsg(pCheck, "failed to get page %d", iPage);
9396 break;
9398 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
9399 if( isFreeList ){
9400 int n = get4byte(&pOvflData[4]);
9401 #ifndef SQLITE_OMIT_AUTOVACUUM
9402 if( pCheck->pBt->autoVacuum ){
9403 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
9405 #endif
9406 if( n>(int)pCheck->pBt->usableSize/4-2 ){
9407 checkAppendMsg(pCheck,
9408 "freelist leaf count too big on page %d", iPage);
9409 N--;
9410 }else{
9411 for(i=0; i<n; i++){
9412 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
9413 #ifndef SQLITE_OMIT_AUTOVACUUM
9414 if( pCheck->pBt->autoVacuum ){
9415 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
9417 #endif
9418 checkRef(pCheck, iFreePage);
9420 N -= n;
9423 #ifndef SQLITE_OMIT_AUTOVACUUM
9424 else{
9425 /* If this database supports auto-vacuum and iPage is not the last
9426 ** page in this overflow list, check that the pointer-map entry for
9427 ** the following page matches iPage.
9429 if( pCheck->pBt->autoVacuum && N>0 ){
9430 i = get4byte(pOvflData);
9431 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
9434 #endif
9435 iPage = get4byte(pOvflData);
9436 sqlite3PagerUnref(pOvflPage);
9438 if( isFreeList && N<(iPage!=0) ){
9439 checkAppendMsg(pCheck, "free-page count in header is too small");
9443 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9446 ** An implementation of a min-heap.
9448 ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
9449 ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
9450 ** and aHeap[N*2+1].
9452 ** The heap property is this: Every node is less than or equal to both
9453 ** of its daughter nodes. A consequence of the heap property is that the
9454 ** root node aHeap[1] is always the minimum value currently in the heap.
9456 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
9457 ** the heap, preserving the heap property. The btreeHeapPull() routine
9458 ** removes the root element from the heap (the minimum value in the heap)
9459 ** and then moves other nodes around as necessary to preserve the heap
9460 ** property.
9462 ** This heap is used for cell overlap and coverage testing. Each u32
9463 ** entry represents the span of a cell or freeblock on a btree page.
9464 ** The upper 16 bits are the index of the first byte of a range and the
9465 ** lower 16 bits are the index of the last byte of that range.
9467 static void btreeHeapInsert(u32 *aHeap, u32 x){
9468 u32 j, i = ++aHeap[0];
9469 aHeap[i] = x;
9470 while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
9471 x = aHeap[j];
9472 aHeap[j] = aHeap[i];
9473 aHeap[i] = x;
9474 i = j;
9477 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
9478 u32 j, i, x;
9479 if( (x = aHeap[0])==0 ) return 0;
9480 *pOut = aHeap[1];
9481 aHeap[1] = aHeap[x];
9482 aHeap[x] = 0xffffffff;
9483 aHeap[0]--;
9484 i = 1;
9485 while( (j = i*2)<=aHeap[0] ){
9486 if( aHeap[j]>aHeap[j+1] ) j++;
9487 if( aHeap[i]<aHeap[j] ) break;
9488 x = aHeap[i];
9489 aHeap[i] = aHeap[j];
9490 aHeap[j] = x;
9491 i = j;
9493 return 1;
9496 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9498 ** Do various sanity checks on a single page of a tree. Return
9499 ** the tree depth. Root pages return 0. Parents of root pages
9500 ** return 1, and so forth.
9502 ** These checks are done:
9504 ** 1. Make sure that cells and freeblocks do not overlap
9505 ** but combine to completely cover the page.
9506 ** 2. Make sure integer cell keys are in order.
9507 ** 3. Check the integrity of overflow pages.
9508 ** 4. Recursively call checkTreePage on all children.
9509 ** 5. Verify that the depth of all children is the same.
9511 static int checkTreePage(
9512 IntegrityCk *pCheck, /* Context for the sanity check */
9513 int iPage, /* Page number of the page to check */
9514 i64 *piMinKey, /* Write minimum integer primary key here */
9515 i64 maxKey /* Error if integer primary key greater than this */
9517 MemPage *pPage = 0; /* The page being analyzed */
9518 int i; /* Loop counter */
9519 int rc; /* Result code from subroutine call */
9520 int depth = -1, d2; /* Depth of a subtree */
9521 int pgno; /* Page number */
9522 int nFrag; /* Number of fragmented bytes on the page */
9523 int hdr; /* Offset to the page header */
9524 int cellStart; /* Offset to the start of the cell pointer array */
9525 int nCell; /* Number of cells */
9526 int doCoverageCheck = 1; /* True if cell coverage checking should be done */
9527 int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
9528 ** False if IPK must be strictly less than maxKey */
9529 u8 *data; /* Page content */
9530 u8 *pCell; /* Cell content */
9531 u8 *pCellIdx; /* Next element of the cell pointer array */
9532 BtShared *pBt; /* The BtShared object that owns pPage */
9533 u32 pc; /* Address of a cell */
9534 u32 usableSize; /* Usable size of the page */
9535 u32 contentOffset; /* Offset to the start of the cell content area */
9536 u32 *heap = 0; /* Min-heap used for checking cell coverage */
9537 u32 x, prev = 0; /* Next and previous entry on the min-heap */
9538 const char *saved_zPfx = pCheck->zPfx;
9539 int saved_v1 = pCheck->v1;
9540 int saved_v2 = pCheck->v2;
9541 u8 savedIsInit = 0;
9543 /* Check that the page exists
9545 pBt = pCheck->pBt;
9546 usableSize = pBt->usableSize;
9547 if( iPage==0 ) return 0;
9548 if( checkRef(pCheck, iPage) ) return 0;
9549 pCheck->zPfx = "Page %d: ";
9550 pCheck->v1 = iPage;
9551 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
9552 checkAppendMsg(pCheck,
9553 "unable to get the page. error code=%d", rc);
9554 goto end_of_check;
9557 /* Clear MemPage.isInit to make sure the corruption detection code in
9558 ** btreeInitPage() is executed. */
9559 savedIsInit = pPage->isInit;
9560 pPage->isInit = 0;
9561 if( (rc = btreeInitPage(pPage))!=0 ){
9562 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
9563 checkAppendMsg(pCheck,
9564 "btreeInitPage() returns error code %d", rc);
9565 goto end_of_check;
9567 data = pPage->aData;
9568 hdr = pPage->hdrOffset;
9570 /* Set up for cell analysis */
9571 pCheck->zPfx = "On tree page %d cell %d: ";
9572 contentOffset = get2byteNotZero(&data[hdr+5]);
9573 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
9575 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
9576 ** number of cells on the page. */
9577 nCell = get2byte(&data[hdr+3]);
9578 assert( pPage->nCell==nCell );
9580 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
9581 ** immediately follows the b-tree page header. */
9582 cellStart = hdr + 12 - 4*pPage->leaf;
9583 assert( pPage->aCellIdx==&data[cellStart] );
9584 pCellIdx = &data[cellStart + 2*(nCell-1)];
9586 if( !pPage->leaf ){
9587 /* Analyze the right-child page of internal pages */
9588 pgno = get4byte(&data[hdr+8]);
9589 #ifndef SQLITE_OMIT_AUTOVACUUM
9590 if( pBt->autoVacuum ){
9591 pCheck->zPfx = "On page %d at right child: ";
9592 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
9594 #endif
9595 depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
9596 keyCanBeEqual = 0;
9597 }else{
9598 /* For leaf pages, the coverage check will occur in the same loop
9599 ** as the other cell checks, so initialize the heap. */
9600 heap = pCheck->heap;
9601 heap[0] = 0;
9604 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
9605 ** integer offsets to the cell contents. */
9606 for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
9607 CellInfo info;
9609 /* Check cell size */
9610 pCheck->v2 = i;
9611 assert( pCellIdx==&data[cellStart + i*2] );
9612 pc = get2byteAligned(pCellIdx);
9613 pCellIdx -= 2;
9614 if( pc<contentOffset || pc>usableSize-4 ){
9615 checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
9616 pc, contentOffset, usableSize-4);
9617 doCoverageCheck = 0;
9618 continue;
9620 pCell = &data[pc];
9621 pPage->xParseCell(pPage, pCell, &info);
9622 if( pc+info.nSize>usableSize ){
9623 checkAppendMsg(pCheck, "Extends off end of page");
9624 doCoverageCheck = 0;
9625 continue;
9628 /* Check for integer primary key out of range */
9629 if( pPage->intKey ){
9630 if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
9631 checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
9633 maxKey = info.nKey;
9634 keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
9637 /* Check the content overflow list */
9638 if( info.nPayload>info.nLocal ){
9639 int nPage; /* Number of pages on the overflow chain */
9640 Pgno pgnoOvfl; /* First page of the overflow chain */
9641 assert( pc + info.nSize - 4 <= usableSize );
9642 nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
9643 pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
9644 #ifndef SQLITE_OMIT_AUTOVACUUM
9645 if( pBt->autoVacuum ){
9646 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
9648 #endif
9649 checkList(pCheck, 0, pgnoOvfl, nPage);
9652 if( !pPage->leaf ){
9653 /* Check sanity of left child page for internal pages */
9654 pgno = get4byte(pCell);
9655 #ifndef SQLITE_OMIT_AUTOVACUUM
9656 if( pBt->autoVacuum ){
9657 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
9659 #endif
9660 d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
9661 keyCanBeEqual = 0;
9662 if( d2!=depth ){
9663 checkAppendMsg(pCheck, "Child page depth differs");
9664 depth = d2;
9666 }else{
9667 /* Populate the coverage-checking heap for leaf pages */
9668 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
9671 *piMinKey = maxKey;
9673 /* Check for complete coverage of the page
9675 pCheck->zPfx = 0;
9676 if( doCoverageCheck && pCheck->mxErr>0 ){
9677 /* For leaf pages, the min-heap has already been initialized and the
9678 ** cells have already been inserted. But for internal pages, that has
9679 ** not yet been done, so do it now */
9680 if( !pPage->leaf ){
9681 heap = pCheck->heap;
9682 heap[0] = 0;
9683 for(i=nCell-1; i>=0; i--){
9684 u32 size;
9685 pc = get2byteAligned(&data[cellStart+i*2]);
9686 size = pPage->xCellSize(pPage, &data[pc]);
9687 btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
9690 /* Add the freeblocks to the min-heap
9692 ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
9693 ** is the offset of the first freeblock, or zero if there are no
9694 ** freeblocks on the page.
9696 i = get2byte(&data[hdr+1]);
9697 while( i>0 ){
9698 int size, j;
9699 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */
9700 size = get2byte(&data[i+2]);
9701 assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */
9702 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
9703 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
9704 ** big-endian integer which is the offset in the b-tree page of the next
9705 ** freeblock in the chain, or zero if the freeblock is the last on the
9706 ** chain. */
9707 j = get2byte(&data[i]);
9708 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
9709 ** increasing offset. */
9710 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
9711 assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */
9712 i = j;
9714 /* Analyze the min-heap looking for overlap between cells and/or
9715 ** freeblocks, and counting the number of untracked bytes in nFrag.
9717 ** Each min-heap entry is of the form: (start_address<<16)|end_address.
9718 ** There is an implied first entry the covers the page header, the cell
9719 ** pointer index, and the gap between the cell pointer index and the start
9720 ** of cell content.
9722 ** The loop below pulls entries from the min-heap in order and compares
9723 ** the start_address against the previous end_address. If there is an
9724 ** overlap, that means bytes are used multiple times. If there is a gap,
9725 ** that gap is added to the fragmentation count.
9727 nFrag = 0;
9728 prev = contentOffset - 1; /* Implied first min-heap entry */
9729 while( btreeHeapPull(heap,&x) ){
9730 if( (prev&0xffff)>=(x>>16) ){
9731 checkAppendMsg(pCheck,
9732 "Multiple uses for byte %u of page %d", x>>16, iPage);
9733 break;
9734 }else{
9735 nFrag += (x>>16) - (prev&0xffff) - 1;
9736 prev = x;
9739 nFrag += usableSize - (prev&0xffff) - 1;
9740 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
9741 ** is stored in the fifth field of the b-tree page header.
9742 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
9743 ** number of fragmented free bytes within the cell content area.
9745 if( heap[0]==0 && nFrag!=data[hdr+7] ){
9746 checkAppendMsg(pCheck,
9747 "Fragmentation of %d bytes reported as %d on page %d",
9748 nFrag, data[hdr+7], iPage);
9752 end_of_check:
9753 if( !doCoverageCheck ) pPage->isInit = savedIsInit;
9754 releasePage(pPage);
9755 pCheck->zPfx = saved_zPfx;
9756 pCheck->v1 = saved_v1;
9757 pCheck->v2 = saved_v2;
9758 return depth+1;
9760 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9762 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9764 ** This routine does a complete check of the given BTree file. aRoot[] is
9765 ** an array of pages numbers were each page number is the root page of
9766 ** a table. nRoot is the number of entries in aRoot.
9768 ** A read-only or read-write transaction must be opened before calling
9769 ** this function.
9771 ** Write the number of error seen in *pnErr. Except for some memory
9772 ** allocation errors, an error message held in memory obtained from
9773 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
9774 ** returned. If a memory allocation error occurs, NULL is returned.
9776 char *sqlite3BtreeIntegrityCheck(
9777 Btree *p, /* The btree to be checked */
9778 int *aRoot, /* An array of root pages numbers for individual trees */
9779 int nRoot, /* Number of entries in aRoot[] */
9780 int mxErr, /* Stop reporting errors after this many */
9781 int *pnErr /* Write number of errors seen to this variable */
9783 Pgno i;
9784 IntegrityCk sCheck;
9785 BtShared *pBt = p->pBt;
9786 int savedDbFlags = pBt->db->flags;
9787 char zErr[100];
9788 VVA_ONLY( int nRef );
9790 sqlite3BtreeEnter(p);
9791 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
9792 VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
9793 assert( nRef>=0 );
9794 sCheck.pBt = pBt;
9795 sCheck.pPager = pBt->pPager;
9796 sCheck.nPage = btreePagecount(sCheck.pBt);
9797 sCheck.mxErr = mxErr;
9798 sCheck.nErr = 0;
9799 sCheck.mallocFailed = 0;
9800 sCheck.zPfx = 0;
9801 sCheck.v1 = 0;
9802 sCheck.v2 = 0;
9803 sCheck.aPgRef = 0;
9804 sCheck.heap = 0;
9805 sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
9806 sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
9807 if( sCheck.nPage==0 ){
9808 goto integrity_ck_cleanup;
9811 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
9812 if( !sCheck.aPgRef ){
9813 sCheck.mallocFailed = 1;
9814 goto integrity_ck_cleanup;
9816 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
9817 if( sCheck.heap==0 ){
9818 sCheck.mallocFailed = 1;
9819 goto integrity_ck_cleanup;
9822 i = PENDING_BYTE_PAGE(pBt);
9823 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
9825 /* Check the integrity of the freelist
9827 sCheck.zPfx = "Main freelist: ";
9828 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
9829 get4byte(&pBt->pPage1->aData[36]));
9830 sCheck.zPfx = 0;
9832 /* Check all the tables.
9834 testcase( pBt->db->flags & SQLITE_CellSizeCk );
9835 pBt->db->flags &= ~SQLITE_CellSizeCk;
9836 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
9837 i64 notUsed;
9838 if( aRoot[i]==0 ) continue;
9839 #ifndef SQLITE_OMIT_AUTOVACUUM
9840 if( pBt->autoVacuum && aRoot[i]>1 ){
9841 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
9843 #endif
9844 checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
9846 pBt->db->flags = savedDbFlags;
9848 /* Make sure every page in the file is referenced
9850 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
9851 #ifdef SQLITE_OMIT_AUTOVACUUM
9852 if( getPageReferenced(&sCheck, i)==0 ){
9853 checkAppendMsg(&sCheck, "Page %d is never used", i);
9855 #else
9856 /* If the database supports auto-vacuum, make sure no tables contain
9857 ** references to pointer-map pages.
9859 if( getPageReferenced(&sCheck, i)==0 &&
9860 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
9861 checkAppendMsg(&sCheck, "Page %d is never used", i);
9863 if( getPageReferenced(&sCheck, i)!=0 &&
9864 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
9865 checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
9867 #endif
9870 /* Clean up and report errors.
9872 integrity_ck_cleanup:
9873 sqlite3PageFree(sCheck.heap);
9874 sqlite3_free(sCheck.aPgRef);
9875 if( sCheck.mallocFailed ){
9876 sqlite3_str_reset(&sCheck.errMsg);
9877 sCheck.nErr++;
9879 *pnErr = sCheck.nErr;
9880 if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
9881 /* Make sure this analysis did not leave any unref() pages. */
9882 assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
9883 sqlite3BtreeLeave(p);
9884 return sqlite3StrAccumFinish(&sCheck.errMsg);
9886 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9889 ** Return the full pathname of the underlying database file. Return
9890 ** an empty string if the database is in-memory or a TEMP database.
9892 ** The pager filename is invariant as long as the pager is
9893 ** open so it is safe to access without the BtShared mutex.
9895 const char *sqlite3BtreeGetFilename(Btree *p){
9896 assert( p->pBt->pPager!=0 );
9897 return sqlite3PagerFilename(p->pBt->pPager, 1);
9901 ** Return the pathname of the journal file for this database. The return
9902 ** value of this routine is the same regardless of whether the journal file
9903 ** has been created or not.
9905 ** The pager journal filename is invariant as long as the pager is
9906 ** open so it is safe to access without the BtShared mutex.
9908 const char *sqlite3BtreeGetJournalname(Btree *p){
9909 assert( p->pBt->pPager!=0 );
9910 return sqlite3PagerJournalname(p->pBt->pPager);
9914 ** Return non-zero if a transaction is active.
9916 int sqlite3BtreeIsInTrans(Btree *p){
9917 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
9918 return (p && (p->inTrans==TRANS_WRITE));
9921 #ifndef SQLITE_OMIT_WAL
9923 ** Run a checkpoint on the Btree passed as the first argument.
9925 ** Return SQLITE_LOCKED if this or any other connection has an open
9926 ** transaction on the shared-cache the argument Btree is connected to.
9928 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
9930 int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
9931 int rc = SQLITE_OK;
9932 if( p ){
9933 BtShared *pBt = p->pBt;
9934 sqlite3BtreeEnter(p);
9935 if( pBt->inTransaction!=TRANS_NONE ){
9936 rc = SQLITE_LOCKED;
9937 }else{
9938 rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
9940 sqlite3BtreeLeave(p);
9942 return rc;
9944 #endif
9947 ** Return non-zero if a read (or write) transaction is active.
9949 int sqlite3BtreeIsInReadTrans(Btree *p){
9950 assert( p );
9951 assert( sqlite3_mutex_held(p->db->mutex) );
9952 return p->inTrans!=TRANS_NONE;
9955 int sqlite3BtreeIsInBackup(Btree *p){
9956 assert( p );
9957 assert( sqlite3_mutex_held(p->db->mutex) );
9958 return p->nBackup!=0;
9962 ** This function returns a pointer to a blob of memory associated with
9963 ** a single shared-btree. The memory is used by client code for its own
9964 ** purposes (for example, to store a high-level schema associated with
9965 ** the shared-btree). The btree layer manages reference counting issues.
9967 ** The first time this is called on a shared-btree, nBytes bytes of memory
9968 ** are allocated, zeroed, and returned to the caller. For each subsequent
9969 ** call the nBytes parameter is ignored and a pointer to the same blob
9970 ** of memory returned.
9972 ** If the nBytes parameter is 0 and the blob of memory has not yet been
9973 ** allocated, a null pointer is returned. If the blob has already been
9974 ** allocated, it is returned as normal.
9976 ** Just before the shared-btree is closed, the function passed as the
9977 ** xFree argument when the memory allocation was made is invoked on the
9978 ** blob of allocated memory. The xFree function should not call sqlite3_free()
9979 ** on the memory, the btree layer does that.
9981 void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
9982 BtShared *pBt = p->pBt;
9983 sqlite3BtreeEnter(p);
9984 if( !pBt->pSchema && nBytes ){
9985 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
9986 pBt->xFreeSchema = xFree;
9988 sqlite3BtreeLeave(p);
9989 return pBt->pSchema;
9993 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
9994 ** btree as the argument handle holds an exclusive lock on the
9995 ** sqlite_master table. Otherwise SQLITE_OK.
9997 int sqlite3BtreeSchemaLocked(Btree *p){
9998 int rc;
9999 assert( sqlite3_mutex_held(p->db->mutex) );
10000 sqlite3BtreeEnter(p);
10001 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
10002 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
10003 sqlite3BtreeLeave(p);
10004 return rc;
10008 #ifndef SQLITE_OMIT_SHARED_CACHE
10010 ** Obtain a lock on the table whose root page is iTab. The
10011 ** lock is a write lock if isWritelock is true or a read lock
10012 ** if it is false.
10014 int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
10015 int rc = SQLITE_OK;
10016 assert( p->inTrans!=TRANS_NONE );
10017 if( p->sharable ){
10018 u8 lockType = READ_LOCK + isWriteLock;
10019 assert( READ_LOCK+1==WRITE_LOCK );
10020 assert( isWriteLock==0 || isWriteLock==1 );
10022 sqlite3BtreeEnter(p);
10023 rc = querySharedCacheTableLock(p, iTab, lockType);
10024 if( rc==SQLITE_OK ){
10025 rc = setSharedCacheTableLock(p, iTab, lockType);
10027 sqlite3BtreeLeave(p);
10029 return rc;
10031 #endif
10033 #ifndef SQLITE_OMIT_INCRBLOB
10035 ** Argument pCsr must be a cursor opened for writing on an
10036 ** INTKEY table currently pointing at a valid table entry.
10037 ** This function modifies the data stored as part of that entry.
10039 ** Only the data content may only be modified, it is not possible to
10040 ** change the length of the data stored. If this function is called with
10041 ** parameters that attempt to write past the end of the existing data,
10042 ** no modifications are made and SQLITE_CORRUPT is returned.
10044 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
10045 int rc;
10046 assert( cursorOwnsBtShared(pCsr) );
10047 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
10048 assert( pCsr->curFlags & BTCF_Incrblob );
10050 rc = restoreCursorPosition(pCsr);
10051 if( rc!=SQLITE_OK ){
10052 return rc;
10054 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
10055 if( pCsr->eState!=CURSOR_VALID ){
10056 return SQLITE_ABORT;
10059 /* Save the positions of all other cursors open on this table. This is
10060 ** required in case any of them are holding references to an xFetch
10061 ** version of the b-tree page modified by the accessPayload call below.
10063 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
10064 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
10065 ** saveAllCursors can only return SQLITE_OK.
10067 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
10068 assert( rc==SQLITE_OK );
10070 /* Check some assumptions:
10071 ** (a) the cursor is open for writing,
10072 ** (b) there is a read/write transaction open,
10073 ** (c) the connection holds a write-lock on the table (if required),
10074 ** (d) there are no conflicting read-locks, and
10075 ** (e) the cursor points at a valid row of an intKey table.
10077 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
10078 return SQLITE_READONLY;
10080 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
10081 && pCsr->pBt->inTransaction==TRANS_WRITE );
10082 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
10083 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
10084 assert( pCsr->pPage->intKey );
10086 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
10090 ** Mark this cursor as an incremental blob cursor.
10092 void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
10093 pCur->curFlags |= BTCF_Incrblob;
10094 pCur->pBtree->hasIncrblobCur = 1;
10096 #endif
10099 ** Set both the "read version" (single byte at byte offset 18) and
10100 ** "write version" (single byte at byte offset 19) fields in the database
10101 ** header to iVersion.
10103 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
10104 BtShared *pBt = pBtree->pBt;
10105 int rc; /* Return code */
10107 assert( iVersion==1 || iVersion==2 );
10109 /* If setting the version fields to 1, do not automatically open the
10110 ** WAL connection, even if the version fields are currently set to 2.
10112 pBt->btsFlags &= ~BTS_NO_WAL;
10113 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
10115 rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
10116 if( rc==SQLITE_OK ){
10117 u8 *aData = pBt->pPage1->aData;
10118 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
10119 rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
10120 if( rc==SQLITE_OK ){
10121 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
10122 if( rc==SQLITE_OK ){
10123 aData[18] = (u8)iVersion;
10124 aData[19] = (u8)iVersion;
10130 pBt->btsFlags &= ~BTS_NO_WAL;
10131 return rc;
10135 ** Return true if the cursor has a hint specified. This routine is
10136 ** only used from within assert() statements
10138 int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
10139 return (pCsr->hints & mask)!=0;
10143 ** Return true if the given Btree is read-only.
10145 int sqlite3BtreeIsReadonly(Btree *p){
10146 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
10150 ** Return the size of the header added to each page by this module.
10152 int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
10154 #if !defined(SQLITE_OMIT_SHARED_CACHE)
10156 ** Return true if the Btree passed as the only argument is sharable.
10158 int sqlite3BtreeSharable(Btree *p){
10159 return p->sharable;
10163 ** Return the number of connections to the BtShared object accessed by
10164 ** the Btree handle passed as the only argument. For private caches
10165 ** this is always 1. For shared caches it may be 1 or greater.
10167 int sqlite3BtreeConnectionCount(Btree *p){
10168 testcase( p->sharable );
10169 return p->pBt->nRef;
10171 #endif