OLD | NEW |
1 /* | 1 /* |
2 ** 2004 April 6 | 2 ** 2004 April 6 |
3 ** | 3 ** |
4 ** The author disclaims copyright to this source code. In place of | 4 ** The author disclaims copyright to this source code. In place of |
5 ** a legal notice, here is a blessing: | 5 ** a legal notice, here is a blessing: |
6 ** | 6 ** |
7 ** May you do good and not evil. | 7 ** May you do good and not evil. |
8 ** May you find forgiveness for yourself and forgive others. | 8 ** May you find forgiveness for yourself and forgive others. |
9 ** May you share freely, never taking more than you give. | 9 ** May you share freely, never taking more than you give. |
10 ** | 10 ** |
11 ************************************************************************* | 11 ************************************************************************* |
12 ** This file implements a external (disk-based) database using BTrees. | 12 ** This file implements an external (disk-based) database using BTrees. |
13 ** See the header comment on "btreeInt.h" for additional information. | 13 ** See the header comment on "btreeInt.h" for additional information. |
14 ** Including a description of file format and an overview of operation. | 14 ** Including a description of file format and an overview of operation. |
15 */ | 15 */ |
16 #include "btreeInt.h" | 16 #include "btreeInt.h" |
17 | 17 |
18 /* | 18 /* |
19 ** The header string that appears at the beginning of every | 19 ** The header string that appears at the beginning of every |
20 ** SQLite database. | 20 ** SQLite database. |
21 */ | 21 */ |
22 static const char zMagicHeader[] = SQLITE_FILE_HEADER; | 22 static const char zMagicHeader[] = SQLITE_FILE_HEADER; |
(...skipping 13 matching lines...) Expand all Loading... |
36 ** Extract a 2-byte big-endian integer from an array of unsigned bytes. | 36 ** Extract a 2-byte big-endian integer from an array of unsigned bytes. |
37 ** But if the value is zero, make it 65536. | 37 ** But if the value is zero, make it 65536. |
38 ** | 38 ** |
39 ** This routine is used to extract the "offset to cell content area" value | 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 | 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. | 41 ** is empty, the offset should be 65536, but the 2-byte value stores zero. |
42 ** This routine makes the necessary adjustment to 65536. | 42 ** This routine makes the necessary adjustment to 65536. |
43 */ | 43 */ |
44 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1) | 44 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1) |
45 | 45 |
| 46 /* |
| 47 ** Values passed as the 5th argument to allocateBtreePage() |
| 48 */ |
| 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 */ |
| 52 |
| 53 /* |
| 54 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not |
| 55 ** defined, or 0 if it is. For example: |
| 56 ** |
| 57 ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum); |
| 58 */ |
| 59 #ifndef SQLITE_OMIT_AUTOVACUUM |
| 60 #define IfNotOmitAV(expr) (expr) |
| 61 #else |
| 62 #define IfNotOmitAV(expr) 0 |
| 63 #endif |
| 64 |
46 #ifndef SQLITE_OMIT_SHARED_CACHE | 65 #ifndef SQLITE_OMIT_SHARED_CACHE |
47 /* | 66 /* |
48 ** A list of BtShared objects that are eligible for participation | 67 ** A list of BtShared objects that are eligible for participation |
49 ** in shared cache. This variable has file scope during normal builds, | 68 ** in shared cache. This variable has file scope during normal builds, |
50 ** but the test harness needs to access it so we make it global for | 69 ** but the test harness needs to access it so we make it global for |
51 ** test builds. | 70 ** test builds. |
52 ** | 71 ** |
53 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER. | 72 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER. |
54 */ | 73 */ |
55 #ifdef SQLITE_TEST | 74 #ifdef SQLITE_TEST |
(...skipping 80 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
136 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted)) | 155 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted)) |
137 ){ | 156 ){ |
138 return 1; | 157 return 1; |
139 } | 158 } |
140 | 159 |
141 /* If the client is reading or writing an index and the schema is | 160 /* If the client is reading or writing an index and the schema is |
142 ** not loaded, then it is too difficult to actually check to see if | 161 ** not loaded, then it is too difficult to actually check to see if |
143 ** the correct locks are held. So do not bother - just return true. | 162 ** the correct locks are held. So do not bother - just return true. |
144 ** This case does not come up very often anyhow. | 163 ** This case does not come up very often anyhow. |
145 */ | 164 */ |
146 if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){ | 165 if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){ |
147 return 1; | 166 return 1; |
148 } | 167 } |
149 | 168 |
150 /* Figure out the root-page that the lock should be held on. For table | 169 /* Figure out the root-page that the lock should be held on. For table |
151 ** b-trees, this is just the root page of the b-tree being read or | 170 ** b-trees, this is just the root page of the b-tree being read or |
152 ** written. For index b-trees, it is the root page of the associated | 171 ** written. For index b-trees, it is the root page of the associated |
153 ** table. */ | 172 ** table. */ |
154 if( isIndex ){ | 173 if( isIndex ){ |
155 HashElem *p; | 174 HashElem *p; |
156 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){ | 175 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){ |
(...skipping 79 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
236 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE ); | 255 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE ); |
237 | 256 |
238 /* This routine is a no-op if the shared-cache is not enabled */ | 257 /* This routine is a no-op if the shared-cache is not enabled */ |
239 if( !p->sharable ){ | 258 if( !p->sharable ){ |
240 return SQLITE_OK; | 259 return SQLITE_OK; |
241 } | 260 } |
242 | 261 |
243 /* If some other connection is holding an exclusive lock, the | 262 /* If some other connection is holding an exclusive lock, the |
244 ** requested lock may not be obtained. | 263 ** requested lock may not be obtained. |
245 */ | 264 */ |
246 if( pBt->pWriter!=p && pBt->isExclusive ){ | 265 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){ |
247 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db); | 266 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db); |
248 return SQLITE_LOCKED_SHAREDCACHE; | 267 return SQLITE_LOCKED_SHAREDCACHE; |
249 } | 268 } |
250 | 269 |
251 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ | 270 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ |
252 /* The condition (pIter->eLock!=eLock) in the following if(...) | 271 /* The condition (pIter->eLock!=eLock) in the following if(...) |
253 ** statement is a simplification of: | 272 ** statement is a simplification of: |
254 ** | 273 ** |
255 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK) | 274 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK) |
256 ** | 275 ** |
257 ** since we know that if eLock==WRITE_LOCK, then no other connection | 276 ** since we know that if eLock==WRITE_LOCK, then no other connection |
258 ** may hold a WRITE_LOCK on any table in this file (since there can | 277 ** may hold a WRITE_LOCK on any table in this file (since there can |
259 ** only be a single writer). | 278 ** only be a single writer). |
260 */ | 279 */ |
261 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK ); | 280 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK ); |
262 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK); | 281 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK); |
263 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){ | 282 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){ |
264 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db); | 283 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db); |
265 if( eLock==WRITE_LOCK ){ | 284 if( eLock==WRITE_LOCK ){ |
266 assert( p==pBt->pWriter ); | 285 assert( p==pBt->pWriter ); |
267 pBt->isPending = 1; | 286 pBt->btsFlags |= BTS_PENDING; |
268 } | 287 } |
269 return SQLITE_LOCKED_SHAREDCACHE; | 288 return SQLITE_LOCKED_SHAREDCACHE; |
270 } | 289 } |
271 } | 290 } |
272 return SQLITE_OK; | 291 return SQLITE_OK; |
273 } | 292 } |
274 #endif /* !SQLITE_OMIT_SHARED_CACHE */ | 293 #endif /* !SQLITE_OMIT_SHARED_CACHE */ |
275 | 294 |
276 #ifndef SQLITE_OMIT_SHARED_CACHE | 295 #ifndef SQLITE_OMIT_SHARED_CACHE |
277 /* | 296 /* |
(...skipping 67 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
345 return SQLITE_OK; | 364 return SQLITE_OK; |
346 } | 365 } |
347 #endif /* !SQLITE_OMIT_SHARED_CACHE */ | 366 #endif /* !SQLITE_OMIT_SHARED_CACHE */ |
348 | 367 |
349 #ifndef SQLITE_OMIT_SHARED_CACHE | 368 #ifndef SQLITE_OMIT_SHARED_CACHE |
350 /* | 369 /* |
351 ** Release all the table locks (locks obtained via calls to | 370 ** Release all the table locks (locks obtained via calls to |
352 ** the setSharedCacheTableLock() procedure) held by Btree object p. | 371 ** the setSharedCacheTableLock() procedure) held by Btree object p. |
353 ** | 372 ** |
354 ** This function assumes that Btree p has an open read or write | 373 ** This function assumes that Btree p has an open read or write |
355 ** transaction. If it does not, then the BtShared.isPending variable | 374 ** transaction. If it does not, then the BTS_PENDING flag |
356 ** may be incorrectly cleared. | 375 ** may be incorrectly cleared. |
357 */ | 376 */ |
358 static void clearAllSharedCacheTableLocks(Btree *p){ | 377 static void clearAllSharedCacheTableLocks(Btree *p){ |
359 BtShared *pBt = p->pBt; | 378 BtShared *pBt = p->pBt; |
360 BtLock **ppIter = &pBt->pLock; | 379 BtLock **ppIter = &pBt->pLock; |
361 | 380 |
362 assert( sqlite3BtreeHoldsMutex(p) ); | 381 assert( sqlite3BtreeHoldsMutex(p) ); |
363 assert( p->sharable || 0==*ppIter ); | 382 assert( p->sharable || 0==*ppIter ); |
364 assert( p->inTrans>0 ); | 383 assert( p->inTrans>0 ); |
365 | 384 |
366 while( *ppIter ){ | 385 while( *ppIter ){ |
367 BtLock *pLock = *ppIter; | 386 BtLock *pLock = *ppIter; |
368 assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree ); | 387 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree ); |
369 assert( pLock->pBtree->inTrans>=pLock->eLock ); | 388 assert( pLock->pBtree->inTrans>=pLock->eLock ); |
370 if( pLock->pBtree==p ){ | 389 if( pLock->pBtree==p ){ |
371 *ppIter = pLock->pNext; | 390 *ppIter = pLock->pNext; |
372 assert( pLock->iTable!=1 || pLock==&p->lock ); | 391 assert( pLock->iTable!=1 || pLock==&p->lock ); |
373 if( pLock->iTable!=1 ){ | 392 if( pLock->iTable!=1 ){ |
374 sqlite3_free(pLock); | 393 sqlite3_free(pLock); |
375 } | 394 } |
376 }else{ | 395 }else{ |
377 ppIter = &pLock->pNext; | 396 ppIter = &pLock->pNext; |
378 } | 397 } |
379 } | 398 } |
380 | 399 |
381 assert( pBt->isPending==0 || pBt->pWriter ); | 400 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter ); |
382 if( pBt->pWriter==p ){ | 401 if( pBt->pWriter==p ){ |
383 pBt->pWriter = 0; | 402 pBt->pWriter = 0; |
384 pBt->isExclusive = 0; | 403 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING); |
385 pBt->isPending = 0; | |
386 }else if( pBt->nTransaction==2 ){ | 404 }else if( pBt->nTransaction==2 ){ |
387 /* This function is called when Btree p is concluding its | 405 /* This function is called when Btree p is concluding its |
388 ** transaction. If there currently exists a writer, and p is not | 406 ** transaction. If there currently exists a writer, and p is not |
389 ** that writer, then the number of locks held by connections other | 407 ** that writer, then the number of locks held by connections other |
390 ** than the writer must be about to drop to zero. In this case | 408 ** than the writer must be about to drop to zero. In this case |
391 ** set the isPending flag to 0. | 409 ** set the BTS_PENDING flag to 0. |
392 ** | 410 ** |
393 ** If there is not currently a writer, then BtShared.isPending must | 411 ** If there is not currently a writer, then BTS_PENDING must |
394 ** be zero already. So this next line is harmless in that case. | 412 ** be zero already. So this next line is harmless in that case. |
395 */ | 413 */ |
396 pBt->isPending = 0; | 414 pBt->btsFlags &= ~BTS_PENDING; |
397 } | 415 } |
398 } | 416 } |
399 | 417 |
400 /* | 418 /* |
401 ** This function changes all write-locks held by Btree p into read-locks. | 419 ** This function changes all write-locks held by Btree p into read-locks. |
402 */ | 420 */ |
403 static void downgradeAllSharedCacheTableLocks(Btree *p){ | 421 static void downgradeAllSharedCacheTableLocks(Btree *p){ |
404 BtShared *pBt = p->pBt; | 422 BtShared *pBt = p->pBt; |
405 if( pBt->pWriter==p ){ | 423 if( pBt->pWriter==p ){ |
406 BtLock *pLock; | 424 BtLock *pLock; |
407 pBt->pWriter = 0; | 425 pBt->pWriter = 0; |
408 pBt->isExclusive = 0; | 426 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING); |
409 pBt->isPending = 0; | |
410 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){ | 427 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){ |
411 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p ); | 428 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p ); |
412 pLock->eLock = READ_LOCK; | 429 pLock->eLock = READ_LOCK; |
413 } | 430 } |
414 } | 431 } |
415 } | 432 } |
416 | 433 |
417 #endif /* SQLITE_OMIT_SHARED_CACHE */ | 434 #endif /* SQLITE_OMIT_SHARED_CACHE */ |
418 | 435 |
419 static void releasePage(MemPage *pPage); /* Forward reference */ | 436 static void releasePage(MemPage *pPage); /* Forward reference */ |
420 | 437 |
421 /* | 438 /* |
422 ***** This routine is used inside of assert() only **** | 439 ***** This routine is used inside of assert() only **** |
423 ** | 440 ** |
424 ** Verify that the cursor holds the mutex on its BtShared | 441 ** Verify that the cursor holds the mutex on its BtShared |
425 */ | 442 */ |
426 #ifdef SQLITE_DEBUG | 443 #ifdef SQLITE_DEBUG |
427 static int cursorHoldsMutex(BtCursor *p){ | 444 static int cursorHoldsMutex(BtCursor *p){ |
428 return sqlite3_mutex_held(p->pBt->mutex); | 445 return sqlite3_mutex_held(p->pBt->mutex); |
429 } | 446 } |
430 #endif | 447 #endif |
431 | 448 |
432 | |
433 #ifndef SQLITE_OMIT_INCRBLOB | |
434 /* | 449 /* |
435 ** Invalidate the overflow page-list cache for cursor pCur, if any. | 450 ** Invalidate the overflow cache of the cursor passed as the first argument. |
| 451 ** on the shared btree structure pBt. |
436 */ | 452 */ |
437 static void invalidateOverflowCache(BtCursor *pCur){ | 453 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl) |
438 assert( cursorHoldsMutex(pCur) ); | |
439 sqlite3_free(pCur->aOverflow); | |
440 pCur->aOverflow = 0; | |
441 } | |
442 | 454 |
443 /* | 455 /* |
444 ** Invalidate the overflow page-list cache for all cursors opened | 456 ** Invalidate the overflow page-list cache for all cursors opened |
445 ** on the shared btree structure pBt. | 457 ** on the shared btree structure pBt. |
446 */ | 458 */ |
447 static void invalidateAllOverflowCache(BtShared *pBt){ | 459 static void invalidateAllOverflowCache(BtShared *pBt){ |
448 BtCursor *p; | 460 BtCursor *p; |
449 assert( sqlite3_mutex_held(pBt->mutex) ); | 461 assert( sqlite3_mutex_held(pBt->mutex) ); |
450 for(p=pBt->pCursor; p; p=p->pNext){ | 462 for(p=pBt->pCursor; p; p=p->pNext){ |
451 invalidateOverflowCache(p); | 463 invalidateOverflowCache(p); |
452 } | 464 } |
453 } | 465 } |
454 | 466 |
| 467 #ifndef SQLITE_OMIT_INCRBLOB |
455 /* | 468 /* |
456 ** This function is called before modifying the contents of a table | 469 ** This function is called before modifying the contents of a table |
457 ** to invalidate any incrblob cursors that are open on the | 470 ** to invalidate any incrblob cursors that are open on the |
458 ** row or one of the rows being modified. | 471 ** row or one of the rows being modified. |
459 ** | 472 ** |
460 ** If argument isClearTable is true, then the entire contents of the | 473 ** If argument isClearTable is true, then the entire contents of the |
461 ** table is about to be deleted. In this case invalidate all incrblob | 474 ** table is about to be deleted. In this case invalidate all incrblob |
462 ** cursors open on any row within the table with root-page pgnoRoot. | 475 ** cursors open on any row within the table with root-page pgnoRoot. |
463 ** | 476 ** |
464 ** Otherwise, if argument isClearTable is false, then the row with | 477 ** Otherwise, if argument isClearTable is false, then the row with |
465 ** rowid iRow is being replaced or deleted. In this case invalidate | 478 ** rowid iRow is being replaced or deleted. In this case invalidate |
466 ** only those incrblob cursors open on that specific row. | 479 ** only those incrblob cursors open on that specific row. |
467 */ | 480 */ |
468 static void invalidateIncrblobCursors( | 481 static void invalidateIncrblobCursors( |
469 Btree *pBtree, /* The database file to check */ | 482 Btree *pBtree, /* The database file to check */ |
470 i64 iRow, /* The rowid that might be changing */ | 483 i64 iRow, /* The rowid that might be changing */ |
471 int isClearTable /* True if all rows are being deleted */ | 484 int isClearTable /* True if all rows are being deleted */ |
472 ){ | 485 ){ |
473 BtCursor *p; | 486 BtCursor *p; |
474 BtShared *pBt = pBtree->pBt; | 487 BtShared *pBt = pBtree->pBt; |
475 assert( sqlite3BtreeHoldsMutex(pBtree) ); | 488 assert( sqlite3BtreeHoldsMutex(pBtree) ); |
476 for(p=pBt->pCursor; p; p=p->pNext){ | 489 for(p=pBt->pCursor; p; p=p->pNext){ |
477 if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){ | 490 if( (p->curFlags & BTCF_Incrblob)!=0 |
| 491 && (isClearTable || p->info.nKey==iRow) |
| 492 ){ |
478 p->eState = CURSOR_INVALID; | 493 p->eState = CURSOR_INVALID; |
479 } | 494 } |
480 } | 495 } |
481 } | 496 } |
482 | 497 |
483 #else | 498 #else |
484 /* Stub functions when INCRBLOB is omitted */ | 499 /* Stub function when INCRBLOB is omitted */ |
485 #define invalidateOverflowCache(x) | |
486 #define invalidateAllOverflowCache(x) | |
487 #define invalidateIncrblobCursors(x,y,z) | 500 #define invalidateIncrblobCursors(x,y,z) |
488 #endif /* SQLITE_OMIT_INCRBLOB */ | 501 #endif /* SQLITE_OMIT_INCRBLOB */ |
489 | 502 |
490 /* | 503 /* |
491 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called | 504 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called |
492 ** when a page that previously contained data becomes a free-list leaf | 505 ** when a page that previously contained data becomes a free-list leaf |
493 ** page. | 506 ** page. |
494 ** | 507 ** |
495 ** The BtShared.pHasContent bitvec exists to work around an obscure | 508 ** The BtShared.pHasContent bitvec exists to work around an obscure |
496 ** bug caused by the interaction of two useful IO optimizations surrounding | 509 ** bug caused by the interaction of two useful IO optimizations surrounding |
(...skipping 55 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
552 /* | 565 /* |
553 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be | 566 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be |
554 ** invoked at the conclusion of each write-transaction. | 567 ** invoked at the conclusion of each write-transaction. |
555 */ | 568 */ |
556 static void btreeClearHasContent(BtShared *pBt){ | 569 static void btreeClearHasContent(BtShared *pBt){ |
557 sqlite3BitvecDestroy(pBt->pHasContent); | 570 sqlite3BitvecDestroy(pBt->pHasContent); |
558 pBt->pHasContent = 0; | 571 pBt->pHasContent = 0; |
559 } | 572 } |
560 | 573 |
561 /* | 574 /* |
| 575 ** Release all of the apPage[] pages for a cursor. |
| 576 */ |
| 577 static void btreeReleaseAllCursorPages(BtCursor *pCur){ |
| 578 int i; |
| 579 for(i=0; i<=pCur->iPage; i++){ |
| 580 releasePage(pCur->apPage[i]); |
| 581 pCur->apPage[i] = 0; |
| 582 } |
| 583 pCur->iPage = -1; |
| 584 } |
| 585 |
| 586 |
| 587 /* |
562 ** Save the current cursor position in the variables BtCursor.nKey | 588 ** Save the current cursor position in the variables BtCursor.nKey |
563 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK. | 589 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK. |
564 ** | 590 ** |
565 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID) | 591 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID) |
566 ** prior to calling this routine. | 592 ** prior to calling this routine. |
567 */ | 593 */ |
568 static int saveCursorPosition(BtCursor *pCur){ | 594 static int saveCursorPosition(BtCursor *pCur){ |
569 int rc; | 595 int rc; |
570 | 596 |
571 assert( CURSOR_VALID==pCur->eState ); | 597 assert( CURSOR_VALID==pCur->eState ); |
572 assert( 0==pCur->pKey ); | 598 assert( 0==pCur->pKey ); |
573 assert( cursorHoldsMutex(pCur) ); | 599 assert( cursorHoldsMutex(pCur) ); |
574 | 600 |
575 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey); | 601 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey); |
576 assert( rc==SQLITE_OK ); /* KeySize() cannot fail */ | 602 assert( rc==SQLITE_OK ); /* KeySize() cannot fail */ |
577 | 603 |
578 /* If this is an intKey table, then the above call to BtreeKeySize() | 604 /* If this is an intKey table, then the above call to BtreeKeySize() |
579 ** stores the integer key in pCur->nKey. In this case this value is | 605 ** stores the integer key in pCur->nKey. In this case this value is |
580 ** all that is required. Otherwise, if pCur is not open on an intKey | 606 ** all that is required. Otherwise, if pCur is not open on an intKey |
581 ** table, then malloc space for and store the pCur->nKey bytes of key | 607 ** table, then malloc space for and store the pCur->nKey bytes of key |
582 ** data. | 608 ** data. |
583 */ | 609 */ |
584 if( 0==pCur->apPage[0]->intKey ){ | 610 if( 0==pCur->apPage[0]->intKey ){ |
585 void *pKey = sqlite3Malloc( (int)pCur->nKey ); | 611 void *pKey = sqlite3Malloc( pCur->nKey ); |
586 if( pKey ){ | 612 if( pKey ){ |
587 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey); | 613 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey); |
588 if( rc==SQLITE_OK ){ | 614 if( rc==SQLITE_OK ){ |
589 pCur->pKey = pKey; | 615 pCur->pKey = pKey; |
590 }else{ | 616 }else{ |
591 sqlite3_free(pKey); | 617 sqlite3_free(pKey); |
592 } | 618 } |
593 }else{ | 619 }else{ |
594 rc = SQLITE_NOMEM; | 620 rc = SQLITE_NOMEM; |
595 } | 621 } |
596 } | 622 } |
597 assert( !pCur->apPage[0]->intKey || !pCur->pKey ); | 623 assert( !pCur->apPage[0]->intKey || !pCur->pKey ); |
598 | 624 |
599 if( rc==SQLITE_OK ){ | 625 if( rc==SQLITE_OK ){ |
600 int i; | 626 btreeReleaseAllCursorPages(pCur); |
601 for(i=0; i<=pCur->iPage; i++){ | |
602 releasePage(pCur->apPage[i]); | |
603 pCur->apPage[i] = 0; | |
604 } | |
605 pCur->iPage = -1; | |
606 pCur->eState = CURSOR_REQUIRESEEK; | 627 pCur->eState = CURSOR_REQUIRESEEK; |
607 } | 628 } |
608 | 629 |
609 invalidateOverflowCache(pCur); | 630 invalidateOverflowCache(pCur); |
610 return rc; | 631 return rc; |
611 } | 632 } |
612 | 633 |
| 634 /* Forward reference */ |
| 635 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*); |
| 636 |
613 /* | 637 /* |
614 ** Save the positions of all cursors (except pExcept) that are open on | 638 ** Save the positions of all cursors (except pExcept) that are open on |
615 ** the table with root-page iRoot. Usually, this is called just before cursor | 639 ** the table with root-page iRoot. "Saving the cursor position" means that |
616 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()). | 640 ** the location in the btree is remembered in such a way that it can be |
| 641 ** moved back to the same spot after the btree has been modified. This |
| 642 ** routine is called just before cursor pExcept is used to modify the |
| 643 ** table, for example in BtreeDelete() or BtreeInsert(). |
| 644 ** |
| 645 ** Implementation note: This routine merely checks to see if any cursors |
| 646 ** need to be saved. It calls out to saveCursorsOnList() in the (unusual) |
| 647 ** event that cursors are in need to being saved. |
617 */ | 648 */ |
618 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){ | 649 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){ |
619 BtCursor *p; | 650 BtCursor *p; |
620 assert( sqlite3_mutex_held(pBt->mutex) ); | 651 assert( sqlite3_mutex_held(pBt->mutex) ); |
621 assert( pExcept==0 || pExcept->pBt==pBt ); | 652 assert( pExcept==0 || pExcept->pBt==pBt ); |
622 for(p=pBt->pCursor; p; p=p->pNext){ | 653 for(p=pBt->pCursor; p; p=p->pNext){ |
623 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && | 654 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break; |
624 p->eState==CURSOR_VALID ){ | 655 } |
625 int rc = saveCursorPosition(p); | 656 return p ? saveCursorsOnList(p, iRoot, pExcept) : SQLITE_OK; |
626 if( SQLITE_OK!=rc ){ | 657 } |
627 return rc; | 658 |
| 659 /* This helper routine to saveAllCursors does the actual work of saving |
| 660 ** the cursors if and when a cursor is found that actually requires saving. |
| 661 ** The common case is that no cursors need to be saved, so this routine is |
| 662 ** broken out from its caller to avoid unnecessary stack pointer movement. |
| 663 */ |
| 664 static int SQLITE_NOINLINE saveCursorsOnList( |
| 665 BtCursor *p, /* The first cursor that needs saving */ |
| 666 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */ |
| 667 BtCursor *pExcept /* Do not save this cursor */ |
| 668 ){ |
| 669 do{ |
| 670 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){ |
| 671 if( p->eState==CURSOR_VALID ){ |
| 672 int rc = saveCursorPosition(p); |
| 673 if( SQLITE_OK!=rc ){ |
| 674 return rc; |
| 675 } |
| 676 }else{ |
| 677 testcase( p->iPage>0 ); |
| 678 btreeReleaseAllCursorPages(p); |
628 } | 679 } |
629 } | 680 } |
630 } | 681 p = p->pNext; |
| 682 }while( p ); |
631 return SQLITE_OK; | 683 return SQLITE_OK; |
632 } | 684 } |
633 | 685 |
634 /* | 686 /* |
635 ** Clear the current cursor position. | 687 ** Clear the current cursor position. |
636 */ | 688 */ |
637 void sqlite3BtreeClearCursor(BtCursor *pCur){ | 689 void sqlite3BtreeClearCursor(BtCursor *pCur){ |
638 assert( cursorHoldsMutex(pCur) ); | 690 assert( cursorHoldsMutex(pCur) ); |
639 sqlite3_free(pCur->pKey); | 691 sqlite3_free(pCur->pKey); |
640 pCur->pKey = 0; | 692 pCur->pKey = 0; |
641 pCur->eState = CURSOR_INVALID; | 693 pCur->eState = CURSOR_INVALID; |
642 } | 694 } |
643 | 695 |
644 /* | 696 /* |
645 ** In this version of BtreeMoveto, pKey is a packed index record | 697 ** In this version of BtreeMoveto, pKey is a packed index record |
646 ** such as is generated by the OP_MakeRecord opcode. Unpack the | 698 ** such as is generated by the OP_MakeRecord opcode. Unpack the |
647 ** record and then call BtreeMovetoUnpacked() to do the work. | 699 ** record and then call BtreeMovetoUnpacked() to do the work. |
648 */ | 700 */ |
649 static int btreeMoveto( | 701 static int btreeMoveto( |
650 BtCursor *pCur, /* Cursor open on the btree to be searched */ | 702 BtCursor *pCur, /* Cursor open on the btree to be searched */ |
651 const void *pKey, /* Packed key if the btree is an index */ | 703 const void *pKey, /* Packed key if the btree is an index */ |
652 i64 nKey, /* Integer key for tables. Size of pKey for indices */ | 704 i64 nKey, /* Integer key for tables. Size of pKey for indices */ |
653 int bias, /* Bias search to the high end */ | 705 int bias, /* Bias search to the high end */ |
654 int *pRes /* Write search results here */ | 706 int *pRes /* Write search results here */ |
655 ){ | 707 ){ |
656 int rc; /* Status code */ | 708 int rc; /* Status code */ |
657 UnpackedRecord *pIdxKey; /* Unpacked index key */ | 709 UnpackedRecord *pIdxKey; /* Unpacked index key */ |
658 char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */ | 710 char aSpace[200]; /* Temp space for pIdxKey - to avoid a malloc */ |
| 711 char *pFree = 0; |
659 | 712 |
660 if( pKey ){ | 713 if( pKey ){ |
661 assert( nKey==(i64)(int)nKey ); | 714 assert( nKey==(i64)(int)nKey ); |
662 pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, | 715 pIdxKey = sqlite3VdbeAllocUnpackedRecord( |
663 aSpace, sizeof(aSpace)); | 716 pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree |
| 717 ); |
664 if( pIdxKey==0 ) return SQLITE_NOMEM; | 718 if( pIdxKey==0 ) return SQLITE_NOMEM; |
| 719 sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey); |
| 720 if( pIdxKey->nField==0 ){ |
| 721 sqlite3DbFree(pCur->pKeyInfo->db, pFree); |
| 722 return SQLITE_CORRUPT_BKPT; |
| 723 } |
665 }else{ | 724 }else{ |
666 pIdxKey = 0; | 725 pIdxKey = 0; |
667 } | 726 } |
668 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes); | 727 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes); |
669 if( pKey ){ | 728 if( pFree ){ |
670 sqlite3VdbeDeleteUnpackedRecord(pIdxKey); | 729 sqlite3DbFree(pCur->pKeyInfo->db, pFree); |
671 } | 730 } |
672 return rc; | 731 return rc; |
673 } | 732 } |
674 | 733 |
675 /* | 734 /* |
676 ** Restore the cursor to the position it was in (or as close to as possible) | 735 ** Restore the cursor to the position it was in (or as close to as possible) |
677 ** when saveCursorPosition() was called. Note that this call deletes the | 736 ** when saveCursorPosition() was called. Note that this call deletes the |
678 ** saved position info stored by saveCursorPosition(), so there can be | 737 ** saved position info stored by saveCursorPosition(), so there can be |
679 ** at most one effective restoreCursorPosition() call after each | 738 ** at most one effective restoreCursorPosition() call after each |
680 ** saveCursorPosition(). | 739 ** saveCursorPosition(). |
681 */ | 740 */ |
682 static int btreeRestoreCursorPosition(BtCursor *pCur){ | 741 static int btreeRestoreCursorPosition(BtCursor *pCur){ |
683 int rc; | 742 int rc; |
684 assert( cursorHoldsMutex(pCur) ); | 743 assert( cursorHoldsMutex(pCur) ); |
685 assert( pCur->eState>=CURSOR_REQUIRESEEK ); | 744 assert( pCur->eState>=CURSOR_REQUIRESEEK ); |
686 if( pCur->eState==CURSOR_FAULT ){ | 745 if( pCur->eState==CURSOR_FAULT ){ |
687 return pCur->skipNext; | 746 return pCur->skipNext; |
688 } | 747 } |
689 pCur->eState = CURSOR_INVALID; | 748 pCur->eState = CURSOR_INVALID; |
690 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext); | 749 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext); |
691 if( rc==SQLITE_OK ){ | 750 if( rc==SQLITE_OK ){ |
692 sqlite3_free(pCur->pKey); | 751 sqlite3_free(pCur->pKey); |
693 pCur->pKey = 0; | 752 pCur->pKey = 0; |
694 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID ); | 753 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID ); |
| 754 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){ |
| 755 pCur->eState = CURSOR_SKIPNEXT; |
| 756 } |
695 } | 757 } |
696 return rc; | 758 return rc; |
697 } | 759 } |
698 | 760 |
699 #define restoreCursorPosition(p) \ | 761 #define restoreCursorPosition(p) \ |
700 (p->eState>=CURSOR_REQUIRESEEK ? \ | 762 (p->eState>=CURSOR_REQUIRESEEK ? \ |
701 btreeRestoreCursorPosition(p) : \ | 763 btreeRestoreCursorPosition(p) : \ |
702 SQLITE_OK) | 764 SQLITE_OK) |
703 | 765 |
704 /* | 766 /* |
705 ** Determine whether or not a cursor has moved from the position it | 767 ** Determine whether or not a cursor has moved from the position where |
706 ** was last placed at. Cursors can move when the row they are pointing | 768 ** it was last placed, or has been invalidated for any other reason. |
707 ** at is deleted out from under them. | 769 ** Cursors can move when the row they are pointing at is deleted out |
| 770 ** from under them, for example. Cursor might also move if a btree |
| 771 ** is rebalanced. |
708 ** | 772 ** |
709 ** This routine returns an error code if something goes wrong. The | 773 ** Calling this routine with a NULL cursor pointer returns false. |
710 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not. | 774 ** |
| 775 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor |
| 776 ** back to where it ought to be if this routine returns true. |
711 */ | 777 */ |
712 int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){ | 778 int sqlite3BtreeCursorHasMoved(BtCursor *pCur){ |
| 779 return pCur->eState!=CURSOR_VALID; |
| 780 } |
| 781 |
| 782 /* |
| 783 ** This routine restores a cursor back to its original position after it |
| 784 ** has been moved by some outside activity (such as a btree rebalance or |
| 785 ** a row having been deleted out from under the cursor). |
| 786 ** |
| 787 ** On success, the *pDifferentRow parameter is false if the cursor is left |
| 788 ** pointing at exactly the same row. *pDifferntRow is the row the cursor |
| 789 ** was pointing to has been deleted, forcing the cursor to point to some |
| 790 ** nearby row. |
| 791 ** |
| 792 ** This routine should only be called for a cursor that just returned |
| 793 ** TRUE from sqlite3BtreeCursorHasMoved(). |
| 794 */ |
| 795 int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){ |
713 int rc; | 796 int rc; |
714 | 797 |
| 798 assert( pCur!=0 ); |
| 799 assert( pCur->eState!=CURSOR_VALID ); |
715 rc = restoreCursorPosition(pCur); | 800 rc = restoreCursorPosition(pCur); |
716 if( rc ){ | 801 if( rc ){ |
717 *pHasMoved = 1; | 802 *pDifferentRow = 1; |
718 return rc; | 803 return rc; |
719 } | 804 } |
720 if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){ | 805 if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){ |
721 *pHasMoved = 1; | 806 *pDifferentRow = 1; |
722 }else{ | 807 }else{ |
723 *pHasMoved = 0; | 808 *pDifferentRow = 0; |
724 } | 809 } |
725 return SQLITE_OK; | 810 return SQLITE_OK; |
726 } | 811 } |
727 | 812 |
728 #ifndef SQLITE_OMIT_AUTOVACUUM | 813 #ifndef SQLITE_OMIT_AUTOVACUUM |
729 /* | 814 /* |
730 ** Given a page number of a regular database page, return the page | 815 ** Given a page number of a regular database page, return the page |
731 ** number for the pointer-map page that contains the entry for the | 816 ** number for the pointer-map page that contains the entry for the |
732 ** input page number. | 817 ** input page number. |
733 ** | 818 ** |
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
781 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage); | 866 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage); |
782 if( rc!=SQLITE_OK ){ | 867 if( rc!=SQLITE_OK ){ |
783 *pRC = rc; | 868 *pRC = rc; |
784 return; | 869 return; |
785 } | 870 } |
786 offset = PTRMAP_PTROFFSET(iPtrmap, key); | 871 offset = PTRMAP_PTROFFSET(iPtrmap, key); |
787 if( offset<0 ){ | 872 if( offset<0 ){ |
788 *pRC = SQLITE_CORRUPT_BKPT; | 873 *pRC = SQLITE_CORRUPT_BKPT; |
789 goto ptrmap_exit; | 874 goto ptrmap_exit; |
790 } | 875 } |
| 876 assert( offset <= (int)pBt->usableSize-5 ); |
791 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); | 877 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); |
792 | 878 |
793 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){ | 879 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){ |
794 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent)); | 880 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent)); |
795 *pRC= rc = sqlite3PagerWrite(pDbPage); | 881 *pRC= rc = sqlite3PagerWrite(pDbPage); |
796 if( rc==SQLITE_OK ){ | 882 if( rc==SQLITE_OK ){ |
797 pPtrmap[offset] = eType; | 883 pPtrmap[offset] = eType; |
798 put4byte(&pPtrmap[offset+1], parent); | 884 put4byte(&pPtrmap[offset+1], parent); |
799 } | 885 } |
800 } | 886 } |
(...skipping 19 matching lines...) Expand all Loading... |
820 assert( sqlite3_mutex_held(pBt->mutex) ); | 906 assert( sqlite3_mutex_held(pBt->mutex) ); |
821 | 907 |
822 iPtrmap = PTRMAP_PAGENO(pBt, key); | 908 iPtrmap = PTRMAP_PAGENO(pBt, key); |
823 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage); | 909 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage); |
824 if( rc!=0 ){ | 910 if( rc!=0 ){ |
825 return rc; | 911 return rc; |
826 } | 912 } |
827 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); | 913 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); |
828 | 914 |
829 offset = PTRMAP_PTROFFSET(iPtrmap, key); | 915 offset = PTRMAP_PTROFFSET(iPtrmap, key); |
| 916 if( offset<0 ){ |
| 917 sqlite3PagerUnref(pDbPage); |
| 918 return SQLITE_CORRUPT_BKPT; |
| 919 } |
| 920 assert( offset <= (int)pBt->usableSize-5 ); |
830 assert( pEType!=0 ); | 921 assert( pEType!=0 ); |
831 *pEType = pPtrmap[offset]; | 922 *pEType = pPtrmap[offset]; |
832 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]); | 923 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]); |
833 | 924 |
834 sqlite3PagerUnref(pDbPage); | 925 sqlite3PagerUnref(pDbPage); |
835 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT; | 926 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT; |
836 return SQLITE_OK; | 927 return SQLITE_OK; |
837 } | 928 } |
838 | 929 |
839 #else /* if defined SQLITE_OMIT_AUTOVACUUM */ | 930 #else /* if defined SQLITE_OMIT_AUTOVACUUM */ |
840 #define ptrmapPut(w,x,y,z,rc) | 931 #define ptrmapPut(w,x,y,z,rc) |
841 #define ptrmapGet(w,x,y,z) SQLITE_OK | 932 #define ptrmapGet(w,x,y,z) SQLITE_OK |
842 #define ptrmapPutOvflPtr(x, y, rc) | 933 #define ptrmapPutOvflPtr(x, y, rc) |
843 #endif | 934 #endif |
844 | 935 |
845 /* | 936 /* |
846 ** Given a btree page and a cell index (0 means the first cell on | 937 ** Given a btree page and a cell index (0 means the first cell on |
847 ** the page, 1 means the second cell, and so forth) return a pointer | 938 ** the page, 1 means the second cell, and so forth) return a pointer |
848 ** to the cell content. | 939 ** to the cell content. |
849 ** | 940 ** |
850 ** This routine works only for pages that do not contain overflow cells. | 941 ** This routine works only for pages that do not contain overflow cells. |
851 */ | 942 */ |
852 #define findCell(P,I) \ | 943 #define findCell(P,I) \ |
853 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)]))) | 944 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)]))) |
| 945 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I))))) |
| 946 |
854 | 947 |
855 /* | 948 /* |
856 ** This a more complex version of findCell() that works for | 949 ** This a more complex version of findCell() that works for |
857 ** pages that do contain overflow cells. | 950 ** pages that do contain overflow cells. |
858 */ | 951 */ |
859 static u8 *findOverflowCell(MemPage *pPage, int iCell){ | 952 static u8 *findOverflowCell(MemPage *pPage, int iCell){ |
860 int i; | 953 int i; |
861 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); | 954 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); |
862 for(i=pPage->nOverflow-1; i>=0; i--){ | 955 for(i=pPage->nOverflow-1; i>=0; i--){ |
863 int k; | 956 int k; |
864 struct _OvflCell *pOvfl; | 957 k = pPage->aiOvfl[i]; |
865 pOvfl = &pPage->aOvfl[i]; | |
866 k = pOvfl->idx; | |
867 if( k<=iCell ){ | 958 if( k<=iCell ){ |
868 if( k==iCell ){ | 959 if( k==iCell ){ |
869 return pOvfl->pCell; | 960 return pPage->apOvfl[i]; |
870 } | 961 } |
871 iCell--; | 962 iCell--; |
872 } | 963 } |
873 } | 964 } |
874 return findCell(pPage, iCell); | 965 return findCell(pPage, iCell); |
875 } | 966 } |
876 | 967 |
877 /* | 968 /* |
878 ** Parse a cell content block and fill in the CellInfo structure. There | 969 ** Parse a cell content block and fill in the CellInfo structure. There |
879 ** are two versions of this function. btreeParseCell() takes a | 970 ** are two versions of this function. btreeParseCell() takes a |
880 ** cell index as the second argument and btreeParseCellPtr() | 971 ** cell index as the second argument and btreeParseCellPtr() |
881 ** takes a pointer to the body of the cell as its second argument. | 972 ** takes a pointer to the body of the cell as its second argument. |
882 ** | |
883 ** Within this file, the parseCell() macro can be called instead of | |
884 ** btreeParseCellPtr(). Using some compilers, this will be faster. | |
885 */ | 973 */ |
886 static void btreeParseCellPtr( | 974 static void btreeParseCellPtr( |
887 MemPage *pPage, /* Page containing the cell */ | 975 MemPage *pPage, /* Page containing the cell */ |
888 u8 *pCell, /* Pointer to the cell text. */ | 976 u8 *pCell, /* Pointer to the cell text. */ |
889 CellInfo *pInfo /* Fill in this structure */ | 977 CellInfo *pInfo /* Fill in this structure */ |
890 ){ | 978 ){ |
891 u16 n; /* Number bytes in cell content header */ | 979 u8 *pIter; /* For scanning through pCell */ |
892 u32 nPayload; /* Number of bytes of cell payload */ | 980 u32 nPayload; /* Number of bytes of cell payload */ |
893 | 981 |
894 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); | 982 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); |
895 | |
896 pInfo->pCell = pCell; | |
897 assert( pPage->leaf==0 || pPage->leaf==1 ); | 983 assert( pPage->leaf==0 || pPage->leaf==1 ); |
898 n = pPage->childPtrSize; | 984 if( pPage->intKeyLeaf ){ |
899 assert( n==4-4*pPage->leaf ); | 985 assert( pPage->childPtrSize==0 ); |
900 if( pPage->intKey ){ | 986 pIter = pCell + getVarint32(pCell, nPayload); |
901 if( pPage->hasData ){ | 987 pIter += getVarint(pIter, (u64*)&pInfo->nKey); |
902 n += getVarint32(&pCell[n], nPayload); | 988 }else if( pPage->noPayload ){ |
903 }else{ | 989 assert( pPage->childPtrSize==4 ); |
904 nPayload = 0; | 990 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey); |
905 } | 991 pInfo->nPayload = 0; |
906 n += getVarint(&pCell[n], (u64*)&pInfo->nKey); | 992 pInfo->nLocal = 0; |
907 pInfo->nData = nPayload; | 993 pInfo->iOverflow = 0; |
| 994 pInfo->pPayload = 0; |
| 995 return; |
908 }else{ | 996 }else{ |
909 pInfo->nData = 0; | 997 pIter = pCell + pPage->childPtrSize; |
910 n += getVarint32(&pCell[n], nPayload); | 998 pIter += getVarint32(pIter, nPayload); |
911 pInfo->nKey = nPayload; | 999 pInfo->nKey = nPayload; |
912 } | 1000 } |
913 pInfo->nPayload = nPayload; | 1001 pInfo->nPayload = nPayload; |
914 pInfo->nHeader = n; | 1002 pInfo->pPayload = pIter; |
915 testcase( nPayload==pPage->maxLocal ); | 1003 testcase( nPayload==pPage->maxLocal ); |
916 testcase( nPayload==pPage->maxLocal+1 ); | 1004 testcase( nPayload==pPage->maxLocal+1 ); |
917 if( likely(nPayload<=pPage->maxLocal) ){ | 1005 if( nPayload<=pPage->maxLocal ){ |
918 /* This is the (easy) common case where the entire payload fits | 1006 /* This is the (easy) common case where the entire payload fits |
919 ** on the local page. No overflow is required. | 1007 ** on the local page. No overflow is required. |
920 */ | 1008 */ |
921 if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4; | 1009 pInfo->nSize = nPayload + (u16)(pIter - pCell); |
| 1010 if( pInfo->nSize<4 ) pInfo->nSize = 4; |
922 pInfo->nLocal = (u16)nPayload; | 1011 pInfo->nLocal = (u16)nPayload; |
923 pInfo->iOverflow = 0; | 1012 pInfo->iOverflow = 0; |
924 }else{ | 1013 }else{ |
925 /* If the payload will not fit completely on the local page, we have | 1014 /* If the payload will not fit completely on the local page, we have |
926 ** to decide how much to store locally and how much to spill onto | 1015 ** to decide how much to store locally and how much to spill onto |
927 ** overflow pages. The strategy is to minimize the amount of unused | 1016 ** overflow pages. The strategy is to minimize the amount of unused |
928 ** space on overflow pages while keeping the amount of local storage | 1017 ** space on overflow pages while keeping the amount of local storage |
929 ** in between minLocal and maxLocal. | 1018 ** in between minLocal and maxLocal. |
930 ** | 1019 ** |
931 ** Warning: changing the way overflow payload is distributed in any | 1020 ** Warning: changing the way overflow payload is distributed in any |
932 ** way will result in an incompatible file format. | 1021 ** way will result in an incompatible file format. |
933 */ | 1022 */ |
934 int minLocal; /* Minimum amount of payload held locally */ | 1023 int minLocal; /* Minimum amount of payload held locally */ |
935 int maxLocal; /* Maximum amount of payload held locally */ | 1024 int maxLocal; /* Maximum amount of payload held locally */ |
936 int surplus; /* Overflow payload available for local storage */ | 1025 int surplus; /* Overflow payload available for local storage */ |
937 | 1026 |
938 minLocal = pPage->minLocal; | 1027 minLocal = pPage->minLocal; |
939 maxLocal = pPage->maxLocal; | 1028 maxLocal = pPage->maxLocal; |
940 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4); | 1029 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4); |
941 testcase( surplus==maxLocal ); | 1030 testcase( surplus==maxLocal ); |
942 testcase( surplus==maxLocal+1 ); | 1031 testcase( surplus==maxLocal+1 ); |
943 if( surplus <= maxLocal ){ | 1032 if( surplus <= maxLocal ){ |
944 pInfo->nLocal = (u16)surplus; | 1033 pInfo->nLocal = (u16)surplus; |
945 }else{ | 1034 }else{ |
946 pInfo->nLocal = (u16)minLocal; | 1035 pInfo->nLocal = (u16)minLocal; |
947 } | 1036 } |
948 pInfo->iOverflow = (u16)(pInfo->nLocal + n); | 1037 pInfo->iOverflow = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell); |
949 pInfo->nSize = pInfo->iOverflow + 4; | 1038 pInfo->nSize = pInfo->iOverflow + 4; |
950 } | 1039 } |
951 } | 1040 } |
952 #define parseCell(pPage, iCell, pInfo) \ | |
953 btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo)) | |
954 static void btreeParseCell( | 1041 static void btreeParseCell( |
955 MemPage *pPage, /* Page containing the cell */ | 1042 MemPage *pPage, /* Page containing the cell */ |
956 int iCell, /* The cell index. First cell is 0 */ | 1043 int iCell, /* The cell index. First cell is 0 */ |
957 CellInfo *pInfo /* Fill in this structure */ | 1044 CellInfo *pInfo /* Fill in this structure */ |
958 ){ | 1045 ){ |
959 parseCell(pPage, iCell, pInfo); | 1046 btreeParseCellPtr(pPage, findCell(pPage, iCell), pInfo); |
960 } | 1047 } |
961 | 1048 |
962 /* | 1049 /* |
963 ** Compute the total number of bytes that a Cell needs in the cell | 1050 ** Compute the total number of bytes that a Cell needs in the cell |
964 ** data area of the btree-page. The return number includes the cell | 1051 ** data area of the btree-page. The return number includes the cell |
965 ** data header and the local payload, but not any overflow page or | 1052 ** data header and the local payload, but not any overflow page or |
966 ** the space used by the cell pointer. | 1053 ** the space used by the cell pointer. |
967 */ | 1054 */ |
968 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){ | 1055 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){ |
969 u8 *pIter = &pCell[pPage->childPtrSize]; | 1056 u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */ |
970 u32 nSize; | 1057 u8 *pEnd; /* End mark for a varint */ |
| 1058 u32 nSize; /* Size value to return */ |
971 | 1059 |
972 #ifdef SQLITE_DEBUG | 1060 #ifdef SQLITE_DEBUG |
973 /* The value returned by this function should always be the same as | 1061 /* The value returned by this function should always be the same as |
974 ** the (CellInfo.nSize) value found by doing a full parse of the | 1062 ** the (CellInfo.nSize) value found by doing a full parse of the |
975 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of | 1063 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of |
976 ** this function verifies that this invariant is not violated. */ | 1064 ** this function verifies that this invariant is not violated. */ |
977 CellInfo debuginfo; | 1065 CellInfo debuginfo; |
978 btreeParseCellPtr(pPage, pCell, &debuginfo); | 1066 btreeParseCellPtr(pPage, pCell, &debuginfo); |
979 #endif | 1067 #endif |
980 | 1068 |
| 1069 if( pPage->noPayload ){ |
| 1070 pEnd = &pIter[9]; |
| 1071 while( (*pIter++)&0x80 && pIter<pEnd ); |
| 1072 assert( pPage->childPtrSize==4 ); |
| 1073 return (u16)(pIter - pCell); |
| 1074 } |
| 1075 nSize = *pIter; |
| 1076 if( nSize>=0x80 ){ |
| 1077 pEnd = &pIter[9]; |
| 1078 nSize &= 0x7f; |
| 1079 do{ |
| 1080 nSize = (nSize<<7) | (*++pIter & 0x7f); |
| 1081 }while( *(pIter)>=0x80 && pIter<pEnd ); |
| 1082 } |
| 1083 pIter++; |
981 if( pPage->intKey ){ | 1084 if( pPage->intKey ){ |
982 u8 *pEnd; | |
983 if( pPage->hasData ){ | |
984 pIter += getVarint32(pIter, nSize); | |
985 }else{ | |
986 nSize = 0; | |
987 } | |
988 | |
989 /* pIter now points at the 64-bit integer key value, a variable length | 1085 /* pIter now points at the 64-bit integer key value, a variable length |
990 ** integer. The following block moves pIter to point at the first byte | 1086 ** integer. The following block moves pIter to point at the first byte |
991 ** past the end of the key value. */ | 1087 ** past the end of the key value. */ |
992 pEnd = &pIter[9]; | 1088 pEnd = &pIter[9]; |
993 while( (*pIter++)&0x80 && pIter<pEnd ); | 1089 while( (*pIter++)&0x80 && pIter<pEnd ); |
994 }else{ | |
995 pIter += getVarint32(pIter, nSize); | |
996 } | 1090 } |
997 | |
998 testcase( nSize==pPage->maxLocal ); | 1091 testcase( nSize==pPage->maxLocal ); |
999 testcase( nSize==pPage->maxLocal+1 ); | 1092 testcase( nSize==pPage->maxLocal+1 ); |
1000 if( nSize>pPage->maxLocal ){ | 1093 if( nSize<=pPage->maxLocal ){ |
| 1094 nSize += (u32)(pIter - pCell); |
| 1095 if( nSize<4 ) nSize = 4; |
| 1096 }else{ |
1001 int minLocal = pPage->minLocal; | 1097 int minLocal = pPage->minLocal; |
1002 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4); | 1098 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4); |
1003 testcase( nSize==pPage->maxLocal ); | 1099 testcase( nSize==pPage->maxLocal ); |
1004 testcase( nSize==pPage->maxLocal+1 ); | 1100 testcase( nSize==pPage->maxLocal+1 ); |
1005 if( nSize>pPage->maxLocal ){ | 1101 if( nSize>pPage->maxLocal ){ |
1006 nSize = minLocal; | 1102 nSize = minLocal; |
1007 } | 1103 } |
1008 nSize += 4; | 1104 nSize += 4 + (u16)(pIter - pCell); |
1009 } | 1105 } |
1010 nSize += (u32)(pIter - pCell); | 1106 assert( nSize==debuginfo.nSize || CORRUPT_DB ); |
1011 | |
1012 /* The minimum size of any cell is 4 bytes. */ | |
1013 if( nSize<4 ){ | |
1014 nSize = 4; | |
1015 } | |
1016 | |
1017 assert( nSize==debuginfo.nSize ); | |
1018 return (u16)nSize; | 1107 return (u16)nSize; |
1019 } | 1108 } |
1020 | 1109 |
1021 #ifdef SQLITE_DEBUG | 1110 #ifdef SQLITE_DEBUG |
1022 /* This variation on cellSizePtr() is used inside of assert() statements | 1111 /* This variation on cellSizePtr() is used inside of assert() statements |
1023 ** only. */ | 1112 ** only. */ |
1024 static u16 cellSize(MemPage *pPage, int iCell){ | 1113 static u16 cellSize(MemPage *pPage, int iCell){ |
1025 return cellSizePtr(pPage, findCell(pPage, iCell)); | 1114 return cellSizePtr(pPage, findCell(pPage, iCell)); |
1026 } | 1115 } |
1027 #endif | 1116 #endif |
1028 | 1117 |
1029 #ifndef SQLITE_OMIT_AUTOVACUUM | 1118 #ifndef SQLITE_OMIT_AUTOVACUUM |
1030 /* | 1119 /* |
1031 ** If the cell pCell, part of page pPage contains a pointer | 1120 ** If the cell pCell, part of page pPage contains a pointer |
1032 ** to an overflow page, insert an entry into the pointer-map | 1121 ** to an overflow page, insert an entry into the pointer-map |
1033 ** for the overflow page. | 1122 ** for the overflow page. |
1034 */ | 1123 */ |
1035 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){ | 1124 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){ |
1036 CellInfo info; | 1125 CellInfo info; |
1037 if( *pRC ) return; | 1126 if( *pRC ) return; |
1038 assert( pCell!=0 ); | 1127 assert( pCell!=0 ); |
1039 btreeParseCellPtr(pPage, pCell, &info); | 1128 btreeParseCellPtr(pPage, pCell, &info); |
1040 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload ); | |
1041 if( info.iOverflow ){ | 1129 if( info.iOverflow ){ |
1042 Pgno ovfl = get4byte(&pCell[info.iOverflow]); | 1130 Pgno ovfl = get4byte(&pCell[info.iOverflow]); |
1043 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC); | 1131 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC); |
1044 } | 1132 } |
1045 } | 1133 } |
1046 #endif | 1134 #endif |
1047 | 1135 |
1048 | 1136 |
1049 /* | 1137 /* |
1050 ** Defragment the page given. All Cells are moved to the | 1138 ** Defragment the page given. All Cells are moved to the |
1051 ** end of the page and all free space is collected into one | 1139 ** end of the page and all free space is collected into one |
1052 ** big FreeBlk that occurs in between the header and cell | 1140 ** big FreeBlk that occurs in between the header and cell |
1053 ** pointer array and the cell content area. | 1141 ** pointer array and the cell content area. |
1054 */ | 1142 */ |
1055 static int defragmentPage(MemPage *pPage){ | 1143 static int defragmentPage(MemPage *pPage){ |
1056 int i; /* Loop counter */ | 1144 int i; /* Loop counter */ |
1057 int pc; /* Address of a i-th cell */ | 1145 int pc; /* Address of the i-th cell */ |
1058 int hdr; /* Offset to the page header */ | 1146 int hdr; /* Offset to the page header */ |
1059 int size; /* Size of a cell */ | 1147 int size; /* Size of a cell */ |
1060 int usableSize; /* Number of usable bytes on a page */ | 1148 int usableSize; /* Number of usable bytes on a page */ |
1061 int cellOffset; /* Offset to the cell pointer array */ | 1149 int cellOffset; /* Offset to the cell pointer array */ |
1062 int cbrk; /* Offset to the cell content area */ | 1150 int cbrk; /* Offset to the cell content area */ |
1063 int nCell; /* Number of cells on the page */ | 1151 int nCell; /* Number of cells on the page */ |
1064 unsigned char *data; /* The page data */ | 1152 unsigned char *data; /* The page data */ |
1065 unsigned char *temp; /* Temp area for cell content */ | 1153 unsigned char *temp; /* Temp area for cell content */ |
1066 int iCellFirst; /* First allowable cell index */ | 1154 int iCellFirst; /* First allowable cell index */ |
1067 int iCellLast; /* Last possible cell index */ | 1155 int iCellLast; /* Last possible cell index */ |
(...skipping 70 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1138 ** The caller guarantees that there is sufficient space to make the | 1226 ** The caller guarantees that there is sufficient space to make the |
1139 ** allocation. This routine might need to defragment in order to bring | 1227 ** allocation. This routine might need to defragment in order to bring |
1140 ** all the space together, however. This routine will avoid using | 1228 ** all the space together, however. This routine will avoid using |
1141 ** the first two bytes past the cell pointer area since presumably this | 1229 ** the first two bytes past the cell pointer area since presumably this |
1142 ** allocation is being made in order to insert a new cell, so we will | 1230 ** allocation is being made in order to insert a new cell, so we will |
1143 ** also end up needing a new cell pointer. | 1231 ** also end up needing a new cell pointer. |
1144 */ | 1232 */ |
1145 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){ | 1233 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){ |
1146 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */ | 1234 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */ |
1147 u8 * const data = pPage->aData; /* Local cache of pPage->aData */ | 1235 u8 * const data = pPage->aData; /* Local cache of pPage->aData */ |
1148 int nFrag; /* Number of fragmented bytes on pPage */ | |
1149 int top; /* First byte of cell content area */ | 1236 int top; /* First byte of cell content area */ |
1150 int gap; /* First byte of gap between cell pointers and cell content */ | 1237 int gap; /* First byte of gap between cell pointers and cell content */ |
1151 int rc; /* Integer return code */ | 1238 int rc; /* Integer return code */ |
1152 int usableSize; /* Usable size of the page */ | 1239 int usableSize; /* Usable size of the page */ |
1153 | 1240 |
1154 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); | 1241 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); |
1155 assert( pPage->pBt ); | 1242 assert( pPage->pBt ); |
1156 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); | 1243 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); |
1157 assert( nByte>=0 ); /* Minimum cell size is 4 */ | 1244 assert( nByte>=0 ); /* Minimum cell size is 4 */ |
1158 assert( pPage->nFree>=nByte ); | 1245 assert( pPage->nFree>=nByte ); |
1159 assert( pPage->nOverflow==0 ); | 1246 assert( pPage->nOverflow==0 ); |
1160 usableSize = pPage->pBt->usableSize; | 1247 usableSize = pPage->pBt->usableSize; |
1161 assert( nByte < usableSize-8 ); | 1248 assert( nByte < usableSize-8 ); |
1162 | 1249 |
1163 nFrag = data[hdr+7]; | |
1164 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf ); | 1250 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf ); |
1165 gap = pPage->cellOffset + 2*pPage->nCell; | 1251 gap = pPage->cellOffset + 2*pPage->nCell; |
1166 top = get2byteNotZero(&data[hdr+5]); | 1252 assert( gap<=65536 ); |
1167 if( gap>top ) return SQLITE_CORRUPT_BKPT; | 1253 top = get2byte(&data[hdr+5]); |
| 1254 if( gap>top ){ |
| 1255 if( top==0 ){ |
| 1256 top = 65536; |
| 1257 }else{ |
| 1258 return SQLITE_CORRUPT_BKPT; |
| 1259 } |
| 1260 } |
| 1261 |
| 1262 /* If there is enough space between gap and top for one more cell pointer |
| 1263 ** array entry offset, and if the freelist is not empty, then search the |
| 1264 ** freelist looking for a free slot big enough to satisfy the request. |
| 1265 */ |
1168 testcase( gap+2==top ); | 1266 testcase( gap+2==top ); |
1169 testcase( gap+1==top ); | 1267 testcase( gap+1==top ); |
1170 testcase( gap==top ); | 1268 testcase( gap==top ); |
1171 | 1269 if( gap+2<=top && (data[hdr+1] || data[hdr+2]) ){ |
1172 if( nFrag>=60 ){ | |
1173 /* Always defragment highly fragmented pages */ | |
1174 rc = defragmentPage(pPage); | |
1175 if( rc ) return rc; | |
1176 top = get2byteNotZero(&data[hdr+5]); | |
1177 }else if( gap+2<=top ){ | |
1178 /* Search the freelist looking for a free slot big enough to satisfy | |
1179 ** the request. The allocation is made from the first free slot in | |
1180 ** the list that is large enough to accomadate it. | |
1181 */ | |
1182 int pc, addr; | 1270 int pc, addr; |
1183 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){ | 1271 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){ |
1184 int size; /* Size of the free slot */ | 1272 int size; /* Size of the free slot */ |
1185 if( pc>usableSize-4 || pc<addr+4 ){ | 1273 if( pc>usableSize-4 || pc<addr+4 ){ |
1186 return SQLITE_CORRUPT_BKPT; | 1274 return SQLITE_CORRUPT_BKPT; |
1187 } | 1275 } |
1188 size = get2byte(&data[pc+2]); | 1276 size = get2byte(&data[pc+2]); |
1189 if( size>=nByte ){ | 1277 if( size>=nByte ){ |
1190 int x = size - nByte; | 1278 int x = size - nByte; |
1191 testcase( x==4 ); | 1279 testcase( x==4 ); |
1192 testcase( x==3 ); | 1280 testcase( x==3 ); |
1193 if( x<4 ){ | 1281 if( x<4 ){ |
| 1282 if( data[hdr+7]>=60 ) goto defragment_page; |
1194 /* Remove the slot from the free-list. Update the number of | 1283 /* Remove the slot from the free-list. Update the number of |
1195 ** fragmented bytes within the page. */ | 1284 ** fragmented bytes within the page. */ |
1196 memcpy(&data[addr], &data[pc], 2); | 1285 memcpy(&data[addr], &data[pc], 2); |
1197 data[hdr+7] = (u8)(nFrag + x); | 1286 data[hdr+7] += (u8)x; |
1198 }else if( size+pc > usableSize ){ | 1287 }else if( size+pc > usableSize ){ |
1199 return SQLITE_CORRUPT_BKPT; | 1288 return SQLITE_CORRUPT_BKPT; |
1200 }else{ | 1289 }else{ |
1201 /* The slot remains on the free-list. Reduce its size to account | 1290 /* The slot remains on the free-list. Reduce its size to account |
1202 ** for the portion used by the new allocation. */ | 1291 ** for the portion used by the new allocation. */ |
1203 put2byte(&data[pc+2], x); | 1292 put2byte(&data[pc+2], x); |
1204 } | 1293 } |
1205 *pIdx = pc + x; | 1294 *pIdx = pc + x; |
1206 return SQLITE_OK; | 1295 return SQLITE_OK; |
1207 } | 1296 } |
1208 } | 1297 } |
1209 } | 1298 } |
1210 | 1299 |
1211 /* Check to make sure there is enough space in the gap to satisfy | 1300 /* The request could not be fulfilled using a freelist slot. Check |
1212 ** the allocation. If not, defragment. | 1301 ** to see if defragmentation is necessary. |
1213 */ | 1302 */ |
1214 testcase( gap+2+nByte==top ); | 1303 testcase( gap+2+nByte==top ); |
1215 if( gap+2+nByte>top ){ | 1304 if( gap+2+nByte>top ){ |
| 1305 defragment_page: |
| 1306 testcase( pPage->nCell==0 ); |
1216 rc = defragmentPage(pPage); | 1307 rc = defragmentPage(pPage); |
1217 if( rc ) return rc; | 1308 if( rc ) return rc; |
1218 top = get2byteNotZero(&data[hdr+5]); | 1309 top = get2byteNotZero(&data[hdr+5]); |
1219 assert( gap+nByte<=top ); | 1310 assert( gap+nByte<=top ); |
1220 } | 1311 } |
1221 | 1312 |
1222 | 1313 |
1223 /* Allocate memory from the gap in between the cell pointer array | 1314 /* Allocate memory from the gap in between the cell pointer array |
1224 ** and the cell content area. The btreeInitPage() call has already | 1315 ** and the cell content area. The btreeInitPage() call has already |
1225 ** validated the freelist. Given that the freelist is valid, there | 1316 ** validated the freelist. Given that the freelist is valid, there |
1226 ** is no way that the allocation can extend off the end of the page. | 1317 ** is no way that the allocation can extend off the end of the page. |
1227 ** The assert() below verifies the previous sentence. | 1318 ** The assert() below verifies the previous sentence. |
1228 */ | 1319 */ |
1229 top -= nByte; | 1320 top -= nByte; |
1230 put2byte(&data[hdr+5], top); | 1321 put2byte(&data[hdr+5], top); |
1231 assert( top+nByte <= (int)pPage->pBt->usableSize ); | 1322 assert( top+nByte <= (int)pPage->pBt->usableSize ); |
1232 *pIdx = top; | 1323 *pIdx = top; |
1233 return SQLITE_OK; | 1324 return SQLITE_OK; |
1234 } | 1325 } |
1235 | 1326 |
1236 /* | 1327 /* |
1237 ** Return a section of the pPage->aData to the freelist. | 1328 ** Return a section of the pPage->aData to the freelist. |
1238 ** The first byte of the new free block is pPage->aDisk[start] | 1329 ** The first byte of the new free block is pPage->aData[iStart] |
1239 ** and the size of the block is "size" bytes. | 1330 ** and the size of the block is iSize bytes. |
1240 ** | 1331 ** |
1241 ** Most of the effort here is involved in coalesing adjacent | 1332 ** Adjacent freeblocks are coalesced. |
1242 ** free blocks into a single big free block. | 1333 ** |
| 1334 ** Note that even though the freeblock list was checked by btreeInitPage(), |
| 1335 ** that routine will not detect overlap between cells or freeblocks. Nor |
| 1336 ** does it detect cells or freeblocks that encrouch into the reserved bytes |
| 1337 ** at the end of the page. So do additional corruption checks inside this |
| 1338 ** routine and return SQLITE_CORRUPT if any problems are found. |
1243 */ | 1339 */ |
1244 static int freeSpace(MemPage *pPage, int start, int size){ | 1340 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){ |
1245 int addr, pbegin, hdr; | 1341 u16 iPtr; /* Address of ptr to next freeblock */ |
1246 int iLast; /* Largest possible freeblock offset */ | 1342 u16 iFreeBlk; /* Address of the next freeblock */ |
1247 unsigned char *data = pPage->aData; | 1343 u8 hdr; /* Page header size. 0 or 100 */ |
| 1344 u8 nFrag = 0; /* Reduction in fragmentation */ |
| 1345 u16 iOrigSize = iSize; /* Original value of iSize */ |
| 1346 u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */ |
| 1347 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */ |
| 1348 unsigned char *data = pPage->aData; /* Page content */ |
1248 | 1349 |
1249 assert( pPage->pBt!=0 ); | 1350 assert( pPage->pBt!=0 ); |
1250 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); | 1351 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); |
1251 assert( start>=pPage->hdrOffset+6+pPage->childPtrSize ); | 1352 assert( iStart>=pPage->hdrOffset+6+pPage->childPtrSize ); |
1252 assert( (start + size) <= (int)pPage->pBt->usableSize ); | 1353 assert( iEnd <= pPage->pBt->usableSize ); |
1253 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); | 1354 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); |
1254 assert( size>=0 ); /* Minimum cell size is 4 */ | 1355 assert( iSize>=4 ); /* Minimum cell size is 4 */ |
| 1356 assert( iStart<=iLast ); |
1255 | 1357 |
1256 if( pPage->pBt->secureDelete ){ | 1358 /* Overwrite deleted information with zeros when the secure_delete |
1257 /* Overwrite deleted information with zeros when the secure_delete | 1359 ** option is enabled */ |
1258 ** option is enabled */ | 1360 if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){ |
1259 memset(&data[start], 0, size); | 1361 memset(&data[iStart], 0, iSize); |
1260 } | 1362 } |
1261 | 1363 |
1262 /* Add the space back into the linked list of freeblocks. Note that | 1364 /* The list of freeblocks must be in ascending order. Find the |
1263 ** even though the freeblock list was checked by btreeInitPage(), | 1365 ** spot on the list where iStart should be inserted. |
1264 ** btreeInitPage() did not detect overlapping cells or | |
1265 ** freeblocks that overlapped cells. Nor does it detect when the | |
1266 ** cell content area exceeds the value in the page header. If these | |
1267 ** situations arise, then subsequent insert operations might corrupt | |
1268 ** the freelist. So we do need to check for corruption while scanning | |
1269 ** the freelist. | |
1270 */ | 1366 */ |
1271 hdr = pPage->hdrOffset; | 1367 hdr = pPage->hdrOffset; |
1272 addr = hdr + 1; | 1368 iPtr = hdr + 1; |
1273 iLast = pPage->pBt->usableSize - 4; | 1369 if( data[iPtr+1]==0 && data[iPtr]==0 ){ |
1274 assert( start<=iLast ); | 1370 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */ |
1275 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){ | 1371 }else{ |
1276 if( pbegin<addr+4 ){ | 1372 while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){ |
1277 return SQLITE_CORRUPT_BKPT; | 1373 if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT; |
| 1374 iPtr = iFreeBlk; |
1278 } | 1375 } |
1279 addr = pbegin; | 1376 if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT; |
| 1377 assert( iFreeBlk>iPtr || iFreeBlk==0 ); |
| 1378 |
| 1379 /* At this point: |
| 1380 ** iFreeBlk: First freeblock after iStart, or zero if none |
| 1381 ** iPtr: The address of a pointer iFreeBlk |
| 1382 ** |
| 1383 ** Check to see if iFreeBlk should be coalesced onto the end of iStart. |
| 1384 */ |
| 1385 if( iFreeBlk && iEnd+3>=iFreeBlk ){ |
| 1386 nFrag = iFreeBlk - iEnd; |
| 1387 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT; |
| 1388 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]); |
| 1389 iSize = iEnd - iStart; |
| 1390 iFreeBlk = get2byte(&data[iFreeBlk]); |
| 1391 } |
| 1392 |
| 1393 /* If iPtr is another freeblock (that is, if iPtr is not the freelist |
| 1394 ** pointer in the page header) then check to see if iStart should be |
| 1395 ** coalesced onto the end of iPtr. |
| 1396 */ |
| 1397 if( iPtr>hdr+1 ){ |
| 1398 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]); |
| 1399 if( iPtrEnd+3>=iStart ){ |
| 1400 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT; |
| 1401 nFrag += iStart - iPtrEnd; |
| 1402 iSize = iEnd - iPtr; |
| 1403 iStart = iPtr; |
| 1404 } |
| 1405 } |
| 1406 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT; |
| 1407 data[hdr+7] -= nFrag; |
1280 } | 1408 } |
1281 if( pbegin>iLast ){ | 1409 if( iStart==get2byte(&data[hdr+5]) ){ |
1282 return SQLITE_CORRUPT_BKPT; | 1410 /* The new freeblock is at the beginning of the cell content area, |
| 1411 ** so just extend the cell content area rather than create another |
| 1412 ** freelist entry */ |
| 1413 if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT; |
| 1414 put2byte(&data[hdr+1], iFreeBlk); |
| 1415 put2byte(&data[hdr+5], iEnd); |
| 1416 }else{ |
| 1417 /* Insert the new freeblock into the freelist */ |
| 1418 put2byte(&data[iPtr], iStart); |
| 1419 put2byte(&data[iStart], iFreeBlk); |
| 1420 put2byte(&data[iStart+2], iSize); |
1283 } | 1421 } |
1284 assert( pbegin>addr || pbegin==0 ); | 1422 pPage->nFree += iOrigSize; |
1285 put2byte(&data[addr], start); | |
1286 put2byte(&data[start], pbegin); | |
1287 put2byte(&data[start+2], size); | |
1288 pPage->nFree = pPage->nFree + (u16)size; | |
1289 | |
1290 /* Coalesce adjacent free blocks */ | |
1291 addr = hdr + 1; | |
1292 while( (pbegin = get2byte(&data[addr]))>0 ){ | |
1293 int pnext, psize, x; | |
1294 assert( pbegin>addr ); | |
1295 assert( pbegin <= (int)pPage->pBt->usableSize-4 ); | |
1296 pnext = get2byte(&data[pbegin]); | |
1297 psize = get2byte(&data[pbegin+2]); | |
1298 if( pbegin + psize + 3 >= pnext && pnext>0 ){ | |
1299 int frag = pnext - (pbegin+psize); | |
1300 if( (frag<0) || (frag>(int)data[hdr+7]) ){ | |
1301 return SQLITE_CORRUPT_BKPT; | |
1302 } | |
1303 data[hdr+7] -= (u8)frag; | |
1304 x = get2byte(&data[pnext]); | |
1305 put2byte(&data[pbegin], x); | |
1306 x = pnext + get2byte(&data[pnext+2]) - pbegin; | |
1307 put2byte(&data[pbegin+2], x); | |
1308 }else{ | |
1309 addr = pbegin; | |
1310 } | |
1311 } | |
1312 | |
1313 /* If the cell content area begins with a freeblock, remove it. */ | |
1314 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){ | |
1315 int top; | |
1316 pbegin = get2byte(&data[hdr+1]); | |
1317 memcpy(&data[hdr+1], &data[pbegin], 2); | |
1318 top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]); | |
1319 put2byte(&data[hdr+5], top); | |
1320 } | |
1321 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); | |
1322 return SQLITE_OK; | 1423 return SQLITE_OK; |
1323 } | 1424 } |
1324 | 1425 |
1325 /* | 1426 /* |
1326 ** Decode the flags byte (the first byte of the header) for a page | 1427 ** Decode the flags byte (the first byte of the header) for a page |
1327 ** and initialize fields of the MemPage structure accordingly. | 1428 ** and initialize fields of the MemPage structure accordingly. |
1328 ** | 1429 ** |
1329 ** Only the following combinations are supported. Anything different | 1430 ** Only the following combinations are supported. Anything different |
1330 ** indicates a corrupt database files: | 1431 ** indicates a corrupt database files: |
1331 ** | 1432 ** |
1332 ** PTF_ZERODATA | 1433 ** PTF_ZERODATA |
1333 ** PTF_ZERODATA | PTF_LEAF | 1434 ** PTF_ZERODATA | PTF_LEAF |
1334 ** PTF_LEAFDATA | PTF_INTKEY | 1435 ** PTF_LEAFDATA | PTF_INTKEY |
1335 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF | 1436 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF |
1336 */ | 1437 */ |
1337 static int decodeFlags(MemPage *pPage, int flagByte){ | 1438 static int decodeFlags(MemPage *pPage, int flagByte){ |
1338 BtShared *pBt; /* A copy of pPage->pBt */ | 1439 BtShared *pBt; /* A copy of pPage->pBt */ |
1339 | 1440 |
1340 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) ); | 1441 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) ); |
1341 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); | 1442 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); |
1342 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 ); | 1443 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 ); |
1343 flagByte &= ~PTF_LEAF; | 1444 flagByte &= ~PTF_LEAF; |
1344 pPage->childPtrSize = 4-4*pPage->leaf; | 1445 pPage->childPtrSize = 4-4*pPage->leaf; |
1345 pBt = pPage->pBt; | 1446 pBt = pPage->pBt; |
1346 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){ | 1447 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){ |
1347 pPage->intKey = 1; | 1448 pPage->intKey = 1; |
1348 pPage->hasData = pPage->leaf; | 1449 pPage->intKeyLeaf = pPage->leaf; |
| 1450 pPage->noPayload = !pPage->leaf; |
1349 pPage->maxLocal = pBt->maxLeaf; | 1451 pPage->maxLocal = pBt->maxLeaf; |
1350 pPage->minLocal = pBt->minLeaf; | 1452 pPage->minLocal = pBt->minLeaf; |
1351 }else if( flagByte==PTF_ZERODATA ){ | 1453 }else if( flagByte==PTF_ZERODATA ){ |
1352 pPage->intKey = 0; | 1454 pPage->intKey = 0; |
1353 pPage->hasData = 0; | 1455 pPage->intKeyLeaf = 0; |
| 1456 pPage->noPayload = 0; |
1354 pPage->maxLocal = pBt->maxLocal; | 1457 pPage->maxLocal = pBt->maxLocal; |
1355 pPage->minLocal = pBt->minLocal; | 1458 pPage->minLocal = pBt->minLocal; |
1356 }else{ | 1459 }else{ |
1357 return SQLITE_CORRUPT_BKPT; | 1460 return SQLITE_CORRUPT_BKPT; |
1358 } | 1461 } |
| 1462 pPage->max1bytePayload = pBt->max1bytePayload; |
1359 return SQLITE_OK; | 1463 return SQLITE_OK; |
1360 } | 1464 } |
1361 | 1465 |
1362 /* | 1466 /* |
1363 ** Initialize the auxiliary information for a disk block. | 1467 ** Initialize the auxiliary information for a disk block. |
1364 ** | 1468 ** |
1365 ** Return SQLITE_OK on success. If we see that the page does | 1469 ** Return SQLITE_OK on success. If we see that the page does |
1366 ** not contain a well-formed database page, then return | 1470 ** not contain a well-formed database page, then return |
1367 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not | 1471 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not |
1368 ** guarantee that the page is well-formed. It only shows that | 1472 ** guarantee that the page is well-formed. It only shows that |
(...skipping 22 matching lines...) Expand all Loading... |
1391 pBt = pPage->pBt; | 1495 pBt = pPage->pBt; |
1392 | 1496 |
1393 hdr = pPage->hdrOffset; | 1497 hdr = pPage->hdrOffset; |
1394 data = pPage->aData; | 1498 data = pPage->aData; |
1395 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT; | 1499 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT; |
1396 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); | 1500 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); |
1397 pPage->maskPage = (u16)(pBt->pageSize - 1); | 1501 pPage->maskPage = (u16)(pBt->pageSize - 1); |
1398 pPage->nOverflow = 0; | 1502 pPage->nOverflow = 0; |
1399 usableSize = pBt->usableSize; | 1503 usableSize = pBt->usableSize; |
1400 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf; | 1504 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf; |
| 1505 pPage->aDataEnd = &data[usableSize]; |
| 1506 pPage->aCellIdx = &data[cellOffset]; |
1401 top = get2byteNotZero(&data[hdr+5]); | 1507 top = get2byteNotZero(&data[hdr+5]); |
1402 pPage->nCell = get2byte(&data[hdr+3]); | 1508 pPage->nCell = get2byte(&data[hdr+3]); |
1403 if( pPage->nCell>MX_CELL(pBt) ){ | 1509 if( pPage->nCell>MX_CELL(pBt) ){ |
1404 /* To many cells for a single page. The page must be corrupt */ | 1510 /* To many cells for a single page. The page must be corrupt */ |
1405 return SQLITE_CORRUPT_BKPT; | 1511 return SQLITE_CORRUPT_BKPT; |
1406 } | 1512 } |
1407 testcase( pPage->nCell==MX_CELL(pBt) ); | 1513 testcase( pPage->nCell==MX_CELL(pBt) ); |
1408 | 1514 |
1409 /* A malformed database page might cause us to read past the end | 1515 /* A malformed database page might cause us to read past the end |
1410 ** of page when parsing a cell. | 1516 ** of page when parsing a cell. |
(...skipping 33 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1444 while( pc>0 ){ | 1550 while( pc>0 ){ |
1445 u16 next, size; | 1551 u16 next, size; |
1446 if( pc<iCellFirst || pc>iCellLast ){ | 1552 if( pc<iCellFirst || pc>iCellLast ){ |
1447 /* Start of free block is off the page */ | 1553 /* Start of free block is off the page */ |
1448 return SQLITE_CORRUPT_BKPT; | 1554 return SQLITE_CORRUPT_BKPT; |
1449 } | 1555 } |
1450 next = get2byte(&data[pc]); | 1556 next = get2byte(&data[pc]); |
1451 size = get2byte(&data[pc+2]); | 1557 size = get2byte(&data[pc+2]); |
1452 if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){ | 1558 if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){ |
1453 /* Free blocks must be in ascending order. And the last byte of | 1559 /* Free blocks must be in ascending order. And the last byte of |
1454 » ** the free-block must lie on the database page. */ | 1560 ** the free-block must lie on the database page. */ |
1455 return SQLITE_CORRUPT_BKPT; | 1561 return SQLITE_CORRUPT_BKPT; |
1456 } | 1562 } |
1457 nFree = nFree + size; | 1563 nFree = nFree + size; |
1458 pc = next; | 1564 pc = next; |
1459 } | 1565 } |
1460 | 1566 |
1461 /* At this point, nFree contains the sum of the offset to the start | 1567 /* At this point, nFree contains the sum of the offset to the start |
1462 ** of the cell-content area plus the number of free bytes within | 1568 ** of the cell-content area plus the number of free bytes within |
1463 ** the cell-content area. If this is greater than the usable-size | 1569 ** the cell-content area. If this is greater than the usable-size |
1464 ** of the page, then the page must be corrupted. This check also | 1570 ** of the page, then the page must be corrupted. This check also |
(...skipping 17 matching lines...) Expand all Loading... |
1482 unsigned char *data = pPage->aData; | 1588 unsigned char *data = pPage->aData; |
1483 BtShared *pBt = pPage->pBt; | 1589 BtShared *pBt = pPage->pBt; |
1484 u8 hdr = pPage->hdrOffset; | 1590 u8 hdr = pPage->hdrOffset; |
1485 u16 first; | 1591 u16 first; |
1486 | 1592 |
1487 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno ); | 1593 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno ); |
1488 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); | 1594 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); |
1489 assert( sqlite3PagerGetData(pPage->pDbPage) == data ); | 1595 assert( sqlite3PagerGetData(pPage->pDbPage) == data ); |
1490 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); | 1596 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); |
1491 assert( sqlite3_mutex_held(pBt->mutex) ); | 1597 assert( sqlite3_mutex_held(pBt->mutex) ); |
1492 if( pBt->secureDelete ){ | 1598 if( pBt->btsFlags & BTS_SECURE_DELETE ){ |
1493 memset(&data[hdr], 0, pBt->usableSize - hdr); | 1599 memset(&data[hdr], 0, pBt->usableSize - hdr); |
1494 } | 1600 } |
1495 data[hdr] = (char)flags; | 1601 data[hdr] = (char)flags; |
1496 first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0); | 1602 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8); |
1497 memset(&data[hdr+1], 0, 4); | 1603 memset(&data[hdr+1], 0, 4); |
1498 data[hdr+7] = 0; | 1604 data[hdr+7] = 0; |
1499 put2byte(&data[hdr+5], pBt->usableSize); | 1605 put2byte(&data[hdr+5], pBt->usableSize); |
1500 pPage->nFree = (u16)(pBt->usableSize - first); | 1606 pPage->nFree = (u16)(pBt->usableSize - first); |
1501 decodeFlags(pPage, flags); | 1607 decodeFlags(pPage, flags); |
1502 pPage->hdrOffset = hdr; | |
1503 pPage->cellOffset = first; | 1608 pPage->cellOffset = first; |
| 1609 pPage->aDataEnd = &data[pBt->usableSize]; |
| 1610 pPage->aCellIdx = &data[first]; |
1504 pPage->nOverflow = 0; | 1611 pPage->nOverflow = 0; |
1505 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); | 1612 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 ); |
1506 pPage->maskPage = (u16)(pBt->pageSize - 1); | 1613 pPage->maskPage = (u16)(pBt->pageSize - 1); |
1507 pPage->nCell = 0; | 1614 pPage->nCell = 0; |
1508 pPage->isInit = 1; | 1615 pPage->isInit = 1; |
1509 } | 1616 } |
1510 | 1617 |
1511 | 1618 |
1512 /* | 1619 /* |
1513 ** Convert a DbPage obtained from the pager into a MemPage used by | 1620 ** Convert a DbPage obtained from the pager into a MemPage used by |
(...skipping 17 matching lines...) Expand all Loading... |
1531 ** the content of the page at this time. So do not go to the disk | 1638 ** the content of the page at this time. So do not go to the disk |
1532 ** to fetch the content. Just fill in the content with zeros for now. | 1639 ** to fetch the content. Just fill in the content with zeros for now. |
1533 ** If in the future we call sqlite3PagerWrite() on this page, that | 1640 ** If in the future we call sqlite3PagerWrite() on this page, that |
1534 ** means we have started to be concerned about content and the disk | 1641 ** means we have started to be concerned about content and the disk |
1535 ** read should occur at that point. | 1642 ** read should occur at that point. |
1536 */ | 1643 */ |
1537 static int btreeGetPage( | 1644 static int btreeGetPage( |
1538 BtShared *pBt, /* The btree */ | 1645 BtShared *pBt, /* The btree */ |
1539 Pgno pgno, /* Number of the page to fetch */ | 1646 Pgno pgno, /* Number of the page to fetch */ |
1540 MemPage **ppPage, /* Return the page in this parameter */ | 1647 MemPage **ppPage, /* Return the page in this parameter */ |
1541 int noContent /* Do not load page content if true */ | 1648 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */ |
1542 ){ | 1649 ){ |
1543 int rc; | 1650 int rc; |
1544 DbPage *pDbPage; | 1651 DbPage *pDbPage; |
1545 | 1652 |
| 1653 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY ); |
1546 assert( sqlite3_mutex_held(pBt->mutex) ); | 1654 assert( sqlite3_mutex_held(pBt->mutex) ); |
1547 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent); | 1655 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags); |
1548 if( rc ) return rc; | 1656 if( rc ) return rc; |
1549 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt); | 1657 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt); |
1550 return SQLITE_OK; | 1658 return SQLITE_OK; |
1551 } | 1659 } |
1552 | 1660 |
1553 /* | 1661 /* |
1554 ** Retrieve a page from the pager cache. If the requested page is not | 1662 ** Retrieve a page from the pager cache. If the requested page is not |
1555 ** already in the pager cache return NULL. Initialize the MemPage.pBt and | 1663 ** already in the pager cache return NULL. Initialize the MemPage.pBt and |
1556 ** MemPage.aData elements if needed. | 1664 ** MemPage.aData elements if needed. |
1557 */ | 1665 */ |
(...skipping 10 matching lines...) Expand all Loading... |
1568 /* | 1676 /* |
1569 ** Return the size of the database file in pages. If there is any kind of | 1677 ** Return the size of the database file in pages. If there is any kind of |
1570 ** error, return ((unsigned int)-1). | 1678 ** error, return ((unsigned int)-1). |
1571 */ | 1679 */ |
1572 static Pgno btreePagecount(BtShared *pBt){ | 1680 static Pgno btreePagecount(BtShared *pBt){ |
1573 return pBt->nPage; | 1681 return pBt->nPage; |
1574 } | 1682 } |
1575 u32 sqlite3BtreeLastPage(Btree *p){ | 1683 u32 sqlite3BtreeLastPage(Btree *p){ |
1576 assert( sqlite3BtreeHoldsMutex(p) ); | 1684 assert( sqlite3BtreeHoldsMutex(p) ); |
1577 assert( ((p->pBt->nPage)&0x8000000)==0 ); | 1685 assert( ((p->pBt->nPage)&0x8000000)==0 ); |
1578 return (int)btreePagecount(p->pBt); | 1686 return btreePagecount(p->pBt); |
1579 } | 1687 } |
1580 | 1688 |
1581 /* | 1689 /* |
1582 ** Get a page from the pager and initialize it. This routine is just a | 1690 ** Get a page from the pager and initialize it. This routine is just a |
1583 ** convenience wrapper around separate calls to btreeGetPage() and | 1691 ** convenience wrapper around separate calls to btreeGetPage() and |
1584 ** btreeInitPage(). | 1692 ** btreeInitPage(). |
1585 ** | 1693 ** |
1586 ** If an error occurs, then the value *ppPage is set to is undefined. It | 1694 ** If an error occurs, then the value *ppPage is set to is undefined. It |
1587 ** may remain unchanged, or it may be set to an invalid value. | 1695 ** may remain unchanged, or it may be set to an invalid value. |
1588 */ | 1696 */ |
1589 static int getAndInitPage( | 1697 static int getAndInitPage( |
1590 BtShared *pBt, /* The database file */ | 1698 BtShared *pBt, /* The database file */ |
1591 Pgno pgno, /* Number of the page to get */ | 1699 Pgno pgno, /* Number of the page to get */ |
1592 MemPage **ppPage /* Write the page pointer here */ | 1700 MemPage **ppPage, /* Write the page pointer here */ |
| 1701 int bReadonly /* PAGER_GET_READONLY or 0 */ |
1593 ){ | 1702 ){ |
1594 int rc; | 1703 int rc; |
1595 assert( sqlite3_mutex_held(pBt->mutex) ); | 1704 assert( sqlite3_mutex_held(pBt->mutex) ); |
| 1705 assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 ); |
1596 | 1706 |
1597 if( pgno>btreePagecount(pBt) ){ | 1707 if( pgno>btreePagecount(pBt) ){ |
1598 rc = SQLITE_CORRUPT_BKPT; | 1708 rc = SQLITE_CORRUPT_BKPT; |
1599 }else{ | 1709 }else{ |
1600 rc = btreeGetPage(pBt, pgno, ppPage, 0); | 1710 rc = btreeGetPage(pBt, pgno, ppPage, bReadonly); |
1601 if( rc==SQLITE_OK ){ | 1711 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){ |
1602 rc = btreeInitPage(*ppPage); | 1712 rc = btreeInitPage(*ppPage); |
1603 if( rc!=SQLITE_OK ){ | 1713 if( rc!=SQLITE_OK ){ |
1604 releasePage(*ppPage); | 1714 releasePage(*ppPage); |
1605 } | 1715 } |
1606 } | 1716 } |
1607 } | 1717 } |
1608 | 1718 |
1609 testcase( pgno==0 ); | 1719 testcase( pgno==0 ); |
1610 assert( pgno!=0 || rc==SQLITE_CORRUPT ); | 1720 assert( pgno!=0 || rc==SQLITE_CORRUPT ); |
1611 return rc; | 1721 return rc; |
1612 } | 1722 } |
1613 | 1723 |
1614 /* | 1724 /* |
1615 ** Release a MemPage. This should be called once for each prior | 1725 ** Release a MemPage. This should be called once for each prior |
1616 ** call to btreeGetPage. | 1726 ** call to btreeGetPage. |
1617 */ | 1727 */ |
1618 static void releasePage(MemPage *pPage){ | 1728 static void releasePage(MemPage *pPage){ |
1619 if( pPage ){ | 1729 if( pPage ){ |
1620 assert( pPage->aData ); | 1730 assert( pPage->aData ); |
1621 assert( pPage->pBt ); | 1731 assert( pPage->pBt ); |
| 1732 assert( pPage->pDbPage!=0 ); |
1622 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); | 1733 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); |
1623 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData ); | 1734 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData ); |
1624 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); | 1735 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); |
1625 sqlite3PagerUnref(pPage->pDbPage); | 1736 sqlite3PagerUnrefNotNull(pPage->pDbPage); |
1626 } | 1737 } |
1627 } | 1738 } |
1628 | 1739 |
1629 /* | 1740 /* |
1630 ** During a rollback, when the pager reloads information into the cache | 1741 ** During a rollback, when the pager reloads information into the cache |
1631 ** so that the cache is restored to its original state at the start of | 1742 ** so that the cache is restored to its original state at the start of |
1632 ** the transaction, for each page restored this routine is called. | 1743 ** the transaction, for each page restored this routine is called. |
1633 ** | 1744 ** |
1634 ** This routine needs to reset the extra data section at the end of the | 1745 ** This routine needs to reset the extra data section at the end of the |
1635 ** page to agree with the restored data. | 1746 ** page to agree with the restored data. |
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1668 ** | 1779 ** |
1669 ** zFilename is the name of the database file. If zFilename is NULL | 1780 ** zFilename is the name of the database file. If zFilename is NULL |
1670 ** then an ephemeral database is created. The ephemeral database might | 1781 ** then an ephemeral database is created. The ephemeral database might |
1671 ** be exclusively in memory, or it might use a disk-based memory cache. | 1782 ** be exclusively in memory, or it might use a disk-based memory cache. |
1672 ** Either way, the ephemeral database will be automatically deleted | 1783 ** Either way, the ephemeral database will be automatically deleted |
1673 ** when sqlite3BtreeClose() is called. | 1784 ** when sqlite3BtreeClose() is called. |
1674 ** | 1785 ** |
1675 ** If zFilename is ":memory:" then an in-memory database is created | 1786 ** If zFilename is ":memory:" then an in-memory database is created |
1676 ** that is automatically destroyed when it is closed. | 1787 ** that is automatically destroyed when it is closed. |
1677 ** | 1788 ** |
1678 ** The "flags" parameter is a bitmask that might contain bits | 1789 ** The "flags" parameter is a bitmask that might contain bits like |
1679 ** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK. The BTREE_NO_READLOCK | 1790 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY. |
1680 ** bit is also set if the SQLITE_NoReadlock flags is set in db->flags. | |
1681 ** These flags are passed through into sqlite3PagerOpen() and must | |
1682 ** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK. | |
1683 ** | 1791 ** |
1684 ** If the database is already opened in the same database connection | 1792 ** If the database is already opened in the same database connection |
1685 ** and we are in shared cache mode, then the open will fail with an | 1793 ** and we are in shared cache mode, then the open will fail with an |
1686 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared | 1794 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared |
1687 ** objects in the same database connection since doing so will lead | 1795 ** objects in the same database connection since doing so will lead |
1688 ** to problems with locking. | 1796 ** to problems with locking. |
1689 */ | 1797 */ |
1690 int sqlite3BtreeOpen( | 1798 int sqlite3BtreeOpen( |
| 1799 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */ |
1691 const char *zFilename, /* Name of the file containing the BTree database */ | 1800 const char *zFilename, /* Name of the file containing the BTree database */ |
1692 sqlite3 *db, /* Associated database handle */ | 1801 sqlite3 *db, /* Associated database handle */ |
1693 Btree **ppBtree, /* Pointer to new Btree object written here */ | 1802 Btree **ppBtree, /* Pointer to new Btree object written here */ |
1694 int flags, /* Options */ | 1803 int flags, /* Options */ |
1695 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */ | 1804 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */ |
1696 ){ | 1805 ){ |
1697 sqlite3_vfs *pVfs; /* The VFS to use for this btree */ | |
1698 BtShared *pBt = 0; /* Shared part of btree structure */ | 1806 BtShared *pBt = 0; /* Shared part of btree structure */ |
1699 Btree *p; /* Handle to return */ | 1807 Btree *p; /* Handle to return */ |
1700 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */ | 1808 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */ |
1701 int rc = SQLITE_OK; /* Result code from this function */ | 1809 int rc = SQLITE_OK; /* Result code from this function */ |
1702 u8 nReserve; /* Byte of unused space on each page */ | 1810 u8 nReserve; /* Byte of unused space on each page */ |
1703 unsigned char zDbHeader[100]; /* Database header content */ | 1811 unsigned char zDbHeader[100]; /* Database header content */ |
1704 | 1812 |
1705 /* True if opening an ephemeral, temporary database */ | 1813 /* True if opening an ephemeral, temporary database */ |
1706 const int isTempDb = zFilename==0 || zFilename[0]==0; | 1814 const int isTempDb = zFilename==0 || zFilename[0]==0; |
1707 | 1815 |
1708 /* Set the variable isMemdb to true for an in-memory database, or | 1816 /* Set the variable isMemdb to true for an in-memory database, or |
1709 ** false for a file-based database. | 1817 ** false for a file-based database. |
1710 */ | 1818 */ |
1711 #ifdef SQLITE_OMIT_MEMORYDB | 1819 #ifdef SQLITE_OMIT_MEMORYDB |
1712 const int isMemdb = 0; | 1820 const int isMemdb = 0; |
1713 #else | 1821 #else |
1714 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0) | 1822 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0) |
1715 || (isTempDb && sqlite3TempInMemory(db)); | 1823 || (isTempDb && sqlite3TempInMemory(db)) |
| 1824 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0; |
1716 #endif | 1825 #endif |
1717 | 1826 |
1718 assert( db!=0 ); | 1827 assert( db!=0 ); |
| 1828 assert( pVfs!=0 ); |
1719 assert( sqlite3_mutex_held(db->mutex) ); | 1829 assert( sqlite3_mutex_held(db->mutex) ); |
1720 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */ | 1830 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */ |
1721 | 1831 |
1722 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */ | 1832 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */ |
1723 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 ); | 1833 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 ); |
1724 | 1834 |
1725 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */ | 1835 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */ |
1726 assert( (flags & BTREE_SINGLE)==0 || isTempDb ); | 1836 assert( (flags & BTREE_SINGLE)==0 || isTempDb ); |
1727 | 1837 |
1728 if( db->flags & SQLITE_NoReadlock ){ | |
1729 flags |= BTREE_NO_READLOCK; | |
1730 } | |
1731 if( isMemdb ){ | 1838 if( isMemdb ){ |
1732 flags |= BTREE_MEMORY; | 1839 flags |= BTREE_MEMORY; |
1733 } | 1840 } |
1734 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){ | 1841 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){ |
1735 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB; | 1842 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB; |
1736 } | 1843 } |
1737 pVfs = db->pVfs; | |
1738 p = sqlite3MallocZero(sizeof(Btree)); | 1844 p = sqlite3MallocZero(sizeof(Btree)); |
1739 if( !p ){ | 1845 if( !p ){ |
1740 return SQLITE_NOMEM; | 1846 return SQLITE_NOMEM; |
1741 } | 1847 } |
1742 p->inTrans = TRANS_NONE; | 1848 p->inTrans = TRANS_NONE; |
1743 p->db = db; | 1849 p->db = db; |
1744 #ifndef SQLITE_OMIT_SHARED_CACHE | 1850 #ifndef SQLITE_OMIT_SHARED_CACHE |
1745 p->lock.pBtree = p; | 1851 p->lock.pBtree = p; |
1746 p->lock.iTable = 1; | 1852 p->lock.iTable = 1; |
1747 #endif | 1853 #endif |
1748 | 1854 |
1749 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) | 1855 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) |
1750 /* | 1856 /* |
1751 ** If this Btree is a candidate for shared cache, try to find an | 1857 ** If this Btree is a candidate for shared cache, try to find an |
1752 ** existing BtShared object that we can share with | 1858 ** existing BtShared object that we can share with |
1753 */ | 1859 */ |
1754 if( isMemdb==0 && isTempDb==0 ){ | 1860 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){ |
1755 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){ | 1861 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){ |
1756 int nFullPathname = pVfs->mxPathname+1; | 1862 int nFullPathname = pVfs->mxPathname+1; |
1757 char *zFullPathname = sqlite3Malloc(nFullPathname); | 1863 char *zFullPathname = sqlite3Malloc(nFullPathname); |
1758 sqlite3_mutex *mutexShared; | 1864 MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) |
1759 p->sharable = 1; | 1865 p->sharable = 1; |
1760 if( !zFullPathname ){ | 1866 if( !zFullPathname ){ |
1761 sqlite3_free(p); | 1867 sqlite3_free(p); |
1762 return SQLITE_NOMEM; | 1868 return SQLITE_NOMEM; |
1763 } | 1869 } |
1764 sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname); | 1870 if( isMemdb ){ |
| 1871 memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1); |
| 1872 }else{ |
| 1873 rc = sqlite3OsFullPathname(pVfs, zFilename, |
| 1874 nFullPathname, zFullPathname); |
| 1875 if( rc ){ |
| 1876 sqlite3_free(zFullPathname); |
| 1877 sqlite3_free(p); |
| 1878 return rc; |
| 1879 } |
| 1880 } |
| 1881 #if SQLITE_THREADSAFE |
1765 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN); | 1882 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN); |
1766 sqlite3_mutex_enter(mutexOpen); | 1883 sqlite3_mutex_enter(mutexOpen); |
1767 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); | 1884 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); |
1768 sqlite3_mutex_enter(mutexShared); | 1885 sqlite3_mutex_enter(mutexShared); |
| 1886 #endif |
1769 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){ | 1887 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){ |
1770 assert( pBt->nRef>0 ); | 1888 assert( pBt->nRef>0 ); |
1771 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager)) | 1889 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0)) |
1772 && sqlite3PagerVfs(pBt->pPager)==pVfs ){ | 1890 && sqlite3PagerVfs(pBt->pPager)==pVfs ){ |
1773 int iDb; | 1891 int iDb; |
1774 for(iDb=db->nDb-1; iDb>=0; iDb--){ | 1892 for(iDb=db->nDb-1; iDb>=0; iDb--){ |
1775 Btree *pExisting = db->aDb[iDb].pBt; | 1893 Btree *pExisting = db->aDb[iDb].pBt; |
1776 if( pExisting && pExisting->pBt==pBt ){ | 1894 if( pExisting && pExisting->pBt==pBt ){ |
1777 sqlite3_mutex_leave(mutexShared); | 1895 sqlite3_mutex_leave(mutexShared); |
1778 sqlite3_mutex_leave(mutexOpen); | 1896 sqlite3_mutex_leave(mutexOpen); |
1779 sqlite3_free(zFullPathname); | 1897 sqlite3_free(zFullPathname); |
1780 sqlite3_free(p); | 1898 sqlite3_free(p); |
1781 return SQLITE_CONSTRAINT; | 1899 return SQLITE_CONSTRAINT; |
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1814 assert( sizeof(Pgno)==4 ); | 1932 assert( sizeof(Pgno)==4 ); |
1815 | 1933 |
1816 pBt = sqlite3MallocZero( sizeof(*pBt) ); | 1934 pBt = sqlite3MallocZero( sizeof(*pBt) ); |
1817 if( pBt==0 ){ | 1935 if( pBt==0 ){ |
1818 rc = SQLITE_NOMEM; | 1936 rc = SQLITE_NOMEM; |
1819 goto btree_open_out; | 1937 goto btree_open_out; |
1820 } | 1938 } |
1821 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename, | 1939 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename, |
1822 EXTRA_SIZE, flags, vfsFlags, pageReinit); | 1940 EXTRA_SIZE, flags, vfsFlags, pageReinit); |
1823 if( rc==SQLITE_OK ){ | 1941 if( rc==SQLITE_OK ){ |
| 1942 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap); |
1824 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader); | 1943 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader); |
1825 } | 1944 } |
1826 if( rc!=SQLITE_OK ){ | 1945 if( rc!=SQLITE_OK ){ |
1827 goto btree_open_out; | 1946 goto btree_open_out; |
1828 } | 1947 } |
1829 pBt->openFlags = (u8)flags; | 1948 pBt->openFlags = (u8)flags; |
1830 pBt->db = db; | 1949 pBt->db = db; |
1831 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt); | 1950 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt); |
1832 p->pBt = pBt; | 1951 p->pBt = pBt; |
1833 | 1952 |
1834 pBt->pCursor = 0; | 1953 pBt->pCursor = 0; |
1835 pBt->pPage1 = 0; | 1954 pBt->pPage1 = 0; |
1836 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager); | 1955 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY; |
1837 #ifdef SQLITE_SECURE_DELETE | 1956 #ifdef SQLITE_SECURE_DELETE |
1838 pBt->secureDelete = 1; | 1957 pBt->btsFlags |= BTS_SECURE_DELETE; |
1839 #endif | 1958 #endif |
1840 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16); | 1959 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16); |
1841 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE | 1960 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE |
1842 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){ | 1961 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){ |
1843 pBt->pageSize = 0; | 1962 pBt->pageSize = 0; |
1844 #ifndef SQLITE_OMIT_AUTOVACUUM | 1963 #ifndef SQLITE_OMIT_AUTOVACUUM |
1845 /* If the magic name ":memory:" will create an in-memory database, then | 1964 /* If the magic name ":memory:" will create an in-memory database, then |
1846 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if | 1965 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if |
1847 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if | 1966 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if |
1848 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a | 1967 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a |
1849 ** regular file-name. In this case the auto-vacuum applies as per normal. | 1968 ** regular file-name. In this case the auto-vacuum applies as per normal. |
1850 */ | 1969 */ |
1851 if( zFilename && !isMemdb ){ | 1970 if( zFilename && !isMemdb ){ |
1852 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0); | 1971 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0); |
1853 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0); | 1972 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0); |
1854 } | 1973 } |
1855 #endif | 1974 #endif |
1856 nReserve = 0; | 1975 nReserve = 0; |
1857 }else{ | 1976 }else{ |
1858 nReserve = zDbHeader[20]; | 1977 nReserve = zDbHeader[20]; |
1859 pBt->pageSizeFixed = 1; | 1978 pBt->btsFlags |= BTS_PAGESIZE_FIXED; |
1860 #ifndef SQLITE_OMIT_AUTOVACUUM | 1979 #ifndef SQLITE_OMIT_AUTOVACUUM |
1861 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0); | 1980 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0); |
1862 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0); | 1981 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0); |
1863 #endif | 1982 #endif |
1864 } | 1983 } |
1865 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); | 1984 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); |
1866 if( rc ) goto btree_open_out; | 1985 if( rc ) goto btree_open_out; |
1867 pBt->usableSize = pBt->pageSize - nReserve; | 1986 pBt->usableSize = pBt->pageSize - nReserve; |
1868 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */ | 1987 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */ |
1869 | 1988 |
1870 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) | 1989 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) |
1871 /* Add the new BtShared object to the linked list sharable BtShareds. | 1990 /* Add the new BtShared object to the linked list sharable BtShareds. |
1872 */ | 1991 */ |
1873 if( p->sharable ){ | 1992 if( p->sharable ){ |
1874 sqlite3_mutex *mutexShared; | 1993 MUTEX_LOGIC( sqlite3_mutex *mutexShared; ) |
1875 pBt->nRef = 1; | 1994 pBt->nRef = 1; |
1876 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); | 1995 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);) |
1877 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){ | 1996 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){ |
1878 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST); | 1997 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST); |
1879 if( pBt->mutex==0 ){ | 1998 if( pBt->mutex==0 ){ |
1880 rc = SQLITE_NOMEM; | 1999 rc = SQLITE_NOMEM; |
1881 db->mallocFailed = 0; | 2000 db->mallocFailed = 0; |
1882 goto btree_open_out; | 2001 goto btree_open_out; |
1883 } | 2002 } |
1884 } | 2003 } |
1885 sqlite3_mutex_enter(mutexShared); | 2004 sqlite3_mutex_enter(mutexShared); |
1886 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList); | 2005 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList); |
(...skipping 61 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1948 } | 2067 } |
1949 | 2068 |
1950 /* | 2069 /* |
1951 ** Decrement the BtShared.nRef counter. When it reaches zero, | 2070 ** Decrement the BtShared.nRef counter. When it reaches zero, |
1952 ** remove the BtShared structure from the sharing list. Return | 2071 ** remove the BtShared structure from the sharing list. Return |
1953 ** true if the BtShared.nRef counter reaches zero and return | 2072 ** true if the BtShared.nRef counter reaches zero and return |
1954 ** false if it is still positive. | 2073 ** false if it is still positive. |
1955 */ | 2074 */ |
1956 static int removeFromSharingList(BtShared *pBt){ | 2075 static int removeFromSharingList(BtShared *pBt){ |
1957 #ifndef SQLITE_OMIT_SHARED_CACHE | 2076 #ifndef SQLITE_OMIT_SHARED_CACHE |
1958 sqlite3_mutex *pMaster; | 2077 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) |
1959 BtShared *pList; | 2078 BtShared *pList; |
1960 int removed = 0; | 2079 int removed = 0; |
1961 | 2080 |
1962 assert( sqlite3_mutex_notheld(pBt->mutex) ); | 2081 assert( sqlite3_mutex_notheld(pBt->mutex) ); |
1963 pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); | 2082 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); ) |
1964 sqlite3_mutex_enter(pMaster); | 2083 sqlite3_mutex_enter(pMaster); |
1965 pBt->nRef--; | 2084 pBt->nRef--; |
1966 if( pBt->nRef<=0 ){ | 2085 if( pBt->nRef<=0 ){ |
1967 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){ | 2086 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){ |
1968 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext; | 2087 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext; |
1969 }else{ | 2088 }else{ |
1970 pList = GLOBAL(BtShared*,sqlite3SharedCacheList); | 2089 pList = GLOBAL(BtShared*,sqlite3SharedCacheList); |
1971 while( ALWAYS(pList) && pList->pNext!=pBt ){ | 2090 while( ALWAYS(pList) && pList->pNext!=pBt ){ |
1972 pList=pList->pNext; | 2091 pList=pList->pNext; |
1973 } | 2092 } |
1974 if( ALWAYS(pList) ){ | 2093 if( ALWAYS(pList) ){ |
1975 pList->pNext = pBt->pNext; | 2094 pList->pNext = pBt->pNext; |
1976 } | 2095 } |
1977 } | 2096 } |
1978 if( SQLITE_THREADSAFE ){ | 2097 if( SQLITE_THREADSAFE ){ |
1979 sqlite3_mutex_free(pBt->mutex); | 2098 sqlite3_mutex_free(pBt->mutex); |
1980 } | 2099 } |
1981 removed = 1; | 2100 removed = 1; |
1982 } | 2101 } |
1983 sqlite3_mutex_leave(pMaster); | 2102 sqlite3_mutex_leave(pMaster); |
1984 return removed; | 2103 return removed; |
1985 #else | 2104 #else |
1986 return 1; | 2105 return 1; |
1987 #endif | 2106 #endif |
1988 } | 2107 } |
1989 | 2108 |
1990 /* | 2109 /* |
1991 ** Make sure pBt->pTmpSpace points to an allocation of | 2110 ** Make sure pBt->pTmpSpace points to an allocation of |
1992 ** MX_CELL_SIZE(pBt) bytes. | 2111 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child |
| 2112 ** pointer. |
1993 */ | 2113 */ |
1994 static void allocateTempSpace(BtShared *pBt){ | 2114 static void allocateTempSpace(BtShared *pBt){ |
1995 if( !pBt->pTmpSpace ){ | 2115 if( !pBt->pTmpSpace ){ |
1996 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize ); | 2116 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize ); |
| 2117 |
| 2118 /* One of the uses of pBt->pTmpSpace is to format cells before |
| 2119 ** inserting them into a leaf page (function fillInCell()). If |
| 2120 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes |
| 2121 ** by the various routines that manipulate binary cells. Which |
| 2122 ** can mean that fillInCell() only initializes the first 2 or 3 |
| 2123 ** bytes of pTmpSpace, but that the first 4 bytes are copied from |
| 2124 ** it into a database page. This is not actually a problem, but it |
| 2125 ** does cause a valgrind error when the 1 or 2 bytes of unitialized |
| 2126 ** data is passed to system call write(). So to avoid this error, |
| 2127 ** zero the first 4 bytes of temp space here. |
| 2128 ** |
| 2129 ** Also: Provide four bytes of initialized space before the |
| 2130 ** beginning of pTmpSpace as an area available to prepend the |
| 2131 ** left-child pointer to the beginning of a cell. |
| 2132 */ |
| 2133 if( pBt->pTmpSpace ){ |
| 2134 memset(pBt->pTmpSpace, 0, 8); |
| 2135 pBt->pTmpSpace += 4; |
| 2136 } |
1997 } | 2137 } |
1998 } | 2138 } |
1999 | 2139 |
2000 /* | 2140 /* |
2001 ** Free the pBt->pTmpSpace allocation | 2141 ** Free the pBt->pTmpSpace allocation |
2002 */ | 2142 */ |
2003 static void freeTempSpace(BtShared *pBt){ | 2143 static void freeTempSpace(BtShared *pBt){ |
2004 sqlite3PageFree( pBt->pTmpSpace); | 2144 if( pBt->pTmpSpace ){ |
2005 pBt->pTmpSpace = 0; | 2145 pBt->pTmpSpace -= 4; |
| 2146 sqlite3PageFree(pBt->pTmpSpace); |
| 2147 pBt->pTmpSpace = 0; |
| 2148 } |
2006 } | 2149 } |
2007 | 2150 |
2008 /* | 2151 /* |
2009 ** Close an open database and invalidate all cursors. | 2152 ** Close an open database and invalidate all cursors. |
2010 */ | 2153 */ |
2011 int sqlite3BtreeClose(Btree *p){ | 2154 int sqlite3BtreeClose(Btree *p){ |
2012 BtShared *pBt = p->pBt; | 2155 BtShared *pBt = p->pBt; |
2013 BtCursor *pCur; | 2156 BtCursor *pCur; |
2014 | 2157 |
2015 /* Close all cursors opened via this handle. */ | 2158 /* Close all cursors opened via this handle. */ |
2016 assert( sqlite3_mutex_held(p->db->mutex) ); | 2159 assert( sqlite3_mutex_held(p->db->mutex) ); |
2017 sqlite3BtreeEnter(p); | 2160 sqlite3BtreeEnter(p); |
2018 pCur = pBt->pCursor; | 2161 pCur = pBt->pCursor; |
2019 while( pCur ){ | 2162 while( pCur ){ |
2020 BtCursor *pTmp = pCur; | 2163 BtCursor *pTmp = pCur; |
2021 pCur = pCur->pNext; | 2164 pCur = pCur->pNext; |
2022 if( pTmp->pBtree==p ){ | 2165 if( pTmp->pBtree==p ){ |
2023 sqlite3BtreeCloseCursor(pTmp); | 2166 sqlite3BtreeCloseCursor(pTmp); |
2024 } | 2167 } |
2025 } | 2168 } |
2026 | 2169 |
2027 /* Rollback any active transaction and free the handle structure. | 2170 /* Rollback any active transaction and free the handle structure. |
2028 ** The call to sqlite3BtreeRollback() drops any table-locks held by | 2171 ** The call to sqlite3BtreeRollback() drops any table-locks held by |
2029 ** this handle. | 2172 ** this handle. |
2030 */ | 2173 */ |
2031 sqlite3BtreeRollback(p); | 2174 sqlite3BtreeRollback(p, SQLITE_OK, 0); |
2032 sqlite3BtreeLeave(p); | 2175 sqlite3BtreeLeave(p); |
2033 | 2176 |
2034 /* If there are still other outstanding references to the shared-btree | 2177 /* If there are still other outstanding references to the shared-btree |
2035 ** structure, return now. The remainder of this procedure cleans | 2178 ** structure, return now. The remainder of this procedure cleans |
2036 ** up the shared-btree. | 2179 ** up the shared-btree. |
2037 */ | 2180 */ |
2038 assert( p->wantToLock==0 && p->locked==0 ); | 2181 assert( p->wantToLock==0 && p->locked==0 ); |
2039 if( !p->sharable || removeFromSharingList(pBt) ){ | 2182 if( !p->sharable || removeFromSharingList(pBt) ){ |
2040 /* The pBt is no longer on the sharing list, so we can access | 2183 /* The pBt is no longer on the sharing list, so we can access |
2041 ** it without having to hold the mutex. | 2184 ** it without having to hold the mutex. |
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
2080 */ | 2223 */ |
2081 int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){ | 2224 int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){ |
2082 BtShared *pBt = p->pBt; | 2225 BtShared *pBt = p->pBt; |
2083 assert( sqlite3_mutex_held(p->db->mutex) ); | 2226 assert( sqlite3_mutex_held(p->db->mutex) ); |
2084 sqlite3BtreeEnter(p); | 2227 sqlite3BtreeEnter(p); |
2085 sqlite3PagerSetCachesize(pBt->pPager, mxPage); | 2228 sqlite3PagerSetCachesize(pBt->pPager, mxPage); |
2086 sqlite3BtreeLeave(p); | 2229 sqlite3BtreeLeave(p); |
2087 return SQLITE_OK; | 2230 return SQLITE_OK; |
2088 } | 2231 } |
2089 | 2232 |
| 2233 #if SQLITE_MAX_MMAP_SIZE>0 |
| 2234 /* |
| 2235 ** Change the limit on the amount of the database file that may be |
| 2236 ** memory mapped. |
| 2237 */ |
| 2238 int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){ |
| 2239 BtShared *pBt = p->pBt; |
| 2240 assert( sqlite3_mutex_held(p->db->mutex) ); |
| 2241 sqlite3BtreeEnter(p); |
| 2242 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap); |
| 2243 sqlite3BtreeLeave(p); |
| 2244 return SQLITE_OK; |
| 2245 } |
| 2246 #endif /* SQLITE_MAX_MMAP_SIZE>0 */ |
| 2247 |
2090 /* | 2248 /* |
2091 ** Change the way data is synced to disk in order to increase or decrease | 2249 ** Change the way data is synced to disk in order to increase or decrease |
2092 ** how well the database resists damage due to OS crashes and power | 2250 ** how well the database resists damage due to OS crashes and power |
2093 ** failures. Level 1 is the same as asynchronous (no syncs() occur and | 2251 ** failures. Level 1 is the same as asynchronous (no syncs() occur and |
2094 ** there is a high probability of damage) Level 2 is the default. There | 2252 ** there is a high probability of damage) Level 2 is the default. There |
2095 ** is a very low but non-zero probability of damage. Level 3 reduces the | 2253 ** is a very low but non-zero probability of damage. Level 3 reduces the |
2096 ** probability of damage to near zero but with a write performance reduction. | 2254 ** probability of damage to near zero but with a write performance reduction. |
2097 */ | 2255 */ |
2098 #ifndef SQLITE_OMIT_PAGER_PRAGMAS | 2256 #ifndef SQLITE_OMIT_PAGER_PRAGMAS |
2099 int sqlite3BtreeSetSafetyLevel( | 2257 int sqlite3BtreeSetPagerFlags( |
2100 Btree *p, /* The btree to set the safety level on */ | 2258 Btree *p, /* The btree to set the safety level on */ |
2101 int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */ | 2259 unsigned pgFlags /* Various PAGER_* flags */ |
2102 int fullSync, /* PRAGMA fullfsync. */ | |
2103 int ckptFullSync /* PRAGMA checkpoint_fullfync */ | |
2104 ){ | 2260 ){ |
2105 BtShared *pBt = p->pBt; | 2261 BtShared *pBt = p->pBt; |
2106 assert( sqlite3_mutex_held(p->db->mutex) ); | 2262 assert( sqlite3_mutex_held(p->db->mutex) ); |
2107 assert( level>=1 && level<=3 ); | |
2108 sqlite3BtreeEnter(p); | 2263 sqlite3BtreeEnter(p); |
2109 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync); | 2264 sqlite3PagerSetFlags(pBt->pPager, pgFlags); |
2110 sqlite3BtreeLeave(p); | 2265 sqlite3BtreeLeave(p); |
2111 return SQLITE_OK; | 2266 return SQLITE_OK; |
2112 } | 2267 } |
2113 #endif | 2268 #endif |
2114 | 2269 |
2115 /* | 2270 /* |
2116 ** Return TRUE if the given btree is set to safety level 1. In other | 2271 ** Return TRUE if the given btree is set to safety level 1. In other |
2117 ** words, return TRUE if no sync() occurs on the disk files. | 2272 ** words, return TRUE if no sync() occurs on the disk files. |
2118 */ | 2273 */ |
2119 int sqlite3BtreeSyncDisabled(Btree *p){ | 2274 int sqlite3BtreeSyncDisabled(Btree *p){ |
(...skipping 17 matching lines...) Expand all Loading... |
2137 ** changed. | 2292 ** changed. |
2138 ** | 2293 ** |
2139 ** Page sizes are constrained to be a power of two so that the region | 2294 ** Page sizes are constrained to be a power of two so that the region |
2140 ** of the database file used for locking (beginning at PENDING_BYTE, | 2295 ** of the database file used for locking (beginning at PENDING_BYTE, |
2141 ** the first byte past the 1GB boundary, 0x40000000) needs to occur | 2296 ** the first byte past the 1GB boundary, 0x40000000) needs to occur |
2142 ** at the beginning of a page. | 2297 ** at the beginning of a page. |
2143 ** | 2298 ** |
2144 ** If parameter nReserve is less than zero, then the number of reserved | 2299 ** If parameter nReserve is less than zero, then the number of reserved |
2145 ** bytes per page is left unchanged. | 2300 ** bytes per page is left unchanged. |
2146 ** | 2301 ** |
2147 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size | 2302 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size |
2148 ** and autovacuum mode can no longer be changed. | 2303 ** and autovacuum mode can no longer be changed. |
2149 */ | 2304 */ |
2150 int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){ | 2305 int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){ |
2151 int rc = SQLITE_OK; | 2306 int rc = SQLITE_OK; |
2152 BtShared *pBt = p->pBt; | 2307 BtShared *pBt = p->pBt; |
2153 assert( nReserve>=-1 && nReserve<=255 ); | 2308 assert( nReserve>=-1 && nReserve<=255 ); |
2154 sqlite3BtreeEnter(p); | 2309 sqlite3BtreeEnter(p); |
2155 if( pBt->pageSizeFixed ){ | 2310 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){ |
2156 sqlite3BtreeLeave(p); | 2311 sqlite3BtreeLeave(p); |
2157 return SQLITE_READONLY; | 2312 return SQLITE_READONLY; |
2158 } | 2313 } |
2159 if( nReserve<0 ){ | 2314 if( nReserve<0 ){ |
2160 nReserve = pBt->pageSize - pBt->usableSize; | 2315 nReserve = pBt->pageSize - pBt->usableSize; |
2161 } | 2316 } |
2162 assert( nReserve>=0 && nReserve<=255 ); | 2317 assert( nReserve>=0 && nReserve<=255 ); |
2163 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE && | 2318 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE && |
2164 ((pageSize-1)&pageSize)==0 ){ | 2319 ((pageSize-1)&pageSize)==0 ){ |
2165 assert( (pageSize & 7)==0 ); | 2320 assert( (pageSize & 7)==0 ); |
2166 assert( !pBt->pPage1 && !pBt->pCursor ); | 2321 assert( !pBt->pPage1 && !pBt->pCursor ); |
2167 pBt->pageSize = (u32)pageSize; | 2322 pBt->pageSize = (u32)pageSize; |
2168 freeTempSpace(pBt); | 2323 freeTempSpace(pBt); |
2169 } | 2324 } |
2170 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); | 2325 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve); |
2171 pBt->usableSize = pBt->pageSize - (u16)nReserve; | 2326 pBt->usableSize = pBt->pageSize - (u16)nReserve; |
2172 if( iFix ) pBt->pageSizeFixed = 1; | 2327 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED; |
2173 sqlite3BtreeLeave(p); | 2328 sqlite3BtreeLeave(p); |
2174 return rc; | 2329 return rc; |
2175 } | 2330 } |
2176 | 2331 |
2177 /* | 2332 /* |
2178 ** Return the currently defined page size | 2333 ** Return the currently defined page size |
2179 */ | 2334 */ |
2180 int sqlite3BtreeGetPageSize(Btree *p){ | 2335 int sqlite3BtreeGetPageSize(Btree *p){ |
2181 return p->pBt->pageSize; | 2336 return p->pBt->pageSize; |
2182 } | 2337 } |
2183 | 2338 |
| 2339 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG) |
| 2340 /* |
| 2341 ** This function is similar to sqlite3BtreeGetReserve(), except that it |
| 2342 ** may only be called if it is guaranteed that the b-tree mutex is already |
| 2343 ** held. |
| 2344 ** |
| 2345 ** This is useful in one special case in the backup API code where it is |
| 2346 ** known that the shared b-tree mutex is held, but the mutex on the |
| 2347 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter() |
| 2348 ** were to be called, it might collide with some other operation on the |
| 2349 ** database handle that owns *p, causing undefined behavior. |
| 2350 */ |
| 2351 int sqlite3BtreeGetReserveNoMutex(Btree *p){ |
| 2352 assert( sqlite3_mutex_held(p->pBt->mutex) ); |
| 2353 return p->pBt->pageSize - p->pBt->usableSize; |
| 2354 } |
| 2355 #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */ |
| 2356 |
2184 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) | 2357 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) |
2185 /* | 2358 /* |
2186 ** Return the number of bytes of space at the end of every page that | 2359 ** Return the number of bytes of space at the end of every page that |
2187 ** are intentually left unused. This is the "reserved" space that is | 2360 ** are intentually left unused. This is the "reserved" space that is |
2188 ** sometimes used by extensions. | 2361 ** sometimes used by extensions. |
2189 */ | 2362 */ |
2190 int sqlite3BtreeGetReserve(Btree *p){ | 2363 int sqlite3BtreeGetReserve(Btree *p){ |
2191 int n; | 2364 int n; |
2192 sqlite3BtreeEnter(p); | 2365 sqlite3BtreeEnter(p); |
2193 n = p->pBt->pageSize - p->pBt->usableSize; | 2366 n = p->pBt->pageSize - p->pBt->usableSize; |
2194 sqlite3BtreeLeave(p); | 2367 sqlite3BtreeLeave(p); |
2195 return n; | 2368 return n; |
2196 } | 2369 } |
2197 | 2370 |
2198 /* | 2371 /* |
2199 ** Set the maximum page count for a database if mxPage is positive. | 2372 ** Set the maximum page count for a database if mxPage is positive. |
2200 ** No changes are made if mxPage is 0 or negative. | 2373 ** No changes are made if mxPage is 0 or negative. |
2201 ** Regardless of the value of mxPage, return the maximum page count. | 2374 ** Regardless of the value of mxPage, return the maximum page count. |
2202 */ | 2375 */ |
2203 int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){ | 2376 int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){ |
2204 int n; | 2377 int n; |
2205 sqlite3BtreeEnter(p); | 2378 sqlite3BtreeEnter(p); |
2206 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage); | 2379 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage); |
2207 sqlite3BtreeLeave(p); | 2380 sqlite3BtreeLeave(p); |
2208 return n; | 2381 return n; |
2209 } | 2382 } |
2210 | 2383 |
2211 /* | 2384 /* |
2212 ** Set the secureDelete flag if newFlag is 0 or 1. If newFlag is -1, | 2385 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1, |
2213 ** then make no changes. Always return the value of the secureDelete | 2386 ** then make no changes. Always return the value of the BTS_SECURE_DELETE |
2214 ** setting after the change. | 2387 ** setting after the change. |
2215 */ | 2388 */ |
2216 int sqlite3BtreeSecureDelete(Btree *p, int newFlag){ | 2389 int sqlite3BtreeSecureDelete(Btree *p, int newFlag){ |
2217 int b; | 2390 int b; |
2218 if( p==0 ) return 0; | 2391 if( p==0 ) return 0; |
2219 sqlite3BtreeEnter(p); | 2392 sqlite3BtreeEnter(p); |
2220 if( newFlag>=0 ){ | 2393 if( newFlag>=0 ){ |
2221 p->pBt->secureDelete = (newFlag!=0) ? 1 : 0; | 2394 p->pBt->btsFlags &= ~BTS_SECURE_DELETE; |
| 2395 if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE; |
2222 } | 2396 } |
2223 b = p->pBt->secureDelete; | 2397 b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0; |
2224 sqlite3BtreeLeave(p); | 2398 sqlite3BtreeLeave(p); |
2225 return b; | 2399 return b; |
2226 } | 2400 } |
2227 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */ | 2401 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */ |
2228 | 2402 |
2229 /* | 2403 /* |
2230 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum' | 2404 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum' |
2231 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it | 2405 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it |
2232 ** is disabled. The default value for the auto-vacuum property is | 2406 ** is disabled. The default value for the auto-vacuum property is |
2233 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro. | 2407 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro. |
2234 */ | 2408 */ |
2235 int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){ | 2409 int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){ |
2236 #ifdef SQLITE_OMIT_AUTOVACUUM | 2410 #ifdef SQLITE_OMIT_AUTOVACUUM |
2237 return SQLITE_READONLY; | 2411 return SQLITE_READONLY; |
2238 #else | 2412 #else |
2239 BtShared *pBt = p->pBt; | 2413 BtShared *pBt = p->pBt; |
2240 int rc = SQLITE_OK; | 2414 int rc = SQLITE_OK; |
2241 u8 av = (u8)autoVacuum; | 2415 u8 av = (u8)autoVacuum; |
2242 | 2416 |
2243 sqlite3BtreeEnter(p); | 2417 sqlite3BtreeEnter(p); |
2244 if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){ | 2418 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){ |
2245 rc = SQLITE_READONLY; | 2419 rc = SQLITE_READONLY; |
2246 }else{ | 2420 }else{ |
2247 pBt->autoVacuum = av ?1:0; | 2421 pBt->autoVacuum = av ?1:0; |
2248 pBt->incrVacuum = av==2 ?1:0; | 2422 pBt->incrVacuum = av==2 ?1:0; |
2249 } | 2423 } |
2250 sqlite3BtreeLeave(p); | 2424 sqlite3BtreeLeave(p); |
2251 return rc; | 2425 return rc; |
2252 #endif | 2426 #endif |
2253 } | 2427 } |
2254 | 2428 |
(...skipping 53 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
2308 u32 pageSize; | 2482 u32 pageSize; |
2309 u32 usableSize; | 2483 u32 usableSize; |
2310 u8 *page1 = pPage1->aData; | 2484 u8 *page1 = pPage1->aData; |
2311 rc = SQLITE_NOTADB; | 2485 rc = SQLITE_NOTADB; |
2312 if( memcmp(page1, zMagicHeader, 16)!=0 ){ | 2486 if( memcmp(page1, zMagicHeader, 16)!=0 ){ |
2313 goto page1_init_failed; | 2487 goto page1_init_failed; |
2314 } | 2488 } |
2315 | 2489 |
2316 #ifdef SQLITE_OMIT_WAL | 2490 #ifdef SQLITE_OMIT_WAL |
2317 if( page1[18]>1 ){ | 2491 if( page1[18]>1 ){ |
2318 pBt->readOnly = 1; | 2492 pBt->btsFlags |= BTS_READ_ONLY; |
2319 } | 2493 } |
2320 if( page1[19]>1 ){ | 2494 if( page1[19]>1 ){ |
2321 goto page1_init_failed; | 2495 goto page1_init_failed; |
2322 } | 2496 } |
2323 #else | 2497 #else |
2324 if( page1[18]>2 ){ | 2498 if( page1[18]>2 ){ |
2325 pBt->readOnly = 1; | 2499 pBt->btsFlags |= BTS_READ_ONLY; |
2326 } | 2500 } |
2327 if( page1[19]>2 ){ | 2501 if( page1[19]>2 ){ |
2328 goto page1_init_failed; | 2502 goto page1_init_failed; |
2329 } | 2503 } |
2330 | 2504 |
2331 /* If the write version is set to 2, this database should be accessed | 2505 /* If the write version is set to 2, this database should be accessed |
2332 ** in WAL mode. If the log is not already open, open it now. Then | 2506 ** in WAL mode. If the log is not already open, open it now. Then |
2333 ** return SQLITE_OK and return without populating BtShared.pPage1. | 2507 ** return SQLITE_OK and return without populating BtShared.pPage1. |
2334 ** The caller detects this and calls this function again. This is | 2508 ** The caller detects this and calls this function again. This is |
2335 ** required as the version of page 1 currently in the page1 buffer | 2509 ** required as the version of page 1 currently in the page1 buffer |
2336 ** may not be the latest version - there may be a newer one in the log | 2510 ** may not be the latest version - there may be a newer one in the log |
2337 ** file. | 2511 ** file. |
2338 */ | 2512 */ |
2339 if( page1[19]==2 && pBt->doNotUseWAL==0 ){ | 2513 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){ |
2340 int isOpen = 0; | 2514 int isOpen = 0; |
2341 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen); | 2515 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen); |
2342 if( rc!=SQLITE_OK ){ | 2516 if( rc!=SQLITE_OK ){ |
2343 goto page1_init_failed; | 2517 goto page1_init_failed; |
2344 }else if( isOpen==0 ){ | 2518 }else if( isOpen==0 ){ |
2345 releasePage(pPage1); | 2519 releasePage(pPage1); |
2346 return SQLITE_OK; | 2520 return SQLITE_OK; |
2347 } | 2521 } |
2348 rc = SQLITE_NOTADB; | 2522 rc = SQLITE_NOTADB; |
2349 } | 2523 } |
(...skipping 56 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
2406 ** 4-byte nData value | 2580 ** 4-byte nData value |
2407 ** 4-byte overflow page pointer | 2581 ** 4-byte overflow page pointer |
2408 ** So a cell consists of a 2-byte pointer, a header which is as much as | 2582 ** So a cell consists of a 2-byte pointer, a header which is as much as |
2409 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow | 2583 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow |
2410 ** page pointer. | 2584 ** page pointer. |
2411 */ | 2585 */ |
2412 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23); | 2586 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23); |
2413 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23); | 2587 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23); |
2414 pBt->maxLeaf = (u16)(pBt->usableSize - 35); | 2588 pBt->maxLeaf = (u16)(pBt->usableSize - 35); |
2415 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23); | 2589 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23); |
| 2590 if( pBt->maxLocal>127 ){ |
| 2591 pBt->max1bytePayload = 127; |
| 2592 }else{ |
| 2593 pBt->max1bytePayload = (u8)pBt->maxLocal; |
| 2594 } |
2416 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) ); | 2595 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) ); |
2417 pBt->pPage1 = pPage1; | 2596 pBt->pPage1 = pPage1; |
2418 pBt->nPage = nPage; | 2597 pBt->nPage = nPage; |
2419 return SQLITE_OK; | 2598 return SQLITE_OK; |
2420 | 2599 |
2421 page1_init_failed: | 2600 page1_init_failed: |
2422 releasePage(pPage1); | 2601 releasePage(pPage1); |
2423 pBt->pPage1 = 0; | 2602 pBt->pPage1 = 0; |
2424 return rc; | 2603 return rc; |
2425 } | 2604 } |
2426 | 2605 |
| 2606 #ifndef NDEBUG |
| 2607 /* |
| 2608 ** Return the number of cursors open on pBt. This is for use |
| 2609 ** in assert() expressions, so it is only compiled if NDEBUG is not |
| 2610 ** defined. |
| 2611 ** |
| 2612 ** Only write cursors are counted if wrOnly is true. If wrOnly is |
| 2613 ** false then all cursors are counted. |
| 2614 ** |
| 2615 ** For the purposes of this routine, a cursor is any cursor that |
| 2616 ** is capable of reading or writing to the database. Cursors that |
| 2617 ** have been tripped into the CURSOR_FAULT state are not counted. |
| 2618 */ |
| 2619 static int countValidCursors(BtShared *pBt, int wrOnly){ |
| 2620 BtCursor *pCur; |
| 2621 int r = 0; |
| 2622 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){ |
| 2623 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0) |
| 2624 && pCur->eState!=CURSOR_FAULT ) r++; |
| 2625 } |
| 2626 return r; |
| 2627 } |
| 2628 #endif |
| 2629 |
2427 /* | 2630 /* |
2428 ** If there are no outstanding cursors and we are not in the middle | 2631 ** If there are no outstanding cursors and we are not in the middle |
2429 ** of a transaction but there is a read lock on the database, then | 2632 ** of a transaction but there is a read lock on the database, then |
2430 ** this routine unrefs the first page of the database file which | 2633 ** this routine unrefs the first page of the database file which |
2431 ** has the effect of releasing the read lock. | 2634 ** has the effect of releasing the read lock. |
2432 ** | 2635 ** |
2433 ** If there is a transaction in progress, this routine is a no-op. | 2636 ** If there is a transaction in progress, this routine is a no-op. |
2434 */ | 2637 */ |
2435 static void unlockBtreeIfUnused(BtShared *pBt){ | 2638 static void unlockBtreeIfUnused(BtShared *pBt){ |
2436 assert( sqlite3_mutex_held(pBt->mutex) ); | 2639 assert( sqlite3_mutex_held(pBt->mutex) ); |
2437 assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE ); | 2640 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE ); |
2438 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){ | 2641 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){ |
2439 assert( pBt->pPage1->aData ); | 2642 MemPage *pPage1 = pBt->pPage1; |
| 2643 assert( pPage1->aData ); |
2440 assert( sqlite3PagerRefcount(pBt->pPager)==1 ); | 2644 assert( sqlite3PagerRefcount(pBt->pPager)==1 ); |
2441 assert( pBt->pPage1->aData ); | |
2442 releasePage(pBt->pPage1); | |
2443 pBt->pPage1 = 0; | 2645 pBt->pPage1 = 0; |
| 2646 releasePage(pPage1); |
2444 } | 2647 } |
2445 } | 2648 } |
2446 | 2649 |
2447 /* | 2650 /* |
2448 ** If pBt points to an empty file then convert that empty file | 2651 ** If pBt points to an empty file then convert that empty file |
2449 ** into a new empty database by initializing the first page of | 2652 ** into a new empty database by initializing the first page of |
2450 ** the database. | 2653 ** the database. |
2451 */ | 2654 */ |
2452 static int newDatabase(BtShared *pBt){ | 2655 static int newDatabase(BtShared *pBt){ |
2453 MemPage *pP1; | 2656 MemPage *pP1; |
(...skipping 15 matching lines...) Expand all Loading... |
2469 data[17] = (u8)((pBt->pageSize>>16)&0xff); | 2672 data[17] = (u8)((pBt->pageSize>>16)&0xff); |
2470 data[18] = 1; | 2673 data[18] = 1; |
2471 data[19] = 1; | 2674 data[19] = 1; |
2472 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize); | 2675 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize); |
2473 data[20] = (u8)(pBt->pageSize - pBt->usableSize); | 2676 data[20] = (u8)(pBt->pageSize - pBt->usableSize); |
2474 data[21] = 64; | 2677 data[21] = 64; |
2475 data[22] = 32; | 2678 data[22] = 32; |
2476 data[23] = 32; | 2679 data[23] = 32; |
2477 memset(&data[24], 0, 100-24); | 2680 memset(&data[24], 0, 100-24); |
2478 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA ); | 2681 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA ); |
2479 pBt->pageSizeFixed = 1; | 2682 pBt->btsFlags |= BTS_PAGESIZE_FIXED; |
2480 #ifndef SQLITE_OMIT_AUTOVACUUM | 2683 #ifndef SQLITE_OMIT_AUTOVACUUM |
2481 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 ); | 2684 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 ); |
2482 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 ); | 2685 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 ); |
2483 put4byte(&data[36 + 4*4], pBt->autoVacuum); | 2686 put4byte(&data[36 + 4*4], pBt->autoVacuum); |
2484 put4byte(&data[36 + 7*4], pBt->incrVacuum); | 2687 put4byte(&data[36 + 7*4], pBt->incrVacuum); |
2485 #endif | 2688 #endif |
2486 pBt->nPage = 1; | 2689 pBt->nPage = 1; |
2487 data[31] = 1; | 2690 data[31] = 1; |
2488 return SQLITE_OK; | 2691 return SQLITE_OK; |
2489 } | 2692 } |
2490 | 2693 |
2491 /* | 2694 /* |
| 2695 ** Initialize the first page of the database file (creating a database |
| 2696 ** consisting of a single page and no schema objects). Return SQLITE_OK |
| 2697 ** if successful, or an SQLite error code otherwise. |
| 2698 */ |
| 2699 int sqlite3BtreeNewDb(Btree *p){ |
| 2700 int rc; |
| 2701 sqlite3BtreeEnter(p); |
| 2702 p->pBt->nPage = 0; |
| 2703 rc = newDatabase(p->pBt); |
| 2704 sqlite3BtreeLeave(p); |
| 2705 return rc; |
| 2706 } |
| 2707 |
| 2708 /* |
2492 ** Attempt to start a new transaction. A write-transaction | 2709 ** Attempt to start a new transaction. A write-transaction |
2493 ** is started if the second argument is nonzero, otherwise a read- | 2710 ** is started if the second argument is nonzero, otherwise a read- |
2494 ** transaction. If the second argument is 2 or more and exclusive | 2711 ** transaction. If the second argument is 2 or more and exclusive |
2495 ** transaction is started, meaning that no other process is allowed | 2712 ** transaction is started, meaning that no other process is allowed |
2496 ** to access the database. A preexisting transaction may not be | 2713 ** to access the database. A preexisting transaction may not be |
2497 ** upgraded to exclusive by calling this routine a second time - the | 2714 ** upgraded to exclusive by calling this routine a second time - the |
2498 ** exclusivity flag only works for a new transaction. | 2715 ** exclusivity flag only works for a new transaction. |
2499 ** | 2716 ** |
2500 ** A write-transaction must be started before attempting any | 2717 ** A write-transaction must be started before attempting any |
2501 ** changes to the database. None of the following routines | 2718 ** changes to the database. None of the following routines |
(...skipping 29 matching lines...) Expand all Loading... |
2531 sqlite3BtreeEnter(p); | 2748 sqlite3BtreeEnter(p); |
2532 btreeIntegrity(p); | 2749 btreeIntegrity(p); |
2533 | 2750 |
2534 /* If the btree is already in a write-transaction, or it | 2751 /* If the btree is already in a write-transaction, or it |
2535 ** is already in a read-transaction and a read-transaction | 2752 ** is already in a read-transaction and a read-transaction |
2536 ** is requested, this is a no-op. | 2753 ** is requested, this is a no-op. |
2537 */ | 2754 */ |
2538 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){ | 2755 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){ |
2539 goto trans_begun; | 2756 goto trans_begun; |
2540 } | 2757 } |
| 2758 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 ); |
2541 | 2759 |
2542 /* Write transactions are not possible on a read-only database */ | 2760 /* Write transactions are not possible on a read-only database */ |
2543 if( pBt->readOnly && wrflag ){ | 2761 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){ |
2544 rc = SQLITE_READONLY; | 2762 rc = SQLITE_READONLY; |
2545 goto trans_begun; | 2763 goto trans_begun; |
2546 } | 2764 } |
2547 | 2765 |
2548 #ifndef SQLITE_OMIT_SHARED_CACHE | 2766 #ifndef SQLITE_OMIT_SHARED_CACHE |
2549 /* If another database handle has already opened a write transaction | 2767 /* If another database handle has already opened a write transaction |
2550 ** on this shared-btree structure and a second write transaction is | 2768 ** on this shared-btree structure and a second write transaction is |
2551 ** requested, return SQLITE_LOCKED. | 2769 ** requested, return SQLITE_LOCKED. |
2552 */ | 2770 */ |
2553 if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){ | 2771 if( (wrflag && pBt->inTransaction==TRANS_WRITE) |
| 2772 || (pBt->btsFlags & BTS_PENDING)!=0 |
| 2773 ){ |
2554 pBlock = pBt->pWriter->db; | 2774 pBlock = pBt->pWriter->db; |
2555 }else if( wrflag>1 ){ | 2775 }else if( wrflag>1 ){ |
2556 BtLock *pIter; | 2776 BtLock *pIter; |
2557 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ | 2777 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ |
2558 if( pIter->pBtree!=p ){ | 2778 if( pIter->pBtree!=p ){ |
2559 pBlock = pIter->pBtree->db; | 2779 pBlock = pIter->pBtree->db; |
2560 break; | 2780 break; |
2561 } | 2781 } |
2562 } | 2782 } |
2563 } | 2783 } |
2564 if( pBlock ){ | 2784 if( pBlock ){ |
2565 sqlite3ConnectionBlocked(p->db, pBlock); | 2785 sqlite3ConnectionBlocked(p->db, pBlock); |
2566 rc = SQLITE_LOCKED_SHAREDCACHE; | 2786 rc = SQLITE_LOCKED_SHAREDCACHE; |
2567 goto trans_begun; | 2787 goto trans_begun; |
2568 } | 2788 } |
2569 #endif | 2789 #endif |
2570 | 2790 |
2571 /* Any read-only or read-write transaction implies a read-lock on | 2791 /* Any read-only or read-write transaction implies a read-lock on |
2572 ** page 1. So if some other shared-cache client already has a write-lock | 2792 ** page 1. So if some other shared-cache client already has a write-lock |
2573 ** on page 1, the transaction cannot be opened. */ | 2793 ** on page 1, the transaction cannot be opened. */ |
2574 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK); | 2794 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK); |
2575 if( SQLITE_OK!=rc ) goto trans_begun; | 2795 if( SQLITE_OK!=rc ) goto trans_begun; |
2576 | 2796 |
2577 pBt->initiallyEmpty = (u8)(pBt->nPage==0); | 2797 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY; |
| 2798 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY; |
2578 do { | 2799 do { |
2579 /* Call lockBtree() until either pBt->pPage1 is populated or | 2800 /* Call lockBtree() until either pBt->pPage1 is populated or |
2580 ** lockBtree() returns something other than SQLITE_OK. lockBtree() | 2801 ** lockBtree() returns something other than SQLITE_OK. lockBtree() |
2581 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after | 2802 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after |
2582 ** reading page 1 it discovers that the page-size of the database | 2803 ** reading page 1 it discovers that the page-size of the database |
2583 ** file is not pBt->pageSize. In this case lockBtree() will update | 2804 ** file is not pBt->pageSize. In this case lockBtree() will update |
2584 ** pBt->pageSize to the page-size of the file on disk. | 2805 ** pBt->pageSize to the page-size of the file on disk. |
2585 */ | 2806 */ |
2586 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) ); | 2807 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) ); |
2587 | 2808 |
2588 if( rc==SQLITE_OK && wrflag ){ | 2809 if( rc==SQLITE_OK && wrflag ){ |
2589 if( pBt->readOnly ){ | 2810 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){ |
2590 rc = SQLITE_READONLY; | 2811 rc = SQLITE_READONLY; |
2591 }else{ | 2812 }else{ |
2592 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db)); | 2813 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db)); |
2593 if( rc==SQLITE_OK ){ | 2814 if( rc==SQLITE_OK ){ |
2594 rc = newDatabase(pBt); | 2815 rc = newDatabase(pBt); |
2595 } | 2816 } |
2596 } | 2817 } |
2597 } | 2818 } |
2598 | 2819 |
2599 if( rc!=SQLITE_OK ){ | 2820 if( rc!=SQLITE_OK ){ |
2600 unlockBtreeIfUnused(pBt); | 2821 unlockBtreeIfUnused(pBt); |
2601 } | 2822 } |
2602 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE && | 2823 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE && |
2603 btreeInvokeBusyHandler(pBt) ); | 2824 btreeInvokeBusyHandler(pBt) ); |
2604 | 2825 |
2605 if( rc==SQLITE_OK ){ | 2826 if( rc==SQLITE_OK ){ |
2606 if( p->inTrans==TRANS_NONE ){ | 2827 if( p->inTrans==TRANS_NONE ){ |
2607 pBt->nTransaction++; | 2828 pBt->nTransaction++; |
2608 #ifndef SQLITE_OMIT_SHARED_CACHE | 2829 #ifndef SQLITE_OMIT_SHARED_CACHE |
2609 if( p->sharable ){ | 2830 if( p->sharable ){ |
2610 » assert( p->lock.pBtree==p && p->lock.iTable==1 ); | 2831 assert( p->lock.pBtree==p && p->lock.iTable==1 ); |
2611 p->lock.eLock = READ_LOCK; | 2832 p->lock.eLock = READ_LOCK; |
2612 p->lock.pNext = pBt->pLock; | 2833 p->lock.pNext = pBt->pLock; |
2613 pBt->pLock = &p->lock; | 2834 pBt->pLock = &p->lock; |
2614 } | 2835 } |
2615 #endif | 2836 #endif |
2616 } | 2837 } |
2617 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ); | 2838 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ); |
2618 if( p->inTrans>pBt->inTransaction ){ | 2839 if( p->inTrans>pBt->inTransaction ){ |
2619 pBt->inTransaction = p->inTrans; | 2840 pBt->inTransaction = p->inTrans; |
2620 } | 2841 } |
2621 if( wrflag ){ | 2842 if( wrflag ){ |
2622 MemPage *pPage1 = pBt->pPage1; | 2843 MemPage *pPage1 = pBt->pPage1; |
2623 #ifndef SQLITE_OMIT_SHARED_CACHE | 2844 #ifndef SQLITE_OMIT_SHARED_CACHE |
2624 assert( !pBt->pWriter ); | 2845 assert( !pBt->pWriter ); |
2625 pBt->pWriter = p; | 2846 pBt->pWriter = p; |
2626 pBt->isExclusive = (u8)(wrflag>1); | 2847 pBt->btsFlags &= ~BTS_EXCLUSIVE; |
| 2848 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE; |
2627 #endif | 2849 #endif |
2628 | 2850 |
2629 /* If the db-size header field is incorrect (as it may be if an old | 2851 /* If the db-size header field is incorrect (as it may be if an old |
2630 ** client has been writing the database file), update it now. Doing | 2852 ** client has been writing the database file), update it now. Doing |
2631 ** this sooner rather than later means the database size can safely | 2853 ** this sooner rather than later means the database size can safely |
2632 ** re-read the database size from page 1 if a savepoint or transaction | 2854 ** re-read the database size from page 1 if a savepoint or transaction |
2633 ** rollback occurs within the transaction. | 2855 ** rollback occurs within the transaction. |
2634 */ | 2856 */ |
2635 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){ | 2857 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){ |
2636 rc = sqlite3PagerWrite(pPage1->pDbPage); | 2858 rc = sqlite3PagerWrite(pPage1->pDbPage); |
(...skipping 91 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
2728 int nCell; | 2950 int nCell; |
2729 | 2951 |
2730 btreeInitPage(pPage); | 2952 btreeInitPage(pPage); |
2731 nCell = pPage->nCell; | 2953 nCell = pPage->nCell; |
2732 | 2954 |
2733 for(i=0; i<nCell; i++){ | 2955 for(i=0; i<nCell; i++){ |
2734 u8 *pCell = findCell(pPage, i); | 2956 u8 *pCell = findCell(pPage, i); |
2735 if( eType==PTRMAP_OVERFLOW1 ){ | 2957 if( eType==PTRMAP_OVERFLOW1 ){ |
2736 CellInfo info; | 2958 CellInfo info; |
2737 btreeParseCellPtr(pPage, pCell, &info); | 2959 btreeParseCellPtr(pPage, pCell, &info); |
2738 if( info.iOverflow ){ | 2960 if( info.iOverflow |
2739 if( iFrom==get4byte(&pCell[info.iOverflow]) ){ | 2961 && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage |
2740 put4byte(&pCell[info.iOverflow], iTo); | 2962 && iFrom==get4byte(&pCell[info.iOverflow]) |
2741 break; | 2963 ){ |
2742 } | 2964 put4byte(&pCell[info.iOverflow], iTo); |
| 2965 break; |
2743 } | 2966 } |
2744 }else{ | 2967 }else{ |
2745 if( get4byte(pCell)==iFrom ){ | 2968 if( get4byte(pCell)==iFrom ){ |
2746 put4byte(pCell, iTo); | 2969 put4byte(pCell, iTo); |
2747 break; | 2970 break; |
2748 } | 2971 } |
2749 } | 2972 } |
2750 } | 2973 } |
2751 | 2974 |
2752 if( i==nCell ){ | 2975 if( i==nCell ){ |
(...skipping 89 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
2842 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc); | 3065 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc); |
2843 } | 3066 } |
2844 } | 3067 } |
2845 return rc; | 3068 return rc; |
2846 } | 3069 } |
2847 | 3070 |
2848 /* Forward declaration required by incrVacuumStep(). */ | 3071 /* Forward declaration required by incrVacuumStep(). */ |
2849 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8); | 3072 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8); |
2850 | 3073 |
2851 /* | 3074 /* |
2852 ** Perform a single step of an incremental-vacuum. If successful, | 3075 ** Perform a single step of an incremental-vacuum. If successful, return |
2853 ** return SQLITE_OK. If there is no work to do (and therefore no | 3076 ** SQLITE_OK. If there is no work to do (and therefore no point in |
2854 ** point in calling this function again), return SQLITE_DONE. | 3077 ** calling this function again), return SQLITE_DONE. Or, if an error |
| 3078 ** occurs, return some other error code. |
2855 ** | 3079 ** |
2856 ** More specificly, this function attempts to re-organize the | 3080 ** More specifically, this function attempts to re-organize the database so |
2857 ** database so that the last page of the file currently in use | 3081 ** that the last page of the file currently in use is no longer in use. |
2858 ** is no longer in use. | |
2859 ** | 3082 ** |
2860 ** If the nFin parameter is non-zero, this function assumes | 3083 ** Parameter nFin is the number of pages that this database would contain |
2861 ** that the caller will keep calling incrVacuumStep() until | 3084 ** were this function called until it returns SQLITE_DONE. |
2862 ** it returns SQLITE_DONE or an error, and that nFin is the | 3085 ** |
2863 ** number of pages the database file will contain after this | 3086 ** If the bCommit parameter is non-zero, this function assumes that the |
2864 ** process is complete. If nFin is zero, it is assumed that | 3087 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE |
2865 ** incrVacuumStep() will be called a finite amount of times | 3088 ** or an error. bCommit is passed true for an auto-vacuum-on-commit |
2866 ** which may or may not empty the freelist. A full autovacuum | 3089 ** operation, or false for an incremental vacuum. |
2867 ** has nFin>0. A "PRAGMA incremental_vacuum" has nFin==0. | |
2868 */ | 3090 */ |
2869 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){ | 3091 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){ |
2870 Pgno nFreeList; /* Number of pages still on the free-list */ | 3092 Pgno nFreeList; /* Number of pages still on the free-list */ |
2871 int rc; | 3093 int rc; |
2872 | 3094 |
2873 assert( sqlite3_mutex_held(pBt->mutex) ); | 3095 assert( sqlite3_mutex_held(pBt->mutex) ); |
2874 assert( iLastPg>nFin ); | 3096 assert( iLastPg>nFin ); |
2875 | 3097 |
2876 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){ | 3098 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){ |
2877 u8 eType; | 3099 u8 eType; |
2878 Pgno iPtrPage; | 3100 Pgno iPtrPage; |
2879 | 3101 |
2880 nFreeList = get4byte(&pBt->pPage1->aData[36]); | 3102 nFreeList = get4byte(&pBt->pPage1->aData[36]); |
2881 if( nFreeList==0 ){ | 3103 if( nFreeList==0 ){ |
2882 return SQLITE_DONE; | 3104 return SQLITE_DONE; |
2883 } | 3105 } |
2884 | 3106 |
2885 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage); | 3107 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage); |
2886 if( rc!=SQLITE_OK ){ | 3108 if( rc!=SQLITE_OK ){ |
2887 return rc; | 3109 return rc; |
2888 } | 3110 } |
2889 if( eType==PTRMAP_ROOTPAGE ){ | 3111 if( eType==PTRMAP_ROOTPAGE ){ |
2890 return SQLITE_CORRUPT_BKPT; | 3112 return SQLITE_CORRUPT_BKPT; |
2891 } | 3113 } |
2892 | 3114 |
2893 if( eType==PTRMAP_FREEPAGE ){ | 3115 if( eType==PTRMAP_FREEPAGE ){ |
2894 if( nFin==0 ){ | 3116 if( bCommit==0 ){ |
2895 /* Remove the page from the files free-list. This is not required | 3117 /* Remove the page from the files free-list. This is not required |
2896 ** if nFin is non-zero. In that case, the free-list will be | 3118 ** if bCommit is non-zero. In that case, the free-list will be |
2897 ** truncated to zero after this function returns, so it doesn't | 3119 ** truncated to zero after this function returns, so it doesn't |
2898 ** matter if it still contains some garbage entries. | 3120 ** matter if it still contains some garbage entries. |
2899 */ | 3121 */ |
2900 Pgno iFreePg; | 3122 Pgno iFreePg; |
2901 MemPage *pFreePg; | 3123 MemPage *pFreePg; |
2902 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1); | 3124 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT); |
2903 if( rc!=SQLITE_OK ){ | 3125 if( rc!=SQLITE_OK ){ |
2904 return rc; | 3126 return rc; |
2905 } | 3127 } |
2906 assert( iFreePg==iLastPg ); | 3128 assert( iFreePg==iLastPg ); |
2907 releasePage(pFreePg); | 3129 releasePage(pFreePg); |
2908 } | 3130 } |
2909 } else { | 3131 } else { |
2910 Pgno iFreePg; /* Index of free page to move pLastPg to */ | 3132 Pgno iFreePg; /* Index of free page to move pLastPg to */ |
2911 MemPage *pLastPg; | 3133 MemPage *pLastPg; |
| 3134 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */ |
| 3135 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */ |
2912 | 3136 |
2913 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0); | 3137 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0); |
2914 if( rc!=SQLITE_OK ){ | 3138 if( rc!=SQLITE_OK ){ |
2915 return rc; | 3139 return rc; |
2916 } | 3140 } |
2917 | 3141 |
2918 /* If nFin is zero, this loop runs exactly once and page pLastPg | 3142 /* If bCommit is zero, this loop runs exactly once and page pLastPg |
2919 ** is swapped with the first free page pulled off the free list. | 3143 ** is swapped with the first free page pulled off the free list. |
2920 ** | 3144 ** |
2921 ** On the other hand, if nFin is greater than zero, then keep | 3145 ** On the other hand, if bCommit is greater than zero, then keep |
2922 ** looping until a free-page located within the first nFin pages | 3146 ** looping until a free-page located within the first nFin pages |
2923 ** of the file is found. | 3147 ** of the file is found. |
2924 */ | 3148 */ |
| 3149 if( bCommit==0 ){ |
| 3150 eMode = BTALLOC_LE; |
| 3151 iNear = nFin; |
| 3152 } |
2925 do { | 3153 do { |
2926 MemPage *pFreePg; | 3154 MemPage *pFreePg; |
2927 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0); | 3155 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode); |
2928 if( rc!=SQLITE_OK ){ | 3156 if( rc!=SQLITE_OK ){ |
2929 releasePage(pLastPg); | 3157 releasePage(pLastPg); |
2930 return rc; | 3158 return rc; |
2931 } | 3159 } |
2932 releasePage(pFreePg); | 3160 releasePage(pFreePg); |
2933 }while( nFin!=0 && iFreePg>nFin ); | 3161 }while( bCommit && iFreePg>nFin ); |
2934 assert( iFreePg<iLastPg ); | 3162 assert( iFreePg<iLastPg ); |
2935 | 3163 |
2936 rc = sqlite3PagerWrite(pLastPg->pDbPage); | 3164 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit); |
2937 if( rc==SQLITE_OK ){ | |
2938 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0); | |
2939 } | |
2940 releasePage(pLastPg); | 3165 releasePage(pLastPg); |
2941 if( rc!=SQLITE_OK ){ | 3166 if( rc!=SQLITE_OK ){ |
2942 return rc; | 3167 return rc; |
2943 } | 3168 } |
2944 } | 3169 } |
2945 } | 3170 } |
2946 | 3171 |
2947 if( nFin==0 ){ | 3172 if( bCommit==0 ){ |
2948 iLastPg--; | 3173 do { |
2949 while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){ | |
2950 if( PTRMAP_ISPAGE(pBt, iLastPg) ){ | |
2951 MemPage *pPg; | |
2952 rc = btreeGetPage(pBt, iLastPg, &pPg, 0); | |
2953 if( rc!=SQLITE_OK ){ | |
2954 return rc; | |
2955 } | |
2956 rc = sqlite3PagerWrite(pPg->pDbPage); | |
2957 releasePage(pPg); | |
2958 if( rc!=SQLITE_OK ){ | |
2959 return rc; | |
2960 } | |
2961 } | |
2962 iLastPg--; | 3174 iLastPg--; |
2963 } | 3175 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) ); |
2964 sqlite3PagerTruncateImage(pBt->pPager, iLastPg); | 3176 pBt->bDoTruncate = 1; |
2965 pBt->nPage = iLastPg; | 3177 pBt->nPage = iLastPg; |
2966 } | 3178 } |
2967 return SQLITE_OK; | 3179 return SQLITE_OK; |
2968 } | 3180 } |
2969 | 3181 |
2970 /* | 3182 /* |
| 3183 ** The database opened by the first argument is an auto-vacuum database |
| 3184 ** nOrig pages in size containing nFree free pages. Return the expected |
| 3185 ** size of the database in pages following an auto-vacuum operation. |
| 3186 */ |
| 3187 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){ |
| 3188 int nEntry; /* Number of entries on one ptrmap page */ |
| 3189 Pgno nPtrmap; /* Number of PtrMap pages to be freed */ |
| 3190 Pgno nFin; /* Return value */ |
| 3191 |
| 3192 nEntry = pBt->usableSize/5; |
| 3193 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry; |
| 3194 nFin = nOrig - nFree - nPtrmap; |
| 3195 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){ |
| 3196 nFin--; |
| 3197 } |
| 3198 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){ |
| 3199 nFin--; |
| 3200 } |
| 3201 |
| 3202 return nFin; |
| 3203 } |
| 3204 |
| 3205 /* |
2971 ** A write-transaction must be opened before calling this function. | 3206 ** A write-transaction must be opened before calling this function. |
2972 ** It performs a single unit of work towards an incremental vacuum. | 3207 ** It performs a single unit of work towards an incremental vacuum. |
2973 ** | 3208 ** |
2974 ** If the incremental vacuum is finished after this function has run, | 3209 ** If the incremental vacuum is finished after this function has run, |
2975 ** SQLITE_DONE is returned. If it is not finished, but no error occurred, | 3210 ** SQLITE_DONE is returned. If it is not finished, but no error occurred, |
2976 ** SQLITE_OK is returned. Otherwise an SQLite error code. | 3211 ** SQLITE_OK is returned. Otherwise an SQLite error code. |
2977 */ | 3212 */ |
2978 int sqlite3BtreeIncrVacuum(Btree *p){ | 3213 int sqlite3BtreeIncrVacuum(Btree *p){ |
2979 int rc; | 3214 int rc; |
2980 BtShared *pBt = p->pBt; | 3215 BtShared *pBt = p->pBt; |
2981 | 3216 |
2982 sqlite3BtreeEnter(p); | 3217 sqlite3BtreeEnter(p); |
2983 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE ); | 3218 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE ); |
2984 if( !pBt->autoVacuum ){ | 3219 if( !pBt->autoVacuum ){ |
2985 rc = SQLITE_DONE; | 3220 rc = SQLITE_DONE; |
2986 }else{ | 3221 }else{ |
2987 invalidateAllOverflowCache(pBt); | 3222 Pgno nOrig = btreePagecount(pBt); |
2988 rc = incrVacuumStep(pBt, 0, btreePagecount(pBt)); | 3223 Pgno nFree = get4byte(&pBt->pPage1->aData[36]); |
2989 if( rc==SQLITE_OK ){ | 3224 Pgno nFin = finalDbSize(pBt, nOrig, nFree); |
2990 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); | 3225 |
2991 put4byte(&pBt->pPage1->aData[28], pBt->nPage); | 3226 if( nOrig<nFin ){ |
| 3227 rc = SQLITE_CORRUPT_BKPT; |
| 3228 }else if( nFree>0 ){ |
| 3229 rc = saveAllCursors(pBt, 0, 0); |
| 3230 if( rc==SQLITE_OK ){ |
| 3231 invalidateAllOverflowCache(pBt); |
| 3232 rc = incrVacuumStep(pBt, nFin, nOrig, 0); |
| 3233 } |
| 3234 if( rc==SQLITE_OK ){ |
| 3235 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); |
| 3236 put4byte(&pBt->pPage1->aData[28], pBt->nPage); |
| 3237 } |
| 3238 }else{ |
| 3239 rc = SQLITE_DONE; |
2992 } | 3240 } |
2993 } | 3241 } |
2994 sqlite3BtreeLeave(p); | 3242 sqlite3BtreeLeave(p); |
2995 return rc; | 3243 return rc; |
2996 } | 3244 } |
2997 | 3245 |
2998 /* | 3246 /* |
2999 ** This routine is called prior to sqlite3PagerCommit when a transaction | 3247 ** This routine is called prior to sqlite3PagerCommit when a transaction |
3000 ** is commited for an auto-vacuum database. | 3248 ** is committed for an auto-vacuum database. |
3001 ** | 3249 ** |
3002 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages | 3250 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages |
3003 ** the database file should be truncated to during the commit process. | 3251 ** the database file should be truncated to during the commit process. |
3004 ** i.e. the database has been reorganized so that only the first *pnTrunc | 3252 ** i.e. the database has been reorganized so that only the first *pnTrunc |
3005 ** pages are in use. | 3253 ** pages are in use. |
3006 */ | 3254 */ |
3007 static int autoVacuumCommit(BtShared *pBt){ | 3255 static int autoVacuumCommit(BtShared *pBt){ |
3008 int rc = SQLITE_OK; | 3256 int rc = SQLITE_OK; |
3009 Pager *pPager = pBt->pPager; | 3257 Pager *pPager = pBt->pPager; |
3010 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) ); | 3258 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) ); |
3011 | 3259 |
3012 assert( sqlite3_mutex_held(pBt->mutex) ); | 3260 assert( sqlite3_mutex_held(pBt->mutex) ); |
3013 invalidateAllOverflowCache(pBt); | 3261 invalidateAllOverflowCache(pBt); |
3014 assert(pBt->autoVacuum); | 3262 assert(pBt->autoVacuum); |
3015 if( !pBt->incrVacuum ){ | 3263 if( !pBt->incrVacuum ){ |
3016 Pgno nFin; /* Number of pages in database after autovacuuming */ | 3264 Pgno nFin; /* Number of pages in database after autovacuuming */ |
3017 Pgno nFree; /* Number of pages on the freelist initially */ | 3265 Pgno nFree; /* Number of pages on the freelist initially */ |
3018 Pgno nPtrmap; /* Number of PtrMap pages to be freed */ | |
3019 Pgno iFree; /* The next page to be freed */ | 3266 Pgno iFree; /* The next page to be freed */ |
3020 int nEntry; /* Number of entries on one ptrmap page */ | |
3021 Pgno nOrig; /* Database size before freeing */ | 3267 Pgno nOrig; /* Database size before freeing */ |
3022 | 3268 |
3023 nOrig = btreePagecount(pBt); | 3269 nOrig = btreePagecount(pBt); |
3024 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){ | 3270 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){ |
3025 /* It is not possible to create a database for which the final page | 3271 /* It is not possible to create a database for which the final page |
3026 ** is either a pointer-map page or the pending-byte page. If one | 3272 ** is either a pointer-map page or the pending-byte page. If one |
3027 ** is encountered, this indicates corruption. | 3273 ** is encountered, this indicates corruption. |
3028 */ | 3274 */ |
3029 return SQLITE_CORRUPT_BKPT; | 3275 return SQLITE_CORRUPT_BKPT; |
3030 } | 3276 } |
3031 | 3277 |
3032 nFree = get4byte(&pBt->pPage1->aData[36]); | 3278 nFree = get4byte(&pBt->pPage1->aData[36]); |
3033 nEntry = pBt->usableSize/5; | 3279 nFin = finalDbSize(pBt, nOrig, nFree); |
3034 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry; | 3280 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT; |
3035 nFin = nOrig - nFree - nPtrmap; | 3281 if( nFin<nOrig ){ |
3036 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){ | 3282 rc = saveAllCursors(pBt, 0, 0); |
3037 nFin--; | |
3038 } | 3283 } |
3039 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){ | |
3040 nFin--; | |
3041 } | |
3042 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT; | |
3043 | |
3044 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){ | 3284 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){ |
3045 rc = incrVacuumStep(pBt, nFin, iFree); | 3285 rc = incrVacuumStep(pBt, nFin, iFree, 1); |
3046 } | 3286 } |
3047 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){ | 3287 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){ |
3048 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); | 3288 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); |
3049 put4byte(&pBt->pPage1->aData[32], 0); | 3289 put4byte(&pBt->pPage1->aData[32], 0); |
3050 put4byte(&pBt->pPage1->aData[36], 0); | 3290 put4byte(&pBt->pPage1->aData[36], 0); |
3051 put4byte(&pBt->pPage1->aData[28], nFin); | 3291 put4byte(&pBt->pPage1->aData[28], nFin); |
3052 sqlite3PagerTruncateImage(pBt->pPager, nFin); | 3292 pBt->bDoTruncate = 1; |
3053 pBt->nPage = nFin; | 3293 pBt->nPage = nFin; |
3054 } | 3294 } |
3055 if( rc!=SQLITE_OK ){ | 3295 if( rc!=SQLITE_OK ){ |
3056 sqlite3PagerRollback(pPager); | 3296 sqlite3PagerRollback(pPager); |
3057 } | 3297 } |
3058 } | 3298 } |
3059 | 3299 |
3060 assert( nRef==sqlite3PagerRefcount(pPager) ); | 3300 assert( nRef>=sqlite3PagerRefcount(pPager) ); |
3061 return rc; | 3301 return rc; |
3062 } | 3302 } |
3063 | 3303 |
3064 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */ | 3304 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */ |
3065 # define setChildPtrmaps(x) SQLITE_OK | 3305 # define setChildPtrmaps(x) SQLITE_OK |
3066 #endif | 3306 #endif |
3067 | 3307 |
3068 /* | 3308 /* |
3069 ** This routine does the first phase of a two-phase commit. This routine | 3309 ** This routine does the first phase of a two-phase commit. This routine |
3070 ** causes a rollback journal to be created (if it does not already exist) | 3310 ** causes a rollback journal to be created (if it does not already exist) |
(...skipping 26 matching lines...) Expand all Loading... |
3097 BtShared *pBt = p->pBt; | 3337 BtShared *pBt = p->pBt; |
3098 sqlite3BtreeEnter(p); | 3338 sqlite3BtreeEnter(p); |
3099 #ifndef SQLITE_OMIT_AUTOVACUUM | 3339 #ifndef SQLITE_OMIT_AUTOVACUUM |
3100 if( pBt->autoVacuum ){ | 3340 if( pBt->autoVacuum ){ |
3101 rc = autoVacuumCommit(pBt); | 3341 rc = autoVacuumCommit(pBt); |
3102 if( rc!=SQLITE_OK ){ | 3342 if( rc!=SQLITE_OK ){ |
3103 sqlite3BtreeLeave(p); | 3343 sqlite3BtreeLeave(p); |
3104 return rc; | 3344 return rc; |
3105 } | 3345 } |
3106 } | 3346 } |
| 3347 if( pBt->bDoTruncate ){ |
| 3348 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage); |
| 3349 } |
3107 #endif | 3350 #endif |
3108 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0); | 3351 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0); |
3109 sqlite3BtreeLeave(p); | 3352 sqlite3BtreeLeave(p); |
3110 } | 3353 } |
3111 return rc; | 3354 return rc; |
3112 } | 3355 } |
3113 | 3356 |
3114 /* | 3357 /* |
3115 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback() | 3358 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback() |
3116 ** at the conclusion of a transaction. | 3359 ** at the conclusion of a transaction. |
3117 */ | 3360 */ |
3118 static void btreeEndTransaction(Btree *p){ | 3361 static void btreeEndTransaction(Btree *p){ |
3119 BtShared *pBt = p->pBt; | 3362 BtShared *pBt = p->pBt; |
| 3363 sqlite3 *db = p->db; |
3120 assert( sqlite3BtreeHoldsMutex(p) ); | 3364 assert( sqlite3BtreeHoldsMutex(p) ); |
3121 | 3365 |
3122 btreeClearHasContent(pBt); | 3366 #ifndef SQLITE_OMIT_AUTOVACUUM |
3123 if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){ | 3367 pBt->bDoTruncate = 0; |
| 3368 #endif |
| 3369 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){ |
3124 /* If there are other active statements that belong to this database | 3370 /* If there are other active statements that belong to this database |
3125 ** handle, downgrade to a read-only transaction. The other statements | 3371 ** handle, downgrade to a read-only transaction. The other statements |
3126 ** may still be reading from the database. */ | 3372 ** may still be reading from the database. */ |
3127 downgradeAllSharedCacheTableLocks(p); | 3373 downgradeAllSharedCacheTableLocks(p); |
3128 p->inTrans = TRANS_READ; | 3374 p->inTrans = TRANS_READ; |
3129 }else{ | 3375 }else{ |
3130 /* If the handle had any kind of transaction open, decrement the | 3376 /* If the handle had any kind of transaction open, decrement the |
3131 ** transaction count of the shared btree. If the transaction count | 3377 ** transaction count of the shared btree. If the transaction count |
3132 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused() | 3378 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused() |
3133 ** call below will unlock the pager. */ | 3379 ** call below will unlock the pager. */ |
(...skipping 53 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
3187 int rc; | 3433 int rc; |
3188 BtShared *pBt = p->pBt; | 3434 BtShared *pBt = p->pBt; |
3189 assert( pBt->inTransaction==TRANS_WRITE ); | 3435 assert( pBt->inTransaction==TRANS_WRITE ); |
3190 assert( pBt->nTransaction>0 ); | 3436 assert( pBt->nTransaction>0 ); |
3191 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager); | 3437 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager); |
3192 if( rc!=SQLITE_OK && bCleanup==0 ){ | 3438 if( rc!=SQLITE_OK && bCleanup==0 ){ |
3193 sqlite3BtreeLeave(p); | 3439 sqlite3BtreeLeave(p); |
3194 return rc; | 3440 return rc; |
3195 } | 3441 } |
3196 pBt->inTransaction = TRANS_READ; | 3442 pBt->inTransaction = TRANS_READ; |
| 3443 btreeClearHasContent(pBt); |
3197 } | 3444 } |
3198 | 3445 |
3199 btreeEndTransaction(p); | 3446 btreeEndTransaction(p); |
3200 sqlite3BtreeLeave(p); | 3447 sqlite3BtreeLeave(p); |
3201 return SQLITE_OK; | 3448 return SQLITE_OK; |
3202 } | 3449 } |
3203 | 3450 |
3204 /* | 3451 /* |
3205 ** Do both phases of a commit. | 3452 ** Do both phases of a commit. |
3206 */ | 3453 */ |
3207 int sqlite3BtreeCommit(Btree *p){ | 3454 int sqlite3BtreeCommit(Btree *p){ |
3208 int rc; | 3455 int rc; |
3209 sqlite3BtreeEnter(p); | 3456 sqlite3BtreeEnter(p); |
3210 rc = sqlite3BtreeCommitPhaseOne(p, 0); | 3457 rc = sqlite3BtreeCommitPhaseOne(p, 0); |
3211 if( rc==SQLITE_OK ){ | 3458 if( rc==SQLITE_OK ){ |
3212 rc = sqlite3BtreeCommitPhaseTwo(p, 0); | 3459 rc = sqlite3BtreeCommitPhaseTwo(p, 0); |
3213 } | 3460 } |
3214 sqlite3BtreeLeave(p); | 3461 sqlite3BtreeLeave(p); |
3215 return rc; | 3462 return rc; |
3216 } | 3463 } |
3217 | 3464 |
3218 #ifndef NDEBUG | |
3219 /* | |
3220 ** Return the number of write-cursors open on this handle. This is for use | |
3221 ** in assert() expressions, so it is only compiled if NDEBUG is not | |
3222 ** defined. | |
3223 ** | |
3224 ** For the purposes of this routine, a write-cursor is any cursor that | |
3225 ** is capable of writing to the databse. That means the cursor was | |
3226 ** originally opened for writing and the cursor has not be disabled | |
3227 ** by having its state changed to CURSOR_FAULT. | |
3228 */ | |
3229 static int countWriteCursors(BtShared *pBt){ | |
3230 BtCursor *pCur; | |
3231 int r = 0; | |
3232 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){ | |
3233 if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; | |
3234 } | |
3235 return r; | |
3236 } | |
3237 #endif | |
3238 | |
3239 /* | 3465 /* |
3240 ** This routine sets the state to CURSOR_FAULT and the error | 3466 ** This routine sets the state to CURSOR_FAULT and the error |
3241 ** code to errCode for every cursor on BtShared that pBtree | 3467 ** code to errCode for every cursor on any BtShared that pBtree |
3242 ** references. | 3468 ** references. Or if the writeOnly flag is set to 1, then only |
| 3469 ** trip write cursors and leave read cursors unchanged. |
3243 ** | 3470 ** |
3244 ** Every cursor is tripped, including cursors that belong | 3471 ** Every cursor is a candidate to be tripped, including cursors |
3245 ** to other database connections that happen to be sharing | 3472 ** that belong to other database connections that happen to be |
3246 ** the cache with pBtree. | 3473 ** sharing the cache with pBtree. |
3247 ** | 3474 ** |
3248 ** This routine gets called when a rollback occurs. | 3475 ** This routine gets called when a rollback occurs. If the writeOnly |
3249 ** All cursors using the same cache must be tripped | 3476 ** flag is true, then only write-cursors need be tripped - read-only |
3250 ** to prevent them from trying to use the btree after | 3477 ** cursors save their current positions so that they may continue |
3251 ** the rollback. The rollback may have deleted tables | 3478 ** following the rollback. Or, if writeOnly is false, all cursors are |
3252 ** or moved root pages, so it is not sufficient to | 3479 ** tripped. In general, writeOnly is false if the transaction being |
3253 ** save the state of the cursor. The cursor must be | 3480 ** rolled back modified the database schema. In this case b-tree root |
3254 ** invalidated. | 3481 ** pages may be moved or deleted from the database altogether, making |
| 3482 ** it unsafe for read cursors to continue. |
| 3483 ** |
| 3484 ** If the writeOnly flag is true and an error is encountered while |
| 3485 ** saving the current position of a read-only cursor, all cursors, |
| 3486 ** including all read-cursors are tripped. |
| 3487 ** |
| 3488 ** SQLITE_OK is returned if successful, or if an error occurs while |
| 3489 ** saving a cursor position, an SQLite error code. |
3255 */ | 3490 */ |
3256 void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){ | 3491 int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){ |
3257 BtCursor *p; | 3492 BtCursor *p; |
3258 sqlite3BtreeEnter(pBtree); | 3493 int rc = SQLITE_OK; |
3259 for(p=pBtree->pBt->pCursor; p; p=p->pNext){ | 3494 |
3260 int i; | 3495 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 ); |
3261 sqlite3BtreeClearCursor(p); | 3496 if( pBtree ){ |
3262 p->eState = CURSOR_FAULT; | 3497 sqlite3BtreeEnter(pBtree); |
3263 p->skipNext = errCode; | 3498 for(p=pBtree->pBt->pCursor; p; p=p->pNext){ |
3264 for(i=0; i<=p->iPage; i++){ | 3499 int i; |
3265 releasePage(p->apPage[i]); | 3500 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){ |
3266 p->apPage[i] = 0; | 3501 if( p->eState==CURSOR_VALID ){ |
| 3502 rc = saveCursorPosition(p); |
| 3503 if( rc!=SQLITE_OK ){ |
| 3504 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0); |
| 3505 break; |
| 3506 } |
| 3507 } |
| 3508 }else{ |
| 3509 sqlite3BtreeClearCursor(p); |
| 3510 p->eState = CURSOR_FAULT; |
| 3511 p->skipNext = errCode; |
| 3512 } |
| 3513 for(i=0; i<=p->iPage; i++){ |
| 3514 releasePage(p->apPage[i]); |
| 3515 p->apPage[i] = 0; |
| 3516 } |
3267 } | 3517 } |
| 3518 sqlite3BtreeLeave(pBtree); |
3268 } | 3519 } |
3269 sqlite3BtreeLeave(pBtree); | 3520 return rc; |
3270 } | 3521 } |
3271 | 3522 |
3272 /* | 3523 /* |
3273 ** Rollback the transaction in progress. All cursors will be | 3524 ** Rollback the transaction in progress. |
3274 ** invalided by this operation. Any attempt to use a cursor | 3525 ** |
3275 ** that was open at the beginning of this operation will result | 3526 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped). |
3276 ** in an error. | 3527 ** Only write cursors are tripped if writeOnly is true but all cursors are |
| 3528 ** tripped if writeOnly is false. Any attempt to use |
| 3529 ** a tripped cursor will result in an error. |
3277 ** | 3530 ** |
3278 ** This will release the write lock on the database file. If there | 3531 ** This will release the write lock on the database file. If there |
3279 ** are no active cursors, it also releases the read lock. | 3532 ** are no active cursors, it also releases the read lock. |
3280 */ | 3533 */ |
3281 int sqlite3BtreeRollback(Btree *p){ | 3534 int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){ |
3282 int rc; | 3535 int rc; |
3283 BtShared *pBt = p->pBt; | 3536 BtShared *pBt = p->pBt; |
3284 MemPage *pPage1; | 3537 MemPage *pPage1; |
3285 | 3538 |
| 3539 assert( writeOnly==1 || writeOnly==0 ); |
| 3540 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK ); |
3286 sqlite3BtreeEnter(p); | 3541 sqlite3BtreeEnter(p); |
3287 rc = saveAllCursors(pBt, 0, 0); | 3542 if( tripCode==SQLITE_OK ){ |
3288 #ifndef SQLITE_OMIT_SHARED_CACHE | 3543 rc = tripCode = saveAllCursors(pBt, 0, 0); |
3289 if( rc!=SQLITE_OK ){ | 3544 if( rc ) writeOnly = 0; |
3290 /* This is a horrible situation. An IO or malloc() error occurred whilst | 3545 }else{ |
3291 ** trying to save cursor positions. If this is an automatic rollback (as | 3546 rc = SQLITE_OK; |
3292 ** the result of a constraint, malloc() failure or IO error) then | |
3293 ** the cache may be internally inconsistent (not contain valid trees) so | |
3294 ** we cannot simply return the error to the caller. Instead, abort | |
3295 ** all queries that may be using any of the cursors that failed to save. | |
3296 */ | |
3297 sqlite3BtreeTripAllCursors(p, rc); | |
3298 } | 3547 } |
3299 #endif | 3548 if( tripCode ){ |
| 3549 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly); |
| 3550 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) ); |
| 3551 if( rc2!=SQLITE_OK ) rc = rc2; |
| 3552 } |
3300 btreeIntegrity(p); | 3553 btreeIntegrity(p); |
3301 | 3554 |
3302 if( p->inTrans==TRANS_WRITE ){ | 3555 if( p->inTrans==TRANS_WRITE ){ |
3303 int rc2; | 3556 int rc2; |
3304 | 3557 |
3305 assert( TRANS_WRITE==pBt->inTransaction ); | 3558 assert( TRANS_WRITE==pBt->inTransaction ); |
3306 rc2 = sqlite3PagerRollback(pBt->pPager); | 3559 rc2 = sqlite3PagerRollback(pBt->pPager); |
3307 if( rc2!=SQLITE_OK ){ | 3560 if( rc2!=SQLITE_OK ){ |
3308 rc = rc2; | 3561 rc = rc2; |
3309 } | 3562 } |
3310 | 3563 |
3311 /* The rollback may have destroyed the pPage1->aData value. So | 3564 /* The rollback may have destroyed the pPage1->aData value. So |
3312 ** call btreeGetPage() on page 1 again to make | 3565 ** call btreeGetPage() on page 1 again to make |
3313 ** sure pPage1->aData is set correctly. */ | 3566 ** sure pPage1->aData is set correctly. */ |
3314 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){ | 3567 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){ |
3315 int nPage = get4byte(28+(u8*)pPage1->aData); | 3568 int nPage = get4byte(28+(u8*)pPage1->aData); |
3316 testcase( nPage==0 ); | 3569 testcase( nPage==0 ); |
3317 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage); | 3570 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage); |
3318 testcase( pBt->nPage!=nPage ); | 3571 testcase( pBt->nPage!=nPage ); |
3319 pBt->nPage = nPage; | 3572 pBt->nPage = nPage; |
3320 releasePage(pPage1); | 3573 releasePage(pPage1); |
3321 } | 3574 } |
3322 assert( countWriteCursors(pBt)==0 ); | 3575 assert( countValidCursors(pBt, 1)==0 ); |
3323 pBt->inTransaction = TRANS_READ; | 3576 pBt->inTransaction = TRANS_READ; |
| 3577 btreeClearHasContent(pBt); |
3324 } | 3578 } |
3325 | 3579 |
3326 btreeEndTransaction(p); | 3580 btreeEndTransaction(p); |
3327 sqlite3BtreeLeave(p); | 3581 sqlite3BtreeLeave(p); |
3328 return rc; | 3582 return rc; |
3329 } | 3583 } |
3330 | 3584 |
3331 /* | 3585 /* |
3332 ** Start a statement subtransaction. The subtransaction can can be rolled | 3586 ** Start a statement subtransaction. The subtransaction can be rolled |
3333 ** back independently of the main transaction. You must start a transaction | 3587 ** back independently of the main transaction. You must start a transaction |
3334 ** before starting a subtransaction. The subtransaction is ended automatically | 3588 ** before starting a subtransaction. The subtransaction is ended automatically |
3335 ** if the main transaction commits or rolls back. | 3589 ** if the main transaction commits or rolls back. |
3336 ** | 3590 ** |
3337 ** Statement subtransactions are used around individual SQL statements | 3591 ** Statement subtransactions are used around individual SQL statements |
3338 ** that are contained within a BEGIN...COMMIT block. If a constraint | 3592 ** that are contained within a BEGIN...COMMIT block. If a constraint |
3339 ** error occurs within the statement, the effect of that one statement | 3593 ** error occurs within the statement, the effect of that one statement |
3340 ** can be rolled back without having to rollback the entire transaction. | 3594 ** can be rolled back without having to rollback the entire transaction. |
3341 ** | 3595 ** |
3342 ** A statement sub-transaction is implemented as an anonymous savepoint. The | 3596 ** A statement sub-transaction is implemented as an anonymous savepoint. The |
3343 ** value passed as the second parameter is the total number of savepoints, | 3597 ** value passed as the second parameter is the total number of savepoints, |
3344 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there | 3598 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there |
3345 ** are no active savepoints and no other statement-transactions open, | 3599 ** are no active savepoints and no other statement-transactions open, |
3346 ** iStatement is 1. This anonymous savepoint can be released or rolled back | 3600 ** iStatement is 1. This anonymous savepoint can be released or rolled back |
3347 ** using the sqlite3BtreeSavepoint() function. | 3601 ** using the sqlite3BtreeSavepoint() function. |
3348 */ | 3602 */ |
3349 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){ | 3603 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){ |
3350 int rc; | 3604 int rc; |
3351 BtShared *pBt = p->pBt; | 3605 BtShared *pBt = p->pBt; |
3352 sqlite3BtreeEnter(p); | 3606 sqlite3BtreeEnter(p); |
3353 assert( p->inTrans==TRANS_WRITE ); | 3607 assert( p->inTrans==TRANS_WRITE ); |
3354 assert( pBt->readOnly==0 ); | 3608 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); |
3355 assert( iStatement>0 ); | 3609 assert( iStatement>0 ); |
3356 assert( iStatement>p->db->nSavepoint ); | 3610 assert( iStatement>p->db->nSavepoint ); |
3357 assert( pBt->inTransaction==TRANS_WRITE ); | 3611 assert( pBt->inTransaction==TRANS_WRITE ); |
3358 /* At the pager level, a statement transaction is a savepoint with | 3612 /* At the pager level, a statement transaction is a savepoint with |
3359 ** an index greater than all savepoints created explicitly using | 3613 ** an index greater than all savepoints created explicitly using |
3360 ** SQL statements. It is illegal to open, release or rollback any | 3614 ** SQL statements. It is illegal to open, release or rollback any |
3361 ** such savepoints while the statement transaction savepoint is active. | 3615 ** such savepoints while the statement transaction savepoint is active. |
3362 */ | 3616 */ |
3363 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement); | 3617 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement); |
3364 sqlite3BtreeLeave(p); | 3618 sqlite3BtreeLeave(p); |
(...skipping 14 matching lines...) Expand all Loading... |
3379 */ | 3633 */ |
3380 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){ | 3634 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){ |
3381 int rc = SQLITE_OK; | 3635 int rc = SQLITE_OK; |
3382 if( p && p->inTrans==TRANS_WRITE ){ | 3636 if( p && p->inTrans==TRANS_WRITE ){ |
3383 BtShared *pBt = p->pBt; | 3637 BtShared *pBt = p->pBt; |
3384 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK ); | 3638 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK ); |
3385 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) ); | 3639 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) ); |
3386 sqlite3BtreeEnter(p); | 3640 sqlite3BtreeEnter(p); |
3387 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint); | 3641 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint); |
3388 if( rc==SQLITE_OK ){ | 3642 if( rc==SQLITE_OK ){ |
3389 if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0; | 3643 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){ |
| 3644 pBt->nPage = 0; |
| 3645 } |
3390 rc = newDatabase(pBt); | 3646 rc = newDatabase(pBt); |
3391 pBt->nPage = get4byte(28 + pBt->pPage1->aData); | 3647 pBt->nPage = get4byte(28 + pBt->pPage1->aData); |
3392 | 3648 |
3393 /* The database size was written into the offset 28 of the header | 3649 /* The database size was written into the offset 28 of the header |
3394 ** when the transaction started, so we know that the value at offset | 3650 ** when the transaction started, so we know that the value at offset |
3395 ** 28 is nonzero. */ | 3651 ** 28 is nonzero. */ |
3396 assert( pBt->nPage>0 ); | 3652 assert( pBt->nPage>0 ); |
3397 } | 3653 } |
3398 sqlite3BtreeLeave(p); | 3654 sqlite3BtreeLeave(p); |
3399 } | 3655 } |
(...skipping 49 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
3449 ** and that no other connection has any open cursor that conflicts with | 3705 ** and that no other connection has any open cursor that conflicts with |
3450 ** this lock. */ | 3706 ** this lock. */ |
3451 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) ); | 3707 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) ); |
3452 assert( wrFlag==0 || !hasReadConflicts(p, iTable) ); | 3708 assert( wrFlag==0 || !hasReadConflicts(p, iTable) ); |
3453 | 3709 |
3454 /* Assert that the caller has opened the required transaction. */ | 3710 /* Assert that the caller has opened the required transaction. */ |
3455 assert( p->inTrans>TRANS_NONE ); | 3711 assert( p->inTrans>TRANS_NONE ); |
3456 assert( wrFlag==0 || p->inTrans==TRANS_WRITE ); | 3712 assert( wrFlag==0 || p->inTrans==TRANS_WRITE ); |
3457 assert( pBt->pPage1 && pBt->pPage1->aData ); | 3713 assert( pBt->pPage1 && pBt->pPage1->aData ); |
3458 | 3714 |
3459 if( NEVER(wrFlag && pBt->readOnly) ){ | 3715 if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){ |
3460 return SQLITE_READONLY; | 3716 return SQLITE_READONLY; |
3461 } | 3717 } |
| 3718 if( wrFlag ){ |
| 3719 allocateTempSpace(pBt); |
| 3720 if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM; |
| 3721 } |
3462 if( iTable==1 && btreePagecount(pBt)==0 ){ | 3722 if( iTable==1 && btreePagecount(pBt)==0 ){ |
3463 return SQLITE_EMPTY; | 3723 assert( wrFlag==0 ); |
| 3724 iTable = 0; |
3464 } | 3725 } |
3465 | 3726 |
3466 /* Now that no other errors can occur, finish filling in the BtCursor | 3727 /* Now that no other errors can occur, finish filling in the BtCursor |
3467 ** variables and link the cursor into the BtShared list. */ | 3728 ** variables and link the cursor into the BtShared list. */ |
3468 pCur->pgnoRoot = (Pgno)iTable; | 3729 pCur->pgnoRoot = (Pgno)iTable; |
3469 pCur->iPage = -1; | 3730 pCur->iPage = -1; |
3470 pCur->pKeyInfo = pKeyInfo; | 3731 pCur->pKeyInfo = pKeyInfo; |
3471 pCur->pBtree = p; | 3732 pCur->pBtree = p; |
3472 pCur->pBt = pBt; | 3733 pCur->pBt = pBt; |
3473 pCur->wrFlag = (u8)wrFlag; | 3734 assert( wrFlag==0 || wrFlag==BTCF_WriteFlag ); |
| 3735 pCur->curFlags = wrFlag; |
3474 pCur->pNext = pBt->pCursor; | 3736 pCur->pNext = pBt->pCursor; |
3475 if( pCur->pNext ){ | 3737 if( pCur->pNext ){ |
3476 pCur->pNext->pPrev = pCur; | 3738 pCur->pNext->pPrev = pCur; |
3477 } | 3739 } |
3478 pBt->pCursor = pCur; | 3740 pBt->pCursor = pCur; |
3479 pCur->eState = CURSOR_INVALID; | 3741 pCur->eState = CURSOR_INVALID; |
3480 pCur->cachedRowid = 0; | |
3481 return SQLITE_OK; | 3742 return SQLITE_OK; |
3482 } | 3743 } |
3483 int sqlite3BtreeCursor( | 3744 int sqlite3BtreeCursor( |
3484 Btree *p, /* The btree */ | 3745 Btree *p, /* The btree */ |
3485 int iTable, /* Root page of table to open */ | 3746 int iTable, /* Root page of table to open */ |
3486 int wrFlag, /* 1 to write. 0 read-only */ | 3747 int wrFlag, /* 1 to write. 0 read-only */ |
3487 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */ | 3748 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */ |
3488 BtCursor *pCur /* Write new cursor here */ | 3749 BtCursor *pCur /* Write new cursor here */ |
3489 ){ | 3750 ){ |
3490 int rc; | 3751 int rc; |
(...skipping 21 matching lines...) Expand all Loading... |
3512 ** The simple approach here would be to memset() the entire object | 3773 ** The simple approach here would be to memset() the entire object |
3513 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays | 3774 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays |
3514 ** do not need to be zeroed and they are large, so we can save a lot | 3775 ** do not need to be zeroed and they are large, so we can save a lot |
3515 ** of run-time by skipping the initialization of those elements. | 3776 ** of run-time by skipping the initialization of those elements. |
3516 */ | 3777 */ |
3517 void sqlite3BtreeCursorZero(BtCursor *p){ | 3778 void sqlite3BtreeCursorZero(BtCursor *p){ |
3518 memset(p, 0, offsetof(BtCursor, iPage)); | 3779 memset(p, 0, offsetof(BtCursor, iPage)); |
3519 } | 3780 } |
3520 | 3781 |
3521 /* | 3782 /* |
3522 ** Set the cached rowid value of every cursor in the same database file | |
3523 ** as pCur and having the same root page number as pCur. The value is | |
3524 ** set to iRowid. | |
3525 ** | |
3526 ** Only positive rowid values are considered valid for this cache. | |
3527 ** The cache is initialized to zero, indicating an invalid cache. | |
3528 ** A btree will work fine with zero or negative rowids. We just cannot | |
3529 ** cache zero or negative rowids, which means tables that use zero or | |
3530 ** negative rowids might run a little slower. But in practice, zero | |
3531 ** or negative rowids are very uncommon so this should not be a problem. | |
3532 */ | |
3533 void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){ | |
3534 BtCursor *p; | |
3535 for(p=pCur->pBt->pCursor; p; p=p->pNext){ | |
3536 if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid; | |
3537 } | |
3538 assert( pCur->cachedRowid==iRowid ); | |
3539 } | |
3540 | |
3541 /* | |
3542 ** Return the cached rowid for the given cursor. A negative or zero | |
3543 ** return value indicates that the rowid cache is invalid and should be | |
3544 ** ignored. If the rowid cache has never before been set, then a | |
3545 ** zero is returned. | |
3546 */ | |
3547 sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){ | |
3548 return pCur->cachedRowid; | |
3549 } | |
3550 | |
3551 /* | |
3552 ** Close a cursor. The read lock on the database file is released | 3783 ** Close a cursor. The read lock on the database file is released |
3553 ** when the last cursor is closed. | 3784 ** when the last cursor is closed. |
3554 */ | 3785 */ |
3555 int sqlite3BtreeCloseCursor(BtCursor *pCur){ | 3786 int sqlite3BtreeCloseCursor(BtCursor *pCur){ |
3556 Btree *pBtree = pCur->pBtree; | 3787 Btree *pBtree = pCur->pBtree; |
3557 if( pBtree ){ | 3788 if( pBtree ){ |
3558 int i; | 3789 int i; |
3559 BtShared *pBt = pCur->pBt; | 3790 BtShared *pBt = pCur->pBt; |
3560 sqlite3BtreeEnter(pBtree); | 3791 sqlite3BtreeEnter(pBtree); |
3561 sqlite3BtreeClearCursor(pCur); | 3792 sqlite3BtreeClearCursor(pCur); |
3562 if( pCur->pPrev ){ | 3793 if( pCur->pPrev ){ |
3563 pCur->pPrev->pNext = pCur->pNext; | 3794 pCur->pPrev->pNext = pCur->pNext; |
3564 }else{ | 3795 }else{ |
3565 pBt->pCursor = pCur->pNext; | 3796 pBt->pCursor = pCur->pNext; |
3566 } | 3797 } |
3567 if( pCur->pNext ){ | 3798 if( pCur->pNext ){ |
3568 pCur->pNext->pPrev = pCur->pPrev; | 3799 pCur->pNext->pPrev = pCur->pPrev; |
3569 } | 3800 } |
3570 for(i=0; i<=pCur->iPage; i++){ | 3801 for(i=0; i<=pCur->iPage; i++){ |
3571 releasePage(pCur->apPage[i]); | 3802 releasePage(pCur->apPage[i]); |
3572 } | 3803 } |
3573 unlockBtreeIfUnused(pBt); | 3804 unlockBtreeIfUnused(pBt); |
3574 invalidateOverflowCache(pCur); | 3805 sqlite3DbFree(pBtree->db, pCur->aOverflow); |
3575 /* sqlite3_free(pCur); */ | 3806 /* sqlite3_free(pCur); */ |
3576 sqlite3BtreeLeave(pBtree); | 3807 sqlite3BtreeLeave(pBtree); |
3577 } | 3808 } |
3578 return SQLITE_OK; | 3809 return SQLITE_OK; |
3579 } | 3810 } |
3580 | 3811 |
3581 /* | 3812 /* |
3582 ** Make sure the BtCursor* given in the argument has a valid | 3813 ** Make sure the BtCursor* given in the argument has a valid |
3583 ** BtCursor.info structure. If it is not already valid, call | 3814 ** BtCursor.info structure. If it is not already valid, call |
3584 ** btreeParseCell() to fill it in. | 3815 ** btreeParseCell() to fill it in. |
3585 ** | 3816 ** |
3586 ** BtCursor.info is a cache of the information in the current cell. | 3817 ** BtCursor.info is a cache of the information in the current cell. |
3587 ** Using this cache reduces the number of calls to btreeParseCell(). | 3818 ** Using this cache reduces the number of calls to btreeParseCell(). |
3588 ** | 3819 ** |
3589 ** 2007-06-25: There is a bug in some versions of MSVC that cause the | 3820 ** 2007-06-25: There is a bug in some versions of MSVC that cause the |
3590 ** compiler to crash when getCellInfo() is implemented as a macro. | 3821 ** compiler to crash when getCellInfo() is implemented as a macro. |
3591 ** But there is a measureable speed advantage to using the macro on gcc | 3822 ** But there is a measureable speed advantage to using the macro on gcc |
3592 ** (when less compiler optimizations like -Os or -O0 are used and the | 3823 ** (when less compiler optimizations like -Os or -O0 are used and the |
3593 ** compiler is not doing agressive inlining.) So we use a real function | 3824 ** compiler is not doing aggressive inlining.) So we use a real function |
3594 ** for MSVC and a macro for everything else. Ticket #2457. | 3825 ** for MSVC and a macro for everything else. Ticket #2457. |
3595 */ | 3826 */ |
3596 #ifndef NDEBUG | 3827 #ifndef NDEBUG |
3597 static void assertCellInfo(BtCursor *pCur){ | 3828 static void assertCellInfo(BtCursor *pCur){ |
3598 CellInfo info; | 3829 CellInfo info; |
3599 int iPage = pCur->iPage; | 3830 int iPage = pCur->iPage; |
3600 memset(&info, 0, sizeof(info)); | 3831 memset(&info, 0, sizeof(info)); |
3601 btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info); | 3832 btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info); |
3602 assert( memcmp(&info, &pCur->info, sizeof(info))==0 ); | 3833 assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 ); |
3603 } | 3834 } |
3604 #else | 3835 #else |
3605 #define assertCellInfo(x) | 3836 #define assertCellInfo(x) |
3606 #endif | 3837 #endif |
3607 #ifdef _MSC_VER | 3838 #ifdef _MSC_VER |
3608 /* Use a real function in MSVC to work around bugs in that compiler. */ | 3839 /* Use a real function in MSVC to work around bugs in that compiler. */ |
3609 static void getCellInfo(BtCursor *pCur){ | 3840 static void getCellInfo(BtCursor *pCur){ |
3610 if( pCur->info.nSize==0 ){ | 3841 if( pCur->info.nSize==0 ){ |
3611 int iPage = pCur->iPage; | 3842 int iPage = pCur->iPage; |
3612 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); | 3843 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); |
3613 pCur->validNKey = 1; | 3844 pCur->curFlags |= BTCF_ValidNKey; |
3614 }else{ | 3845 }else{ |
3615 assertCellInfo(pCur); | 3846 assertCellInfo(pCur); |
3616 } | 3847 } |
3617 } | 3848 } |
3618 #else /* if not _MSC_VER */ | 3849 #else /* if not _MSC_VER */ |
3619 /* Use a macro in all other compilers so that the function is inlined */ | 3850 /* Use a macro in all other compilers so that the function is inlined */ |
3620 #define getCellInfo(pCur) \ | 3851 #define getCellInfo(pCur) \ |
3621 if( pCur->info.nSize==0 ){ \ | 3852 if( pCur->info.nSize==0 ){ \ |
3622 int iPage = pCur->iPage; \ | 3853 int iPage = pCur->iPage; \ |
3623 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \ | 3854 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \ |
3624 pCur->validNKey = 1; \ | 3855 pCur->curFlags |= BTCF_ValidNKey; \ |
3625 }else{ \ | 3856 }else{ \ |
3626 assertCellInfo(pCur); \ | 3857 assertCellInfo(pCur); \ |
3627 } | 3858 } |
3628 #endif /* _MSC_VER */ | 3859 #endif /* _MSC_VER */ |
3629 | 3860 |
3630 #ifndef NDEBUG /* The next routine used only within assert() statements */ | 3861 #ifndef NDEBUG /* The next routine used only within assert() statements */ |
3631 /* | 3862 /* |
3632 ** Return true if the given BtCursor is valid. A valid cursor is one | 3863 ** Return true if the given BtCursor is valid. A valid cursor is one |
3633 ** that is currently pointing to a row in a (non-empty) table. | 3864 ** that is currently pointing to a row in a (non-empty) table. |
3634 ** This is a verification routine is used only within assert() statements. | 3865 ** This is a verification routine is used only within assert() statements. |
(...skipping 10 matching lines...) Expand all Loading... |
3645 ** | 3876 ** |
3646 ** For a table with the INTKEY flag set, this routine returns the key | 3877 ** For a table with the INTKEY flag set, this routine returns the key |
3647 ** itself, not the number of bytes in the key. | 3878 ** itself, not the number of bytes in the key. |
3648 ** | 3879 ** |
3649 ** The caller must position the cursor prior to invoking this routine. | 3880 ** The caller must position the cursor prior to invoking this routine. |
3650 ** | 3881 ** |
3651 ** This routine cannot fail. It always returns SQLITE_OK. | 3882 ** This routine cannot fail. It always returns SQLITE_OK. |
3652 */ | 3883 */ |
3653 int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){ | 3884 int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){ |
3654 assert( cursorHoldsMutex(pCur) ); | 3885 assert( cursorHoldsMutex(pCur) ); |
3655 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID ); | 3886 assert( pCur->eState==CURSOR_VALID ); |
3656 if( pCur->eState!=CURSOR_VALID ){ | 3887 getCellInfo(pCur); |
3657 *pSize = 0; | 3888 *pSize = pCur->info.nKey; |
3658 }else{ | |
3659 getCellInfo(pCur); | |
3660 *pSize = pCur->info.nKey; | |
3661 } | |
3662 return SQLITE_OK; | 3889 return SQLITE_OK; |
3663 } | 3890 } |
3664 | 3891 |
3665 /* | 3892 /* |
3666 ** Set *pSize to the number of bytes of data in the entry the | 3893 ** Set *pSize to the number of bytes of data in the entry the |
3667 ** cursor currently points to. | 3894 ** cursor currently points to. |
3668 ** | 3895 ** |
3669 ** The caller must guarantee that the cursor is pointing to a non-NULL | 3896 ** The caller must guarantee that the cursor is pointing to a non-NULL |
3670 ** valid entry. In other words, the calling procedure must guarantee | 3897 ** valid entry. In other words, the calling procedure must guarantee |
3671 ** that the cursor has Cursor.eState==CURSOR_VALID. | 3898 ** that the cursor has Cursor.eState==CURSOR_VALID. |
3672 ** | 3899 ** |
3673 ** Failure is not possible. This function always returns SQLITE_OK. | 3900 ** Failure is not possible. This function always returns SQLITE_OK. |
3674 ** It might just as well be a procedure (returning void) but we continue | 3901 ** It might just as well be a procedure (returning void) but we continue |
3675 ** to return an integer result code for historical reasons. | 3902 ** to return an integer result code for historical reasons. |
3676 */ | 3903 */ |
3677 int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){ | 3904 int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){ |
3678 assert( cursorHoldsMutex(pCur) ); | 3905 assert( cursorHoldsMutex(pCur) ); |
3679 assert( pCur->eState==CURSOR_VALID ); | 3906 assert( pCur->eState==CURSOR_VALID ); |
| 3907 assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 ); |
3680 getCellInfo(pCur); | 3908 getCellInfo(pCur); |
3681 *pSize = pCur->info.nData; | 3909 *pSize = pCur->info.nPayload; |
3682 return SQLITE_OK; | 3910 return SQLITE_OK; |
3683 } | 3911 } |
3684 | 3912 |
3685 /* | 3913 /* |
3686 ** Given the page number of an overflow page in the database (parameter | 3914 ** Given the page number of an overflow page in the database (parameter |
3687 ** ovfl), this function finds the page number of the next page in the | 3915 ** ovfl), this function finds the page number of the next page in the |
3688 ** linked list of overflow pages. If possible, it uses the auto-vacuum | 3916 ** linked list of overflow pages. If possible, it uses the auto-vacuum |
3689 ** pointer-map data instead of reading the content of page ovfl to do so. | 3917 ** pointer-map data instead of reading the content of page ovfl to do so. |
3690 ** | 3918 ** |
3691 ** If an error occurs an SQLite error code is returned. Otherwise: | 3919 ** If an error occurs an SQLite error code is returned. Otherwise: |
(...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
3735 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){ | 3963 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){ |
3736 next = iGuess; | 3964 next = iGuess; |
3737 rc = SQLITE_DONE; | 3965 rc = SQLITE_DONE; |
3738 } | 3966 } |
3739 } | 3967 } |
3740 } | 3968 } |
3741 #endif | 3969 #endif |
3742 | 3970 |
3743 assert( next==0 || rc==SQLITE_DONE ); | 3971 assert( next==0 || rc==SQLITE_DONE ); |
3744 if( rc==SQLITE_OK ){ | 3972 if( rc==SQLITE_OK ){ |
3745 rc = btreeGetPage(pBt, ovfl, &pPage, 0); | 3973 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0); |
3746 assert( rc==SQLITE_OK || pPage==0 ); | 3974 assert( rc==SQLITE_OK || pPage==0 ); |
3747 if( rc==SQLITE_OK ){ | 3975 if( rc==SQLITE_OK ){ |
3748 next = get4byte(pPage->aData); | 3976 next = get4byte(pPage->aData); |
3749 } | 3977 } |
3750 } | 3978 } |
3751 | 3979 |
3752 *pPgnoNext = next; | 3980 *pPgnoNext = next; |
3753 if( ppPage ){ | 3981 if( ppPage ){ |
3754 *ppPage = pPage; | 3982 *ppPage = pPage; |
3755 }else{ | 3983 }else{ |
(...skipping 29 matching lines...) Expand all Loading... |
3785 memcpy(pPayload, pBuf, nByte); | 4013 memcpy(pPayload, pBuf, nByte); |
3786 }else{ | 4014 }else{ |
3787 /* Copy data from page to buffer (a read operation) */ | 4015 /* Copy data from page to buffer (a read operation) */ |
3788 memcpy(pBuf, pPayload, nByte); | 4016 memcpy(pBuf, pPayload, nByte); |
3789 } | 4017 } |
3790 return SQLITE_OK; | 4018 return SQLITE_OK; |
3791 } | 4019 } |
3792 | 4020 |
3793 /* | 4021 /* |
3794 ** This function is used to read or overwrite payload information | 4022 ** This function is used to read or overwrite payload information |
3795 ** for the entry that the pCur cursor is pointing to. If the eOp | 4023 ** for the entry that the pCur cursor is pointing to. The eOp |
3796 ** parameter is 0, this is a read operation (data copied into | 4024 ** argument is interpreted as follows: |
3797 ** buffer pBuf). If it is non-zero, a write (data copied from | 4025 ** |
3798 ** buffer pBuf). | 4026 ** 0: The operation is a read. Populate the overflow cache. |
| 4027 ** 1: The operation is a write. Populate the overflow cache. |
| 4028 ** 2: The operation is a read. Do not populate the overflow cache. |
3799 ** | 4029 ** |
3800 ** A total of "amt" bytes are read or written beginning at "offset". | 4030 ** A total of "amt" bytes are read or written beginning at "offset". |
3801 ** Data is read to or from the buffer pBuf. | 4031 ** Data is read to or from the buffer pBuf. |
3802 ** | 4032 ** |
3803 ** The content being read or written might appear on the main page | 4033 ** The content being read or written might appear on the main page |
3804 ** or be scattered out on multiple overflow pages. | 4034 ** or be scattered out on multiple overflow pages. |
3805 ** | 4035 ** |
3806 ** If the BtCursor.isIncrblobHandle flag is set, and the current | 4036 ** If the current cursor entry uses one or more overflow pages and the |
3807 ** cursor entry uses one or more overflow pages, this function | 4037 ** eOp argument is not 2, this function may allocate space for and lazily |
3808 ** allocates space for and lazily popluates the overflow page-list | 4038 ** populates the overflow page-list cache array (BtCursor.aOverflow). |
3809 ** cache array (BtCursor.aOverflow). Subsequent calls use this | 4039 ** Subsequent calls use this cache to make seeking to the supplied offset |
3810 ** cache to make seeking to the supplied offset more efficient. | 4040 ** more efficient. |
3811 ** | 4041 ** |
3812 ** Once an overflow page-list cache has been allocated, it may be | 4042 ** Once an overflow page-list cache has been allocated, it may be |
3813 ** invalidated if some other cursor writes to the same table, or if | 4043 ** invalidated if some other cursor writes to the same table, or if |
3814 ** the cursor is moved to a different row. Additionally, in auto-vacuum | 4044 ** the cursor is moved to a different row. Additionally, in auto-vacuum |
3815 ** mode, the following events may invalidate an overflow page-list cache. | 4045 ** mode, the following events may invalidate an overflow page-list cache. |
3816 ** | 4046 ** |
3817 ** * An incremental vacuum, | 4047 ** * An incremental vacuum, |
3818 ** * A commit in auto_vacuum="full" mode, | 4048 ** * A commit in auto_vacuum="full" mode, |
3819 ** * Creating a table (may require moving an overflow page). | 4049 ** * Creating a table (may require moving an overflow page). |
3820 */ | 4050 */ |
3821 static int accessPayload( | 4051 static int accessPayload( |
3822 BtCursor *pCur, /* Cursor pointing to entry to read from */ | 4052 BtCursor *pCur, /* Cursor pointing to entry to read from */ |
3823 u32 offset, /* Begin reading this far into payload */ | 4053 u32 offset, /* Begin reading this far into payload */ |
3824 u32 amt, /* Read this many bytes */ | 4054 u32 amt, /* Read this many bytes */ |
3825 unsigned char *pBuf, /* Write the bytes into this buffer */ | 4055 unsigned char *pBuf, /* Write the bytes into this buffer */ |
3826 int eOp /* zero to read. non-zero to write. */ | 4056 int eOp /* zero to read. non-zero to write. */ |
3827 ){ | 4057 ){ |
3828 unsigned char *aPayload; | 4058 unsigned char *aPayload; |
3829 int rc = SQLITE_OK; | 4059 int rc = SQLITE_OK; |
3830 u32 nKey; | |
3831 int iIdx = 0; | 4060 int iIdx = 0; |
3832 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */ | 4061 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */ |
3833 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */ | 4062 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */ |
| 4063 #ifdef SQLITE_DIRECT_OVERFLOW_READ |
| 4064 unsigned char * const pBufStart = pBuf; |
| 4065 int bEnd; /* True if reading to end of data */ |
| 4066 #endif |
3834 | 4067 |
3835 assert( pPage ); | 4068 assert( pPage ); |
3836 assert( pCur->eState==CURSOR_VALID ); | 4069 assert( pCur->eState==CURSOR_VALID ); |
3837 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell ); | 4070 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell ); |
3838 assert( cursorHoldsMutex(pCur) ); | 4071 assert( cursorHoldsMutex(pCur) ); |
| 4072 assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */ |
3839 | 4073 |
3840 getCellInfo(pCur); | 4074 getCellInfo(pCur); |
3841 aPayload = pCur->info.pCell + pCur->info.nHeader; | 4075 aPayload = pCur->info.pPayload; |
3842 nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey); | 4076 #ifdef SQLITE_DIRECT_OVERFLOW_READ |
| 4077 bEnd = offset+amt==pCur->info.nPayload; |
| 4078 #endif |
| 4079 assert( offset+amt <= pCur->info.nPayload ); |
3843 | 4080 |
3844 if( NEVER(offset+amt > nKey+pCur->info.nData) | 4081 if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){ |
3845 || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] | |
3846 ){ | |
3847 /* Trying to read or write past the end of the data is an error */ | 4082 /* Trying to read or write past the end of the data is an error */ |
3848 return SQLITE_CORRUPT_BKPT; | 4083 return SQLITE_CORRUPT_BKPT; |
3849 } | 4084 } |
3850 | 4085 |
3851 /* Check if data must be read/written to/from the btree page itself. */ | 4086 /* Check if data must be read/written to/from the btree page itself. */ |
3852 if( offset<pCur->info.nLocal ){ | 4087 if( offset<pCur->info.nLocal ){ |
3853 int a = amt; | 4088 int a = amt; |
3854 if( a+offset>pCur->info.nLocal ){ | 4089 if( a+offset>pCur->info.nLocal ){ |
3855 a = pCur->info.nLocal - offset; | 4090 a = pCur->info.nLocal - offset; |
3856 } | 4091 } |
3857 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage); | 4092 rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage); |
3858 offset = 0; | 4093 offset = 0; |
3859 pBuf += a; | 4094 pBuf += a; |
3860 amt -= a; | 4095 amt -= a; |
3861 }else{ | 4096 }else{ |
3862 offset -= pCur->info.nLocal; | 4097 offset -= pCur->info.nLocal; |
3863 } | 4098 } |
3864 | 4099 |
3865 if( rc==SQLITE_OK && amt>0 ){ | 4100 if( rc==SQLITE_OK && amt>0 ){ |
3866 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */ | 4101 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */ |
3867 Pgno nextPage; | 4102 Pgno nextPage; |
3868 | 4103 |
3869 nextPage = get4byte(&aPayload[pCur->info.nLocal]); | 4104 nextPage = get4byte(&aPayload[pCur->info.nLocal]); |
3870 | 4105 |
3871 #ifndef SQLITE_OMIT_INCRBLOB | 4106 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now. |
3872 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[] | 4107 ** Except, do not allocate aOverflow[] for eOp==2. |
3873 ** has not been allocated, allocate it now. The array is sized at | 4108 ** |
3874 ** one entry for each overflow page in the overflow chain. The | 4109 ** The aOverflow[] array is sized at one entry for each overflow page |
3875 ** page number of the first overflow page is stored in aOverflow[0], | 4110 ** in the overflow chain. The page number of the first overflow page is |
3876 ** etc. A value of 0 in the aOverflow[] array means "not yet known" | 4111 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array |
3877 ** (the cache is lazily populated). | 4112 ** means "not yet known" (the cache is lazily populated). |
3878 */ | 4113 */ |
3879 if( pCur->isIncrblobHandle && !pCur->aOverflow ){ | 4114 if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){ |
3880 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize; | 4115 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize; |
3881 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl); | 4116 if( nOvfl>pCur->nOvflAlloc ){ |
3882 /* nOvfl is always positive. If it were zero, fetchPayload would have | 4117 Pgno *aNew = (Pgno*)sqlite3DbRealloc( |
3883 ** been used instead of this routine. */ | 4118 pCur->pBtree->db, pCur->aOverflow, nOvfl*2*sizeof(Pgno) |
3884 if( ALWAYS(nOvfl) && !pCur->aOverflow ){ | 4119 ); |
3885 rc = SQLITE_NOMEM; | 4120 if( aNew==0 ){ |
| 4121 rc = SQLITE_NOMEM; |
| 4122 }else{ |
| 4123 pCur->nOvflAlloc = nOvfl*2; |
| 4124 pCur->aOverflow = aNew; |
| 4125 } |
| 4126 } |
| 4127 if( rc==SQLITE_OK ){ |
| 4128 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno)); |
| 4129 pCur->curFlags |= BTCF_ValidOvfl; |
3886 } | 4130 } |
3887 } | 4131 } |
3888 | 4132 |
3889 /* If the overflow page-list cache has been allocated and the | 4133 /* If the overflow page-list cache has been allocated and the |
3890 ** entry for the first required overflow page is valid, skip | 4134 ** entry for the first required overflow page is valid, skip |
3891 ** directly to it. | 4135 ** directly to it. |
3892 */ | 4136 */ |
3893 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){ | 4137 if( (pCur->curFlags & BTCF_ValidOvfl)!=0 |
| 4138 && pCur->aOverflow[offset/ovflSize] |
| 4139 ){ |
3894 iIdx = (offset/ovflSize); | 4140 iIdx = (offset/ovflSize); |
3895 nextPage = pCur->aOverflow[iIdx]; | 4141 nextPage = pCur->aOverflow[iIdx]; |
3896 offset = (offset%ovflSize); | 4142 offset = (offset%ovflSize); |
3897 } | 4143 } |
3898 #endif | |
3899 | 4144 |
3900 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){ | 4145 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){ |
3901 | 4146 |
3902 #ifndef SQLITE_OMIT_INCRBLOB | |
3903 /* If required, populate the overflow page-list cache. */ | 4147 /* If required, populate the overflow page-list cache. */ |
3904 if( pCur->aOverflow ){ | 4148 if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){ |
3905 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage); | 4149 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage); |
3906 pCur->aOverflow[iIdx] = nextPage; | 4150 pCur->aOverflow[iIdx] = nextPage; |
3907 } | 4151 } |
3908 #endif | |
3909 | 4152 |
3910 if( offset>=ovflSize ){ | 4153 if( offset>=ovflSize ){ |
3911 /* The only reason to read this page is to obtain the page | 4154 /* The only reason to read this page is to obtain the page |
3912 ** number for the next page in the overflow chain. The page | 4155 ** number for the next page in the overflow chain. The page |
3913 ** data is not required. So first try to lookup the overflow | 4156 ** data is not required. So first try to lookup the overflow |
3914 ** page-list cache, if any, then fall back to the getOverflowPage() | 4157 ** page-list cache, if any, then fall back to the getOverflowPage() |
3915 ** function. | 4158 ** function. |
| 4159 ** |
| 4160 ** Note that the aOverflow[] array must be allocated because eOp!=2 |
| 4161 ** here. If eOp==2, then offset==0 and this branch is never taken. |
3916 */ | 4162 */ |
3917 #ifndef SQLITE_OMIT_INCRBLOB | 4163 assert( eOp!=2 ); |
3918 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){ | 4164 assert( pCur->curFlags & BTCF_ValidOvfl ); |
| 4165 if( pCur->aOverflow[iIdx+1] ){ |
3919 nextPage = pCur->aOverflow[iIdx+1]; | 4166 nextPage = pCur->aOverflow[iIdx+1]; |
3920 } else | 4167 }else{ |
3921 #endif | |
3922 rc = getOverflowPage(pBt, nextPage, 0, &nextPage); | 4168 rc = getOverflowPage(pBt, nextPage, 0, &nextPage); |
| 4169 } |
3923 offset -= ovflSize; | 4170 offset -= ovflSize; |
3924 }else{ | 4171 }else{ |
3925 /* Need to read this page properly. It contains some of the | 4172 /* Need to read this page properly. It contains some of the |
3926 ** range of data that is being read (eOp==0) or written (eOp!=0). | 4173 ** range of data that is being read (eOp==0) or written (eOp!=0). |
3927 */ | 4174 */ |
3928 DbPage *pDbPage; | 4175 #ifdef SQLITE_DIRECT_OVERFLOW_READ |
| 4176 sqlite3_file *fd; |
| 4177 #endif |
3929 int a = amt; | 4178 int a = amt; |
3930 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage); | 4179 if( a + offset > ovflSize ){ |
3931 if( rc==SQLITE_OK ){ | 4180 a = ovflSize - offset; |
3932 aPayload = sqlite3PagerGetData(pDbPage); | 4181 } |
3933 nextPage = get4byte(aPayload); | 4182 |
3934 if( a + offset > ovflSize ){ | 4183 #ifdef SQLITE_DIRECT_OVERFLOW_READ |
3935 a = ovflSize - offset; | 4184 /* If all the following are true: |
| 4185 ** |
| 4186 ** 1) this is a read operation, and |
| 4187 ** 2) data is required from the start of this overflow page, and |
| 4188 ** 3) the database is file-backed, and |
| 4189 ** 4) there is no open write-transaction, and |
| 4190 ** 5) the database is not a WAL database, |
| 4191 ** 6) all data from the page is being read. |
| 4192 ** 7) at least 4 bytes have already been read into the output buffer |
| 4193 ** |
| 4194 ** then data can be read directly from the database file into the |
| 4195 ** output buffer, bypassing the page-cache altogether. This speeds |
| 4196 ** up loading large records that span many overflow pages. |
| 4197 */ |
| 4198 if( (eOp&0x01)==0 /* (1) */ |
| 4199 && offset==0 /* (2) */ |
| 4200 && (bEnd || a==ovflSize) /* (6) */ |
| 4201 && pBt->inTransaction==TRANS_READ /* (4) */ |
| 4202 && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */ |
| 4203 && pBt->pPage1->aData[19]==0x01 /* (5) */ |
| 4204 && &pBuf[-4]>=pBufStart /* (7) */ |
| 4205 ){ |
| 4206 u8 aSave[4]; |
| 4207 u8 *aWrite = &pBuf[-4]; |
| 4208 assert( aWrite>=pBufStart ); /* hence (7) */ |
| 4209 memcpy(aSave, aWrite, 4); |
| 4210 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1)); |
| 4211 nextPage = get4byte(aWrite); |
| 4212 memcpy(aWrite, aSave, 4); |
| 4213 }else |
| 4214 #endif |
| 4215 |
| 4216 { |
| 4217 DbPage *pDbPage; |
| 4218 rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage, |
| 4219 ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0) |
| 4220 ); |
| 4221 if( rc==SQLITE_OK ){ |
| 4222 aPayload = sqlite3PagerGetData(pDbPage); |
| 4223 nextPage = get4byte(aPayload); |
| 4224 rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage); |
| 4225 sqlite3PagerUnref(pDbPage); |
| 4226 offset = 0; |
3936 } | 4227 } |
3937 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage); | |
3938 sqlite3PagerUnref(pDbPage); | |
3939 offset = 0; | |
3940 amt -= a; | |
3941 pBuf += a; | |
3942 } | 4228 } |
| 4229 amt -= a; |
| 4230 pBuf += a; |
3943 } | 4231 } |
3944 } | 4232 } |
3945 } | 4233 } |
3946 | 4234 |
3947 if( rc==SQLITE_OK && amt>0 ){ | 4235 if( rc==SQLITE_OK && amt>0 ){ |
3948 return SQLITE_CORRUPT_BKPT; | 4236 return SQLITE_CORRUPT_BKPT; |
3949 } | 4237 } |
3950 return rc; | 4238 return rc; |
3951 } | 4239 } |
3952 | 4240 |
3953 /* | 4241 /* |
3954 ** Read part of the key associated with cursor pCur. Exactly | 4242 ** Read part of the key associated with cursor pCur. Exactly |
3955 ** "amt" bytes will be transfered into pBuf[]. The transfer | 4243 ** "amt" bytes will be transferred into pBuf[]. The transfer |
3956 ** begins at "offset". | 4244 ** begins at "offset". |
3957 ** | 4245 ** |
3958 ** The caller must ensure that pCur is pointing to a valid row | 4246 ** The caller must ensure that pCur is pointing to a valid row |
3959 ** in the table. | 4247 ** in the table. |
3960 ** | 4248 ** |
3961 ** Return SQLITE_OK on success or an error code if anything goes | 4249 ** Return SQLITE_OK on success or an error code if anything goes |
3962 ** wrong. An error is returned if "offset+amt" is larger than | 4250 ** wrong. An error is returned if "offset+amt" is larger than |
3963 ** the available payload. | 4251 ** the available payload. |
3964 */ | 4252 */ |
3965 int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ | 4253 int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ |
(...skipping 29 matching lines...) Expand all Loading... |
3995 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] ); | 4283 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] ); |
3996 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell ); | 4284 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell ); |
3997 rc = accessPayload(pCur, offset, amt, pBuf, 0); | 4285 rc = accessPayload(pCur, offset, amt, pBuf, 0); |
3998 } | 4286 } |
3999 return rc; | 4287 return rc; |
4000 } | 4288 } |
4001 | 4289 |
4002 /* | 4290 /* |
4003 ** Return a pointer to payload information from the entry that the | 4291 ** Return a pointer to payload information from the entry that the |
4004 ** pCur cursor is pointing to. The pointer is to the beginning of | 4292 ** pCur cursor is pointing to. The pointer is to the beginning of |
4005 ** the key if skipKey==0 and it points to the beginning of data if | 4293 ** the key if index btrees (pPage->intKey==0) and is the data for |
4006 ** skipKey==1. The number of bytes of available key/data is written | 4294 ** table btrees (pPage->intKey==1). The number of bytes of available |
4007 ** into *pAmt. If *pAmt==0, then the value returned will not be | 4295 ** key/data is written into *pAmt. If *pAmt==0, then the value |
4008 ** a valid pointer. | 4296 ** returned will not be a valid pointer. |
4009 ** | 4297 ** |
4010 ** This routine is an optimization. It is common for the entire key | 4298 ** This routine is an optimization. It is common for the entire key |
4011 ** and data to fit on the local page and for there to be no overflow | 4299 ** and data to fit on the local page and for there to be no overflow |
4012 ** pages. When that is so, this routine can be used to access the | 4300 ** pages. When that is so, this routine can be used to access the |
4013 ** key and data without making a copy. If the key and/or data spills | 4301 ** key and data without making a copy. If the key and/or data spills |
4014 ** onto overflow pages, then accessPayload() must be used to reassemble | 4302 ** onto overflow pages, then accessPayload() must be used to reassemble |
4015 ** the key/data and copy it into a preallocated buffer. | 4303 ** the key/data and copy it into a preallocated buffer. |
4016 ** | 4304 ** |
4017 ** The pointer returned by this routine looks directly into the cached | 4305 ** The pointer returned by this routine looks directly into the cached |
4018 ** page of the database. The data might change or move the next time | 4306 ** page of the database. The data might change or move the next time |
4019 ** any btree routine is called. | 4307 ** any btree routine is called. |
4020 */ | 4308 */ |
4021 static const unsigned char *fetchPayload( | 4309 static const void *fetchPayload( |
4022 BtCursor *pCur, /* Cursor pointing to entry to read from */ | 4310 BtCursor *pCur, /* Cursor pointing to entry to read from */ |
4023 int *pAmt, /* Write the number of available bytes here */ | 4311 u32 *pAmt /* Write the number of available bytes here */ |
4024 int skipKey /* read beginning at data if this is true */ | |
4025 ){ | 4312 ){ |
4026 unsigned char *aPayload; | |
4027 MemPage *pPage; | |
4028 u32 nKey; | |
4029 u32 nLocal; | |
4030 | |
4031 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]); | 4313 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]); |
4032 assert( pCur->eState==CURSOR_VALID ); | 4314 assert( pCur->eState==CURSOR_VALID ); |
| 4315 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); |
4033 assert( cursorHoldsMutex(pCur) ); | 4316 assert( cursorHoldsMutex(pCur) ); |
4034 pPage = pCur->apPage[pCur->iPage]; | 4317 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell ); |
4035 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell ); | 4318 assert( pCur->info.nSize>0 ); |
4036 if( NEVER(pCur->info.nSize==0) ){ | 4319 *pAmt = pCur->info.nLocal; |
4037 btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage], | 4320 return (void*)pCur->info.pPayload; |
4038 &pCur->info); | |
4039 } | |
4040 aPayload = pCur->info.pCell; | |
4041 aPayload += pCur->info.nHeader; | |
4042 if( pPage->intKey ){ | |
4043 nKey = 0; | |
4044 }else{ | |
4045 nKey = (int)pCur->info.nKey; | |
4046 } | |
4047 if( skipKey ){ | |
4048 aPayload += nKey; | |
4049 nLocal = pCur->info.nLocal - nKey; | |
4050 }else{ | |
4051 nLocal = pCur->info.nLocal; | |
4052 assert( nLocal<=nKey ); | |
4053 } | |
4054 *pAmt = nLocal; | |
4055 return aPayload; | |
4056 } | 4321 } |
4057 | 4322 |
4058 | 4323 |
4059 /* | 4324 /* |
4060 ** For the entry that cursor pCur is point to, return as | 4325 ** For the entry that cursor pCur is point to, return as |
4061 ** many bytes of the key or data as are available on the local | 4326 ** many bytes of the key or data as are available on the local |
4062 ** b-tree page. Write the number of available bytes into *pAmt. | 4327 ** b-tree page. Write the number of available bytes into *pAmt. |
4063 ** | 4328 ** |
4064 ** The pointer returned is ephemeral. The key/data may move | 4329 ** The pointer returned is ephemeral. The key/data may move |
4065 ** or be destroyed on the next call to any Btree routine, | 4330 ** or be destroyed on the next call to any Btree routine, |
4066 ** including calls from other threads against the same cache. | 4331 ** including calls from other threads against the same cache. |
4067 ** Hence, a mutex on the BtShared should be held prior to calling | 4332 ** Hence, a mutex on the BtShared should be held prior to calling |
4068 ** this routine. | 4333 ** this routine. |
4069 ** | 4334 ** |
4070 ** These routines is used to get quick access to key and data | 4335 ** These routines is used to get quick access to key and data |
4071 ** in the common case where no overflow pages are used. | 4336 ** in the common case where no overflow pages are used. |
4072 */ | 4337 */ |
4073 const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){ | 4338 const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){ |
4074 const void *p = 0; | 4339 return fetchPayload(pCur, pAmt); |
4075 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); | |
4076 assert( cursorHoldsMutex(pCur) ); | |
4077 if( ALWAYS(pCur->eState==CURSOR_VALID) ){ | |
4078 p = (const void*)fetchPayload(pCur, pAmt, 0); | |
4079 } | |
4080 return p; | |
4081 } | 4340 } |
4082 const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){ | 4341 const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){ |
4083 const void *p = 0; | 4342 return fetchPayload(pCur, pAmt); |
4084 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); | |
4085 assert( cursorHoldsMutex(pCur) ); | |
4086 if( ALWAYS(pCur->eState==CURSOR_VALID) ){ | |
4087 p = (const void*)fetchPayload(pCur, pAmt, 1); | |
4088 } | |
4089 return p; | |
4090 } | 4343 } |
4091 | 4344 |
4092 | 4345 |
4093 /* | 4346 /* |
4094 ** Move the cursor down to a new child page. The newPgno argument is the | 4347 ** Move the cursor down to a new child page. The newPgno argument is the |
4095 ** page number of the child page to move to. | 4348 ** page number of the child page to move to. |
4096 ** | 4349 ** |
4097 ** This function returns SQLITE_CORRUPT if the page-header flags field of | 4350 ** This function returns SQLITE_CORRUPT if the page-header flags field of |
4098 ** the new child page does not match the flags field of the parent (i.e. | 4351 ** the new child page does not match the flags field of the parent (i.e. |
4099 ** if an intkey page appears to be the parent of a non-intkey page, or | 4352 ** if an intkey page appears to be the parent of a non-intkey page, or |
4100 ** vice-versa). | 4353 ** vice-versa). |
4101 */ | 4354 */ |
4102 static int moveToChild(BtCursor *pCur, u32 newPgno){ | 4355 static int moveToChild(BtCursor *pCur, u32 newPgno){ |
4103 int rc; | 4356 int rc; |
4104 int i = pCur->iPage; | 4357 int i = pCur->iPage; |
4105 MemPage *pNewPage; | 4358 MemPage *pNewPage; |
4106 BtShared *pBt = pCur->pBt; | 4359 BtShared *pBt = pCur->pBt; |
4107 | 4360 |
4108 assert( cursorHoldsMutex(pCur) ); | 4361 assert( cursorHoldsMutex(pCur) ); |
4109 assert( pCur->eState==CURSOR_VALID ); | 4362 assert( pCur->eState==CURSOR_VALID ); |
4110 assert( pCur->iPage<BTCURSOR_MAX_DEPTH ); | 4363 assert( pCur->iPage<BTCURSOR_MAX_DEPTH ); |
| 4364 assert( pCur->iPage>=0 ); |
4111 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){ | 4365 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){ |
4112 return SQLITE_CORRUPT_BKPT; | 4366 return SQLITE_CORRUPT_BKPT; |
4113 } | 4367 } |
4114 rc = getAndInitPage(pBt, newPgno, &pNewPage); | 4368 rc = getAndInitPage(pBt, newPgno, &pNewPage, |
| 4369 (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0); |
4115 if( rc ) return rc; | 4370 if( rc ) return rc; |
4116 pCur->apPage[i+1] = pNewPage; | 4371 pCur->apPage[i+1] = pNewPage; |
4117 pCur->aiIdx[i+1] = 0; | 4372 pCur->aiIdx[i+1] = 0; |
4118 pCur->iPage++; | 4373 pCur->iPage++; |
4119 | 4374 |
4120 pCur->info.nSize = 0; | 4375 pCur->info.nSize = 0; |
4121 pCur->validNKey = 0; | 4376 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); |
4122 if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){ | 4377 if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){ |
4123 return SQLITE_CORRUPT_BKPT; | 4378 return SQLITE_CORRUPT_BKPT; |
4124 } | 4379 } |
4125 return SQLITE_OK; | 4380 return SQLITE_OK; |
4126 } | 4381 } |
4127 | 4382 |
4128 #ifndef NDEBUG | 4383 #if 0 |
4129 /* | 4384 /* |
4130 ** Page pParent is an internal (non-leaf) tree page. This function | 4385 ** Page pParent is an internal (non-leaf) tree page. This function |
4131 ** asserts that page number iChild is the left-child if the iIdx'th | 4386 ** asserts that page number iChild is the left-child if the iIdx'th |
4132 ** cell in page pParent. Or, if iIdx is equal to the total number of | 4387 ** cell in page pParent. Or, if iIdx is equal to the total number of |
4133 ** cells in pParent, that page number iChild is the right-child of | 4388 ** cells in pParent, that page number iChild is the right-child of |
4134 ** the page. | 4389 ** the page. |
4135 */ | 4390 */ |
4136 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){ | 4391 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){ |
4137 assert( iIdx<=pParent->nCell ); | 4392 assert( iIdx<=pParent->nCell ); |
4138 if( iIdx==pParent->nCell ){ | 4393 if( iIdx==pParent->nCell ){ |
(...skipping 12 matching lines...) Expand all Loading... |
4151 ** pCur->idx is set to the cell index that contains the pointer | 4406 ** pCur->idx is set to the cell index that contains the pointer |
4152 ** to the page we are coming from. If we are coming from the | 4407 ** to the page we are coming from. If we are coming from the |
4153 ** right-most child page then pCur->idx is set to one more than | 4408 ** right-most child page then pCur->idx is set to one more than |
4154 ** the largest cell index. | 4409 ** the largest cell index. |
4155 */ | 4410 */ |
4156 static void moveToParent(BtCursor *pCur){ | 4411 static void moveToParent(BtCursor *pCur){ |
4157 assert( cursorHoldsMutex(pCur) ); | 4412 assert( cursorHoldsMutex(pCur) ); |
4158 assert( pCur->eState==CURSOR_VALID ); | 4413 assert( pCur->eState==CURSOR_VALID ); |
4159 assert( pCur->iPage>0 ); | 4414 assert( pCur->iPage>0 ); |
4160 assert( pCur->apPage[pCur->iPage] ); | 4415 assert( pCur->apPage[pCur->iPage] ); |
| 4416 |
| 4417 /* UPDATE: It is actually possible for the condition tested by the assert |
| 4418 ** below to be untrue if the database file is corrupt. This can occur if |
| 4419 ** one cursor has modified page pParent while a reference to it is held |
| 4420 ** by a second cursor. Which can only happen if a single page is linked |
| 4421 ** into more than one b-tree structure in a corrupt database. */ |
| 4422 #if 0 |
4161 assertParentIndex( | 4423 assertParentIndex( |
4162 pCur->apPage[pCur->iPage-1], | 4424 pCur->apPage[pCur->iPage-1], |
4163 pCur->aiIdx[pCur->iPage-1], | 4425 pCur->aiIdx[pCur->iPage-1], |
4164 pCur->apPage[pCur->iPage]->pgno | 4426 pCur->apPage[pCur->iPage]->pgno |
4165 ); | 4427 ); |
| 4428 #endif |
| 4429 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell ); |
| 4430 |
4166 releasePage(pCur->apPage[pCur->iPage]); | 4431 releasePage(pCur->apPage[pCur->iPage]); |
4167 pCur->iPage--; | 4432 pCur->iPage--; |
4168 pCur->info.nSize = 0; | 4433 pCur->info.nSize = 0; |
4169 pCur->validNKey = 0; | 4434 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); |
4170 } | 4435 } |
4171 | 4436 |
4172 /* | 4437 /* |
4173 ** Move the cursor to point to the root page of its b-tree structure. | 4438 ** Move the cursor to point to the root page of its b-tree structure. |
4174 ** | 4439 ** |
4175 ** If the table has a virtual root page, then the cursor is moved to point | 4440 ** If the table has a virtual root page, then the cursor is moved to point |
4176 ** to the virtual root page instead of the actual root page. A table has a | 4441 ** to the virtual root page instead of the actual root page. A table has a |
4177 ** virtual root page when the actual root page contains no cells and a | 4442 ** virtual root page when the actual root page contains no cells and a |
4178 ** single child page. This can only happen with the table rooted at page 1. | 4443 ** single child page. This can only happen with the table rooted at page 1. |
4179 ** | 4444 ** |
4180 ** If the b-tree structure is empty, the cursor state is set to | 4445 ** If the b-tree structure is empty, the cursor state is set to |
4181 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first | 4446 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first |
4182 ** cell located on the root (or virtual root) page and the cursor state | 4447 ** cell located on the root (or virtual root) page and the cursor state |
4183 ** is set to CURSOR_VALID. | 4448 ** is set to CURSOR_VALID. |
4184 ** | 4449 ** |
4185 ** If this function returns successfully, it may be assumed that the | 4450 ** If this function returns successfully, it may be assumed that the |
4186 ** page-header flags indicate that the [virtual] root-page is the expected | 4451 ** page-header flags indicate that the [virtual] root-page is the expected |
4187 ** kind of b-tree page (i.e. if when opening the cursor the caller did not | 4452 ** kind of b-tree page (i.e. if when opening the cursor the caller did not |
4188 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D, | 4453 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D, |
4189 ** indicating a table b-tree, or if the caller did specify a KeyInfo | 4454 ** indicating a table b-tree, or if the caller did specify a KeyInfo |
4190 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index | 4455 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index |
4191 ** b-tree). | 4456 ** b-tree). |
4192 */ | 4457 */ |
4193 static int moveToRoot(BtCursor *pCur){ | 4458 static int moveToRoot(BtCursor *pCur){ |
4194 MemPage *pRoot; | 4459 MemPage *pRoot; |
4195 int rc = SQLITE_OK; | 4460 int rc = SQLITE_OK; |
4196 Btree *p = pCur->pBtree; | |
4197 BtShared *pBt = p->pBt; | |
4198 | 4461 |
4199 assert( cursorHoldsMutex(pCur) ); | 4462 assert( cursorHoldsMutex(pCur) ); |
4200 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK ); | 4463 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK ); |
4201 assert( CURSOR_VALID < CURSOR_REQUIRESEEK ); | 4464 assert( CURSOR_VALID < CURSOR_REQUIRESEEK ); |
4202 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK ); | 4465 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK ); |
4203 if( pCur->eState>=CURSOR_REQUIRESEEK ){ | 4466 if( pCur->eState>=CURSOR_REQUIRESEEK ){ |
4204 if( pCur->eState==CURSOR_FAULT ){ | 4467 if( pCur->eState==CURSOR_FAULT ){ |
4205 assert( pCur->skipNext!=SQLITE_OK ); | 4468 assert( pCur->skipNext!=SQLITE_OK ); |
4206 return pCur->skipNext; | 4469 return pCur->skipNext; |
4207 } | 4470 } |
4208 sqlite3BtreeClearCursor(pCur); | 4471 sqlite3BtreeClearCursor(pCur); |
4209 } | 4472 } |
4210 | 4473 |
4211 if( pCur->iPage>=0 ){ | 4474 if( pCur->iPage>=0 ){ |
4212 int i; | 4475 while( pCur->iPage ) releasePage(pCur->apPage[pCur->iPage--]); |
4213 for(i=1; i<=pCur->iPage; i++){ | 4476 }else if( pCur->pgnoRoot==0 ){ |
4214 releasePage(pCur->apPage[i]); | 4477 pCur->eState = CURSOR_INVALID; |
4215 } | 4478 return SQLITE_OK; |
4216 pCur->iPage = 0; | |
4217 }else{ | 4479 }else{ |
4218 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]); | 4480 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0], |
| 4481 (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0); |
4219 if( rc!=SQLITE_OK ){ | 4482 if( rc!=SQLITE_OK ){ |
4220 pCur->eState = CURSOR_INVALID; | 4483 pCur->eState = CURSOR_INVALID; |
4221 return rc; | 4484 return rc; |
4222 } | 4485 } |
4223 pCur->iPage = 0; | 4486 pCur->iPage = 0; |
4224 | |
4225 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor | |
4226 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is | |
4227 ** NULL, the caller expects a table b-tree. If this is not the case, | |
4228 ** return an SQLITE_CORRUPT error. */ | |
4229 assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 ); | |
4230 if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){ | |
4231 return SQLITE_CORRUPT_BKPT; | |
4232 } | |
4233 } | 4487 } |
4234 | |
4235 /* Assert that the root page is of the correct type. This must be the | |
4236 ** case as the call to this function that loaded the root-page (either | |
4237 ** this call or a previous invocation) would have detected corruption | |
4238 ** if the assumption were not true, and it is not possible for the flags | |
4239 ** byte to have been modified while this cursor is holding a reference | |
4240 ** to the page. */ | |
4241 pRoot = pCur->apPage[0]; | 4488 pRoot = pCur->apPage[0]; |
4242 assert( pRoot->pgno==pCur->pgnoRoot ); | 4489 assert( pRoot->pgno==pCur->pgnoRoot ); |
4243 assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey ); | 4490 |
| 4491 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor |
| 4492 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is |
| 4493 ** NULL, the caller expects a table b-tree. If this is not the case, |
| 4494 ** return an SQLITE_CORRUPT error. |
| 4495 ** |
| 4496 ** Earlier versions of SQLite assumed that this test could not fail |
| 4497 ** if the root page was already loaded when this function was called (i.e. |
| 4498 ** if pCur->iPage>=0). But this is not so if the database is corrupted |
| 4499 ** in such a way that page pRoot is linked into a second b-tree table |
| 4500 ** (or the freelist). */ |
| 4501 assert( pRoot->intKey==1 || pRoot->intKey==0 ); |
| 4502 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){ |
| 4503 return SQLITE_CORRUPT_BKPT; |
| 4504 } |
4244 | 4505 |
4245 pCur->aiIdx[0] = 0; | 4506 pCur->aiIdx[0] = 0; |
4246 pCur->info.nSize = 0; | 4507 pCur->info.nSize = 0; |
4247 pCur->atLast = 0; | 4508 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl); |
4248 pCur->validNKey = 0; | |
4249 | 4509 |
4250 if( pRoot->nCell==0 && !pRoot->leaf ){ | 4510 if( pRoot->nCell>0 ){ |
| 4511 pCur->eState = CURSOR_VALID; |
| 4512 }else if( !pRoot->leaf ){ |
4251 Pgno subpage; | 4513 Pgno subpage; |
4252 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT; | 4514 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT; |
4253 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]); | 4515 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]); |
4254 pCur->eState = CURSOR_VALID; | 4516 pCur->eState = CURSOR_VALID; |
4255 rc = moveToChild(pCur, subpage); | 4517 rc = moveToChild(pCur, subpage); |
4256 }else{ | 4518 }else{ |
4257 pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID); | 4519 pCur->eState = CURSOR_INVALID; |
4258 } | 4520 } |
4259 return rc; | 4521 return rc; |
4260 } | 4522 } |
4261 | 4523 |
4262 /* | 4524 /* |
4263 ** Move the cursor down to the left-most leaf entry beneath the | 4525 ** Move the cursor down to the left-most leaf entry beneath the |
4264 ** entry to which it is currently pointing. | 4526 ** entry to which it is currently pointing. |
4265 ** | 4527 ** |
4266 ** The left-most leaf is the one with the smallest key - the first | 4528 ** The left-most leaf is the one with the smallest key - the first |
4267 ** in ascending order. | 4529 ** in ascending order. |
(...skipping 23 matching lines...) Expand all Loading... |
4291 ** The right-most entry is the one with the largest key - the last | 4553 ** The right-most entry is the one with the largest key - the last |
4292 ** key in ascending order. | 4554 ** key in ascending order. |
4293 */ | 4555 */ |
4294 static int moveToRightmost(BtCursor *pCur){ | 4556 static int moveToRightmost(BtCursor *pCur){ |
4295 Pgno pgno; | 4557 Pgno pgno; |
4296 int rc = SQLITE_OK; | 4558 int rc = SQLITE_OK; |
4297 MemPage *pPage = 0; | 4559 MemPage *pPage = 0; |
4298 | 4560 |
4299 assert( cursorHoldsMutex(pCur) ); | 4561 assert( cursorHoldsMutex(pCur) ); |
4300 assert( pCur->eState==CURSOR_VALID ); | 4562 assert( pCur->eState==CURSOR_VALID ); |
4301 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){ | 4563 while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){ |
4302 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); | 4564 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); |
4303 pCur->aiIdx[pCur->iPage] = pPage->nCell; | 4565 pCur->aiIdx[pCur->iPage] = pPage->nCell; |
4304 rc = moveToChild(pCur, pgno); | 4566 rc = moveToChild(pCur, pgno); |
| 4567 if( rc ) return rc; |
4305 } | 4568 } |
4306 if( rc==SQLITE_OK ){ | 4569 pCur->aiIdx[pCur->iPage] = pPage->nCell-1; |
4307 pCur->aiIdx[pCur->iPage] = pPage->nCell-1; | 4570 assert( pCur->info.nSize==0 ); |
4308 pCur->info.nSize = 0; | 4571 assert( (pCur->curFlags & BTCF_ValidNKey)==0 ); |
4309 pCur->validNKey = 0; | 4572 return SQLITE_OK; |
4310 } | |
4311 return rc; | |
4312 } | 4573 } |
4313 | 4574 |
4314 /* Move the cursor to the first entry in the table. Return SQLITE_OK | 4575 /* Move the cursor to the first entry in the table. Return SQLITE_OK |
4315 ** on success. Set *pRes to 0 if the cursor actually points to something | 4576 ** on success. Set *pRes to 0 if the cursor actually points to something |
4316 ** or set *pRes to 1 if the table is empty. | 4577 ** or set *pRes to 1 if the table is empty. |
4317 */ | 4578 */ |
4318 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){ | 4579 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){ |
4319 int rc; | 4580 int rc; |
4320 | 4581 |
4321 assert( cursorHoldsMutex(pCur) ); | 4582 assert( cursorHoldsMutex(pCur) ); |
4322 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); | 4583 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); |
4323 rc = moveToRoot(pCur); | 4584 rc = moveToRoot(pCur); |
4324 if( rc==SQLITE_OK ){ | 4585 if( rc==SQLITE_OK ){ |
4325 if( pCur->eState==CURSOR_INVALID ){ | 4586 if( pCur->eState==CURSOR_INVALID ){ |
4326 assert( pCur->apPage[pCur->iPage]->nCell==0 ); | 4587 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); |
4327 *pRes = 1; | 4588 *pRes = 1; |
4328 }else{ | 4589 }else{ |
4329 assert( pCur->apPage[pCur->iPage]->nCell>0 ); | 4590 assert( pCur->apPage[pCur->iPage]->nCell>0 ); |
4330 *pRes = 0; | 4591 *pRes = 0; |
4331 rc = moveToLeftmost(pCur); | 4592 rc = moveToLeftmost(pCur); |
4332 } | 4593 } |
4333 } | 4594 } |
4334 return rc; | 4595 return rc; |
4335 } | 4596 } |
4336 | 4597 |
4337 /* Move the cursor to the last entry in the table. Return SQLITE_OK | 4598 /* Move the cursor to the last entry in the table. Return SQLITE_OK |
4338 ** on success. Set *pRes to 0 if the cursor actually points to something | 4599 ** on success. Set *pRes to 0 if the cursor actually points to something |
4339 ** or set *pRes to 1 if the table is empty. | 4600 ** or set *pRes to 1 if the table is empty. |
4340 */ | 4601 */ |
4341 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){ | 4602 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){ |
4342 int rc; | 4603 int rc; |
4343 | 4604 |
4344 assert( cursorHoldsMutex(pCur) ); | 4605 assert( cursorHoldsMutex(pCur) ); |
4345 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); | 4606 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); |
4346 | 4607 |
4347 /* If the cursor already points to the last entry, this is a no-op. */ | 4608 /* If the cursor already points to the last entry, this is a no-op. */ |
4348 if( CURSOR_VALID==pCur->eState && pCur->atLast ){ | 4609 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){ |
4349 #ifdef SQLITE_DEBUG | 4610 #ifdef SQLITE_DEBUG |
4350 /* This block serves to assert() that the cursor really does point | 4611 /* This block serves to assert() that the cursor really does point |
4351 ** to the last entry in the b-tree. */ | 4612 ** to the last entry in the b-tree. */ |
4352 int ii; | 4613 int ii; |
4353 for(ii=0; ii<pCur->iPage; ii++){ | 4614 for(ii=0; ii<pCur->iPage; ii++){ |
4354 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell ); | 4615 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell ); |
4355 } | 4616 } |
4356 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 ); | 4617 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 ); |
4357 assert( pCur->apPage[pCur->iPage]->leaf ); | 4618 assert( pCur->apPage[pCur->iPage]->leaf ); |
4358 #endif | 4619 #endif |
4359 return SQLITE_OK; | 4620 return SQLITE_OK; |
4360 } | 4621 } |
4361 | 4622 |
4362 rc = moveToRoot(pCur); | 4623 rc = moveToRoot(pCur); |
4363 if( rc==SQLITE_OK ){ | 4624 if( rc==SQLITE_OK ){ |
4364 if( CURSOR_INVALID==pCur->eState ){ | 4625 if( CURSOR_INVALID==pCur->eState ){ |
4365 assert( pCur->apPage[pCur->iPage]->nCell==0 ); | 4626 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); |
4366 *pRes = 1; | 4627 *pRes = 1; |
4367 }else{ | 4628 }else{ |
4368 assert( pCur->eState==CURSOR_VALID ); | 4629 assert( pCur->eState==CURSOR_VALID ); |
4369 *pRes = 0; | 4630 *pRes = 0; |
4370 rc = moveToRightmost(pCur); | 4631 rc = moveToRightmost(pCur); |
4371 pCur->atLast = rc==SQLITE_OK ?1:0; | 4632 if( rc==SQLITE_OK ){ |
| 4633 pCur->curFlags |= BTCF_AtLast; |
| 4634 }else{ |
| 4635 pCur->curFlags &= ~BTCF_AtLast; |
| 4636 } |
| 4637 |
4372 } | 4638 } |
4373 } | 4639 } |
4374 return rc; | 4640 return rc; |
4375 } | 4641 } |
4376 | 4642 |
4377 /* Move the cursor so that it points to an entry near the key | 4643 /* Move the cursor so that it points to an entry near the key |
4378 ** specified by pIdxKey or intKey. Return a success code. | 4644 ** specified by pIdxKey or intKey. Return a success code. |
4379 ** | 4645 ** |
4380 ** For INTKEY tables, the intKey parameter is used. pIdxKey | 4646 ** For INTKEY tables, the intKey parameter is used. pIdxKey |
4381 ** must be NULL. For index tables, pIdxKey is used and intKey | 4647 ** must be NULL. For index tables, pIdxKey is used and intKey |
(...skipping 21 matching lines...) Expand all Loading... |
4403 ** | 4669 ** |
4404 */ | 4670 */ |
4405 int sqlite3BtreeMovetoUnpacked( | 4671 int sqlite3BtreeMovetoUnpacked( |
4406 BtCursor *pCur, /* The cursor to be moved */ | 4672 BtCursor *pCur, /* The cursor to be moved */ |
4407 UnpackedRecord *pIdxKey, /* Unpacked index key */ | 4673 UnpackedRecord *pIdxKey, /* Unpacked index key */ |
4408 i64 intKey, /* The table key */ | 4674 i64 intKey, /* The table key */ |
4409 int biasRight, /* If true, bias the search to the high end */ | 4675 int biasRight, /* If true, bias the search to the high end */ |
4410 int *pRes /* Write search results here */ | 4676 int *pRes /* Write search results here */ |
4411 ){ | 4677 ){ |
4412 int rc; | 4678 int rc; |
| 4679 RecordCompare xRecordCompare; |
4413 | 4680 |
4414 assert( cursorHoldsMutex(pCur) ); | 4681 assert( cursorHoldsMutex(pCur) ); |
4415 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); | 4682 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); |
4416 assert( pRes ); | 4683 assert( pRes ); |
4417 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) ); | 4684 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) ); |
4418 | 4685 |
4419 /* If the cursor is already positioned at the point we are trying | 4686 /* If the cursor is already positioned at the point we are trying |
4420 ** to move to, then just return without doing any work */ | 4687 ** to move to, then just return without doing any work */ |
4421 if( pCur->eState==CURSOR_VALID && pCur->validNKey | 4688 if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0 |
4422 && pCur->apPage[0]->intKey | 4689 && pCur->apPage[0]->intKey |
4423 ){ | 4690 ){ |
4424 if( pCur->info.nKey==intKey ){ | 4691 if( pCur->info.nKey==intKey ){ |
4425 *pRes = 0; | 4692 *pRes = 0; |
4426 return SQLITE_OK; | 4693 return SQLITE_OK; |
4427 } | 4694 } |
4428 if( pCur->atLast && pCur->info.nKey<intKey ){ | 4695 if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){ |
4429 *pRes = -1; | 4696 *pRes = -1; |
4430 return SQLITE_OK; | 4697 return SQLITE_OK; |
4431 } | 4698 } |
4432 } | 4699 } |
4433 | 4700 |
| 4701 if( pIdxKey ){ |
| 4702 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey); |
| 4703 pIdxKey->errCode = 0; |
| 4704 assert( pIdxKey->default_rc==1 |
| 4705 || pIdxKey->default_rc==0 |
| 4706 || pIdxKey->default_rc==-1 |
| 4707 ); |
| 4708 }else{ |
| 4709 xRecordCompare = 0; /* All keys are integers */ |
| 4710 } |
| 4711 |
4434 rc = moveToRoot(pCur); | 4712 rc = moveToRoot(pCur); |
4435 if( rc ){ | 4713 if( rc ){ |
4436 return rc; | 4714 return rc; |
4437 } | 4715 } |
4438 assert( pCur->apPage[pCur->iPage] ); | 4716 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] ); |
4439 assert( pCur->apPage[pCur->iPage]->isInit ); | 4717 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit ); |
4440 assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID ); | 4718 assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 ); |
4441 if( pCur->eState==CURSOR_INVALID ){ | 4719 if( pCur->eState==CURSOR_INVALID ){ |
4442 *pRes = -1; | 4720 *pRes = -1; |
4443 assert( pCur->apPage[pCur->iPage]->nCell==0 ); | 4721 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 ); |
4444 return SQLITE_OK; | 4722 return SQLITE_OK; |
4445 } | 4723 } |
4446 assert( pCur->apPage[0]->intKey || pIdxKey ); | 4724 assert( pCur->apPage[0]->intKey || pIdxKey ); |
4447 for(;;){ | 4725 for(;;){ |
4448 int lwr, upr; | 4726 int lwr, upr, idx, c; |
4449 Pgno chldPg; | 4727 Pgno chldPg; |
4450 MemPage *pPage = pCur->apPage[pCur->iPage]; | 4728 MemPage *pPage = pCur->apPage[pCur->iPage]; |
4451 int c; | 4729 u8 *pCell; /* Pointer to current cell in pPage */ |
4452 | 4730 |
4453 /* pPage->nCell must be greater than zero. If this is the root-page | 4731 /* pPage->nCell must be greater than zero. If this is the root-page |
4454 ** the cursor would have been INVALID above and this for(;;) loop | 4732 ** the cursor would have been INVALID above and this for(;;) loop |
4455 ** not run. If this is not the root-page, then the moveToChild() routine | 4733 ** not run. If this is not the root-page, then the moveToChild() routine |
4456 ** would have already detected db corruption. Similarly, pPage must | 4734 ** would have already detected db corruption. Similarly, pPage must |
4457 ** be the right kind (index or table) of b-tree page. Otherwise | 4735 ** be the right kind (index or table) of b-tree page. Otherwise |
4458 ** a moveToChild() or moveToRoot() call would have detected corruption. */ | 4736 ** a moveToChild() or moveToRoot() call would have detected corruption. */ |
4459 assert( pPage->nCell>0 ); | 4737 assert( pPage->nCell>0 ); |
4460 assert( pPage->intKey==(pIdxKey==0) ); | 4738 assert( pPage->intKey==(pIdxKey==0) ); |
4461 lwr = 0; | 4739 lwr = 0; |
4462 upr = pPage->nCell-1; | 4740 upr = pPage->nCell-1; |
4463 if( biasRight ){ | 4741 assert( biasRight==0 || biasRight==1 ); |
4464 pCur->aiIdx[pCur->iPage] = (u16)upr; | 4742 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */ |
4465 }else{ | 4743 pCur->aiIdx[pCur->iPage] = (u16)idx; |
4466 pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2); | 4744 if( xRecordCompare==0 ){ |
4467 } | 4745 for(;;){ |
4468 for(;;){ | |
4469 int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */ | |
4470 u8 *pCell; /* Pointer to current cell in pPage */ | |
4471 | |
4472 pCur->info.nSize = 0; | |
4473 pCell = findCell(pPage, idx) + pPage->childPtrSize; | |
4474 if( pPage->intKey ){ | |
4475 i64 nCellKey; | 4746 i64 nCellKey; |
4476 if( pPage->hasData ){ | 4747 pCell = findCell(pPage, idx) + pPage->childPtrSize; |
4477 u32 dummy; | 4748 if( pPage->intKeyLeaf ){ |
4478 pCell += getVarint32(pCell, dummy); | 4749 while( 0x80 <= *(pCell++) ){ |
| 4750 if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT; |
| 4751 } |
4479 } | 4752 } |
4480 getVarint(pCell, (u64*)&nCellKey); | 4753 getVarint(pCell, (u64*)&nCellKey); |
4481 if( nCellKey==intKey ){ | 4754 if( nCellKey<intKey ){ |
4482 c = 0; | 4755 lwr = idx+1; |
4483 }else if( nCellKey<intKey ){ | 4756 if( lwr>upr ){ c = -1; break; } |
4484 c = -1; | 4757 }else if( nCellKey>intKey ){ |
| 4758 upr = idx-1; |
| 4759 if( lwr>upr ){ c = +1; break; } |
4485 }else{ | 4760 }else{ |
4486 assert( nCellKey>intKey ); | 4761 assert( nCellKey==intKey ); |
4487 c = +1; | 4762 pCur->curFlags |= BTCF_ValidNKey; |
| 4763 pCur->info.nKey = nCellKey; |
| 4764 pCur->aiIdx[pCur->iPage] = (u16)idx; |
| 4765 if( !pPage->leaf ){ |
| 4766 lwr = idx; |
| 4767 goto moveto_next_layer; |
| 4768 }else{ |
| 4769 *pRes = 0; |
| 4770 rc = SQLITE_OK; |
| 4771 goto moveto_finish; |
| 4772 } |
4488 } | 4773 } |
4489 pCur->validNKey = 1; | 4774 assert( lwr+upr>=0 ); |
4490 pCur->info.nKey = nCellKey; | 4775 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */ |
4491 }else{ | 4776 } |
| 4777 }else{ |
| 4778 for(;;){ |
| 4779 int nCell; |
| 4780 pCell = findCell(pPage, idx) + pPage->childPtrSize; |
| 4781 |
4492 /* The maximum supported page-size is 65536 bytes. This means that | 4782 /* The maximum supported page-size is 65536 bytes. This means that |
4493 ** the maximum number of record bytes stored on an index B-Tree | 4783 ** the maximum number of record bytes stored on an index B-Tree |
4494 ** page is less than 16384 bytes and may be stored as a 2-byte | 4784 ** page is less than 16384 bytes and may be stored as a 2-byte |
4495 ** varint. This information is used to attempt to avoid parsing | 4785 ** varint. This information is used to attempt to avoid parsing |
4496 ** the entire cell by checking for the cases where the record is | 4786 ** the entire cell by checking for the cases where the record is |
4497 ** stored entirely within the b-tree page by inspecting the first | 4787 ** stored entirely within the b-tree page by inspecting the first |
4498 ** 2 bytes of the cell. | 4788 ** 2 bytes of the cell. |
4499 */ | 4789 */ |
4500 int nCell = pCell[0]; | 4790 nCell = pCell[0]; |
4501 if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){ | 4791 if( nCell<=pPage->max1bytePayload ){ |
4502 /* This branch runs if the record-size field of the cell is a | 4792 /* This branch runs if the record-size field of the cell is a |
4503 ** single byte varint and the record fits entirely on the main | 4793 ** single byte varint and the record fits entirely on the main |
4504 ** b-tree page. */ | 4794 ** b-tree page. */ |
4505 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey); | 4795 testcase( pCell+nCell+1==pPage->aDataEnd ); |
| 4796 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey); |
4506 }else if( !(pCell[1] & 0x80) | 4797 }else if( !(pCell[1] & 0x80) |
4507 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal | 4798 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal |
4508 ){ | 4799 ){ |
4509 /* The record-size field is a 2 byte varint and the record | 4800 /* The record-size field is a 2 byte varint and the record |
4510 ** fits entirely on the main b-tree page. */ | 4801 ** fits entirely on the main b-tree page. */ |
4511 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey); | 4802 testcase( pCell+nCell+2==pPage->aDataEnd ); |
| 4803 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey); |
4512 }else{ | 4804 }else{ |
4513 /* The record flows over onto one or more overflow pages. In | 4805 /* The record flows over onto one or more overflow pages. In |
4514 ** this case the whole cell needs to be parsed, a buffer allocated | 4806 ** this case the whole cell needs to be parsed, a buffer allocated |
4515 ** and accessPayload() used to retrieve the record into the | 4807 ** and accessPayload() used to retrieve the record into the |
4516 ** buffer before VdbeRecordCompare() can be called. */ | 4808 ** buffer before VdbeRecordCompare() can be called. */ |
4517 void *pCellKey; | 4809 void *pCellKey; |
4518 u8 * const pCellBody = pCell - pPage->childPtrSize; | 4810 u8 * const pCellBody = pCell - pPage->childPtrSize; |
4519 btreeParseCellPtr(pPage, pCellBody, &pCur->info); | 4811 btreeParseCellPtr(pPage, pCellBody, &pCur->info); |
4520 nCell = (int)pCur->info.nKey; | 4812 nCell = (int)pCur->info.nKey; |
4521 pCellKey = sqlite3Malloc( nCell ); | 4813 pCellKey = sqlite3Malloc( nCell ); |
4522 if( pCellKey==0 ){ | 4814 if( pCellKey==0 ){ |
4523 rc = SQLITE_NOMEM; | 4815 rc = SQLITE_NOMEM; |
4524 goto moveto_finish; | 4816 goto moveto_finish; |
4525 } | 4817 } |
4526 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0); | 4818 pCur->aiIdx[pCur->iPage] = (u16)idx; |
| 4819 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2); |
4527 if( rc ){ | 4820 if( rc ){ |
4528 sqlite3_free(pCellKey); | 4821 sqlite3_free(pCellKey); |
4529 goto moveto_finish; | 4822 goto moveto_finish; |
4530 } | 4823 } |
4531 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey); | 4824 c = xRecordCompare(nCell, pCellKey, pIdxKey); |
4532 sqlite3_free(pCellKey); | 4825 sqlite3_free(pCellKey); |
4533 } | 4826 } |
4534 } | 4827 assert( |
4535 if( c==0 ){ | 4828 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0) |
4536 if( pPage->intKey && !pPage->leaf ){ | 4829 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed) |
4537 lwr = idx; | 4830 ); |
4538 upr = lwr - 1; | 4831 if( c<0 ){ |
4539 break; | 4832 lwr = idx+1; |
| 4833 }else if( c>0 ){ |
| 4834 upr = idx-1; |
4540 }else{ | 4835 }else{ |
| 4836 assert( c==0 ); |
4541 *pRes = 0; | 4837 *pRes = 0; |
4542 rc = SQLITE_OK; | 4838 rc = SQLITE_OK; |
| 4839 pCur->aiIdx[pCur->iPage] = (u16)idx; |
| 4840 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT; |
4543 goto moveto_finish; | 4841 goto moveto_finish; |
4544 } | 4842 } |
| 4843 if( lwr>upr ) break; |
| 4844 assert( lwr+upr>=0 ); |
| 4845 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */ |
4545 } | 4846 } |
4546 if( c<0 ){ | |
4547 lwr = idx+1; | |
4548 }else{ | |
4549 upr = idx-1; | |
4550 } | |
4551 if( lwr>upr ){ | |
4552 break; | |
4553 } | |
4554 pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2); | |
4555 } | 4847 } |
4556 assert( lwr==upr+1 ); | 4848 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) ); |
4557 assert( pPage->isInit ); | 4849 assert( pPage->isInit ); |
4558 if( pPage->leaf ){ | 4850 if( pPage->leaf ){ |
4559 chldPg = 0; | 4851 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell ); |
4560 }else if( lwr>=pPage->nCell ){ | 4852 pCur->aiIdx[pCur->iPage] = (u16)idx; |
| 4853 *pRes = c; |
| 4854 rc = SQLITE_OK; |
| 4855 goto moveto_finish; |
| 4856 } |
| 4857 moveto_next_layer: |
| 4858 if( lwr>=pPage->nCell ){ |
4561 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]); | 4859 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]); |
4562 }else{ | 4860 }else{ |
4563 chldPg = get4byte(findCell(pPage, lwr)); | 4861 chldPg = get4byte(findCell(pPage, lwr)); |
4564 } | 4862 } |
4565 if( chldPg==0 ){ | |
4566 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell ); | |
4567 *pRes = c; | |
4568 rc = SQLITE_OK; | |
4569 goto moveto_finish; | |
4570 } | |
4571 pCur->aiIdx[pCur->iPage] = (u16)lwr; | 4863 pCur->aiIdx[pCur->iPage] = (u16)lwr; |
4572 pCur->info.nSize = 0; | |
4573 pCur->validNKey = 0; | |
4574 rc = moveToChild(pCur, chldPg); | 4864 rc = moveToChild(pCur, chldPg); |
4575 if( rc ) goto moveto_finish; | 4865 if( rc ) break; |
4576 } | 4866 } |
4577 moveto_finish: | 4867 moveto_finish: |
| 4868 pCur->info.nSize = 0; |
| 4869 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); |
4578 return rc; | 4870 return rc; |
4579 } | 4871 } |
4580 | 4872 |
4581 | 4873 |
4582 /* | 4874 /* |
4583 ** Return TRUE if the cursor is not pointing at an entry of the table. | 4875 ** Return TRUE if the cursor is not pointing at an entry of the table. |
4584 ** | 4876 ** |
4585 ** TRUE will be returned after a call to sqlite3BtreeNext() moves | 4877 ** TRUE will be returned after a call to sqlite3BtreeNext() moves |
4586 ** past the last entry in the table or sqlite3BtreePrev() moves past | 4878 ** past the last entry in the table or sqlite3BtreePrev() moves past |
4587 ** the first entry. TRUE is also returned if the table is empty. | 4879 ** the first entry. TRUE is also returned if the table is empty. |
4588 */ | 4880 */ |
4589 int sqlite3BtreeEof(BtCursor *pCur){ | 4881 int sqlite3BtreeEof(BtCursor *pCur){ |
4590 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries | 4882 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries |
4591 ** have been deleted? This API will need to change to return an error code | 4883 ** have been deleted? This API will need to change to return an error code |
4592 ** as well as the boolean result value. | 4884 ** as well as the boolean result value. |
4593 */ | 4885 */ |
4594 return (CURSOR_VALID!=pCur->eState); | 4886 return (CURSOR_VALID!=pCur->eState); |
4595 } | 4887 } |
4596 | 4888 |
4597 /* | 4889 /* |
4598 ** Advance the cursor to the next entry in the database. If | 4890 ** Advance the cursor to the next entry in the database. If |
4599 ** successful then set *pRes=0. If the cursor | 4891 ** successful then set *pRes=0. If the cursor |
4600 ** was already pointing to the last entry in the database before | 4892 ** was already pointing to the last entry in the database before |
4601 ** this routine was called, then set *pRes=1. | 4893 ** this routine was called, then set *pRes=1. |
| 4894 ** |
| 4895 ** The main entry point is sqlite3BtreeNext(). That routine is optimized |
| 4896 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx |
| 4897 ** to the next cell on the current page. The (slower) btreeNext() helper |
| 4898 ** routine is called when it is necessary to move to a different page or |
| 4899 ** to restore the cursor. |
| 4900 ** |
| 4901 ** The calling function will set *pRes to 0 or 1. The initial *pRes value |
| 4902 ** will be 1 if the cursor being stepped corresponds to an SQL index and |
| 4903 ** if this routine could have been skipped if that SQL index had been |
| 4904 ** a unique index. Otherwise the caller will have set *pRes to zero. |
| 4905 ** Zero is the common case. The btree implementation is free to use the |
| 4906 ** initial *pRes value as a hint to improve performance, but the current |
| 4907 ** SQLite btree implementation does not. (Note that the comdb2 btree |
| 4908 ** implementation does use this hint, however.) |
4602 */ | 4909 */ |
4603 int sqlite3BtreeNext(BtCursor *pCur, int *pRes){ | 4910 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){ |
4604 int rc; | 4911 int rc; |
4605 int idx; | 4912 int idx; |
4606 MemPage *pPage; | 4913 MemPage *pPage; |
4607 | 4914 |
4608 assert( cursorHoldsMutex(pCur) ); | 4915 assert( cursorHoldsMutex(pCur) ); |
4609 rc = restoreCursorPosition(pCur); | 4916 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); |
4610 if( rc!=SQLITE_OK ){ | 4917 assert( *pRes==0 ); |
4611 return rc; | 4918 if( pCur->eState!=CURSOR_VALID ){ |
| 4919 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 ); |
| 4920 rc = restoreCursorPosition(pCur); |
| 4921 if( rc!=SQLITE_OK ){ |
| 4922 return rc; |
| 4923 } |
| 4924 if( CURSOR_INVALID==pCur->eState ){ |
| 4925 *pRes = 1; |
| 4926 return SQLITE_OK; |
| 4927 } |
| 4928 if( pCur->skipNext ){ |
| 4929 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT ); |
| 4930 pCur->eState = CURSOR_VALID; |
| 4931 if( pCur->skipNext>0 ){ |
| 4932 pCur->skipNext = 0; |
| 4933 return SQLITE_OK; |
| 4934 } |
| 4935 pCur->skipNext = 0; |
| 4936 } |
4612 } | 4937 } |
4613 assert( pRes!=0 ); | |
4614 if( CURSOR_INVALID==pCur->eState ){ | |
4615 *pRes = 1; | |
4616 return SQLITE_OK; | |
4617 } | |
4618 if( pCur->skipNext>0 ){ | |
4619 pCur->skipNext = 0; | |
4620 *pRes = 0; | |
4621 return SQLITE_OK; | |
4622 } | |
4623 pCur->skipNext = 0; | |
4624 | 4938 |
4625 pPage = pCur->apPage[pCur->iPage]; | 4939 pPage = pCur->apPage[pCur->iPage]; |
4626 idx = ++pCur->aiIdx[pCur->iPage]; | 4940 idx = ++pCur->aiIdx[pCur->iPage]; |
4627 assert( pPage->isInit ); | 4941 assert( pPage->isInit ); |
4628 assert( idx<=pPage->nCell ); | |
4629 | 4942 |
4630 pCur->info.nSize = 0; | 4943 /* If the database file is corrupt, it is possible for the value of idx |
4631 pCur->validNKey = 0; | 4944 ** to be invalid here. This can only occur if a second cursor modifies |
| 4945 ** the page while cursor pCur is holding a reference to it. Which can |
| 4946 ** only happen if the database is corrupt in such a way as to link the |
| 4947 ** page into more than one b-tree structure. */ |
| 4948 testcase( idx>pPage->nCell ); |
| 4949 |
4632 if( idx>=pPage->nCell ){ | 4950 if( idx>=pPage->nCell ){ |
4633 if( !pPage->leaf ){ | 4951 if( !pPage->leaf ){ |
4634 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); | 4952 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); |
4635 if( rc ) return rc; | 4953 if( rc ) return rc; |
4636 rc = moveToLeftmost(pCur); | 4954 return moveToLeftmost(pCur); |
4637 *pRes = 0; | |
4638 return rc; | |
4639 } | 4955 } |
4640 do{ | 4956 do{ |
4641 if( pCur->iPage==0 ){ | 4957 if( pCur->iPage==0 ){ |
4642 *pRes = 1; | 4958 *pRes = 1; |
4643 pCur->eState = CURSOR_INVALID; | 4959 pCur->eState = CURSOR_INVALID; |
4644 return SQLITE_OK; | 4960 return SQLITE_OK; |
4645 } | 4961 } |
4646 moveToParent(pCur); | 4962 moveToParent(pCur); |
4647 pPage = pCur->apPage[pCur->iPage]; | 4963 pPage = pCur->apPage[pCur->iPage]; |
4648 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell ); | 4964 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell ); |
4649 *pRes = 0; | |
4650 if( pPage->intKey ){ | 4965 if( pPage->intKey ){ |
4651 rc = sqlite3BtreeNext(pCur, pRes); | 4966 return sqlite3BtreeNext(pCur, pRes); |
4652 }else{ | 4967 }else{ |
4653 rc = SQLITE_OK; | 4968 return SQLITE_OK; |
4654 } | 4969 } |
4655 return rc; | |
4656 } | 4970 } |
4657 *pRes = 0; | |
4658 if( pPage->leaf ){ | 4971 if( pPage->leaf ){ |
4659 return SQLITE_OK; | 4972 return SQLITE_OK; |
| 4973 }else{ |
| 4974 return moveToLeftmost(pCur); |
4660 } | 4975 } |
4661 rc = moveToLeftmost(pCur); | |
4662 return rc; | |
4663 } | 4976 } |
4664 | 4977 int sqlite3BtreeNext(BtCursor *pCur, int *pRes){ |
| 4978 MemPage *pPage; |
| 4979 assert( cursorHoldsMutex(pCur) ); |
| 4980 assert( pRes!=0 ); |
| 4981 assert( *pRes==0 || *pRes==1 ); |
| 4982 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); |
| 4983 pCur->info.nSize = 0; |
| 4984 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl); |
| 4985 *pRes = 0; |
| 4986 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes); |
| 4987 pPage = pCur->apPage[pCur->iPage]; |
| 4988 if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){ |
| 4989 pCur->aiIdx[pCur->iPage]--; |
| 4990 return btreeNext(pCur, pRes); |
| 4991 } |
| 4992 if( pPage->leaf ){ |
| 4993 return SQLITE_OK; |
| 4994 }else{ |
| 4995 return moveToLeftmost(pCur); |
| 4996 } |
| 4997 } |
4665 | 4998 |
4666 /* | 4999 /* |
4667 ** Step the cursor to the back to the previous entry in the database. If | 5000 ** Step the cursor to the back to the previous entry in the database. If |
4668 ** successful then set *pRes=0. If the cursor | 5001 ** successful then set *pRes=0. If the cursor |
4669 ** was already pointing to the first entry in the database before | 5002 ** was already pointing to the first entry in the database before |
4670 ** this routine was called, then set *pRes=1. | 5003 ** this routine was called, then set *pRes=1. |
| 5004 ** |
| 5005 ** The main entry point is sqlite3BtreePrevious(). That routine is optimized |
| 5006 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx |
| 5007 ** to the previous cell on the current page. The (slower) btreePrevious() |
| 5008 ** helper routine is called when it is necessary to move to a different page |
| 5009 ** or to restore the cursor. |
| 5010 ** |
| 5011 ** The calling function will set *pRes to 0 or 1. The initial *pRes value |
| 5012 ** will be 1 if the cursor being stepped corresponds to an SQL index and |
| 5013 ** if this routine could have been skipped if that SQL index had been |
| 5014 ** a unique index. Otherwise the caller will have set *pRes to zero. |
| 5015 ** Zero is the common case. The btree implementation is free to use the |
| 5016 ** initial *pRes value as a hint to improve performance, but the current |
| 5017 ** SQLite btree implementation does not. (Note that the comdb2 btree |
| 5018 ** implementation does use this hint, however.) |
4671 */ | 5019 */ |
4672 int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){ | 5020 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){ |
4673 int rc; | 5021 int rc; |
4674 MemPage *pPage; | 5022 MemPage *pPage; |
4675 | 5023 |
4676 assert( cursorHoldsMutex(pCur) ); | 5024 assert( cursorHoldsMutex(pCur) ); |
4677 rc = restoreCursorPosition(pCur); | 5025 assert( pRes!=0 ); |
4678 if( rc!=SQLITE_OK ){ | 5026 assert( *pRes==0 ); |
4679 return rc; | 5027 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); |
| 5028 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 ); |
| 5029 assert( pCur->info.nSize==0 ); |
| 5030 if( pCur->eState!=CURSOR_VALID ){ |
| 5031 rc = restoreCursorPosition(pCur); |
| 5032 if( rc!=SQLITE_OK ){ |
| 5033 return rc; |
| 5034 } |
| 5035 if( CURSOR_INVALID==pCur->eState ){ |
| 5036 *pRes = 1; |
| 5037 return SQLITE_OK; |
| 5038 } |
| 5039 if( pCur->skipNext ){ |
| 5040 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT ); |
| 5041 pCur->eState = CURSOR_VALID; |
| 5042 if( pCur->skipNext<0 ){ |
| 5043 pCur->skipNext = 0; |
| 5044 return SQLITE_OK; |
| 5045 } |
| 5046 pCur->skipNext = 0; |
| 5047 } |
4680 } | 5048 } |
4681 pCur->atLast = 0; | |
4682 if( CURSOR_INVALID==pCur->eState ){ | |
4683 *pRes = 1; | |
4684 return SQLITE_OK; | |
4685 } | |
4686 if( pCur->skipNext<0 ){ | |
4687 pCur->skipNext = 0; | |
4688 *pRes = 0; | |
4689 return SQLITE_OK; | |
4690 } | |
4691 pCur->skipNext = 0; | |
4692 | 5049 |
4693 pPage = pCur->apPage[pCur->iPage]; | 5050 pPage = pCur->apPage[pCur->iPage]; |
4694 assert( pPage->isInit ); | 5051 assert( pPage->isInit ); |
4695 if( !pPage->leaf ){ | 5052 if( !pPage->leaf ){ |
4696 int idx = pCur->aiIdx[pCur->iPage]; | 5053 int idx = pCur->aiIdx[pCur->iPage]; |
4697 rc = moveToChild(pCur, get4byte(findCell(pPage, idx))); | 5054 rc = moveToChild(pCur, get4byte(findCell(pPage, idx))); |
4698 if( rc ){ | 5055 if( rc ) return rc; |
4699 return rc; | |
4700 } | |
4701 rc = moveToRightmost(pCur); | 5056 rc = moveToRightmost(pCur); |
4702 }else{ | 5057 }else{ |
4703 while( pCur->aiIdx[pCur->iPage]==0 ){ | 5058 while( pCur->aiIdx[pCur->iPage]==0 ){ |
4704 if( pCur->iPage==0 ){ | 5059 if( pCur->iPage==0 ){ |
4705 pCur->eState = CURSOR_INVALID; | 5060 pCur->eState = CURSOR_INVALID; |
4706 *pRes = 1; | 5061 *pRes = 1; |
4707 return SQLITE_OK; | 5062 return SQLITE_OK; |
4708 } | 5063 } |
4709 moveToParent(pCur); | 5064 moveToParent(pCur); |
4710 } | 5065 } |
4711 pCur->info.nSize = 0; | 5066 assert( pCur->info.nSize==0 ); |
4712 pCur->validNKey = 0; | 5067 assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 ); |
4713 | 5068 |
4714 pCur->aiIdx[pCur->iPage]--; | 5069 pCur->aiIdx[pCur->iPage]--; |
4715 pPage = pCur->apPage[pCur->iPage]; | 5070 pPage = pCur->apPage[pCur->iPage]; |
4716 if( pPage->intKey && !pPage->leaf ){ | 5071 if( pPage->intKey && !pPage->leaf ){ |
4717 rc = sqlite3BtreePrevious(pCur, pRes); | 5072 rc = sqlite3BtreePrevious(pCur, pRes); |
4718 }else{ | 5073 }else{ |
4719 rc = SQLITE_OK; | 5074 rc = SQLITE_OK; |
4720 } | 5075 } |
4721 } | 5076 } |
| 5077 return rc; |
| 5078 } |
| 5079 int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){ |
| 5080 assert( cursorHoldsMutex(pCur) ); |
| 5081 assert( pRes!=0 ); |
| 5082 assert( *pRes==0 || *pRes==1 ); |
| 5083 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID ); |
4722 *pRes = 0; | 5084 *pRes = 0; |
4723 return rc; | 5085 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey); |
| 5086 pCur->info.nSize = 0; |
| 5087 if( pCur->eState!=CURSOR_VALID |
| 5088 || pCur->aiIdx[pCur->iPage]==0 |
| 5089 || pCur->apPage[pCur->iPage]->leaf==0 |
| 5090 ){ |
| 5091 return btreePrevious(pCur, pRes); |
| 5092 } |
| 5093 pCur->aiIdx[pCur->iPage]--; |
| 5094 return SQLITE_OK; |
4724 } | 5095 } |
4725 | 5096 |
4726 /* | 5097 /* |
4727 ** Allocate a new page from the database file. | 5098 ** Allocate a new page from the database file. |
4728 ** | 5099 ** |
4729 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite() | 5100 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite() |
4730 ** has already been called on the new page.) The new page has also | 5101 ** has already been called on the new page.) The new page has also |
4731 ** been referenced and the calling routine is responsible for calling | 5102 ** been referenced and the calling routine is responsible for calling |
4732 ** sqlite3PagerUnref() on the new page when it is done. | 5103 ** sqlite3PagerUnref() on the new page when it is done. |
4733 ** | 5104 ** |
4734 ** SQLITE_OK is returned on success. Any other return value indicates | 5105 ** SQLITE_OK is returned on success. Any other return value indicates |
4735 ** an error. *ppPage and *pPgno are undefined in the event of an error. | 5106 ** an error. *ppPage and *pPgno are undefined in the event of an error. |
4736 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned. | 5107 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned. |
4737 ** | 5108 ** |
4738 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to | 5109 ** If the "nearby" parameter is not 0, then an effort is made to |
4739 ** locate a page close to the page number "nearby". This can be used in an | 5110 ** locate a page close to the page number "nearby". This can be used in an |
4740 ** attempt to keep related pages close to each other in the database file, | 5111 ** attempt to keep related pages close to each other in the database file, |
4741 ** which in turn can make database access faster. | 5112 ** which in turn can make database access faster. |
4742 ** | 5113 ** |
4743 ** If the "exact" parameter is not 0, and the page-number nearby exists | 5114 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists |
4744 ** anywhere on the free-list, then it is guarenteed to be returned. This | 5115 ** anywhere on the free-list, then it is guaranteed to be returned. If |
4745 ** is only used by auto-vacuum databases when allocating a new table. | 5116 ** eMode is BTALLOC_LT then the page returned will be less than or equal |
| 5117 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there |
| 5118 ** are no restrictions on which page is returned. |
4746 */ | 5119 */ |
4747 static int allocateBtreePage( | 5120 static int allocateBtreePage( |
4748 BtShared *pBt, | 5121 BtShared *pBt, /* The btree */ |
4749 MemPage **ppPage, | 5122 MemPage **ppPage, /* Store pointer to the allocated page here */ |
4750 Pgno *pPgno, | 5123 Pgno *pPgno, /* Store the page number here */ |
4751 Pgno nearby, | 5124 Pgno nearby, /* Search for a page near this one */ |
4752 u8 exact | 5125 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */ |
4753 ){ | 5126 ){ |
4754 MemPage *pPage1; | 5127 MemPage *pPage1; |
4755 int rc; | 5128 int rc; |
4756 u32 n; /* Number of pages on the freelist */ | 5129 u32 n; /* Number of pages on the freelist */ |
4757 u32 k; /* Number of leaves on the trunk of the freelist */ | 5130 u32 k; /* Number of leaves on the trunk of the freelist */ |
4758 MemPage *pTrunk = 0; | 5131 MemPage *pTrunk = 0; |
4759 MemPage *pPrevTrunk = 0; | 5132 MemPage *pPrevTrunk = 0; |
4760 Pgno mxPage; /* Total size of the database file */ | 5133 Pgno mxPage; /* Total size of the database file */ |
4761 | 5134 |
4762 assert( sqlite3_mutex_held(pBt->mutex) ); | 5135 assert( sqlite3_mutex_held(pBt->mutex) ); |
| 5136 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) ); |
4763 pPage1 = pBt->pPage1; | 5137 pPage1 = pBt->pPage1; |
4764 mxPage = btreePagecount(pBt); | 5138 mxPage = btreePagecount(pBt); |
4765 n = get4byte(&pPage1->aData[36]); | 5139 n = get4byte(&pPage1->aData[36]); |
4766 testcase( n==mxPage-1 ); | 5140 testcase( n==mxPage-1 ); |
4767 if( n>=mxPage ){ | 5141 if( n>=mxPage ){ |
4768 return SQLITE_CORRUPT_BKPT; | 5142 return SQLITE_CORRUPT_BKPT; |
4769 } | 5143 } |
4770 if( n>0 ){ | 5144 if( n>0 ){ |
4771 /* There are pages on the freelist. Reuse one of those pages. */ | 5145 /* There are pages on the freelist. Reuse one of those pages. */ |
4772 Pgno iTrunk; | 5146 Pgno iTrunk; |
4773 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */ | 5147 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */ |
4774 | 5148 |
4775 /* If the 'exact' parameter was true and a query of the pointer-map | 5149 /* If eMode==BTALLOC_EXACT and a query of the pointer-map |
4776 ** shows that the page 'nearby' is somewhere on the free-list, then | 5150 ** shows that the page 'nearby' is somewhere on the free-list, then |
4777 ** the entire-list will be searched for that page. | 5151 ** the entire-list will be searched for that page. |
4778 */ | 5152 */ |
4779 #ifndef SQLITE_OMIT_AUTOVACUUM | 5153 #ifndef SQLITE_OMIT_AUTOVACUUM |
4780 if( exact && nearby<=mxPage ){ | 5154 if( eMode==BTALLOC_EXACT ){ |
4781 u8 eType; | 5155 if( nearby<=mxPage ){ |
4782 assert( nearby>0 ); | 5156 u8 eType; |
4783 assert( pBt->autoVacuum ); | 5157 assert( nearby>0 ); |
4784 rc = ptrmapGet(pBt, nearby, &eType, 0); | 5158 assert( pBt->autoVacuum ); |
4785 if( rc ) return rc; | 5159 rc = ptrmapGet(pBt, nearby, &eType, 0); |
4786 if( eType==PTRMAP_FREEPAGE ){ | 5160 if( rc ) return rc; |
4787 searchList = 1; | 5161 if( eType==PTRMAP_FREEPAGE ){ |
| 5162 searchList = 1; |
| 5163 } |
4788 } | 5164 } |
4789 *pPgno = nearby; | 5165 }else if( eMode==BTALLOC_LE ){ |
| 5166 searchList = 1; |
4790 } | 5167 } |
4791 #endif | 5168 #endif |
4792 | 5169 |
4793 /* Decrement the free-list count by 1. Set iTrunk to the index of the | 5170 /* Decrement the free-list count by 1. Set iTrunk to the index of the |
4794 ** first free-list trunk page. iPrevTrunk is initially 1. | 5171 ** first free-list trunk page. iPrevTrunk is initially 1. |
4795 */ | 5172 */ |
4796 rc = sqlite3PagerWrite(pPage1->pDbPage); | 5173 rc = sqlite3PagerWrite(pPage1->pDbPage); |
4797 if( rc ) return rc; | 5174 if( rc ) return rc; |
4798 put4byte(&pPage1->aData[36], n-1); | 5175 put4byte(&pPage1->aData[36], n-1); |
4799 | 5176 |
4800 /* The code within this loop is run only once if the 'searchList' variable | 5177 /* The code within this loop is run only once if the 'searchList' variable |
4801 ** is not true. Otherwise, it runs once for each trunk-page on the | 5178 ** is not true. Otherwise, it runs once for each trunk-page on the |
4802 ** free-list until the page 'nearby' is located. | 5179 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT) |
| 5180 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT) |
4803 */ | 5181 */ |
4804 do { | 5182 do { |
4805 pPrevTrunk = pTrunk; | 5183 pPrevTrunk = pTrunk; |
4806 if( pPrevTrunk ){ | 5184 if( pPrevTrunk ){ |
4807 iTrunk = get4byte(&pPrevTrunk->aData[0]); | 5185 iTrunk = get4byte(&pPrevTrunk->aData[0]); |
4808 }else{ | 5186 }else{ |
4809 iTrunk = get4byte(&pPage1->aData[32]); | 5187 iTrunk = get4byte(&pPage1->aData[32]); |
4810 } | 5188 } |
4811 testcase( iTrunk==mxPage ); | 5189 testcase( iTrunk==mxPage ); |
4812 if( iTrunk>mxPage ){ | 5190 if( iTrunk>mxPage ){ |
4813 rc = SQLITE_CORRUPT_BKPT; | 5191 rc = SQLITE_CORRUPT_BKPT; |
4814 }else{ | 5192 }else{ |
4815 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0); | 5193 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0); |
4816 } | 5194 } |
4817 if( rc ){ | 5195 if( rc ){ |
4818 pTrunk = 0; | 5196 pTrunk = 0; |
4819 goto end_allocate_page; | 5197 goto end_allocate_page; |
4820 } | 5198 } |
| 5199 assert( pTrunk!=0 ); |
| 5200 assert( pTrunk->aData!=0 ); |
4821 | 5201 |
4822 k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */ | 5202 k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */ |
4823 if( k==0 && !searchList ){ | 5203 if( k==0 && !searchList ){ |
4824 /* The trunk has no leaves and the list is not being searched. | 5204 /* The trunk has no leaves and the list is not being searched. |
4825 ** So extract the trunk page itself and use it as the newly | 5205 ** So extract the trunk page itself and use it as the newly |
4826 ** allocated page */ | 5206 ** allocated page */ |
4827 assert( pPrevTrunk==0 ); | 5207 assert( pPrevTrunk==0 ); |
4828 rc = sqlite3PagerWrite(pTrunk->pDbPage); | 5208 rc = sqlite3PagerWrite(pTrunk->pDbPage); |
4829 if( rc ){ | 5209 if( rc ){ |
4830 goto end_allocate_page; | 5210 goto end_allocate_page; |
4831 } | 5211 } |
4832 *pPgno = iTrunk; | 5212 *pPgno = iTrunk; |
4833 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); | 5213 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); |
4834 *ppPage = pTrunk; | 5214 *ppPage = pTrunk; |
4835 pTrunk = 0; | 5215 pTrunk = 0; |
4836 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); | 5216 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); |
4837 }else if( k>(u32)(pBt->usableSize/4 - 2) ){ | 5217 }else if( k>(u32)(pBt->usableSize/4 - 2) ){ |
4838 /* Value of k is out of range. Database corruption */ | 5218 /* Value of k is out of range. Database corruption */ |
4839 rc = SQLITE_CORRUPT_BKPT; | 5219 rc = SQLITE_CORRUPT_BKPT; |
4840 goto end_allocate_page; | 5220 goto end_allocate_page; |
4841 #ifndef SQLITE_OMIT_AUTOVACUUM | 5221 #ifndef SQLITE_OMIT_AUTOVACUUM |
4842 }else if( searchList && nearby==iTrunk ){ | 5222 }else if( searchList |
| 5223 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE)) |
| 5224 ){ |
4843 /* The list is being searched and this trunk page is the page | 5225 /* The list is being searched and this trunk page is the page |
4844 ** to allocate, regardless of whether it has leaves. | 5226 ** to allocate, regardless of whether it has leaves. |
4845 */ | 5227 */ |
4846 assert( *pPgno==iTrunk ); | 5228 *pPgno = iTrunk; |
4847 *ppPage = pTrunk; | 5229 *ppPage = pTrunk; |
4848 searchList = 0; | 5230 searchList = 0; |
4849 rc = sqlite3PagerWrite(pTrunk->pDbPage); | 5231 rc = sqlite3PagerWrite(pTrunk->pDbPage); |
4850 if( rc ){ | 5232 if( rc ){ |
4851 goto end_allocate_page; | 5233 goto end_allocate_page; |
4852 } | 5234 } |
4853 if( k==0 ){ | 5235 if( k==0 ){ |
4854 if( !pPrevTrunk ){ | 5236 if( !pPrevTrunk ){ |
4855 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); | 5237 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); |
4856 }else{ | 5238 }else{ |
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
4899 pTrunk = 0; | 5281 pTrunk = 0; |
4900 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); | 5282 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); |
4901 #endif | 5283 #endif |
4902 }else if( k>0 ){ | 5284 }else if( k>0 ){ |
4903 /* Extract a leaf from the trunk */ | 5285 /* Extract a leaf from the trunk */ |
4904 u32 closest; | 5286 u32 closest; |
4905 Pgno iPage; | 5287 Pgno iPage; |
4906 unsigned char *aData = pTrunk->aData; | 5288 unsigned char *aData = pTrunk->aData; |
4907 if( nearby>0 ){ | 5289 if( nearby>0 ){ |
4908 u32 i; | 5290 u32 i; |
4909 int dist; | |
4910 closest = 0; | 5291 closest = 0; |
4911 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby); | 5292 if( eMode==BTALLOC_LE ){ |
4912 for(i=1; i<k; i++){ | 5293 for(i=0; i<k; i++){ |
4913 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby); | 5294 iPage = get4byte(&aData[8+i*4]); |
4914 if( d2<dist ){ | 5295 if( iPage<=nearby ){ |
4915 closest = i; | 5296 closest = i; |
4916 dist = d2; | 5297 break; |
| 5298 } |
| 5299 } |
| 5300 }else{ |
| 5301 int dist; |
| 5302 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby); |
| 5303 for(i=1; i<k; i++){ |
| 5304 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby); |
| 5305 if( d2<dist ){ |
| 5306 closest = i; |
| 5307 dist = d2; |
| 5308 } |
4917 } | 5309 } |
4918 } | 5310 } |
4919 }else{ | 5311 }else{ |
4920 closest = 0; | 5312 closest = 0; |
4921 } | 5313 } |
4922 | 5314 |
4923 iPage = get4byte(&aData[8+closest*4]); | 5315 iPage = get4byte(&aData[8+closest*4]); |
4924 testcase( iPage==mxPage ); | 5316 testcase( iPage==mxPage ); |
4925 if( iPage>mxPage ){ | 5317 if( iPage>mxPage ){ |
4926 rc = SQLITE_CORRUPT_BKPT; | 5318 rc = SQLITE_CORRUPT_BKPT; |
4927 goto end_allocate_page; | 5319 goto end_allocate_page; |
4928 } | 5320 } |
4929 testcase( iPage==mxPage ); | 5321 testcase( iPage==mxPage ); |
4930 if( !searchList || iPage==nearby ){ | 5322 if( !searchList |
| 5323 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE)) |
| 5324 ){ |
4931 int noContent; | 5325 int noContent; |
4932 *pPgno = iPage; | 5326 *pPgno = iPage; |
4933 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d" | 5327 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d" |
4934 ": %d more free pages\n", | 5328 ": %d more free pages\n", |
4935 *pPgno, closest+1, k, pTrunk->pgno, n-1)); | 5329 *pPgno, closest+1, k, pTrunk->pgno, n-1)); |
4936 rc = sqlite3PagerWrite(pTrunk->pDbPage); | 5330 rc = sqlite3PagerWrite(pTrunk->pDbPage); |
4937 if( rc ) goto end_allocate_page; | 5331 if( rc ) goto end_allocate_page; |
4938 if( closest<k-1 ){ | 5332 if( closest<k-1 ){ |
4939 memcpy(&aData[8+closest*4], &aData[4+k*4], 4); | 5333 memcpy(&aData[8+closest*4], &aData[4+k*4], 4); |
4940 } | 5334 } |
4941 put4byte(&aData[4], k-1); | 5335 put4byte(&aData[4], k-1); |
4942 noContent = !btreeGetHasContent(pBt, *pPgno); | 5336 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0; |
4943 rc = btreeGetPage(pBt, *pPgno, ppPage, noContent); | 5337 rc = btreeGetPage(pBt, *pPgno, ppPage, noContent); |
4944 if( rc==SQLITE_OK ){ | 5338 if( rc==SQLITE_OK ){ |
4945 rc = sqlite3PagerWrite((*ppPage)->pDbPage); | 5339 rc = sqlite3PagerWrite((*ppPage)->pDbPage); |
4946 if( rc!=SQLITE_OK ){ | 5340 if( rc!=SQLITE_OK ){ |
4947 releasePage(*ppPage); | 5341 releasePage(*ppPage); |
4948 } | 5342 } |
4949 } | 5343 } |
4950 searchList = 0; | 5344 searchList = 0; |
4951 } | 5345 } |
4952 } | 5346 } |
4953 releasePage(pPrevTrunk); | 5347 releasePage(pPrevTrunk); |
4954 pPrevTrunk = 0; | 5348 pPrevTrunk = 0; |
4955 }while( searchList ); | 5349 }while( searchList ); |
4956 }else{ | 5350 }else{ |
4957 /* There are no pages on the freelist, so create a new page at the | 5351 /* There are no pages on the freelist, so append a new page to the |
4958 ** end of the file */ | 5352 ** database image. |
| 5353 ** |
| 5354 ** Normally, new pages allocated by this block can be requested from the |
| 5355 ** pager layer with the 'no-content' flag set. This prevents the pager |
| 5356 ** from trying to read the pages content from disk. However, if the |
| 5357 ** current transaction has already run one or more incremental-vacuum |
| 5358 ** steps, then the page we are about to allocate may contain content |
| 5359 ** that is required in the event of a rollback. In this case, do |
| 5360 ** not set the no-content flag. This causes the pager to load and journal |
| 5361 ** the current page content before overwriting it. |
| 5362 ** |
| 5363 ** Note that the pager will not actually attempt to load or journal |
| 5364 ** content for any page that really does lie past the end of the database |
| 5365 ** file on disk. So the effects of disabling the no-content optimization |
| 5366 ** here are confined to those pages that lie between the end of the |
| 5367 ** database image and the end of the database file. |
| 5368 */ |
| 5369 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0; |
| 5370 |
4959 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); | 5371 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); |
4960 if( rc ) return rc; | 5372 if( rc ) return rc; |
4961 pBt->nPage++; | 5373 pBt->nPage++; |
4962 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++; | 5374 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++; |
4963 | 5375 |
4964 #ifndef SQLITE_OMIT_AUTOVACUUM | 5376 #ifndef SQLITE_OMIT_AUTOVACUUM |
4965 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){ | 5377 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){ |
4966 /* If *pPgno refers to a pointer-map page, allocate two new pages | 5378 /* If *pPgno refers to a pointer-map page, allocate two new pages |
4967 ** at the end of the file instead of one. The first allocated page | 5379 ** at the end of the file instead of one. The first allocated page |
4968 ** becomes a new pointer-map page, the second is used by the caller. | 5380 ** becomes a new pointer-map page, the second is used by the caller. |
4969 */ | 5381 */ |
4970 MemPage *pPg = 0; | 5382 MemPage *pPg = 0; |
4971 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage)); | 5383 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage)); |
4972 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) ); | 5384 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) ); |
4973 rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1); | 5385 rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent); |
4974 if( rc==SQLITE_OK ){ | 5386 if( rc==SQLITE_OK ){ |
4975 rc = sqlite3PagerWrite(pPg->pDbPage); | 5387 rc = sqlite3PagerWrite(pPg->pDbPage); |
4976 releasePage(pPg); | 5388 releasePage(pPg); |
4977 } | 5389 } |
4978 if( rc ) return rc; | 5390 if( rc ) return rc; |
4979 pBt->nPage++; | 5391 pBt->nPage++; |
4980 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; } | 5392 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; } |
4981 } | 5393 } |
4982 #endif | 5394 #endif |
4983 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage); | 5395 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage); |
4984 *pPgno = pBt->nPage; | 5396 *pPgno = pBt->nPage; |
4985 | 5397 |
4986 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); | 5398 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); |
4987 rc = btreeGetPage(pBt, *pPgno, ppPage, 1); | 5399 rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent); |
4988 if( rc ) return rc; | 5400 if( rc ) return rc; |
4989 rc = sqlite3PagerWrite((*ppPage)->pDbPage); | 5401 rc = sqlite3PagerWrite((*ppPage)->pDbPage); |
4990 if( rc!=SQLITE_OK ){ | 5402 if( rc!=SQLITE_OK ){ |
4991 releasePage(*ppPage); | 5403 releasePage(*ppPage); |
4992 } | 5404 } |
4993 TRACE(("ALLOCATE: %d from end of file\n", *pPgno)); | 5405 TRACE(("ALLOCATE: %d from end of file\n", *pPgno)); |
4994 } | 5406 } |
4995 | 5407 |
4996 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); | 5408 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); |
4997 | 5409 |
4998 end_allocate_page: | 5410 end_allocate_page: |
4999 releasePage(pTrunk); | 5411 releasePage(pTrunk); |
5000 releasePage(pPrevTrunk); | 5412 releasePage(pPrevTrunk); |
5001 if( rc==SQLITE_OK ){ | 5413 if( rc==SQLITE_OK ){ |
5002 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){ | 5414 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){ |
5003 releasePage(*ppPage); | 5415 releasePage(*ppPage); |
| 5416 *ppPage = 0; |
5004 return SQLITE_CORRUPT_BKPT; | 5417 return SQLITE_CORRUPT_BKPT; |
5005 } | 5418 } |
5006 (*ppPage)->isInit = 0; | 5419 (*ppPage)->isInit = 0; |
5007 }else{ | 5420 }else{ |
5008 *ppPage = 0; | 5421 *ppPage = 0; |
5009 } | 5422 } |
5010 assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) ); | 5423 assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) ); |
5011 return rc; | 5424 return rc; |
5012 } | 5425 } |
5013 | 5426 |
(...skipping 27 matching lines...) Expand all Loading... |
5041 }else{ | 5454 }else{ |
5042 pPage = btreePageLookup(pBt, iPage); | 5455 pPage = btreePageLookup(pBt, iPage); |
5043 } | 5456 } |
5044 | 5457 |
5045 /* Increment the free page count on pPage1 */ | 5458 /* Increment the free page count on pPage1 */ |
5046 rc = sqlite3PagerWrite(pPage1->pDbPage); | 5459 rc = sqlite3PagerWrite(pPage1->pDbPage); |
5047 if( rc ) goto freepage_out; | 5460 if( rc ) goto freepage_out; |
5048 nFree = get4byte(&pPage1->aData[36]); | 5461 nFree = get4byte(&pPage1->aData[36]); |
5049 put4byte(&pPage1->aData[36], nFree+1); | 5462 put4byte(&pPage1->aData[36], nFree+1); |
5050 | 5463 |
5051 if( pBt->secureDelete ){ | 5464 if( pBt->btsFlags & BTS_SECURE_DELETE ){ |
5052 /* If the secure_delete option is enabled, then | 5465 /* If the secure_delete option is enabled, then |
5053 ** always fully overwrite deleted information with zeros. | 5466 ** always fully overwrite deleted information with zeros. |
5054 */ | 5467 */ |
5055 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) ) | 5468 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) ) |
5056 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0) | 5469 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0) |
5057 ){ | 5470 ){ |
5058 goto freepage_out; | 5471 goto freepage_out; |
5059 } | 5472 } |
5060 memset(pPage->aData, 0, pPage->pBt->pageSize); | 5473 memset(pPage->aData, 0, pPage->pBt->pageSize); |
5061 } | 5474 } |
(...skipping 40 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
5102 ** to maintain backwards compatibility with older versions of SQLite, | 5515 ** to maintain backwards compatibility with older versions of SQLite, |
5103 ** we will continue to restrict the number of entries to usableSize/4 - 8 | 5516 ** we will continue to restrict the number of entries to usableSize/4 - 8 |
5104 ** for now. At some point in the future (once everyone has upgraded | 5517 ** for now. At some point in the future (once everyone has upgraded |
5105 ** to 3.6.0 or later) we should consider fixing the conditional above | 5518 ** to 3.6.0 or later) we should consider fixing the conditional above |
5106 ** to read "usableSize/4-2" instead of "usableSize/4-8". | 5519 ** to read "usableSize/4-2" instead of "usableSize/4-8". |
5107 */ | 5520 */ |
5108 rc = sqlite3PagerWrite(pTrunk->pDbPage); | 5521 rc = sqlite3PagerWrite(pTrunk->pDbPage); |
5109 if( rc==SQLITE_OK ){ | 5522 if( rc==SQLITE_OK ){ |
5110 put4byte(&pTrunk->aData[4], nLeaf+1); | 5523 put4byte(&pTrunk->aData[4], nLeaf+1); |
5111 put4byte(&pTrunk->aData[8+nLeaf*4], iPage); | 5524 put4byte(&pTrunk->aData[8+nLeaf*4], iPage); |
5112 if( pPage && !pBt->secureDelete ){ | 5525 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){ |
5113 sqlite3PagerDontWrite(pPage->pDbPage); | 5526 sqlite3PagerDontWrite(pPage->pDbPage); |
5114 } | 5527 } |
5115 rc = btreeSetHasContent(pBt, iPage); | 5528 rc = btreeSetHasContent(pBt, iPage); |
5116 } | 5529 } |
5117 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno)); | 5530 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno)); |
5118 goto freepage_out; | 5531 goto freepage_out; |
5119 } | 5532 } |
5120 } | 5533 } |
5121 | 5534 |
5122 /* If control flows to this point, then it was not possible to add the | 5535 /* If control flows to this point, then it was not possible to add the |
(...skipping 22 matching lines...) Expand all Loading... |
5145 releasePage(pTrunk); | 5558 releasePage(pTrunk); |
5146 return rc; | 5559 return rc; |
5147 } | 5560 } |
5148 static void freePage(MemPage *pPage, int *pRC){ | 5561 static void freePage(MemPage *pPage, int *pRC){ |
5149 if( (*pRC)==SQLITE_OK ){ | 5562 if( (*pRC)==SQLITE_OK ){ |
5150 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno); | 5563 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno); |
5151 } | 5564 } |
5152 } | 5565 } |
5153 | 5566 |
5154 /* | 5567 /* |
5155 ** Free any overflow pages associated with the given Cell. | 5568 ** Free any overflow pages associated with the given Cell. Write the |
| 5569 ** local Cell size (the number of bytes on the original page, omitting |
| 5570 ** overflow) into *pnSize. |
5156 */ | 5571 */ |
5157 static int clearCell(MemPage *pPage, unsigned char *pCell){ | 5572 static int clearCell( |
| 5573 MemPage *pPage, /* The page that contains the Cell */ |
| 5574 unsigned char *pCell, /* First byte of the Cell */ |
| 5575 u16 *pnSize /* Write the size of the Cell here */ |
| 5576 ){ |
5158 BtShared *pBt = pPage->pBt; | 5577 BtShared *pBt = pPage->pBt; |
5159 CellInfo info; | 5578 CellInfo info; |
5160 Pgno ovflPgno; | 5579 Pgno ovflPgno; |
5161 int rc; | 5580 int rc; |
5162 int nOvfl; | 5581 int nOvfl; |
5163 u32 ovflPageSize; | 5582 u32 ovflPageSize; |
5164 | 5583 |
5165 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); | 5584 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); |
5166 btreeParseCellPtr(pPage, pCell, &info); | 5585 btreeParseCellPtr(pPage, pCell, &info); |
| 5586 *pnSize = info.nSize; |
5167 if( info.iOverflow==0 ){ | 5587 if( info.iOverflow==0 ){ |
5168 return SQLITE_OK; /* No overflow pages. Return without doing anything */ | 5588 return SQLITE_OK; /* No overflow pages. Return without doing anything */ |
5169 } | 5589 } |
| 5590 if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){ |
| 5591 return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */ |
| 5592 } |
5170 ovflPgno = get4byte(&pCell[info.iOverflow]); | 5593 ovflPgno = get4byte(&pCell[info.iOverflow]); |
5171 assert( pBt->usableSize > 4 ); | 5594 assert( pBt->usableSize > 4 ); |
5172 ovflPageSize = pBt->usableSize - 4; | 5595 ovflPageSize = pBt->usableSize - 4; |
5173 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize; | 5596 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize; |
5174 assert( ovflPgno==0 || nOvfl>0 ); | 5597 assert( ovflPgno==0 || nOvfl>0 ); |
5175 while( nOvfl-- ){ | 5598 while( nOvfl-- ){ |
5176 Pgno iNext = 0; | 5599 Pgno iNext = 0; |
5177 MemPage *pOvfl = 0; | 5600 MemPage *pOvfl = 0; |
5178 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){ | 5601 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){ |
5179 /* 0 is not a legal page number and page 1 cannot be an | 5602 /* 0 is not a legal page number and page 1 cannot be an |
(...skipping 57 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
5237 const u8 *pSrc; | 5660 const u8 *pSrc; |
5238 int nSrc, n, rc; | 5661 int nSrc, n, rc; |
5239 int spaceLeft; | 5662 int spaceLeft; |
5240 MemPage *pOvfl = 0; | 5663 MemPage *pOvfl = 0; |
5241 MemPage *pToRelease = 0; | 5664 MemPage *pToRelease = 0; |
5242 unsigned char *pPrior; | 5665 unsigned char *pPrior; |
5243 unsigned char *pPayload; | 5666 unsigned char *pPayload; |
5244 BtShared *pBt = pPage->pBt; | 5667 BtShared *pBt = pPage->pBt; |
5245 Pgno pgnoOvfl = 0; | 5668 Pgno pgnoOvfl = 0; |
5246 int nHeader; | 5669 int nHeader; |
5247 CellInfo info; | |
5248 | 5670 |
5249 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); | 5671 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); |
5250 | 5672 |
5251 /* pPage is not necessarily writeable since pCell might be auxiliary | 5673 /* pPage is not necessarily writeable since pCell might be auxiliary |
5252 ** buffer space that is separate from the pPage buffer area */ | 5674 ** buffer space that is separate from the pPage buffer area */ |
5253 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize] | 5675 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize] |
5254 || sqlite3PagerIswriteable(pPage->pDbPage) ); | 5676 || sqlite3PagerIswriteable(pPage->pDbPage) ); |
5255 | 5677 |
5256 /* Fill in the header. */ | 5678 /* Fill in the header. */ |
5257 nHeader = 0; | 5679 nHeader = pPage->childPtrSize; |
5258 if( !pPage->leaf ){ | 5680 nPayload = nData + nZero; |
5259 nHeader += 4; | 5681 if( pPage->intKeyLeaf ){ |
5260 } | 5682 nHeader += putVarint32(&pCell[nHeader], nPayload); |
5261 if( pPage->hasData ){ | |
5262 nHeader += putVarint(&pCell[nHeader], nData+nZero); | |
5263 }else{ | 5683 }else{ |
5264 nData = nZero = 0; | 5684 assert( nData==0 ); |
| 5685 assert( nZero==0 ); |
5265 } | 5686 } |
5266 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey); | 5687 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey); |
5267 btreeParseCellPtr(pPage, pCell, &info); | |
5268 assert( info.nHeader==nHeader ); | |
5269 assert( info.nKey==nKey ); | |
5270 assert( info.nData==(u32)(nData+nZero) ); | |
5271 | 5688 |
5272 /* Fill in the payload */ | 5689 /* Fill in the payload size */ |
5273 nPayload = nData + nZero; | |
5274 if( pPage->intKey ){ | 5690 if( pPage->intKey ){ |
5275 pSrc = pData; | 5691 pSrc = pData; |
5276 nSrc = nData; | 5692 nSrc = nData; |
5277 nData = 0; | 5693 nData = 0; |
5278 }else{ | 5694 }else{ |
5279 if( NEVER(nKey>0x7fffffff || pKey==0) ){ | 5695 if( NEVER(nKey>0x7fffffff || pKey==0) ){ |
5280 return SQLITE_CORRUPT_BKPT; | 5696 return SQLITE_CORRUPT_BKPT; |
5281 } | 5697 } |
5282 nPayload += (int)nKey; | 5698 nPayload = (int)nKey; |
5283 pSrc = pKey; | 5699 pSrc = pKey; |
5284 nSrc = (int)nKey; | 5700 nSrc = (int)nKey; |
5285 } | 5701 } |
5286 *pnSize = info.nSize; | 5702 if( nPayload<=pPage->maxLocal ){ |
5287 spaceLeft = info.nLocal; | 5703 n = nHeader + nPayload; |
| 5704 testcase( n==3 ); |
| 5705 testcase( n==4 ); |
| 5706 if( n<4 ) n = 4; |
| 5707 *pnSize = n; |
| 5708 spaceLeft = nPayload; |
| 5709 pPrior = pCell; |
| 5710 }else{ |
| 5711 int mn = pPage->minLocal; |
| 5712 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4); |
| 5713 testcase( n==pPage->maxLocal ); |
| 5714 testcase( n==pPage->maxLocal+1 ); |
| 5715 if( n > pPage->maxLocal ) n = mn; |
| 5716 spaceLeft = n; |
| 5717 *pnSize = n + nHeader + 4; |
| 5718 pPrior = &pCell[nHeader+n]; |
| 5719 } |
5288 pPayload = &pCell[nHeader]; | 5720 pPayload = &pCell[nHeader]; |
5289 pPrior = &pCell[info.iOverflow]; | |
5290 | 5721 |
| 5722 /* At this point variables should be set as follows: |
| 5723 ** |
| 5724 ** nPayload Total payload size in bytes |
| 5725 ** pPayload Begin writing payload here |
| 5726 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft, |
| 5727 ** that means content must spill into overflow pages. |
| 5728 ** *pnSize Size of the local cell (not counting overflow pages) |
| 5729 ** pPrior Where to write the pgno of the first overflow page |
| 5730 ** |
| 5731 ** Use a call to btreeParseCellPtr() to verify that the values above |
| 5732 ** were computed correctly. |
| 5733 */ |
| 5734 #if SQLITE_DEBUG |
| 5735 { |
| 5736 CellInfo info; |
| 5737 btreeParseCellPtr(pPage, pCell, &info); |
| 5738 assert( nHeader=(int)(info.pPayload - pCell) ); |
| 5739 assert( info.nKey==nKey ); |
| 5740 assert( *pnSize == info.nSize ); |
| 5741 assert( spaceLeft == info.nLocal ); |
| 5742 assert( pPrior == &pCell[info.iOverflow] ); |
| 5743 } |
| 5744 #endif |
| 5745 |
| 5746 /* Write the payload into the local Cell and any extra into overflow pages */ |
5291 while( nPayload>0 ){ | 5747 while( nPayload>0 ){ |
5292 if( spaceLeft==0 ){ | 5748 if( spaceLeft==0 ){ |
5293 #ifndef SQLITE_OMIT_AUTOVACUUM | 5749 #ifndef SQLITE_OMIT_AUTOVACUUM |
5294 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */ | 5750 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */ |
5295 if( pBt->autoVacuum ){ | 5751 if( pBt->autoVacuum ){ |
5296 do{ | 5752 do{ |
5297 pgnoOvfl++; | 5753 pgnoOvfl++; |
5298 } while( | 5754 } while( |
5299 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) | 5755 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) |
5300 ); | 5756 ); |
5301 } | 5757 } |
5302 #endif | 5758 #endif |
5303 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0); | 5759 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0); |
5304 #ifndef SQLITE_OMIT_AUTOVACUUM | 5760 #ifndef SQLITE_OMIT_AUTOVACUUM |
5305 /* If the database supports auto-vacuum, and the second or subsequent | 5761 /* If the database supports auto-vacuum, and the second or subsequent |
5306 ** overflow page is being allocated, add an entry to the pointer-map | 5762 ** overflow page is being allocated, add an entry to the pointer-map |
5307 ** for that page now. | 5763 ** for that page now. |
5308 ** | 5764 ** |
5309 ** If this is the first overflow page, then write a partial entry | 5765 ** If this is the first overflow page, then write a partial entry |
5310 ** to the pointer-map. If we write nothing to this pointer-map slot, | 5766 ** to the pointer-map. If we write nothing to this pointer-map slot, |
5311 ** then the optimistic overflow chain processing in clearCell() | 5767 ** then the optimistic overflow chain processing in clearCell() |
5312 ** may misinterpret the uninitialised values and delete the | 5768 ** may misinterpret the uninitialized values and delete the |
5313 ** wrong pages from the database. | 5769 ** wrong pages from the database. |
5314 */ | 5770 */ |
5315 if( pBt->autoVacuum && rc==SQLITE_OK ){ | 5771 if( pBt->autoVacuum && rc==SQLITE_OK ){ |
5316 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1); | 5772 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1); |
5317 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc); | 5773 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc); |
5318 if( rc ){ | 5774 if( rc ){ |
5319 releasePage(pOvfl); | 5775 releasePage(pOvfl); |
5320 } | 5776 } |
5321 } | 5777 } |
5322 #endif | 5778 #endif |
(...skipping 54 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
5377 | 5833 |
5378 /* | 5834 /* |
5379 ** Remove the i-th cell from pPage. This routine effects pPage only. | 5835 ** Remove the i-th cell from pPage. This routine effects pPage only. |
5380 ** The cell content is not freed or deallocated. It is assumed that | 5836 ** The cell content is not freed or deallocated. It is assumed that |
5381 ** the cell content has been copied someplace else. This routine just | 5837 ** the cell content has been copied someplace else. This routine just |
5382 ** removes the reference to the cell from pPage. | 5838 ** removes the reference to the cell from pPage. |
5383 ** | 5839 ** |
5384 ** "sz" must be the number of bytes in the cell. | 5840 ** "sz" must be the number of bytes in the cell. |
5385 */ | 5841 */ |
5386 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){ | 5842 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){ |
5387 int i; /* Loop counter */ | |
5388 u32 pc; /* Offset to cell content of cell being deleted */ | 5843 u32 pc; /* Offset to cell content of cell being deleted */ |
5389 u8 *data; /* pPage->aData */ | 5844 u8 *data; /* pPage->aData */ |
5390 u8 *ptr; /* Used to move bytes around within data[] */ | 5845 u8 *ptr; /* Used to move bytes around within data[] */ |
5391 int rc; /* The return code */ | 5846 int rc; /* The return code */ |
5392 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */ | 5847 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */ |
5393 | 5848 |
5394 if( *pRC ) return; | 5849 if( *pRC ) return; |
5395 | 5850 |
5396 assert( idx>=0 && idx<pPage->nCell ); | 5851 assert( idx>=0 && idx<pPage->nCell ); |
5397 assert( sz==cellSize(pPage, idx) ); | 5852 assert( sz==cellSize(pPage, idx) ); |
5398 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); | 5853 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); |
5399 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); | 5854 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); |
5400 data = pPage->aData; | 5855 data = pPage->aData; |
5401 ptr = &data[pPage->cellOffset + 2*idx]; | 5856 ptr = &pPage->aCellIdx[2*idx]; |
5402 pc = get2byte(ptr); | 5857 pc = get2byte(ptr); |
5403 hdr = pPage->hdrOffset; | 5858 hdr = pPage->hdrOffset; |
5404 testcase( pc==get2byte(&data[hdr+5]) ); | 5859 testcase( pc==get2byte(&data[hdr+5]) ); |
5405 testcase( pc+sz==pPage->pBt->usableSize ); | 5860 testcase( pc+sz==pPage->pBt->usableSize ); |
5406 if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){ | 5861 if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){ |
5407 *pRC = SQLITE_CORRUPT_BKPT; | 5862 *pRC = SQLITE_CORRUPT_BKPT; |
5408 return; | 5863 return; |
5409 } | 5864 } |
5410 rc = freeSpace(pPage, pc, sz); | 5865 rc = freeSpace(pPage, pc, sz); |
5411 if( rc ){ | 5866 if( rc ){ |
5412 *pRC = rc; | 5867 *pRC = rc; |
5413 return; | 5868 return; |
5414 } | 5869 } |
5415 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){ | |
5416 ptr[0] = ptr[2]; | |
5417 ptr[1] = ptr[3]; | |
5418 } | |
5419 pPage->nCell--; | 5870 pPage->nCell--; |
| 5871 memmove(ptr, ptr+2, 2*(pPage->nCell - idx)); |
5420 put2byte(&data[hdr+3], pPage->nCell); | 5872 put2byte(&data[hdr+3], pPage->nCell); |
5421 pPage->nFree += 2; | 5873 pPage->nFree += 2; |
5422 } | 5874 } |
5423 | 5875 |
5424 /* | 5876 /* |
5425 ** Insert a new cell on pPage at cell index "i". pCell points to the | 5877 ** Insert a new cell on pPage at cell index "i". pCell points to the |
5426 ** content of the cell. | 5878 ** content of the cell. |
5427 ** | 5879 ** |
5428 ** If the cell content will fit on the page, then put it there. If it | 5880 ** If the cell content will fit on the page, then put it there. If it |
5429 ** will not fit, then make a copy of the cell content into pTemp if | 5881 ** will not fit, then make a copy of the cell content into pTemp if |
5430 ** pTemp is not null. Regardless of pTemp, allocate a new entry | 5882 ** pTemp is not null. Regardless of pTemp, allocate a new entry |
5431 ** in pPage->aOvfl[] and make it point to the cell content (either | 5883 ** in pPage->apOvfl[] and make it point to the cell content (either |
5432 ** in pTemp or the original pCell) and also record its index. | 5884 ** in pTemp or the original pCell) and also record its index. |
5433 ** Allocating a new entry in pPage->aCell[] implies that | 5885 ** Allocating a new entry in pPage->aCell[] implies that |
5434 ** pPage->nOverflow is incremented. | 5886 ** pPage->nOverflow is incremented. |
5435 ** | |
5436 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the | |
5437 ** cell. The caller will overwrite them after this function returns. If | |
5438 ** nSkip is non-zero, then pCell may not point to an invalid memory location | |
5439 ** (but pCell+nSkip is always valid). | |
5440 */ | 5887 */ |
5441 static void insertCell( | 5888 static void insertCell( |
5442 MemPage *pPage, /* Page into which we are copying */ | 5889 MemPage *pPage, /* Page into which we are copying */ |
5443 int i, /* New cell becomes the i-th cell of the page */ | 5890 int i, /* New cell becomes the i-th cell of the page */ |
5444 u8 *pCell, /* Content of the new cell */ | 5891 u8 *pCell, /* Content of the new cell */ |
5445 int sz, /* Bytes of content in pCell */ | 5892 int sz, /* Bytes of content in pCell */ |
5446 u8 *pTemp, /* Temp storage space for pCell, if needed */ | 5893 u8 *pTemp, /* Temp storage space for pCell, if needed */ |
5447 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */ | 5894 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */ |
5448 int *pRC /* Read and write return code from here */ | 5895 int *pRC /* Read and write return code from here */ |
5449 ){ | 5896 ){ |
5450 int idx = 0; /* Where to write new cell content in data[] */ | 5897 int idx = 0; /* Where to write new cell content in data[] */ |
5451 int j; /* Loop counter */ | 5898 int j; /* Loop counter */ |
5452 int end; /* First byte past the last cell pointer in data[] */ | 5899 int end; /* First byte past the last cell pointer in data[] */ |
5453 int ins; /* Index in data[] where new cell pointer is inserted */ | 5900 int ins; /* Index in data[] where new cell pointer is inserted */ |
5454 int cellOffset; /* Address of first cell pointer in data[] */ | 5901 int cellOffset; /* Address of first cell pointer in data[] */ |
5455 u8 *data; /* The content of the whole page */ | 5902 u8 *data; /* The content of the whole page */ |
5456 u8 *ptr; /* Used for moving information around in data[] */ | |
5457 | |
5458 int nSkip = (iChild ? 4 : 0); | |
5459 | 5903 |
5460 if( *pRC ) return; | 5904 if( *pRC ) return; |
5461 | 5905 |
5462 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow ); | 5906 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow ); |
5463 assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 ); | 5907 assert( MX_CELL(pPage->pBt)<=10921 ); |
5464 assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) ); | 5908 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB ); |
| 5909 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) ); |
| 5910 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) ); |
5465 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); | 5911 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); |
5466 /* The cell should normally be sized correctly. However, when moving a | 5912 /* The cell should normally be sized correctly. However, when moving a |
5467 ** malformed cell from a leaf page to an interior page, if the cell size | 5913 ** malformed cell from a leaf page to an interior page, if the cell size |
5468 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size | 5914 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size |
5469 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence | 5915 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence |
5470 ** the term after the || in the following assert(). */ | 5916 ** the term after the || in the following assert(). */ |
5471 assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) ); | 5917 assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) ); |
5472 if( pPage->nOverflow || sz+2>pPage->nFree ){ | 5918 if( pPage->nOverflow || sz+2>pPage->nFree ){ |
5473 if( pTemp ){ | 5919 if( pTemp ){ |
5474 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip); | 5920 memcpy(pTemp, pCell, sz); |
5475 pCell = pTemp; | 5921 pCell = pTemp; |
5476 } | 5922 } |
5477 if( iChild ){ | 5923 if( iChild ){ |
5478 put4byte(pCell, iChild); | 5924 put4byte(pCell, iChild); |
5479 } | 5925 } |
5480 j = pPage->nOverflow++; | 5926 j = pPage->nOverflow++; |
5481 assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) ); | 5927 assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) ); |
5482 pPage->aOvfl[j].pCell = pCell; | 5928 pPage->apOvfl[j] = pCell; |
5483 pPage->aOvfl[j].idx = (u16)i; | 5929 pPage->aiOvfl[j] = (u16)i; |
5484 }else{ | 5930 }else{ |
5485 int rc = sqlite3PagerWrite(pPage->pDbPage); | 5931 int rc = sqlite3PagerWrite(pPage->pDbPage); |
5486 if( rc!=SQLITE_OK ){ | 5932 if( rc!=SQLITE_OK ){ |
5487 *pRC = rc; | 5933 *pRC = rc; |
5488 return; | 5934 return; |
5489 } | 5935 } |
5490 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); | 5936 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); |
5491 data = pPage->aData; | 5937 data = pPage->aData; |
5492 cellOffset = pPage->cellOffset; | 5938 cellOffset = pPage->cellOffset; |
5493 end = cellOffset + 2*pPage->nCell; | 5939 end = cellOffset + 2*pPage->nCell; |
5494 ins = cellOffset + 2*i; | 5940 ins = cellOffset + 2*i; |
5495 rc = allocateSpace(pPage, sz, &idx); | 5941 rc = allocateSpace(pPage, sz, &idx); |
5496 if( rc ){ *pRC = rc; return; } | 5942 if( rc ){ *pRC = rc; return; } |
5497 /* The allocateSpace() routine guarantees the following two properties | 5943 /* The allocateSpace() routine guarantees the following two properties |
5498 ** if it returns success */ | 5944 ** if it returns success */ |
5499 assert( idx >= end+2 ); | 5945 assert( idx >= end+2 ); |
5500 assert( idx+sz <= (int)pPage->pBt->usableSize ); | 5946 assert( idx+sz <= (int)pPage->pBt->usableSize ); |
5501 pPage->nCell++; | 5947 pPage->nCell++; |
5502 pPage->nFree -= (u16)(2 + sz); | 5948 pPage->nFree -= (u16)(2 + sz); |
5503 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip); | 5949 memcpy(&data[idx], pCell, sz); |
5504 if( iChild ){ | 5950 if( iChild ){ |
5505 put4byte(&data[idx], iChild); | 5951 put4byte(&data[idx], iChild); |
5506 } | 5952 } |
5507 for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){ | 5953 memmove(&data[ins+2], &data[ins], end-ins); |
5508 ptr[0] = ptr[-2]; | |
5509 ptr[1] = ptr[-1]; | |
5510 } | |
5511 put2byte(&data[ins], idx); | 5954 put2byte(&data[ins], idx); |
5512 put2byte(&data[pPage->hdrOffset+3], pPage->nCell); | 5955 put2byte(&data[pPage->hdrOffset+3], pPage->nCell); |
5513 #ifndef SQLITE_OMIT_AUTOVACUUM | 5956 #ifndef SQLITE_OMIT_AUTOVACUUM |
5514 if( pPage->pBt->autoVacuum ){ | 5957 if( pPage->pBt->autoVacuum ){ |
5515 /* The cell may contain a pointer to an overflow page. If so, write | 5958 /* The cell may contain a pointer to an overflow page. If so, write |
5516 ** the entry for the overflow page into the pointer map. | 5959 ** the entry for the overflow page into the pointer map. |
5517 */ | 5960 */ |
5518 ptrmapPutOvflPtr(pPage, pCell, pRC); | 5961 ptrmapPutOvflPtr(pPage, pCell, pRC); |
5519 } | 5962 } |
5520 #endif | 5963 #endif |
5521 } | 5964 } |
5522 } | 5965 } |
5523 | 5966 |
5524 /* | 5967 /* |
5525 ** Add a list of cells to a page. The page should be initially empty. | 5968 ** Add a list of cells to a page. The page should be initially empty. |
5526 ** The cells are guaranteed to fit on the page. | 5969 ** The cells are guaranteed to fit on the page. |
5527 */ | 5970 */ |
5528 static void assemblePage( | 5971 static void assemblePage( |
5529 MemPage *pPage, /* The page to be assemblied */ | 5972 MemPage *pPage, /* The page to be assembled */ |
5530 int nCell, /* The number of cells to add to this page */ | 5973 int nCell, /* The number of cells to add to this page */ |
5531 u8 **apCell, /* Pointers to cell bodies */ | 5974 u8 **apCell, /* Pointers to cell bodies */ |
5532 u16 *aSize /* Sizes of the cells */ | 5975 u16 *aSize /* Sizes of the cells */ |
5533 ){ | 5976 ){ |
5534 int i; /* Loop counter */ | 5977 int i; /* Loop counter */ |
5535 u8 *pCellptr; /* Address of next cell pointer */ | 5978 u8 *pCellptr; /* Address of next cell pointer */ |
5536 int cellbody; /* Address of next cell body */ | 5979 int cellbody; /* Address of next cell body */ |
5537 u8 * const data = pPage->aData; /* Pointer to data for pPage */ | 5980 u8 * const data = pPage->aData; /* Pointer to data for pPage */ |
5538 const int hdr = pPage->hdrOffset; /* Offset of header on pPage */ | 5981 const int hdr = pPage->hdrOffset; /* Offset of header on pPage */ |
5539 const int nUsable = pPage->pBt->usableSize; /* Usable size of page */ | 5982 const int nUsable = pPage->pBt->usableSize; /* Usable size of page */ |
5540 | 5983 |
5541 assert( pPage->nOverflow==0 ); | 5984 assert( pPage->nOverflow==0 ); |
5542 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); | 5985 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); |
5543 assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt) | 5986 assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt) |
5544 && (int)MX_CELL(pPage->pBt)<=10921); | 5987 && (int)MX_CELL(pPage->pBt)<=10921); |
5545 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); | 5988 assert( sqlite3PagerIswriteable(pPage->pDbPage) ); |
5546 | 5989 |
5547 /* Check that the page has just been zeroed by zeroPage() */ | 5990 /* Check that the page has just been zeroed by zeroPage() */ |
5548 assert( pPage->nCell==0 ); | 5991 assert( pPage->nCell==0 ); |
5549 assert( get2byteNotZero(&data[hdr+5])==nUsable ); | 5992 assert( get2byteNotZero(&data[hdr+5])==nUsable ); |
5550 | 5993 |
5551 pCellptr = &data[pPage->cellOffset + nCell*2]; | 5994 pCellptr = &pPage->aCellIdx[nCell*2]; |
5552 cellbody = nUsable; | 5995 cellbody = nUsable; |
5553 for(i=nCell-1; i>=0; i--){ | 5996 for(i=nCell-1; i>=0; i--){ |
| 5997 u16 sz = aSize[i]; |
5554 pCellptr -= 2; | 5998 pCellptr -= 2; |
5555 cellbody -= aSize[i]; | 5999 cellbody -= sz; |
5556 put2byte(pCellptr, cellbody); | 6000 put2byte(pCellptr, cellbody); |
5557 memcpy(&data[cellbody], apCell[i], aSize[i]); | 6001 memcpy(&data[cellbody], apCell[i], sz); |
5558 } | 6002 } |
5559 put2byte(&data[hdr+3], nCell); | 6003 put2byte(&data[hdr+3], nCell); |
5560 put2byte(&data[hdr+5], cellbody); | 6004 put2byte(&data[hdr+5], cellbody); |
5561 pPage->nFree -= (nCell*2 + nUsable - cellbody); | 6005 pPage->nFree -= (nCell*2 + nUsable - cellbody); |
5562 pPage->nCell = (u16)nCell; | 6006 pPage->nCell = (u16)nCell; |
5563 } | 6007 } |
5564 | 6008 |
5565 /* | 6009 /* |
5566 ** The following parameters determine how many adjacent pages get involved | 6010 ** The following parameters determine how many adjacent pages get involved |
5567 ** in a balancing operation. NN is the number of neighbors on either side | 6011 ** in a balancing operation. NN is the number of neighbors on either side |
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
5606 BtShared *const pBt = pPage->pBt; /* B-Tree Database */ | 6050 BtShared *const pBt = pPage->pBt; /* B-Tree Database */ |
5607 MemPage *pNew; /* Newly allocated page */ | 6051 MemPage *pNew; /* Newly allocated page */ |
5608 int rc; /* Return Code */ | 6052 int rc; /* Return Code */ |
5609 Pgno pgnoNew; /* Page number of pNew */ | 6053 Pgno pgnoNew; /* Page number of pNew */ |
5610 | 6054 |
5611 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); | 6055 assert( sqlite3_mutex_held(pPage->pBt->mutex) ); |
5612 assert( sqlite3PagerIswriteable(pParent->pDbPage) ); | 6056 assert( sqlite3PagerIswriteable(pParent->pDbPage) ); |
5613 assert( pPage->nOverflow==1 ); | 6057 assert( pPage->nOverflow==1 ); |
5614 | 6058 |
5615 /* This error condition is now caught prior to reaching this function */ | 6059 /* This error condition is now caught prior to reaching this function */ |
5616 if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT; | 6060 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; |
5617 | 6061 |
5618 /* Allocate a new page. This page will become the right-sibling of | 6062 /* Allocate a new page. This page will become the right-sibling of |
5619 ** pPage. Make the parent page writable, so that the new divider cell | 6063 ** pPage. Make the parent page writable, so that the new divider cell |
5620 ** may be inserted. If both these operations are successful, proceed. | 6064 ** may be inserted. If both these operations are successful, proceed. |
5621 */ | 6065 */ |
5622 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0); | 6066 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0); |
5623 | 6067 |
5624 if( rc==SQLITE_OK ){ | 6068 if( rc==SQLITE_OK ){ |
5625 | 6069 |
5626 u8 *pOut = &pSpace[4]; | 6070 u8 *pOut = &pSpace[4]; |
5627 u8 *pCell = pPage->aOvfl[0].pCell; | 6071 u8 *pCell = pPage->apOvfl[0]; |
5628 u16 szCell = cellSizePtr(pPage, pCell); | 6072 u16 szCell = cellSizePtr(pPage, pCell); |
5629 u8 *pStop; | 6073 u8 *pStop; |
5630 | 6074 |
5631 assert( sqlite3PagerIswriteable(pNew->pDbPage) ); | 6075 assert( sqlite3PagerIswriteable(pNew->pDbPage) ); |
5632 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) ); | 6076 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) ); |
5633 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF); | 6077 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF); |
5634 assemblePage(pNew, 1, &pCell, &szCell); | 6078 assemblePage(pNew, 1, &pCell, &szCell); |
5635 | 6079 |
5636 /* If this is an auto-vacuum database, update the pointer map | 6080 /* If this is an auto-vacuum database, update the pointer map |
5637 ** with entries for the new page, and any pointer from the | 6081 ** with entries for the new page, and any pointer from the |
(...skipping 89 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
5727 | 6171 |
5728 /* | 6172 /* |
5729 ** This function is used to copy the contents of the b-tree node stored | 6173 ** This function is used to copy the contents of the b-tree node stored |
5730 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then | 6174 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then |
5731 ** the pointer-map entries for each child page are updated so that the | 6175 ** the pointer-map entries for each child page are updated so that the |
5732 ** parent page stored in the pointer map is page pTo. If pFrom contained | 6176 ** parent page stored in the pointer map is page pTo. If pFrom contained |
5733 ** any cells with overflow page pointers, then the corresponding pointer | 6177 ** any cells with overflow page pointers, then the corresponding pointer |
5734 ** map entries are also updated so that the parent page is page pTo. | 6178 ** map entries are also updated so that the parent page is page pTo. |
5735 ** | 6179 ** |
5736 ** If pFrom is currently carrying any overflow cells (entries in the | 6180 ** If pFrom is currently carrying any overflow cells (entries in the |
5737 ** MemPage.aOvfl[] array), they are not copied to pTo. | 6181 ** MemPage.apOvfl[] array), they are not copied to pTo. |
5738 ** | 6182 ** |
5739 ** Before returning, page pTo is reinitialized using btreeInitPage(). | 6183 ** Before returning, page pTo is reinitialized using btreeInitPage(). |
5740 ** | 6184 ** |
5741 ** The performance of this function is not critical. It is only used by | 6185 ** The performance of this function is not critical. It is only used by |
5742 ** the balance_shallower() and balance_deeper() procedures, neither of | 6186 ** the balance_shallower() and balance_deeper() procedures, neither of |
5743 ** which are called often under normal circumstances. | 6187 ** which are called often under normal circumstances. |
5744 */ | 6188 */ |
5745 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){ | 6189 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){ |
5746 if( (*pRC)==SQLITE_OK ){ | 6190 if( (*pRC)==SQLITE_OK ){ |
5747 BtShared * const pBt = pFrom->pBt; | 6191 BtShared * const pBt = pFrom->pBt; |
(...skipping 68 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
5816 ** page (pParent) the parent page becomes overfull, this buffer is | 6260 ** page (pParent) the parent page becomes overfull, this buffer is |
5817 ** used to store the parent's overflow cells. Because this function inserts | 6261 ** used to store the parent's overflow cells. Because this function inserts |
5818 ** a maximum of four divider cells into the parent page, and the maximum | 6262 ** a maximum of four divider cells into the parent page, and the maximum |
5819 ** size of a cell stored within an internal node is always less than 1/4 | 6263 ** size of a cell stored within an internal node is always less than 1/4 |
5820 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large | 6264 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large |
5821 ** enough for all overflow cells. | 6265 ** enough for all overflow cells. |
5822 ** | 6266 ** |
5823 ** If aOvflSpace is set to a null pointer, this function returns | 6267 ** If aOvflSpace is set to a null pointer, this function returns |
5824 ** SQLITE_NOMEM. | 6268 ** SQLITE_NOMEM. |
5825 */ | 6269 */ |
| 6270 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM) |
| 6271 #pragma optimize("", off) |
| 6272 #endif |
5826 static int balance_nonroot( | 6273 static int balance_nonroot( |
5827 MemPage *pParent, /* Parent page of siblings being balanced */ | 6274 MemPage *pParent, /* Parent page of siblings being balanced */ |
5828 int iParentIdx, /* Index of "the page" in pParent */ | 6275 int iParentIdx, /* Index of "the page" in pParent */ |
5829 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */ | 6276 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */ |
5830 int isRoot /* True if pParent is a root-page */ | 6277 int isRoot, /* True if pParent is a root-page */ |
| 6278 int bBulk /* True if this call is part of a bulk load */ |
5831 ){ | 6279 ){ |
5832 BtShared *pBt; /* The whole database */ | 6280 BtShared *pBt; /* The whole database */ |
5833 int nCell = 0; /* Number of cells in apCell[] */ | 6281 int nCell = 0; /* Number of cells in apCell[] */ |
5834 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */ | 6282 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */ |
5835 int nNew = 0; /* Number of pages in apNew[] */ | 6283 int nNew = 0; /* Number of pages in apNew[] */ |
5836 int nOld; /* Number of pages in apOld[] */ | 6284 int nOld; /* Number of pages in apOld[] */ |
5837 int i, j, k; /* Loop counters */ | 6285 int i, j, k; /* Loop counters */ |
5838 int nxDiv; /* Next divider slot in pParent->aCell[] */ | 6286 int nxDiv; /* Next divider slot in pParent->aCell[] */ |
5839 int rc = SQLITE_OK; /* The return code */ | 6287 int rc = SQLITE_OK; /* The return code */ |
5840 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */ | 6288 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */ |
(...skipping 23 matching lines...) Expand all Loading... |
5864 #if 0 | 6312 #if 0 |
5865 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno)); | 6313 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno)); |
5866 #endif | 6314 #endif |
5867 | 6315 |
5868 /* At this point pParent may have at most one overflow cell. And if | 6316 /* At this point pParent may have at most one overflow cell. And if |
5869 ** this overflow cell is present, it must be the cell with | 6317 ** this overflow cell is present, it must be the cell with |
5870 ** index iParentIdx. This scenario comes about when this function | 6318 ** index iParentIdx. This scenario comes about when this function |
5871 ** is called (indirectly) from sqlite3BtreeDelete(). | 6319 ** is called (indirectly) from sqlite3BtreeDelete(). |
5872 */ | 6320 */ |
5873 assert( pParent->nOverflow==0 || pParent->nOverflow==1 ); | 6321 assert( pParent->nOverflow==0 || pParent->nOverflow==1 ); |
5874 assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx ); | 6322 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx ); |
5875 | 6323 |
5876 if( !aOvflSpace ){ | 6324 if( !aOvflSpace ){ |
5877 return SQLITE_NOMEM; | 6325 return SQLITE_NOMEM; |
5878 } | 6326 } |
5879 | 6327 |
5880 /* Find the sibling pages to balance. Also locate the cells in pParent | 6328 /* Find the sibling pages to balance. Also locate the cells in pParent |
5881 ** that divide the siblings. An attempt is made to find NN siblings on | 6329 ** that divide the siblings. An attempt is made to find NN siblings on |
5882 ** either side of pPage. More siblings are taken from one side, however, | 6330 ** either side of pPage. More siblings are taken from one side, however, |
5883 ** if there are fewer than NN siblings on the other side. If pParent | 6331 ** if there are fewer than NN siblings on the other side. If pParent |
5884 ** has NB or fewer children then all children of pParent are taken. | 6332 ** has NB or fewer children then all children of pParent are taken. |
5885 ** | 6333 ** |
5886 ** This loop also drops the divider cells from the parent page. This | 6334 ** This loop also drops the divider cells from the parent page. This |
5887 ** way, the remainder of the function does not have to deal with any | 6335 ** way, the remainder of the function does not have to deal with any |
5888 ** overflow cells in the parent page, since if any existed they will | 6336 ** overflow cells in the parent page, since if any existed they will |
5889 ** have already been removed. | 6337 ** have already been removed. |
5890 */ | 6338 */ |
5891 i = pParent->nOverflow + pParent->nCell; | 6339 i = pParent->nOverflow + pParent->nCell; |
5892 if( i<2 ){ | 6340 if( i<2 ){ |
5893 nxDiv = 0; | 6341 nxDiv = 0; |
5894 nOld = i+1; | |
5895 }else{ | 6342 }else{ |
5896 nOld = 3; | 6343 assert( bBulk==0 || bBulk==1 ); |
5897 if( iParentIdx==0 ){ | 6344 if( iParentIdx==0 ){ |
5898 nxDiv = 0; | 6345 nxDiv = 0; |
5899 }else if( iParentIdx==i ){ | 6346 }else if( iParentIdx==i ){ |
5900 nxDiv = i-2; | 6347 nxDiv = i-2+bBulk; |
5901 }else{ | 6348 }else{ |
| 6349 assert( bBulk==0 ); |
5902 nxDiv = iParentIdx-1; | 6350 nxDiv = iParentIdx-1; |
5903 } | 6351 } |
5904 i = 2; | 6352 i = 2-bBulk; |
5905 } | 6353 } |
| 6354 nOld = i+1; |
5906 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){ | 6355 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){ |
5907 pRight = &pParent->aData[pParent->hdrOffset+8]; | 6356 pRight = &pParent->aData[pParent->hdrOffset+8]; |
5908 }else{ | 6357 }else{ |
5909 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow); | 6358 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow); |
5910 } | 6359 } |
5911 pgno = get4byte(pRight); | 6360 pgno = get4byte(pRight); |
5912 while( 1 ){ | 6361 while( 1 ){ |
5913 rc = getAndInitPage(pBt, pgno, &apOld[i]); | 6362 rc = getAndInitPage(pBt, pgno, &apOld[i], 0); |
5914 if( rc ){ | 6363 if( rc ){ |
5915 memset(apOld, 0, (i+1)*sizeof(MemPage*)); | 6364 memset(apOld, 0, (i+1)*sizeof(MemPage*)); |
5916 goto balance_cleanup; | 6365 goto balance_cleanup; |
5917 } | 6366 } |
5918 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow; | 6367 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow; |
5919 if( (i--)==0 ) break; | 6368 if( (i--)==0 ) break; |
5920 | 6369 |
5921 if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){ | 6370 if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){ |
5922 apDiv[i] = pParent->aOvfl[0].pCell; | 6371 apDiv[i] = pParent->apOvfl[0]; |
5923 pgno = get4byte(apDiv[i]); | 6372 pgno = get4byte(apDiv[i]); |
5924 szNew[i] = cellSizePtr(pParent, apDiv[i]); | 6373 szNew[i] = cellSizePtr(pParent, apDiv[i]); |
5925 pParent->nOverflow = 0; | 6374 pParent->nOverflow = 0; |
5926 }else{ | 6375 }else{ |
5927 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow); | 6376 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow); |
5928 pgno = get4byte(apDiv[i]); | 6377 pgno = get4byte(apDiv[i]); |
5929 szNew[i] = cellSizePtr(pParent, apDiv[i]); | 6378 szNew[i] = cellSizePtr(pParent, apDiv[i]); |
5930 | 6379 |
5931 /* Drop the cell from the parent page. apDiv[i] still points to | 6380 /* Drop the cell from the parent page. apDiv[i] still points to |
5932 ** the cell within the parent, even though it has been dropped. | 6381 ** the cell within the parent, even though it has been dropped. |
5933 ** This is safe because dropping a cell only overwrites the first | 6382 ** This is safe because dropping a cell only overwrites the first |
5934 ** four bytes of it, and this function does not need the first | 6383 ** four bytes of it, and this function does not need the first |
5935 ** four bytes of the divider cell. So the pointer is safe to use | 6384 ** four bytes of the divider cell. So the pointer is safe to use |
5936 ** later on. | 6385 ** later on. |
5937 ** | 6386 ** |
5938 ** Unless SQLite is compiled in secure-delete mode. In this case, | 6387 ** But not if we are in secure-delete mode. In secure-delete mode, |
5939 ** the dropCell() routine will overwrite the entire cell with zeroes. | 6388 ** the dropCell() routine will overwrite the entire cell with zeroes. |
5940 ** In this case, temporarily copy the cell into the aOvflSpace[] | 6389 ** In this case, temporarily copy the cell into the aOvflSpace[] |
5941 ** buffer. It will be copied out again as soon as the aSpace[] buffer | 6390 ** buffer. It will be copied out again as soon as the aSpace[] buffer |
5942 ** is allocated. */ | 6391 ** is allocated. */ |
5943 if( pBt->secureDelete ){ | 6392 if( pBt->btsFlags & BTS_SECURE_DELETE ){ |
5944 int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aDat
a); | 6393 int iOff; |
| 6394 |
| 6395 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData); |
5945 if( (iOff+szNew[i])>(int)pBt->usableSize ){ | 6396 if( (iOff+szNew[i])>(int)pBt->usableSize ){ |
5946 rc = SQLITE_CORRUPT_BKPT; | 6397 rc = SQLITE_CORRUPT_BKPT; |
5947 memset(apOld, 0, (i+1)*sizeof(MemPage*)); | 6398 memset(apOld, 0, (i+1)*sizeof(MemPage*)); |
5948 goto balance_cleanup; | 6399 goto balance_cleanup; |
5949 }else{ | 6400 }else{ |
5950 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]); | 6401 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]); |
5951 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData]; | 6402 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData]; |
5952 } | 6403 } |
5953 } | 6404 } |
5954 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc); | 6405 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc); |
(...skipping 18 matching lines...) Expand all Loading... |
5973 rc = SQLITE_NOMEM; | 6424 rc = SQLITE_NOMEM; |
5974 goto balance_cleanup; | 6425 goto balance_cleanup; |
5975 } | 6426 } |
5976 szCell = (u16*)&apCell[nMaxCells]; | 6427 szCell = (u16*)&apCell[nMaxCells]; |
5977 aSpace1 = (u8*)&szCell[nMaxCells]; | 6428 aSpace1 = (u8*)&szCell[nMaxCells]; |
5978 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) ); | 6429 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) ); |
5979 | 6430 |
5980 /* | 6431 /* |
5981 ** Load pointers to all cells on sibling pages and the divider cells | 6432 ** Load pointers to all cells on sibling pages and the divider cells |
5982 ** into the local apCell[] array. Make copies of the divider cells | 6433 ** into the local apCell[] array. Make copies of the divider cells |
5983 ** into space obtained from aSpace1[] and remove the the divider Cells | 6434 ** into space obtained from aSpace1[] and remove the divider cells |
5984 ** from pParent. | 6435 ** from pParent. |
5985 ** | 6436 ** |
5986 ** If the siblings are on leaf pages, then the child pointers of the | 6437 ** If the siblings are on leaf pages, then the child pointers of the |
5987 ** divider cells are stripped from the cells before they are copied | 6438 ** divider cells are stripped from the cells before they are copied |
5988 ** into aSpace1[]. In this way, all cells in apCell[] are without | 6439 ** into aSpace1[]. In this way, all cells in apCell[] are without |
5989 ** child pointers. If siblings are not leaves, then all cell in | 6440 ** child pointers. If siblings are not leaves, then all cell in |
5990 ** apCell[] include child pointers. Either way, all cells in apCell[] | 6441 ** apCell[] include child pointers. Either way, all cells in apCell[] |
5991 ** are alike. | 6442 ** are alike. |
5992 ** | 6443 ** |
5993 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf. | 6444 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf. |
5994 ** leafData: 1 if pPage holds key+data and pParent holds only keys. | 6445 ** leafData: 1 if pPage holds key+data and pParent holds only keys. |
5995 */ | 6446 */ |
5996 leafCorrection = apOld[0]->leaf*4; | 6447 leafCorrection = apOld[0]->leaf*4; |
5997 leafData = apOld[0]->hasData; | 6448 leafData = apOld[0]->intKeyLeaf; |
5998 for(i=0; i<nOld; i++){ | 6449 for(i=0; i<nOld; i++){ |
5999 int limit; | 6450 int limit; |
6000 | 6451 |
6001 /* Before doing anything else, take a copy of the i'th original sibling | 6452 /* Before doing anything else, take a copy of the i'th original sibling |
6002 ** The rest of this function will use data from the copies rather | 6453 ** The rest of this function will use data from the copies rather |
6003 ** that the original pages since the original pages will be in the | 6454 ** that the original pages since the original pages will be in the |
6004 ** process of being overwritten. */ | 6455 ** process of being overwritten. */ |
6005 MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i]; | 6456 MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i]; |
6006 memcpy(pOld, apOld[i], sizeof(MemPage)); | 6457 memcpy(pOld, apOld[i], sizeof(MemPage)); |
6007 pOld->aData = (void*)&pOld[1]; | 6458 pOld->aData = (void*)&pOld[1]; |
6008 memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize); | 6459 memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize); |
6009 | 6460 |
6010 limit = pOld->nCell+pOld->nOverflow; | 6461 limit = pOld->nCell+pOld->nOverflow; |
6011 for(j=0; j<limit; j++){ | 6462 if( pOld->nOverflow>0 ){ |
6012 assert( nCell<nMaxCells ); | 6463 for(j=0; j<limit; j++){ |
6013 apCell[nCell] = findOverflowCell(pOld, j); | 6464 assert( nCell<nMaxCells ); |
6014 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]); | 6465 apCell[nCell] = findOverflowCell(pOld, j); |
6015 nCell++; | 6466 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]); |
6016 } | 6467 nCell++; |
| 6468 } |
| 6469 }else{ |
| 6470 u8 *aData = pOld->aData; |
| 6471 u16 maskPage = pOld->maskPage; |
| 6472 u16 cellOffset = pOld->cellOffset; |
| 6473 for(j=0; j<limit; j++){ |
| 6474 assert( nCell<nMaxCells ); |
| 6475 apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j); |
| 6476 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]); |
| 6477 nCell++; |
| 6478 } |
| 6479 } |
6017 if( i<nOld-1 && !leafData){ | 6480 if( i<nOld-1 && !leafData){ |
6018 u16 sz = (u16)szNew[i]; | 6481 u16 sz = (u16)szNew[i]; |
6019 u8 *pTemp; | 6482 u8 *pTemp; |
6020 assert( nCell<nMaxCells ); | 6483 assert( nCell<nMaxCells ); |
6021 szCell[nCell] = sz; | 6484 szCell[nCell] = sz; |
6022 pTemp = &aSpace1[iSpace1]; | 6485 pTemp = &aSpace1[iSpace1]; |
6023 iSpace1 += sz; | 6486 iSpace1 += sz; |
6024 assert( sz<=pBt->maxLocal+23 ); | 6487 assert( sz<=pBt->maxLocal+23 ); |
6025 assert( iSpace1 <= (int)pBt->pageSize ); | 6488 assert( iSpace1 <= (int)pBt->pageSize ); |
6026 memcpy(pTemp, apDiv[i], sz); | 6489 memcpy(pTemp, apDiv[i], sz); |
(...skipping 63 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
6090 for(i=k-1; i>0; i--){ | 6553 for(i=k-1; i>0; i--){ |
6091 int szRight = szNew[i]; /* Size of sibling on the right */ | 6554 int szRight = szNew[i]; /* Size of sibling on the right */ |
6092 int szLeft = szNew[i-1]; /* Size of sibling on the left */ | 6555 int szLeft = szNew[i-1]; /* Size of sibling on the left */ |
6093 int r; /* Index of right-most cell in left sibling */ | 6556 int r; /* Index of right-most cell in left sibling */ |
6094 int d; /* Index of first cell to the left of right sibling */ | 6557 int d; /* Index of first cell to the left of right sibling */ |
6095 | 6558 |
6096 r = cntNew[i-1] - 1; | 6559 r = cntNew[i-1] - 1; |
6097 d = r + 1 - leafData; | 6560 d = r + 1 - leafData; |
6098 assert( d<nMaxCells ); | 6561 assert( d<nMaxCells ); |
6099 assert( r<nMaxCells ); | 6562 assert( r<nMaxCells ); |
6100 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){ | 6563 while( szRight==0 |
| 6564 || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2)) |
| 6565 ){ |
6101 szRight += szCell[d] + 2; | 6566 szRight += szCell[d] + 2; |
6102 szLeft -= szCell[r] + 2; | 6567 szLeft -= szCell[r] + 2; |
6103 cntNew[i-1]--; | 6568 cntNew[i-1]--; |
6104 r = cntNew[i-1] - 1; | 6569 r = cntNew[i-1] - 1; |
6105 d = r + 1 - leafData; | 6570 d = r + 1 - leafData; |
6106 } | 6571 } |
6107 szNew[i] = szRight; | 6572 szNew[i] = szRight; |
6108 szNew[i-1] = szLeft; | 6573 szNew[i-1] = szLeft; |
6109 } | 6574 } |
6110 | 6575 |
6111 /* Either we found one or more cells (cntnew[0])>0) or pPage is | 6576 /* Either we found one or more cells (cntnew[0])>0) or pPage is |
6112 ** a virtual root page. A virtual root page is when the real root | 6577 ** a virtual root page. A virtual root page is when the real root |
6113 ** page is page 1 and we are the only child of that page. | 6578 ** page is page 1 and we are the only child of that page. |
| 6579 ** |
| 6580 ** UPDATE: The assert() below is not necessarily true if the database |
| 6581 ** file is corrupt. The corruption will be detected and reported later |
| 6582 ** in this procedure so there is no need to act upon it now. |
6114 */ | 6583 */ |
| 6584 #if 0 |
6115 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) ); | 6585 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) ); |
| 6586 #endif |
6116 | 6587 |
6117 TRACE(("BALANCE: old: %d %d %d ", | 6588 TRACE(("BALANCE: old: %d %d %d ", |
6118 apOld[0]->pgno, | 6589 apOld[0]->pgno, |
6119 nOld>=2 ? apOld[1]->pgno : 0, | 6590 nOld>=2 ? apOld[1]->pgno : 0, |
6120 nOld>=3 ? apOld[2]->pgno : 0 | 6591 nOld>=3 ? apOld[2]->pgno : 0 |
6121 )); | 6592 )); |
6122 | 6593 |
6123 /* | 6594 /* |
6124 ** Allocate k new pages. Reuse old pages where possible. | 6595 ** Allocate k new pages. Reuse old pages where possible. |
6125 */ | 6596 */ |
6126 if( apOld[0]->pgno<=1 ){ | 6597 if( apOld[0]->pgno<=1 ){ |
6127 rc = SQLITE_CORRUPT_BKPT; | 6598 rc = SQLITE_CORRUPT_BKPT; |
6128 goto balance_cleanup; | 6599 goto balance_cleanup; |
6129 } | 6600 } |
6130 pageFlags = apOld[0]->aData[0]; | 6601 pageFlags = apOld[0]->aData[0]; |
6131 for(i=0; i<k; i++){ | 6602 for(i=0; i<k; i++){ |
6132 MemPage *pNew; | 6603 MemPage *pNew; |
6133 if( i<nOld ){ | 6604 if( i<nOld ){ |
6134 pNew = apNew[i] = apOld[i]; | 6605 pNew = apNew[i] = apOld[i]; |
6135 apOld[i] = 0; | 6606 apOld[i] = 0; |
6136 rc = sqlite3PagerWrite(pNew->pDbPage); | 6607 rc = sqlite3PagerWrite(pNew->pDbPage); |
6137 nNew++; | 6608 nNew++; |
6138 if( rc ) goto balance_cleanup; | 6609 if( rc ) goto balance_cleanup; |
6139 }else{ | 6610 }else{ |
6140 assert( i>0 ); | 6611 assert( i>0 ); |
6141 rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0); | 6612 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0); |
6142 if( rc ) goto balance_cleanup; | 6613 if( rc ) goto balance_cleanup; |
6143 apNew[i] = pNew; | 6614 apNew[i] = pNew; |
6144 nNew++; | 6615 nNew++; |
6145 | 6616 |
6146 /* Set the pointer-map entry for the new sibling page. */ | 6617 /* Set the pointer-map entry for the new sibling page. */ |
6147 if( ISAUTOVACUUM ){ | 6618 if( ISAUTOVACUUM ){ |
6148 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc); | 6619 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc); |
6149 if( rc!=SQLITE_OK ){ | 6620 if( rc!=SQLITE_OK ){ |
6150 goto balance_cleanup; | 6621 goto balance_cleanup; |
6151 } | 6622 } |
6152 } | 6623 } |
6153 } | 6624 } |
6154 } | 6625 } |
6155 | 6626 |
6156 /* Free any old pages that were not reused as new pages. | 6627 /* Free any old pages that were not reused as new pages. |
6157 */ | 6628 */ |
6158 while( i<nOld ){ | 6629 while( i<nOld ){ |
6159 freePage(apOld[i], &rc); | 6630 freePage(apOld[i], &rc); |
6160 if( rc ) goto balance_cleanup; | 6631 if( rc ) goto balance_cleanup; |
6161 releasePage(apOld[i]); | 6632 releasePage(apOld[i]); |
6162 apOld[i] = 0; | 6633 apOld[i] = 0; |
6163 i++; | 6634 i++; |
6164 } | 6635 } |
6165 | 6636 |
6166 /* | 6637 /* |
6167 ** Put the new pages in accending order. This helps to | 6638 ** Put the new pages in ascending order. This helps to |
6168 ** keep entries in the disk file in order so that a scan | 6639 ** keep entries in the disk file in order so that a scan |
6169 ** of the table is a linear scan through the file. That | 6640 ** of the table is a linear scan through the file. That |
6170 ** in turn helps the operating system to deliver pages | 6641 ** in turn helps the operating system to deliver pages |
6171 ** from the disk more rapidly. | 6642 ** from the disk more rapidly. |
6172 ** | 6643 ** |
6173 ** An O(n^2) insertion sort algorithm is used, but since | 6644 ** An O(n^2) insertion sort algorithm is used, but since |
6174 ** n is never more than NB (a small constant), that should | 6645 ** n is never more than NB (a small constant), that should |
6175 ** not be a problem. | 6646 ** not be a problem. |
6176 ** | 6647 ** |
6177 ** When NB==3, this one optimization makes the database | 6648 ** When NB==3, this one optimization makes the database |
(...skipping 155 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
6333 ** | 6804 ** |
6334 ** Cases 1 and 2 are dealt with above by other code. The next | 6805 ** Cases 1 and 2 are dealt with above by other code. The next |
6335 ** block deals with cases 3 and 4 and the one after that, case 5. Since | 6806 ** block deals with cases 3 and 4 and the one after that, case 5. Since |
6336 ** setting a pointer map entry is a relatively expensive operation, this | 6807 ** setting a pointer map entry is a relatively expensive operation, this |
6337 ** code only sets pointer map entries for child or overflow pages that have | 6808 ** code only sets pointer map entries for child or overflow pages that have |
6338 ** actually moved between pages. */ | 6809 ** actually moved between pages. */ |
6339 MemPage *pNew = apNew[0]; | 6810 MemPage *pNew = apNew[0]; |
6340 MemPage *pOld = apCopy[0]; | 6811 MemPage *pOld = apCopy[0]; |
6341 int nOverflow = pOld->nOverflow; | 6812 int nOverflow = pOld->nOverflow; |
6342 int iNextOld = pOld->nCell + nOverflow; | 6813 int iNextOld = pOld->nCell + nOverflow; |
6343 int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1); | 6814 int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1); |
6344 j = 0; /* Current 'old' sibling page */ | 6815 j = 0; /* Current 'old' sibling page */ |
6345 k = 0; /* Current 'new' sibling page */ | 6816 k = 0; /* Current 'new' sibling page */ |
6346 for(i=0; i<nCell; i++){ | 6817 for(i=0; i<nCell; i++){ |
6347 int isDivider = 0; | 6818 int isDivider = 0; |
6348 while( i==iNextOld ){ | 6819 while( i==iNextOld ){ |
6349 /* Cell i is the cell immediately following the last cell on old | 6820 /* Cell i is the cell immediately following the last cell on old |
6350 ** sibling page j. If the siblings are not leaf pages of an | 6821 ** sibling page j. If the siblings are not leaf pages of an |
6351 ** intkey b-tree, then cell i was a divider cell. */ | 6822 ** intkey b-tree, then cell i was a divider cell. */ |
| 6823 assert( j+1 < ArraySize(apCopy) ); |
| 6824 assert( j+1 < nOld ); |
6352 pOld = apCopy[++j]; | 6825 pOld = apCopy[++j]; |
6353 iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow; | 6826 iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow; |
6354 if( pOld->nOverflow ){ | 6827 if( pOld->nOverflow ){ |
6355 nOverflow = pOld->nOverflow; | 6828 nOverflow = pOld->nOverflow; |
6356 iOverflow = i + !leafData + pOld->aOvfl[0].idx; | 6829 iOverflow = i + !leafData + pOld->aiOvfl[0]; |
6357 } | 6830 } |
6358 isDivider = !leafData; | 6831 isDivider = !leafData; |
6359 } | 6832 } |
6360 | 6833 |
6361 assert(nOverflow>0 || iOverflow<i ); | 6834 assert(nOverflow>0 || iOverflow<i ); |
6362 assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1); | 6835 assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1); |
6363 assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1); | 6836 assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1); |
6364 if( i==iOverflow ){ | 6837 if( i==iOverflow ){ |
6365 isDivider = 1; | 6838 isDivider = 1; |
6366 if( (--nOverflow)>0 ){ | 6839 if( (--nOverflow)>0 ){ |
6367 iOverflow++; | 6840 iOverflow++; |
6368 } | 6841 } |
6369 } | 6842 } |
6370 | 6843 |
6371 if( i==cntNew[k] ){ | 6844 if( i==cntNew[k] ){ |
6372 /* Cell i is the cell immediately following the last cell on new | 6845 /* Cell i is the cell immediately following the last cell on new |
6373 ** sibling page k. If the siblings are not leaf pages of an | 6846 ** sibling page k. If the siblings are not leaf pages of an |
(...skipping 46 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
6420 sqlite3ScratchFree(apCell); | 6893 sqlite3ScratchFree(apCell); |
6421 for(i=0; i<nOld; i++){ | 6894 for(i=0; i<nOld; i++){ |
6422 releasePage(apOld[i]); | 6895 releasePage(apOld[i]); |
6423 } | 6896 } |
6424 for(i=0; i<nNew; i++){ | 6897 for(i=0; i<nNew; i++){ |
6425 releasePage(apNew[i]); | 6898 releasePage(apNew[i]); |
6426 } | 6899 } |
6427 | 6900 |
6428 return rc; | 6901 return rc; |
6429 } | 6902 } |
| 6903 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM) |
| 6904 #pragma optimize("", on) |
| 6905 #endif |
6430 | 6906 |
6431 | 6907 |
6432 /* | 6908 /* |
6433 ** This function is called when the root page of a b-tree structure is | 6909 ** This function is called when the root page of a b-tree structure is |
6434 ** overfull (has one or more overflow pages). | 6910 ** overfull (has one or more overflow pages). |
6435 ** | 6911 ** |
6436 ** A new child page is allocated and the contents of the current root | 6912 ** A new child page is allocated and the contents of the current root |
6437 ** page, including overflow cells, are copied into the child. The root | 6913 ** page, including overflow cells, are copied into the child. The root |
6438 ** page is then overwritten to make it an empty page with the right-child | 6914 ** page is then overwritten to make it an empty page with the right-child |
6439 ** pointer pointing to the new page. | 6915 ** pointer pointing to the new page. |
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
6474 releasePage(pChild); | 6950 releasePage(pChild); |
6475 return rc; | 6951 return rc; |
6476 } | 6952 } |
6477 assert( sqlite3PagerIswriteable(pChild->pDbPage) ); | 6953 assert( sqlite3PagerIswriteable(pChild->pDbPage) ); |
6478 assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); | 6954 assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); |
6479 assert( pChild->nCell==pRoot->nCell ); | 6955 assert( pChild->nCell==pRoot->nCell ); |
6480 | 6956 |
6481 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno)); | 6957 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno)); |
6482 | 6958 |
6483 /* Copy the overflow cells from pRoot to pChild */ | 6959 /* Copy the overflow cells from pRoot to pChild */ |
6484 memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0])); | 6960 memcpy(pChild->aiOvfl, pRoot->aiOvfl, |
| 6961 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0])); |
| 6962 memcpy(pChild->apOvfl, pRoot->apOvfl, |
| 6963 pRoot->nOverflow*sizeof(pRoot->apOvfl[0])); |
6485 pChild->nOverflow = pRoot->nOverflow; | 6964 pChild->nOverflow = pRoot->nOverflow; |
6486 | 6965 |
6487 /* Zero the contents of pRoot. Then install pChild as the right-child. */ | 6966 /* Zero the contents of pRoot. Then install pChild as the right-child. */ |
6488 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF); | 6967 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF); |
6489 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild); | 6968 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild); |
6490 | 6969 |
6491 *ppChild = pChild; | 6970 *ppChild = pChild; |
6492 return SQLITE_OK; | 6971 return SQLITE_OK; |
6493 } | 6972 } |
6494 | 6973 |
(...skipping 40 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
6535 } | 7014 } |
6536 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){ | 7015 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){ |
6537 break; | 7016 break; |
6538 }else{ | 7017 }else{ |
6539 MemPage * const pParent = pCur->apPage[iPage-1]; | 7018 MemPage * const pParent = pCur->apPage[iPage-1]; |
6540 int const iIdx = pCur->aiIdx[iPage-1]; | 7019 int const iIdx = pCur->aiIdx[iPage-1]; |
6541 | 7020 |
6542 rc = sqlite3PagerWrite(pParent->pDbPage); | 7021 rc = sqlite3PagerWrite(pParent->pDbPage); |
6543 if( rc==SQLITE_OK ){ | 7022 if( rc==SQLITE_OK ){ |
6544 #ifndef SQLITE_OMIT_QUICKBALANCE | 7023 #ifndef SQLITE_OMIT_QUICKBALANCE |
6545 if( pPage->hasData | 7024 if( pPage->intKeyLeaf |
6546 && pPage->nOverflow==1 | 7025 && pPage->nOverflow==1 |
6547 && pPage->aOvfl[0].idx==pPage->nCell | 7026 && pPage->aiOvfl[0]==pPage->nCell |
6548 && pParent->pgno!=1 | 7027 && pParent->pgno!=1 |
6549 && pParent->nCell==iIdx | 7028 && pParent->nCell==iIdx |
6550 ){ | 7029 ){ |
6551 /* Call balance_quick() to create a new sibling of pPage on which | 7030 /* Call balance_quick() to create a new sibling of pPage on which |
6552 ** to store the overflow cell. balance_quick() inserts a new cell | 7031 ** to store the overflow cell. balance_quick() inserts a new cell |
6553 ** into pParent, which may cause pParent overflow. If this | 7032 ** into pParent, which may cause pParent overflow. If this |
6554 ** happens, the next interation of the do-loop will balance pParent | 7033 ** happens, the next iteration of the do-loop will balance pParent |
6555 ** use either balance_nonroot() or balance_deeper(). Until this | 7034 ** use either balance_nonroot() or balance_deeper(). Until this |
6556 ** happens, the overflow cell is stored in the aBalanceQuickSpace[] | 7035 ** happens, the overflow cell is stored in the aBalanceQuickSpace[] |
6557 ** buffer. | 7036 ** buffer. |
6558 ** | 7037 ** |
6559 ** The purpose of the following assert() is to check that only a | 7038 ** The purpose of the following assert() is to check that only a |
6560 ** single call to balance_quick() is made for each call to this | 7039 ** single call to balance_quick() is made for each call to this |
6561 ** function. If this were not verified, a subtle bug involving reuse | 7040 ** function. If this were not verified, a subtle bug involving reuse |
6562 ** of the aBalanceQuickSpace[] might sneak in. | 7041 ** of the aBalanceQuickSpace[] might sneak in. |
6563 */ | 7042 */ |
6564 assert( (balance_quick_called++)==0 ); | 7043 assert( (balance_quick_called++)==0 ); |
(...skipping 12 matching lines...) Expand all Loading... |
6577 ** A subsequent iteration of the do-loop will deal with this by | 7056 ** A subsequent iteration of the do-loop will deal with this by |
6578 ** calling balance_nonroot() (balance_deeper() may be called first, | 7057 ** calling balance_nonroot() (balance_deeper() may be called first, |
6579 ** but it doesn't deal with overflow cells - just moves them to a | 7058 ** but it doesn't deal with overflow cells - just moves them to a |
6580 ** different page). Once this subsequent call to balance_nonroot() | 7059 ** different page). Once this subsequent call to balance_nonroot() |
6581 ** has completed, it is safe to release the pSpace buffer used by | 7060 ** has completed, it is safe to release the pSpace buffer used by |
6582 ** the previous call, as the overflow cell data will have been | 7061 ** the previous call, as the overflow cell data will have been |
6583 ** copied either into the body of a database page or into the new | 7062 ** copied either into the body of a database page or into the new |
6584 ** pSpace buffer passed to the latter call to balance_nonroot(). | 7063 ** pSpace buffer passed to the latter call to balance_nonroot(). |
6585 */ | 7064 */ |
6586 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize); | 7065 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize); |
6587 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1); | 7066 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints); |
6588 if( pFree ){ | 7067 if( pFree ){ |
6589 /* If pFree is not NULL, it points to the pSpace buffer used | 7068 /* If pFree is not NULL, it points to the pSpace buffer used |
6590 ** by a previous call to balance_nonroot(). Its contents are | 7069 ** by a previous call to balance_nonroot(). Its contents are |
6591 ** now stored either on real database pages or within the | 7070 ** now stored either on real database pages or within the |
6592 ** new pSpace buffer, so it may be safely freed here. */ | 7071 ** new pSpace buffer, so it may be safely freed here. */ |
6593 sqlite3PageFree(pFree); | 7072 sqlite3PageFree(pFree); |
6594 } | 7073 } |
6595 | 7074 |
6596 /* The pSpace buffer will be freed after the next call to | 7075 /* The pSpace buffer will be freed after the next call to |
6597 ** balance_nonroot(), or just before this function returns, whichever | 7076 ** balance_nonroot(), or just before this function returns, whichever |
(...skipping 23 matching lines...) Expand all Loading... |
6621 ** define what table the record should be inserted into. The cursor | 7100 ** define what table the record should be inserted into. The cursor |
6622 ** is left pointing at a random location. | 7101 ** is left pointing at a random location. |
6623 ** | 7102 ** |
6624 ** For an INTKEY table, only the nKey value of the key is used. pKey is | 7103 ** For an INTKEY table, only the nKey value of the key is used. pKey is |
6625 ** ignored. For a ZERODATA table, the pData and nData are both ignored. | 7104 ** ignored. For a ZERODATA table, the pData and nData are both ignored. |
6626 ** | 7105 ** |
6627 ** If the seekResult parameter is non-zero, then a successful call to | 7106 ** If the seekResult parameter is non-zero, then a successful call to |
6628 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already | 7107 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already |
6629 ** been performed. seekResult is the search result returned (a negative | 7108 ** been performed. seekResult is the search result returned (a negative |
6630 ** number if pCur points at an entry that is smaller than (pKey, nKey), or | 7109 ** number if pCur points at an entry that is smaller than (pKey, nKey), or |
6631 ** a positive value if pCur points at an etry that is larger than | 7110 ** a positive value if pCur points at an entry that is larger than |
6632 ** (pKey, nKey)). | 7111 ** (pKey, nKey)). |
6633 ** | 7112 ** |
6634 ** If the seekResult parameter is non-zero, then the caller guarantees that | 7113 ** If the seekResult parameter is non-zero, then the caller guarantees that |
6635 ** cursor pCur is pointing at the existing copy of a row that is to be | 7114 ** cursor pCur is pointing at the existing copy of a row that is to be |
6636 ** overwritten. If the seekResult parameter is 0, then cursor pCur may | 7115 ** overwritten. If the seekResult parameter is 0, then cursor pCur may |
6637 ** point to any entry or to no entry at all and so this function has to seek | 7116 ** point to any entry or to no entry at all and so this function has to seek |
6638 ** the cursor before the new key can be inserted. | 7117 ** the cursor before the new key can be inserted. |
6639 */ | 7118 */ |
6640 int sqlite3BtreeInsert( | 7119 int sqlite3BtreeInsert( |
6641 BtCursor *pCur, /* Insert data into the table of this cursor */ | 7120 BtCursor *pCur, /* Insert data into the table of this cursor */ |
(...skipping 12 matching lines...) Expand all Loading... |
6654 BtShared *pBt = p->pBt; | 7133 BtShared *pBt = p->pBt; |
6655 unsigned char *oldCell; | 7134 unsigned char *oldCell; |
6656 unsigned char *newCell = 0; | 7135 unsigned char *newCell = 0; |
6657 | 7136 |
6658 if( pCur->eState==CURSOR_FAULT ){ | 7137 if( pCur->eState==CURSOR_FAULT ){ |
6659 assert( pCur->skipNext!=SQLITE_OK ); | 7138 assert( pCur->skipNext!=SQLITE_OK ); |
6660 return pCur->skipNext; | 7139 return pCur->skipNext; |
6661 } | 7140 } |
6662 | 7141 |
6663 assert( cursorHoldsMutex(pCur) ); | 7142 assert( cursorHoldsMutex(pCur) ); |
6664 assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly ); | 7143 assert( (pCur->curFlags & BTCF_WriteFlag)!=0 |
| 7144 && pBt->inTransaction==TRANS_WRITE |
| 7145 && (pBt->btsFlags & BTS_READ_ONLY)==0 ); |
6665 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); | 7146 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); |
6666 | 7147 |
6667 /* Assert that the caller has been consistent. If this cursor was opened | 7148 /* Assert that the caller has been consistent. If this cursor was opened |
6668 ** expecting an index b-tree, then the caller should be inserting blob | 7149 ** expecting an index b-tree, then the caller should be inserting blob |
6669 ** keys with no associated data. If the cursor was opened expecting an | 7150 ** keys with no associated data. If the cursor was opened expecting an |
6670 ** intkey table, the caller should be inserting integer keys with a | 7151 ** intkey table, the caller should be inserting integer keys with a |
6671 ** blob of associated data. */ | 7152 ** blob of associated data. */ |
6672 assert( (pKey==0)==(pCur->pKeyInfo==0) ); | 7153 assert( (pKey==0)==(pCur->pKeyInfo==0) ); |
6673 | 7154 |
6674 /* If this is an insert into a table b-tree, invalidate any incrblob | |
6675 ** cursors open on the row being replaced (assuming this is a replace | |
6676 ** operation - if it is not, the following is a no-op). */ | |
6677 if( pCur->pKeyInfo==0 ){ | |
6678 invalidateIncrblobCursors(p, nKey, 0); | |
6679 } | |
6680 | |
6681 /* Save the positions of any other cursors open on this table. | 7155 /* Save the positions of any other cursors open on this table. |
6682 ** | 7156 ** |
6683 ** In some cases, the call to btreeMoveto() below is a no-op. For | 7157 ** In some cases, the call to btreeMoveto() below is a no-op. For |
6684 ** example, when inserting data into a table with auto-generated integer | 7158 ** example, when inserting data into a table with auto-generated integer |
6685 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the | 7159 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the |
6686 ** integer key to use. It then calls this function to actually insert the | 7160 ** integer key to use. It then calls this function to actually insert the |
6687 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes | 7161 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes |
6688 ** that the cursor is already where it needs to be and returns without | 7162 ** that the cursor is already where it needs to be and returns without |
6689 ** doing any work. To avoid thwarting these optimizations, it is important | 7163 ** doing any work. To avoid thwarting these optimizations, it is important |
6690 ** not to clear the cursor here. | 7164 ** not to clear the cursor here. |
6691 */ | 7165 */ |
6692 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); | 7166 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); |
6693 if( rc ) return rc; | 7167 if( rc ) return rc; |
| 7168 |
| 7169 if( pCur->pKeyInfo==0 ){ |
| 7170 /* If this is an insert into a table b-tree, invalidate any incrblob |
| 7171 ** cursors open on the row being replaced */ |
| 7172 invalidateIncrblobCursors(p, nKey, 0); |
| 7173 |
| 7174 /* If the cursor is currently on the last row and we are appending a |
| 7175 ** new row onto the end, set the "loc" to avoid an unnecessary btreeMoveto() |
| 7176 ** call */ |
| 7177 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0 |
| 7178 && pCur->info.nKey==nKey-1 ){ |
| 7179 loc = -1; |
| 7180 } |
| 7181 } |
| 7182 |
6694 if( !loc ){ | 7183 if( !loc ){ |
6695 rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc); | 7184 rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc); |
6696 if( rc ) return rc; | 7185 if( rc ) return rc; |
6697 } | 7186 } |
6698 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) ); | 7187 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) ); |
6699 | 7188 |
6700 pPage = pCur->apPage[pCur->iPage]; | 7189 pPage = pCur->apPage[pCur->iPage]; |
6701 assert( pPage->intKey || nKey>=0 ); | 7190 assert( pPage->intKey || nKey>=0 ); |
6702 assert( pPage->leaf || !pPage->intKey ); | 7191 assert( pPage->leaf || !pPage->intKey ); |
6703 | 7192 |
6704 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n", | 7193 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n", |
6705 pCur->pgnoRoot, nKey, nData, pPage->pgno, | 7194 pCur->pgnoRoot, nKey, nData, pPage->pgno, |
6706 loc==0 ? "overwrite" : "new entry")); | 7195 loc==0 ? "overwrite" : "new entry")); |
6707 assert( pPage->isInit ); | 7196 assert( pPage->isInit ); |
6708 allocateTempSpace(pBt); | |
6709 newCell = pBt->pTmpSpace; | 7197 newCell = pBt->pTmpSpace; |
6710 if( newCell==0 ) return SQLITE_NOMEM; | 7198 assert( newCell!=0 ); |
6711 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew); | 7199 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew); |
6712 if( rc ) goto end_insert; | 7200 if( rc ) goto end_insert; |
6713 assert( szNew==cellSizePtr(pPage, newCell) ); | 7201 assert( szNew==cellSizePtr(pPage, newCell) ); |
6714 assert( szNew <= MX_CELL_SIZE(pBt) ); | 7202 assert( szNew <= MX_CELL_SIZE(pBt) ); |
6715 idx = pCur->aiIdx[pCur->iPage]; | 7203 idx = pCur->aiIdx[pCur->iPage]; |
6716 if( loc==0 ){ | 7204 if( loc==0 ){ |
6717 u16 szOld; | 7205 u16 szOld; |
6718 assert( idx<pPage->nCell ); | 7206 assert( idx<pPage->nCell ); |
6719 rc = sqlite3PagerWrite(pPage->pDbPage); | 7207 rc = sqlite3PagerWrite(pPage->pDbPage); |
6720 if( rc ){ | 7208 if( rc ){ |
6721 goto end_insert; | 7209 goto end_insert; |
6722 } | 7210 } |
6723 oldCell = findCell(pPage, idx); | 7211 oldCell = findCell(pPage, idx); |
6724 if( !pPage->leaf ){ | 7212 if( !pPage->leaf ){ |
6725 memcpy(newCell, oldCell, 4); | 7213 memcpy(newCell, oldCell, 4); |
6726 } | 7214 } |
6727 szOld = cellSizePtr(pPage, oldCell); | 7215 rc = clearCell(pPage, oldCell, &szOld); |
6728 rc = clearCell(pPage, oldCell); | |
6729 dropCell(pPage, idx, szOld, &rc); | 7216 dropCell(pPage, idx, szOld, &rc); |
6730 if( rc ) goto end_insert; | 7217 if( rc ) goto end_insert; |
6731 }else if( loc<0 && pPage->nCell>0 ){ | 7218 }else if( loc<0 && pPage->nCell>0 ){ |
6732 assert( pPage->leaf ); | 7219 assert( pPage->leaf ); |
6733 idx = ++pCur->aiIdx[pCur->iPage]; | 7220 idx = ++pCur->aiIdx[pCur->iPage]; |
6734 }else{ | 7221 }else{ |
6735 assert( pPage->leaf ); | 7222 assert( pPage->leaf ); |
6736 } | 7223 } |
6737 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc); | 7224 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc); |
6738 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 ); | 7225 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 ); |
6739 | 7226 |
6740 /* If no error has occured and pPage has an overflow cell, call balance() | 7227 /* If no error has occurred and pPage has an overflow cell, call balance() |
6741 ** to redistribute the cells within the tree. Since balance() may move | 7228 ** to redistribute the cells within the tree. Since balance() may move |
6742 ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey | 7229 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey |
6743 ** variables. | 7230 ** variables. |
6744 ** | 7231 ** |
6745 ** Previous versions of SQLite called moveToRoot() to move the cursor | 7232 ** Previous versions of SQLite called moveToRoot() to move the cursor |
6746 ** back to the root page as balance() used to invalidate the contents | 7233 ** back to the root page as balance() used to invalidate the contents |
6747 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that, | 7234 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that, |
6748 ** set the cursor state to "invalid". This makes common insert operations | 7235 ** set the cursor state to "invalid". This makes common insert operations |
6749 ** slightly faster. | 7236 ** slightly faster. |
6750 ** | 7237 ** |
6751 ** There is a subtle but important optimization here too. When inserting | 7238 ** There is a subtle but important optimization here too. When inserting |
6752 ** multiple records into an intkey b-tree using a single cursor (as can | 7239 ** multiple records into an intkey b-tree using a single cursor (as can |
6753 ** happen while processing an "INSERT INTO ... SELECT" statement), it | 7240 ** happen while processing an "INSERT INTO ... SELECT" statement), it |
6754 ** is advantageous to leave the cursor pointing to the last entry in | 7241 ** is advantageous to leave the cursor pointing to the last entry in |
6755 ** the b-tree if possible. If the cursor is left pointing to the last | 7242 ** the b-tree if possible. If the cursor is left pointing to the last |
6756 ** entry in the table, and the next row inserted has an integer key | 7243 ** entry in the table, and the next row inserted has an integer key |
6757 ** larger than the largest existing key, it is possible to insert the | 7244 ** larger than the largest existing key, it is possible to insert the |
6758 ** row without seeking the cursor. This can be a big performance boost. | 7245 ** row without seeking the cursor. This can be a big performance boost. |
6759 */ | 7246 */ |
6760 pCur->info.nSize = 0; | 7247 pCur->info.nSize = 0; |
6761 pCur->validNKey = 0; | |
6762 if( rc==SQLITE_OK && pPage->nOverflow ){ | 7248 if( rc==SQLITE_OK && pPage->nOverflow ){ |
| 7249 pCur->curFlags &= ~(BTCF_ValidNKey); |
6763 rc = balance(pCur); | 7250 rc = balance(pCur); |
6764 | 7251 |
6765 /* Must make sure nOverflow is reset to zero even if the balance() | 7252 /* Must make sure nOverflow is reset to zero even if the balance() |
6766 ** fails. Internal data structure corruption will result otherwise. | 7253 ** fails. Internal data structure corruption will result otherwise. |
6767 ** Also, set the cursor state to invalid. This stops saveCursorPosition() | 7254 ** Also, set the cursor state to invalid. This stops saveCursorPosition() |
6768 ** from trying to save the current position of the cursor. */ | 7255 ** from trying to save the current position of the cursor. */ |
6769 pCur->apPage[pCur->iPage]->nOverflow = 0; | 7256 pCur->apPage[pCur->iPage]->nOverflow = 0; |
6770 pCur->eState = CURSOR_INVALID; | 7257 pCur->eState = CURSOR_INVALID; |
6771 } | 7258 } |
6772 assert( pCur->apPage[pCur->iPage]->nOverflow==0 ); | 7259 assert( pCur->apPage[pCur->iPage]->nOverflow==0 ); |
6773 | 7260 |
6774 end_insert: | 7261 end_insert: |
6775 return rc; | 7262 return rc; |
6776 } | 7263 } |
6777 | 7264 |
6778 /* | 7265 /* |
6779 ** Delete the entry that the cursor is pointing to. The cursor | 7266 ** Delete the entry that the cursor is pointing to. The cursor |
6780 ** is left pointing at a arbitrary location. | 7267 ** is left pointing at an arbitrary location. |
6781 */ | 7268 */ |
6782 int sqlite3BtreeDelete(BtCursor *pCur){ | 7269 int sqlite3BtreeDelete(BtCursor *pCur){ |
6783 Btree *p = pCur->pBtree; | 7270 Btree *p = pCur->pBtree; |
6784 BtShared *pBt = p->pBt; | 7271 BtShared *pBt = p->pBt; |
6785 int rc; /* Return code */ | 7272 int rc; /* Return code */ |
6786 MemPage *pPage; /* Page to delete cell from */ | 7273 MemPage *pPage; /* Page to delete cell from */ |
6787 unsigned char *pCell; /* Pointer to cell to delete */ | 7274 unsigned char *pCell; /* Pointer to cell to delete */ |
6788 int iCellIdx; /* Index of cell to delete */ | 7275 int iCellIdx; /* Index of cell to delete */ |
6789 int iCellDepth; /* Depth of node containing pCell */ | 7276 int iCellDepth; /* Depth of node containing pCell */ |
| 7277 u16 szCell; /* Size of the cell being deleted */ |
6790 | 7278 |
6791 assert( cursorHoldsMutex(pCur) ); | 7279 assert( cursorHoldsMutex(pCur) ); |
6792 assert( pBt->inTransaction==TRANS_WRITE ); | 7280 assert( pBt->inTransaction==TRANS_WRITE ); |
6793 assert( !pBt->readOnly ); | 7281 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); |
6794 assert( pCur->wrFlag ); | 7282 assert( pCur->curFlags & BTCF_WriteFlag ); |
6795 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); | 7283 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) ); |
6796 assert( !hasReadConflicts(p, pCur->pgnoRoot) ); | 7284 assert( !hasReadConflicts(p, pCur->pgnoRoot) ); |
6797 | 7285 |
6798 if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) | 7286 if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) |
6799 || NEVER(pCur->eState!=CURSOR_VALID) | 7287 || NEVER(pCur->eState!=CURSOR_VALID) |
6800 ){ | 7288 ){ |
6801 return SQLITE_ERROR; /* Something has gone awry. */ | 7289 return SQLITE_ERROR; /* Something has gone awry. */ |
6802 } | 7290 } |
6803 | 7291 |
6804 /* If this is a delete operation to remove a row from a table b-tree, | |
6805 ** invalidate any incrblob cursors open on the row being deleted. */ | |
6806 if( pCur->pKeyInfo==0 ){ | |
6807 invalidateIncrblobCursors(p, pCur->info.nKey, 0); | |
6808 } | |
6809 | |
6810 iCellDepth = pCur->iPage; | 7292 iCellDepth = pCur->iPage; |
6811 iCellIdx = pCur->aiIdx[iCellDepth]; | 7293 iCellIdx = pCur->aiIdx[iCellDepth]; |
6812 pPage = pCur->apPage[iCellDepth]; | 7294 pPage = pCur->apPage[iCellDepth]; |
6813 pCell = findCell(pPage, iCellIdx); | 7295 pCell = findCell(pPage, iCellIdx); |
6814 | 7296 |
6815 /* If the page containing the entry to delete is not a leaf page, move | 7297 /* If the page containing the entry to delete is not a leaf page, move |
6816 ** the cursor to the largest entry in the tree that is smaller than | 7298 ** the cursor to the largest entry in the tree that is smaller than |
6817 ** the entry being deleted. This cell will replace the cell being deleted | 7299 ** the entry being deleted. This cell will replace the cell being deleted |
6818 ** from the internal node. The 'previous' entry is used for this instead | 7300 ** from the internal node. The 'previous' entry is used for this instead |
6819 ** of the 'next' entry, as the previous entry is always a part of the | 7301 ** of the 'next' entry, as the previous entry is always a part of the |
6820 ** sub-tree headed by the child page of the cell being deleted. This makes | 7302 ** sub-tree headed by the child page of the cell being deleted. This makes |
6821 ** balancing the tree following the delete operation easier. */ | 7303 ** balancing the tree following the delete operation easier. */ |
6822 if( !pPage->leaf ){ | 7304 if( !pPage->leaf ){ |
6823 int notUsed; | 7305 int notUsed = 0; |
6824 rc = sqlite3BtreePrevious(pCur, ¬Used); | 7306 rc = sqlite3BtreePrevious(pCur, ¬Used); |
6825 if( rc ) return rc; | 7307 if( rc ) return rc; |
6826 } | 7308 } |
6827 | 7309 |
6828 /* Save the positions of any other cursors open on this table before | 7310 /* Save the positions of any other cursors open on this table before |
6829 ** making any modifications. Make the page containing the entry to be | 7311 ** making any modifications. Make the page containing the entry to be |
6830 ** deleted writable. Then free any overflow pages associated with the | 7312 ** deleted writable. Then free any overflow pages associated with the |
6831 ** entry and finally remove the cell itself from within the page. | 7313 ** entry and finally remove the cell itself from within the page. |
6832 */ | 7314 */ |
6833 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); | 7315 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur); |
6834 if( rc ) return rc; | 7316 if( rc ) return rc; |
| 7317 |
| 7318 /* If this is a delete operation to remove a row from a table b-tree, |
| 7319 ** invalidate any incrblob cursors open on the row being deleted. */ |
| 7320 if( pCur->pKeyInfo==0 ){ |
| 7321 invalidateIncrblobCursors(p, pCur->info.nKey, 0); |
| 7322 } |
| 7323 |
6835 rc = sqlite3PagerWrite(pPage->pDbPage); | 7324 rc = sqlite3PagerWrite(pPage->pDbPage); |
6836 if( rc ) return rc; | 7325 if( rc ) return rc; |
6837 rc = clearCell(pPage, pCell); | 7326 rc = clearCell(pPage, pCell, &szCell); |
6838 dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc); | 7327 dropCell(pPage, iCellIdx, szCell, &rc); |
6839 if( rc ) return rc; | 7328 if( rc ) return rc; |
6840 | 7329 |
6841 /* If the cell deleted was not located on a leaf page, then the cursor | 7330 /* If the cell deleted was not located on a leaf page, then the cursor |
6842 ** is currently pointing to the largest entry in the sub-tree headed | 7331 ** is currently pointing to the largest entry in the sub-tree headed |
6843 ** by the child-page of the cell that was just deleted from an internal | 7332 ** by the child-page of the cell that was just deleted from an internal |
6844 ** node. The cell from the leaf node needs to be moved to the internal | 7333 ** node. The cell from the leaf node needs to be moved to the internal |
6845 ** node to replace the deleted cell. */ | 7334 ** node to replace the deleted cell. */ |
6846 if( !pPage->leaf ){ | 7335 if( !pPage->leaf ){ |
6847 MemPage *pLeaf = pCur->apPage[pCur->iPage]; | 7336 MemPage *pLeaf = pCur->apPage[pCur->iPage]; |
6848 int nCell; | 7337 int nCell; |
6849 Pgno n = pCur->apPage[iCellDepth+1]->pgno; | 7338 Pgno n = pCur->apPage[iCellDepth+1]->pgno; |
6850 unsigned char *pTmp; | 7339 unsigned char *pTmp; |
6851 | 7340 |
6852 pCell = findCell(pLeaf, pLeaf->nCell-1); | 7341 pCell = findCell(pLeaf, pLeaf->nCell-1); |
6853 nCell = cellSizePtr(pLeaf, pCell); | 7342 nCell = cellSizePtr(pLeaf, pCell); |
6854 assert( MX_CELL_SIZE(pBt) >= nCell ); | 7343 assert( MX_CELL_SIZE(pBt) >= nCell ); |
6855 | |
6856 allocateTempSpace(pBt); | |
6857 pTmp = pBt->pTmpSpace; | 7344 pTmp = pBt->pTmpSpace; |
6858 | 7345 assert( pTmp!=0 ); |
6859 rc = sqlite3PagerWrite(pLeaf->pDbPage); | 7346 rc = sqlite3PagerWrite(pLeaf->pDbPage); |
6860 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc); | 7347 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc); |
6861 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc); | 7348 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc); |
6862 if( rc ) return rc; | 7349 if( rc ) return rc; |
6863 } | 7350 } |
6864 | 7351 |
6865 /* Balance the tree. If the entry deleted was located on a leaf page, | 7352 /* Balance the tree. If the entry deleted was located on a leaf page, |
6866 ** then the cursor still points to that page. In this case the first | 7353 ** then the cursor still points to that page. In this case the first |
6867 ** call to balance() repairs the tree, and the if(...) condition is | 7354 ** call to balance() repairs the tree, and the if(...) condition is |
6868 ** never true. | 7355 ** never true. |
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
6904 */ | 7391 */ |
6905 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){ | 7392 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){ |
6906 BtShared *pBt = p->pBt; | 7393 BtShared *pBt = p->pBt; |
6907 MemPage *pRoot; | 7394 MemPage *pRoot; |
6908 Pgno pgnoRoot; | 7395 Pgno pgnoRoot; |
6909 int rc; | 7396 int rc; |
6910 int ptfFlags; /* Page-type flage for the root page of new table */ | 7397 int ptfFlags; /* Page-type flage for the root page of new table */ |
6911 | 7398 |
6912 assert( sqlite3BtreeHoldsMutex(p) ); | 7399 assert( sqlite3BtreeHoldsMutex(p) ); |
6913 assert( pBt->inTransaction==TRANS_WRITE ); | 7400 assert( pBt->inTransaction==TRANS_WRITE ); |
6914 assert( !pBt->readOnly ); | 7401 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 ); |
6915 | 7402 |
6916 #ifdef SQLITE_OMIT_AUTOVACUUM | 7403 #ifdef SQLITE_OMIT_AUTOVACUUM |
6917 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); | 7404 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); |
6918 if( rc ){ | 7405 if( rc ){ |
6919 return rc; | 7406 return rc; |
6920 } | 7407 } |
6921 #else | 7408 #else |
6922 if( pBt->autoVacuum ){ | 7409 if( pBt->autoVacuum ){ |
6923 Pgno pgnoMove; /* Move a page here to make room for the root-page */ | 7410 Pgno pgnoMove; /* Move a page here to make room for the root-page */ |
6924 MemPage *pPageMove; /* The page to move to. */ | 7411 MemPage *pPageMove; /* The page to move to. */ |
(...skipping 18 matching lines...) Expand all Loading... |
6943 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) || | 7430 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) || |
6944 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){ | 7431 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){ |
6945 pgnoRoot++; | 7432 pgnoRoot++; |
6946 } | 7433 } |
6947 assert( pgnoRoot>=3 ); | 7434 assert( pgnoRoot>=3 ); |
6948 | 7435 |
6949 /* Allocate a page. The page that currently resides at pgnoRoot will | 7436 /* Allocate a page. The page that currently resides at pgnoRoot will |
6950 ** be moved to the allocated page (unless the allocated page happens | 7437 ** be moved to the allocated page (unless the allocated page happens |
6951 ** to reside at pgnoRoot). | 7438 ** to reside at pgnoRoot). |
6952 */ | 7439 */ |
6953 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1); | 7440 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT); |
6954 if( rc!=SQLITE_OK ){ | 7441 if( rc!=SQLITE_OK ){ |
6955 return rc; | 7442 return rc; |
6956 } | 7443 } |
6957 | 7444 |
6958 if( pgnoMove!=pgnoRoot ){ | 7445 if( pgnoMove!=pgnoRoot ){ |
6959 /* pgnoRoot is the page that will be used for the root-page of | 7446 /* pgnoRoot is the page that will be used for the root-page of |
6960 ** the new table (assuming an error did not occur). But we were | 7447 ** the new table (assuming an error did not occur). But we were |
6961 ** allocated pgnoMove. If required (i.e. if it was not allocated | 7448 ** allocated pgnoMove. If required (i.e. if it was not allocated |
6962 ** by extending the file), the current page at position pgnoMove | 7449 ** by extending the file), the current page at position pgnoMove |
6963 ** is already journaled. | 7450 ** is already journaled. |
6964 */ | 7451 */ |
6965 u8 eType = 0; | 7452 u8 eType = 0; |
6966 Pgno iPtrPage = 0; | 7453 Pgno iPtrPage = 0; |
6967 | 7454 |
| 7455 /* Save the positions of any open cursors. This is required in |
| 7456 ** case they are holding a reference to an xFetch reference |
| 7457 ** corresponding to page pgnoRoot. */ |
| 7458 rc = saveAllCursors(pBt, 0, 0); |
6968 releasePage(pPageMove); | 7459 releasePage(pPageMove); |
| 7460 if( rc!=SQLITE_OK ){ |
| 7461 return rc; |
| 7462 } |
6969 | 7463 |
6970 /* Move the page currently at pgnoRoot to pgnoMove. */ | 7464 /* Move the page currently at pgnoRoot to pgnoMove. */ |
6971 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); | 7465 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0); |
6972 if( rc!=SQLITE_OK ){ | 7466 if( rc!=SQLITE_OK ){ |
6973 return rc; | 7467 return rc; |
6974 } | 7468 } |
6975 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage); | 7469 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage); |
6976 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){ | 7470 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){ |
6977 rc = SQLITE_CORRUPT_BKPT; | 7471 rc = SQLITE_CORRUPT_BKPT; |
6978 } | 7472 } |
(...skipping 73 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
7052 static int clearDatabasePage( | 7546 static int clearDatabasePage( |
7053 BtShared *pBt, /* The BTree that contains the table */ | 7547 BtShared *pBt, /* The BTree that contains the table */ |
7054 Pgno pgno, /* Page number to clear */ | 7548 Pgno pgno, /* Page number to clear */ |
7055 int freePageFlag, /* Deallocate page if true */ | 7549 int freePageFlag, /* Deallocate page if true */ |
7056 int *pnChange /* Add number of Cells freed to this counter */ | 7550 int *pnChange /* Add number of Cells freed to this counter */ |
7057 ){ | 7551 ){ |
7058 MemPage *pPage; | 7552 MemPage *pPage; |
7059 int rc; | 7553 int rc; |
7060 unsigned char *pCell; | 7554 unsigned char *pCell; |
7061 int i; | 7555 int i; |
| 7556 int hdr; |
| 7557 u16 szCell; |
7062 | 7558 |
7063 assert( sqlite3_mutex_held(pBt->mutex) ); | 7559 assert( sqlite3_mutex_held(pBt->mutex) ); |
7064 if( pgno>btreePagecount(pBt) ){ | 7560 if( pgno>btreePagecount(pBt) ){ |
7065 return SQLITE_CORRUPT_BKPT; | 7561 return SQLITE_CORRUPT_BKPT; |
7066 } | 7562 } |
7067 | 7563 |
7068 rc = getAndInitPage(pBt, pgno, &pPage); | 7564 rc = getAndInitPage(pBt, pgno, &pPage, 0); |
7069 if( rc ) return rc; | 7565 if( rc ) return rc; |
| 7566 hdr = pPage->hdrOffset; |
7070 for(i=0; i<pPage->nCell; i++){ | 7567 for(i=0; i<pPage->nCell; i++){ |
7071 pCell = findCell(pPage, i); | 7568 pCell = findCell(pPage, i); |
7072 if( !pPage->leaf ){ | 7569 if( !pPage->leaf ){ |
7073 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange); | 7570 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange); |
7074 if( rc ) goto cleardatabasepage_out; | 7571 if( rc ) goto cleardatabasepage_out; |
7075 } | 7572 } |
7076 rc = clearCell(pPage, pCell); | 7573 rc = clearCell(pPage, pCell, &szCell); |
7077 if( rc ) goto cleardatabasepage_out; | 7574 if( rc ) goto cleardatabasepage_out; |
7078 } | 7575 } |
7079 if( !pPage->leaf ){ | 7576 if( !pPage->leaf ){ |
7080 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange); | 7577 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange); |
7081 if( rc ) goto cleardatabasepage_out; | 7578 if( rc ) goto cleardatabasepage_out; |
7082 }else if( pnChange ){ | 7579 }else if( pnChange ){ |
7083 assert( pPage->intKey ); | 7580 assert( pPage->intKey ); |
7084 *pnChange += pPage->nCell; | 7581 *pnChange += pPage->nCell; |
7085 } | 7582 } |
7086 if( freePageFlag ){ | 7583 if( freePageFlag ){ |
7087 freePage(pPage, &rc); | 7584 freePage(pPage, &rc); |
7088 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){ | 7585 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){ |
7089 zeroPage(pPage, pPage->aData[0] | PTF_LEAF); | 7586 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF); |
7090 } | 7587 } |
7091 | 7588 |
7092 cleardatabasepage_out: | 7589 cleardatabasepage_out: |
7093 releasePage(pPage); | 7590 releasePage(pPage); |
7094 return rc; | 7591 return rc; |
7095 } | 7592 } |
7096 | 7593 |
7097 /* | 7594 /* |
7098 ** Delete all information from a single table in the database. iTable is | 7595 ** Delete all information from a single table in the database. iTable is |
7099 ** the page number of the root of the table. After this routine returns, | 7596 ** the page number of the root of the table. After this routine returns, |
7100 ** the root page is empty, but still exists. | 7597 ** the root page is empty, but still exists. |
7101 ** | 7598 ** |
7102 ** This routine will fail with SQLITE_LOCKED if there are any open | 7599 ** This routine will fail with SQLITE_LOCKED if there are any open |
7103 ** read cursors on the table. Open write cursors are moved to the | 7600 ** read cursors on the table. Open write cursors are moved to the |
7104 ** root of the table. | 7601 ** root of the table. |
7105 ** | 7602 ** |
7106 ** If pnChange is not NULL, then table iTable must be an intkey table. The | 7603 ** If pnChange is not NULL, then table iTable must be an intkey table. The |
7107 ** integer value pointed to by pnChange is incremented by the number of | 7604 ** integer value pointed to by pnChange is incremented by the number of |
7108 ** entries in the table. | 7605 ** entries in the table. |
7109 */ | 7606 */ |
7110 int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){ | 7607 int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){ |
7111 int rc; | 7608 int rc; |
7112 BtShared *pBt = p->pBt; | 7609 BtShared *pBt = p->pBt; |
7113 sqlite3BtreeEnter(p); | 7610 sqlite3BtreeEnter(p); |
7114 assert( p->inTrans==TRANS_WRITE ); | 7611 assert( p->inTrans==TRANS_WRITE ); |
7115 | 7612 |
7116 /* Invalidate all incrblob cursors open on table iTable (assuming iTable | 7613 rc = saveAllCursors(pBt, (Pgno)iTable, 0); |
7117 ** is the root of a table b-tree - if it is not, the following call is | |
7118 ** a no-op). */ | |
7119 invalidateIncrblobCursors(p, 0, 1); | |
7120 | 7614 |
7121 rc = saveAllCursors(pBt, (Pgno)iTable, 0); | |
7122 if( SQLITE_OK==rc ){ | 7615 if( SQLITE_OK==rc ){ |
| 7616 /* Invalidate all incrblob cursors open on table iTable (assuming iTable |
| 7617 ** is the root of a table b-tree - if it is not, the following call is |
| 7618 ** a no-op). */ |
| 7619 invalidateIncrblobCursors(p, 0, 1); |
7123 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange); | 7620 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange); |
7124 } | 7621 } |
7125 sqlite3BtreeLeave(p); | 7622 sqlite3BtreeLeave(p); |
7126 return rc; | 7623 return rc; |
7127 } | 7624 } |
7128 | 7625 |
7129 /* | 7626 /* |
| 7627 ** Delete all information from the single table that pCur is open on. |
| 7628 ** |
| 7629 ** This routine only work for pCur on an ephemeral table. |
| 7630 */ |
| 7631 int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){ |
| 7632 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0); |
| 7633 } |
| 7634 |
| 7635 /* |
7130 ** Erase all information in a table and add the root of the table to | 7636 ** Erase all information in a table and add the root of the table to |
7131 ** the freelist. Except, the root of the principle table (the one on | 7637 ** the freelist. Except, the root of the principle table (the one on |
7132 ** page 1) is never added to the freelist. | 7638 ** page 1) is never added to the freelist. |
7133 ** | 7639 ** |
7134 ** This routine will fail with SQLITE_LOCKED if there are any open | 7640 ** This routine will fail with SQLITE_LOCKED if there are any open |
7135 ** cursors on the table. | 7641 ** cursors on the table. |
7136 ** | 7642 ** |
7137 ** If AUTOVACUUM is enabled and the page at iTable is not the last | 7643 ** If AUTOVACUUM is enabled and the page at iTable is not the last |
7138 ** root page in the database file, then the last root page | 7644 ** root page in the database file, then the last root page |
7139 ** in the database file is moved into the slot formerly occupied by | 7645 ** in the database file is moved into the slot formerly occupied by |
(...skipping 138 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
7278 assert( p->inTrans>TRANS_NONE ); | 7784 assert( p->inTrans>TRANS_NONE ); |
7279 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) ); | 7785 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) ); |
7280 assert( pBt->pPage1 ); | 7786 assert( pBt->pPage1 ); |
7281 assert( idx>=0 && idx<=15 ); | 7787 assert( idx>=0 && idx<=15 ); |
7282 | 7788 |
7283 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]); | 7789 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]); |
7284 | 7790 |
7285 /* If auto-vacuum is disabled in this build and this is an auto-vacuum | 7791 /* If auto-vacuum is disabled in this build and this is an auto-vacuum |
7286 ** database, mark the database as read-only. */ | 7792 ** database, mark the database as read-only. */ |
7287 #ifdef SQLITE_OMIT_AUTOVACUUM | 7793 #ifdef SQLITE_OMIT_AUTOVACUUM |
7288 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1; | 7794 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){ |
| 7795 pBt->btsFlags |= BTS_READ_ONLY; |
| 7796 } |
7289 #endif | 7797 #endif |
7290 | 7798 |
7291 sqlite3BtreeLeave(p); | 7799 sqlite3BtreeLeave(p); |
7292 } | 7800 } |
7293 | 7801 |
7294 /* | 7802 /* |
7295 ** Write meta-information back into the database. Meta[0] is | 7803 ** Write meta-information back into the database. Meta[0] is |
7296 ** read-only and may not be written. | 7804 ** read-only and may not be written. |
7297 */ | 7805 */ |
7298 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){ | 7806 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){ |
(...skipping 25 matching lines...) Expand all Loading... |
7324 ** The first argument, pCur, is a cursor opened on some b-tree. Count the | 7832 ** The first argument, pCur, is a cursor opened on some b-tree. Count the |
7325 ** number of entries in the b-tree and write the result to *pnEntry. | 7833 ** number of entries in the b-tree and write the result to *pnEntry. |
7326 ** | 7834 ** |
7327 ** SQLITE_OK is returned if the operation is successfully executed. | 7835 ** SQLITE_OK is returned if the operation is successfully executed. |
7328 ** Otherwise, if an error is encountered (i.e. an IO error or database | 7836 ** Otherwise, if an error is encountered (i.e. an IO error or database |
7329 ** corruption) an SQLite error code is returned. | 7837 ** corruption) an SQLite error code is returned. |
7330 */ | 7838 */ |
7331 int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){ | 7839 int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){ |
7332 i64 nEntry = 0; /* Value to return in *pnEntry */ | 7840 i64 nEntry = 0; /* Value to return in *pnEntry */ |
7333 int rc; /* Return code */ | 7841 int rc; /* Return code */ |
| 7842 |
| 7843 if( pCur->pgnoRoot==0 ){ |
| 7844 *pnEntry = 0; |
| 7845 return SQLITE_OK; |
| 7846 } |
7334 rc = moveToRoot(pCur); | 7847 rc = moveToRoot(pCur); |
7335 | 7848 |
7336 /* Unless an error occurs, the following loop runs one iteration for each | 7849 /* Unless an error occurs, the following loop runs one iteration for each |
7337 ** page in the B-Tree structure (not including overflow pages). | 7850 ** page in the B-Tree structure (not including overflow pages). |
7338 */ | 7851 */ |
7339 while( rc==SQLITE_OK ){ | 7852 while( rc==SQLITE_OK ){ |
7340 int iIdx; /* Index of child node in parent */ | 7853 int iIdx; /* Index of child node in parent */ |
7341 MemPage *pPage; /* Current page of the b-tree */ | 7854 MemPage *pPage; /* Current page of the b-tree */ |
7342 | 7855 |
7343 /* If this is a leaf page or the tree is not an int-key tree, then | 7856 /* If this is a leaf page or the tree is not an int-key tree, then |
(...skipping 52 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
7396 Pager *sqlite3BtreePager(Btree *p){ | 7909 Pager *sqlite3BtreePager(Btree *p){ |
7397 return p->pBt->pPager; | 7910 return p->pBt->pPager; |
7398 } | 7911 } |
7399 | 7912 |
7400 #ifndef SQLITE_OMIT_INTEGRITY_CHECK | 7913 #ifndef SQLITE_OMIT_INTEGRITY_CHECK |
7401 /* | 7914 /* |
7402 ** Append a message to the error message string. | 7915 ** Append a message to the error message string. |
7403 */ | 7916 */ |
7404 static void checkAppendMsg( | 7917 static void checkAppendMsg( |
7405 IntegrityCk *pCheck, | 7918 IntegrityCk *pCheck, |
7406 char *zMsg1, | |
7407 const char *zFormat, | 7919 const char *zFormat, |
7408 ... | 7920 ... |
7409 ){ | 7921 ){ |
7410 va_list ap; | 7922 va_list ap; |
| 7923 char zBuf[200]; |
7411 if( !pCheck->mxErr ) return; | 7924 if( !pCheck->mxErr ) return; |
7412 pCheck->mxErr--; | 7925 pCheck->mxErr--; |
7413 pCheck->nErr++; | 7926 pCheck->nErr++; |
7414 va_start(ap, zFormat); | 7927 va_start(ap, zFormat); |
7415 if( pCheck->errMsg.nChar ){ | 7928 if( pCheck->errMsg.nChar ){ |
7416 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1); | 7929 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1); |
7417 } | 7930 } |
7418 if( zMsg1 ){ | 7931 if( pCheck->zPfx ){ |
7419 sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1); | 7932 sqlite3_snprintf(sizeof(zBuf), zBuf, pCheck->zPfx, pCheck->v1, pCheck->v2); |
| 7933 sqlite3StrAccumAppendAll(&pCheck->errMsg, zBuf); |
7420 } | 7934 } |
7421 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap); | 7935 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap); |
7422 va_end(ap); | 7936 va_end(ap); |
7423 if( pCheck->errMsg.mallocFailed ){ | 7937 if( pCheck->errMsg.accError==STRACCUM_NOMEM ){ |
7424 pCheck->mallocFailed = 1; | 7938 pCheck->mallocFailed = 1; |
7425 } | 7939 } |
7426 } | 7940 } |
7427 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ | 7941 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ |
7428 | 7942 |
7429 #ifndef SQLITE_OMIT_INTEGRITY_CHECK | 7943 #ifndef SQLITE_OMIT_INTEGRITY_CHECK |
| 7944 |
| 7945 /* |
| 7946 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that |
| 7947 ** corresponds to page iPg is already set. |
| 7948 */ |
| 7949 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){ |
| 7950 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 ); |
| 7951 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07))); |
| 7952 } |
| 7953 |
| 7954 /* |
| 7955 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg. |
| 7956 */ |
| 7957 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){ |
| 7958 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 ); |
| 7959 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07)); |
| 7960 } |
| 7961 |
| 7962 |
7430 /* | 7963 /* |
7431 ** Add 1 to the reference count for page iPage. If this is the second | 7964 ** Add 1 to the reference count for page iPage. If this is the second |
7432 ** reference to the page, add an error message to pCheck->zErrMsg. | 7965 ** reference to the page, add an error message to pCheck->zErrMsg. |
7433 ** Return 1 if there are 2 ore more references to the page and 0 if | 7966 ** Return 1 if there are 2 or more references to the page and 0 if |
7434 ** if this is the first reference to the page. | 7967 ** if this is the first reference to the page. |
7435 ** | 7968 ** |
7436 ** Also check that the page number is in bounds. | 7969 ** Also check that the page number is in bounds. |
7437 */ | 7970 */ |
7438 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){ | 7971 static int checkRef(IntegrityCk *pCheck, Pgno iPage){ |
7439 if( iPage==0 ) return 1; | 7972 if( iPage==0 ) return 1; |
7440 if( iPage>pCheck->nPage ){ | 7973 if( iPage>pCheck->nPage ){ |
7441 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage); | 7974 checkAppendMsg(pCheck, "invalid page number %d", iPage); |
7442 return 1; | 7975 return 1; |
7443 } | 7976 } |
7444 if( pCheck->anRef[iPage]==1 ){ | 7977 if( getPageReferenced(pCheck, iPage) ){ |
7445 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage); | 7978 checkAppendMsg(pCheck, "2nd reference to page %d", iPage); |
7446 return 1; | 7979 return 1; |
7447 } | 7980 } |
7448 return (pCheck->anRef[iPage]++)>1; | 7981 setPageReferenced(pCheck, iPage); |
| 7982 return 0; |
7449 } | 7983 } |
7450 | 7984 |
7451 #ifndef SQLITE_OMIT_AUTOVACUUM | 7985 #ifndef SQLITE_OMIT_AUTOVACUUM |
7452 /* | 7986 /* |
7453 ** Check that the entry in the pointer-map for page iChild maps to | 7987 ** Check that the entry in the pointer-map for page iChild maps to |
7454 ** page iParent, pointer type ptrType. If not, append an error message | 7988 ** page iParent, pointer type ptrType. If not, append an error message |
7455 ** to pCheck. | 7989 ** to pCheck. |
7456 */ | 7990 */ |
7457 static void checkPtrmap( | 7991 static void checkPtrmap( |
7458 IntegrityCk *pCheck, /* Integrity check context */ | 7992 IntegrityCk *pCheck, /* Integrity check context */ |
7459 Pgno iChild, /* Child page number */ | 7993 Pgno iChild, /* Child page number */ |
7460 u8 eType, /* Expected pointer map type */ | 7994 u8 eType, /* Expected pointer map type */ |
7461 Pgno iParent, /* Expected pointer map parent page number */ | 7995 Pgno iParent /* Expected pointer map parent page number */ |
7462 char *zContext /* Context description (used for error msg) */ | |
7463 ){ | 7996 ){ |
7464 int rc; | 7997 int rc; |
7465 u8 ePtrmapType; | 7998 u8 ePtrmapType; |
7466 Pgno iPtrmapParent; | 7999 Pgno iPtrmapParent; |
7467 | 8000 |
7468 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent); | 8001 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent); |
7469 if( rc!=SQLITE_OK ){ | 8002 if( rc!=SQLITE_OK ){ |
7470 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1; | 8003 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1; |
7471 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild); | 8004 checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild); |
7472 return; | 8005 return; |
7473 } | 8006 } |
7474 | 8007 |
7475 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){ | 8008 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){ |
7476 checkAppendMsg(pCheck, zContext, | 8009 checkAppendMsg(pCheck, |
7477 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", | 8010 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", |
7478 iChild, eType, iParent, ePtrmapType, iPtrmapParent); | 8011 iChild, eType, iParent, ePtrmapType, iPtrmapParent); |
7479 } | 8012 } |
7480 } | 8013 } |
7481 #endif | 8014 #endif |
7482 | 8015 |
7483 /* | 8016 /* |
7484 ** Check the integrity of the freelist or of an overflow page list. | 8017 ** Check the integrity of the freelist or of an overflow page list. |
7485 ** Verify that the number of pages on the list is N. | 8018 ** Verify that the number of pages on the list is N. |
7486 */ | 8019 */ |
7487 static void checkList( | 8020 static void checkList( |
7488 IntegrityCk *pCheck, /* Integrity checking context */ | 8021 IntegrityCk *pCheck, /* Integrity checking context */ |
7489 int isFreeList, /* True for a freelist. False for overflow page list */ | 8022 int isFreeList, /* True for a freelist. False for overflow page list */ |
7490 int iPage, /* Page number for first page in the list */ | 8023 int iPage, /* Page number for first page in the list */ |
7491 int N, /* Expected number of pages in the list */ | 8024 int N /* Expected number of pages in the list */ |
7492 char *zContext /* Context for error messages */ | |
7493 ){ | 8025 ){ |
7494 int i; | 8026 int i; |
7495 int expected = N; | 8027 int expected = N; |
7496 int iFirst = iPage; | 8028 int iFirst = iPage; |
7497 while( N-- > 0 && pCheck->mxErr ){ | 8029 while( N-- > 0 && pCheck->mxErr ){ |
7498 DbPage *pOvflPage; | 8030 DbPage *pOvflPage; |
7499 unsigned char *pOvflData; | 8031 unsigned char *pOvflData; |
7500 if( iPage<1 ){ | 8032 if( iPage<1 ){ |
7501 checkAppendMsg(pCheck, zContext, | 8033 checkAppendMsg(pCheck, |
7502 "%d of %d pages missing from overflow list starting at %d", | 8034 "%d of %d pages missing from overflow list starting at %d", |
7503 N+1, expected, iFirst); | 8035 N+1, expected, iFirst); |
7504 break; | 8036 break; |
7505 } | 8037 } |
7506 if( checkRef(pCheck, iPage, zContext) ) break; | 8038 if( checkRef(pCheck, iPage) ) break; |
7507 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){ | 8039 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){ |
7508 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage); | 8040 checkAppendMsg(pCheck, "failed to get page %d", iPage); |
7509 break; | 8041 break; |
7510 } | 8042 } |
7511 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage); | 8043 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage); |
7512 if( isFreeList ){ | 8044 if( isFreeList ){ |
7513 int n = get4byte(&pOvflData[4]); | 8045 int n = get4byte(&pOvflData[4]); |
7514 #ifndef SQLITE_OMIT_AUTOVACUUM | 8046 #ifndef SQLITE_OMIT_AUTOVACUUM |
7515 if( pCheck->pBt->autoVacuum ){ | 8047 if( pCheck->pBt->autoVacuum ){ |
7516 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext); | 8048 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0); |
7517 } | 8049 } |
7518 #endif | 8050 #endif |
7519 if( n>(int)pCheck->pBt->usableSize/4-2 ){ | 8051 if( n>(int)pCheck->pBt->usableSize/4-2 ){ |
7520 checkAppendMsg(pCheck, zContext, | 8052 checkAppendMsg(pCheck, |
7521 "freelist leaf count too big on page %d", iPage); | 8053 "freelist leaf count too big on page %d", iPage); |
7522 N--; | 8054 N--; |
7523 }else{ | 8055 }else{ |
7524 for(i=0; i<n; i++){ | 8056 for(i=0; i<n; i++){ |
7525 Pgno iFreePage = get4byte(&pOvflData[8+i*4]); | 8057 Pgno iFreePage = get4byte(&pOvflData[8+i*4]); |
7526 #ifndef SQLITE_OMIT_AUTOVACUUM | 8058 #ifndef SQLITE_OMIT_AUTOVACUUM |
7527 if( pCheck->pBt->autoVacuum ){ | 8059 if( pCheck->pBt->autoVacuum ){ |
7528 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext); | 8060 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0); |
7529 } | 8061 } |
7530 #endif | 8062 #endif |
7531 checkRef(pCheck, iFreePage, zContext); | 8063 checkRef(pCheck, iFreePage); |
7532 } | 8064 } |
7533 N -= n; | 8065 N -= n; |
7534 } | 8066 } |
7535 } | 8067 } |
7536 #ifndef SQLITE_OMIT_AUTOVACUUM | 8068 #ifndef SQLITE_OMIT_AUTOVACUUM |
7537 else{ | 8069 else{ |
7538 /* If this database supports auto-vacuum and iPage is not the last | 8070 /* If this database supports auto-vacuum and iPage is not the last |
7539 ** page in this overflow list, check that the pointer-map entry for | 8071 ** page in this overflow list, check that the pointer-map entry for |
7540 ** the following page matches iPage. | 8072 ** the following page matches iPage. |
7541 */ | 8073 */ |
7542 if( pCheck->pBt->autoVacuum && N>0 ){ | 8074 if( pCheck->pBt->autoVacuum && N>0 ){ |
7543 i = get4byte(pOvflData); | 8075 i = get4byte(pOvflData); |
7544 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext); | 8076 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage); |
7545 } | 8077 } |
7546 } | 8078 } |
7547 #endif | 8079 #endif |
7548 iPage = get4byte(pOvflData); | 8080 iPage = get4byte(pOvflData); |
7549 sqlite3PagerUnref(pOvflPage); | 8081 sqlite3PagerUnref(pOvflPage); |
7550 } | 8082 } |
7551 } | 8083 } |
7552 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ | 8084 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ |
7553 | 8085 |
7554 #ifndef SQLITE_OMIT_INTEGRITY_CHECK | 8086 #ifndef SQLITE_OMIT_INTEGRITY_CHECK |
(...skipping 11 matching lines...) Expand all Loading... |
7566 ** NO 4. Make sure no key is greater than or equal to zUpperBound. | 8098 ** NO 4. Make sure no key is greater than or equal to zUpperBound. |
7567 ** 5. Check the integrity of overflow pages. | 8099 ** 5. Check the integrity of overflow pages. |
7568 ** 6. Recursively call checkTreePage on all children. | 8100 ** 6. Recursively call checkTreePage on all children. |
7569 ** 7. Verify that the depth of all children is the same. | 8101 ** 7. Verify that the depth of all children is the same. |
7570 ** 8. Make sure this page is at least 33% full or else it is | 8102 ** 8. Make sure this page is at least 33% full or else it is |
7571 ** the root of the tree. | 8103 ** the root of the tree. |
7572 */ | 8104 */ |
7573 static int checkTreePage( | 8105 static int checkTreePage( |
7574 IntegrityCk *pCheck, /* Context for the sanity check */ | 8106 IntegrityCk *pCheck, /* Context for the sanity check */ |
7575 int iPage, /* Page number of the page to check */ | 8107 int iPage, /* Page number of the page to check */ |
7576 char *zParentContext, /* Parent context */ | |
7577 i64 *pnParentMinKey, | 8108 i64 *pnParentMinKey, |
7578 i64 *pnParentMaxKey | 8109 i64 *pnParentMaxKey |
7579 ){ | 8110 ){ |
7580 MemPage *pPage; | 8111 MemPage *pPage; |
7581 int i, rc, depth, d2, pgno, cnt; | 8112 int i, rc, depth, d2, pgno, cnt; |
7582 int hdr, cellStart; | 8113 int hdr, cellStart; |
7583 int nCell; | 8114 int nCell; |
7584 u8 *data; | 8115 u8 *data; |
7585 BtShared *pBt; | 8116 BtShared *pBt; |
7586 int usableSize; | 8117 int usableSize; |
7587 char zContext[100]; | |
7588 char *hit = 0; | 8118 char *hit = 0; |
7589 i64 nMinKey = 0; | 8119 i64 nMinKey = 0; |
7590 i64 nMaxKey = 0; | 8120 i64 nMaxKey = 0; |
7591 | 8121 const char *saved_zPfx = pCheck->zPfx; |
7592 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage); | 8122 int saved_v1 = pCheck->v1; |
| 8123 int saved_v2 = pCheck->v2; |
7593 | 8124 |
7594 /* Check that the page exists | 8125 /* Check that the page exists |
7595 */ | 8126 */ |
7596 pBt = pCheck->pBt; | 8127 pBt = pCheck->pBt; |
7597 usableSize = pBt->usableSize; | 8128 usableSize = pBt->usableSize; |
7598 if( iPage==0 ) return 0; | 8129 if( iPage==0 ) return 0; |
7599 if( checkRef(pCheck, iPage, zParentContext) ) return 0; | 8130 if( checkRef(pCheck, iPage) ) return 0; |
| 8131 pCheck->zPfx = "Page %d: "; |
| 8132 pCheck->v1 = iPage; |
7600 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){ | 8133 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){ |
7601 checkAppendMsg(pCheck, zContext, | 8134 checkAppendMsg(pCheck, |
7602 "unable to get the page. error code=%d", rc); | 8135 "unable to get the page. error code=%d", rc); |
7603 return 0; | 8136 depth = -1; |
| 8137 goto end_of_check; |
7604 } | 8138 } |
7605 | 8139 |
7606 /* Clear MemPage.isInit to make sure the corruption detection code in | 8140 /* Clear MemPage.isInit to make sure the corruption detection code in |
7607 ** btreeInitPage() is executed. */ | 8141 ** btreeInitPage() is executed. */ |
7608 pPage->isInit = 0; | 8142 pPage->isInit = 0; |
7609 if( (rc = btreeInitPage(pPage))!=0 ){ | 8143 if( (rc = btreeInitPage(pPage))!=0 ){ |
7610 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */ | 8144 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */ |
7611 checkAppendMsg(pCheck, zContext, | 8145 checkAppendMsg(pCheck, |
7612 "btreeInitPage() returns error code %d", rc); | 8146 "btreeInitPage() returns error code %d", rc); |
7613 releasePage(pPage); | 8147 releasePage(pPage); |
7614 return 0; | 8148 depth = -1; |
| 8149 goto end_of_check; |
7615 } | 8150 } |
7616 | 8151 |
7617 /* Check out all the cells. | 8152 /* Check out all the cells. |
7618 */ | 8153 */ |
7619 depth = 0; | 8154 depth = 0; |
7620 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){ | 8155 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){ |
7621 u8 *pCell; | 8156 u8 *pCell; |
7622 u32 sz; | 8157 u32 sz; |
7623 CellInfo info; | 8158 CellInfo info; |
7624 | 8159 |
7625 /* Check payload overflow pages | 8160 /* Check payload overflow pages |
7626 */ | 8161 */ |
7627 sqlite3_snprintf(sizeof(zContext), zContext, | 8162 pCheck->zPfx = "On tree page %d cell %d: "; |
7628 "On tree page %d cell %d: ", iPage, i); | 8163 pCheck->v1 = iPage; |
| 8164 pCheck->v2 = i; |
7629 pCell = findCell(pPage,i); | 8165 pCell = findCell(pPage,i); |
7630 btreeParseCellPtr(pPage, pCell, &info); | 8166 btreeParseCellPtr(pPage, pCell, &info); |
7631 sz = info.nData; | 8167 sz = info.nPayload; |
7632 if( !pPage->intKey ) sz += (int)info.nKey; | |
7633 /* For intKey pages, check that the keys are in order. | 8168 /* For intKey pages, check that the keys are in order. |
7634 */ | 8169 */ |
7635 else if( i==0 ) nMinKey = nMaxKey = info.nKey; | 8170 if( pPage->intKey ){ |
7636 else{ | 8171 if( i==0 ){ |
7637 if( info.nKey <= nMaxKey ){ | 8172 nMinKey = nMaxKey = info.nKey; |
7638 checkAppendMsg(pCheck, zContext, | 8173 }else if( info.nKey <= nMaxKey ){ |
7639 "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey); | 8174 checkAppendMsg(pCheck, |
| 8175 "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey); |
7640 } | 8176 } |
7641 nMaxKey = info.nKey; | 8177 nMaxKey = info.nKey; |
7642 } | 8178 } |
7643 assert( sz==info.nPayload ); | |
7644 if( (sz>info.nLocal) | 8179 if( (sz>info.nLocal) |
7645 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize]) | 8180 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize]) |
7646 ){ | 8181 ){ |
7647 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4); | 8182 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4); |
7648 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]); | 8183 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]); |
7649 #ifndef SQLITE_OMIT_AUTOVACUUM | 8184 #ifndef SQLITE_OMIT_AUTOVACUUM |
7650 if( pBt->autoVacuum ){ | 8185 if( pBt->autoVacuum ){ |
7651 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext); | 8186 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage); |
7652 } | 8187 } |
7653 #endif | 8188 #endif |
7654 checkList(pCheck, 0, pgnoOvfl, nPage, zContext); | 8189 checkList(pCheck, 0, pgnoOvfl, nPage); |
7655 } | 8190 } |
7656 | 8191 |
7657 /* Check sanity of left child page. | 8192 /* Check sanity of left child page. |
7658 */ | 8193 */ |
7659 if( !pPage->leaf ){ | 8194 if( !pPage->leaf ){ |
7660 pgno = get4byte(pCell); | 8195 pgno = get4byte(pCell); |
7661 #ifndef SQLITE_OMIT_AUTOVACUUM | 8196 #ifndef SQLITE_OMIT_AUTOVACUUM |
7662 if( pBt->autoVacuum ){ | 8197 if( pBt->autoVacuum ){ |
7663 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext); | 8198 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage); |
7664 } | 8199 } |
7665 #endif | 8200 #endif |
7666 d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKe
y); | 8201 d2 = checkTreePage(pCheck, pgno, &nMinKey, i==0?NULL:&nMaxKey); |
7667 if( i>0 && d2!=depth ){ | 8202 if( i>0 && d2!=depth ){ |
7668 checkAppendMsg(pCheck, zContext, "Child page depth differs"); | 8203 checkAppendMsg(pCheck, "Child page depth differs"); |
7669 } | 8204 } |
7670 depth = d2; | 8205 depth = d2; |
7671 } | 8206 } |
7672 } | 8207 } |
7673 | 8208 |
7674 if( !pPage->leaf ){ | 8209 if( !pPage->leaf ){ |
7675 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); | 8210 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); |
7676 sqlite3_snprintf(sizeof(zContext), zContext, | 8211 pCheck->zPfx = "On page %d at right child: "; |
7677 "On page %d at right child: ", iPage); | 8212 pCheck->v1 = iPage; |
7678 #ifndef SQLITE_OMIT_AUTOVACUUM | 8213 #ifndef SQLITE_OMIT_AUTOVACUUM |
7679 if( pBt->autoVacuum ){ | 8214 if( pBt->autoVacuum ){ |
7680 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext); | 8215 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage); |
7681 } | 8216 } |
7682 #endif | 8217 #endif |
7683 checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey)
; | 8218 checkTreePage(pCheck, pgno, NULL, !pPage->nCell?NULL:&nMaxKey); |
7684 } | 8219 } |
7685 | 8220 |
7686 /* For intKey leaf pages, check that the min/max keys are in order | 8221 /* For intKey leaf pages, check that the min/max keys are in order |
7687 ** with any left/parent/right pages. | 8222 ** with any left/parent/right pages. |
7688 */ | 8223 */ |
| 8224 pCheck->zPfx = "Page %d: "; |
| 8225 pCheck->v1 = iPage; |
7689 if( pPage->leaf && pPage->intKey ){ | 8226 if( pPage->leaf && pPage->intKey ){ |
7690 /* if we are a left child page */ | 8227 /* if we are a left child page */ |
7691 if( pnParentMinKey ){ | 8228 if( pnParentMinKey ){ |
7692 /* if we are the left most child page */ | 8229 /* if we are the left most child page */ |
7693 if( !pnParentMaxKey ){ | 8230 if( !pnParentMaxKey ){ |
7694 if( nMaxKey > *pnParentMinKey ){ | 8231 if( nMaxKey > *pnParentMinKey ){ |
7695 checkAppendMsg(pCheck, zContext, | 8232 checkAppendMsg(pCheck, |
7696 "Rowid %lld out of order (max larger than parent min of %lld)", | 8233 "Rowid %lld out of order (max larger than parent min of %lld)", |
7697 nMaxKey, *pnParentMinKey); | 8234 nMaxKey, *pnParentMinKey); |
7698 } | 8235 } |
7699 }else{ | 8236 }else{ |
7700 if( nMinKey <= *pnParentMinKey ){ | 8237 if( nMinKey <= *pnParentMinKey ){ |
7701 checkAppendMsg(pCheck, zContext, | 8238 checkAppendMsg(pCheck, |
7702 "Rowid %lld out of order (min less than parent min of %lld)", | 8239 "Rowid %lld out of order (min less than parent min of %lld)", |
7703 nMinKey, *pnParentMinKey); | 8240 nMinKey, *pnParentMinKey); |
7704 } | 8241 } |
7705 if( nMaxKey > *pnParentMaxKey ){ | 8242 if( nMaxKey > *pnParentMaxKey ){ |
7706 checkAppendMsg(pCheck, zContext, | 8243 checkAppendMsg(pCheck, |
7707 "Rowid %lld out of order (max larger than parent max of %lld)", | 8244 "Rowid %lld out of order (max larger than parent max of %lld)", |
7708 nMaxKey, *pnParentMaxKey); | 8245 nMaxKey, *pnParentMaxKey); |
7709 } | 8246 } |
7710 *pnParentMinKey = nMaxKey; | 8247 *pnParentMinKey = nMaxKey; |
7711 } | 8248 } |
7712 /* else if we're a right child page */ | 8249 /* else if we're a right child page */ |
7713 } else if( pnParentMaxKey ){ | 8250 } else if( pnParentMaxKey ){ |
7714 if( nMinKey <= *pnParentMaxKey ){ | 8251 if( nMinKey <= *pnParentMaxKey ){ |
7715 checkAppendMsg(pCheck, zContext, | 8252 checkAppendMsg(pCheck, |
7716 "Rowid %lld out of order (min less than parent max of %lld)", | 8253 "Rowid %lld out of order (min less than parent max of %lld)", |
7717 nMinKey, *pnParentMaxKey); | 8254 nMinKey, *pnParentMaxKey); |
7718 } | 8255 } |
7719 } | 8256 } |
7720 } | 8257 } |
7721 | 8258 |
7722 /* Check for complete coverage of the page | 8259 /* Check for complete coverage of the page |
7723 */ | 8260 */ |
7724 data = pPage->aData; | 8261 data = pPage->aData; |
7725 hdr = pPage->hdrOffset; | 8262 hdr = pPage->hdrOffset; |
7726 hit = sqlite3PageMalloc( pBt->pageSize ); | 8263 hit = sqlite3PageMalloc( pBt->pageSize ); |
| 8264 pCheck->zPfx = 0; |
7727 if( hit==0 ){ | 8265 if( hit==0 ){ |
7728 pCheck->mallocFailed = 1; | 8266 pCheck->mallocFailed = 1; |
7729 }else{ | 8267 }else{ |
7730 int contentOffset = get2byteNotZero(&data[hdr+5]); | 8268 int contentOffset = get2byteNotZero(&data[hdr+5]); |
7731 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */ | 8269 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */ |
7732 memset(hit+contentOffset, 0, usableSize-contentOffset); | 8270 memset(hit+contentOffset, 0, usableSize-contentOffset); |
7733 memset(hit, 1, contentOffset); | 8271 memset(hit, 1, contentOffset); |
7734 nCell = get2byte(&data[hdr+3]); | 8272 nCell = get2byte(&data[hdr+3]); |
7735 cellStart = hdr + 12 - 4*pPage->leaf; | 8273 cellStart = hdr + 12 - 4*pPage->leaf; |
7736 for(i=0; i<nCell; i++){ | 8274 for(i=0; i<nCell; i++){ |
7737 int pc = get2byte(&data[cellStart+i*2]); | 8275 int pc = get2byte(&data[cellStart+i*2]); |
7738 u32 size = 65536; | 8276 u32 size = 65536; |
7739 int j; | 8277 int j; |
7740 if( pc<=usableSize-4 ){ | 8278 if( pc<=usableSize-4 ){ |
7741 size = cellSizePtr(pPage, &data[pc]); | 8279 size = cellSizePtr(pPage, &data[pc]); |
7742 } | 8280 } |
7743 if( (int)(pc+size-1)>=usableSize ){ | 8281 if( (int)(pc+size-1)>=usableSize ){ |
7744 checkAppendMsg(pCheck, 0, | 8282 pCheck->zPfx = 0; |
| 8283 checkAppendMsg(pCheck, |
7745 "Corruption detected in cell %d on page %d",i,iPage); | 8284 "Corruption detected in cell %d on page %d",i,iPage); |
7746 }else{ | 8285 }else{ |
7747 for(j=pc+size-1; j>=pc; j--) hit[j]++; | 8286 for(j=pc+size-1; j>=pc; j--) hit[j]++; |
7748 } | 8287 } |
7749 } | 8288 } |
7750 i = get2byte(&data[hdr+1]); | 8289 i = get2byte(&data[hdr+1]); |
7751 while( i>0 ){ | 8290 while( i>0 ){ |
7752 int size, j; | 8291 int size, j; |
7753 assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */ | 8292 assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */ |
7754 size = get2byte(&data[i+2]); | 8293 size = get2byte(&data[i+2]); |
7755 assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */ | 8294 assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */ |
7756 for(j=i+size-1; j>=i; j--) hit[j]++; | 8295 for(j=i+size-1; j>=i; j--) hit[j]++; |
7757 j = get2byte(&data[i]); | 8296 j = get2byte(&data[i]); |
7758 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */ | 8297 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */ |
7759 assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */ | 8298 assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */ |
7760 i = j; | 8299 i = j; |
7761 } | 8300 } |
7762 for(i=cnt=0; i<usableSize; i++){ | 8301 for(i=cnt=0; i<usableSize; i++){ |
7763 if( hit[i]==0 ){ | 8302 if( hit[i]==0 ){ |
7764 cnt++; | 8303 cnt++; |
7765 }else if( hit[i]>1 ){ | 8304 }else if( hit[i]>1 ){ |
7766 checkAppendMsg(pCheck, 0, | 8305 checkAppendMsg(pCheck, |
7767 "Multiple uses for byte %d of page %d", i, iPage); | 8306 "Multiple uses for byte %d of page %d", i, iPage); |
7768 break; | 8307 break; |
7769 } | 8308 } |
7770 } | 8309 } |
7771 if( cnt!=data[hdr+7] ){ | 8310 if( cnt!=data[hdr+7] ){ |
7772 checkAppendMsg(pCheck, 0, | 8311 checkAppendMsg(pCheck, |
7773 "Fragmentation of %d bytes reported as %d on page %d", | 8312 "Fragmentation of %d bytes reported as %d on page %d", |
7774 cnt, data[hdr+7], iPage); | 8313 cnt, data[hdr+7], iPage); |
7775 } | 8314 } |
7776 } | 8315 } |
7777 sqlite3PageFree(hit); | 8316 sqlite3PageFree(hit); |
7778 releasePage(pPage); | 8317 releasePage(pPage); |
| 8318 |
| 8319 end_of_check: |
| 8320 pCheck->zPfx = saved_zPfx; |
| 8321 pCheck->v1 = saved_v1; |
| 8322 pCheck->v2 = saved_v2; |
7779 return depth+1; | 8323 return depth+1; |
7780 } | 8324 } |
7781 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ | 8325 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ |
7782 | 8326 |
7783 #ifndef SQLITE_OMIT_INTEGRITY_CHECK | 8327 #ifndef SQLITE_OMIT_INTEGRITY_CHECK |
7784 /* | 8328 /* |
7785 ** This routine does a complete check of the given BTree file. aRoot[] is | 8329 ** This routine does a complete check of the given BTree file. aRoot[] is |
7786 ** an array of pages numbers were each page number is the root page of | 8330 ** an array of pages numbers were each page number is the root page of |
7787 ** a table. nRoot is the number of entries in aRoot. | 8331 ** a table. nRoot is the number of entries in aRoot. |
7788 ** | 8332 ** |
(...skipping 20 matching lines...) Expand all Loading... |
7809 | 8353 |
7810 sqlite3BtreeEnter(p); | 8354 sqlite3BtreeEnter(p); |
7811 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE ); | 8355 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE ); |
7812 nRef = sqlite3PagerRefcount(pBt->pPager); | 8356 nRef = sqlite3PagerRefcount(pBt->pPager); |
7813 sCheck.pBt = pBt; | 8357 sCheck.pBt = pBt; |
7814 sCheck.pPager = pBt->pPager; | 8358 sCheck.pPager = pBt->pPager; |
7815 sCheck.nPage = btreePagecount(sCheck.pBt); | 8359 sCheck.nPage = btreePagecount(sCheck.pBt); |
7816 sCheck.mxErr = mxErr; | 8360 sCheck.mxErr = mxErr; |
7817 sCheck.nErr = 0; | 8361 sCheck.nErr = 0; |
7818 sCheck.mallocFailed = 0; | 8362 sCheck.mallocFailed = 0; |
| 8363 sCheck.zPfx = 0; |
| 8364 sCheck.v1 = 0; |
| 8365 sCheck.v2 = 0; |
7819 *pnErr = 0; | 8366 *pnErr = 0; |
7820 if( sCheck.nPage==0 ){ | 8367 if( sCheck.nPage==0 ){ |
7821 sqlite3BtreeLeave(p); | 8368 sqlite3BtreeLeave(p); |
7822 return 0; | 8369 return 0; |
7823 } | 8370 } |
7824 sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) ); | 8371 |
7825 if( !sCheck.anRef ){ | 8372 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1); |
| 8373 if( !sCheck.aPgRef ){ |
7826 *pnErr = 1; | 8374 *pnErr = 1; |
7827 sqlite3BtreeLeave(p); | 8375 sqlite3BtreeLeave(p); |
7828 return 0; | 8376 return 0; |
7829 } | 8377 } |
7830 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; } | |
7831 i = PENDING_BYTE_PAGE(pBt); | 8378 i = PENDING_BYTE_PAGE(pBt); |
7832 if( i<=sCheck.nPage ){ | 8379 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i); |
7833 sCheck.anRef[i] = 1; | 8380 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH); |
7834 } | |
7835 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000); | |
7836 sCheck.errMsg.useMalloc = 2; | 8381 sCheck.errMsg.useMalloc = 2; |
7837 | 8382 |
7838 /* Check the integrity of the freelist | 8383 /* Check the integrity of the freelist |
7839 */ | 8384 */ |
| 8385 sCheck.zPfx = "Main freelist: "; |
7840 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]), | 8386 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]), |
7841 get4byte(&pBt->pPage1->aData[36]), "Main freelist: "); | 8387 get4byte(&pBt->pPage1->aData[36])); |
| 8388 sCheck.zPfx = 0; |
7842 | 8389 |
7843 /* Check all the tables. | 8390 /* Check all the tables. |
7844 */ | 8391 */ |
7845 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){ | 8392 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){ |
7846 if( aRoot[i]==0 ) continue; | 8393 if( aRoot[i]==0 ) continue; |
7847 #ifndef SQLITE_OMIT_AUTOVACUUM | 8394 #ifndef SQLITE_OMIT_AUTOVACUUM |
7848 if( pBt->autoVacuum && aRoot[i]>1 ){ | 8395 if( pBt->autoVacuum && aRoot[i]>1 ){ |
7849 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0); | 8396 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0); |
7850 } | 8397 } |
7851 #endif | 8398 #endif |
7852 checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL); | 8399 sCheck.zPfx = "List of tree roots: "; |
| 8400 checkTreePage(&sCheck, aRoot[i], NULL, NULL); |
| 8401 sCheck.zPfx = 0; |
7853 } | 8402 } |
7854 | 8403 |
7855 /* Make sure every page in the file is referenced | 8404 /* Make sure every page in the file is referenced |
7856 */ | 8405 */ |
7857 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){ | 8406 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){ |
7858 #ifdef SQLITE_OMIT_AUTOVACUUM | 8407 #ifdef SQLITE_OMIT_AUTOVACUUM |
7859 if( sCheck.anRef[i]==0 ){ | 8408 if( getPageReferenced(&sCheck, i)==0 ){ |
7860 checkAppendMsg(&sCheck, 0, "Page %d is never used", i); | 8409 checkAppendMsg(&sCheck, "Page %d is never used", i); |
7861 } | 8410 } |
7862 #else | 8411 #else |
7863 /* If the database supports auto-vacuum, make sure no tables contain | 8412 /* If the database supports auto-vacuum, make sure no tables contain |
7864 ** references to pointer-map pages. | 8413 ** references to pointer-map pages. |
7865 */ | 8414 */ |
7866 if( sCheck.anRef[i]==0 && | 8415 if( getPageReferenced(&sCheck, i)==0 && |
7867 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){ | 8416 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){ |
7868 checkAppendMsg(&sCheck, 0, "Page %d is never used", i); | 8417 checkAppendMsg(&sCheck, "Page %d is never used", i); |
7869 } | 8418 } |
7870 if( sCheck.anRef[i]!=0 && | 8419 if( getPageReferenced(&sCheck, i)!=0 && |
7871 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){ | 8420 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){ |
7872 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i); | 8421 checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i); |
7873 } | 8422 } |
7874 #endif | 8423 #endif |
7875 } | 8424 } |
7876 | 8425 |
7877 /* Make sure this analysis did not leave any unref() pages. | 8426 /* Make sure this analysis did not leave any unref() pages. |
7878 ** This is an internal consistency check; an integrity check | 8427 ** This is an internal consistency check; an integrity check |
7879 ** of the integrity check. | 8428 ** of the integrity check. |
7880 */ | 8429 */ |
7881 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){ | 8430 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){ |
7882 checkAppendMsg(&sCheck, 0, | 8431 checkAppendMsg(&sCheck, |
7883 "Outstanding page count goes from %d to %d during this analysis", | 8432 "Outstanding page count goes from %d to %d during this analysis", |
7884 nRef, sqlite3PagerRefcount(pBt->pPager) | 8433 nRef, sqlite3PagerRefcount(pBt->pPager) |
7885 ); | 8434 ); |
7886 } | 8435 } |
7887 | 8436 |
7888 /* Clean up and report errors. | 8437 /* Clean up and report errors. |
7889 */ | 8438 */ |
7890 sqlite3BtreeLeave(p); | 8439 sqlite3BtreeLeave(p); |
7891 sqlite3_free(sCheck.anRef); | 8440 sqlite3_free(sCheck.aPgRef); |
7892 if( sCheck.mallocFailed ){ | 8441 if( sCheck.mallocFailed ){ |
7893 sqlite3StrAccumReset(&sCheck.errMsg); | 8442 sqlite3StrAccumReset(&sCheck.errMsg); |
7894 *pnErr = sCheck.nErr+1; | 8443 *pnErr = sCheck.nErr+1; |
7895 return 0; | 8444 return 0; |
7896 } | 8445 } |
7897 *pnErr = sCheck.nErr; | 8446 *pnErr = sCheck.nErr; |
7898 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg); | 8447 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg); |
7899 return sqlite3StrAccumFinish(&sCheck.errMsg); | 8448 return sqlite3StrAccumFinish(&sCheck.errMsg); |
7900 } | 8449 } |
7901 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ | 8450 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ |
7902 | 8451 |
7903 /* | 8452 /* |
7904 ** Return the full pathname of the underlying database file. | 8453 ** Return the full pathname of the underlying database file. Return |
| 8454 ** an empty string if the database is in-memory or a TEMP database. |
7905 ** | 8455 ** |
7906 ** The pager filename is invariant as long as the pager is | 8456 ** The pager filename is invariant as long as the pager is |
7907 ** open so it is safe to access without the BtShared mutex. | 8457 ** open so it is safe to access without the BtShared mutex. |
7908 */ | 8458 */ |
7909 const char *sqlite3BtreeGetFilename(Btree *p){ | 8459 const char *sqlite3BtreeGetFilename(Btree *p){ |
7910 assert( p->pBt->pPager!=0 ); | 8460 assert( p->pBt->pPager!=0 ); |
7911 return sqlite3PagerFilename(p->pBt->pPager); | 8461 return sqlite3PagerFilename(p->pBt->pPager, 1); |
7912 } | 8462 } |
7913 | 8463 |
7914 /* | 8464 /* |
7915 ** Return the pathname of the journal file for this database. The return | 8465 ** Return the pathname of the journal file for this database. The return |
7916 ** value of this routine is the same regardless of whether the journal file | 8466 ** value of this routine is the same regardless of whether the journal file |
7917 ** has been created or not. | 8467 ** has been created or not. |
7918 ** | 8468 ** |
7919 ** The pager journal filename is invariant as long as the pager is | 8469 ** The pager journal filename is invariant as long as the pager is |
7920 ** open so it is safe to access without the BtShared mutex. | 8470 ** open so it is safe to access without the BtShared mutex. |
7921 */ | 8471 */ |
(...skipping 130 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
8052 ** | 8602 ** |
8053 ** Only the data content may only be modified, it is not possible to | 8603 ** Only the data content may only be modified, it is not possible to |
8054 ** change the length of the data stored. If this function is called with | 8604 ** change the length of the data stored. If this function is called with |
8055 ** parameters that attempt to write past the end of the existing data, | 8605 ** parameters that attempt to write past the end of the existing data, |
8056 ** no modifications are made and SQLITE_CORRUPT is returned. | 8606 ** no modifications are made and SQLITE_CORRUPT is returned. |
8057 */ | 8607 */ |
8058 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){ | 8608 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){ |
8059 int rc; | 8609 int rc; |
8060 assert( cursorHoldsMutex(pCsr) ); | 8610 assert( cursorHoldsMutex(pCsr) ); |
8061 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) ); | 8611 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) ); |
8062 assert( pCsr->isIncrblobHandle ); | 8612 assert( pCsr->curFlags & BTCF_Incrblob ); |
8063 | 8613 |
8064 rc = restoreCursorPosition(pCsr); | 8614 rc = restoreCursorPosition(pCsr); |
8065 if( rc!=SQLITE_OK ){ | 8615 if( rc!=SQLITE_OK ){ |
8066 return rc; | 8616 return rc; |
8067 } | 8617 } |
8068 assert( pCsr->eState!=CURSOR_REQUIRESEEK ); | 8618 assert( pCsr->eState!=CURSOR_REQUIRESEEK ); |
8069 if( pCsr->eState!=CURSOR_VALID ){ | 8619 if( pCsr->eState!=CURSOR_VALID ){ |
8070 return SQLITE_ABORT; | 8620 return SQLITE_ABORT; |
8071 } | 8621 } |
8072 | 8622 |
| 8623 /* Save the positions of all other cursors open on this table. This is |
| 8624 ** required in case any of them are holding references to an xFetch |
| 8625 ** version of the b-tree page modified by the accessPayload call below. |
| 8626 ** |
| 8627 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition() |
| 8628 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence |
| 8629 ** saveAllCursors can only return SQLITE_OK. |
| 8630 */ |
| 8631 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr); |
| 8632 assert( rc==SQLITE_OK ); |
| 8633 |
8073 /* Check some assumptions: | 8634 /* Check some assumptions: |
8074 ** (a) the cursor is open for writing, | 8635 ** (a) the cursor is open for writing, |
8075 ** (b) there is a read/write transaction open, | 8636 ** (b) there is a read/write transaction open, |
8076 ** (c) the connection holds a write-lock on the table (if required), | 8637 ** (c) the connection holds a write-lock on the table (if required), |
8077 ** (d) there are no conflicting read-locks, and | 8638 ** (d) there are no conflicting read-locks, and |
8078 ** (e) the cursor points at a valid row of an intKey table. | 8639 ** (e) the cursor points at a valid row of an intKey table. |
8079 */ | 8640 */ |
8080 if( !pCsr->wrFlag ){ | 8641 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){ |
8081 return SQLITE_READONLY; | 8642 return SQLITE_READONLY; |
8082 } | 8643 } |
8083 assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE ); | 8644 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0 |
| 8645 && pCsr->pBt->inTransaction==TRANS_WRITE ); |
8084 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) ); | 8646 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) ); |
8085 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) ); | 8647 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) ); |
8086 assert( pCsr->apPage[pCsr->iPage]->intKey ); | 8648 assert( pCsr->apPage[pCsr->iPage]->intKey ); |
8087 | 8649 |
8088 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1); | 8650 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1); |
8089 } | 8651 } |
8090 | 8652 |
8091 /* | 8653 /* |
8092 ** Set a flag on this cursor to cache the locations of pages from the | 8654 ** Mark this cursor as an incremental blob cursor. |
8093 ** overflow list for the current row. This is used by cursors opened | |
8094 ** for incremental blob IO only. | |
8095 ** | |
8096 ** This function sets a flag only. The actual page location cache | |
8097 ** (stored in BtCursor.aOverflow[]) is allocated and used by function | |
8098 ** accessPayload() (the worker function for sqlite3BtreeData() and | |
8099 ** sqlite3BtreePutData()). | |
8100 */ | 8655 */ |
8101 void sqlite3BtreeCacheOverflow(BtCursor *pCur){ | 8656 void sqlite3BtreeIncrblobCursor(BtCursor *pCur){ |
8102 assert( cursorHoldsMutex(pCur) ); | 8657 pCur->curFlags |= BTCF_Incrblob; |
8103 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); | |
8104 invalidateOverflowCache(pCur); | |
8105 pCur->isIncrblobHandle = 1; | |
8106 } | 8658 } |
8107 #endif | 8659 #endif |
8108 | 8660 |
8109 /* | 8661 /* |
8110 ** Set both the "read version" (single byte at byte offset 18) and | 8662 ** Set both the "read version" (single byte at byte offset 18) and |
8111 ** "write version" (single byte at byte offset 19) fields in the database | 8663 ** "write version" (single byte at byte offset 19) fields in the database |
8112 ** header to iVersion. | 8664 ** header to iVersion. |
8113 */ | 8665 */ |
8114 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){ | 8666 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){ |
8115 BtShared *pBt = pBtree->pBt; | 8667 BtShared *pBt = pBtree->pBt; |
8116 int rc; /* Return code */ | 8668 int rc; /* Return code */ |
8117 | 8669 |
8118 assert( pBtree->inTrans==TRANS_NONE ); | |
8119 assert( iVersion==1 || iVersion==2 ); | 8670 assert( iVersion==1 || iVersion==2 ); |
8120 | 8671 |
8121 /* If setting the version fields to 1, do not automatically open the | 8672 /* If setting the version fields to 1, do not automatically open the |
8122 ** WAL connection, even if the version fields are currently set to 2. | 8673 ** WAL connection, even if the version fields are currently set to 2. |
8123 */ | 8674 */ |
8124 pBt->doNotUseWAL = (u8)(iVersion==1); | 8675 pBt->btsFlags &= ~BTS_NO_WAL; |
| 8676 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL; |
8125 | 8677 |
8126 rc = sqlite3BtreeBeginTrans(pBtree, 0); | 8678 rc = sqlite3BtreeBeginTrans(pBtree, 0); |
8127 if( rc==SQLITE_OK ){ | 8679 if( rc==SQLITE_OK ){ |
8128 u8 *aData = pBt->pPage1->aData; | 8680 u8 *aData = pBt->pPage1->aData; |
8129 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){ | 8681 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){ |
8130 rc = sqlite3BtreeBeginTrans(pBtree, 2); | 8682 rc = sqlite3BtreeBeginTrans(pBtree, 2); |
8131 if( rc==SQLITE_OK ){ | 8683 if( rc==SQLITE_OK ){ |
8132 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); | 8684 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); |
8133 if( rc==SQLITE_OK ){ | 8685 if( rc==SQLITE_OK ){ |
8134 aData[18] = (u8)iVersion; | 8686 aData[18] = (u8)iVersion; |
8135 aData[19] = (u8)iVersion; | 8687 aData[19] = (u8)iVersion; |
8136 } | 8688 } |
8137 } | 8689 } |
8138 } | 8690 } |
8139 } | 8691 } |
8140 | 8692 |
8141 pBt->doNotUseWAL = 0; | 8693 pBt->btsFlags &= ~BTS_NO_WAL; |
8142 return rc; | 8694 return rc; |
8143 } | 8695 } |
| 8696 |
| 8697 /* |
| 8698 ** set the mask of hint flags for cursor pCsr. Currently the only valid |
| 8699 ** values are 0 and BTREE_BULKLOAD. |
| 8700 */ |
| 8701 void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){ |
| 8702 assert( mask==BTREE_BULKLOAD || mask==0 ); |
| 8703 pCsr->hints = mask; |
| 8704 } |
| 8705 |
| 8706 /* |
| 8707 ** Return true if the given Btree is read-only. |
| 8708 */ |
| 8709 int sqlite3BtreeIsReadonly(Btree *p){ |
| 8710 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0; |
| 8711 } |
OLD | NEW |