Merge sqlite-release(3.33.0) into prerelease-integration
[sqlcipher.git] / src / btree.c
blob919d3b87cd88622d3d7d0045588e2da85662e410
1 /*
2 ** 2004 April 6
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file implements an external (disk-based) database using BTrees.
13 ** See the header comment on "btreeInt.h" for additional information.
14 ** Including a description of file format and an overview of operation.
16 #include "btreeInt.h"
19 ** The header string that appears at the beginning of every
20 ** SQLite database.
22 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
25 ** Set this global variable to 1 to enable tracing using the TRACE
26 ** macro.
28 #if 0
29 int sqlite3BtreeTrace=1; /* True to enable tracing */
30 # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
31 #else
32 # define TRACE(X)
33 #endif
36 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
37 ** But if the value is zero, make it 65536.
39 ** This routine is used to extract the "offset to cell content area" value
40 ** from the header of a btree page. If the page size is 65536 and the page
41 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
42 ** This routine makes the necessary adjustment to 65536.
44 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
47 ** Values passed as the 5th argument to allocateBtreePage()
49 #define BTALLOC_ANY 0 /* Allocate any page */
50 #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
51 #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
54 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
55 ** defined, or 0 if it is. For example:
57 ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
59 #ifndef SQLITE_OMIT_AUTOVACUUM
60 #define IfNotOmitAV(expr) (expr)
61 #else
62 #define IfNotOmitAV(expr) 0
63 #endif
65 #ifndef SQLITE_OMIT_SHARED_CACHE
67 ** A list of BtShared objects that are eligible for participation
68 ** in shared cache. This variable has file scope during normal builds,
69 ** but the test harness needs to access it so we make it global for
70 ** test builds.
72 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MAIN.
74 #ifdef SQLITE_TEST
75 BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
76 #else
77 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
78 #endif
79 #endif /* SQLITE_OMIT_SHARED_CACHE */
81 #ifndef SQLITE_OMIT_SHARED_CACHE
83 ** Enable or disable the shared pager and schema features.
85 ** This routine has no effect on existing database connections.
86 ** The shared cache setting effects only future calls to
87 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
89 int sqlite3_enable_shared_cache(int enable){
90 sqlite3GlobalConfig.sharedCacheEnabled = enable;
91 return SQLITE_OK;
93 #endif
97 #ifdef SQLITE_OMIT_SHARED_CACHE
99 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
100 ** and clearAllSharedCacheTableLocks()
101 ** manipulate entries in the BtShared.pLock linked list used to store
102 ** shared-cache table level locks. If the library is compiled with the
103 ** shared-cache feature disabled, then there is only ever one user
104 ** of each BtShared structure and so this locking is not necessary.
105 ** So define the lock related functions as no-ops.
107 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
108 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
109 #define clearAllSharedCacheTableLocks(a)
110 #define downgradeAllSharedCacheTableLocks(a)
111 #define hasSharedCacheTableLock(a,b,c,d) 1
112 #define hasReadConflicts(a, b) 0
113 #endif
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 int bSeen = 0;
204 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
205 Index *pIdx = (Index *)sqliteHashData(p);
206 if( pIdx->tnum==(int)iRoot ){
207 if( bSeen ){
208 /* Two or more indexes share the same root page. There must
209 ** be imposter tables. So just return true. The assert is not
210 ** useful in that case. */
211 return 1;
213 iTab = pIdx->pTable->tnum;
214 bSeen = 1;
217 }else{
218 iTab = iRoot;
221 /* Search for the required lock. Either a write-lock on root-page iTab, a
222 ** write-lock on the schema table, or (if the client is reading) a
223 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
224 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
225 if( pLock->pBtree==pBtree
226 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
227 && pLock->eLock>=eLockType
229 return 1;
233 /* Failed to find the required lock. */
234 return 0;
236 #endif /* SQLITE_DEBUG */
238 #ifdef SQLITE_DEBUG
240 **** This function may be used as part of assert() statements only. ****
242 ** Return true if it would be illegal for pBtree to write into the
243 ** table or index rooted at iRoot because other shared connections are
244 ** simultaneously reading that same table or index.
246 ** It is illegal for pBtree to write if some other Btree object that
247 ** shares the same BtShared object is currently reading or writing
248 ** the iRoot table. Except, if the other Btree object has the
249 ** read-uncommitted flag set, then it is OK for the other object to
250 ** have a read cursor.
252 ** For example, before writing to any part of the table or index
253 ** rooted at page iRoot, one should call:
255 ** assert( !hasReadConflicts(pBtree, iRoot) );
257 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
258 BtCursor *p;
259 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
260 if( p->pgnoRoot==iRoot
261 && p->pBtree!=pBtree
262 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
264 return 1;
267 return 0;
269 #endif /* #ifdef SQLITE_DEBUG */
272 ** Query to see if Btree handle p may obtain a lock of type eLock
273 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
274 ** SQLITE_OK if the lock may be obtained (by calling
275 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
277 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
278 BtShared *pBt = p->pBt;
279 BtLock *pIter;
281 assert( sqlite3BtreeHoldsMutex(p) );
282 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
283 assert( p->db!=0 );
284 assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
286 /* If requesting a write-lock, then the Btree must have an open write
287 ** transaction on this file. And, obviously, for this to be so there
288 ** must be an open write transaction on the file itself.
290 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
291 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
293 /* This routine is a no-op if the shared-cache is not enabled */
294 if( !p->sharable ){
295 return SQLITE_OK;
298 /* If some other connection is holding an exclusive lock, the
299 ** requested lock may not be obtained.
301 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
302 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
303 return SQLITE_LOCKED_SHAREDCACHE;
306 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
307 /* The condition (pIter->eLock!=eLock) in the following if(...)
308 ** statement is a simplification of:
310 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
312 ** since we know that if eLock==WRITE_LOCK, then no other connection
313 ** may hold a WRITE_LOCK on any table in this file (since there can
314 ** only be a single writer).
316 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
317 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
318 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
319 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
320 if( eLock==WRITE_LOCK ){
321 assert( p==pBt->pWriter );
322 pBt->btsFlags |= BTS_PENDING;
324 return SQLITE_LOCKED_SHAREDCACHE;
327 return SQLITE_OK;
329 #endif /* !SQLITE_OMIT_SHARED_CACHE */
331 #ifndef SQLITE_OMIT_SHARED_CACHE
333 ** Add a lock on the table with root-page iTable to the shared-btree used
334 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
335 ** WRITE_LOCK.
337 ** This function assumes the following:
339 ** (a) The specified Btree object p is connected to a sharable
340 ** database (one with the BtShared.sharable flag set), and
342 ** (b) No other Btree objects hold a lock that conflicts
343 ** with the requested lock (i.e. querySharedCacheTableLock() has
344 ** already been called and returned SQLITE_OK).
346 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
347 ** is returned if a malloc attempt fails.
349 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
350 BtShared *pBt = p->pBt;
351 BtLock *pLock = 0;
352 BtLock *pIter;
354 assert( sqlite3BtreeHoldsMutex(p) );
355 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
356 assert( p->db!=0 );
358 /* A connection with the read-uncommitted flag set will never try to
359 ** obtain a read-lock using this function. The only read-lock obtained
360 ** by a connection in read-uncommitted mode is on the sqlite_schema
361 ** table, and that lock is obtained in BtreeBeginTrans(). */
362 assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
364 /* This function should only be called on a sharable b-tree after it
365 ** has been determined that no other b-tree holds a conflicting lock. */
366 assert( p->sharable );
367 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
369 /* First search the list for an existing lock on this table. */
370 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
371 if( pIter->iTable==iTable && pIter->pBtree==p ){
372 pLock = pIter;
373 break;
377 /* If the above search did not find a BtLock struct associating Btree p
378 ** with table iTable, allocate one and link it into the list.
380 if( !pLock ){
381 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
382 if( !pLock ){
383 return SQLITE_NOMEM_BKPT;
385 pLock->iTable = iTable;
386 pLock->pBtree = p;
387 pLock->pNext = pBt->pLock;
388 pBt->pLock = pLock;
391 /* Set the BtLock.eLock variable to the maximum of the current lock
392 ** and the requested lock. This means if a write-lock was already held
393 ** and a read-lock requested, we don't incorrectly downgrade the lock.
395 assert( WRITE_LOCK>READ_LOCK );
396 if( eLock>pLock->eLock ){
397 pLock->eLock = eLock;
400 return SQLITE_OK;
402 #endif /* !SQLITE_OMIT_SHARED_CACHE */
404 #ifndef SQLITE_OMIT_SHARED_CACHE
406 ** Release all the table locks (locks obtained via calls to
407 ** the setSharedCacheTableLock() procedure) held by Btree object p.
409 ** This function assumes that Btree p has an open read or write
410 ** transaction. If it does not, then the BTS_PENDING flag
411 ** may be incorrectly cleared.
413 static void clearAllSharedCacheTableLocks(Btree *p){
414 BtShared *pBt = p->pBt;
415 BtLock **ppIter = &pBt->pLock;
417 assert( sqlite3BtreeHoldsMutex(p) );
418 assert( p->sharable || 0==*ppIter );
419 assert( p->inTrans>0 );
421 while( *ppIter ){
422 BtLock *pLock = *ppIter;
423 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
424 assert( pLock->pBtree->inTrans>=pLock->eLock );
425 if( pLock->pBtree==p ){
426 *ppIter = pLock->pNext;
427 assert( pLock->iTable!=1 || pLock==&p->lock );
428 if( pLock->iTable!=1 ){
429 sqlite3_free(pLock);
431 }else{
432 ppIter = &pLock->pNext;
436 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
437 if( pBt->pWriter==p ){
438 pBt->pWriter = 0;
439 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
440 }else if( pBt->nTransaction==2 ){
441 /* This function is called when Btree p is concluding its
442 ** transaction. If there currently exists a writer, and p is not
443 ** that writer, then the number of locks held by connections other
444 ** than the writer must be about to drop to zero. In this case
445 ** set the BTS_PENDING flag to 0.
447 ** If there is not currently a writer, then BTS_PENDING must
448 ** be zero already. So this next line is harmless in that case.
450 pBt->btsFlags &= ~BTS_PENDING;
455 ** This function changes all write-locks held by Btree p into read-locks.
457 static void downgradeAllSharedCacheTableLocks(Btree *p){
458 BtShared *pBt = p->pBt;
459 if( pBt->pWriter==p ){
460 BtLock *pLock;
461 pBt->pWriter = 0;
462 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
463 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
464 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
465 pLock->eLock = READ_LOCK;
470 #endif /* SQLITE_OMIT_SHARED_CACHE */
472 static void releasePage(MemPage *pPage); /* Forward reference */
473 static void releasePageOne(MemPage *pPage); /* Forward reference */
474 static void releasePageNotNull(MemPage *pPage); /* Forward reference */
477 ***** This routine is used inside of assert() only ****
479 ** Verify that the cursor holds the mutex on its BtShared
481 #ifdef SQLITE_DEBUG
482 static int cursorHoldsMutex(BtCursor *p){
483 return sqlite3_mutex_held(p->pBt->mutex);
486 /* Verify that the cursor and the BtShared agree about what is the current
487 ** database connetion. This is important in shared-cache mode. If the database
488 ** connection pointers get out-of-sync, it is possible for routines like
489 ** btreeInitPage() to reference an stale connection pointer that references a
490 ** a connection that has already closed. This routine is used inside assert()
491 ** statements only and for the purpose of double-checking that the btree code
492 ** does keep the database connection pointers up-to-date.
494 static int cursorOwnsBtShared(BtCursor *p){
495 assert( cursorHoldsMutex(p) );
496 return (p->pBtree->db==p->pBt->db);
498 #endif
501 ** Invalidate the overflow cache of the cursor passed as the first argument.
502 ** on the shared btree structure pBt.
504 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
507 ** Invalidate the overflow page-list cache for all cursors opened
508 ** on the shared btree structure pBt.
510 static void invalidateAllOverflowCache(BtShared *pBt){
511 BtCursor *p;
512 assert( sqlite3_mutex_held(pBt->mutex) );
513 for(p=pBt->pCursor; p; p=p->pNext){
514 invalidateOverflowCache(p);
518 #ifndef SQLITE_OMIT_INCRBLOB
520 ** This function is called before modifying the contents of a table
521 ** to invalidate any incrblob cursors that are open on the
522 ** row or one of the rows being modified.
524 ** If argument isClearTable is true, then the entire contents of the
525 ** table is about to be deleted. In this case invalidate all incrblob
526 ** cursors open on any row within the table with root-page pgnoRoot.
528 ** Otherwise, if argument isClearTable is false, then the row with
529 ** rowid iRow is being replaced or deleted. In this case invalidate
530 ** only those incrblob cursors open on that specific row.
532 static void invalidateIncrblobCursors(
533 Btree *pBtree, /* The database file to check */
534 Pgno pgnoRoot, /* The table that might be changing */
535 i64 iRow, /* The rowid that might be changing */
536 int isClearTable /* True if all rows are being deleted */
538 BtCursor *p;
539 if( pBtree->hasIncrblobCur==0 ) return;
540 assert( sqlite3BtreeHoldsMutex(pBtree) );
541 pBtree->hasIncrblobCur = 0;
542 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
543 if( (p->curFlags & BTCF_Incrblob)!=0 ){
544 pBtree->hasIncrblobCur = 1;
545 if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
546 p->eState = CURSOR_INVALID;
552 #else
553 /* Stub function when INCRBLOB is omitted */
554 #define invalidateIncrblobCursors(w,x,y,z)
555 #endif /* SQLITE_OMIT_INCRBLOB */
558 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
559 ** when a page that previously contained data becomes a free-list leaf
560 ** page.
562 ** The BtShared.pHasContent bitvec exists to work around an obscure
563 ** bug caused by the interaction of two useful IO optimizations surrounding
564 ** free-list leaf pages:
566 ** 1) When all data is deleted from a page and the page becomes
567 ** a free-list leaf page, the page is not written to the database
568 ** (as free-list leaf pages contain no meaningful data). Sometimes
569 ** such a page is not even journalled (as it will not be modified,
570 ** why bother journalling it?).
572 ** 2) When a free-list leaf page is reused, its content is not read
573 ** from the database or written to the journal file (why should it
574 ** be, if it is not at all meaningful?).
576 ** By themselves, these optimizations work fine and provide a handy
577 ** performance boost to bulk delete or insert operations. However, if
578 ** a page is moved to the free-list and then reused within the same
579 ** transaction, a problem comes up. If the page is not journalled when
580 ** it is moved to the free-list and it is also not journalled when it
581 ** is extracted from the free-list and reused, then the original data
582 ** may be lost. In the event of a rollback, it may not be possible
583 ** to restore the database to its original configuration.
585 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
586 ** moved to become a free-list leaf page, the corresponding bit is
587 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
588 ** optimization 2 above is omitted if the corresponding bit is already
589 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
590 ** at the end of every transaction.
592 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
593 int rc = SQLITE_OK;
594 if( !pBt->pHasContent ){
595 assert( pgno<=pBt->nPage );
596 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
597 if( !pBt->pHasContent ){
598 rc = SQLITE_NOMEM_BKPT;
601 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
602 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
604 return rc;
608 ** Query the BtShared.pHasContent vector.
610 ** This function is called when a free-list leaf page is removed from the
611 ** free-list for reuse. It returns false if it is safe to retrieve the
612 ** page from the pager layer with the 'no-content' flag set. True otherwise.
614 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
615 Bitvec *p = pBt->pHasContent;
616 return p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTestNotNull(p, pgno));
620 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
621 ** invoked at the conclusion of each write-transaction.
623 static void btreeClearHasContent(BtShared *pBt){
624 sqlite3BitvecDestroy(pBt->pHasContent);
625 pBt->pHasContent = 0;
629 ** Release all of the apPage[] pages for a cursor.
631 static void btreeReleaseAllCursorPages(BtCursor *pCur){
632 int i;
633 if( pCur->iPage>=0 ){
634 for(i=0; i<pCur->iPage; i++){
635 releasePageNotNull(pCur->apPage[i]);
637 releasePageNotNull(pCur->pPage);
638 pCur->iPage = -1;
643 ** The cursor passed as the only argument must point to a valid entry
644 ** when this function is called (i.e. have eState==CURSOR_VALID). This
645 ** function saves the current cursor key in variables pCur->nKey and
646 ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
647 ** code otherwise.
649 ** If the cursor is open on an intkey table, then the integer key
650 ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
651 ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
652 ** set to point to a malloced buffer pCur->nKey bytes in size containing
653 ** the key.
655 static int saveCursorKey(BtCursor *pCur){
656 int rc = SQLITE_OK;
657 assert( CURSOR_VALID==pCur->eState );
658 assert( 0==pCur->pKey );
659 assert( cursorHoldsMutex(pCur) );
661 if( pCur->curIntKey ){
662 /* Only the rowid is required for a table btree */
663 pCur->nKey = sqlite3BtreeIntegerKey(pCur);
664 }else{
665 /* For an index btree, save the complete key content. It is possible
666 ** that the current key is corrupt. In that case, it is possible that
667 ** the sqlite3VdbeRecordUnpack() function may overread the buffer by
668 ** up to the size of 1 varint plus 1 8-byte value when the cursor
669 ** position is restored. Hence the 17 bytes of padding allocated
670 ** below. */
671 void *pKey;
672 pCur->nKey = sqlite3BtreePayloadSize(pCur);
673 pKey = sqlite3Malloc( pCur->nKey + 9 + 8 );
674 if( pKey ){
675 rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
676 if( rc==SQLITE_OK ){
677 memset(((u8*)pKey)+pCur->nKey, 0, 9+8);
678 pCur->pKey = pKey;
679 }else{
680 sqlite3_free(pKey);
682 }else{
683 rc = SQLITE_NOMEM_BKPT;
686 assert( !pCur->curIntKey || !pCur->pKey );
687 return rc;
691 ** Save the current cursor position in the variables BtCursor.nKey
692 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
694 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
695 ** prior to calling this routine.
697 static int saveCursorPosition(BtCursor *pCur){
698 int rc;
700 assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
701 assert( 0==pCur->pKey );
702 assert( cursorHoldsMutex(pCur) );
704 if( pCur->curFlags & BTCF_Pinned ){
705 return SQLITE_CONSTRAINT_PINNED;
707 if( pCur->eState==CURSOR_SKIPNEXT ){
708 pCur->eState = CURSOR_VALID;
709 }else{
710 pCur->skipNext = 0;
713 rc = saveCursorKey(pCur);
714 if( rc==SQLITE_OK ){
715 btreeReleaseAllCursorPages(pCur);
716 pCur->eState = CURSOR_REQUIRESEEK;
719 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
720 return rc;
723 /* Forward reference */
724 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
727 ** Save the positions of all cursors (except pExcept) that are open on
728 ** the table with root-page iRoot. "Saving the cursor position" means that
729 ** the location in the btree is remembered in such a way that it can be
730 ** moved back to the same spot after the btree has been modified. This
731 ** routine is called just before cursor pExcept is used to modify the
732 ** table, for example in BtreeDelete() or BtreeInsert().
734 ** If there are two or more cursors on the same btree, then all such
735 ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
736 ** routine enforces that rule. This routine only needs to be called in
737 ** the uncommon case when pExpect has the BTCF_Multiple flag set.
739 ** If pExpect!=NULL and if no other cursors are found on the same root-page,
740 ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
741 ** pointless call to this routine.
743 ** Implementation note: This routine merely checks to see if any cursors
744 ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
745 ** event that cursors are in need to being saved.
747 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
748 BtCursor *p;
749 assert( sqlite3_mutex_held(pBt->mutex) );
750 assert( pExcept==0 || pExcept->pBt==pBt );
751 for(p=pBt->pCursor; p; p=p->pNext){
752 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
754 if( p ) return saveCursorsOnList(p, iRoot, pExcept);
755 if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
756 return SQLITE_OK;
759 /* This helper routine to saveAllCursors does the actual work of saving
760 ** the cursors if and when a cursor is found that actually requires saving.
761 ** The common case is that no cursors need to be saved, so this routine is
762 ** broken out from its caller to avoid unnecessary stack pointer movement.
764 static int SQLITE_NOINLINE saveCursorsOnList(
765 BtCursor *p, /* The first cursor that needs saving */
766 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
767 BtCursor *pExcept /* Do not save this cursor */
770 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
771 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
772 int rc = saveCursorPosition(p);
773 if( SQLITE_OK!=rc ){
774 return rc;
776 }else{
777 testcase( p->iPage>=0 );
778 btreeReleaseAllCursorPages(p);
781 p = p->pNext;
782 }while( p );
783 return SQLITE_OK;
787 ** Clear the current cursor position.
789 void sqlite3BtreeClearCursor(BtCursor *pCur){
790 assert( cursorHoldsMutex(pCur) );
791 sqlite3_free(pCur->pKey);
792 pCur->pKey = 0;
793 pCur->eState = CURSOR_INVALID;
797 ** In this version of BtreeMoveto, pKey is a packed index record
798 ** such as is generated by the OP_MakeRecord opcode. Unpack the
799 ** record and then call BtreeMovetoUnpacked() to do the work.
801 static int btreeMoveto(
802 BtCursor *pCur, /* Cursor open on the btree to be searched */
803 const void *pKey, /* Packed key if the btree is an index */
804 i64 nKey, /* Integer key for tables. Size of pKey for indices */
805 int bias, /* Bias search to the high end */
806 int *pRes /* Write search results here */
808 int rc; /* Status code */
809 UnpackedRecord *pIdxKey; /* Unpacked index key */
811 if( pKey ){
812 KeyInfo *pKeyInfo = pCur->pKeyInfo;
813 assert( nKey==(i64)(int)nKey );
814 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
815 if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
816 sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey);
817 if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){
818 rc = SQLITE_CORRUPT_BKPT;
819 goto moveto_done;
821 }else{
822 pIdxKey = 0;
824 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
825 moveto_done:
826 if( pIdxKey ){
827 sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
829 return rc;
833 ** Restore the cursor to the position it was in (or as close to as possible)
834 ** when saveCursorPosition() was called. Note that this call deletes the
835 ** saved position info stored by saveCursorPosition(), so there can be
836 ** at most one effective restoreCursorPosition() call after each
837 ** saveCursorPosition().
839 static int btreeRestoreCursorPosition(BtCursor *pCur){
840 int rc;
841 int skipNext = 0;
842 assert( cursorOwnsBtShared(pCur) );
843 assert( pCur->eState>=CURSOR_REQUIRESEEK );
844 if( pCur->eState==CURSOR_FAULT ){
845 return pCur->skipNext;
847 pCur->eState = CURSOR_INVALID;
848 if( sqlite3FaultSim(410) ){
849 rc = SQLITE_IOERR;
850 }else{
851 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
853 if( rc==SQLITE_OK ){
854 sqlite3_free(pCur->pKey);
855 pCur->pKey = 0;
856 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
857 if( skipNext ) pCur->skipNext = skipNext;
858 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
859 pCur->eState = CURSOR_SKIPNEXT;
862 return rc;
865 #define restoreCursorPosition(p) \
866 (p->eState>=CURSOR_REQUIRESEEK ? \
867 btreeRestoreCursorPosition(p) : \
868 SQLITE_OK)
871 ** Determine whether or not a cursor has moved from the position where
872 ** it was last placed, or has been invalidated for any other reason.
873 ** Cursors can move when the row they are pointing at is deleted out
874 ** from under them, for example. Cursor might also move if a btree
875 ** is rebalanced.
877 ** Calling this routine with a NULL cursor pointer returns false.
879 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
880 ** back to where it ought to be if this routine returns true.
882 int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
883 assert( EIGHT_BYTE_ALIGNMENT(pCur)
884 || pCur==sqlite3BtreeFakeValidCursor() );
885 assert( offsetof(BtCursor, eState)==0 );
886 assert( sizeof(pCur->eState)==1 );
887 return CURSOR_VALID != *(u8*)pCur;
891 ** Return a pointer to a fake BtCursor object that will always answer
892 ** false to the sqlite3BtreeCursorHasMoved() routine above. The fake
893 ** cursor returned must not be used with any other Btree interface.
895 BtCursor *sqlite3BtreeFakeValidCursor(void){
896 static u8 fakeCursor = CURSOR_VALID;
897 assert( offsetof(BtCursor, eState)==0 );
898 return (BtCursor*)&fakeCursor;
902 ** This routine restores a cursor back to its original position after it
903 ** has been moved by some outside activity (such as a btree rebalance or
904 ** a row having been deleted out from under the cursor).
906 ** On success, the *pDifferentRow parameter is false if the cursor is left
907 ** pointing at exactly the same row. *pDifferntRow is the row the cursor
908 ** was pointing to has been deleted, forcing the cursor to point to some
909 ** nearby row.
911 ** This routine should only be called for a cursor that just returned
912 ** TRUE from sqlite3BtreeCursorHasMoved().
914 int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
915 int rc;
917 assert( pCur!=0 );
918 assert( pCur->eState!=CURSOR_VALID );
919 rc = restoreCursorPosition(pCur);
920 if( rc ){
921 *pDifferentRow = 1;
922 return rc;
924 if( pCur->eState!=CURSOR_VALID ){
925 *pDifferentRow = 1;
926 }else{
927 *pDifferentRow = 0;
929 return SQLITE_OK;
932 #ifdef SQLITE_ENABLE_CURSOR_HINTS
934 ** Provide hints to the cursor. The particular hint given (and the type
935 ** and number of the varargs parameters) is determined by the eHintType
936 ** parameter. See the definitions of the BTREE_HINT_* macros for details.
938 void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
939 /* Used only by system that substitute their own storage engine */
941 #endif
944 ** Provide flag hints to the cursor.
946 void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
947 assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
948 pCur->hints = x;
952 #ifndef SQLITE_OMIT_AUTOVACUUM
954 ** Given a page number of a regular database page, return the page
955 ** number for the pointer-map page that contains the entry for the
956 ** input page number.
958 ** Return 0 (not a valid page) for pgno==1 since there is
959 ** no pointer map associated with page 1. The integrity_check logic
960 ** requires that ptrmapPageno(*,1)!=1.
962 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
963 int nPagesPerMapPage;
964 Pgno iPtrMap, ret;
965 assert( sqlite3_mutex_held(pBt->mutex) );
966 if( pgno<2 ) return 0;
967 nPagesPerMapPage = (pBt->usableSize/5)+1;
968 iPtrMap = (pgno-2)/nPagesPerMapPage;
969 ret = (iPtrMap*nPagesPerMapPage) + 2;
970 if( ret==PENDING_BYTE_PAGE(pBt) ){
971 ret++;
973 return ret;
977 ** Write an entry into the pointer map.
979 ** This routine updates the pointer map entry for page number 'key'
980 ** so that it maps to type 'eType' and parent page number 'pgno'.
982 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
983 ** a no-op. If an error occurs, the appropriate error code is written
984 ** into *pRC.
986 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
987 DbPage *pDbPage; /* The pointer map page */
988 u8 *pPtrmap; /* The pointer map data */
989 Pgno iPtrmap; /* The pointer map page number */
990 int offset; /* Offset in pointer map page */
991 int rc; /* Return code from subfunctions */
993 if( *pRC ) return;
995 assert( sqlite3_mutex_held(pBt->mutex) );
996 /* The super-journal page number must never be used as a pointer map page */
997 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
999 assert( pBt->autoVacuum );
1000 if( key==0 ){
1001 *pRC = SQLITE_CORRUPT_BKPT;
1002 return;
1004 iPtrmap = PTRMAP_PAGENO(pBt, key);
1005 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
1006 if( rc!=SQLITE_OK ){
1007 *pRC = rc;
1008 return;
1010 if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){
1011 /* The first byte of the extra data is the MemPage.isInit byte.
1012 ** If that byte is set, it means this page is also being used
1013 ** as a btree page. */
1014 *pRC = SQLITE_CORRUPT_BKPT;
1015 goto ptrmap_exit;
1017 offset = PTRMAP_PTROFFSET(iPtrmap, key);
1018 if( offset<0 ){
1019 *pRC = SQLITE_CORRUPT_BKPT;
1020 goto ptrmap_exit;
1022 assert( offset <= (int)pBt->usableSize-5 );
1023 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1025 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
1026 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
1027 *pRC= rc = sqlite3PagerWrite(pDbPage);
1028 if( rc==SQLITE_OK ){
1029 pPtrmap[offset] = eType;
1030 put4byte(&pPtrmap[offset+1], parent);
1034 ptrmap_exit:
1035 sqlite3PagerUnref(pDbPage);
1039 ** Read an entry from the pointer map.
1041 ** This routine retrieves the pointer map entry for page 'key', writing
1042 ** the type and parent page number to *pEType and *pPgno respectively.
1043 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
1045 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
1046 DbPage *pDbPage; /* The pointer map page */
1047 int iPtrmap; /* Pointer map page index */
1048 u8 *pPtrmap; /* Pointer map page data */
1049 int offset; /* Offset of entry in pointer map */
1050 int rc;
1052 assert( sqlite3_mutex_held(pBt->mutex) );
1054 iPtrmap = PTRMAP_PAGENO(pBt, key);
1055 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
1056 if( rc!=0 ){
1057 return rc;
1059 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1061 offset = PTRMAP_PTROFFSET(iPtrmap, key);
1062 if( offset<0 ){
1063 sqlite3PagerUnref(pDbPage);
1064 return SQLITE_CORRUPT_BKPT;
1066 assert( offset <= (int)pBt->usableSize-5 );
1067 assert( pEType!=0 );
1068 *pEType = pPtrmap[offset];
1069 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
1071 sqlite3PagerUnref(pDbPage);
1072 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
1073 return SQLITE_OK;
1076 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
1077 #define ptrmapPut(w,x,y,z,rc)
1078 #define ptrmapGet(w,x,y,z) SQLITE_OK
1079 #define ptrmapPutOvflPtr(x, y, z, rc)
1080 #endif
1083 ** Given a btree page and a cell index (0 means the first cell on
1084 ** the page, 1 means the second cell, and so forth) return a pointer
1085 ** to the cell content.
1087 ** findCellPastPtr() does the same except it skips past the initial
1088 ** 4-byte child pointer found on interior pages, if there is one.
1090 ** This routine works only for pages that do not contain overflow cells.
1092 #define findCell(P,I) \
1093 ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1094 #define findCellPastPtr(P,I) \
1095 ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1099 ** This is common tail processing for btreeParseCellPtr() and
1100 ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
1101 ** on a single B-tree page. Make necessary adjustments to the CellInfo
1102 ** structure.
1104 static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
1105 MemPage *pPage, /* Page containing the cell */
1106 u8 *pCell, /* Pointer to the cell text. */
1107 CellInfo *pInfo /* Fill in this structure */
1109 /* If the payload will not fit completely on the local page, we have
1110 ** to decide how much to store locally and how much to spill onto
1111 ** overflow pages. The strategy is to minimize the amount of unused
1112 ** space on overflow pages while keeping the amount of local storage
1113 ** in between minLocal and maxLocal.
1115 ** Warning: changing the way overflow payload is distributed in any
1116 ** way will result in an incompatible file format.
1118 int minLocal; /* Minimum amount of payload held locally */
1119 int maxLocal; /* Maximum amount of payload held locally */
1120 int surplus; /* Overflow payload available for local storage */
1122 minLocal = pPage->minLocal;
1123 maxLocal = pPage->maxLocal;
1124 surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
1125 testcase( surplus==maxLocal );
1126 testcase( surplus==maxLocal+1 );
1127 if( surplus <= maxLocal ){
1128 pInfo->nLocal = (u16)surplus;
1129 }else{
1130 pInfo->nLocal = (u16)minLocal;
1132 pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
1136 ** The following routines are implementations of the MemPage.xParseCell()
1137 ** method.
1139 ** Parse a cell content block and fill in the CellInfo structure.
1141 ** btreeParseCellPtr() => table btree leaf nodes
1142 ** btreeParseCellNoPayload() => table btree internal nodes
1143 ** btreeParseCellPtrIndex() => index btree nodes
1145 ** There is also a wrapper function btreeParseCell() that works for
1146 ** all MemPage types and that references the cell by index rather than
1147 ** by pointer.
1149 static void btreeParseCellPtrNoPayload(
1150 MemPage *pPage, /* Page containing the cell */
1151 u8 *pCell, /* Pointer to the cell text. */
1152 CellInfo *pInfo /* Fill in this structure */
1154 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1155 assert( pPage->leaf==0 );
1156 assert( pPage->childPtrSize==4 );
1157 #ifndef SQLITE_DEBUG
1158 UNUSED_PARAMETER(pPage);
1159 #endif
1160 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
1161 pInfo->nPayload = 0;
1162 pInfo->nLocal = 0;
1163 pInfo->pPayload = 0;
1164 return;
1166 static void btreeParseCellPtr(
1167 MemPage *pPage, /* Page containing the cell */
1168 u8 *pCell, /* Pointer to the cell text. */
1169 CellInfo *pInfo /* Fill in this structure */
1171 u8 *pIter; /* For scanning through pCell */
1172 u32 nPayload; /* Number of bytes of cell payload */
1173 u64 iKey; /* Extracted Key value */
1175 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1176 assert( pPage->leaf==0 || pPage->leaf==1 );
1177 assert( pPage->intKeyLeaf );
1178 assert( pPage->childPtrSize==0 );
1179 pIter = pCell;
1181 /* The next block of code is equivalent to:
1183 ** pIter += getVarint32(pIter, nPayload);
1185 ** The code is inlined to avoid a function call.
1187 nPayload = *pIter;
1188 if( nPayload>=0x80 ){
1189 u8 *pEnd = &pIter[8];
1190 nPayload &= 0x7f;
1192 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1193 }while( (*pIter)>=0x80 && pIter<pEnd );
1195 pIter++;
1197 /* The next block of code is equivalent to:
1199 ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
1201 ** The code is inlined to avoid a function call.
1203 iKey = *pIter;
1204 if( iKey>=0x80 ){
1205 u8 *pEnd = &pIter[7];
1206 iKey &= 0x7f;
1207 while(1){
1208 iKey = (iKey<<7) | (*++pIter & 0x7f);
1209 if( (*pIter)<0x80 ) break;
1210 if( pIter>=pEnd ){
1211 iKey = (iKey<<8) | *++pIter;
1212 break;
1216 pIter++;
1218 pInfo->nKey = *(i64*)&iKey;
1219 pInfo->nPayload = nPayload;
1220 pInfo->pPayload = pIter;
1221 testcase( nPayload==pPage->maxLocal );
1222 testcase( nPayload==pPage->maxLocal+1 );
1223 if( nPayload<=pPage->maxLocal ){
1224 /* This is the (easy) common case where the entire payload fits
1225 ** on the local page. No overflow is required.
1227 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1228 if( pInfo->nSize<4 ) pInfo->nSize = 4;
1229 pInfo->nLocal = (u16)nPayload;
1230 }else{
1231 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1234 static void btreeParseCellPtrIndex(
1235 MemPage *pPage, /* Page containing the cell */
1236 u8 *pCell, /* Pointer to the cell text. */
1237 CellInfo *pInfo /* Fill in this structure */
1239 u8 *pIter; /* For scanning through pCell */
1240 u32 nPayload; /* Number of bytes of cell payload */
1242 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1243 assert( pPage->leaf==0 || pPage->leaf==1 );
1244 assert( pPage->intKeyLeaf==0 );
1245 pIter = pCell + pPage->childPtrSize;
1246 nPayload = *pIter;
1247 if( nPayload>=0x80 ){
1248 u8 *pEnd = &pIter[8];
1249 nPayload &= 0x7f;
1251 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1252 }while( *(pIter)>=0x80 && pIter<pEnd );
1254 pIter++;
1255 pInfo->nKey = nPayload;
1256 pInfo->nPayload = nPayload;
1257 pInfo->pPayload = pIter;
1258 testcase( nPayload==pPage->maxLocal );
1259 testcase( nPayload==pPage->maxLocal+1 );
1260 if( nPayload<=pPage->maxLocal ){
1261 /* This is the (easy) common case where the entire payload fits
1262 ** on the local page. No overflow is required.
1264 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1265 if( pInfo->nSize<4 ) pInfo->nSize = 4;
1266 pInfo->nLocal = (u16)nPayload;
1267 }else{
1268 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1271 static void btreeParseCell(
1272 MemPage *pPage, /* Page containing the cell */
1273 int iCell, /* The cell index. First cell is 0 */
1274 CellInfo *pInfo /* Fill in this structure */
1276 pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
1280 ** The following routines are implementations of the MemPage.xCellSize
1281 ** method.
1283 ** Compute the total number of bytes that a Cell needs in the cell
1284 ** data area of the btree-page. The return number includes the cell
1285 ** data header and the local payload, but not any overflow page or
1286 ** the space used by the cell pointer.
1288 ** cellSizePtrNoPayload() => table internal nodes
1289 ** cellSizePtr() => all index nodes & table leaf nodes
1291 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
1292 u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
1293 u8 *pEnd; /* End mark for a varint */
1294 u32 nSize; /* Size value to return */
1296 #ifdef SQLITE_DEBUG
1297 /* The value returned by this function should always be the same as
1298 ** the (CellInfo.nSize) value found by doing a full parse of the
1299 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1300 ** this function verifies that this invariant is not violated. */
1301 CellInfo debuginfo;
1302 pPage->xParseCell(pPage, pCell, &debuginfo);
1303 #endif
1305 nSize = *pIter;
1306 if( nSize>=0x80 ){
1307 pEnd = &pIter[8];
1308 nSize &= 0x7f;
1310 nSize = (nSize<<7) | (*++pIter & 0x7f);
1311 }while( *(pIter)>=0x80 && pIter<pEnd );
1313 pIter++;
1314 if( pPage->intKey ){
1315 /* pIter now points at the 64-bit integer key value, a variable length
1316 ** integer. The following block moves pIter to point at the first byte
1317 ** past the end of the key value. */
1318 pEnd = &pIter[9];
1319 while( (*pIter++)&0x80 && pIter<pEnd );
1321 testcase( nSize==pPage->maxLocal );
1322 testcase( nSize==pPage->maxLocal+1 );
1323 if( nSize<=pPage->maxLocal ){
1324 nSize += (u32)(pIter - pCell);
1325 if( nSize<4 ) nSize = 4;
1326 }else{
1327 int minLocal = pPage->minLocal;
1328 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1329 testcase( nSize==pPage->maxLocal );
1330 testcase( nSize==pPage->maxLocal+1 );
1331 if( nSize>pPage->maxLocal ){
1332 nSize = minLocal;
1334 nSize += 4 + (u16)(pIter - pCell);
1336 assert( nSize==debuginfo.nSize || CORRUPT_DB );
1337 return (u16)nSize;
1339 static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
1340 u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
1341 u8 *pEnd; /* End mark for a varint */
1343 #ifdef SQLITE_DEBUG
1344 /* The value returned by this function should always be the same as
1345 ** the (CellInfo.nSize) value found by doing a full parse of the
1346 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1347 ** this function verifies that this invariant is not violated. */
1348 CellInfo debuginfo;
1349 pPage->xParseCell(pPage, pCell, &debuginfo);
1350 #else
1351 UNUSED_PARAMETER(pPage);
1352 #endif
1354 assert( pPage->childPtrSize==4 );
1355 pEnd = pIter + 9;
1356 while( (*pIter++)&0x80 && pIter<pEnd );
1357 assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
1358 return (u16)(pIter - pCell);
1362 #ifdef SQLITE_DEBUG
1363 /* This variation on cellSizePtr() is used inside of assert() statements
1364 ** only. */
1365 static u16 cellSize(MemPage *pPage, int iCell){
1366 return pPage->xCellSize(pPage, findCell(pPage, iCell));
1368 #endif
1370 #ifndef SQLITE_OMIT_AUTOVACUUM
1372 ** The cell pCell is currently part of page pSrc but will ultimately be part
1373 ** of pPage. (pSrc and pPager are often the same.) If pCell contains a
1374 ** pointer to an overflow page, insert an entry into the pointer-map for
1375 ** the overflow page that will be valid after pCell has been moved to pPage.
1377 static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){
1378 CellInfo info;
1379 if( *pRC ) return;
1380 assert( pCell!=0 );
1381 pPage->xParseCell(pPage, pCell, &info);
1382 if( info.nLocal<info.nPayload ){
1383 Pgno ovfl;
1384 if( SQLITE_WITHIN(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){
1385 testcase( pSrc!=pPage );
1386 *pRC = SQLITE_CORRUPT_BKPT;
1387 return;
1389 ovfl = get4byte(&pCell[info.nSize-4]);
1390 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
1393 #endif
1397 ** Defragment the page given. This routine reorganizes cells within the
1398 ** page so that there are no free-blocks on the free-block list.
1400 ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
1401 ** present in the page after this routine returns.
1403 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
1404 ** b-tree page so that there are no freeblocks or fragment bytes, all
1405 ** unused bytes are contained in the unallocated space region, and all
1406 ** cells are packed tightly at the end of the page.
1408 static int defragmentPage(MemPage *pPage, int nMaxFrag){
1409 int i; /* Loop counter */
1410 int pc; /* Address of the i-th cell */
1411 int hdr; /* Offset to the page header */
1412 int size; /* Size of a cell */
1413 int usableSize; /* Number of usable bytes on a page */
1414 int cellOffset; /* Offset to the cell pointer array */
1415 int cbrk; /* Offset to the cell content area */
1416 int nCell; /* Number of cells on the page */
1417 unsigned char *data; /* The page data */
1418 unsigned char *temp; /* Temp area for cell content */
1419 unsigned char *src; /* Source of content */
1420 int iCellFirst; /* First allowable cell index */
1421 int iCellLast; /* Last possible cell index */
1423 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1424 assert( pPage->pBt!=0 );
1425 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
1426 assert( pPage->nOverflow==0 );
1427 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1428 temp = 0;
1429 src = data = pPage->aData;
1430 hdr = pPage->hdrOffset;
1431 cellOffset = pPage->cellOffset;
1432 nCell = pPage->nCell;
1433 assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB );
1434 iCellFirst = cellOffset + 2*nCell;
1435 usableSize = pPage->pBt->usableSize;
1437 /* This block handles pages with two or fewer free blocks and nMaxFrag
1438 ** or fewer fragmented bytes. In this case it is faster to move the
1439 ** two (or one) blocks of cells using memmove() and add the required
1440 ** offsets to each pointer in the cell-pointer array than it is to
1441 ** reconstruct the entire page. */
1442 if( (int)data[hdr+7]<=nMaxFrag ){
1443 int iFree = get2byte(&data[hdr+1]);
1444 if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1445 if( iFree ){
1446 int iFree2 = get2byte(&data[iFree]);
1447 if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1448 if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
1449 u8 *pEnd = &data[cellOffset + nCell*2];
1450 u8 *pAddr;
1451 int sz2 = 0;
1452 int sz = get2byte(&data[iFree+2]);
1453 int top = get2byte(&data[hdr+5]);
1454 if( top>=iFree ){
1455 return SQLITE_CORRUPT_PAGE(pPage);
1457 if( iFree2 ){
1458 if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage);
1459 sz2 = get2byte(&data[iFree2+2]);
1460 if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage);
1461 memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
1462 sz += sz2;
1463 }else if( NEVER(iFree+sz>usableSize) ){
1464 return SQLITE_CORRUPT_PAGE(pPage);
1467 cbrk = top+sz;
1468 assert( cbrk+(iFree-top) <= usableSize );
1469 memmove(&data[cbrk], &data[top], iFree-top);
1470 for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
1471 pc = get2byte(pAddr);
1472 if( pc<iFree ){ put2byte(pAddr, pc+sz); }
1473 else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
1475 goto defragment_out;
1480 cbrk = usableSize;
1481 iCellLast = usableSize - 4;
1482 for(i=0; i<nCell; i++){
1483 u8 *pAddr; /* The i-th cell pointer */
1484 pAddr = &data[cellOffset + i*2];
1485 pc = get2byte(pAddr);
1486 testcase( pc==iCellFirst );
1487 testcase( pc==iCellLast );
1488 /* These conditions have already been verified in btreeInitPage()
1489 ** if PRAGMA cell_size_check=ON.
1491 if( pc<iCellFirst || pc>iCellLast ){
1492 return SQLITE_CORRUPT_PAGE(pPage);
1494 assert( pc>=iCellFirst && pc<=iCellLast );
1495 size = pPage->xCellSize(pPage, &src[pc]);
1496 cbrk -= size;
1497 if( cbrk<iCellFirst || pc+size>usableSize ){
1498 return SQLITE_CORRUPT_PAGE(pPage);
1500 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
1501 testcase( cbrk+size==usableSize );
1502 testcase( pc+size==usableSize );
1503 put2byte(pAddr, cbrk);
1504 if( temp==0 ){
1505 int x;
1506 if( cbrk==pc ) continue;
1507 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
1508 x = get2byte(&data[hdr+5]);
1509 memcpy(&temp[x], &data[x], (cbrk+size) - x);
1510 src = temp;
1512 memcpy(&data[cbrk], &src[pc], size);
1514 data[hdr+7] = 0;
1516 defragment_out:
1517 assert( pPage->nFree>=0 );
1518 if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
1519 return SQLITE_CORRUPT_PAGE(pPage);
1521 assert( cbrk>=iCellFirst );
1522 put2byte(&data[hdr+5], cbrk);
1523 data[hdr+1] = 0;
1524 data[hdr+2] = 0;
1525 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
1526 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1527 return SQLITE_OK;
1531 ** Search the free-list on page pPg for space to store a cell nByte bytes in
1532 ** size. If one can be found, return a pointer to the space and remove it
1533 ** from the free-list.
1535 ** If no suitable space can be found on the free-list, return NULL.
1537 ** This function may detect corruption within pPg. If corruption is
1538 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
1540 ** Slots on the free list that are between 1 and 3 bytes larger than nByte
1541 ** will be ignored if adding the extra space to the fragmentation count
1542 ** causes the fragmentation count to exceed 60.
1544 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
1545 const int hdr = pPg->hdrOffset; /* Offset to page header */
1546 u8 * const aData = pPg->aData; /* Page data */
1547 int iAddr = hdr + 1; /* Address of ptr to pc */
1548 int pc = get2byte(&aData[iAddr]); /* Address of a free slot */
1549 int x; /* Excess size of the slot */
1550 int maxPC = pPg->pBt->usableSize - nByte; /* Max address for a usable slot */
1551 int size; /* Size of the free slot */
1553 assert( pc>0 );
1554 while( pc<=maxPC ){
1555 /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
1556 ** freeblock form a big-endian integer which is the size of the freeblock
1557 ** in bytes, including the 4-byte header. */
1558 size = get2byte(&aData[pc+2]);
1559 if( (x = size - nByte)>=0 ){
1560 testcase( x==4 );
1561 testcase( x==3 );
1562 if( x<4 ){
1563 /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
1564 ** number of bytes in fragments may not exceed 60. */
1565 if( aData[hdr+7]>57 ) return 0;
1567 /* Remove the slot from the free-list. Update the number of
1568 ** fragmented bytes within the page. */
1569 memcpy(&aData[iAddr], &aData[pc], 2);
1570 aData[hdr+7] += (u8)x;
1571 }else if( x+pc > maxPC ){
1572 /* This slot extends off the end of the usable part of the page */
1573 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1574 return 0;
1575 }else{
1576 /* The slot remains on the free-list. Reduce its size to account
1577 ** for the portion used by the new allocation. */
1578 put2byte(&aData[pc+2], x);
1580 return &aData[pc + x];
1582 iAddr = pc;
1583 pc = get2byte(&aData[pc]);
1584 if( pc<=iAddr+size ){
1585 if( pc ){
1586 /* The next slot in the chain is not past the end of the current slot */
1587 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1589 return 0;
1592 if( pc>maxPC+nByte-4 ){
1593 /* The free slot chain extends off the end of the page */
1594 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1596 return 0;
1600 ** Allocate nByte bytes of space from within the B-Tree page passed
1601 ** as the first argument. Write into *pIdx the index into pPage->aData[]
1602 ** of the first byte of allocated space. Return either SQLITE_OK or
1603 ** an error code (usually SQLITE_CORRUPT).
1605 ** The caller guarantees that there is sufficient space to make the
1606 ** allocation. This routine might need to defragment in order to bring
1607 ** all the space together, however. This routine will avoid using
1608 ** the first two bytes past the cell pointer area since presumably this
1609 ** allocation is being made in order to insert a new cell, so we will
1610 ** also end up needing a new cell pointer.
1612 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
1613 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1614 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
1615 int top; /* First byte of cell content area */
1616 int rc = SQLITE_OK; /* Integer return code */
1617 int gap; /* First byte of gap between cell pointers and cell content */
1619 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1620 assert( pPage->pBt );
1621 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1622 assert( nByte>=0 ); /* Minimum cell size is 4 */
1623 assert( pPage->nFree>=nByte );
1624 assert( pPage->nOverflow==0 );
1625 assert( nByte < (int)(pPage->pBt->usableSize-8) );
1627 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1628 gap = pPage->cellOffset + 2*pPage->nCell;
1629 assert( gap<=65536 );
1630 /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
1631 ** and the reserved space is zero (the usual value for reserved space)
1632 ** then the cell content offset of an empty page wants to be 65536.
1633 ** However, that integer is too large to be stored in a 2-byte unsigned
1634 ** integer, so a value of 0 is used in its place. */
1635 top = get2byte(&data[hdr+5]);
1636 assert( top<=(int)pPage->pBt->usableSize ); /* by btreeComputeFreeSpace() */
1637 if( gap>top ){
1638 if( top==0 && pPage->pBt->usableSize==65536 ){
1639 top = 65536;
1640 }else{
1641 return SQLITE_CORRUPT_PAGE(pPage);
1645 /* If there is enough space between gap and top for one more cell pointer,
1646 ** and if the freelist is not empty, then search the
1647 ** freelist looking for a slot big enough to satisfy the request.
1649 testcase( gap+2==top );
1650 testcase( gap+1==top );
1651 testcase( gap==top );
1652 if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
1653 u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
1654 if( pSpace ){
1655 int g2;
1656 assert( pSpace+nByte<=data+pPage->pBt->usableSize );
1657 *pIdx = g2 = (int)(pSpace-data);
1658 if( NEVER(g2<=gap) ){
1659 return SQLITE_CORRUPT_PAGE(pPage);
1660 }else{
1661 return SQLITE_OK;
1663 }else if( rc ){
1664 return rc;
1668 /* The request could not be fulfilled using a freelist slot. Check
1669 ** to see if defragmentation is necessary.
1671 testcase( gap+2+nByte==top );
1672 if( gap+2+nByte>top ){
1673 assert( pPage->nCell>0 || CORRUPT_DB );
1674 assert( pPage->nFree>=0 );
1675 rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
1676 if( rc ) return rc;
1677 top = get2byteNotZero(&data[hdr+5]);
1678 assert( gap+2+nByte<=top );
1682 /* Allocate memory from the gap in between the cell pointer array
1683 ** and the cell content area. The btreeComputeFreeSpace() call has already
1684 ** validated the freelist. Given that the freelist is valid, there
1685 ** is no way that the allocation can extend off the end of the page.
1686 ** The assert() below verifies the previous sentence.
1688 top -= nByte;
1689 put2byte(&data[hdr+5], top);
1690 assert( top+nByte <= (int)pPage->pBt->usableSize );
1691 *pIdx = top;
1692 return SQLITE_OK;
1696 ** Return a section of the pPage->aData to the freelist.
1697 ** The first byte of the new free block is pPage->aData[iStart]
1698 ** and the size of the block is iSize bytes.
1700 ** Adjacent freeblocks are coalesced.
1702 ** Even though the freeblock list was checked by btreeComputeFreeSpace(),
1703 ** that routine will not detect overlap between cells or freeblocks. Nor
1704 ** does it detect cells or freeblocks that encrouch into the reserved bytes
1705 ** at the end of the page. So do additional corruption checks inside this
1706 ** routine and return SQLITE_CORRUPT if any problems are found.
1708 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
1709 u16 iPtr; /* Address of ptr to next freeblock */
1710 u16 iFreeBlk; /* Address of the next freeblock */
1711 u8 hdr; /* Page header size. 0 or 100 */
1712 u8 nFrag = 0; /* Reduction in fragmentation */
1713 u16 iOrigSize = iSize; /* Original value of iSize */
1714 u16 x; /* Offset to cell content area */
1715 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
1716 unsigned char *data = pPage->aData; /* Page content */
1718 assert( pPage->pBt!=0 );
1719 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1720 assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
1721 assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
1722 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1723 assert( iSize>=4 ); /* Minimum cell size is 4 */
1724 assert( iStart<=pPage->pBt->usableSize-4 );
1726 /* The list of freeblocks must be in ascending order. Find the
1727 ** spot on the list where iStart should be inserted.
1729 hdr = pPage->hdrOffset;
1730 iPtr = hdr + 1;
1731 if( data[iPtr+1]==0 && data[iPtr]==0 ){
1732 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
1733 }else{
1734 while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
1735 if( iFreeBlk<iPtr+4 ){
1736 if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */
1737 return SQLITE_CORRUPT_PAGE(pPage);
1739 iPtr = iFreeBlk;
1741 if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */
1742 return SQLITE_CORRUPT_PAGE(pPage);
1744 assert( iFreeBlk>iPtr || iFreeBlk==0 );
1746 /* At this point:
1747 ** iFreeBlk: First freeblock after iStart, or zero if none
1748 ** iPtr: The address of a pointer to iFreeBlk
1750 ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
1752 if( iFreeBlk && iEnd+3>=iFreeBlk ){
1753 nFrag = iFreeBlk - iEnd;
1754 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
1755 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
1756 if( iEnd > pPage->pBt->usableSize ){
1757 return SQLITE_CORRUPT_PAGE(pPage);
1759 iSize = iEnd - iStart;
1760 iFreeBlk = get2byte(&data[iFreeBlk]);
1763 /* If iPtr is another freeblock (that is, if iPtr is not the freelist
1764 ** pointer in the page header) then check to see if iStart should be
1765 ** coalesced onto the end of iPtr.
1767 if( iPtr>hdr+1 ){
1768 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
1769 if( iPtrEnd+3>=iStart ){
1770 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
1771 nFrag += iStart - iPtrEnd;
1772 iSize = iEnd - iPtr;
1773 iStart = iPtr;
1776 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
1777 data[hdr+7] -= nFrag;
1779 x = get2byte(&data[hdr+5]);
1780 if( iStart<=x ){
1781 /* The new freeblock is at the beginning of the cell content area,
1782 ** so just extend the cell content area rather than create another
1783 ** freelist entry */
1784 if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage);
1785 if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
1786 put2byte(&data[hdr+1], iFreeBlk);
1787 put2byte(&data[hdr+5], iEnd);
1788 }else{
1789 /* Insert the new freeblock into the freelist */
1790 put2byte(&data[iPtr], iStart);
1792 if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
1793 /* Overwrite deleted information with zeros when the secure_delete
1794 ** option is enabled */
1795 memset(&data[iStart], 0, iSize);
1797 put2byte(&data[iStart], iFreeBlk);
1798 put2byte(&data[iStart+2], iSize);
1799 pPage->nFree += iOrigSize;
1800 return SQLITE_OK;
1804 ** Decode the flags byte (the first byte of the header) for a page
1805 ** and initialize fields of the MemPage structure accordingly.
1807 ** Only the following combinations are supported. Anything different
1808 ** indicates a corrupt database files:
1810 ** PTF_ZERODATA
1811 ** PTF_ZERODATA | PTF_LEAF
1812 ** PTF_LEAFDATA | PTF_INTKEY
1813 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
1815 static int decodeFlags(MemPage *pPage, int flagByte){
1816 BtShared *pBt; /* A copy of pPage->pBt */
1818 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
1819 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1820 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
1821 flagByte &= ~PTF_LEAF;
1822 pPage->childPtrSize = 4-4*pPage->leaf;
1823 pPage->xCellSize = cellSizePtr;
1824 pBt = pPage->pBt;
1825 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
1826 /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
1827 ** interior table b-tree page. */
1828 assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
1829 /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
1830 ** leaf table b-tree page. */
1831 assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
1832 pPage->intKey = 1;
1833 if( pPage->leaf ){
1834 pPage->intKeyLeaf = 1;
1835 pPage->xParseCell = btreeParseCellPtr;
1836 }else{
1837 pPage->intKeyLeaf = 0;
1838 pPage->xCellSize = cellSizePtrNoPayload;
1839 pPage->xParseCell = btreeParseCellPtrNoPayload;
1841 pPage->maxLocal = pBt->maxLeaf;
1842 pPage->minLocal = pBt->minLeaf;
1843 }else if( flagByte==PTF_ZERODATA ){
1844 /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
1845 ** interior index b-tree page. */
1846 assert( (PTF_ZERODATA)==2 );
1847 /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
1848 ** leaf index b-tree page. */
1849 assert( (PTF_ZERODATA|PTF_LEAF)==10 );
1850 pPage->intKey = 0;
1851 pPage->intKeyLeaf = 0;
1852 pPage->xParseCell = btreeParseCellPtrIndex;
1853 pPage->maxLocal = pBt->maxLocal;
1854 pPage->minLocal = pBt->minLocal;
1855 }else{
1856 /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
1857 ** an error. */
1858 return SQLITE_CORRUPT_PAGE(pPage);
1860 pPage->max1bytePayload = pBt->max1bytePayload;
1861 return SQLITE_OK;
1865 ** Compute the amount of freespace on the page. In other words, fill
1866 ** in the pPage->nFree field.
1868 static int btreeComputeFreeSpace(MemPage *pPage){
1869 int pc; /* Address of a freeblock within pPage->aData[] */
1870 u8 hdr; /* Offset to beginning of page header */
1871 u8 *data; /* Equal to pPage->aData */
1872 int usableSize; /* Amount of usable space on each page */
1873 int nFree; /* Number of unused bytes on the page */
1874 int top; /* First byte of the cell content area */
1875 int iCellFirst; /* First allowable cell or freeblock offset */
1876 int iCellLast; /* Last possible cell or freeblock offset */
1878 assert( pPage->pBt!=0 );
1879 assert( pPage->pBt->db!=0 );
1880 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1881 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
1882 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1883 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
1884 assert( pPage->isInit==1 );
1885 assert( pPage->nFree<0 );
1887 usableSize = pPage->pBt->usableSize;
1888 hdr = pPage->hdrOffset;
1889 data = pPage->aData;
1890 /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
1891 ** the start of the cell content area. A zero value for this integer is
1892 ** interpreted as 65536. */
1893 top = get2byteNotZero(&data[hdr+5]);
1894 iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell;
1895 iCellLast = usableSize - 4;
1897 /* Compute the total free space on the page
1898 ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
1899 ** start of the first freeblock on the page, or is zero if there are no
1900 ** freeblocks. */
1901 pc = get2byte(&data[hdr+1]);
1902 nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
1903 if( pc>0 ){
1904 u32 next, size;
1905 if( pc<top ){
1906 /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
1907 ** always be at least one cell before the first freeblock.
1909 return SQLITE_CORRUPT_PAGE(pPage);
1911 while( 1 ){
1912 if( pc>iCellLast ){
1913 /* Freeblock off the end of the page */
1914 return SQLITE_CORRUPT_PAGE(pPage);
1916 next = get2byte(&data[pc]);
1917 size = get2byte(&data[pc+2]);
1918 nFree = nFree + size;
1919 if( next<=pc+size+3 ) break;
1920 pc = next;
1922 if( next>0 ){
1923 /* Freeblock not in ascending order */
1924 return SQLITE_CORRUPT_PAGE(pPage);
1926 if( pc+size>(unsigned int)usableSize ){
1927 /* Last freeblock extends past page end */
1928 return SQLITE_CORRUPT_PAGE(pPage);
1932 /* At this point, nFree contains the sum of the offset to the start
1933 ** of the cell-content area plus the number of free bytes within
1934 ** the cell-content area. If this is greater than the usable-size
1935 ** of the page, then the page must be corrupted. This check also
1936 ** serves to verify that the offset to the start of the cell-content
1937 ** area, according to the page header, lies within the page.
1939 if( nFree>usableSize || nFree<iCellFirst ){
1940 return SQLITE_CORRUPT_PAGE(pPage);
1942 pPage->nFree = (u16)(nFree - iCellFirst);
1943 return SQLITE_OK;
1947 ** Do additional sanity check after btreeInitPage() if
1948 ** PRAGMA cell_size_check=ON
1950 static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){
1951 int iCellFirst; /* First allowable cell or freeblock offset */
1952 int iCellLast; /* Last possible cell or freeblock offset */
1953 int i; /* Index into the cell pointer array */
1954 int sz; /* Size of a cell */
1955 int pc; /* Address of a freeblock within pPage->aData[] */
1956 u8 *data; /* Equal to pPage->aData */
1957 int usableSize; /* Maximum usable space on the page */
1958 int cellOffset; /* Start of cell content area */
1960 iCellFirst = pPage->cellOffset + 2*pPage->nCell;
1961 usableSize = pPage->pBt->usableSize;
1962 iCellLast = usableSize - 4;
1963 data = pPage->aData;
1964 cellOffset = pPage->cellOffset;
1965 if( !pPage->leaf ) iCellLast--;
1966 for(i=0; i<pPage->nCell; i++){
1967 pc = get2byteAligned(&data[cellOffset+i*2]);
1968 testcase( pc==iCellFirst );
1969 testcase( pc==iCellLast );
1970 if( pc<iCellFirst || pc>iCellLast ){
1971 return SQLITE_CORRUPT_PAGE(pPage);
1973 sz = pPage->xCellSize(pPage, &data[pc]);
1974 testcase( pc+sz==usableSize );
1975 if( pc+sz>usableSize ){
1976 return SQLITE_CORRUPT_PAGE(pPage);
1979 return SQLITE_OK;
1983 ** Initialize the auxiliary information for a disk block.
1985 ** Return SQLITE_OK on success. If we see that the page does
1986 ** not contain a well-formed database page, then return
1987 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1988 ** guarantee that the page is well-formed. It only shows that
1989 ** we failed to detect any corruption.
1991 static int btreeInitPage(MemPage *pPage){
1992 u8 *data; /* Equal to pPage->aData */
1993 BtShared *pBt; /* The main btree structure */
1995 assert( pPage->pBt!=0 );
1996 assert( pPage->pBt->db!=0 );
1997 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1998 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
1999 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
2000 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
2001 assert( pPage->isInit==0 );
2003 pBt = pPage->pBt;
2004 data = pPage->aData + pPage->hdrOffset;
2005 /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
2006 ** the b-tree page type. */
2007 if( decodeFlags(pPage, data[0]) ){
2008 return SQLITE_CORRUPT_PAGE(pPage);
2010 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2011 pPage->maskPage = (u16)(pBt->pageSize - 1);
2012 pPage->nOverflow = 0;
2013 pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize;
2014 pPage->aCellIdx = data + pPage->childPtrSize + 8;
2015 pPage->aDataEnd = pPage->aData + pBt->usableSize;
2016 pPage->aDataOfst = pPage->aData + pPage->childPtrSize;
2017 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
2018 ** number of cells on the page. */
2019 pPage->nCell = get2byte(&data[3]);
2020 if( pPage->nCell>MX_CELL(pBt) ){
2021 /* To many cells for a single page. The page must be corrupt */
2022 return SQLITE_CORRUPT_PAGE(pPage);
2024 testcase( pPage->nCell==MX_CELL(pBt) );
2025 /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
2026 ** possible for a root page of a table that contains no rows) then the
2027 ** offset to the cell content area will equal the page size minus the
2028 ** bytes of reserved space. */
2029 assert( pPage->nCell>0
2030 || get2byteNotZero(&data[5])==(int)pBt->usableSize
2031 || CORRUPT_DB );
2032 pPage->nFree = -1; /* Indicate that this value is yet uncomputed */
2033 pPage->isInit = 1;
2034 if( pBt->db->flags & SQLITE_CellSizeCk ){
2035 return btreeCellSizeCheck(pPage);
2037 return SQLITE_OK;
2041 ** Set up a raw page so that it looks like a database page holding
2042 ** no entries.
2044 static void zeroPage(MemPage *pPage, int flags){
2045 unsigned char *data = pPage->aData;
2046 BtShared *pBt = pPage->pBt;
2047 u8 hdr = pPage->hdrOffset;
2048 u16 first;
2050 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
2051 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2052 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
2053 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
2054 assert( sqlite3_mutex_held(pBt->mutex) );
2055 if( pBt->btsFlags & BTS_FAST_SECURE ){
2056 memset(&data[hdr], 0, pBt->usableSize - hdr);
2058 data[hdr] = (char)flags;
2059 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
2060 memset(&data[hdr+1], 0, 4);
2061 data[hdr+7] = 0;
2062 put2byte(&data[hdr+5], pBt->usableSize);
2063 pPage->nFree = (u16)(pBt->usableSize - first);
2064 decodeFlags(pPage, flags);
2065 pPage->cellOffset = first;
2066 pPage->aDataEnd = &data[pBt->usableSize];
2067 pPage->aCellIdx = &data[first];
2068 pPage->aDataOfst = &data[pPage->childPtrSize];
2069 pPage->nOverflow = 0;
2070 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2071 pPage->maskPage = (u16)(pBt->pageSize - 1);
2072 pPage->nCell = 0;
2073 pPage->isInit = 1;
2078 ** Convert a DbPage obtained from the pager into a MemPage used by
2079 ** the btree layer.
2081 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
2082 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2083 if( pgno!=pPage->pgno ){
2084 pPage->aData = sqlite3PagerGetData(pDbPage);
2085 pPage->pDbPage = pDbPage;
2086 pPage->pBt = pBt;
2087 pPage->pgno = pgno;
2088 pPage->hdrOffset = pgno==1 ? 100 : 0;
2090 assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
2091 return pPage;
2095 ** Get a page from the pager. Initialize the MemPage.pBt and
2096 ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
2098 ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
2099 ** about the content of the page at this time. So do not go to the disk
2100 ** to fetch the content. Just fill in the content with zeros for now.
2101 ** If in the future we call sqlite3PagerWrite() on this page, that
2102 ** means we have started to be concerned about content and the disk
2103 ** read should occur at that point.
2105 static int btreeGetPage(
2106 BtShared *pBt, /* The btree */
2107 Pgno pgno, /* Number of the page to fetch */
2108 MemPage **ppPage, /* Return the page in this parameter */
2109 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2111 int rc;
2112 DbPage *pDbPage;
2114 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
2115 assert( sqlite3_mutex_held(pBt->mutex) );
2116 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
2117 if( rc ) return rc;
2118 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
2119 return SQLITE_OK;
2123 ** Retrieve a page from the pager cache. If the requested page is not
2124 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
2125 ** MemPage.aData elements if needed.
2127 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
2128 DbPage *pDbPage;
2129 assert( sqlite3_mutex_held(pBt->mutex) );
2130 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
2131 if( pDbPage ){
2132 return btreePageFromDbPage(pDbPage, pgno, pBt);
2134 return 0;
2138 ** Return the size of the database file in pages. If there is any kind of
2139 ** error, return ((unsigned int)-1).
2141 static Pgno btreePagecount(BtShared *pBt){
2142 return pBt->nPage;
2144 Pgno sqlite3BtreeLastPage(Btree *p){
2145 assert( sqlite3BtreeHoldsMutex(p) );
2146 return btreePagecount(p->pBt);
2150 ** Get a page from the pager and initialize it.
2152 ** If pCur!=0 then the page is being fetched as part of a moveToChild()
2153 ** call. Do additional sanity checking on the page in this case.
2154 ** And if the fetch fails, this routine must decrement pCur->iPage.
2156 ** The page is fetched as read-write unless pCur is not NULL and is
2157 ** a read-only cursor.
2159 ** If an error occurs, then *ppPage is undefined. It
2160 ** may remain unchanged, or it may be set to an invalid value.
2162 static int getAndInitPage(
2163 BtShared *pBt, /* The database file */
2164 Pgno pgno, /* Number of the page to get */
2165 MemPage **ppPage, /* Write the page pointer here */
2166 BtCursor *pCur, /* Cursor to receive the page, or NULL */
2167 int bReadOnly /* True for a read-only page */
2169 int rc;
2170 DbPage *pDbPage;
2171 assert( sqlite3_mutex_held(pBt->mutex) );
2172 assert( pCur==0 || ppPage==&pCur->pPage );
2173 assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
2174 assert( pCur==0 || pCur->iPage>0 );
2176 if( pgno>btreePagecount(pBt) ){
2177 rc = SQLITE_CORRUPT_BKPT;
2178 goto getAndInitPage_error1;
2180 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
2181 if( rc ){
2182 goto getAndInitPage_error1;
2184 *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2185 if( (*ppPage)->isInit==0 ){
2186 btreePageFromDbPage(pDbPage, pgno, pBt);
2187 rc = btreeInitPage(*ppPage);
2188 if( rc!=SQLITE_OK ){
2189 goto getAndInitPage_error2;
2192 assert( (*ppPage)->pgno==pgno );
2193 assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
2195 /* If obtaining a child page for a cursor, we must verify that the page is
2196 ** compatible with the root page. */
2197 if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
2198 rc = SQLITE_CORRUPT_PGNO(pgno);
2199 goto getAndInitPage_error2;
2201 return SQLITE_OK;
2203 getAndInitPage_error2:
2204 releasePage(*ppPage);
2205 getAndInitPage_error1:
2206 if( pCur ){
2207 pCur->iPage--;
2208 pCur->pPage = pCur->apPage[pCur->iPage];
2210 testcase( pgno==0 );
2211 assert( pgno!=0 || rc==SQLITE_CORRUPT );
2212 return rc;
2216 ** Release a MemPage. This should be called once for each prior
2217 ** call to btreeGetPage.
2219 ** Page1 is a special case and must be released using releasePageOne().
2221 static void releasePageNotNull(MemPage *pPage){
2222 assert( pPage->aData );
2223 assert( pPage->pBt );
2224 assert( pPage->pDbPage!=0 );
2225 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2226 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2227 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2228 sqlite3PagerUnrefNotNull(pPage->pDbPage);
2230 static void releasePage(MemPage *pPage){
2231 if( pPage ) releasePageNotNull(pPage);
2233 static void releasePageOne(MemPage *pPage){
2234 assert( pPage!=0 );
2235 assert( pPage->aData );
2236 assert( pPage->pBt );
2237 assert( pPage->pDbPage!=0 );
2238 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2239 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2240 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2241 sqlite3PagerUnrefPageOne(pPage->pDbPage);
2245 ** Get an unused page.
2247 ** This works just like btreeGetPage() with the addition:
2249 ** * If the page is already in use for some other purpose, immediately
2250 ** release it and return an SQLITE_CURRUPT error.
2251 ** * Make sure the isInit flag is clear
2253 static int btreeGetUnusedPage(
2254 BtShared *pBt, /* The btree */
2255 Pgno pgno, /* Number of the page to fetch */
2256 MemPage **ppPage, /* Return the page in this parameter */
2257 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2259 int rc = btreeGetPage(pBt, pgno, ppPage, flags);
2260 if( rc==SQLITE_OK ){
2261 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
2262 releasePage(*ppPage);
2263 *ppPage = 0;
2264 return SQLITE_CORRUPT_BKPT;
2266 (*ppPage)->isInit = 0;
2267 }else{
2268 *ppPage = 0;
2270 return rc;
2275 ** During a rollback, when the pager reloads information into the cache
2276 ** so that the cache is restored to its original state at the start of
2277 ** the transaction, for each page restored this routine is called.
2279 ** This routine needs to reset the extra data section at the end of the
2280 ** page to agree with the restored data.
2282 static void pageReinit(DbPage *pData){
2283 MemPage *pPage;
2284 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
2285 assert( sqlite3PagerPageRefcount(pData)>0 );
2286 if( pPage->isInit ){
2287 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2288 pPage->isInit = 0;
2289 if( sqlite3PagerPageRefcount(pData)>1 ){
2290 /* pPage might not be a btree page; it might be an overflow page
2291 ** or ptrmap page or a free page. In those cases, the following
2292 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
2293 ** But no harm is done by this. And it is very important that
2294 ** btreeInitPage() be called on every btree page so we make
2295 ** the call for every page that comes in for re-initing. */
2296 btreeInitPage(pPage);
2302 ** Invoke the busy handler for a btree.
2304 static int btreeInvokeBusyHandler(void *pArg){
2305 BtShared *pBt = (BtShared*)pArg;
2306 assert( pBt->db );
2307 assert( sqlite3_mutex_held(pBt->db->mutex) );
2308 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
2312 ** Open a database file.
2314 ** zFilename is the name of the database file. If zFilename is NULL
2315 ** then an ephemeral database is created. The ephemeral database might
2316 ** be exclusively in memory, or it might use a disk-based memory cache.
2317 ** Either way, the ephemeral database will be automatically deleted
2318 ** when sqlite3BtreeClose() is called.
2320 ** If zFilename is ":memory:" then an in-memory database is created
2321 ** that is automatically destroyed when it is closed.
2323 ** The "flags" parameter is a bitmask that might contain bits like
2324 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
2326 ** If the database is already opened in the same database connection
2327 ** and we are in shared cache mode, then the open will fail with an
2328 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
2329 ** objects in the same database connection since doing so will lead
2330 ** to problems with locking.
2332 int sqlite3BtreeOpen(
2333 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
2334 const char *zFilename, /* Name of the file containing the BTree database */
2335 sqlite3 *db, /* Associated database handle */
2336 Btree **ppBtree, /* Pointer to new Btree object written here */
2337 int flags, /* Options */
2338 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
2340 BtShared *pBt = 0; /* Shared part of btree structure */
2341 Btree *p; /* Handle to return */
2342 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
2343 int rc = SQLITE_OK; /* Result code from this function */
2344 u8 nReserve; /* Byte of unused space on each page */
2345 unsigned char zDbHeader[100]; /* Database header content */
2347 /* True if opening an ephemeral, temporary database */
2348 const int isTempDb = zFilename==0 || zFilename[0]==0;
2350 /* Set the variable isMemdb to true for an in-memory database, or
2351 ** false for a file-based database.
2353 #ifdef SQLITE_OMIT_MEMORYDB
2354 const int isMemdb = 0;
2355 #else
2356 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
2357 || (isTempDb && sqlite3TempInMemory(db))
2358 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
2359 #endif
2361 assert( db!=0 );
2362 assert( pVfs!=0 );
2363 assert( sqlite3_mutex_held(db->mutex) );
2364 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
2366 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
2367 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
2369 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
2370 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
2372 if( isMemdb ){
2373 flags |= BTREE_MEMORY;
2375 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
2376 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
2378 p = sqlite3MallocZero(sizeof(Btree));
2379 if( !p ){
2380 return SQLITE_NOMEM_BKPT;
2382 p->inTrans = TRANS_NONE;
2383 p->db = db;
2384 #ifndef SQLITE_OMIT_SHARED_CACHE
2385 p->lock.pBtree = p;
2386 p->lock.iTable = 1;
2387 #endif
2389 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2391 ** If this Btree is a candidate for shared cache, try to find an
2392 ** existing BtShared object that we can share with
2394 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
2395 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
2396 int nFilename = sqlite3Strlen30(zFilename)+1;
2397 int nFullPathname = pVfs->mxPathname+1;
2398 char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
2399 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2401 p->sharable = 1;
2402 if( !zFullPathname ){
2403 sqlite3_free(p);
2404 return SQLITE_NOMEM_BKPT;
2406 if( isMemdb ){
2407 memcpy(zFullPathname, zFilename, nFilename);
2408 }else{
2409 rc = sqlite3OsFullPathname(pVfs, zFilename,
2410 nFullPathname, zFullPathname);
2411 if( rc ){
2412 if( rc==SQLITE_OK_SYMLINK ){
2413 rc = SQLITE_OK;
2414 }else{
2415 sqlite3_free(zFullPathname);
2416 sqlite3_free(p);
2417 return rc;
2421 #if SQLITE_THREADSAFE
2422 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
2423 sqlite3_mutex_enter(mutexOpen);
2424 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
2425 sqlite3_mutex_enter(mutexShared);
2426 #endif
2427 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
2428 assert( pBt->nRef>0 );
2429 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
2430 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
2431 int iDb;
2432 for(iDb=db->nDb-1; iDb>=0; iDb--){
2433 Btree *pExisting = db->aDb[iDb].pBt;
2434 if( pExisting && pExisting->pBt==pBt ){
2435 sqlite3_mutex_leave(mutexShared);
2436 sqlite3_mutex_leave(mutexOpen);
2437 sqlite3_free(zFullPathname);
2438 sqlite3_free(p);
2439 return SQLITE_CONSTRAINT;
2442 p->pBt = pBt;
2443 pBt->nRef++;
2444 break;
2447 sqlite3_mutex_leave(mutexShared);
2448 sqlite3_free(zFullPathname);
2450 #ifdef SQLITE_DEBUG
2451 else{
2452 /* In debug mode, we mark all persistent databases as sharable
2453 ** even when they are not. This exercises the locking code and
2454 ** gives more opportunity for asserts(sqlite3_mutex_held())
2455 ** statements to find locking problems.
2457 p->sharable = 1;
2459 #endif
2461 #endif
2462 if( pBt==0 ){
2464 ** The following asserts make sure that structures used by the btree are
2465 ** the right size. This is to guard against size changes that result
2466 ** when compiling on a different architecture.
2468 assert( sizeof(i64)==8 );
2469 assert( sizeof(u64)==8 );
2470 assert( sizeof(u32)==4 );
2471 assert( sizeof(u16)==2 );
2472 assert( sizeof(Pgno)==4 );
2474 pBt = sqlite3MallocZero( sizeof(*pBt) );
2475 if( pBt==0 ){
2476 rc = SQLITE_NOMEM_BKPT;
2477 goto btree_open_out;
2479 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
2480 sizeof(MemPage), flags, vfsFlags, pageReinit);
2481 if( rc==SQLITE_OK ){
2482 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
2483 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
2485 if( rc!=SQLITE_OK ){
2486 goto btree_open_out;
2488 pBt->openFlags = (u8)flags;
2489 pBt->db = db;
2490 sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
2491 p->pBt = pBt;
2493 pBt->pCursor = 0;
2494 pBt->pPage1 = 0;
2495 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
2496 #if defined(SQLITE_SECURE_DELETE)
2497 pBt->btsFlags |= BTS_SECURE_DELETE;
2498 #elif defined(SQLITE_FAST_SECURE_DELETE)
2499 pBt->btsFlags |= BTS_OVERWRITE;
2500 #endif
2501 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2502 ** determined by the 2-byte integer located at an offset of 16 bytes from
2503 ** the beginning of the database file. */
2504 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
2505 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
2506 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
2507 pBt->pageSize = 0;
2508 #ifndef SQLITE_OMIT_AUTOVACUUM
2509 /* If the magic name ":memory:" will create an in-memory database, then
2510 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
2511 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
2512 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
2513 ** regular file-name. In this case the auto-vacuum applies as per normal.
2515 if( zFilename && !isMemdb ){
2516 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
2517 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
2519 #endif
2520 nReserve = 0;
2521 }else{
2522 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2523 ** determined by the one-byte unsigned integer found at an offset of 20
2524 ** into the database file header. */
2525 nReserve = zDbHeader[20];
2526 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2527 #ifndef SQLITE_OMIT_AUTOVACUUM
2528 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
2529 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
2530 #endif
2532 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2533 if( rc ) goto btree_open_out;
2534 pBt->usableSize = pBt->pageSize - nReserve;
2535 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
2537 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2538 /* Add the new BtShared object to the linked list sharable BtShareds.
2540 pBt->nRef = 1;
2541 if( p->sharable ){
2542 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2543 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);)
2544 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
2545 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
2546 if( pBt->mutex==0 ){
2547 rc = SQLITE_NOMEM_BKPT;
2548 goto btree_open_out;
2551 sqlite3_mutex_enter(mutexShared);
2552 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2553 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
2554 sqlite3_mutex_leave(mutexShared);
2556 #endif
2559 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2560 /* If the new Btree uses a sharable pBtShared, then link the new
2561 ** Btree into the list of all sharable Btrees for the same connection.
2562 ** The list is kept in ascending order by pBt address.
2564 if( p->sharable ){
2565 int i;
2566 Btree *pSib;
2567 for(i=0; i<db->nDb; i++){
2568 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
2569 while( pSib->pPrev ){ pSib = pSib->pPrev; }
2570 if( (uptr)p->pBt<(uptr)pSib->pBt ){
2571 p->pNext = pSib;
2572 p->pPrev = 0;
2573 pSib->pPrev = p;
2574 }else{
2575 while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
2576 pSib = pSib->pNext;
2578 p->pNext = pSib->pNext;
2579 p->pPrev = pSib;
2580 if( p->pNext ){
2581 p->pNext->pPrev = p;
2583 pSib->pNext = p;
2585 break;
2589 #endif
2590 *ppBtree = p;
2592 btree_open_out:
2593 if( rc!=SQLITE_OK ){
2594 if( pBt && pBt->pPager ){
2595 sqlite3PagerClose(pBt->pPager, 0);
2597 sqlite3_free(pBt);
2598 sqlite3_free(p);
2599 *ppBtree = 0;
2600 }else{
2601 sqlite3_file *pFile;
2603 /* If the B-Tree was successfully opened, set the pager-cache size to the
2604 ** default value. Except, when opening on an existing shared pager-cache,
2605 ** do not change the pager-cache size.
2607 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
2608 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
2611 pFile = sqlite3PagerFile(pBt->pPager);
2612 if( pFile->pMethods ){
2613 sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
2616 if( mutexOpen ){
2617 assert( sqlite3_mutex_held(mutexOpen) );
2618 sqlite3_mutex_leave(mutexOpen);
2620 assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
2621 return rc;
2625 ** Decrement the BtShared.nRef counter. When it reaches zero,
2626 ** remove the BtShared structure from the sharing list. Return
2627 ** true if the BtShared.nRef counter reaches zero and return
2628 ** false if it is still positive.
2630 static int removeFromSharingList(BtShared *pBt){
2631 #ifndef SQLITE_OMIT_SHARED_CACHE
2632 MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )
2633 BtShared *pList;
2634 int removed = 0;
2636 assert( sqlite3_mutex_notheld(pBt->mutex) );
2637 MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
2638 sqlite3_mutex_enter(pMainMtx);
2639 pBt->nRef--;
2640 if( pBt->nRef<=0 ){
2641 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2642 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
2643 }else{
2644 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
2645 while( ALWAYS(pList) && pList->pNext!=pBt ){
2646 pList=pList->pNext;
2648 if( ALWAYS(pList) ){
2649 pList->pNext = pBt->pNext;
2652 if( SQLITE_THREADSAFE ){
2653 sqlite3_mutex_free(pBt->mutex);
2655 removed = 1;
2657 sqlite3_mutex_leave(pMainMtx);
2658 return removed;
2659 #else
2660 return 1;
2661 #endif
2665 ** Make sure pBt->pTmpSpace points to an allocation of
2666 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
2667 ** pointer.
2669 static void allocateTempSpace(BtShared *pBt){
2670 if( !pBt->pTmpSpace ){
2671 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
2673 /* One of the uses of pBt->pTmpSpace is to format cells before
2674 ** inserting them into a leaf page (function fillInCell()). If
2675 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
2676 ** by the various routines that manipulate binary cells. Which
2677 ** can mean that fillInCell() only initializes the first 2 or 3
2678 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
2679 ** it into a database page. This is not actually a problem, but it
2680 ** does cause a valgrind error when the 1 or 2 bytes of unitialized
2681 ** data is passed to system call write(). So to avoid this error,
2682 ** zero the first 4 bytes of temp space here.
2684 ** Also: Provide four bytes of initialized space before the
2685 ** beginning of pTmpSpace as an area available to prepend the
2686 ** left-child pointer to the beginning of a cell.
2688 if( pBt->pTmpSpace ){
2689 memset(pBt->pTmpSpace, 0, 8);
2690 pBt->pTmpSpace += 4;
2696 ** Free the pBt->pTmpSpace allocation
2698 static void freeTempSpace(BtShared *pBt){
2699 if( pBt->pTmpSpace ){
2700 pBt->pTmpSpace -= 4;
2701 sqlite3PageFree(pBt->pTmpSpace);
2702 pBt->pTmpSpace = 0;
2707 ** Close an open database and invalidate all cursors.
2709 int sqlite3BtreeClose(Btree *p){
2710 BtShared *pBt = p->pBt;
2711 BtCursor *pCur;
2713 /* Close all cursors opened via this handle. */
2714 assert( sqlite3_mutex_held(p->db->mutex) );
2715 sqlite3BtreeEnter(p);
2716 pCur = pBt->pCursor;
2717 while( pCur ){
2718 BtCursor *pTmp = pCur;
2719 pCur = pCur->pNext;
2720 if( pTmp->pBtree==p ){
2721 sqlite3BtreeCloseCursor(pTmp);
2725 /* Rollback any active transaction and free the handle structure.
2726 ** The call to sqlite3BtreeRollback() drops any table-locks held by
2727 ** this handle.
2729 sqlite3BtreeRollback(p, SQLITE_OK, 0);
2730 sqlite3BtreeLeave(p);
2732 /* If there are still other outstanding references to the shared-btree
2733 ** structure, return now. The remainder of this procedure cleans
2734 ** up the shared-btree.
2736 assert( p->wantToLock==0 && p->locked==0 );
2737 if( !p->sharable || removeFromSharingList(pBt) ){
2738 /* The pBt is no longer on the sharing list, so we can access
2739 ** it without having to hold the mutex.
2741 ** Clean out and delete the BtShared object.
2743 assert( !pBt->pCursor );
2744 sqlite3PagerClose(pBt->pPager, p->db);
2745 if( pBt->xFreeSchema && pBt->pSchema ){
2746 pBt->xFreeSchema(pBt->pSchema);
2748 sqlite3DbFree(0, pBt->pSchema);
2749 freeTempSpace(pBt);
2750 sqlite3_free(pBt);
2753 #ifndef SQLITE_OMIT_SHARED_CACHE
2754 assert( p->wantToLock==0 );
2755 assert( p->locked==0 );
2756 if( p->pPrev ) p->pPrev->pNext = p->pNext;
2757 if( p->pNext ) p->pNext->pPrev = p->pPrev;
2758 #endif
2760 sqlite3_free(p);
2761 return SQLITE_OK;
2765 ** Change the "soft" limit on the number of pages in the cache.
2766 ** Unused and unmodified pages will be recycled when the number of
2767 ** pages in the cache exceeds this soft limit. But the size of the
2768 ** cache is allowed to grow larger than this limit if it contains
2769 ** dirty pages or pages still in active use.
2771 int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2772 BtShared *pBt = p->pBt;
2773 assert( sqlite3_mutex_held(p->db->mutex) );
2774 sqlite3BtreeEnter(p);
2775 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
2776 sqlite3BtreeLeave(p);
2777 return SQLITE_OK;
2781 ** Change the "spill" limit on the number of pages in the cache.
2782 ** If the number of pages exceeds this limit during a write transaction,
2783 ** the pager might attempt to "spill" pages to the journal early in
2784 ** order to free up memory.
2786 ** The value returned is the current spill size. If zero is passed
2787 ** as an argument, no changes are made to the spill size setting, so
2788 ** using mxPage of 0 is a way to query the current spill size.
2790 int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
2791 BtShared *pBt = p->pBt;
2792 int res;
2793 assert( sqlite3_mutex_held(p->db->mutex) );
2794 sqlite3BtreeEnter(p);
2795 res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
2796 sqlite3BtreeLeave(p);
2797 return res;
2800 #if SQLITE_MAX_MMAP_SIZE>0
2802 ** Change the limit on the amount of the database file that may be
2803 ** memory mapped.
2805 int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
2806 BtShared *pBt = p->pBt;
2807 assert( sqlite3_mutex_held(p->db->mutex) );
2808 sqlite3BtreeEnter(p);
2809 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
2810 sqlite3BtreeLeave(p);
2811 return SQLITE_OK;
2813 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
2816 ** Change the way data is synced to disk in order to increase or decrease
2817 ** how well the database resists damage due to OS crashes and power
2818 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
2819 ** there is a high probability of damage) Level 2 is the default. There
2820 ** is a very low but non-zero probability of damage. Level 3 reduces the
2821 ** probability of damage to near zero but with a write performance reduction.
2823 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
2824 int sqlite3BtreeSetPagerFlags(
2825 Btree *p, /* The btree to set the safety level on */
2826 unsigned pgFlags /* Various PAGER_* flags */
2828 BtShared *pBt = p->pBt;
2829 assert( sqlite3_mutex_held(p->db->mutex) );
2830 sqlite3BtreeEnter(p);
2831 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
2832 sqlite3BtreeLeave(p);
2833 return SQLITE_OK;
2835 #endif
2838 ** Change the default pages size and the number of reserved bytes per page.
2839 ** Or, if the page size has already been fixed, return SQLITE_READONLY
2840 ** without changing anything.
2842 ** The page size must be a power of 2 between 512 and 65536. If the page
2843 ** size supplied does not meet this constraint then the page size is not
2844 ** changed.
2846 ** Page sizes are constrained to be a power of two so that the region
2847 ** of the database file used for locking (beginning at PENDING_BYTE,
2848 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
2849 ** at the beginning of a page.
2851 ** If parameter nReserve is less than zero, then the number of reserved
2852 ** bytes per page is left unchanged.
2854 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
2855 ** and autovacuum mode can no longer be changed.
2857 int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
2858 int rc = SQLITE_OK;
2859 int x;
2860 BtShared *pBt = p->pBt;
2861 assert( nReserve>=0 && nReserve<=255 );
2862 sqlite3BtreeEnter(p);
2863 pBt->nReserveWanted = nReserve;
2864 x = pBt->pageSize - pBt->usableSize;
2865 if( nReserve<x ) nReserve = x;
2866 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
2867 sqlite3BtreeLeave(p);
2868 return SQLITE_READONLY;
2870 assert( nReserve>=0 && nReserve<=255 );
2871 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2872 ((pageSize-1)&pageSize)==0 ){
2873 assert( (pageSize & 7)==0 );
2874 assert( !pBt->pCursor );
2875 pBt->pageSize = (u32)pageSize;
2876 freeTempSpace(pBt);
2878 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2879 pBt->usableSize = pBt->pageSize - (u16)nReserve;
2880 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2881 sqlite3BtreeLeave(p);
2882 return rc;
2886 ** Return the currently defined page size
2888 int sqlite3BtreeGetPageSize(Btree *p){
2889 return p->pBt->pageSize;
2893 ** This function is similar to sqlite3BtreeGetReserve(), except that it
2894 ** may only be called if it is guaranteed that the b-tree mutex is already
2895 ** held.
2897 ** This is useful in one special case in the backup API code where it is
2898 ** known that the shared b-tree mutex is held, but the mutex on the
2899 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
2900 ** were to be called, it might collide with some other operation on the
2901 ** database handle that owns *p, causing undefined behavior.
2903 int sqlite3BtreeGetReserveNoMutex(Btree *p){
2904 int n;
2905 assert( sqlite3_mutex_held(p->pBt->mutex) );
2906 n = p->pBt->pageSize - p->pBt->usableSize;
2907 return n;
2911 ** Return the number of bytes of space at the end of every page that
2912 ** are intentually left unused. This is the "reserved" space that is
2913 ** sometimes used by extensions.
2915 ** The value returned is the larger of the current reserve size and
2916 ** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES.
2917 ** The amount of reserve can only grow - never shrink.
2919 int sqlite3BtreeGetRequestedReserve(Btree *p){
2920 int n1, n2;
2921 sqlite3BtreeEnter(p);
2922 n1 = (int)p->pBt->nReserveWanted;
2923 n2 = sqlite3BtreeGetReserveNoMutex(p);
2924 sqlite3BtreeLeave(p);
2925 return n1>n2 ? n1 : n2;
2930 ** Set the maximum page count for a database if mxPage is positive.
2931 ** No changes are made if mxPage is 0 or negative.
2932 ** Regardless of the value of mxPage, return the maximum page count.
2934 Pgno sqlite3BtreeMaxPageCount(Btree *p, Pgno mxPage){
2935 Pgno n;
2936 sqlite3BtreeEnter(p);
2937 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
2938 sqlite3BtreeLeave(p);
2939 return n;
2943 ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
2945 ** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
2946 ** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
2947 ** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
2948 ** newFlag==(-1) No changes
2950 ** This routine acts as a query if newFlag is less than zero
2952 ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
2953 ** freelist leaf pages are not written back to the database. Thus in-page
2954 ** deleted content is cleared, but freelist deleted content is not.
2956 ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
2957 ** that freelist leaf pages are written back into the database, increasing
2958 ** the amount of disk I/O.
2960 int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
2961 int b;
2962 if( p==0 ) return 0;
2963 sqlite3BtreeEnter(p);
2964 assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
2965 assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
2966 if( newFlag>=0 ){
2967 p->pBt->btsFlags &= ~BTS_FAST_SECURE;
2968 p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
2970 b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
2971 sqlite3BtreeLeave(p);
2972 return b;
2976 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
2977 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
2978 ** is disabled. The default value for the auto-vacuum property is
2979 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
2981 int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
2982 #ifdef SQLITE_OMIT_AUTOVACUUM
2983 return SQLITE_READONLY;
2984 #else
2985 BtShared *pBt = p->pBt;
2986 int rc = SQLITE_OK;
2987 u8 av = (u8)autoVacuum;
2989 sqlite3BtreeEnter(p);
2990 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
2991 rc = SQLITE_READONLY;
2992 }else{
2993 pBt->autoVacuum = av ?1:0;
2994 pBt->incrVacuum = av==2 ?1:0;
2996 sqlite3BtreeLeave(p);
2997 return rc;
2998 #endif
3002 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
3003 ** enabled 1 is returned. Otherwise 0.
3005 int sqlite3BtreeGetAutoVacuum(Btree *p){
3006 #ifdef SQLITE_OMIT_AUTOVACUUM
3007 return BTREE_AUTOVACUUM_NONE;
3008 #else
3009 int rc;
3010 sqlite3BtreeEnter(p);
3011 rc = (
3012 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
3013 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
3014 BTREE_AUTOVACUUM_INCR
3016 sqlite3BtreeLeave(p);
3017 return rc;
3018 #endif
3022 ** If the user has not set the safety-level for this database connection
3023 ** using "PRAGMA synchronous", and if the safety-level is not already
3024 ** set to the value passed to this function as the second parameter,
3025 ** set it so.
3027 #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
3028 && !defined(SQLITE_OMIT_WAL)
3029 static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
3030 sqlite3 *db;
3031 Db *pDb;
3032 if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
3033 while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
3034 if( pDb->bSyncSet==0
3035 && pDb->safety_level!=safety_level
3036 && pDb!=&db->aDb[1]
3038 pDb->safety_level = safety_level;
3039 sqlite3PagerSetFlags(pBt->pPager,
3040 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
3044 #else
3045 # define setDefaultSyncFlag(pBt,safety_level)
3046 #endif
3048 /* Forward declaration */
3049 static int newDatabase(BtShared*);
3053 ** Get a reference to pPage1 of the database file. This will
3054 ** also acquire a readlock on that file.
3056 ** SQLITE_OK is returned on success. If the file is not a
3057 ** well-formed database file, then SQLITE_CORRUPT is returned.
3058 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
3059 ** is returned if we run out of memory.
3061 static int lockBtree(BtShared *pBt){
3062 int rc; /* Result code from subfunctions */
3063 MemPage *pPage1; /* Page 1 of the database file */
3064 u32 nPage; /* Number of pages in the database */
3065 u32 nPageFile = 0; /* Number of pages in the database file */
3066 u32 nPageHeader; /* Number of pages in the database according to hdr */
3068 assert( sqlite3_mutex_held(pBt->mutex) );
3069 assert( pBt->pPage1==0 );
3070 rc = sqlite3PagerSharedLock(pBt->pPager);
3071 if( rc!=SQLITE_OK ) return rc;
3072 rc = btreeGetPage(pBt, 1, &pPage1, 0);
3073 if( rc!=SQLITE_OK ) return rc;
3075 /* Do some checking to help insure the file we opened really is
3076 ** a valid database file.
3078 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
3079 sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
3080 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
3081 nPage = nPageFile;
3083 if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
3084 nPage = 0;
3086 if( nPage>0 ){
3087 u32 pageSize;
3088 u32 usableSize;
3089 u8 *page1 = pPage1->aData;
3090 rc = SQLITE_NOTADB;
3091 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
3092 ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
3093 ** 61 74 20 33 00. */
3094 if( memcmp(page1, zMagicHeader, 16)!=0 ){
3095 goto page1_init_failed;
3098 #ifdef SQLITE_OMIT_WAL
3099 if( page1[18]>1 ){
3100 pBt->btsFlags |= BTS_READ_ONLY;
3102 if( page1[19]>1 ){
3103 goto page1_init_failed;
3105 #else
3106 if( page1[18]>2 ){
3107 pBt->btsFlags |= BTS_READ_ONLY;
3109 if( page1[19]>2 ){
3110 goto page1_init_failed;
3113 /* If the write version is set to 2, this database should be accessed
3114 ** in WAL mode. If the log is not already open, open it now. Then
3115 ** return SQLITE_OK and return without populating BtShared.pPage1.
3116 ** The caller detects this and calls this function again. This is
3117 ** required as the version of page 1 currently in the page1 buffer
3118 ** may not be the latest version - there may be a newer one in the log
3119 ** file.
3121 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
3122 int isOpen = 0;
3123 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
3124 if( rc!=SQLITE_OK ){
3125 goto page1_init_failed;
3126 }else{
3127 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
3128 if( isOpen==0 ){
3129 releasePageOne(pPage1);
3130 return SQLITE_OK;
3133 rc = SQLITE_NOTADB;
3134 }else{
3135 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
3137 #endif
3139 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
3140 ** fractions and the leaf payload fraction values must be 64, 32, and 32.
3142 ** The original design allowed these amounts to vary, but as of
3143 ** version 3.6.0, we require them to be fixed.
3145 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
3146 goto page1_init_failed;
3148 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
3149 ** determined by the 2-byte integer located at an offset of 16 bytes from
3150 ** the beginning of the database file. */
3151 pageSize = (page1[16]<<8) | (page1[17]<<16);
3152 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
3153 ** between 512 and 65536 inclusive. */
3154 if( ((pageSize-1)&pageSize)!=0
3155 || pageSize>SQLITE_MAX_PAGE_SIZE
3156 || pageSize<=256
3158 goto page1_init_failed;
3160 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3161 assert( (pageSize & 7)==0 );
3162 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
3163 ** integer at offset 20 is the number of bytes of space at the end of
3164 ** each page to reserve for extensions.
3166 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
3167 ** determined by the one-byte unsigned integer found at an offset of 20
3168 ** into the database file header. */
3169 usableSize = pageSize - page1[20];
3170 if( (u32)pageSize!=pBt->pageSize ){
3171 /* After reading the first page of the database assuming a page size
3172 ** of BtShared.pageSize, we have discovered that the page-size is
3173 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
3174 ** zero and return SQLITE_OK. The caller will call this function
3175 ** again with the correct page-size.
3177 releasePageOne(pPage1);
3178 pBt->usableSize = usableSize;
3179 pBt->pageSize = pageSize;
3180 freeTempSpace(pBt);
3181 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
3182 pageSize-usableSize);
3183 return rc;
3185 if( sqlite3WritableSchema(pBt->db)==0 && nPage>nPageFile ){
3186 rc = SQLITE_CORRUPT_BKPT;
3187 goto page1_init_failed;
3189 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
3190 ** be less than 480. In other words, if the page size is 512, then the
3191 ** reserved space size cannot exceed 32. */
3192 if( usableSize<480 ){
3193 goto page1_init_failed;
3195 pBt->pageSize = pageSize;
3196 pBt->usableSize = usableSize;
3197 #ifndef SQLITE_OMIT_AUTOVACUUM
3198 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
3199 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
3200 #endif
3203 /* maxLocal is the maximum amount of payload to store locally for
3204 ** a cell. Make sure it is small enough so that at least minFanout
3205 ** cells can will fit on one page. We assume a 10-byte page header.
3206 ** Besides the payload, the cell must store:
3207 ** 2-byte pointer to the cell
3208 ** 4-byte child pointer
3209 ** 9-byte nKey value
3210 ** 4-byte nData value
3211 ** 4-byte overflow page pointer
3212 ** So a cell consists of a 2-byte pointer, a header which is as much as
3213 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
3214 ** page pointer.
3216 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
3217 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
3218 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
3219 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
3220 if( pBt->maxLocal>127 ){
3221 pBt->max1bytePayload = 127;
3222 }else{
3223 pBt->max1bytePayload = (u8)pBt->maxLocal;
3225 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
3226 pBt->pPage1 = pPage1;
3227 pBt->nPage = nPage;
3228 return SQLITE_OK;
3230 page1_init_failed:
3231 releasePageOne(pPage1);
3232 pBt->pPage1 = 0;
3233 return rc;
3236 #ifndef NDEBUG
3238 ** Return the number of cursors open on pBt. This is for use
3239 ** in assert() expressions, so it is only compiled if NDEBUG is not
3240 ** defined.
3242 ** Only write cursors are counted if wrOnly is true. If wrOnly is
3243 ** false then all cursors are counted.
3245 ** For the purposes of this routine, a cursor is any cursor that
3246 ** is capable of reading or writing to the database. Cursors that
3247 ** have been tripped into the CURSOR_FAULT state are not counted.
3249 static int countValidCursors(BtShared *pBt, int wrOnly){
3250 BtCursor *pCur;
3251 int r = 0;
3252 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3253 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
3254 && pCur->eState!=CURSOR_FAULT ) r++;
3256 return r;
3258 #endif
3261 ** If there are no outstanding cursors and we are not in the middle
3262 ** of a transaction but there is a read lock on the database, then
3263 ** this routine unrefs the first page of the database file which
3264 ** has the effect of releasing the read lock.
3266 ** If there is a transaction in progress, this routine is a no-op.
3268 static void unlockBtreeIfUnused(BtShared *pBt){
3269 assert( sqlite3_mutex_held(pBt->mutex) );
3270 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
3271 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
3272 MemPage *pPage1 = pBt->pPage1;
3273 assert( pPage1->aData );
3274 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
3275 pBt->pPage1 = 0;
3276 releasePageOne(pPage1);
3281 ** If pBt points to an empty file then convert that empty file
3282 ** into a new empty database by initializing the first page of
3283 ** the database.
3285 static int newDatabase(BtShared *pBt){
3286 MemPage *pP1;
3287 unsigned char *data;
3288 int rc;
3290 assert( sqlite3_mutex_held(pBt->mutex) );
3291 if( pBt->nPage>0 ){
3292 return SQLITE_OK;
3294 pP1 = pBt->pPage1;
3295 assert( pP1!=0 );
3296 data = pP1->aData;
3297 rc = sqlite3PagerWrite(pP1->pDbPage);
3298 if( rc ) return rc;
3299 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
3300 assert( sizeof(zMagicHeader)==16 );
3301 data[16] = (u8)((pBt->pageSize>>8)&0xff);
3302 data[17] = (u8)((pBt->pageSize>>16)&0xff);
3303 data[18] = 1;
3304 data[19] = 1;
3305 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
3306 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
3307 data[21] = 64;
3308 data[22] = 32;
3309 data[23] = 32;
3310 memset(&data[24], 0, 100-24);
3311 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
3312 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3313 #ifndef SQLITE_OMIT_AUTOVACUUM
3314 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
3315 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
3316 put4byte(&data[36 + 4*4], pBt->autoVacuum);
3317 put4byte(&data[36 + 7*4], pBt->incrVacuum);
3318 #endif
3319 pBt->nPage = 1;
3320 data[31] = 1;
3321 return SQLITE_OK;
3325 ** Initialize the first page of the database file (creating a database
3326 ** consisting of a single page and no schema objects). Return SQLITE_OK
3327 ** if successful, or an SQLite error code otherwise.
3329 int sqlite3BtreeNewDb(Btree *p){
3330 int rc;
3331 sqlite3BtreeEnter(p);
3332 p->pBt->nPage = 0;
3333 rc = newDatabase(p->pBt);
3334 sqlite3BtreeLeave(p);
3335 return rc;
3339 ** Attempt to start a new transaction. A write-transaction
3340 ** is started if the second argument is nonzero, otherwise a read-
3341 ** transaction. If the second argument is 2 or more and exclusive
3342 ** transaction is started, meaning that no other process is allowed
3343 ** to access the database. A preexisting transaction may not be
3344 ** upgraded to exclusive by calling this routine a second time - the
3345 ** exclusivity flag only works for a new transaction.
3347 ** A write-transaction must be started before attempting any
3348 ** changes to the database. None of the following routines
3349 ** will work unless a transaction is started first:
3351 ** sqlite3BtreeCreateTable()
3352 ** sqlite3BtreeCreateIndex()
3353 ** sqlite3BtreeClearTable()
3354 ** sqlite3BtreeDropTable()
3355 ** sqlite3BtreeInsert()
3356 ** sqlite3BtreeDelete()
3357 ** sqlite3BtreeUpdateMeta()
3359 ** If an initial attempt to acquire the lock fails because of lock contention
3360 ** and the database was previously unlocked, then invoke the busy handler
3361 ** if there is one. But if there was previously a read-lock, do not
3362 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
3363 ** returned when there is already a read-lock in order to avoid a deadlock.
3365 ** Suppose there are two processes A and B. A has a read lock and B has
3366 ** a reserved lock. B tries to promote to exclusive but is blocked because
3367 ** of A's read lock. A tries to promote to reserved but is blocked by B.
3368 ** One or the other of the two processes must give way or there can be
3369 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
3370 ** when A already has a read lock, we encourage A to give up and let B
3371 ** proceed.
3373 int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
3374 BtShared *pBt = p->pBt;
3375 Pager *pPager = pBt->pPager;
3376 int rc = SQLITE_OK;
3378 sqlite3BtreeEnter(p);
3379 btreeIntegrity(p);
3381 /* If the btree is already in a write-transaction, or it
3382 ** is already in a read-transaction and a read-transaction
3383 ** is requested, this is a no-op.
3385 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
3386 goto trans_begun;
3388 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
3390 if( (p->db->flags & SQLITE_ResetDatabase)
3391 && sqlite3PagerIsreadonly(pPager)==0
3393 pBt->btsFlags &= ~BTS_READ_ONLY;
3396 /* Write transactions are not possible on a read-only database */
3397 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
3398 rc = SQLITE_READONLY;
3399 goto trans_begun;
3402 #ifndef SQLITE_OMIT_SHARED_CACHE
3404 sqlite3 *pBlock = 0;
3405 /* If another database handle has already opened a write transaction
3406 ** on this shared-btree structure and a second write transaction is
3407 ** requested, return SQLITE_LOCKED.
3409 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
3410 || (pBt->btsFlags & BTS_PENDING)!=0
3412 pBlock = pBt->pWriter->db;
3413 }else if( wrflag>1 ){
3414 BtLock *pIter;
3415 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
3416 if( pIter->pBtree!=p ){
3417 pBlock = pIter->pBtree->db;
3418 break;
3422 if( pBlock ){
3423 sqlite3ConnectionBlocked(p->db, pBlock);
3424 rc = SQLITE_LOCKED_SHAREDCACHE;
3425 goto trans_begun;
3428 #endif
3430 /* Any read-only or read-write transaction implies a read-lock on
3431 ** page 1. So if some other shared-cache client already has a write-lock
3432 ** on page 1, the transaction cannot be opened. */
3433 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
3434 if( SQLITE_OK!=rc ) goto trans_begun;
3436 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
3437 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
3438 do {
3439 sqlite3PagerWalDb(pPager, p->db);
3441 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3442 /* If transitioning from no transaction directly to a write transaction,
3443 ** block for the WRITER lock first if possible. */
3444 if( pBt->pPage1==0 && wrflag ){
3445 assert( pBt->inTransaction==TRANS_NONE );
3446 rc = sqlite3PagerWalWriteLock(pPager, 1);
3447 if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break;
3449 #endif
3451 /* Call lockBtree() until either pBt->pPage1 is populated or
3452 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
3453 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
3454 ** reading page 1 it discovers that the page-size of the database
3455 ** file is not pBt->pageSize. In this case lockBtree() will update
3456 ** pBt->pageSize to the page-size of the file on disk.
3458 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
3460 if( rc==SQLITE_OK && wrflag ){
3461 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
3462 rc = SQLITE_READONLY;
3463 }else{
3464 rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db));
3465 if( rc==SQLITE_OK ){
3466 rc = newDatabase(pBt);
3467 }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
3468 /* if there was no transaction opened when this function was
3469 ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
3470 ** code to SQLITE_BUSY. */
3471 rc = SQLITE_BUSY;
3476 if( rc!=SQLITE_OK ){
3477 (void)sqlite3PagerWalWriteLock(pPager, 0);
3478 unlockBtreeIfUnused(pBt);
3480 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
3481 btreeInvokeBusyHandler(pBt) );
3482 sqlite3PagerWalDb(pPager, 0);
3483 #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3484 if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
3485 #endif
3487 if( rc==SQLITE_OK ){
3488 if( p->inTrans==TRANS_NONE ){
3489 pBt->nTransaction++;
3490 #ifndef SQLITE_OMIT_SHARED_CACHE
3491 if( p->sharable ){
3492 assert( p->lock.pBtree==p && p->lock.iTable==1 );
3493 p->lock.eLock = READ_LOCK;
3494 p->lock.pNext = pBt->pLock;
3495 pBt->pLock = &p->lock;
3497 #endif
3499 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
3500 if( p->inTrans>pBt->inTransaction ){
3501 pBt->inTransaction = p->inTrans;
3503 if( wrflag ){
3504 MemPage *pPage1 = pBt->pPage1;
3505 #ifndef SQLITE_OMIT_SHARED_CACHE
3506 assert( !pBt->pWriter );
3507 pBt->pWriter = p;
3508 pBt->btsFlags &= ~BTS_EXCLUSIVE;
3509 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
3510 #endif
3512 /* If the db-size header field is incorrect (as it may be if an old
3513 ** client has been writing the database file), update it now. Doing
3514 ** this sooner rather than later means the database size can safely
3515 ** re-read the database size from page 1 if a savepoint or transaction
3516 ** rollback occurs within the transaction.
3518 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
3519 rc = sqlite3PagerWrite(pPage1->pDbPage);
3520 if( rc==SQLITE_OK ){
3521 put4byte(&pPage1->aData[28], pBt->nPage);
3527 trans_begun:
3528 if( rc==SQLITE_OK ){
3529 if( pSchemaVersion ){
3530 *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
3532 if( wrflag ){
3533 /* This call makes sure that the pager has the correct number of
3534 ** open savepoints. If the second parameter is greater than 0 and
3535 ** the sub-journal is not already open, then it will be opened here.
3537 rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint);
3541 btreeIntegrity(p);
3542 sqlite3BtreeLeave(p);
3543 return rc;
3546 #ifndef SQLITE_OMIT_AUTOVACUUM
3549 ** Set the pointer-map entries for all children of page pPage. Also, if
3550 ** pPage contains cells that point to overflow pages, set the pointer
3551 ** map entries for the overflow pages as well.
3553 static int setChildPtrmaps(MemPage *pPage){
3554 int i; /* Counter variable */
3555 int nCell; /* Number of cells in page pPage */
3556 int rc; /* Return code */
3557 BtShared *pBt = pPage->pBt;
3558 Pgno pgno = pPage->pgno;
3560 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3561 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3562 if( rc!=SQLITE_OK ) return rc;
3563 nCell = pPage->nCell;
3565 for(i=0; i<nCell; i++){
3566 u8 *pCell = findCell(pPage, i);
3568 ptrmapPutOvflPtr(pPage, pPage, pCell, &rc);
3570 if( !pPage->leaf ){
3571 Pgno childPgno = get4byte(pCell);
3572 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3576 if( !pPage->leaf ){
3577 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
3578 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3581 return rc;
3585 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
3586 ** that it points to iTo. Parameter eType describes the type of pointer to
3587 ** be modified, as follows:
3589 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
3590 ** page of pPage.
3592 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3593 ** page pointed to by one of the cells on pPage.
3595 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3596 ** overflow page in the list.
3598 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
3599 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3600 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
3601 if( eType==PTRMAP_OVERFLOW2 ){
3602 /* The pointer is always the first 4 bytes of the page in this case. */
3603 if( get4byte(pPage->aData)!=iFrom ){
3604 return SQLITE_CORRUPT_PAGE(pPage);
3606 put4byte(pPage->aData, iTo);
3607 }else{
3608 int i;
3609 int nCell;
3610 int rc;
3612 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3613 if( rc ) return rc;
3614 nCell = pPage->nCell;
3616 for(i=0; i<nCell; i++){
3617 u8 *pCell = findCell(pPage, i);
3618 if( eType==PTRMAP_OVERFLOW1 ){
3619 CellInfo info;
3620 pPage->xParseCell(pPage, pCell, &info);
3621 if( info.nLocal<info.nPayload ){
3622 if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
3623 return SQLITE_CORRUPT_PAGE(pPage);
3625 if( iFrom==get4byte(pCell+info.nSize-4) ){
3626 put4byte(pCell+info.nSize-4, iTo);
3627 break;
3630 }else{
3631 if( get4byte(pCell)==iFrom ){
3632 put4byte(pCell, iTo);
3633 break;
3638 if( i==nCell ){
3639 if( eType!=PTRMAP_BTREE ||
3640 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
3641 return SQLITE_CORRUPT_PAGE(pPage);
3643 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3646 return SQLITE_OK;
3651 ** Move the open database page pDbPage to location iFreePage in the
3652 ** database. The pDbPage reference remains valid.
3654 ** The isCommit flag indicates that there is no need to remember that
3655 ** the journal needs to be sync()ed before database page pDbPage->pgno
3656 ** can be written to. The caller has already promised not to write to that
3657 ** page.
3659 static int relocatePage(
3660 BtShared *pBt, /* Btree */
3661 MemPage *pDbPage, /* Open page to move */
3662 u8 eType, /* Pointer map 'type' entry for pDbPage */
3663 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
3664 Pgno iFreePage, /* The location to move pDbPage to */
3665 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
3667 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
3668 Pgno iDbPage = pDbPage->pgno;
3669 Pager *pPager = pBt->pPager;
3670 int rc;
3672 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3673 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
3674 assert( sqlite3_mutex_held(pBt->mutex) );
3675 assert( pDbPage->pBt==pBt );
3676 if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
3678 /* Move page iDbPage from its current location to page number iFreePage */
3679 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
3680 iDbPage, iFreePage, iPtrPage, eType));
3681 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
3682 if( rc!=SQLITE_OK ){
3683 return rc;
3685 pDbPage->pgno = iFreePage;
3687 /* If pDbPage was a btree-page, then it may have child pages and/or cells
3688 ** that point to overflow pages. The pointer map entries for all these
3689 ** pages need to be changed.
3691 ** If pDbPage is an overflow page, then the first 4 bytes may store a
3692 ** pointer to a subsequent overflow page. If this is the case, then
3693 ** the pointer map needs to be updated for the subsequent overflow page.
3695 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
3696 rc = setChildPtrmaps(pDbPage);
3697 if( rc!=SQLITE_OK ){
3698 return rc;
3700 }else{
3701 Pgno nextOvfl = get4byte(pDbPage->aData);
3702 if( nextOvfl!=0 ){
3703 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
3704 if( rc!=SQLITE_OK ){
3705 return rc;
3710 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3711 ** that it points at iFreePage. Also fix the pointer map entry for
3712 ** iPtrPage.
3714 if( eType!=PTRMAP_ROOTPAGE ){
3715 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
3716 if( rc!=SQLITE_OK ){
3717 return rc;
3719 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
3720 if( rc!=SQLITE_OK ){
3721 releasePage(pPtrPage);
3722 return rc;
3724 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
3725 releasePage(pPtrPage);
3726 if( rc==SQLITE_OK ){
3727 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
3730 return rc;
3733 /* Forward declaration required by incrVacuumStep(). */
3734 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
3737 ** Perform a single step of an incremental-vacuum. If successful, return
3738 ** SQLITE_OK. If there is no work to do (and therefore no point in
3739 ** calling this function again), return SQLITE_DONE. Or, if an error
3740 ** occurs, return some other error code.
3742 ** More specifically, this function attempts to re-organize the database so
3743 ** that the last page of the file currently in use is no longer in use.
3745 ** Parameter nFin is the number of pages that this database would contain
3746 ** were this function called until it returns SQLITE_DONE.
3748 ** If the bCommit parameter is non-zero, this function assumes that the
3749 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
3750 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
3751 ** operation, or false for an incremental vacuum.
3753 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
3754 Pgno nFreeList; /* Number of pages still on the free-list */
3755 int rc;
3757 assert( sqlite3_mutex_held(pBt->mutex) );
3758 assert( iLastPg>nFin );
3760 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
3761 u8 eType;
3762 Pgno iPtrPage;
3764 nFreeList = get4byte(&pBt->pPage1->aData[36]);
3765 if( nFreeList==0 ){
3766 return SQLITE_DONE;
3769 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3770 if( rc!=SQLITE_OK ){
3771 return rc;
3773 if( eType==PTRMAP_ROOTPAGE ){
3774 return SQLITE_CORRUPT_BKPT;
3777 if( eType==PTRMAP_FREEPAGE ){
3778 if( bCommit==0 ){
3779 /* Remove the page from the files free-list. This is not required
3780 ** if bCommit is non-zero. In that case, the free-list will be
3781 ** truncated to zero after this function returns, so it doesn't
3782 ** matter if it still contains some garbage entries.
3784 Pgno iFreePg;
3785 MemPage *pFreePg;
3786 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
3787 if( rc!=SQLITE_OK ){
3788 return rc;
3790 assert( iFreePg==iLastPg );
3791 releasePage(pFreePg);
3793 } else {
3794 Pgno iFreePg; /* Index of free page to move pLastPg to */
3795 MemPage *pLastPg;
3796 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
3797 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
3799 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
3800 if( rc!=SQLITE_OK ){
3801 return rc;
3804 /* If bCommit is zero, this loop runs exactly once and page pLastPg
3805 ** is swapped with the first free page pulled off the free list.
3807 ** On the other hand, if bCommit is greater than zero, then keep
3808 ** looping until a free-page located within the first nFin pages
3809 ** of the file is found.
3811 if( bCommit==0 ){
3812 eMode = BTALLOC_LE;
3813 iNear = nFin;
3815 do {
3816 MemPage *pFreePg;
3817 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
3818 if( rc!=SQLITE_OK ){
3819 releasePage(pLastPg);
3820 return rc;
3822 releasePage(pFreePg);
3823 }while( bCommit && iFreePg>nFin );
3824 assert( iFreePg<iLastPg );
3826 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
3827 releasePage(pLastPg);
3828 if( rc!=SQLITE_OK ){
3829 return rc;
3834 if( bCommit==0 ){
3835 do {
3836 iLastPg--;
3837 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
3838 pBt->bDoTruncate = 1;
3839 pBt->nPage = iLastPg;
3841 return SQLITE_OK;
3845 ** The database opened by the first argument is an auto-vacuum database
3846 ** nOrig pages in size containing nFree free pages. Return the expected
3847 ** size of the database in pages following an auto-vacuum operation.
3849 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
3850 int nEntry; /* Number of entries on one ptrmap page */
3851 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
3852 Pgno nFin; /* Return value */
3854 nEntry = pBt->usableSize/5;
3855 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
3856 nFin = nOrig - nFree - nPtrmap;
3857 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
3858 nFin--;
3860 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
3861 nFin--;
3864 return nFin;
3868 ** A write-transaction must be opened before calling this function.
3869 ** It performs a single unit of work towards an incremental vacuum.
3871 ** If the incremental vacuum is finished after this function has run,
3872 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
3873 ** SQLITE_OK is returned. Otherwise an SQLite error code.
3875 int sqlite3BtreeIncrVacuum(Btree *p){
3876 int rc;
3877 BtShared *pBt = p->pBt;
3879 sqlite3BtreeEnter(p);
3880 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
3881 if( !pBt->autoVacuum ){
3882 rc = SQLITE_DONE;
3883 }else{
3884 Pgno nOrig = btreePagecount(pBt);
3885 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
3886 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
3888 if( nOrig<nFin || nFree>=nOrig ){
3889 rc = SQLITE_CORRUPT_BKPT;
3890 }else if( nFree>0 ){
3891 rc = saveAllCursors(pBt, 0, 0);
3892 if( rc==SQLITE_OK ){
3893 invalidateAllOverflowCache(pBt);
3894 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
3896 if( rc==SQLITE_OK ){
3897 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3898 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
3900 }else{
3901 rc = SQLITE_DONE;
3904 sqlite3BtreeLeave(p);
3905 return rc;
3909 ** This routine is called prior to sqlite3PagerCommit when a transaction
3910 ** is committed for an auto-vacuum database.
3912 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
3913 ** the database file should be truncated to during the commit process.
3914 ** i.e. the database has been reorganized so that only the first *pnTrunc
3915 ** pages are in use.
3917 static int autoVacuumCommit(BtShared *pBt){
3918 int rc = SQLITE_OK;
3919 Pager *pPager = pBt->pPager;
3920 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
3922 assert( sqlite3_mutex_held(pBt->mutex) );
3923 invalidateAllOverflowCache(pBt);
3924 assert(pBt->autoVacuum);
3925 if( !pBt->incrVacuum ){
3926 Pgno nFin; /* Number of pages in database after autovacuuming */
3927 Pgno nFree; /* Number of pages on the freelist initially */
3928 Pgno iFree; /* The next page to be freed */
3929 Pgno nOrig; /* Database size before freeing */
3931 nOrig = btreePagecount(pBt);
3932 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
3933 /* It is not possible to create a database for which the final page
3934 ** is either a pointer-map page or the pending-byte page. If one
3935 ** is encountered, this indicates corruption.
3937 return SQLITE_CORRUPT_BKPT;
3940 nFree = get4byte(&pBt->pPage1->aData[36]);
3941 nFin = finalDbSize(pBt, nOrig, nFree);
3942 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
3943 if( nFin<nOrig ){
3944 rc = saveAllCursors(pBt, 0, 0);
3946 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
3947 rc = incrVacuumStep(pBt, nFin, iFree, 1);
3949 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
3950 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3951 put4byte(&pBt->pPage1->aData[32], 0);
3952 put4byte(&pBt->pPage1->aData[36], 0);
3953 put4byte(&pBt->pPage1->aData[28], nFin);
3954 pBt->bDoTruncate = 1;
3955 pBt->nPage = nFin;
3957 if( rc!=SQLITE_OK ){
3958 sqlite3PagerRollback(pPager);
3962 assert( nRef>=sqlite3PagerRefcount(pPager) );
3963 return rc;
3966 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
3967 # define setChildPtrmaps(x) SQLITE_OK
3968 #endif
3971 ** This routine does the first phase of a two-phase commit. This routine
3972 ** causes a rollback journal to be created (if it does not already exist)
3973 ** and populated with enough information so that if a power loss occurs
3974 ** the database can be restored to its original state by playing back
3975 ** the journal. Then the contents of the journal are flushed out to
3976 ** the disk. After the journal is safely on oxide, the changes to the
3977 ** database are written into the database file and flushed to oxide.
3978 ** At the end of this call, the rollback journal still exists on the
3979 ** disk and we are still holding all locks, so the transaction has not
3980 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
3981 ** commit process.
3983 ** This call is a no-op if no write-transaction is currently active on pBt.
3985 ** Otherwise, sync the database file for the btree pBt. zSuperJrnl points to
3986 ** the name of a super-journal file that should be written into the
3987 ** individual journal file, or is NULL, indicating no super-journal file
3988 ** (single database transaction).
3990 ** When this is called, the super-journal should already have been
3991 ** created, populated with this journal pointer and synced to disk.
3993 ** Once this is routine has returned, the only thing required to commit
3994 ** the write-transaction for this database file is to delete the journal.
3996 int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zSuperJrnl){
3997 int rc = SQLITE_OK;
3998 if( p->inTrans==TRANS_WRITE ){
3999 BtShared *pBt = p->pBt;
4000 sqlite3BtreeEnter(p);
4001 #ifndef SQLITE_OMIT_AUTOVACUUM
4002 if( pBt->autoVacuum ){
4003 rc = autoVacuumCommit(pBt);
4004 if( rc!=SQLITE_OK ){
4005 sqlite3BtreeLeave(p);
4006 return rc;
4009 if( pBt->bDoTruncate ){
4010 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
4012 #endif
4013 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0);
4014 sqlite3BtreeLeave(p);
4016 return rc;
4020 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
4021 ** at the conclusion of a transaction.
4023 static void btreeEndTransaction(Btree *p){
4024 BtShared *pBt = p->pBt;
4025 sqlite3 *db = p->db;
4026 assert( sqlite3BtreeHoldsMutex(p) );
4028 #ifndef SQLITE_OMIT_AUTOVACUUM
4029 pBt->bDoTruncate = 0;
4030 #endif
4031 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
4032 /* If there are other active statements that belong to this database
4033 ** handle, downgrade to a read-only transaction. The other statements
4034 ** may still be reading from the database. */
4035 downgradeAllSharedCacheTableLocks(p);
4036 p->inTrans = TRANS_READ;
4037 }else{
4038 /* If the handle had any kind of transaction open, decrement the
4039 ** transaction count of the shared btree. If the transaction count
4040 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
4041 ** call below will unlock the pager. */
4042 if( p->inTrans!=TRANS_NONE ){
4043 clearAllSharedCacheTableLocks(p);
4044 pBt->nTransaction--;
4045 if( 0==pBt->nTransaction ){
4046 pBt->inTransaction = TRANS_NONE;
4050 /* Set the current transaction state to TRANS_NONE and unlock the
4051 ** pager if this call closed the only read or write transaction. */
4052 p->inTrans = TRANS_NONE;
4053 unlockBtreeIfUnused(pBt);
4056 btreeIntegrity(p);
4060 ** Commit the transaction currently in progress.
4062 ** This routine implements the second phase of a 2-phase commit. The
4063 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
4064 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
4065 ** routine did all the work of writing information out to disk and flushing the
4066 ** contents so that they are written onto the disk platter. All this
4067 ** routine has to do is delete or truncate or zero the header in the
4068 ** the rollback journal (which causes the transaction to commit) and
4069 ** drop locks.
4071 ** Normally, if an error occurs while the pager layer is attempting to
4072 ** finalize the underlying journal file, this function returns an error and
4073 ** the upper layer will attempt a rollback. However, if the second argument
4074 ** is non-zero then this b-tree transaction is part of a multi-file
4075 ** transaction. In this case, the transaction has already been committed
4076 ** (by deleting a super-journal file) and the caller will ignore this
4077 ** functions return code. So, even if an error occurs in the pager layer,
4078 ** reset the b-tree objects internal state to indicate that the write
4079 ** transaction has been closed. This is quite safe, as the pager will have
4080 ** transitioned to the error state.
4082 ** This will release the write lock on the database file. If there
4083 ** are no active cursors, it also releases the read lock.
4085 int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
4087 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
4088 sqlite3BtreeEnter(p);
4089 btreeIntegrity(p);
4091 /* If the handle has a write-transaction open, commit the shared-btrees
4092 ** transaction and set the shared state to TRANS_READ.
4094 if( p->inTrans==TRANS_WRITE ){
4095 int rc;
4096 BtShared *pBt = p->pBt;
4097 assert( pBt->inTransaction==TRANS_WRITE );
4098 assert( pBt->nTransaction>0 );
4099 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
4100 if( rc!=SQLITE_OK && bCleanup==0 ){
4101 sqlite3BtreeLeave(p);
4102 return rc;
4104 p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
4105 pBt->inTransaction = TRANS_READ;
4106 btreeClearHasContent(pBt);
4109 btreeEndTransaction(p);
4110 sqlite3BtreeLeave(p);
4111 return SQLITE_OK;
4115 ** Do both phases of a commit.
4117 int sqlite3BtreeCommit(Btree *p){
4118 int rc;
4119 sqlite3BtreeEnter(p);
4120 rc = sqlite3BtreeCommitPhaseOne(p, 0);
4121 if( rc==SQLITE_OK ){
4122 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
4124 sqlite3BtreeLeave(p);
4125 return rc;
4129 ** This routine sets the state to CURSOR_FAULT and the error
4130 ** code to errCode for every cursor on any BtShared that pBtree
4131 ** references. Or if the writeOnly flag is set to 1, then only
4132 ** trip write cursors and leave read cursors unchanged.
4134 ** Every cursor is a candidate to be tripped, including cursors
4135 ** that belong to other database connections that happen to be
4136 ** sharing the cache with pBtree.
4138 ** This routine gets called when a rollback occurs. If the writeOnly
4139 ** flag is true, then only write-cursors need be tripped - read-only
4140 ** cursors save their current positions so that they may continue
4141 ** following the rollback. Or, if writeOnly is false, all cursors are
4142 ** tripped. In general, writeOnly is false if the transaction being
4143 ** rolled back modified the database schema. In this case b-tree root
4144 ** pages may be moved or deleted from the database altogether, making
4145 ** it unsafe for read cursors to continue.
4147 ** If the writeOnly flag is true and an error is encountered while
4148 ** saving the current position of a read-only cursor, all cursors,
4149 ** including all read-cursors are tripped.
4151 ** SQLITE_OK is returned if successful, or if an error occurs while
4152 ** saving a cursor position, an SQLite error code.
4154 int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
4155 BtCursor *p;
4156 int rc = SQLITE_OK;
4158 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
4159 if( pBtree ){
4160 sqlite3BtreeEnter(pBtree);
4161 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
4162 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
4163 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
4164 rc = saveCursorPosition(p);
4165 if( rc!=SQLITE_OK ){
4166 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
4167 break;
4170 }else{
4171 sqlite3BtreeClearCursor(p);
4172 p->eState = CURSOR_FAULT;
4173 p->skipNext = errCode;
4175 btreeReleaseAllCursorPages(p);
4177 sqlite3BtreeLeave(pBtree);
4179 return rc;
4183 ** Set the pBt->nPage field correctly, according to the current
4184 ** state of the database. Assume pBt->pPage1 is valid.
4186 static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){
4187 int nPage = get4byte(&pPage1->aData[28]);
4188 testcase( nPage==0 );
4189 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
4190 testcase( pBt->nPage!=nPage );
4191 pBt->nPage = nPage;
4195 ** Rollback the transaction in progress.
4197 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
4198 ** Only write cursors are tripped if writeOnly is true but all cursors are
4199 ** tripped if writeOnly is false. Any attempt to use
4200 ** a tripped cursor will result in an error.
4202 ** This will release the write lock on the database file. If there
4203 ** are no active cursors, it also releases the read lock.
4205 int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
4206 int rc;
4207 BtShared *pBt = p->pBt;
4208 MemPage *pPage1;
4210 assert( writeOnly==1 || writeOnly==0 );
4211 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
4212 sqlite3BtreeEnter(p);
4213 if( tripCode==SQLITE_OK ){
4214 rc = tripCode = saveAllCursors(pBt, 0, 0);
4215 if( rc ) writeOnly = 0;
4216 }else{
4217 rc = SQLITE_OK;
4219 if( tripCode ){
4220 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
4221 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
4222 if( rc2!=SQLITE_OK ) rc = rc2;
4224 btreeIntegrity(p);
4226 if( p->inTrans==TRANS_WRITE ){
4227 int rc2;
4229 assert( TRANS_WRITE==pBt->inTransaction );
4230 rc2 = sqlite3PagerRollback(pBt->pPager);
4231 if( rc2!=SQLITE_OK ){
4232 rc = rc2;
4235 /* The rollback may have destroyed the pPage1->aData value. So
4236 ** call btreeGetPage() on page 1 again to make
4237 ** sure pPage1->aData is set correctly. */
4238 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
4239 btreeSetNPage(pBt, pPage1);
4240 releasePageOne(pPage1);
4242 assert( countValidCursors(pBt, 1)==0 );
4243 pBt->inTransaction = TRANS_READ;
4244 btreeClearHasContent(pBt);
4247 btreeEndTransaction(p);
4248 sqlite3BtreeLeave(p);
4249 return rc;
4253 ** Start a statement subtransaction. The subtransaction can be rolled
4254 ** back independently of the main transaction. You must start a transaction
4255 ** before starting a subtransaction. The subtransaction is ended automatically
4256 ** if the main transaction commits or rolls back.
4258 ** Statement subtransactions are used around individual SQL statements
4259 ** that are contained within a BEGIN...COMMIT block. If a constraint
4260 ** error occurs within the statement, the effect of that one statement
4261 ** can be rolled back without having to rollback the entire transaction.
4263 ** A statement sub-transaction is implemented as an anonymous savepoint. The
4264 ** value passed as the second parameter is the total number of savepoints,
4265 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
4266 ** are no active savepoints and no other statement-transactions open,
4267 ** iStatement is 1. This anonymous savepoint can be released or rolled back
4268 ** using the sqlite3BtreeSavepoint() function.
4270 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
4271 int rc;
4272 BtShared *pBt = p->pBt;
4273 sqlite3BtreeEnter(p);
4274 assert( p->inTrans==TRANS_WRITE );
4275 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
4276 assert( iStatement>0 );
4277 assert( iStatement>p->db->nSavepoint );
4278 assert( pBt->inTransaction==TRANS_WRITE );
4279 /* At the pager level, a statement transaction is a savepoint with
4280 ** an index greater than all savepoints created explicitly using
4281 ** SQL statements. It is illegal to open, release or rollback any
4282 ** such savepoints while the statement transaction savepoint is active.
4284 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
4285 sqlite3BtreeLeave(p);
4286 return rc;
4290 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
4291 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
4292 ** savepoint identified by parameter iSavepoint, depending on the value
4293 ** of op.
4295 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
4296 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
4297 ** contents of the entire transaction are rolled back. This is different
4298 ** from a normal transaction rollback, as no locks are released and the
4299 ** transaction remains open.
4301 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
4302 int rc = SQLITE_OK;
4303 if( p && p->inTrans==TRANS_WRITE ){
4304 BtShared *pBt = p->pBt;
4305 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
4306 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
4307 sqlite3BtreeEnter(p);
4308 if( op==SAVEPOINT_ROLLBACK ){
4309 rc = saveAllCursors(pBt, 0, 0);
4311 if( rc==SQLITE_OK ){
4312 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
4314 if( rc==SQLITE_OK ){
4315 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
4316 pBt->nPage = 0;
4318 rc = newDatabase(pBt);
4319 btreeSetNPage(pBt, pBt->pPage1);
4321 /* pBt->nPage might be zero if the database was corrupt when
4322 ** the transaction was started. Otherwise, it must be at least 1. */
4323 assert( CORRUPT_DB || pBt->nPage>0 );
4325 sqlite3BtreeLeave(p);
4327 return rc;
4331 ** Create a new cursor for the BTree whose root is on the page
4332 ** iTable. If a read-only cursor is requested, it is assumed that
4333 ** the caller already has at least a read-only transaction open
4334 ** on the database already. If a write-cursor is requested, then
4335 ** the caller is assumed to have an open write transaction.
4337 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
4338 ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
4339 ** can be used for reading or for writing if other conditions for writing
4340 ** are also met. These are the conditions that must be met in order
4341 ** for writing to be allowed:
4343 ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
4345 ** 2: Other database connections that share the same pager cache
4346 ** but which are not in the READ_UNCOMMITTED state may not have
4347 ** cursors open with wrFlag==0 on the same table. Otherwise
4348 ** the changes made by this write cursor would be visible to
4349 ** the read cursors in the other database connection.
4351 ** 3: The database must be writable (not on read-only media)
4353 ** 4: There must be an active transaction.
4355 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
4356 ** is set. If FORDELETE is set, that is a hint to the implementation that
4357 ** this cursor will only be used to seek to and delete entries of an index
4358 ** as part of a larger DELETE statement. The FORDELETE hint is not used by
4359 ** this implementation. But in a hypothetical alternative storage engine
4360 ** in which index entries are automatically deleted when corresponding table
4361 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
4362 ** operations on this cursor can be no-ops and all READ operations can
4363 ** return a null row (2-bytes: 0x01 0x00).
4365 ** No checking is done to make sure that page iTable really is the
4366 ** root page of a b-tree. If it is not, then the cursor acquired
4367 ** will not work correctly.
4369 ** It is assumed that the sqlite3BtreeCursorZero() has been called
4370 ** on pCur to initialize the memory space prior to invoking this routine.
4372 static int btreeCursor(
4373 Btree *p, /* The btree */
4374 Pgno iTable, /* Root page of table to open */
4375 int wrFlag, /* 1 to write. 0 read-only */
4376 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4377 BtCursor *pCur /* Space for new cursor */
4379 BtShared *pBt = p->pBt; /* Shared b-tree handle */
4380 BtCursor *pX; /* Looping over other all cursors */
4382 assert( sqlite3BtreeHoldsMutex(p) );
4383 assert( wrFlag==0
4384 || wrFlag==BTREE_WRCSR
4385 || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
4388 /* The following assert statements verify that if this is a sharable
4389 ** b-tree database, the connection is holding the required table locks,
4390 ** and that no other connection has any open cursor that conflicts with
4391 ** this lock. The iTable<1 term disables the check for corrupt schemas. */
4392 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1))
4393 || iTable<1 );
4394 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
4396 /* Assert that the caller has opened the required transaction. */
4397 assert( p->inTrans>TRANS_NONE );
4398 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
4399 assert( pBt->pPage1 && pBt->pPage1->aData );
4400 assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
4402 if( wrFlag ){
4403 allocateTempSpace(pBt);
4404 if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
4406 if( iTable<=1 ){
4407 if( iTable<1 ){
4408 return SQLITE_CORRUPT_BKPT;
4409 }else if( btreePagecount(pBt)==0 ){
4410 assert( wrFlag==0 );
4411 iTable = 0;
4415 /* Now that no other errors can occur, finish filling in the BtCursor
4416 ** variables and link the cursor into the BtShared list. */
4417 pCur->pgnoRoot = iTable;
4418 pCur->iPage = -1;
4419 pCur->pKeyInfo = pKeyInfo;
4420 pCur->pBtree = p;
4421 pCur->pBt = pBt;
4422 pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
4423 pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
4424 /* If there are two or more cursors on the same btree, then all such
4425 ** cursors *must* have the BTCF_Multiple flag set. */
4426 for(pX=pBt->pCursor; pX; pX=pX->pNext){
4427 if( pX->pgnoRoot==iTable ){
4428 pX->curFlags |= BTCF_Multiple;
4429 pCur->curFlags |= BTCF_Multiple;
4432 pCur->pNext = pBt->pCursor;
4433 pBt->pCursor = pCur;
4434 pCur->eState = CURSOR_INVALID;
4435 return SQLITE_OK;
4437 static int btreeCursorWithLock(
4438 Btree *p, /* The btree */
4439 Pgno iTable, /* Root page of table to open */
4440 int wrFlag, /* 1 to write. 0 read-only */
4441 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4442 BtCursor *pCur /* Space for new cursor */
4444 int rc;
4445 sqlite3BtreeEnter(p);
4446 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4447 sqlite3BtreeLeave(p);
4448 return rc;
4450 int sqlite3BtreeCursor(
4451 Btree *p, /* The btree */
4452 Pgno iTable, /* Root page of table to open */
4453 int wrFlag, /* 1 to write. 0 read-only */
4454 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
4455 BtCursor *pCur /* Write new cursor here */
4457 if( p->sharable ){
4458 return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur);
4459 }else{
4460 return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4465 ** Return the size of a BtCursor object in bytes.
4467 ** This interfaces is needed so that users of cursors can preallocate
4468 ** sufficient storage to hold a cursor. The BtCursor object is opaque
4469 ** to users so they cannot do the sizeof() themselves - they must call
4470 ** this routine.
4472 int sqlite3BtreeCursorSize(void){
4473 return ROUND8(sizeof(BtCursor));
4477 ** Initialize memory that will be converted into a BtCursor object.
4479 ** The simple approach here would be to memset() the entire object
4480 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
4481 ** do not need to be zeroed and they are large, so we can save a lot
4482 ** of run-time by skipping the initialization of those elements.
4484 void sqlite3BtreeCursorZero(BtCursor *p){
4485 memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
4489 ** Close a cursor. The read lock on the database file is released
4490 ** when the last cursor is closed.
4492 int sqlite3BtreeCloseCursor(BtCursor *pCur){
4493 Btree *pBtree = pCur->pBtree;
4494 if( pBtree ){
4495 BtShared *pBt = pCur->pBt;
4496 sqlite3BtreeEnter(pBtree);
4497 assert( pBt->pCursor!=0 );
4498 if( pBt->pCursor==pCur ){
4499 pBt->pCursor = pCur->pNext;
4500 }else{
4501 BtCursor *pPrev = pBt->pCursor;
4503 if( pPrev->pNext==pCur ){
4504 pPrev->pNext = pCur->pNext;
4505 break;
4507 pPrev = pPrev->pNext;
4508 }while( ALWAYS(pPrev) );
4510 btreeReleaseAllCursorPages(pCur);
4511 unlockBtreeIfUnused(pBt);
4512 sqlite3_free(pCur->aOverflow);
4513 sqlite3_free(pCur->pKey);
4514 sqlite3BtreeLeave(pBtree);
4515 pCur->pBtree = 0;
4517 return SQLITE_OK;
4521 ** Make sure the BtCursor* given in the argument has a valid
4522 ** BtCursor.info structure. If it is not already valid, call
4523 ** btreeParseCell() to fill it in.
4525 ** BtCursor.info is a cache of the information in the current cell.
4526 ** Using this cache reduces the number of calls to btreeParseCell().
4528 #ifndef NDEBUG
4529 static int cellInfoEqual(CellInfo *a, CellInfo *b){
4530 if( a->nKey!=b->nKey ) return 0;
4531 if( a->pPayload!=b->pPayload ) return 0;
4532 if( a->nPayload!=b->nPayload ) return 0;
4533 if( a->nLocal!=b->nLocal ) return 0;
4534 if( a->nSize!=b->nSize ) return 0;
4535 return 1;
4537 static void assertCellInfo(BtCursor *pCur){
4538 CellInfo info;
4539 memset(&info, 0, sizeof(info));
4540 btreeParseCell(pCur->pPage, pCur->ix, &info);
4541 assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
4543 #else
4544 #define assertCellInfo(x)
4545 #endif
4546 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
4547 if( pCur->info.nSize==0 ){
4548 pCur->curFlags |= BTCF_ValidNKey;
4549 btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
4550 }else{
4551 assertCellInfo(pCur);
4555 #ifndef NDEBUG /* The next routine used only within assert() statements */
4557 ** Return true if the given BtCursor is valid. A valid cursor is one
4558 ** that is currently pointing to a row in a (non-empty) table.
4559 ** This is a verification routine is used only within assert() statements.
4561 int sqlite3BtreeCursorIsValid(BtCursor *pCur){
4562 return pCur && pCur->eState==CURSOR_VALID;
4564 #endif /* NDEBUG */
4565 int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
4566 assert( pCur!=0 );
4567 return pCur->eState==CURSOR_VALID;
4571 ** Return the value of the integer key or "rowid" for a table btree.
4572 ** This routine is only valid for a cursor that is pointing into a
4573 ** ordinary table btree. If the cursor points to an index btree or
4574 ** is invalid, the result of this routine is undefined.
4576 i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
4577 assert( cursorHoldsMutex(pCur) );
4578 assert( pCur->eState==CURSOR_VALID );
4579 assert( pCur->curIntKey );
4580 getCellInfo(pCur);
4581 return pCur->info.nKey;
4585 ** Pin or unpin a cursor.
4587 void sqlite3BtreeCursorPin(BtCursor *pCur){
4588 assert( (pCur->curFlags & BTCF_Pinned)==0 );
4589 pCur->curFlags |= BTCF_Pinned;
4591 void sqlite3BtreeCursorUnpin(BtCursor *pCur){
4592 assert( (pCur->curFlags & BTCF_Pinned)!=0 );
4593 pCur->curFlags &= ~BTCF_Pinned;
4596 #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
4598 ** Return the offset into the database file for the start of the
4599 ** payload to which the cursor is pointing.
4601 i64 sqlite3BtreeOffset(BtCursor *pCur){
4602 assert( cursorHoldsMutex(pCur) );
4603 assert( pCur->eState==CURSOR_VALID );
4604 getCellInfo(pCur);
4605 return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
4606 (i64)(pCur->info.pPayload - pCur->pPage->aData);
4608 #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
4611 ** Return the number of bytes of payload for the entry that pCur is
4612 ** currently pointing to. For table btrees, this will be the amount
4613 ** of data. For index btrees, this will be the size of the key.
4615 ** The caller must guarantee that the cursor is pointing to a non-NULL
4616 ** valid entry. In other words, the calling procedure must guarantee
4617 ** that the cursor has Cursor.eState==CURSOR_VALID.
4619 u32 sqlite3BtreePayloadSize(BtCursor *pCur){
4620 assert( cursorHoldsMutex(pCur) );
4621 assert( pCur->eState==CURSOR_VALID );
4622 getCellInfo(pCur);
4623 return pCur->info.nPayload;
4627 ** Return an upper bound on the size of any record for the table
4628 ** that the cursor is pointing into.
4630 ** This is an optimization. Everything will still work if this
4631 ** routine always returns 2147483647 (which is the largest record
4632 ** that SQLite can handle) or more. But returning a smaller value might
4633 ** prevent large memory allocations when trying to interpret a
4634 ** corrupt datrabase.
4636 ** The current implementation merely returns the size of the underlying
4637 ** database file.
4639 sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){
4640 assert( cursorHoldsMutex(pCur) );
4641 assert( pCur->eState==CURSOR_VALID );
4642 return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
4646 ** Given the page number of an overflow page in the database (parameter
4647 ** ovfl), this function finds the page number of the next page in the
4648 ** linked list of overflow pages. If possible, it uses the auto-vacuum
4649 ** pointer-map data instead of reading the content of page ovfl to do so.
4651 ** If an error occurs an SQLite error code is returned. Otherwise:
4653 ** The page number of the next overflow page in the linked list is
4654 ** written to *pPgnoNext. If page ovfl is the last page in its linked
4655 ** list, *pPgnoNext is set to zero.
4657 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
4658 ** to page number pOvfl was obtained, then *ppPage is set to point to that
4659 ** reference. It is the responsibility of the caller to call releasePage()
4660 ** on *ppPage to free the reference. In no reference was obtained (because
4661 ** the pointer-map was used to obtain the value for *pPgnoNext), then
4662 ** *ppPage is set to zero.
4664 static int getOverflowPage(
4665 BtShared *pBt, /* The database file */
4666 Pgno ovfl, /* Current overflow page number */
4667 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
4668 Pgno *pPgnoNext /* OUT: Next overflow page number */
4670 Pgno next = 0;
4671 MemPage *pPage = 0;
4672 int rc = SQLITE_OK;
4674 assert( sqlite3_mutex_held(pBt->mutex) );
4675 assert(pPgnoNext);
4677 #ifndef SQLITE_OMIT_AUTOVACUUM
4678 /* Try to find the next page in the overflow list using the
4679 ** autovacuum pointer-map pages. Guess that the next page in
4680 ** the overflow list is page number (ovfl+1). If that guess turns
4681 ** out to be wrong, fall back to loading the data of page
4682 ** number ovfl to determine the next page number.
4684 if( pBt->autoVacuum ){
4685 Pgno pgno;
4686 Pgno iGuess = ovfl+1;
4687 u8 eType;
4689 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
4690 iGuess++;
4693 if( iGuess<=btreePagecount(pBt) ){
4694 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
4695 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
4696 next = iGuess;
4697 rc = SQLITE_DONE;
4701 #endif
4703 assert( next==0 || rc==SQLITE_DONE );
4704 if( rc==SQLITE_OK ){
4705 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
4706 assert( rc==SQLITE_OK || pPage==0 );
4707 if( rc==SQLITE_OK ){
4708 next = get4byte(pPage->aData);
4712 *pPgnoNext = next;
4713 if( ppPage ){
4714 *ppPage = pPage;
4715 }else{
4716 releasePage(pPage);
4718 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
4722 ** Copy data from a buffer to a page, or from a page to a buffer.
4724 ** pPayload is a pointer to data stored on database page pDbPage.
4725 ** If argument eOp is false, then nByte bytes of data are copied
4726 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4727 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4728 ** of data are copied from the buffer pBuf to pPayload.
4730 ** SQLITE_OK is returned on success, otherwise an error code.
4732 static int copyPayload(
4733 void *pPayload, /* Pointer to page data */
4734 void *pBuf, /* Pointer to buffer */
4735 int nByte, /* Number of bytes to copy */
4736 int eOp, /* 0 -> copy from page, 1 -> copy to page */
4737 DbPage *pDbPage /* Page containing pPayload */
4739 if( eOp ){
4740 /* Copy data from buffer to page (a write operation) */
4741 int rc = sqlite3PagerWrite(pDbPage);
4742 if( rc!=SQLITE_OK ){
4743 return rc;
4745 memcpy(pPayload, pBuf, nByte);
4746 }else{
4747 /* Copy data from page to buffer (a read operation) */
4748 memcpy(pBuf, pPayload, nByte);
4750 return SQLITE_OK;
4754 ** This function is used to read or overwrite payload information
4755 ** for the entry that the pCur cursor is pointing to. The eOp
4756 ** argument is interpreted as follows:
4758 ** 0: The operation is a read. Populate the overflow cache.
4759 ** 1: The operation is a write. Populate the overflow cache.
4761 ** A total of "amt" bytes are read or written beginning at "offset".
4762 ** Data is read to or from the buffer pBuf.
4764 ** The content being read or written might appear on the main page
4765 ** or be scattered out on multiple overflow pages.
4767 ** If the current cursor entry uses one or more overflow pages
4768 ** this function may allocate space for and lazily populate
4769 ** the overflow page-list cache array (BtCursor.aOverflow).
4770 ** Subsequent calls use this cache to make seeking to the supplied offset
4771 ** more efficient.
4773 ** Once an overflow page-list cache has been allocated, it must be
4774 ** invalidated if some other cursor writes to the same table, or if
4775 ** the cursor is moved to a different row. Additionally, in auto-vacuum
4776 ** mode, the following events may invalidate an overflow page-list cache.
4778 ** * An incremental vacuum,
4779 ** * A commit in auto_vacuum="full" mode,
4780 ** * Creating a table (may require moving an overflow page).
4782 static int accessPayload(
4783 BtCursor *pCur, /* Cursor pointing to entry to read from */
4784 u32 offset, /* Begin reading this far into payload */
4785 u32 amt, /* Read this many bytes */
4786 unsigned char *pBuf, /* Write the bytes into this buffer */
4787 int eOp /* zero to read. non-zero to write. */
4789 unsigned char *aPayload;
4790 int rc = SQLITE_OK;
4791 int iIdx = 0;
4792 MemPage *pPage = pCur->pPage; /* Btree page of current entry */
4793 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
4794 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4795 unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
4796 #endif
4798 assert( pPage );
4799 assert( eOp==0 || eOp==1 );
4800 assert( pCur->eState==CURSOR_VALID );
4801 assert( pCur->ix<pPage->nCell );
4802 assert( cursorHoldsMutex(pCur) );
4804 getCellInfo(pCur);
4805 aPayload = pCur->info.pPayload;
4806 assert( offset+amt <= pCur->info.nPayload );
4808 assert( aPayload > pPage->aData );
4809 if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
4810 /* Trying to read or write past the end of the data is an error. The
4811 ** conditional above is really:
4812 ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
4813 ** but is recast into its current form to avoid integer overflow problems
4815 return SQLITE_CORRUPT_PAGE(pPage);
4818 /* Check if data must be read/written to/from the btree page itself. */
4819 if( offset<pCur->info.nLocal ){
4820 int a = amt;
4821 if( a+offset>pCur->info.nLocal ){
4822 a = pCur->info.nLocal - offset;
4824 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
4825 offset = 0;
4826 pBuf += a;
4827 amt -= a;
4828 }else{
4829 offset -= pCur->info.nLocal;
4833 if( rc==SQLITE_OK && amt>0 ){
4834 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
4835 Pgno nextPage;
4837 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
4839 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
4841 ** The aOverflow[] array is sized at one entry for each overflow page
4842 ** in the overflow chain. The page number of the first overflow page is
4843 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
4844 ** means "not yet known" (the cache is lazily populated).
4846 if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
4847 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
4848 if( pCur->aOverflow==0
4849 || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
4851 Pgno *aNew = (Pgno*)sqlite3Realloc(
4852 pCur->aOverflow, nOvfl*2*sizeof(Pgno)
4854 if( aNew==0 ){
4855 return SQLITE_NOMEM_BKPT;
4856 }else{
4857 pCur->aOverflow = aNew;
4860 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
4861 pCur->curFlags |= BTCF_ValidOvfl;
4862 }else{
4863 /* If the overflow page-list cache has been allocated and the
4864 ** entry for the first required overflow page is valid, skip
4865 ** directly to it.
4867 if( pCur->aOverflow[offset/ovflSize] ){
4868 iIdx = (offset/ovflSize);
4869 nextPage = pCur->aOverflow[iIdx];
4870 offset = (offset%ovflSize);
4874 assert( rc==SQLITE_OK && amt>0 );
4875 while( nextPage ){
4876 /* If required, populate the overflow page-list cache. */
4877 if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPT;
4878 assert( pCur->aOverflow[iIdx]==0
4879 || pCur->aOverflow[iIdx]==nextPage
4880 || CORRUPT_DB );
4881 pCur->aOverflow[iIdx] = nextPage;
4883 if( offset>=ovflSize ){
4884 /* The only reason to read this page is to obtain the page
4885 ** number for the next page in the overflow chain. The page
4886 ** data is not required. So first try to lookup the overflow
4887 ** page-list cache, if any, then fall back to the getOverflowPage()
4888 ** function.
4890 assert( pCur->curFlags & BTCF_ValidOvfl );
4891 assert( pCur->pBtree->db==pBt->db );
4892 if( pCur->aOverflow[iIdx+1] ){
4893 nextPage = pCur->aOverflow[iIdx+1];
4894 }else{
4895 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
4897 offset -= ovflSize;
4898 }else{
4899 /* Need to read this page properly. It contains some of the
4900 ** range of data that is being read (eOp==0) or written (eOp!=0).
4902 int a = amt;
4903 if( a + offset > ovflSize ){
4904 a = ovflSize - offset;
4907 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4908 /* If all the following are true:
4910 ** 1) this is a read operation, and
4911 ** 2) data is required from the start of this overflow page, and
4912 ** 3) there are no dirty pages in the page-cache
4913 ** 4) the database is file-backed, and
4914 ** 5) the page is not in the WAL file
4915 ** 6) at least 4 bytes have already been read into the output buffer
4917 ** then data can be read directly from the database file into the
4918 ** output buffer, bypassing the page-cache altogether. This speeds
4919 ** up loading large records that span many overflow pages.
4921 if( eOp==0 /* (1) */
4922 && offset==0 /* (2) */
4923 && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */
4924 && &pBuf[-4]>=pBufStart /* (6) */
4926 sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
4927 u8 aSave[4];
4928 u8 *aWrite = &pBuf[-4];
4929 assert( aWrite>=pBufStart ); /* due to (6) */
4930 memcpy(aSave, aWrite, 4);
4931 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
4932 if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT;
4933 nextPage = get4byte(aWrite);
4934 memcpy(aWrite, aSave, 4);
4935 }else
4936 #endif
4939 DbPage *pDbPage;
4940 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
4941 (eOp==0 ? PAGER_GET_READONLY : 0)
4943 if( rc==SQLITE_OK ){
4944 aPayload = sqlite3PagerGetData(pDbPage);
4945 nextPage = get4byte(aPayload);
4946 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
4947 sqlite3PagerUnref(pDbPage);
4948 offset = 0;
4951 amt -= a;
4952 if( amt==0 ) return rc;
4953 pBuf += a;
4955 if( rc ) break;
4956 iIdx++;
4960 if( rc==SQLITE_OK && amt>0 ){
4961 /* Overflow chain ends prematurely */
4962 return SQLITE_CORRUPT_PAGE(pPage);
4964 return rc;
4968 ** Read part of the payload for the row at which that cursor pCur is currently
4969 ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
4970 ** begins at "offset".
4972 ** pCur can be pointing to either a table or an index b-tree.
4973 ** If pointing to a table btree, then the content section is read. If
4974 ** pCur is pointing to an index b-tree then the key section is read.
4976 ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
4977 ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
4978 ** cursor might be invalid or might need to be restored before being read.
4980 ** Return SQLITE_OK on success or an error code if anything goes
4981 ** wrong. An error is returned if "offset+amt" is larger than
4982 ** the available payload.
4984 int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
4985 assert( cursorHoldsMutex(pCur) );
4986 assert( pCur->eState==CURSOR_VALID );
4987 assert( pCur->iPage>=0 && pCur->pPage );
4988 assert( pCur->ix<pCur->pPage->nCell );
4989 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
4993 ** This variant of sqlite3BtreePayload() works even if the cursor has not
4994 ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
4995 ** interface.
4997 #ifndef SQLITE_OMIT_INCRBLOB
4998 static SQLITE_NOINLINE int accessPayloadChecked(
4999 BtCursor *pCur,
5000 u32 offset,
5001 u32 amt,
5002 void *pBuf
5004 int rc;
5005 if ( pCur->eState==CURSOR_INVALID ){
5006 return SQLITE_ABORT;
5008 assert( cursorOwnsBtShared(pCur) );
5009 rc = btreeRestoreCursorPosition(pCur);
5010 return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
5012 int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5013 if( pCur->eState==CURSOR_VALID ){
5014 assert( cursorOwnsBtShared(pCur) );
5015 return accessPayload(pCur, offset, amt, pBuf, 0);
5016 }else{
5017 return accessPayloadChecked(pCur, offset, amt, pBuf);
5020 #endif /* SQLITE_OMIT_INCRBLOB */
5023 ** Return a pointer to payload information from the entry that the
5024 ** pCur cursor is pointing to. The pointer is to the beginning of
5025 ** the key if index btrees (pPage->intKey==0) and is the data for
5026 ** table btrees (pPage->intKey==1). The number of bytes of available
5027 ** key/data is written into *pAmt. If *pAmt==0, then the value
5028 ** returned will not be a valid pointer.
5030 ** This routine is an optimization. It is common for the entire key
5031 ** and data to fit on the local page and for there to be no overflow
5032 ** pages. When that is so, this routine can be used to access the
5033 ** key and data without making a copy. If the key and/or data spills
5034 ** onto overflow pages, then accessPayload() must be used to reassemble
5035 ** the key/data and copy it into a preallocated buffer.
5037 ** The pointer returned by this routine looks directly into the cached
5038 ** page of the database. The data might change or move the next time
5039 ** any btree routine is called.
5041 static const void *fetchPayload(
5042 BtCursor *pCur, /* Cursor pointing to entry to read from */
5043 u32 *pAmt /* Write the number of available bytes here */
5045 int amt;
5046 assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
5047 assert( pCur->eState==CURSOR_VALID );
5048 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5049 assert( cursorOwnsBtShared(pCur) );
5050 assert( pCur->ix<pCur->pPage->nCell );
5051 assert( pCur->info.nSize>0 );
5052 assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
5053 assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
5054 amt = pCur->info.nLocal;
5055 if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
5056 /* There is too little space on the page for the expected amount
5057 ** of local content. Database must be corrupt. */
5058 assert( CORRUPT_DB );
5059 amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
5061 *pAmt = (u32)amt;
5062 return (void*)pCur->info.pPayload;
5067 ** For the entry that cursor pCur is point to, return as
5068 ** many bytes of the key or data as are available on the local
5069 ** b-tree page. Write the number of available bytes into *pAmt.
5071 ** The pointer returned is ephemeral. The key/data may move
5072 ** or be destroyed on the next call to any Btree routine,
5073 ** including calls from other threads against the same cache.
5074 ** Hence, a mutex on the BtShared should be held prior to calling
5075 ** this routine.
5077 ** These routines is used to get quick access to key and data
5078 ** in the common case where no overflow pages are used.
5080 const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
5081 return fetchPayload(pCur, pAmt);
5086 ** Move the cursor down to a new child page. The newPgno argument is the
5087 ** page number of the child page to move to.
5089 ** This function returns SQLITE_CORRUPT if the page-header flags field of
5090 ** the new child page does not match the flags field of the parent (i.e.
5091 ** if an intkey page appears to be the parent of a non-intkey page, or
5092 ** vice-versa).
5094 static int moveToChild(BtCursor *pCur, u32 newPgno){
5095 BtShared *pBt = pCur->pBt;
5097 assert( cursorOwnsBtShared(pCur) );
5098 assert( pCur->eState==CURSOR_VALID );
5099 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
5100 assert( pCur->iPage>=0 );
5101 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
5102 return SQLITE_CORRUPT_BKPT;
5104 pCur->info.nSize = 0;
5105 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5106 pCur->aiIdx[pCur->iPage] = pCur->ix;
5107 pCur->apPage[pCur->iPage] = pCur->pPage;
5108 pCur->ix = 0;
5109 pCur->iPage++;
5110 return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
5113 #ifdef SQLITE_DEBUG
5115 ** Page pParent is an internal (non-leaf) tree page. This function
5116 ** asserts that page number iChild is the left-child if the iIdx'th
5117 ** cell in page pParent. Or, if iIdx is equal to the total number of
5118 ** cells in pParent, that page number iChild is the right-child of
5119 ** the page.
5121 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
5122 if( CORRUPT_DB ) return; /* The conditions tested below might not be true
5123 ** in a corrupt database */
5124 assert( iIdx<=pParent->nCell );
5125 if( iIdx==pParent->nCell ){
5126 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
5127 }else{
5128 assert( get4byte(findCell(pParent, iIdx))==iChild );
5131 #else
5132 # define assertParentIndex(x,y,z)
5133 #endif
5136 ** Move the cursor up to the parent page.
5138 ** pCur->idx is set to the cell index that contains the pointer
5139 ** to the page we are coming from. If we are coming from the
5140 ** right-most child page then pCur->idx is set to one more than
5141 ** the largest cell index.
5143 static void moveToParent(BtCursor *pCur){
5144 MemPage *pLeaf;
5145 assert( cursorOwnsBtShared(pCur) );
5146 assert( pCur->eState==CURSOR_VALID );
5147 assert( pCur->iPage>0 );
5148 assert( pCur->pPage );
5149 assertParentIndex(
5150 pCur->apPage[pCur->iPage-1],
5151 pCur->aiIdx[pCur->iPage-1],
5152 pCur->pPage->pgno
5154 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
5155 pCur->info.nSize = 0;
5156 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5157 pCur->ix = pCur->aiIdx[pCur->iPage-1];
5158 pLeaf = pCur->pPage;
5159 pCur->pPage = pCur->apPage[--pCur->iPage];
5160 releasePageNotNull(pLeaf);
5164 ** Move the cursor to point to the root page of its b-tree structure.
5166 ** If the table has a virtual root page, then the cursor is moved to point
5167 ** to the virtual root page instead of the actual root page. A table has a
5168 ** virtual root page when the actual root page contains no cells and a
5169 ** single child page. This can only happen with the table rooted at page 1.
5171 ** If the b-tree structure is empty, the cursor state is set to
5172 ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
5173 ** the cursor is set to point to the first cell located on the root
5174 ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
5176 ** If this function returns successfully, it may be assumed that the
5177 ** page-header flags indicate that the [virtual] root-page is the expected
5178 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
5179 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
5180 ** indicating a table b-tree, or if the caller did specify a KeyInfo
5181 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
5182 ** b-tree).
5184 static int moveToRoot(BtCursor *pCur){
5185 MemPage *pRoot;
5186 int rc = SQLITE_OK;
5188 assert( cursorOwnsBtShared(pCur) );
5189 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
5190 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
5191 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
5192 assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
5193 assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
5195 if( pCur->iPage>=0 ){
5196 if( pCur->iPage ){
5197 releasePageNotNull(pCur->pPage);
5198 while( --pCur->iPage ){
5199 releasePageNotNull(pCur->apPage[pCur->iPage]);
5201 pCur->pPage = pCur->apPage[0];
5202 goto skip_init;
5204 }else if( pCur->pgnoRoot==0 ){
5205 pCur->eState = CURSOR_INVALID;
5206 return SQLITE_EMPTY;
5207 }else{
5208 assert( pCur->iPage==(-1) );
5209 if( pCur->eState>=CURSOR_REQUIRESEEK ){
5210 if( pCur->eState==CURSOR_FAULT ){
5211 assert( pCur->skipNext!=SQLITE_OK );
5212 return pCur->skipNext;
5214 sqlite3BtreeClearCursor(pCur);
5216 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
5217 0, pCur->curPagerFlags);
5218 if( rc!=SQLITE_OK ){
5219 pCur->eState = CURSOR_INVALID;
5220 return rc;
5222 pCur->iPage = 0;
5223 pCur->curIntKey = pCur->pPage->intKey;
5225 pRoot = pCur->pPage;
5226 assert( pRoot->pgno==pCur->pgnoRoot );
5228 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
5229 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
5230 ** NULL, the caller expects a table b-tree. If this is not the case,
5231 ** return an SQLITE_CORRUPT error.
5233 ** Earlier versions of SQLite assumed that this test could not fail
5234 ** if the root page was already loaded when this function was called (i.e.
5235 ** if pCur->iPage>=0). But this is not so if the database is corrupted
5236 ** in such a way that page pRoot is linked into a second b-tree table
5237 ** (or the freelist). */
5238 assert( pRoot->intKey==1 || pRoot->intKey==0 );
5239 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
5240 return SQLITE_CORRUPT_PAGE(pCur->pPage);
5243 skip_init:
5244 pCur->ix = 0;
5245 pCur->info.nSize = 0;
5246 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
5248 pRoot = pCur->pPage;
5249 if( pRoot->nCell>0 ){
5250 pCur->eState = CURSOR_VALID;
5251 }else if( !pRoot->leaf ){
5252 Pgno subpage;
5253 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
5254 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
5255 pCur->eState = CURSOR_VALID;
5256 rc = moveToChild(pCur, subpage);
5257 }else{
5258 pCur->eState = CURSOR_INVALID;
5259 rc = SQLITE_EMPTY;
5261 return rc;
5265 ** Move the cursor down to the left-most leaf entry beneath the
5266 ** entry to which it is currently pointing.
5268 ** The left-most leaf is the one with the smallest key - the first
5269 ** in ascending order.
5271 static int moveToLeftmost(BtCursor *pCur){
5272 Pgno pgno;
5273 int rc = SQLITE_OK;
5274 MemPage *pPage;
5276 assert( cursorOwnsBtShared(pCur) );
5277 assert( pCur->eState==CURSOR_VALID );
5278 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
5279 assert( pCur->ix<pPage->nCell );
5280 pgno = get4byte(findCell(pPage, pCur->ix));
5281 rc = moveToChild(pCur, pgno);
5283 return rc;
5287 ** Move the cursor down to the right-most leaf entry beneath the
5288 ** page to which it is currently pointing. Notice the difference
5289 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
5290 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
5291 ** finds the right-most entry beneath the *page*.
5293 ** The right-most entry is the one with the largest key - the last
5294 ** key in ascending order.
5296 static int moveToRightmost(BtCursor *pCur){
5297 Pgno pgno;
5298 int rc = SQLITE_OK;
5299 MemPage *pPage = 0;
5301 assert( cursorOwnsBtShared(pCur) );
5302 assert( pCur->eState==CURSOR_VALID );
5303 while( !(pPage = pCur->pPage)->leaf ){
5304 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5305 pCur->ix = pPage->nCell;
5306 rc = moveToChild(pCur, pgno);
5307 if( rc ) return rc;
5309 pCur->ix = pPage->nCell-1;
5310 assert( pCur->info.nSize==0 );
5311 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
5312 return SQLITE_OK;
5315 /* Move the cursor to the first entry in the table. Return SQLITE_OK
5316 ** on success. Set *pRes to 0 if the cursor actually points to something
5317 ** or set *pRes to 1 if the table is empty.
5319 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
5320 int rc;
5322 assert( cursorOwnsBtShared(pCur) );
5323 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5324 rc = moveToRoot(pCur);
5325 if( rc==SQLITE_OK ){
5326 assert( pCur->pPage->nCell>0 );
5327 *pRes = 0;
5328 rc = moveToLeftmost(pCur);
5329 }else if( rc==SQLITE_EMPTY ){
5330 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5331 *pRes = 1;
5332 rc = SQLITE_OK;
5334 return rc;
5337 /* Move the cursor to the last entry in the table. Return SQLITE_OK
5338 ** on success. Set *pRes to 0 if the cursor actually points to something
5339 ** or set *pRes to 1 if the table is empty.
5341 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
5342 int rc;
5344 assert( cursorOwnsBtShared(pCur) );
5345 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5347 /* If the cursor already points to the last entry, this is a no-op. */
5348 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
5349 #ifdef SQLITE_DEBUG
5350 /* This block serves to assert() that the cursor really does point
5351 ** to the last entry in the b-tree. */
5352 int ii;
5353 for(ii=0; ii<pCur->iPage; ii++){
5354 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
5356 assert( pCur->ix==pCur->pPage->nCell-1 );
5357 assert( pCur->pPage->leaf );
5358 #endif
5359 *pRes = 0;
5360 return SQLITE_OK;
5363 rc = moveToRoot(pCur);
5364 if( rc==SQLITE_OK ){
5365 assert( pCur->eState==CURSOR_VALID );
5366 *pRes = 0;
5367 rc = moveToRightmost(pCur);
5368 if( rc==SQLITE_OK ){
5369 pCur->curFlags |= BTCF_AtLast;
5370 }else{
5371 pCur->curFlags &= ~BTCF_AtLast;
5373 }else if( rc==SQLITE_EMPTY ){
5374 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5375 *pRes = 1;
5376 rc = SQLITE_OK;
5378 return rc;
5381 /* Move the cursor so that it points to an entry near the key
5382 ** specified by pIdxKey or intKey. Return a success code.
5384 ** For INTKEY tables, the intKey parameter is used. pIdxKey
5385 ** must be NULL. For index tables, pIdxKey is used and intKey
5386 ** is ignored.
5388 ** If an exact match is not found, then the cursor is always
5389 ** left pointing at a leaf page which would hold the entry if it
5390 ** were present. The cursor might point to an entry that comes
5391 ** before or after the key.
5393 ** An integer is written into *pRes which is the result of
5394 ** comparing the key with the entry to which the cursor is
5395 ** pointing. The meaning of the integer written into
5396 ** *pRes is as follows:
5398 ** *pRes<0 The cursor is left pointing at an entry that
5399 ** is smaller than intKey/pIdxKey or if the table is empty
5400 ** and the cursor is therefore left point to nothing.
5402 ** *pRes==0 The cursor is left pointing at an entry that
5403 ** exactly matches intKey/pIdxKey.
5405 ** *pRes>0 The cursor is left pointing at an entry that
5406 ** is larger than intKey/pIdxKey.
5408 ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
5409 ** exists an entry in the table that exactly matches pIdxKey.
5411 int sqlite3BtreeMovetoUnpacked(
5412 BtCursor *pCur, /* The cursor to be moved */
5413 UnpackedRecord *pIdxKey, /* Unpacked index key */
5414 i64 intKey, /* The table key */
5415 int biasRight, /* If true, bias the search to the high end */
5416 int *pRes /* Write search results here */
5418 int rc;
5419 RecordCompare xRecordCompare;
5421 assert( cursorOwnsBtShared(pCur) );
5422 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5423 assert( pRes );
5424 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
5425 assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
5427 /* If the cursor is already positioned at the point we are trying
5428 ** to move to, then just return without doing any work */
5429 if( pIdxKey==0
5430 && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
5432 if( pCur->info.nKey==intKey ){
5433 *pRes = 0;
5434 return SQLITE_OK;
5436 if( pCur->info.nKey<intKey ){
5437 if( (pCur->curFlags & BTCF_AtLast)!=0 ){
5438 *pRes = -1;
5439 return SQLITE_OK;
5441 /* If the requested key is one more than the previous key, then
5442 ** try to get there using sqlite3BtreeNext() rather than a full
5443 ** binary search. This is an optimization only. The correct answer
5444 ** is still obtained without this case, only a little more slowely */
5445 if( pCur->info.nKey+1==intKey ){
5446 *pRes = 0;
5447 rc = sqlite3BtreeNext(pCur, 0);
5448 if( rc==SQLITE_OK ){
5449 getCellInfo(pCur);
5450 if( pCur->info.nKey==intKey ){
5451 return SQLITE_OK;
5453 }else if( rc==SQLITE_DONE ){
5454 rc = SQLITE_OK;
5455 }else{
5456 return rc;
5462 if( pIdxKey ){
5463 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
5464 pIdxKey->errCode = 0;
5465 assert( pIdxKey->default_rc==1
5466 || pIdxKey->default_rc==0
5467 || pIdxKey->default_rc==-1
5469 }else{
5470 xRecordCompare = 0; /* All keys are integers */
5473 rc = moveToRoot(pCur);
5474 if( rc ){
5475 if( rc==SQLITE_EMPTY ){
5476 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5477 *pRes = -1;
5478 return SQLITE_OK;
5480 return rc;
5482 assert( pCur->pPage );
5483 assert( pCur->pPage->isInit );
5484 assert( pCur->eState==CURSOR_VALID );
5485 assert( pCur->pPage->nCell > 0 );
5486 assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
5487 assert( pCur->curIntKey || pIdxKey );
5488 for(;;){
5489 int lwr, upr, idx, c;
5490 Pgno chldPg;
5491 MemPage *pPage = pCur->pPage;
5492 u8 *pCell; /* Pointer to current cell in pPage */
5494 /* pPage->nCell must be greater than zero. If this is the root-page
5495 ** the cursor would have been INVALID above and this for(;;) loop
5496 ** not run. If this is not the root-page, then the moveToChild() routine
5497 ** would have already detected db corruption. Similarly, pPage must
5498 ** be the right kind (index or table) of b-tree page. Otherwise
5499 ** a moveToChild() or moveToRoot() call would have detected corruption. */
5500 assert( pPage->nCell>0 );
5501 assert( pPage->intKey==(pIdxKey==0) );
5502 lwr = 0;
5503 upr = pPage->nCell-1;
5504 assert( biasRight==0 || biasRight==1 );
5505 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
5506 pCur->ix = (u16)idx;
5507 if( xRecordCompare==0 ){
5508 for(;;){
5509 i64 nCellKey;
5510 pCell = findCellPastPtr(pPage, idx);
5511 if( pPage->intKeyLeaf ){
5512 while( 0x80 <= *(pCell++) ){
5513 if( pCell>=pPage->aDataEnd ){
5514 return SQLITE_CORRUPT_PAGE(pPage);
5518 getVarint(pCell, (u64*)&nCellKey);
5519 if( nCellKey<intKey ){
5520 lwr = idx+1;
5521 if( lwr>upr ){ c = -1; break; }
5522 }else if( nCellKey>intKey ){
5523 upr = idx-1;
5524 if( lwr>upr ){ c = +1; break; }
5525 }else{
5526 assert( nCellKey==intKey );
5527 pCur->ix = (u16)idx;
5528 if( !pPage->leaf ){
5529 lwr = idx;
5530 goto moveto_next_layer;
5531 }else{
5532 pCur->curFlags |= BTCF_ValidNKey;
5533 pCur->info.nKey = nCellKey;
5534 pCur->info.nSize = 0;
5535 *pRes = 0;
5536 return SQLITE_OK;
5539 assert( lwr+upr>=0 );
5540 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
5542 }else{
5543 for(;;){
5544 int nCell; /* Size of the pCell cell in bytes */
5545 pCell = findCellPastPtr(pPage, idx);
5547 /* The maximum supported page-size is 65536 bytes. This means that
5548 ** the maximum number of record bytes stored on an index B-Tree
5549 ** page is less than 16384 bytes and may be stored as a 2-byte
5550 ** varint. This information is used to attempt to avoid parsing
5551 ** the entire cell by checking for the cases where the record is
5552 ** stored entirely within the b-tree page by inspecting the first
5553 ** 2 bytes of the cell.
5555 nCell = pCell[0];
5556 if( nCell<=pPage->max1bytePayload ){
5557 /* This branch runs if the record-size field of the cell is a
5558 ** single byte varint and the record fits entirely on the main
5559 ** b-tree page. */
5560 testcase( pCell+nCell+1==pPage->aDataEnd );
5561 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
5562 }else if( !(pCell[1] & 0x80)
5563 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5565 /* The record-size field is a 2 byte varint and the record
5566 ** fits entirely on the main b-tree page. */
5567 testcase( pCell+nCell+2==pPage->aDataEnd );
5568 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
5569 }else{
5570 /* The record flows over onto one or more overflow pages. In
5571 ** this case the whole cell needs to be parsed, a buffer allocated
5572 ** and accessPayload() used to retrieve the record into the
5573 ** buffer before VdbeRecordCompare() can be called.
5575 ** If the record is corrupt, the xRecordCompare routine may read
5576 ** up to two varints past the end of the buffer. An extra 18
5577 ** bytes of padding is allocated at the end of the buffer in
5578 ** case this happens. */
5579 void *pCellKey;
5580 u8 * const pCellBody = pCell - pPage->childPtrSize;
5581 const int nOverrun = 18; /* Size of the overrun padding */
5582 pPage->xParseCell(pPage, pCellBody, &pCur->info);
5583 nCell = (int)pCur->info.nKey;
5584 testcase( nCell<0 ); /* True if key size is 2^32 or more */
5585 testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
5586 testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
5587 testcase( nCell==2 ); /* Minimum legal index key size */
5588 if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
5589 rc = SQLITE_CORRUPT_PAGE(pPage);
5590 goto moveto_finish;
5592 pCellKey = sqlite3Malloc( nCell+nOverrun );
5593 if( pCellKey==0 ){
5594 rc = SQLITE_NOMEM_BKPT;
5595 goto moveto_finish;
5597 pCur->ix = (u16)idx;
5598 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
5599 memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */
5600 pCur->curFlags &= ~BTCF_ValidOvfl;
5601 if( rc ){
5602 sqlite3_free(pCellKey);
5603 goto moveto_finish;
5605 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
5606 sqlite3_free(pCellKey);
5608 assert(
5609 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
5610 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
5612 if( c<0 ){
5613 lwr = idx+1;
5614 }else if( c>0 ){
5615 upr = idx-1;
5616 }else{
5617 assert( c==0 );
5618 *pRes = 0;
5619 rc = SQLITE_OK;
5620 pCur->ix = (u16)idx;
5621 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
5622 goto moveto_finish;
5624 if( lwr>upr ) break;
5625 assert( lwr+upr>=0 );
5626 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
5629 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
5630 assert( pPage->isInit );
5631 if( pPage->leaf ){
5632 assert( pCur->ix<pCur->pPage->nCell );
5633 pCur->ix = (u16)idx;
5634 *pRes = c;
5635 rc = SQLITE_OK;
5636 goto moveto_finish;
5638 moveto_next_layer:
5639 if( lwr>=pPage->nCell ){
5640 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5641 }else{
5642 chldPg = get4byte(findCell(pPage, lwr));
5644 pCur->ix = (u16)lwr;
5645 rc = moveToChild(pCur, chldPg);
5646 if( rc ) break;
5648 moveto_finish:
5649 pCur->info.nSize = 0;
5650 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5651 return rc;
5656 ** Return TRUE if the cursor is not pointing at an entry of the table.
5658 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
5659 ** past the last entry in the table or sqlite3BtreePrev() moves past
5660 ** the first entry. TRUE is also returned if the table is empty.
5662 int sqlite3BtreeEof(BtCursor *pCur){
5663 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
5664 ** have been deleted? This API will need to change to return an error code
5665 ** as well as the boolean result value.
5667 return (CURSOR_VALID!=pCur->eState);
5671 ** Return an estimate for the number of rows in the table that pCur is
5672 ** pointing to. Return a negative number if no estimate is currently
5673 ** available.
5675 i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
5676 i64 n;
5677 u8 i;
5679 assert( cursorOwnsBtShared(pCur) );
5680 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5682 /* Currently this interface is only called by the OP_IfSmaller
5683 ** opcode, and it that case the cursor will always be valid and
5684 ** will always point to a leaf node. */
5685 if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
5686 if( NEVER(pCur->pPage->leaf==0) ) return -1;
5688 n = pCur->pPage->nCell;
5689 for(i=0; i<pCur->iPage; i++){
5690 n *= pCur->apPage[i]->nCell;
5692 return n;
5696 ** Advance the cursor to the next entry in the database.
5697 ** Return value:
5699 ** SQLITE_OK success
5700 ** SQLITE_DONE cursor is already pointing at the last element
5701 ** otherwise some kind of error occurred
5703 ** The main entry point is sqlite3BtreeNext(). That routine is optimized
5704 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
5705 ** to the next cell on the current page. The (slower) btreeNext() helper
5706 ** routine is called when it is necessary to move to a different page or
5707 ** to restore the cursor.
5709 ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
5710 ** cursor corresponds to an SQL index and this routine could have been
5711 ** skipped if the SQL index had been a unique index. The F argument
5712 ** is a hint to the implement. SQLite btree implementation does not use
5713 ** this hint, but COMDB2 does.
5715 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
5716 int rc;
5717 int idx;
5718 MemPage *pPage;
5720 assert( cursorOwnsBtShared(pCur) );
5721 if( pCur->eState!=CURSOR_VALID ){
5722 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5723 rc = restoreCursorPosition(pCur);
5724 if( rc!=SQLITE_OK ){
5725 return rc;
5727 if( CURSOR_INVALID==pCur->eState ){
5728 return SQLITE_DONE;
5730 if( pCur->eState==CURSOR_SKIPNEXT ){
5731 pCur->eState = CURSOR_VALID;
5732 if( pCur->skipNext>0 ) return SQLITE_OK;
5736 pPage = pCur->pPage;
5737 idx = ++pCur->ix;
5738 if( !pPage->isInit ){
5739 /* The only known way for this to happen is for there to be a
5740 ** recursive SQL function that does a DELETE operation as part of a
5741 ** SELECT which deletes content out from under an active cursor
5742 ** in a corrupt database file where the table being DELETE-ed from
5743 ** has pages in common with the table being queried. See TH3
5744 ** module cov1/btree78.test testcase 220 (2018-06-08) for an
5745 ** example. */
5746 return SQLITE_CORRUPT_BKPT;
5749 /* If the database file is corrupt, it is possible for the value of idx
5750 ** to be invalid here. This can only occur if a second cursor modifies
5751 ** the page while cursor pCur is holding a reference to it. Which can
5752 ** only happen if the database is corrupt in such a way as to link the
5753 ** page into more than one b-tree structure.
5755 ** Update 2019-12-23: appears to long longer be possible after the
5756 ** addition of anotherValidCursor() condition on balance_deeper(). */
5757 harmless( idx>pPage->nCell );
5759 if( idx>=pPage->nCell ){
5760 if( !pPage->leaf ){
5761 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
5762 if( rc ) return rc;
5763 return moveToLeftmost(pCur);
5766 if( pCur->iPage==0 ){
5767 pCur->eState = CURSOR_INVALID;
5768 return SQLITE_DONE;
5770 moveToParent(pCur);
5771 pPage = pCur->pPage;
5772 }while( pCur->ix>=pPage->nCell );
5773 if( pPage->intKey ){
5774 return sqlite3BtreeNext(pCur, 0);
5775 }else{
5776 return SQLITE_OK;
5779 if( pPage->leaf ){
5780 return SQLITE_OK;
5781 }else{
5782 return moveToLeftmost(pCur);
5785 int sqlite3BtreeNext(BtCursor *pCur, int flags){
5786 MemPage *pPage;
5787 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
5788 assert( cursorOwnsBtShared(pCur) );
5789 assert( flags==0 || flags==1 );
5790 pCur->info.nSize = 0;
5791 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5792 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
5793 pPage = pCur->pPage;
5794 if( (++pCur->ix)>=pPage->nCell ){
5795 pCur->ix--;
5796 return btreeNext(pCur);
5798 if( pPage->leaf ){
5799 return SQLITE_OK;
5800 }else{
5801 return moveToLeftmost(pCur);
5806 ** Step the cursor to the back to the previous entry in the database.
5807 ** Return values:
5809 ** SQLITE_OK success
5810 ** SQLITE_DONE the cursor is already on the first element of the table
5811 ** otherwise some kind of error occurred
5813 ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
5814 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
5815 ** to the previous cell on the current page. The (slower) btreePrevious()
5816 ** helper routine is called when it is necessary to move to a different page
5817 ** or to restore the cursor.
5819 ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
5820 ** the cursor corresponds to an SQL index and this routine could have been
5821 ** skipped if the SQL index had been a unique index. The F argument is a
5822 ** hint to the implement. The native SQLite btree implementation does not
5823 ** use this hint, but COMDB2 does.
5825 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
5826 int rc;
5827 MemPage *pPage;
5829 assert( cursorOwnsBtShared(pCur) );
5830 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
5831 assert( pCur->info.nSize==0 );
5832 if( pCur->eState!=CURSOR_VALID ){
5833 rc = restoreCursorPosition(pCur);
5834 if( rc!=SQLITE_OK ){
5835 return rc;
5837 if( CURSOR_INVALID==pCur->eState ){
5838 return SQLITE_DONE;
5840 if( CURSOR_SKIPNEXT==pCur->eState ){
5841 pCur->eState = CURSOR_VALID;
5842 if( pCur->skipNext<0 ) return SQLITE_OK;
5846 pPage = pCur->pPage;
5847 assert( pPage->isInit );
5848 if( !pPage->leaf ){
5849 int idx = pCur->ix;
5850 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
5851 if( rc ) return rc;
5852 rc = moveToRightmost(pCur);
5853 }else{
5854 while( pCur->ix==0 ){
5855 if( pCur->iPage==0 ){
5856 pCur->eState = CURSOR_INVALID;
5857 return SQLITE_DONE;
5859 moveToParent(pCur);
5861 assert( pCur->info.nSize==0 );
5862 assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
5864 pCur->ix--;
5865 pPage = pCur->pPage;
5866 if( pPage->intKey && !pPage->leaf ){
5867 rc = sqlite3BtreePrevious(pCur, 0);
5868 }else{
5869 rc = SQLITE_OK;
5872 return rc;
5874 int sqlite3BtreePrevious(BtCursor *pCur, int flags){
5875 assert( cursorOwnsBtShared(pCur) );
5876 assert( flags==0 || flags==1 );
5877 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
5878 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
5879 pCur->info.nSize = 0;
5880 if( pCur->eState!=CURSOR_VALID
5881 || pCur->ix==0
5882 || pCur->pPage->leaf==0
5884 return btreePrevious(pCur);
5886 pCur->ix--;
5887 return SQLITE_OK;
5891 ** Allocate a new page from the database file.
5893 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
5894 ** has already been called on the new page.) The new page has also
5895 ** been referenced and the calling routine is responsible for calling
5896 ** sqlite3PagerUnref() on the new page when it is done.
5898 ** SQLITE_OK is returned on success. Any other return value indicates
5899 ** an error. *ppPage is set to NULL in the event of an error.
5901 ** If the "nearby" parameter is not 0, then an effort is made to
5902 ** locate a page close to the page number "nearby". This can be used in an
5903 ** attempt to keep related pages close to each other in the database file,
5904 ** which in turn can make database access faster.
5906 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
5907 ** anywhere on the free-list, then it is guaranteed to be returned. If
5908 ** eMode is BTALLOC_LT then the page returned will be less than or equal
5909 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
5910 ** are no restrictions on which page is returned.
5912 static int allocateBtreePage(
5913 BtShared *pBt, /* The btree */
5914 MemPage **ppPage, /* Store pointer to the allocated page here */
5915 Pgno *pPgno, /* Store the page number here */
5916 Pgno nearby, /* Search for a page near this one */
5917 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
5919 MemPage *pPage1;
5920 int rc;
5921 u32 n; /* Number of pages on the freelist */
5922 u32 k; /* Number of leaves on the trunk of the freelist */
5923 MemPage *pTrunk = 0;
5924 MemPage *pPrevTrunk = 0;
5925 Pgno mxPage; /* Total size of the database file */
5927 assert( sqlite3_mutex_held(pBt->mutex) );
5928 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
5929 pPage1 = pBt->pPage1;
5930 mxPage = btreePagecount(pBt);
5931 /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
5932 ** stores stores the total number of pages on the freelist. */
5933 n = get4byte(&pPage1->aData[36]);
5934 testcase( n==mxPage-1 );
5935 if( n>=mxPage ){
5936 return SQLITE_CORRUPT_BKPT;
5938 if( n>0 ){
5939 /* There are pages on the freelist. Reuse one of those pages. */
5940 Pgno iTrunk;
5941 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
5942 u32 nSearch = 0; /* Count of the number of search attempts */
5944 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
5945 ** shows that the page 'nearby' is somewhere on the free-list, then
5946 ** the entire-list will be searched for that page.
5948 #ifndef SQLITE_OMIT_AUTOVACUUM
5949 if( eMode==BTALLOC_EXACT ){
5950 if( nearby<=mxPage ){
5951 u8 eType;
5952 assert( nearby>0 );
5953 assert( pBt->autoVacuum );
5954 rc = ptrmapGet(pBt, nearby, &eType, 0);
5955 if( rc ) return rc;
5956 if( eType==PTRMAP_FREEPAGE ){
5957 searchList = 1;
5960 }else if( eMode==BTALLOC_LE ){
5961 searchList = 1;
5963 #endif
5965 /* Decrement the free-list count by 1. Set iTrunk to the index of the
5966 ** first free-list trunk page. iPrevTrunk is initially 1.
5968 rc = sqlite3PagerWrite(pPage1->pDbPage);
5969 if( rc ) return rc;
5970 put4byte(&pPage1->aData[36], n-1);
5972 /* The code within this loop is run only once if the 'searchList' variable
5973 ** is not true. Otherwise, it runs once for each trunk-page on the
5974 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
5975 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
5977 do {
5978 pPrevTrunk = pTrunk;
5979 if( pPrevTrunk ){
5980 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
5981 ** is the page number of the next freelist trunk page in the list or
5982 ** zero if this is the last freelist trunk page. */
5983 iTrunk = get4byte(&pPrevTrunk->aData[0]);
5984 }else{
5985 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
5986 ** stores the page number of the first page of the freelist, or zero if
5987 ** the freelist is empty. */
5988 iTrunk = get4byte(&pPage1->aData[32]);
5990 testcase( iTrunk==mxPage );
5991 if( iTrunk>mxPage || nSearch++ > n ){
5992 rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
5993 }else{
5994 rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
5996 if( rc ){
5997 pTrunk = 0;
5998 goto end_allocate_page;
6000 assert( pTrunk!=0 );
6001 assert( pTrunk->aData!=0 );
6002 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
6003 ** is the number of leaf page pointers to follow. */
6004 k = get4byte(&pTrunk->aData[4]);
6005 if( k==0 && !searchList ){
6006 /* The trunk has no leaves and the list is not being searched.
6007 ** So extract the trunk page itself and use it as the newly
6008 ** allocated page */
6009 assert( pPrevTrunk==0 );
6010 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6011 if( rc ){
6012 goto end_allocate_page;
6014 *pPgno = iTrunk;
6015 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6016 *ppPage = pTrunk;
6017 pTrunk = 0;
6018 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
6019 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
6020 /* Value of k is out of range. Database corruption */
6021 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6022 goto end_allocate_page;
6023 #ifndef SQLITE_OMIT_AUTOVACUUM
6024 }else if( searchList
6025 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
6027 /* The list is being searched and this trunk page is the page
6028 ** to allocate, regardless of whether it has leaves.
6030 *pPgno = iTrunk;
6031 *ppPage = pTrunk;
6032 searchList = 0;
6033 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6034 if( rc ){
6035 goto end_allocate_page;
6037 if( k==0 ){
6038 if( !pPrevTrunk ){
6039 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6040 }else{
6041 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6042 if( rc!=SQLITE_OK ){
6043 goto end_allocate_page;
6045 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
6047 }else{
6048 /* The trunk page is required by the caller but it contains
6049 ** pointers to free-list leaves. The first leaf becomes a trunk
6050 ** page in this case.
6052 MemPage *pNewTrunk;
6053 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
6054 if( iNewTrunk>mxPage ){
6055 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6056 goto end_allocate_page;
6058 testcase( iNewTrunk==mxPage );
6059 rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
6060 if( rc!=SQLITE_OK ){
6061 goto end_allocate_page;
6063 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
6064 if( rc!=SQLITE_OK ){
6065 releasePage(pNewTrunk);
6066 goto end_allocate_page;
6068 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
6069 put4byte(&pNewTrunk->aData[4], k-1);
6070 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
6071 releasePage(pNewTrunk);
6072 if( !pPrevTrunk ){
6073 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
6074 put4byte(&pPage1->aData[32], iNewTrunk);
6075 }else{
6076 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6077 if( rc ){
6078 goto end_allocate_page;
6080 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
6083 pTrunk = 0;
6084 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
6085 #endif
6086 }else if( k>0 ){
6087 /* Extract a leaf from the trunk */
6088 u32 closest;
6089 Pgno iPage;
6090 unsigned char *aData = pTrunk->aData;
6091 if( nearby>0 ){
6092 u32 i;
6093 closest = 0;
6094 if( eMode==BTALLOC_LE ){
6095 for(i=0; i<k; i++){
6096 iPage = get4byte(&aData[8+i*4]);
6097 if( iPage<=nearby ){
6098 closest = i;
6099 break;
6102 }else{
6103 int dist;
6104 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
6105 for(i=1; i<k; i++){
6106 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
6107 if( d2<dist ){
6108 closest = i;
6109 dist = d2;
6113 }else{
6114 closest = 0;
6117 iPage = get4byte(&aData[8+closest*4]);
6118 testcase( iPage==mxPage );
6119 if( iPage>mxPage ){
6120 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6121 goto end_allocate_page;
6123 testcase( iPage==mxPage );
6124 if( !searchList
6125 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
6127 int noContent;
6128 *pPgno = iPage;
6129 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
6130 ": %d more free pages\n",
6131 *pPgno, closest+1, k, pTrunk->pgno, n-1));
6132 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6133 if( rc ) goto end_allocate_page;
6134 if( closest<k-1 ){
6135 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
6137 put4byte(&aData[4], k-1);
6138 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
6139 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
6140 if( rc==SQLITE_OK ){
6141 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6142 if( rc!=SQLITE_OK ){
6143 releasePage(*ppPage);
6144 *ppPage = 0;
6147 searchList = 0;
6150 releasePage(pPrevTrunk);
6151 pPrevTrunk = 0;
6152 }while( searchList );
6153 }else{
6154 /* There are no pages on the freelist, so append a new page to the
6155 ** database image.
6157 ** Normally, new pages allocated by this block can be requested from the
6158 ** pager layer with the 'no-content' flag set. This prevents the pager
6159 ** from trying to read the pages content from disk. However, if the
6160 ** current transaction has already run one or more incremental-vacuum
6161 ** steps, then the page we are about to allocate may contain content
6162 ** that is required in the event of a rollback. In this case, do
6163 ** not set the no-content flag. This causes the pager to load and journal
6164 ** the current page content before overwriting it.
6166 ** Note that the pager will not actually attempt to load or journal
6167 ** content for any page that really does lie past the end of the database
6168 ** file on disk. So the effects of disabling the no-content optimization
6169 ** here are confined to those pages that lie between the end of the
6170 ** database image and the end of the database file.
6172 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
6174 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6175 if( rc ) return rc;
6176 pBt->nPage++;
6177 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
6179 #ifndef SQLITE_OMIT_AUTOVACUUM
6180 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
6181 /* If *pPgno refers to a pointer-map page, allocate two new pages
6182 ** at the end of the file instead of one. The first allocated page
6183 ** becomes a new pointer-map page, the second is used by the caller.
6185 MemPage *pPg = 0;
6186 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
6187 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
6188 rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
6189 if( rc==SQLITE_OK ){
6190 rc = sqlite3PagerWrite(pPg->pDbPage);
6191 releasePage(pPg);
6193 if( rc ) return rc;
6194 pBt->nPage++;
6195 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
6197 #endif
6198 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
6199 *pPgno = pBt->nPage;
6201 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
6202 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
6203 if( rc ) return rc;
6204 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6205 if( rc!=SQLITE_OK ){
6206 releasePage(*ppPage);
6207 *ppPage = 0;
6209 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
6212 assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );
6214 end_allocate_page:
6215 releasePage(pTrunk);
6216 releasePage(pPrevTrunk);
6217 assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
6218 assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
6219 return rc;
6223 ** This function is used to add page iPage to the database file free-list.
6224 ** It is assumed that the page is not already a part of the free-list.
6226 ** The value passed as the second argument to this function is optional.
6227 ** If the caller happens to have a pointer to the MemPage object
6228 ** corresponding to page iPage handy, it may pass it as the second value.
6229 ** Otherwise, it may pass NULL.
6231 ** If a pointer to a MemPage object is passed as the second argument,
6232 ** its reference count is not altered by this function.
6234 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
6235 MemPage *pTrunk = 0; /* Free-list trunk page */
6236 Pgno iTrunk = 0; /* Page number of free-list trunk page */
6237 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
6238 MemPage *pPage; /* Page being freed. May be NULL. */
6239 int rc; /* Return Code */
6240 u32 nFree; /* Initial number of pages on free-list */
6242 assert( sqlite3_mutex_held(pBt->mutex) );
6243 assert( CORRUPT_DB || iPage>1 );
6244 assert( !pMemPage || pMemPage->pgno==iPage );
6246 if( iPage<2 || iPage>pBt->nPage ){
6247 return SQLITE_CORRUPT_BKPT;
6249 if( pMemPage ){
6250 pPage = pMemPage;
6251 sqlite3PagerRef(pPage->pDbPage);
6252 }else{
6253 pPage = btreePageLookup(pBt, iPage);
6256 /* Increment the free page count on pPage1 */
6257 rc = sqlite3PagerWrite(pPage1->pDbPage);
6258 if( rc ) goto freepage_out;
6259 nFree = get4byte(&pPage1->aData[36]);
6260 put4byte(&pPage1->aData[36], nFree+1);
6262 if( pBt->btsFlags & BTS_SECURE_DELETE ){
6263 /* If the secure_delete option is enabled, then
6264 ** always fully overwrite deleted information with zeros.
6266 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
6267 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
6269 goto freepage_out;
6271 memset(pPage->aData, 0, pPage->pBt->pageSize);
6274 /* If the database supports auto-vacuum, write an entry in the pointer-map
6275 ** to indicate that the page is free.
6277 if( ISAUTOVACUUM ){
6278 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
6279 if( rc ) goto freepage_out;
6282 /* Now manipulate the actual database free-list structure. There are two
6283 ** possibilities. If the free-list is currently empty, or if the first
6284 ** trunk page in the free-list is full, then this page will become a
6285 ** new free-list trunk page. Otherwise, it will become a leaf of the
6286 ** first trunk page in the current free-list. This block tests if it
6287 ** is possible to add the page as a new free-list leaf.
6289 if( nFree!=0 ){
6290 u32 nLeaf; /* Initial number of leaf cells on trunk page */
6292 iTrunk = get4byte(&pPage1->aData[32]);
6293 if( iTrunk>btreePagecount(pBt) ){
6294 rc = SQLITE_CORRUPT_BKPT;
6295 goto freepage_out;
6297 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
6298 if( rc!=SQLITE_OK ){
6299 goto freepage_out;
6302 nLeaf = get4byte(&pTrunk->aData[4]);
6303 assert( pBt->usableSize>32 );
6304 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
6305 rc = SQLITE_CORRUPT_BKPT;
6306 goto freepage_out;
6308 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
6309 /* In this case there is room on the trunk page to insert the page
6310 ** being freed as a new leaf.
6312 ** Note that the trunk page is not really full until it contains
6313 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
6314 ** coded. But due to a coding error in versions of SQLite prior to
6315 ** 3.6.0, databases with freelist trunk pages holding more than
6316 ** usableSize/4 - 8 entries will be reported as corrupt. In order
6317 ** to maintain backwards compatibility with older versions of SQLite,
6318 ** we will continue to restrict the number of entries to usableSize/4 - 8
6319 ** for now. At some point in the future (once everyone has upgraded
6320 ** to 3.6.0 or later) we should consider fixing the conditional above
6321 ** to read "usableSize/4-2" instead of "usableSize/4-8".
6323 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
6324 ** avoid using the last six entries in the freelist trunk page array in
6325 ** order that database files created by newer versions of SQLite can be
6326 ** read by older versions of SQLite.
6328 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6329 if( rc==SQLITE_OK ){
6330 put4byte(&pTrunk->aData[4], nLeaf+1);
6331 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
6332 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
6333 sqlite3PagerDontWrite(pPage->pDbPage);
6335 rc = btreeSetHasContent(pBt, iPage);
6337 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
6338 goto freepage_out;
6342 /* If control flows to this point, then it was not possible to add the
6343 ** the page being freed as a leaf page of the first trunk in the free-list.
6344 ** Possibly because the free-list is empty, or possibly because the
6345 ** first trunk in the free-list is full. Either way, the page being freed
6346 ** will become the new first trunk page in the free-list.
6348 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
6349 goto freepage_out;
6351 rc = sqlite3PagerWrite(pPage->pDbPage);
6352 if( rc!=SQLITE_OK ){
6353 goto freepage_out;
6355 put4byte(pPage->aData, iTrunk);
6356 put4byte(&pPage->aData[4], 0);
6357 put4byte(&pPage1->aData[32], iPage);
6358 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
6360 freepage_out:
6361 if( pPage ){
6362 pPage->isInit = 0;
6364 releasePage(pPage);
6365 releasePage(pTrunk);
6366 return rc;
6368 static void freePage(MemPage *pPage, int *pRC){
6369 if( (*pRC)==SQLITE_OK ){
6370 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
6375 ** Free any overflow pages associated with the given Cell. Store
6376 ** size information about the cell in pInfo.
6378 static int clearCell(
6379 MemPage *pPage, /* The page that contains the Cell */
6380 unsigned char *pCell, /* First byte of the Cell */
6381 CellInfo *pInfo /* Size information about the cell */
6383 BtShared *pBt;
6384 Pgno ovflPgno;
6385 int rc;
6386 int nOvfl;
6387 u32 ovflPageSize;
6389 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6390 pPage->xParseCell(pPage, pCell, pInfo);
6391 if( pInfo->nLocal==pInfo->nPayload ){
6392 return SQLITE_OK; /* No overflow pages. Return without doing anything */
6394 testcase( pCell + pInfo->nSize == pPage->aDataEnd );
6395 testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
6396 if( pCell + pInfo->nSize > pPage->aDataEnd ){
6397 /* Cell extends past end of page */
6398 return SQLITE_CORRUPT_PAGE(pPage);
6400 ovflPgno = get4byte(pCell + pInfo->nSize - 4);
6401 pBt = pPage->pBt;
6402 assert( pBt->usableSize > 4 );
6403 ovflPageSize = pBt->usableSize - 4;
6404 nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
6405 assert( nOvfl>0 ||
6406 (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
6408 while( nOvfl-- ){
6409 Pgno iNext = 0;
6410 MemPage *pOvfl = 0;
6411 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
6412 /* 0 is not a legal page number and page 1 cannot be an
6413 ** overflow page. Therefore if ovflPgno<2 or past the end of the
6414 ** file the database must be corrupt. */
6415 return SQLITE_CORRUPT_BKPT;
6417 if( nOvfl ){
6418 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
6419 if( rc ) return rc;
6422 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
6423 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
6425 /* There is no reason any cursor should have an outstanding reference
6426 ** to an overflow page belonging to a cell that is being deleted/updated.
6427 ** So if there exists more than one reference to this page, then it
6428 ** must not really be an overflow page and the database must be corrupt.
6429 ** It is helpful to detect this before calling freePage2(), as
6430 ** freePage2() may zero the page contents if secure-delete mode is
6431 ** enabled. If this 'overflow' page happens to be a page that the
6432 ** caller is iterating through or using in some other way, this
6433 ** can be problematic.
6435 rc = SQLITE_CORRUPT_BKPT;
6436 }else{
6437 rc = freePage2(pBt, pOvfl, ovflPgno);
6440 if( pOvfl ){
6441 sqlite3PagerUnref(pOvfl->pDbPage);
6443 if( rc ) return rc;
6444 ovflPgno = iNext;
6446 return SQLITE_OK;
6450 ** Create the byte sequence used to represent a cell on page pPage
6451 ** and write that byte sequence into pCell[]. Overflow pages are
6452 ** allocated and filled in as necessary. The calling procedure
6453 ** is responsible for making sure sufficient space has been allocated
6454 ** for pCell[].
6456 ** Note that pCell does not necessary need to point to the pPage->aData
6457 ** area. pCell might point to some temporary storage. The cell will
6458 ** be constructed in this temporary area then copied into pPage->aData
6459 ** later.
6461 static int fillInCell(
6462 MemPage *pPage, /* The page that contains the cell */
6463 unsigned char *pCell, /* Complete text of the cell */
6464 const BtreePayload *pX, /* Payload with which to construct the cell */
6465 int *pnSize /* Write cell size here */
6467 int nPayload;
6468 const u8 *pSrc;
6469 int nSrc, n, rc, mn;
6470 int spaceLeft;
6471 MemPage *pToRelease;
6472 unsigned char *pPrior;
6473 unsigned char *pPayload;
6474 BtShared *pBt;
6475 Pgno pgnoOvfl;
6476 int nHeader;
6478 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6480 /* pPage is not necessarily writeable since pCell might be auxiliary
6481 ** buffer space that is separate from the pPage buffer area */
6482 assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
6483 || sqlite3PagerIswriteable(pPage->pDbPage) );
6485 /* Fill in the header. */
6486 nHeader = pPage->childPtrSize;
6487 if( pPage->intKey ){
6488 nPayload = pX->nData + pX->nZero;
6489 pSrc = pX->pData;
6490 nSrc = pX->nData;
6491 assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
6492 nHeader += putVarint32(&pCell[nHeader], nPayload);
6493 nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
6494 }else{
6495 assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
6496 nSrc = nPayload = (int)pX->nKey;
6497 pSrc = pX->pKey;
6498 nHeader += putVarint32(&pCell[nHeader], nPayload);
6501 /* Fill in the payload */
6502 pPayload = &pCell[nHeader];
6503 if( nPayload<=pPage->maxLocal ){
6504 /* This is the common case where everything fits on the btree page
6505 ** and no overflow pages are required. */
6506 n = nHeader + nPayload;
6507 testcase( n==3 );
6508 testcase( n==4 );
6509 if( n<4 ) n = 4;
6510 *pnSize = n;
6511 assert( nSrc<=nPayload );
6512 testcase( nSrc<nPayload );
6513 memcpy(pPayload, pSrc, nSrc);
6514 memset(pPayload+nSrc, 0, nPayload-nSrc);
6515 return SQLITE_OK;
6518 /* If we reach this point, it means that some of the content will need
6519 ** to spill onto overflow pages.
6521 mn = pPage->minLocal;
6522 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
6523 testcase( n==pPage->maxLocal );
6524 testcase( n==pPage->maxLocal+1 );
6525 if( n > pPage->maxLocal ) n = mn;
6526 spaceLeft = n;
6527 *pnSize = n + nHeader + 4;
6528 pPrior = &pCell[nHeader+n];
6529 pToRelease = 0;
6530 pgnoOvfl = 0;
6531 pBt = pPage->pBt;
6533 /* At this point variables should be set as follows:
6535 ** nPayload Total payload size in bytes
6536 ** pPayload Begin writing payload here
6537 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
6538 ** that means content must spill into overflow pages.
6539 ** *pnSize Size of the local cell (not counting overflow pages)
6540 ** pPrior Where to write the pgno of the first overflow page
6542 ** Use a call to btreeParseCellPtr() to verify that the values above
6543 ** were computed correctly.
6545 #ifdef SQLITE_DEBUG
6547 CellInfo info;
6548 pPage->xParseCell(pPage, pCell, &info);
6549 assert( nHeader==(int)(info.pPayload - pCell) );
6550 assert( info.nKey==pX->nKey );
6551 assert( *pnSize == info.nSize );
6552 assert( spaceLeft == info.nLocal );
6554 #endif
6556 /* Write the payload into the local Cell and any extra into overflow pages */
6557 while( 1 ){
6558 n = nPayload;
6559 if( n>spaceLeft ) n = spaceLeft;
6561 /* If pToRelease is not zero than pPayload points into the data area
6562 ** of pToRelease. Make sure pToRelease is still writeable. */
6563 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6565 /* If pPayload is part of the data area of pPage, then make sure pPage
6566 ** is still writeable */
6567 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
6568 || sqlite3PagerIswriteable(pPage->pDbPage) );
6570 if( nSrc>=n ){
6571 memcpy(pPayload, pSrc, n);
6572 }else if( nSrc>0 ){
6573 n = nSrc;
6574 memcpy(pPayload, pSrc, n);
6575 }else{
6576 memset(pPayload, 0, n);
6578 nPayload -= n;
6579 if( nPayload<=0 ) break;
6580 pPayload += n;
6581 pSrc += n;
6582 nSrc -= n;
6583 spaceLeft -= n;
6584 if( spaceLeft==0 ){
6585 MemPage *pOvfl = 0;
6586 #ifndef SQLITE_OMIT_AUTOVACUUM
6587 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
6588 if( pBt->autoVacuum ){
6590 pgnoOvfl++;
6591 } while(
6592 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
6595 #endif
6596 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
6597 #ifndef SQLITE_OMIT_AUTOVACUUM
6598 /* If the database supports auto-vacuum, and the second or subsequent
6599 ** overflow page is being allocated, add an entry to the pointer-map
6600 ** for that page now.
6602 ** If this is the first overflow page, then write a partial entry
6603 ** to the pointer-map. If we write nothing to this pointer-map slot,
6604 ** then the optimistic overflow chain processing in clearCell()
6605 ** may misinterpret the uninitialized values and delete the
6606 ** wrong pages from the database.
6608 if( pBt->autoVacuum && rc==SQLITE_OK ){
6609 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
6610 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
6611 if( rc ){
6612 releasePage(pOvfl);
6615 #endif
6616 if( rc ){
6617 releasePage(pToRelease);
6618 return rc;
6621 /* If pToRelease is not zero than pPrior points into the data area
6622 ** of pToRelease. Make sure pToRelease is still writeable. */
6623 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6625 /* If pPrior is part of the data area of pPage, then make sure pPage
6626 ** is still writeable */
6627 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
6628 || sqlite3PagerIswriteable(pPage->pDbPage) );
6630 put4byte(pPrior, pgnoOvfl);
6631 releasePage(pToRelease);
6632 pToRelease = pOvfl;
6633 pPrior = pOvfl->aData;
6634 put4byte(pPrior, 0);
6635 pPayload = &pOvfl->aData[4];
6636 spaceLeft = pBt->usableSize - 4;
6639 releasePage(pToRelease);
6640 return SQLITE_OK;
6644 ** Remove the i-th cell from pPage. This routine effects pPage only.
6645 ** The cell content is not freed or deallocated. It is assumed that
6646 ** the cell content has been copied someplace else. This routine just
6647 ** removes the reference to the cell from pPage.
6649 ** "sz" must be the number of bytes in the cell.
6651 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
6652 u32 pc; /* Offset to cell content of cell being deleted */
6653 u8 *data; /* pPage->aData */
6654 u8 *ptr; /* Used to move bytes around within data[] */
6655 int rc; /* The return code */
6656 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
6658 if( *pRC ) return;
6659 assert( idx>=0 && idx<pPage->nCell );
6660 assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
6661 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6662 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6663 assert( pPage->nFree>=0 );
6664 data = pPage->aData;
6665 ptr = &pPage->aCellIdx[2*idx];
6666 pc = get2byte(ptr);
6667 hdr = pPage->hdrOffset;
6668 testcase( pc==get2byte(&data[hdr+5]) );
6669 testcase( pc+sz==pPage->pBt->usableSize );
6670 if( pc+sz > pPage->pBt->usableSize ){
6671 *pRC = SQLITE_CORRUPT_BKPT;
6672 return;
6674 rc = freeSpace(pPage, pc, sz);
6675 if( rc ){
6676 *pRC = rc;
6677 return;
6679 pPage->nCell--;
6680 if( pPage->nCell==0 ){
6681 memset(&data[hdr+1], 0, 4);
6682 data[hdr+7] = 0;
6683 put2byte(&data[hdr+5], pPage->pBt->usableSize);
6684 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
6685 - pPage->childPtrSize - 8;
6686 }else{
6687 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
6688 put2byte(&data[hdr+3], pPage->nCell);
6689 pPage->nFree += 2;
6694 ** Insert a new cell on pPage at cell index "i". pCell points to the
6695 ** content of the cell.
6697 ** If the cell content will fit on the page, then put it there. If it
6698 ** will not fit, then make a copy of the cell content into pTemp if
6699 ** pTemp is not null. Regardless of pTemp, allocate a new entry
6700 ** in pPage->apOvfl[] and make it point to the cell content (either
6701 ** in pTemp or the original pCell) and also record its index.
6702 ** Allocating a new entry in pPage->aCell[] implies that
6703 ** pPage->nOverflow is incremented.
6705 ** *pRC must be SQLITE_OK when this routine is called.
6707 static void insertCell(
6708 MemPage *pPage, /* Page into which we are copying */
6709 int i, /* New cell becomes the i-th cell of the page */
6710 u8 *pCell, /* Content of the new cell */
6711 int sz, /* Bytes of content in pCell */
6712 u8 *pTemp, /* Temp storage space for pCell, if needed */
6713 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
6714 int *pRC /* Read and write return code from here */
6716 int idx = 0; /* Where to write new cell content in data[] */
6717 int j; /* Loop counter */
6718 u8 *data; /* The content of the whole page */
6719 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
6721 assert( *pRC==SQLITE_OK );
6722 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
6723 assert( MX_CELL(pPage->pBt)<=10921 );
6724 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
6725 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
6726 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
6727 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6728 assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
6729 assert( pPage->nFree>=0 );
6730 if( pPage->nOverflow || sz+2>pPage->nFree ){
6731 if( pTemp ){
6732 memcpy(pTemp, pCell, sz);
6733 pCell = pTemp;
6735 if( iChild ){
6736 put4byte(pCell, iChild);
6738 j = pPage->nOverflow++;
6739 /* Comparison against ArraySize-1 since we hold back one extra slot
6740 ** as a contingency. In other words, never need more than 3 overflow
6741 ** slots but 4 are allocated, just to be safe. */
6742 assert( j < ArraySize(pPage->apOvfl)-1 );
6743 pPage->apOvfl[j] = pCell;
6744 pPage->aiOvfl[j] = (u16)i;
6746 /* When multiple overflows occur, they are always sequential and in
6747 ** sorted order. This invariants arise because multiple overflows can
6748 ** only occur when inserting divider cells into the parent page during
6749 ** balancing, and the dividers are adjacent and sorted.
6751 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
6752 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
6753 }else{
6754 int rc = sqlite3PagerWrite(pPage->pDbPage);
6755 if( rc!=SQLITE_OK ){
6756 *pRC = rc;
6757 return;
6759 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6760 data = pPage->aData;
6761 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
6762 rc = allocateSpace(pPage, sz, &idx);
6763 if( rc ){ *pRC = rc; return; }
6764 /* The allocateSpace() routine guarantees the following properties
6765 ** if it returns successfully */
6766 assert( idx >= 0 );
6767 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
6768 assert( idx+sz <= (int)pPage->pBt->usableSize );
6769 pPage->nFree -= (u16)(2 + sz);
6770 if( iChild ){
6771 /* In a corrupt database where an entry in the cell index section of
6772 ** a btree page has a value of 3 or less, the pCell value might point
6773 ** as many as 4 bytes in front of the start of the aData buffer for
6774 ** the source page. Make sure this does not cause problems by not
6775 ** reading the first 4 bytes */
6776 memcpy(&data[idx+4], pCell+4, sz-4);
6777 put4byte(&data[idx], iChild);
6778 }else{
6779 memcpy(&data[idx], pCell, sz);
6781 pIns = pPage->aCellIdx + i*2;
6782 memmove(pIns+2, pIns, 2*(pPage->nCell - i));
6783 put2byte(pIns, idx);
6784 pPage->nCell++;
6785 /* increment the cell count */
6786 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
6787 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
6788 #ifndef SQLITE_OMIT_AUTOVACUUM
6789 if( pPage->pBt->autoVacuum ){
6790 /* The cell may contain a pointer to an overflow page. If so, write
6791 ** the entry for the overflow page into the pointer map.
6793 ptrmapPutOvflPtr(pPage, pPage, pCell, pRC);
6795 #endif
6800 ** The following parameters determine how many adjacent pages get involved
6801 ** in a balancing operation. NN is the number of neighbors on either side
6802 ** of the page that participate in the balancing operation. NB is the
6803 ** total number of pages that participate, including the target page and
6804 ** NN neighbors on either side.
6806 ** The minimum value of NN is 1 (of course). Increasing NN above 1
6807 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
6808 ** in exchange for a larger degradation in INSERT and UPDATE performance.
6809 ** The value of NN appears to give the best results overall.
6811 ** (Later:) The description above makes it seem as if these values are
6812 ** tunable - as if you could change them and recompile and it would all work.
6813 ** But that is unlikely. NB has been 3 since the inception of SQLite and
6814 ** we have never tested any other value.
6816 #define NN 1 /* Number of neighbors on either side of pPage */
6817 #define NB 3 /* (NN*2+1): Total pages involved in the balance */
6820 ** A CellArray object contains a cache of pointers and sizes for a
6821 ** consecutive sequence of cells that might be held on multiple pages.
6823 ** The cells in this array are the divider cell or cells from the pParent
6824 ** page plus up to three child pages. There are a total of nCell cells.
6826 ** pRef is a pointer to one of the pages that contributes cells. This is
6827 ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
6828 ** which should be common to all pages that contribute cells to this array.
6830 ** apCell[] and szCell[] hold, respectively, pointers to the start of each
6831 ** cell and the size of each cell. Some of the apCell[] pointers might refer
6832 ** to overflow cells. In other words, some apCel[] pointers might not point
6833 ** to content area of the pages.
6835 ** A szCell[] of zero means the size of that cell has not yet been computed.
6837 ** The cells come from as many as four different pages:
6839 ** -----------
6840 ** | Parent |
6841 ** -----------
6842 ** / | \
6843 ** / | \
6844 ** --------- --------- ---------
6845 ** |Child-1| |Child-2| |Child-3|
6846 ** --------- --------- ---------
6848 ** The order of cells is in the array is for an index btree is:
6850 ** 1. All cells from Child-1 in order
6851 ** 2. The first divider cell from Parent
6852 ** 3. All cells from Child-2 in order
6853 ** 4. The second divider cell from Parent
6854 ** 5. All cells from Child-3 in order
6856 ** For a table-btree (with rowids) the items 2 and 4 are empty because
6857 ** content exists only in leaves and there are no divider cells.
6859 ** For an index btree, the apEnd[] array holds pointer to the end of page
6860 ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
6861 ** respectively. The ixNx[] array holds the number of cells contained in
6862 ** each of these 5 stages, and all stages to the left. Hence:
6864 ** ixNx[0] = Number of cells in Child-1.
6865 ** ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
6866 ** ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
6867 ** ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
6868 ** ixNx[4] = Total number of cells.
6870 ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
6871 ** are used and they point to the leaf pages only, and the ixNx value are:
6873 ** ixNx[0] = Number of cells in Child-1.
6874 ** ixNx[1] = Number of cells in Child-1 and Child-2.
6875 ** ixNx[2] = Total number of cells.
6877 ** Sometimes when deleting, a child page can have zero cells. In those
6878 ** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[]
6879 ** entries, shift down. The end result is that each ixNx[] entry should
6880 ** be larger than the previous
6882 typedef struct CellArray CellArray;
6883 struct CellArray {
6884 int nCell; /* Number of cells in apCell[] */
6885 MemPage *pRef; /* Reference page */
6886 u8 **apCell; /* All cells begin balanced */
6887 u16 *szCell; /* Local size of all cells in apCell[] */
6888 u8 *apEnd[NB*2]; /* MemPage.aDataEnd values */
6889 int ixNx[NB*2]; /* Index of at which we move to the next apEnd[] */
6893 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
6894 ** computed.
6896 static void populateCellCache(CellArray *p, int idx, int N){
6897 assert( idx>=0 && idx+N<=p->nCell );
6898 while( N>0 ){
6899 assert( p->apCell[idx]!=0 );
6900 if( p->szCell[idx]==0 ){
6901 p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
6902 }else{
6903 assert( CORRUPT_DB ||
6904 p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
6906 idx++;
6907 N--;
6912 ** Return the size of the Nth element of the cell array
6914 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
6915 assert( N>=0 && N<p->nCell );
6916 assert( p->szCell[N]==0 );
6917 p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
6918 return p->szCell[N];
6920 static u16 cachedCellSize(CellArray *p, int N){
6921 assert( N>=0 && N<p->nCell );
6922 if( p->szCell[N] ) return p->szCell[N];
6923 return computeCellSize(p, N);
6927 ** Array apCell[] contains pointers to nCell b-tree page cells. The
6928 ** szCell[] array contains the size in bytes of each cell. This function
6929 ** replaces the current contents of page pPg with the contents of the cell
6930 ** array.
6932 ** Some of the cells in apCell[] may currently be stored in pPg. This
6933 ** function works around problems caused by this by making a copy of any
6934 ** such cells before overwriting the page data.
6936 ** The MemPage.nFree field is invalidated by this function. It is the
6937 ** responsibility of the caller to set it correctly.
6939 static int rebuildPage(
6940 CellArray *pCArray, /* Content to be added to page pPg */
6941 int iFirst, /* First cell in pCArray to use */
6942 int nCell, /* Final number of cells on page */
6943 MemPage *pPg /* The page to be reconstructed */
6945 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
6946 u8 * const aData = pPg->aData; /* Pointer to data for pPg */
6947 const int usableSize = pPg->pBt->usableSize;
6948 u8 * const pEnd = &aData[usableSize];
6949 int i = iFirst; /* Which cell to copy from pCArray*/
6950 u32 j; /* Start of cell content area */
6951 int iEnd = i+nCell; /* Loop terminator */
6952 u8 *pCellptr = pPg->aCellIdx;
6953 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6954 u8 *pData;
6955 int k; /* Current slot in pCArray->apEnd[] */
6956 u8 *pSrcEnd; /* Current pCArray->apEnd[k] value */
6958 assert( i<iEnd );
6959 j = get2byte(&aData[hdr+5]);
6960 if( NEVER(j>(u32)usableSize) ){ j = 0; }
6961 memcpy(&pTmp[j], &aData[j], usableSize - j);
6963 for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
6964 pSrcEnd = pCArray->apEnd[k];
6966 pData = pEnd;
6967 while( 1/*exit by break*/ ){
6968 u8 *pCell = pCArray->apCell[i];
6969 u16 sz = pCArray->szCell[i];
6970 assert( sz>0 );
6971 if( SQLITE_WITHIN(pCell,aData,pEnd) ){
6972 if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
6973 pCell = &pTmp[pCell - aData];
6974 }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
6975 && (uptr)(pCell)<(uptr)pSrcEnd
6977 return SQLITE_CORRUPT_BKPT;
6980 pData -= sz;
6981 put2byte(pCellptr, (pData - aData));
6982 pCellptr += 2;
6983 if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
6984 memcpy(pData, pCell, sz);
6985 assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
6986 testcase( sz!=pPg->xCellSize(pPg,pCell) )
6987 i++;
6988 if( i>=iEnd ) break;
6989 if( pCArray->ixNx[k]<=i ){
6990 k++;
6991 pSrcEnd = pCArray->apEnd[k];
6995 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
6996 pPg->nCell = nCell;
6997 pPg->nOverflow = 0;
6999 put2byte(&aData[hdr+1], 0);
7000 put2byte(&aData[hdr+3], pPg->nCell);
7001 put2byte(&aData[hdr+5], pData - aData);
7002 aData[hdr+7] = 0x00;
7003 return SQLITE_OK;
7007 ** The pCArray objects contains pointers to b-tree cells and the cell sizes.
7008 ** This function attempts to add the cells stored in the array to page pPg.
7009 ** If it cannot (because the page needs to be defragmented before the cells
7010 ** will fit), non-zero is returned. Otherwise, if the cells are added
7011 ** successfully, zero is returned.
7013 ** Argument pCellptr points to the first entry in the cell-pointer array
7014 ** (part of page pPg) to populate. After cell apCell[0] is written to the
7015 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
7016 ** cell in the array. It is the responsibility of the caller to ensure
7017 ** that it is safe to overwrite this part of the cell-pointer array.
7019 ** When this function is called, *ppData points to the start of the
7020 ** content area on page pPg. If the size of the content area is extended,
7021 ** *ppData is updated to point to the new start of the content area
7022 ** before returning.
7024 ** Finally, argument pBegin points to the byte immediately following the
7025 ** end of the space required by this page for the cell-pointer area (for
7026 ** all cells - not just those inserted by the current call). If the content
7027 ** area must be extended to before this point in order to accomodate all
7028 ** cells in apCell[], then the cells do not fit and non-zero is returned.
7030 static int pageInsertArray(
7031 MemPage *pPg, /* Page to add cells to */
7032 u8 *pBegin, /* End of cell-pointer array */
7033 u8 **ppData, /* IN/OUT: Page content-area pointer */
7034 u8 *pCellptr, /* Pointer to cell-pointer area */
7035 int iFirst, /* Index of first cell to add */
7036 int nCell, /* Number of cells to add to pPg */
7037 CellArray *pCArray /* Array of cells */
7039 int i = iFirst; /* Loop counter - cell index to insert */
7040 u8 *aData = pPg->aData; /* Complete page */
7041 u8 *pData = *ppData; /* Content area. A subset of aData[] */
7042 int iEnd = iFirst + nCell; /* End of loop. One past last cell to ins */
7043 int k; /* Current slot in pCArray->apEnd[] */
7044 u8 *pEnd; /* Maximum extent of cell data */
7045 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
7046 if( iEnd<=iFirst ) return 0;
7047 for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
7048 pEnd = pCArray->apEnd[k];
7049 while( 1 /*Exit by break*/ ){
7050 int sz, rc;
7051 u8 *pSlot;
7052 assert( pCArray->szCell[i]!=0 );
7053 sz = pCArray->szCell[i];
7054 if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
7055 if( (pData - pBegin)<sz ) return 1;
7056 pData -= sz;
7057 pSlot = pData;
7059 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
7060 ** database. But they might for a corrupt database. Hence use memmove()
7061 ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
7062 assert( (pSlot+sz)<=pCArray->apCell[i]
7063 || pSlot>=(pCArray->apCell[i]+sz)
7064 || CORRUPT_DB );
7065 if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
7066 && (uptr)(pCArray->apCell[i])<(uptr)pEnd
7068 assert( CORRUPT_DB );
7069 (void)SQLITE_CORRUPT_BKPT;
7070 return 1;
7072 memmove(pSlot, pCArray->apCell[i], sz);
7073 put2byte(pCellptr, (pSlot - aData));
7074 pCellptr += 2;
7075 i++;
7076 if( i>=iEnd ) break;
7077 if( pCArray->ixNx[k]<=i ){
7078 k++;
7079 pEnd = pCArray->apEnd[k];
7082 *ppData = pData;
7083 return 0;
7087 ** The pCArray object contains pointers to b-tree cells and their sizes.
7089 ** This function adds the space associated with each cell in the array
7090 ** that is currently stored within the body of pPg to the pPg free-list.
7091 ** The cell-pointers and other fields of the page are not updated.
7093 ** This function returns the total number of cells added to the free-list.
7095 static int pageFreeArray(
7096 MemPage *pPg, /* Page to edit */
7097 int iFirst, /* First cell to delete */
7098 int nCell, /* Cells to delete */
7099 CellArray *pCArray /* Array of cells */
7101 u8 * const aData = pPg->aData;
7102 u8 * const pEnd = &aData[pPg->pBt->usableSize];
7103 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
7104 int nRet = 0;
7105 int i;
7106 int iEnd = iFirst + nCell;
7107 u8 *pFree = 0;
7108 int szFree = 0;
7110 for(i=iFirst; i<iEnd; i++){
7111 u8 *pCell = pCArray->apCell[i];
7112 if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
7113 int sz;
7114 /* No need to use cachedCellSize() here. The sizes of all cells that
7115 ** are to be freed have already been computing while deciding which
7116 ** cells need freeing */
7117 sz = pCArray->szCell[i]; assert( sz>0 );
7118 if( pFree!=(pCell + sz) ){
7119 if( pFree ){
7120 assert( pFree>aData && (pFree - aData)<65536 );
7121 freeSpace(pPg, (u16)(pFree - aData), szFree);
7123 pFree = pCell;
7124 szFree = sz;
7125 if( pFree+sz>pEnd ) return 0;
7126 }else{
7127 pFree = pCell;
7128 szFree += sz;
7130 nRet++;
7133 if( pFree ){
7134 assert( pFree>aData && (pFree - aData)<65536 );
7135 freeSpace(pPg, (u16)(pFree - aData), szFree);
7137 return nRet;
7141 ** pCArray contains pointers to and sizes of all cells in the page being
7142 ** balanced. The current page, pPg, has pPg->nCell cells starting with
7143 ** pCArray->apCell[iOld]. After balancing, this page should hold nNew cells
7144 ** starting at apCell[iNew].
7146 ** This routine makes the necessary adjustments to pPg so that it contains
7147 ** the correct cells after being balanced.
7149 ** The pPg->nFree field is invalid when this function returns. It is the
7150 ** responsibility of the caller to set it correctly.
7152 static int editPage(
7153 MemPage *pPg, /* Edit this page */
7154 int iOld, /* Index of first cell currently on page */
7155 int iNew, /* Index of new first cell on page */
7156 int nNew, /* Final number of cells on page */
7157 CellArray *pCArray /* Array of cells and sizes */
7159 u8 * const aData = pPg->aData;
7160 const int hdr = pPg->hdrOffset;
7161 u8 *pBegin = &pPg->aCellIdx[nNew * 2];
7162 int nCell = pPg->nCell; /* Cells stored on pPg */
7163 u8 *pData;
7164 u8 *pCellptr;
7165 int i;
7166 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
7167 int iNewEnd = iNew + nNew;
7169 #ifdef SQLITE_DEBUG
7170 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7171 memcpy(pTmp, aData, pPg->pBt->usableSize);
7172 #endif
7174 /* Remove cells from the start and end of the page */
7175 assert( nCell>=0 );
7176 if( iOld<iNew ){
7177 int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
7178 if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT;
7179 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
7180 nCell -= nShift;
7182 if( iNewEnd < iOldEnd ){
7183 int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
7184 assert( nCell>=nTail );
7185 nCell -= nTail;
7188 pData = &aData[get2byteNotZero(&aData[hdr+5])];
7189 if( pData<pBegin ) goto editpage_fail;
7191 /* Add cells to the start of the page */
7192 if( iNew<iOld ){
7193 int nAdd = MIN(nNew,iOld-iNew);
7194 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
7195 assert( nAdd>=0 );
7196 pCellptr = pPg->aCellIdx;
7197 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
7198 if( pageInsertArray(
7199 pPg, pBegin, &pData, pCellptr,
7200 iNew, nAdd, pCArray
7201 ) ) goto editpage_fail;
7202 nCell += nAdd;
7205 /* Add any overflow cells */
7206 for(i=0; i<pPg->nOverflow; i++){
7207 int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
7208 if( iCell>=0 && iCell<nNew ){
7209 pCellptr = &pPg->aCellIdx[iCell * 2];
7210 if( nCell>iCell ){
7211 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
7213 nCell++;
7214 cachedCellSize(pCArray, iCell+iNew);
7215 if( pageInsertArray(
7216 pPg, pBegin, &pData, pCellptr,
7217 iCell+iNew, 1, pCArray
7218 ) ) goto editpage_fail;
7222 /* Append cells to the end of the page */
7223 assert( nCell>=0 );
7224 pCellptr = &pPg->aCellIdx[nCell*2];
7225 if( pageInsertArray(
7226 pPg, pBegin, &pData, pCellptr,
7227 iNew+nCell, nNew-nCell, pCArray
7228 ) ) goto editpage_fail;
7230 pPg->nCell = nNew;
7231 pPg->nOverflow = 0;
7233 put2byte(&aData[hdr+3], pPg->nCell);
7234 put2byte(&aData[hdr+5], pData - aData);
7236 #ifdef SQLITE_DEBUG
7237 for(i=0; i<nNew && !CORRUPT_DB; i++){
7238 u8 *pCell = pCArray->apCell[i+iNew];
7239 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
7240 if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
7241 pCell = &pTmp[pCell - aData];
7243 assert( 0==memcmp(pCell, &aData[iOff],
7244 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
7246 #endif
7248 return SQLITE_OK;
7249 editpage_fail:
7250 /* Unable to edit this page. Rebuild it from scratch instead. */
7251 populateCellCache(pCArray, iNew, nNew);
7252 return rebuildPage(pCArray, iNew, nNew, pPg);
7256 #ifndef SQLITE_OMIT_QUICKBALANCE
7258 ** This version of balance() handles the common special case where
7259 ** a new entry is being inserted on the extreme right-end of the
7260 ** tree, in other words, when the new entry will become the largest
7261 ** entry in the tree.
7263 ** Instead of trying to balance the 3 right-most leaf pages, just add
7264 ** a new page to the right-hand side and put the one new entry in
7265 ** that page. This leaves the right side of the tree somewhat
7266 ** unbalanced. But odds are that we will be inserting new entries
7267 ** at the end soon afterwards so the nearly empty page will quickly
7268 ** fill up. On average.
7270 ** pPage is the leaf page which is the right-most page in the tree.
7271 ** pParent is its parent. pPage must have a single overflow entry
7272 ** which is also the right-most entry on the page.
7274 ** The pSpace buffer is used to store a temporary copy of the divider
7275 ** cell that will be inserted into pParent. Such a cell consists of a 4
7276 ** byte page number followed by a variable length integer. In other
7277 ** words, at most 13 bytes. Hence the pSpace buffer must be at
7278 ** least 13 bytes in size.
7280 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
7281 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
7282 MemPage *pNew; /* Newly allocated page */
7283 int rc; /* Return Code */
7284 Pgno pgnoNew; /* Page number of pNew */
7286 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7287 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7288 assert( pPage->nOverflow==1 );
7290 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; /* dbfuzz001.test */
7291 assert( pPage->nFree>=0 );
7292 assert( pParent->nFree>=0 );
7294 /* Allocate a new page. This page will become the right-sibling of
7295 ** pPage. Make the parent page writable, so that the new divider cell
7296 ** may be inserted. If both these operations are successful, proceed.
7298 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
7300 if( rc==SQLITE_OK ){
7302 u8 *pOut = &pSpace[4];
7303 u8 *pCell = pPage->apOvfl[0];
7304 u16 szCell = pPage->xCellSize(pPage, pCell);
7305 u8 *pStop;
7306 CellArray b;
7308 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
7309 assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
7310 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
7311 b.nCell = 1;
7312 b.pRef = pPage;
7313 b.apCell = &pCell;
7314 b.szCell = &szCell;
7315 b.apEnd[0] = pPage->aDataEnd;
7316 b.ixNx[0] = 2;
7317 rc = rebuildPage(&b, 0, 1, pNew);
7318 if( NEVER(rc) ){
7319 releasePage(pNew);
7320 return rc;
7322 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
7324 /* If this is an auto-vacuum database, update the pointer map
7325 ** with entries for the new page, and any pointer from the
7326 ** cell on the page to an overflow page. If either of these
7327 ** operations fails, the return code is set, but the contents
7328 ** of the parent page are still manipulated by thh code below.
7329 ** That is Ok, at this point the parent page is guaranteed to
7330 ** be marked as dirty. Returning an error code will cause a
7331 ** rollback, undoing any changes made to the parent page.
7333 if( ISAUTOVACUUM ){
7334 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
7335 if( szCell>pNew->minLocal ){
7336 ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
7340 /* Create a divider cell to insert into pParent. The divider cell
7341 ** consists of a 4-byte page number (the page number of pPage) and
7342 ** a variable length key value (which must be the same value as the
7343 ** largest key on pPage).
7345 ** To find the largest key value on pPage, first find the right-most
7346 ** cell on pPage. The first two fields of this cell are the
7347 ** record-length (a variable length integer at most 32-bits in size)
7348 ** and the key value (a variable length integer, may have any value).
7349 ** The first of the while(...) loops below skips over the record-length
7350 ** field. The second while(...) loop copies the key value from the
7351 ** cell on pPage into the pSpace buffer.
7353 pCell = findCell(pPage, pPage->nCell-1);
7354 pStop = &pCell[9];
7355 while( (*(pCell++)&0x80) && pCell<pStop );
7356 pStop = &pCell[9];
7357 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
7359 /* Insert the new divider cell into pParent. */
7360 if( rc==SQLITE_OK ){
7361 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
7362 0, pPage->pgno, &rc);
7365 /* Set the right-child pointer of pParent to point to the new page. */
7366 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
7368 /* Release the reference to the new page. */
7369 releasePage(pNew);
7372 return rc;
7374 #endif /* SQLITE_OMIT_QUICKBALANCE */
7376 #if 0
7378 ** This function does not contribute anything to the operation of SQLite.
7379 ** it is sometimes activated temporarily while debugging code responsible
7380 ** for setting pointer-map entries.
7382 static int ptrmapCheckPages(MemPage **apPage, int nPage){
7383 int i, j;
7384 for(i=0; i<nPage; i++){
7385 Pgno n;
7386 u8 e;
7387 MemPage *pPage = apPage[i];
7388 BtShared *pBt = pPage->pBt;
7389 assert( pPage->isInit );
7391 for(j=0; j<pPage->nCell; j++){
7392 CellInfo info;
7393 u8 *z;
7395 z = findCell(pPage, j);
7396 pPage->xParseCell(pPage, z, &info);
7397 if( info.nLocal<info.nPayload ){
7398 Pgno ovfl = get4byte(&z[info.nSize-4]);
7399 ptrmapGet(pBt, ovfl, &e, &n);
7400 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
7402 if( !pPage->leaf ){
7403 Pgno child = get4byte(z);
7404 ptrmapGet(pBt, child, &e, &n);
7405 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7408 if( !pPage->leaf ){
7409 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
7410 ptrmapGet(pBt, child, &e, &n);
7411 assert( n==pPage->pgno && e==PTRMAP_BTREE );
7414 return 1;
7416 #endif
7419 ** This function is used to copy the contents of the b-tree node stored
7420 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
7421 ** the pointer-map entries for each child page are updated so that the
7422 ** parent page stored in the pointer map is page pTo. If pFrom contained
7423 ** any cells with overflow page pointers, then the corresponding pointer
7424 ** map entries are also updated so that the parent page is page pTo.
7426 ** If pFrom is currently carrying any overflow cells (entries in the
7427 ** MemPage.apOvfl[] array), they are not copied to pTo.
7429 ** Before returning, page pTo is reinitialized using btreeInitPage().
7431 ** The performance of this function is not critical. It is only used by
7432 ** the balance_shallower() and balance_deeper() procedures, neither of
7433 ** which are called often under normal circumstances.
7435 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
7436 if( (*pRC)==SQLITE_OK ){
7437 BtShared * const pBt = pFrom->pBt;
7438 u8 * const aFrom = pFrom->aData;
7439 u8 * const aTo = pTo->aData;
7440 int const iFromHdr = pFrom->hdrOffset;
7441 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
7442 int rc;
7443 int iData;
7446 assert( pFrom->isInit );
7447 assert( pFrom->nFree>=iToHdr );
7448 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
7450 /* Copy the b-tree node content from page pFrom to page pTo. */
7451 iData = get2byte(&aFrom[iFromHdr+5]);
7452 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
7453 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
7455 /* Reinitialize page pTo so that the contents of the MemPage structure
7456 ** match the new data. The initialization of pTo can actually fail under
7457 ** fairly obscure circumstances, even though it is a copy of initialized
7458 ** page pFrom.
7460 pTo->isInit = 0;
7461 rc = btreeInitPage(pTo);
7462 if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo);
7463 if( rc!=SQLITE_OK ){
7464 *pRC = rc;
7465 return;
7468 /* If this is an auto-vacuum database, update the pointer-map entries
7469 ** for any b-tree or overflow pages that pTo now contains the pointers to.
7471 if( ISAUTOVACUUM ){
7472 *pRC = setChildPtrmaps(pTo);
7478 ** This routine redistributes cells on the iParentIdx'th child of pParent
7479 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
7480 ** same amount of free space. Usually a single sibling on either side of the
7481 ** page are used in the balancing, though both siblings might come from one
7482 ** side if the page is the first or last child of its parent. If the page
7483 ** has fewer than 2 siblings (something which can only happen if the page
7484 ** is a root page or a child of a root page) then all available siblings
7485 ** participate in the balancing.
7487 ** The number of siblings of the page might be increased or decreased by
7488 ** one or two in an effort to keep pages nearly full but not over full.
7490 ** Note that when this routine is called, some of the cells on the page
7491 ** might not actually be stored in MemPage.aData[]. This can happen
7492 ** if the page is overfull. This routine ensures that all cells allocated
7493 ** to the page and its siblings fit into MemPage.aData[] before returning.
7495 ** In the course of balancing the page and its siblings, cells may be
7496 ** inserted into or removed from the parent page (pParent). Doing so
7497 ** may cause the parent page to become overfull or underfull. If this
7498 ** happens, it is the responsibility of the caller to invoke the correct
7499 ** balancing routine to fix this problem (see the balance() routine).
7501 ** If this routine fails for any reason, it might leave the database
7502 ** in a corrupted state. So if this routine fails, the database should
7503 ** be rolled back.
7505 ** The third argument to this function, aOvflSpace, is a pointer to a
7506 ** buffer big enough to hold one page. If while inserting cells into the parent
7507 ** page (pParent) the parent page becomes overfull, this buffer is
7508 ** used to store the parent's overflow cells. Because this function inserts
7509 ** a maximum of four divider cells into the parent page, and the maximum
7510 ** size of a cell stored within an internal node is always less than 1/4
7511 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
7512 ** enough for all overflow cells.
7514 ** If aOvflSpace is set to a null pointer, this function returns
7515 ** SQLITE_NOMEM.
7517 static int balance_nonroot(
7518 MemPage *pParent, /* Parent page of siblings being balanced */
7519 int iParentIdx, /* Index of "the page" in pParent */
7520 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
7521 int isRoot, /* True if pParent is a root-page */
7522 int bBulk /* True if this call is part of a bulk load */
7524 BtShared *pBt; /* The whole database */
7525 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
7526 int nNew = 0; /* Number of pages in apNew[] */
7527 int nOld; /* Number of pages in apOld[] */
7528 int i, j, k; /* Loop counters */
7529 int nxDiv; /* Next divider slot in pParent->aCell[] */
7530 int rc = SQLITE_OK; /* The return code */
7531 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
7532 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
7533 int usableSpace; /* Bytes in pPage beyond the header */
7534 int pageFlags; /* Value of pPage->aData[0] */
7535 int iSpace1 = 0; /* First unused byte of aSpace1[] */
7536 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
7537 int szScratch; /* Size of scratch memory requested */
7538 MemPage *apOld[NB]; /* pPage and up to two siblings */
7539 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
7540 u8 *pRight; /* Location in parent of right-sibling pointer */
7541 u8 *apDiv[NB-1]; /* Divider cells in pParent */
7542 int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
7543 int cntOld[NB+2]; /* Old index in b.apCell[] */
7544 int szNew[NB+2]; /* Combined size of cells placed on i-th page */
7545 u8 *aSpace1; /* Space for copies of dividers cells */
7546 Pgno pgno; /* Temp var to store a page number in */
7547 u8 abDone[NB+2]; /* True after i'th new page is populated */
7548 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
7549 Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
7550 u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
7551 CellArray b; /* Parsed information on cells being balanced */
7553 memset(abDone, 0, sizeof(abDone));
7554 b.nCell = 0;
7555 b.apCell = 0;
7556 pBt = pParent->pBt;
7557 assert( sqlite3_mutex_held(pBt->mutex) );
7558 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7560 /* At this point pParent may have at most one overflow cell. And if
7561 ** this overflow cell is present, it must be the cell with
7562 ** index iParentIdx. This scenario comes about when this function
7563 ** is called (indirectly) from sqlite3BtreeDelete().
7565 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
7566 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
7568 if( !aOvflSpace ){
7569 return SQLITE_NOMEM_BKPT;
7571 assert( pParent->nFree>=0 );
7573 /* Find the sibling pages to balance. Also locate the cells in pParent
7574 ** that divide the siblings. An attempt is made to find NN siblings on
7575 ** either side of pPage. More siblings are taken from one side, however,
7576 ** if there are fewer than NN siblings on the other side. If pParent
7577 ** has NB or fewer children then all children of pParent are taken.
7579 ** This loop also drops the divider cells from the parent page. This
7580 ** way, the remainder of the function does not have to deal with any
7581 ** overflow cells in the parent page, since if any existed they will
7582 ** have already been removed.
7584 i = pParent->nOverflow + pParent->nCell;
7585 if( i<2 ){
7586 nxDiv = 0;
7587 }else{
7588 assert( bBulk==0 || bBulk==1 );
7589 if( iParentIdx==0 ){
7590 nxDiv = 0;
7591 }else if( iParentIdx==i ){
7592 nxDiv = i-2+bBulk;
7593 }else{
7594 nxDiv = iParentIdx-1;
7596 i = 2-bBulk;
7598 nOld = i+1;
7599 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
7600 pRight = &pParent->aData[pParent->hdrOffset+8];
7601 }else{
7602 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
7604 pgno = get4byte(pRight);
7605 while( 1 ){
7606 rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
7607 if( rc ){
7608 memset(apOld, 0, (i+1)*sizeof(MemPage*));
7609 goto balance_cleanup;
7611 if( apOld[i]->nFree<0 ){
7612 rc = btreeComputeFreeSpace(apOld[i]);
7613 if( rc ){
7614 memset(apOld, 0, (i)*sizeof(MemPage*));
7615 goto balance_cleanup;
7618 if( (i--)==0 ) break;
7620 if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
7621 apDiv[i] = pParent->apOvfl[0];
7622 pgno = get4byte(apDiv[i]);
7623 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7624 pParent->nOverflow = 0;
7625 }else{
7626 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
7627 pgno = get4byte(apDiv[i]);
7628 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7630 /* Drop the cell from the parent page. apDiv[i] still points to
7631 ** the cell within the parent, even though it has been dropped.
7632 ** This is safe because dropping a cell only overwrites the first
7633 ** four bytes of it, and this function does not need the first
7634 ** four bytes of the divider cell. So the pointer is safe to use
7635 ** later on.
7637 ** But not if we are in secure-delete mode. In secure-delete mode,
7638 ** the dropCell() routine will overwrite the entire cell with zeroes.
7639 ** In this case, temporarily copy the cell into the aOvflSpace[]
7640 ** buffer. It will be copied out again as soon as the aSpace[] buffer
7641 ** is allocated. */
7642 if( pBt->btsFlags & BTS_FAST_SECURE ){
7643 int iOff;
7645 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
7646 if( (iOff+szNew[i])>(int)pBt->usableSize ){
7647 rc = SQLITE_CORRUPT_BKPT;
7648 memset(apOld, 0, (i+1)*sizeof(MemPage*));
7649 goto balance_cleanup;
7650 }else{
7651 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
7652 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
7655 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
7659 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
7660 ** alignment */
7661 nMaxCells = nOld*(MX_CELL(pBt) + ArraySize(pParent->apOvfl));
7662 nMaxCells = (nMaxCells + 3)&~3;
7665 ** Allocate space for memory structures
7667 szScratch =
7668 nMaxCells*sizeof(u8*) /* b.apCell */
7669 + nMaxCells*sizeof(u16) /* b.szCell */
7670 + pBt->pageSize; /* aSpace1 */
7672 assert( szScratch<=7*(int)pBt->pageSize );
7673 b.apCell = sqlite3StackAllocRaw(0, szScratch );
7674 if( b.apCell==0 ){
7675 rc = SQLITE_NOMEM_BKPT;
7676 goto balance_cleanup;
7678 b.szCell = (u16*)&b.apCell[nMaxCells];
7679 aSpace1 = (u8*)&b.szCell[nMaxCells];
7680 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
7683 ** Load pointers to all cells on sibling pages and the divider cells
7684 ** into the local b.apCell[] array. Make copies of the divider cells
7685 ** into space obtained from aSpace1[]. The divider cells have already
7686 ** been removed from pParent.
7688 ** If the siblings are on leaf pages, then the child pointers of the
7689 ** divider cells are stripped from the cells before they are copied
7690 ** into aSpace1[]. In this way, all cells in b.apCell[] are without
7691 ** child pointers. If siblings are not leaves, then all cell in
7692 ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
7693 ** are alike.
7695 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
7696 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
7698 b.pRef = apOld[0];
7699 leafCorrection = b.pRef->leaf*4;
7700 leafData = b.pRef->intKeyLeaf;
7701 for(i=0; i<nOld; i++){
7702 MemPage *pOld = apOld[i];
7703 int limit = pOld->nCell;
7704 u8 *aData = pOld->aData;
7705 u16 maskPage = pOld->maskPage;
7706 u8 *piCell = aData + pOld->cellOffset;
7707 u8 *piEnd;
7708 VVA_ONLY( int nCellAtStart = b.nCell; )
7710 /* Verify that all sibling pages are of the same "type" (table-leaf,
7711 ** table-interior, index-leaf, or index-interior).
7713 if( pOld->aData[0]!=apOld[0]->aData[0] ){
7714 rc = SQLITE_CORRUPT_BKPT;
7715 goto balance_cleanup;
7718 /* Load b.apCell[] with pointers to all cells in pOld. If pOld
7719 ** contains overflow cells, include them in the b.apCell[] array
7720 ** in the correct spot.
7722 ** Note that when there are multiple overflow cells, it is always the
7723 ** case that they are sequential and adjacent. This invariant arises
7724 ** because multiple overflows can only occurs when inserting divider
7725 ** cells into a parent on a prior balance, and divider cells are always
7726 ** adjacent and are inserted in order. There is an assert() tagged
7727 ** with "NOTE 1" in the overflow cell insertion loop to prove this
7728 ** invariant.
7730 ** This must be done in advance. Once the balance starts, the cell
7731 ** offset section of the btree page will be overwritten and we will no
7732 ** long be able to find the cells if a pointer to each cell is not saved
7733 ** first.
7735 memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
7736 if( pOld->nOverflow>0 ){
7737 if( NEVER(limit<pOld->aiOvfl[0]) ){
7738 rc = SQLITE_CORRUPT_BKPT;
7739 goto balance_cleanup;
7741 limit = pOld->aiOvfl[0];
7742 for(j=0; j<limit; j++){
7743 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7744 piCell += 2;
7745 b.nCell++;
7747 for(k=0; k<pOld->nOverflow; k++){
7748 assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
7749 b.apCell[b.nCell] = pOld->apOvfl[k];
7750 b.nCell++;
7753 piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
7754 while( piCell<piEnd ){
7755 assert( b.nCell<nMaxCells );
7756 b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7757 piCell += 2;
7758 b.nCell++;
7760 assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );
7762 cntOld[i] = b.nCell;
7763 if( i<nOld-1 && !leafData){
7764 u16 sz = (u16)szNew[i];
7765 u8 *pTemp;
7766 assert( b.nCell<nMaxCells );
7767 b.szCell[b.nCell] = sz;
7768 pTemp = &aSpace1[iSpace1];
7769 iSpace1 += sz;
7770 assert( sz<=pBt->maxLocal+23 );
7771 assert( iSpace1 <= (int)pBt->pageSize );
7772 memcpy(pTemp, apDiv[i], sz);
7773 b.apCell[b.nCell] = pTemp+leafCorrection;
7774 assert( leafCorrection==0 || leafCorrection==4 );
7775 b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
7776 if( !pOld->leaf ){
7777 assert( leafCorrection==0 );
7778 assert( pOld->hdrOffset==0 );
7779 /* The right pointer of the child page pOld becomes the left
7780 ** pointer of the divider cell */
7781 memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
7782 }else{
7783 assert( leafCorrection==4 );
7784 while( b.szCell[b.nCell]<4 ){
7785 /* Do not allow any cells smaller than 4 bytes. If a smaller cell
7786 ** does exist, pad it with 0x00 bytes. */
7787 assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
7788 assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
7789 aSpace1[iSpace1++] = 0x00;
7790 b.szCell[b.nCell]++;
7793 b.nCell++;
7798 ** Figure out the number of pages needed to hold all b.nCell cells.
7799 ** Store this number in "k". Also compute szNew[] which is the total
7800 ** size of all cells on the i-th page and cntNew[] which is the index
7801 ** in b.apCell[] of the cell that divides page i from page i+1.
7802 ** cntNew[k] should equal b.nCell.
7804 ** Values computed by this block:
7806 ** k: The total number of sibling pages
7807 ** szNew[i]: Spaced used on the i-th sibling page.
7808 ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
7809 ** the right of the i-th sibling page.
7810 ** usableSpace: Number of bytes of space available on each sibling.
7813 usableSpace = pBt->usableSize - 12 + leafCorrection;
7814 for(i=k=0; i<nOld; i++, k++){
7815 MemPage *p = apOld[i];
7816 b.apEnd[k] = p->aDataEnd;
7817 b.ixNx[k] = cntOld[i];
7818 if( k && b.ixNx[k]==b.ixNx[k-1] ){
7819 k--; /* Omit b.ixNx[] entry for child pages with no cells */
7821 if( !leafData ){
7822 k++;
7823 b.apEnd[k] = pParent->aDataEnd;
7824 b.ixNx[k] = cntOld[i]+1;
7826 assert( p->nFree>=0 );
7827 szNew[i] = usableSpace - p->nFree;
7828 for(j=0; j<p->nOverflow; j++){
7829 szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
7831 cntNew[i] = cntOld[i];
7833 k = nOld;
7834 for(i=0; i<k; i++){
7835 int sz;
7836 while( szNew[i]>usableSpace ){
7837 if( i+1>=k ){
7838 k = i+2;
7839 if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
7840 szNew[k-1] = 0;
7841 cntNew[k-1] = b.nCell;
7843 sz = 2 + cachedCellSize(&b, cntNew[i]-1);
7844 szNew[i] -= sz;
7845 if( !leafData ){
7846 if( cntNew[i]<b.nCell ){
7847 sz = 2 + cachedCellSize(&b, cntNew[i]);
7848 }else{
7849 sz = 0;
7852 szNew[i+1] += sz;
7853 cntNew[i]--;
7855 while( cntNew[i]<b.nCell ){
7856 sz = 2 + cachedCellSize(&b, cntNew[i]);
7857 if( szNew[i]+sz>usableSpace ) break;
7858 szNew[i] += sz;
7859 cntNew[i]++;
7860 if( !leafData ){
7861 if( cntNew[i]<b.nCell ){
7862 sz = 2 + cachedCellSize(&b, cntNew[i]);
7863 }else{
7864 sz = 0;
7867 szNew[i+1] -= sz;
7869 if( cntNew[i]>=b.nCell ){
7870 k = i+1;
7871 }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
7872 rc = SQLITE_CORRUPT_BKPT;
7873 goto balance_cleanup;
7878 ** The packing computed by the previous block is biased toward the siblings
7879 ** on the left side (siblings with smaller keys). The left siblings are
7880 ** always nearly full, while the right-most sibling might be nearly empty.
7881 ** The next block of code attempts to adjust the packing of siblings to
7882 ** get a better balance.
7884 ** This adjustment is more than an optimization. The packing above might
7885 ** be so out of balance as to be illegal. For example, the right-most
7886 ** sibling might be completely empty. This adjustment is not optional.
7888 for(i=k-1; i>0; i--){
7889 int szRight = szNew[i]; /* Size of sibling on the right */
7890 int szLeft = szNew[i-1]; /* Size of sibling on the left */
7891 int r; /* Index of right-most cell in left sibling */
7892 int d; /* Index of first cell to the left of right sibling */
7894 r = cntNew[i-1] - 1;
7895 d = r + 1 - leafData;
7896 (void)cachedCellSize(&b, d);
7898 assert( d<nMaxCells );
7899 assert( r<nMaxCells );
7900 (void)cachedCellSize(&b, r);
7901 if( szRight!=0
7902 && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
7903 break;
7905 szRight += b.szCell[d] + 2;
7906 szLeft -= b.szCell[r] + 2;
7907 cntNew[i-1] = r;
7908 r--;
7909 d--;
7910 }while( r>=0 );
7911 szNew[i] = szRight;
7912 szNew[i-1] = szLeft;
7913 if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
7914 rc = SQLITE_CORRUPT_BKPT;
7915 goto balance_cleanup;
7919 /* Sanity check: For a non-corrupt database file one of the follwing
7920 ** must be true:
7921 ** (1) We found one or more cells (cntNew[0])>0), or
7922 ** (2) pPage is a virtual root page. A virtual root page is when
7923 ** the real root page is page 1 and we are the only child of
7924 ** that page.
7926 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
7927 TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
7928 apOld[0]->pgno, apOld[0]->nCell,
7929 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
7930 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
7934 ** Allocate k new pages. Reuse old pages where possible.
7936 pageFlags = apOld[0]->aData[0];
7937 for(i=0; i<k; i++){
7938 MemPage *pNew;
7939 if( i<nOld ){
7940 pNew = apNew[i] = apOld[i];
7941 apOld[i] = 0;
7942 rc = sqlite3PagerWrite(pNew->pDbPage);
7943 nNew++;
7944 if( rc ) goto balance_cleanup;
7945 }else{
7946 assert( i>0 );
7947 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
7948 if( rc ) goto balance_cleanup;
7949 zeroPage(pNew, pageFlags);
7950 apNew[i] = pNew;
7951 nNew++;
7952 cntOld[i] = b.nCell;
7954 /* Set the pointer-map entry for the new sibling page. */
7955 if( ISAUTOVACUUM ){
7956 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
7957 if( rc!=SQLITE_OK ){
7958 goto balance_cleanup;
7965 ** Reassign page numbers so that the new pages are in ascending order.
7966 ** This helps to keep entries in the disk file in order so that a scan
7967 ** of the table is closer to a linear scan through the file. That in turn
7968 ** helps the operating system to deliver pages from the disk more rapidly.
7970 ** An O(n^2) insertion sort algorithm is used, but since n is never more
7971 ** than (NB+2) (a small constant), that should not be a problem.
7973 ** When NB==3, this one optimization makes the database about 25% faster
7974 ** for large insertions and deletions.
7976 for(i=0; i<nNew; i++){
7977 aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
7978 aPgFlags[i] = apNew[i]->pDbPage->flags;
7979 for(j=0; j<i; j++){
7980 if( aPgno[j]==aPgno[i] ){
7981 /* This branch is taken if the set of sibling pages somehow contains
7982 ** duplicate entries. This can happen if the database is corrupt.
7983 ** It would be simpler to detect this as part of the loop below, but
7984 ** we do the detection here in order to avoid populating the pager
7985 ** cache with two separate objects associated with the same
7986 ** page number. */
7987 assert( CORRUPT_DB );
7988 rc = SQLITE_CORRUPT_BKPT;
7989 goto balance_cleanup;
7993 for(i=0; i<nNew; i++){
7994 int iBest = 0; /* aPgno[] index of page number to use */
7995 for(j=1; j<nNew; j++){
7996 if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
7998 pgno = aPgOrder[iBest];
7999 aPgOrder[iBest] = 0xffffffff;
8000 if( iBest!=i ){
8001 if( iBest>i ){
8002 sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
8004 sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
8005 apNew[i]->pgno = pgno;
8009 TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
8010 "%d(%d nc=%d) %d(%d nc=%d)\n",
8011 apNew[0]->pgno, szNew[0], cntNew[0],
8012 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
8013 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
8014 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
8015 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
8016 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
8017 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
8018 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
8019 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
8022 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8023 assert( nNew>=1 && nNew<=ArraySize(apNew) );
8024 assert( apNew[nNew-1]!=0 );
8025 put4byte(pRight, apNew[nNew-1]->pgno);
8027 /* If the sibling pages are not leaves, ensure that the right-child pointer
8028 ** of the right-most new sibling page is set to the value that was
8029 ** originally in the same field of the right-most old sibling page. */
8030 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
8031 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
8032 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
8035 /* Make any required updates to pointer map entries associated with
8036 ** cells stored on sibling pages following the balance operation. Pointer
8037 ** map entries associated with divider cells are set by the insertCell()
8038 ** routine. The associated pointer map entries are:
8040 ** a) if the cell contains a reference to an overflow chain, the
8041 ** entry associated with the first page in the overflow chain, and
8043 ** b) if the sibling pages are not leaves, the child page associated
8044 ** with the cell.
8046 ** If the sibling pages are not leaves, then the pointer map entry
8047 ** associated with the right-child of each sibling may also need to be
8048 ** updated. This happens below, after the sibling pages have been
8049 ** populated, not here.
8051 if( ISAUTOVACUUM ){
8052 MemPage *pOld;
8053 MemPage *pNew = pOld = apNew[0];
8054 int cntOldNext = pNew->nCell + pNew->nOverflow;
8055 int iNew = 0;
8056 int iOld = 0;
8058 for(i=0; i<b.nCell; i++){
8059 u8 *pCell = b.apCell[i];
8060 while( i==cntOldNext ){
8061 iOld++;
8062 assert( iOld<nNew || iOld<nOld );
8063 assert( iOld>=0 && iOld<NB );
8064 pOld = iOld<nNew ? apNew[iOld] : apOld[iOld];
8065 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
8067 if( i==cntNew[iNew] ){
8068 pNew = apNew[++iNew];
8069 if( !leafData ) continue;
8072 /* Cell pCell is destined for new sibling page pNew. Originally, it
8073 ** was either part of sibling page iOld (possibly an overflow cell),
8074 ** or else the divider cell to the left of sibling page iOld. So,
8075 ** if sibling page iOld had the same page number as pNew, and if
8076 ** pCell really was a part of sibling page iOld (not a divider or
8077 ** overflow cell), we can skip updating the pointer map entries. */
8078 if( iOld>=nNew
8079 || pNew->pgno!=aPgno[iOld]
8080 || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
8082 if( !leafCorrection ){
8083 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
8085 if( cachedCellSize(&b,i)>pNew->minLocal ){
8086 ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);
8088 if( rc ) goto balance_cleanup;
8093 /* Insert new divider cells into pParent. */
8094 for(i=0; i<nNew-1; i++){
8095 u8 *pCell;
8096 u8 *pTemp;
8097 int sz;
8098 MemPage *pNew = apNew[i];
8099 j = cntNew[i];
8101 assert( j<nMaxCells );
8102 assert( b.apCell[j]!=0 );
8103 pCell = b.apCell[j];
8104 sz = b.szCell[j] + leafCorrection;
8105 pTemp = &aOvflSpace[iOvflSpace];
8106 if( !pNew->leaf ){
8107 memcpy(&pNew->aData[8], pCell, 4);
8108 }else if( leafData ){
8109 /* If the tree is a leaf-data tree, and the siblings are leaves,
8110 ** then there is no divider cell in b.apCell[]. Instead, the divider
8111 ** cell consists of the integer key for the right-most cell of
8112 ** the sibling-page assembled above only.
8114 CellInfo info;
8115 j--;
8116 pNew->xParseCell(pNew, b.apCell[j], &info);
8117 pCell = pTemp;
8118 sz = 4 + putVarint(&pCell[4], info.nKey);
8119 pTemp = 0;
8120 }else{
8121 pCell -= 4;
8122 /* Obscure case for non-leaf-data trees: If the cell at pCell was
8123 ** previously stored on a leaf node, and its reported size was 4
8124 ** bytes, then it may actually be smaller than this
8125 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
8126 ** any cell). But it is important to pass the correct size to
8127 ** insertCell(), so reparse the cell now.
8129 ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
8130 ** and WITHOUT ROWID tables with exactly one column which is the
8131 ** primary key.
8133 if( b.szCell[j]==4 ){
8134 assert(leafCorrection==4);
8135 sz = pParent->xCellSize(pParent, pCell);
8138 iOvflSpace += sz;
8139 assert( sz<=pBt->maxLocal+23 );
8140 assert( iOvflSpace <= (int)pBt->pageSize );
8141 insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
8142 if( rc!=SQLITE_OK ) goto balance_cleanup;
8143 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8146 /* Now update the actual sibling pages. The order in which they are updated
8147 ** is important, as this code needs to avoid disrupting any page from which
8148 ** cells may still to be read. In practice, this means:
8150 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
8151 ** then it is not safe to update page apNew[iPg] until after
8152 ** the left-hand sibling apNew[iPg-1] has been updated.
8154 ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
8155 ** then it is not safe to update page apNew[iPg] until after
8156 ** the right-hand sibling apNew[iPg+1] has been updated.
8158 ** If neither of the above apply, the page is safe to update.
8160 ** The iPg value in the following loop starts at nNew-1 goes down
8161 ** to 0, then back up to nNew-1 again, thus making two passes over
8162 ** the pages. On the initial downward pass, only condition (1) above
8163 ** needs to be tested because (2) will always be true from the previous
8164 ** step. On the upward pass, both conditions are always true, so the
8165 ** upwards pass simply processes pages that were missed on the downward
8166 ** pass.
8168 for(i=1-nNew; i<nNew; i++){
8169 int iPg = i<0 ? -i : i;
8170 assert( iPg>=0 && iPg<nNew );
8171 if( abDone[iPg] ) continue; /* Skip pages already processed */
8172 if( i>=0 /* On the upwards pass, or... */
8173 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
8175 int iNew;
8176 int iOld;
8177 int nNewCell;
8179 /* Verify condition (1): If cells are moving left, update iPg
8180 ** only after iPg-1 has already been updated. */
8181 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
8183 /* Verify condition (2): If cells are moving right, update iPg
8184 ** only after iPg+1 has already been updated. */
8185 assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
8187 if( iPg==0 ){
8188 iNew = iOld = 0;
8189 nNewCell = cntNew[0];
8190 }else{
8191 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
8192 iNew = cntNew[iPg-1] + !leafData;
8193 nNewCell = cntNew[iPg] - iNew;
8196 rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
8197 if( rc ) goto balance_cleanup;
8198 abDone[iPg]++;
8199 apNew[iPg]->nFree = usableSpace-szNew[iPg];
8200 assert( apNew[iPg]->nOverflow==0 );
8201 assert( apNew[iPg]->nCell==nNewCell );
8205 /* All pages have been processed exactly once */
8206 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
8208 assert( nOld>0 );
8209 assert( nNew>0 );
8211 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
8212 /* The root page of the b-tree now contains no cells. The only sibling
8213 ** page is the right-child of the parent. Copy the contents of the
8214 ** child page into the parent, decreasing the overall height of the
8215 ** b-tree structure by one. This is described as the "balance-shallower"
8216 ** sub-algorithm in some documentation.
8218 ** If this is an auto-vacuum database, the call to copyNodeContent()
8219 ** sets all pointer-map entries corresponding to database image pages
8220 ** for which the pointer is stored within the content being copied.
8222 ** It is critical that the child page be defragmented before being
8223 ** copied into the parent, because if the parent is page 1 then it will
8224 ** by smaller than the child due to the database header, and so all the
8225 ** free space needs to be up front.
8227 assert( nNew==1 || CORRUPT_DB );
8228 rc = defragmentPage(apNew[0], -1);
8229 testcase( rc!=SQLITE_OK );
8230 assert( apNew[0]->nFree ==
8231 (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
8232 - apNew[0]->nCell*2)
8233 || rc!=SQLITE_OK
8235 copyNodeContent(apNew[0], pParent, &rc);
8236 freePage(apNew[0], &rc);
8237 }else if( ISAUTOVACUUM && !leafCorrection ){
8238 /* Fix the pointer map entries associated with the right-child of each
8239 ** sibling page. All other pointer map entries have already been taken
8240 ** care of. */
8241 for(i=0; i<nNew; i++){
8242 u32 key = get4byte(&apNew[i]->aData[8]);
8243 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
8247 assert( pParent->isInit );
8248 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
8249 nOld, nNew, b.nCell));
8251 /* Free any old pages that were not reused as new pages.
8253 for(i=nNew; i<nOld; i++){
8254 freePage(apOld[i], &rc);
8257 #if 0
8258 if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
8259 /* The ptrmapCheckPages() contains assert() statements that verify that
8260 ** all pointer map pages are set correctly. This is helpful while
8261 ** debugging. This is usually disabled because a corrupt database may
8262 ** cause an assert() statement to fail. */
8263 ptrmapCheckPages(apNew, nNew);
8264 ptrmapCheckPages(&pParent, 1);
8266 #endif
8269 ** Cleanup before returning.
8271 balance_cleanup:
8272 sqlite3StackFree(0, b.apCell);
8273 for(i=0; i<nOld; i++){
8274 releasePage(apOld[i]);
8276 for(i=0; i<nNew; i++){
8277 releasePage(apNew[i]);
8280 return rc;
8285 ** This function is called when the root page of a b-tree structure is
8286 ** overfull (has one or more overflow pages).
8288 ** A new child page is allocated and the contents of the current root
8289 ** page, including overflow cells, are copied into the child. The root
8290 ** page is then overwritten to make it an empty page with the right-child
8291 ** pointer pointing to the new page.
8293 ** Before returning, all pointer-map entries corresponding to pages
8294 ** that the new child-page now contains pointers to are updated. The
8295 ** entry corresponding to the new right-child pointer of the root
8296 ** page is also updated.
8298 ** If successful, *ppChild is set to contain a reference to the child
8299 ** page and SQLITE_OK is returned. In this case the caller is required
8300 ** to call releasePage() on *ppChild exactly once. If an error occurs,
8301 ** an error code is returned and *ppChild is set to 0.
8303 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
8304 int rc; /* Return value from subprocedures */
8305 MemPage *pChild = 0; /* Pointer to a new child page */
8306 Pgno pgnoChild = 0; /* Page number of the new child page */
8307 BtShared *pBt = pRoot->pBt; /* The BTree */
8309 assert( pRoot->nOverflow>0 );
8310 assert( sqlite3_mutex_held(pBt->mutex) );
8312 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
8313 ** page that will become the new right-child of pPage. Copy the contents
8314 ** of the node stored on pRoot into the new child page.
8316 rc = sqlite3PagerWrite(pRoot->pDbPage);
8317 if( rc==SQLITE_OK ){
8318 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
8319 copyNodeContent(pRoot, pChild, &rc);
8320 if( ISAUTOVACUUM ){
8321 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
8324 if( rc ){
8325 *ppChild = 0;
8326 releasePage(pChild);
8327 return rc;
8329 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
8330 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
8331 assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
8333 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
8335 /* Copy the overflow cells from pRoot to pChild */
8336 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
8337 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
8338 memcpy(pChild->apOvfl, pRoot->apOvfl,
8339 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
8340 pChild->nOverflow = pRoot->nOverflow;
8342 /* Zero the contents of pRoot. Then install pChild as the right-child. */
8343 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
8344 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
8346 *ppChild = pChild;
8347 return SQLITE_OK;
8351 ** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid
8352 ** on the same B-tree as pCur.
8354 ** This can if a database is corrupt with two or more SQL tables
8355 ** pointing to the same b-tree. If an insert occurs on one SQL table
8356 ** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL
8357 ** table linked to the same b-tree. If the secondary insert causes a
8358 ** rebalance, that can change content out from under the cursor on the
8359 ** first SQL table, violating invariants on the first insert.
8361 static int anotherValidCursor(BtCursor *pCur){
8362 BtCursor *pOther;
8363 for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){
8364 if( pOther!=pCur
8365 && pOther->eState==CURSOR_VALID
8366 && pOther->pPage==pCur->pPage
8368 return SQLITE_CORRUPT_BKPT;
8371 return SQLITE_OK;
8375 ** The page that pCur currently points to has just been modified in
8376 ** some way. This function figures out if this modification means the
8377 ** tree needs to be balanced, and if so calls the appropriate balancing
8378 ** routine. Balancing routines are:
8380 ** balance_quick()
8381 ** balance_deeper()
8382 ** balance_nonroot()
8384 static int balance(BtCursor *pCur){
8385 int rc = SQLITE_OK;
8386 const int nMin = pCur->pBt->usableSize * 2 / 3;
8387 u8 aBalanceQuickSpace[13];
8388 u8 *pFree = 0;
8390 VVA_ONLY( int balance_quick_called = 0 );
8391 VVA_ONLY( int balance_deeper_called = 0 );
8393 do {
8394 int iPage;
8395 MemPage *pPage = pCur->pPage;
8397 if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
8398 if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
8399 break;
8400 }else if( (iPage = pCur->iPage)==0 ){
8401 if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){
8402 /* The root page of the b-tree is overfull. In this case call the
8403 ** balance_deeper() function to create a new child for the root-page
8404 ** and copy the current contents of the root-page to it. The
8405 ** next iteration of the do-loop will balance the child page.
8407 assert( balance_deeper_called==0 );
8408 VVA_ONLY( balance_deeper_called++ );
8409 rc = balance_deeper(pPage, &pCur->apPage[1]);
8410 if( rc==SQLITE_OK ){
8411 pCur->iPage = 1;
8412 pCur->ix = 0;
8413 pCur->aiIdx[0] = 0;
8414 pCur->apPage[0] = pPage;
8415 pCur->pPage = pCur->apPage[1];
8416 assert( pCur->pPage->nOverflow );
8418 }else{
8419 break;
8421 }else{
8422 MemPage * const pParent = pCur->apPage[iPage-1];
8423 int const iIdx = pCur->aiIdx[iPage-1];
8425 rc = sqlite3PagerWrite(pParent->pDbPage);
8426 if( rc==SQLITE_OK && pParent->nFree<0 ){
8427 rc = btreeComputeFreeSpace(pParent);
8429 if( rc==SQLITE_OK ){
8430 #ifndef SQLITE_OMIT_QUICKBALANCE
8431 if( pPage->intKeyLeaf
8432 && pPage->nOverflow==1
8433 && pPage->aiOvfl[0]==pPage->nCell
8434 && pParent->pgno!=1
8435 && pParent->nCell==iIdx
8437 /* Call balance_quick() to create a new sibling of pPage on which
8438 ** to store the overflow cell. balance_quick() inserts a new cell
8439 ** into pParent, which may cause pParent overflow. If this
8440 ** happens, the next iteration of the do-loop will balance pParent
8441 ** use either balance_nonroot() or balance_deeper(). Until this
8442 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
8443 ** buffer.
8445 ** The purpose of the following assert() is to check that only a
8446 ** single call to balance_quick() is made for each call to this
8447 ** function. If this were not verified, a subtle bug involving reuse
8448 ** of the aBalanceQuickSpace[] might sneak in.
8450 assert( balance_quick_called==0 );
8451 VVA_ONLY( balance_quick_called++ );
8452 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
8453 }else
8454 #endif
8456 /* In this case, call balance_nonroot() to redistribute cells
8457 ** between pPage and up to 2 of its sibling pages. This involves
8458 ** modifying the contents of pParent, which may cause pParent to
8459 ** become overfull or underfull. The next iteration of the do-loop
8460 ** will balance the parent page to correct this.
8462 ** If the parent page becomes overfull, the overflow cell or cells
8463 ** are stored in the pSpace buffer allocated immediately below.
8464 ** A subsequent iteration of the do-loop will deal with this by
8465 ** calling balance_nonroot() (balance_deeper() may be called first,
8466 ** but it doesn't deal with overflow cells - just moves them to a
8467 ** different page). Once this subsequent call to balance_nonroot()
8468 ** has completed, it is safe to release the pSpace buffer used by
8469 ** the previous call, as the overflow cell data will have been
8470 ** copied either into the body of a database page or into the new
8471 ** pSpace buffer passed to the latter call to balance_nonroot().
8473 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
8474 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
8475 pCur->hints&BTREE_BULKLOAD);
8476 if( pFree ){
8477 /* If pFree is not NULL, it points to the pSpace buffer used
8478 ** by a previous call to balance_nonroot(). Its contents are
8479 ** now stored either on real database pages or within the
8480 ** new pSpace buffer, so it may be safely freed here. */
8481 sqlite3PageFree(pFree);
8484 /* The pSpace buffer will be freed after the next call to
8485 ** balance_nonroot(), or just before this function returns, whichever
8486 ** comes first. */
8487 pFree = pSpace;
8491 pPage->nOverflow = 0;
8493 /* The next iteration of the do-loop balances the parent page. */
8494 releasePage(pPage);
8495 pCur->iPage--;
8496 assert( pCur->iPage>=0 );
8497 pCur->pPage = pCur->apPage[pCur->iPage];
8499 }while( rc==SQLITE_OK );
8501 if( pFree ){
8502 sqlite3PageFree(pFree);
8504 return rc;
8507 /* Overwrite content from pX into pDest. Only do the write if the
8508 ** content is different from what is already there.
8510 static int btreeOverwriteContent(
8511 MemPage *pPage, /* MemPage on which writing will occur */
8512 u8 *pDest, /* Pointer to the place to start writing */
8513 const BtreePayload *pX, /* Source of data to write */
8514 int iOffset, /* Offset of first byte to write */
8515 int iAmt /* Number of bytes to be written */
8517 int nData = pX->nData - iOffset;
8518 if( nData<=0 ){
8519 /* Overwritting with zeros */
8520 int i;
8521 for(i=0; i<iAmt && pDest[i]==0; i++){}
8522 if( i<iAmt ){
8523 int rc = sqlite3PagerWrite(pPage->pDbPage);
8524 if( rc ) return rc;
8525 memset(pDest + i, 0, iAmt - i);
8527 }else{
8528 if( nData<iAmt ){
8529 /* Mixed read data and zeros at the end. Make a recursive call
8530 ** to write the zeros then fall through to write the real data */
8531 int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
8532 iAmt-nData);
8533 if( rc ) return rc;
8534 iAmt = nData;
8536 if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
8537 int rc = sqlite3PagerWrite(pPage->pDbPage);
8538 if( rc ) return rc;
8539 /* In a corrupt database, it is possible for the source and destination
8540 ** buffers to overlap. This is harmless since the database is already
8541 ** corrupt but it does cause valgrind and ASAN warnings. So use
8542 ** memmove(). */
8543 memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
8546 return SQLITE_OK;
8550 ** Overwrite the cell that cursor pCur is pointing to with fresh content
8551 ** contained in pX.
8553 static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
8554 int iOffset; /* Next byte of pX->pData to write */
8555 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
8556 int rc; /* Return code */
8557 MemPage *pPage = pCur->pPage; /* Page being written */
8558 BtShared *pBt; /* Btree */
8559 Pgno ovflPgno; /* Next overflow page to write */
8560 u32 ovflPageSize; /* Size to write on overflow page */
8562 if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd
8563 || pCur->info.pPayload < pPage->aData + pPage->cellOffset
8565 return SQLITE_CORRUPT_BKPT;
8567 /* Overwrite the local portion first */
8568 rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
8569 0, pCur->info.nLocal);
8570 if( rc ) return rc;
8571 if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
8573 /* Now overwrite the overflow pages */
8574 iOffset = pCur->info.nLocal;
8575 assert( nTotal>=0 );
8576 assert( iOffset>=0 );
8577 ovflPgno = get4byte(pCur->info.pPayload + iOffset);
8578 pBt = pPage->pBt;
8579 ovflPageSize = pBt->usableSize - 4;
8581 rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
8582 if( rc ) return rc;
8583 if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){
8584 rc = SQLITE_CORRUPT_BKPT;
8585 }else{
8586 if( iOffset+ovflPageSize<(u32)nTotal ){
8587 ovflPgno = get4byte(pPage->aData);
8588 }else{
8589 ovflPageSize = nTotal - iOffset;
8591 rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
8592 iOffset, ovflPageSize);
8594 sqlite3PagerUnref(pPage->pDbPage);
8595 if( rc ) return rc;
8596 iOffset += ovflPageSize;
8597 }while( iOffset<nTotal );
8598 return SQLITE_OK;
8603 ** Insert a new record into the BTree. The content of the new record
8604 ** is described by the pX object. The pCur cursor is used only to
8605 ** define what table the record should be inserted into, and is left
8606 ** pointing at a random location.
8608 ** For a table btree (used for rowid tables), only the pX.nKey value of
8609 ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
8610 ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
8611 ** hold the content of the row.
8613 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
8614 ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
8615 ** pX.pData,nData,nZero fields must be zero.
8617 ** If the seekResult parameter is non-zero, then a successful call to
8618 ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
8619 ** been performed. In other words, if seekResult!=0 then the cursor
8620 ** is currently pointing to a cell that will be adjacent to the cell
8621 ** to be inserted. If seekResult<0 then pCur points to a cell that is
8622 ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
8623 ** that is larger than (pKey,nKey).
8625 ** If seekResult==0, that means pCur is pointing at some unknown location.
8626 ** In that case, this routine must seek the cursor to the correct insertion
8627 ** point for (pKey,nKey) before doing the insertion. For index btrees,
8628 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
8629 ** key values and pX->aMem can be used instead of pX->pKey to avoid having
8630 ** to decode the key.
8632 int sqlite3BtreeInsert(
8633 BtCursor *pCur, /* Insert data into the table of this cursor */
8634 const BtreePayload *pX, /* Content of the row to be inserted */
8635 int flags, /* True if this is likely an append */
8636 int seekResult /* Result of prior MovetoUnpacked() call */
8638 int rc;
8639 int loc = seekResult; /* -1: before desired location +1: after */
8640 int szNew = 0;
8641 int idx;
8642 MemPage *pPage;
8643 Btree *p = pCur->pBtree;
8644 BtShared *pBt = p->pBt;
8645 unsigned char *oldCell;
8646 unsigned char *newCell = 0;
8648 assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
8650 if( pCur->eState==CURSOR_FAULT ){
8651 assert( pCur->skipNext!=SQLITE_OK );
8652 return pCur->skipNext;
8655 assert( cursorOwnsBtShared(pCur) );
8656 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
8657 && pBt->inTransaction==TRANS_WRITE
8658 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
8659 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8661 /* Assert that the caller has been consistent. If this cursor was opened
8662 ** expecting an index b-tree, then the caller should be inserting blob
8663 ** keys with no associated data. If the cursor was opened expecting an
8664 ** intkey table, the caller should be inserting integer keys with a
8665 ** blob of associated data. */
8666 assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
8668 /* Save the positions of any other cursors open on this table.
8670 ** In some cases, the call to btreeMoveto() below is a no-op. For
8671 ** example, when inserting data into a table with auto-generated integer
8672 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
8673 ** integer key to use. It then calls this function to actually insert the
8674 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
8675 ** that the cursor is already where it needs to be and returns without
8676 ** doing any work. To avoid thwarting these optimizations, it is important
8677 ** not to clear the cursor here.
8679 if( pCur->curFlags & BTCF_Multiple ){
8680 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8681 if( rc ) return rc;
8684 if( pCur->pKeyInfo==0 ){
8685 assert( pX->pKey==0 );
8686 /* If this is an insert into a table b-tree, invalidate any incrblob
8687 ** cursors open on the row being replaced */
8688 invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
8690 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8691 ** to a row with the same key as the new entry being inserted.
8693 #ifdef SQLITE_DEBUG
8694 if( flags & BTREE_SAVEPOSITION ){
8695 assert( pCur->curFlags & BTCF_ValidNKey );
8696 assert( pX->nKey==pCur->info.nKey );
8697 assert( loc==0 );
8699 #endif
8701 /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
8702 ** that the cursor is not pointing to a row to be overwritten.
8703 ** So do a complete check.
8705 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
8706 /* The cursor is pointing to the entry that is to be
8707 ** overwritten */
8708 assert( pX->nData>=0 && pX->nZero>=0 );
8709 if( pCur->info.nSize!=0
8710 && pCur->info.nPayload==(u32)pX->nData+pX->nZero
8712 /* New entry is the same size as the old. Do an overwrite */
8713 return btreeOverwriteCell(pCur, pX);
8715 assert( loc==0 );
8716 }else if( loc==0 ){
8717 /* The cursor is *not* pointing to the cell to be overwritten, nor
8718 ** to an adjacent cell. Move the cursor so that it is pointing either
8719 ** to the cell to be overwritten or an adjacent cell.
8721 rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
8722 if( rc ) return rc;
8724 }else{
8725 /* This is an index or a WITHOUT ROWID table */
8727 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8728 ** to a row with the same key as the new entry being inserted.
8730 assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
8732 /* If the cursor is not already pointing either to the cell to be
8733 ** overwritten, or if a new cell is being inserted, if the cursor is
8734 ** not pointing to an immediately adjacent cell, then move the cursor
8735 ** so that it does.
8737 if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
8738 if( pX->nMem ){
8739 UnpackedRecord r;
8740 r.pKeyInfo = pCur->pKeyInfo;
8741 r.aMem = pX->aMem;
8742 r.nField = pX->nMem;
8743 r.default_rc = 0;
8744 r.errCode = 0;
8745 r.r1 = 0;
8746 r.r2 = 0;
8747 r.eqSeen = 0;
8748 rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
8749 }else{
8750 rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
8752 if( rc ) return rc;
8755 /* If the cursor is currently pointing to an entry to be overwritten
8756 ** and the new content is the same as as the old, then use the
8757 ** overwrite optimization.
8759 if( loc==0 ){
8760 getCellInfo(pCur);
8761 if( pCur->info.nKey==pX->nKey ){
8762 BtreePayload x2;
8763 x2.pData = pX->pKey;
8764 x2.nData = pX->nKey;
8765 x2.nZero = 0;
8766 return btreeOverwriteCell(pCur, &x2);
8771 assert( pCur->eState==CURSOR_VALID
8772 || (pCur->eState==CURSOR_INVALID && loc)
8773 || CORRUPT_DB );
8775 pPage = pCur->pPage;
8776 assert( pPage->intKey || pX->nKey>=0 );
8777 assert( pPage->leaf || !pPage->intKey );
8778 if( pPage->nFree<0 ){
8779 if( pCur->eState>CURSOR_INVALID ){
8780 rc = SQLITE_CORRUPT_BKPT;
8781 }else{
8782 rc = btreeComputeFreeSpace(pPage);
8784 if( rc ) return rc;
8787 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
8788 pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
8789 loc==0 ? "overwrite" : "new entry"));
8790 assert( pPage->isInit );
8791 newCell = pBt->pTmpSpace;
8792 assert( newCell!=0 );
8793 rc = fillInCell(pPage, newCell, pX, &szNew);
8794 if( rc ) goto end_insert;
8795 assert( szNew==pPage->xCellSize(pPage, newCell) );
8796 assert( szNew <= MX_CELL_SIZE(pBt) );
8797 idx = pCur->ix;
8798 if( loc==0 ){
8799 CellInfo info;
8800 assert( idx<pPage->nCell );
8801 rc = sqlite3PagerWrite(pPage->pDbPage);
8802 if( rc ){
8803 goto end_insert;
8805 oldCell = findCell(pPage, idx);
8806 if( !pPage->leaf ){
8807 memcpy(newCell, oldCell, 4);
8809 rc = clearCell(pPage, oldCell, &info);
8810 testcase( pCur->curFlags & BTCF_ValidOvfl );
8811 invalidateOverflowCache(pCur);
8812 if( info.nSize==szNew && info.nLocal==info.nPayload
8813 && (!ISAUTOVACUUM || szNew<pPage->minLocal)
8815 /* Overwrite the old cell with the new if they are the same size.
8816 ** We could also try to do this if the old cell is smaller, then add
8817 ** the leftover space to the free list. But experiments show that
8818 ** doing that is no faster then skipping this optimization and just
8819 ** calling dropCell() and insertCell().
8821 ** This optimization cannot be used on an autovacuum database if the
8822 ** new entry uses overflow pages, as the insertCell() call below is
8823 ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
8824 assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
8825 if( oldCell < pPage->aData+pPage->hdrOffset+10 ){
8826 return SQLITE_CORRUPT_BKPT;
8828 if( oldCell+szNew > pPage->aDataEnd ){
8829 return SQLITE_CORRUPT_BKPT;
8831 memcpy(oldCell, newCell, szNew);
8832 return SQLITE_OK;
8834 dropCell(pPage, idx, info.nSize, &rc);
8835 if( rc ) goto end_insert;
8836 }else if( loc<0 && pPage->nCell>0 ){
8837 assert( pPage->leaf );
8838 idx = ++pCur->ix;
8839 pCur->curFlags &= ~BTCF_ValidNKey;
8840 }else{
8841 assert( pPage->leaf );
8843 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
8844 assert( pPage->nOverflow==0 || rc==SQLITE_OK );
8845 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
8847 /* If no error has occurred and pPage has an overflow cell, call balance()
8848 ** to redistribute the cells within the tree. Since balance() may move
8849 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
8850 ** variables.
8852 ** Previous versions of SQLite called moveToRoot() to move the cursor
8853 ** back to the root page as balance() used to invalidate the contents
8854 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
8855 ** set the cursor state to "invalid". This makes common insert operations
8856 ** slightly faster.
8858 ** There is a subtle but important optimization here too. When inserting
8859 ** multiple records into an intkey b-tree using a single cursor (as can
8860 ** happen while processing an "INSERT INTO ... SELECT" statement), it
8861 ** is advantageous to leave the cursor pointing to the last entry in
8862 ** the b-tree if possible. If the cursor is left pointing to the last
8863 ** entry in the table, and the next row inserted has an integer key
8864 ** larger than the largest existing key, it is possible to insert the
8865 ** row without seeking the cursor. This can be a big performance boost.
8867 pCur->info.nSize = 0;
8868 if( pPage->nOverflow ){
8869 assert( rc==SQLITE_OK );
8870 pCur->curFlags &= ~(BTCF_ValidNKey);
8871 rc = balance(pCur);
8873 /* Must make sure nOverflow is reset to zero even if the balance()
8874 ** fails. Internal data structure corruption will result otherwise.
8875 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
8876 ** from trying to save the current position of the cursor. */
8877 pCur->pPage->nOverflow = 0;
8878 pCur->eState = CURSOR_INVALID;
8879 if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
8880 btreeReleaseAllCursorPages(pCur);
8881 if( pCur->pKeyInfo ){
8882 assert( pCur->pKey==0 );
8883 pCur->pKey = sqlite3Malloc( pX->nKey );
8884 if( pCur->pKey==0 ){
8885 rc = SQLITE_NOMEM;
8886 }else{
8887 memcpy(pCur->pKey, pX->pKey, pX->nKey);
8890 pCur->eState = CURSOR_REQUIRESEEK;
8891 pCur->nKey = pX->nKey;
8894 assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
8896 end_insert:
8897 return rc;
8901 ** Delete the entry that the cursor is pointing to.
8903 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
8904 ** the cursor is left pointing at an arbitrary location after the delete.
8905 ** But if that bit is set, then the cursor is left in a state such that
8906 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
8907 ** as it would have been on if the call to BtreeDelete() had been omitted.
8909 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
8910 ** associated with a single table entry and its indexes. Only one of those
8911 ** deletes is considered the "primary" delete. The primary delete occurs
8912 ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
8913 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
8914 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
8915 ** but which might be used by alternative storage engines.
8917 int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
8918 Btree *p = pCur->pBtree;
8919 BtShared *pBt = p->pBt;
8920 int rc; /* Return code */
8921 MemPage *pPage; /* Page to delete cell from */
8922 unsigned char *pCell; /* Pointer to cell to delete */
8923 int iCellIdx; /* Index of cell to delete */
8924 int iCellDepth; /* Depth of node containing pCell */
8925 CellInfo info; /* Size of the cell being deleted */
8926 int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
8927 u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
8929 assert( cursorOwnsBtShared(pCur) );
8930 assert( pBt->inTransaction==TRANS_WRITE );
8931 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
8932 assert( pCur->curFlags & BTCF_WriteFlag );
8933 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8934 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
8935 assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
8936 if( pCur->eState==CURSOR_REQUIRESEEK ){
8937 rc = btreeRestoreCursorPosition(pCur);
8938 if( rc ) return rc;
8940 assert( pCur->eState==CURSOR_VALID );
8942 iCellDepth = pCur->iPage;
8943 iCellIdx = pCur->ix;
8944 pPage = pCur->pPage;
8945 pCell = findCell(pPage, iCellIdx);
8946 if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ) return SQLITE_CORRUPT;
8948 /* If the bPreserve flag is set to true, then the cursor position must
8949 ** be preserved following this delete operation. If the current delete
8950 ** will cause a b-tree rebalance, then this is done by saving the cursor
8951 ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
8952 ** returning.
8954 ** Or, if the current delete will not cause a rebalance, then the cursor
8955 ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
8956 ** before or after the deleted entry. In this case set bSkipnext to true. */
8957 if( bPreserve ){
8958 if( !pPage->leaf
8959 || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
8960 || pPage->nCell==1 /* See dbfuzz001.test for a test case */
8962 /* A b-tree rebalance will be required after deleting this entry.
8963 ** Save the cursor key. */
8964 rc = saveCursorKey(pCur);
8965 if( rc ) return rc;
8966 }else{
8967 bSkipnext = 1;
8971 /* If the page containing the entry to delete is not a leaf page, move
8972 ** the cursor to the largest entry in the tree that is smaller than
8973 ** the entry being deleted. This cell will replace the cell being deleted
8974 ** from the internal node. The 'previous' entry is used for this instead
8975 ** of the 'next' entry, as the previous entry is always a part of the
8976 ** sub-tree headed by the child page of the cell being deleted. This makes
8977 ** balancing the tree following the delete operation easier. */
8978 if( !pPage->leaf ){
8979 rc = sqlite3BtreePrevious(pCur, 0);
8980 assert( rc!=SQLITE_DONE );
8981 if( rc ) return rc;
8984 /* Save the positions of any other cursors open on this table before
8985 ** making any modifications. */
8986 if( pCur->curFlags & BTCF_Multiple ){
8987 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8988 if( rc ) return rc;
8991 /* If this is a delete operation to remove a row from a table b-tree,
8992 ** invalidate any incrblob cursors open on the row being deleted. */
8993 if( pCur->pKeyInfo==0 ){
8994 invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
8997 /* Make the page containing the entry to be deleted writable. Then free any
8998 ** overflow pages associated with the entry and finally remove the cell
8999 ** itself from within the page. */
9000 rc = sqlite3PagerWrite(pPage->pDbPage);
9001 if( rc ) return rc;
9002 rc = clearCell(pPage, pCell, &info);
9003 dropCell(pPage, iCellIdx, info.nSize, &rc);
9004 if( rc ) return rc;
9006 /* If the cell deleted was not located on a leaf page, then the cursor
9007 ** is currently pointing to the largest entry in the sub-tree headed
9008 ** by the child-page of the cell that was just deleted from an internal
9009 ** node. The cell from the leaf node needs to be moved to the internal
9010 ** node to replace the deleted cell. */
9011 if( !pPage->leaf ){
9012 MemPage *pLeaf = pCur->pPage;
9013 int nCell;
9014 Pgno n;
9015 unsigned char *pTmp;
9017 if( pLeaf->nFree<0 ){
9018 rc = btreeComputeFreeSpace(pLeaf);
9019 if( rc ) return rc;
9021 if( iCellDepth<pCur->iPage-1 ){
9022 n = pCur->apPage[iCellDepth+1]->pgno;
9023 }else{
9024 n = pCur->pPage->pgno;
9026 pCell = findCell(pLeaf, pLeaf->nCell-1);
9027 if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
9028 nCell = pLeaf->xCellSize(pLeaf, pCell);
9029 assert( MX_CELL_SIZE(pBt) >= nCell );
9030 pTmp = pBt->pTmpSpace;
9031 assert( pTmp!=0 );
9032 rc = sqlite3PagerWrite(pLeaf->pDbPage);
9033 if( rc==SQLITE_OK ){
9034 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
9036 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
9037 if( rc ) return rc;
9040 /* Balance the tree. If the entry deleted was located on a leaf page,
9041 ** then the cursor still points to that page. In this case the first
9042 ** call to balance() repairs the tree, and the if(...) condition is
9043 ** never true.
9045 ** Otherwise, if the entry deleted was on an internal node page, then
9046 ** pCur is pointing to the leaf page from which a cell was removed to
9047 ** replace the cell deleted from the internal node. This is slightly
9048 ** tricky as the leaf node may be underfull, and the internal node may
9049 ** be either under or overfull. In this case run the balancing algorithm
9050 ** on the leaf node first. If the balance proceeds far enough up the
9051 ** tree that we can be sure that any problem in the internal node has
9052 ** been corrected, so be it. Otherwise, after balancing the leaf node,
9053 ** walk the cursor up the tree to the internal node and balance it as
9054 ** well. */
9055 rc = balance(pCur);
9056 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
9057 releasePageNotNull(pCur->pPage);
9058 pCur->iPage--;
9059 while( pCur->iPage>iCellDepth ){
9060 releasePage(pCur->apPage[pCur->iPage--]);
9062 pCur->pPage = pCur->apPage[pCur->iPage];
9063 rc = balance(pCur);
9066 if( rc==SQLITE_OK ){
9067 if( bSkipnext ){
9068 assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
9069 assert( pPage==pCur->pPage || CORRUPT_DB );
9070 assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
9071 pCur->eState = CURSOR_SKIPNEXT;
9072 if( iCellIdx>=pPage->nCell ){
9073 pCur->skipNext = -1;
9074 pCur->ix = pPage->nCell-1;
9075 }else{
9076 pCur->skipNext = 1;
9078 }else{
9079 rc = moveToRoot(pCur);
9080 if( bPreserve ){
9081 btreeReleaseAllCursorPages(pCur);
9082 pCur->eState = CURSOR_REQUIRESEEK;
9084 if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
9087 return rc;
9091 ** Create a new BTree table. Write into *piTable the page
9092 ** number for the root page of the new table.
9094 ** The type of type is determined by the flags parameter. Only the
9095 ** following values of flags are currently in use. Other values for
9096 ** flags might not work:
9098 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
9099 ** BTREE_ZERODATA Used for SQL indices
9101 static int btreeCreateTable(Btree *p, Pgno *piTable, int createTabFlags){
9102 BtShared *pBt = p->pBt;
9103 MemPage *pRoot;
9104 Pgno pgnoRoot;
9105 int rc;
9106 int ptfFlags; /* Page-type flage for the root page of new table */
9108 assert( sqlite3BtreeHoldsMutex(p) );
9109 assert( pBt->inTransaction==TRANS_WRITE );
9110 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9112 #ifdef SQLITE_OMIT_AUTOVACUUM
9113 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9114 if( rc ){
9115 return rc;
9117 #else
9118 if( pBt->autoVacuum ){
9119 Pgno pgnoMove; /* Move a page here to make room for the root-page */
9120 MemPage *pPageMove; /* The page to move to. */
9122 /* Creating a new table may probably require moving an existing database
9123 ** to make room for the new tables root page. In case this page turns
9124 ** out to be an overflow page, delete all overflow page-map caches
9125 ** held by open cursors.
9127 invalidateAllOverflowCache(pBt);
9129 /* Read the value of meta[3] from the database to determine where the
9130 ** root page of the new table should go. meta[3] is the largest root-page
9131 ** created so far, so the new root-page is (meta[3]+1).
9133 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
9134 if( pgnoRoot>btreePagecount(pBt) ){
9135 return SQLITE_CORRUPT_BKPT;
9137 pgnoRoot++;
9139 /* The new root-page may not be allocated on a pointer-map page, or the
9140 ** PENDING_BYTE page.
9142 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
9143 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
9144 pgnoRoot++;
9146 assert( pgnoRoot>=3 );
9148 /* Allocate a page. The page that currently resides at pgnoRoot will
9149 ** be moved to the allocated page (unless the allocated page happens
9150 ** to reside at pgnoRoot).
9152 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
9153 if( rc!=SQLITE_OK ){
9154 return rc;
9157 if( pgnoMove!=pgnoRoot ){
9158 /* pgnoRoot is the page that will be used for the root-page of
9159 ** the new table (assuming an error did not occur). But we were
9160 ** allocated pgnoMove. If required (i.e. if it was not allocated
9161 ** by extending the file), the current page at position pgnoMove
9162 ** is already journaled.
9164 u8 eType = 0;
9165 Pgno iPtrPage = 0;
9167 /* Save the positions of any open cursors. This is required in
9168 ** case they are holding a reference to an xFetch reference
9169 ** corresponding to page pgnoRoot. */
9170 rc = saveAllCursors(pBt, 0, 0);
9171 releasePage(pPageMove);
9172 if( rc!=SQLITE_OK ){
9173 return rc;
9176 /* Move the page currently at pgnoRoot to pgnoMove. */
9177 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9178 if( rc!=SQLITE_OK ){
9179 return rc;
9181 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
9182 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
9183 rc = SQLITE_CORRUPT_BKPT;
9185 if( rc!=SQLITE_OK ){
9186 releasePage(pRoot);
9187 return rc;
9189 assert( eType!=PTRMAP_ROOTPAGE );
9190 assert( eType!=PTRMAP_FREEPAGE );
9191 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
9192 releasePage(pRoot);
9194 /* Obtain the page at pgnoRoot */
9195 if( rc!=SQLITE_OK ){
9196 return rc;
9198 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
9199 if( rc!=SQLITE_OK ){
9200 return rc;
9202 rc = sqlite3PagerWrite(pRoot->pDbPage);
9203 if( rc!=SQLITE_OK ){
9204 releasePage(pRoot);
9205 return rc;
9207 }else{
9208 pRoot = pPageMove;
9211 /* Update the pointer-map and meta-data with the new root-page number. */
9212 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
9213 if( rc ){
9214 releasePage(pRoot);
9215 return rc;
9218 /* When the new root page was allocated, page 1 was made writable in
9219 ** order either to increase the database filesize, or to decrement the
9220 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
9222 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
9223 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
9224 if( NEVER(rc) ){
9225 releasePage(pRoot);
9226 return rc;
9229 }else{
9230 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
9231 if( rc ) return rc;
9233 #endif
9234 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
9235 if( createTabFlags & BTREE_INTKEY ){
9236 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
9237 }else{
9238 ptfFlags = PTF_ZERODATA | PTF_LEAF;
9240 zeroPage(pRoot, ptfFlags);
9241 sqlite3PagerUnref(pRoot->pDbPage);
9242 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
9243 *piTable = pgnoRoot;
9244 return SQLITE_OK;
9246 int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){
9247 int rc;
9248 sqlite3BtreeEnter(p);
9249 rc = btreeCreateTable(p, piTable, flags);
9250 sqlite3BtreeLeave(p);
9251 return rc;
9255 ** Erase the given database page and all its children. Return
9256 ** the page to the freelist.
9258 static int clearDatabasePage(
9259 BtShared *pBt, /* The BTree that contains the table */
9260 Pgno pgno, /* Page number to clear */
9261 int freePageFlag, /* Deallocate page if true */
9262 int *pnChange /* Add number of Cells freed to this counter */
9264 MemPage *pPage;
9265 int rc;
9266 unsigned char *pCell;
9267 int i;
9268 int hdr;
9269 CellInfo info;
9271 assert( sqlite3_mutex_held(pBt->mutex) );
9272 if( pgno>btreePagecount(pBt) ){
9273 return SQLITE_CORRUPT_BKPT;
9275 rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
9276 if( rc ) return rc;
9277 if( pPage->bBusy ){
9278 rc = SQLITE_CORRUPT_BKPT;
9279 goto cleardatabasepage_out;
9281 pPage->bBusy = 1;
9282 hdr = pPage->hdrOffset;
9283 for(i=0; i<pPage->nCell; i++){
9284 pCell = findCell(pPage, i);
9285 if( !pPage->leaf ){
9286 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
9287 if( rc ) goto cleardatabasepage_out;
9289 rc = clearCell(pPage, pCell, &info);
9290 if( rc ) goto cleardatabasepage_out;
9292 if( !pPage->leaf ){
9293 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
9294 if( rc ) goto cleardatabasepage_out;
9295 }else if( pnChange ){
9296 assert( pPage->intKey || CORRUPT_DB );
9297 testcase( !pPage->intKey );
9298 *pnChange += pPage->nCell;
9300 if( freePageFlag ){
9301 freePage(pPage, &rc);
9302 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
9303 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
9306 cleardatabasepage_out:
9307 pPage->bBusy = 0;
9308 releasePage(pPage);
9309 return rc;
9313 ** Delete all information from a single table in the database. iTable is
9314 ** the page number of the root of the table. After this routine returns,
9315 ** the root page is empty, but still exists.
9317 ** This routine will fail with SQLITE_LOCKED if there are any open
9318 ** read cursors on the table. Open write cursors are moved to the
9319 ** root of the table.
9321 ** If pnChange is not NULL, then table iTable must be an intkey table. The
9322 ** integer value pointed to by pnChange is incremented by the number of
9323 ** entries in the table.
9325 int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
9326 int rc;
9327 BtShared *pBt = p->pBt;
9328 sqlite3BtreeEnter(p);
9329 assert( p->inTrans==TRANS_WRITE );
9331 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
9333 if( SQLITE_OK==rc ){
9334 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
9335 ** is the root of a table b-tree - if it is not, the following call is
9336 ** a no-op). */
9337 invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
9338 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
9340 sqlite3BtreeLeave(p);
9341 return rc;
9345 ** Delete all information from the single table that pCur is open on.
9347 ** This routine only work for pCur on an ephemeral table.
9349 int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
9350 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
9354 ** Erase all information in a table and add the root of the table to
9355 ** the freelist. Except, the root of the principle table (the one on
9356 ** page 1) is never added to the freelist.
9358 ** This routine will fail with SQLITE_LOCKED if there are any open
9359 ** cursors on the table.
9361 ** If AUTOVACUUM is enabled and the page at iTable is not the last
9362 ** root page in the database file, then the last root page
9363 ** in the database file is moved into the slot formerly occupied by
9364 ** iTable and that last slot formerly occupied by the last root page
9365 ** is added to the freelist instead of iTable. In this say, all
9366 ** root pages are kept at the beginning of the database file, which
9367 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
9368 ** page number that used to be the last root page in the file before
9369 ** the move. If no page gets moved, *piMoved is set to 0.
9370 ** The last root page is recorded in meta[3] and the value of
9371 ** meta[3] is updated by this procedure.
9373 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
9374 int rc;
9375 MemPage *pPage = 0;
9376 BtShared *pBt = p->pBt;
9378 assert( sqlite3BtreeHoldsMutex(p) );
9379 assert( p->inTrans==TRANS_WRITE );
9380 assert( iTable>=2 );
9381 if( iTable>btreePagecount(pBt) ){
9382 return SQLITE_CORRUPT_BKPT;
9385 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
9386 if( rc ) return rc;
9387 rc = sqlite3BtreeClearTable(p, iTable, 0);
9388 if( rc ){
9389 releasePage(pPage);
9390 return rc;
9393 *piMoved = 0;
9395 #ifdef SQLITE_OMIT_AUTOVACUUM
9396 freePage(pPage, &rc);
9397 releasePage(pPage);
9398 #else
9399 if( pBt->autoVacuum ){
9400 Pgno maxRootPgno;
9401 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
9403 if( iTable==maxRootPgno ){
9404 /* If the table being dropped is the table with the largest root-page
9405 ** number in the database, put the root page on the free list.
9407 freePage(pPage, &rc);
9408 releasePage(pPage);
9409 if( rc!=SQLITE_OK ){
9410 return rc;
9412 }else{
9413 /* The table being dropped does not have the largest root-page
9414 ** number in the database. So move the page that does into the
9415 ** gap left by the deleted root-page.
9417 MemPage *pMove;
9418 releasePage(pPage);
9419 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9420 if( rc!=SQLITE_OK ){
9421 return rc;
9423 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
9424 releasePage(pMove);
9425 if( rc!=SQLITE_OK ){
9426 return rc;
9428 pMove = 0;
9429 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
9430 freePage(pMove, &rc);
9431 releasePage(pMove);
9432 if( rc!=SQLITE_OK ){
9433 return rc;
9435 *piMoved = maxRootPgno;
9438 /* Set the new 'max-root-page' value in the database header. This
9439 ** is the old value less one, less one more if that happens to
9440 ** be a root-page number, less one again if that is the
9441 ** PENDING_BYTE_PAGE.
9443 maxRootPgno--;
9444 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
9445 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
9446 maxRootPgno--;
9448 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
9450 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
9451 }else{
9452 freePage(pPage, &rc);
9453 releasePage(pPage);
9455 #endif
9456 return rc;
9458 int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
9459 int rc;
9460 sqlite3BtreeEnter(p);
9461 rc = btreeDropTable(p, iTable, piMoved);
9462 sqlite3BtreeLeave(p);
9463 return rc;
9468 ** This function may only be called if the b-tree connection already
9469 ** has a read or write transaction open on the database.
9471 ** Read the meta-information out of a database file. Meta[0]
9472 ** is the number of free pages currently in the database. Meta[1]
9473 ** through meta[15] are available for use by higher layers. Meta[0]
9474 ** is read-only, the others are read/write.
9476 ** The schema layer numbers meta values differently. At the schema
9477 ** layer (and the SetCookie and ReadCookie opcodes) the number of
9478 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
9480 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
9481 ** of reading the value out of the header, it instead loads the "DataVersion"
9482 ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
9483 ** database file. It is a number computed by the pager. But its access
9484 ** pattern is the same as header meta values, and so it is convenient to
9485 ** read it from this routine.
9487 void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
9488 BtShared *pBt = p->pBt;
9490 sqlite3BtreeEnter(p);
9491 assert( p->inTrans>TRANS_NONE );
9492 assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) );
9493 assert( pBt->pPage1 );
9494 assert( idx>=0 && idx<=15 );
9496 if( idx==BTREE_DATA_VERSION ){
9497 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
9498 }else{
9499 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
9502 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
9503 ** database, mark the database as read-only. */
9504 #ifdef SQLITE_OMIT_AUTOVACUUM
9505 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
9506 pBt->btsFlags |= BTS_READ_ONLY;
9508 #endif
9510 sqlite3BtreeLeave(p);
9514 ** Write meta-information back into the database. Meta[0] is
9515 ** read-only and may not be written.
9517 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
9518 BtShared *pBt = p->pBt;
9519 unsigned char *pP1;
9520 int rc;
9521 assert( idx>=1 && idx<=15 );
9522 sqlite3BtreeEnter(p);
9523 assert( p->inTrans==TRANS_WRITE );
9524 assert( pBt->pPage1!=0 );
9525 pP1 = pBt->pPage1->aData;
9526 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
9527 if( rc==SQLITE_OK ){
9528 put4byte(&pP1[36 + idx*4], iMeta);
9529 #ifndef SQLITE_OMIT_AUTOVACUUM
9530 if( idx==BTREE_INCR_VACUUM ){
9531 assert( pBt->autoVacuum || iMeta==0 );
9532 assert( iMeta==0 || iMeta==1 );
9533 pBt->incrVacuum = (u8)iMeta;
9535 #endif
9537 sqlite3BtreeLeave(p);
9538 return rc;
9542 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
9543 ** number of entries in the b-tree and write the result to *pnEntry.
9545 ** SQLITE_OK is returned if the operation is successfully executed.
9546 ** Otherwise, if an error is encountered (i.e. an IO error or database
9547 ** corruption) an SQLite error code is returned.
9549 int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){
9550 i64 nEntry = 0; /* Value to return in *pnEntry */
9551 int rc; /* Return code */
9553 rc = moveToRoot(pCur);
9554 if( rc==SQLITE_EMPTY ){
9555 *pnEntry = 0;
9556 return SQLITE_OK;
9559 /* Unless an error occurs, the following loop runs one iteration for each
9560 ** page in the B-Tree structure (not including overflow pages).
9562 while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){
9563 int iIdx; /* Index of child node in parent */
9564 MemPage *pPage; /* Current page of the b-tree */
9566 /* If this is a leaf page or the tree is not an int-key tree, then
9567 ** this page contains countable entries. Increment the entry counter
9568 ** accordingly.
9570 pPage = pCur->pPage;
9571 if( pPage->leaf || !pPage->intKey ){
9572 nEntry += pPage->nCell;
9575 /* pPage is a leaf node. This loop navigates the cursor so that it
9576 ** points to the first interior cell that it points to the parent of
9577 ** the next page in the tree that has not yet been visited. The
9578 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
9579 ** of the page, or to the number of cells in the page if the next page
9580 ** to visit is the right-child of its parent.
9582 ** If all pages in the tree have been visited, return SQLITE_OK to the
9583 ** caller.
9585 if( pPage->leaf ){
9586 do {
9587 if( pCur->iPage==0 ){
9588 /* All pages of the b-tree have been visited. Return successfully. */
9589 *pnEntry = nEntry;
9590 return moveToRoot(pCur);
9592 moveToParent(pCur);
9593 }while ( pCur->ix>=pCur->pPage->nCell );
9595 pCur->ix++;
9596 pPage = pCur->pPage;
9599 /* Descend to the child node of the cell that the cursor currently
9600 ** points at. This is the right-child if (iIdx==pPage->nCell).
9602 iIdx = pCur->ix;
9603 if( iIdx==pPage->nCell ){
9604 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
9605 }else{
9606 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
9610 /* An error has occurred. Return an error code. */
9611 return rc;
9615 ** Return the pager associated with a BTree. This routine is used for
9616 ** testing and debugging only.
9618 Pager *sqlite3BtreePager(Btree *p){
9619 return p->pBt->pPager;
9622 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9624 ** Append a message to the error message string.
9626 static void checkAppendMsg(
9627 IntegrityCk *pCheck,
9628 const char *zFormat,
9631 va_list ap;
9632 if( !pCheck->mxErr ) return;
9633 pCheck->mxErr--;
9634 pCheck->nErr++;
9635 va_start(ap, zFormat);
9636 if( pCheck->errMsg.nChar ){
9637 sqlite3_str_append(&pCheck->errMsg, "\n", 1);
9639 if( pCheck->zPfx ){
9640 sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
9642 sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
9643 va_end(ap);
9644 if( pCheck->errMsg.accError==SQLITE_NOMEM ){
9645 pCheck->bOomFault = 1;
9648 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9650 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9653 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
9654 ** corresponds to page iPg is already set.
9656 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9657 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9658 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
9662 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
9664 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9665 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9666 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
9671 ** Add 1 to the reference count for page iPage. If this is the second
9672 ** reference to the page, add an error message to pCheck->zErrMsg.
9673 ** Return 1 if there are 2 or more references to the page and 0 if
9674 ** if this is the first reference to the page.
9676 ** Also check that the page number is in bounds.
9678 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
9679 if( iPage>pCheck->nPage || iPage==0 ){
9680 checkAppendMsg(pCheck, "invalid page number %d", iPage);
9681 return 1;
9683 if( getPageReferenced(pCheck, iPage) ){
9684 checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
9685 return 1;
9687 if( AtomicLoad(&pCheck->db->u1.isInterrupted) ) return 1;
9688 setPageReferenced(pCheck, iPage);
9689 return 0;
9692 #ifndef SQLITE_OMIT_AUTOVACUUM
9694 ** Check that the entry in the pointer-map for page iChild maps to
9695 ** page iParent, pointer type ptrType. If not, append an error message
9696 ** to pCheck.
9698 static void checkPtrmap(
9699 IntegrityCk *pCheck, /* Integrity check context */
9700 Pgno iChild, /* Child page number */
9701 u8 eType, /* Expected pointer map type */
9702 Pgno iParent /* Expected pointer map parent page number */
9704 int rc;
9705 u8 ePtrmapType;
9706 Pgno iPtrmapParent;
9708 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
9709 if( rc!=SQLITE_OK ){
9710 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->bOomFault = 1;
9711 checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
9712 return;
9715 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
9716 checkAppendMsg(pCheck,
9717 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
9718 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
9721 #endif
9724 ** Check the integrity of the freelist or of an overflow page list.
9725 ** Verify that the number of pages on the list is N.
9727 static void checkList(
9728 IntegrityCk *pCheck, /* Integrity checking context */
9729 int isFreeList, /* True for a freelist. False for overflow page list */
9730 Pgno iPage, /* Page number for first page in the list */
9731 u32 N /* Expected number of pages in the list */
9733 int i;
9734 u32 expected = N;
9735 int nErrAtStart = pCheck->nErr;
9736 while( iPage!=0 && pCheck->mxErr ){
9737 DbPage *pOvflPage;
9738 unsigned char *pOvflData;
9739 if( checkRef(pCheck, iPage) ) break;
9740 N--;
9741 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
9742 checkAppendMsg(pCheck, "failed to get page %d", iPage);
9743 break;
9745 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
9746 if( isFreeList ){
9747 u32 n = (u32)get4byte(&pOvflData[4]);
9748 #ifndef SQLITE_OMIT_AUTOVACUUM
9749 if( pCheck->pBt->autoVacuum ){
9750 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
9752 #endif
9753 if( n>pCheck->pBt->usableSize/4-2 ){
9754 checkAppendMsg(pCheck,
9755 "freelist leaf count too big on page %d", iPage);
9756 N--;
9757 }else{
9758 for(i=0; i<(int)n; i++){
9759 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
9760 #ifndef SQLITE_OMIT_AUTOVACUUM
9761 if( pCheck->pBt->autoVacuum ){
9762 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
9764 #endif
9765 checkRef(pCheck, iFreePage);
9767 N -= n;
9770 #ifndef SQLITE_OMIT_AUTOVACUUM
9771 else{
9772 /* If this database supports auto-vacuum and iPage is not the last
9773 ** page in this overflow list, check that the pointer-map entry for
9774 ** the following page matches iPage.
9776 if( pCheck->pBt->autoVacuum && N>0 ){
9777 i = get4byte(pOvflData);
9778 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
9781 #endif
9782 iPage = get4byte(pOvflData);
9783 sqlite3PagerUnref(pOvflPage);
9785 if( N && nErrAtStart==pCheck->nErr ){
9786 checkAppendMsg(pCheck,
9787 "%s is %d but should be %d",
9788 isFreeList ? "size" : "overflow list length",
9789 expected-N, expected);
9792 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9795 ** An implementation of a min-heap.
9797 ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
9798 ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
9799 ** and aHeap[N*2+1].
9801 ** The heap property is this: Every node is less than or equal to both
9802 ** of its daughter nodes. A consequence of the heap property is that the
9803 ** root node aHeap[1] is always the minimum value currently in the heap.
9805 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
9806 ** the heap, preserving the heap property. The btreeHeapPull() routine
9807 ** removes the root element from the heap (the minimum value in the heap)
9808 ** and then moves other nodes around as necessary to preserve the heap
9809 ** property.
9811 ** This heap is used for cell overlap and coverage testing. Each u32
9812 ** entry represents the span of a cell or freeblock on a btree page.
9813 ** The upper 16 bits are the index of the first byte of a range and the
9814 ** lower 16 bits are the index of the last byte of that range.
9816 static void btreeHeapInsert(u32 *aHeap, u32 x){
9817 u32 j, i = ++aHeap[0];
9818 aHeap[i] = x;
9819 while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
9820 x = aHeap[j];
9821 aHeap[j] = aHeap[i];
9822 aHeap[i] = x;
9823 i = j;
9826 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
9827 u32 j, i, x;
9828 if( (x = aHeap[0])==0 ) return 0;
9829 *pOut = aHeap[1];
9830 aHeap[1] = aHeap[x];
9831 aHeap[x] = 0xffffffff;
9832 aHeap[0]--;
9833 i = 1;
9834 while( (j = i*2)<=aHeap[0] ){
9835 if( aHeap[j]>aHeap[j+1] ) j++;
9836 if( aHeap[i]<aHeap[j] ) break;
9837 x = aHeap[i];
9838 aHeap[i] = aHeap[j];
9839 aHeap[j] = x;
9840 i = j;
9842 return 1;
9845 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9847 ** Do various sanity checks on a single page of a tree. Return
9848 ** the tree depth. Root pages return 0. Parents of root pages
9849 ** return 1, and so forth.
9851 ** These checks are done:
9853 ** 1. Make sure that cells and freeblocks do not overlap
9854 ** but combine to completely cover the page.
9855 ** 2. Make sure integer cell keys are in order.
9856 ** 3. Check the integrity of overflow pages.
9857 ** 4. Recursively call checkTreePage on all children.
9858 ** 5. Verify that the depth of all children is the same.
9860 static int checkTreePage(
9861 IntegrityCk *pCheck, /* Context for the sanity check */
9862 Pgno iPage, /* Page number of the page to check */
9863 i64 *piMinKey, /* Write minimum integer primary key here */
9864 i64 maxKey /* Error if integer primary key greater than this */
9866 MemPage *pPage = 0; /* The page being analyzed */
9867 int i; /* Loop counter */
9868 int rc; /* Result code from subroutine call */
9869 int depth = -1, d2; /* Depth of a subtree */
9870 int pgno; /* Page number */
9871 int nFrag; /* Number of fragmented bytes on the page */
9872 int hdr; /* Offset to the page header */
9873 int cellStart; /* Offset to the start of the cell pointer array */
9874 int nCell; /* Number of cells */
9875 int doCoverageCheck = 1; /* True if cell coverage checking should be done */
9876 int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
9877 ** False if IPK must be strictly less than maxKey */
9878 u8 *data; /* Page content */
9879 u8 *pCell; /* Cell content */
9880 u8 *pCellIdx; /* Next element of the cell pointer array */
9881 BtShared *pBt; /* The BtShared object that owns pPage */
9882 u32 pc; /* Address of a cell */
9883 u32 usableSize; /* Usable size of the page */
9884 u32 contentOffset; /* Offset to the start of the cell content area */
9885 u32 *heap = 0; /* Min-heap used for checking cell coverage */
9886 u32 x, prev = 0; /* Next and previous entry on the min-heap */
9887 const char *saved_zPfx = pCheck->zPfx;
9888 int saved_v1 = pCheck->v1;
9889 int saved_v2 = pCheck->v2;
9890 u8 savedIsInit = 0;
9892 /* Check that the page exists
9894 pBt = pCheck->pBt;
9895 usableSize = pBt->usableSize;
9896 if( iPage==0 ) return 0;
9897 if( checkRef(pCheck, iPage) ) return 0;
9898 pCheck->zPfx = "Page %u: ";
9899 pCheck->v1 = iPage;
9900 if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){
9901 checkAppendMsg(pCheck,
9902 "unable to get the page. error code=%d", rc);
9903 goto end_of_check;
9906 /* Clear MemPage.isInit to make sure the corruption detection code in
9907 ** btreeInitPage() is executed. */
9908 savedIsInit = pPage->isInit;
9909 pPage->isInit = 0;
9910 if( (rc = btreeInitPage(pPage))!=0 ){
9911 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
9912 checkAppendMsg(pCheck,
9913 "btreeInitPage() returns error code %d", rc);
9914 goto end_of_check;
9916 if( (rc = btreeComputeFreeSpace(pPage))!=0 ){
9917 assert( rc==SQLITE_CORRUPT );
9918 checkAppendMsg(pCheck, "free space corruption", rc);
9919 goto end_of_check;
9921 data = pPage->aData;
9922 hdr = pPage->hdrOffset;
9924 /* Set up for cell analysis */
9925 pCheck->zPfx = "On tree page %u cell %d: ";
9926 contentOffset = get2byteNotZero(&data[hdr+5]);
9927 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
9929 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
9930 ** number of cells on the page. */
9931 nCell = get2byte(&data[hdr+3]);
9932 assert( pPage->nCell==nCell );
9934 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
9935 ** immediately follows the b-tree page header. */
9936 cellStart = hdr + 12 - 4*pPage->leaf;
9937 assert( pPage->aCellIdx==&data[cellStart] );
9938 pCellIdx = &data[cellStart + 2*(nCell-1)];
9940 if( !pPage->leaf ){
9941 /* Analyze the right-child page of internal pages */
9942 pgno = get4byte(&data[hdr+8]);
9943 #ifndef SQLITE_OMIT_AUTOVACUUM
9944 if( pBt->autoVacuum ){
9945 pCheck->zPfx = "On page %u at right child: ";
9946 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
9948 #endif
9949 depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
9950 keyCanBeEqual = 0;
9951 }else{
9952 /* For leaf pages, the coverage check will occur in the same loop
9953 ** as the other cell checks, so initialize the heap. */
9954 heap = pCheck->heap;
9955 heap[0] = 0;
9958 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
9959 ** integer offsets to the cell contents. */
9960 for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
9961 CellInfo info;
9963 /* Check cell size */
9964 pCheck->v2 = i;
9965 assert( pCellIdx==&data[cellStart + i*2] );
9966 pc = get2byteAligned(pCellIdx);
9967 pCellIdx -= 2;
9968 if( pc<contentOffset || pc>usableSize-4 ){
9969 checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
9970 pc, contentOffset, usableSize-4);
9971 doCoverageCheck = 0;
9972 continue;
9974 pCell = &data[pc];
9975 pPage->xParseCell(pPage, pCell, &info);
9976 if( pc+info.nSize>usableSize ){
9977 checkAppendMsg(pCheck, "Extends off end of page");
9978 doCoverageCheck = 0;
9979 continue;
9982 /* Check for integer primary key out of range */
9983 if( pPage->intKey ){
9984 if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
9985 checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
9987 maxKey = info.nKey;
9988 keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
9991 /* Check the content overflow list */
9992 if( info.nPayload>info.nLocal ){
9993 u32 nPage; /* Number of pages on the overflow chain */
9994 Pgno pgnoOvfl; /* First page of the overflow chain */
9995 assert( pc + info.nSize - 4 <= usableSize );
9996 nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
9997 pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
9998 #ifndef SQLITE_OMIT_AUTOVACUUM
9999 if( pBt->autoVacuum ){
10000 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
10002 #endif
10003 checkList(pCheck, 0, pgnoOvfl, nPage);
10006 if( !pPage->leaf ){
10007 /* Check sanity of left child page for internal pages */
10008 pgno = get4byte(pCell);
10009 #ifndef SQLITE_OMIT_AUTOVACUUM
10010 if( pBt->autoVacuum ){
10011 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
10013 #endif
10014 d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
10015 keyCanBeEqual = 0;
10016 if( d2!=depth ){
10017 checkAppendMsg(pCheck, "Child page depth differs");
10018 depth = d2;
10020 }else{
10021 /* Populate the coverage-checking heap for leaf pages */
10022 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
10025 *piMinKey = maxKey;
10027 /* Check for complete coverage of the page
10029 pCheck->zPfx = 0;
10030 if( doCoverageCheck && pCheck->mxErr>0 ){
10031 /* For leaf pages, the min-heap has already been initialized and the
10032 ** cells have already been inserted. But for internal pages, that has
10033 ** not yet been done, so do it now */
10034 if( !pPage->leaf ){
10035 heap = pCheck->heap;
10036 heap[0] = 0;
10037 for(i=nCell-1; i>=0; i--){
10038 u32 size;
10039 pc = get2byteAligned(&data[cellStart+i*2]);
10040 size = pPage->xCellSize(pPage, &data[pc]);
10041 btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
10044 /* Add the freeblocks to the min-heap
10046 ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
10047 ** is the offset of the first freeblock, or zero if there are no
10048 ** freeblocks on the page.
10050 i = get2byte(&data[hdr+1]);
10051 while( i>0 ){
10052 int size, j;
10053 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10054 size = get2byte(&data[i+2]);
10055 assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
10056 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
10057 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
10058 ** big-endian integer which is the offset in the b-tree page of the next
10059 ** freeblock in the chain, or zero if the freeblock is the last on the
10060 ** chain. */
10061 j = get2byte(&data[i]);
10062 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
10063 ** increasing offset. */
10064 assert( j==0 || j>i+size ); /* Enforced by btreeComputeFreeSpace() */
10065 assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
10066 i = j;
10068 /* Analyze the min-heap looking for overlap between cells and/or
10069 ** freeblocks, and counting the number of untracked bytes in nFrag.
10071 ** Each min-heap entry is of the form: (start_address<<16)|end_address.
10072 ** There is an implied first entry the covers the page header, the cell
10073 ** pointer index, and the gap between the cell pointer index and the start
10074 ** of cell content.
10076 ** The loop below pulls entries from the min-heap in order and compares
10077 ** the start_address against the previous end_address. If there is an
10078 ** overlap, that means bytes are used multiple times. If there is a gap,
10079 ** that gap is added to the fragmentation count.
10081 nFrag = 0;
10082 prev = contentOffset - 1; /* Implied first min-heap entry */
10083 while( btreeHeapPull(heap,&x) ){
10084 if( (prev&0xffff)>=(x>>16) ){
10085 checkAppendMsg(pCheck,
10086 "Multiple uses for byte %u of page %u", x>>16, iPage);
10087 break;
10088 }else{
10089 nFrag += (x>>16) - (prev&0xffff) - 1;
10090 prev = x;
10093 nFrag += usableSize - (prev&0xffff) - 1;
10094 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
10095 ** is stored in the fifth field of the b-tree page header.
10096 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
10097 ** number of fragmented free bytes within the cell content area.
10099 if( heap[0]==0 && nFrag!=data[hdr+7] ){
10100 checkAppendMsg(pCheck,
10101 "Fragmentation of %d bytes reported as %d on page %u",
10102 nFrag, data[hdr+7], iPage);
10106 end_of_check:
10107 if( !doCoverageCheck ) pPage->isInit = savedIsInit;
10108 releasePage(pPage);
10109 pCheck->zPfx = saved_zPfx;
10110 pCheck->v1 = saved_v1;
10111 pCheck->v2 = saved_v2;
10112 return depth+1;
10114 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10116 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
10118 ** This routine does a complete check of the given BTree file. aRoot[] is
10119 ** an array of pages numbers were each page number is the root page of
10120 ** a table. nRoot is the number of entries in aRoot.
10122 ** A read-only or read-write transaction must be opened before calling
10123 ** this function.
10125 ** Write the number of error seen in *pnErr. Except for some memory
10126 ** allocation errors, an error message held in memory obtained from
10127 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
10128 ** returned. If a memory allocation error occurs, NULL is returned.
10130 ** If the first entry in aRoot[] is 0, that indicates that the list of
10131 ** root pages is incomplete. This is a "partial integrity-check". This
10132 ** happens when performing an integrity check on a single table. The
10133 ** zero is skipped, of course. But in addition, the freelist checks
10134 ** and the checks to make sure every page is referenced are also skipped,
10135 ** since obviously it is not possible to know which pages are covered by
10136 ** the unverified btrees. Except, if aRoot[1] is 1, then the freelist
10137 ** checks are still performed.
10139 char *sqlite3BtreeIntegrityCheck(
10140 sqlite3 *db, /* Database connection that is running the check */
10141 Btree *p, /* The btree to be checked */
10142 Pgno *aRoot, /* An array of root pages numbers for individual trees */
10143 int nRoot, /* Number of entries in aRoot[] */
10144 int mxErr, /* Stop reporting errors after this many */
10145 int *pnErr /* Write number of errors seen to this variable */
10147 Pgno i;
10148 IntegrityCk sCheck;
10149 BtShared *pBt = p->pBt;
10150 u64 savedDbFlags = pBt->db->flags;
10151 char zErr[100];
10152 int bPartial = 0; /* True if not checking all btrees */
10153 int bCkFreelist = 1; /* True to scan the freelist */
10154 VVA_ONLY( int nRef );
10155 assert( nRoot>0 );
10157 /* aRoot[0]==0 means this is a partial check */
10158 if( aRoot[0]==0 ){
10159 assert( nRoot>1 );
10160 bPartial = 1;
10161 if( aRoot[1]!=1 ) bCkFreelist = 0;
10164 sqlite3BtreeEnter(p);
10165 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
10166 VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
10167 assert( nRef>=0 );
10168 sCheck.db = db;
10169 sCheck.pBt = pBt;
10170 sCheck.pPager = pBt->pPager;
10171 sCheck.nPage = btreePagecount(sCheck.pBt);
10172 sCheck.mxErr = mxErr;
10173 sCheck.nErr = 0;
10174 sCheck.bOomFault = 0;
10175 sCheck.zPfx = 0;
10176 sCheck.v1 = 0;
10177 sCheck.v2 = 0;
10178 sCheck.aPgRef = 0;
10179 sCheck.heap = 0;
10180 sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
10181 sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
10182 if( sCheck.nPage==0 ){
10183 goto integrity_ck_cleanup;
10186 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
10187 if( !sCheck.aPgRef ){
10188 sCheck.bOomFault = 1;
10189 goto integrity_ck_cleanup;
10191 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
10192 if( sCheck.heap==0 ){
10193 sCheck.bOomFault = 1;
10194 goto integrity_ck_cleanup;
10197 i = PENDING_BYTE_PAGE(pBt);
10198 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
10200 /* Check the integrity of the freelist
10202 if( bCkFreelist ){
10203 sCheck.zPfx = "Main freelist: ";
10204 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
10205 get4byte(&pBt->pPage1->aData[36]));
10206 sCheck.zPfx = 0;
10209 /* Check all the tables.
10211 #ifndef SQLITE_OMIT_AUTOVACUUM
10212 if( !bPartial ){
10213 if( pBt->autoVacuum ){
10214 Pgno mx = 0;
10215 Pgno mxInHdr;
10216 for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
10217 mxInHdr = get4byte(&pBt->pPage1->aData[52]);
10218 if( mx!=mxInHdr ){
10219 checkAppendMsg(&sCheck,
10220 "max rootpage (%d) disagrees with header (%d)",
10221 mx, mxInHdr
10224 }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
10225 checkAppendMsg(&sCheck,
10226 "incremental_vacuum enabled with a max rootpage of zero"
10230 #endif
10231 testcase( pBt->db->flags & SQLITE_CellSizeCk );
10232 pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
10233 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
10234 i64 notUsed;
10235 if( aRoot[i]==0 ) continue;
10236 #ifndef SQLITE_OMIT_AUTOVACUUM
10237 if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){
10238 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
10240 #endif
10241 checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
10243 pBt->db->flags = savedDbFlags;
10245 /* Make sure every page in the file is referenced
10247 if( !bPartial ){
10248 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
10249 #ifdef SQLITE_OMIT_AUTOVACUUM
10250 if( getPageReferenced(&sCheck, i)==0 ){
10251 checkAppendMsg(&sCheck, "Page %d is never used", i);
10253 #else
10254 /* If the database supports auto-vacuum, make sure no tables contain
10255 ** references to pointer-map pages.
10257 if( getPageReferenced(&sCheck, i)==0 &&
10258 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
10259 checkAppendMsg(&sCheck, "Page %d is never used", i);
10261 if( getPageReferenced(&sCheck, i)!=0 &&
10262 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
10263 checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
10265 #endif
10269 /* Clean up and report errors.
10271 integrity_ck_cleanup:
10272 sqlite3PageFree(sCheck.heap);
10273 sqlite3_free(sCheck.aPgRef);
10274 if( sCheck.bOomFault ){
10275 sqlite3_str_reset(&sCheck.errMsg);
10276 sCheck.nErr++;
10278 *pnErr = sCheck.nErr;
10279 if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
10280 /* Make sure this analysis did not leave any unref() pages. */
10281 assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
10282 sqlite3BtreeLeave(p);
10283 return sqlite3StrAccumFinish(&sCheck.errMsg);
10285 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10288 ** Return the full pathname of the underlying database file. Return
10289 ** an empty string if the database is in-memory or a TEMP database.
10291 ** The pager filename is invariant as long as the pager is
10292 ** open so it is safe to access without the BtShared mutex.
10294 const char *sqlite3BtreeGetFilename(Btree *p){
10295 assert( p->pBt->pPager!=0 );
10296 return sqlite3PagerFilename(p->pBt->pPager, 1);
10300 ** Return the pathname of the journal file for this database. The return
10301 ** value of this routine is the same regardless of whether the journal file
10302 ** has been created or not.
10304 ** The pager journal filename is invariant as long as the pager is
10305 ** open so it is safe to access without the BtShared mutex.
10307 const char *sqlite3BtreeGetJournalname(Btree *p){
10308 assert( p->pBt->pPager!=0 );
10309 return sqlite3PagerJournalname(p->pBt->pPager);
10313 ** Return non-zero if a transaction is active.
10315 int sqlite3BtreeIsInTrans(Btree *p){
10316 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
10317 return (p && (p->inTrans==TRANS_WRITE));
10320 #ifndef SQLITE_OMIT_WAL
10322 ** Run a checkpoint on the Btree passed as the first argument.
10324 ** Return SQLITE_LOCKED if this or any other connection has an open
10325 ** transaction on the shared-cache the argument Btree is connected to.
10327 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
10329 int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
10330 int rc = SQLITE_OK;
10331 if( p ){
10332 BtShared *pBt = p->pBt;
10333 sqlite3BtreeEnter(p);
10334 if( pBt->inTransaction!=TRANS_NONE ){
10335 rc = SQLITE_LOCKED;
10336 }else{
10337 rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
10339 sqlite3BtreeLeave(p);
10341 return rc;
10343 #endif
10346 ** Return non-zero if a read (or write) transaction is active.
10348 int sqlite3BtreeIsInReadTrans(Btree *p){
10349 assert( p );
10350 assert( sqlite3_mutex_held(p->db->mutex) );
10351 return p->inTrans!=TRANS_NONE;
10354 int sqlite3BtreeIsInBackup(Btree *p){
10355 assert( p );
10356 assert( sqlite3_mutex_held(p->db->mutex) );
10357 return p->nBackup!=0;
10361 ** This function returns a pointer to a blob of memory associated with
10362 ** a single shared-btree. The memory is used by client code for its own
10363 ** purposes (for example, to store a high-level schema associated with
10364 ** the shared-btree). The btree layer manages reference counting issues.
10366 ** The first time this is called on a shared-btree, nBytes bytes of memory
10367 ** are allocated, zeroed, and returned to the caller. For each subsequent
10368 ** call the nBytes parameter is ignored and a pointer to the same blob
10369 ** of memory returned.
10371 ** If the nBytes parameter is 0 and the blob of memory has not yet been
10372 ** allocated, a null pointer is returned. If the blob has already been
10373 ** allocated, it is returned as normal.
10375 ** Just before the shared-btree is closed, the function passed as the
10376 ** xFree argument when the memory allocation was made is invoked on the
10377 ** blob of allocated memory. The xFree function should not call sqlite3_free()
10378 ** on the memory, the btree layer does that.
10380 void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
10381 BtShared *pBt = p->pBt;
10382 sqlite3BtreeEnter(p);
10383 if( !pBt->pSchema && nBytes ){
10384 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
10385 pBt->xFreeSchema = xFree;
10387 sqlite3BtreeLeave(p);
10388 return pBt->pSchema;
10392 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
10393 ** btree as the argument handle holds an exclusive lock on the
10394 ** sqlite_schema table. Otherwise SQLITE_OK.
10396 int sqlite3BtreeSchemaLocked(Btree *p){
10397 int rc;
10398 assert( sqlite3_mutex_held(p->db->mutex) );
10399 sqlite3BtreeEnter(p);
10400 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
10401 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
10402 sqlite3BtreeLeave(p);
10403 return rc;
10407 #ifndef SQLITE_OMIT_SHARED_CACHE
10409 ** Obtain a lock on the table whose root page is iTab. The
10410 ** lock is a write lock if isWritelock is true or a read lock
10411 ** if it is false.
10413 int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
10414 int rc = SQLITE_OK;
10415 assert( p->inTrans!=TRANS_NONE );
10416 if( p->sharable ){
10417 u8 lockType = READ_LOCK + isWriteLock;
10418 assert( READ_LOCK+1==WRITE_LOCK );
10419 assert( isWriteLock==0 || isWriteLock==1 );
10421 sqlite3BtreeEnter(p);
10422 rc = querySharedCacheTableLock(p, iTab, lockType);
10423 if( rc==SQLITE_OK ){
10424 rc = setSharedCacheTableLock(p, iTab, lockType);
10426 sqlite3BtreeLeave(p);
10428 return rc;
10430 #endif
10432 #ifndef SQLITE_OMIT_INCRBLOB
10434 ** Argument pCsr must be a cursor opened for writing on an
10435 ** INTKEY table currently pointing at a valid table entry.
10436 ** This function modifies the data stored as part of that entry.
10438 ** Only the data content may only be modified, it is not possible to
10439 ** change the length of the data stored. If this function is called with
10440 ** parameters that attempt to write past the end of the existing data,
10441 ** no modifications are made and SQLITE_CORRUPT is returned.
10443 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
10444 int rc;
10445 assert( cursorOwnsBtShared(pCsr) );
10446 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
10447 assert( pCsr->curFlags & BTCF_Incrblob );
10449 rc = restoreCursorPosition(pCsr);
10450 if( rc!=SQLITE_OK ){
10451 return rc;
10453 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
10454 if( pCsr->eState!=CURSOR_VALID ){
10455 return SQLITE_ABORT;
10458 /* Save the positions of all other cursors open on this table. This is
10459 ** required in case any of them are holding references to an xFetch
10460 ** version of the b-tree page modified by the accessPayload call below.
10462 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
10463 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
10464 ** saveAllCursors can only return SQLITE_OK.
10466 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
10467 assert( rc==SQLITE_OK );
10469 /* Check some assumptions:
10470 ** (a) the cursor is open for writing,
10471 ** (b) there is a read/write transaction open,
10472 ** (c) the connection holds a write-lock on the table (if required),
10473 ** (d) there are no conflicting read-locks, and
10474 ** (e) the cursor points at a valid row of an intKey table.
10476 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
10477 return SQLITE_READONLY;
10479 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
10480 && pCsr->pBt->inTransaction==TRANS_WRITE );
10481 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
10482 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
10483 assert( pCsr->pPage->intKey );
10485 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
10489 ** Mark this cursor as an incremental blob cursor.
10491 void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
10492 pCur->curFlags |= BTCF_Incrblob;
10493 pCur->pBtree->hasIncrblobCur = 1;
10495 #endif
10498 ** Set both the "read version" (single byte at byte offset 18) and
10499 ** "write version" (single byte at byte offset 19) fields in the database
10500 ** header to iVersion.
10502 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
10503 BtShared *pBt = pBtree->pBt;
10504 int rc; /* Return code */
10506 assert( iVersion==1 || iVersion==2 );
10508 /* If setting the version fields to 1, do not automatically open the
10509 ** WAL connection, even if the version fields are currently set to 2.
10511 pBt->btsFlags &= ~BTS_NO_WAL;
10512 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
10514 rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
10515 if( rc==SQLITE_OK ){
10516 u8 *aData = pBt->pPage1->aData;
10517 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
10518 rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
10519 if( rc==SQLITE_OK ){
10520 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
10521 if( rc==SQLITE_OK ){
10522 aData[18] = (u8)iVersion;
10523 aData[19] = (u8)iVersion;
10529 pBt->btsFlags &= ~BTS_NO_WAL;
10530 return rc;
10534 ** Return true if the cursor has a hint specified. This routine is
10535 ** only used from within assert() statements
10537 int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
10538 return (pCsr->hints & mask)!=0;
10542 ** Return true if the given Btree is read-only.
10544 int sqlite3BtreeIsReadonly(Btree *p){
10545 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
10549 ** Return the size of the header added to each page by this module.
10551 int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
10553 #if !defined(SQLITE_OMIT_SHARED_CACHE)
10555 ** Return true if the Btree passed as the only argument is sharable.
10557 int sqlite3BtreeSharable(Btree *p){
10558 return p->sharable;
10562 ** Return the number of connections to the BtShared object accessed by
10563 ** the Btree handle passed as the only argument. For private caches
10564 ** this is always 1. For shared caches it may be 1 or greater.
10566 int sqlite3BtreeConnectionCount(Btree *p){
10567 testcase( p->sharable );
10568 return p->pBt->nRef;
10570 #endif