ds@1952: /* ds@1952: ** 2004 April 6 ds@1952: ** ds@1952: ** The author disclaims copyright to this source code. In place of ds@1952: ** a legal notice, here is a blessing: ds@1952: ** ds@1952: ** May you do good and not evil. ds@1952: ** May you find forgiveness for yourself and forgive others. ds@1952: ** May you share freely, never taking more than you give. ds@1952: ** ds@1952: ************************************************************************* ds@1952: ** $Id$ ds@1952: ** ds@1952: ** This file implements a external (disk-based) database using BTrees. ds@1952: ** See the header comment on "btreeInt.h" for additional information. ds@1952: ** Including a description of file format and an overview of operation. ds@1952: */ ds@1952: #include "btreeInt.h" ds@1952: ds@1952: /* ds@1952: ** The header string that appears at the beginning of every ds@1952: ** SQLite database. ds@1952: */ ds@1952: static const char zMagicHeader[] = SQLITE_FILE_HEADER; ds@1952: ds@1952: /* ds@1952: ** Set this global variable to 1 to enable tracing using the TRACE ds@1952: ** macro. ds@1952: */ ds@1952: #if SQLITE_TEST ds@1952: int sqlite3_btree_trace=0; /* True to enable tracing */ ds@1952: #endif ds@1952: ds@1952: ds@1952: ds@1952: #ifndef SQLITE_OMIT_SHARED_CACHE ds@1952: /* ds@1952: ** A flag to indicate whether or not shared cache is enabled. Also, ds@1952: ** a list of BtShared objects that are eligible for participation ds@1952: ** in shared cache. The variables have file scope during normal builds, ds@1952: ** but the test harness needs to access these variables so we make them ds@1952: ** global for test builds. ds@1952: */ ds@1952: #ifdef SQLITE_TEST ds@1952: BtShared *sqlite3SharedCacheList = 0; ds@1952: int sqlite3SharedCacheEnabled = 0; ds@1952: #else ds@1952: static BtShared *sqlite3SharedCacheList = 0; ds@1952: static int sqlite3SharedCacheEnabled = 0; ds@1952: #endif ds@1952: #endif /* SQLITE_OMIT_SHARED_CACHE */ ds@1952: ds@1952: #ifndef SQLITE_OMIT_SHARED_CACHE ds@1952: /* ds@1952: ** Enable or disable the shared pager and schema features. ds@1952: ** ds@1952: ** This routine has no effect on existing database connections. ds@1952: ** The shared cache setting effects only future calls to ds@1952: ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2(). ds@1952: */ ds@1952: int sqlite3_enable_shared_cache(int enable){ ds@1952: sqlite3SharedCacheEnabled = enable; ds@1952: return SQLITE_OK; ds@1952: } ds@1952: #endif ds@1952: ds@1952: ds@1952: /* ds@1952: ** Forward declaration ds@1952: */ ds@1952: static int checkReadLocks(Btree*,Pgno,BtCursor*); ds@1952: ds@1952: ds@1952: #ifdef SQLITE_OMIT_SHARED_CACHE ds@1952: /* ds@1952: ** The functions queryTableLock(), lockTable() and unlockAllTables() ds@1952: ** manipulate entries in the BtShared.pLock linked list used to store ds@1952: ** shared-cache table level locks. If the library is compiled with the ds@1952: ** shared-cache feature disabled, then there is only ever one user ds@1952: ** of each BtShared structure and so this locking is not necessary. ds@1952: ** So define the lock related functions as no-ops. ds@1952: */ ds@1952: #define queryTableLock(a,b,c) SQLITE_OK ds@1952: #define lockTable(a,b,c) SQLITE_OK ds@1952: #define unlockAllTables(a) ds@1952: #endif ds@1952: ds@1952: #ifndef SQLITE_OMIT_SHARED_CACHE ds@1952: /* ds@1952: ** Query to see if btree handle p may obtain a lock of type eLock ds@1952: ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return ds@1952: ** SQLITE_OK if the lock may be obtained (by calling lockTable()), or ds@1952: ** SQLITE_LOCKED if not. ds@1952: */ ds@1952: static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){ ds@1952: BtShared *pBt = p->pBt; ds@1952: BtLock *pIter; ds@1952: ds@1952: assert( sqlite3BtreeHoldsMutex(p) ); ds@1952: ds@1952: /* This is a no-op if the shared-cache is not enabled */ ds@1952: if( !p->sharable ){ ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* This (along with lockTable()) is where the ReadUncommitted flag is ds@1952: ** dealt with. If the caller is querying for a read-lock and the flag is ds@1952: ** set, it is unconditionally granted - even if there are write-locks ds@1952: ** on the table. If a write-lock is requested, the ReadUncommitted flag ds@1952: ** is not considered. ds@1952: ** ds@1952: ** In function lockTable(), if a read-lock is demanded and the ds@1952: ** ReadUncommitted flag is set, no entry is added to the locks list ds@1952: ** (BtShared.pLock). ds@1952: ** ds@1952: ** To summarize: If the ReadUncommitted flag is set, then read cursors do ds@1952: ** not create or respect table locks. The locking procedure for a ds@1952: ** write-cursor does not change. ds@1952: */ ds@1952: if( ds@1952: !p->pSqlite || ds@1952: 0==(p->pSqlite->flags&SQLITE_ReadUncommitted) || ds@1952: eLock==WRITE_LOCK || ds@1952: iTab==MASTER_ROOT ds@1952: ){ ds@1952: for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ ds@1952: if( pIter->pBtree!=p && pIter->iTable==iTab && ds@1952: (pIter->eLock!=eLock || eLock!=READ_LOCK) ){ ds@1952: return SQLITE_LOCKED; ds@1952: } ds@1952: } ds@1952: } ds@1952: return SQLITE_OK; ds@1952: } ds@1952: #endif /* !SQLITE_OMIT_SHARED_CACHE */ ds@1952: ds@1952: #ifndef SQLITE_OMIT_SHARED_CACHE ds@1952: /* ds@1952: ** Add a lock on the table with root-page iTable to the shared-btree used ds@1952: ** by Btree handle p. Parameter eLock must be either READ_LOCK or ds@1952: ** WRITE_LOCK. ds@1952: ** ds@1952: ** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and ds@1952: ** SQLITE_NOMEM may also be returned. ds@1952: */ ds@1952: static int lockTable(Btree *p, Pgno iTable, u8 eLock){ ds@1952: BtShared *pBt = p->pBt; ds@1952: BtLock *pLock = 0; ds@1952: BtLock *pIter; ds@1952: ds@1952: assert( sqlite3BtreeHoldsMutex(p) ); ds@1952: ds@1952: /* This is a no-op if the shared-cache is not enabled */ ds@1952: if( !p->sharable ){ ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: assert( SQLITE_OK==queryTableLock(p, iTable, eLock) ); ds@1952: ds@1952: /* If the read-uncommitted flag is set and a read-lock is requested, ds@1952: ** return early without adding an entry to the BtShared.pLock list. See ds@1952: ** comment in function queryTableLock() for more info on handling ds@1952: ** the ReadUncommitted flag. ds@1952: */ ds@1952: if( ds@1952: (p->pSqlite) && ds@1952: (p->pSqlite->flags&SQLITE_ReadUncommitted) && ds@1952: (eLock==READ_LOCK) && ds@1952: iTable!=MASTER_ROOT ds@1952: ){ ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* First search the list for an existing lock on this table. */ ds@1952: for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ ds@1952: if( pIter->iTable==iTable && pIter->pBtree==p ){ ds@1952: pLock = pIter; ds@1952: break; ds@1952: } ds@1952: } ds@1952: ds@1952: /* If the above search did not find a BtLock struct associating Btree p ds@1952: ** with table iTable, allocate one and link it into the list. ds@1952: */ ds@1952: if( !pLock ){ ds@1952: pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock)); ds@1952: if( !pLock ){ ds@1952: return SQLITE_NOMEM; ds@1952: } ds@1952: pLock->iTable = iTable; ds@1952: pLock->pBtree = p; ds@1952: pLock->pNext = pBt->pLock; ds@1952: pBt->pLock = pLock; ds@1952: } ds@1952: ds@1952: /* Set the BtLock.eLock variable to the maximum of the current lock ds@1952: ** and the requested lock. This means if a write-lock was already held ds@1952: ** and a read-lock requested, we don't incorrectly downgrade the lock. ds@1952: */ ds@1952: assert( WRITE_LOCK>READ_LOCK ); ds@1952: if( eLock>pLock->eLock ){ ds@1952: pLock->eLock = eLock; ds@1952: } ds@1952: ds@1952: return SQLITE_OK; ds@1952: } ds@1952: #endif /* !SQLITE_OMIT_SHARED_CACHE */ ds@1952: ds@1952: #ifndef SQLITE_OMIT_SHARED_CACHE ds@1952: /* ds@1952: ** Release all the table locks (locks obtained via calls to the lockTable() ds@1952: ** procedure) held by Btree handle p. ds@1952: */ ds@1952: static void unlockAllTables(Btree *p){ ds@1952: BtLock **ppIter = &p->pBt->pLock; ds@1952: ds@1952: assert( sqlite3BtreeHoldsMutex(p) ); ds@1952: assert( p->sharable || 0==*ppIter ); ds@1952: ds@1952: while( *ppIter ){ ds@1952: BtLock *pLock = *ppIter; ds@1952: if( pLock->pBtree==p ){ ds@1952: *ppIter = pLock->pNext; ds@1952: sqlite3_free(pLock); ds@1952: }else{ ds@1952: ppIter = &pLock->pNext; ds@1952: } ds@1952: } ds@1952: } ds@1952: #endif /* SQLITE_OMIT_SHARED_CACHE */ ds@1952: ds@1952: static void releasePage(MemPage *pPage); /* Forward reference */ ds@1952: ds@1952: /* ds@1952: ** Verify that the cursor holds a mutex on the BtShared ds@1952: */ ds@1952: #ifndef NDEBUG ds@1952: static int cursorHoldsMutex(BtCursor *p){ ds@1952: return sqlite3_mutex_held(p->pBt->mutex); ds@1952: } ds@1952: #endif ds@1952: ds@1952: ds@1952: #ifndef SQLITE_OMIT_INCRBLOB ds@1952: /* ds@1952: ** Invalidate the overflow page-list cache for cursor pCur, if any. ds@1952: */ ds@1952: static void invalidateOverflowCache(BtCursor *pCur){ ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: sqlite3_free(pCur->aOverflow); ds@1952: pCur->aOverflow = 0; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Invalidate the overflow page-list cache for all cursors opened ds@1952: ** on the shared btree structure pBt. ds@1952: */ ds@1952: static void invalidateAllOverflowCache(BtShared *pBt){ ds@1952: BtCursor *p; ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: for(p=pBt->pCursor; p; p=p->pNext){ ds@1952: invalidateOverflowCache(p); ds@1952: } ds@1952: } ds@1952: #else ds@1952: #define invalidateOverflowCache(x) ds@1952: #define invalidateAllOverflowCache(x) ds@1952: #endif ds@1952: ds@1952: /* ds@1952: ** Save the current cursor position in the variables BtCursor.nKey ds@1952: ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK. ds@1952: */ ds@1952: static int saveCursorPosition(BtCursor *pCur){ ds@1952: int rc; ds@1952: ds@1952: assert( CURSOR_VALID==pCur->eState ); ds@1952: assert( 0==pCur->pKey ); ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: ds@1952: rc = sqlite3BtreeKeySize(pCur, &pCur->nKey); ds@1952: ds@1952: /* If this is an intKey table, then the above call to BtreeKeySize() ds@1952: ** stores the integer key in pCur->nKey. In this case this value is ds@1952: ** all that is required. Otherwise, if pCur is not open on an intKey ds@1952: ** table, then malloc space for and store the pCur->nKey bytes of key ds@1952: ** data. ds@1952: */ ds@1952: if( rc==SQLITE_OK && 0==pCur->pPage->intKey){ ds@1952: void *pKey = sqlite3_malloc(pCur->nKey); ds@1952: if( pKey ){ ds@1952: rc = sqlite3BtreeKey(pCur, 0, pCur->nKey, pKey); ds@1952: if( rc==SQLITE_OK ){ ds@1952: pCur->pKey = pKey; ds@1952: }else{ ds@1952: sqlite3_free(pKey); ds@1952: } ds@1952: }else{ ds@1952: rc = SQLITE_NOMEM; ds@1952: } ds@1952: } ds@1952: assert( !pCur->pPage->intKey || !pCur->pKey ); ds@1952: ds@1952: if( rc==SQLITE_OK ){ ds@1952: releasePage(pCur->pPage); ds@1952: pCur->pPage = 0; ds@1952: pCur->eState = CURSOR_REQUIRESEEK; ds@1952: } ds@1952: ds@1952: invalidateOverflowCache(pCur); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Save the positions of all cursors except pExcept open on the table ds@1952: ** with root-page iRoot. Usually, this is called just before cursor ds@1952: ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()). ds@1952: */ ds@1952: static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){ ds@1952: BtCursor *p; ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: assert( pExcept==0 || pExcept->pBt==pBt ); ds@1952: for(p=pBt->pCursor; p; p=p->pNext){ ds@1952: if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && ds@1952: p->eState==CURSOR_VALID ){ ds@1952: int rc = saveCursorPosition(p); ds@1952: if( SQLITE_OK!=rc ){ ds@1952: return rc; ds@1952: } ds@1952: } ds@1952: } ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Clear the current cursor position. ds@1952: */ ds@1952: static void clearCursorPosition(BtCursor *pCur){ ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: sqlite3_free(pCur->pKey); ds@1952: pCur->pKey = 0; ds@1952: pCur->eState = CURSOR_INVALID; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Restore the cursor to the position it was in (or as close to as possible) ds@1952: ** when saveCursorPosition() was called. Note that this call deletes the ds@1952: ** saved position info stored by saveCursorPosition(), so there can be ds@1952: ** at most one effective restoreOrClearCursorPosition() call after each ds@1952: ** saveCursorPosition(). ds@1952: ** ds@1952: ** If the second argument argument - doSeek - is false, then instead of ds@1952: ** returning the cursor to it's saved position, any saved position is deleted ds@1952: ** and the cursor state set to CURSOR_INVALID. ds@1952: */ ds@1952: int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur){ ds@1952: int rc; ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: assert( pCur->eState>=CURSOR_REQUIRESEEK ); ds@1952: if( pCur->eState==CURSOR_FAULT ){ ds@1952: return pCur->skip; ds@1952: } ds@1952: #ifndef SQLITE_OMIT_INCRBLOB ds@1952: if( pCur->isIncrblobHandle ){ ds@1952: return SQLITE_ABORT; ds@1952: } ds@1952: #endif ds@1952: pCur->eState = CURSOR_INVALID; ds@1952: rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skip); ds@1952: if( rc==SQLITE_OK ){ ds@1952: sqlite3_free(pCur->pKey); ds@1952: pCur->pKey = 0; ds@1952: assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID ); ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: ds@1952: #define restoreOrClearCursorPosition(p) \ ds@1952: (p->eState>=CURSOR_REQUIRESEEK ? \ ds@1952: sqlite3BtreeRestoreOrClearCursorPosition(p) : \ ds@1952: SQLITE_OK) ds@1952: ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: /* ds@1952: ** Given a page number of a regular database page, return the page ds@1952: ** number for the pointer-map page that contains the entry for the ds@1952: ** input page number. ds@1952: */ ds@1952: static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){ ds@1952: int nPagesPerMapPage, iPtrMap, ret; ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: nPagesPerMapPage = (pBt->usableSize/5)+1; ds@1952: iPtrMap = (pgno-2)/nPagesPerMapPage; ds@1952: ret = (iPtrMap*nPagesPerMapPage) + 2; ds@1952: if( ret==PENDING_BYTE_PAGE(pBt) ){ ds@1952: ret++; ds@1952: } ds@1952: return ret; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Write an entry into the pointer map. ds@1952: ** ds@1952: ** This routine updates the pointer map entry for page number 'key' ds@1952: ** so that it maps to type 'eType' and parent page number 'pgno'. ds@1952: ** An error code is returned if something goes wrong, otherwise SQLITE_OK. ds@1952: */ ds@1952: static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){ ds@1952: DbPage *pDbPage; /* The pointer map page */ ds@1952: u8 *pPtrmap; /* The pointer map data */ ds@1952: Pgno iPtrmap; /* The pointer map page number */ ds@1952: int offset; /* Offset in pointer map page */ ds@1952: int rc; ds@1952: ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: /* The master-journal page number must never be used as a pointer map page */ ds@1952: assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) ); ds@1952: ds@1952: assert( pBt->autoVacuum ); ds@1952: if( key==0 ){ ds@1952: return SQLITE_CORRUPT_BKPT; ds@1952: } ds@1952: iPtrmap = PTRMAP_PAGENO(pBt, key); ds@1952: rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: offset = PTRMAP_PTROFFSET(pBt, key); ds@1952: pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); ds@1952: ds@1952: if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){ ds@1952: TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent)); ds@1952: rc = sqlite3PagerWrite(pDbPage); ds@1952: if( rc==SQLITE_OK ){ ds@1952: pPtrmap[offset] = eType; ds@1952: put4byte(&pPtrmap[offset+1], parent); ds@1952: } ds@1952: } ds@1952: ds@1952: sqlite3PagerUnref(pDbPage); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Read an entry from the pointer map. ds@1952: ** ds@1952: ** This routine retrieves the pointer map entry for page 'key', writing ds@1952: ** the type and parent page number to *pEType and *pPgno respectively. ds@1952: ** An error code is returned if something goes wrong, otherwise SQLITE_OK. ds@1952: */ ds@1952: static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){ ds@1952: DbPage *pDbPage; /* The pointer map page */ ds@1952: int iPtrmap; /* Pointer map page index */ ds@1952: u8 *pPtrmap; /* Pointer map page data */ ds@1952: int offset; /* Offset of entry in pointer map */ ds@1952: int rc; ds@1952: ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: ds@1952: iPtrmap = PTRMAP_PAGENO(pBt, key); ds@1952: rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage); ds@1952: if( rc!=0 ){ ds@1952: return rc; ds@1952: } ds@1952: pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage); ds@1952: ds@1952: offset = PTRMAP_PTROFFSET(pBt, key); ds@1952: assert( pEType!=0 ); ds@1952: *pEType = pPtrmap[offset]; ds@1952: if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]); ds@1952: ds@1952: sqlite3PagerUnref(pDbPage); ds@1952: if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT; ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: #endif /* SQLITE_OMIT_AUTOVACUUM */ ds@1952: ds@1952: /* ds@1952: ** Given a btree page and a cell index (0 means the first cell on ds@1952: ** the page, 1 means the second cell, and so forth) return a pointer ds@1952: ** to the cell content. ds@1952: ** ds@1952: ** This routine works only for pages that do not contain overflow cells. ds@1952: */ ds@1952: #define findCell(pPage, iCell) \ ds@1952: ((pPage)->aData + get2byte(&(pPage)->aData[(pPage)->cellOffset+2*(iCell)])) ds@1952: #ifdef SQLITE_TEST ds@1952: u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell){ ds@1952: assert( iCell>=0 ); ds@1952: assert( iCellaData[pPage->hdrOffset+3]) ); ds@1952: return findCell(pPage, iCell); ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* ds@1952: ** This a more complex version of sqlite3BtreeFindCell() that works for ds@1952: ** pages that do contain overflow cells. See insert ds@1952: */ ds@1952: static u8 *findOverflowCell(MemPage *pPage, int iCell){ ds@1952: int i; ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: for(i=pPage->nOverflow-1; i>=0; i--){ ds@1952: int k; ds@1952: struct _OvflCell *pOvfl; ds@1952: pOvfl = &pPage->aOvfl[i]; ds@1952: k = pOvfl->idx; ds@1952: if( k<=iCell ){ ds@1952: if( k==iCell ){ ds@1952: return pOvfl->pCell; ds@1952: } ds@1952: iCell--; ds@1952: } ds@1952: } ds@1952: return findCell(pPage, iCell); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Parse a cell content block and fill in the CellInfo structure. There ds@1952: ** are two versions of this function. sqlite3BtreeParseCell() takes a ds@1952: ** cell index as the second argument and sqlite3BtreeParseCellPtr() ds@1952: ** takes a pointer to the body of the cell as its second argument. ds@1952: ** ds@1952: ** Within this file, the parseCell() macro can be called instead of ds@1952: ** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster. ds@1952: */ ds@1952: void sqlite3BtreeParseCellPtr( ds@1952: MemPage *pPage, /* Page containing the cell */ ds@1952: u8 *pCell, /* Pointer to the cell text. */ ds@1952: CellInfo *pInfo /* Fill in this structure */ ds@1952: ){ ds@1952: int n; /* Number bytes in cell content header */ ds@1952: u32 nPayload; /* Number of bytes of cell payload */ ds@1952: ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: ds@1952: pInfo->pCell = pCell; ds@1952: assert( pPage->leaf==0 || pPage->leaf==1 ); ds@1952: n = pPage->childPtrSize; ds@1952: assert( n==4-4*pPage->leaf ); ds@1952: if( pPage->hasData ){ ds@1952: n += getVarint32(&pCell[n], &nPayload); ds@1952: }else{ ds@1952: nPayload = 0; ds@1952: } ds@1952: pInfo->nData = nPayload; ds@1952: if( pPage->intKey ){ ds@1952: n += getVarint(&pCell[n], (u64 *)&pInfo->nKey); ds@1952: }else{ ds@1952: u32 x; ds@1952: n += getVarint32(&pCell[n], &x); ds@1952: pInfo->nKey = x; ds@1952: nPayload += x; ds@1952: } ds@1952: pInfo->nPayload = nPayload; ds@1952: pInfo->nHeader = n; ds@1952: if( nPayload<=pPage->maxLocal ){ ds@1952: /* This is the (easy) common case where the entire payload fits ds@1952: ** on the local page. No overflow is required. ds@1952: */ ds@1952: int nSize; /* Total size of cell content in bytes */ ds@1952: pInfo->nLocal = nPayload; ds@1952: pInfo->iOverflow = 0; ds@1952: nSize = nPayload + n; ds@1952: if( nSize<4 ){ ds@1952: nSize = 4; /* Minimum cell size is 4 */ ds@1952: } ds@1952: pInfo->nSize = nSize; ds@1952: }else{ ds@1952: /* If the payload will not fit completely on the local page, we have ds@1952: ** to decide how much to store locally and how much to spill onto ds@1952: ** overflow pages. The strategy is to minimize the amount of unused ds@1952: ** space on overflow pages while keeping the amount of local storage ds@1952: ** in between minLocal and maxLocal. ds@1952: ** ds@1952: ** Warning: changing the way overflow payload is distributed in any ds@1952: ** way will result in an incompatible file format. ds@1952: */ ds@1952: int minLocal; /* Minimum amount of payload held locally */ ds@1952: int maxLocal; /* Maximum amount of payload held locally */ ds@1952: int surplus; /* Overflow payload available for local storage */ ds@1952: ds@1952: minLocal = pPage->minLocal; ds@1952: maxLocal = pPage->maxLocal; ds@1952: surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4); ds@1952: if( surplus <= maxLocal ){ ds@1952: pInfo->nLocal = surplus; ds@1952: }else{ ds@1952: pInfo->nLocal = minLocal; ds@1952: } ds@1952: pInfo->iOverflow = pInfo->nLocal + n; ds@1952: pInfo->nSize = pInfo->iOverflow + 4; ds@1952: } ds@1952: } ds@1952: #define parseCell(pPage, iCell, pInfo) \ ds@1952: sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo)) ds@1952: void sqlite3BtreeParseCell( ds@1952: MemPage *pPage, /* Page containing the cell */ ds@1952: int iCell, /* The cell index. First cell is 0 */ ds@1952: CellInfo *pInfo /* Fill in this structure */ ds@1952: ){ ds@1952: parseCell(pPage, iCell, pInfo); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Compute the total number of bytes that a Cell needs in the cell ds@1952: ** data area of the btree-page. The return number includes the cell ds@1952: ** data header and the local payload, but not any overflow page or ds@1952: ** the space used by the cell pointer. ds@1952: */ ds@1952: #ifndef NDEBUG ds@1952: static int cellSize(MemPage *pPage, int iCell){ ds@1952: CellInfo info; ds@1952: sqlite3BtreeParseCell(pPage, iCell, &info); ds@1952: return info.nSize; ds@1952: } ds@1952: #endif ds@1952: static int cellSizePtr(MemPage *pPage, u8 *pCell){ ds@1952: CellInfo info; ds@1952: sqlite3BtreeParseCellPtr(pPage, pCell, &info); ds@1952: return info.nSize; ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: /* ds@1952: ** If the cell pCell, part of page pPage contains a pointer ds@1952: ** to an overflow page, insert an entry into the pointer-map ds@1952: ** for the overflow page. ds@1952: */ ds@1952: static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){ ds@1952: if( pCell ){ ds@1952: CellInfo info; ds@1952: sqlite3BtreeParseCellPtr(pPage, pCell, &info); ds@1952: assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload ); ds@1952: if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){ ds@1952: Pgno ovfl = get4byte(&pCell[info.iOverflow]); ds@1952: return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno); ds@1952: } ds@1952: } ds@1952: return SQLITE_OK; ds@1952: } ds@1952: /* ds@1952: ** If the cell with index iCell on page pPage contains a pointer ds@1952: ** to an overflow page, insert an entry into the pointer-map ds@1952: ** for the overflow page. ds@1952: */ ds@1952: static int ptrmapPutOvfl(MemPage *pPage, int iCell){ ds@1952: u8 *pCell; ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: pCell = findOverflowCell(pPage, iCell); ds@1952: return ptrmapPutOvflPtr(pPage, pCell); ds@1952: } ds@1952: #endif ds@1952: ds@1952: ds@1952: /* ds@1952: ** Defragment the page given. All Cells are moved to the ds@1952: ** end of the page and all free space is collected into one ds@1952: ** big FreeBlk that occurs in between the header and cell ds@1952: ** pointer array and the cell content area. ds@1952: */ ds@1952: static int defragmentPage(MemPage *pPage){ ds@1952: int i; /* Loop counter */ ds@1952: int pc; /* Address of a i-th cell */ ds@1952: int addr; /* Offset of first byte after cell pointer array */ ds@1952: int hdr; /* Offset to the page header */ ds@1952: int size; /* Size of a cell */ ds@1952: int usableSize; /* Number of usable bytes on a page */ ds@1952: int cellOffset; /* Offset to the cell pointer array */ ds@1952: int brk; /* Offset to the cell content area */ ds@1952: int nCell; /* Number of cells on the page */ ds@1952: unsigned char *data; /* The page data */ ds@1952: unsigned char *temp; /* Temp area for cell content */ ds@1952: ds@1952: assert( sqlite3PagerIswriteable(pPage->pDbPage) ); ds@1952: assert( pPage->pBt!=0 ); ds@1952: assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE ); ds@1952: assert( pPage->nOverflow==0 ); ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: temp = sqlite3_malloc( pPage->pBt->pageSize ); ds@1952: if( temp==0 ) return SQLITE_NOMEM; ds@1952: data = pPage->aData; ds@1952: hdr = pPage->hdrOffset; ds@1952: cellOffset = pPage->cellOffset; ds@1952: nCell = pPage->nCell; ds@1952: assert( nCell==get2byte(&data[hdr+3]) ); ds@1952: usableSize = pPage->pBt->usableSize; ds@1952: brk = get2byte(&data[hdr+5]); ds@1952: memcpy(&temp[brk], &data[brk], usableSize - brk); ds@1952: brk = usableSize; ds@1952: for(i=0; ipBt->usableSize ); ds@1952: size = cellSizePtr(pPage, &temp[pc]); ds@1952: brk -= size; ds@1952: memcpy(&data[brk], &temp[pc], size); ds@1952: put2byte(pAddr, brk); ds@1952: } ds@1952: assert( brk>=cellOffset+2*nCell ); ds@1952: put2byte(&data[hdr+5], brk); ds@1952: data[hdr+1] = 0; ds@1952: data[hdr+2] = 0; ds@1952: data[hdr+7] = 0; ds@1952: addr = cellOffset+2*nCell; ds@1952: memset(&data[addr], 0, brk-addr); ds@1952: sqlite3_free(temp); ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Allocate nByte bytes of space on a page. ds@1952: ** ds@1952: ** Return the index into pPage->aData[] of the first byte of ds@1952: ** the new allocation. Or return 0 if there is not enough free ds@1952: ** space on the page to satisfy the allocation request. ds@1952: ** ds@1952: ** If the page contains nBytes of free space but does not contain ds@1952: ** nBytes of contiguous free space, then this routine automatically ds@1952: ** calls defragementPage() to consolidate all free space before ds@1952: ** allocating the new chunk. ds@1952: */ ds@1952: static int allocateSpace(MemPage *pPage, int nByte){ ds@1952: int addr, pc, hdr; ds@1952: int size; ds@1952: int nFrag; ds@1952: int top; ds@1952: int nCell; ds@1952: int cellOffset; ds@1952: unsigned char *data; ds@1952: ds@1952: data = pPage->aData; ds@1952: assert( sqlite3PagerIswriteable(pPage->pDbPage) ); ds@1952: assert( pPage->pBt ); ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: if( nByte<4 ) nByte = 4; ds@1952: if( pPage->nFreenOverflow>0 ) return 0; ds@1952: pPage->nFree -= nByte; ds@1952: hdr = pPage->hdrOffset; ds@1952: ds@1952: nFrag = data[hdr+7]; ds@1952: if( nFrag<60 ){ ds@1952: /* Search the freelist looking for a slot big enough to satisfy the ds@1952: ** space request. */ ds@1952: addr = hdr+1; ds@1952: while( (pc = get2byte(&data[addr]))>0 ){ ds@1952: size = get2byte(&data[pc+2]); ds@1952: if( size>=nByte ){ ds@1952: if( sizecellOffset; ds@1952: if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){ ds@1952: if( defragmentPage(pPage) ) return 0; ds@1952: top = get2byte(&data[hdr+5]); ds@1952: } ds@1952: top -= nByte; ds@1952: assert( cellOffset + 2*nCell <= top ); ds@1952: put2byte(&data[hdr+5], top); ds@1952: return top; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Return a section of the pPage->aData to the freelist. ds@1952: ** The first byte of the new free block is pPage->aDisk[start] ds@1952: ** and the size of the block is "size" bytes. ds@1952: ** ds@1952: ** Most of the effort here is involved in coalesing adjacent ds@1952: ** free blocks into a single big free block. ds@1952: */ ds@1952: static void freeSpace(MemPage *pPage, int start, int size){ ds@1952: int addr, pbegin, hdr; ds@1952: unsigned char *data = pPage->aData; ds@1952: ds@1952: assert( pPage->pBt!=0 ); ds@1952: assert( sqlite3PagerIswriteable(pPage->pDbPage) ); ds@1952: assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) ); ds@1952: assert( (start + size)<=pPage->pBt->usableSize ); ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: if( size<4 ) size = 4; ds@1952: ds@1952: #ifdef SQLITE_SECURE_DELETE ds@1952: /* Overwrite deleted information with zeros when the SECURE_DELETE ds@1952: ** option is enabled at compile-time */ ds@1952: memset(&data[start], 0, size); ds@1952: #endif ds@1952: ds@1952: /* Add the space back into the linked list of freeblocks */ ds@1952: hdr = pPage->hdrOffset; ds@1952: addr = hdr + 1; ds@1952: while( (pbegin = get2byte(&data[addr]))0 ){ ds@1952: assert( pbegin<=pPage->pBt->usableSize-4 ); ds@1952: assert( pbegin>addr ); ds@1952: addr = pbegin; ds@1952: } ds@1952: assert( pbegin<=pPage->pBt->usableSize-4 ); ds@1952: assert( pbegin>addr || pbegin==0 ); ds@1952: put2byte(&data[addr], start); ds@1952: put2byte(&data[start], pbegin); ds@1952: put2byte(&data[start+2], size); ds@1952: pPage->nFree += size; ds@1952: ds@1952: /* Coalesce adjacent free blocks */ ds@1952: addr = pPage->hdrOffset + 1; ds@1952: while( (pbegin = get2byte(&data[addr]))>0 ){ ds@1952: int pnext, psize; ds@1952: assert( pbegin>addr ); ds@1952: assert( pbegin<=pPage->pBt->usableSize-4 ); ds@1952: pnext = get2byte(&data[pbegin]); ds@1952: psize = get2byte(&data[pbegin+2]); ds@1952: if( pbegin + psize + 3 >= pnext && pnext>0 ){ ds@1952: int frag = pnext - (pbegin+psize); ds@1952: assert( frag<=data[pPage->hdrOffset+7] ); ds@1952: data[pPage->hdrOffset+7] -= frag; ds@1952: put2byte(&data[pbegin], get2byte(&data[pnext])); ds@1952: put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin); ds@1952: }else{ ds@1952: addr = pbegin; ds@1952: } ds@1952: } ds@1952: ds@1952: /* If the cell content area begins with a freeblock, remove it. */ ds@1952: if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){ ds@1952: int top; ds@1952: pbegin = get2byte(&data[hdr+1]); ds@1952: memcpy(&data[hdr+1], &data[pbegin], 2); ds@1952: top = get2byte(&data[hdr+5]); ds@1952: put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2])); ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Decode the flags byte (the first byte of the header) for a page ds@1952: ** and initialize fields of the MemPage structure accordingly. ds@1952: */ ds@1952: static void decodeFlags(MemPage *pPage, int flagByte){ ds@1952: BtShared *pBt; /* A copy of pPage->pBt */ ds@1952: ds@1952: assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) ); ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0; ds@1952: pPage->zeroData = (flagByte & PTF_ZERODATA)!=0; ds@1952: pPage->leaf = (flagByte & PTF_LEAF)!=0; ds@1952: pPage->childPtrSize = 4*(pPage->leaf==0); ds@1952: pBt = pPage->pBt; ds@1952: if( flagByte & PTF_LEAFDATA ){ ds@1952: pPage->leafData = 1; ds@1952: pPage->maxLocal = pBt->maxLeaf; ds@1952: pPage->minLocal = pBt->minLeaf; ds@1952: }else{ ds@1952: pPage->leafData = 0; ds@1952: pPage->maxLocal = pBt->maxLocal; ds@1952: pPage->minLocal = pBt->minLocal; ds@1952: } ds@1952: pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData)); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Initialize the auxiliary information for a disk block. ds@1952: ** ds@1952: ** The pParent parameter must be a pointer to the MemPage which ds@1952: ** is the parent of the page being initialized. The root of a ds@1952: ** BTree has no parent and so for that page, pParent==NULL. ds@1952: ** ds@1952: ** Return SQLITE_OK on success. If we see that the page does ds@1952: ** not contain a well-formed database page, then return ds@1952: ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not ds@1952: ** guarantee that the page is well-formed. It only shows that ds@1952: ** we failed to detect any corruption. ds@1952: */ ds@1952: int sqlite3BtreeInitPage( ds@1952: MemPage *pPage, /* The page to be initialized */ ds@1952: MemPage *pParent /* The parent. Might be NULL */ ds@1952: ){ ds@1952: int pc; /* Address of a freeblock within pPage->aData[] */ ds@1952: int hdr; /* Offset to beginning of page header */ ds@1952: u8 *data; /* Equal to pPage->aData */ ds@1952: BtShared *pBt; /* The main btree structure */ ds@1952: int usableSize; /* Amount of usable space on each page */ ds@1952: int cellOffset; /* Offset from start of page to first cell pointer */ ds@1952: int nFree; /* Number of unused bytes on the page */ ds@1952: int top; /* First byte of the cell content area */ ds@1952: ds@1952: pBt = pPage->pBt; ds@1952: assert( pBt!=0 ); ds@1952: assert( pParent==0 || pParent->pBt==pBt ); ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) ); ds@1952: assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) ); ds@1952: assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) ); ds@1952: if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){ ds@1952: /* The parent page should never change unless the file is corrupt */ ds@1952: return SQLITE_CORRUPT_BKPT; ds@1952: } ds@1952: if( pPage->isInit ) return SQLITE_OK; ds@1952: if( pPage->pParent==0 && pParent!=0 ){ ds@1952: pPage->pParent = pParent; ds@1952: sqlite3PagerRef(pParent->pDbPage); ds@1952: } ds@1952: hdr = pPage->hdrOffset; ds@1952: data = pPage->aData; ds@1952: decodeFlags(pPage, data[hdr]); ds@1952: pPage->nOverflow = 0; ds@1952: pPage->idxShift = 0; ds@1952: usableSize = pBt->usableSize; ds@1952: pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf; ds@1952: top = get2byte(&data[hdr+5]); ds@1952: pPage->nCell = get2byte(&data[hdr+3]); ds@1952: if( pPage->nCell>MX_CELL(pBt) ){ ds@1952: /* To many cells for a single page. The page must be corrupt */ ds@1952: return SQLITE_CORRUPT_BKPT; ds@1952: } ds@1952: if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){ ds@1952: /* All pages must have at least one cell, except for root pages */ ds@1952: return SQLITE_CORRUPT_BKPT; ds@1952: } ds@1952: ds@1952: /* Compute the total free space on the page */ ds@1952: pc = get2byte(&data[hdr+1]); ds@1952: nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell); ds@1952: while( pc>0 ){ ds@1952: int next, size; ds@1952: if( pc>usableSize-4 ){ ds@1952: /* Free block is off the page */ ds@1952: return SQLITE_CORRUPT_BKPT; ds@1952: } ds@1952: next = get2byte(&data[pc]); ds@1952: size = get2byte(&data[pc+2]); ds@1952: if( next>0 && next<=pc+size+3 ){ ds@1952: /* Free blocks must be in accending order */ ds@1952: return SQLITE_CORRUPT_BKPT; ds@1952: } ds@1952: nFree += size; ds@1952: pc = next; ds@1952: } ds@1952: pPage->nFree = nFree; ds@1952: if( nFree>=usableSize ){ ds@1952: /* Free space cannot exceed total page size */ ds@1952: return SQLITE_CORRUPT_BKPT; ds@1952: } ds@1952: ds@1952: pPage->isInit = 1; ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Set up a raw page so that it looks like a database page holding ds@1952: ** no entries. ds@1952: */ ds@1952: static void zeroPage(MemPage *pPage, int flags){ ds@1952: unsigned char *data = pPage->aData; ds@1952: BtShared *pBt = pPage->pBt; ds@1952: int hdr = pPage->hdrOffset; ds@1952: int first; ds@1952: ds@1952: assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno ); ds@1952: assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); ds@1952: assert( sqlite3PagerGetData(pPage->pDbPage) == data ); ds@1952: assert( sqlite3PagerIswriteable(pPage->pDbPage) ); ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: memset(&data[hdr], 0, pBt->usableSize - hdr); ds@1952: data[hdr] = flags; ds@1952: first = hdr + 8 + 4*((flags&PTF_LEAF)==0); ds@1952: memset(&data[hdr+1], 0, 4); ds@1952: data[hdr+7] = 0; ds@1952: put2byte(&data[hdr+5], pBt->usableSize); ds@1952: pPage->nFree = pBt->usableSize - first; ds@1952: decodeFlags(pPage, flags); ds@1952: pPage->hdrOffset = hdr; ds@1952: pPage->cellOffset = first; ds@1952: pPage->nOverflow = 0; ds@1952: pPage->idxShift = 0; ds@1952: pPage->nCell = 0; ds@1952: pPage->isInit = 1; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Get a page from the pager. Initialize the MemPage.pBt and ds@1952: ** MemPage.aData elements if needed. ds@1952: ** ds@1952: ** If the noContent flag is set, it means that we do not care about ds@1952: ** the content of the page at this time. So do not go to the disk ds@1952: ** to fetch the content. Just fill in the content with zeros for now. ds@1952: ** If in the future we call sqlite3PagerWrite() on this page, that ds@1952: ** means we have started to be concerned about content and the disk ds@1952: ** read should occur at that point. ds@1952: */ ds@1952: int sqlite3BtreeGetPage( ds@1952: BtShared *pBt, /* The btree */ ds@1952: Pgno pgno, /* Number of the page to fetch */ ds@1952: MemPage **ppPage, /* Return the page in this parameter */ ds@1952: int noContent /* Do not load page content if true */ ds@1952: ){ ds@1952: int rc; ds@1952: MemPage *pPage; ds@1952: DbPage *pDbPage; ds@1952: ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent); ds@1952: if( rc ) return rc; ds@1952: pPage = (MemPage *)sqlite3PagerGetExtra(pDbPage); ds@1952: pPage->aData = sqlite3PagerGetData(pDbPage); ds@1952: pPage->pDbPage = pDbPage; ds@1952: pPage->pBt = pBt; ds@1952: pPage->pgno = pgno; ds@1952: pPage->hdrOffset = pPage->pgno==1 ? 100 : 0; ds@1952: *ppPage = pPage; ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Get a page from the pager and initialize it. This routine ds@1952: ** is just a convenience wrapper around separate calls to ds@1952: ** sqlite3BtreeGetPage() and sqlite3BtreeInitPage(). ds@1952: */ ds@1952: static int getAndInitPage( ds@1952: BtShared *pBt, /* The database file */ ds@1952: Pgno pgno, /* Number of the page to get */ ds@1952: MemPage **ppPage, /* Write the page pointer here */ ds@1952: MemPage *pParent /* Parent of the page */ ds@1952: ){ ds@1952: int rc; ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: if( pgno==0 ){ ds@1952: return SQLITE_CORRUPT_BKPT; ds@1952: } ds@1952: rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0); ds@1952: if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){ ds@1952: rc = sqlite3BtreeInitPage(*ppPage, pParent); ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Release a MemPage. This should be called once for each prior ds@1952: ** call to sqlite3BtreeGetPage. ds@1952: */ ds@1952: static void releasePage(MemPage *pPage){ ds@1952: if( pPage ){ ds@1952: assert( pPage->aData ); ds@1952: assert( pPage->pBt ); ds@1952: assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage ); ds@1952: assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData ); ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: sqlite3PagerUnref(pPage->pDbPage); ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine is called when the reference count for a page ds@1952: ** reaches zero. We need to unref the pParent pointer when that ds@1952: ** happens. ds@1952: */ ds@1952: static void pageDestructor(DbPage *pData, int pageSize){ ds@1952: MemPage *pPage; ds@1952: assert( (pageSize & 7)==0 ); ds@1952: pPage = (MemPage *)sqlite3PagerGetExtra(pData); ds@1952: assert( pPage->isInit==0 || sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: if( pPage->pParent ){ ds@1952: MemPage *pParent = pPage->pParent; ds@1952: assert( pParent->pBt==pPage->pBt ); ds@1952: pPage->pParent = 0; ds@1952: releasePage(pParent); ds@1952: } ds@1952: pPage->isInit = 0; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** During a rollback, when the pager reloads information into the cache ds@1952: ** so that the cache is restored to its original state at the start of ds@1952: ** the transaction, for each page restored this routine is called. ds@1952: ** ds@1952: ** This routine needs to reset the extra data section at the end of the ds@1952: ** page to agree with the restored data. ds@1952: */ ds@1952: static void pageReinit(DbPage *pData, int pageSize){ ds@1952: MemPage *pPage; ds@1952: assert( (pageSize & 7)==0 ); ds@1952: pPage = (MemPage *)sqlite3PagerGetExtra(pData); ds@1952: if( pPage->isInit ){ ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: pPage->isInit = 0; ds@1952: sqlite3BtreeInitPage(pPage, pPage->pParent); ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Open a database file. ds@1952: ** ds@1952: ** zFilename is the name of the database file. If zFilename is NULL ds@1952: ** a new database with a random name is created. This randomly named ds@1952: ** database file will be deleted when sqlite3BtreeClose() is called. ds@1952: ** If zFilename is ":memory:" then an in-memory database is created ds@1952: ** that is automatically destroyed when it is closed. ds@1952: */ ds@1952: int sqlite3BtreeOpen( ds@1952: const char *zFilename, /* Name of the file containing the BTree database */ ds@1952: sqlite3 *pSqlite, /* Associated database handle */ ds@1952: Btree **ppBtree, /* Pointer to new Btree object written here */ ds@1952: int flags, /* Options */ ds@1952: int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */ ds@1952: ){ ds@1952: sqlite3_vfs *pVfs; /* The VFS to use for this btree */ ds@1952: BtShared *pBt = 0; /* Shared part of btree structure */ ds@1952: Btree *p; /* Handle to return */ ds@1952: int rc = SQLITE_OK; ds@1952: int nReserve; ds@1952: unsigned char zDbHeader[100]; ds@1952: ds@1952: /* Set the variable isMemdb to true for an in-memory database, or ds@1952: ** false for a file-based database. This symbol is only required if ds@1952: ** either of the shared-data or autovacuum features are compiled ds@1952: ** into the library. ds@1952: */ ds@1952: #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM) ds@1952: #ifdef SQLITE_OMIT_MEMORYDB ds@1952: const int isMemdb = 0; ds@1952: #else ds@1952: const int isMemdb = zFilename && !strcmp(zFilename, ":memory:"); ds@1952: #endif ds@1952: #endif ds@1952: ds@1952: assert( pSqlite!=0 ); ds@1952: assert( sqlite3_mutex_held(pSqlite->mutex) ); ds@1952: ds@1952: pVfs = pSqlite->pVfs; ds@1952: p = sqlite3MallocZero(sizeof(Btree)); ds@1952: if( !p ){ ds@1952: return SQLITE_NOMEM; ds@1952: } ds@1952: p->inTrans = TRANS_NONE; ds@1952: p->pSqlite = pSqlite; ds@1952: ds@1952: #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) ds@1952: /* ds@1952: ** If this Btree is a candidate for shared cache, try to find an ds@1952: ** existing BtShared object that we can share with ds@1952: */ ds@1952: if( (flags & BTREE_PRIVATE)==0 ds@1952: && isMemdb==0 ds@1952: && (pSqlite->flags & SQLITE_Vtab)==0 ds@1952: && zFilename && zFilename[0] ds@1952: ){ ds@1952: if( sqlite3SharedCacheEnabled ){ ds@1952: int nFullPathname = pVfs->mxPathname+1; ds@1952: char *zFullPathname = (char *)sqlite3_malloc(nFullPathname); ds@1952: sqlite3_mutex *mutexShared; ds@1952: p->sharable = 1; ds@1952: if( pSqlite ){ ds@1952: pSqlite->flags |= SQLITE_SharedCache; ds@1952: } ds@1952: if( !zFullPathname ){ ds@1952: sqlite3_free(p); ds@1952: return SQLITE_NOMEM; ds@1952: } ds@1952: sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname); ds@1952: mutexShared = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); ds@1952: sqlite3_mutex_enter(mutexShared); ds@1952: for(pBt=sqlite3SharedCacheList; pBt; pBt=pBt->pNext){ ds@1952: assert( pBt->nRef>0 ); ds@1952: if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager)) ds@1952: && sqlite3PagerVfs(pBt->pPager)==pVfs ){ ds@1952: p->pBt = pBt; ds@1952: pBt->nRef++; ds@1952: break; ds@1952: } ds@1952: } ds@1952: sqlite3_mutex_leave(mutexShared); ds@1952: sqlite3_free(zFullPathname); ds@1952: } ds@1952: #ifdef SQLITE_DEBUG ds@1952: else{ ds@1952: /* In debug mode, we mark all persistent databases as sharable ds@1952: ** even when they are not. This exercises the locking code and ds@1952: ** gives more opportunity for asserts(sqlite3_mutex_held()) ds@1952: ** statements to find locking problems. ds@1952: */ ds@1952: p->sharable = 1; ds@1952: } ds@1952: #endif ds@1952: } ds@1952: #endif ds@1952: if( pBt==0 ){ ds@1952: /* ds@1952: ** The following asserts make sure that structures used by the btree are ds@1952: ** the right size. This is to guard against size changes that result ds@1952: ** when compiling on a different architecture. ds@1952: */ ds@1952: assert( sizeof(i64)==8 || sizeof(i64)==4 ); ds@1952: assert( sizeof(u64)==8 || sizeof(u64)==4 ); ds@1952: assert( sizeof(u32)==4 ); ds@1952: assert( sizeof(u16)==2 ); ds@1952: assert( sizeof(Pgno)==4 ); ds@1952: ds@1952: pBt = sqlite3MallocZero( sizeof(*pBt) ); ds@1952: if( pBt==0 ){ ds@1952: rc = SQLITE_NOMEM; ds@1952: goto btree_open_out; ds@1952: } ds@1952: rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename, ds@1952: EXTRA_SIZE, flags, vfsFlags); ds@1952: if( rc==SQLITE_OK ){ ds@1952: rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader); ds@1952: } ds@1952: if( rc!=SQLITE_OK ){ ds@1952: goto btree_open_out; ds@1952: } ds@1952: p->pBt = pBt; ds@1952: ds@1952: sqlite3PagerSetDestructor(pBt->pPager, pageDestructor); ds@1952: sqlite3PagerSetReiniter(pBt->pPager, pageReinit); ds@1952: pBt->pCursor = 0; ds@1952: pBt->pPage1 = 0; ds@1952: pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager); ds@1952: pBt->pageSize = get2byte(&zDbHeader[16]); ds@1952: if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE ds@1952: || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){ ds@1952: pBt->pageSize = 0; ds@1952: sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize); ds@1952: pBt->maxEmbedFrac = 64; /* 25% */ ds@1952: pBt->minEmbedFrac = 32; /* 12.5% */ ds@1952: pBt->minLeafFrac = 32; /* 12.5% */ ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: /* If the magic name ":memory:" will create an in-memory database, then ds@1952: ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if ds@1952: ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if ds@1952: ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a ds@1952: ** regular file-name. In this case the auto-vacuum applies as per normal. ds@1952: */ ds@1952: if( zFilename && !isMemdb ){ ds@1952: pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0); ds@1952: pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0); ds@1952: } ds@1952: #endif ds@1952: nReserve = 0; ds@1952: }else{ ds@1952: nReserve = zDbHeader[20]; ds@1952: pBt->maxEmbedFrac = zDbHeader[21]; ds@1952: pBt->minEmbedFrac = zDbHeader[22]; ds@1952: pBt->minLeafFrac = zDbHeader[23]; ds@1952: pBt->pageSizeFixed = 1; ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0); ds@1952: pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0); ds@1952: #endif ds@1952: } ds@1952: pBt->usableSize = pBt->pageSize - nReserve; ds@1952: assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */ ds@1952: sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize); ds@1952: ds@1952: #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) ds@1952: /* Add the new BtShared object to the linked list sharable BtShareds. ds@1952: */ ds@1952: if( p->sharable ){ ds@1952: sqlite3_mutex *mutexShared; ds@1952: pBt->nRef = 1; ds@1952: mutexShared = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); ds@1952: if( SQLITE_THREADSAFE ){ ds@1952: pBt->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); ds@1952: if( pBt->mutex==0 ){ ds@1952: rc = SQLITE_NOMEM; ds@1952: pSqlite->mallocFailed = 0; ds@1952: goto btree_open_out; ds@1952: } ds@1952: } ds@1952: sqlite3_mutex_enter(mutexShared); ds@1952: pBt->pNext = sqlite3SharedCacheList; ds@1952: sqlite3SharedCacheList = pBt; ds@1952: sqlite3_mutex_leave(mutexShared); ds@1952: } ds@1952: #endif ds@1952: } ds@1952: ds@1952: #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) ds@1952: /* If the new Btree uses a sharable pBtShared, then link the new ds@1952: ** Btree into the list of all sharable Btrees for the same connection. ds@1952: ** The list is kept in ascending order by pBt address. ds@1952: */ ds@1952: if( p->sharable ){ ds@1952: int i; ds@1952: Btree *pSib; ds@1952: for(i=0; inDb; i++){ ds@1952: if( (pSib = pSqlite->aDb[i].pBt)!=0 && pSib->sharable ){ ds@1952: while( pSib->pPrev ){ pSib = pSib->pPrev; } ds@1952: if( p->pBtpBt ){ ds@1952: p->pNext = pSib; ds@1952: p->pPrev = 0; ds@1952: pSib->pPrev = p; ds@1952: }else{ ds@1952: while( pSib->pNext && pSib->pNext->pBtpBt ){ ds@1952: pSib = pSib->pNext; ds@1952: } ds@1952: p->pNext = pSib->pNext; ds@1952: p->pPrev = pSib; ds@1952: if( p->pNext ){ ds@1952: p->pNext->pPrev = p; ds@1952: } ds@1952: pSib->pNext = p; ds@1952: } ds@1952: break; ds@1952: } ds@1952: } ds@1952: } ds@1952: #endif ds@1952: *ppBtree = p; ds@1952: ds@1952: btree_open_out: ds@1952: if( rc!=SQLITE_OK ){ ds@1952: if( pBt && pBt->pPager ){ ds@1952: sqlite3PagerClose(pBt->pPager); ds@1952: } ds@1952: sqlite3_free(pBt); ds@1952: sqlite3_free(p); ds@1952: *ppBtree = 0; ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Decrement the BtShared.nRef counter. When it reaches zero, ds@1952: ** remove the BtShared structure from the sharing list. Return ds@1952: ** true if the BtShared.nRef counter reaches zero and return ds@1952: ** false if it is still positive. ds@1952: */ ds@1952: static int removeFromSharingList(BtShared *pBt){ ds@1952: #ifndef SQLITE_OMIT_SHARED_CACHE ds@1952: sqlite3_mutex *pMaster; ds@1952: BtShared *pList; ds@1952: int removed = 0; ds@1952: ds@1952: assert( sqlite3_mutex_notheld(pBt->mutex) ); ds@1952: pMaster = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); ds@1952: sqlite3_mutex_enter(pMaster); ds@1952: pBt->nRef--; ds@1952: if( pBt->nRef<=0 ){ ds@1952: if( sqlite3SharedCacheList==pBt ){ ds@1952: sqlite3SharedCacheList = pBt->pNext; ds@1952: }else{ ds@1952: pList = sqlite3SharedCacheList; ds@1952: while( pList && pList->pNext!=pBt ){ ds@1952: pList=pList->pNext; ds@1952: } ds@1952: if( pList ){ ds@1952: pList->pNext = pBt->pNext; ds@1952: } ds@1952: } ds@1952: if( SQLITE_THREADSAFE ){ ds@1952: sqlite3_mutex_free(pBt->mutex); ds@1952: } ds@1952: removed = 1; ds@1952: } ds@1952: sqlite3_mutex_leave(pMaster); ds@1952: return removed; ds@1952: #else ds@1952: return 1; ds@1952: #endif ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Close an open database and invalidate all cursors. ds@1952: */ ds@1952: int sqlite3BtreeClose(Btree *p){ ds@1952: BtShared *pBt = p->pBt; ds@1952: BtCursor *pCur; ds@1952: ds@1952: /* Close all cursors opened via this handle. */ ds@1952: assert( sqlite3_mutex_held(p->pSqlite->mutex) ); ds@1952: sqlite3BtreeEnter(p); ds@1952: pCur = pBt->pCursor; ds@1952: while( pCur ){ ds@1952: BtCursor *pTmp = pCur; ds@1952: pCur = pCur->pNext; ds@1952: if( pTmp->pBtree==p ){ ds@1952: sqlite3BtreeCloseCursor(pTmp); ds@1952: } ds@1952: } ds@1952: ds@1952: /* Rollback any active transaction and free the handle structure. ds@1952: ** The call to sqlite3BtreeRollback() drops any table-locks held by ds@1952: ** this handle. ds@1952: */ ds@1952: sqlite3BtreeRollback(p); ds@1952: sqlite3BtreeLeave(p); ds@1952: ds@1952: /* If there are still other outstanding references to the shared-btree ds@1952: ** structure, return now. The remainder of this procedure cleans ds@1952: ** up the shared-btree. ds@1952: */ ds@1952: assert( p->wantToLock==0 && p->locked==0 ); ds@1952: if( !p->sharable || removeFromSharingList(pBt) ){ ds@1952: /* The pBt is no longer on the sharing list, so we can access ds@1952: ** it without having to hold the mutex. ds@1952: ** ds@1952: ** Clean out and delete the BtShared object. ds@1952: */ ds@1952: assert( !pBt->pCursor ); ds@1952: sqlite3PagerClose(pBt->pPager); ds@1952: if( pBt->xFreeSchema && pBt->pSchema ){ ds@1952: pBt->xFreeSchema(pBt->pSchema); ds@1952: } ds@1952: sqlite3_free(pBt->pSchema); ds@1952: sqlite3_free(pBt); ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_SHARED_CACHE ds@1952: assert( p->wantToLock==0 ); ds@1952: assert( p->locked==0 ); ds@1952: if( p->pPrev ) p->pPrev->pNext = p->pNext; ds@1952: if( p->pNext ) p->pNext->pPrev = p->pPrev; ds@1952: #endif ds@1952: ds@1952: sqlite3_free(p); ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Change the busy handler callback function. ds@1952: */ ds@1952: int sqlite3BtreeSetBusyHandler(Btree *p, BusyHandler *pHandler){ ds@1952: BtShared *pBt = p->pBt; ds@1952: assert( sqlite3_mutex_held(p->pSqlite->mutex) ); ds@1952: sqlite3BtreeEnter(p); ds@1952: pBt->pBusyHandler = pHandler; ds@1952: sqlite3PagerSetBusyhandler(pBt->pPager, pHandler); ds@1952: sqlite3BtreeLeave(p); ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Change the limit on the number of pages allowed in the cache. ds@1952: ** ds@1952: ** The maximum number of cache pages is set to the absolute ds@1952: ** value of mxPage. If mxPage is negative, the pager will ds@1952: ** operate asynchronously - it will not stop to do fsync()s ds@1952: ** to insure data is written to the disk surface before ds@1952: ** continuing. Transactions still work if synchronous is off, ds@1952: ** and the database cannot be corrupted if this program ds@1952: ** crashes. But if the operating system crashes or there is ds@1952: ** an abrupt power failure when synchronous is off, the database ds@1952: ** could be left in an inconsistent and unrecoverable state. ds@1952: ** Synchronous is on by default so database corruption is not ds@1952: ** normally a worry. ds@1952: */ ds@1952: int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){ ds@1952: BtShared *pBt = p->pBt; ds@1952: assert( sqlite3_mutex_held(p->pSqlite->mutex) ); ds@1952: sqlite3BtreeEnter(p); ds@1952: sqlite3PagerSetCachesize(pBt->pPager, mxPage); ds@1952: sqlite3BtreeLeave(p); ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Change the way data is synced to disk in order to increase or decrease ds@1952: ** how well the database resists damage due to OS crashes and power ds@1952: ** failures. Level 1 is the same as asynchronous (no syncs() occur and ds@1952: ** there is a high probability of damage) Level 2 is the default. There ds@1952: ** is a very low but non-zero probability of damage. Level 3 reduces the ds@1952: ** probability of damage to near zero but with a write performance reduction. ds@1952: */ ds@1952: #ifndef SQLITE_OMIT_PAGER_PRAGMAS ds@1952: int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){ ds@1952: BtShared *pBt = p->pBt; ds@1952: assert( sqlite3_mutex_held(p->pSqlite->mutex) ); ds@1952: sqlite3BtreeEnter(p); ds@1952: sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync); ds@1952: sqlite3BtreeLeave(p); ds@1952: return SQLITE_OK; ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* ds@1952: ** Return TRUE if the given btree is set to safety level 1. In other ds@1952: ** words, return TRUE if no sync() occurs on the disk files. ds@1952: */ ds@1952: int sqlite3BtreeSyncDisabled(Btree *p){ ds@1952: BtShared *pBt = p->pBt; ds@1952: int rc; ds@1952: assert( sqlite3_mutex_held(p->pSqlite->mutex) ); ds@1952: sqlite3BtreeEnter(p); ds@1952: assert( pBt && pBt->pPager ); ds@1952: rc = sqlite3PagerNosync(pBt->pPager); ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) ds@1952: /* ds@1952: ** Change the default pages size and the number of reserved bytes per page. ds@1952: ** ds@1952: ** The page size must be a power of 2 between 512 and 65536. If the page ds@1952: ** size supplied does not meet this constraint then the page size is not ds@1952: ** changed. ds@1952: ** ds@1952: ** Page sizes are constrained to be a power of two so that the region ds@1952: ** of the database file used for locking (beginning at PENDING_BYTE, ds@1952: ** the first byte past the 1GB boundary, 0x40000000) needs to occur ds@1952: ** at the beginning of a page. ds@1952: ** ds@1952: ** If parameter nReserve is less than zero, then the number of reserved ds@1952: ** bytes per page is left unchanged. ds@1952: */ ds@1952: int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){ ds@1952: int rc = SQLITE_OK; ds@1952: BtShared *pBt = p->pBt; ds@1952: sqlite3BtreeEnter(p); ds@1952: if( pBt->pageSizeFixed ){ ds@1952: sqlite3BtreeLeave(p); ds@1952: return SQLITE_READONLY; ds@1952: } ds@1952: if( nReserve<0 ){ ds@1952: nReserve = pBt->pageSize - pBt->usableSize; ds@1952: } ds@1952: if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE && ds@1952: ((pageSize-1)&pageSize)==0 ){ ds@1952: assert( (pageSize & 7)==0 ); ds@1952: assert( !pBt->pPage1 && !pBt->pCursor ); ds@1952: pBt->pageSize = pageSize; ds@1952: rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize); ds@1952: } ds@1952: pBt->usableSize = pBt->pageSize - nReserve; ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Return the currently defined page size ds@1952: */ ds@1952: int sqlite3BtreeGetPageSize(Btree *p){ ds@1952: return p->pBt->pageSize; ds@1952: } ds@1952: int sqlite3BtreeGetReserve(Btree *p){ ds@1952: int n; ds@1952: sqlite3BtreeEnter(p); ds@1952: n = p->pBt->pageSize - p->pBt->usableSize; ds@1952: sqlite3BtreeLeave(p); ds@1952: return n; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Set the maximum page count for a database if mxPage is positive. ds@1952: ** No changes are made if mxPage is 0 or negative. ds@1952: ** Regardless of the value of mxPage, return the maximum page count. ds@1952: */ ds@1952: int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){ ds@1952: int n; ds@1952: sqlite3BtreeEnter(p); ds@1952: n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage); ds@1952: sqlite3BtreeLeave(p); ds@1952: return n; ds@1952: } ds@1952: #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */ ds@1952: ds@1952: /* ds@1952: ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum' ds@1952: ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it ds@1952: ** is disabled. The default value for the auto-vacuum property is ds@1952: ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro. ds@1952: */ ds@1952: int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){ ds@1952: #ifdef SQLITE_OMIT_AUTOVACUUM ds@1952: return SQLITE_READONLY; ds@1952: #else ds@1952: BtShared *pBt = p->pBt; ds@1952: int rc = SQLITE_OK; ds@1952: int av = (autoVacuum?1:0); ds@1952: ds@1952: sqlite3BtreeEnter(p); ds@1952: if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){ ds@1952: rc = SQLITE_READONLY; ds@1952: }else{ ds@1952: pBt->autoVacuum = av; ds@1952: } ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: #endif ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Return the value of the 'auto-vacuum' property. If auto-vacuum is ds@1952: ** enabled 1 is returned. Otherwise 0. ds@1952: */ ds@1952: int sqlite3BtreeGetAutoVacuum(Btree *p){ ds@1952: #ifdef SQLITE_OMIT_AUTOVACUUM ds@1952: return BTREE_AUTOVACUUM_NONE; ds@1952: #else ds@1952: int rc; ds@1952: sqlite3BtreeEnter(p); ds@1952: rc = ( ds@1952: (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE: ds@1952: (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL: ds@1952: BTREE_AUTOVACUUM_INCR ds@1952: ); ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: #endif ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** Get a reference to pPage1 of the database file. This will ds@1952: ** also acquire a readlock on that file. ds@1952: ** ds@1952: ** SQLITE_OK is returned on success. If the file is not a ds@1952: ** well-formed database file, then SQLITE_CORRUPT is returned. ds@1952: ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM ds@1952: ** is returned if we run out of memory. ds@1952: */ ds@1952: static int lockBtree(BtShared *pBt){ ds@1952: int rc, pageSize; ds@1952: MemPage *pPage1; ds@1952: ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: if( pBt->pPage1 ) return SQLITE_OK; ds@1952: rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0); ds@1952: if( rc!=SQLITE_OK ) return rc; ds@1952: ds@1952: ds@1952: /* Do some checking to help insure the file we opened really is ds@1952: ** a valid database file. ds@1952: */ ds@1952: rc = SQLITE_NOTADB; ds@1952: if( sqlite3PagerPagecount(pBt->pPager)>0 ){ ds@1952: u8 *page1 = pPage1->aData; ds@1952: if( memcmp(page1, zMagicHeader, 16)!=0 ){ ds@1952: goto page1_init_failed; ds@1952: } ds@1952: if( page1[18]>1 ){ ds@1952: pBt->readOnly = 1; ds@1952: } ds@1952: if( page1[19]>1 ){ ds@1952: goto page1_init_failed; ds@1952: } ds@1952: pageSize = get2byte(&page1[16]); ds@1952: if( ((pageSize-1)&pageSize)!=0 || pageSize<512 || ds@1952: (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE) ds@1952: ){ ds@1952: goto page1_init_failed; ds@1952: } ds@1952: assert( (pageSize & 7)==0 ); ds@1952: pBt->pageSize = pageSize; ds@1952: pBt->usableSize = pageSize - page1[20]; ds@1952: if( pBt->usableSize<500 ){ ds@1952: goto page1_init_failed; ds@1952: } ds@1952: pBt->maxEmbedFrac = page1[21]; ds@1952: pBt->minEmbedFrac = page1[22]; ds@1952: pBt->minLeafFrac = page1[23]; ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0); ds@1952: pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0); ds@1952: #endif ds@1952: } ds@1952: ds@1952: /* maxLocal is the maximum amount of payload to store locally for ds@1952: ** a cell. Make sure it is small enough so that at least minFanout ds@1952: ** cells can will fit on one page. We assume a 10-byte page header. ds@1952: ** Besides the payload, the cell must store: ds@1952: ** 2-byte pointer to the cell ds@1952: ** 4-byte child pointer ds@1952: ** 9-byte nKey value ds@1952: ** 4-byte nData value ds@1952: ** 4-byte overflow page pointer ds@1952: ** So a cell consists of a 2-byte poiner, a header which is as much as ds@1952: ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow ds@1952: ** page pointer. ds@1952: */ ds@1952: pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23; ds@1952: pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23; ds@1952: pBt->maxLeaf = pBt->usableSize - 35; ds@1952: pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23; ds@1952: if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){ ds@1952: goto page1_init_failed; ds@1952: } ds@1952: assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) ); ds@1952: pBt->pPage1 = pPage1; ds@1952: return SQLITE_OK; ds@1952: ds@1952: page1_init_failed: ds@1952: releasePage(pPage1); ds@1952: pBt->pPage1 = 0; ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine works like lockBtree() except that it also invokes the ds@1952: ** busy callback if there is lock contention. ds@1952: */ ds@1952: static int lockBtreeWithRetry(Btree *pRef){ ds@1952: int rc = SQLITE_OK; ds@1952: ds@1952: assert( sqlite3BtreeHoldsMutex(pRef) ); ds@1952: if( pRef->inTrans==TRANS_NONE ){ ds@1952: u8 inTransaction = pRef->pBt->inTransaction; ds@1952: btreeIntegrity(pRef); ds@1952: rc = sqlite3BtreeBeginTrans(pRef, 0); ds@1952: pRef->pBt->inTransaction = inTransaction; ds@1952: pRef->inTrans = TRANS_NONE; ds@1952: if( rc==SQLITE_OK ){ ds@1952: pRef->pBt->nTransaction--; ds@1952: } ds@1952: btreeIntegrity(pRef); ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** If there are no outstanding cursors and we are not in the middle ds@1952: ** of a transaction but there is a read lock on the database, then ds@1952: ** this routine unrefs the first page of the database file which ds@1952: ** has the effect of releasing the read lock. ds@1952: ** ds@1952: ** If there are any outstanding cursors, this routine is a no-op. ds@1952: ** ds@1952: ** If there is a transaction in progress, this routine is a no-op. ds@1952: */ ds@1952: static void unlockBtreeIfUnused(BtShared *pBt){ ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){ ds@1952: if( sqlite3PagerRefcount(pBt->pPager)>=1 ){ ds@1952: if( pBt->pPage1->aData==0 ){ ds@1952: MemPage *pPage = pBt->pPage1; ds@1952: pPage->aData = sqlite3PagerGetData(pPage->pDbPage); ds@1952: pPage->pBt = pBt; ds@1952: pPage->pgno = 1; ds@1952: } ds@1952: releasePage(pBt->pPage1); ds@1952: } ds@1952: pBt->pPage1 = 0; ds@1952: pBt->inStmt = 0; ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Create a new database by initializing the first page of the ds@1952: ** file. ds@1952: */ ds@1952: static int newDatabase(BtShared *pBt){ ds@1952: MemPage *pP1; ds@1952: unsigned char *data; ds@1952: int rc; ds@1952: ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: if( sqlite3PagerPagecount(pBt->pPager)>0 ) return SQLITE_OK; ds@1952: pP1 = pBt->pPage1; ds@1952: assert( pP1!=0 ); ds@1952: data = pP1->aData; ds@1952: rc = sqlite3PagerWrite(pP1->pDbPage); ds@1952: if( rc ) return rc; ds@1952: memcpy(data, zMagicHeader, sizeof(zMagicHeader)); ds@1952: assert( sizeof(zMagicHeader)==16 ); ds@1952: put2byte(&data[16], pBt->pageSize); ds@1952: data[18] = 1; ds@1952: data[19] = 1; ds@1952: data[20] = pBt->pageSize - pBt->usableSize; ds@1952: data[21] = pBt->maxEmbedFrac; ds@1952: data[22] = pBt->minEmbedFrac; ds@1952: data[23] = pBt->minLeafFrac; ds@1952: memset(&data[24], 0, 100-24); ds@1952: zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA ); ds@1952: pBt->pageSizeFixed = 1; ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 ); ds@1952: assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 ); ds@1952: put4byte(&data[36 + 4*4], pBt->autoVacuum); ds@1952: put4byte(&data[36 + 7*4], pBt->incrVacuum); ds@1952: #endif ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Attempt to start a new transaction. A write-transaction ds@1952: ** is started if the second argument is nonzero, otherwise a read- ds@1952: ** transaction. If the second argument is 2 or more and exclusive ds@1952: ** transaction is started, meaning that no other process is allowed ds@1952: ** to access the database. A preexisting transaction may not be ds@1952: ** upgraded to exclusive by calling this routine a second time - the ds@1952: ** exclusivity flag only works for a new transaction. ds@1952: ** ds@1952: ** A write-transaction must be started before attempting any ds@1952: ** changes to the database. None of the following routines ds@1952: ** will work unless a transaction is started first: ds@1952: ** ds@1952: ** sqlite3BtreeCreateTable() ds@1952: ** sqlite3BtreeCreateIndex() ds@1952: ** sqlite3BtreeClearTable() ds@1952: ** sqlite3BtreeDropTable() ds@1952: ** sqlite3BtreeInsert() ds@1952: ** sqlite3BtreeDelete() ds@1952: ** sqlite3BtreeUpdateMeta() ds@1952: ** ds@1952: ** If an initial attempt to acquire the lock fails because of lock contention ds@1952: ** and the database was previously unlocked, then invoke the busy handler ds@1952: ** if there is one. But if there was previously a read-lock, do not ds@1952: ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is ds@1952: ** returned when there is already a read-lock in order to avoid a deadlock. ds@1952: ** ds@1952: ** Suppose there are two processes A and B. A has a read lock and B has ds@1952: ** a reserved lock. B tries to promote to exclusive but is blocked because ds@1952: ** of A's read lock. A tries to promote to reserved but is blocked by B. ds@1952: ** One or the other of the two processes must give way or there can be ds@1952: ** no progress. By returning SQLITE_BUSY and not invoking the busy callback ds@1952: ** when A already has a read lock, we encourage A to give up and let B ds@1952: ** proceed. ds@1952: */ ds@1952: int sqlite3BtreeBeginTrans(Btree *p, int wrflag){ ds@1952: BtShared *pBt = p->pBt; ds@1952: int rc = SQLITE_OK; ds@1952: ds@1952: sqlite3BtreeEnter(p); ds@1952: btreeIntegrity(p); ds@1952: ds@1952: /* If the btree is already in a write-transaction, or it ds@1952: ** is already in a read-transaction and a read-transaction ds@1952: ** is requested, this is a no-op. ds@1952: */ ds@1952: if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){ ds@1952: goto trans_begun; ds@1952: } ds@1952: ds@1952: /* Write transactions are not possible on a read-only database */ ds@1952: if( pBt->readOnly && wrflag ){ ds@1952: rc = SQLITE_READONLY; ds@1952: goto trans_begun; ds@1952: } ds@1952: ds@1952: /* If another database handle has already opened a write transaction ds@1952: ** on this shared-btree structure and a second write transaction is ds@1952: ** requested, return SQLITE_BUSY. ds@1952: */ ds@1952: if( pBt->inTransaction==TRANS_WRITE && wrflag ){ ds@1952: rc = SQLITE_BUSY; ds@1952: goto trans_begun; ds@1952: } ds@1952: ds@1952: do { ds@1952: if( pBt->pPage1==0 ){ ds@1952: rc = lockBtree(pBt); ds@1952: } ds@1952: ds@1952: if( rc==SQLITE_OK && wrflag ){ ds@1952: if( pBt->readOnly ){ ds@1952: rc = SQLITE_READONLY; ds@1952: }else{ ds@1952: rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1); ds@1952: if( rc==SQLITE_OK ){ ds@1952: rc = newDatabase(pBt); ds@1952: } ds@1952: } ds@1952: } ds@1952: ds@1952: if( rc==SQLITE_OK ){ ds@1952: if( wrflag ) pBt->inStmt = 0; ds@1952: }else{ ds@1952: unlockBtreeIfUnused(pBt); ds@1952: } ds@1952: }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE && ds@1952: sqlite3InvokeBusyHandler(pBt->pBusyHandler) ); ds@1952: ds@1952: if( rc==SQLITE_OK ){ ds@1952: if( p->inTrans==TRANS_NONE ){ ds@1952: pBt->nTransaction++; ds@1952: } ds@1952: p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ); ds@1952: if( p->inTrans>pBt->inTransaction ){ ds@1952: pBt->inTransaction = p->inTrans; ds@1952: } ds@1952: } ds@1952: ds@1952: ds@1952: trans_begun: ds@1952: btreeIntegrity(p); ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: ds@1952: /* ds@1952: ** Set the pointer-map entries for all children of page pPage. Also, if ds@1952: ** pPage contains cells that point to overflow pages, set the pointer ds@1952: ** map entries for the overflow pages as well. ds@1952: */ ds@1952: static int setChildPtrmaps(MemPage *pPage){ ds@1952: int i; /* Counter variable */ ds@1952: int nCell; /* Number of cells in page pPage */ ds@1952: int rc; /* Return code */ ds@1952: BtShared *pBt = pPage->pBt; ds@1952: int isInitOrig = pPage->isInit; ds@1952: Pgno pgno = pPage->pgno; ds@1952: ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: rc = sqlite3BtreeInitPage(pPage, pPage->pParent); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: goto set_child_ptrmaps_out; ds@1952: } ds@1952: nCell = pPage->nCell; ds@1952: ds@1952: for(i=0; ileaf ){ ds@1952: Pgno childPgno = get4byte(pCell); ds@1952: rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno); ds@1952: if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out; ds@1952: } ds@1952: } ds@1952: ds@1952: if( !pPage->leaf ){ ds@1952: Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); ds@1952: rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno); ds@1952: } ds@1952: ds@1952: set_child_ptrmaps_out: ds@1952: pPage->isInit = isInitOrig; ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow ds@1952: ** page, is a pointer to page iFrom. Modify this pointer so that it points to ds@1952: ** iTo. Parameter eType describes the type of pointer to be modified, as ds@1952: ** follows: ds@1952: ** ds@1952: ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child ds@1952: ** page of pPage. ds@1952: ** ds@1952: ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow ds@1952: ** page pointed to by one of the cells on pPage. ds@1952: ** ds@1952: ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next ds@1952: ** overflow page in the list. ds@1952: */ ds@1952: static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){ ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: if( eType==PTRMAP_OVERFLOW2 ){ ds@1952: /* The pointer is always the first 4 bytes of the page in this case. */ ds@1952: if( get4byte(pPage->aData)!=iFrom ){ ds@1952: return SQLITE_CORRUPT_BKPT; ds@1952: } ds@1952: put4byte(pPage->aData, iTo); ds@1952: }else{ ds@1952: int isInitOrig = pPage->isInit; ds@1952: int i; ds@1952: int nCell; ds@1952: ds@1952: sqlite3BtreeInitPage(pPage, 0); ds@1952: nCell = pPage->nCell; ds@1952: ds@1952: for(i=0; iaData[pPage->hdrOffset+8])!=iFrom ){ ds@1952: return SQLITE_CORRUPT_BKPT; ds@1952: } ds@1952: put4byte(&pPage->aData[pPage->hdrOffset+8], iTo); ds@1952: } ds@1952: ds@1952: pPage->isInit = isInitOrig; ds@1952: } ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** Move the open database page pDbPage to location iFreePage in the ds@1952: ** database. The pDbPage reference remains valid. ds@1952: */ ds@1952: static int relocatePage( ds@1952: BtShared *pBt, /* Btree */ ds@1952: MemPage *pDbPage, /* Open page to move */ ds@1952: u8 eType, /* Pointer map 'type' entry for pDbPage */ ds@1952: Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */ ds@1952: Pgno iFreePage /* The location to move pDbPage to */ ds@1952: ){ ds@1952: MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */ ds@1952: Pgno iDbPage = pDbPage->pgno; ds@1952: Pager *pPager = pBt->pPager; ds@1952: int rc; ds@1952: ds@1952: assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || ds@1952: eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ); ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: assert( pDbPage->pBt==pBt ); ds@1952: ds@1952: /* Move page iDbPage from it's current location to page number iFreePage */ ds@1952: TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", ds@1952: iDbPage, iFreePage, iPtrPage, eType)); ds@1952: rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: pDbPage->pgno = iFreePage; ds@1952: ds@1952: /* If pDbPage was a btree-page, then it may have child pages and/or cells ds@1952: ** that point to overflow pages. The pointer map entries for all these ds@1952: ** pages need to be changed. ds@1952: ** ds@1952: ** If pDbPage is an overflow page, then the first 4 bytes may store a ds@1952: ** pointer to a subsequent overflow page. If this is the case, then ds@1952: ** the pointer map needs to be updated for the subsequent overflow page. ds@1952: */ ds@1952: if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){ ds@1952: rc = setChildPtrmaps(pDbPage); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: }else{ ds@1952: Pgno nextOvfl = get4byte(pDbPage->aData); ds@1952: if( nextOvfl!=0 ){ ds@1952: rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: } ds@1952: } ds@1952: ds@1952: /* Fix the database pointer on page iPtrPage that pointed at iDbPage so ds@1952: ** that it points at iFreePage. Also fix the pointer map entry for ds@1952: ** iPtrPage. ds@1952: */ ds@1952: if( eType!=PTRMAP_ROOTPAGE ){ ds@1952: rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: rc = sqlite3PagerWrite(pPtrPage->pDbPage); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: releasePage(pPtrPage); ds@1952: return rc; ds@1952: } ds@1952: rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType); ds@1952: releasePage(pPtrPage); ds@1952: if( rc==SQLITE_OK ){ ds@1952: rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage); ds@1952: } ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* Forward declaration required by incrVacuumStep(). */ ds@1952: static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8); ds@1952: ds@1952: /* ds@1952: ** Perform a single step of an incremental-vacuum. If successful, ds@1952: ** return SQLITE_OK. If there is no work to do (and therefore no ds@1952: ** point in calling this function again), return SQLITE_DONE. ds@1952: ** ds@1952: ** More specificly, this function attempts to re-organize the ds@1952: ** database so that the last page of the file currently in use ds@1952: ** is no longer in use. ds@1952: ** ds@1952: ** If the nFin parameter is non-zero, the implementation assumes ds@1952: ** that the caller will keep calling incrVacuumStep() until ds@1952: ** it returns SQLITE_DONE or an error, and that nFin is the ds@1952: ** number of pages the database file will contain after this ds@1952: ** process is complete. ds@1952: */ ds@1952: static int incrVacuumStep(BtShared *pBt, Pgno nFin){ ds@1952: Pgno iLastPg; /* Last page in the database */ ds@1952: Pgno nFreeList; /* Number of pages still on the free-list */ ds@1952: ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: iLastPg = pBt->nTrunc; ds@1952: if( iLastPg==0 ){ ds@1952: iLastPg = sqlite3PagerPagecount(pBt->pPager); ds@1952: } ds@1952: ds@1952: if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){ ds@1952: int rc; ds@1952: u8 eType; ds@1952: Pgno iPtrPage; ds@1952: ds@1952: nFreeList = get4byte(&pBt->pPage1->aData[36]); ds@1952: if( nFreeList==0 || nFin==iLastPg ){ ds@1952: return SQLITE_DONE; ds@1952: } ds@1952: ds@1952: rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: if( eType==PTRMAP_ROOTPAGE ){ ds@1952: return SQLITE_CORRUPT_BKPT; ds@1952: } ds@1952: ds@1952: if( eType==PTRMAP_FREEPAGE ){ ds@1952: if( nFin==0 ){ ds@1952: /* Remove the page from the files free-list. This is not required ds@1952: ** if nFin is non-zero. In that case, the free-list will be ds@1952: ** truncated to zero after this function returns, so it doesn't ds@1952: ** matter if it still contains some garbage entries. ds@1952: */ ds@1952: Pgno iFreePg; ds@1952: MemPage *pFreePg; ds@1952: rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: assert( iFreePg==iLastPg ); ds@1952: releasePage(pFreePg); ds@1952: } ds@1952: } else { ds@1952: Pgno iFreePg; /* Index of free page to move pLastPg to */ ds@1952: MemPage *pLastPg; ds@1952: ds@1952: rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* If nFin is zero, this loop runs exactly once and page pLastPg ds@1952: ** is swapped with the first free page pulled off the free list. ds@1952: ** ds@1952: ** On the other hand, if nFin is greater than zero, then keep ds@1952: ** looping until a free-page located within the first nFin pages ds@1952: ** of the file is found. ds@1952: */ ds@1952: do { ds@1952: MemPage *pFreePg; ds@1952: rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: releasePage(pLastPg); ds@1952: return rc; ds@1952: } ds@1952: releasePage(pFreePg); ds@1952: }while( nFin!=0 && iFreePg>nFin ); ds@1952: assert( iFreePgpDbPage); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg); ds@1952: releasePage(pLastPg); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: } ds@1952: } ds@1952: ds@1952: pBt->nTrunc = iLastPg - 1; ds@1952: while( pBt->nTrunc==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, pBt->nTrunc) ){ ds@1952: pBt->nTrunc--; ds@1952: } ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** A write-transaction must be opened before calling this function. ds@1952: ** It performs a single unit of work towards an incremental vacuum. ds@1952: ** ds@1952: ** If the incremental vacuum is finished after this function has run, ds@1952: ** SQLITE_DONE is returned. If it is not finished, but no error occured, ds@1952: ** SQLITE_OK is returned. Otherwise an SQLite error code. ds@1952: */ ds@1952: int sqlite3BtreeIncrVacuum(Btree *p){ ds@1952: int rc; ds@1952: BtShared *pBt = p->pBt; ds@1952: ds@1952: sqlite3BtreeEnter(p); ds@1952: assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE ); ds@1952: if( !pBt->autoVacuum ){ ds@1952: rc = SQLITE_DONE; ds@1952: }else{ ds@1952: invalidateAllOverflowCache(pBt); ds@1952: rc = incrVacuumStep(pBt, 0); ds@1952: } ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine is called prior to sqlite3PagerCommit when a transaction ds@1952: ** is commited for an auto-vacuum database. ds@1952: ** ds@1952: ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages ds@1952: ** the database file should be truncated to during the commit process. ds@1952: ** i.e. the database has been reorganized so that only the first *pnTrunc ds@1952: ** pages are in use. ds@1952: */ ds@1952: static int autoVacuumCommit(BtShared *pBt, Pgno *pnTrunc){ ds@1952: int rc = SQLITE_OK; ds@1952: Pager *pPager = pBt->pPager; ds@1952: #ifndef NDEBUG ds@1952: int nRef = sqlite3PagerRefcount(pPager); ds@1952: #endif ds@1952: ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: invalidateAllOverflowCache(pBt); ds@1952: assert(pBt->autoVacuum); ds@1952: if( !pBt->incrVacuum ){ ds@1952: Pgno nFin = 0; ds@1952: ds@1952: if( pBt->nTrunc==0 ){ ds@1952: Pgno nFree; ds@1952: Pgno nPtrmap; ds@1952: const int pgsz = pBt->pageSize; ds@1952: Pgno nOrig = sqlite3PagerPagecount(pBt->pPager); ds@1952: ds@1952: if( PTRMAP_ISPAGE(pBt, nOrig) ){ ds@1952: return SQLITE_CORRUPT_BKPT; ds@1952: } ds@1952: if( nOrig==PENDING_BYTE_PAGE(pBt) ){ ds@1952: nOrig--; ds@1952: } ds@1952: nFree = get4byte(&pBt->pPage1->aData[36]); ds@1952: nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5); ds@1952: nFin = nOrig - nFree - nPtrmap; ds@1952: if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){ ds@1952: nFin--; ds@1952: } ds@1952: while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){ ds@1952: nFin--; ds@1952: } ds@1952: } ds@1952: ds@1952: while( rc==SQLITE_OK ){ ds@1952: rc = incrVacuumStep(pBt, nFin); ds@1952: } ds@1952: if( rc==SQLITE_DONE ){ ds@1952: assert(nFin==0 || pBt->nTrunc==0 || nFin<=pBt->nTrunc); ds@1952: rc = SQLITE_OK; ds@1952: if( pBt->nTrunc ){ ds@1952: rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); ds@1952: put4byte(&pBt->pPage1->aData[32], 0); ds@1952: put4byte(&pBt->pPage1->aData[36], 0); ds@1952: pBt->nTrunc = nFin; ds@1952: } ds@1952: } ds@1952: if( rc!=SQLITE_OK ){ ds@1952: sqlite3PagerRollback(pPager); ds@1952: } ds@1952: } ds@1952: ds@1952: if( rc==SQLITE_OK ){ ds@1952: *pnTrunc = pBt->nTrunc; ds@1952: pBt->nTrunc = 0; ds@1952: } ds@1952: assert( nRef==sqlite3PagerRefcount(pPager) ); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: #endif ds@1952: ds@1952: /* ds@1952: ** This routine does the first phase of a two-phase commit. This routine ds@1952: ** causes a rollback journal to be created (if it does not already exist) ds@1952: ** and populated with enough information so that if a power loss occurs ds@1952: ** the database can be restored to its original state by playing back ds@1952: ** the journal. Then the contents of the journal are flushed out to ds@1952: ** the disk. After the journal is safely on oxide, the changes to the ds@1952: ** database are written into the database file and flushed to oxide. ds@1952: ** At the end of this call, the rollback journal still exists on the ds@1952: ** disk and we are still holding all locks, so the transaction has not ds@1952: ** committed. See sqlite3BtreeCommit() for the second phase of the ds@1952: ** commit process. ds@1952: ** ds@1952: ** This call is a no-op if no write-transaction is currently active on pBt. ds@1952: ** ds@1952: ** Otherwise, sync the database file for the btree pBt. zMaster points to ds@1952: ** the name of a master journal file that should be written into the ds@1952: ** individual journal file, or is NULL, indicating no master journal file ds@1952: ** (single database transaction). ds@1952: ** ds@1952: ** When this is called, the master journal should already have been ds@1952: ** created, populated with this journal pointer and synced to disk. ds@1952: ** ds@1952: ** Once this is routine has returned, the only thing required to commit ds@1952: ** the write-transaction for this database file is to delete the journal. ds@1952: */ ds@1952: int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){ ds@1952: int rc = SQLITE_OK; ds@1952: if( p->inTrans==TRANS_WRITE ){ ds@1952: BtShared *pBt = p->pBt; ds@1952: Pgno nTrunc = 0; ds@1952: sqlite3BtreeEnter(p); ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: if( pBt->autoVacuum ){ ds@1952: rc = autoVacuumCommit(pBt, &nTrunc); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: } ds@1952: #endif ds@1952: rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, nTrunc); ds@1952: sqlite3BtreeLeave(p); ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Commit the transaction currently in progress. ds@1952: ** ds@1952: ** This routine implements the second phase of a 2-phase commit. The ds@1952: ** sqlite3BtreeSync() routine does the first phase and should be invoked ds@1952: ** prior to calling this routine. The sqlite3BtreeSync() routine did ds@1952: ** all the work of writing information out to disk and flushing the ds@1952: ** contents so that they are written onto the disk platter. All this ds@1952: ** routine has to do is delete or truncate the rollback journal ds@1952: ** (which causes the transaction to commit) and drop locks. ds@1952: ** ds@1952: ** This will release the write lock on the database file. If there ds@1952: ** are no active cursors, it also releases the read lock. ds@1952: */ ds@1952: int sqlite3BtreeCommitPhaseTwo(Btree *p){ ds@1952: BtShared *pBt = p->pBt; ds@1952: ds@1952: sqlite3BtreeEnter(p); ds@1952: btreeIntegrity(p); ds@1952: ds@1952: /* If the handle has a write-transaction open, commit the shared-btrees ds@1952: ** transaction and set the shared state to TRANS_READ. ds@1952: */ ds@1952: if( p->inTrans==TRANS_WRITE ){ ds@1952: int rc; ds@1952: assert( pBt->inTransaction==TRANS_WRITE ); ds@1952: assert( pBt->nTransaction>0 ); ds@1952: rc = sqlite3PagerCommitPhaseTwo(pBt->pPager); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: pBt->inTransaction = TRANS_READ; ds@1952: pBt->inStmt = 0; ds@1952: } ds@1952: unlockAllTables(p); ds@1952: ds@1952: /* If the handle has any kind of transaction open, decrement the transaction ds@1952: ** count of the shared btree. If the transaction count reaches 0, set ds@1952: ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below ds@1952: ** will unlock the pager. ds@1952: */ ds@1952: if( p->inTrans!=TRANS_NONE ){ ds@1952: pBt->nTransaction--; ds@1952: if( 0==pBt->nTransaction ){ ds@1952: pBt->inTransaction = TRANS_NONE; ds@1952: } ds@1952: } ds@1952: ds@1952: /* Set the handles current transaction state to TRANS_NONE and unlock ds@1952: ** the pager if this call closed the only read or write transaction. ds@1952: */ ds@1952: p->inTrans = TRANS_NONE; ds@1952: unlockBtreeIfUnused(pBt); ds@1952: ds@1952: btreeIntegrity(p); ds@1952: sqlite3BtreeLeave(p); ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Do both phases of a commit. ds@1952: */ ds@1952: int sqlite3BtreeCommit(Btree *p){ ds@1952: int rc; ds@1952: sqlite3BtreeEnter(p); ds@1952: rc = sqlite3BtreeCommitPhaseOne(p, 0); ds@1952: if( rc==SQLITE_OK ){ ds@1952: rc = sqlite3BtreeCommitPhaseTwo(p); ds@1952: } ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: #ifndef NDEBUG ds@1952: /* ds@1952: ** Return the number of write-cursors open on this handle. This is for use ds@1952: ** in assert() expressions, so it is only compiled if NDEBUG is not ds@1952: ** defined. ds@1952: ** ds@1952: ** For the purposes of this routine, a write-cursor is any cursor that ds@1952: ** is capable of writing to the databse. That means the cursor was ds@1952: ** originally opened for writing and the cursor has not be disabled ds@1952: ** by having its state changed to CURSOR_FAULT. ds@1952: */ ds@1952: static int countWriteCursors(BtShared *pBt){ ds@1952: BtCursor *pCur; ds@1952: int r = 0; ds@1952: for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){ ds@1952: if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; ds@1952: } ds@1952: return r; ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* ds@1952: ** This routine sets the state to CURSOR_FAULT and the error ds@1952: ** code to errCode for every cursor on BtShared that pBtree ds@1952: ** references. ds@1952: ** ds@1952: ** Every cursor is tripped, including cursors that belong ds@1952: ** to other database connections that happen to be sharing ds@1952: ** the cache with pBtree. ds@1952: ** ds@1952: ** This routine gets called when a rollback occurs. ds@1952: ** All cursors using the same cache must be tripped ds@1952: ** to prevent them from trying to use the btree after ds@1952: ** the rollback. The rollback may have deleted tables ds@1952: ** or moved root pages, so it is not sufficient to ds@1952: ** save the state of the cursor. The cursor must be ds@1952: ** invalidated. ds@1952: */ ds@1952: void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){ ds@1952: BtCursor *p; ds@1952: sqlite3BtreeEnter(pBtree); ds@1952: for(p=pBtree->pBt->pCursor; p; p=p->pNext){ ds@1952: clearCursorPosition(p); ds@1952: p->eState = CURSOR_FAULT; ds@1952: p->skip = errCode; ds@1952: } ds@1952: sqlite3BtreeLeave(pBtree); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Rollback the transaction in progress. All cursors will be ds@1952: ** invalided by this operation. Any attempt to use a cursor ds@1952: ** that was open at the beginning of this operation will result ds@1952: ** in an error. ds@1952: ** ds@1952: ** This will release the write lock on the database file. If there ds@1952: ** are no active cursors, it also releases the read lock. ds@1952: */ ds@1952: int sqlite3BtreeRollback(Btree *p){ ds@1952: int rc; ds@1952: BtShared *pBt = p->pBt; ds@1952: MemPage *pPage1; ds@1952: ds@1952: sqlite3BtreeEnter(p); ds@1952: rc = saveAllCursors(pBt, 0, 0); ds@1952: #ifndef SQLITE_OMIT_SHARED_CACHE ds@1952: if( rc!=SQLITE_OK ){ ds@1952: /* This is a horrible situation. An IO or malloc() error occured whilst ds@1952: ** trying to save cursor positions. If this is an automatic rollback (as ds@1952: ** the result of a constraint, malloc() failure or IO error) then ds@1952: ** the cache may be internally inconsistent (not contain valid trees) so ds@1952: ** we cannot simply return the error to the caller. Instead, abort ds@1952: ** all queries that may be using any of the cursors that failed to save. ds@1952: */ ds@1952: sqlite3BtreeTripAllCursors(p, rc); ds@1952: } ds@1952: #endif ds@1952: btreeIntegrity(p); ds@1952: unlockAllTables(p); ds@1952: ds@1952: if( p->inTrans==TRANS_WRITE ){ ds@1952: int rc2; ds@1952: ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: pBt->nTrunc = 0; ds@1952: #endif ds@1952: ds@1952: assert( TRANS_WRITE==pBt->inTransaction ); ds@1952: rc2 = sqlite3PagerRollback(pBt->pPager); ds@1952: if( rc2!=SQLITE_OK ){ ds@1952: rc = rc2; ds@1952: } ds@1952: ds@1952: /* The rollback may have destroyed the pPage1->aData value. So ds@1952: ** call sqlite3BtreeGetPage() on page 1 again to make ds@1952: ** sure pPage1->aData is set correctly. */ ds@1952: if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){ ds@1952: releasePage(pPage1); ds@1952: } ds@1952: assert( countWriteCursors(pBt)==0 ); ds@1952: pBt->inTransaction = TRANS_READ; ds@1952: } ds@1952: ds@1952: if( p->inTrans!=TRANS_NONE ){ ds@1952: assert( pBt->nTransaction>0 ); ds@1952: pBt->nTransaction--; ds@1952: if( 0==pBt->nTransaction ){ ds@1952: pBt->inTransaction = TRANS_NONE; ds@1952: } ds@1952: } ds@1952: ds@1952: p->inTrans = TRANS_NONE; ds@1952: pBt->inStmt = 0; ds@1952: unlockBtreeIfUnused(pBt); ds@1952: ds@1952: btreeIntegrity(p); ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Start a statement subtransaction. The subtransaction can ds@1952: ** can be rolled back independently of the main transaction. ds@1952: ** You must start a transaction before starting a subtransaction. ds@1952: ** The subtransaction is ended automatically if the main transaction ds@1952: ** commits or rolls back. ds@1952: ** ds@1952: ** Only one subtransaction may be active at a time. It is an error to try ds@1952: ** to start a new subtransaction if another subtransaction is already active. ds@1952: ** ds@1952: ** Statement subtransactions are used around individual SQL statements ds@1952: ** that are contained within a BEGIN...COMMIT block. If a constraint ds@1952: ** error occurs within the statement, the effect of that one statement ds@1952: ** can be rolled back without having to rollback the entire transaction. ds@1952: */ ds@1952: int sqlite3BtreeBeginStmt(Btree *p){ ds@1952: int rc; ds@1952: BtShared *pBt = p->pBt; ds@1952: sqlite3BtreeEnter(p); ds@1952: if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){ ds@1952: rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR; ds@1952: }else{ ds@1952: assert( pBt->inTransaction==TRANS_WRITE ); ds@1952: rc = pBt->readOnly ? SQLITE_OK : sqlite3PagerStmtBegin(pBt->pPager); ds@1952: pBt->inStmt = 1; ds@1952: } ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** Commit the statment subtransaction currently in progress. If no ds@1952: ** subtransaction is active, this is a no-op. ds@1952: */ ds@1952: int sqlite3BtreeCommitStmt(Btree *p){ ds@1952: int rc; ds@1952: BtShared *pBt = p->pBt; ds@1952: sqlite3BtreeEnter(p); ds@1952: if( pBt->inStmt && !pBt->readOnly ){ ds@1952: rc = sqlite3PagerStmtCommit(pBt->pPager); ds@1952: }else{ ds@1952: rc = SQLITE_OK; ds@1952: } ds@1952: pBt->inStmt = 0; ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Rollback the active statement subtransaction. If no subtransaction ds@1952: ** is active this routine is a no-op. ds@1952: ** ds@1952: ** All cursors will be invalidated by this operation. Any attempt ds@1952: ** to use a cursor that was open at the beginning of this operation ds@1952: ** will result in an error. ds@1952: */ ds@1952: int sqlite3BtreeRollbackStmt(Btree *p){ ds@1952: int rc = SQLITE_OK; ds@1952: BtShared *pBt = p->pBt; ds@1952: sqlite3BtreeEnter(p); ds@1952: if( pBt->inStmt && !pBt->readOnly ){ ds@1952: rc = sqlite3PagerStmtRollback(pBt->pPager); ds@1952: assert( countWriteCursors(pBt)==0 ); ds@1952: pBt->inStmt = 0; ds@1952: } ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Default key comparison function to be used if no comparison function ds@1952: ** is specified on the sqlite3BtreeCursor() call. ds@1952: */ ds@1952: static int dfltCompare( ds@1952: void *NotUsed, /* User data is not used */ ds@1952: int n1, const void *p1, /* First key to compare */ ds@1952: int n2, const void *p2 /* Second key to compare */ ds@1952: ){ ds@1952: int c; ds@1952: c = memcmp(p1, p2, n1pBt; ds@1952: ds@1952: assert( sqlite3BtreeHoldsMutex(p) ); ds@1952: *ppCur = 0; ds@1952: if( wrFlag ){ ds@1952: if( pBt->readOnly ){ ds@1952: return SQLITE_READONLY; ds@1952: } ds@1952: if( checkReadLocks(p, iTable, 0) ){ ds@1952: return SQLITE_LOCKED; ds@1952: } ds@1952: } ds@1952: ds@1952: if( pBt->pPage1==0 ){ ds@1952: rc = lockBtreeWithRetry(p); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: if( pBt->readOnly && wrFlag ){ ds@1952: return SQLITE_READONLY; ds@1952: } ds@1952: } ds@1952: pCur = sqlite3MallocZero( sizeof(*pCur) ); ds@1952: if( pCur==0 ){ ds@1952: rc = SQLITE_NOMEM; ds@1952: goto create_cursor_exception; ds@1952: } ds@1952: pCur->pgnoRoot = (Pgno)iTable; ds@1952: if( iTable==1 && sqlite3PagerPagecount(pBt->pPager)==0 ){ ds@1952: rc = SQLITE_EMPTY; ds@1952: goto create_cursor_exception; ds@1952: } ds@1952: rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: goto create_cursor_exception; ds@1952: } ds@1952: ds@1952: /* Now that no other errors can occur, finish filling in the BtCursor ds@1952: ** variables, link the cursor into the BtShared list and set *ppCur (the ds@1952: ** output argument to this function). ds@1952: */ ds@1952: pCur->xCompare = xCmp ? xCmp : dfltCompare; ds@1952: pCur->pArg = pArg; ds@1952: pCur->pBtree = p; ds@1952: pCur->pBt = pBt; ds@1952: pCur->wrFlag = wrFlag; ds@1952: pCur->pNext = pBt->pCursor; ds@1952: if( pCur->pNext ){ ds@1952: pCur->pNext->pPrev = pCur; ds@1952: } ds@1952: pBt->pCursor = pCur; ds@1952: pCur->eState = CURSOR_INVALID; ds@1952: *ppCur = pCur; ds@1952: ds@1952: return SQLITE_OK; ds@1952: ds@1952: create_cursor_exception: ds@1952: if( pCur ){ ds@1952: releasePage(pCur->pPage); ds@1952: sqlite3_free(pCur); ds@1952: } ds@1952: unlockBtreeIfUnused(pBt); ds@1952: return rc; ds@1952: } ds@1952: int sqlite3BtreeCursor( ds@1952: Btree *p, /* The btree */ ds@1952: int iTable, /* Root page of table to open */ ds@1952: int wrFlag, /* 1 to write. 0 read-only */ ds@1952: int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */ ds@1952: void *pArg, /* First arg to xCompare() */ ds@1952: BtCursor **ppCur /* Write new cursor here */ ds@1952: ){ ds@1952: int rc; ds@1952: sqlite3BtreeEnter(p); ds@1952: rc = btreeCursor(p, iTable, wrFlag, xCmp, pArg, ppCur); ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** Close a cursor. The read lock on the database file is released ds@1952: ** when the last cursor is closed. ds@1952: */ ds@1952: int sqlite3BtreeCloseCursor(BtCursor *pCur){ ds@1952: BtShared *pBt = pCur->pBt; ds@1952: Btree *pBtree = pCur->pBtree; ds@1952: ds@1952: sqlite3BtreeEnter(pBtree); ds@1952: clearCursorPosition(pCur); ds@1952: if( pCur->pPrev ){ ds@1952: pCur->pPrev->pNext = pCur->pNext; ds@1952: }else{ ds@1952: pBt->pCursor = pCur->pNext; ds@1952: } ds@1952: if( pCur->pNext ){ ds@1952: pCur->pNext->pPrev = pCur->pPrev; ds@1952: } ds@1952: releasePage(pCur->pPage); ds@1952: unlockBtreeIfUnused(pBt); ds@1952: invalidateOverflowCache(pCur); ds@1952: sqlite3_free(pCur); ds@1952: sqlite3BtreeLeave(pBtree); ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Make a temporary cursor by filling in the fields of pTempCur. ds@1952: ** The temporary cursor is not on the cursor list for the Btree. ds@1952: */ ds@1952: void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){ ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: memcpy(pTempCur, pCur, sizeof(*pCur)); ds@1952: pTempCur->pNext = 0; ds@1952: pTempCur->pPrev = 0; ds@1952: if( pTempCur->pPage ){ ds@1952: sqlite3PagerRef(pTempCur->pPage->pDbPage); ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Delete a temporary cursor such as was made by the CreateTemporaryCursor() ds@1952: ** function above. ds@1952: */ ds@1952: void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){ ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: if( pCur->pPage ){ ds@1952: sqlite3PagerUnref(pCur->pPage->pDbPage); ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Make sure the BtCursor* given in the argument has a valid ds@1952: ** BtCursor.info structure. If it is not already valid, call ds@1952: ** sqlite3BtreeParseCell() to fill it in. ds@1952: ** ds@1952: ** BtCursor.info is a cache of the information in the current cell. ds@1952: ** Using this cache reduces the number of calls to sqlite3BtreeParseCell(). ds@1952: ** ds@1952: ** 2007-06-25: There is a bug in some versions of MSVC that cause the ds@1952: ** compiler to crash when getCellInfo() is implemented as a macro. ds@1952: ** But there is a measureable speed advantage to using the macro on gcc ds@1952: ** (when less compiler optimizations like -Os or -O0 are used and the ds@1952: ** compiler is not doing agressive inlining.) So we use a real function ds@1952: ** for MSVC and a macro for everything else. Ticket #2457. ds@1952: */ ds@1952: #ifndef NDEBUG ds@1952: static void assertCellInfo(BtCursor *pCur){ ds@1952: CellInfo info; ds@1952: memset(&info, 0, sizeof(info)); ds@1952: sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &info); ds@1952: assert( memcmp(&info, &pCur->info, sizeof(info))==0 ); ds@1952: } ds@1952: #else ds@1952: #define assertCellInfo(x) ds@1952: #endif ds@1952: #ifdef _MSC_VER ds@1952: /* Use a real function in MSVC to work around bugs in that compiler. */ ds@1952: static void getCellInfo(BtCursor *pCur){ ds@1952: if( pCur->info.nSize==0 ){ ds@1952: sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info); ds@1952: }else{ ds@1952: assertCellInfo(pCur); ds@1952: } ds@1952: } ds@1952: #else /* if not _MSC_VER */ ds@1952: /* Use a macro in all other compilers so that the function is inlined */ ds@1952: #define getCellInfo(pCur) \ ds@1952: if( pCur->info.nSize==0 ){ \ ds@1952: sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info); \ ds@1952: }else{ \ ds@1952: assertCellInfo(pCur); \ ds@1952: } ds@1952: #endif /* _MSC_VER */ ds@1952: ds@1952: /* ds@1952: ** Set *pSize to the size of the buffer needed to hold the value of ds@1952: ** the key for the current entry. If the cursor is not pointing ds@1952: ** to a valid entry, *pSize is set to 0. ds@1952: ** ds@1952: ** For a table with the INTKEY flag set, this routine returns the key ds@1952: ** itself, not the number of bytes in the key. ds@1952: */ ds@1952: int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){ ds@1952: int rc; ds@1952: ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: rc = restoreOrClearCursorPosition(pCur); ds@1952: if( rc==SQLITE_OK ){ ds@1952: assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID ); ds@1952: if( pCur->eState==CURSOR_INVALID ){ ds@1952: *pSize = 0; ds@1952: }else{ ds@1952: getCellInfo(pCur); ds@1952: *pSize = pCur->info.nKey; ds@1952: } ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Set *pSize to the number of bytes of data in the entry the ds@1952: ** cursor currently points to. Always return SQLITE_OK. ds@1952: ** Failure is not possible. If the cursor is not currently ds@1952: ** pointing to an entry (which can happen, for example, if ds@1952: ** the database is empty) then *pSize is set to 0. ds@1952: */ ds@1952: int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){ ds@1952: int rc; ds@1952: ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: rc = restoreOrClearCursorPosition(pCur); ds@1952: if( rc==SQLITE_OK ){ ds@1952: assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID ); ds@1952: if( pCur->eState==CURSOR_INVALID ){ ds@1952: /* Not pointing at a valid entry - set *pSize to 0. */ ds@1952: *pSize = 0; ds@1952: }else{ ds@1952: getCellInfo(pCur); ds@1952: *pSize = pCur->info.nData; ds@1952: } ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Given the page number of an overflow page in the database (parameter ds@1952: ** ovfl), this function finds the page number of the next page in the ds@1952: ** linked list of overflow pages. If possible, it uses the auto-vacuum ds@1952: ** pointer-map data instead of reading the content of page ovfl to do so. ds@1952: ** ds@1952: ** If an error occurs an SQLite error code is returned. Otherwise: ds@1952: ** ds@1952: ** Unless pPgnoNext is NULL, the page number of the next overflow ds@1952: ** page in the linked list is written to *pPgnoNext. If page ovfl ds@1952: ** is the last page in it's linked list, *pPgnoNext is set to zero. ds@1952: ** ds@1952: ** If ppPage is not NULL, *ppPage is set to the MemPage* handle ds@1952: ** for page ovfl. The underlying pager page may have been requested ds@1952: ** with the noContent flag set, so the page data accessable via ds@1952: ** this handle may not be trusted. ds@1952: */ ds@1952: static int getOverflowPage( ds@1952: BtShared *pBt, ds@1952: Pgno ovfl, /* Overflow page */ ds@1952: MemPage **ppPage, /* OUT: MemPage handle */ ds@1952: Pgno *pPgnoNext /* OUT: Next overflow page number */ ds@1952: ){ ds@1952: Pgno next = 0; ds@1952: int rc; ds@1952: ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: /* One of these must not be NULL. Otherwise, why call this function? */ ds@1952: assert(ppPage || pPgnoNext); ds@1952: ds@1952: /* If pPgnoNext is NULL, then this function is being called to obtain ds@1952: ** a MemPage* reference only. No page-data is required in this case. ds@1952: */ ds@1952: if( !pPgnoNext ){ ds@1952: return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1); ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: /* Try to find the next page in the overflow list using the ds@1952: ** autovacuum pointer-map pages. Guess that the next page in ds@1952: ** the overflow list is page number (ovfl+1). If that guess turns ds@1952: ** out to be wrong, fall back to loading the data of page ds@1952: ** number ovfl to determine the next page number. ds@1952: */ ds@1952: if( pBt->autoVacuum ){ ds@1952: Pgno pgno; ds@1952: Pgno iGuess = ovfl+1; ds@1952: u8 eType; ds@1952: ds@1952: while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){ ds@1952: iGuess++; ds@1952: } ds@1952: ds@1952: if( iGuess<=sqlite3PagerPagecount(pBt->pPager) ){ ds@1952: rc = ptrmapGet(pBt, iGuess, &eType, &pgno); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){ ds@1952: next = iGuess; ds@1952: } ds@1952: } ds@1952: } ds@1952: #endif ds@1952: ds@1952: if( next==0 || ppPage ){ ds@1952: MemPage *pPage = 0; ds@1952: ds@1952: rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0); ds@1952: assert(rc==SQLITE_OK || pPage==0); ds@1952: if( next==0 && rc==SQLITE_OK ){ ds@1952: next = get4byte(pPage->aData); ds@1952: } ds@1952: ds@1952: if( ppPage ){ ds@1952: *ppPage = pPage; ds@1952: }else{ ds@1952: releasePage(pPage); ds@1952: } ds@1952: } ds@1952: *pPgnoNext = next; ds@1952: ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Copy data from a buffer to a page, or from a page to a buffer. ds@1952: ** ds@1952: ** pPayload is a pointer to data stored on database page pDbPage. ds@1952: ** If argument eOp is false, then nByte bytes of data are copied ds@1952: ** from pPayload to the buffer pointed at by pBuf. If eOp is true, ds@1952: ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes ds@1952: ** of data are copied from the buffer pBuf to pPayload. ds@1952: ** ds@1952: ** SQLITE_OK is returned on success, otherwise an error code. ds@1952: */ ds@1952: static int copyPayload( ds@1952: void *pPayload, /* Pointer to page data */ ds@1952: void *pBuf, /* Pointer to buffer */ ds@1952: int nByte, /* Number of bytes to copy */ ds@1952: int eOp, /* 0 -> copy from page, 1 -> copy to page */ ds@1952: DbPage *pDbPage /* Page containing pPayload */ ds@1952: ){ ds@1952: if( eOp ){ ds@1952: /* Copy data from buffer to page (a write operation) */ ds@1952: int rc = sqlite3PagerWrite(pDbPage); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: memcpy(pPayload, pBuf, nByte); ds@1952: }else{ ds@1952: /* Copy data from page to buffer (a read operation) */ ds@1952: memcpy(pBuf, pPayload, nByte); ds@1952: } ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This function is used to read or overwrite payload information ds@1952: ** for the entry that the pCur cursor is pointing to. If the eOp ds@1952: ** parameter is 0, this is a read operation (data copied into ds@1952: ** buffer pBuf). If it is non-zero, a write (data copied from ds@1952: ** buffer pBuf). ds@1952: ** ds@1952: ** A total of "amt" bytes are read or written beginning at "offset". ds@1952: ** Data is read to or from the buffer pBuf. ds@1952: ** ds@1952: ** This routine does not make a distinction between key and data. ds@1952: ** It just reads or writes bytes from the payload area. Data might ds@1952: ** appear on the main page or be scattered out on multiple overflow ds@1952: ** pages. ds@1952: ** ds@1952: ** If the BtCursor.isIncrblobHandle flag is set, and the current ds@1952: ** cursor entry uses one or more overflow pages, this function ds@1952: ** allocates space for and lazily popluates the overflow page-list ds@1952: ** cache array (BtCursor.aOverflow). Subsequent calls use this ds@1952: ** cache to make seeking to the supplied offset more efficient. ds@1952: ** ds@1952: ** Once an overflow page-list cache has been allocated, it may be ds@1952: ** invalidated if some other cursor writes to the same table, or if ds@1952: ** the cursor is moved to a different row. Additionally, in auto-vacuum ds@1952: ** mode, the following events may invalidate an overflow page-list cache. ds@1952: ** ds@1952: ** * An incremental vacuum, ds@1952: ** * A commit in auto_vacuum="full" mode, ds@1952: ** * Creating a table (may require moving an overflow page). ds@1952: */ ds@1952: static int accessPayload( ds@1952: BtCursor *pCur, /* Cursor pointing to entry to read from */ ds@1952: int offset, /* Begin reading this far into payload */ ds@1952: int amt, /* Read this many bytes */ ds@1952: unsigned char *pBuf, /* Write the bytes into this buffer */ ds@1952: int skipKey, /* offset begins at data if this is true */ ds@1952: int eOp /* zero to read. non-zero to write. */ ds@1952: ){ ds@1952: unsigned char *aPayload; ds@1952: int rc = SQLITE_OK; ds@1952: u32 nKey; ds@1952: int iIdx = 0; ds@1952: MemPage *pPage = pCur->pPage; /* Btree page of current cursor entry */ ds@1952: BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */ ds@1952: ds@1952: assert( pPage ); ds@1952: assert( pCur->eState==CURSOR_VALID ); ds@1952: assert( pCur->idx>=0 && pCur->idxnCell ); ds@1952: assert( offset>=0 ); ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: ds@1952: getCellInfo(pCur); ds@1952: aPayload = pCur->info.pCell + pCur->info.nHeader; ds@1952: nKey = (pPage->intKey ? 0 : pCur->info.nKey); ds@1952: ds@1952: if( skipKey ){ ds@1952: offset += nKey; ds@1952: } ds@1952: if( offset+amt > nKey+pCur->info.nData ){ ds@1952: /* Trying to read or write past the end of the data is an error */ ds@1952: return SQLITE_ERROR; ds@1952: } ds@1952: ds@1952: /* Check if data must be read/written to/from the btree page itself. */ ds@1952: if( offsetinfo.nLocal ){ ds@1952: int a = amt; ds@1952: if( a+offset>pCur->info.nLocal ){ ds@1952: a = pCur->info.nLocal - offset; ds@1952: } ds@1952: rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage); ds@1952: offset = 0; ds@1952: pBuf += a; ds@1952: amt -= a; ds@1952: }else{ ds@1952: offset -= pCur->info.nLocal; ds@1952: } ds@1952: ds@1952: if( rc==SQLITE_OK && amt>0 ){ ds@1952: const int ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */ ds@1952: Pgno nextPage; ds@1952: ds@1952: nextPage = get4byte(&aPayload[pCur->info.nLocal]); ds@1952: ds@1952: #ifndef SQLITE_OMIT_INCRBLOB ds@1952: /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[] ds@1952: ** has not been allocated, allocate it now. The array is sized at ds@1952: ** one entry for each overflow page in the overflow chain. The ds@1952: ** page number of the first overflow page is stored in aOverflow[0], ds@1952: ** etc. A value of 0 in the aOverflow[] array means "not yet known" ds@1952: ** (the cache is lazily populated). ds@1952: */ ds@1952: if( pCur->isIncrblobHandle && !pCur->aOverflow ){ ds@1952: int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize; ds@1952: pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl); ds@1952: if( nOvfl && !pCur->aOverflow ){ ds@1952: rc = SQLITE_NOMEM; ds@1952: } ds@1952: } ds@1952: ds@1952: /* If the overflow page-list cache has been allocated and the ds@1952: ** entry for the first required overflow page is valid, skip ds@1952: ** directly to it. ds@1952: */ ds@1952: if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){ ds@1952: iIdx = (offset/ovflSize); ds@1952: nextPage = pCur->aOverflow[iIdx]; ds@1952: offset = (offset%ovflSize); ds@1952: } ds@1952: #endif ds@1952: ds@1952: for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){ ds@1952: ds@1952: #ifndef SQLITE_OMIT_INCRBLOB ds@1952: /* If required, populate the overflow page-list cache. */ ds@1952: if( pCur->aOverflow ){ ds@1952: assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage); ds@1952: pCur->aOverflow[iIdx] = nextPage; ds@1952: } ds@1952: #endif ds@1952: ds@1952: if( offset>=ovflSize ){ ds@1952: /* The only reason to read this page is to obtain the page ds@1952: ** number for the next page in the overflow chain. The page ds@1952: ** data is not required. So first try to lookup the overflow ds@1952: ** page-list cache, if any, then fall back to the getOverflowPage() ds@1952: ** function. ds@1952: */ ds@1952: #ifndef SQLITE_OMIT_INCRBLOB ds@1952: if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){ ds@1952: nextPage = pCur->aOverflow[iIdx+1]; ds@1952: } else ds@1952: #endif ds@1952: rc = getOverflowPage(pBt, nextPage, 0, &nextPage); ds@1952: offset -= ovflSize; ds@1952: }else{ ds@1952: /* Need to read this page properly. It contains some of the ds@1952: ** range of data that is being read (eOp==0) or written (eOp!=0). ds@1952: */ ds@1952: DbPage *pDbPage; ds@1952: int a = amt; ds@1952: rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage); ds@1952: if( rc==SQLITE_OK ){ ds@1952: aPayload = sqlite3PagerGetData(pDbPage); ds@1952: nextPage = get4byte(aPayload); ds@1952: if( a + offset > ovflSize ){ ds@1952: a = ovflSize - offset; ds@1952: } ds@1952: rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage); ds@1952: sqlite3PagerUnref(pDbPage); ds@1952: offset = 0; ds@1952: amt -= a; ds@1952: pBuf += a; ds@1952: } ds@1952: } ds@1952: } ds@1952: } ds@1952: ds@1952: if( rc==SQLITE_OK && amt>0 ){ ds@1952: return SQLITE_CORRUPT_BKPT; ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Read part of the key associated with cursor pCur. Exactly ds@1952: ** "amt" bytes will be transfered into pBuf[]. The transfer ds@1952: ** begins at "offset". ds@1952: ** ds@1952: ** Return SQLITE_OK on success or an error code if anything goes ds@1952: ** wrong. An error is returned if "offset+amt" is larger than ds@1952: ** the available payload. ds@1952: */ ds@1952: int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ ds@1952: int rc; ds@1952: ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: rc = restoreOrClearCursorPosition(pCur); ds@1952: if( rc==SQLITE_OK ){ ds@1952: assert( pCur->eState==CURSOR_VALID ); ds@1952: assert( pCur->pPage!=0 ); ds@1952: if( pCur->pPage->intKey ){ ds@1952: return SQLITE_CORRUPT_BKPT; ds@1952: } ds@1952: assert( pCur->pPage->intKey==0 ); ds@1952: assert( pCur->idx>=0 && pCur->idxpPage->nCell ); ds@1952: rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0); ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Read part of the data associated with cursor pCur. Exactly ds@1952: ** "amt" bytes will be transfered into pBuf[]. The transfer ds@1952: ** begins at "offset". ds@1952: ** ds@1952: ** Return SQLITE_OK on success or an error code if anything goes ds@1952: ** wrong. An error is returned if "offset+amt" is larger than ds@1952: ** the available payload. ds@1952: */ ds@1952: int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){ ds@1952: int rc; ds@1952: ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: rc = restoreOrClearCursorPosition(pCur); ds@1952: if( rc==SQLITE_OK ){ ds@1952: assert( pCur->eState==CURSOR_VALID ); ds@1952: assert( pCur->pPage!=0 ); ds@1952: assert( pCur->idx>=0 && pCur->idxpPage->nCell ); ds@1952: rc = accessPayload(pCur, offset, amt, pBuf, 1, 0); ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Return a pointer to payload information from the entry that the ds@1952: ** pCur cursor is pointing to. The pointer is to the beginning of ds@1952: ** the key if skipKey==0 and it points to the beginning of data if ds@1952: ** skipKey==1. The number of bytes of available key/data is written ds@1952: ** into *pAmt. If *pAmt==0, then the value returned will not be ds@1952: ** a valid pointer. ds@1952: ** ds@1952: ** This routine is an optimization. It is common for the entire key ds@1952: ** and data to fit on the local page and for there to be no overflow ds@1952: ** pages. When that is so, this routine can be used to access the ds@1952: ** key and data without making a copy. If the key and/or data spills ds@1952: ** onto overflow pages, then accessPayload() must be used to reassembly ds@1952: ** the key/data and copy it into a preallocated buffer. ds@1952: ** ds@1952: ** The pointer returned by this routine looks directly into the cached ds@1952: ** page of the database. The data might change or move the next time ds@1952: ** any btree routine is called. ds@1952: */ ds@1952: static const unsigned char *fetchPayload( ds@1952: BtCursor *pCur, /* Cursor pointing to entry to read from */ ds@1952: int *pAmt, /* Write the number of available bytes here */ ds@1952: int skipKey /* read beginning at data if this is true */ ds@1952: ){ ds@1952: unsigned char *aPayload; ds@1952: MemPage *pPage; ds@1952: u32 nKey; ds@1952: int nLocal; ds@1952: ds@1952: assert( pCur!=0 && pCur->pPage!=0 ); ds@1952: assert( pCur->eState==CURSOR_VALID ); ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: pPage = pCur->pPage; ds@1952: assert( pCur->idx>=0 && pCur->idxnCell ); ds@1952: getCellInfo(pCur); ds@1952: aPayload = pCur->info.pCell; ds@1952: aPayload += pCur->info.nHeader; ds@1952: if( pPage->intKey ){ ds@1952: nKey = 0; ds@1952: }else{ ds@1952: nKey = pCur->info.nKey; ds@1952: } ds@1952: if( skipKey ){ ds@1952: aPayload += nKey; ds@1952: nLocal = pCur->info.nLocal - nKey; ds@1952: }else{ ds@1952: nLocal = pCur->info.nLocal; ds@1952: if( nLocal>nKey ){ ds@1952: nLocal = nKey; ds@1952: } ds@1952: } ds@1952: *pAmt = nLocal; ds@1952: return aPayload; ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** For the entry that cursor pCur is point to, return as ds@1952: ** many bytes of the key or data as are available on the local ds@1952: ** b-tree page. Write the number of available bytes into *pAmt. ds@1952: ** ds@1952: ** The pointer returned is ephemeral. The key/data may move ds@1952: ** or be destroyed on the next call to any Btree routine, ds@1952: ** including calls from other threads against the same cache. ds@1952: ** Hence, a mutex on the BtShared should be held prior to calling ds@1952: ** this routine. ds@1952: ** ds@1952: ** These routines is used to get quick access to key and data ds@1952: ** in the common case where no overflow pages are used. ds@1952: */ ds@1952: const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){ ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: if( pCur->eState==CURSOR_VALID ){ ds@1952: return (const void*)fetchPayload(pCur, pAmt, 0); ds@1952: } ds@1952: return 0; ds@1952: } ds@1952: const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){ ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: if( pCur->eState==CURSOR_VALID ){ ds@1952: return (const void*)fetchPayload(pCur, pAmt, 1); ds@1952: } ds@1952: return 0; ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** Move the cursor down to a new child page. The newPgno argument is the ds@1952: ** page number of the child page to move to. ds@1952: */ ds@1952: static int moveToChild(BtCursor *pCur, u32 newPgno){ ds@1952: int rc; ds@1952: MemPage *pNewPage; ds@1952: MemPage *pOldPage; ds@1952: BtShared *pBt = pCur->pBt; ds@1952: ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: assert( pCur->eState==CURSOR_VALID ); ds@1952: rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage); ds@1952: if( rc ) return rc; ds@1952: pNewPage->idxParent = pCur->idx; ds@1952: pOldPage = pCur->pPage; ds@1952: pOldPage->idxShift = 0; ds@1952: releasePage(pOldPage); ds@1952: pCur->pPage = pNewPage; ds@1952: pCur->idx = 0; ds@1952: pCur->info.nSize = 0; ds@1952: if( pNewPage->nCell<1 ){ ds@1952: return SQLITE_CORRUPT_BKPT; ds@1952: } ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Return true if the page is the virtual root of its table. ds@1952: ** ds@1952: ** The virtual root page is the root page for most tables. But ds@1952: ** for the table rooted on page 1, sometime the real root page ds@1952: ** is empty except for the right-pointer. In such cases the ds@1952: ** virtual root page is the page that the right-pointer of page ds@1952: ** 1 is pointing to. ds@1952: */ ds@1952: int sqlite3BtreeIsRootPage(MemPage *pPage){ ds@1952: MemPage *pParent; ds@1952: ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: pParent = pPage->pParent; ds@1952: if( pParent==0 ) return 1; ds@1952: if( pParent->pgno>1 ) return 0; ds@1952: if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1; ds@1952: return 0; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Move the cursor up to the parent page. ds@1952: ** ds@1952: ** pCur->idx is set to the cell index that contains the pointer ds@1952: ** to the page we are coming from. If we are coming from the ds@1952: ** right-most child page then pCur->idx is set to one more than ds@1952: ** the largest cell index. ds@1952: */ ds@1952: void sqlite3BtreeMoveToParent(BtCursor *pCur){ ds@1952: MemPage *pParent; ds@1952: MemPage *pPage; ds@1952: int idxParent; ds@1952: ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: assert( pCur->eState==CURSOR_VALID ); ds@1952: pPage = pCur->pPage; ds@1952: assert( pPage!=0 ); ds@1952: assert( !sqlite3BtreeIsRootPage(pPage) ); ds@1952: pParent = pPage->pParent; ds@1952: assert( pParent!=0 ); ds@1952: idxParent = pPage->idxParent; ds@1952: sqlite3PagerRef(pParent->pDbPage); ds@1952: releasePage(pPage); ds@1952: pCur->pPage = pParent; ds@1952: pCur->info.nSize = 0; ds@1952: assert( pParent->idxShift==0 ); ds@1952: pCur->idx = idxParent; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Move the cursor to the root page ds@1952: */ ds@1952: static int moveToRoot(BtCursor *pCur){ ds@1952: MemPage *pRoot; ds@1952: int rc = SQLITE_OK; ds@1952: Btree *p = pCur->pBtree; ds@1952: BtShared *pBt = p->pBt; ds@1952: ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: assert( CURSOR_INVALID < CURSOR_REQUIRESEEK ); ds@1952: assert( CURSOR_VALID < CURSOR_REQUIRESEEK ); ds@1952: assert( CURSOR_FAULT > CURSOR_REQUIRESEEK ); ds@1952: if( pCur->eState>=CURSOR_REQUIRESEEK ){ ds@1952: if( pCur->eState==CURSOR_FAULT ){ ds@1952: return pCur->skip; ds@1952: } ds@1952: clearCursorPosition(pCur); ds@1952: } ds@1952: pRoot = pCur->pPage; ds@1952: if( pRoot && pRoot->pgno==pCur->pgnoRoot ){ ds@1952: assert( pRoot->isInit ); ds@1952: }else{ ds@1952: if( ds@1952: SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0)) ds@1952: ){ ds@1952: pCur->eState = CURSOR_INVALID; ds@1952: return rc; ds@1952: } ds@1952: releasePage(pCur->pPage); ds@1952: pCur->pPage = pRoot; ds@1952: } ds@1952: pCur->idx = 0; ds@1952: pCur->info.nSize = 0; ds@1952: if( pRoot->nCell==0 && !pRoot->leaf ){ ds@1952: Pgno subpage; ds@1952: assert( pRoot->pgno==1 ); ds@1952: subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]); ds@1952: assert( subpage>0 ); ds@1952: pCur->eState = CURSOR_VALID; ds@1952: rc = moveToChild(pCur, subpage); ds@1952: } ds@1952: pCur->eState = ((pCur->pPage->nCell>0)?CURSOR_VALID:CURSOR_INVALID); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Move the cursor down to the left-most leaf entry beneath the ds@1952: ** entry to which it is currently pointing. ds@1952: ** ds@1952: ** The left-most leaf is the one with the smallest key - the first ds@1952: ** in ascending order. ds@1952: */ ds@1952: static int moveToLeftmost(BtCursor *pCur){ ds@1952: Pgno pgno; ds@1952: int rc = SQLITE_OK; ds@1952: MemPage *pPage; ds@1952: ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: assert( pCur->eState==CURSOR_VALID ); ds@1952: while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){ ds@1952: assert( pCur->idx>=0 && pCur->idxnCell ); ds@1952: pgno = get4byte(findCell(pPage, pCur->idx)); ds@1952: rc = moveToChild(pCur, pgno); ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Move the cursor down to the right-most leaf entry beneath the ds@1952: ** page to which it is currently pointing. Notice the difference ds@1952: ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost() ds@1952: ** finds the left-most entry beneath the *entry* whereas moveToRightmost() ds@1952: ** finds the right-most entry beneath the *page*. ds@1952: ** ds@1952: ** The right-most entry is the one with the largest key - the last ds@1952: ** key in ascending order. ds@1952: */ ds@1952: static int moveToRightmost(BtCursor *pCur){ ds@1952: Pgno pgno; ds@1952: int rc = SQLITE_OK; ds@1952: MemPage *pPage; ds@1952: ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: assert( pCur->eState==CURSOR_VALID ); ds@1952: while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){ ds@1952: pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); ds@1952: pCur->idx = pPage->nCell; ds@1952: rc = moveToChild(pCur, pgno); ds@1952: } ds@1952: if( rc==SQLITE_OK ){ ds@1952: pCur->idx = pPage->nCell - 1; ds@1952: pCur->info.nSize = 0; ds@1952: } ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* Move the cursor to the first entry in the table. Return SQLITE_OK ds@1952: ** on success. Set *pRes to 0 if the cursor actually points to something ds@1952: ** or set *pRes to 1 if the table is empty. ds@1952: */ ds@1952: int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){ ds@1952: int rc; ds@1952: ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: assert( sqlite3_mutex_held(pCur->pBtree->pSqlite->mutex) ); ds@1952: rc = moveToRoot(pCur); ds@1952: if( rc==SQLITE_OK ){ ds@1952: if( pCur->eState==CURSOR_INVALID ){ ds@1952: assert( pCur->pPage->nCell==0 ); ds@1952: *pRes = 1; ds@1952: rc = SQLITE_OK; ds@1952: }else{ ds@1952: assert( pCur->pPage->nCell>0 ); ds@1952: *pRes = 0; ds@1952: rc = moveToLeftmost(pCur); ds@1952: } ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* Move the cursor to the last entry in the table. Return SQLITE_OK ds@1952: ** on success. Set *pRes to 0 if the cursor actually points to something ds@1952: ** or set *pRes to 1 if the table is empty. ds@1952: */ ds@1952: int sqlite3BtreeLast(BtCursor *pCur, int *pRes){ ds@1952: int rc; ds@1952: ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: assert( sqlite3_mutex_held(pCur->pBtree->pSqlite->mutex) ); ds@1952: rc = moveToRoot(pCur); ds@1952: if( rc==SQLITE_OK ){ ds@1952: if( CURSOR_INVALID==pCur->eState ){ ds@1952: assert( pCur->pPage->nCell==0 ); ds@1952: *pRes = 1; ds@1952: }else{ ds@1952: assert( pCur->eState==CURSOR_VALID ); ds@1952: *pRes = 0; ds@1952: rc = moveToRightmost(pCur); ds@1952: } ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* Move the cursor so that it points to an entry near pKey/nKey. ds@1952: ** Return a success code. ds@1952: ** ds@1952: ** For INTKEY tables, only the nKey parameter is used. pKey is ds@1952: ** ignored. For other tables, nKey is the number of bytes of data ds@1952: ** in pKey. The comparison function specified when the cursor was ds@1952: ** created is used to compare keys. ds@1952: ** ds@1952: ** If an exact match is not found, then the cursor is always ds@1952: ** left pointing at a leaf page which would hold the entry if it ds@1952: ** were present. The cursor might point to an entry that comes ds@1952: ** before or after the key. ds@1952: ** ds@1952: ** The result of comparing the key with the entry to which the ds@1952: ** cursor is written to *pRes if pRes!=NULL. The meaning of ds@1952: ** this value is as follows: ds@1952: ** ds@1952: ** *pRes<0 The cursor is left pointing at an entry that ds@1952: ** is smaller than pKey or if the table is empty ds@1952: ** and the cursor is therefore left point to nothing. ds@1952: ** ds@1952: ** *pRes==0 The cursor is left pointing at an entry that ds@1952: ** exactly matches pKey. ds@1952: ** ds@1952: ** *pRes>0 The cursor is left pointing at an entry that ds@1952: ** is larger than pKey. ds@1952: ** ds@1952: */ ds@1952: int sqlite3BtreeMoveto( ds@1952: BtCursor *pCur, /* The cursor to be moved */ ds@1952: const void *pKey, /* The key content for indices. Not used by tables */ ds@1952: i64 nKey, /* Size of pKey. Or the key for tables */ ds@1952: int biasRight, /* If true, bias the search to the high end */ ds@1952: int *pRes /* Search result flag */ ds@1952: ){ ds@1952: int rc; ds@1952: ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: assert( sqlite3_mutex_held(pCur->pBtree->pSqlite->mutex) ); ds@1952: rc = moveToRoot(pCur); ds@1952: if( rc ){ ds@1952: return rc; ds@1952: } ds@1952: assert( pCur->pPage ); ds@1952: assert( pCur->pPage->isInit ); ds@1952: if( pCur->eState==CURSOR_INVALID ){ ds@1952: *pRes = -1; ds@1952: assert( pCur->pPage->nCell==0 ); ds@1952: return SQLITE_OK; ds@1952: } ds@1952: for(;;){ ds@1952: int lwr, upr; ds@1952: Pgno chldPg; ds@1952: MemPage *pPage = pCur->pPage; ds@1952: int c = -1; /* pRes return if table is empty must be -1 */ ds@1952: lwr = 0; ds@1952: upr = pPage->nCell-1; ds@1952: if( !pPage->intKey && pKey==0 ){ ds@1952: return SQLITE_CORRUPT_BKPT; ds@1952: } ds@1952: if( biasRight ){ ds@1952: pCur->idx = upr; ds@1952: }else{ ds@1952: pCur->idx = (upr+lwr)/2; ds@1952: } ds@1952: if( lwr<=upr ) for(;;){ ds@1952: void *pCellKey; ds@1952: i64 nCellKey; ds@1952: pCur->info.nSize = 0; ds@1952: if( pPage->intKey ){ ds@1952: u8 *pCell; ds@1952: pCell = findCell(pPage, pCur->idx) + pPage->childPtrSize; ds@1952: if( pPage->hasData ){ ds@1952: u32 dummy; ds@1952: pCell += getVarint32(pCell, &dummy); ds@1952: } ds@1952: getVarint(pCell, (u64 *)&nCellKey); ds@1952: if( nCellKeynKey ){ ds@1952: c = +1; ds@1952: }else{ ds@1952: c = 0; ds@1952: } ds@1952: }else{ ds@1952: int available; ds@1952: pCellKey = (void *)fetchPayload(pCur, &available, 0); ds@1952: nCellKey = pCur->info.nKey; ds@1952: if( available>=nCellKey ){ ds@1952: c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey); ds@1952: }else{ ds@1952: pCellKey = sqlite3_malloc( nCellKey ); ds@1952: if( pCellKey==0 ) return SQLITE_NOMEM; ds@1952: rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey); ds@1952: c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey); ds@1952: sqlite3_free(pCellKey); ds@1952: if( rc ){ ds@1952: return rc; ds@1952: } ds@1952: } ds@1952: } ds@1952: if( c==0 ){ ds@1952: if( pPage->leafData && !pPage->leaf ){ ds@1952: lwr = pCur->idx; ds@1952: upr = lwr - 1; ds@1952: break; ds@1952: }else{ ds@1952: if( pRes ) *pRes = 0; ds@1952: return SQLITE_OK; ds@1952: } ds@1952: } ds@1952: if( c<0 ){ ds@1952: lwr = pCur->idx+1; ds@1952: }else{ ds@1952: upr = pCur->idx-1; ds@1952: } ds@1952: if( lwr>upr ){ ds@1952: break; ds@1952: } ds@1952: pCur->idx = (lwr+upr)/2; ds@1952: } ds@1952: assert( lwr==upr+1 ); ds@1952: assert( pPage->isInit ); ds@1952: if( pPage->leaf ){ ds@1952: chldPg = 0; ds@1952: }else if( lwr>=pPage->nCell ){ ds@1952: chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]); ds@1952: }else{ ds@1952: chldPg = get4byte(findCell(pPage, lwr)); ds@1952: } ds@1952: if( chldPg==0 ){ ds@1952: assert( pCur->idx>=0 && pCur->idxpPage->nCell ); ds@1952: if( pRes ) *pRes = c; ds@1952: return SQLITE_OK; ds@1952: } ds@1952: pCur->idx = lwr; ds@1952: pCur->info.nSize = 0; ds@1952: rc = moveToChild(pCur, chldPg); ds@1952: if( rc ){ ds@1952: return rc; ds@1952: } ds@1952: } ds@1952: /* NOT REACHED */ ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** Return TRUE if the cursor is not pointing at an entry of the table. ds@1952: ** ds@1952: ** TRUE will be returned after a call to sqlite3BtreeNext() moves ds@1952: ** past the last entry in the table or sqlite3BtreePrev() moves past ds@1952: ** the first entry. TRUE is also returned if the table is empty. ds@1952: */ ds@1952: int sqlite3BtreeEof(BtCursor *pCur){ ds@1952: /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries ds@1952: ** have been deleted? This API will need to change to return an error code ds@1952: ** as well as the boolean result value. ds@1952: */ ds@1952: return (CURSOR_VALID!=pCur->eState); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Return the database connection handle for a cursor. ds@1952: */ ds@1952: sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){ ds@1952: assert( sqlite3_mutex_held(pCur->pBtree->pSqlite->mutex) ); ds@1952: return pCur->pBtree->pSqlite; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Advance the cursor to the next entry in the database. If ds@1952: ** successful then set *pRes=0. If the cursor ds@1952: ** was already pointing to the last entry in the database before ds@1952: ** this routine was called, then set *pRes=1. ds@1952: */ ds@1952: static int btreeNext(BtCursor *pCur, int *pRes){ ds@1952: int rc; ds@1952: MemPage *pPage; ds@1952: ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: rc = restoreOrClearCursorPosition(pCur); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: assert( pRes!=0 ); ds@1952: pPage = pCur->pPage; ds@1952: if( CURSOR_INVALID==pCur->eState ){ ds@1952: *pRes = 1; ds@1952: return SQLITE_OK; ds@1952: } ds@1952: if( pCur->skip>0 ){ ds@1952: pCur->skip = 0; ds@1952: *pRes = 0; ds@1952: return SQLITE_OK; ds@1952: } ds@1952: pCur->skip = 0; ds@1952: ds@1952: assert( pPage->isInit ); ds@1952: assert( pCur->idxnCell ); ds@1952: ds@1952: pCur->idx++; ds@1952: pCur->info.nSize = 0; ds@1952: if( pCur->idx>=pPage->nCell ){ ds@1952: if( !pPage->leaf ){ ds@1952: rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8])); ds@1952: if( rc ) return rc; ds@1952: rc = moveToLeftmost(pCur); ds@1952: *pRes = 0; ds@1952: return rc; ds@1952: } ds@1952: do{ ds@1952: if( sqlite3BtreeIsRootPage(pPage) ){ ds@1952: *pRes = 1; ds@1952: pCur->eState = CURSOR_INVALID; ds@1952: return SQLITE_OK; ds@1952: } ds@1952: sqlite3BtreeMoveToParent(pCur); ds@1952: pPage = pCur->pPage; ds@1952: }while( pCur->idx>=pPage->nCell ); ds@1952: *pRes = 0; ds@1952: if( pPage->leafData ){ ds@1952: rc = sqlite3BtreeNext(pCur, pRes); ds@1952: }else{ ds@1952: rc = SQLITE_OK; ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: *pRes = 0; ds@1952: if( pPage->leaf ){ ds@1952: return SQLITE_OK; ds@1952: } ds@1952: rc = moveToLeftmost(pCur); ds@1952: return rc; ds@1952: } ds@1952: int sqlite3BtreeNext(BtCursor *pCur, int *pRes){ ds@1952: int rc; ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: rc = btreeNext(pCur, pRes); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** Step the cursor to the back to the previous entry in the database. If ds@1952: ** successful then set *pRes=0. If the cursor ds@1952: ** was already pointing to the first entry in the database before ds@1952: ** this routine was called, then set *pRes=1. ds@1952: */ ds@1952: static int btreePrevious(BtCursor *pCur, int *pRes){ ds@1952: int rc; ds@1952: Pgno pgno; ds@1952: MemPage *pPage; ds@1952: ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: rc = restoreOrClearCursorPosition(pCur); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: if( CURSOR_INVALID==pCur->eState ){ ds@1952: *pRes = 1; ds@1952: return SQLITE_OK; ds@1952: } ds@1952: if( pCur->skip<0 ){ ds@1952: pCur->skip = 0; ds@1952: *pRes = 0; ds@1952: return SQLITE_OK; ds@1952: } ds@1952: pCur->skip = 0; ds@1952: ds@1952: pPage = pCur->pPage; ds@1952: assert( pPage->isInit ); ds@1952: assert( pCur->idx>=0 ); ds@1952: if( !pPage->leaf ){ ds@1952: pgno = get4byte( findCell(pPage, pCur->idx) ); ds@1952: rc = moveToChild(pCur, pgno); ds@1952: if( rc ){ ds@1952: return rc; ds@1952: } ds@1952: rc = moveToRightmost(pCur); ds@1952: }else{ ds@1952: while( pCur->idx==0 ){ ds@1952: if( sqlite3BtreeIsRootPage(pPage) ){ ds@1952: pCur->eState = CURSOR_INVALID; ds@1952: *pRes = 1; ds@1952: return SQLITE_OK; ds@1952: } ds@1952: sqlite3BtreeMoveToParent(pCur); ds@1952: pPage = pCur->pPage; ds@1952: } ds@1952: pCur->idx--; ds@1952: pCur->info.nSize = 0; ds@1952: if( pPage->leafData && !pPage->leaf ){ ds@1952: rc = sqlite3BtreePrevious(pCur, pRes); ds@1952: }else{ ds@1952: rc = SQLITE_OK; ds@1952: } ds@1952: } ds@1952: *pRes = 0; ds@1952: return rc; ds@1952: } ds@1952: int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){ ds@1952: int rc; ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: rc = btreePrevious(pCur, pRes); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Allocate a new page from the database file. ds@1952: ** ds@1952: ** The new page is marked as dirty. (In other words, sqlite3PagerWrite() ds@1952: ** has already been called on the new page.) The new page has also ds@1952: ** been referenced and the calling routine is responsible for calling ds@1952: ** sqlite3PagerUnref() on the new page when it is done. ds@1952: ** ds@1952: ** SQLITE_OK is returned on success. Any other return value indicates ds@1952: ** an error. *ppPage and *pPgno are undefined in the event of an error. ds@1952: ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned. ds@1952: ** ds@1952: ** If the "nearby" parameter is not 0, then a (feeble) effort is made to ds@1952: ** locate a page close to the page number "nearby". This can be used in an ds@1952: ** attempt to keep related pages close to each other in the database file, ds@1952: ** which in turn can make database access faster. ds@1952: ** ds@1952: ** If the "exact" parameter is not 0, and the page-number nearby exists ds@1952: ** anywhere on the free-list, then it is guarenteed to be returned. This ds@1952: ** is only used by auto-vacuum databases when allocating a new table. ds@1952: */ ds@1952: static int allocateBtreePage( ds@1952: BtShared *pBt, ds@1952: MemPage **ppPage, ds@1952: Pgno *pPgno, ds@1952: Pgno nearby, ds@1952: u8 exact ds@1952: ){ ds@1952: MemPage *pPage1; ds@1952: int rc; ds@1952: int n; /* Number of pages on the freelist */ ds@1952: int k; /* Number of leaves on the trunk of the freelist */ ds@1952: MemPage *pTrunk = 0; ds@1952: MemPage *pPrevTrunk = 0; ds@1952: ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: pPage1 = pBt->pPage1; ds@1952: n = get4byte(&pPage1->aData[36]); ds@1952: if( n>0 ){ ds@1952: /* There are pages on the freelist. Reuse one of those pages. */ ds@1952: Pgno iTrunk; ds@1952: u8 searchList = 0; /* If the free-list must be searched for 'nearby' */ ds@1952: ds@1952: /* If the 'exact' parameter was true and a query of the pointer-map ds@1952: ** shows that the page 'nearby' is somewhere on the free-list, then ds@1952: ** the entire-list will be searched for that page. ds@1952: */ ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: if( exact && nearby<=sqlite3PagerPagecount(pBt->pPager) ){ ds@1952: u8 eType; ds@1952: assert( nearby>0 ); ds@1952: assert( pBt->autoVacuum ); ds@1952: rc = ptrmapGet(pBt, nearby, &eType, 0); ds@1952: if( rc ) return rc; ds@1952: if( eType==PTRMAP_FREEPAGE ){ ds@1952: searchList = 1; ds@1952: } ds@1952: *pPgno = nearby; ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* Decrement the free-list count by 1. Set iTrunk to the index of the ds@1952: ** first free-list trunk page. iPrevTrunk is initially 1. ds@1952: */ ds@1952: rc = sqlite3PagerWrite(pPage1->pDbPage); ds@1952: if( rc ) return rc; ds@1952: put4byte(&pPage1->aData[36], n-1); ds@1952: ds@1952: /* The code within this loop is run only once if the 'searchList' variable ds@1952: ** is not true. Otherwise, it runs once for each trunk-page on the ds@1952: ** free-list until the page 'nearby' is located. ds@1952: */ ds@1952: do { ds@1952: pPrevTrunk = pTrunk; ds@1952: if( pPrevTrunk ){ ds@1952: iTrunk = get4byte(&pPrevTrunk->aData[0]); ds@1952: }else{ ds@1952: iTrunk = get4byte(&pPage1->aData[32]); ds@1952: } ds@1952: rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0); ds@1952: if( rc ){ ds@1952: pTrunk = 0; ds@1952: goto end_allocate_page; ds@1952: } ds@1952: ds@1952: k = get4byte(&pTrunk->aData[4]); ds@1952: if( k==0 && !searchList ){ ds@1952: /* The trunk has no leaves and the list is not being searched. ds@1952: ** So extract the trunk page itself and use it as the newly ds@1952: ** allocated page */ ds@1952: assert( pPrevTrunk==0 ); ds@1952: rc = sqlite3PagerWrite(pTrunk->pDbPage); ds@1952: if( rc ){ ds@1952: goto end_allocate_page; ds@1952: } ds@1952: *pPgno = iTrunk; ds@1952: memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); ds@1952: *ppPage = pTrunk; ds@1952: pTrunk = 0; ds@1952: TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); ds@1952: }else if( k>pBt->usableSize/4 - 8 ){ ds@1952: /* Value of k is out of range. Database corruption */ ds@1952: rc = SQLITE_CORRUPT_BKPT; ds@1952: goto end_allocate_page; ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: }else if( searchList && nearby==iTrunk ){ ds@1952: /* The list is being searched and this trunk page is the page ds@1952: ** to allocate, regardless of whether it has leaves. ds@1952: */ ds@1952: assert( *pPgno==iTrunk ); ds@1952: *ppPage = pTrunk; ds@1952: searchList = 0; ds@1952: rc = sqlite3PagerWrite(pTrunk->pDbPage); ds@1952: if( rc ){ ds@1952: goto end_allocate_page; ds@1952: } ds@1952: if( k==0 ){ ds@1952: if( !pPrevTrunk ){ ds@1952: memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4); ds@1952: }else{ ds@1952: memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4); ds@1952: } ds@1952: }else{ ds@1952: /* The trunk page is required by the caller but it contains ds@1952: ** pointers to free-list leaves. The first leaf becomes a trunk ds@1952: ** page in this case. ds@1952: */ ds@1952: MemPage *pNewTrunk; ds@1952: Pgno iNewTrunk = get4byte(&pTrunk->aData[8]); ds@1952: rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: goto end_allocate_page; ds@1952: } ds@1952: rc = sqlite3PagerWrite(pNewTrunk->pDbPage); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: releasePage(pNewTrunk); ds@1952: goto end_allocate_page; ds@1952: } ds@1952: memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4); ds@1952: put4byte(&pNewTrunk->aData[4], k-1); ds@1952: memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4); ds@1952: releasePage(pNewTrunk); ds@1952: if( !pPrevTrunk ){ ds@1952: put4byte(&pPage1->aData[32], iNewTrunk); ds@1952: }else{ ds@1952: rc = sqlite3PagerWrite(pPrevTrunk->pDbPage); ds@1952: if( rc ){ ds@1952: goto end_allocate_page; ds@1952: } ds@1952: put4byte(&pPrevTrunk->aData[0], iNewTrunk); ds@1952: } ds@1952: } ds@1952: pTrunk = 0; ds@1952: TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1)); ds@1952: #endif ds@1952: }else{ ds@1952: /* Extract a leaf from the trunk */ ds@1952: int closest; ds@1952: Pgno iPage; ds@1952: unsigned char *aData = pTrunk->aData; ds@1952: rc = sqlite3PagerWrite(pTrunk->pDbPage); ds@1952: if( rc ){ ds@1952: goto end_allocate_page; ds@1952: } ds@1952: if( nearby>0 ){ ds@1952: int i, dist; ds@1952: closest = 0; ds@1952: dist = get4byte(&aData[8]) - nearby; ds@1952: if( dist<0 ) dist = -dist; ds@1952: for(i=1; isqlite3PagerPagecount(pBt->pPager) ){ ds@1952: /* Free page off the end of the file */ ds@1952: return SQLITE_CORRUPT_BKPT; ds@1952: } ds@1952: TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d" ds@1952: ": %d more free pages\n", ds@1952: *pPgno, closest+1, k, pTrunk->pgno, n-1)); ds@1952: if( closestpDbPage); ds@1952: rc = sqlite3PagerWrite((*ppPage)->pDbPage); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: releasePage(*ppPage); ds@1952: } ds@1952: } ds@1952: searchList = 0; ds@1952: } ds@1952: } ds@1952: releasePage(pPrevTrunk); ds@1952: pPrevTrunk = 0; ds@1952: }while( searchList ); ds@1952: }else{ ds@1952: /* There are no pages on the freelist, so create a new page at the ds@1952: ** end of the file */ ds@1952: *pPgno = sqlite3PagerPagecount(pBt->pPager) + 1; ds@1952: ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: if( pBt->nTrunc ){ ds@1952: /* An incr-vacuum has already run within this transaction. So the ds@1952: ** page to allocate is not from the physical end of the file, but ds@1952: ** at pBt->nTrunc. ds@1952: */ ds@1952: *pPgno = pBt->nTrunc+1; ds@1952: if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ ds@1952: (*pPgno)++; ds@1952: } ds@1952: } ds@1952: if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){ ds@1952: /* If *pPgno refers to a pointer-map page, allocate two new pages ds@1952: ** at the end of the file instead of one. The first allocated page ds@1952: ** becomes a new pointer-map page, the second is used by the caller. ds@1952: */ ds@1952: TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno)); ds@1952: assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); ds@1952: (*pPgno)++; ds@1952: } ds@1952: if( pBt->nTrunc ){ ds@1952: pBt->nTrunc = *pPgno; ds@1952: } ds@1952: #endif ds@1952: ds@1952: assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); ds@1952: rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0); ds@1952: if( rc ) return rc; ds@1952: rc = sqlite3PagerWrite((*ppPage)->pDbPage); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: releasePage(*ppPage); ds@1952: } ds@1952: TRACE(("ALLOCATE: %d from end of file\n", *pPgno)); ds@1952: } ds@1952: ds@1952: assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); ds@1952: ds@1952: end_allocate_page: ds@1952: releasePage(pTrunk); ds@1952: releasePage(pPrevTrunk); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Add a page of the database file to the freelist. ds@1952: ** ds@1952: ** sqlite3PagerUnref() is NOT called for pPage. ds@1952: */ ds@1952: static int freePage(MemPage *pPage){ ds@1952: BtShared *pBt = pPage->pBt; ds@1952: MemPage *pPage1 = pBt->pPage1; ds@1952: int rc, n, k; ds@1952: ds@1952: /* Prepare the page for freeing */ ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: assert( pPage->pgno>1 ); ds@1952: pPage->isInit = 0; ds@1952: releasePage(pPage->pParent); ds@1952: pPage->pParent = 0; ds@1952: ds@1952: /* Increment the free page count on pPage1 */ ds@1952: rc = sqlite3PagerWrite(pPage1->pDbPage); ds@1952: if( rc ) return rc; ds@1952: n = get4byte(&pPage1->aData[36]); ds@1952: put4byte(&pPage1->aData[36], n+1); ds@1952: ds@1952: #ifdef SQLITE_SECURE_DELETE ds@1952: /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then ds@1952: ** always fully overwrite deleted information with zeros. ds@1952: */ ds@1952: rc = sqlite3PagerWrite(pPage->pDbPage); ds@1952: if( rc ) return rc; ds@1952: memset(pPage->aData, 0, pPage->pBt->pageSize); ds@1952: #endif ds@1952: ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: /* If the database supports auto-vacuum, write an entry in the pointer-map ds@1952: ** to indicate that the page is free. ds@1952: */ ds@1952: if( pBt->autoVacuum ){ ds@1952: rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0); ds@1952: if( rc ) return rc; ds@1952: } ds@1952: #endif ds@1952: ds@1952: if( n==0 ){ ds@1952: /* This is the first free page */ ds@1952: rc = sqlite3PagerWrite(pPage->pDbPage); ds@1952: if( rc ) return rc; ds@1952: memset(pPage->aData, 0, 8); ds@1952: put4byte(&pPage1->aData[32], pPage->pgno); ds@1952: TRACE(("FREE-PAGE: %d first\n", pPage->pgno)); ds@1952: }else{ ds@1952: /* Other free pages already exist. Retrive the first trunk page ds@1952: ** of the freelist and find out how many leaves it has. */ ds@1952: MemPage *pTrunk; ds@1952: rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0); ds@1952: if( rc ) return rc; ds@1952: k = get4byte(&pTrunk->aData[4]); ds@1952: if( k>=pBt->usableSize/4 - 8 ){ ds@1952: /* The trunk is full. Turn the page being freed into a new ds@1952: ** trunk page with no leaves. */ ds@1952: rc = sqlite3PagerWrite(pPage->pDbPage); ds@1952: if( rc==SQLITE_OK ){ ds@1952: put4byte(pPage->aData, pTrunk->pgno); ds@1952: put4byte(&pPage->aData[4], 0); ds@1952: put4byte(&pPage1->aData[32], pPage->pgno); ds@1952: TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", ds@1952: pPage->pgno, pTrunk->pgno)); ds@1952: } ds@1952: }else if( k<0 ){ ds@1952: rc = SQLITE_CORRUPT; ds@1952: }else{ ds@1952: /* Add the newly freed page as a leaf on the current trunk */ ds@1952: rc = sqlite3PagerWrite(pTrunk->pDbPage); ds@1952: if( rc==SQLITE_OK ){ ds@1952: put4byte(&pTrunk->aData[4], k+1); ds@1952: put4byte(&pTrunk->aData[8+k*4], pPage->pgno); ds@1952: #ifndef SQLITE_SECURE_DELETE ds@1952: sqlite3PagerDontWrite(pPage->pDbPage); ds@1952: #endif ds@1952: } ds@1952: TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno)); ds@1952: } ds@1952: releasePage(pTrunk); ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Free any overflow pages associated with the given Cell. ds@1952: */ ds@1952: static int clearCell(MemPage *pPage, unsigned char *pCell){ ds@1952: BtShared *pBt = pPage->pBt; ds@1952: CellInfo info; ds@1952: Pgno ovflPgno; ds@1952: int rc; ds@1952: int nOvfl; ds@1952: int ovflPageSize; ds@1952: ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: sqlite3BtreeParseCellPtr(pPage, pCell, &info); ds@1952: if( info.iOverflow==0 ){ ds@1952: return SQLITE_OK; /* No overflow pages. Return without doing anything */ ds@1952: } ds@1952: ovflPgno = get4byte(&pCell[info.iOverflow]); ds@1952: ovflPageSize = pBt->usableSize - 4; ds@1952: nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize; ds@1952: assert( ovflPgno==0 || nOvfl>0 ); ds@1952: while( nOvfl-- ){ ds@1952: MemPage *pOvfl; ds@1952: if( ovflPgno==0 || ovflPgno>sqlite3PagerPagecount(pBt->pPager) ){ ds@1952: return SQLITE_CORRUPT_BKPT; ds@1952: } ds@1952: ds@1952: rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno); ds@1952: if( rc ) return rc; ds@1952: rc = freePage(pOvfl); ds@1952: sqlite3PagerUnref(pOvfl->pDbPage); ds@1952: if( rc ) return rc; ds@1952: } ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Create the byte sequence used to represent a cell on page pPage ds@1952: ** and write that byte sequence into pCell[]. Overflow pages are ds@1952: ** allocated and filled in as necessary. The calling procedure ds@1952: ** is responsible for making sure sufficient space has been allocated ds@1952: ** for pCell[]. ds@1952: ** ds@1952: ** Note that pCell does not necessary need to point to the pPage->aData ds@1952: ** area. pCell might point to some temporary storage. The cell will ds@1952: ** be constructed in this temporary area then copied into pPage->aData ds@1952: ** later. ds@1952: */ ds@1952: static int fillInCell( ds@1952: MemPage *pPage, /* The page that contains the cell */ ds@1952: unsigned char *pCell, /* Complete text of the cell */ ds@1952: const void *pKey, i64 nKey, /* The key */ ds@1952: const void *pData,int nData, /* The data */ ds@1952: int nZero, /* Extra zero bytes to append to pData */ ds@1952: int *pnSize /* Write cell size here */ ds@1952: ){ ds@1952: int nPayload; ds@1952: const u8 *pSrc; ds@1952: int nSrc, n, rc; ds@1952: int spaceLeft; ds@1952: MemPage *pOvfl = 0; ds@1952: MemPage *pToRelease = 0; ds@1952: unsigned char *pPrior; ds@1952: unsigned char *pPayload; ds@1952: BtShared *pBt = pPage->pBt; ds@1952: Pgno pgnoOvfl = 0; ds@1952: int nHeader; ds@1952: CellInfo info; ds@1952: ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: ds@1952: /* Fill in the header. */ ds@1952: nHeader = 0; ds@1952: if( !pPage->leaf ){ ds@1952: nHeader += 4; ds@1952: } ds@1952: if( pPage->hasData ){ ds@1952: nHeader += putVarint(&pCell[nHeader], nData+nZero); ds@1952: }else{ ds@1952: nData = nZero = 0; ds@1952: } ds@1952: nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey); ds@1952: sqlite3BtreeParseCellPtr(pPage, pCell, &info); ds@1952: assert( info.nHeader==nHeader ); ds@1952: assert( info.nKey==nKey ); ds@1952: assert( info.nData==nData+nZero ); ds@1952: ds@1952: /* Fill in the payload */ ds@1952: nPayload = nData + nZero; ds@1952: if( pPage->intKey ){ ds@1952: pSrc = pData; ds@1952: nSrc = nData; ds@1952: nData = 0; ds@1952: }else{ ds@1952: nPayload += nKey; ds@1952: pSrc = pKey; ds@1952: nSrc = nKey; ds@1952: } ds@1952: *pnSize = info.nSize; ds@1952: spaceLeft = info.nLocal; ds@1952: pPayload = &pCell[nHeader]; ds@1952: pPrior = &pCell[info.iOverflow]; ds@1952: ds@1952: while( nPayload>0 ){ ds@1952: if( spaceLeft==0 ){ ds@1952: int isExact = 0; ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */ ds@1952: if( pBt->autoVacuum ){ ds@1952: do{ ds@1952: pgnoOvfl++; ds@1952: } while( ds@1952: PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) ds@1952: ); ds@1952: if( pgnoOvfl>1 ){ ds@1952: /* isExact = 1; */ ds@1952: } ds@1952: } ds@1952: #endif ds@1952: rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, isExact); ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: /* If the database supports auto-vacuum, and the second or subsequent ds@1952: ** overflow page is being allocated, add an entry to the pointer-map ds@1952: ** for that page now. ds@1952: ** ds@1952: ** If this is the first overflow page, then write a partial entry ds@1952: ** to the pointer-map. If we write nothing to this pointer-map slot, ds@1952: ** then the optimistic overflow chain processing in clearCell() ds@1952: ** may misinterpret the uninitialised values and delete the ds@1952: ** wrong pages from the database. ds@1952: */ ds@1952: if( pBt->autoVacuum && rc==SQLITE_OK ){ ds@1952: u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1); ds@1952: rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap); ds@1952: if( rc ){ ds@1952: releasePage(pOvfl); ds@1952: } ds@1952: } ds@1952: #endif ds@1952: if( rc ){ ds@1952: releasePage(pToRelease); ds@1952: return rc; ds@1952: } ds@1952: put4byte(pPrior, pgnoOvfl); ds@1952: releasePage(pToRelease); ds@1952: pToRelease = pOvfl; ds@1952: pPrior = pOvfl->aData; ds@1952: put4byte(pPrior, 0); ds@1952: pPayload = &pOvfl->aData[4]; ds@1952: spaceLeft = pBt->usableSize - 4; ds@1952: } ds@1952: n = nPayload; ds@1952: if( n>spaceLeft ) n = spaceLeft; ds@1952: if( nSrc>0 ){ ds@1952: if( n>nSrc ) n = nSrc; ds@1952: assert( pSrc ); ds@1952: memcpy(pPayload, pSrc, n); ds@1952: }else{ ds@1952: memset(pPayload, 0, n); ds@1952: } ds@1952: nPayload -= n; ds@1952: pPayload += n; ds@1952: pSrc += n; ds@1952: nSrc -= n; ds@1952: spaceLeft -= n; ds@1952: if( nSrc==0 ){ ds@1952: nSrc = nData; ds@1952: pSrc = pData; ds@1952: } ds@1952: } ds@1952: releasePage(pToRelease); ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Change the MemPage.pParent pointer on the page whose number is ds@1952: ** given in the second argument so that MemPage.pParent holds the ds@1952: ** pointer in the third argument. ds@1952: */ ds@1952: static int reparentPage(BtShared *pBt, Pgno pgno, MemPage *pNewParent, int idx){ ds@1952: MemPage *pThis; ds@1952: DbPage *pDbPage; ds@1952: ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: assert( pNewParent!=0 ); ds@1952: if( pgno==0 ) return SQLITE_OK; ds@1952: assert( pBt->pPager!=0 ); ds@1952: pDbPage = sqlite3PagerLookup(pBt->pPager, pgno); ds@1952: if( pDbPage ){ ds@1952: pThis = (MemPage *)sqlite3PagerGetExtra(pDbPage); ds@1952: if( pThis->isInit ){ ds@1952: assert( pThis->aData==sqlite3PagerGetData(pDbPage) ); ds@1952: if( pThis->pParent!=pNewParent ){ ds@1952: if( pThis->pParent ) sqlite3PagerUnref(pThis->pParent->pDbPage); ds@1952: pThis->pParent = pNewParent; ds@1952: sqlite3PagerRef(pNewParent->pDbPage); ds@1952: } ds@1952: pThis->idxParent = idx; ds@1952: } ds@1952: sqlite3PagerUnref(pDbPage); ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: if( pBt->autoVacuum ){ ds@1952: return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno); ds@1952: } ds@1952: #endif ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: ds@1952: ds@1952: /* ds@1952: ** Change the pParent pointer of all children of pPage to point back ds@1952: ** to pPage. ds@1952: ** ds@1952: ** In other words, for every child of pPage, invoke reparentPage() ds@1952: ** to make sure that each child knows that pPage is its parent. ds@1952: ** ds@1952: ** This routine gets called after you memcpy() one page into ds@1952: ** another. ds@1952: */ ds@1952: static int reparentChildPages(MemPage *pPage){ ds@1952: int i; ds@1952: BtShared *pBt = pPage->pBt; ds@1952: int rc = SQLITE_OK; ds@1952: ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: if( pPage->leaf ) return SQLITE_OK; ds@1952: ds@1952: for(i=0; inCell; i++){ ds@1952: u8 *pCell = findCell(pPage, i); ds@1952: if( !pPage->leaf ){ ds@1952: rc = reparentPage(pBt, get4byte(pCell), pPage, i); ds@1952: if( rc!=SQLITE_OK ) return rc; ds@1952: } ds@1952: } ds@1952: if( !pPage->leaf ){ ds@1952: rc = reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]), ds@1952: pPage, i); ds@1952: pPage->idxShift = 0; ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Remove the i-th cell from pPage. This routine effects pPage only. ds@1952: ** The cell content is not freed or deallocated. It is assumed that ds@1952: ** the cell content has been copied someplace else. This routine just ds@1952: ** removes the reference to the cell from pPage. ds@1952: ** ds@1952: ** "sz" must be the number of bytes in the cell. ds@1952: */ ds@1952: static void dropCell(MemPage *pPage, int idx, int sz){ ds@1952: int i; /* Loop counter */ ds@1952: int pc; /* Offset to cell content of cell being deleted */ ds@1952: u8 *data; /* pPage->aData */ ds@1952: u8 *ptr; /* Used to move bytes around within data[] */ ds@1952: ds@1952: assert( idx>=0 && idxnCell ); ds@1952: assert( sz==cellSize(pPage, idx) ); ds@1952: assert( sqlite3PagerIswriteable(pPage->pDbPage) ); ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: data = pPage->aData; ds@1952: ptr = &data[pPage->cellOffset + 2*idx]; ds@1952: pc = get2byte(ptr); ds@1952: assert( pc>10 && pc+sz<=pPage->pBt->usableSize ); ds@1952: freeSpace(pPage, pc, sz); ds@1952: for(i=idx+1; inCell; i++, ptr+=2){ ds@1952: ptr[0] = ptr[2]; ds@1952: ptr[1] = ptr[3]; ds@1952: } ds@1952: pPage->nCell--; ds@1952: put2byte(&data[pPage->hdrOffset+3], pPage->nCell); ds@1952: pPage->nFree += 2; ds@1952: pPage->idxShift = 1; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Insert a new cell on pPage at cell index "i". pCell points to the ds@1952: ** content of the cell. ds@1952: ** ds@1952: ** If the cell content will fit on the page, then put it there. If it ds@1952: ** will not fit, then make a copy of the cell content into pTemp if ds@1952: ** pTemp is not null. Regardless of pTemp, allocate a new entry ds@1952: ** in pPage->aOvfl[] and make it point to the cell content (either ds@1952: ** in pTemp or the original pCell) and also record its index. ds@1952: ** Allocating a new entry in pPage->aCell[] implies that ds@1952: ** pPage->nOverflow is incremented. ds@1952: ** ds@1952: ** If nSkip is non-zero, then do not copy the first nSkip bytes of the ds@1952: ** cell. The caller will overwrite them after this function returns. If ds@1952: ** nSkip is non-zero, then pCell may not point to an invalid memory location ds@1952: ** (but pCell+nSkip is always valid). ds@1952: */ ds@1952: static int insertCell( ds@1952: MemPage *pPage, /* Page into which we are copying */ ds@1952: int i, /* New cell becomes the i-th cell of the page */ ds@1952: u8 *pCell, /* Content of the new cell */ ds@1952: int sz, /* Bytes of content in pCell */ ds@1952: u8 *pTemp, /* Temp storage space for pCell, if needed */ ds@1952: u8 nSkip /* Do not write the first nSkip bytes of the cell */ ds@1952: ){ ds@1952: int idx; /* Where to write new cell content in data[] */ ds@1952: int j; /* Loop counter */ ds@1952: int top; /* First byte of content for any cell in data[] */ ds@1952: int end; /* First byte past the last cell pointer in data[] */ ds@1952: int ins; /* Index in data[] where new cell pointer is inserted */ ds@1952: int hdr; /* Offset into data[] of the page header */ ds@1952: int cellOffset; /* Address of first cell pointer in data[] */ ds@1952: u8 *data; /* The content of the whole page */ ds@1952: u8 *ptr; /* Used for moving information around in data[] */ ds@1952: ds@1952: assert( i>=0 && i<=pPage->nCell+pPage->nOverflow ); ds@1952: assert( sz==cellSizePtr(pPage, pCell) ); ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: if( pPage->nOverflow || sz+2>pPage->nFree ){ ds@1952: if( pTemp ){ ds@1952: memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip); ds@1952: pCell = pTemp; ds@1952: } ds@1952: j = pPage->nOverflow++; ds@1952: assert( jaOvfl)/sizeof(pPage->aOvfl[0]) ); ds@1952: pPage->aOvfl[j].pCell = pCell; ds@1952: pPage->aOvfl[j].idx = i; ds@1952: pPage->nFree = 0; ds@1952: }else{ ds@1952: int rc = sqlite3PagerWrite(pPage->pDbPage); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: assert( sqlite3PagerIswriteable(pPage->pDbPage) ); ds@1952: data = pPage->aData; ds@1952: hdr = pPage->hdrOffset; ds@1952: top = get2byte(&data[hdr+5]); ds@1952: cellOffset = pPage->cellOffset; ds@1952: end = cellOffset + 2*pPage->nCell + 2; ds@1952: ins = cellOffset + 2*i; ds@1952: if( end > top - sz ){ ds@1952: rc = defragmentPage(pPage); ds@1952: if( rc!=SQLITE_OK ) return rc; ds@1952: top = get2byte(&data[hdr+5]); ds@1952: assert( end + sz <= top ); ds@1952: } ds@1952: idx = allocateSpace(pPage, sz); ds@1952: assert( idx>0 ); ds@1952: assert( end <= get2byte(&data[hdr+5]) ); ds@1952: pPage->nCell++; ds@1952: pPage->nFree -= 2; ds@1952: memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip); ds@1952: for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){ ds@1952: ptr[0] = ptr[-2]; ds@1952: ptr[1] = ptr[-1]; ds@1952: } ds@1952: put2byte(&data[ins], idx); ds@1952: put2byte(&data[hdr+3], pPage->nCell); ds@1952: pPage->idxShift = 1; ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: if( pPage->pBt->autoVacuum ){ ds@1952: /* The cell may contain a pointer to an overflow page. If so, write ds@1952: ** the entry for the overflow page into the pointer map. ds@1952: */ ds@1952: CellInfo info; ds@1952: sqlite3BtreeParseCellPtr(pPage, pCell, &info); ds@1952: assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload ); ds@1952: if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){ ds@1952: Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]); ds@1952: rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno); ds@1952: if( rc!=SQLITE_OK ) return rc; ds@1952: } ds@1952: } ds@1952: #endif ds@1952: } ds@1952: ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Add a list of cells to a page. The page should be initially empty. ds@1952: ** The cells are guaranteed to fit on the page. ds@1952: */ ds@1952: static void assemblePage( ds@1952: MemPage *pPage, /* The page to be assemblied */ ds@1952: int nCell, /* The number of cells to add to this page */ ds@1952: u8 **apCell, /* Pointers to cell bodies */ ds@1952: int *aSize /* Sizes of the cells */ ds@1952: ){ ds@1952: int i; /* Loop counter */ ds@1952: int totalSize; /* Total size of all cells */ ds@1952: int hdr; /* Index of page header */ ds@1952: int cellptr; /* Address of next cell pointer */ ds@1952: int cellbody; /* Address of next cell body */ ds@1952: u8 *data; /* Data for the page */ ds@1952: ds@1952: assert( pPage->nOverflow==0 ); ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: totalSize = 0; ds@1952: for(i=0; inFree ); ds@1952: assert( pPage->nCell==0 ); ds@1952: cellptr = pPage->cellOffset; ds@1952: data = pPage->aData; ds@1952: hdr = pPage->hdrOffset; ds@1952: put2byte(&data[hdr+3], nCell); ds@1952: if( nCell ){ ds@1952: cellbody = allocateSpace(pPage, totalSize); ds@1952: assert( cellbody>0 ); ds@1952: assert( pPage->nFree >= 2*nCell ); ds@1952: pPage->nFree -= 2*nCell; ds@1952: for(i=0; ipBt->usableSize ); ds@1952: } ds@1952: pPage->nCell = nCell; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** The following parameters determine how many adjacent pages get involved ds@1952: ** in a balancing operation. NN is the number of neighbors on either side ds@1952: ** of the page that participate in the balancing operation. NB is the ds@1952: ** total number of pages that participate, including the target page and ds@1952: ** NN neighbors on either side. ds@1952: ** ds@1952: ** The minimum value of NN is 1 (of course). Increasing NN above 1 ds@1952: ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance ds@1952: ** in exchange for a larger degradation in INSERT and UPDATE performance. ds@1952: ** The value of NN appears to give the best results overall. ds@1952: */ ds@1952: #define NN 1 /* Number of neighbors on either side of pPage */ ds@1952: #define NB (NN*2+1) /* Total pages involved in the balance */ ds@1952: ds@1952: /* Forward reference */ ds@1952: static int balance(MemPage*, int); ds@1952: ds@1952: #ifndef SQLITE_OMIT_QUICKBALANCE ds@1952: /* ds@1952: ** This version of balance() handles the common special case where ds@1952: ** a new entry is being inserted on the extreme right-end of the ds@1952: ** tree, in other words, when the new entry will become the largest ds@1952: ** entry in the tree. ds@1952: ** ds@1952: ** Instead of trying balance the 3 right-most leaf pages, just add ds@1952: ** a new page to the right-hand side and put the one new entry in ds@1952: ** that page. This leaves the right side of the tree somewhat ds@1952: ** unbalanced. But odds are that we will be inserting new entries ds@1952: ** at the end soon afterwards so the nearly empty page will quickly ds@1952: ** fill up. On average. ds@1952: ** ds@1952: ** pPage is the leaf page which is the right-most page in the tree. ds@1952: ** pParent is its parent. pPage must have a single overflow entry ds@1952: ** which is also the right-most entry on the page. ds@1952: */ ds@1952: static int balance_quick(MemPage *pPage, MemPage *pParent){ ds@1952: int rc; ds@1952: MemPage *pNew; ds@1952: Pgno pgnoNew; ds@1952: u8 *pCell; ds@1952: int szCell; ds@1952: CellInfo info; ds@1952: BtShared *pBt = pPage->pBt; ds@1952: int parentIdx = pParent->nCell; /* pParent new divider cell index */ ds@1952: int parentSize; /* Size of new divider cell */ ds@1952: u8 parentCell[64]; /* Space for the new divider cell */ ds@1952: ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: ds@1952: /* Allocate a new page. Insert the overflow cell from pPage ds@1952: ** into it. Then remove the overflow cell from pPage. ds@1952: */ ds@1952: rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: pCell = pPage->aOvfl[0].pCell; ds@1952: szCell = cellSizePtr(pPage, pCell); ds@1952: zeroPage(pNew, pPage->aData[0]); ds@1952: assemblePage(pNew, 1, &pCell, &szCell); ds@1952: pPage->nOverflow = 0; ds@1952: ds@1952: /* Set the parent of the newly allocated page to pParent. */ ds@1952: pNew->pParent = pParent; ds@1952: sqlite3PagerRef(pParent->pDbPage); ds@1952: ds@1952: /* pPage is currently the right-child of pParent. Change this ds@1952: ** so that the right-child is the new page allocated above and ds@1952: ** pPage is the next-to-right child. ds@1952: */ ds@1952: assert( pPage->nCell>0 ); ds@1952: pCell = findCell(pPage, pPage->nCell-1); ds@1952: sqlite3BtreeParseCellPtr(pPage, pCell, &info); ds@1952: rc = fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: assert( parentSize<64 ); ds@1952: rc = insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno); ds@1952: put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew); ds@1952: ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: /* If this is an auto-vacuum database, update the pointer map ds@1952: ** with entries for the new page, and any pointer from the ds@1952: ** cell on the page to an overflow page. ds@1952: */ ds@1952: if( pBt->autoVacuum ){ ds@1952: rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno); ds@1952: if( rc==SQLITE_OK ){ ds@1952: rc = ptrmapPutOvfl(pNew, 0); ds@1952: } ds@1952: if( rc!=SQLITE_OK ){ ds@1952: releasePage(pNew); ds@1952: return rc; ds@1952: } ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* Release the reference to the new page and balance the parent page, ds@1952: ** in case the divider cell inserted caused it to become overfull. ds@1952: */ ds@1952: releasePage(pNew); ds@1952: return balance(pParent, 0); ds@1952: } ds@1952: #endif /* SQLITE_OMIT_QUICKBALANCE */ ds@1952: ds@1952: /* ds@1952: ** This routine redistributes Cells on pPage and up to NN*2 siblings ds@1952: ** of pPage so that all pages have about the same amount of free space. ds@1952: ** Usually NN siblings on either side of pPage is used in the balancing, ds@1952: ** though more siblings might come from one side if pPage is the first ds@1952: ** or last child of its parent. If pPage has fewer than 2*NN siblings ds@1952: ** (something which can only happen if pPage is the root page or a ds@1952: ** child of root) then all available siblings participate in the balancing. ds@1952: ** ds@1952: ** The number of siblings of pPage might be increased or decreased by one or ds@1952: ** two in an effort to keep pages nearly full but not over full. The root page ds@1952: ** is special and is allowed to be nearly empty. If pPage is ds@1952: ** the root page, then the depth of the tree might be increased ds@1952: ** or decreased by one, as necessary, to keep the root page from being ds@1952: ** overfull or completely empty. ds@1952: ** ds@1952: ** Note that when this routine is called, some of the Cells on pPage ds@1952: ** might not actually be stored in pPage->aData[]. This can happen ds@1952: ** if the page is overfull. Part of the job of this routine is to ds@1952: ** make sure all Cells for pPage once again fit in pPage->aData[]. ds@1952: ** ds@1952: ** In the course of balancing the siblings of pPage, the parent of pPage ds@1952: ** might become overfull or underfull. If that happens, then this routine ds@1952: ** is called recursively on the parent. ds@1952: ** ds@1952: ** If this routine fails for any reason, it might leave the database ds@1952: ** in a corrupted state. So if this routine fails, the database should ds@1952: ** be rolled back. ds@1952: */ ds@1952: static int balance_nonroot(MemPage *pPage){ ds@1952: MemPage *pParent; /* The parent of pPage */ ds@1952: BtShared *pBt; /* The whole database */ ds@1952: int nCell = 0; /* Number of cells in apCell[] */ ds@1952: int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */ ds@1952: int nOld; /* Number of pages in apOld[] */ ds@1952: int nNew; /* Number of pages in apNew[] */ ds@1952: int nDiv; /* Number of cells in apDiv[] */ ds@1952: int i, j, k; /* Loop counters */ ds@1952: int idx; /* Index of pPage in pParent->aCell[] */ ds@1952: int nxDiv; /* Next divider slot in pParent->aCell[] */ ds@1952: int rc; /* The return code */ ds@1952: int leafCorrection; /* 4 if pPage is a leaf. 0 if not */ ds@1952: int leafData; /* True if pPage is a leaf of a LEAFDATA tree */ ds@1952: int usableSpace; /* Bytes in pPage beyond the header */ ds@1952: int pageFlags; /* Value of pPage->aData[0] */ ds@1952: int subtotal; /* Subtotal of bytes in cells on one page */ ds@1952: int iSpace = 0; /* First unused byte of aSpace[] */ ds@1952: MemPage *apOld[NB]; /* pPage and up to two siblings */ ds@1952: Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */ ds@1952: MemPage *apCopy[NB]; /* Private copies of apOld[] pages */ ds@1952: MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */ ds@1952: Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */ ds@1952: u8 *apDiv[NB]; /* Divider cells in pParent */ ds@1952: int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */ ds@1952: int szNew[NB+2]; /* Combined size of cells place on i-th page */ ds@1952: u8 **apCell = 0; /* All cells begin balanced */ ds@1952: int *szCell; /* Local size of all cells in apCell[] */ ds@1952: u8 *aCopy[NB]; /* Space for holding data of apCopy[] */ ds@1952: u8 *aSpace; /* Space to hold copies of dividers cells */ ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: u8 *aFrom = 0; ds@1952: #endif ds@1952: ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: ds@1952: /* ds@1952: ** Find the parent page. ds@1952: */ ds@1952: assert( pPage->isInit ); ds@1952: assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 ); ds@1952: pBt = pPage->pBt; ds@1952: pParent = pPage->pParent; ds@1952: assert( pParent ); ds@1952: if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){ ds@1952: return rc; ds@1952: } ds@1952: TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno)); ds@1952: ds@1952: #ifndef SQLITE_OMIT_QUICKBALANCE ds@1952: /* ds@1952: ** A special case: If a new entry has just been inserted into a ds@1952: ** table (that is, a btree with integer keys and all data at the leaves) ds@1952: ** and the new entry is the right-most entry in the tree (it has the ds@1952: ** largest key) then use the special balance_quick() routine for ds@1952: ** balancing. balance_quick() is much faster and results in a tighter ds@1952: ** packing of data in the common case. ds@1952: */ ds@1952: if( pPage->leaf && ds@1952: pPage->intKey && ds@1952: pPage->leafData && ds@1952: pPage->nOverflow==1 && ds@1952: pPage->aOvfl[0].idx==pPage->nCell && ds@1952: pPage->pParent->pgno!=1 && ds@1952: get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno ds@1952: ){ ds@1952: /* ds@1952: ** TODO: Check the siblings to the left of pPage. It may be that ds@1952: ** they are not full and no new page is required. ds@1952: */ ds@1952: return balance_quick(pPage, pParent); ds@1952: } ds@1952: #endif ds@1952: ds@1952: if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){ ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Find the cell in the parent page whose left child points back ds@1952: ** to pPage. The "idx" variable is the index of that cell. If pPage ds@1952: ** is the rightmost child of pParent then set idx to pParent->nCell ds@1952: */ ds@1952: if( pParent->idxShift ){ ds@1952: Pgno pgno; ds@1952: pgno = pPage->pgno; ds@1952: assert( pgno==sqlite3PagerPagenumber(pPage->pDbPage) ); ds@1952: for(idx=0; idxnCell; idx++){ ds@1952: if( get4byte(findCell(pParent, idx))==pgno ){ ds@1952: break; ds@1952: } ds@1952: } ds@1952: assert( idxnCell ds@1952: || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno ); ds@1952: }else{ ds@1952: idx = pPage->idxParent; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Initialize variables so that it will be safe to jump ds@1952: ** directly to balance_cleanup at any moment. ds@1952: */ ds@1952: nOld = nNew = 0; ds@1952: sqlite3PagerRef(pParent->pDbPage); ds@1952: ds@1952: /* ds@1952: ** Find sibling pages to pPage and the cells in pParent that divide ds@1952: ** the siblings. An attempt is made to find NN siblings on either ds@1952: ** side of pPage. More siblings are taken from one side, however, if ds@1952: ** pPage there are fewer than NN siblings on the other side. If pParent ds@1952: ** has NB or fewer children then all children of pParent are taken. ds@1952: */ ds@1952: nxDiv = idx - NN; ds@1952: if( nxDiv + NB > pParent->nCell ){ ds@1952: nxDiv = pParent->nCell - NB + 1; ds@1952: } ds@1952: if( nxDiv<0 ){ ds@1952: nxDiv = 0; ds@1952: } ds@1952: nDiv = 0; ds@1952: for(i=0, k=nxDiv; inCell ){ ds@1952: apDiv[i] = findCell(pParent, k); ds@1952: nDiv++; ds@1952: assert( !pParent->leaf ); ds@1952: pgnoOld[i] = get4byte(apDiv[i]); ds@1952: }else if( k==pParent->nCell ){ ds@1952: pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]); ds@1952: }else{ ds@1952: break; ds@1952: } ds@1952: rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent); ds@1952: if( rc ) goto balance_cleanup; ds@1952: apOld[i]->idxParent = k; ds@1952: apCopy[i] = 0; ds@1952: assert( i==nOld ); ds@1952: nOld++; ds@1952: nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow; ds@1952: } ds@1952: ds@1952: /* Make nMaxCells a multiple of 2 in order to preserve 8-byte ds@1952: ** alignment */ ds@1952: nMaxCells = (nMaxCells + 1)&~1; ds@1952: ds@1952: /* ds@1952: ** Allocate space for memory structures ds@1952: */ ds@1952: apCell = sqlite3_malloc( ds@1952: nMaxCells*sizeof(u8*) /* apCell */ ds@1952: + nMaxCells*sizeof(int) /* szCell */ ds@1952: + ROUND8(sizeof(MemPage))*NB /* aCopy */ ds@1952: + pBt->pageSize*(5+NB) /* aSpace */ ds@1952: + (ISAUTOVACUUM ? nMaxCells : 0) /* aFrom */ ds@1952: ); ds@1952: if( apCell==0 ){ ds@1952: rc = SQLITE_NOMEM; ds@1952: goto balance_cleanup; ds@1952: } ds@1952: szCell = (int*)&apCell[nMaxCells]; ds@1952: aCopy[0] = (u8*)&szCell[nMaxCells]; ds@1952: assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */ ds@1952: for(i=1; ipageSize+ROUND8(sizeof(MemPage))]; ds@1952: assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */ ds@1952: } ds@1952: aSpace = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))]; ds@1952: assert( ((aSpace - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */ ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: if( pBt->autoVacuum ){ ds@1952: aFrom = &aSpace[5*pBt->pageSize]; ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* ds@1952: ** Make copies of the content of pPage and its siblings into aOld[]. ds@1952: ** The rest of this function will use data from the copies rather ds@1952: ** that the original pages since the original pages will be in the ds@1952: ** process of being overwritten. ds@1952: */ ds@1952: for(i=0; iaData = (void*)&p[1]; ds@1952: memcpy(p->aData, apOld[i]->aData, pBt->pageSize); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Load pointers to all cells on sibling pages and the divider cells ds@1952: ** into the local apCell[] array. Make copies of the divider cells ds@1952: ** into space obtained form aSpace[] and remove the the divider Cells ds@1952: ** from pParent. ds@1952: ** ds@1952: ** If the siblings are on leaf pages, then the child pointers of the ds@1952: ** divider cells are stripped from the cells before they are copied ds@1952: ** into aSpace[]. In this way, all cells in apCell[] are without ds@1952: ** child pointers. If siblings are not leaves, then all cell in ds@1952: ** apCell[] include child pointers. Either way, all cells in apCell[] ds@1952: ** are alike. ds@1952: ** ds@1952: ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf. ds@1952: ** leafData: 1 if pPage holds key+data and pParent holds only keys. ds@1952: */ ds@1952: nCell = 0; ds@1952: leafCorrection = pPage->leaf*4; ds@1952: leafData = pPage->leafData && pPage->leaf; ds@1952: for(i=0; inCell+pOld->nOverflow; ds@1952: for(j=0; jautoVacuum ){ ds@1952: int a; ds@1952: aFrom[nCell] = i; ds@1952: for(a=0; anOverflow; a++){ ds@1952: if( pOld->aOvfl[a].pCell==apCell[nCell] ){ ds@1952: aFrom[nCell] = 0xFF; ds@1952: break; ds@1952: } ds@1952: } ds@1952: } ds@1952: #endif ds@1952: nCell++; ds@1952: } ds@1952: if( ipageSize*5 ); ds@1952: memcpy(pTemp, apDiv[i], sz); ds@1952: apCell[nCell] = pTemp+leafCorrection; ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: if( pBt->autoVacuum ){ ds@1952: aFrom[nCell] = 0xFF; ds@1952: } ds@1952: #endif ds@1952: dropCell(pParent, nxDiv, sz); ds@1952: szCell[nCell] -= leafCorrection; ds@1952: assert( get4byte(pTemp)==pgnoOld[i] ); ds@1952: if( !pOld->leaf ){ ds@1952: assert( leafCorrection==0 ); ds@1952: /* The right pointer of the child page pOld becomes the left ds@1952: ** pointer of the divider cell */ ds@1952: memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4); ds@1952: }else{ ds@1952: assert( leafCorrection==4 ); ds@1952: if( szCell[nCell]<4 ){ ds@1952: /* Do not allow any cells smaller than 4 bytes. */ ds@1952: szCell[nCell] = 4; ds@1952: } ds@1952: } ds@1952: nCell++; ds@1952: } ds@1952: } ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Figure out the number of pages needed to hold all nCell cells. ds@1952: ** Store this number in "k". Also compute szNew[] which is the total ds@1952: ** size of all cells on the i-th page and cntNew[] which is the index ds@1952: ** in apCell[] of the cell that divides page i from page i+1. ds@1952: ** cntNew[k] should equal nCell. ds@1952: ** ds@1952: ** Values computed by this block: ds@1952: ** ds@1952: ** k: The total number of sibling pages ds@1952: ** szNew[i]: Spaced used on the i-th sibling page. ds@1952: ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to ds@1952: ** the right of the i-th sibling page. ds@1952: ** usableSpace: Number of bytes of space available on each sibling. ds@1952: ** ds@1952: */ ds@1952: usableSpace = pBt->usableSize - 12 + leafCorrection; ds@1952: for(subtotal=k=i=0; i usableSpace ){ ds@1952: szNew[k] = subtotal - szCell[i]; ds@1952: cntNew[k] = i; ds@1952: if( leafData ){ i--; } ds@1952: subtotal = 0; ds@1952: k++; ds@1952: } ds@1952: } ds@1952: szNew[k] = subtotal; ds@1952: cntNew[k] = nCell; ds@1952: k++; ds@1952: ds@1952: /* ds@1952: ** The packing computed by the previous block is biased toward the siblings ds@1952: ** on the left side. The left siblings are always nearly full, while the ds@1952: ** right-most sibling might be nearly empty. This block of code attempts ds@1952: ** to adjust the packing of siblings to get a better balance. ds@1952: ** ds@1952: ** This adjustment is more than an optimization. The packing above might ds@1952: ** be so out of balance as to be illegal. For example, the right-most ds@1952: ** sibling might be completely empty. This adjustment is not optional. ds@1952: */ ds@1952: for(i=k-1; i>0; i--){ ds@1952: int szRight = szNew[i]; /* Size of sibling on the right */ ds@1952: int szLeft = szNew[i-1]; /* Size of sibling on the left */ ds@1952: int r; /* Index of right-most cell in left sibling */ ds@1952: int d; /* Index of first cell to the left of right sibling */ ds@1952: ds@1952: r = cntNew[i-1] - 1; ds@1952: d = r + 1 - leafData; ds@1952: assert( d0) or we are the ds@1952: ** a virtual root page. A virtual root page is when the real root ds@1952: ** page is page 1 and we are the only child of that page. ds@1952: */ ds@1952: assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) ); ds@1952: ds@1952: /* ds@1952: ** Allocate k new pages. Reuse old pages where possible. ds@1952: */ ds@1952: assert( pPage->pgno>1 ); ds@1952: pageFlags = pPage->aData[0]; ds@1952: for(i=0; ipDbPage); ds@1952: nNew++; ds@1952: if( rc ) goto balance_cleanup; ds@1952: }else{ ds@1952: assert( i>0 ); ds@1952: rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0); ds@1952: if( rc ) goto balance_cleanup; ds@1952: apNew[i] = pNew; ds@1952: nNew++; ds@1952: } ds@1952: zeroPage(pNew, pageFlags); ds@1952: } ds@1952: ds@1952: /* Free any old pages that were not reused as new pages. ds@1952: */ ds@1952: while( ii ){ ds@1952: int t; ds@1952: MemPage *pT; ds@1952: t = pgnoNew[i]; ds@1952: pT = apNew[i]; ds@1952: pgnoNew[i] = pgnoNew[minI]; ds@1952: apNew[i] = apNew[minI]; ds@1952: pgnoNew[minI] = t; ds@1952: apNew[minI] = pT; ds@1952: } ds@1952: } ds@1952: TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n", ds@1952: pgnoOld[0], ds@1952: nOld>=2 ? pgnoOld[1] : 0, ds@1952: nOld>=3 ? pgnoOld[2] : 0, ds@1952: pgnoNew[0], szNew[0], ds@1952: nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0, ds@1952: nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0, ds@1952: nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0, ds@1952: nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0)); ds@1952: ds@1952: /* ds@1952: ** Evenly distribute the data in apCell[] across the new pages. ds@1952: ** Insert divider cells into pParent as necessary. ds@1952: */ ds@1952: j = 0; ds@1952: for(i=0; ipgno==pgnoNew[i] ); ds@1952: assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]); ds@1952: assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) ); ds@1952: assert( pNew->nOverflow==0 ); ds@1952: ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: /* If this is an auto-vacuum database, update the pointer map entries ds@1952: ** that point to the siblings that were rearranged. These can be: left ds@1952: ** children of cells, the right-child of the page, or overflow pages ds@1952: ** pointed to by cells. ds@1952: */ ds@1952: if( pBt->autoVacuum ){ ds@1952: for(k=j; kpgno!=pNew->pgno ){ ds@1952: rc = ptrmapPutOvfl(pNew, k-j); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: goto balance_cleanup; ds@1952: } ds@1952: } ds@1952: } ds@1952: } ds@1952: #endif ds@1952: ds@1952: j = cntNew[i]; ds@1952: ds@1952: /* If the sibling page assembled above was not the right-most sibling, ds@1952: ** insert a divider cell into the parent page. ds@1952: */ ds@1952: if( ileaf ){ ds@1952: memcpy(&pNew->aData[8], pCell, 4); ds@1952: pTemp = 0; ds@1952: }else if( leafData ){ ds@1952: /* If the tree is a leaf-data tree, and the siblings are leaves, ds@1952: ** then there is no divider cell in apCell[]. Instead, the divider ds@1952: ** cell consists of the integer key for the right-most cell of ds@1952: ** the sibling-page assembled above only. ds@1952: */ ds@1952: CellInfo info; ds@1952: j--; ds@1952: sqlite3BtreeParseCellPtr(pNew, apCell[j], &info); ds@1952: pCell = &aSpace[iSpace]; ds@1952: fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz); ds@1952: iSpace += sz; ds@1952: assert( iSpace<=pBt->pageSize*5 ); ds@1952: pTemp = 0; ds@1952: }else{ ds@1952: pCell -= 4; ds@1952: pTemp = &aSpace[iSpace]; ds@1952: iSpace += sz; ds@1952: assert( iSpace<=pBt->pageSize*5 ); ds@1952: /* Obscure case for non-leaf-data trees: If the cell at pCell was ds@1952: ** previously stored on a leaf node, and it's reported size was 4 ds@1952: ** bytes, then it may actually be smaller than this ds@1952: ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of ds@1952: ** any cell). But it's important to pass the correct size to ds@1952: ** insertCell(), so reparse the cell now. ds@1952: ** ds@1952: ** Note that this can never happen in an SQLite data file, as all ds@1952: ** cells are at least 4 bytes. It only happens in b-trees used ds@1952: ** to evaluate "IN (SELECT ...)" and similar clauses. ds@1952: */ ds@1952: if( szCell[j]==4 ){ ds@1952: assert(leafCorrection==4); ds@1952: sz = cellSizePtr(pParent, pCell); ds@1952: } ds@1952: } ds@1952: rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4); ds@1952: if( rc!=SQLITE_OK ) goto balance_cleanup; ds@1952: put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno); ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: /* If this is an auto-vacuum database, and not a leaf-data tree, ds@1952: ** then update the pointer map with an entry for the overflow page ds@1952: ** that the cell just inserted points to (if any). ds@1952: */ ds@1952: if( pBt->autoVacuum && !leafData ){ ds@1952: rc = ptrmapPutOvfl(pParent, nxDiv); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: goto balance_cleanup; ds@1952: } ds@1952: } ds@1952: #endif ds@1952: j++; ds@1952: nxDiv++; ds@1952: } ds@1952: } ds@1952: assert( j==nCell ); ds@1952: assert( nOld>0 ); ds@1952: assert( nNew>0 ); ds@1952: if( (pageFlags & PTF_LEAF)==0 ){ ds@1952: memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4); ds@1952: } ds@1952: if( nxDiv==pParent->nCell+pParent->nOverflow ){ ds@1952: /* Right-most sibling is the right-most child of pParent */ ds@1952: put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]); ds@1952: }else{ ds@1952: /* Right-most sibling is the left child of the first entry in pParent ds@1952: ** past the right-most divider entry */ ds@1952: put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Reparent children of all cells. ds@1952: */ ds@1952: for(i=0; iisInit ); ds@1952: rc = balance(pParent, 0); ds@1952: ds@1952: /* ds@1952: ** Cleanup before returning. ds@1952: */ ds@1952: balance_cleanup: ds@1952: sqlite3_free(apCell); ds@1952: for(i=0; ipgno, nOld, nNew, nCell)); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine is called for the root page of a btree when the root ds@1952: ** page contains no cells. This is an opportunity to make the tree ds@1952: ** shallower by one level. ds@1952: */ ds@1952: static int balance_shallower(MemPage *pPage){ ds@1952: MemPage *pChild; /* The only child page of pPage */ ds@1952: Pgno pgnoChild; /* Page number for pChild */ ds@1952: int rc = SQLITE_OK; /* Return code from subprocedures */ ds@1952: BtShared *pBt; /* The main BTree structure */ ds@1952: int mxCellPerPage; /* Maximum number of cells per page */ ds@1952: u8 **apCell; /* All cells from pages being balanced */ ds@1952: int *szCell; /* Local size of all cells */ ds@1952: ds@1952: assert( pPage->pParent==0 ); ds@1952: assert( pPage->nCell==0 ); ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: pBt = pPage->pBt; ds@1952: mxCellPerPage = MX_CELL(pBt); ds@1952: apCell = sqlite3_malloc( mxCellPerPage*(sizeof(u8*)+sizeof(int)) ); ds@1952: if( apCell==0 ) return SQLITE_NOMEM; ds@1952: szCell = (int*)&apCell[mxCellPerPage]; ds@1952: if( pPage->leaf ){ ds@1952: /* The table is completely empty */ ds@1952: TRACE(("BALANCE: empty table %d\n", pPage->pgno)); ds@1952: }else{ ds@1952: /* The root page is empty but has one child. Transfer the ds@1952: ** information from that one child into the root page if it ds@1952: ** will fit. This reduces the depth of the tree by one. ds@1952: ** ds@1952: ** If the root page is page 1, it has less space available than ds@1952: ** its child (due to the 100 byte header that occurs at the beginning ds@1952: ** of the database fle), so it might not be able to hold all of the ds@1952: ** information currently contained in the child. If this is the ds@1952: ** case, then do not do the transfer. Leave page 1 empty except ds@1952: ** for the right-pointer to the child page. The child page becomes ds@1952: ** the virtual root of the tree. ds@1952: */ ds@1952: pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]); ds@1952: assert( pgnoChild>0 ); ds@1952: assert( pgnoChild<=sqlite3PagerPagecount(pPage->pBt->pPager) ); ds@1952: rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0); ds@1952: if( rc ) goto end_shallow_balance; ds@1952: if( pPage->pgno==1 ){ ds@1952: rc = sqlite3BtreeInitPage(pChild, pPage); ds@1952: if( rc ) goto end_shallow_balance; ds@1952: assert( pChild->nOverflow==0 ); ds@1952: if( pChild->nFree>=100 ){ ds@1952: /* The child information will fit on the root page, so do the ds@1952: ** copy */ ds@1952: int i; ds@1952: zeroPage(pPage, pChild->aData[0]); ds@1952: for(i=0; inCell; i++){ ds@1952: apCell[i] = findCell(pChild,i); ds@1952: szCell[i] = cellSizePtr(pChild, apCell[i]); ds@1952: } ds@1952: assemblePage(pPage, pChild->nCell, apCell, szCell); ds@1952: /* Copy the right-pointer of the child to the parent. */ ds@1952: put4byte(&pPage->aData[pPage->hdrOffset+8], ds@1952: get4byte(&pChild->aData[pChild->hdrOffset+8])); ds@1952: freePage(pChild); ds@1952: TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno)); ds@1952: }else{ ds@1952: /* The child has more information that will fit on the root. ds@1952: ** The tree is already balanced. Do nothing. */ ds@1952: TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno)); ds@1952: } ds@1952: }else{ ds@1952: memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize); ds@1952: pPage->isInit = 0; ds@1952: pPage->pParent = 0; ds@1952: rc = sqlite3BtreeInitPage(pPage, 0); ds@1952: assert( rc==SQLITE_OK ); ds@1952: freePage(pChild); ds@1952: TRACE(("BALANCE: transfer child %d into root %d\n", ds@1952: pChild->pgno, pPage->pgno)); ds@1952: } ds@1952: rc = reparentChildPages(pPage); ds@1952: assert( pPage->nOverflow==0 ); ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: if( pBt->autoVacuum ){ ds@1952: int i; ds@1952: for(i=0; inCell; i++){ ds@1952: rc = ptrmapPutOvfl(pPage, i); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: goto end_shallow_balance; ds@1952: } ds@1952: } ds@1952: } ds@1952: #endif ds@1952: releasePage(pChild); ds@1952: } ds@1952: end_shallow_balance: ds@1952: sqlite3_free(apCell); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** The root page is overfull ds@1952: ** ds@1952: ** When this happens, Create a new child page and copy the ds@1952: ** contents of the root into the child. Then make the root ds@1952: ** page an empty page with rightChild pointing to the new ds@1952: ** child. Finally, call balance_internal() on the new child ds@1952: ** to cause it to split. ds@1952: */ ds@1952: static int balance_deeper(MemPage *pPage){ ds@1952: int rc; /* Return value from subprocedures */ ds@1952: MemPage *pChild; /* Pointer to a new child page */ ds@1952: Pgno pgnoChild; /* Page number of the new child page */ ds@1952: BtShared *pBt; /* The BTree */ ds@1952: int usableSize; /* Total usable size of a page */ ds@1952: u8 *data; /* Content of the parent page */ ds@1952: u8 *cdata; /* Content of the child page */ ds@1952: int hdr; /* Offset to page header in parent */ ds@1952: int brk; /* Offset to content of first cell in parent */ ds@1952: ds@1952: assert( pPage->pParent==0 ); ds@1952: assert( pPage->nOverflow>0 ); ds@1952: pBt = pPage->pBt; ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0); ds@1952: if( rc ) return rc; ds@1952: assert( sqlite3PagerIswriteable(pChild->pDbPage) ); ds@1952: usableSize = pBt->usableSize; ds@1952: data = pPage->aData; ds@1952: hdr = pPage->hdrOffset; ds@1952: brk = get2byte(&data[hdr+5]); ds@1952: cdata = pChild->aData; ds@1952: memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr); ds@1952: memcpy(&cdata[brk], &data[brk], usableSize-brk); ds@1952: assert( pChild->isInit==0 ); ds@1952: rc = sqlite3BtreeInitPage(pChild, pPage); ds@1952: if( rc ) goto balancedeeper_out; ds@1952: memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0])); ds@1952: pChild->nOverflow = pPage->nOverflow; ds@1952: if( pChild->nOverflow ){ ds@1952: pChild->nFree = 0; ds@1952: } ds@1952: assert( pChild->nCell==pPage->nCell ); ds@1952: zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF); ds@1952: put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild); ds@1952: TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno)); ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: if( pBt->autoVacuum ){ ds@1952: int i; ds@1952: rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno); ds@1952: if( rc ) goto balancedeeper_out; ds@1952: for(i=0; inCell; i++){ ds@1952: rc = ptrmapPutOvfl(pChild, i); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: } ds@1952: } ds@1952: #endif ds@1952: rc = balance_nonroot(pChild); ds@1952: ds@1952: balancedeeper_out: ds@1952: releasePage(pChild); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Decide if the page pPage needs to be balanced. If balancing is ds@1952: ** required, call the appropriate balancing routine. ds@1952: */ ds@1952: static int balance(MemPage *pPage, int insert){ ds@1952: int rc = SQLITE_OK; ds@1952: assert( sqlite3_mutex_held(pPage->pBt->mutex) ); ds@1952: if( pPage->pParent==0 ){ ds@1952: rc = sqlite3PagerWrite(pPage->pDbPage); ds@1952: if( rc==SQLITE_OK && pPage->nOverflow>0 ){ ds@1952: rc = balance_deeper(pPage); ds@1952: } ds@1952: if( rc==SQLITE_OK && pPage->nCell==0 ){ ds@1952: rc = balance_shallower(pPage); ds@1952: } ds@1952: }else{ ds@1952: if( pPage->nOverflow>0 || ds@1952: (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){ ds@1952: rc = balance_nonroot(pPage); ds@1952: } ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This routine checks all cursors that point to table pgnoRoot. ds@1952: ** If any of those cursors were opened with wrFlag==0 in a different ds@1952: ** database connection (a database connection that shares the pager ds@1952: ** cache with the current connection) and that other connection ds@1952: ** is not in the ReadUncommmitted state, then this routine returns ds@1952: ** SQLITE_LOCKED. ds@1952: ** ds@1952: ** In addition to checking for read-locks (where a read-lock ds@1952: ** means a cursor opened with wrFlag==0) this routine also moves ds@1952: ** all write cursors so that they are pointing to the ds@1952: ** first Cell on the root page. This is necessary because an insert ds@1952: ** or delete might change the number of cells on a page or delete ds@1952: ** a page entirely and we do not want to leave any cursors ds@1952: ** pointing to non-existant pages or cells. ds@1952: */ ds@1952: static int checkReadLocks(Btree *pBtree, Pgno pgnoRoot, BtCursor *pExclude){ ds@1952: BtCursor *p; ds@1952: BtShared *pBt = pBtree->pBt; ds@1952: sqlite3 *db = pBtree->pSqlite; ds@1952: assert( sqlite3BtreeHoldsMutex(pBtree) ); ds@1952: for(p=pBt->pCursor; p; p=p->pNext){ ds@1952: if( p==pExclude ) continue; ds@1952: if( p->eState!=CURSOR_VALID ) continue; ds@1952: if( p->pgnoRoot!=pgnoRoot ) continue; ds@1952: if( p->wrFlag==0 ){ ds@1952: sqlite3 *dbOther = p->pBtree->pSqlite; ds@1952: if( dbOther==0 || ds@1952: (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){ ds@1952: return SQLITE_LOCKED; ds@1952: } ds@1952: }else if( p->pPage->pgno!=p->pgnoRoot ){ ds@1952: moveToRoot(p); ds@1952: } ds@1952: } ds@1952: return SQLITE_OK; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Insert a new record into the BTree. The key is given by (pKey,nKey) ds@1952: ** and the data is given by (pData,nData). The cursor is used only to ds@1952: ** define what table the record should be inserted into. The cursor ds@1952: ** is left pointing at a random location. ds@1952: ** ds@1952: ** For an INTKEY table, only the nKey value of the key is used. pKey is ds@1952: ** ignored. For a ZERODATA table, the pData and nData are both ignored. ds@1952: */ ds@1952: int sqlite3BtreeInsert( ds@1952: BtCursor *pCur, /* Insert data into the table of this cursor */ ds@1952: const void *pKey, i64 nKey, /* The key of the new record */ ds@1952: const void *pData, int nData, /* The data of the new record */ ds@1952: int nZero, /* Number of extra 0 bytes to append to data */ ds@1952: int appendBias /* True if this is likely an append */ ds@1952: ){ ds@1952: int rc; ds@1952: int loc; ds@1952: int szNew; ds@1952: MemPage *pPage; ds@1952: Btree *p = pCur->pBtree; ds@1952: BtShared *pBt = p->pBt; ds@1952: unsigned char *oldCell; ds@1952: unsigned char *newCell = 0; ds@1952: ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: if( pBt->inTransaction!=TRANS_WRITE ){ ds@1952: /* Must start a transaction before doing an insert */ ds@1952: rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR; ds@1952: return rc; ds@1952: } ds@1952: assert( !pBt->readOnly ); ds@1952: if( !pCur->wrFlag ){ ds@1952: return SQLITE_PERM; /* Cursor not open for writing */ ds@1952: } ds@1952: if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){ ds@1952: return SQLITE_LOCKED; /* The table pCur points to has a read lock */ ds@1952: } ds@1952: if( pCur->eState==CURSOR_FAULT ){ ds@1952: return pCur->skip; ds@1952: } ds@1952: ds@1952: /* Save the positions of any other cursors open on this table */ ds@1952: clearCursorPosition(pCur); ds@1952: if( ds@1952: SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) || ds@1952: SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc)) ds@1952: ){ ds@1952: return rc; ds@1952: } ds@1952: ds@1952: pPage = pCur->pPage; ds@1952: assert( pPage->intKey || nKey>=0 ); ds@1952: assert( pPage->leaf || !pPage->leafData ); ds@1952: TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n", ds@1952: pCur->pgnoRoot, nKey, nData, pPage->pgno, ds@1952: loc==0 ? "overwrite" : "new entry")); ds@1952: assert( pPage->isInit ); ds@1952: newCell = sqlite3_malloc( MX_CELL_SIZE(pBt) ); ds@1952: if( newCell==0 ) return SQLITE_NOMEM; ds@1952: rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew); ds@1952: if( rc ) goto end_insert; ds@1952: assert( szNew==cellSizePtr(pPage, newCell) ); ds@1952: assert( szNew<=MX_CELL_SIZE(pBt) ); ds@1952: if( loc==0 && CURSOR_VALID==pCur->eState ){ ds@1952: int szOld; ds@1952: assert( pCur->idx>=0 && pCur->idxnCell ); ds@1952: rc = sqlite3PagerWrite(pPage->pDbPage); ds@1952: if( rc ){ ds@1952: goto end_insert; ds@1952: } ds@1952: oldCell = findCell(pPage, pCur->idx); ds@1952: if( !pPage->leaf ){ ds@1952: memcpy(newCell, oldCell, 4); ds@1952: } ds@1952: szOld = cellSizePtr(pPage, oldCell); ds@1952: rc = clearCell(pPage, oldCell); ds@1952: if( rc ) goto end_insert; ds@1952: dropCell(pPage, pCur->idx, szOld); ds@1952: }else if( loc<0 && pPage->nCell>0 ){ ds@1952: assert( pPage->leaf ); ds@1952: pCur->idx++; ds@1952: pCur->info.nSize = 0; ds@1952: }else{ ds@1952: assert( pPage->leaf ); ds@1952: } ds@1952: rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0); ds@1952: if( rc!=SQLITE_OK ) goto end_insert; ds@1952: rc = balance(pPage, 1); ds@1952: /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */ ds@1952: /* fflush(stdout); */ ds@1952: if( rc==SQLITE_OK ){ ds@1952: moveToRoot(pCur); ds@1952: } ds@1952: end_insert: ds@1952: sqlite3_free(newCell); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Delete the entry that the cursor is pointing to. The cursor ds@1952: ** is left pointing at a random location. ds@1952: */ ds@1952: int sqlite3BtreeDelete(BtCursor *pCur){ ds@1952: MemPage *pPage = pCur->pPage; ds@1952: unsigned char *pCell; ds@1952: int rc; ds@1952: Pgno pgnoChild = 0; ds@1952: Btree *p = pCur->pBtree; ds@1952: BtShared *pBt = p->pBt; ds@1952: ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: assert( pPage->isInit ); ds@1952: if( pBt->inTransaction!=TRANS_WRITE ){ ds@1952: /* Must start a transaction before doing a delete */ ds@1952: rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR; ds@1952: return rc; ds@1952: } ds@1952: assert( !pBt->readOnly ); ds@1952: if( pCur->eState==CURSOR_FAULT ){ ds@1952: return pCur->skip; ds@1952: } ds@1952: if( pCur->idx >= pPage->nCell ){ ds@1952: return SQLITE_ERROR; /* The cursor is not pointing to anything */ ds@1952: } ds@1952: if( !pCur->wrFlag ){ ds@1952: return SQLITE_PERM; /* Did not open this cursor for writing */ ds@1952: } ds@1952: if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){ ds@1952: return SQLITE_LOCKED; /* The table pCur points to has a read lock */ ds@1952: } ds@1952: ds@1952: /* Restore the current cursor position (a no-op if the cursor is not in ds@1952: ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors ds@1952: ** open on the same table. Then call sqlite3PagerWrite() on the page ds@1952: ** that the entry will be deleted from. ds@1952: */ ds@1952: if( ds@1952: (rc = restoreOrClearCursorPosition(pCur))!=0 || ds@1952: (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 || ds@1952: (rc = sqlite3PagerWrite(pPage->pDbPage))!=0 ds@1952: ){ ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* Locate the cell within it's page and leave pCell pointing to the ds@1952: ** data. The clearCell() call frees any overflow pages associated with the ds@1952: ** cell. The cell itself is still intact. ds@1952: */ ds@1952: pCell = findCell(pPage, pCur->idx); ds@1952: if( !pPage->leaf ){ ds@1952: pgnoChild = get4byte(pCell); ds@1952: } ds@1952: rc = clearCell(pPage, pCell); ds@1952: if( rc ){ ds@1952: return rc; ds@1952: } ds@1952: ds@1952: if( !pPage->leaf ){ ds@1952: /* ds@1952: ** The entry we are about to delete is not a leaf so if we do not ds@1952: ** do something we will leave a hole on an internal page. ds@1952: ** We have to fill the hole by moving in a cell from a leaf. The ds@1952: ** next Cell after the one to be deleted is guaranteed to exist and ds@1952: ** to be a leaf so we can use it. ds@1952: */ ds@1952: BtCursor leafCur; ds@1952: unsigned char *pNext; ds@1952: int szNext; /* The compiler warning is wrong: szNext is always ds@1952: ** initialized before use. Adding an extra initialization ds@1952: ** to silence the compiler slows down the code. */ ds@1952: int notUsed; ds@1952: unsigned char *tempCell = 0; ds@1952: assert( !pPage->leafData ); ds@1952: sqlite3BtreeGetTempCursor(pCur, &leafCur); ds@1952: rc = sqlite3BtreeNext(&leafCur, ¬Used); ds@1952: if( rc==SQLITE_OK ){ ds@1952: rc = sqlite3PagerWrite(leafCur.pPage->pDbPage); ds@1952: } ds@1952: if( rc==SQLITE_OK ){ ds@1952: TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n", ds@1952: pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno)); ds@1952: dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell)); ds@1952: pNext = findCell(leafCur.pPage, leafCur.idx); ds@1952: szNext = cellSizePtr(leafCur.pPage, pNext); ds@1952: assert( MX_CELL_SIZE(pBt)>=szNext+4 ); ds@1952: tempCell = sqlite3_malloc( MX_CELL_SIZE(pBt) ); ds@1952: if( tempCell==0 ){ ds@1952: rc = SQLITE_NOMEM; ds@1952: } ds@1952: } ds@1952: if( rc==SQLITE_OK ){ ds@1952: rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0); ds@1952: } ds@1952: if( rc==SQLITE_OK ){ ds@1952: put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild); ds@1952: rc = balance(pPage, 0); ds@1952: } ds@1952: if( rc==SQLITE_OK ){ ds@1952: dropCell(leafCur.pPage, leafCur.idx, szNext); ds@1952: rc = balance(leafCur.pPage, 0); ds@1952: } ds@1952: sqlite3_free(tempCell); ds@1952: sqlite3BtreeReleaseTempCursor(&leafCur); ds@1952: }else{ ds@1952: TRACE(("DELETE: table=%d delete from leaf %d\n", ds@1952: pCur->pgnoRoot, pPage->pgno)); ds@1952: dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell)); ds@1952: rc = balance(pPage, 0); ds@1952: } ds@1952: if( rc==SQLITE_OK ){ ds@1952: moveToRoot(pCur); ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Create a new BTree table. Write into *piTable the page ds@1952: ** number for the root page of the new table. ds@1952: ** ds@1952: ** The type of type is determined by the flags parameter. Only the ds@1952: ** following values of flags are currently in use. Other values for ds@1952: ** flags might not work: ds@1952: ** ds@1952: ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys ds@1952: ** BTREE_ZERODATA Used for SQL indices ds@1952: */ ds@1952: static int btreeCreateTable(Btree *p, int *piTable, int flags){ ds@1952: BtShared *pBt = p->pBt; ds@1952: MemPage *pRoot; ds@1952: Pgno pgnoRoot; ds@1952: int rc; ds@1952: ds@1952: assert( sqlite3BtreeHoldsMutex(p) ); ds@1952: if( pBt->inTransaction!=TRANS_WRITE ){ ds@1952: /* Must start a transaction first */ ds@1952: rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR; ds@1952: return rc; ds@1952: } ds@1952: assert( !pBt->readOnly ); ds@1952: ds@1952: #ifdef SQLITE_OMIT_AUTOVACUUM ds@1952: rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); ds@1952: if( rc ){ ds@1952: return rc; ds@1952: } ds@1952: #else ds@1952: if( pBt->autoVacuum ){ ds@1952: Pgno pgnoMove; /* Move a page here to make room for the root-page */ ds@1952: MemPage *pPageMove; /* The page to move to. */ ds@1952: ds@1952: /* Creating a new table may probably require moving an existing database ds@1952: ** to make room for the new tables root page. In case this page turns ds@1952: ** out to be an overflow page, delete all overflow page-map caches ds@1952: ** held by open cursors. ds@1952: */ ds@1952: invalidateAllOverflowCache(pBt); ds@1952: ds@1952: /* Read the value of meta[3] from the database to determine where the ds@1952: ** root page of the new table should go. meta[3] is the largest root-page ds@1952: ** created so far, so the new root-page is (meta[3]+1). ds@1952: */ ds@1952: rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: pgnoRoot++; ds@1952: ds@1952: /* The new root-page may not be allocated on a pointer-map page, or the ds@1952: ** PENDING_BYTE page. ds@1952: */ ds@1952: if( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) || ds@1952: pgnoRoot==PENDING_BYTE_PAGE(pBt) ){ ds@1952: pgnoRoot++; ds@1952: } ds@1952: assert( pgnoRoot>=3 ); ds@1952: ds@1952: /* Allocate a page. The page that currently resides at pgnoRoot will ds@1952: ** be moved to the allocated page (unless the allocated page happens ds@1952: ** to reside at pgnoRoot). ds@1952: */ ds@1952: rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: ds@1952: if( pgnoMove!=pgnoRoot ){ ds@1952: /* pgnoRoot is the page that will be used for the root-page of ds@1952: ** the new table (assuming an error did not occur). But we were ds@1952: ** allocated pgnoMove. If required (i.e. if it was not allocated ds@1952: ** by extending the file), the current page at position pgnoMove ds@1952: ** is already journaled. ds@1952: */ ds@1952: u8 eType; ds@1952: Pgno iPtrPage; ds@1952: ds@1952: releasePage(pPageMove); ds@1952: ds@1952: /* Move the page currently at pgnoRoot to pgnoMove. */ ds@1952: rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage); ds@1952: if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){ ds@1952: releasePage(pRoot); ds@1952: return rc; ds@1952: } ds@1952: assert( eType!=PTRMAP_ROOTPAGE ); ds@1952: assert( eType!=PTRMAP_FREEPAGE ); ds@1952: rc = sqlite3PagerWrite(pRoot->pDbPage); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: releasePage(pRoot); ds@1952: return rc; ds@1952: } ds@1952: rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove); ds@1952: releasePage(pRoot); ds@1952: ds@1952: /* Obtain the page at pgnoRoot */ ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: rc = sqlite3PagerWrite(pRoot->pDbPage); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: releasePage(pRoot); ds@1952: return rc; ds@1952: } ds@1952: }else{ ds@1952: pRoot = pPageMove; ds@1952: } ds@1952: ds@1952: /* Update the pointer-map and meta-data with the new root-page number. */ ds@1952: rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0); ds@1952: if( rc ){ ds@1952: releasePage(pRoot); ds@1952: return rc; ds@1952: } ds@1952: rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot); ds@1952: if( rc ){ ds@1952: releasePage(pRoot); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: }else{ ds@1952: rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0); ds@1952: if( rc ) return rc; ds@1952: } ds@1952: #endif ds@1952: assert( sqlite3PagerIswriteable(pRoot->pDbPage) ); ds@1952: zeroPage(pRoot, flags | PTF_LEAF); ds@1952: sqlite3PagerUnref(pRoot->pDbPage); ds@1952: *piTable = (int)pgnoRoot; ds@1952: return SQLITE_OK; ds@1952: } ds@1952: int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){ ds@1952: int rc; ds@1952: sqlite3BtreeEnter(p); ds@1952: rc = btreeCreateTable(p, piTable, flags); ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Erase the given database page and all its children. Return ds@1952: ** the page to the freelist. ds@1952: */ ds@1952: static int clearDatabasePage( ds@1952: BtShared *pBt, /* The BTree that contains the table */ ds@1952: Pgno pgno, /* Page number to clear */ ds@1952: MemPage *pParent, /* Parent page. NULL for the root */ ds@1952: int freePageFlag /* Deallocate page if true */ ds@1952: ){ ds@1952: MemPage *pPage = 0; ds@1952: int rc; ds@1952: unsigned char *pCell; ds@1952: int i; ds@1952: ds@1952: assert( sqlite3_mutex_held(pBt->mutex) ); ds@1952: if( pgno>sqlite3PagerPagecount(pBt->pPager) ){ ds@1952: return SQLITE_CORRUPT_BKPT; ds@1952: } ds@1952: ds@1952: rc = getAndInitPage(pBt, pgno, &pPage, pParent); ds@1952: if( rc ) goto cleardatabasepage_out; ds@1952: for(i=0; inCell; i++){ ds@1952: pCell = findCell(pPage, i); ds@1952: if( !pPage->leaf ){ ds@1952: rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1); ds@1952: if( rc ) goto cleardatabasepage_out; ds@1952: } ds@1952: rc = clearCell(pPage, pCell); ds@1952: if( rc ) goto cleardatabasepage_out; ds@1952: } ds@1952: if( !pPage->leaf ){ ds@1952: rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1); ds@1952: if( rc ) goto cleardatabasepage_out; ds@1952: } ds@1952: if( freePageFlag ){ ds@1952: rc = freePage(pPage); ds@1952: }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){ ds@1952: zeroPage(pPage, pPage->aData[0] | PTF_LEAF); ds@1952: } ds@1952: ds@1952: cleardatabasepage_out: ds@1952: releasePage(pPage); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Delete all information from a single table in the database. iTable is ds@1952: ** the page number of the root of the table. After this routine returns, ds@1952: ** the root page is empty, but still exists. ds@1952: ** ds@1952: ** This routine will fail with SQLITE_LOCKED if there are any open ds@1952: ** read cursors on the table. Open write cursors are moved to the ds@1952: ** root of the table. ds@1952: */ ds@1952: int sqlite3BtreeClearTable(Btree *p, int iTable){ ds@1952: int rc; ds@1952: BtShared *pBt = p->pBt; ds@1952: sqlite3BtreeEnter(p); ds@1952: if( p->inTrans!=TRANS_WRITE ){ ds@1952: rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR; ds@1952: }else if( (rc = checkReadLocks(p, iTable, 0))!=SQLITE_OK ){ ds@1952: /* nothing to do */ ds@1952: }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){ ds@1952: /* nothing to do */ ds@1952: }else{ ds@1952: rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0); ds@1952: } ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Erase all information in a table and add the root of the table to ds@1952: ** the freelist. Except, the root of the principle table (the one on ds@1952: ** page 1) is never added to the freelist. ds@1952: ** ds@1952: ** This routine will fail with SQLITE_LOCKED if there are any open ds@1952: ** cursors on the table. ds@1952: ** ds@1952: ** If AUTOVACUUM is enabled and the page at iTable is not the last ds@1952: ** root page in the database file, then the last root page ds@1952: ** in the database file is moved into the slot formerly occupied by ds@1952: ** iTable and that last slot formerly occupied by the last root page ds@1952: ** is added to the freelist instead of iTable. In this say, all ds@1952: ** root pages are kept at the beginning of the database file, which ds@1952: ** is necessary for AUTOVACUUM to work right. *piMoved is set to the ds@1952: ** page number that used to be the last root page in the file before ds@1952: ** the move. If no page gets moved, *piMoved is set to 0. ds@1952: ** The last root page is recorded in meta[3] and the value of ds@1952: ** meta[3] is updated by this procedure. ds@1952: */ ds@1952: static int btreeDropTable(Btree *p, int iTable, int *piMoved){ ds@1952: int rc; ds@1952: MemPage *pPage = 0; ds@1952: BtShared *pBt = p->pBt; ds@1952: ds@1952: assert( sqlite3BtreeHoldsMutex(p) ); ds@1952: if( p->inTrans!=TRANS_WRITE ){ ds@1952: return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR; ds@1952: } ds@1952: ds@1952: /* It is illegal to drop a table if any cursors are open on the ds@1952: ** database. This is because in auto-vacuum mode the backend may ds@1952: ** need to move another root-page to fill a gap left by the deleted ds@1952: ** root page. If an open cursor was using this page a problem would ds@1952: ** occur. ds@1952: */ ds@1952: if( pBt->pCursor ){ ds@1952: return SQLITE_LOCKED; ds@1952: } ds@1952: ds@1952: rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0); ds@1952: if( rc ) return rc; ds@1952: rc = sqlite3BtreeClearTable(p, iTable); ds@1952: if( rc ){ ds@1952: releasePage(pPage); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: *piMoved = 0; ds@1952: ds@1952: if( iTable>1 ){ ds@1952: #ifdef SQLITE_OMIT_AUTOVACUUM ds@1952: rc = freePage(pPage); ds@1952: releasePage(pPage); ds@1952: #else ds@1952: if( pBt->autoVacuum ){ ds@1952: Pgno maxRootPgno; ds@1952: rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: releasePage(pPage); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: if( iTable==maxRootPgno ){ ds@1952: /* If the table being dropped is the table with the largest root-page ds@1952: ** number in the database, put the root page on the free list. ds@1952: */ ds@1952: rc = freePage(pPage); ds@1952: releasePage(pPage); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: }else{ ds@1952: /* The table being dropped does not have the largest root-page ds@1952: ** number in the database. So move the page that does into the ds@1952: ** gap left by the deleted root-page. ds@1952: */ ds@1952: MemPage *pMove; ds@1952: releasePage(pPage); ds@1952: rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable); ds@1952: releasePage(pMove); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: rc = freePage(pMove); ds@1952: releasePage(pMove); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: return rc; ds@1952: } ds@1952: *piMoved = maxRootPgno; ds@1952: } ds@1952: ds@1952: /* Set the new 'max-root-page' value in the database header. This ds@1952: ** is the old value less one, less one more if that happens to ds@1952: ** be a root-page number, less one again if that is the ds@1952: ** PENDING_BYTE_PAGE. ds@1952: */ ds@1952: maxRootPgno--; ds@1952: if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){ ds@1952: maxRootPgno--; ds@1952: } ds@1952: if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){ ds@1952: maxRootPgno--; ds@1952: } ds@1952: assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) ); ds@1952: ds@1952: rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno); ds@1952: }else{ ds@1952: rc = freePage(pPage); ds@1952: releasePage(pPage); ds@1952: } ds@1952: #endif ds@1952: }else{ ds@1952: /* If sqlite3BtreeDropTable was called on page 1. */ ds@1952: zeroPage(pPage, PTF_INTKEY|PTF_LEAF ); ds@1952: releasePage(pPage); ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){ ds@1952: int rc; ds@1952: sqlite3BtreeEnter(p); ds@1952: rc = btreeDropTable(p, iTable, piMoved); ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** Read the meta-information out of a database file. Meta[0] ds@1952: ** is the number of free pages currently in the database. Meta[1] ds@1952: ** through meta[15] are available for use by higher layers. Meta[0] ds@1952: ** is read-only, the others are read/write. ds@1952: ** ds@1952: ** The schema layer numbers meta values differently. At the schema ds@1952: ** layer (and the SetCookie and ReadCookie opcodes) the number of ds@1952: ** free pages is not visible. So Cookie[0] is the same as Meta[1]. ds@1952: */ ds@1952: int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){ ds@1952: DbPage *pDbPage; ds@1952: int rc; ds@1952: unsigned char *pP1; ds@1952: BtShared *pBt = p->pBt; ds@1952: ds@1952: sqlite3BtreeEnter(p); ds@1952: ds@1952: /* Reading a meta-data value requires a read-lock on page 1 (and hence ds@1952: ** the sqlite_master table. We grab this lock regardless of whether or ds@1952: ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page ds@1952: ** 1 is treated as a special case by queryTableLock() and lockTable()). ds@1952: */ ds@1952: rc = queryTableLock(p, 1, READ_LOCK); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: assert( idx>=0 && idx<=15 ); ds@1952: rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage); ds@1952: if( rc ){ ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage); ds@1952: *pMeta = get4byte(&pP1[36 + idx*4]); ds@1952: sqlite3PagerUnref(pDbPage); ds@1952: ds@1952: /* If autovacuumed is disabled in this build but we are trying to ds@1952: ** access an autovacuumed database, then make the database readonly. ds@1952: */ ds@1952: #ifdef SQLITE_OMIT_AUTOVACUUM ds@1952: if( idx==4 && *pMeta>0 ) pBt->readOnly = 1; ds@1952: #endif ds@1952: ds@1952: /* Grab the read-lock on page 1. */ ds@1952: rc = lockTable(p, 1, READ_LOCK); ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Write meta-information back into the database. Meta[0] is ds@1952: ** read-only and may not be written. ds@1952: */ ds@1952: int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){ ds@1952: BtShared *pBt = p->pBt; ds@1952: unsigned char *pP1; ds@1952: int rc; ds@1952: assert( idx>=1 && idx<=15 ); ds@1952: sqlite3BtreeEnter(p); ds@1952: if( p->inTrans!=TRANS_WRITE ){ ds@1952: rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR; ds@1952: }else{ ds@1952: assert( pBt->pPage1!=0 ); ds@1952: pP1 = pBt->pPage1->aData; ds@1952: rc = sqlite3PagerWrite(pBt->pPage1->pDbPage); ds@1952: if( rc==SQLITE_OK ){ ds@1952: put4byte(&pP1[36 + idx*4], iMeta); ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: if( idx==7 ){ ds@1952: assert( pBt->autoVacuum || iMeta==0 ); ds@1952: assert( iMeta==0 || iMeta==1 ); ds@1952: pBt->incrVacuum = iMeta; ds@1952: } ds@1952: #endif ds@1952: } ds@1952: } ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Return the flag byte at the beginning of the page that the cursor ds@1952: ** is currently pointing to. ds@1952: */ ds@1952: int sqlite3BtreeFlags(BtCursor *pCur){ ds@1952: /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call ds@1952: ** restoreOrClearCursorPosition() here. ds@1952: */ ds@1952: MemPage *pPage = pCur->pPage; ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: assert( pPage->pBt==pCur->pBt ); ds@1952: return pPage ? pPage->aData[pPage->hdrOffset] : 0; ds@1952: } ds@1952: ds@1952: ds@1952: /* ds@1952: ** Return the pager associated with a BTree. This routine is used for ds@1952: ** testing and debugging only. ds@1952: */ ds@1952: Pager *sqlite3BtreePager(Btree *p){ ds@1952: return p->pBt->pPager; ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_INTEGRITY_CHECK ds@1952: /* ds@1952: ** Append a message to the error message string. ds@1952: */ ds@1952: static void checkAppendMsg( ds@1952: IntegrityCk *pCheck, ds@1952: char *zMsg1, ds@1952: const char *zFormat, ds@1952: ... ds@1952: ){ ds@1952: va_list ap; ds@1952: char *zMsg2; ds@1952: if( !pCheck->mxErr ) return; ds@1952: pCheck->mxErr--; ds@1952: pCheck->nErr++; ds@1952: va_start(ap, zFormat); ds@1952: zMsg2 = sqlite3VMPrintf(0, zFormat, ap); ds@1952: va_end(ap); ds@1952: if( zMsg1==0 ) zMsg1 = ""; ds@1952: if( pCheck->zErrMsg ){ ds@1952: char *zOld = pCheck->zErrMsg; ds@1952: pCheck->zErrMsg = 0; ds@1952: sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0); ds@1952: sqlite3_free(zOld); ds@1952: }else{ ds@1952: sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0); ds@1952: } ds@1952: sqlite3_free(zMsg2); ds@1952: } ds@1952: #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ ds@1952: ds@1952: #ifndef SQLITE_OMIT_INTEGRITY_CHECK ds@1952: /* ds@1952: ** Add 1 to the reference count for page iPage. If this is the second ds@1952: ** reference to the page, add an error message to pCheck->zErrMsg. ds@1952: ** Return 1 if there are 2 ore more references to the page and 0 if ds@1952: ** if this is the first reference to the page. ds@1952: ** ds@1952: ** Also check that the page number is in bounds. ds@1952: */ ds@1952: static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){ ds@1952: if( iPage==0 ) return 1; ds@1952: if( iPage>pCheck->nPage || iPage<0 ){ ds@1952: checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage); ds@1952: return 1; ds@1952: } ds@1952: if( pCheck->anRef[iPage]==1 ){ ds@1952: checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage); ds@1952: return 1; ds@1952: } ds@1952: return (pCheck->anRef[iPage]++)>1; ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: /* ds@1952: ** Check that the entry in the pointer-map for page iChild maps to ds@1952: ** page iParent, pointer type ptrType. If not, append an error message ds@1952: ** to pCheck. ds@1952: */ ds@1952: static void checkPtrmap( ds@1952: IntegrityCk *pCheck, /* Integrity check context */ ds@1952: Pgno iChild, /* Child page number */ ds@1952: u8 eType, /* Expected pointer map type */ ds@1952: Pgno iParent, /* Expected pointer map parent page number */ ds@1952: char *zContext /* Context description (used for error msg) */ ds@1952: ){ ds@1952: int rc; ds@1952: u8 ePtrmapType; ds@1952: Pgno iPtrmapParent; ds@1952: ds@1952: rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent); ds@1952: if( rc!=SQLITE_OK ){ ds@1952: checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild); ds@1952: return; ds@1952: } ds@1952: ds@1952: if( ePtrmapType!=eType || iPtrmapParent!=iParent ){ ds@1952: checkAppendMsg(pCheck, zContext, ds@1952: "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", ds@1952: iChild, eType, iParent, ePtrmapType, iPtrmapParent); ds@1952: } ds@1952: } ds@1952: #endif ds@1952: ds@1952: /* ds@1952: ** Check the integrity of the freelist or of an overflow page list. ds@1952: ** Verify that the number of pages on the list is N. ds@1952: */ ds@1952: static void checkList( ds@1952: IntegrityCk *pCheck, /* Integrity checking context */ ds@1952: int isFreeList, /* True for a freelist. False for overflow page list */ ds@1952: int iPage, /* Page number for first page in the list */ ds@1952: int N, /* Expected number of pages in the list */ ds@1952: char *zContext /* Context for error messages */ ds@1952: ){ ds@1952: int i; ds@1952: int expected = N; ds@1952: int iFirst = iPage; ds@1952: while( N-- > 0 && pCheck->mxErr ){ ds@1952: DbPage *pOvflPage; ds@1952: unsigned char *pOvflData; ds@1952: if( iPage<1 ){ ds@1952: checkAppendMsg(pCheck, zContext, ds@1952: "%d of %d pages missing from overflow list starting at %d", ds@1952: N+1, expected, iFirst); ds@1952: break; ds@1952: } ds@1952: if( checkRef(pCheck, iPage, zContext) ) break; ds@1952: if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){ ds@1952: checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage); ds@1952: break; ds@1952: } ds@1952: pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage); ds@1952: if( isFreeList ){ ds@1952: int n = get4byte(&pOvflData[4]); ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: if( pCheck->pBt->autoVacuum ){ ds@1952: checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext); ds@1952: } ds@1952: #endif ds@1952: if( n>pCheck->pBt->usableSize/4-8 ){ ds@1952: checkAppendMsg(pCheck, zContext, ds@1952: "freelist leaf count too big on page %d", iPage); ds@1952: N--; ds@1952: }else{ ds@1952: for(i=0; ipBt->autoVacuum ){ ds@1952: checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext); ds@1952: } ds@1952: #endif ds@1952: checkRef(pCheck, iFreePage, zContext); ds@1952: } ds@1952: N -= n; ds@1952: } ds@1952: } ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: else{ ds@1952: /* If this database supports auto-vacuum and iPage is not the last ds@1952: ** page in this overflow list, check that the pointer-map entry for ds@1952: ** the following page matches iPage. ds@1952: */ ds@1952: if( pCheck->pBt->autoVacuum && N>0 ){ ds@1952: i = get4byte(pOvflData); ds@1952: checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext); ds@1952: } ds@1952: } ds@1952: #endif ds@1952: iPage = get4byte(pOvflData); ds@1952: sqlite3PagerUnref(pOvflPage); ds@1952: } ds@1952: } ds@1952: #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ ds@1952: ds@1952: #ifndef SQLITE_OMIT_INTEGRITY_CHECK ds@1952: /* ds@1952: ** Do various sanity checks on a single page of a tree. Return ds@1952: ** the tree depth. Root pages return 0. Parents of root pages ds@1952: ** return 1, and so forth. ds@1952: ** ds@1952: ** These checks are done: ds@1952: ** ds@1952: ** 1. Make sure that cells and freeblocks do not overlap ds@1952: ** but combine to completely cover the page. ds@1952: ** NO 2. Make sure cell keys are in order. ds@1952: ** NO 3. Make sure no key is less than or equal to zLowerBound. ds@1952: ** NO 4. Make sure no key is greater than or equal to zUpperBound. ds@1952: ** 5. Check the integrity of overflow pages. ds@1952: ** 6. Recursively call checkTreePage on all children. ds@1952: ** 7. Verify that the depth of all children is the same. ds@1952: ** 8. Make sure this page is at least 33% full or else it is ds@1952: ** the root of the tree. ds@1952: */ ds@1952: static int checkTreePage( ds@1952: IntegrityCk *pCheck, /* Context for the sanity check */ ds@1952: int iPage, /* Page number of the page to check */ ds@1952: MemPage *pParent, /* Parent page */ ds@1952: char *zParentContext /* Parent context */ ds@1952: ){ ds@1952: MemPage *pPage; ds@1952: int i, rc, depth, d2, pgno, cnt; ds@1952: int hdr, cellStart; ds@1952: int nCell; ds@1952: u8 *data; ds@1952: BtShared *pBt; ds@1952: int usableSize; ds@1952: char zContext[100]; ds@1952: char *hit; ds@1952: ds@1952: sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage); ds@1952: ds@1952: /* Check that the page exists ds@1952: */ ds@1952: pBt = pCheck->pBt; ds@1952: usableSize = pBt->usableSize; ds@1952: if( iPage==0 ) return 0; ds@1952: if( checkRef(pCheck, iPage, zParentContext) ) return 0; ds@1952: if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){ ds@1952: checkAppendMsg(pCheck, zContext, ds@1952: "unable to get the page. error code=%d", rc); ds@1952: return 0; ds@1952: } ds@1952: if( (rc = sqlite3BtreeInitPage(pPage, pParent))!=0 ){ ds@1952: checkAppendMsg(pCheck, zContext, ds@1952: "sqlite3BtreeInitPage() returns error code %d", rc); ds@1952: releasePage(pPage); ds@1952: return 0; ds@1952: } ds@1952: ds@1952: /* Check out all the cells. ds@1952: */ ds@1952: depth = 0; ds@1952: for(i=0; inCell && pCheck->mxErr; i++){ ds@1952: u8 *pCell; ds@1952: int sz; ds@1952: CellInfo info; ds@1952: ds@1952: /* Check payload overflow pages ds@1952: */ ds@1952: sqlite3_snprintf(sizeof(zContext), zContext, ds@1952: "On tree page %d cell %d: ", iPage, i); ds@1952: pCell = findCell(pPage,i); ds@1952: sqlite3BtreeParseCellPtr(pPage, pCell, &info); ds@1952: sz = info.nData; ds@1952: if( !pPage->intKey ) sz += info.nKey; ds@1952: assert( sz==info.nPayload ); ds@1952: if( sz>info.nLocal ){ ds@1952: int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4); ds@1952: Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]); ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: if( pBt->autoVacuum ){ ds@1952: checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext); ds@1952: } ds@1952: #endif ds@1952: checkList(pCheck, 0, pgnoOvfl, nPage, zContext); ds@1952: } ds@1952: ds@1952: /* Check sanity of left child page. ds@1952: */ ds@1952: if( !pPage->leaf ){ ds@1952: pgno = get4byte(pCell); ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: if( pBt->autoVacuum ){ ds@1952: checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext); ds@1952: } ds@1952: #endif ds@1952: d2 = checkTreePage(pCheck,pgno,pPage,zContext); ds@1952: if( i>0 && d2!=depth ){ ds@1952: checkAppendMsg(pCheck, zContext, "Child page depth differs"); ds@1952: } ds@1952: depth = d2; ds@1952: } ds@1952: } ds@1952: if( !pPage->leaf ){ ds@1952: pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]); ds@1952: sqlite3_snprintf(sizeof(zContext), zContext, ds@1952: "On page %d at right child: ", iPage); ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: if( pBt->autoVacuum ){ ds@1952: checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0); ds@1952: } ds@1952: #endif ds@1952: checkTreePage(pCheck, pgno, pPage, zContext); ds@1952: } ds@1952: ds@1952: /* Check for complete coverage of the page ds@1952: */ ds@1952: data = pPage->aData; ds@1952: hdr = pPage->hdrOffset; ds@1952: hit = sqlite3MallocZero( usableSize ); ds@1952: if( hit ){ ds@1952: memset(hit, 1, get2byte(&data[hdr+5])); ds@1952: nCell = get2byte(&data[hdr+3]); ds@1952: cellStart = hdr + 12 - 4*pPage->leaf; ds@1952: for(i=0; i=usableSize || pc<0 ){ ds@1952: checkAppendMsg(pCheck, 0, ds@1952: "Corruption detected in cell %d on page %d",i,iPage,0); ds@1952: }else{ ds@1952: for(j=pc+size-1; j>=pc; j--) hit[j]++; ds@1952: } ds@1952: } ds@1952: for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i=usableSize || i<0 ){ ds@1952: checkAppendMsg(pCheck, 0, ds@1952: "Corruption detected in cell %d on page %d",i,iPage,0); ds@1952: }else{ ds@1952: for(j=i+size-1; j>=i; j--) hit[j]++; ds@1952: } ds@1952: i = get2byte(&data[i]); ds@1952: } ds@1952: for(i=cnt=0; i1 ){ ds@1952: checkAppendMsg(pCheck, 0, ds@1952: "Multiple uses for byte %d of page %d", i, iPage); ds@1952: break; ds@1952: } ds@1952: } ds@1952: if( cnt!=data[hdr+7] ){ ds@1952: checkAppendMsg(pCheck, 0, ds@1952: "Fragmented space is %d byte reported as %d on page %d", ds@1952: cnt, data[hdr+7], iPage); ds@1952: } ds@1952: } ds@1952: sqlite3_free(hit); ds@1952: ds@1952: releasePage(pPage); ds@1952: return depth+1; ds@1952: } ds@1952: #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ ds@1952: ds@1952: #ifndef SQLITE_OMIT_INTEGRITY_CHECK ds@1952: /* ds@1952: ** This routine does a complete check of the given BTree file. aRoot[] is ds@1952: ** an array of pages numbers were each page number is the root page of ds@1952: ** a table. nRoot is the number of entries in aRoot. ds@1952: ** ds@1952: ** If everything checks out, this routine returns NULL. If something is ds@1952: ** amiss, an error message is written into memory obtained from malloc() ds@1952: ** and a pointer to that error message is returned. The calling function ds@1952: ** is responsible for freeing the error message when it is done. ds@1952: */ ds@1952: char *sqlite3BtreeIntegrityCheck( ds@1952: Btree *p, /* The btree to be checked */ ds@1952: int *aRoot, /* An array of root pages numbers for individual trees */ ds@1952: int nRoot, /* Number of entries in aRoot[] */ ds@1952: int mxErr, /* Stop reporting errors after this many */ ds@1952: int *pnErr /* Write number of errors seen to this variable */ ds@1952: ){ ds@1952: int i; ds@1952: int nRef; ds@1952: IntegrityCk sCheck; ds@1952: BtShared *pBt = p->pBt; ds@1952: ds@1952: sqlite3BtreeEnter(p); ds@1952: nRef = sqlite3PagerRefcount(pBt->pPager); ds@1952: if( lockBtreeWithRetry(p)!=SQLITE_OK ){ ds@1952: sqlite3BtreeLeave(p); ds@1952: return sqlite3StrDup("Unable to acquire a read lock on the database"); ds@1952: } ds@1952: sCheck.pBt = pBt; ds@1952: sCheck.pPager = pBt->pPager; ds@1952: sCheck.nPage = sqlite3PagerPagecount(sCheck.pPager); ds@1952: sCheck.mxErr = mxErr; ds@1952: sCheck.nErr = 0; ds@1952: *pnErr = 0; ds@1952: #ifndef SQLITE_OMIT_AUTOVACUUM ds@1952: if( pBt->nTrunc!=0 ){ ds@1952: sCheck.nPage = pBt->nTrunc; ds@1952: } ds@1952: #endif ds@1952: if( sCheck.nPage==0 ){ ds@1952: unlockBtreeIfUnused(pBt); ds@1952: sqlite3BtreeLeave(p); ds@1952: return 0; ds@1952: } ds@1952: sCheck.anRef = sqlite3_malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) ); ds@1952: if( !sCheck.anRef ){ ds@1952: unlockBtreeIfUnused(pBt); ds@1952: *pnErr = 1; ds@1952: sqlite3BtreeLeave(p); ds@1952: return sqlite3MPrintf(p->pSqlite, "Unable to malloc %d bytes", ds@1952: (sCheck.nPage+1)*sizeof(sCheck.anRef[0])); ds@1952: } ds@1952: for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; } ds@1952: i = PENDING_BYTE_PAGE(pBt); ds@1952: if( i<=sCheck.nPage ){ ds@1952: sCheck.anRef[i] = 1; ds@1952: } ds@1952: sCheck.zErrMsg = 0; ds@1952: ds@1952: /* Check the integrity of the freelist ds@1952: */ ds@1952: checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]), ds@1952: get4byte(&pBt->pPage1->aData[36]), "Main freelist: "); ds@1952: ds@1952: /* Check all the tables. ds@1952: */ ds@1952: for(i=0; iautoVacuum && aRoot[i]>1 ){ ds@1952: checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0); ds@1952: } ds@1952: #endif ds@1952: checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: "); ds@1952: } ds@1952: ds@1952: /* Make sure every page in the file is referenced ds@1952: */ ds@1952: for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){ ds@1952: #ifdef SQLITE_OMIT_AUTOVACUUM ds@1952: if( sCheck.anRef[i]==0 ){ ds@1952: checkAppendMsg(&sCheck, 0, "Page %d is never used", i); ds@1952: } ds@1952: #else ds@1952: /* If the database supports auto-vacuum, make sure no tables contain ds@1952: ** references to pointer-map pages. ds@1952: */ ds@1952: if( sCheck.anRef[i]==0 && ds@1952: (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){ ds@1952: checkAppendMsg(&sCheck, 0, "Page %d is never used", i); ds@1952: } ds@1952: if( sCheck.anRef[i]!=0 && ds@1952: (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){ ds@1952: checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i); ds@1952: } ds@1952: #endif ds@1952: } ds@1952: ds@1952: /* Make sure this analysis did not leave any unref() pages ds@1952: */ ds@1952: unlockBtreeIfUnused(pBt); ds@1952: if( nRef != sqlite3PagerRefcount(pBt->pPager) ){ ds@1952: checkAppendMsg(&sCheck, 0, ds@1952: "Outstanding page count goes from %d to %d during this analysis", ds@1952: nRef, sqlite3PagerRefcount(pBt->pPager) ds@1952: ); ds@1952: } ds@1952: ds@1952: /* Clean up and report errors. ds@1952: */ ds@1952: sqlite3BtreeLeave(p); ds@1952: sqlite3_free(sCheck.anRef); ds@1952: *pnErr = sCheck.nErr; ds@1952: return sCheck.zErrMsg; ds@1952: } ds@1952: #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ ds@1952: ds@1952: /* ds@1952: ** Return the full pathname of the underlying database file. ds@1952: ** ds@1952: ** The pager filename is invariant as long as the pager is ds@1952: ** open so it is safe to access without the BtShared mutex. ds@1952: */ ds@1952: const char *sqlite3BtreeGetFilename(Btree *p){ ds@1952: assert( p->pBt->pPager!=0 ); ds@1952: return sqlite3PagerFilename(p->pBt->pPager); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Return the pathname of the directory that contains the database file. ds@1952: ** ds@1952: ** The pager directory name is invariant as long as the pager is ds@1952: ** open so it is safe to access without the BtShared mutex. ds@1952: */ ds@1952: const char *sqlite3BtreeGetDirname(Btree *p){ ds@1952: assert( p->pBt->pPager!=0 ); ds@1952: return sqlite3PagerDirname(p->pBt->pPager); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Return the pathname of the journal file for this database. The return ds@1952: ** value of this routine is the same regardless of whether the journal file ds@1952: ** has been created or not. ds@1952: ** ds@1952: ** The pager journal filename is invariant as long as the pager is ds@1952: ** open so it is safe to access without the BtShared mutex. ds@1952: */ ds@1952: const char *sqlite3BtreeGetJournalname(Btree *p){ ds@1952: assert( p->pBt->pPager!=0 ); ds@1952: return sqlite3PagerJournalname(p->pBt->pPager); ds@1952: } ds@1952: ds@1952: #ifndef SQLITE_OMIT_VACUUM ds@1952: /* ds@1952: ** Copy the complete content of pBtFrom into pBtTo. A transaction ds@1952: ** must be active for both files. ds@1952: ** ds@1952: ** The size of file pBtFrom may be reduced by this operation. ds@1952: ** If anything goes wrong, the transaction on pBtFrom is rolled back. ds@1952: */ ds@1952: static int btreeCopyFile(Btree *pTo, Btree *pFrom){ ds@1952: int rc = SQLITE_OK; ds@1952: Pgno i, nPage, nToPage, iSkip; ds@1952: ds@1952: BtShared *pBtTo = pTo->pBt; ds@1952: BtShared *pBtFrom = pFrom->pBt; ds@1952: ds@1952: if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){ ds@1952: return SQLITE_ERROR; ds@1952: } ds@1952: if( pBtTo->pCursor ) return SQLITE_BUSY; ds@1952: nToPage = sqlite3PagerPagecount(pBtTo->pPager); ds@1952: nPage = sqlite3PagerPagecount(pBtFrom->pPager); ds@1952: iSkip = PENDING_BYTE_PAGE(pBtTo); ds@1952: for(i=1; rc==SQLITE_OK && i<=nPage; i++){ ds@1952: DbPage *pDbPage; ds@1952: if( i==iSkip ) continue; ds@1952: rc = sqlite3PagerGet(pBtFrom->pPager, i, &pDbPage); ds@1952: if( rc ) break; ds@1952: rc = sqlite3PagerOverwrite(pBtTo->pPager, i, sqlite3PagerGetData(pDbPage)); ds@1952: sqlite3PagerUnref(pDbPage); ds@1952: } ds@1952: ds@1952: /* If the file is shrinking, journal the pages that are being truncated ds@1952: ** so that they can be rolled back if the commit fails. ds@1952: */ ds@1952: for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){ ds@1952: DbPage *pDbPage; ds@1952: if( i==iSkip ) continue; ds@1952: rc = sqlite3PagerGet(pBtTo->pPager, i, &pDbPage); ds@1952: if( rc ) break; ds@1952: rc = sqlite3PagerWrite(pDbPage); ds@1952: sqlite3PagerDontWrite(pDbPage); ds@1952: /* Yeah. It seems wierd to call DontWrite() right after Write(). But ds@1952: ** that is because the names of those procedures do not exactly ds@1952: ** represent what they do. Write() really means "put this page in the ds@1952: ** rollback journal and mark it as dirty so that it will be written ds@1952: ** to the database file later." DontWrite() undoes the second part of ds@1952: ** that and prevents the page from being written to the database. The ds@1952: ** page is still on the rollback journal, though. And that is the whole ds@1952: ** point of this loop: to put pages on the rollback journal. */ ds@1952: sqlite3PagerUnref(pDbPage); ds@1952: } ds@1952: if( !rc && nPagepPager, nPage); ds@1952: } ds@1952: ds@1952: if( rc ){ ds@1952: sqlite3BtreeRollback(pTo); ds@1952: } ds@1952: return rc; ds@1952: } ds@1952: int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){ ds@1952: int rc; ds@1952: sqlite3BtreeEnter(pTo); ds@1952: sqlite3BtreeEnter(pFrom); ds@1952: rc = btreeCopyFile(pTo, pFrom); ds@1952: sqlite3BtreeLeave(pFrom); ds@1952: sqlite3BtreeLeave(pTo); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: #endif /* SQLITE_OMIT_VACUUM */ ds@1952: ds@1952: /* ds@1952: ** Return non-zero if a transaction is active. ds@1952: */ ds@1952: int sqlite3BtreeIsInTrans(Btree *p){ ds@1952: assert( p==0 || sqlite3_mutex_held(p->pSqlite->mutex) ); ds@1952: return (p && (p->inTrans==TRANS_WRITE)); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Return non-zero if a statement transaction is active. ds@1952: */ ds@1952: int sqlite3BtreeIsInStmt(Btree *p){ ds@1952: assert( sqlite3BtreeHoldsMutex(p) ); ds@1952: return (p->pBt && p->pBt->inStmt); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Return non-zero if a read (or write) transaction is active. ds@1952: */ ds@1952: int sqlite3BtreeIsInReadTrans(Btree *p){ ds@1952: assert( sqlite3_mutex_held(p->pSqlite->mutex) ); ds@1952: return (p && (p->inTrans!=TRANS_NONE)); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** This function returns a pointer to a blob of memory associated with ds@1952: ** a single shared-btree. The memory is used by client code for it's own ds@1952: ** purposes (for example, to store a high-level schema associated with ds@1952: ** the shared-btree). The btree layer manages reference counting issues. ds@1952: ** ds@1952: ** The first time this is called on a shared-btree, nBytes bytes of memory ds@1952: ** are allocated, zeroed, and returned to the caller. For each subsequent ds@1952: ** call the nBytes parameter is ignored and a pointer to the same blob ds@1952: ** of memory returned. ds@1952: ** ds@1952: ** Just before the shared-btree is closed, the function passed as the ds@1952: ** xFree argument when the memory allocation was made is invoked on the ds@1952: ** blob of allocated memory. This function should not call sqlite3_free() ds@1952: ** on the memory, the btree layer does that. ds@1952: */ ds@1952: void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){ ds@1952: BtShared *pBt = p->pBt; ds@1952: sqlite3BtreeEnter(p); ds@1952: if( !pBt->pSchema ){ ds@1952: pBt->pSchema = sqlite3MallocZero(nBytes); ds@1952: pBt->xFreeSchema = xFree; ds@1952: } ds@1952: sqlite3BtreeLeave(p); ds@1952: return pBt->pSchema; ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Return true if another user of the same shared btree as the argument ds@1952: ** handle holds an exclusive lock on the sqlite_master table. ds@1952: */ ds@1952: int sqlite3BtreeSchemaLocked(Btree *p){ ds@1952: int rc; ds@1952: assert( sqlite3_mutex_held(p->pSqlite->mutex) ); ds@1952: sqlite3BtreeEnter(p); ds@1952: rc = (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK); ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: ds@1952: ds@1952: #ifndef SQLITE_OMIT_SHARED_CACHE ds@1952: /* ds@1952: ** Obtain a lock on the table whose root page is iTab. The ds@1952: ** lock is a write lock if isWritelock is true or a read lock ds@1952: ** if it is false. ds@1952: */ ds@1952: int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){ ds@1952: int rc = SQLITE_OK; ds@1952: u8 lockType = (isWriteLock?WRITE_LOCK:READ_LOCK); ds@1952: sqlite3BtreeEnter(p); ds@1952: rc = queryTableLock(p, iTab, lockType); ds@1952: if( rc==SQLITE_OK ){ ds@1952: rc = lockTable(p, iTab, lockType); ds@1952: } ds@1952: sqlite3BtreeLeave(p); ds@1952: return rc; ds@1952: } ds@1952: #endif ds@1952: ds@1952: #ifndef SQLITE_OMIT_INCRBLOB ds@1952: /* ds@1952: ** Argument pCsr must be a cursor opened for writing on an ds@1952: ** INTKEY table currently pointing at a valid table entry. ds@1952: ** This function modifies the data stored as part of that entry. ds@1952: ** Only the data content may only be modified, it is not possible ds@1952: ** to change the length of the data stored. ds@1952: */ ds@1952: int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){ ds@1952: assert( cursorHoldsMutex(pCsr) ); ds@1952: assert( sqlite3_mutex_held(pCsr->pBtree->pSqlite->mutex) ); ds@1952: assert(pCsr->isIncrblobHandle); ds@1952: if( pCsr->eState>=CURSOR_REQUIRESEEK ){ ds@1952: if( pCsr->eState==CURSOR_FAULT ){ ds@1952: return pCsr->skip; ds@1952: }else{ ds@1952: return SQLITE_ABORT; ds@1952: } ds@1952: } ds@1952: ds@1952: /* Check some preconditions: ds@1952: ** (a) the cursor is open for writing, ds@1952: ** (b) there is no read-lock on the table being modified and ds@1952: ** (c) the cursor points at a valid row of an intKey table. ds@1952: */ ds@1952: if( !pCsr->wrFlag ){ ds@1952: return SQLITE_READONLY; ds@1952: } ds@1952: assert( !pCsr->pBt->readOnly ds@1952: && pCsr->pBt->inTransaction==TRANS_WRITE ); ds@1952: if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr) ){ ds@1952: return SQLITE_LOCKED; /* The table pCur points to has a read lock */ ds@1952: } ds@1952: if( pCsr->eState==CURSOR_INVALID || !pCsr->pPage->intKey ){ ds@1952: return SQLITE_ERROR; ds@1952: } ds@1952: ds@1952: return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1); ds@1952: } ds@1952: ds@1952: /* ds@1952: ** Set a flag on this cursor to cache the locations of pages from the ds@1952: ** overflow list for the current row. This is used by cursors opened ds@1952: ** for incremental blob IO only. ds@1952: ** ds@1952: ** This function sets a flag only. The actual page location cache ds@1952: ** (stored in BtCursor.aOverflow[]) is allocated and used by function ds@1952: ** accessPayload() (the worker function for sqlite3BtreeData() and ds@1952: ** sqlite3BtreePutData()). ds@1952: */ ds@1952: void sqlite3BtreeCacheOverflow(BtCursor *pCur){ ds@1952: assert( cursorHoldsMutex(pCur) ); ds@1952: assert( sqlite3_mutex_held(pCur->pBtree->pSqlite->mutex) ); ds@1952: assert(!pCur->isIncrblobHandle); ds@1952: assert(!pCur->aOverflow); ds@1952: pCur->isIncrblobHandle = 1; ds@1952: } ds@1952: #endif