blob: 06e7536870c0e1b3c42b0ef066f7acdc3cd4ec3f [file] [log] [blame]
drha059ad02001-04-17 20:09:11 +00001/*
drh9e572e62004-04-23 23:43:10 +00002** 2004 April 6
drha059ad02001-04-17 20:09:11 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drha059ad02001-04-17 20:09:11 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
drha059ad02001-04-17 20:09:11 +000010**
11*************************************************************************
danielk1977bd434552009-03-18 10:33:00 +000012** $Id: btree.c,v 1.575 2009/03/18 10:33:01 danielk1977 Exp $
drh8b2f49b2001-06-08 00:21:52 +000013**
14** This file implements a external (disk-based) database using BTrees.
drha3152892007-05-05 11:48:52 +000015** See the header comment on "btreeInt.h" for additional information.
16** Including a description of file format and an overview of operation.
drha059ad02001-04-17 20:09:11 +000017*/
drha3152892007-05-05 11:48:52 +000018#include "btreeInt.h"
paulb95a8862003-04-01 21:16:41 +000019
drh8c42ca92001-06-22 19:15:00 +000020/*
drha3152892007-05-05 11:48:52 +000021** The header string that appears at the beginning of every
22** SQLite database.
drh556b2a22005-06-14 16:04:05 +000023*/
drh556b2a22005-06-14 16:04:05 +000024static const char zMagicHeader[] = SQLITE_FILE_HEADER;
drh08ed44e2001-04-29 23:32:55 +000025
drh8c42ca92001-06-22 19:15:00 +000026/*
drha3152892007-05-05 11:48:52 +000027** Set this global variable to 1 to enable tracing using the TRACE
28** macro.
drh615ae552005-01-16 23:21:00 +000029*/
drhe8f52c52008-07-12 14:52:20 +000030#if 0
mlcreech3a00f902008-03-04 17:45:01 +000031int sqlite3BtreeTrace=0; /* True to enable tracing */
drhe8f52c52008-07-12 14:52:20 +000032# define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
33#else
34# define TRACE(X)
drh615ae552005-01-16 23:21:00 +000035#endif
drh615ae552005-01-16 23:21:00 +000036
drh86f8c192007-08-22 00:39:19 +000037
38
drhe53831d2007-08-17 01:14:38 +000039#ifndef SQLITE_OMIT_SHARED_CACHE
40/*
danielk1977502b4e02008-09-02 14:07:24 +000041** A list of BtShared objects that are eligible for participation
42** in shared cache. This variable has file scope during normal builds,
43** but the test harness needs to access it so we make it global for
44** test builds.
drhe53831d2007-08-17 01:14:38 +000045*/
46#ifdef SQLITE_TEST
drh78f82d12008-09-02 00:52:52 +000047BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
drhe53831d2007-08-17 01:14:38 +000048#else
drh78f82d12008-09-02 00:52:52 +000049static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
drhe53831d2007-08-17 01:14:38 +000050#endif
drhe53831d2007-08-17 01:14:38 +000051#endif /* SQLITE_OMIT_SHARED_CACHE */
52
53#ifndef SQLITE_OMIT_SHARED_CACHE
54/*
55** Enable or disable the shared pager and schema features.
56**
57** This routine has no effect on existing database connections.
58** The shared cache setting effects only future calls to
59** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
60*/
61int sqlite3_enable_shared_cache(int enable){
danielk1977502b4e02008-09-02 14:07:24 +000062 sqlite3GlobalConfig.sharedCacheEnabled = enable;
drhe53831d2007-08-17 01:14:38 +000063 return SQLITE_OK;
64}
65#endif
66
drhd677b3d2007-08-20 22:48:41 +000067
drh615ae552005-01-16 23:21:00 +000068/*
drh66cbd152004-09-01 16:12:25 +000069** Forward declaration
70*/
drh11b57d62009-02-24 19:21:41 +000071static int checkForReadConflicts(Btree*, Pgno, BtCursor*, i64);
drh66cbd152004-09-01 16:12:25 +000072
danielk1977aef0bf62005-12-30 16:28:01 +000073
74#ifdef SQLITE_OMIT_SHARED_CACHE
75 /*
drhc25eabe2009-02-24 18:57:31 +000076 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
77 ** and clearAllSharedCacheTableLocks()
danielk1977aef0bf62005-12-30 16:28:01 +000078 ** manipulate entries in the BtShared.pLock linked list used to store
79 ** shared-cache table level locks. If the library is compiled with the
80 ** shared-cache feature disabled, then there is only ever one user
danielk1977da184232006-01-05 11:34:32 +000081 ** of each BtShared structure and so this locking is not necessary.
82 ** So define the lock related functions as no-ops.
danielk1977aef0bf62005-12-30 16:28:01 +000083 */
drhc25eabe2009-02-24 18:57:31 +000084 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
85 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
86 #define clearAllSharedCacheTableLocks(a)
drhe53831d2007-08-17 01:14:38 +000087#endif
danielk1977aef0bf62005-12-30 16:28:01 +000088
drhe53831d2007-08-17 01:14:38 +000089#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977da184232006-01-05 11:34:32 +000090/*
danielk1977aef0bf62005-12-30 16:28:01 +000091** Query to see if btree handle p may obtain a lock of type eLock
92** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
drhc25eabe2009-02-24 18:57:31 +000093** SQLITE_OK if the lock may be obtained (by calling
94** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
danielk1977aef0bf62005-12-30 16:28:01 +000095*/
drhc25eabe2009-02-24 18:57:31 +000096static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
danielk1977aef0bf62005-12-30 16:28:01 +000097 BtShared *pBt = p->pBt;
98 BtLock *pIter;
99
drh1fee73e2007-08-29 04:00:57 +0000100 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000101 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
102 assert( p->db!=0 );
drhd677b3d2007-08-20 22:48:41 +0000103
danielk1977da184232006-01-05 11:34:32 +0000104 /* This is a no-op if the shared-cache is not enabled */
drhe53831d2007-08-17 01:14:38 +0000105 if( !p->sharable ){
danielk1977da184232006-01-05 11:34:32 +0000106 return SQLITE_OK;
107 }
108
danielk1977641b0f42007-12-21 04:47:25 +0000109 /* If some other connection is holding an exclusive lock, the
110 ** requested lock may not be obtained.
111 */
danielk1977404ca072009-03-16 13:19:36 +0000112 if( pBt->pWriter!=p && pBt->isExclusive ){
113 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
114 return SQLITE_LOCKED_SHAREDCACHE;
danielk1977641b0f42007-12-21 04:47:25 +0000115 }
116
drhc25eabe2009-02-24 18:57:31 +0000117 /* This (along with setSharedCacheTableLock()) is where
118 ** the ReadUncommitted flag is dealt with.
119 ** If the caller is querying for a read-lock on any table
drhc74d0b1d2009-02-24 16:18:05 +0000120 ** other than the sqlite_master table (table 1) and if the ReadUncommitted
121 ** flag is set, then the lock granted even if there are write-locks
danielk1977da184232006-01-05 11:34:32 +0000122 ** on the table. If a write-lock is requested, the ReadUncommitted flag
123 ** is not considered.
124 **
drhc25eabe2009-02-24 18:57:31 +0000125 ** In function setSharedCacheTableLock(), if a read-lock is demanded and the
danielk1977da184232006-01-05 11:34:32 +0000126 ** ReadUncommitted flag is set, no entry is added to the locks list
127 ** (BtShared.pLock).
128 **
drhc74d0b1d2009-02-24 16:18:05 +0000129 ** To summarize: If the ReadUncommitted flag is set, then read cursors
130 ** on non-schema tables do not create or respect table locks. The locking
131 ** procedure for a write-cursor does not change.
danielk1977da184232006-01-05 11:34:32 +0000132 */
133 if(
drhe5fe6902007-12-07 18:55:28 +0000134 0==(p->db->flags&SQLITE_ReadUncommitted) ||
danielk1977da184232006-01-05 11:34:32 +0000135 eLock==WRITE_LOCK ||
drh47ded162006-01-06 01:42:58 +0000136 iTab==MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000137 ){
138 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
139 if( pIter->pBtree!=p && pIter->iTable==iTab &&
140 (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
danielk1977404ca072009-03-16 13:19:36 +0000141 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
142 if( eLock==WRITE_LOCK ){
143 assert( p==pBt->pWriter );
144 pBt->isPending = 1;
145 }
146 return SQLITE_LOCKED_SHAREDCACHE;
danielk1977da184232006-01-05 11:34:32 +0000147 }
danielk1977aef0bf62005-12-30 16:28:01 +0000148 }
149 }
150 return SQLITE_OK;
151}
drhe53831d2007-08-17 01:14:38 +0000152#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000153
drhe53831d2007-08-17 01:14:38 +0000154#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000155/*
156** Add a lock on the table with root-page iTable to the shared-btree used
157** by Btree handle p. Parameter eLock must be either READ_LOCK or
158** WRITE_LOCK.
159**
160** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
161** SQLITE_NOMEM may also be returned.
162*/
drhc25eabe2009-02-24 18:57:31 +0000163static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
danielk1977aef0bf62005-12-30 16:28:01 +0000164 BtShared *pBt = p->pBt;
165 BtLock *pLock = 0;
166 BtLock *pIter;
167
drh1fee73e2007-08-29 04:00:57 +0000168 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000169 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
170 assert( p->db!=0 );
drhd677b3d2007-08-20 22:48:41 +0000171
danielk1977da184232006-01-05 11:34:32 +0000172 /* This is a no-op if the shared-cache is not enabled */
drhe53831d2007-08-17 01:14:38 +0000173 if( !p->sharable ){
danielk1977da184232006-01-05 11:34:32 +0000174 return SQLITE_OK;
175 }
176
drhc25eabe2009-02-24 18:57:31 +0000177 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
danielk1977aef0bf62005-12-30 16:28:01 +0000178
drhc74d0b1d2009-02-24 16:18:05 +0000179 /* If the read-uncommitted flag is set and a read-lock is requested on
180 ** a non-schema table, then the lock is always granted. Return early
181 ** without adding an entry to the BtShared.pLock list. See
drhc25eabe2009-02-24 18:57:31 +0000182 ** comment in function querySharedCacheTableLock() for more info
183 ** on handling the ReadUncommitted flag.
danielk1977da184232006-01-05 11:34:32 +0000184 */
185 if(
drhe5fe6902007-12-07 18:55:28 +0000186 (p->db->flags&SQLITE_ReadUncommitted) &&
danielk1977da184232006-01-05 11:34:32 +0000187 (eLock==READ_LOCK) &&
drh47ded162006-01-06 01:42:58 +0000188 iTable!=MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000189 ){
190 return SQLITE_OK;
191 }
192
danielk1977aef0bf62005-12-30 16:28:01 +0000193 /* First search the list for an existing lock on this table. */
194 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
195 if( pIter->iTable==iTable && pIter->pBtree==p ){
196 pLock = pIter;
197 break;
198 }
199 }
200
201 /* If the above search did not find a BtLock struct associating Btree p
202 ** with table iTable, allocate one and link it into the list.
203 */
204 if( !pLock ){
drh17435752007-08-16 04:30:38 +0000205 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
danielk1977aef0bf62005-12-30 16:28:01 +0000206 if( !pLock ){
207 return SQLITE_NOMEM;
208 }
209 pLock->iTable = iTable;
210 pLock->pBtree = p;
211 pLock->pNext = pBt->pLock;
212 pBt->pLock = pLock;
213 }
214
215 /* Set the BtLock.eLock variable to the maximum of the current lock
216 ** and the requested lock. This means if a write-lock was already held
217 ** and a read-lock requested, we don't incorrectly downgrade the lock.
218 */
219 assert( WRITE_LOCK>READ_LOCK );
danielk19775118b912005-12-30 16:31:53 +0000220 if( eLock>pLock->eLock ){
221 pLock->eLock = eLock;
222 }
danielk1977aef0bf62005-12-30 16:28:01 +0000223
224 return SQLITE_OK;
225}
drhe53831d2007-08-17 01:14:38 +0000226#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000227
drhe53831d2007-08-17 01:14:38 +0000228#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000229/*
drhc25eabe2009-02-24 18:57:31 +0000230** Release all the table locks (locks obtained via calls to
231** the setSharedCacheTableLock() procedure) held by Btree handle p.
danielk1977aef0bf62005-12-30 16:28:01 +0000232*/
drhc25eabe2009-02-24 18:57:31 +0000233static void clearAllSharedCacheTableLocks(Btree *p){
danielk1977641b0f42007-12-21 04:47:25 +0000234 BtShared *pBt = p->pBt;
235 BtLock **ppIter = &pBt->pLock;
danielk1977da184232006-01-05 11:34:32 +0000236
drh1fee73e2007-08-29 04:00:57 +0000237 assert( sqlite3BtreeHoldsMutex(p) );
drhe53831d2007-08-17 01:14:38 +0000238 assert( p->sharable || 0==*ppIter );
danielk1977da184232006-01-05 11:34:32 +0000239
danielk1977aef0bf62005-12-30 16:28:01 +0000240 while( *ppIter ){
241 BtLock *pLock = *ppIter;
danielk1977404ca072009-03-16 13:19:36 +0000242 assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
danielk1977aef0bf62005-12-30 16:28:01 +0000243 if( pLock->pBtree==p ){
244 *ppIter = pLock->pNext;
drh17435752007-08-16 04:30:38 +0000245 sqlite3_free(pLock);
danielk1977aef0bf62005-12-30 16:28:01 +0000246 }else{
247 ppIter = &pLock->pNext;
248 }
249 }
danielk1977641b0f42007-12-21 04:47:25 +0000250
danielk1977404ca072009-03-16 13:19:36 +0000251 assert( pBt->isPending==0 || pBt->pWriter );
252 if( pBt->pWriter==p ){
253 pBt->pWriter = 0;
254 pBt->isExclusive = 0;
255 pBt->isPending = 0;
256 }else if( pBt->nTransaction==2 ){
257 /* This function is called when connection p is concluding its
258 ** transaction. If there currently exists a writer, and p is not
259 ** that writer, then the number of locks held by connections other
260 ** than the writer must be about to drop to zero. In this case
261 ** set the isPending flag to 0.
262 **
263 ** If there is not currently a writer, then BtShared.isPending must
264 ** be zero already. So this next line is harmless in that case.
265 */
266 pBt->isPending = 0;
danielk1977641b0f42007-12-21 04:47:25 +0000267 }
danielk1977aef0bf62005-12-30 16:28:01 +0000268}
269#endif /* SQLITE_OMIT_SHARED_CACHE */
270
drh980b1a72006-08-16 16:42:48 +0000271static void releasePage(MemPage *pPage); /* Forward reference */
272
drh1fee73e2007-08-29 04:00:57 +0000273/*
274** Verify that the cursor holds a mutex on the BtShared
275*/
276#ifndef NDEBUG
277static int cursorHoldsMutex(BtCursor *p){
drhff0587c2007-08-29 17:43:19 +0000278 return sqlite3_mutex_held(p->pBt->mutex);
drh1fee73e2007-08-29 04:00:57 +0000279}
280#endif
281
282
danielk197792d4d7a2007-05-04 12:05:56 +0000283#ifndef SQLITE_OMIT_INCRBLOB
284/*
285** Invalidate the overflow page-list cache for cursor pCur, if any.
286*/
287static void invalidateOverflowCache(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000288 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000289 sqlite3_free(pCur->aOverflow);
danielk197792d4d7a2007-05-04 12:05:56 +0000290 pCur->aOverflow = 0;
291}
292
293/*
294** Invalidate the overflow page-list cache for all cursors opened
295** on the shared btree structure pBt.
296*/
297static void invalidateAllOverflowCache(BtShared *pBt){
298 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000299 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +0000300 for(p=pBt->pCursor; p; p=p->pNext){
301 invalidateOverflowCache(p);
302 }
303}
304#else
305 #define invalidateOverflowCache(x)
306 #define invalidateAllOverflowCache(x)
307#endif
308
drh980b1a72006-08-16 16:42:48 +0000309/*
danielk1977bea2a942009-01-20 17:06:27 +0000310** Set bit pgno of the BtShared.pHasContent bitvec. This is called
311** when a page that previously contained data becomes a free-list leaf
312** page.
313**
314** The BtShared.pHasContent bitvec exists to work around an obscure
315** bug caused by the interaction of two useful IO optimizations surrounding
316** free-list leaf pages:
317**
318** 1) When all data is deleted from a page and the page becomes
319** a free-list leaf page, the page is not written to the database
320** (as free-list leaf pages contain no meaningful data). Sometimes
321** such a page is not even journalled (as it will not be modified,
322** why bother journalling it?).
323**
324** 2) When a free-list leaf page is reused, its content is not read
325** from the database or written to the journal file (why should it
326** be, if it is not at all meaningful?).
327**
328** By themselves, these optimizations work fine and provide a handy
329** performance boost to bulk delete or insert operations. However, if
330** a page is moved to the free-list and then reused within the same
331** transaction, a problem comes up. If the page is not journalled when
332** it is moved to the free-list and it is also not journalled when it
333** is extracted from the free-list and reused, then the original data
334** may be lost. In the event of a rollback, it may not be possible
335** to restore the database to its original configuration.
336**
337** The solution is the BtShared.pHasContent bitvec. Whenever a page is
338** moved to become a free-list leaf page, the corresponding bit is
339** set in the bitvec. Whenever a leaf page is extracted from the free-list,
340** optimization 2 above is ommitted if the corresponding bit is already
341** set in BtShared.pHasContent. The contents of the bitvec are cleared
342** at the end of every transaction.
343*/
344static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
345 int rc = SQLITE_OK;
346 if( !pBt->pHasContent ){
347 int nPage;
348 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
349 if( rc==SQLITE_OK ){
350 pBt->pHasContent = sqlite3BitvecCreate((u32)nPage);
351 if( !pBt->pHasContent ){
352 rc = SQLITE_NOMEM;
353 }
354 }
355 }
356 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
357 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
358 }
359 return rc;
360}
361
362/*
363** Query the BtShared.pHasContent vector.
364**
365** This function is called when a free-list leaf page is removed from the
366** free-list for reuse. It returns false if it is safe to retrieve the
367** page from the pager layer with the 'no-content' flag set. True otherwise.
368*/
369static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
370 Bitvec *p = pBt->pHasContent;
371 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
372}
373
374/*
375** Clear (destroy) the BtShared.pHasContent bitvec. This should be
376** invoked at the conclusion of each write-transaction.
377*/
378static void btreeClearHasContent(BtShared *pBt){
379 sqlite3BitvecDestroy(pBt->pHasContent);
380 pBt->pHasContent = 0;
381}
382
383/*
drh980b1a72006-08-16 16:42:48 +0000384** Save the current cursor position in the variables BtCursor.nKey
385** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
386*/
387static int saveCursorPosition(BtCursor *pCur){
388 int rc;
389
390 assert( CURSOR_VALID==pCur->eState );
391 assert( 0==pCur->pKey );
drh1fee73e2007-08-29 04:00:57 +0000392 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000393
394 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
395
396 /* If this is an intKey table, then the above call to BtreeKeySize()
397 ** stores the integer key in pCur->nKey. In this case this value is
398 ** all that is required. Otherwise, if pCur is not open on an intKey
399 ** table, then malloc space for and store the pCur->nKey bytes of key
400 ** data.
401 */
danielk197771d5d2c2008-09-29 11:49:47 +0000402 if( rc==SQLITE_OK && 0==pCur->apPage[0]->intKey){
drhf49661a2008-12-10 16:45:50 +0000403 void *pKey = sqlite3Malloc( (int)pCur->nKey );
drh980b1a72006-08-16 16:42:48 +0000404 if( pKey ){
drhf49661a2008-12-10 16:45:50 +0000405 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
drh980b1a72006-08-16 16:42:48 +0000406 if( rc==SQLITE_OK ){
407 pCur->pKey = pKey;
408 }else{
drh17435752007-08-16 04:30:38 +0000409 sqlite3_free(pKey);
drh980b1a72006-08-16 16:42:48 +0000410 }
411 }else{
412 rc = SQLITE_NOMEM;
413 }
414 }
danielk197771d5d2c2008-09-29 11:49:47 +0000415 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
drh980b1a72006-08-16 16:42:48 +0000416
417 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +0000418 int i;
419 for(i=0; i<=pCur->iPage; i++){
420 releasePage(pCur->apPage[i]);
421 pCur->apPage[i] = 0;
422 }
423 pCur->iPage = -1;
drh980b1a72006-08-16 16:42:48 +0000424 pCur->eState = CURSOR_REQUIRESEEK;
425 }
426
danielk197792d4d7a2007-05-04 12:05:56 +0000427 invalidateOverflowCache(pCur);
drh980b1a72006-08-16 16:42:48 +0000428 return rc;
429}
430
431/*
432** Save the positions of all cursors except pExcept open on the table
433** with root-page iRoot. Usually, this is called just before cursor
434** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
435*/
436static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
437 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000438 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +0000439 assert( pExcept==0 || pExcept->pBt==pBt );
drh980b1a72006-08-16 16:42:48 +0000440 for(p=pBt->pCursor; p; p=p->pNext){
441 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
442 p->eState==CURSOR_VALID ){
443 int rc = saveCursorPosition(p);
444 if( SQLITE_OK!=rc ){
445 return rc;
446 }
447 }
448 }
449 return SQLITE_OK;
450}
451
452/*
drhbf700f32007-03-31 02:36:44 +0000453** Clear the current cursor position.
454*/
danielk1977be51a652008-10-08 17:58:48 +0000455void sqlite3BtreeClearCursor(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000456 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000457 sqlite3_free(pCur->pKey);
drhbf700f32007-03-31 02:36:44 +0000458 pCur->pKey = 0;
459 pCur->eState = CURSOR_INVALID;
460}
461
462/*
drh980b1a72006-08-16 16:42:48 +0000463** Restore the cursor to the position it was in (or as close to as possible)
464** when saveCursorPosition() was called. Note that this call deletes the
465** saved position info stored by saveCursorPosition(), so there can be
drha3460582008-07-11 21:02:53 +0000466** at most one effective restoreCursorPosition() call after each
drh980b1a72006-08-16 16:42:48 +0000467** saveCursorPosition().
drh980b1a72006-08-16 16:42:48 +0000468*/
drha3460582008-07-11 21:02:53 +0000469int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +0000470 int rc;
drh1fee73e2007-08-29 04:00:57 +0000471 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +0000472 assert( pCur->eState>=CURSOR_REQUIRESEEK );
473 if( pCur->eState==CURSOR_FAULT ){
474 return pCur->skip;
475 }
drh980b1a72006-08-16 16:42:48 +0000476 pCur->eState = CURSOR_INVALID;
drhe63d9992008-08-13 19:11:48 +0000477 rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skip);
drh980b1a72006-08-16 16:42:48 +0000478 if( rc==SQLITE_OK ){
drh17435752007-08-16 04:30:38 +0000479 sqlite3_free(pCur->pKey);
drh980b1a72006-08-16 16:42:48 +0000480 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +0000481 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drh980b1a72006-08-16 16:42:48 +0000482 }
483 return rc;
484}
485
drha3460582008-07-11 21:02:53 +0000486#define restoreCursorPosition(p) \
drhfb982642007-08-30 01:19:59 +0000487 (p->eState>=CURSOR_REQUIRESEEK ? \
drha3460582008-07-11 21:02:53 +0000488 sqlite3BtreeRestoreCursorPosition(p) : \
drh16a9b832007-05-05 18:39:25 +0000489 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +0000490
drha3460582008-07-11 21:02:53 +0000491/*
492** Determine whether or not a cursor has moved from the position it
drhdfe88ec2008-11-03 20:55:06 +0000493** was last placed at. Cursors can move when the row they are pointing
drha3460582008-07-11 21:02:53 +0000494** at is deleted out from under them.
495**
496** This routine returns an error code if something goes wrong. The
497** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
498*/
499int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
500 int rc;
501
502 rc = restoreCursorPosition(pCur);
503 if( rc ){
504 *pHasMoved = 1;
505 return rc;
506 }
507 if( pCur->eState!=CURSOR_VALID || pCur->skip!=0 ){
508 *pHasMoved = 1;
509 }else{
510 *pHasMoved = 0;
511 }
512 return SQLITE_OK;
513}
514
danielk1977599fcba2004-11-08 07:13:13 +0000515#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000516/*
drha3152892007-05-05 11:48:52 +0000517** Given a page number of a regular database page, return the page
518** number for the pointer-map page that contains the entry for the
519** input page number.
danielk1977afcdd022004-10-31 16:25:42 +0000520*/
danielk1977266664d2006-02-10 08:24:21 +0000521static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
danielk197789d40042008-11-17 14:20:56 +0000522 int nPagesPerMapPage;
523 Pgno iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +0000524 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000525 nPagesPerMapPage = (pBt->usableSize/5)+1;
526 iPtrMap = (pgno-2)/nPagesPerMapPage;
527 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +0000528 if( ret==PENDING_BYTE_PAGE(pBt) ){
529 ret++;
530 }
531 return ret;
532}
danielk1977a19df672004-11-03 11:37:07 +0000533
danielk1977afcdd022004-10-31 16:25:42 +0000534/*
danielk1977afcdd022004-10-31 16:25:42 +0000535** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000536**
537** This routine updates the pointer map entry for page number 'key'
538** so that it maps to type 'eType' and parent page number 'pgno'.
539** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000540*/
danielk1977aef0bf62005-12-30 16:28:01 +0000541static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
danielk19773b8a05f2007-03-19 17:44:26 +0000542 DbPage *pDbPage; /* The pointer map page */
543 u8 *pPtrmap; /* The pointer map data */
544 Pgno iPtrmap; /* The pointer map page number */
545 int offset; /* Offset in pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000546 int rc;
547
drh1fee73e2007-08-29 04:00:57 +0000548 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977266664d2006-02-10 08:24:21 +0000549 /* The master-journal page number must never be used as a pointer map page */
550 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
551
danielk1977ac11ee62005-01-15 12:45:51 +0000552 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000553 if( key==0 ){
drh49285702005-09-17 15:20:26 +0000554 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000555 }
danielk1977266664d2006-02-10 08:24:21 +0000556 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000557 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977687566d2004-11-02 12:56:41 +0000558 if( rc!=SQLITE_OK ){
danielk1977afcdd022004-10-31 16:25:42 +0000559 return rc;
560 }
danielk19778c666b12008-07-18 09:34:57 +0000561 offset = PTRMAP_PTROFFSET(iPtrmap, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000562 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000563
drh615ae552005-01-16 23:21:00 +0000564 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
565 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
danielk19773b8a05f2007-03-19 17:44:26 +0000566 rc = sqlite3PagerWrite(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000567 if( rc==SQLITE_OK ){
568 pPtrmap[offset] = eType;
569 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000570 }
danielk1977afcdd022004-10-31 16:25:42 +0000571 }
572
danielk19773b8a05f2007-03-19 17:44:26 +0000573 sqlite3PagerUnref(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000574 return rc;
danielk1977afcdd022004-10-31 16:25:42 +0000575}
576
577/*
578** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000579**
580** This routine retrieves the pointer map entry for page 'key', writing
581** the type and parent page number to *pEType and *pPgno respectively.
582** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000583*/
danielk1977aef0bf62005-12-30 16:28:01 +0000584static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +0000585 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000586 int iPtrmap; /* Pointer map page index */
587 u8 *pPtrmap; /* Pointer map page data */
588 int offset; /* Offset of entry in pointer map */
589 int rc;
590
drh1fee73e2007-08-29 04:00:57 +0000591 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000592
danielk1977266664d2006-02-10 08:24:21 +0000593 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000594 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000595 if( rc!=0 ){
596 return rc;
597 }
danielk19773b8a05f2007-03-19 17:44:26 +0000598 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000599
danielk19778c666b12008-07-18 09:34:57 +0000600 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drh43617e92006-03-06 20:55:46 +0000601 assert( pEType!=0 );
602 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +0000603 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000604
danielk19773b8a05f2007-03-19 17:44:26 +0000605 sqlite3PagerUnref(pDbPage);
drh49285702005-09-17 15:20:26 +0000606 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000607 return SQLITE_OK;
608}
609
danielk197785d90ca2008-07-19 14:25:15 +0000610#else /* if defined SQLITE_OMIT_AUTOVACUUM */
611 #define ptrmapPut(w,x,y,z) SQLITE_OK
612 #define ptrmapGet(w,x,y,z) SQLITE_OK
613 #define ptrmapPutOvfl(y,z) SQLITE_OK
614#endif
danielk1977afcdd022004-10-31 16:25:42 +0000615
drh0d316a42002-08-11 20:10:47 +0000616/*
drh271efa52004-05-30 19:19:05 +0000617** Given a btree page and a cell index (0 means the first cell on
618** the page, 1 means the second cell, and so forth) return a pointer
619** to the cell content.
620**
621** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000622*/
drh1688c862008-07-18 02:44:17 +0000623#define findCell(P,I) \
624 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
drh43605152004-05-29 21:46:49 +0000625
626/*
drh93a960a2008-07-10 00:32:42 +0000627** This a more complex version of findCell() that works for
drh43605152004-05-29 21:46:49 +0000628** pages that do contain overflow cells. See insert
629*/
630static u8 *findOverflowCell(MemPage *pPage, int iCell){
631 int i;
drh1fee73e2007-08-29 04:00:57 +0000632 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +0000633 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000634 int k;
635 struct _OvflCell *pOvfl;
636 pOvfl = &pPage->aOvfl[i];
637 k = pOvfl->idx;
638 if( k<=iCell ){
639 if( k==iCell ){
640 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000641 }
642 iCell--;
643 }
644 }
danielk19771cc5ed82007-05-16 17:28:43 +0000645 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000646}
647
648/*
649** Parse a cell content block and fill in the CellInfo structure. There
drh16a9b832007-05-05 18:39:25 +0000650** are two versions of this function. sqlite3BtreeParseCell() takes a
651** cell index as the second argument and sqlite3BtreeParseCellPtr()
652** takes a pointer to the body of the cell as its second argument.
danielk19771cc5ed82007-05-16 17:28:43 +0000653**
654** Within this file, the parseCell() macro can be called instead of
655** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
drh43605152004-05-29 21:46:49 +0000656*/
drh16a9b832007-05-05 18:39:25 +0000657void sqlite3BtreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000658 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000659 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000660 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000661){
drhf49661a2008-12-10 16:45:50 +0000662 u16 n; /* Number bytes in cell content header */
drh271efa52004-05-30 19:19:05 +0000663 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000664
drh1fee73e2007-08-29 04:00:57 +0000665 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000666
drh43605152004-05-29 21:46:49 +0000667 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000668 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000669 n = pPage->childPtrSize;
670 assert( n==4-4*pPage->leaf );
drh504b6982006-01-22 21:52:56 +0000671 if( pPage->intKey ){
drh79df1f42008-07-18 00:57:33 +0000672 if( pPage->hasData ){
673 n += getVarint32(&pCell[n], nPayload);
674 }else{
675 nPayload = 0;
676 }
drh1bd10f82008-12-10 21:19:56 +0000677 n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
drh79df1f42008-07-18 00:57:33 +0000678 pInfo->nData = nPayload;
drh504b6982006-01-22 21:52:56 +0000679 }else{
drh79df1f42008-07-18 00:57:33 +0000680 pInfo->nData = 0;
681 n += getVarint32(&pCell[n], nPayload);
682 pInfo->nKey = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000683 }
drh72365832007-03-06 15:53:44 +0000684 pInfo->nPayload = nPayload;
drh504b6982006-01-22 21:52:56 +0000685 pInfo->nHeader = n;
drh79df1f42008-07-18 00:57:33 +0000686 if( likely(nPayload<=pPage->maxLocal) ){
drh271efa52004-05-30 19:19:05 +0000687 /* This is the (easy) common case where the entire payload fits
688 ** on the local page. No overflow is required.
689 */
690 int nSize; /* Total size of cell content in bytes */
drh79df1f42008-07-18 00:57:33 +0000691 nSize = nPayload + n;
drhf49661a2008-12-10 16:45:50 +0000692 pInfo->nLocal = (u16)nPayload;
drh6f11bef2004-05-13 01:12:56 +0000693 pInfo->iOverflow = 0;
drh79df1f42008-07-18 00:57:33 +0000694 if( (nSize & ~3)==0 ){
drh271efa52004-05-30 19:19:05 +0000695 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000696 }
drh1bd10f82008-12-10 21:19:56 +0000697 pInfo->nSize = (u16)nSize;
drh6f11bef2004-05-13 01:12:56 +0000698 }else{
drh271efa52004-05-30 19:19:05 +0000699 /* If the payload will not fit completely on the local page, we have
700 ** to decide how much to store locally and how much to spill onto
701 ** overflow pages. The strategy is to minimize the amount of unused
702 ** space on overflow pages while keeping the amount of local storage
703 ** in between minLocal and maxLocal.
704 **
705 ** Warning: changing the way overflow payload is distributed in any
706 ** way will result in an incompatible file format.
707 */
708 int minLocal; /* Minimum amount of payload held locally */
709 int maxLocal; /* Maximum amount of payload held locally */
710 int surplus; /* Overflow payload available for local storage */
711
712 minLocal = pPage->minLocal;
713 maxLocal = pPage->maxLocal;
714 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000715 if( surplus <= maxLocal ){
drhf49661a2008-12-10 16:45:50 +0000716 pInfo->nLocal = (u16)surplus;
drh6f11bef2004-05-13 01:12:56 +0000717 }else{
drhf49661a2008-12-10 16:45:50 +0000718 pInfo->nLocal = (u16)minLocal;
drh6f11bef2004-05-13 01:12:56 +0000719 }
drhf49661a2008-12-10 16:45:50 +0000720 pInfo->iOverflow = (u16)(pInfo->nLocal + n);
drh6f11bef2004-05-13 01:12:56 +0000721 pInfo->nSize = pInfo->iOverflow + 4;
722 }
drh3aac2dd2004-04-26 14:10:20 +0000723}
danielk19771cc5ed82007-05-16 17:28:43 +0000724#define parseCell(pPage, iCell, pInfo) \
725 sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
drh16a9b832007-05-05 18:39:25 +0000726void sqlite3BtreeParseCell(
drh43605152004-05-29 21:46:49 +0000727 MemPage *pPage, /* Page containing the cell */
728 int iCell, /* The cell index. First cell is 0 */
729 CellInfo *pInfo /* Fill in this structure */
730){
danielk19771cc5ed82007-05-16 17:28:43 +0000731 parseCell(pPage, iCell, pInfo);
drh43605152004-05-29 21:46:49 +0000732}
drh3aac2dd2004-04-26 14:10:20 +0000733
734/*
drh43605152004-05-29 21:46:49 +0000735** Compute the total number of bytes that a Cell needs in the cell
736** data area of the btree-page. The return number includes the cell
737** data header and the local payload, but not any overflow page or
738** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000739*/
danielk1977bc6ada42004-06-30 08:20:16 +0000740#ifndef NDEBUG
drha9121e42008-02-19 14:59:35 +0000741static u16 cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000742 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000743 sqlite3BtreeParseCell(pPage, iCell, &info);
drh43605152004-05-29 21:46:49 +0000744 return info.nSize;
745}
danielk1977bc6ada42004-06-30 08:20:16 +0000746#endif
drha9121e42008-02-19 14:59:35 +0000747static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
drh43605152004-05-29 21:46:49 +0000748 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000749 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000750 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000751}
752
danielk197779a40da2005-01-16 08:00:01 +0000753#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +0000754/*
danielk197726836652005-01-17 01:33:13 +0000755** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +0000756** to an overflow page, insert an entry into the pointer-map
757** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +0000758*/
danielk197726836652005-01-17 01:33:13 +0000759static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
drhfa67c3c2008-07-11 02:21:40 +0000760 CellInfo info;
761 assert( pCell!=0 );
762 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
763 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
764 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
765 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
766 return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +0000767 }
danielk197779a40da2005-01-16 08:00:01 +0000768 return SQLITE_OK;
danielk1977ac11ee62005-01-15 12:45:51 +0000769}
danielk197726836652005-01-17 01:33:13 +0000770/*
771** If the cell with index iCell on page pPage contains a pointer
772** to an overflow page, insert an entry into the pointer-map
773** for the overflow page.
774*/
775static int ptrmapPutOvfl(MemPage *pPage, int iCell){
776 u8 *pCell;
drh1fee73e2007-08-29 04:00:57 +0000777 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197726836652005-01-17 01:33:13 +0000778 pCell = findOverflowCell(pPage, iCell);
779 return ptrmapPutOvflPtr(pPage, pCell);
780}
danielk197779a40da2005-01-16 08:00:01 +0000781#endif
782
danielk1977ac11ee62005-01-15 12:45:51 +0000783
drhda200cc2004-05-09 11:51:38 +0000784/*
drh72f82862001-05-24 21:06:34 +0000785** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +0000786** end of the page and all free space is collected into one
787** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +0000788** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +0000789*/
shane0af3f892008-11-12 04:55:34 +0000790static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000791 int i; /* Loop counter */
792 int pc; /* Address of a i-th cell */
793 int addr; /* Offset of first byte after cell pointer array */
794 int hdr; /* Offset to the page header */
795 int size; /* Size of a cell */
796 int usableSize; /* Number of usable bytes on a page */
797 int cellOffset; /* Offset to the cell pointer array */
drh281b21d2008-08-22 12:57:08 +0000798 int cbrk; /* Offset to the cell content area */
drh43605152004-05-29 21:46:49 +0000799 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +0000800 unsigned char *data; /* The page data */
801 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +0000802
danielk19773b8a05f2007-03-19 17:44:26 +0000803 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000804 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +0000805 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000806 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +0000807 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh26b79942007-11-28 16:19:56 +0000808 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
drh43605152004-05-29 21:46:49 +0000809 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +0000810 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000811 cellOffset = pPage->cellOffset;
812 nCell = pPage->nCell;
813 assert( nCell==get2byte(&data[hdr+3]) );
814 usableSize = pPage->pBt->usableSize;
drh281b21d2008-08-22 12:57:08 +0000815 cbrk = get2byte(&data[hdr+5]);
816 memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
817 cbrk = usableSize;
drh43605152004-05-29 21:46:49 +0000818 for(i=0; i<nCell; i++){
819 u8 *pAddr; /* The i-th cell pointer */
820 pAddr = &data[cellOffset + i*2];
821 pc = get2byte(pAddr);
shanedcc50b72008-11-13 18:29:50 +0000822 if( pc>=usableSize ){
shane0af3f892008-11-12 04:55:34 +0000823 return SQLITE_CORRUPT_BKPT;
824 }
drh43605152004-05-29 21:46:49 +0000825 size = cellSizePtr(pPage, &temp[pc]);
drh281b21d2008-08-22 12:57:08 +0000826 cbrk -= size;
danielk19770d065412008-11-12 18:21:36 +0000827 if( cbrk<cellOffset+2*nCell || pc+size>usableSize ){
shane0af3f892008-11-12 04:55:34 +0000828 return SQLITE_CORRUPT_BKPT;
829 }
danielk19770d065412008-11-12 18:21:36 +0000830 assert( cbrk+size<=usableSize && cbrk>=0 );
drh281b21d2008-08-22 12:57:08 +0000831 memcpy(&data[cbrk], &temp[pc], size);
832 put2byte(pAddr, cbrk);
drh2af926b2001-05-15 00:39:25 +0000833 }
drh281b21d2008-08-22 12:57:08 +0000834 assert( cbrk>=cellOffset+2*nCell );
835 put2byte(&data[hdr+5], cbrk);
drh43605152004-05-29 21:46:49 +0000836 data[hdr+1] = 0;
837 data[hdr+2] = 0;
838 data[hdr+7] = 0;
839 addr = cellOffset+2*nCell;
drh281b21d2008-08-22 12:57:08 +0000840 memset(&data[addr], 0, cbrk-addr);
drhc5053fb2008-11-27 02:22:10 +0000841 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977360e6342008-11-12 08:49:51 +0000842 if( cbrk-addr!=pPage->nFree ){
843 return SQLITE_CORRUPT_BKPT;
844 }
shane0af3f892008-11-12 04:55:34 +0000845 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +0000846}
847
drha059ad02001-04-17 20:09:11 +0000848/*
drh43605152004-05-29 21:46:49 +0000849** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +0000850**
drh9e572e62004-04-23 23:43:10 +0000851** Return the index into pPage->aData[] of the first byte of
drhfa67c3c2008-07-11 02:21:40 +0000852** the new allocation. The caller guarantees that there is enough
853** space. This routine will never fail.
drh2af926b2001-05-15 00:39:25 +0000854**
drh72f82862001-05-24 21:06:34 +0000855** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000856** nBytes of contiguous free space, then this routine automatically
857** calls defragementPage() to consolidate all free space before
858** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000859*/
drh9e572e62004-04-23 23:43:10 +0000860static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +0000861 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +0000862 int size;
drh24cd67e2004-05-10 16:18:47 +0000863 int nFrag;
drh43605152004-05-29 21:46:49 +0000864 int top;
865 int nCell;
866 int cellOffset;
drh9e572e62004-04-23 23:43:10 +0000867 unsigned char *data;
drh43605152004-05-29 21:46:49 +0000868
drh9e572e62004-04-23 23:43:10 +0000869 data = pPage->aData;
danielk19773b8a05f2007-03-19 17:44:26 +0000870 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000871 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +0000872 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa67c3c2008-07-11 02:21:40 +0000873 assert( nByte>=0 ); /* Minimum cell size is 4 */
874 assert( pPage->nFree>=nByte );
875 assert( pPage->nOverflow==0 );
drhf49661a2008-12-10 16:45:50 +0000876 pPage->nFree -= (u16)nByte;
drh9e572e62004-04-23 23:43:10 +0000877 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000878
879 nFrag = data[hdr+7];
880 if( nFrag<60 ){
881 /* Search the freelist looking for a slot big enough to satisfy the
882 ** space request. */
883 addr = hdr+1;
884 while( (pc = get2byte(&data[addr]))>0 ){
885 size = get2byte(&data[pc+2]);
886 if( size>=nByte ){
drhf49661a2008-12-10 16:45:50 +0000887 int x = size - nByte;
drh43605152004-05-29 21:46:49 +0000888 if( size<nByte+4 ){
889 memcpy(&data[addr], &data[pc], 2);
drhf49661a2008-12-10 16:45:50 +0000890 data[hdr+7] = (u8)(nFrag + x);
drh43605152004-05-29 21:46:49 +0000891 return pc;
892 }else{
drhf49661a2008-12-10 16:45:50 +0000893 put2byte(&data[pc+2], x);
894 return pc + x;
drh43605152004-05-29 21:46:49 +0000895 }
896 }
897 addr = pc;
drh9e572e62004-04-23 23:43:10 +0000898 }
899 }
drh43605152004-05-29 21:46:49 +0000900
901 /* Allocate memory from the gap in between the cell pointer array
902 ** and the cell content area.
903 */
904 top = get2byte(&data[hdr+5]);
905 nCell = get2byte(&data[hdr+3]);
906 cellOffset = pPage->cellOffset;
907 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
danielk1977474b7cc2008-07-09 11:49:46 +0000908 defragmentPage(pPage);
drh43605152004-05-29 21:46:49 +0000909 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +0000910 }
drh43605152004-05-29 21:46:49 +0000911 top -= nByte;
912 assert( cellOffset + 2*nCell <= top );
913 put2byte(&data[hdr+5], top);
drhc5053fb2008-11-27 02:22:10 +0000914 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +0000915 return top;
drh7e3b0a02001-04-28 16:52:40 +0000916}
917
918/*
drh9e572e62004-04-23 23:43:10 +0000919** Return a section of the pPage->aData to the freelist.
920** The first byte of the new free block is pPage->aDisk[start]
921** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +0000922**
923** Most of the effort here is involved in coalesing adjacent
924** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000925*/
shanedcc50b72008-11-13 18:29:50 +0000926static int freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +0000927 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +0000928 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +0000929
drh9e572e62004-04-23 23:43:10 +0000930 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +0000931 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000932 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +0000933 assert( (start + size)<=pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +0000934 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh34004ce2008-07-11 16:15:17 +0000935 assert( size>=0 ); /* Minimum cell size is 4 */
drh9e572e62004-04-23 23:43:10 +0000936
drhfcce93f2006-02-22 03:08:32 +0000937#ifdef SQLITE_SECURE_DELETE
938 /* Overwrite deleted information with zeros when the SECURE_DELETE
939 ** option is enabled at compile-time */
940 memset(&data[start], 0, size);
941#endif
942
drh9e572e62004-04-23 23:43:10 +0000943 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +0000944 hdr = pPage->hdrOffset;
945 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +0000946 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +0000947 assert( pbegin<=pPage->pBt->usableSize-4 );
shanedcc50b72008-11-13 18:29:50 +0000948 if( pbegin<=addr ) {
949 return SQLITE_CORRUPT_BKPT;
950 }
drh3aac2dd2004-04-26 14:10:20 +0000951 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +0000952 }
shanedcc50b72008-11-13 18:29:50 +0000953 if ( pbegin>pPage->pBt->usableSize-4 ) {
954 return SQLITE_CORRUPT_BKPT;
955 }
drh3aac2dd2004-04-26 14:10:20 +0000956 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +0000957 put2byte(&data[addr], start);
958 put2byte(&data[start], pbegin);
959 put2byte(&data[start+2], size);
drhf49661a2008-12-10 16:45:50 +0000960 pPage->nFree += (u16)size;
drh9e572e62004-04-23 23:43:10 +0000961
962 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +0000963 addr = pPage->hdrOffset + 1;
964 while( (pbegin = get2byte(&data[addr]))>0 ){
drhf49661a2008-12-10 16:45:50 +0000965 int pnext, psize, x;
drh3aac2dd2004-04-26 14:10:20 +0000966 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +0000967 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +0000968 pnext = get2byte(&data[pbegin]);
969 psize = get2byte(&data[pbegin+2]);
970 if( pbegin + psize + 3 >= pnext && pnext>0 ){
971 int frag = pnext - (pbegin+psize);
drhf49661a2008-12-10 16:45:50 +0000972 if( (frag<0) || (frag>(int)data[pPage->hdrOffset+7]) ){
shanedcc50b72008-11-13 18:29:50 +0000973 return SQLITE_CORRUPT_BKPT;
974 }
drhf49661a2008-12-10 16:45:50 +0000975 data[pPage->hdrOffset+7] -= (u8)frag;
976 x = get2byte(&data[pnext]);
977 put2byte(&data[pbegin], x);
978 x = pnext + get2byte(&data[pnext+2]) - pbegin;
979 put2byte(&data[pbegin+2], x);
drh9e572e62004-04-23 23:43:10 +0000980 }else{
drh3aac2dd2004-04-26 14:10:20 +0000981 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +0000982 }
983 }
drh7e3b0a02001-04-28 16:52:40 +0000984
drh43605152004-05-29 21:46:49 +0000985 /* If the cell content area begins with a freeblock, remove it. */
986 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
987 int top;
988 pbegin = get2byte(&data[hdr+1]);
989 memcpy(&data[hdr+1], &data[pbegin], 2);
drhf49661a2008-12-10 16:45:50 +0000990 top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
991 put2byte(&data[hdr+5], top);
drh4b70f112004-05-02 21:12:19 +0000992 }
drhc5053fb2008-11-27 02:22:10 +0000993 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
shanedcc50b72008-11-13 18:29:50 +0000994 return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +0000995}
996
997/*
drh271efa52004-05-30 19:19:05 +0000998** Decode the flags byte (the first byte of the header) for a page
999** and initialize fields of the MemPage structure accordingly.
drh44845222008-07-17 18:39:57 +00001000**
1001** Only the following combinations are supported. Anything different
1002** indicates a corrupt database files:
1003**
1004** PTF_ZERODATA
1005** PTF_ZERODATA | PTF_LEAF
1006** PTF_LEAFDATA | PTF_INTKEY
1007** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
drh271efa52004-05-30 19:19:05 +00001008*/
drh44845222008-07-17 18:39:57 +00001009static int decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +00001010 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +00001011
1012 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +00001013 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00001014 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
drh44845222008-07-17 18:39:57 +00001015 flagByte &= ~PTF_LEAF;
1016 pPage->childPtrSize = 4-4*pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001017 pBt = pPage->pBt;
drh44845222008-07-17 18:39:57 +00001018 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
1019 pPage->intKey = 1;
1020 pPage->hasData = pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001021 pPage->maxLocal = pBt->maxLeaf;
1022 pPage->minLocal = pBt->minLeaf;
drh44845222008-07-17 18:39:57 +00001023 }else if( flagByte==PTF_ZERODATA ){
1024 pPage->intKey = 0;
1025 pPage->hasData = 0;
drh271efa52004-05-30 19:19:05 +00001026 pPage->maxLocal = pBt->maxLocal;
1027 pPage->minLocal = pBt->minLocal;
drh44845222008-07-17 18:39:57 +00001028 }else{
1029 return SQLITE_CORRUPT_BKPT;
drh271efa52004-05-30 19:19:05 +00001030 }
drh44845222008-07-17 18:39:57 +00001031 return SQLITE_OK;
drh271efa52004-05-30 19:19:05 +00001032}
1033
1034/*
drh7e3b0a02001-04-28 16:52:40 +00001035** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +00001036**
1037** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +00001038** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +00001039** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1040** guarantee that the page is well-formed. It only shows that
1041** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001042*/
danielk197771d5d2c2008-09-29 11:49:47 +00001043int sqlite3BtreeInitPage(MemPage *pPage){
drh2af926b2001-05-15 00:39:25 +00001044
danielk197771d5d2c2008-09-29 11:49:47 +00001045 assert( pPage->pBt!=0 );
1046 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001047 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +00001048 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1049 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00001050
1051 if( !pPage->isInit ){
drhf49661a2008-12-10 16:45:50 +00001052 u16 pc; /* Address of a freeblock within pPage->aData[] */
1053 u8 hdr; /* Offset to beginning of page header */
danielk197771d5d2c2008-09-29 11:49:47 +00001054 u8 *data; /* Equal to pPage->aData */
1055 BtShared *pBt; /* The main btree structure */
drhf49661a2008-12-10 16:45:50 +00001056 u16 usableSize; /* Amount of usable space on each page */
1057 u16 cellOffset; /* Offset from start of page to first cell pointer */
1058 u16 nFree; /* Number of unused bytes on the page */
1059 u16 top; /* First byte of the cell content area */
danielk197771d5d2c2008-09-29 11:49:47 +00001060
1061 pBt = pPage->pBt;
1062
danielk1977eaa06f62008-09-18 17:34:44 +00001063 hdr = pPage->hdrOffset;
1064 data = pPage->aData;
1065 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
1066 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
1067 pPage->maskPage = pBt->pageSize - 1;
1068 pPage->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00001069 usableSize = pBt->usableSize;
1070 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
1071 top = get2byte(&data[hdr+5]);
1072 pPage->nCell = get2byte(&data[hdr+3]);
1073 if( pPage->nCell>MX_CELL(pBt) ){
1074 /* To many cells for a single page. The page must be corrupt */
1075 return SQLITE_CORRUPT_BKPT;
1076 }
danielk1977eaa06f62008-09-18 17:34:44 +00001077
1078 /* Compute the total free space on the page */
1079 pc = get2byte(&data[hdr+1]);
1080 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
1081 while( pc>0 ){
drh1bd10f82008-12-10 21:19:56 +00001082 u16 next, size;
danielk1977eaa06f62008-09-18 17:34:44 +00001083 if( pc>usableSize-4 ){
1084 /* Free block is off the page */
1085 return SQLITE_CORRUPT_BKPT;
1086 }
1087 next = get2byte(&data[pc]);
1088 size = get2byte(&data[pc+2]);
1089 if( next>0 && next<=pc+size+3 ){
1090 /* Free blocks must be in accending order */
1091 return SQLITE_CORRUPT_BKPT;
1092 }
1093 nFree += size;
1094 pc = next;
1095 }
drhf49661a2008-12-10 16:45:50 +00001096 pPage->nFree = (u16)nFree;
danielk1977eaa06f62008-09-18 17:34:44 +00001097 if( nFree>=usableSize ){
1098 /* Free space cannot exceed total page size */
drh49285702005-09-17 15:20:26 +00001099 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001100 }
drh9e572e62004-04-23 23:43:10 +00001101
drh1688c862008-07-18 02:44:17 +00001102#if 0
1103 /* Check that all the offsets in the cell offset array are within range.
1104 **
1105 ** Omitting this consistency check and using the pPage->maskPage mask
1106 ** to prevent overrunning the page buffer in findCell() results in a
1107 ** 2.5% performance gain.
1108 */
1109 {
1110 u8 *pOff; /* Iterator used to check all cell offsets are in range */
1111 u8 *pEnd; /* Pointer to end of cell offset array */
1112 u8 mask; /* Mask of bits that must be zero in MSB of cell offsets */
1113 mask = ~(((u8)(pBt->pageSize>>8))-1);
1114 pEnd = &data[cellOffset + pPage->nCell*2];
1115 for(pOff=&data[cellOffset]; pOff!=pEnd && !((*pOff)&mask); pOff+=2);
1116 if( pOff!=pEnd ){
1117 return SQLITE_CORRUPT_BKPT;
1118 }
danielk1977e16535f2008-06-11 18:15:29 +00001119 }
drh1688c862008-07-18 02:44:17 +00001120#endif
danielk1977e16535f2008-06-11 18:15:29 +00001121
danielk197771d5d2c2008-09-29 11:49:47 +00001122 pPage->isInit = 1;
1123 }
drh9e572e62004-04-23 23:43:10 +00001124 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001125}
1126
1127/*
drh8b2f49b2001-06-08 00:21:52 +00001128** Set up a raw page so that it looks like a database page holding
1129** no entries.
drhbd03cae2001-06-02 02:40:57 +00001130*/
drh9e572e62004-04-23 23:43:10 +00001131static void zeroPage(MemPage *pPage, int flags){
1132 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001133 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00001134 u8 hdr = pPage->hdrOffset;
1135 u16 first;
drh9e572e62004-04-23 23:43:10 +00001136
danielk19773b8a05f2007-03-19 17:44:26 +00001137 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drhbf4bca52007-09-06 22:19:14 +00001138 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1139 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +00001140 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00001141 assert( sqlite3_mutex_held(pBt->mutex) );
drh1af4a6e2008-07-18 03:32:51 +00001142 /*memset(&data[hdr], 0, pBt->usableSize - hdr);*/
drh1bd10f82008-12-10 21:19:56 +00001143 data[hdr] = (char)flags;
1144 first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
drh43605152004-05-29 21:46:49 +00001145 memset(&data[hdr+1], 0, 4);
1146 data[hdr+7] = 0;
1147 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +00001148 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +00001149 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +00001150 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +00001151 pPage->cellOffset = first;
1152 pPage->nOverflow = 0;
drh1688c862008-07-18 02:44:17 +00001153 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
1154 pPage->maskPage = pBt->pageSize - 1;
drh43605152004-05-29 21:46:49 +00001155 pPage->nCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001156 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00001157}
1158
drh897a8202008-09-18 01:08:15 +00001159
1160/*
1161** Convert a DbPage obtained from the pager into a MemPage used by
1162** the btree layer.
1163*/
1164static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
1165 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
1166 pPage->aData = sqlite3PagerGetData(pDbPage);
1167 pPage->pDbPage = pDbPage;
1168 pPage->pBt = pBt;
1169 pPage->pgno = pgno;
1170 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
1171 return pPage;
1172}
1173
drhbd03cae2001-06-02 02:40:57 +00001174/*
drh3aac2dd2004-04-26 14:10:20 +00001175** Get a page from the pager. Initialize the MemPage.pBt and
1176** MemPage.aData elements if needed.
drh538f5702007-04-13 02:14:30 +00001177**
1178** If the noContent flag is set, it means that we do not care about
1179** the content of the page at this time. So do not go to the disk
1180** to fetch the content. Just fill in the content with zeros for now.
1181** If in the future we call sqlite3PagerWrite() on this page, that
1182** means we have started to be concerned about content and the disk
1183** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00001184*/
drh16a9b832007-05-05 18:39:25 +00001185int sqlite3BtreeGetPage(
1186 BtShared *pBt, /* The btree */
1187 Pgno pgno, /* Number of the page to fetch */
1188 MemPage **ppPage, /* Return the page in this parameter */
1189 int noContent /* Do not load page content if true */
1190){
drh3aac2dd2004-04-26 14:10:20 +00001191 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001192 DbPage *pDbPage;
1193
drh1fee73e2007-08-29 04:00:57 +00001194 assert( sqlite3_mutex_held(pBt->mutex) );
drh538f5702007-04-13 02:14:30 +00001195 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
drh3aac2dd2004-04-26 14:10:20 +00001196 if( rc ) return rc;
drh897a8202008-09-18 01:08:15 +00001197 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
drh3aac2dd2004-04-26 14:10:20 +00001198 return SQLITE_OK;
1199}
1200
1201/*
danielk1977bea2a942009-01-20 17:06:27 +00001202** Retrieve a page from the pager cache. If the requested page is not
1203** already in the pager cache return NULL. Initialize the MemPage.pBt and
1204** MemPage.aData elements if needed.
1205*/
1206static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
1207 DbPage *pDbPage;
1208 assert( sqlite3_mutex_held(pBt->mutex) );
1209 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
1210 if( pDbPage ){
1211 return btreePageFromDbPage(pDbPage, pgno, pBt);
1212 }
1213 return 0;
1214}
1215
1216/*
danielk197789d40042008-11-17 14:20:56 +00001217** Return the size of the database file in pages. If there is any kind of
1218** error, return ((unsigned int)-1).
danielk197767fd7a92008-09-10 17:53:35 +00001219*/
danielk197789d40042008-11-17 14:20:56 +00001220static Pgno pagerPagecount(BtShared *pBt){
1221 int nPage = -1;
danielk197767fd7a92008-09-10 17:53:35 +00001222 int rc;
danielk197789d40042008-11-17 14:20:56 +00001223 assert( pBt->pPage1 );
1224 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1225 assert( rc==SQLITE_OK || nPage==-1 );
1226 return (Pgno)nPage;
danielk197767fd7a92008-09-10 17:53:35 +00001227}
1228
1229/*
drhde647132004-05-07 17:57:49 +00001230** Get a page from the pager and initialize it. This routine
1231** is just a convenience wrapper around separate calls to
drh16a9b832007-05-05 18:39:25 +00001232** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
drhde647132004-05-07 17:57:49 +00001233*/
1234static int getAndInitPage(
danielk1977aef0bf62005-12-30 16:28:01 +00001235 BtShared *pBt, /* The database file */
drhde647132004-05-07 17:57:49 +00001236 Pgno pgno, /* Number of the page to get */
danielk197771d5d2c2008-09-29 11:49:47 +00001237 MemPage **ppPage /* Write the page pointer here */
drhde647132004-05-07 17:57:49 +00001238){
1239 int rc;
drh897a8202008-09-18 01:08:15 +00001240 MemPage *pPage;
1241
drh1fee73e2007-08-29 04:00:57 +00001242 assert( sqlite3_mutex_held(pBt->mutex) );
drh897a8202008-09-18 01:08:15 +00001243 if( pgno==0 ){
drh49285702005-09-17 15:20:26 +00001244 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001245 }
danielk19779f580ad2008-09-10 14:45:57 +00001246
drh897a8202008-09-18 01:08:15 +00001247 /* It is often the case that the page we want is already in cache.
1248 ** If so, get it directly. This saves us from having to call
1249 ** pagerPagecount() to make sure pgno is within limits, which results
1250 ** in a measureable performance improvements.
1251 */
danielk1977bea2a942009-01-20 17:06:27 +00001252 *ppPage = pPage = btreePageLookup(pBt, pgno);
1253 if( pPage ){
drh897a8202008-09-18 01:08:15 +00001254 /* Page is already in cache */
drh897a8202008-09-18 01:08:15 +00001255 rc = SQLITE_OK;
1256 }else{
1257 /* Page not in cache. Acquire it. */
danielk197789d40042008-11-17 14:20:56 +00001258 if( pgno>pagerPagecount(pBt) ){
drh897a8202008-09-18 01:08:15 +00001259 return SQLITE_CORRUPT_BKPT;
1260 }
1261 rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
1262 if( rc ) return rc;
1263 pPage = *ppPage;
1264 }
danielk197771d5d2c2008-09-29 11:49:47 +00001265 if( !pPage->isInit ){
1266 rc = sqlite3BtreeInitPage(pPage);
drh897a8202008-09-18 01:08:15 +00001267 }
1268 if( rc!=SQLITE_OK ){
1269 releasePage(pPage);
1270 *ppPage = 0;
1271 }
drhde647132004-05-07 17:57:49 +00001272 return rc;
1273}
1274
1275/*
drh3aac2dd2004-04-26 14:10:20 +00001276** Release a MemPage. This should be called once for each prior
drh16a9b832007-05-05 18:39:25 +00001277** call to sqlite3BtreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +00001278*/
drh4b70f112004-05-02 21:12:19 +00001279static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001280 if( pPage ){
drh30df0092008-12-23 15:58:06 +00001281 assert( pPage->nOverflow==0 || sqlite3PagerPageRefcount(pPage->pDbPage)>1 );
drh3aac2dd2004-04-26 14:10:20 +00001282 assert( pPage->aData );
1283 assert( pPage->pBt );
drhbf4bca52007-09-06 22:19:14 +00001284 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1285 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
drh1fee73e2007-08-29 04:00:57 +00001286 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001287 sqlite3PagerUnref(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00001288 }
1289}
1290
1291/*
drha6abd042004-06-09 17:37:22 +00001292** During a rollback, when the pager reloads information into the cache
1293** so that the cache is restored to its original state at the start of
1294** the transaction, for each page restored this routine is called.
1295**
1296** This routine needs to reset the extra data section at the end of the
1297** page to agree with the restored data.
1298*/
danielk1977eaa06f62008-09-18 17:34:44 +00001299static void pageReinit(DbPage *pData){
drh07d183d2005-05-01 22:52:42 +00001300 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00001301 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
danielk197771d5d2c2008-09-29 11:49:47 +00001302 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00001303 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00001304 pPage->isInit = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001305 if( sqlite3PagerPageRefcount(pData)>0 ){
1306 sqlite3BtreeInitPage(pPage);
1307 }
drha6abd042004-06-09 17:37:22 +00001308 }
1309}
1310
1311/*
drhe5fe6902007-12-07 18:55:28 +00001312** Invoke the busy handler for a btree.
1313*/
danielk19771ceedd32008-11-19 10:22:33 +00001314static int btreeInvokeBusyHandler(void *pArg){
drhe5fe6902007-12-07 18:55:28 +00001315 BtShared *pBt = (BtShared*)pArg;
1316 assert( pBt->db );
1317 assert( sqlite3_mutex_held(pBt->db->mutex) );
1318 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
1319}
1320
1321/*
drhad3e0102004-09-03 23:32:18 +00001322** Open a database file.
1323**
drh382c0242001-10-06 16:33:02 +00001324** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001325** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001326** database file will be deleted when sqlite3BtreeClose() is called.
drhe53831d2007-08-17 01:14:38 +00001327** If zFilename is ":memory:" then an in-memory database is created
1328** that is automatically destroyed when it is closed.
drha059ad02001-04-17 20:09:11 +00001329*/
drh23e11ca2004-05-04 17:27:28 +00001330int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001331 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00001332 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001333 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00001334 int flags, /* Options */
1335 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00001336){
drhd677b3d2007-08-20 22:48:41 +00001337 sqlite3_vfs *pVfs; /* The VFS to use for this btree */
drhe53831d2007-08-17 01:14:38 +00001338 BtShared *pBt = 0; /* Shared part of btree structure */
danielk1977aef0bf62005-12-30 16:28:01 +00001339 Btree *p; /* Handle to return */
danielk1977dddbcdc2007-04-26 14:42:34 +00001340 int rc = SQLITE_OK;
drhf49661a2008-12-10 16:45:50 +00001341 u8 nReserve;
drh90f5ecb2004-07-22 01:19:35 +00001342 unsigned char zDbHeader[100];
danielk1977aef0bf62005-12-30 16:28:01 +00001343
1344 /* Set the variable isMemdb to true for an in-memory database, or
1345 ** false for a file-based database. This symbol is only required if
1346 ** either of the shared-data or autovacuum features are compiled
1347 ** into the library.
1348 */
1349#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
1350 #ifdef SQLITE_OMIT_MEMORYDB
drh980b1a72006-08-16 16:42:48 +00001351 const int isMemdb = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00001352 #else
drh980b1a72006-08-16 16:42:48 +00001353 const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
danielk1977aef0bf62005-12-30 16:28:01 +00001354 #endif
1355#endif
1356
drhe5fe6902007-12-07 18:55:28 +00001357 assert( db!=0 );
1358 assert( sqlite3_mutex_held(db->mutex) );
drh153c62c2007-08-24 03:51:33 +00001359
drhe5fe6902007-12-07 18:55:28 +00001360 pVfs = db->pVfs;
drh17435752007-08-16 04:30:38 +00001361 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00001362 if( !p ){
1363 return SQLITE_NOMEM;
1364 }
1365 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00001366 p->db = db;
danielk1977aef0bf62005-12-30 16:28:01 +00001367
drh198bf392006-01-06 21:52:49 +00001368#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001369 /*
1370 ** If this Btree is a candidate for shared cache, try to find an
1371 ** existing BtShared object that we can share with
1372 */
drh34004ce2008-07-11 16:15:17 +00001373 if( isMemdb==0
drhe5fe6902007-12-07 18:55:28 +00001374 && (db->flags & SQLITE_Vtab)==0
drhe53831d2007-08-17 01:14:38 +00001375 && zFilename && zFilename[0]
drhe53831d2007-08-17 01:14:38 +00001376 ){
danielk1977502b4e02008-09-02 14:07:24 +00001377 if( sqlite3GlobalConfig.sharedCacheEnabled ){
danielk1977adfb9b02007-09-17 07:02:56 +00001378 int nFullPathname = pVfs->mxPathname+1;
drhe5ae5732008-06-15 02:51:47 +00001379 char *zFullPathname = sqlite3Malloc(nFullPathname);
drhff0587c2007-08-29 17:43:19 +00001380 sqlite3_mutex *mutexShared;
1381 p->sharable = 1;
drh34004ce2008-07-11 16:15:17 +00001382 db->flags |= SQLITE_SharedCache;
drhff0587c2007-08-29 17:43:19 +00001383 if( !zFullPathname ){
1384 sqlite3_free(p);
1385 return SQLITE_NOMEM;
1386 }
danielk1977adfb9b02007-09-17 07:02:56 +00001387 sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
danielk197759f8c082008-06-18 17:09:10 +00001388 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhff0587c2007-08-29 17:43:19 +00001389 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001390 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
drhff0587c2007-08-29 17:43:19 +00001391 assert( pBt->nRef>0 );
1392 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
1393 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
1394 p->pBt = pBt;
1395 pBt->nRef++;
1396 break;
1397 }
1398 }
1399 sqlite3_mutex_leave(mutexShared);
1400 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00001401 }
drhff0587c2007-08-29 17:43:19 +00001402#ifdef SQLITE_DEBUG
1403 else{
1404 /* In debug mode, we mark all persistent databases as sharable
1405 ** even when they are not. This exercises the locking code and
1406 ** gives more opportunity for asserts(sqlite3_mutex_held())
1407 ** statements to find locking problems.
1408 */
1409 p->sharable = 1;
1410 }
1411#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001412 }
1413#endif
drha059ad02001-04-17 20:09:11 +00001414 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00001415 /*
1416 ** The following asserts make sure that structures used by the btree are
1417 ** the right size. This is to guard against size changes that result
1418 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00001419 */
drhe53831d2007-08-17 01:14:38 +00001420 assert( sizeof(i64)==8 || sizeof(i64)==4 );
1421 assert( sizeof(u64)==8 || sizeof(u64)==4 );
1422 assert( sizeof(u32)==4 );
1423 assert( sizeof(u16)==2 );
1424 assert( sizeof(Pgno)==4 );
1425
1426 pBt = sqlite3MallocZero( sizeof(*pBt) );
1427 if( pBt==0 ){
1428 rc = SQLITE_NOMEM;
1429 goto btree_open_out;
1430 }
danielk197771d5d2c2008-09-29 11:49:47 +00001431 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
drh33f4e022007-09-03 15:19:34 +00001432 EXTRA_SIZE, flags, vfsFlags);
drhe53831d2007-08-17 01:14:38 +00001433 if( rc==SQLITE_OK ){
1434 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
1435 }
1436 if( rc!=SQLITE_OK ){
1437 goto btree_open_out;
1438 }
danielk19771ceedd32008-11-19 10:22:33 +00001439 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
drhe53831d2007-08-17 01:14:38 +00001440 p->pBt = pBt;
1441
drhe53831d2007-08-17 01:14:38 +00001442 sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
1443 pBt->pCursor = 0;
1444 pBt->pPage1 = 0;
1445 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
1446 pBt->pageSize = get2byte(&zDbHeader[16]);
1447 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1448 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00001449 pBt->pageSize = 0;
1450 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drhe53831d2007-08-17 01:14:38 +00001451#ifndef SQLITE_OMIT_AUTOVACUUM
1452 /* If the magic name ":memory:" will create an in-memory database, then
1453 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
1454 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
1455 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
1456 ** regular file-name. In this case the auto-vacuum applies as per normal.
1457 */
1458 if( zFilename && !isMemdb ){
1459 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
1460 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
1461 }
1462#endif
1463 nReserve = 0;
1464 }else{
1465 nReserve = zDbHeader[20];
drhe53831d2007-08-17 01:14:38 +00001466 pBt->pageSizeFixed = 1;
1467#ifndef SQLITE_OMIT_AUTOVACUUM
1468 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1469 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
1470#endif
1471 }
1472 pBt->usableSize = pBt->pageSize - nReserve;
1473 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
danielk1977a1644fd2007-08-29 12:31:25 +00001474 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drhe53831d2007-08-17 01:14:38 +00001475
1476#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1477 /* Add the new BtShared object to the linked list sharable BtShareds.
1478 */
1479 if( p->sharable ){
1480 sqlite3_mutex *mutexShared;
1481 pBt->nRef = 1;
danielk197759f8c082008-06-18 17:09:10 +00001482 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
danielk1977075c23a2008-09-01 18:34:20 +00001483 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
danielk197759f8c082008-06-18 17:09:10 +00001484 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
drh3285db22007-09-03 22:00:39 +00001485 if( pBt->mutex==0 ){
1486 rc = SQLITE_NOMEM;
drhe5fe6902007-12-07 18:55:28 +00001487 db->mallocFailed = 0;
drh3285db22007-09-03 22:00:39 +00001488 goto btree_open_out;
1489 }
drhff0587c2007-08-29 17:43:19 +00001490 }
drhe53831d2007-08-17 01:14:38 +00001491 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001492 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
1493 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
drhe53831d2007-08-17 01:14:38 +00001494 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00001495 }
drheee46cf2004-11-06 00:02:48 +00001496#endif
drh90f5ecb2004-07-22 01:19:35 +00001497 }
danielk1977aef0bf62005-12-30 16:28:01 +00001498
drhcfed7bc2006-03-13 14:28:05 +00001499#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001500 /* If the new Btree uses a sharable pBtShared, then link the new
1501 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00001502 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00001503 */
drhe53831d2007-08-17 01:14:38 +00001504 if( p->sharable ){
1505 int i;
1506 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00001507 for(i=0; i<db->nDb; i++){
1508 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00001509 while( pSib->pPrev ){ pSib = pSib->pPrev; }
1510 if( p->pBt<pSib->pBt ){
1511 p->pNext = pSib;
1512 p->pPrev = 0;
1513 pSib->pPrev = p;
1514 }else{
drhabddb0c2007-08-20 13:14:28 +00001515 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
drhe53831d2007-08-17 01:14:38 +00001516 pSib = pSib->pNext;
1517 }
1518 p->pNext = pSib->pNext;
1519 p->pPrev = pSib;
1520 if( p->pNext ){
1521 p->pNext->pPrev = p;
1522 }
1523 pSib->pNext = p;
1524 }
1525 break;
1526 }
1527 }
danielk1977aef0bf62005-12-30 16:28:01 +00001528 }
danielk1977aef0bf62005-12-30 16:28:01 +00001529#endif
1530 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00001531
1532btree_open_out:
1533 if( rc!=SQLITE_OK ){
1534 if( pBt && pBt->pPager ){
1535 sqlite3PagerClose(pBt->pPager);
1536 }
drh17435752007-08-16 04:30:38 +00001537 sqlite3_free(pBt);
1538 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00001539 *ppBtree = 0;
1540 }
1541 return rc;
drha059ad02001-04-17 20:09:11 +00001542}
1543
1544/*
drhe53831d2007-08-17 01:14:38 +00001545** Decrement the BtShared.nRef counter. When it reaches zero,
1546** remove the BtShared structure from the sharing list. Return
1547** true if the BtShared.nRef counter reaches zero and return
1548** false if it is still positive.
1549*/
1550static int removeFromSharingList(BtShared *pBt){
1551#ifndef SQLITE_OMIT_SHARED_CACHE
1552 sqlite3_mutex *pMaster;
1553 BtShared *pList;
1554 int removed = 0;
1555
drhd677b3d2007-08-20 22:48:41 +00001556 assert( sqlite3_mutex_notheld(pBt->mutex) );
danielk197759f8c082008-06-18 17:09:10 +00001557 pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhe53831d2007-08-17 01:14:38 +00001558 sqlite3_mutex_enter(pMaster);
1559 pBt->nRef--;
1560 if( pBt->nRef<=0 ){
drh78f82d12008-09-02 00:52:52 +00001561 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
1562 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
drhe53831d2007-08-17 01:14:38 +00001563 }else{
drh78f82d12008-09-02 00:52:52 +00001564 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
drh34004ce2008-07-11 16:15:17 +00001565 while( ALWAYS(pList) && pList->pNext!=pBt ){
drhe53831d2007-08-17 01:14:38 +00001566 pList=pList->pNext;
1567 }
drh34004ce2008-07-11 16:15:17 +00001568 if( ALWAYS(pList) ){
drhe53831d2007-08-17 01:14:38 +00001569 pList->pNext = pBt->pNext;
1570 }
1571 }
drh3285db22007-09-03 22:00:39 +00001572 if( SQLITE_THREADSAFE ){
1573 sqlite3_mutex_free(pBt->mutex);
1574 }
drhe53831d2007-08-17 01:14:38 +00001575 removed = 1;
1576 }
1577 sqlite3_mutex_leave(pMaster);
1578 return removed;
1579#else
1580 return 1;
1581#endif
1582}
1583
1584/*
drhf7141992008-06-19 00:16:08 +00001585** Make sure pBt->pTmpSpace points to an allocation of
1586** MX_CELL_SIZE(pBt) bytes.
1587*/
1588static void allocateTempSpace(BtShared *pBt){
1589 if( !pBt->pTmpSpace ){
1590 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
1591 }
1592}
1593
1594/*
1595** Free the pBt->pTmpSpace allocation
1596*/
1597static void freeTempSpace(BtShared *pBt){
1598 sqlite3PageFree( pBt->pTmpSpace);
1599 pBt->pTmpSpace = 0;
1600}
1601
1602/*
drha059ad02001-04-17 20:09:11 +00001603** Close an open database and invalidate all cursors.
1604*/
danielk1977aef0bf62005-12-30 16:28:01 +00001605int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00001606 BtShared *pBt = p->pBt;
1607 BtCursor *pCur;
1608
danielk1977aef0bf62005-12-30 16:28:01 +00001609 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00001610 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00001611 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00001612 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00001613 pCur = pBt->pCursor;
1614 while( pCur ){
1615 BtCursor *pTmp = pCur;
1616 pCur = pCur->pNext;
1617 if( pTmp->pBtree==p ){
1618 sqlite3BtreeCloseCursor(pTmp);
1619 }
drha059ad02001-04-17 20:09:11 +00001620 }
danielk1977aef0bf62005-12-30 16:28:01 +00001621
danielk19778d34dfd2006-01-24 16:37:57 +00001622 /* Rollback any active transaction and free the handle structure.
1623 ** The call to sqlite3BtreeRollback() drops any table-locks held by
1624 ** this handle.
1625 */
danielk1977b597f742006-01-15 11:39:18 +00001626 sqlite3BtreeRollback(p);
drhe53831d2007-08-17 01:14:38 +00001627 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001628
danielk1977aef0bf62005-12-30 16:28:01 +00001629 /* If there are still other outstanding references to the shared-btree
1630 ** structure, return now. The remainder of this procedure cleans
1631 ** up the shared-btree.
1632 */
drhe53831d2007-08-17 01:14:38 +00001633 assert( p->wantToLock==0 && p->locked==0 );
1634 if( !p->sharable || removeFromSharingList(pBt) ){
1635 /* The pBt is no longer on the sharing list, so we can access
1636 ** it without having to hold the mutex.
1637 **
1638 ** Clean out and delete the BtShared object.
1639 */
1640 assert( !pBt->pCursor );
drhe53831d2007-08-17 01:14:38 +00001641 sqlite3PagerClose(pBt->pPager);
1642 if( pBt->xFreeSchema && pBt->pSchema ){
1643 pBt->xFreeSchema(pBt->pSchema);
1644 }
1645 sqlite3_free(pBt->pSchema);
drhf7141992008-06-19 00:16:08 +00001646 freeTempSpace(pBt);
drh65bbf292008-06-19 01:03:17 +00001647 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00001648 }
1649
drhe53831d2007-08-17 01:14:38 +00001650#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00001651 assert( p->wantToLock==0 );
1652 assert( p->locked==0 );
1653 if( p->pPrev ) p->pPrev->pNext = p->pNext;
1654 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00001655#endif
1656
drhe53831d2007-08-17 01:14:38 +00001657 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00001658 return SQLITE_OK;
1659}
1660
1661/*
drhda47d772002-12-02 04:25:19 +00001662** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001663**
1664** The maximum number of cache pages is set to the absolute
1665** value of mxPage. If mxPage is negative, the pager will
1666** operate asynchronously - it will not stop to do fsync()s
1667** to insure data is written to the disk surface before
1668** continuing. Transactions still work if synchronous is off,
1669** and the database cannot be corrupted if this program
1670** crashes. But if the operating system crashes or there is
1671** an abrupt power failure when synchronous is off, the database
1672** could be left in an inconsistent and unrecoverable state.
1673** Synchronous is on by default so database corruption is not
1674** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001675*/
danielk1977aef0bf62005-12-30 16:28:01 +00001676int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
1677 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001678 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001679 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001680 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00001681 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00001682 return SQLITE_OK;
1683}
1684
1685/*
drh973b6e32003-02-12 14:09:42 +00001686** Change the way data is synced to disk in order to increase or decrease
1687** how well the database resists damage due to OS crashes and power
1688** failures. Level 1 is the same as asynchronous (no syncs() occur and
1689** there is a high probability of damage) Level 2 is the default. There
1690** is a very low but non-zero probability of damage. Level 3 reduces the
1691** probability of damage to near zero but with a write performance reduction.
1692*/
danielk197793758c82005-01-21 08:13:14 +00001693#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drhac530b12006-02-11 01:25:50 +00001694int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
danielk1977aef0bf62005-12-30 16:28:01 +00001695 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001696 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001697 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001698 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
drhd677b3d2007-08-20 22:48:41 +00001699 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00001700 return SQLITE_OK;
1701}
danielk197793758c82005-01-21 08:13:14 +00001702#endif
drh973b6e32003-02-12 14:09:42 +00001703
drh2c8997b2005-08-27 16:36:48 +00001704/*
1705** Return TRUE if the given btree is set to safety level 1. In other
1706** words, return TRUE if no sync() occurs on the disk files.
1707*/
danielk1977aef0bf62005-12-30 16:28:01 +00001708int sqlite3BtreeSyncDisabled(Btree *p){
1709 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001710 int rc;
drhe5fe6902007-12-07 18:55:28 +00001711 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001712 sqlite3BtreeEnter(p);
drhd0679ed2007-08-28 22:24:34 +00001713 assert( pBt && pBt->pPager );
drhd677b3d2007-08-20 22:48:41 +00001714 rc = sqlite3PagerNosync(pBt->pPager);
1715 sqlite3BtreeLeave(p);
1716 return rc;
drh2c8997b2005-08-27 16:36:48 +00001717}
1718
danielk1977576ec6b2005-01-21 11:55:25 +00001719#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00001720/*
drh90f5ecb2004-07-22 01:19:35 +00001721** Change the default pages size and the number of reserved bytes per page.
drh06f50212004-11-02 14:24:33 +00001722**
1723** The page size must be a power of 2 between 512 and 65536. If the page
1724** size supplied does not meet this constraint then the page size is not
1725** changed.
1726**
1727** Page sizes are constrained to be a power of two so that the region
1728** of the database file used for locking (beginning at PENDING_BYTE,
1729** the first byte past the 1GB boundary, 0x40000000) needs to occur
1730** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001731**
1732** If parameter nReserve is less than zero, then the number of reserved
1733** bytes per page is left unchanged.
drh90f5ecb2004-07-22 01:19:35 +00001734*/
danielk1977aef0bf62005-12-30 16:28:01 +00001735int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
danielk1977a1644fd2007-08-29 12:31:25 +00001736 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00001737 BtShared *pBt = p->pBt;
drhf49661a2008-12-10 16:45:50 +00001738 assert( nReserve>=-1 && nReserve<=255 );
drhd677b3d2007-08-20 22:48:41 +00001739 sqlite3BtreeEnter(p);
drh90f5ecb2004-07-22 01:19:35 +00001740 if( pBt->pageSizeFixed ){
drhd677b3d2007-08-20 22:48:41 +00001741 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00001742 return SQLITE_READONLY;
1743 }
1744 if( nReserve<0 ){
1745 nReserve = pBt->pageSize - pBt->usableSize;
1746 }
drhf49661a2008-12-10 16:45:50 +00001747 assert( nReserve>=0 && nReserve<=255 );
drh06f50212004-11-02 14:24:33 +00001748 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
1749 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00001750 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00001751 assert( !pBt->pPage1 && !pBt->pCursor );
drh1bd10f82008-12-10 21:19:56 +00001752 pBt->pageSize = (u16)pageSize;
drhf7141992008-06-19 00:16:08 +00001753 freeTempSpace(pBt);
danielk1977a1644fd2007-08-29 12:31:25 +00001754 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001755 }
drhf49661a2008-12-10 16:45:50 +00001756 pBt->usableSize = pBt->pageSize - (u16)nReserve;
drhd677b3d2007-08-20 22:48:41 +00001757 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00001758 return rc;
drh90f5ecb2004-07-22 01:19:35 +00001759}
1760
1761/*
1762** Return the currently defined page size
1763*/
danielk1977aef0bf62005-12-30 16:28:01 +00001764int sqlite3BtreeGetPageSize(Btree *p){
1765 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00001766}
drh7f751222009-03-17 22:33:00 +00001767
1768/*
1769** Return the number of bytes of space at the end of every page that
1770** are intentually left unused. This is the "reserved" space that is
1771** sometimes used by extensions.
1772*/
danielk1977aef0bf62005-12-30 16:28:01 +00001773int sqlite3BtreeGetReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00001774 int n;
1775 sqlite3BtreeEnter(p);
1776 n = p->pBt->pageSize - p->pBt->usableSize;
1777 sqlite3BtreeLeave(p);
1778 return n;
drh2011d5f2004-07-22 02:40:37 +00001779}
drhf8e632b2007-05-08 14:51:36 +00001780
1781/*
1782** Set the maximum page count for a database if mxPage is positive.
1783** No changes are made if mxPage is 0 or negative.
1784** Regardless of the value of mxPage, return the maximum page count.
1785*/
1786int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00001787 int n;
1788 sqlite3BtreeEnter(p);
1789 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
1790 sqlite3BtreeLeave(p);
1791 return n;
drhf8e632b2007-05-08 14:51:36 +00001792}
danielk1977576ec6b2005-01-21 11:55:25 +00001793#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00001794
1795/*
danielk1977951af802004-11-05 15:45:09 +00001796** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
1797** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
1798** is disabled. The default value for the auto-vacuum property is
1799** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
1800*/
danielk1977aef0bf62005-12-30 16:28:01 +00001801int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00001802#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001803 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00001804#else
danielk1977dddbcdc2007-04-26 14:42:34 +00001805 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001806 int rc = SQLITE_OK;
drh076d4662009-02-18 20:31:18 +00001807 u8 av = (u8)autoVacuum;
drhd677b3d2007-08-20 22:48:41 +00001808
1809 sqlite3BtreeEnter(p);
drh076d4662009-02-18 20:31:18 +00001810 if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00001811 rc = SQLITE_READONLY;
1812 }else{
drh076d4662009-02-18 20:31:18 +00001813 pBt->autoVacuum = av ?1:0;
1814 pBt->incrVacuum = av==2 ?1:0;
danielk1977951af802004-11-05 15:45:09 +00001815 }
drhd677b3d2007-08-20 22:48:41 +00001816 sqlite3BtreeLeave(p);
1817 return rc;
danielk1977951af802004-11-05 15:45:09 +00001818#endif
1819}
1820
1821/*
1822** Return the value of the 'auto-vacuum' property. If auto-vacuum is
1823** enabled 1 is returned. Otherwise 0.
1824*/
danielk1977aef0bf62005-12-30 16:28:01 +00001825int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00001826#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00001827 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00001828#else
drhd677b3d2007-08-20 22:48:41 +00001829 int rc;
1830 sqlite3BtreeEnter(p);
1831 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00001832 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
1833 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
1834 BTREE_AUTOVACUUM_INCR
1835 );
drhd677b3d2007-08-20 22:48:41 +00001836 sqlite3BtreeLeave(p);
1837 return rc;
danielk1977951af802004-11-05 15:45:09 +00001838#endif
1839}
1840
1841
1842/*
drha34b6762004-05-07 13:30:42 +00001843** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001844** also acquire a readlock on that file.
1845**
1846** SQLITE_OK is returned on success. If the file is not a
1847** well-formed database file, then SQLITE_CORRUPT is returned.
1848** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00001849** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00001850*/
danielk1977aef0bf62005-12-30 16:28:01 +00001851static int lockBtree(BtShared *pBt){
danielk1977f653d782008-03-20 11:04:21 +00001852 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001853 MemPage *pPage1;
danielk197793f7af92008-05-09 16:57:50 +00001854 int nPage;
drhd677b3d2007-08-20 22:48:41 +00001855
drh1fee73e2007-08-29 04:00:57 +00001856 assert( sqlite3_mutex_held(pBt->mutex) );
drha34b6762004-05-07 13:30:42 +00001857 if( pBt->pPage1 ) return SQLITE_OK;
drh16a9b832007-05-05 18:39:25 +00001858 rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00001859 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00001860
1861 /* Do some checking to help insure the file we opened really is
1862 ** a valid database file.
1863 */
danielk1977ad0132d2008-06-07 08:58:22 +00001864 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1865 if( rc!=SQLITE_OK ){
danielk197793f7af92008-05-09 16:57:50 +00001866 goto page1_init_failed;
1867 }else if( nPage>0 ){
danielk1977f653d782008-03-20 11:04:21 +00001868 int pageSize;
1869 int usableSize;
drhb6f41482004-05-14 01:58:11 +00001870 u8 *page1 = pPage1->aData;
danielk1977ad0132d2008-06-07 08:58:22 +00001871 rc = SQLITE_NOTADB;
drhb6f41482004-05-14 01:58:11 +00001872 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001873 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001874 }
drh309169a2007-04-24 17:27:51 +00001875 if( page1[18]>1 ){
1876 pBt->readOnly = 1;
1877 }
1878 if( page1[19]>1 ){
drhb6f41482004-05-14 01:58:11 +00001879 goto page1_init_failed;
1880 }
drhe5ae5732008-06-15 02:51:47 +00001881
1882 /* The maximum embedded fraction must be exactly 25%. And the minimum
1883 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
1884 ** The original design allowed these amounts to vary, but as of
1885 ** version 3.6.0, we require them to be fixed.
1886 */
1887 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
1888 goto page1_init_failed;
1889 }
drh07d183d2005-05-01 22:52:42 +00001890 pageSize = get2byte(&page1[16]);
drh7dc385e2007-09-06 23:39:36 +00001891 if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
1892 (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
1893 ){
drh07d183d2005-05-01 22:52:42 +00001894 goto page1_init_failed;
1895 }
1896 assert( (pageSize & 7)==0 );
danielk1977f653d782008-03-20 11:04:21 +00001897 usableSize = pageSize - page1[20];
1898 if( pageSize!=pBt->pageSize ){
1899 /* After reading the first page of the database assuming a page size
1900 ** of BtShared.pageSize, we have discovered that the page-size is
1901 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
1902 ** zero and return SQLITE_OK. The caller will call this function
1903 ** again with the correct page-size.
1904 */
1905 releasePage(pPage1);
drhf49661a2008-12-10 16:45:50 +00001906 pBt->usableSize = (u16)usableSize;
1907 pBt->pageSize = (u16)pageSize;
drhf7141992008-06-19 00:16:08 +00001908 freeTempSpace(pBt);
danielk1977f653d782008-03-20 11:04:21 +00001909 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
1910 return SQLITE_OK;
1911 }
1912 if( usableSize<500 ){
drhb6f41482004-05-14 01:58:11 +00001913 goto page1_init_failed;
1914 }
drh1bd10f82008-12-10 21:19:56 +00001915 pBt->pageSize = (u16)pageSize;
1916 pBt->usableSize = (u16)usableSize;
drh057cd3a2005-02-15 16:23:02 +00001917#ifndef SQLITE_OMIT_AUTOVACUUM
1918 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00001919 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00001920#endif
drh306dc212001-05-21 13:45:10 +00001921 }
drhb6f41482004-05-14 01:58:11 +00001922
1923 /* maxLocal is the maximum amount of payload to store locally for
1924 ** a cell. Make sure it is small enough so that at least minFanout
1925 ** cells can will fit on one page. We assume a 10-byte page header.
1926 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001927 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001928 ** 4-byte child pointer
1929 ** 9-byte nKey value
1930 ** 4-byte nData value
1931 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001932 ** So a cell consists of a 2-byte poiner, a header which is as much as
1933 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1934 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001935 */
drhe5ae5732008-06-15 02:51:47 +00001936 pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
1937 pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
drh43605152004-05-29 21:46:49 +00001938 pBt->maxLeaf = pBt->usableSize - 35;
drhe5ae5732008-06-15 02:51:47 +00001939 pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
drh2e38c322004-09-03 18:38:44 +00001940 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00001941 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001942 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001943
drh72f82862001-05-24 21:06:34 +00001944page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001945 releasePage(pPage1);
1946 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001947 return rc;
drh306dc212001-05-21 13:45:10 +00001948}
1949
1950/*
drhb8ef32c2005-03-14 02:01:49 +00001951** This routine works like lockBtree() except that it also invokes the
1952** busy callback if there is lock contention.
1953*/
danielk1977aef0bf62005-12-30 16:28:01 +00001954static int lockBtreeWithRetry(Btree *pRef){
drhb8ef32c2005-03-14 02:01:49 +00001955 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00001956
drh1fee73e2007-08-29 04:00:57 +00001957 assert( sqlite3BtreeHoldsMutex(pRef) );
danielk1977aef0bf62005-12-30 16:28:01 +00001958 if( pRef->inTrans==TRANS_NONE ){
1959 u8 inTransaction = pRef->pBt->inTransaction;
1960 btreeIntegrity(pRef);
1961 rc = sqlite3BtreeBeginTrans(pRef, 0);
1962 pRef->pBt->inTransaction = inTransaction;
1963 pRef->inTrans = TRANS_NONE;
1964 if( rc==SQLITE_OK ){
1965 pRef->pBt->nTransaction--;
1966 }
1967 btreeIntegrity(pRef);
drhb8ef32c2005-03-14 02:01:49 +00001968 }
1969 return rc;
1970}
1971
1972
1973/*
drhb8ca3072001-12-05 00:21:20 +00001974** If there are no outstanding cursors and we are not in the middle
1975** of a transaction but there is a read lock on the database, then
1976** this routine unrefs the first page of the database file which
1977** has the effect of releasing the read lock.
1978**
1979** If there are any outstanding cursors, this routine is a no-op.
1980**
1981** If there is a transaction in progress, this routine is a no-op.
1982*/
danielk1977aef0bf62005-12-30 16:28:01 +00001983static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00001984 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00001985 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00001986 if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
drhde4fcfd2008-01-19 23:50:26 +00001987 assert( pBt->pPage1->aData );
1988#if 0
drh24c9a2e2007-01-05 02:00:47 +00001989 if( pBt->pPage1->aData==0 ){
1990 MemPage *pPage = pBt->pPage1;
drhbf4bca52007-09-06 22:19:14 +00001991 pPage->aData = sqlite3PagerGetData(pPage->pDbPage);
drh24c9a2e2007-01-05 02:00:47 +00001992 pPage->pBt = pBt;
1993 pPage->pgno = 1;
1994 }
drhde4fcfd2008-01-19 23:50:26 +00001995#endif
drh24c9a2e2007-01-05 02:00:47 +00001996 releasePage(pBt->pPage1);
drh51c6d962004-06-06 00:42:25 +00001997 }
drh3aac2dd2004-04-26 14:10:20 +00001998 pBt->pPage1 = 0;
drhb8ca3072001-12-05 00:21:20 +00001999 }
2000}
2001
2002/*
drh9e572e62004-04-23 23:43:10 +00002003** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00002004** file.
drh8b2f49b2001-06-08 00:21:52 +00002005*/
danielk1977aef0bf62005-12-30 16:28:01 +00002006static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00002007 MemPage *pP1;
2008 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00002009 int rc;
danielk1977ad0132d2008-06-07 08:58:22 +00002010 int nPage;
drhd677b3d2007-08-20 22:48:41 +00002011
drh1fee73e2007-08-29 04:00:57 +00002012 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977ad0132d2008-06-07 08:58:22 +00002013 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
2014 if( rc!=SQLITE_OK || nPage>0 ){
2015 return rc;
2016 }
drh3aac2dd2004-04-26 14:10:20 +00002017 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00002018 assert( pP1!=0 );
2019 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00002020 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00002021 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00002022 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
2023 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00002024 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00002025 data[18] = 1;
2026 data[19] = 1;
drhf49661a2008-12-10 16:45:50 +00002027 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
2028 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
drhe5ae5732008-06-15 02:51:47 +00002029 data[21] = 64;
2030 data[22] = 32;
2031 data[23] = 32;
drhb6f41482004-05-14 01:58:11 +00002032 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00002033 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00002034 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00002035#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002036 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00002037 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00002038 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00002039 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00002040#endif
drh8b2f49b2001-06-08 00:21:52 +00002041 return SQLITE_OK;
2042}
2043
2044/*
danielk1977ee5741e2004-05-31 10:01:34 +00002045** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00002046** is started if the second argument is nonzero, otherwise a read-
2047** transaction. If the second argument is 2 or more and exclusive
2048** transaction is started, meaning that no other process is allowed
2049** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00002050** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00002051** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00002052**
danielk1977ee5741e2004-05-31 10:01:34 +00002053** A write-transaction must be started before attempting any
2054** changes to the database. None of the following routines
2055** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00002056**
drh23e11ca2004-05-04 17:27:28 +00002057** sqlite3BtreeCreateTable()
2058** sqlite3BtreeCreateIndex()
2059** sqlite3BtreeClearTable()
2060** sqlite3BtreeDropTable()
2061** sqlite3BtreeInsert()
2062** sqlite3BtreeDelete()
2063** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00002064**
drhb8ef32c2005-03-14 02:01:49 +00002065** If an initial attempt to acquire the lock fails because of lock contention
2066** and the database was previously unlocked, then invoke the busy handler
2067** if there is one. But if there was previously a read-lock, do not
2068** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
2069** returned when there is already a read-lock in order to avoid a deadlock.
2070**
2071** Suppose there are two processes A and B. A has a read lock and B has
2072** a reserved lock. B tries to promote to exclusive but is blocked because
2073** of A's read lock. A tries to promote to reserved but is blocked by B.
2074** One or the other of the two processes must give way or there can be
2075** no progress. By returning SQLITE_BUSY and not invoking the busy callback
2076** when A already has a read lock, we encourage A to give up and let B
2077** proceed.
drha059ad02001-04-17 20:09:11 +00002078*/
danielk1977aef0bf62005-12-30 16:28:01 +00002079int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
danielk1977404ca072009-03-16 13:19:36 +00002080 sqlite3 *pBlock = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00002081 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00002082 int rc = SQLITE_OK;
2083
drhd677b3d2007-08-20 22:48:41 +00002084 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002085 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00002086 btreeIntegrity(p);
2087
danielk1977ee5741e2004-05-31 10:01:34 +00002088 /* If the btree is already in a write-transaction, or it
2089 ** is already in a read-transaction and a read-transaction
2090 ** is requested, this is a no-op.
2091 */
danielk1977aef0bf62005-12-30 16:28:01 +00002092 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00002093 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002094 }
drhb8ef32c2005-03-14 02:01:49 +00002095
2096 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00002097 if( pBt->readOnly && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00002098 rc = SQLITE_READONLY;
2099 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002100 }
2101
danielk1977404ca072009-03-16 13:19:36 +00002102#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +00002103 /* If another database handle has already opened a write transaction
2104 ** on this shared-btree structure and a second write transaction is
danielk1977404ca072009-03-16 13:19:36 +00002105 ** requested, return SQLITE_LOCKED.
danielk1977aef0bf62005-12-30 16:28:01 +00002106 */
danielk1977404ca072009-03-16 13:19:36 +00002107 if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
2108 pBlock = pBt->pWriter->db;
2109 }else if( wrflag>1 ){
danielk1977641b0f42007-12-21 04:47:25 +00002110 BtLock *pIter;
2111 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
2112 if( pIter->pBtree!=p ){
danielk1977404ca072009-03-16 13:19:36 +00002113 pBlock = pIter->pBtree->db;
2114 break;
danielk1977641b0f42007-12-21 04:47:25 +00002115 }
2116 }
2117 }
danielk1977404ca072009-03-16 13:19:36 +00002118 if( pBlock ){
2119 sqlite3ConnectionBlocked(p->db, pBlock);
2120 rc = SQLITE_LOCKED_SHAREDCACHE;
2121 goto trans_begun;
2122 }
danielk1977641b0f42007-12-21 04:47:25 +00002123#endif
2124
drhb8ef32c2005-03-14 02:01:49 +00002125 do {
drh8a9c17f2008-05-02 14:23:54 +00002126 if( pBt->pPage1==0 ){
2127 do{
2128 rc = lockBtree(pBt);
2129 }while( pBt->pPage1==0 && rc==SQLITE_OK );
drh8c42ca92001-06-22 19:15:00 +00002130 }
drh309169a2007-04-24 17:27:51 +00002131
drhb8ef32c2005-03-14 02:01:49 +00002132 if( rc==SQLITE_OK && wrflag ){
drh309169a2007-04-24 17:27:51 +00002133 if( pBt->readOnly ){
2134 rc = SQLITE_READONLY;
2135 }else{
danielk1977bea2a942009-01-20 17:06:27 +00002136 rc = sqlite3PagerBegin(pBt->pPager, wrflag>1);
drh309169a2007-04-24 17:27:51 +00002137 if( rc==SQLITE_OK ){
2138 rc = newDatabase(pBt);
2139 }
drhb8ef32c2005-03-14 02:01:49 +00002140 }
2141 }
2142
danielk1977bd434552009-03-18 10:33:00 +00002143 if( rc!=SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00002144 unlockBtreeIfUnused(pBt);
2145 }
danielk1977aef0bf62005-12-30 16:28:01 +00002146 }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
danielk19771ceedd32008-11-19 10:22:33 +00002147 btreeInvokeBusyHandler(pBt) );
danielk1977aef0bf62005-12-30 16:28:01 +00002148
2149 if( rc==SQLITE_OK ){
2150 if( p->inTrans==TRANS_NONE ){
2151 pBt->nTransaction++;
2152 }
2153 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
2154 if( p->inTrans>pBt->inTransaction ){
2155 pBt->inTransaction = p->inTrans;
2156 }
danielk1977641b0f42007-12-21 04:47:25 +00002157#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977404ca072009-03-16 13:19:36 +00002158 if( wrflag ){
2159 assert( !pBt->pWriter );
2160 pBt->pWriter = p;
2161 pBt->isExclusive = (wrflag>1);
danielk1977641b0f42007-12-21 04:47:25 +00002162 }
2163#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002164 }
2165
drhd677b3d2007-08-20 22:48:41 +00002166
2167trans_begun:
danielk1977fd7f0452008-12-17 17:30:26 +00002168 if( rc==SQLITE_OK && wrflag ){
danielk197712dd5492008-12-18 15:45:07 +00002169 /* This call makes sure that the pager has the correct number of
2170 ** open savepoints. If the second parameter is greater than 0 and
2171 ** the sub-journal is not already open, then it will be opened here.
2172 */
danielk1977fd7f0452008-12-17 17:30:26 +00002173 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
2174 }
danielk197712dd5492008-12-18 15:45:07 +00002175
danielk1977aef0bf62005-12-30 16:28:01 +00002176 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002177 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00002178 return rc;
drha059ad02001-04-17 20:09:11 +00002179}
2180
danielk1977687566d2004-11-02 12:56:41 +00002181#ifndef SQLITE_OMIT_AUTOVACUUM
2182
2183/*
2184** Set the pointer-map entries for all children of page pPage. Also, if
2185** pPage contains cells that point to overflow pages, set the pointer
2186** map entries for the overflow pages as well.
2187*/
2188static int setChildPtrmaps(MemPage *pPage){
2189 int i; /* Counter variable */
2190 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00002191 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00002192 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00002193 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002194 Pgno pgno = pPage->pgno;
2195
drh1fee73e2007-08-29 04:00:57 +00002196 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197771d5d2c2008-09-29 11:49:47 +00002197 rc = sqlite3BtreeInitPage(pPage);
danielk19772df71c72007-05-24 07:22:42 +00002198 if( rc!=SQLITE_OK ){
2199 goto set_child_ptrmaps_out;
2200 }
danielk1977687566d2004-11-02 12:56:41 +00002201 nCell = pPage->nCell;
2202
2203 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002204 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002205
danielk197726836652005-01-17 01:33:13 +00002206 rc = ptrmapPutOvflPtr(pPage, pCell);
2207 if( rc!=SQLITE_OK ){
2208 goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002209 }
danielk197726836652005-01-17 01:33:13 +00002210
danielk1977687566d2004-11-02 12:56:41 +00002211 if( !pPage->leaf ){
2212 Pgno childPgno = get4byte(pCell);
2213 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
danielk197700a696d2008-09-29 16:41:31 +00002214 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002215 }
2216 }
2217
2218 if( !pPage->leaf ){
2219 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
2220 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
2221 }
2222
2223set_child_ptrmaps_out:
2224 pPage->isInit = isInitOrig;
2225 return rc;
2226}
2227
2228/*
2229** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
2230** page, is a pointer to page iFrom. Modify this pointer so that it points to
2231** iTo. Parameter eType describes the type of pointer to be modified, as
2232** follows:
2233**
2234** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
2235** page of pPage.
2236**
2237** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
2238** page pointed to by one of the cells on pPage.
2239**
2240** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
2241** overflow page in the list.
2242*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00002243static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00002244 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00002245 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977687566d2004-11-02 12:56:41 +00002246 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00002247 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00002248 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00002249 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002250 }
danielk1977f78fc082004-11-02 14:40:32 +00002251 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00002252 }else{
drhf49661a2008-12-10 16:45:50 +00002253 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002254 int i;
2255 int nCell;
2256
danielk197771d5d2c2008-09-29 11:49:47 +00002257 sqlite3BtreeInitPage(pPage);
danielk1977687566d2004-11-02 12:56:41 +00002258 nCell = pPage->nCell;
2259
danielk1977687566d2004-11-02 12:56:41 +00002260 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002261 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002262 if( eType==PTRMAP_OVERFLOW1 ){
2263 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00002264 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
danielk1977687566d2004-11-02 12:56:41 +00002265 if( info.iOverflow ){
2266 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
2267 put4byte(&pCell[info.iOverflow], iTo);
2268 break;
2269 }
2270 }
2271 }else{
2272 if( get4byte(pCell)==iFrom ){
2273 put4byte(pCell, iTo);
2274 break;
2275 }
2276 }
2277 }
2278
2279 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00002280 if( eType!=PTRMAP_BTREE ||
2281 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00002282 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002283 }
danielk1977687566d2004-11-02 12:56:41 +00002284 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
2285 }
2286
2287 pPage->isInit = isInitOrig;
2288 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002289 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002290}
2291
danielk1977003ba062004-11-04 02:57:33 +00002292
danielk19777701e812005-01-10 12:59:51 +00002293/*
2294** Move the open database page pDbPage to location iFreePage in the
2295** database. The pDbPage reference remains valid.
2296*/
danielk1977003ba062004-11-04 02:57:33 +00002297static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00002298 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00002299 MemPage *pDbPage, /* Open page to move */
2300 u8 eType, /* Pointer map 'type' entry for pDbPage */
2301 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
danielk19774c999992008-07-16 18:17:55 +00002302 Pgno iFreePage, /* The location to move pDbPage to */
2303 int isCommit
danielk1977003ba062004-11-04 02:57:33 +00002304){
2305 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
2306 Pgno iDbPage = pDbPage->pgno;
2307 Pager *pPager = pBt->pPager;
2308 int rc;
2309
danielk1977a0bf2652004-11-04 14:30:04 +00002310 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
2311 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00002312 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00002313 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00002314
drh85b623f2007-12-13 21:54:09 +00002315 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00002316 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
2317 iDbPage, iFreePage, iPtrPage, eType));
danielk19774c999992008-07-16 18:17:55 +00002318 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
danielk1977003ba062004-11-04 02:57:33 +00002319 if( rc!=SQLITE_OK ){
2320 return rc;
2321 }
2322 pDbPage->pgno = iFreePage;
2323
2324 /* If pDbPage was a btree-page, then it may have child pages and/or cells
2325 ** that point to overflow pages. The pointer map entries for all these
2326 ** pages need to be changed.
2327 **
2328 ** If pDbPage is an overflow page, then the first 4 bytes may store a
2329 ** pointer to a subsequent overflow page. If this is the case, then
2330 ** the pointer map needs to be updated for the subsequent overflow page.
2331 */
danielk1977a0bf2652004-11-04 14:30:04 +00002332 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00002333 rc = setChildPtrmaps(pDbPage);
2334 if( rc!=SQLITE_OK ){
2335 return rc;
2336 }
2337 }else{
2338 Pgno nextOvfl = get4byte(pDbPage->aData);
2339 if( nextOvfl!=0 ){
danielk1977003ba062004-11-04 02:57:33 +00002340 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
2341 if( rc!=SQLITE_OK ){
2342 return rc;
2343 }
2344 }
2345 }
2346
2347 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
2348 ** that it points at iFreePage. Also fix the pointer map entry for
2349 ** iPtrPage.
2350 */
danielk1977a0bf2652004-11-04 14:30:04 +00002351 if( eType!=PTRMAP_ROOTPAGE ){
drh16a9b832007-05-05 18:39:25 +00002352 rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00002353 if( rc!=SQLITE_OK ){
2354 return rc;
2355 }
danielk19773b8a05f2007-03-19 17:44:26 +00002356 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00002357 if( rc!=SQLITE_OK ){
2358 releasePage(pPtrPage);
2359 return rc;
2360 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002361 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00002362 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00002363 if( rc==SQLITE_OK ){
2364 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
2365 }
danielk1977003ba062004-11-04 02:57:33 +00002366 }
danielk1977003ba062004-11-04 02:57:33 +00002367 return rc;
2368}
2369
danielk1977dddbcdc2007-04-26 14:42:34 +00002370/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00002371static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00002372
2373/*
danielk1977dddbcdc2007-04-26 14:42:34 +00002374** Perform a single step of an incremental-vacuum. If successful,
2375** return SQLITE_OK. If there is no work to do (and therefore no
2376** point in calling this function again), return SQLITE_DONE.
2377**
2378** More specificly, this function attempts to re-organize the
2379** database so that the last page of the file currently in use
2380** is no longer in use.
2381**
2382** If the nFin parameter is non-zero, the implementation assumes
2383** that the caller will keep calling incrVacuumStep() until
2384** it returns SQLITE_DONE or an error, and that nFin is the
2385** number of pages the database file will contain after this
2386** process is complete.
2387*/
danielk19773460d192008-12-27 15:23:13 +00002388static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
danielk1977dddbcdc2007-04-26 14:42:34 +00002389 Pgno nFreeList; /* Number of pages still on the free-list */
2390
drh1fee73e2007-08-29 04:00:57 +00002391 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977dddbcdc2007-04-26 14:42:34 +00002392
2393 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
2394 int rc;
2395 u8 eType;
2396 Pgno iPtrPage;
2397
2398 nFreeList = get4byte(&pBt->pPage1->aData[36]);
2399 if( nFreeList==0 || nFin==iLastPg ){
2400 return SQLITE_DONE;
2401 }
2402
2403 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
2404 if( rc!=SQLITE_OK ){
2405 return rc;
2406 }
2407 if( eType==PTRMAP_ROOTPAGE ){
2408 return SQLITE_CORRUPT_BKPT;
2409 }
2410
2411 if( eType==PTRMAP_FREEPAGE ){
2412 if( nFin==0 ){
2413 /* Remove the page from the files free-list. This is not required
danielk19774ef24492007-05-23 09:52:41 +00002414 ** if nFin is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00002415 ** truncated to zero after this function returns, so it doesn't
2416 ** matter if it still contains some garbage entries.
2417 */
2418 Pgno iFreePg;
2419 MemPage *pFreePg;
2420 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
2421 if( rc!=SQLITE_OK ){
2422 return rc;
2423 }
2424 assert( iFreePg==iLastPg );
2425 releasePage(pFreePg);
2426 }
2427 } else {
2428 Pgno iFreePg; /* Index of free page to move pLastPg to */
2429 MemPage *pLastPg;
2430
drh16a9b832007-05-05 18:39:25 +00002431 rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002432 if( rc!=SQLITE_OK ){
2433 return rc;
2434 }
2435
danielk1977b4626a32007-04-28 15:47:43 +00002436 /* If nFin is zero, this loop runs exactly once and page pLastPg
2437 ** is swapped with the first free page pulled off the free list.
2438 **
2439 ** On the other hand, if nFin is greater than zero, then keep
2440 ** looping until a free-page located within the first nFin pages
2441 ** of the file is found.
2442 */
danielk1977dddbcdc2007-04-26 14:42:34 +00002443 do {
2444 MemPage *pFreePg;
2445 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
2446 if( rc!=SQLITE_OK ){
2447 releasePage(pLastPg);
2448 return rc;
2449 }
2450 releasePage(pFreePg);
2451 }while( nFin!=0 && iFreePg>nFin );
2452 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00002453
2454 rc = sqlite3PagerWrite(pLastPg->pDbPage);
danielk1977662278e2007-11-05 15:30:12 +00002455 if( rc==SQLITE_OK ){
danielk19774c999992008-07-16 18:17:55 +00002456 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
danielk1977662278e2007-11-05 15:30:12 +00002457 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002458 releasePage(pLastPg);
2459 if( rc!=SQLITE_OK ){
2460 return rc;
danielk1977662278e2007-11-05 15:30:12 +00002461 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002462 }
2463 }
2464
danielk19773460d192008-12-27 15:23:13 +00002465 if( nFin==0 ){
2466 iLastPg--;
2467 while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
2468 iLastPg--;
2469 }
2470 sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
danielk1977dddbcdc2007-04-26 14:42:34 +00002471 }
2472 return SQLITE_OK;
2473}
2474
2475/*
2476** A write-transaction must be opened before calling this function.
2477** It performs a single unit of work towards an incremental vacuum.
2478**
2479** If the incremental vacuum is finished after this function has run,
shanebe217792009-03-05 04:20:31 +00002480** SQLITE_DONE is returned. If it is not finished, but no error occurred,
danielk1977dddbcdc2007-04-26 14:42:34 +00002481** SQLITE_OK is returned. Otherwise an SQLite error code.
2482*/
2483int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002484 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002485 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002486
2487 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002488 pBt->db = p->db;
danielk1977dddbcdc2007-04-26 14:42:34 +00002489 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
2490 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002491 rc = SQLITE_DONE;
2492 }else{
2493 invalidateAllOverflowCache(pBt);
danielk1977bea2a942009-01-20 17:06:27 +00002494 rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt));
danielk1977dddbcdc2007-04-26 14:42:34 +00002495 }
drhd677b3d2007-08-20 22:48:41 +00002496 sqlite3BtreeLeave(p);
2497 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002498}
2499
2500/*
danielk19773b8a05f2007-03-19 17:44:26 +00002501** This routine is called prior to sqlite3PagerCommit when a transaction
danielk1977687566d2004-11-02 12:56:41 +00002502** is commited for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00002503**
2504** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
2505** the database file should be truncated to during the commit process.
2506** i.e. the database has been reorganized so that only the first *pnTrunc
2507** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00002508*/
danielk19773460d192008-12-27 15:23:13 +00002509static int autoVacuumCommit(BtShared *pBt){
danielk1977dddbcdc2007-04-26 14:42:34 +00002510 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002511 Pager *pPager = pBt->pPager;
drhf94a1732008-09-30 17:18:17 +00002512 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002513
drh1fee73e2007-08-29 04:00:57 +00002514 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00002515 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00002516 assert(pBt->autoVacuum);
2517 if( !pBt->incrVacuum ){
danielk19773460d192008-12-27 15:23:13 +00002518 Pgno nFin;
2519 Pgno nFree;
2520 Pgno nPtrmap;
2521 Pgno iFree;
2522 const int pgsz = pBt->pageSize;
2523 Pgno nOrig = pagerPagecount(pBt);
danielk1977687566d2004-11-02 12:56:41 +00002524
danielk19773460d192008-12-27 15:23:13 +00002525 if( PTRMAP_ISPAGE(pBt, nOrig) ){
2526 return SQLITE_CORRUPT_BKPT;
2527 }
2528 if( nOrig==PENDING_BYTE_PAGE(pBt) ){
2529 nOrig--;
2530 }
2531 nFree = get4byte(&pBt->pPage1->aData[36]);
2532 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
2533 nFin = nOrig - nFree - nPtrmap;
2534 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
2535 nFin--;
2536 }
2537 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
2538 nFin--;
danielk1977dddbcdc2007-04-26 14:42:34 +00002539 }
danielk1977687566d2004-11-02 12:56:41 +00002540
danielk19773460d192008-12-27 15:23:13 +00002541 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
2542 rc = incrVacuumStep(pBt, nFin, iFree);
danielk1977dddbcdc2007-04-26 14:42:34 +00002543 }
danielk19773460d192008-12-27 15:23:13 +00002544 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00002545 rc = SQLITE_OK;
danielk19773460d192008-12-27 15:23:13 +00002546 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
2547 put4byte(&pBt->pPage1->aData[32], 0);
2548 put4byte(&pBt->pPage1->aData[36], 0);
2549 sqlite3PagerTruncateImage(pBt->pPager, nFin);
danielk1977dddbcdc2007-04-26 14:42:34 +00002550 }
2551 if( rc!=SQLITE_OK ){
2552 sqlite3PagerRollback(pPager);
2553 }
danielk1977687566d2004-11-02 12:56:41 +00002554 }
2555
danielk19773b8a05f2007-03-19 17:44:26 +00002556 assert( nRef==sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002557 return rc;
2558}
danielk1977dddbcdc2007-04-26 14:42:34 +00002559
shane831c3292008-11-10 17:14:58 +00002560#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
danielk1977687566d2004-11-02 12:56:41 +00002561
2562/*
drh80e35f42007-03-30 14:06:34 +00002563** This routine does the first phase of a two-phase commit. This routine
2564** causes a rollback journal to be created (if it does not already exist)
2565** and populated with enough information so that if a power loss occurs
2566** the database can be restored to its original state by playing back
2567** the journal. Then the contents of the journal are flushed out to
2568** the disk. After the journal is safely on oxide, the changes to the
2569** database are written into the database file and flushed to oxide.
2570** At the end of this call, the rollback journal still exists on the
2571** disk and we are still holding all locks, so the transaction has not
2572** committed. See sqlite3BtreeCommit() for the second phase of the
2573** commit process.
2574**
2575** This call is a no-op if no write-transaction is currently active on pBt.
2576**
2577** Otherwise, sync the database file for the btree pBt. zMaster points to
2578** the name of a master journal file that should be written into the
2579** individual journal file, or is NULL, indicating no master journal file
2580** (single database transaction).
2581**
2582** When this is called, the master journal should already have been
2583** created, populated with this journal pointer and synced to disk.
2584**
2585** Once this is routine has returned, the only thing required to commit
2586** the write-transaction for this database file is to delete the journal.
2587*/
2588int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
2589 int rc = SQLITE_OK;
2590 if( p->inTrans==TRANS_WRITE ){
2591 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002592 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002593 pBt->db = p->db;
drh80e35f42007-03-30 14:06:34 +00002594#ifndef SQLITE_OMIT_AUTOVACUUM
2595 if( pBt->autoVacuum ){
danielk19773460d192008-12-27 15:23:13 +00002596 rc = autoVacuumCommit(pBt);
drh80e35f42007-03-30 14:06:34 +00002597 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002598 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002599 return rc;
2600 }
2601 }
2602#endif
drh49b9d332009-01-02 18:10:42 +00002603 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
drhd677b3d2007-08-20 22:48:41 +00002604 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002605 }
2606 return rc;
2607}
2608
2609/*
drh2aa679f2001-06-25 02:11:07 +00002610** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00002611**
drh6e345992007-03-30 11:12:08 +00002612** This routine implements the second phase of a 2-phase commit. The
2613** sqlite3BtreeSync() routine does the first phase and should be invoked
2614** prior to calling this routine. The sqlite3BtreeSync() routine did
2615** all the work of writing information out to disk and flushing the
2616** contents so that they are written onto the disk platter. All this
2617** routine has to do is delete or truncate the rollback journal
2618** (which causes the transaction to commit) and drop locks.
2619**
drh5e00f6c2001-09-13 13:46:56 +00002620** This will release the write lock on the database file. If there
2621** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002622*/
drh80e35f42007-03-30 14:06:34 +00002623int sqlite3BtreeCommitPhaseTwo(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002624 BtShared *pBt = p->pBt;
2625
drhd677b3d2007-08-20 22:48:41 +00002626 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002627 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00002628 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002629
2630 /* If the handle has a write-transaction open, commit the shared-btrees
2631 ** transaction and set the shared state to TRANS_READ.
2632 */
2633 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00002634 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002635 assert( pBt->inTransaction==TRANS_WRITE );
2636 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00002637 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
danielk19777f7bc662006-01-23 13:47:47 +00002638 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002639 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002640 return rc;
2641 }
danielk1977aef0bf62005-12-30 16:28:01 +00002642 pBt->inTransaction = TRANS_READ;
danielk1977ee5741e2004-05-31 10:01:34 +00002643 }
drhc25eabe2009-02-24 18:57:31 +00002644 clearAllSharedCacheTableLocks(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002645
2646 /* If the handle has any kind of transaction open, decrement the transaction
2647 ** count of the shared btree. If the transaction count reaches 0, set
2648 ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
2649 ** will unlock the pager.
2650 */
2651 if( p->inTrans!=TRANS_NONE ){
2652 pBt->nTransaction--;
2653 if( 0==pBt->nTransaction ){
2654 pBt->inTransaction = TRANS_NONE;
2655 }
2656 }
2657
2658 /* Set the handles current transaction state to TRANS_NONE and unlock
2659 ** the pager if this call closed the only read or write transaction.
2660 */
danielk1977bea2a942009-01-20 17:06:27 +00002661 btreeClearHasContent(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002662 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00002663 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002664
2665 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002666 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002667 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002668}
2669
drh80e35f42007-03-30 14:06:34 +00002670/*
2671** Do both phases of a commit.
2672*/
2673int sqlite3BtreeCommit(Btree *p){
2674 int rc;
drhd677b3d2007-08-20 22:48:41 +00002675 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00002676 rc = sqlite3BtreeCommitPhaseOne(p, 0);
2677 if( rc==SQLITE_OK ){
2678 rc = sqlite3BtreeCommitPhaseTwo(p);
2679 }
drhd677b3d2007-08-20 22:48:41 +00002680 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002681 return rc;
2682}
2683
danielk1977fbcd5852004-06-15 02:44:18 +00002684#ifndef NDEBUG
2685/*
2686** Return the number of write-cursors open on this handle. This is for use
2687** in assert() expressions, so it is only compiled if NDEBUG is not
2688** defined.
drhfb982642007-08-30 01:19:59 +00002689**
2690** For the purposes of this routine, a write-cursor is any cursor that
2691** is capable of writing to the databse. That means the cursor was
2692** originally opened for writing and the cursor has not be disabled
2693** by having its state changed to CURSOR_FAULT.
danielk1977fbcd5852004-06-15 02:44:18 +00002694*/
danielk1977aef0bf62005-12-30 16:28:01 +00002695static int countWriteCursors(BtShared *pBt){
danielk1977fbcd5852004-06-15 02:44:18 +00002696 BtCursor *pCur;
2697 int r = 0;
2698 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drhfb982642007-08-30 01:19:59 +00002699 if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
danielk1977fbcd5852004-06-15 02:44:18 +00002700 }
2701 return r;
2702}
2703#endif
2704
drhc39e0002004-05-07 23:50:57 +00002705/*
drhfb982642007-08-30 01:19:59 +00002706** This routine sets the state to CURSOR_FAULT and the error
2707** code to errCode for every cursor on BtShared that pBtree
2708** references.
2709**
2710** Every cursor is tripped, including cursors that belong
2711** to other database connections that happen to be sharing
2712** the cache with pBtree.
2713**
2714** This routine gets called when a rollback occurs.
2715** All cursors using the same cache must be tripped
2716** to prevent them from trying to use the btree after
2717** the rollback. The rollback may have deleted tables
2718** or moved root pages, so it is not sufficient to
2719** save the state of the cursor. The cursor must be
2720** invalidated.
2721*/
2722void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
2723 BtCursor *p;
2724 sqlite3BtreeEnter(pBtree);
2725 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
danielk1977bc2ca9e2008-11-13 14:28:28 +00002726 int i;
danielk1977be51a652008-10-08 17:58:48 +00002727 sqlite3BtreeClearCursor(p);
drhfb982642007-08-30 01:19:59 +00002728 p->eState = CURSOR_FAULT;
2729 p->skip = errCode;
danielk1977bc2ca9e2008-11-13 14:28:28 +00002730 for(i=0; i<=p->iPage; i++){
2731 releasePage(p->apPage[i]);
2732 p->apPage[i] = 0;
2733 }
drhfb982642007-08-30 01:19:59 +00002734 }
2735 sqlite3BtreeLeave(pBtree);
2736}
2737
2738/*
drhecdc7532001-09-23 02:35:53 +00002739** Rollback the transaction in progress. All cursors will be
2740** invalided by this operation. Any attempt to use a cursor
2741** that was open at the beginning of this operation will result
2742** in an error.
drh5e00f6c2001-09-13 13:46:56 +00002743**
2744** This will release the write lock on the database file. If there
2745** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002746*/
danielk1977aef0bf62005-12-30 16:28:01 +00002747int sqlite3BtreeRollback(Btree *p){
danielk19778d34dfd2006-01-24 16:37:57 +00002748 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002749 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00002750 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00002751
drhd677b3d2007-08-20 22:48:41 +00002752 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002753 pBt->db = p->db;
danielk19772b8c13e2006-01-24 14:21:24 +00002754 rc = saveAllCursors(pBt, 0, 0);
danielk19778d34dfd2006-01-24 16:37:57 +00002755#ifndef SQLITE_OMIT_SHARED_CACHE
danielk19772b8c13e2006-01-24 14:21:24 +00002756 if( rc!=SQLITE_OK ){
shanebe217792009-03-05 04:20:31 +00002757 /* This is a horrible situation. An IO or malloc() error occurred whilst
danielk19778d34dfd2006-01-24 16:37:57 +00002758 ** trying to save cursor positions. If this is an automatic rollback (as
2759 ** the result of a constraint, malloc() failure or IO error) then
2760 ** the cache may be internally inconsistent (not contain valid trees) so
2761 ** we cannot simply return the error to the caller. Instead, abort
2762 ** all queries that may be using any of the cursors that failed to save.
2763 */
drhfb982642007-08-30 01:19:59 +00002764 sqlite3BtreeTripAllCursors(p, rc);
danielk19772b8c13e2006-01-24 14:21:24 +00002765 }
danielk19778d34dfd2006-01-24 16:37:57 +00002766#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002767 btreeIntegrity(p);
drhc25eabe2009-02-24 18:57:31 +00002768 clearAllSharedCacheTableLocks(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002769
2770 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00002771 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00002772
danielk19778d34dfd2006-01-24 16:37:57 +00002773 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00002774 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00002775 if( rc2!=SQLITE_OK ){
2776 rc = rc2;
2777 }
2778
drh24cd67e2004-05-10 16:18:47 +00002779 /* The rollback may have destroyed the pPage1->aData value. So
drh16a9b832007-05-05 18:39:25 +00002780 ** call sqlite3BtreeGetPage() on page 1 again to make
2781 ** sure pPage1->aData is set correctly. */
2782 if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh24cd67e2004-05-10 16:18:47 +00002783 releasePage(pPage1);
2784 }
danielk1977fbcd5852004-06-15 02:44:18 +00002785 assert( countWriteCursors(pBt)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002786 pBt->inTransaction = TRANS_READ;
drh24cd67e2004-05-10 16:18:47 +00002787 }
danielk1977aef0bf62005-12-30 16:28:01 +00002788
2789 if( p->inTrans!=TRANS_NONE ){
2790 assert( pBt->nTransaction>0 );
2791 pBt->nTransaction--;
2792 if( 0==pBt->nTransaction ){
2793 pBt->inTransaction = TRANS_NONE;
2794 }
2795 }
2796
danielk1977bea2a942009-01-20 17:06:27 +00002797 btreeClearHasContent(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002798 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00002799 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002800
2801 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002802 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00002803 return rc;
2804}
2805
2806/*
danielk1977bd434552009-03-18 10:33:00 +00002807** Start a statement subtransaction. The subtransaction can can be rolled
2808** back independently of the main transaction. You must start a transaction
2809** before starting a subtransaction. The subtransaction is ended automatically
2810** if the main transaction commits or rolls back.
drhab01f612004-05-22 02:55:23 +00002811**
2812** Statement subtransactions are used around individual SQL statements
2813** that are contained within a BEGIN...COMMIT block. If a constraint
2814** error occurs within the statement, the effect of that one statement
2815** can be rolled back without having to rollback the entire transaction.
danielk1977bd434552009-03-18 10:33:00 +00002816**
2817** A statement sub-transaction is implemented as an anonymous savepoint. The
2818** value passed as the second parameter is the total number of savepoints,
2819** including the new anonymous savepoint, open on the B-Tree. i.e. if there
2820** are no active savepoints and no other statement-transactions open,
2821** iStatement is 1. This anonymous savepoint can be released or rolled back
2822** using the sqlite3BtreeSavepoint() function.
drh663fc632002-02-02 18:49:19 +00002823*/
danielk1977bd434552009-03-18 10:33:00 +00002824int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
drh663fc632002-02-02 18:49:19 +00002825 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002826 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002827 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002828 pBt->db = p->db;
drh64022502009-01-09 14:11:04 +00002829 assert( p->inTrans==TRANS_WRITE );
drh64022502009-01-09 14:11:04 +00002830 assert( pBt->readOnly==0 );
danielk1977bd434552009-03-18 10:33:00 +00002831 assert( iStatement>0 );
2832 assert( iStatement>p->db->nSavepoint );
2833 if( NEVER(p->inTrans!=TRANS_WRITE || pBt->readOnly) ){
drh64022502009-01-09 14:11:04 +00002834 rc = SQLITE_INTERNAL;
drhd677b3d2007-08-20 22:48:41 +00002835 }else{
2836 assert( pBt->inTransaction==TRANS_WRITE );
drh64022502009-01-09 14:11:04 +00002837 /* At the pager level, a statement transaction is a savepoint with
2838 ** an index greater than all savepoints created explicitly using
2839 ** SQL statements. It is illegal to open, release or rollback any
2840 ** such savepoints while the statement transaction savepoint is active.
2841 */
danielk1977bd434552009-03-18 10:33:00 +00002842 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
danielk197797a227c2006-01-20 16:32:04 +00002843 }
drhd677b3d2007-08-20 22:48:41 +00002844 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002845 return rc;
2846}
2847
2848/*
danielk1977fd7f0452008-12-17 17:30:26 +00002849** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
2850** or SAVEPOINT_RELEASE. This function either releases or rolls back the
danielk197712dd5492008-12-18 15:45:07 +00002851** savepoint identified by parameter iSavepoint, depending on the value
2852** of op.
2853**
2854** Normally, iSavepoint is greater than or equal to zero. However, if op is
2855** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
2856** contents of the entire transaction are rolled back. This is different
2857** from a normal transaction rollback, as no locks are released and the
2858** transaction remains open.
danielk1977fd7f0452008-12-17 17:30:26 +00002859*/
2860int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
2861 int rc = SQLITE_OK;
2862 if( p && p->inTrans==TRANS_WRITE ){
2863 BtShared *pBt = p->pBt;
danielk1977fd7f0452008-12-17 17:30:26 +00002864 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
2865 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
2866 sqlite3BtreeEnter(p);
2867 pBt->db = p->db;
2868 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
drh9f0bbf92009-01-02 21:08:09 +00002869 if( rc==SQLITE_OK ){
2870 rc = newDatabase(pBt);
2871 }
danielk1977fd7f0452008-12-17 17:30:26 +00002872 sqlite3BtreeLeave(p);
2873 }
2874 return rc;
2875}
2876
2877/*
drh8b2f49b2001-06-08 00:21:52 +00002878** Create a new cursor for the BTree whose root is on the page
2879** iTable. The act of acquiring a cursor gets a read lock on
2880** the database file.
drh1bee3d72001-10-15 00:44:35 +00002881**
2882** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00002883** If wrFlag==1, then the cursor can be used for reading or for
2884** writing if other conditions for writing are also met. These
2885** are the conditions that must be met in order for writing to
2886** be allowed:
drh6446c4d2001-12-15 14:22:18 +00002887**
drhf74b8d92002-09-01 23:20:45 +00002888** 1: The cursor must have been opened with wrFlag==1
2889**
drhfe5d71d2007-03-19 11:54:10 +00002890** 2: Other database connections that share the same pager cache
2891** but which are not in the READ_UNCOMMITTED state may not have
2892** cursors open with wrFlag==0 on the same table. Otherwise
2893** the changes made by this write cursor would be visible to
2894** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00002895**
2896** 3: The database must be writable (not on read-only media)
2897**
2898** 4: There must be an active transaction.
2899**
drh6446c4d2001-12-15 14:22:18 +00002900** No checking is done to make sure that page iTable really is the
2901** root page of a b-tree. If it is not, then the cursor acquired
2902** will not work correctly.
danielk197771d5d2c2008-09-29 11:49:47 +00002903**
2904** It is assumed that the sqlite3BtreeCursorSize() bytes of memory
2905** pointed to by pCur have been zeroed by the caller.
drha059ad02001-04-17 20:09:11 +00002906*/
drhd677b3d2007-08-20 22:48:41 +00002907static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00002908 Btree *p, /* The btree */
2909 int iTable, /* Root page of table to open */
2910 int wrFlag, /* 1 to write. 0 read-only */
2911 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
2912 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00002913){
drha059ad02001-04-17 20:09:11 +00002914 int rc;
danielk197789d40042008-11-17 14:20:56 +00002915 Pgno nPage;
danielk1977aef0bf62005-12-30 16:28:01 +00002916 BtShared *pBt = p->pBt;
drhecdc7532001-09-23 02:35:53 +00002917
drh1fee73e2007-08-29 04:00:57 +00002918 assert( sqlite3BtreeHoldsMutex(p) );
drhf49661a2008-12-10 16:45:50 +00002919 assert( wrFlag==0 || wrFlag==1 );
drh8dcd7ca2004-08-08 19:43:29 +00002920 if( wrFlag ){
drh64022502009-01-09 14:11:04 +00002921 assert( !pBt->readOnly );
2922 if( NEVER(pBt->readOnly) ){
drh8dcd7ca2004-08-08 19:43:29 +00002923 return SQLITE_READONLY;
2924 }
danielk1977404ca072009-03-16 13:19:36 +00002925 rc = checkForReadConflicts(p, iTable, 0, 0);
2926 if( rc!=SQLITE_OK ){
2927 assert( rc==SQLITE_LOCKED_SHAREDCACHE );
2928 return rc;
drh8dcd7ca2004-08-08 19:43:29 +00002929 }
drha0c9a112004-03-10 13:42:37 +00002930 }
danielk1977aef0bf62005-12-30 16:28:01 +00002931
drh4b70f112004-05-02 21:12:19 +00002932 if( pBt->pPage1==0 ){
danielk1977aef0bf62005-12-30 16:28:01 +00002933 rc = lockBtreeWithRetry(p);
drha059ad02001-04-17 20:09:11 +00002934 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00002935 return rc;
2936 }
2937 }
drh8b2f49b2001-06-08 00:21:52 +00002938 pCur->pgnoRoot = (Pgno)iTable;
danielk197789d40042008-11-17 14:20:56 +00002939 rc = sqlite3PagerPagecount(pBt->pPager, (int *)&nPage);
2940 if( rc!=SQLITE_OK ){
2941 return rc;
2942 }
2943 if( iTable==1 && nPage==0 ){
drh24cd67e2004-05-10 16:18:47 +00002944 rc = SQLITE_EMPTY;
2945 goto create_cursor_exception;
2946 }
danielk197771d5d2c2008-09-29 11:49:47 +00002947 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
drhbd03cae2001-06-02 02:40:57 +00002948 if( rc!=SQLITE_OK ){
2949 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00002950 }
danielk1977aef0bf62005-12-30 16:28:01 +00002951
danielk1977aef0bf62005-12-30 16:28:01 +00002952 /* Now that no other errors can occur, finish filling in the BtCursor
2953 ** variables, link the cursor into the BtShared list and set *ppCur (the
2954 ** output argument to this function).
2955 */
drh1e968a02008-03-25 00:22:21 +00002956 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00002957 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00002958 pCur->pBt = pBt;
drhf49661a2008-12-10 16:45:50 +00002959 pCur->wrFlag = (u8)wrFlag;
drha059ad02001-04-17 20:09:11 +00002960 pCur->pNext = pBt->pCursor;
2961 if( pCur->pNext ){
2962 pCur->pNext->pPrev = pCur;
2963 }
2964 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00002965 pCur->eState = CURSOR_INVALID;
drh7f751222009-03-17 22:33:00 +00002966 pCur->cachedRowid = 0;
drhbd03cae2001-06-02 02:40:57 +00002967
danielk1977aef0bf62005-12-30 16:28:01 +00002968 return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00002969
drhbd03cae2001-06-02 02:40:57 +00002970create_cursor_exception:
danielk197771d5d2c2008-09-29 11:49:47 +00002971 releasePage(pCur->apPage[0]);
drh5e00f6c2001-09-13 13:46:56 +00002972 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00002973 return rc;
drha059ad02001-04-17 20:09:11 +00002974}
drhd677b3d2007-08-20 22:48:41 +00002975int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00002976 Btree *p, /* The btree */
2977 int iTable, /* Root page of table to open */
2978 int wrFlag, /* 1 to write. 0 read-only */
2979 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
2980 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00002981){
2982 int rc;
2983 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002984 p->pBt->db = p->db;
danielk1977cd3e8f72008-03-25 09:47:35 +00002985 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
drhd677b3d2007-08-20 22:48:41 +00002986 sqlite3BtreeLeave(p);
2987 return rc;
2988}
drh7f751222009-03-17 22:33:00 +00002989
2990/*
2991** Return the size of a BtCursor object in bytes.
2992**
2993** This interfaces is needed so that users of cursors can preallocate
2994** sufficient storage to hold a cursor. The BtCursor object is opaque
2995** to users so they cannot do the sizeof() themselves - they must call
2996** this routine.
2997*/
2998int sqlite3BtreeCursorSize(void){
danielk1977cd3e8f72008-03-25 09:47:35 +00002999 return sizeof(BtCursor);
3000}
3001
drh7f751222009-03-17 22:33:00 +00003002/*
3003** Set the cached rowid value of every cursor in the same database file
3004** as pCur and having the same root page number as pCur. The value is
3005** set to iRowid.
3006**
3007** Only positive rowid values are considered valid for this cache.
3008** The cache is initialized to zero, indicating an invalid cache.
3009** A btree will work fine with zero or negative rowids. We just cannot
3010** cache zero or negative rowids, which means tables that use zero or
3011** negative rowids might run a little slower. But in practice, zero
3012** or negative rowids are very uncommon so this should not be a problem.
3013*/
3014void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
3015 BtCursor *p;
3016 for(p=pCur->pBt->pCursor; p; p=p->pNext){
3017 if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
3018 }
3019 assert( pCur->cachedRowid==iRowid );
3020}
drhd677b3d2007-08-20 22:48:41 +00003021
drh7f751222009-03-17 22:33:00 +00003022/*
3023** Return the cached rowid for the given cursor. A negative or zero
3024** return value indicates that the rowid cache is invalid and should be
3025** ignored. If the rowid cache has never before been set, then a
3026** zero is returned.
3027*/
3028sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
3029 return pCur->cachedRowid;
3030}
drha059ad02001-04-17 20:09:11 +00003031
3032/*
drh5e00f6c2001-09-13 13:46:56 +00003033** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00003034** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00003035*/
drh3aac2dd2004-04-26 14:10:20 +00003036int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00003037 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00003038 if( pBtree ){
danielk197771d5d2c2008-09-29 11:49:47 +00003039 int i;
danielk1977cd3e8f72008-03-25 09:47:35 +00003040 BtShared *pBt = pCur->pBt;
3041 sqlite3BtreeEnter(pBtree);
3042 pBt->db = pBtree->db;
danielk1977be51a652008-10-08 17:58:48 +00003043 sqlite3BtreeClearCursor(pCur);
danielk1977cd3e8f72008-03-25 09:47:35 +00003044 if( pCur->pPrev ){
3045 pCur->pPrev->pNext = pCur->pNext;
3046 }else{
3047 pBt->pCursor = pCur->pNext;
3048 }
3049 if( pCur->pNext ){
3050 pCur->pNext->pPrev = pCur->pPrev;
3051 }
danielk197771d5d2c2008-09-29 11:49:47 +00003052 for(i=0; i<=pCur->iPage; i++){
3053 releasePage(pCur->apPage[i]);
3054 }
danielk1977cd3e8f72008-03-25 09:47:35 +00003055 unlockBtreeIfUnused(pBt);
3056 invalidateOverflowCache(pCur);
3057 /* sqlite3_free(pCur); */
3058 sqlite3BtreeLeave(pBtree);
drha059ad02001-04-17 20:09:11 +00003059 }
drh8c42ca92001-06-22 19:15:00 +00003060 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003061}
3062
drh7e3b0a02001-04-28 16:52:40 +00003063/*
drh5e2f8b92001-05-28 00:41:15 +00003064** Make a temporary cursor by filling in the fields of pTempCur.
3065** The temporary cursor is not on the cursor list for the Btree.
3066*/
drh16a9b832007-05-05 18:39:25 +00003067void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
danielk197771d5d2c2008-09-29 11:49:47 +00003068 int i;
drh1fee73e2007-08-29 04:00:57 +00003069 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00003070 memcpy(pTempCur, pCur, sizeof(BtCursor));
drh5e2f8b92001-05-28 00:41:15 +00003071 pTempCur->pNext = 0;
3072 pTempCur->pPrev = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003073 for(i=0; i<=pTempCur->iPage; i++){
3074 sqlite3PagerRef(pTempCur->apPage[i]->pDbPage);
drhecdc7532001-09-23 02:35:53 +00003075 }
danielk197736e20932008-11-26 07:40:30 +00003076 assert( pTempCur->pKey==0 );
drh5e2f8b92001-05-28 00:41:15 +00003077}
3078
3079/*
drhbd03cae2001-06-02 02:40:57 +00003080** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00003081** function above.
3082*/
drh16a9b832007-05-05 18:39:25 +00003083void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
danielk197771d5d2c2008-09-29 11:49:47 +00003084 int i;
drh1fee73e2007-08-29 04:00:57 +00003085 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00003086 for(i=0; i<=pCur->iPage; i++){
3087 sqlite3PagerUnref(pCur->apPage[i]->pDbPage);
drhecdc7532001-09-23 02:35:53 +00003088 }
danielk197736e20932008-11-26 07:40:30 +00003089 sqlite3_free(pCur->pKey);
drh5e2f8b92001-05-28 00:41:15 +00003090}
3091
drh7f751222009-03-17 22:33:00 +00003092
3093
drh5e2f8b92001-05-28 00:41:15 +00003094/*
drh86057612007-06-26 01:04:48 +00003095** Make sure the BtCursor* given in the argument has a valid
3096** BtCursor.info structure. If it is not already valid, call
danielk19771cc5ed82007-05-16 17:28:43 +00003097** sqlite3BtreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00003098**
3099** BtCursor.info is a cache of the information in the current cell.
drh16a9b832007-05-05 18:39:25 +00003100** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
drh86057612007-06-26 01:04:48 +00003101**
3102** 2007-06-25: There is a bug in some versions of MSVC that cause the
3103** compiler to crash when getCellInfo() is implemented as a macro.
3104** But there is a measureable speed advantage to using the macro on gcc
3105** (when less compiler optimizations like -Os or -O0 are used and the
3106** compiler is not doing agressive inlining.) So we use a real function
3107** for MSVC and a macro for everything else. Ticket #2457.
drh9188b382004-05-14 21:12:22 +00003108*/
drh9188b382004-05-14 21:12:22 +00003109#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00003110 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00003111 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00003112 int iPage = pCur->iPage;
drh51c6d962004-06-06 00:42:25 +00003113 memset(&info, 0, sizeof(info));
danielk197771d5d2c2008-09-29 11:49:47 +00003114 sqlite3BtreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
drh9188b382004-05-14 21:12:22 +00003115 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00003116 }
danielk19771cc5ed82007-05-16 17:28:43 +00003117#else
3118 #define assertCellInfo(x)
3119#endif
drh86057612007-06-26 01:04:48 +00003120#ifdef _MSC_VER
3121 /* Use a real function in MSVC to work around bugs in that compiler. */
3122 static void getCellInfo(BtCursor *pCur){
3123 if( pCur->info.nSize==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003124 int iPage = pCur->iPage;
3125 sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
drha2c20e42008-03-29 16:01:04 +00003126 pCur->validNKey = 1;
drh86057612007-06-26 01:04:48 +00003127 }else{
3128 assertCellInfo(pCur);
3129 }
3130 }
3131#else /* if not _MSC_VER */
3132 /* Use a macro in all other compilers so that the function is inlined */
danielk197771d5d2c2008-09-29 11:49:47 +00003133#define getCellInfo(pCur) \
3134 if( pCur->info.nSize==0 ){ \
3135 int iPage = pCur->iPage; \
3136 sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
3137 pCur->validNKey = 1; \
3138 }else{ \
3139 assertCellInfo(pCur); \
drh86057612007-06-26 01:04:48 +00003140 }
3141#endif /* _MSC_VER */
drh9188b382004-05-14 21:12:22 +00003142
3143/*
drh3aac2dd2004-04-26 14:10:20 +00003144** Set *pSize to the size of the buffer needed to hold the value of
3145** the key for the current entry. If the cursor is not pointing
3146** to a valid entry, *pSize is set to 0.
3147**
drh4b70f112004-05-02 21:12:19 +00003148** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00003149** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00003150*/
drh4a1c3802004-05-12 15:15:47 +00003151int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drhd677b3d2007-08-20 22:48:41 +00003152 int rc;
3153
drh1fee73e2007-08-29 04:00:57 +00003154 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003155 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003156 if( rc==SQLITE_OK ){
3157 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3158 if( pCur->eState==CURSOR_INVALID ){
3159 *pSize = 0;
3160 }else{
drh86057612007-06-26 01:04:48 +00003161 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00003162 *pSize = pCur->info.nKey;
3163 }
drh72f82862001-05-24 21:06:34 +00003164 }
danielk1977da184232006-01-05 11:34:32 +00003165 return rc;
drha059ad02001-04-17 20:09:11 +00003166}
drh2af926b2001-05-15 00:39:25 +00003167
drh72f82862001-05-24 21:06:34 +00003168/*
drh0e1c19e2004-05-11 00:58:56 +00003169** Set *pSize to the number of bytes of data in the entry the
3170** cursor currently points to. Always return SQLITE_OK.
3171** Failure is not possible. If the cursor is not currently
3172** pointing to an entry (which can happen, for example, if
3173** the database is empty) then *pSize is set to 0.
3174*/
3175int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drhd677b3d2007-08-20 22:48:41 +00003176 int rc;
3177
drh1fee73e2007-08-29 04:00:57 +00003178 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003179 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003180 if( rc==SQLITE_OK ){
3181 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3182 if( pCur->eState==CURSOR_INVALID ){
3183 /* Not pointing at a valid entry - set *pSize to 0. */
3184 *pSize = 0;
3185 }else{
drh86057612007-06-26 01:04:48 +00003186 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00003187 *pSize = pCur->info.nData;
3188 }
drh0e1c19e2004-05-11 00:58:56 +00003189 }
danielk1977da184232006-01-05 11:34:32 +00003190 return rc;
drh0e1c19e2004-05-11 00:58:56 +00003191}
3192
3193/*
danielk1977d04417962007-05-02 13:16:30 +00003194** Given the page number of an overflow page in the database (parameter
3195** ovfl), this function finds the page number of the next page in the
3196** linked list of overflow pages. If possible, it uses the auto-vacuum
3197** pointer-map data instead of reading the content of page ovfl to do so.
3198**
3199** If an error occurs an SQLite error code is returned. Otherwise:
3200**
danielk1977bea2a942009-01-20 17:06:27 +00003201** The page number of the next overflow page in the linked list is
3202** written to *pPgnoNext. If page ovfl is the last page in its linked
3203** list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003204**
danielk1977bea2a942009-01-20 17:06:27 +00003205** If ppPage is not NULL, and a reference to the MemPage object corresponding
3206** to page number pOvfl was obtained, then *ppPage is set to point to that
3207** reference. It is the responsibility of the caller to call releasePage()
3208** on *ppPage to free the reference. In no reference was obtained (because
3209** the pointer-map was used to obtain the value for *pPgnoNext), then
3210** *ppPage is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003211*/
3212static int getOverflowPage(
3213 BtShared *pBt,
3214 Pgno ovfl, /* Overflow page */
danielk1977bea2a942009-01-20 17:06:27 +00003215 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
danielk1977d04417962007-05-02 13:16:30 +00003216 Pgno *pPgnoNext /* OUT: Next overflow page number */
3217){
3218 Pgno next = 0;
danielk1977bea2a942009-01-20 17:06:27 +00003219 MemPage *pPage = 0;
drh1bd10f82008-12-10 21:19:56 +00003220 int rc = SQLITE_OK;
danielk1977d04417962007-05-02 13:16:30 +00003221
drh1fee73e2007-08-29 04:00:57 +00003222 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bea2a942009-01-20 17:06:27 +00003223 assert(pPgnoNext);
danielk1977d04417962007-05-02 13:16:30 +00003224
3225#ifndef SQLITE_OMIT_AUTOVACUUM
3226 /* Try to find the next page in the overflow list using the
3227 ** autovacuum pointer-map pages. Guess that the next page in
3228 ** the overflow list is page number (ovfl+1). If that guess turns
3229 ** out to be wrong, fall back to loading the data of page
3230 ** number ovfl to determine the next page number.
3231 */
3232 if( pBt->autoVacuum ){
3233 Pgno pgno;
3234 Pgno iGuess = ovfl+1;
3235 u8 eType;
3236
3237 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
3238 iGuess++;
3239 }
3240
danielk197789d40042008-11-17 14:20:56 +00003241 if( iGuess<=pagerPagecount(pBt) ){
danielk1977d04417962007-05-02 13:16:30 +00003242 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
danielk1977bea2a942009-01-20 17:06:27 +00003243 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
danielk1977d04417962007-05-02 13:16:30 +00003244 next = iGuess;
danielk1977bea2a942009-01-20 17:06:27 +00003245 rc = SQLITE_DONE;
danielk1977d04417962007-05-02 13:16:30 +00003246 }
3247 }
3248 }
3249#endif
3250
danielk1977bea2a942009-01-20 17:06:27 +00003251 if( rc==SQLITE_OK ){
3252 rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, 0);
danielk1977d04417962007-05-02 13:16:30 +00003253 assert(rc==SQLITE_OK || pPage==0);
3254 if( next==0 && rc==SQLITE_OK ){
3255 next = get4byte(pPage->aData);
3256 }
danielk1977443c0592009-01-16 15:21:05 +00003257 }
danielk197745d68822009-01-16 16:23:38 +00003258
danielk1977bea2a942009-01-20 17:06:27 +00003259 *pPgnoNext = next;
3260 if( ppPage ){
3261 *ppPage = pPage;
3262 }else{
3263 releasePage(pPage);
3264 }
3265 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
danielk1977d04417962007-05-02 13:16:30 +00003266}
3267
danielk1977da107192007-05-04 08:32:13 +00003268/*
3269** Copy data from a buffer to a page, or from a page to a buffer.
3270**
3271** pPayload is a pointer to data stored on database page pDbPage.
3272** If argument eOp is false, then nByte bytes of data are copied
3273** from pPayload to the buffer pointed at by pBuf. If eOp is true,
3274** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
3275** of data are copied from the buffer pBuf to pPayload.
3276**
3277** SQLITE_OK is returned on success, otherwise an error code.
3278*/
3279static int copyPayload(
3280 void *pPayload, /* Pointer to page data */
3281 void *pBuf, /* Pointer to buffer */
3282 int nByte, /* Number of bytes to copy */
3283 int eOp, /* 0 -> copy from page, 1 -> copy to page */
3284 DbPage *pDbPage /* Page containing pPayload */
3285){
3286 if( eOp ){
3287 /* Copy data from buffer to page (a write operation) */
3288 int rc = sqlite3PagerWrite(pDbPage);
3289 if( rc!=SQLITE_OK ){
3290 return rc;
3291 }
3292 memcpy(pPayload, pBuf, nByte);
3293 }else{
3294 /* Copy data from page to buffer (a read operation) */
3295 memcpy(pBuf, pPayload, nByte);
3296 }
3297 return SQLITE_OK;
3298}
danielk1977d04417962007-05-02 13:16:30 +00003299
3300/*
danielk19779f8d6402007-05-02 17:48:45 +00003301** This function is used to read or overwrite payload information
3302** for the entry that the pCur cursor is pointing to. If the eOp
3303** parameter is 0, this is a read operation (data copied into
3304** buffer pBuf). If it is non-zero, a write (data copied from
3305** buffer pBuf).
3306**
3307** A total of "amt" bytes are read or written beginning at "offset".
3308** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00003309**
3310** This routine does not make a distinction between key and data.
danielk19779f8d6402007-05-02 17:48:45 +00003311** It just reads or writes bytes from the payload area. Data might
3312** appear on the main page or be scattered out on multiple overflow
3313** pages.
danielk1977da107192007-05-04 08:32:13 +00003314**
danielk1977dcbb5d32007-05-04 18:36:44 +00003315** If the BtCursor.isIncrblobHandle flag is set, and the current
danielk1977da107192007-05-04 08:32:13 +00003316** cursor entry uses one or more overflow pages, this function
3317** allocates space for and lazily popluates the overflow page-list
3318** cache array (BtCursor.aOverflow). Subsequent calls use this
3319** cache to make seeking to the supplied offset more efficient.
3320**
3321** Once an overflow page-list cache has been allocated, it may be
3322** invalidated if some other cursor writes to the same table, or if
3323** the cursor is moved to a different row. Additionally, in auto-vacuum
3324** mode, the following events may invalidate an overflow page-list cache.
3325**
3326** * An incremental vacuum,
3327** * A commit in auto_vacuum="full" mode,
3328** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00003329*/
danielk19779f8d6402007-05-02 17:48:45 +00003330static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00003331 BtCursor *pCur, /* Cursor pointing to entry to read from */
danielk197789d40042008-11-17 14:20:56 +00003332 u32 offset, /* Begin reading this far into payload */
3333 u32 amt, /* Read this many bytes */
drh3aac2dd2004-04-26 14:10:20 +00003334 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00003335 int skipKey, /* offset begins at data if this is true */
3336 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00003337){
3338 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00003339 int rc = SQLITE_OK;
drhfa1a98a2004-05-14 19:08:17 +00003340 u32 nKey;
danielk19772dec9702007-05-02 16:48:37 +00003341 int iIdx = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003342 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
danielk19770d065412008-11-12 18:21:36 +00003343 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
drh3aac2dd2004-04-26 14:10:20 +00003344
danielk1977da107192007-05-04 08:32:13 +00003345 assert( pPage );
danielk1977da184232006-01-05 11:34:32 +00003346 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003347 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh1fee73e2007-08-29 04:00:57 +00003348 assert( cursorHoldsMutex(pCur) );
danielk1977da107192007-05-04 08:32:13 +00003349
drh86057612007-06-26 01:04:48 +00003350 getCellInfo(pCur);
drh366fda62006-01-13 02:35:09 +00003351 aPayload = pCur->info.pCell + pCur->info.nHeader;
drhf49661a2008-12-10 16:45:50 +00003352 nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
danielk1977da107192007-05-04 08:32:13 +00003353
drh3aac2dd2004-04-26 14:10:20 +00003354 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003355 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00003356 }
danielk19770d065412008-11-12 18:21:36 +00003357 if( offset+amt > nKey+pCur->info.nData
3358 || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
3359 ){
danielk1977da107192007-05-04 08:32:13 +00003360 /* Trying to read or write past the end of the data is an error */
danielk197767fd7a92008-09-10 17:53:35 +00003361 return SQLITE_CORRUPT_BKPT;
drh3aac2dd2004-04-26 14:10:20 +00003362 }
danielk1977da107192007-05-04 08:32:13 +00003363
3364 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00003365 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00003366 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00003367 if( a+offset>pCur->info.nLocal ){
3368 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00003369 }
danielk1977da107192007-05-04 08:32:13 +00003370 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00003371 offset = 0;
drha34b6762004-05-07 13:30:42 +00003372 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00003373 amt -= a;
drhdd793422001-06-28 01:54:48 +00003374 }else{
drhfa1a98a2004-05-14 19:08:17 +00003375 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00003376 }
danielk1977da107192007-05-04 08:32:13 +00003377
3378 if( rc==SQLITE_OK && amt>0 ){
danielk197789d40042008-11-17 14:20:56 +00003379 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
danielk1977da107192007-05-04 08:32:13 +00003380 Pgno nextPage;
3381
drhfa1a98a2004-05-14 19:08:17 +00003382 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00003383
danielk19772dec9702007-05-02 16:48:37 +00003384#ifndef SQLITE_OMIT_INCRBLOB
danielk1977dcbb5d32007-05-04 18:36:44 +00003385 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
danielk1977da107192007-05-04 08:32:13 +00003386 ** has not been allocated, allocate it now. The array is sized at
3387 ** one entry for each overflow page in the overflow chain. The
3388 ** page number of the first overflow page is stored in aOverflow[0],
3389 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
3390 ** (the cache is lazily populated).
3391 */
danielk1977dcbb5d32007-05-04 18:36:44 +00003392 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
danielk19772dec9702007-05-02 16:48:37 +00003393 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
drh17435752007-08-16 04:30:38 +00003394 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
danielk19772dec9702007-05-02 16:48:37 +00003395 if( nOvfl && !pCur->aOverflow ){
danielk1977da107192007-05-04 08:32:13 +00003396 rc = SQLITE_NOMEM;
danielk19772dec9702007-05-02 16:48:37 +00003397 }
3398 }
danielk1977da107192007-05-04 08:32:13 +00003399
3400 /* If the overflow page-list cache has been allocated and the
3401 ** entry for the first required overflow page is valid, skip
3402 ** directly to it.
3403 */
danielk19772dec9702007-05-02 16:48:37 +00003404 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
3405 iIdx = (offset/ovflSize);
3406 nextPage = pCur->aOverflow[iIdx];
3407 offset = (offset%ovflSize);
3408 }
3409#endif
danielk1977da107192007-05-04 08:32:13 +00003410
3411 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
3412
3413#ifndef SQLITE_OMIT_INCRBLOB
3414 /* If required, populate the overflow page-list cache. */
3415 if( pCur->aOverflow ){
3416 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
3417 pCur->aOverflow[iIdx] = nextPage;
3418 }
3419#endif
3420
danielk1977d04417962007-05-02 13:16:30 +00003421 if( offset>=ovflSize ){
3422 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00003423 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00003424 ** data is not required. So first try to lookup the overflow
3425 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00003426 ** function.
danielk1977d04417962007-05-02 13:16:30 +00003427 */
danielk19772dec9702007-05-02 16:48:37 +00003428#ifndef SQLITE_OMIT_INCRBLOB
danielk1977da107192007-05-04 08:32:13 +00003429 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
3430 nextPage = pCur->aOverflow[iIdx+1];
3431 } else
danielk19772dec9702007-05-02 16:48:37 +00003432#endif
danielk1977da107192007-05-04 08:32:13 +00003433 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
danielk1977da107192007-05-04 08:32:13 +00003434 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00003435 }else{
danielk19779f8d6402007-05-02 17:48:45 +00003436 /* Need to read this page properly. It contains some of the
3437 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00003438 */
3439 DbPage *pDbPage;
danielk1977cfe9a692004-06-16 12:00:29 +00003440 int a = amt;
danielk1977d04417962007-05-02 13:16:30 +00003441 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
danielk1977da107192007-05-04 08:32:13 +00003442 if( rc==SQLITE_OK ){
3443 aPayload = sqlite3PagerGetData(pDbPage);
3444 nextPage = get4byte(aPayload);
3445 if( a + offset > ovflSize ){
3446 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00003447 }
danielk1977da107192007-05-04 08:32:13 +00003448 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
3449 sqlite3PagerUnref(pDbPage);
3450 offset = 0;
3451 amt -= a;
3452 pBuf += a;
danielk19779f8d6402007-05-02 17:48:45 +00003453 }
danielk1977cfe9a692004-06-16 12:00:29 +00003454 }
drh2af926b2001-05-15 00:39:25 +00003455 }
drh2af926b2001-05-15 00:39:25 +00003456 }
danielk1977cfe9a692004-06-16 12:00:29 +00003457
danielk1977da107192007-05-04 08:32:13 +00003458 if( rc==SQLITE_OK && amt>0 ){
drh49285702005-09-17 15:20:26 +00003459 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00003460 }
danielk1977da107192007-05-04 08:32:13 +00003461 return rc;
drh2af926b2001-05-15 00:39:25 +00003462}
3463
drh72f82862001-05-24 21:06:34 +00003464/*
drh3aac2dd2004-04-26 14:10:20 +00003465** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003466** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003467** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00003468**
drh3aac2dd2004-04-26 14:10:20 +00003469** Return SQLITE_OK on success or an error code if anything goes
3470** wrong. An error is returned if "offset+amt" is larger than
3471** the available payload.
drh72f82862001-05-24 21:06:34 +00003472*/
drha34b6762004-05-07 13:30:42 +00003473int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003474 int rc;
3475
drh1fee73e2007-08-29 04:00:57 +00003476 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003477 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003478 if( rc==SQLITE_OK ){
3479 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003480 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3481 if( pCur->apPage[0]->intKey ){
danielk1977da184232006-01-05 11:34:32 +00003482 return SQLITE_CORRUPT_BKPT;
3483 }
danielk197771d5d2c2008-09-29 11:49:47 +00003484 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh16a9b832007-05-05 18:39:25 +00003485 rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
drh6575a222005-03-10 17:06:34 +00003486 }
danielk1977da184232006-01-05 11:34:32 +00003487 return rc;
drh3aac2dd2004-04-26 14:10:20 +00003488}
3489
3490/*
drh3aac2dd2004-04-26 14:10:20 +00003491** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003492** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003493** begins at "offset".
3494**
3495** Return SQLITE_OK on success or an error code if anything goes
3496** wrong. An error is returned if "offset+amt" is larger than
3497** the available payload.
drh72f82862001-05-24 21:06:34 +00003498*/
drh3aac2dd2004-04-26 14:10:20 +00003499int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003500 int rc;
3501
danielk19773588ceb2008-06-10 17:30:26 +00003502#ifndef SQLITE_OMIT_INCRBLOB
3503 if ( pCur->eState==CURSOR_INVALID ){
3504 return SQLITE_ABORT;
3505 }
3506#endif
3507
drh1fee73e2007-08-29 04:00:57 +00003508 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003509 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003510 if( rc==SQLITE_OK ){
3511 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003512 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3513 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh16a9b832007-05-05 18:39:25 +00003514 rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
danielk1977da184232006-01-05 11:34:32 +00003515 }
3516 return rc;
drh2af926b2001-05-15 00:39:25 +00003517}
3518
drh72f82862001-05-24 21:06:34 +00003519/*
drh0e1c19e2004-05-11 00:58:56 +00003520** Return a pointer to payload information from the entry that the
3521** pCur cursor is pointing to. The pointer is to the beginning of
3522** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00003523** skipKey==1. The number of bytes of available key/data is written
3524** into *pAmt. If *pAmt==0, then the value returned will not be
3525** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00003526**
3527** This routine is an optimization. It is common for the entire key
3528** and data to fit on the local page and for there to be no overflow
3529** pages. When that is so, this routine can be used to access the
3530** key and data without making a copy. If the key and/or data spills
drh7f751222009-03-17 22:33:00 +00003531** onto overflow pages, then accessPayload() must be used to reassemble
drh0e1c19e2004-05-11 00:58:56 +00003532** the key/data and copy it into a preallocated buffer.
3533**
3534** The pointer returned by this routine looks directly into the cached
3535** page of the database. The data might change or move the next time
3536** any btree routine is called.
3537*/
3538static const unsigned char *fetchPayload(
3539 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00003540 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00003541 int skipKey /* read beginning at data if this is true */
3542){
3543 unsigned char *aPayload;
3544 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00003545 u32 nKey;
danielk197789d40042008-11-17 14:20:56 +00003546 u32 nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003547
danielk197771d5d2c2008-09-29 11:49:47 +00003548 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
danielk1977da184232006-01-05 11:34:32 +00003549 assert( pCur->eState==CURSOR_VALID );
drh1fee73e2007-08-29 04:00:57 +00003550 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00003551 pPage = pCur->apPage[pCur->iPage];
3552 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh86057612007-06-26 01:04:48 +00003553 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00003554 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00003555 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00003556 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00003557 nKey = 0;
3558 }else{
drhf49661a2008-12-10 16:45:50 +00003559 nKey = (int)pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00003560 }
drh0e1c19e2004-05-11 00:58:56 +00003561 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003562 aPayload += nKey;
3563 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00003564 }else{
drhfa1a98a2004-05-14 19:08:17 +00003565 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00003566 if( nLocal>nKey ){
3567 nLocal = nKey;
3568 }
drh0e1c19e2004-05-11 00:58:56 +00003569 }
drhe51c44f2004-05-30 20:46:09 +00003570 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003571 return aPayload;
3572}
3573
3574
3575/*
drhe51c44f2004-05-30 20:46:09 +00003576** For the entry that cursor pCur is point to, return as
3577** many bytes of the key or data as are available on the local
3578** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00003579**
3580** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00003581** or be destroyed on the next call to any Btree routine,
3582** including calls from other threads against the same cache.
3583** Hence, a mutex on the BtShared should be held prior to calling
3584** this routine.
drh0e1c19e2004-05-11 00:58:56 +00003585**
3586** These routines is used to get quick access to key and data
3587** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00003588*/
drhe51c44f2004-05-30 20:46:09 +00003589const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
drh1fee73e2007-08-29 04:00:57 +00003590 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003591 if( pCur->eState==CURSOR_VALID ){
3592 return (const void*)fetchPayload(pCur, pAmt, 0);
3593 }
3594 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003595}
drhe51c44f2004-05-30 20:46:09 +00003596const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
drh1fee73e2007-08-29 04:00:57 +00003597 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003598 if( pCur->eState==CURSOR_VALID ){
3599 return (const void*)fetchPayload(pCur, pAmt, 1);
3600 }
3601 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003602}
3603
3604
3605/*
drh8178a752003-01-05 21:41:40 +00003606** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00003607** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00003608*/
drh3aac2dd2004-04-26 14:10:20 +00003609static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00003610 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003611 int i = pCur->iPage;
drh72f82862001-05-24 21:06:34 +00003612 MemPage *pNewPage;
drhd0679ed2007-08-28 22:24:34 +00003613 BtShared *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00003614
drh1fee73e2007-08-29 04:00:57 +00003615 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003616 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003617 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
3618 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
3619 return SQLITE_CORRUPT_BKPT;
3620 }
3621 rc = getAndInitPage(pBt, newPgno, &pNewPage);
drh6019e162001-07-02 17:51:45 +00003622 if( rc ) return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003623 pCur->apPage[i+1] = pNewPage;
3624 pCur->aiIdx[i+1] = 0;
3625 pCur->iPage++;
3626
drh271efa52004-05-30 19:19:05 +00003627 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003628 pCur->validNKey = 0;
drh4be295b2003-12-16 03:44:47 +00003629 if( pNewPage->nCell<1 ){
drh49285702005-09-17 15:20:26 +00003630 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00003631 }
drh72f82862001-05-24 21:06:34 +00003632 return SQLITE_OK;
3633}
3634
danielk1977bf93c562008-09-29 15:53:25 +00003635#ifndef NDEBUG
3636/*
3637** Page pParent is an internal (non-leaf) tree page. This function
3638** asserts that page number iChild is the left-child if the iIdx'th
3639** cell in page pParent. Or, if iIdx is equal to the total number of
3640** cells in pParent, that page number iChild is the right-child of
3641** the page.
3642*/
3643static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
3644 assert( iIdx<=pParent->nCell );
3645 if( iIdx==pParent->nCell ){
3646 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
3647 }else{
3648 assert( get4byte(findCell(pParent, iIdx))==iChild );
3649 }
3650}
3651#else
3652# define assertParentIndex(x,y,z)
3653#endif
3654
drh72f82862001-05-24 21:06:34 +00003655/*
drh5e2f8b92001-05-28 00:41:15 +00003656** Move the cursor up to the parent page.
3657**
3658** pCur->idx is set to the cell index that contains the pointer
3659** to the page we are coming from. If we are coming from the
3660** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00003661** the largest cell index.
drh72f82862001-05-24 21:06:34 +00003662*/
drh16a9b832007-05-05 18:39:25 +00003663void sqlite3BtreeMoveToParent(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00003664 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003665 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003666 assert( pCur->iPage>0 );
3667 assert( pCur->apPage[pCur->iPage] );
danielk1977bf93c562008-09-29 15:53:25 +00003668 assertParentIndex(
3669 pCur->apPage[pCur->iPage-1],
3670 pCur->aiIdx[pCur->iPage-1],
3671 pCur->apPage[pCur->iPage]->pgno
3672 );
danielk197771d5d2c2008-09-29 11:49:47 +00003673 releasePage(pCur->apPage[pCur->iPage]);
3674 pCur->iPage--;
drh271efa52004-05-30 19:19:05 +00003675 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003676 pCur->validNKey = 0;
drh72f82862001-05-24 21:06:34 +00003677}
3678
3679/*
3680** Move the cursor to the root page
3681*/
drh5e2f8b92001-05-28 00:41:15 +00003682static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00003683 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00003684 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003685 Btree *p = pCur->pBtree;
3686 BtShared *pBt = p->pBt;
drhbd03cae2001-06-02 02:40:57 +00003687
drh1fee73e2007-08-29 04:00:57 +00003688 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +00003689 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
3690 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
3691 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
3692 if( pCur->eState>=CURSOR_REQUIRESEEK ){
3693 if( pCur->eState==CURSOR_FAULT ){
3694 return pCur->skip;
3695 }
danielk1977be51a652008-10-08 17:58:48 +00003696 sqlite3BtreeClearCursor(pCur);
drhbf700f32007-03-31 02:36:44 +00003697 }
danielk197771d5d2c2008-09-29 11:49:47 +00003698
3699 if( pCur->iPage>=0 ){
3700 int i;
3701 for(i=1; i<=pCur->iPage; i++){
3702 releasePage(pCur->apPage[i]);
danielk1977d9f6c532008-09-19 16:39:38 +00003703 }
drh777e4c42006-01-13 04:31:58 +00003704 }else{
3705 if(
danielk197771d5d2c2008-09-29 11:49:47 +00003706 SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]))
drh777e4c42006-01-13 04:31:58 +00003707 ){
3708 pCur->eState = CURSOR_INVALID;
3709 return rc;
3710 }
drhc39e0002004-05-07 23:50:57 +00003711 }
danielk197771d5d2c2008-09-29 11:49:47 +00003712
3713 pRoot = pCur->apPage[0];
3714 assert( pRoot->pgno==pCur->pgnoRoot );
3715 pCur->iPage = 0;
3716 pCur->aiIdx[0] = 0;
drh271efa52004-05-30 19:19:05 +00003717 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003718 pCur->atLast = 0;
3719 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003720
drh8856d6a2004-04-29 14:42:46 +00003721 if( pRoot->nCell==0 && !pRoot->leaf ){
3722 Pgno subpage;
3723 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00003724 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00003725 assert( subpage>0 );
danielk1977da184232006-01-05 11:34:32 +00003726 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00003727 rc = moveToChild(pCur, subpage);
danielk197771d5d2c2008-09-29 11:49:47 +00003728 }else{
3729 pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
drh8856d6a2004-04-29 14:42:46 +00003730 }
3731 return rc;
drh72f82862001-05-24 21:06:34 +00003732}
drh2af926b2001-05-15 00:39:25 +00003733
drh5e2f8b92001-05-28 00:41:15 +00003734/*
3735** Move the cursor down to the left-most leaf entry beneath the
3736** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00003737**
3738** The left-most leaf is the one with the smallest key - the first
3739** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00003740*/
3741static int moveToLeftmost(BtCursor *pCur){
3742 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00003743 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00003744 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00003745
drh1fee73e2007-08-29 04:00:57 +00003746 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003747 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003748 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
3749 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
3750 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
drh8178a752003-01-05 21:41:40 +00003751 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00003752 }
drhd677b3d2007-08-20 22:48:41 +00003753 return rc;
drh5e2f8b92001-05-28 00:41:15 +00003754}
3755
drh2dcc9aa2002-12-04 13:40:25 +00003756/*
3757** Move the cursor down to the right-most leaf entry beneath the
3758** page to which it is currently pointing. Notice the difference
3759** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
3760** finds the left-most entry beneath the *entry* whereas moveToRightmost()
3761** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00003762**
3763** The right-most entry is the one with the largest key - the last
3764** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00003765*/
3766static int moveToRightmost(BtCursor *pCur){
3767 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00003768 int rc = SQLITE_OK;
drh1bd10f82008-12-10 21:19:56 +00003769 MemPage *pPage = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003770
drh1fee73e2007-08-29 04:00:57 +00003771 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003772 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003773 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
drh43605152004-05-29 21:46:49 +00003774 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
danielk197771d5d2c2008-09-29 11:49:47 +00003775 pCur->aiIdx[pCur->iPage] = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00003776 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003777 }
drhd677b3d2007-08-20 22:48:41 +00003778 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00003779 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
drhd677b3d2007-08-20 22:48:41 +00003780 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003781 pCur->validNKey = 0;
drhd677b3d2007-08-20 22:48:41 +00003782 }
danielk1977518002e2008-09-05 05:02:46 +00003783 return rc;
drh2dcc9aa2002-12-04 13:40:25 +00003784}
3785
drh5e00f6c2001-09-13 13:46:56 +00003786/* Move the cursor to the first entry in the table. Return SQLITE_OK
3787** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003788** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00003789*/
drh3aac2dd2004-04-26 14:10:20 +00003790int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00003791 int rc;
drhd677b3d2007-08-20 22:48:41 +00003792
drh1fee73e2007-08-29 04:00:57 +00003793 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003794 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00003795 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003796 if( rc==SQLITE_OK ){
3797 if( pCur->eState==CURSOR_INVALID ){
danielk197771d5d2c2008-09-29 11:49:47 +00003798 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00003799 *pRes = 1;
3800 rc = SQLITE_OK;
3801 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00003802 assert( pCur->apPage[pCur->iPage]->nCell>0 );
drhd677b3d2007-08-20 22:48:41 +00003803 *pRes = 0;
3804 rc = moveToLeftmost(pCur);
3805 }
drh5e00f6c2001-09-13 13:46:56 +00003806 }
drh5e00f6c2001-09-13 13:46:56 +00003807 return rc;
3808}
drh5e2f8b92001-05-28 00:41:15 +00003809
drh9562b552002-02-19 15:00:07 +00003810/* Move the cursor to the last entry in the table. Return SQLITE_OK
3811** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003812** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00003813*/
drh3aac2dd2004-04-26 14:10:20 +00003814int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00003815 int rc;
drhd677b3d2007-08-20 22:48:41 +00003816
drh1fee73e2007-08-29 04:00:57 +00003817 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003818 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh9562b552002-02-19 15:00:07 +00003819 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003820 if( rc==SQLITE_OK ){
3821 if( CURSOR_INVALID==pCur->eState ){
danielk197771d5d2c2008-09-29 11:49:47 +00003822 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00003823 *pRes = 1;
3824 }else{
3825 assert( pCur->eState==CURSOR_VALID );
3826 *pRes = 0;
3827 rc = moveToRightmost(pCur);
drha2c20e42008-03-29 16:01:04 +00003828 getCellInfo(pCur);
drhf49661a2008-12-10 16:45:50 +00003829 pCur->atLast = rc==SQLITE_OK ?1:0;
drhd677b3d2007-08-20 22:48:41 +00003830 }
drh9562b552002-02-19 15:00:07 +00003831 }
drh9562b552002-02-19 15:00:07 +00003832 return rc;
3833}
3834
drhe14006d2008-03-25 17:23:32 +00003835/* Move the cursor so that it points to an entry near the key
drhe63d9992008-08-13 19:11:48 +00003836** specified by pIdxKey or intKey. Return a success code.
drh72f82862001-05-24 21:06:34 +00003837**
drhe63d9992008-08-13 19:11:48 +00003838** For INTKEY tables, the intKey parameter is used. pIdxKey
3839** must be NULL. For index tables, pIdxKey is used and intKey
3840** is ignored.
drh3aac2dd2004-04-26 14:10:20 +00003841**
drh5e2f8b92001-05-28 00:41:15 +00003842** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00003843** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00003844** were present. The cursor might point to an entry that comes
3845** before or after the key.
3846**
drh64022502009-01-09 14:11:04 +00003847** An integer is written into *pRes which is the result of
3848** comparing the key with the entry to which the cursor is
3849** pointing. The meaning of the integer written into
3850** *pRes is as follows:
drhbd03cae2001-06-02 02:40:57 +00003851**
3852** *pRes<0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00003853** is smaller than intKey/pIdxKey or if the table is empty
drh1a844c32002-12-04 22:29:28 +00003854** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00003855**
3856** *pRes==0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00003857** exactly matches intKey/pIdxKey.
drhbd03cae2001-06-02 02:40:57 +00003858**
3859** *pRes>0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00003860** is larger than intKey/pIdxKey.
drhd677b3d2007-08-20 22:48:41 +00003861**
drha059ad02001-04-17 20:09:11 +00003862*/
drhe63d9992008-08-13 19:11:48 +00003863int sqlite3BtreeMovetoUnpacked(
3864 BtCursor *pCur, /* The cursor to be moved */
3865 UnpackedRecord *pIdxKey, /* Unpacked index key */
3866 i64 intKey, /* The table key */
3867 int biasRight, /* If true, bias the search to the high end */
3868 int *pRes /* Write search results here */
drhe4d90812007-03-29 05:51:49 +00003869){
drh72f82862001-05-24 21:06:34 +00003870 int rc;
drhd677b3d2007-08-20 22:48:41 +00003871
drh1fee73e2007-08-29 04:00:57 +00003872 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003873 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drha2c20e42008-03-29 16:01:04 +00003874
3875 /* If the cursor is already positioned at the point we are trying
3876 ** to move to, then just return without doing any work */
danielk197771d5d2c2008-09-29 11:49:47 +00003877 if( pCur->eState==CURSOR_VALID && pCur->validNKey
3878 && pCur->apPage[0]->intKey
3879 ){
drhe63d9992008-08-13 19:11:48 +00003880 if( pCur->info.nKey==intKey ){
drha2c20e42008-03-29 16:01:04 +00003881 *pRes = 0;
3882 return SQLITE_OK;
3883 }
drhe63d9992008-08-13 19:11:48 +00003884 if( pCur->atLast && pCur->info.nKey<intKey ){
drha2c20e42008-03-29 16:01:04 +00003885 *pRes = -1;
3886 return SQLITE_OK;
3887 }
3888 }
3889
drh5e2f8b92001-05-28 00:41:15 +00003890 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003891 if( rc ){
3892 return rc;
3893 }
danielk197771d5d2c2008-09-29 11:49:47 +00003894 assert( pCur->apPage[pCur->iPage] );
3895 assert( pCur->apPage[pCur->iPage]->isInit );
danielk1977da184232006-01-05 11:34:32 +00003896 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00003897 *pRes = -1;
danielk197771d5d2c2008-09-29 11:49:47 +00003898 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhc39e0002004-05-07 23:50:57 +00003899 return SQLITE_OK;
3900 }
danielk197771d5d2c2008-09-29 11:49:47 +00003901 assert( pCur->apPage[0]->intKey || pIdxKey );
drh14684382006-11-30 13:05:29 +00003902 for(;;){
drh72f82862001-05-24 21:06:34 +00003903 int lwr, upr;
3904 Pgno chldPg;
danielk197771d5d2c2008-09-29 11:49:47 +00003905 MemPage *pPage = pCur->apPage[pCur->iPage];
drh1a844c32002-12-04 22:29:28 +00003906 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00003907 lwr = 0;
3908 upr = pPage->nCell-1;
drh64022502009-01-09 14:11:04 +00003909 if( (!pPage->intKey && pIdxKey==0) || upr<0 ){
drh1e968a02008-03-25 00:22:21 +00003910 rc = SQLITE_CORRUPT_BKPT;
3911 goto moveto_finish;
drh4eec4c12005-01-21 00:22:37 +00003912 }
drhe4d90812007-03-29 05:51:49 +00003913 if( biasRight ){
drhf49661a2008-12-10 16:45:50 +00003914 pCur->aiIdx[pCur->iPage] = (u16)upr;
drhe4d90812007-03-29 05:51:49 +00003915 }else{
drhf49661a2008-12-10 16:45:50 +00003916 pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
drhe4d90812007-03-29 05:51:49 +00003917 }
drh64022502009-01-09 14:11:04 +00003918 for(;;){
danielk197713adf8a2004-06-03 16:08:41 +00003919 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00003920 i64 nCellKey;
danielk197771d5d2c2008-09-29 11:49:47 +00003921 int idx = pCur->aiIdx[pCur->iPage];
drh366fda62006-01-13 02:35:09 +00003922 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003923 pCur->validNKey = 1;
drh3aac2dd2004-04-26 14:10:20 +00003924 if( pPage->intKey ){
drh777e4c42006-01-13 04:31:58 +00003925 u8 *pCell;
danielk197771d5d2c2008-09-29 11:49:47 +00003926 pCell = findCell(pPage, idx) + pPage->childPtrSize;
drhd172f862006-01-12 15:01:15 +00003927 if( pPage->hasData ){
danielk1977bab45c62006-01-16 15:14:27 +00003928 u32 dummy;
shane3f8d5cf2008-04-24 19:15:09 +00003929 pCell += getVarint32(pCell, dummy);
drhd172f862006-01-12 15:01:15 +00003930 }
drha2c20e42008-03-29 16:01:04 +00003931 getVarint(pCell, (u64*)&nCellKey);
drhe63d9992008-08-13 19:11:48 +00003932 if( nCellKey==intKey ){
drh3aac2dd2004-04-26 14:10:20 +00003933 c = 0;
drhe63d9992008-08-13 19:11:48 +00003934 }else if( nCellKey<intKey ){
drh41eb9e92008-04-02 18:33:07 +00003935 c = -1;
3936 }else{
drhe63d9992008-08-13 19:11:48 +00003937 assert( nCellKey>intKey );
drh41eb9e92008-04-02 18:33:07 +00003938 c = +1;
drh3aac2dd2004-04-26 14:10:20 +00003939 }
drh3aac2dd2004-04-26 14:10:20 +00003940 }else{
drhe51c44f2004-05-30 20:46:09 +00003941 int available;
danielk197713adf8a2004-06-03 16:08:41 +00003942 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drh366fda62006-01-13 02:35:09 +00003943 nCellKey = pCur->info.nKey;
drhe51c44f2004-05-30 20:46:09 +00003944 if( available>=nCellKey ){
drhf49661a2008-12-10 16:45:50 +00003945 c = sqlite3VdbeRecordCompare((int)nCellKey, pCellKey, pIdxKey);
drhe51c44f2004-05-30 20:46:09 +00003946 }else{
drhf49661a2008-12-10 16:45:50 +00003947 pCellKey = sqlite3Malloc( (int)nCellKey );
danielk19776507ecb2008-03-25 09:56:44 +00003948 if( pCellKey==0 ){
3949 rc = SQLITE_NOMEM;
3950 goto moveto_finish;
3951 }
drhf49661a2008-12-10 16:45:50 +00003952 rc = sqlite3BtreeKey(pCur, 0, (int)nCellKey, (void*)pCellKey);
drh1bd10f82008-12-10 21:19:56 +00003953 c = sqlite3VdbeRecordCompare((int)nCellKey, pCellKey, pIdxKey);
drhfacf0302008-06-17 15:12:00 +00003954 sqlite3_free(pCellKey);
drh1e968a02008-03-25 00:22:21 +00003955 if( rc ) goto moveto_finish;
drhe51c44f2004-05-30 20:46:09 +00003956 }
drh3aac2dd2004-04-26 14:10:20 +00003957 }
drh72f82862001-05-24 21:06:34 +00003958 if( c==0 ){
drha2c20e42008-03-29 16:01:04 +00003959 pCur->info.nKey = nCellKey;
drh44845222008-07-17 18:39:57 +00003960 if( pPage->intKey && !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00003961 lwr = idx;
drhfc70e6f2004-05-12 21:11:27 +00003962 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00003963 break;
3964 }else{
drh64022502009-01-09 14:11:04 +00003965 *pRes = 0;
drh1e968a02008-03-25 00:22:21 +00003966 rc = SQLITE_OK;
3967 goto moveto_finish;
drh8b18dd42004-05-12 19:18:15 +00003968 }
drh72f82862001-05-24 21:06:34 +00003969 }
3970 if( c<0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003971 lwr = idx+1;
drh72f82862001-05-24 21:06:34 +00003972 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00003973 upr = idx-1;
drh72f82862001-05-24 21:06:34 +00003974 }
drhf1d68b32007-03-29 04:43:26 +00003975 if( lwr>upr ){
drha2c20e42008-03-29 16:01:04 +00003976 pCur->info.nKey = nCellKey;
drhf1d68b32007-03-29 04:43:26 +00003977 break;
3978 }
drhf49661a2008-12-10 16:45:50 +00003979 pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
drh72f82862001-05-24 21:06:34 +00003980 }
3981 assert( lwr==upr+1 );
danielk197771d5d2c2008-09-29 11:49:47 +00003982 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00003983 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00003984 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00003985 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00003986 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00003987 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00003988 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00003989 }
3990 if( chldPg==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003991 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh72f82862001-05-24 21:06:34 +00003992 if( pRes ) *pRes = c;
drh1e968a02008-03-25 00:22:21 +00003993 rc = SQLITE_OK;
3994 goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00003995 }
drhf49661a2008-12-10 16:45:50 +00003996 pCur->aiIdx[pCur->iPage] = (u16)lwr;
drh271efa52004-05-30 19:19:05 +00003997 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003998 pCur->validNKey = 0;
drh8178a752003-01-05 21:41:40 +00003999 rc = moveToChild(pCur, chldPg);
drh1e968a02008-03-25 00:22:21 +00004000 if( rc ) goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00004001 }
drh1e968a02008-03-25 00:22:21 +00004002moveto_finish:
drhe63d9992008-08-13 19:11:48 +00004003 return rc;
4004}
4005
4006/*
4007** In this version of BtreeMoveto, pKey is a packed index record
4008** such as is generated by the OP_MakeRecord opcode. Unpack the
4009** record and then call BtreeMovetoUnpacked() to do the work.
4010*/
4011int sqlite3BtreeMoveto(
4012 BtCursor *pCur, /* Cursor open on the btree to be searched */
4013 const void *pKey, /* Packed key if the btree is an index */
4014 i64 nKey, /* Integer key for tables. Size of pKey for indices */
4015 int bias, /* Bias search to the high end */
4016 int *pRes /* Write search results here */
4017){
4018 int rc; /* Status code */
4019 UnpackedRecord *pIdxKey; /* Unpacked index key */
drh23f79d02008-08-20 22:06:47 +00004020 UnpackedRecord aSpace[16]; /* Temp space for pIdxKey - to avoid a malloc */
drhe63d9992008-08-13 19:11:48 +00004021
drhe14006d2008-03-25 17:23:32 +00004022 if( pKey ){
drhf49661a2008-12-10 16:45:50 +00004023 assert( nKey==(i64)(int)nKey );
4024 pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
drh23f79d02008-08-20 22:06:47 +00004025 aSpace, sizeof(aSpace));
drhe63d9992008-08-13 19:11:48 +00004026 if( pIdxKey==0 ) return SQLITE_NOMEM;
4027 }else{
4028 pIdxKey = 0;
4029 }
4030 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
4031 if( pKey ){
4032 sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
drhe14006d2008-03-25 17:23:32 +00004033 }
drh1e968a02008-03-25 00:22:21 +00004034 return rc;
drh72f82862001-05-24 21:06:34 +00004035}
4036
drhd677b3d2007-08-20 22:48:41 +00004037
drh72f82862001-05-24 21:06:34 +00004038/*
drhc39e0002004-05-07 23:50:57 +00004039** Return TRUE if the cursor is not pointing at an entry of the table.
4040**
4041** TRUE will be returned after a call to sqlite3BtreeNext() moves
4042** past the last entry in the table or sqlite3BtreePrev() moves past
4043** the first entry. TRUE is also returned if the table is empty.
4044*/
4045int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00004046 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
4047 ** have been deleted? This API will need to change to return an error code
4048 ** as well as the boolean result value.
4049 */
4050 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00004051}
4052
4053/*
drhb21c8cd2007-08-21 19:33:56 +00004054** Return the database connection handle for a cursor.
4055*/
4056sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){
drhe5fe6902007-12-07 18:55:28 +00004057 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
4058 return pCur->pBtree->db;
drhb21c8cd2007-08-21 19:33:56 +00004059}
4060
4061/*
drhbd03cae2001-06-02 02:40:57 +00004062** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00004063** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00004064** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00004065** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00004066*/
drhd094db12008-04-03 21:46:57 +00004067int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00004068 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00004069 int idx;
danielk197797a227c2006-01-20 16:32:04 +00004070 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00004071
drh1fee73e2007-08-29 04:00:57 +00004072 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004073 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004074 if( rc!=SQLITE_OK ){
4075 return rc;
4076 }
drh8c4d3a62007-04-06 01:03:32 +00004077 assert( pRes!=0 );
drh8c4d3a62007-04-06 01:03:32 +00004078 if( CURSOR_INVALID==pCur->eState ){
4079 *pRes = 1;
4080 return SQLITE_OK;
4081 }
danielk1977da184232006-01-05 11:34:32 +00004082 if( pCur->skip>0 ){
4083 pCur->skip = 0;
4084 *pRes = 0;
4085 return SQLITE_OK;
4086 }
4087 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00004088
danielk197771d5d2c2008-09-29 11:49:47 +00004089 pPage = pCur->apPage[pCur->iPage];
4090 idx = ++pCur->aiIdx[pCur->iPage];
4091 assert( pPage->isInit );
4092 assert( idx<=pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00004093
drh271efa52004-05-30 19:19:05 +00004094 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004095 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004096 if( idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00004097 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004098 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00004099 if( rc ) return rc;
4100 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00004101 *pRes = 0;
4102 return rc;
drh72f82862001-05-24 21:06:34 +00004103 }
drh5e2f8b92001-05-28 00:41:15 +00004104 do{
danielk197771d5d2c2008-09-29 11:49:47 +00004105 if( pCur->iPage==0 ){
drh8c1238a2003-01-02 14:43:55 +00004106 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00004107 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00004108 return SQLITE_OK;
4109 }
drh16a9b832007-05-05 18:39:25 +00004110 sqlite3BtreeMoveToParent(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00004111 pPage = pCur->apPage[pCur->iPage];
4112 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00004113 *pRes = 0;
drh44845222008-07-17 18:39:57 +00004114 if( pPage->intKey ){
drh8b18dd42004-05-12 19:18:15 +00004115 rc = sqlite3BtreeNext(pCur, pRes);
4116 }else{
4117 rc = SQLITE_OK;
4118 }
4119 return rc;
drh8178a752003-01-05 21:41:40 +00004120 }
4121 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00004122 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00004123 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00004124 }
drh5e2f8b92001-05-28 00:41:15 +00004125 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00004126 return rc;
drh72f82862001-05-24 21:06:34 +00004127}
drhd677b3d2007-08-20 22:48:41 +00004128
drh72f82862001-05-24 21:06:34 +00004129
drh3b7511c2001-05-26 13:15:44 +00004130/*
drh2dcc9aa2002-12-04 13:40:25 +00004131** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00004132** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00004133** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00004134** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00004135*/
drhd094db12008-04-03 21:46:57 +00004136int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00004137 int rc;
drh8178a752003-01-05 21:41:40 +00004138 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00004139
drh1fee73e2007-08-29 04:00:57 +00004140 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004141 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004142 if( rc!=SQLITE_OK ){
4143 return rc;
4144 }
drha2c20e42008-03-29 16:01:04 +00004145 pCur->atLast = 0;
drh8c4d3a62007-04-06 01:03:32 +00004146 if( CURSOR_INVALID==pCur->eState ){
4147 *pRes = 1;
4148 return SQLITE_OK;
4149 }
danielk1977da184232006-01-05 11:34:32 +00004150 if( pCur->skip<0 ){
4151 pCur->skip = 0;
4152 *pRes = 0;
4153 return SQLITE_OK;
4154 }
4155 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00004156
danielk197771d5d2c2008-09-29 11:49:47 +00004157 pPage = pCur->apPage[pCur->iPage];
4158 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00004159 if( !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00004160 int idx = pCur->aiIdx[pCur->iPage];
4161 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
drhd677b3d2007-08-20 22:48:41 +00004162 if( rc ){
4163 return rc;
4164 }
drh2dcc9aa2002-12-04 13:40:25 +00004165 rc = moveToRightmost(pCur);
4166 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004167 while( pCur->aiIdx[pCur->iPage]==0 ){
4168 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00004169 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00004170 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00004171 return SQLITE_OK;
4172 }
drh16a9b832007-05-05 18:39:25 +00004173 sqlite3BtreeMoveToParent(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00004174 }
drh271efa52004-05-30 19:19:05 +00004175 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004176 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004177
4178 pCur->aiIdx[pCur->iPage]--;
4179 pPage = pCur->apPage[pCur->iPage];
drh44845222008-07-17 18:39:57 +00004180 if( pPage->intKey && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00004181 rc = sqlite3BtreePrevious(pCur, pRes);
4182 }else{
4183 rc = SQLITE_OK;
4184 }
drh2dcc9aa2002-12-04 13:40:25 +00004185 }
drh8178a752003-01-05 21:41:40 +00004186 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00004187 return rc;
4188}
4189
4190/*
drh3b7511c2001-05-26 13:15:44 +00004191** Allocate a new page from the database file.
4192**
danielk19773b8a05f2007-03-19 17:44:26 +00004193** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00004194** has already been called on the new page.) The new page has also
4195** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00004196** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00004197**
4198** SQLITE_OK is returned on success. Any other return value indicates
4199** an error. *ppPage and *pPgno are undefined in the event of an error.
danielk19773b8a05f2007-03-19 17:44:26 +00004200** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00004201**
drh199e3cf2002-07-18 11:01:47 +00004202** If the "nearby" parameter is not 0, then a (feeble) effort is made to
4203** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00004204** attempt to keep related pages close to each other in the database file,
4205** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00004206**
4207** If the "exact" parameter is not 0, and the page-number nearby exists
4208** anywhere on the free-list, then it is guarenteed to be returned. This
4209** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00004210*/
drh4f0c5872007-03-26 22:05:01 +00004211static int allocateBtreePage(
danielk1977aef0bf62005-12-30 16:28:01 +00004212 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00004213 MemPage **ppPage,
4214 Pgno *pPgno,
4215 Pgno nearby,
4216 u8 exact
4217){
drh3aac2dd2004-04-26 14:10:20 +00004218 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00004219 int rc;
drh3aac2dd2004-04-26 14:10:20 +00004220 int n; /* Number of pages on the freelist */
4221 int k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00004222 MemPage *pTrunk = 0;
4223 MemPage *pPrevTrunk = 0;
drh30e58752002-03-02 20:41:57 +00004224
drh1fee73e2007-08-29 04:00:57 +00004225 assert( sqlite3_mutex_held(pBt->mutex) );
drh3aac2dd2004-04-26 14:10:20 +00004226 pPage1 = pBt->pPage1;
4227 n = get4byte(&pPage1->aData[36]);
4228 if( n>0 ){
drh91025292004-05-03 19:49:32 +00004229 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00004230 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004231 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
4232
4233 /* If the 'exact' parameter was true and a query of the pointer-map
4234 ** shows that the page 'nearby' is somewhere on the free-list, then
4235 ** the entire-list will be searched for that page.
4236 */
4237#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197789d40042008-11-17 14:20:56 +00004238 if( exact && nearby<=pagerPagecount(pBt) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004239 u8 eType;
4240 assert( nearby>0 );
4241 assert( pBt->autoVacuum );
4242 rc = ptrmapGet(pBt, nearby, &eType, 0);
4243 if( rc ) return rc;
4244 if( eType==PTRMAP_FREEPAGE ){
4245 searchList = 1;
4246 }
4247 *pPgno = nearby;
4248 }
4249#endif
4250
4251 /* Decrement the free-list count by 1. Set iTrunk to the index of the
4252 ** first free-list trunk page. iPrevTrunk is initially 1.
4253 */
danielk19773b8a05f2007-03-19 17:44:26 +00004254 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00004255 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004256 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004257
4258 /* The code within this loop is run only once if the 'searchList' variable
4259 ** is not true. Otherwise, it runs once for each trunk-page on the
4260 ** free-list until the page 'nearby' is located.
4261 */
4262 do {
4263 pPrevTrunk = pTrunk;
4264 if( pPrevTrunk ){
4265 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00004266 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004267 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00004268 }
drh16a9b832007-05-05 18:39:25 +00004269 rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004270 if( rc ){
drhd3627af2006-12-18 18:34:51 +00004271 pTrunk = 0;
4272 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004273 }
4274
4275 k = get4byte(&pTrunk->aData[4]);
4276 if( k==0 && !searchList ){
4277 /* The trunk has no leaves and the list is not being searched.
4278 ** So extract the trunk page itself and use it as the newly
4279 ** allocated page */
4280 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00004281 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004282 if( rc ){
4283 goto end_allocate_page;
4284 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004285 *pPgno = iTrunk;
4286 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4287 *ppPage = pTrunk;
4288 pTrunk = 0;
4289 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh45b1fac2008-07-04 17:52:42 +00004290 }else if( k>pBt->usableSize/4 - 2 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004291 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00004292 rc = SQLITE_CORRUPT_BKPT;
4293 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004294#ifndef SQLITE_OMIT_AUTOVACUUM
4295 }else if( searchList && nearby==iTrunk ){
4296 /* The list is being searched and this trunk page is the page
4297 ** to allocate, regardless of whether it has leaves.
4298 */
4299 assert( *pPgno==iTrunk );
4300 *ppPage = pTrunk;
4301 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00004302 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004303 if( rc ){
4304 goto end_allocate_page;
4305 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004306 if( k==0 ){
4307 if( !pPrevTrunk ){
4308 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4309 }else{
4310 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
4311 }
4312 }else{
4313 /* The trunk page is required by the caller but it contains
4314 ** pointers to free-list leaves. The first leaf becomes a trunk
4315 ** page in this case.
4316 */
4317 MemPage *pNewTrunk;
4318 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh16a9b832007-05-05 18:39:25 +00004319 rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004320 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00004321 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004322 }
danielk19773b8a05f2007-03-19 17:44:26 +00004323 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004324 if( rc!=SQLITE_OK ){
4325 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00004326 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004327 }
4328 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
4329 put4byte(&pNewTrunk->aData[4], k-1);
4330 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00004331 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004332 if( !pPrevTrunk ){
drhc5053fb2008-11-27 02:22:10 +00004333 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
danielk1977cb1a7eb2004-11-05 12:27:02 +00004334 put4byte(&pPage1->aData[32], iNewTrunk);
4335 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00004336 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004337 if( rc ){
4338 goto end_allocate_page;
4339 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004340 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
4341 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004342 }
4343 pTrunk = 0;
4344 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
4345#endif
4346 }else{
4347 /* Extract a leaf from the trunk */
4348 int closest;
4349 Pgno iPage;
4350 unsigned char *aData = pTrunk->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00004351 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004352 if( rc ){
4353 goto end_allocate_page;
4354 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004355 if( nearby>0 ){
4356 int i, dist;
4357 closest = 0;
4358 dist = get4byte(&aData[8]) - nearby;
4359 if( dist<0 ) dist = -dist;
4360 for(i=1; i<k; i++){
4361 int d2 = get4byte(&aData[8+i*4]) - nearby;
4362 if( d2<0 ) d2 = -d2;
4363 if( d2<dist ){
4364 closest = i;
4365 dist = d2;
4366 }
4367 }
4368 }else{
4369 closest = 0;
4370 }
4371
4372 iPage = get4byte(&aData[8+closest*4]);
4373 if( !searchList || iPage==nearby ){
danielk1977bea2a942009-01-20 17:06:27 +00004374 int noContent;
danielk197789d40042008-11-17 14:20:56 +00004375 Pgno nPage;
shane1f9e6aa2008-06-09 19:27:11 +00004376 *pPgno = iPage;
danielk197789d40042008-11-17 14:20:56 +00004377 nPage = pagerPagecount(pBt);
danielk1977ad0132d2008-06-07 08:58:22 +00004378 if( *pPgno>nPage ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004379 /* Free page off the end of the file */
danielk197743e377a2008-05-05 12:09:32 +00004380 rc = SQLITE_CORRUPT_BKPT;
4381 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004382 }
4383 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
4384 ": %d more free pages\n",
4385 *pPgno, closest+1, k, pTrunk->pgno, n-1));
4386 if( closest<k-1 ){
4387 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
4388 }
4389 put4byte(&aData[4], k-1);
drhc5053fb2008-11-27 02:22:10 +00004390 assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
danielk1977bea2a942009-01-20 17:06:27 +00004391 noContent = !btreeGetHasContent(pBt, *pPgno);
4392 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, noContent);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004393 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00004394 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004395 if( rc!=SQLITE_OK ){
4396 releasePage(*ppPage);
4397 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004398 }
4399 searchList = 0;
4400 }
drhee696e22004-08-30 16:52:17 +00004401 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004402 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00004403 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004404 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00004405 }else{
drh3aac2dd2004-04-26 14:10:20 +00004406 /* There are no pages on the freelist, so create a new page at the
4407 ** end of the file */
danielk197789d40042008-11-17 14:20:56 +00004408 int nPage = pagerPagecount(pBt);
danielk1977ad0132d2008-06-07 08:58:22 +00004409 *pPgno = nPage + 1;
danielk1977afcdd022004-10-31 16:25:42 +00004410
danielk1977bea2a942009-01-20 17:06:27 +00004411 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
4412 (*pPgno)++;
4413 }
4414
danielk1977afcdd022004-10-31 16:25:42 +00004415#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977266664d2006-02-10 08:24:21 +00004416 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00004417 /* If *pPgno refers to a pointer-map page, allocate two new pages
4418 ** at the end of the file instead of one. The first allocated page
4419 ** becomes a new pointer-map page, the second is used by the caller.
4420 */
4421 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00004422 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977afcdd022004-10-31 16:25:42 +00004423 (*pPgno)++;
drh72190432008-01-31 14:54:43 +00004424 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
danielk1977afcdd022004-10-31 16:25:42 +00004425 }
4426#endif
4427
danielk1977599fcba2004-11-08 07:13:13 +00004428 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh16a9b832007-05-05 18:39:25 +00004429 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
drh3b7511c2001-05-26 13:15:44 +00004430 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00004431 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004432 if( rc!=SQLITE_OK ){
4433 releasePage(*ppPage);
4434 }
drh3a4c1412004-05-09 20:40:11 +00004435 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00004436 }
danielk1977599fcba2004-11-08 07:13:13 +00004437
4438 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00004439
4440end_allocate_page:
4441 releasePage(pTrunk);
4442 releasePage(pPrevTrunk);
danielk1977b247c212008-11-21 09:09:01 +00004443 if( rc==SQLITE_OK ){
4444 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
4445 releasePage(*ppPage);
4446 return SQLITE_CORRUPT_BKPT;
4447 }
4448 (*ppPage)->isInit = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00004449 }
drh3b7511c2001-05-26 13:15:44 +00004450 return rc;
4451}
4452
4453/*
danielk1977bea2a942009-01-20 17:06:27 +00004454** This function is used to add page iPage to the database file free-list.
4455** It is assumed that the page is not already a part of the free-list.
drh5e2f8b92001-05-28 00:41:15 +00004456**
danielk1977bea2a942009-01-20 17:06:27 +00004457** The value passed as the second argument to this function is optional.
4458** If the caller happens to have a pointer to the MemPage object
4459** corresponding to page iPage handy, it may pass it as the second value.
4460** Otherwise, it may pass NULL.
4461**
4462** If a pointer to a MemPage object is passed as the second argument,
4463** its reference count is not altered by this function.
drh3b7511c2001-05-26 13:15:44 +00004464*/
danielk1977bea2a942009-01-20 17:06:27 +00004465static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
4466 MemPage *pTrunk = 0; /* Free-list trunk page */
4467 Pgno iTrunk = 0; /* Page number of free-list trunk page */
4468 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
4469 MemPage *pPage; /* Page being freed. May be NULL. */
4470 int rc; /* Return Code */
4471 int nFree; /* Initial number of pages on free-list */
drh8b2f49b2001-06-08 00:21:52 +00004472
danielk1977bea2a942009-01-20 17:06:27 +00004473 assert( sqlite3_mutex_held(pBt->mutex) );
4474 assert( iPage>1 );
4475 assert( !pMemPage || pMemPage->pgno==iPage );
4476
4477 if( pMemPage ){
4478 pPage = pMemPage;
4479 sqlite3PagerRef(pPage->pDbPage);
4480 }else{
4481 pPage = btreePageLookup(pBt, iPage);
4482 }
drh3aac2dd2004-04-26 14:10:20 +00004483
drha34b6762004-05-07 13:30:42 +00004484 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00004485 rc = sqlite3PagerWrite(pPage1->pDbPage);
danielk1977bea2a942009-01-20 17:06:27 +00004486 if( rc ) goto freepage_out;
4487 nFree = get4byte(&pPage1->aData[36]);
4488 put4byte(&pPage1->aData[36], nFree+1);
drh3aac2dd2004-04-26 14:10:20 +00004489
drhfcce93f2006-02-22 03:08:32 +00004490#ifdef SQLITE_SECURE_DELETE
4491 /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
4492 ** always fully overwrite deleted information with zeros.
4493 */
danielk1977bea2a942009-01-20 17:06:27 +00004494 if( (!pPage && (rc = sqlite3BtreeGetPage(pBt, iPage, &pPage, 0)))
4495 || (rc = sqlite3PagerWrite(pPage->pDbPage))
4496 ){
4497 goto freepage_out;
4498 }
drhfcce93f2006-02-22 03:08:32 +00004499 memset(pPage->aData, 0, pPage->pBt->pageSize);
4500#endif
4501
danielk1977687566d2004-11-02 12:56:41 +00004502 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00004503 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00004504 */
danielk197785d90ca2008-07-19 14:25:15 +00004505 if( ISAUTOVACUUM ){
danielk1977bea2a942009-01-20 17:06:27 +00004506 rc = ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0);
4507 if( rc ) goto freepage_out;
danielk1977687566d2004-11-02 12:56:41 +00004508 }
danielk1977687566d2004-11-02 12:56:41 +00004509
danielk1977bea2a942009-01-20 17:06:27 +00004510 /* Now manipulate the actual database free-list structure. There are two
4511 ** possibilities. If the free-list is currently empty, or if the first
4512 ** trunk page in the free-list is full, then this page will become a
4513 ** new free-list trunk page. Otherwise, it will become a leaf of the
4514 ** first trunk page in the current free-list. This block tests if it
4515 ** is possible to add the page as a new free-list leaf.
4516 */
4517 if( nFree!=0 ){
4518 int nLeaf; /* Initial number of leaf cells on trunk page */
4519
4520 iTrunk = get4byte(&pPage1->aData[32]);
4521 rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
4522 if( rc!=SQLITE_OK ){
4523 goto freepage_out;
4524 }
4525
4526 nLeaf = get4byte(&pTrunk->aData[4]);
4527 if( nLeaf<0 ){
4528 rc = SQLITE_CORRUPT_BKPT;
4529 goto freepage_out;
4530 }
4531 if( nLeaf<pBt->usableSize/4 - 8 ){
4532 /* In this case there is room on the trunk page to insert the page
4533 ** being freed as a new leaf.
drh45b1fac2008-07-04 17:52:42 +00004534 **
4535 ** Note that the trunk page is not really full until it contains
4536 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
4537 ** coded. But due to a coding error in versions of SQLite prior to
4538 ** 3.6.0, databases with freelist trunk pages holding more than
4539 ** usableSize/4 - 8 entries will be reported as corrupt. In order
4540 ** to maintain backwards compatibility with older versions of SQLite,
4541 ** we will contain to restrict the number of entries to usableSize/4 - 8
4542 ** for now. At some point in the future (once everyone has upgraded
4543 ** to 3.6.0 or later) we should consider fixing the conditional above
4544 ** to read "usableSize/4-2" instead of "usableSize/4-8".
4545 */
danielk19773b8a05f2007-03-19 17:44:26 +00004546 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00004547 if( rc==SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00004548 put4byte(&pTrunk->aData[4], nLeaf+1);
4549 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
drhfcce93f2006-02-22 03:08:32 +00004550#ifndef SQLITE_SECURE_DELETE
danielk1977bea2a942009-01-20 17:06:27 +00004551 if( pPage ){
4552 sqlite3PagerDontWrite(pPage->pDbPage);
4553 }
drhfcce93f2006-02-22 03:08:32 +00004554#endif
danielk1977bea2a942009-01-20 17:06:27 +00004555 rc = btreeSetHasContent(pBt, iPage);
drhf5345442007-04-09 12:45:02 +00004556 }
drh3a4c1412004-05-09 20:40:11 +00004557 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
danielk1977bea2a942009-01-20 17:06:27 +00004558 goto freepage_out;
drh3aac2dd2004-04-26 14:10:20 +00004559 }
drh3b7511c2001-05-26 13:15:44 +00004560 }
danielk1977bea2a942009-01-20 17:06:27 +00004561
4562 /* If control flows to this point, then it was not possible to add the
4563 ** the page being freed as a leaf page of the first trunk in the free-list.
4564 ** Possibly because the free-list is empty, or possibly because the
4565 ** first trunk in the free-list is full. Either way, the page being freed
4566 ** will become the new first trunk page in the free-list.
4567 */
shane63207ab2009-02-04 01:49:30 +00004568 if( ((!pPage) && (0 != (rc = sqlite3BtreeGetPage(pBt, iPage, &pPage, 0))))
4569 || (0 != (rc = sqlite3PagerWrite(pPage->pDbPage)))
danielk1977bea2a942009-01-20 17:06:27 +00004570 ){
4571 goto freepage_out;
4572 }
4573 put4byte(pPage->aData, iTrunk);
4574 put4byte(&pPage->aData[4], 0);
4575 put4byte(&pPage1->aData[32], iPage);
4576 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
4577
4578freepage_out:
4579 if( pPage ){
4580 pPage->isInit = 0;
4581 }
4582 releasePage(pPage);
4583 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00004584 return rc;
4585}
danielk1977bea2a942009-01-20 17:06:27 +00004586static int freePage(MemPage *pPage){
4587 return freePage2(pPage->pBt, pPage, pPage->pgno);
4588}
drh3b7511c2001-05-26 13:15:44 +00004589
4590/*
drh3aac2dd2004-04-26 14:10:20 +00004591** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00004592*/
drh3aac2dd2004-04-26 14:10:20 +00004593static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00004594 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00004595 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00004596 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00004597 int rc;
drh94440812007-03-06 11:42:19 +00004598 int nOvfl;
shane63207ab2009-02-04 01:49:30 +00004599 u16 ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00004600
drh1fee73e2007-08-29 04:00:57 +00004601 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh16a9b832007-05-05 18:39:25 +00004602 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004603 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00004604 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00004605 }
drh6f11bef2004-05-13 01:12:56 +00004606 ovflPgno = get4byte(&pCell[info.iOverflow]);
shane63207ab2009-02-04 01:49:30 +00004607 assert( pBt->usableSize > 4 );
drh94440812007-03-06 11:42:19 +00004608 ovflPageSize = pBt->usableSize - 4;
drh72365832007-03-06 15:53:44 +00004609 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
4610 assert( ovflPgno==0 || nOvfl>0 );
4611 while( nOvfl-- ){
shane63207ab2009-02-04 01:49:30 +00004612 Pgno iNext = 0;
danielk1977bea2a942009-01-20 17:06:27 +00004613 MemPage *pOvfl = 0;
danielk197789d40042008-11-17 14:20:56 +00004614 if( ovflPgno==0 || ovflPgno>pagerPagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00004615 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00004616 }
danielk1977bea2a942009-01-20 17:06:27 +00004617 if( nOvfl ){
4618 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
4619 if( rc ) return rc;
4620 }
4621 rc = freePage2(pBt, pOvfl, ovflPgno);
4622 if( pOvfl ){
4623 sqlite3PagerUnref(pOvfl->pDbPage);
4624 }
drh3b7511c2001-05-26 13:15:44 +00004625 if( rc ) return rc;
danielk1977bea2a942009-01-20 17:06:27 +00004626 ovflPgno = iNext;
drh3b7511c2001-05-26 13:15:44 +00004627 }
drh5e2f8b92001-05-28 00:41:15 +00004628 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00004629}
4630
4631/*
drh91025292004-05-03 19:49:32 +00004632** Create the byte sequence used to represent a cell on page pPage
4633** and write that byte sequence into pCell[]. Overflow pages are
4634** allocated and filled in as necessary. The calling procedure
4635** is responsible for making sure sufficient space has been allocated
4636** for pCell[].
4637**
4638** Note that pCell does not necessary need to point to the pPage->aData
4639** area. pCell might point to some temporary storage. The cell will
4640** be constructed in this temporary area then copied into pPage->aData
4641** later.
drh3b7511c2001-05-26 13:15:44 +00004642*/
4643static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00004644 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00004645 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00004646 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00004647 const void *pData,int nData, /* The data */
drhb026e052007-05-02 01:34:31 +00004648 int nZero, /* Extra zero bytes to append to pData */
drh4b70f112004-05-02 21:12:19 +00004649 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00004650){
drh3b7511c2001-05-26 13:15:44 +00004651 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00004652 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00004653 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00004654 int spaceLeft;
4655 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00004656 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00004657 unsigned char *pPrior;
4658 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00004659 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00004660 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00004661 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00004662 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00004663
drh1fee73e2007-08-29 04:00:57 +00004664 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00004665
drhc5053fb2008-11-27 02:22:10 +00004666 /* pPage is not necessarily writeable since pCell might be auxiliary
4667 ** buffer space that is separate from the pPage buffer area */
4668 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
4669 || sqlite3PagerIswriteable(pPage->pDbPage) );
4670
drh91025292004-05-03 19:49:32 +00004671 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00004672 nHeader = 0;
drh91025292004-05-03 19:49:32 +00004673 if( !pPage->leaf ){
4674 nHeader += 4;
4675 }
drh8b18dd42004-05-12 19:18:15 +00004676 if( pPage->hasData ){
drhb026e052007-05-02 01:34:31 +00004677 nHeader += putVarint(&pCell[nHeader], nData+nZero);
drh6f11bef2004-05-13 01:12:56 +00004678 }else{
drhb026e052007-05-02 01:34:31 +00004679 nData = nZero = 0;
drh91025292004-05-03 19:49:32 +00004680 }
drh6f11bef2004-05-13 01:12:56 +00004681 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh16a9b832007-05-05 18:39:25 +00004682 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004683 assert( info.nHeader==nHeader );
4684 assert( info.nKey==nKey );
danielk197789d40042008-11-17 14:20:56 +00004685 assert( info.nData==(u32)(nData+nZero) );
drh6f11bef2004-05-13 01:12:56 +00004686
4687 /* Fill in the payload */
drhb026e052007-05-02 01:34:31 +00004688 nPayload = nData + nZero;
drh3aac2dd2004-04-26 14:10:20 +00004689 if( pPage->intKey ){
4690 pSrc = pData;
4691 nSrc = nData;
drh91025292004-05-03 19:49:32 +00004692 nData = 0;
drhf49661a2008-12-10 16:45:50 +00004693 }else{
drh20abac22009-01-28 20:21:17 +00004694 if( nKey>0x7fffffff || pKey==0 ){
4695 return SQLITE_CORRUPT;
4696 }
drhf49661a2008-12-10 16:45:50 +00004697 nPayload += (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00004698 pSrc = pKey;
drhf49661a2008-12-10 16:45:50 +00004699 nSrc = (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00004700 }
drh6f11bef2004-05-13 01:12:56 +00004701 *pnSize = info.nSize;
4702 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00004703 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00004704 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00004705
drh3b7511c2001-05-26 13:15:44 +00004706 while( nPayload>0 ){
4707 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00004708#ifndef SQLITE_OMIT_AUTOVACUUM
4709 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00004710 if( pBt->autoVacuum ){
4711 do{
4712 pgnoOvfl++;
4713 } while(
4714 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
4715 );
danielk1977b39f70b2007-05-17 18:28:11 +00004716 }
danielk1977afcdd022004-10-31 16:25:42 +00004717#endif
drhf49661a2008-12-10 16:45:50 +00004718 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00004719#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00004720 /* If the database supports auto-vacuum, and the second or subsequent
4721 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00004722 ** for that page now.
4723 **
4724 ** If this is the first overflow page, then write a partial entry
4725 ** to the pointer-map. If we write nothing to this pointer-map slot,
4726 ** then the optimistic overflow chain processing in clearCell()
4727 ** may misinterpret the uninitialised values and delete the
4728 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00004729 */
danielk19774ef24492007-05-23 09:52:41 +00004730 if( pBt->autoVacuum && rc==SQLITE_OK ){
4731 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
4732 rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
danielk197789a4be82007-05-23 13:34:32 +00004733 if( rc ){
4734 releasePage(pOvfl);
4735 }
danielk1977afcdd022004-10-31 16:25:42 +00004736 }
4737#endif
drh3b7511c2001-05-26 13:15:44 +00004738 if( rc ){
drh9b171272004-05-08 02:03:22 +00004739 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00004740 return rc;
4741 }
drhc5053fb2008-11-27 02:22:10 +00004742
4743 /* If pToRelease is not zero than pPrior points into the data area
4744 ** of pToRelease. Make sure pToRelease is still writeable. */
4745 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
4746
4747 /* If pPrior is part of the data area of pPage, then make sure pPage
4748 ** is still writeable */
4749 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
4750 || sqlite3PagerIswriteable(pPage->pDbPage) );
4751
drh3aac2dd2004-04-26 14:10:20 +00004752 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00004753 releasePage(pToRelease);
4754 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00004755 pPrior = pOvfl->aData;
4756 put4byte(pPrior, 0);
4757 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00004758 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00004759 }
4760 n = nPayload;
4761 if( n>spaceLeft ) n = spaceLeft;
drhc5053fb2008-11-27 02:22:10 +00004762
4763 /* If pToRelease is not zero than pPayload points into the data area
4764 ** of pToRelease. Make sure pToRelease is still writeable. */
4765 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
4766
4767 /* If pPayload is part of the data area of pPage, then make sure pPage
4768 ** is still writeable */
4769 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
4770 || sqlite3PagerIswriteable(pPage->pDbPage) );
4771
drhb026e052007-05-02 01:34:31 +00004772 if( nSrc>0 ){
4773 if( n>nSrc ) n = nSrc;
4774 assert( pSrc );
4775 memcpy(pPayload, pSrc, n);
4776 }else{
4777 memset(pPayload, 0, n);
4778 }
drh3b7511c2001-05-26 13:15:44 +00004779 nPayload -= n;
drhde647132004-05-07 17:57:49 +00004780 pPayload += n;
drh9b171272004-05-08 02:03:22 +00004781 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00004782 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00004783 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00004784 if( nSrc==0 ){
4785 nSrc = nData;
4786 pSrc = pData;
4787 }
drhdd793422001-06-28 01:54:48 +00004788 }
drh9b171272004-05-08 02:03:22 +00004789 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00004790 return SQLITE_OK;
4791}
4792
drh14acc042001-06-10 19:56:58 +00004793/*
4794** Remove the i-th cell from pPage. This routine effects pPage only.
4795** The cell content is not freed or deallocated. It is assumed that
4796** the cell content has been copied someplace else. This routine just
4797** removes the reference to the cell from pPage.
4798**
4799** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00004800*/
shane0af3f892008-11-12 04:55:34 +00004801static int dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00004802 int i; /* Loop counter */
4803 int pc; /* Offset to cell content of cell being deleted */
4804 u8 *data; /* pPage->aData */
4805 u8 *ptr; /* Used to move bytes around within data[] */
shanedcc50b72008-11-13 18:29:50 +00004806 int rc; /* The return code */
drh43605152004-05-29 21:46:49 +00004807
drh8c42ca92001-06-22 19:15:00 +00004808 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00004809 assert( sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00004810 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00004811 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00004812 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00004813 ptr = &data[pPage->cellOffset + 2*idx];
shane0af3f892008-11-12 04:55:34 +00004814 pc = get2byte(ptr);
drhc5053fb2008-11-27 02:22:10 +00004815 if( (pc<pPage->hdrOffset+6+(pPage->leaf?0:4))
4816 || (pc+sz>pPage->pBt->usableSize) ){
shane0af3f892008-11-12 04:55:34 +00004817 return SQLITE_CORRUPT_BKPT;
4818 }
shanedcc50b72008-11-13 18:29:50 +00004819 rc = freeSpace(pPage, pc, sz);
4820 if( rc!=SQLITE_OK ){
4821 return rc;
4822 }
drh43605152004-05-29 21:46:49 +00004823 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
4824 ptr[0] = ptr[2];
4825 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00004826 }
4827 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00004828 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
4829 pPage->nFree += 2;
shane0af3f892008-11-12 04:55:34 +00004830 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004831}
4832
4833/*
4834** Insert a new cell on pPage at cell index "i". pCell points to the
4835** content of the cell.
4836**
4837** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00004838** will not fit, then make a copy of the cell content into pTemp if
4839** pTemp is not null. Regardless of pTemp, allocate a new entry
4840** in pPage->aOvfl[] and make it point to the cell content (either
4841** in pTemp or the original pCell) and also record its index.
4842** Allocating a new entry in pPage->aCell[] implies that
4843** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00004844**
4845** If nSkip is non-zero, then do not copy the first nSkip bytes of the
4846** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00004847** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00004848** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00004849*/
danielk1977e80463b2004-11-03 03:01:16 +00004850static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00004851 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00004852 int i, /* New cell becomes the i-th cell of the page */
4853 u8 *pCell, /* Content of the new cell */
4854 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00004855 u8 *pTemp, /* Temp storage space for pCell, if needed */
4856 u8 nSkip /* Do not write the first nSkip bytes of the cell */
drh24cd67e2004-05-10 16:18:47 +00004857){
drh43605152004-05-29 21:46:49 +00004858 int idx; /* Where to write new cell content in data[] */
4859 int j; /* Loop counter */
4860 int top; /* First byte of content for any cell in data[] */
4861 int end; /* First byte past the last cell pointer in data[] */
4862 int ins; /* Index in data[] where new cell pointer is inserted */
4863 int hdr; /* Offset into data[] of the page header */
4864 int cellOffset; /* Address of first cell pointer in data[] */
4865 u8 *data; /* The content of the whole page */
4866 u8 *ptr; /* Used for moving information around in data[] */
4867
4868 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
drhf49661a2008-12-10 16:45:50 +00004869 assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
4870 assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
drh43605152004-05-29 21:46:49 +00004871 assert( sz==cellSizePtr(pPage, pCell) );
drh1fee73e2007-08-29 04:00:57 +00004872 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +00004873 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00004874 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00004875 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004876 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00004877 }
drh43605152004-05-29 21:46:49 +00004878 j = pPage->nOverflow++;
danielk197789d40042008-11-17 14:20:56 +00004879 assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
drh43605152004-05-29 21:46:49 +00004880 pPage->aOvfl[j].pCell = pCell;
drhf49661a2008-12-10 16:45:50 +00004881 pPage->aOvfl[j].idx = (u16)i;
drh43605152004-05-29 21:46:49 +00004882 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00004883 }else{
danielk19776e465eb2007-08-21 13:11:00 +00004884 int rc = sqlite3PagerWrite(pPage->pDbPage);
4885 if( rc!=SQLITE_OK ){
4886 return rc;
4887 }
4888 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00004889 data = pPage->aData;
4890 hdr = pPage->hdrOffset;
4891 top = get2byte(&data[hdr+5]);
4892 cellOffset = pPage->cellOffset;
4893 end = cellOffset + 2*pPage->nCell + 2;
4894 ins = cellOffset + 2*i;
4895 if( end > top - sz ){
shane0af3f892008-11-12 04:55:34 +00004896 rc = defragmentPage(pPage);
4897 if( rc!=SQLITE_OK ){
4898 return rc;
4899 }
drh43605152004-05-29 21:46:49 +00004900 top = get2byte(&data[hdr+5]);
4901 assert( end + sz <= top );
4902 }
4903 idx = allocateSpace(pPage, sz);
4904 assert( idx>0 );
4905 assert( end <= get2byte(&data[hdr+5]) );
shane0af3f892008-11-12 04:55:34 +00004906 if (idx+sz > pPage->pBt->usableSize) {
shane34ac18d2008-11-11 22:18:20 +00004907 return SQLITE_CORRUPT_BKPT;
shane0af3f892008-11-12 04:55:34 +00004908 }
drh43605152004-05-29 21:46:49 +00004909 pPage->nCell++;
4910 pPage->nFree -= 2;
danielk1977a3ad5e72005-01-07 08:56:44 +00004911 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004912 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
4913 ptr[0] = ptr[-2];
4914 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00004915 }
drh43605152004-05-29 21:46:49 +00004916 put2byte(&data[ins], idx);
4917 put2byte(&data[hdr+3], pPage->nCell);
danielk1977a19df672004-11-03 11:37:07 +00004918#ifndef SQLITE_OMIT_AUTOVACUUM
4919 if( pPage->pBt->autoVacuum ){
4920 /* The cell may contain a pointer to an overflow page. If so, write
4921 ** the entry for the overflow page into the pointer map.
4922 */
4923 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00004924 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh72365832007-03-06 15:53:44 +00004925 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk1977a19df672004-11-03 11:37:07 +00004926 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
4927 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
danielk19776e465eb2007-08-21 13:11:00 +00004928 rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
danielk1977a19df672004-11-03 11:37:07 +00004929 if( rc!=SQLITE_OK ) return rc;
4930 }
4931 }
4932#endif
drh14acc042001-06-10 19:56:58 +00004933 }
danielk1977e80463b2004-11-03 03:01:16 +00004934
danielk1977e80463b2004-11-03 03:01:16 +00004935 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004936}
4937
4938/*
drhfa1a98a2004-05-14 19:08:17 +00004939** Add a list of cells to a page. The page should be initially empty.
4940** The cells are guaranteed to fit on the page.
4941*/
4942static void assemblePage(
4943 MemPage *pPage, /* The page to be assemblied */
4944 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00004945 u8 **apCell, /* Pointers to cell bodies */
drha9121e42008-02-19 14:59:35 +00004946 u16 *aSize /* Sizes of the cells */
drhfa1a98a2004-05-14 19:08:17 +00004947){
4948 int i; /* Loop counter */
4949 int totalSize; /* Total size of all cells */
4950 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00004951 int cellptr; /* Address of next cell pointer */
4952 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00004953 u8 *data; /* Data for the page */
4954
drh43605152004-05-29 21:46:49 +00004955 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00004956 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00004957 assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
drhfa1a98a2004-05-14 19:08:17 +00004958 totalSize = 0;
4959 for(i=0; i<nCell; i++){
4960 totalSize += aSize[i];
4961 }
drh43605152004-05-29 21:46:49 +00004962 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00004963 assert( pPage->nCell==0 );
drhc5053fb2008-11-27 02:22:10 +00004964 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00004965 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00004966 data = pPage->aData;
4967 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00004968 put2byte(&data[hdr+3], nCell);
drh09d0deb2005-08-02 17:13:09 +00004969 if( nCell ){
4970 cellbody = allocateSpace(pPage, totalSize);
4971 assert( cellbody>0 );
4972 assert( pPage->nFree >= 2*nCell );
4973 pPage->nFree -= 2*nCell;
4974 for(i=0; i<nCell; i++){
4975 put2byte(&data[cellptr], cellbody);
4976 memcpy(&data[cellbody], apCell[i], aSize[i]);
4977 cellptr += 2;
4978 cellbody += aSize[i];
4979 }
4980 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00004981 }
drhf49661a2008-12-10 16:45:50 +00004982 pPage->nCell = (u16)nCell;
drhfa1a98a2004-05-14 19:08:17 +00004983}
4984
drh14acc042001-06-10 19:56:58 +00004985/*
drhc3b70572003-01-04 19:44:07 +00004986** The following parameters determine how many adjacent pages get involved
4987** in a balancing operation. NN is the number of neighbors on either side
4988** of the page that participate in the balancing operation. NB is the
4989** total number of pages that participate, including the target page and
4990** NN neighbors on either side.
4991**
4992** The minimum value of NN is 1 (of course). Increasing NN above 1
4993** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
4994** in exchange for a larger degradation in INSERT and UPDATE performance.
4995** The value of NN appears to give the best results overall.
4996*/
4997#define NN 1 /* Number of neighbors on either side of pPage */
4998#define NB (NN*2+1) /* Total pages involved in the balance */
4999
drh43605152004-05-29 21:46:49 +00005000/* Forward reference */
danielk197771d5d2c2008-09-29 11:49:47 +00005001static int balance(BtCursor*, int);
danielk1977ac245ec2005-01-14 13:50:11 +00005002
drh615ae552005-01-16 23:21:00 +00005003#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00005004/*
5005** This version of balance() handles the common special case where
5006** a new entry is being inserted on the extreme right-end of the
5007** tree, in other words, when the new entry will become the largest
5008** entry in the tree.
5009**
5010** Instead of trying balance the 3 right-most leaf pages, just add
5011** a new page to the right-hand side and put the one new entry in
5012** that page. This leaves the right side of the tree somewhat
5013** unbalanced. But odds are that we will be inserting new entries
5014** at the end soon afterwards so the nearly empty page will quickly
5015** fill up. On average.
5016**
5017** pPage is the leaf page which is the right-most page in the tree.
5018** pParent is its parent. pPage must have a single overflow entry
5019** which is also the right-most entry on the page.
5020*/
danielk197771d5d2c2008-09-29 11:49:47 +00005021static int balance_quick(BtCursor *pCur){
danielk1977ac245ec2005-01-14 13:50:11 +00005022 int rc;
danielk1977eaa06f62008-09-18 17:34:44 +00005023 MemPage *pNew = 0;
danielk1977ac245ec2005-01-14 13:50:11 +00005024 Pgno pgnoNew;
5025 u8 *pCell;
drha9121e42008-02-19 14:59:35 +00005026 u16 szCell;
danielk1977ac245ec2005-01-14 13:50:11 +00005027 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00005028 MemPage *pPage = pCur->apPage[pCur->iPage];
5029 MemPage *pParent = pCur->apPage[pCur->iPage-1];
danielk1977aef0bf62005-12-30 16:28:01 +00005030 BtShared *pBt = pPage->pBt;
danielk197779a40da2005-01-16 08:00:01 +00005031 int parentIdx = pParent->nCell; /* pParent new divider cell index */
5032 int parentSize; /* Size of new divider cell */
5033 u8 parentCell[64]; /* Space for the new divider cell */
danielk1977ac245ec2005-01-14 13:50:11 +00005034
drh1fee73e2007-08-29 04:00:57 +00005035 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00005036
danielk1977ac245ec2005-01-14 13:50:11 +00005037 /* Allocate a new page. Insert the overflow cell from pPage
5038 ** into it. Then remove the overflow cell from pPage.
5039 */
drh4f0c5872007-03-26 22:05:01 +00005040 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk1977eaa06f62008-09-18 17:34:44 +00005041 if( rc==SQLITE_OK ){
5042 pCell = pPage->aOvfl[0].pCell;
5043 szCell = cellSizePtr(pPage, pCell);
drhc5053fb2008-11-27 02:22:10 +00005044 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
danielk1977eaa06f62008-09-18 17:34:44 +00005045 zeroPage(pNew, pPage->aData[0]);
5046 assemblePage(pNew, 1, &pCell, &szCell);
5047 pPage->nOverflow = 0;
5048
danielk1977eaa06f62008-09-18 17:34:44 +00005049 /* pPage is currently the right-child of pParent. Change this
5050 ** so that the right-child is the new page allocated above and
5051 ** pPage is the next-to-right child.
5052 **
5053 ** Ignore the return value of the call to fillInCell(). fillInCell()
5054 ** may only return other than SQLITE_OK if it is required to allocate
5055 ** one or more overflow pages. Since an internal table B-Tree cell
5056 ** may never spill over onto an overflow page (it is a maximum of
5057 ** 13 bytes in size), it is not neccessary to check the return code.
5058 **
5059 ** Similarly, the insertCell() function cannot fail if the page
5060 ** being inserted into is already writable and the cell does not
5061 ** contain an overflow pointer. So ignore this return code too.
5062 */
5063 assert( pPage->nCell>0 );
5064 pCell = findCell(pPage, pPage->nCell-1);
5065 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
5066 fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
5067 assert( parentSize<64 );
5068 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
5069 insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
5070 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
5071 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
5072
5073 /* If this is an auto-vacuum database, update the pointer map
5074 ** with entries for the new page, and any pointer from the
5075 ** cell on the page to an overflow page.
5076 */
5077 if( ISAUTOVACUUM ){
5078 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
5079 if( rc==SQLITE_OK ){
5080 rc = ptrmapPutOvfl(pNew, 0);
5081 }
danielk1977ac11ee62005-01-15 12:45:51 +00005082 }
danielk1977e08a3c42008-09-18 18:17:03 +00005083
5084 /* Release the reference to the new page. */
5085 releasePage(pNew);
danielk1977ac11ee62005-01-15 12:45:51 +00005086 }
5087
danielk1977eaa06f62008-09-18 17:34:44 +00005088 /* At this point the pPage->nFree variable is not set correctly with
5089 ** respect to the content of the page (because it was set to 0 by
5090 ** insertCell). So call sqlite3BtreeInitPage() to make sure it is
5091 ** correct.
5092 **
5093 ** This has to be done even if an error will be returned. Normally, if
5094 ** an error occurs during tree balancing, the contents of MemPage are
5095 ** not important, as they will be recalculated when the page is rolled
5096 ** back. But here, in balance_quick(), it is possible that pPage has
5097 ** not yet been marked dirty or written into the journal file. Therefore
5098 ** it will not be rolled back and so it is important to make sure that
5099 ** the page data and contents of MemPage are consistent.
5100 */
5101 pPage->isInit = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005102 sqlite3BtreeInitPage(pPage);
danielk1977a4124bd2008-12-23 10:37:47 +00005103 assert( pPage->nOverflow==0 );
danielk1977eaa06f62008-09-18 17:34:44 +00005104
danielk1977e08a3c42008-09-18 18:17:03 +00005105 /* If everything else succeeded, balance the parent page, in
5106 ** case the divider cell inserted caused it to become overfull.
danielk197779a40da2005-01-16 08:00:01 +00005107 */
danielk1977eaa06f62008-09-18 17:34:44 +00005108 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00005109 releasePage(pPage);
5110 pCur->iPage--;
5111 rc = balance(pCur, 0);
danielk1977eaa06f62008-09-18 17:34:44 +00005112 }
5113 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00005114}
drh615ae552005-01-16 23:21:00 +00005115#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00005116
drhc3b70572003-01-04 19:44:07 +00005117/*
drhab01f612004-05-22 02:55:23 +00005118** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00005119** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00005120** Usually NN siblings on either side of pPage is used in the balancing,
5121** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00005122** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00005123** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00005124** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00005125**
drh0c6cc4e2004-06-15 02:13:26 +00005126** The number of siblings of pPage might be increased or decreased by one or
5127** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00005128** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00005129** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00005130** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00005131** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00005132**
drh8b2f49b2001-06-08 00:21:52 +00005133** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00005134** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00005135** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00005136** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00005137**
drh8c42ca92001-06-22 19:15:00 +00005138** In the course of balancing the siblings of pPage, the parent of pPage
5139** might become overfull or underfull. If that happens, then this routine
5140** is called recursively on the parent.
5141**
drh5e00f6c2001-09-13 13:46:56 +00005142** If this routine fails for any reason, it might leave the database
5143** in a corrupted state. So if this routine fails, the database should
5144** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00005145*/
danielk197771d5d2c2008-09-29 11:49:47 +00005146static int balance_nonroot(BtCursor *pCur){
5147 MemPage *pPage; /* The over or underfull page to balance */
drh8b2f49b2001-06-08 00:21:52 +00005148 MemPage *pParent; /* The parent of pPage */
drh16a9b832007-05-05 18:39:25 +00005149 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00005150 int nCell = 0; /* Number of cells in apCell[] */
5151 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
danielk1977a4124bd2008-12-23 10:37:47 +00005152 int nOld = 0; /* Number of pages in apOld[] */
5153 int nNew = 0; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00005154 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00005155 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00005156 int idx; /* Index of pPage in pParent->aCell[] */
5157 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00005158 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00005159 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00005160 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00005161 int usableSpace; /* Bytes in pPage beyond the header */
5162 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00005163 int subtotal; /* Subtotal of bytes in cells on one page */
drhe5ae5732008-06-15 02:51:47 +00005164 int iSpace1 = 0; /* First unused byte of aSpace1[] */
5165 int iSpace2 = 0; /* First unused byte of aSpace2[] */
drhfacf0302008-06-17 15:12:00 +00005166 int szScratch; /* Size of scratch memory requested */
drhc3b70572003-01-04 19:44:07 +00005167 MemPage *apOld[NB]; /* pPage and up to two siblings */
5168 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00005169 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00005170 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
5171 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drh4b70f112004-05-02 21:12:19 +00005172 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00005173 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
5174 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00005175 u8 **apCell = 0; /* All cells begin balanced */
drha9121e42008-02-19 14:59:35 +00005176 u16 *szCell; /* Local size of all cells in apCell[] */
drhe5ae5732008-06-15 02:51:47 +00005177 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
5178 u8 *aSpace1; /* Space for copies of dividers cells before balance */
5179 u8 *aSpace2 = 0; /* Space for overflow dividers cells after balance */
danielk1977ac11ee62005-01-15 12:45:51 +00005180 u8 *aFrom = 0;
drh8b2f49b2001-06-08 00:21:52 +00005181
danielk197771d5d2c2008-09-29 11:49:47 +00005182 pPage = pCur->apPage[pCur->iPage];
drh1fee73e2007-08-29 04:00:57 +00005183 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf94a1732008-09-30 17:18:17 +00005184 VVA_ONLY( pCur->pagesShuffled = 1 );
drhd677b3d2007-08-20 22:48:41 +00005185
drh14acc042001-06-10 19:56:58 +00005186 /*
drh43605152004-05-29 21:46:49 +00005187 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00005188 */
danielk197771d5d2c2008-09-29 11:49:47 +00005189 assert( pCur->iPage>0 );
5190 assert( pPage->isInit );
danielk19776e465eb2007-08-21 13:11:00 +00005191 assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 );
drh4b70f112004-05-02 21:12:19 +00005192 pBt = pPage->pBt;
danielk197771d5d2c2008-09-29 11:49:47 +00005193 pParent = pCur->apPage[pCur->iPage-1];
drh43605152004-05-29 21:46:49 +00005194 assert( pParent );
danielk19773b8a05f2007-03-19 17:44:26 +00005195 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
danielk1977a4124bd2008-12-23 10:37:47 +00005196 goto balance_cleanup;
danielk197707cb5602006-01-20 10:55:05 +00005197 }
danielk1977474b7cc2008-07-09 11:49:46 +00005198
drh43605152004-05-29 21:46:49 +00005199 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00005200
drh615ae552005-01-16 23:21:00 +00005201#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00005202 /*
5203 ** A special case: If a new entry has just been inserted into a
5204 ** table (that is, a btree with integer keys and all data at the leaves)
drh09d0deb2005-08-02 17:13:09 +00005205 ** and the new entry is the right-most entry in the tree (it has the
drhf222e712005-01-14 22:55:49 +00005206 ** largest key) then use the special balance_quick() routine for
5207 ** balancing. balance_quick() is much faster and results in a tighter
5208 ** packing of data in the common case.
5209 */
danielk1977ac245ec2005-01-14 13:50:11 +00005210 if( pPage->leaf &&
5211 pPage->intKey &&
danielk1977ac245ec2005-01-14 13:50:11 +00005212 pPage->nOverflow==1 &&
5213 pPage->aOvfl[0].idx==pPage->nCell &&
danielk197771d5d2c2008-09-29 11:49:47 +00005214 pParent->pgno!=1 &&
danielk1977ac245ec2005-01-14 13:50:11 +00005215 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
5216 ){
drh44845222008-07-17 18:39:57 +00005217 assert( pPage->intKey );
danielk1977ac11ee62005-01-15 12:45:51 +00005218 /*
5219 ** TODO: Check the siblings to the left of pPage. It may be that
5220 ** they are not full and no new page is required.
5221 */
danielk197771d5d2c2008-09-29 11:49:47 +00005222 return balance_quick(pCur);
danielk1977ac245ec2005-01-14 13:50:11 +00005223 }
5224#endif
5225
danielk19776e465eb2007-08-21 13:11:00 +00005226 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){
danielk1977a4124bd2008-12-23 10:37:47 +00005227 goto balance_cleanup;
danielk19776e465eb2007-08-21 13:11:00 +00005228 }
5229
drh2e38c322004-09-03 18:38:44 +00005230 /*
drh4b70f112004-05-02 21:12:19 +00005231 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00005232 ** to pPage. The "idx" variable is the index of that cell. If pPage
5233 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00005234 */
danielk1977bf93c562008-09-29 15:53:25 +00005235 idx = pCur->aiIdx[pCur->iPage-1];
5236 assertParentIndex(pParent, idx, pPage->pgno);
drh8b2f49b2001-06-08 00:21:52 +00005237
5238 /*
drh4b70f112004-05-02 21:12:19 +00005239 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00005240 ** the siblings. An attempt is made to find NN siblings on either
5241 ** side of pPage. More siblings are taken from one side, however, if
5242 ** pPage there are fewer than NN siblings on the other side. If pParent
5243 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00005244 */
drhc3b70572003-01-04 19:44:07 +00005245 nxDiv = idx - NN;
5246 if( nxDiv + NB > pParent->nCell ){
5247 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00005248 }
drhc3b70572003-01-04 19:44:07 +00005249 if( nxDiv<0 ){
5250 nxDiv = 0;
5251 }
drh8b2f49b2001-06-08 00:21:52 +00005252 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00005253 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00005254 if( k<pParent->nCell ){
danielk19771cc5ed82007-05-16 17:28:43 +00005255 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00005256 nDiv++;
drha34b6762004-05-07 13:30:42 +00005257 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00005258 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00005259 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00005260 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00005261 }else{
5262 break;
drh8b2f49b2001-06-08 00:21:52 +00005263 }
danielk197771d5d2c2008-09-29 11:49:47 +00005264 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i]);
drh6019e162001-07-02 17:51:45 +00005265 if( rc ) goto balance_cleanup;
danielk197771d5d2c2008-09-29 11:49:47 +00005266 /* apOld[i]->idxParent = k; */
drh91025292004-05-03 19:49:32 +00005267 apCopy[i] = 0;
5268 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00005269 nOld++;
danielk1977634f2982005-03-28 08:44:07 +00005270 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
drh8b2f49b2001-06-08 00:21:52 +00005271 }
5272
drha9121e42008-02-19 14:59:35 +00005273 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00005274 ** alignment */
drha9121e42008-02-19 14:59:35 +00005275 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00005276
drh8b2f49b2001-06-08 00:21:52 +00005277 /*
danielk1977634f2982005-03-28 08:44:07 +00005278 ** Allocate space for memory structures
5279 */
drhfacf0302008-06-17 15:12:00 +00005280 szScratch =
drha9121e42008-02-19 14:59:35 +00005281 nMaxCells*sizeof(u8*) /* apCell */
5282 + nMaxCells*sizeof(u16) /* szCell */
5283 + (ROUND8(sizeof(MemPage))+pBt->pageSize)*NB /* aCopy */
drhe5ae5732008-06-15 02:51:47 +00005284 + pBt->pageSize /* aSpace1 */
drhfacf0302008-06-17 15:12:00 +00005285 + (ISAUTOVACUUM ? nMaxCells : 0); /* aFrom */
5286 apCell = sqlite3ScratchMalloc( szScratch );
danielk1977634f2982005-03-28 08:44:07 +00005287 if( apCell==0 ){
5288 rc = SQLITE_NOMEM;
5289 goto balance_cleanup;
5290 }
drha9121e42008-02-19 14:59:35 +00005291 szCell = (u16*)&apCell[nMaxCells];
danielk1977634f2982005-03-28 08:44:07 +00005292 aCopy[0] = (u8*)&szCell[nMaxCells];
drh66e80082008-12-16 13:46:29 +00005293 assert( ((aCopy[0] - (u8*)0) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00005294 for(i=1; i<NB; i++){
drhc96d8532005-05-03 12:30:33 +00005295 aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
drh66e80082008-12-16 13:46:29 +00005296 assert( ((aCopy[i] - (u8*)0) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00005297 }
drhe5ae5732008-06-15 02:51:47 +00005298 aSpace1 = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
drh66e80082008-12-16 13:46:29 +00005299 assert( ((aSpace1 - (u8*)0) & 7)==0 ); /* 8-byte alignment required */
danielk197785d90ca2008-07-19 14:25:15 +00005300 if( ISAUTOVACUUM ){
drhe5ae5732008-06-15 02:51:47 +00005301 aFrom = &aSpace1[pBt->pageSize];
danielk1977634f2982005-03-28 08:44:07 +00005302 }
drhfacf0302008-06-17 15:12:00 +00005303 aSpace2 = sqlite3PageMalloc(pBt->pageSize);
drhe5ae5732008-06-15 02:51:47 +00005304 if( aSpace2==0 ){
5305 rc = SQLITE_NOMEM;
5306 goto balance_cleanup;
5307 }
danielk1977634f2982005-03-28 08:44:07 +00005308
5309 /*
drh14acc042001-06-10 19:56:58 +00005310 ** Make copies of the content of pPage and its siblings into aOld[].
5311 ** The rest of this function will use data from the copies rather
5312 ** that the original pages since the original pages will be in the
5313 ** process of being overwritten.
5314 */
5315 for(i=0; i<nOld; i++){
drhbf4bca52007-09-06 22:19:14 +00005316 MemPage *p = apCopy[i] = (MemPage*)aCopy[i];
5317 memcpy(p, apOld[i], sizeof(MemPage));
5318 p->aData = (void*)&p[1];
5319 memcpy(p->aData, apOld[i]->aData, pBt->pageSize);
drh14acc042001-06-10 19:56:58 +00005320 }
5321
5322 /*
5323 ** Load pointers to all cells on sibling pages and the divider cells
5324 ** into the local apCell[] array. Make copies of the divider cells
drhe5ae5732008-06-15 02:51:47 +00005325 ** into space obtained form aSpace1[] and remove the the divider Cells
drhb6f41482004-05-14 01:58:11 +00005326 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00005327 **
5328 ** If the siblings are on leaf pages, then the child pointers of the
5329 ** divider cells are stripped from the cells before they are copied
drhe5ae5732008-06-15 02:51:47 +00005330 ** into aSpace1[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00005331 ** child pointers. If siblings are not leaves, then all cell in
5332 ** apCell[] include child pointers. Either way, all cells in apCell[]
5333 ** are alike.
drh96f5b762004-05-16 16:24:36 +00005334 **
5335 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
5336 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00005337 */
5338 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00005339 leafCorrection = pPage->leaf*4;
drh44845222008-07-17 18:39:57 +00005340 leafData = pPage->hasData;
drh8b2f49b2001-06-08 00:21:52 +00005341 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00005342 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00005343 int limit = pOld->nCell+pOld->nOverflow;
5344 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00005345 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00005346 apCell[nCell] = findOverflowCell(pOld, j);
5347 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk197785d90ca2008-07-19 14:25:15 +00005348 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005349 int a;
drhf49661a2008-12-10 16:45:50 +00005350 aFrom[nCell] = (u8)i; assert( i>=0 && i<6 );
danielk1977ac11ee62005-01-15 12:45:51 +00005351 for(a=0; a<pOld->nOverflow; a++){
5352 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
5353 aFrom[nCell] = 0xFF;
5354 break;
5355 }
5356 }
5357 }
drh14acc042001-06-10 19:56:58 +00005358 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00005359 }
5360 if( i<nOld-1 ){
drha9121e42008-02-19 14:59:35 +00005361 u16 sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00005362 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00005363 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
5364 ** are duplicates of keys on the child pages. We need to remove
5365 ** the divider cells from pParent, but the dividers cells are not
5366 ** added to apCell[] because they are duplicates of child cells.
5367 */
drh8b18dd42004-05-12 19:18:15 +00005368 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00005369 }else{
drhb6f41482004-05-14 01:58:11 +00005370 u8 *pTemp;
danielk1977634f2982005-03-28 08:44:07 +00005371 assert( nCell<nMaxCells );
drhb6f41482004-05-14 01:58:11 +00005372 szCell[nCell] = sz;
drhe5ae5732008-06-15 02:51:47 +00005373 pTemp = &aSpace1[iSpace1];
5374 iSpace1 += sz;
5375 assert( sz<=pBt->pageSize/4 );
5376 assert( iSpace1<=pBt->pageSize );
drhb6f41482004-05-14 01:58:11 +00005377 memcpy(pTemp, apDiv[i], sz);
5378 apCell[nCell] = pTemp+leafCorrection;
danielk197785d90ca2008-07-19 14:25:15 +00005379 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005380 aFrom[nCell] = 0xFF;
5381 }
drhb6f41482004-05-14 01:58:11 +00005382 dropCell(pParent, nxDiv, sz);
drhf49661a2008-12-10 16:45:50 +00005383 assert( leafCorrection==0 || leafCorrection==4 );
5384 szCell[nCell] -= (u16)leafCorrection;
drh43605152004-05-29 21:46:49 +00005385 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00005386 if( !pOld->leaf ){
5387 assert( leafCorrection==0 );
5388 /* The right pointer of the child page pOld becomes the left
5389 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00005390 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00005391 }else{
5392 assert( leafCorrection==4 );
danielk197739c96042007-05-12 10:41:47 +00005393 if( szCell[nCell]<4 ){
5394 /* Do not allow any cells smaller than 4 bytes. */
5395 szCell[nCell] = 4;
5396 }
drh8b18dd42004-05-12 19:18:15 +00005397 }
5398 nCell++;
drh4b70f112004-05-02 21:12:19 +00005399 }
drh8b2f49b2001-06-08 00:21:52 +00005400 }
5401 }
5402
5403 /*
drh6019e162001-07-02 17:51:45 +00005404 ** Figure out the number of pages needed to hold all nCell cells.
5405 ** Store this number in "k". Also compute szNew[] which is the total
5406 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00005407 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00005408 ** cntNew[k] should equal nCell.
5409 **
drh96f5b762004-05-16 16:24:36 +00005410 ** Values computed by this block:
5411 **
5412 ** k: The total number of sibling pages
5413 ** szNew[i]: Spaced used on the i-th sibling page.
5414 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
5415 ** the right of the i-th sibling page.
5416 ** usableSpace: Number of bytes of space available on each sibling.
5417 **
drh8b2f49b2001-06-08 00:21:52 +00005418 */
drh43605152004-05-29 21:46:49 +00005419 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00005420 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00005421 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00005422 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00005423 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00005424 szNew[k] = subtotal - szCell[i];
5425 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00005426 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00005427 subtotal = 0;
5428 k++;
5429 }
5430 }
5431 szNew[k] = subtotal;
5432 cntNew[k] = nCell;
5433 k++;
drh96f5b762004-05-16 16:24:36 +00005434
5435 /*
5436 ** The packing computed by the previous block is biased toward the siblings
5437 ** on the left side. The left siblings are always nearly full, while the
5438 ** right-most sibling might be nearly empty. This block of code attempts
5439 ** to adjust the packing of siblings to get a better balance.
5440 **
5441 ** This adjustment is more than an optimization. The packing above might
5442 ** be so out of balance as to be illegal. For example, the right-most
5443 ** sibling might be completely empty. This adjustment is not optional.
5444 */
drh6019e162001-07-02 17:51:45 +00005445 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00005446 int szRight = szNew[i]; /* Size of sibling on the right */
5447 int szLeft = szNew[i-1]; /* Size of sibling on the left */
5448 int r; /* Index of right-most cell in left sibling */
5449 int d; /* Index of first cell to the left of right sibling */
5450
5451 r = cntNew[i-1] - 1;
5452 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00005453 assert( d<nMaxCells );
5454 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00005455 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
5456 szRight += szCell[d] + 2;
5457 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00005458 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00005459 r = cntNew[i-1] - 1;
5460 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00005461 }
drh96f5b762004-05-16 16:24:36 +00005462 szNew[i] = szRight;
5463 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00005464 }
drh09d0deb2005-08-02 17:13:09 +00005465
5466 /* Either we found one or more cells (cntnew[0])>0) or we are the
5467 ** a virtual root page. A virtual root page is when the real root
5468 ** page is page 1 and we are the only child of that page.
5469 */
5470 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00005471
5472 /*
drh6b308672002-07-08 02:16:37 +00005473 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00005474 */
drh4b70f112004-05-02 21:12:19 +00005475 assert( pPage->pgno>1 );
5476 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00005477 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00005478 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00005479 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00005480 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00005481 pgnoNew[i] = pgnoOld[i];
5482 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00005483 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00005484 nNew++;
danielk197728129562005-01-11 10:25:06 +00005485 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00005486 }else{
drh7aa8f852006-03-28 00:24:44 +00005487 assert( i>0 );
drh4f0c5872007-03-26 22:05:01 +00005488 rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
drh6b308672002-07-08 02:16:37 +00005489 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00005490 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00005491 nNew++;
drh6b308672002-07-08 02:16:37 +00005492 }
drh8b2f49b2001-06-08 00:21:52 +00005493 }
5494
danielk1977299b1872004-11-22 10:02:10 +00005495 /* Free any old pages that were not reused as new pages.
5496 */
5497 while( i<nOld ){
5498 rc = freePage(apOld[i]);
5499 if( rc ) goto balance_cleanup;
5500 releasePage(apOld[i]);
5501 apOld[i] = 0;
5502 i++;
5503 }
5504
drh8b2f49b2001-06-08 00:21:52 +00005505 /*
drhf9ffac92002-03-02 19:00:31 +00005506 ** Put the new pages in accending order. This helps to
5507 ** keep entries in the disk file in order so that a scan
5508 ** of the table is a linear scan through the file. That
5509 ** in turn helps the operating system to deliver pages
5510 ** from the disk more rapidly.
5511 **
5512 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00005513 ** n is never more than NB (a small constant), that should
5514 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00005515 **
drhc3b70572003-01-04 19:44:07 +00005516 ** When NB==3, this one optimization makes the database
5517 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00005518 */
5519 for(i=0; i<k-1; i++){
5520 int minV = pgnoNew[i];
5521 int minI = i;
5522 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00005523 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00005524 minI = j;
5525 minV = pgnoNew[j];
5526 }
5527 }
5528 if( minI>i ){
5529 int t;
5530 MemPage *pT;
5531 t = pgnoNew[i];
5532 pT = apNew[i];
5533 pgnoNew[i] = pgnoNew[minI];
5534 apNew[i] = apNew[minI];
5535 pgnoNew[minI] = t;
5536 apNew[minI] = pT;
5537 }
5538 }
drha2fce642004-06-05 00:01:44 +00005539 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00005540 pgnoOld[0],
5541 nOld>=2 ? pgnoOld[1] : 0,
5542 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00005543 pgnoNew[0], szNew[0],
5544 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
5545 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00005546 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
5547 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00005548
drhf9ffac92002-03-02 19:00:31 +00005549 /*
drh14acc042001-06-10 19:56:58 +00005550 ** Evenly distribute the data in apCell[] across the new pages.
5551 ** Insert divider cells into pParent as necessary.
5552 */
5553 j = 0;
5554 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00005555 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00005556 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00005557 assert( j<nMaxCells );
drh4b70f112004-05-02 21:12:19 +00005558 assert( pNew->pgno==pgnoNew[i] );
drh10131482008-07-11 03:34:09 +00005559 zeroPage(pNew, pageFlags);
drhfa1a98a2004-05-14 19:08:17 +00005560 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00005561 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00005562 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00005563
danielk1977ac11ee62005-01-15 12:45:51 +00005564 /* If this is an auto-vacuum database, update the pointer map entries
5565 ** that point to the siblings that were rearranged. These can be: left
5566 ** children of cells, the right-child of the page, or overflow pages
5567 ** pointed to by cells.
5568 */
danielk197785d90ca2008-07-19 14:25:15 +00005569 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005570 for(k=j; k<cntNew[i]; k++){
danielk1977634f2982005-03-28 08:44:07 +00005571 assert( k<nMaxCells );
danielk1977ac11ee62005-01-15 12:45:51 +00005572 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
danielk197779a40da2005-01-16 08:00:01 +00005573 rc = ptrmapPutOvfl(pNew, k-j);
danielk197787c52b52008-07-19 11:49:07 +00005574 if( rc==SQLITE_OK && leafCorrection==0 ){
5575 rc = ptrmapPut(pBt, get4byte(apCell[k]), PTRMAP_BTREE, pNew->pgno);
5576 }
danielk197779a40da2005-01-16 08:00:01 +00005577 if( rc!=SQLITE_OK ){
5578 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00005579 }
5580 }
5581 }
5582 }
danielk1977ac11ee62005-01-15 12:45:51 +00005583
5584 j = cntNew[i];
5585
5586 /* If the sibling page assembled above was not the right-most sibling,
5587 ** insert a divider cell into the parent page.
5588 */
drh14acc042001-06-10 19:56:58 +00005589 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00005590 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00005591 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00005592 int sz;
danielk1977634f2982005-03-28 08:44:07 +00005593
5594 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00005595 pCell = apCell[j];
5596 sz = szCell[j] + leafCorrection;
drhe5ae5732008-06-15 02:51:47 +00005597 pTemp = &aSpace2[iSpace2];
drh4b70f112004-05-02 21:12:19 +00005598 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00005599 memcpy(&pNew->aData[8], pCell, 4);
danielk197785d90ca2008-07-19 14:25:15 +00005600 if( ISAUTOVACUUM
danielk197787c52b52008-07-19 11:49:07 +00005601 && (aFrom[j]==0xFF || apCopy[aFrom[j]]->pgno!=pNew->pgno)
5602 ){
5603 rc = ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno);
5604 if( rc!=SQLITE_OK ){
5605 goto balance_cleanup;
5606 }
5607 }
drh8b18dd42004-05-12 19:18:15 +00005608 }else if( leafData ){
drhfd131da2007-08-07 17:13:03 +00005609 /* If the tree is a leaf-data tree, and the siblings are leaves,
danielk1977ac11ee62005-01-15 12:45:51 +00005610 ** then there is no divider cell in apCell[]. Instead, the divider
5611 ** cell consists of the integer key for the right-most cell of
5612 ** the sibling-page assembled above only.
5613 */
drh6f11bef2004-05-13 01:12:56 +00005614 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00005615 j--;
drh16a9b832007-05-05 18:39:25 +00005616 sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
drhe5ae5732008-06-15 02:51:47 +00005617 pCell = pTemp;
drh20abac22009-01-28 20:21:17 +00005618 rc = fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
5619 if( rc!=SQLITE_OK ){
5620 goto balance_cleanup;
5621 }
drh8b18dd42004-05-12 19:18:15 +00005622 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00005623 }else{
5624 pCell -= 4;
danielk19774aeff622007-05-12 09:30:47 +00005625 /* Obscure case for non-leaf-data trees: If the cell at pCell was
drh85b623f2007-12-13 21:54:09 +00005626 ** previously stored on a leaf node, and its reported size was 4
danielk19774aeff622007-05-12 09:30:47 +00005627 ** bytes, then it may actually be smaller than this
5628 ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
drh85b623f2007-12-13 21:54:09 +00005629 ** any cell). But it is important to pass the correct size to
danielk19774aeff622007-05-12 09:30:47 +00005630 ** insertCell(), so reparse the cell now.
5631 **
5632 ** Note that this can never happen in an SQLite data file, as all
5633 ** cells are at least 4 bytes. It only happens in b-trees used
5634 ** to evaluate "IN (SELECT ...)" and similar clauses.
5635 */
5636 if( szCell[j]==4 ){
5637 assert(leafCorrection==4);
5638 sz = cellSizePtr(pParent, pCell);
5639 }
drh4b70f112004-05-02 21:12:19 +00005640 }
drhe5ae5732008-06-15 02:51:47 +00005641 iSpace2 += sz;
5642 assert( sz<=pBt->pageSize/4 );
5643 assert( iSpace2<=pBt->pageSize );
danielk1977a3ad5e72005-01-07 08:56:44 +00005644 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
danielk1977e80463b2004-11-03 03:01:16 +00005645 if( rc!=SQLITE_OK ) goto balance_cleanup;
drhc5053fb2008-11-27 02:22:10 +00005646 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
drh43605152004-05-29 21:46:49 +00005647 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
danielk197785d90ca2008-07-19 14:25:15 +00005648
danielk1977ac11ee62005-01-15 12:45:51 +00005649 /* If this is an auto-vacuum database, and not a leaf-data tree,
5650 ** then update the pointer map with an entry for the overflow page
5651 ** that the cell just inserted points to (if any).
5652 */
danielk197785d90ca2008-07-19 14:25:15 +00005653 if( ISAUTOVACUUM && !leafData ){
danielk197779a40da2005-01-16 08:00:01 +00005654 rc = ptrmapPutOvfl(pParent, nxDiv);
5655 if( rc!=SQLITE_OK ){
5656 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00005657 }
5658 }
drh14acc042001-06-10 19:56:58 +00005659 j++;
5660 nxDiv++;
5661 }
danielk197787c52b52008-07-19 11:49:07 +00005662
danielk197787c52b52008-07-19 11:49:07 +00005663 /* Set the pointer-map entry for the new sibling page. */
danielk197785d90ca2008-07-19 14:25:15 +00005664 if( ISAUTOVACUUM ){
danielk197787c52b52008-07-19 11:49:07 +00005665 rc = ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno);
5666 if( rc!=SQLITE_OK ){
5667 goto balance_cleanup;
5668 }
5669 }
drh14acc042001-06-10 19:56:58 +00005670 }
drh6019e162001-07-02 17:51:45 +00005671 assert( j==nCell );
drh7aa8f852006-03-28 00:24:44 +00005672 assert( nOld>0 );
5673 assert( nNew>0 );
drh4b70f112004-05-02 21:12:19 +00005674 if( (pageFlags & PTF_LEAF)==0 ){
danielk197787c52b52008-07-19 11:49:07 +00005675 u8 *zChild = &apCopy[nOld-1]->aData[8];
5676 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
danielk197785d90ca2008-07-19 14:25:15 +00005677 if( ISAUTOVACUUM ){
danielk197787c52b52008-07-19 11:49:07 +00005678 rc = ptrmapPut(pBt, get4byte(zChild), PTRMAP_BTREE, apNew[nNew-1]->pgno);
5679 if( rc!=SQLITE_OK ){
5680 goto balance_cleanup;
5681 }
5682 }
drh14acc042001-06-10 19:56:58 +00005683 }
drhc5053fb2008-11-27 02:22:10 +00005684 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
drh43605152004-05-29 21:46:49 +00005685 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00005686 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00005687 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00005688 }else{
5689 /* Right-most sibling is the left child of the first entry in pParent
5690 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00005691 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00005692 }
5693
5694 /*
drh3a4c1412004-05-09 20:40:11 +00005695 ** Balance the parent page. Note that the current page (pPage) might
danielk1977ac11ee62005-01-15 12:45:51 +00005696 ** have been added to the freelist so it might no longer be initialized.
drh3a4c1412004-05-09 20:40:11 +00005697 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00005698 */
danielk197771d5d2c2008-09-29 11:49:47 +00005699 assert( pParent->isInit );
drhfacf0302008-06-17 15:12:00 +00005700 sqlite3ScratchFree(apCell);
drhe5ae5732008-06-15 02:51:47 +00005701 apCell = 0;
danielk1977a4124bd2008-12-23 10:37:47 +00005702 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
5703 pPage->pgno, nOld, nNew, nCell));
5704 pPage->nOverflow = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005705 releasePage(pPage);
5706 pCur->iPage--;
5707 rc = balance(pCur, 0);
drhda200cc2004-05-09 11:51:38 +00005708
drh8b2f49b2001-06-08 00:21:52 +00005709 /*
drh14acc042001-06-10 19:56:58 +00005710 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00005711 */
drh14acc042001-06-10 19:56:58 +00005712balance_cleanup:
drhfacf0302008-06-17 15:12:00 +00005713 sqlite3PageFree(aSpace2);
5714 sqlite3ScratchFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00005715 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00005716 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00005717 }
drh14acc042001-06-10 19:56:58 +00005718 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00005719 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00005720 }
danielk1977a4124bd2008-12-23 10:37:47 +00005721 pCur->apPage[pCur->iPage]->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00005722
drh8b2f49b2001-06-08 00:21:52 +00005723 return rc;
5724}
5725
5726/*
drh43605152004-05-29 21:46:49 +00005727** This routine is called for the root page of a btree when the root
5728** page contains no cells. This is an opportunity to make the tree
5729** shallower by one level.
5730*/
danielk197771d5d2c2008-09-29 11:49:47 +00005731static int balance_shallower(BtCursor *pCur){
5732 MemPage *pPage; /* Root page of B-Tree */
drh43605152004-05-29 21:46:49 +00005733 MemPage *pChild; /* The only child page of pPage */
5734 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00005735 int rc = SQLITE_OK; /* Return code from subprocedures */
danielk1977aef0bf62005-12-30 16:28:01 +00005736 BtShared *pBt; /* The main BTree structure */
drh2e38c322004-09-03 18:38:44 +00005737 int mxCellPerPage; /* Maximum number of cells per page */
5738 u8 **apCell; /* All cells from pages being balanced */
drha9121e42008-02-19 14:59:35 +00005739 u16 *szCell; /* Local size of all cells */
drh43605152004-05-29 21:46:49 +00005740
danielk197771d5d2c2008-09-29 11:49:47 +00005741 assert( pCur->iPage==0 );
5742 pPage = pCur->apPage[0];
5743
drh43605152004-05-29 21:46:49 +00005744 assert( pPage->nCell==0 );
drh1fee73e2007-08-29 04:00:57 +00005745 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh2e38c322004-09-03 18:38:44 +00005746 pBt = pPage->pBt;
5747 mxCellPerPage = MX_CELL(pBt);
drhe5ae5732008-06-15 02:51:47 +00005748 apCell = sqlite3Malloc( mxCellPerPage*(sizeof(u8*)+sizeof(u16)) );
drh2e38c322004-09-03 18:38:44 +00005749 if( apCell==0 ) return SQLITE_NOMEM;
drha9121e42008-02-19 14:59:35 +00005750 szCell = (u16*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00005751 if( pPage->leaf ){
5752 /* The table is completely empty */
5753 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
5754 }else{
5755 /* The root page is empty but has one child. Transfer the
5756 ** information from that one child into the root page if it
5757 ** will fit. This reduces the depth of the tree by one.
5758 **
5759 ** If the root page is page 1, it has less space available than
5760 ** its child (due to the 100 byte header that occurs at the beginning
5761 ** of the database fle), so it might not be able to hold all of the
5762 ** information currently contained in the child. If this is the
5763 ** case, then do not do the transfer. Leave page 1 empty except
5764 ** for the right-pointer to the child page. The child page becomes
5765 ** the virtual root of the tree.
5766 */
drhf94a1732008-09-30 17:18:17 +00005767 VVA_ONLY( pCur->pagesShuffled = 1 );
drh43605152004-05-29 21:46:49 +00005768 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5769 assert( pgnoChild>0 );
danielk197789d40042008-11-17 14:20:56 +00005770 assert( pgnoChild<=pagerPagecount(pPage->pBt) );
drh16a9b832007-05-05 18:39:25 +00005771 rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
drh2e38c322004-09-03 18:38:44 +00005772 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005773 if( pPage->pgno==1 ){
danielk197771d5d2c2008-09-29 11:49:47 +00005774 rc = sqlite3BtreeInitPage(pChild);
drh2e38c322004-09-03 18:38:44 +00005775 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005776 assert( pChild->nOverflow==0 );
5777 if( pChild->nFree>=100 ){
5778 /* The child information will fit on the root page, so do the
5779 ** copy */
5780 int i;
5781 zeroPage(pPage, pChild->aData[0]);
5782 for(i=0; i<pChild->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00005783 apCell[i] = findCell(pChild,i);
drh43605152004-05-29 21:46:49 +00005784 szCell[i] = cellSizePtr(pChild, apCell[i]);
5785 }
5786 assemblePage(pPage, pChild->nCell, apCell, szCell);
danielk1977ae825582004-11-23 09:06:55 +00005787 /* Copy the right-pointer of the child to the parent. */
drhc5053fb2008-11-27 02:22:10 +00005788 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977ae825582004-11-23 09:06:55 +00005789 put4byte(&pPage->aData[pPage->hdrOffset+8],
5790 get4byte(&pChild->aData[pChild->hdrOffset+8]));
drh9bf9e9c2008-12-05 20:01:43 +00005791 rc = freePage(pChild);
drh43605152004-05-29 21:46:49 +00005792 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
5793 }else{
5794 /* The child has more information that will fit on the root.
5795 ** The tree is already balanced. Do nothing. */
5796 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
5797 }
5798 }else{
5799 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
5800 pPage->isInit = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005801 rc = sqlite3BtreeInitPage(pPage);
drh43605152004-05-29 21:46:49 +00005802 assert( rc==SQLITE_OK );
5803 freePage(pChild);
5804 TRACE(("BALANCE: transfer child %d into root %d\n",
5805 pChild->pgno, pPage->pgno));
5806 }
danielk1977ac11ee62005-01-15 12:45:51 +00005807 assert( pPage->nOverflow==0 );
shane831c3292008-11-10 17:14:58 +00005808#ifndef SQLITE_OMIT_AUTOVACUUM
drh9bf9e9c2008-12-05 20:01:43 +00005809 if( ISAUTOVACUUM && rc==SQLITE_OK ){
danielk197700a696d2008-09-29 16:41:31 +00005810 rc = setChildPtrmaps(pPage);
danielk1977ac11ee62005-01-15 12:45:51 +00005811 }
shane831c3292008-11-10 17:14:58 +00005812#endif
drh43605152004-05-29 21:46:49 +00005813 releasePage(pChild);
5814 }
drh2e38c322004-09-03 18:38:44 +00005815end_shallow_balance:
drh17435752007-08-16 04:30:38 +00005816 sqlite3_free(apCell);
drh2e38c322004-09-03 18:38:44 +00005817 return rc;
drh43605152004-05-29 21:46:49 +00005818}
5819
5820
5821/*
5822** The root page is overfull
5823**
5824** When this happens, Create a new child page and copy the
5825** contents of the root into the child. Then make the root
5826** page an empty page with rightChild pointing to the new
5827** child. Finally, call balance_internal() on the new child
5828** to cause it to split.
5829*/
danielk197771d5d2c2008-09-29 11:49:47 +00005830static int balance_deeper(BtCursor *pCur){
drh43605152004-05-29 21:46:49 +00005831 int rc; /* Return value from subprocedures */
danielk197771d5d2c2008-09-29 11:49:47 +00005832 MemPage *pPage; /* Pointer to the root page */
drh43605152004-05-29 21:46:49 +00005833 MemPage *pChild; /* Pointer to a new child page */
5834 Pgno pgnoChild; /* Page number of the new child page */
danielk1977aef0bf62005-12-30 16:28:01 +00005835 BtShared *pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00005836 int usableSize; /* Total usable size of a page */
5837 u8 *data; /* Content of the parent page */
5838 u8 *cdata; /* Content of the child page */
5839 int hdr; /* Offset to page header in parent */
drh281b21d2008-08-22 12:57:08 +00005840 int cbrk; /* Offset to content of first cell in parent */
drh43605152004-05-29 21:46:49 +00005841
danielk197771d5d2c2008-09-29 11:49:47 +00005842 assert( pCur->iPage==0 );
5843 assert( pCur->apPage[0]->nOverflow>0 );
5844
drhf94a1732008-09-30 17:18:17 +00005845 VVA_ONLY( pCur->pagesShuffled = 1 );
danielk197771d5d2c2008-09-29 11:49:47 +00005846 pPage = pCur->apPage[0];
drh43605152004-05-29 21:46:49 +00005847 pBt = pPage->pBt;
drh1fee73e2007-08-29 04:00:57 +00005848 assert( sqlite3_mutex_held(pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00005849 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh4f0c5872007-03-26 22:05:01 +00005850 rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
drh43605152004-05-29 21:46:49 +00005851 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00005852 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
drh43605152004-05-29 21:46:49 +00005853 usableSize = pBt->usableSize;
5854 data = pPage->aData;
5855 hdr = pPage->hdrOffset;
drh281b21d2008-08-22 12:57:08 +00005856 cbrk = get2byte(&data[hdr+5]);
drh43605152004-05-29 21:46:49 +00005857 cdata = pChild->aData;
5858 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
drh281b21d2008-08-22 12:57:08 +00005859 memcpy(&cdata[cbrk], &data[cbrk], usableSize-cbrk);
danielk1977bc2ca9e2008-11-13 14:28:28 +00005860
5861 assert( pChild->isInit==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00005862 rc = sqlite3BtreeInitPage(pChild);
5863 if( rc==SQLITE_OK ){
5864 int nCopy = pPage->nOverflow*sizeof(pPage->aOvfl[0]);
5865 memcpy(pChild->aOvfl, pPage->aOvfl, nCopy);
5866 pChild->nOverflow = pPage->nOverflow;
5867 if( pChild->nOverflow ){
5868 pChild->nFree = 0;
5869 }
5870 assert( pChild->nCell==pPage->nCell );
drhc5053fb2008-11-27 02:22:10 +00005871 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00005872 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
5873 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
5874 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
5875 if( ISAUTOVACUUM ){
danielk197771d5d2c2008-09-29 11:49:47 +00005876 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
shane831c3292008-11-10 17:14:58 +00005877#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197771d5d2c2008-09-29 11:49:47 +00005878 if( rc==SQLITE_OK ){
danielk197700a696d2008-09-29 16:41:31 +00005879 rc = setChildPtrmaps(pChild);
danielk1977ac11ee62005-01-15 12:45:51 +00005880 }
drh30df0092008-12-23 15:58:06 +00005881 if( rc ){
5882 pChild->nOverflow = 0;
5883 }
shane831c3292008-11-10 17:14:58 +00005884#endif
danielk1977ac11ee62005-01-15 12:45:51 +00005885 }
danielk197787c52b52008-07-19 11:49:07 +00005886 }
danielk19776b456a22005-03-21 04:04:02 +00005887
danielk197771d5d2c2008-09-29 11:49:47 +00005888 if( rc==SQLITE_OK ){
5889 pCur->iPage++;
5890 pCur->apPage[1] = pChild;
danielk1977bf93c562008-09-29 15:53:25 +00005891 pCur->aiIdx[0] = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005892 rc = balance_nonroot(pCur);
5893 }else{
5894 releasePage(pChild);
5895 }
5896
drh43605152004-05-29 21:46:49 +00005897 return rc;
5898}
5899
5900/*
danielk197771d5d2c2008-09-29 11:49:47 +00005901** The page that pCur currently points to has just been modified in
5902** some way. This function figures out if this modification means the
5903** tree needs to be balanced, and if so calls the appropriate balancing
5904** routine.
5905**
5906** Parameter isInsert is true if a new cell was just inserted into the
5907** page, or false otherwise.
drh43605152004-05-29 21:46:49 +00005908*/
danielk197771d5d2c2008-09-29 11:49:47 +00005909static int balance(BtCursor *pCur, int isInsert){
drh43605152004-05-29 21:46:49 +00005910 int rc = SQLITE_OK;
danielk197771d5d2c2008-09-29 11:49:47 +00005911 MemPage *pPage = pCur->apPage[pCur->iPage];
5912
drh1fee73e2007-08-29 04:00:57 +00005913 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197771d5d2c2008-09-29 11:49:47 +00005914 if( pCur->iPage==0 ){
danielk19776e465eb2007-08-21 13:11:00 +00005915 rc = sqlite3PagerWrite(pPage->pDbPage);
5916 if( rc==SQLITE_OK && pPage->nOverflow>0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00005917 rc = balance_deeper(pCur);
danielk1977a4124bd2008-12-23 10:37:47 +00005918 assert( pCur->apPage[0]==pPage );
drh9bf9e9c2008-12-05 20:01:43 +00005919 assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
drh43605152004-05-29 21:46:49 +00005920 }
danielk1977687566d2004-11-02 12:56:41 +00005921 if( rc==SQLITE_OK && pPage->nCell==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00005922 rc = balance_shallower(pCur);
danielk1977a4124bd2008-12-23 10:37:47 +00005923 assert( pCur->apPage[0]==pPage );
drh9bf9e9c2008-12-05 20:01:43 +00005924 assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
drh43605152004-05-29 21:46:49 +00005925 }
5926 }else{
danielk1977ac245ec2005-01-14 13:50:11 +00005927 if( pPage->nOverflow>0 ||
danielk197771d5d2c2008-09-29 11:49:47 +00005928 (!isInsert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
5929 rc = balance_nonroot(pCur);
drh43605152004-05-29 21:46:49 +00005930 }
5931 }
5932 return rc;
5933}
5934
5935/*
drh8dcd7ca2004-08-08 19:43:29 +00005936** This routine checks all cursors that point to table pgnoRoot.
drh980b1a72006-08-16 16:42:48 +00005937** If any of those cursors were opened with wrFlag==0 in a different
5938** database connection (a database connection that shares the pager
5939** cache with the current connection) and that other connection
5940** is not in the ReadUncommmitted state, then this routine returns
5941** SQLITE_LOCKED.
danielk1977299b1872004-11-22 10:02:10 +00005942**
drh11b57d62009-02-24 19:21:41 +00005943** As well as cursors with wrFlag==0, cursors with
5944** isIncrblobHandle==1 are also considered 'read' cursors because
5945** incremental blob cursors are used for both reading and writing.
danielk19773588ceb2008-06-10 17:30:26 +00005946**
5947** When pgnoRoot is the root page of an intkey table, this function is also
5948** responsible for invalidating incremental blob cursors when the table row
5949** on which they are opened is deleted or modified. Cursors are invalidated
5950** according to the following rules:
5951**
5952** 1) When BtreeClearTable() is called to completely delete the contents
5953** of a B-Tree table, pExclude is set to zero and parameter iRow is
5954** set to non-zero. In this case all incremental blob cursors open
5955** on the table rooted at pgnoRoot are invalidated.
5956**
5957** 2) When BtreeInsert(), BtreeDelete() or BtreePutData() is called to
5958** modify a table row via an SQL statement, pExclude is set to the
5959** write cursor used to do the modification and parameter iRow is set
5960** to the integer row id of the B-Tree entry being modified. Unless
5961** pExclude is itself an incremental blob cursor, then all incremental
5962** blob cursors open on row iRow of the B-Tree are invalidated.
5963**
5964** 3) If both pExclude and iRow are set to zero, no incremental blob
5965** cursors are invalidated.
drhf74b8d92002-09-01 23:20:45 +00005966*/
drh11b57d62009-02-24 19:21:41 +00005967static int checkForReadConflicts(
5968 Btree *pBtree, /* The database file to check */
5969 Pgno pgnoRoot, /* Look for read cursors on this btree */
5970 BtCursor *pExclude, /* Ignore this cursor */
5971 i64 iRow /* The rowid that might be changing */
danielk19773588ceb2008-06-10 17:30:26 +00005972){
danielk1977299b1872004-11-22 10:02:10 +00005973 BtCursor *p;
drh980b1a72006-08-16 16:42:48 +00005974 BtShared *pBt = pBtree->pBt;
drhe5fe6902007-12-07 18:55:28 +00005975 sqlite3 *db = pBtree->db;
drh1fee73e2007-08-29 04:00:57 +00005976 assert( sqlite3BtreeHoldsMutex(pBtree) );
danielk1977299b1872004-11-22 10:02:10 +00005977 for(p=pBt->pCursor; p; p=p->pNext){
drh980b1a72006-08-16 16:42:48 +00005978 if( p==pExclude ) continue;
drh980b1a72006-08-16 16:42:48 +00005979 if( p->pgnoRoot!=pgnoRoot ) continue;
danielk19773588ceb2008-06-10 17:30:26 +00005980#ifndef SQLITE_OMIT_INCRBLOB
5981 if( p->isIncrblobHandle && (
5982 (!pExclude && iRow)
5983 || (pExclude && !pExclude->isIncrblobHandle && p->info.nKey==iRow)
5984 )){
5985 p->eState = CURSOR_INVALID;
5986 }
5987#endif
5988 if( p->eState!=CURSOR_VALID ) continue;
5989 if( p->wrFlag==0
5990#ifndef SQLITE_OMIT_INCRBLOB
5991 || p->isIncrblobHandle
5992#endif
5993 ){
drhe5fe6902007-12-07 18:55:28 +00005994 sqlite3 *dbOther = p->pBtree->db;
danielk1977404ca072009-03-16 13:19:36 +00005995 assert(dbOther);
5996 if( dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0 ){
5997 sqlite3ConnectionBlocked(db, dbOther);
5998 return SQLITE_LOCKED_SHAREDCACHE;
drh980b1a72006-08-16 16:42:48 +00005999 }
danielk1977299b1872004-11-22 10:02:10 +00006000 }
6001 }
drhf74b8d92002-09-01 23:20:45 +00006002 return SQLITE_OK;
6003}
6004
6005/*
drh3b7511c2001-05-26 13:15:44 +00006006** Insert a new record into the BTree. The key is given by (pKey,nKey)
6007** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00006008** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00006009** is left pointing at a random location.
6010**
6011** For an INTKEY table, only the nKey value of the key is used. pKey is
6012** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00006013*/
drh3aac2dd2004-04-26 14:10:20 +00006014int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00006015 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00006016 const void *pKey, i64 nKey, /* The key of the new record */
drhe4d90812007-03-29 05:51:49 +00006017 const void *pData, int nData, /* The data of the new record */
drhb026e052007-05-02 01:34:31 +00006018 int nZero, /* Number of extra 0 bytes to append to data */
drhe4d90812007-03-29 05:51:49 +00006019 int appendBias /* True if this is likely an append */
drh3b7511c2001-05-26 13:15:44 +00006020){
drh3b7511c2001-05-26 13:15:44 +00006021 int rc;
6022 int loc;
drh14acc042001-06-10 19:56:58 +00006023 int szNew;
danielk197771d5d2c2008-09-29 11:49:47 +00006024 int idx;
drh3b7511c2001-05-26 13:15:44 +00006025 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00006026 Btree *p = pCur->pBtree;
6027 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00006028 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00006029 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00006030
drh1fee73e2007-08-29 04:00:57 +00006031 assert( cursorHoldsMutex(pCur) );
drh64022502009-01-09 14:11:04 +00006032 assert( pBt->inTransaction==TRANS_WRITE );
drhf74b8d92002-09-01 23:20:45 +00006033 assert( !pBt->readOnly );
drh64022502009-01-09 14:11:04 +00006034 assert( pCur->wrFlag );
danielk1977404ca072009-03-16 13:19:36 +00006035 rc = checkForReadConflicts(pCur->pBtree, pCur->pgnoRoot, pCur, nKey);
6036 if( rc ){
6037 /* The table pCur points to has a read lock */
6038 assert( rc==SQLITE_LOCKED_SHAREDCACHE );
6039 return rc;
drhf74b8d92002-09-01 23:20:45 +00006040 }
drhfb982642007-08-30 01:19:59 +00006041 if( pCur->eState==CURSOR_FAULT ){
6042 return pCur->skip;
6043 }
danielk1977da184232006-01-05 11:34:32 +00006044
6045 /* Save the positions of any other cursors open on this table */
danielk1977be51a652008-10-08 17:58:48 +00006046 sqlite3BtreeClearCursor(pCur);
danielk19772e94d4d2006-01-09 05:36:27 +00006047 if(
danielk19772e94d4d2006-01-09 05:36:27 +00006048 SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
drhe63d9992008-08-13 19:11:48 +00006049 SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
danielk19772e94d4d2006-01-09 05:36:27 +00006050 ){
danielk1977da184232006-01-05 11:34:32 +00006051 return rc;
6052 }
6053
danielk197771d5d2c2008-09-29 11:49:47 +00006054 pPage = pCur->apPage[pCur->iPage];
drh4a1c3802004-05-12 15:15:47 +00006055 assert( pPage->intKey || nKey>=0 );
drh44845222008-07-17 18:39:57 +00006056 assert( pPage->leaf || !pPage->intKey );
drh3a4c1412004-05-09 20:40:11 +00006057 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
6058 pCur->pgnoRoot, nKey, nData, pPage->pgno,
6059 loc==0 ? "overwrite" : "new entry"));
danielk197771d5d2c2008-09-29 11:49:47 +00006060 assert( pPage->isInit );
danielk197752ae7242008-03-25 14:24:56 +00006061 allocateTempSpace(pBt);
6062 newCell = pBt->pTmpSpace;
drh2e38c322004-09-03 18:38:44 +00006063 if( newCell==0 ) return SQLITE_NOMEM;
drhb026e052007-05-02 01:34:31 +00006064 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
drh2e38c322004-09-03 18:38:44 +00006065 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00006066 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00006067 assert( szNew<=MX_CELL_SIZE(pBt) );
danielk197771d5d2c2008-09-29 11:49:47 +00006068 idx = pCur->aiIdx[pCur->iPage];
danielk1977da184232006-01-05 11:34:32 +00006069 if( loc==0 && CURSOR_VALID==pCur->eState ){
drha9121e42008-02-19 14:59:35 +00006070 u16 szOld;
danielk197771d5d2c2008-09-29 11:49:47 +00006071 assert( idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00006072 rc = sqlite3PagerWrite(pPage->pDbPage);
6073 if( rc ){
6074 goto end_insert;
6075 }
danielk197771d5d2c2008-09-29 11:49:47 +00006076 oldCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00006077 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006078 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00006079 }
drh43605152004-05-29 21:46:49 +00006080 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00006081 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00006082 if( rc ) goto end_insert;
shane0af3f892008-11-12 04:55:34 +00006083 rc = dropCell(pPage, idx, szOld);
6084 if( rc!=SQLITE_OK ) {
6085 goto end_insert;
6086 }
drh7c717f72001-06-24 20:39:41 +00006087 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00006088 assert( pPage->leaf );
danielk197771d5d2c2008-09-29 11:49:47 +00006089 idx = ++pCur->aiIdx[pCur->iPage];
drh271efa52004-05-30 19:19:05 +00006090 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00006091 pCur->validNKey = 0;
drh14acc042001-06-10 19:56:58 +00006092 }else{
drh4b70f112004-05-02 21:12:19 +00006093 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00006094 }
danielk197771d5d2c2008-09-29 11:49:47 +00006095 rc = insertCell(pPage, idx, newCell, szNew, 0, 0);
drh9bf9e9c2008-12-05 20:01:43 +00006096 if( rc==SQLITE_OK ){
6097 rc = balance(pCur, 1);
6098 }
6099
6100 /* Must make sure nOverflow is reset to zero even if the balance()
6101 ** fails. Internal data structure corruption will result otherwise. */
danielk1977a4124bd2008-12-23 10:37:47 +00006102 pCur->apPage[pCur->iPage]->nOverflow = 0;
drh9bf9e9c2008-12-05 20:01:43 +00006103
danielk1977299b1872004-11-22 10:02:10 +00006104 if( rc==SQLITE_OK ){
6105 moveToRoot(pCur);
6106 }
drh2e38c322004-09-03 18:38:44 +00006107end_insert:
drh5e2f8b92001-05-28 00:41:15 +00006108 return rc;
6109}
6110
6111/*
drh4b70f112004-05-02 21:12:19 +00006112** Delete the entry that the cursor is pointing to. The cursor
drhf94a1732008-09-30 17:18:17 +00006113** is left pointing at a arbitrary location.
drh3b7511c2001-05-26 13:15:44 +00006114*/
drh3aac2dd2004-04-26 14:10:20 +00006115int sqlite3BtreeDelete(BtCursor *pCur){
danielk197771d5d2c2008-09-29 11:49:47 +00006116 MemPage *pPage = pCur->apPage[pCur->iPage];
6117 int idx;
drh4b70f112004-05-02 21:12:19 +00006118 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00006119 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00006120 Pgno pgnoChild = 0;
drhd677b3d2007-08-20 22:48:41 +00006121 Btree *p = pCur->pBtree;
6122 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006123
drh1fee73e2007-08-29 04:00:57 +00006124 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00006125 assert( pPage->isInit );
drh64022502009-01-09 14:11:04 +00006126 assert( pBt->inTransaction==TRANS_WRITE );
drhf74b8d92002-09-01 23:20:45 +00006127 assert( !pBt->readOnly );
drhfb982642007-08-30 01:19:59 +00006128 if( pCur->eState==CURSOR_FAULT ){
6129 return pCur->skip;
6130 }
drh64022502009-01-09 14:11:04 +00006131 if( NEVER(pCur->aiIdx[pCur->iPage]>=pPage->nCell) ){
drhbd03cae2001-06-02 02:40:57 +00006132 return SQLITE_ERROR; /* The cursor is not pointing to anything */
6133 }
drh64022502009-01-09 14:11:04 +00006134 assert( pCur->wrFlag );
danielk1977404ca072009-03-16 13:19:36 +00006135 rc = checkForReadConflicts(p, pCur->pgnoRoot, pCur, pCur->info.nKey);
6136 if( rc!=SQLITE_OK ){
6137 /* The table pCur points to has a read lock */
6138 assert( rc==SQLITE_LOCKED_SHAREDCACHE );
6139 return rc;
drhf74b8d92002-09-01 23:20:45 +00006140 }
danielk1977da184232006-01-05 11:34:32 +00006141
6142 /* Restore the current cursor position (a no-op if the cursor is not in
6143 ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors
danielk19773b8a05f2007-03-19 17:44:26 +00006144 ** open on the same table. Then call sqlite3PagerWrite() on the page
danielk1977da184232006-01-05 11:34:32 +00006145 ** that the entry will be deleted from.
6146 */
6147 if(
drha3460582008-07-11 21:02:53 +00006148 (rc = restoreCursorPosition(pCur))!=0 ||
drhd1167392006-01-23 13:00:35 +00006149 (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
danielk19773b8a05f2007-03-19 17:44:26 +00006150 (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
danielk1977da184232006-01-05 11:34:32 +00006151 ){
6152 return rc;
6153 }
danielk1977e6efa742004-11-10 11:55:10 +00006154
drh85b623f2007-12-13 21:54:09 +00006155 /* Locate the cell within its page and leave pCell pointing to the
danielk1977e6efa742004-11-10 11:55:10 +00006156 ** data. The clearCell() call frees any overflow pages associated with the
6157 ** cell. The cell itself is still intact.
6158 */
danielk197771d5d2c2008-09-29 11:49:47 +00006159 idx = pCur->aiIdx[pCur->iPage];
6160 pCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00006161 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006162 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00006163 }
danielk197728129562005-01-11 10:25:06 +00006164 rc = clearCell(pPage, pCell);
drhd677b3d2007-08-20 22:48:41 +00006165 if( rc ){
drhd677b3d2007-08-20 22:48:41 +00006166 return rc;
6167 }
danielk1977e6efa742004-11-10 11:55:10 +00006168
drh4b70f112004-05-02 21:12:19 +00006169 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00006170 /*
drh5e00f6c2001-09-13 13:46:56 +00006171 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00006172 ** do something we will leave a hole on an internal page.
6173 ** We have to fill the hole by moving in a cell from a leaf. The
6174 ** next Cell after the one to be deleted is guaranteed to exist and
danielk1977299b1872004-11-22 10:02:10 +00006175 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00006176 */
drh14acc042001-06-10 19:56:58 +00006177 BtCursor leafCur;
drh1bd10f82008-12-10 21:19:56 +00006178 MemPage *pLeafPage = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00006179
drh4b70f112004-05-02 21:12:19 +00006180 unsigned char *pNext;
danielk1977299b1872004-11-22 10:02:10 +00006181 int notUsed;
danielk19776b456a22005-03-21 04:04:02 +00006182 unsigned char *tempCell = 0;
drh44845222008-07-17 18:39:57 +00006183 assert( !pPage->intKey );
drh16a9b832007-05-05 18:39:25 +00006184 sqlite3BtreeGetTempCursor(pCur, &leafCur);
danielk1977299b1872004-11-22 10:02:10 +00006185 rc = sqlite3BtreeNext(&leafCur, &notUsed);
danielk19776b456a22005-03-21 04:04:02 +00006186 if( rc==SQLITE_OK ){
danielk19772f78fc62008-09-30 09:31:45 +00006187 assert( leafCur.aiIdx[leafCur.iPage]==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00006188 pLeafPage = leafCur.apPage[leafCur.iPage];
danielk197771d5d2c2008-09-29 11:49:47 +00006189 rc = sqlite3PagerWrite(pLeafPage->pDbPage);
danielk19776b456a22005-03-21 04:04:02 +00006190 }
6191 if( rc==SQLITE_OK ){
danielk19772f78fc62008-09-30 09:31:45 +00006192 int leafCursorInvalid = 0;
drha9121e42008-02-19 14:59:35 +00006193 u16 szNext;
danielk19776b456a22005-03-21 04:04:02 +00006194 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
danielk197771d5d2c2008-09-29 11:49:47 +00006195 pCur->pgnoRoot, pPage->pgno, pLeafPage->pgno));
6196 dropCell(pPage, idx, cellSizePtr(pPage, pCell));
danielk19772f78fc62008-09-30 09:31:45 +00006197 pNext = findCell(pLeafPage, 0);
danielk197771d5d2c2008-09-29 11:49:47 +00006198 szNext = cellSizePtr(pLeafPage, pNext);
danielk19776b456a22005-03-21 04:04:02 +00006199 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
danielk197752ae7242008-03-25 14:24:56 +00006200 allocateTempSpace(pBt);
6201 tempCell = pBt->pTmpSpace;
danielk19776b456a22005-03-21 04:04:02 +00006202 if( tempCell==0 ){
6203 rc = SQLITE_NOMEM;
6204 }
danielk19778ea1cfa2008-01-01 06:19:02 +00006205 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00006206 rc = insertCell(pPage, idx, pNext-4, szNext+4, tempCell, 0);
danielk19778ea1cfa2008-01-01 06:19:02 +00006207 }
danielk19772f78fc62008-09-30 09:31:45 +00006208
drhf94a1732008-09-30 17:18:17 +00006209
6210 /* The "if" statement in the next code block is critical. The
6211 ** slightest error in that statement would allow SQLite to operate
6212 ** correctly most of the time but produce very rare failures. To
6213 ** guard against this, the following macros help to verify that
6214 ** the "if" statement is well tested.
6215 */
6216 testcase( pPage->nOverflow==0 && pPage->nFree<pBt->usableSize*2/3
6217 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6218 testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3
6219 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6220 testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3+1
6221 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6222 testcase( pPage->nOverflow>0 && pPage->nFree<=pBt->usableSize*2/3
6223 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6224 testcase( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3))
6225 && pLeafPage->nFree+2+szNext == pBt->usableSize*2/3 );
6226
6227
danielk19772f78fc62008-09-30 09:31:45 +00006228 if( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3)) &&
6229 (pLeafPage->nFree+2+szNext > pBt->usableSize*2/3)
6230 ){
drhf94a1732008-09-30 17:18:17 +00006231 /* This branch is taken if the internal node is now either overflowing
6232 ** or underfull and the leaf node will be underfull after the just cell
danielk19772f78fc62008-09-30 09:31:45 +00006233 ** copied to the internal node is deleted from it. This is a special
6234 ** case because the call to balance() to correct the internal node
6235 ** may change the tree structure and invalidate the contents of
6236 ** the leafCur.apPage[] and leafCur.aiIdx[] arrays, which will be
6237 ** used by the balance() required to correct the underfull leaf
6238 ** node.
6239 **
6240 ** The formula used in the expression above are based on facets of
6241 ** the SQLite file-format that do not change over time.
6242 */
drhf94a1732008-09-30 17:18:17 +00006243 testcase( pPage->nFree==pBt->usableSize*2/3+1 );
6244 testcase( pLeafPage->nFree+2+szNext==pBt->usableSize*2/3+1 );
danielk19772f78fc62008-09-30 09:31:45 +00006245 leafCursorInvalid = 1;
6246 }
6247
danielk19778ea1cfa2008-01-01 06:19:02 +00006248 if( rc==SQLITE_OK ){
drhc5053fb2008-11-27 02:22:10 +00006249 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00006250 put4byte(findOverflowCell(pPage, idx), pgnoChild);
drhf94a1732008-09-30 17:18:17 +00006251 VVA_ONLY( pCur->pagesShuffled = 0 );
danielk197771d5d2c2008-09-29 11:49:47 +00006252 rc = balance(pCur, 0);
danielk19778ea1cfa2008-01-01 06:19:02 +00006253 }
danielk19772f78fc62008-09-30 09:31:45 +00006254
6255 if( rc==SQLITE_OK && leafCursorInvalid ){
6256 /* The leaf-node is now underfull and so the tree needs to be
6257 ** rebalanced. However, the balance() operation on the internal
6258 ** node above may have modified the structure of the B-Tree and
6259 ** so the current contents of leafCur.apPage[] and leafCur.aiIdx[]
6260 ** may not be trusted.
6261 **
6262 ** It is not possible to copy the ancestry from pCur, as the same
6263 ** balance() call has invalidated the pCur->apPage[] and aiIdx[]
6264 ** arrays.
drh7b682802008-09-30 14:06:28 +00006265 **
6266 ** The call to saveCursorPosition() below internally saves the
6267 ** key that leafCur is currently pointing to. Currently, there
6268 ** are two copies of that key in the tree - one here on the leaf
6269 ** page and one on some internal node in the tree. The copy on
6270 ** the leaf node is always the next key in tree-order after the
6271 ** copy on the internal node. So, the call to sqlite3BtreeNext()
6272 ** calls restoreCursorPosition() to point the cursor to the copy
6273 ** stored on the internal node, then advances to the next entry,
6274 ** which happens to be the copy of the key on the internal node.
danielk1977a69fda22008-09-30 16:48:10 +00006275 ** Net effect: leafCur is pointing back to the duplicate cell
6276 ** that needs to be removed, and the leafCur.apPage[] and
6277 ** leafCur.aiIdx[] arrays are correct.
danielk19772f78fc62008-09-30 09:31:45 +00006278 */
drhf94a1732008-09-30 17:18:17 +00006279 VVA_ONLY( Pgno leafPgno = pLeafPage->pgno );
danielk19772f78fc62008-09-30 09:31:45 +00006280 rc = saveCursorPosition(&leafCur);
6281 if( rc==SQLITE_OK ){
6282 rc = sqlite3BtreeNext(&leafCur, &notUsed);
6283 }
6284 pLeafPage = leafCur.apPage[leafCur.iPage];
6285 assert( pLeafPage->pgno==leafPgno );
6286 assert( leafCur.aiIdx[leafCur.iPage]==0 );
6287 }
6288
danielk19770cd1bbd2008-11-26 07:25:52 +00006289 if( SQLITE_OK==rc
6290 && SQLITE_OK==(rc = sqlite3PagerWrite(pLeafPage->pDbPage))
6291 ){
danielk19772f78fc62008-09-30 09:31:45 +00006292 dropCell(pLeafPage, 0, szNext);
drhf94a1732008-09-30 17:18:17 +00006293 VVA_ONLY( leafCur.pagesShuffled = 0 );
danielk197771d5d2c2008-09-29 11:49:47 +00006294 rc = balance(&leafCur, 0);
drhf94a1732008-09-30 17:18:17 +00006295 assert( leafCursorInvalid || !leafCur.pagesShuffled
6296 || !pCur->pagesShuffled );
danielk19778ea1cfa2008-01-01 06:19:02 +00006297 }
danielk19776b456a22005-03-21 04:04:02 +00006298 }
drh16a9b832007-05-05 18:39:25 +00006299 sqlite3BtreeReleaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00006300 }else{
danielk1977299b1872004-11-22 10:02:10 +00006301 TRACE(("DELETE: table=%d delete from leaf %d\n",
6302 pCur->pgnoRoot, pPage->pgno));
shanedcc50b72008-11-13 18:29:50 +00006303 rc = dropCell(pPage, idx, cellSizePtr(pPage, pCell));
6304 if( rc==SQLITE_OK ){
6305 rc = balance(pCur, 0);
6306 }
drh5e2f8b92001-05-28 00:41:15 +00006307 }
danielk19776b456a22005-03-21 04:04:02 +00006308 if( rc==SQLITE_OK ){
6309 moveToRoot(pCur);
6310 }
drh5e2f8b92001-05-28 00:41:15 +00006311 return rc;
drh3b7511c2001-05-26 13:15:44 +00006312}
drh8b2f49b2001-06-08 00:21:52 +00006313
6314/*
drhc6b52df2002-01-04 03:09:29 +00006315** Create a new BTree table. Write into *piTable the page
6316** number for the root page of the new table.
6317**
drhab01f612004-05-22 02:55:23 +00006318** The type of type is determined by the flags parameter. Only the
6319** following values of flags are currently in use. Other values for
6320** flags might not work:
6321**
6322** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
6323** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00006324*/
drhd677b3d2007-08-20 22:48:41 +00006325static int btreeCreateTable(Btree *p, int *piTable, int flags){
danielk1977aef0bf62005-12-30 16:28:01 +00006326 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006327 MemPage *pRoot;
6328 Pgno pgnoRoot;
6329 int rc;
drhd677b3d2007-08-20 22:48:41 +00006330
drh1fee73e2007-08-29 04:00:57 +00006331 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00006332 assert( pBt->inTransaction==TRANS_WRITE );
danielk197728129562005-01-11 10:25:06 +00006333 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00006334
danielk1977003ba062004-11-04 02:57:33 +00006335#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00006336 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00006337 if( rc ){
6338 return rc;
6339 }
danielk1977003ba062004-11-04 02:57:33 +00006340#else
danielk1977687566d2004-11-02 12:56:41 +00006341 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00006342 Pgno pgnoMove; /* Move a page here to make room for the root-page */
6343 MemPage *pPageMove; /* The page to move to. */
6344
danielk197720713f32007-05-03 11:43:33 +00006345 /* Creating a new table may probably require moving an existing database
6346 ** to make room for the new tables root page. In case this page turns
6347 ** out to be an overflow page, delete all overflow page-map caches
6348 ** held by open cursors.
6349 */
danielk197792d4d7a2007-05-04 12:05:56 +00006350 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00006351
danielk1977003ba062004-11-04 02:57:33 +00006352 /* Read the value of meta[3] from the database to determine where the
6353 ** root page of the new table should go. meta[3] is the largest root-page
6354 ** created so far, so the new root-page is (meta[3]+1).
6355 */
danielk1977aef0bf62005-12-30 16:28:01 +00006356 rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
drhd677b3d2007-08-20 22:48:41 +00006357 if( rc!=SQLITE_OK ){
6358 return rc;
6359 }
danielk1977003ba062004-11-04 02:57:33 +00006360 pgnoRoot++;
6361
danielk1977599fcba2004-11-08 07:13:13 +00006362 /* The new root-page may not be allocated on a pointer-map page, or the
6363 ** PENDING_BYTE page.
6364 */
drh72190432008-01-31 14:54:43 +00006365 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00006366 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00006367 pgnoRoot++;
6368 }
6369 assert( pgnoRoot>=3 );
6370
6371 /* Allocate a page. The page that currently resides at pgnoRoot will
6372 ** be moved to the allocated page (unless the allocated page happens
6373 ** to reside at pgnoRoot).
6374 */
drh4f0c5872007-03-26 22:05:01 +00006375 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00006376 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00006377 return rc;
6378 }
danielk1977003ba062004-11-04 02:57:33 +00006379
6380 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00006381 /* pgnoRoot is the page that will be used for the root-page of
6382 ** the new table (assuming an error did not occur). But we were
6383 ** allocated pgnoMove. If required (i.e. if it was not allocated
6384 ** by extending the file), the current page at position pgnoMove
6385 ** is already journaled.
6386 */
danielk1977003ba062004-11-04 02:57:33 +00006387 u8 eType;
6388 Pgno iPtrPage;
6389
6390 releasePage(pPageMove);
danielk1977f35843b2007-04-07 15:03:17 +00006391
6392 /* Move the page currently at pgnoRoot to pgnoMove. */
drh16a9b832007-05-05 18:39:25 +00006393 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006394 if( rc!=SQLITE_OK ){
6395 return rc;
6396 }
6397 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drhccae6022005-02-26 17:31:26 +00006398 if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00006399 releasePage(pRoot);
6400 return rc;
6401 }
drhccae6022005-02-26 17:31:26 +00006402 assert( eType!=PTRMAP_ROOTPAGE );
6403 assert( eType!=PTRMAP_FREEPAGE );
danielk19774c999992008-07-16 18:17:55 +00006404 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
danielk1977003ba062004-11-04 02:57:33 +00006405 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00006406
6407 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00006408 if( rc!=SQLITE_OK ){
6409 return rc;
6410 }
drh16a9b832007-05-05 18:39:25 +00006411 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006412 if( rc!=SQLITE_OK ){
6413 return rc;
6414 }
danielk19773b8a05f2007-03-19 17:44:26 +00006415 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00006416 if( rc!=SQLITE_OK ){
6417 releasePage(pRoot);
6418 return rc;
6419 }
6420 }else{
6421 pRoot = pPageMove;
6422 }
6423
danielk197742741be2005-01-08 12:42:39 +00006424 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00006425 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
6426 if( rc ){
6427 releasePage(pRoot);
6428 return rc;
6429 }
danielk1977aef0bf62005-12-30 16:28:01 +00006430 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00006431 if( rc ){
6432 releasePage(pRoot);
6433 return rc;
6434 }
danielk197742741be2005-01-08 12:42:39 +00006435
danielk1977003ba062004-11-04 02:57:33 +00006436 }else{
drh4f0c5872007-03-26 22:05:01 +00006437 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00006438 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00006439 }
6440#endif
danielk19773b8a05f2007-03-19 17:44:26 +00006441 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhde647132004-05-07 17:57:49 +00006442 zeroPage(pRoot, flags | PTF_LEAF);
danielk19773b8a05f2007-03-19 17:44:26 +00006443 sqlite3PagerUnref(pRoot->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00006444 *piTable = (int)pgnoRoot;
6445 return SQLITE_OK;
6446}
drhd677b3d2007-08-20 22:48:41 +00006447int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
6448 int rc;
6449 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006450 p->pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006451 rc = btreeCreateTable(p, piTable, flags);
6452 sqlite3BtreeLeave(p);
6453 return rc;
6454}
drh8b2f49b2001-06-08 00:21:52 +00006455
6456/*
6457** Erase the given database page and all its children. Return
6458** the page to the freelist.
6459*/
drh4b70f112004-05-02 21:12:19 +00006460static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00006461 BtShared *pBt, /* The BTree that contains the table */
drh4b70f112004-05-02 21:12:19 +00006462 Pgno pgno, /* Page number to clear */
danielk1977c7af4842008-10-27 13:59:33 +00006463 int freePageFlag, /* Deallocate page if true */
6464 int *pnChange
drh4b70f112004-05-02 21:12:19 +00006465){
danielk19776b456a22005-03-21 04:04:02 +00006466 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00006467 int rc;
drh4b70f112004-05-02 21:12:19 +00006468 unsigned char *pCell;
6469 int i;
drh8b2f49b2001-06-08 00:21:52 +00006470
drh1fee73e2007-08-29 04:00:57 +00006471 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197789d40042008-11-17 14:20:56 +00006472 if( pgno>pagerPagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00006473 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00006474 }
6475
danielk197771d5d2c2008-09-29 11:49:47 +00006476 rc = getAndInitPage(pBt, pgno, &pPage);
danielk19776b456a22005-03-21 04:04:02 +00006477 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00006478 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00006479 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00006480 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00006481 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00006482 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006483 }
drh4b70f112004-05-02 21:12:19 +00006484 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00006485 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006486 }
drha34b6762004-05-07 13:30:42 +00006487 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00006488 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00006489 if( rc ) goto cleardatabasepage_out;
danielk1977c7af4842008-10-27 13:59:33 +00006490 }else if( pnChange ){
6491 assert( pPage->intKey );
6492 *pnChange += pPage->nCell;
drh2aa679f2001-06-25 02:11:07 +00006493 }
6494 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00006495 rc = freePage(pPage);
danielk19773b8a05f2007-03-19 17:44:26 +00006496 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
drh3a4c1412004-05-09 20:40:11 +00006497 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00006498 }
danielk19776b456a22005-03-21 04:04:02 +00006499
6500cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00006501 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00006502 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006503}
6504
6505/*
drhab01f612004-05-22 02:55:23 +00006506** Delete all information from a single table in the database. iTable is
6507** the page number of the root of the table. After this routine returns,
6508** the root page is empty, but still exists.
6509**
6510** This routine will fail with SQLITE_LOCKED if there are any open
6511** read cursors on the table. Open write cursors are moved to the
6512** root of the table.
danielk1977c7af4842008-10-27 13:59:33 +00006513**
6514** If pnChange is not NULL, then table iTable must be an intkey table. The
6515** integer value pointed to by pnChange is incremented by the number of
6516** entries in the table.
drh8b2f49b2001-06-08 00:21:52 +00006517*/
danielk1977c7af4842008-10-27 13:59:33 +00006518int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
drh8b2f49b2001-06-08 00:21:52 +00006519 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00006520 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00006521 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006522 pBt->db = p->db;
drh64022502009-01-09 14:11:04 +00006523 assert( p->inTrans==TRANS_WRITE );
drh11b57d62009-02-24 19:21:41 +00006524 if( (rc = checkForReadConflicts(p, iTable, 0, 1))!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00006525 /* nothing to do */
6526 }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
6527 /* nothing to do */
6528 }else{
danielk197762c14b32008-11-19 09:05:26 +00006529 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
drh8b2f49b2001-06-08 00:21:52 +00006530 }
drhd677b3d2007-08-20 22:48:41 +00006531 sqlite3BtreeLeave(p);
6532 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006533}
6534
6535/*
6536** Erase all information in a table and add the root of the table to
6537** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00006538** page 1) is never added to the freelist.
6539**
6540** This routine will fail with SQLITE_LOCKED if there are any open
6541** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00006542**
6543** If AUTOVACUUM is enabled and the page at iTable is not the last
6544** root page in the database file, then the last root page
6545** in the database file is moved into the slot formerly occupied by
6546** iTable and that last slot formerly occupied by the last root page
6547** is added to the freelist instead of iTable. In this say, all
6548** root pages are kept at the beginning of the database file, which
6549** is necessary for AUTOVACUUM to work right. *piMoved is set to the
6550** page number that used to be the last root page in the file before
6551** the move. If no page gets moved, *piMoved is set to 0.
6552** The last root page is recorded in meta[3] and the value of
6553** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00006554*/
danielk197789d40042008-11-17 14:20:56 +00006555static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00006556 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00006557 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00006558 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00006559
drh1fee73e2007-08-29 04:00:57 +00006560 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00006561 assert( p->inTrans==TRANS_WRITE );
danielk1977a0bf2652004-11-04 14:30:04 +00006562
danielk1977e6efa742004-11-10 11:55:10 +00006563 /* It is illegal to drop a table if any cursors are open on the
6564 ** database. This is because in auto-vacuum mode the backend may
6565 ** need to move another root-page to fill a gap left by the deleted
6566 ** root page. If an open cursor was using this page a problem would
6567 ** occur.
6568 */
6569 if( pBt->pCursor ){
danielk1977404ca072009-03-16 13:19:36 +00006570 sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
6571 return SQLITE_LOCKED_SHAREDCACHE;
drh5df72a52002-06-06 23:16:05 +00006572 }
danielk1977a0bf2652004-11-04 14:30:04 +00006573
drh16a9b832007-05-05 18:39:25 +00006574 rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00006575 if( rc ) return rc;
danielk1977c7af4842008-10-27 13:59:33 +00006576 rc = sqlite3BtreeClearTable(p, iTable, 0);
danielk19776b456a22005-03-21 04:04:02 +00006577 if( rc ){
6578 releasePage(pPage);
6579 return rc;
6580 }
danielk1977a0bf2652004-11-04 14:30:04 +00006581
drh205f48e2004-11-05 00:43:11 +00006582 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00006583
drh4b70f112004-05-02 21:12:19 +00006584 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00006585#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00006586 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00006587 releasePage(pPage);
6588#else
6589 if( pBt->autoVacuum ){
6590 Pgno maxRootPgno;
danielk1977aef0bf62005-12-30 16:28:01 +00006591 rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006592 if( rc!=SQLITE_OK ){
6593 releasePage(pPage);
6594 return rc;
6595 }
6596
6597 if( iTable==maxRootPgno ){
6598 /* If the table being dropped is the table with the largest root-page
6599 ** number in the database, put the root page on the free list.
6600 */
6601 rc = freePage(pPage);
6602 releasePage(pPage);
6603 if( rc!=SQLITE_OK ){
6604 return rc;
6605 }
6606 }else{
6607 /* The table being dropped does not have the largest root-page
6608 ** number in the database. So move the page that does into the
6609 ** gap left by the deleted root-page.
6610 */
6611 MemPage *pMove;
6612 releasePage(pPage);
drh16a9b832007-05-05 18:39:25 +00006613 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006614 if( rc!=SQLITE_OK ){
6615 return rc;
6616 }
danielk19774c999992008-07-16 18:17:55 +00006617 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006618 releasePage(pMove);
6619 if( rc!=SQLITE_OK ){
6620 return rc;
6621 }
drh16a9b832007-05-05 18:39:25 +00006622 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006623 if( rc!=SQLITE_OK ){
6624 return rc;
6625 }
6626 rc = freePage(pMove);
6627 releasePage(pMove);
6628 if( rc!=SQLITE_OK ){
6629 return rc;
6630 }
6631 *piMoved = maxRootPgno;
6632 }
6633
danielk1977599fcba2004-11-08 07:13:13 +00006634 /* Set the new 'max-root-page' value in the database header. This
6635 ** is the old value less one, less one more if that happens to
6636 ** be a root-page number, less one again if that is the
6637 ** PENDING_BYTE_PAGE.
6638 */
danielk197787a6e732004-11-05 12:58:25 +00006639 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00006640 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
6641 maxRootPgno--;
6642 }
danielk1977266664d2006-02-10 08:24:21 +00006643 if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00006644 maxRootPgno--;
6645 }
danielk1977599fcba2004-11-08 07:13:13 +00006646 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
6647
danielk1977aef0bf62005-12-30 16:28:01 +00006648 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006649 }else{
6650 rc = freePage(pPage);
6651 releasePage(pPage);
6652 }
6653#endif
drh2aa679f2001-06-25 02:11:07 +00006654 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00006655 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00006656 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00006657 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00006658 }
drh8b2f49b2001-06-08 00:21:52 +00006659 return rc;
6660}
drhd677b3d2007-08-20 22:48:41 +00006661int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
6662 int rc;
6663 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006664 p->pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006665 rc = btreeDropTable(p, iTable, piMoved);
6666 sqlite3BtreeLeave(p);
6667 return rc;
6668}
drh8b2f49b2001-06-08 00:21:52 +00006669
drh001bbcb2003-03-19 03:14:00 +00006670
drh8b2f49b2001-06-08 00:21:52 +00006671/*
drh23e11ca2004-05-04 17:27:28 +00006672** Read the meta-information out of a database file. Meta[0]
6673** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00006674** through meta[15] are available for use by higher layers. Meta[0]
6675** is read-only, the others are read/write.
6676**
6677** The schema layer numbers meta values differently. At the schema
6678** layer (and the SetCookie and ReadCookie opcodes) the number of
6679** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00006680*/
danielk1977aef0bf62005-12-30 16:28:01 +00006681int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
drh1bd10f82008-12-10 21:19:56 +00006682 DbPage *pDbPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00006683 int rc;
drh4b70f112004-05-02 21:12:19 +00006684 unsigned char *pP1;
danielk1977aef0bf62005-12-30 16:28:01 +00006685 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006686
drhd677b3d2007-08-20 22:48:41 +00006687 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006688 pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006689
danielk1977da184232006-01-05 11:34:32 +00006690 /* Reading a meta-data value requires a read-lock on page 1 (and hence
6691 ** the sqlite_master table. We grab this lock regardless of whether or
6692 ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
drhc25eabe2009-02-24 18:57:31 +00006693 ** 1 is treated as a special case by querySharedCacheTableLock()
6694 ** and setSharedCacheTableLock()).
danielk1977da184232006-01-05 11:34:32 +00006695 */
drhc25eabe2009-02-24 18:57:31 +00006696 rc = querySharedCacheTableLock(p, 1, READ_LOCK);
danielk1977da184232006-01-05 11:34:32 +00006697 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00006698 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00006699 return rc;
6700 }
6701
drh23e11ca2004-05-04 17:27:28 +00006702 assert( idx>=0 && idx<=15 );
danielk1977d9f6c532008-09-19 16:39:38 +00006703 if( pBt->pPage1 ){
6704 /* The b-tree is already holding a reference to page 1 of the database
6705 ** file. In this case the required meta-data value can be read directly
6706 ** from the page data of this reference. This is slightly faster than
6707 ** requesting a new reference from the pager layer.
6708 */
6709 pP1 = (unsigned char *)pBt->pPage1->aData;
6710 }else{
6711 /* The b-tree does not have a reference to page 1 of the database file.
6712 ** Obtain one from the pager layer.
6713 */
danielk1977ea897302008-09-19 15:10:58 +00006714 rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
6715 if( rc ){
6716 sqlite3BtreeLeave(p);
6717 return rc;
6718 }
6719 pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
drhd677b3d2007-08-20 22:48:41 +00006720 }
drh23e11ca2004-05-04 17:27:28 +00006721 *pMeta = get4byte(&pP1[36 + idx*4]);
danielk1977ea897302008-09-19 15:10:58 +00006722
danielk1977d9f6c532008-09-19 16:39:38 +00006723 /* If the b-tree is not holding a reference to page 1, then one was
6724 ** requested from the pager layer in the above block. Release it now.
6725 */
danielk1977ea897302008-09-19 15:10:58 +00006726 if( !pBt->pPage1 ){
6727 sqlite3PagerUnref(pDbPage);
6728 }
drhae157872004-08-14 19:20:09 +00006729
danielk1977599fcba2004-11-08 07:13:13 +00006730 /* If autovacuumed is disabled in this build but we are trying to
6731 ** access an autovacuumed database, then make the database readonly.
6732 */
danielk1977003ba062004-11-04 02:57:33 +00006733#ifdef SQLITE_OMIT_AUTOVACUUM
drhae157872004-08-14 19:20:09 +00006734 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00006735#endif
drhae157872004-08-14 19:20:09 +00006736
danielk1977da184232006-01-05 11:34:32 +00006737 /* Grab the read-lock on page 1. */
drhc25eabe2009-02-24 18:57:31 +00006738 rc = setSharedCacheTableLock(p, 1, READ_LOCK);
drhd677b3d2007-08-20 22:48:41 +00006739 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00006740 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006741}
6742
6743/*
drh23e11ca2004-05-04 17:27:28 +00006744** Write meta-information back into the database. Meta[0] is
6745** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00006746*/
danielk1977aef0bf62005-12-30 16:28:01 +00006747int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
6748 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00006749 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00006750 int rc;
drh23e11ca2004-05-04 17:27:28 +00006751 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00006752 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006753 pBt->db = p->db;
drh64022502009-01-09 14:11:04 +00006754 assert( p->inTrans==TRANS_WRITE );
6755 assert( pBt->pPage1!=0 );
6756 pP1 = pBt->pPage1->aData;
6757 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6758 if( rc==SQLITE_OK ){
6759 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +00006760#ifndef SQLITE_OMIT_AUTOVACUUM
drh64022502009-01-09 14:11:04 +00006761 if( idx==7 ){
6762 assert( pBt->autoVacuum || iMeta==0 );
6763 assert( iMeta==0 || iMeta==1 );
6764 pBt->incrVacuum = (u8)iMeta;
drhd677b3d2007-08-20 22:48:41 +00006765 }
drh64022502009-01-09 14:11:04 +00006766#endif
drh5df72a52002-06-06 23:16:05 +00006767 }
drhd677b3d2007-08-20 22:48:41 +00006768 sqlite3BtreeLeave(p);
6769 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006770}
drh8c42ca92001-06-22 19:15:00 +00006771
drhf328bc82004-05-10 23:29:49 +00006772/*
6773** Return the flag byte at the beginning of the page that the cursor
6774** is currently pointing to.
6775*/
6776int sqlite3BtreeFlags(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00006777 /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
drha3460582008-07-11 21:02:53 +00006778 ** restoreCursorPosition() here.
danielk1977da184232006-01-05 11:34:32 +00006779 */
danielk1977e448dc42008-01-02 11:50:51 +00006780 MemPage *pPage;
drha3460582008-07-11 21:02:53 +00006781 restoreCursorPosition(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00006782 pPage = pCur->apPage[pCur->iPage];
drh1fee73e2007-08-29 04:00:57 +00006783 assert( cursorHoldsMutex(pCur) );
drh64022502009-01-09 14:11:04 +00006784 assert( pPage!=0 );
drhd0679ed2007-08-28 22:24:34 +00006785 assert( pPage->pBt==pCur->pBt );
drh64022502009-01-09 14:11:04 +00006786 return pPage->aData[pPage->hdrOffset];
drhf328bc82004-05-10 23:29:49 +00006787}
6788
danielk1977a5533162009-02-24 10:01:51 +00006789#ifndef SQLITE_OMIT_BTREECOUNT
6790/*
6791** The first argument, pCur, is a cursor opened on some b-tree. Count the
6792** number of entries in the b-tree and write the result to *pnEntry.
6793**
6794** SQLITE_OK is returned if the operation is successfully executed.
6795** Otherwise, if an error is encountered (i.e. an IO error or database
6796** corruption) an SQLite error code is returned.
6797*/
6798int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
6799 i64 nEntry = 0; /* Value to return in *pnEntry */
6800 int rc; /* Return code */
6801 rc = moveToRoot(pCur);
6802
6803 /* Unless an error occurs, the following loop runs one iteration for each
6804 ** page in the B-Tree structure (not including overflow pages).
6805 */
6806 while( rc==SQLITE_OK ){
6807 int iIdx; /* Index of child node in parent */
6808 MemPage *pPage; /* Current page of the b-tree */
6809
6810 /* If this is a leaf page or the tree is not an int-key tree, then
6811 ** this page contains countable entries. Increment the entry counter
6812 ** accordingly.
6813 */
6814 pPage = pCur->apPage[pCur->iPage];
6815 if( pPage->leaf || !pPage->intKey ){
6816 nEntry += pPage->nCell;
6817 }
6818
6819 /* pPage is a leaf node. This loop navigates the cursor so that it
6820 ** points to the first interior cell that it points to the parent of
6821 ** the next page in the tree that has not yet been visited. The
6822 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
6823 ** of the page, or to the number of cells in the page if the next page
6824 ** to visit is the right-child of its parent.
6825 **
6826 ** If all pages in the tree have been visited, return SQLITE_OK to the
6827 ** caller.
6828 */
6829 if( pPage->leaf ){
6830 do {
6831 if( pCur->iPage==0 ){
6832 /* All pages of the b-tree have been visited. Return successfully. */
6833 *pnEntry = nEntry;
6834 return SQLITE_OK;
6835 }
6836 sqlite3BtreeMoveToParent(pCur);
6837 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
6838
6839 pCur->aiIdx[pCur->iPage]++;
6840 pPage = pCur->apPage[pCur->iPage];
6841 }
6842
6843 /* Descend to the child node of the cell that the cursor currently
6844 ** points at. This is the right-child if (iIdx==pPage->nCell).
6845 */
6846 iIdx = pCur->aiIdx[pCur->iPage];
6847 if( iIdx==pPage->nCell ){
6848 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
6849 }else{
6850 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
6851 }
6852 }
6853
shanebe217792009-03-05 04:20:31 +00006854 /* An error has occurred. Return an error code. */
danielk1977a5533162009-02-24 10:01:51 +00006855 return rc;
6856}
6857#endif
drhdd793422001-06-28 01:54:48 +00006858
drhdd793422001-06-28 01:54:48 +00006859/*
drh5eddca62001-06-30 21:53:53 +00006860** Return the pager associated with a BTree. This routine is used for
6861** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00006862*/
danielk1977aef0bf62005-12-30 16:28:01 +00006863Pager *sqlite3BtreePager(Btree *p){
6864 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00006865}
drh5eddca62001-06-30 21:53:53 +00006866
drhb7f91642004-10-31 02:22:47 +00006867#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006868/*
6869** Append a message to the error message string.
6870*/
drh2e38c322004-09-03 18:38:44 +00006871static void checkAppendMsg(
6872 IntegrityCk *pCheck,
6873 char *zMsg1,
6874 const char *zFormat,
6875 ...
6876){
6877 va_list ap;
drh1dcdbc02007-01-27 02:24:54 +00006878 if( !pCheck->mxErr ) return;
6879 pCheck->mxErr--;
6880 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00006881 va_start(ap, zFormat);
drhf089aa42008-07-08 19:34:06 +00006882 if( pCheck->errMsg.nChar ){
6883 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
drh5eddca62001-06-30 21:53:53 +00006884 }
drhf089aa42008-07-08 19:34:06 +00006885 if( zMsg1 ){
6886 sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
6887 }
6888 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
6889 va_end(ap);
drhc890fec2008-08-01 20:10:08 +00006890 if( pCheck->errMsg.mallocFailed ){
6891 pCheck->mallocFailed = 1;
6892 }
drh5eddca62001-06-30 21:53:53 +00006893}
drhb7f91642004-10-31 02:22:47 +00006894#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006895
drhb7f91642004-10-31 02:22:47 +00006896#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006897/*
6898** Add 1 to the reference count for page iPage. If this is the second
6899** reference to the page, add an error message to pCheck->zErrMsg.
6900** Return 1 if there are 2 ore more references to the page and 0 if
6901** if this is the first reference to the page.
6902**
6903** Also check that the page number is in bounds.
6904*/
danielk197789d40042008-11-17 14:20:56 +00006905static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00006906 if( iPage==0 ) return 1;
danielk197789d40042008-11-17 14:20:56 +00006907 if( iPage>pCheck->nPage ){
drh2e38c322004-09-03 18:38:44 +00006908 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006909 return 1;
6910 }
6911 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00006912 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006913 return 1;
6914 }
6915 return (pCheck->anRef[iPage]++)>1;
6916}
6917
danielk1977afcdd022004-10-31 16:25:42 +00006918#ifndef SQLITE_OMIT_AUTOVACUUM
6919/*
6920** Check that the entry in the pointer-map for page iChild maps to
6921** page iParent, pointer type ptrType. If not, append an error message
6922** to pCheck.
6923*/
6924static void checkPtrmap(
6925 IntegrityCk *pCheck, /* Integrity check context */
6926 Pgno iChild, /* Child page number */
6927 u8 eType, /* Expected pointer map type */
6928 Pgno iParent, /* Expected pointer map parent page number */
6929 char *zContext /* Context description (used for error msg) */
6930){
6931 int rc;
6932 u8 ePtrmapType;
6933 Pgno iPtrmapParent;
6934
6935 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
6936 if( rc!=SQLITE_OK ){
drhe43ba702008-12-05 22:40:08 +00006937 if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
danielk1977afcdd022004-10-31 16:25:42 +00006938 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
6939 return;
6940 }
6941
6942 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
6943 checkAppendMsg(pCheck, zContext,
6944 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
6945 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
6946 }
6947}
6948#endif
6949
drh5eddca62001-06-30 21:53:53 +00006950/*
6951** Check the integrity of the freelist or of an overflow page list.
6952** Verify that the number of pages on the list is N.
6953*/
drh30e58752002-03-02 20:41:57 +00006954static void checkList(
6955 IntegrityCk *pCheck, /* Integrity checking context */
6956 int isFreeList, /* True for a freelist. False for overflow page list */
6957 int iPage, /* Page number for first page in the list */
6958 int N, /* Expected number of pages in the list */
6959 char *zContext /* Context for error messages */
6960){
6961 int i;
drh3a4c1412004-05-09 20:40:11 +00006962 int expected = N;
6963 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00006964 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00006965 DbPage *pOvflPage;
6966 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00006967 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00006968 checkAppendMsg(pCheck, zContext,
6969 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00006970 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00006971 break;
6972 }
6973 if( checkRef(pCheck, iPage, zContext) ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00006974 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
drh2e38c322004-09-03 18:38:44 +00006975 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006976 break;
6977 }
danielk19773b8a05f2007-03-19 17:44:26 +00006978 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00006979 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00006980 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00006981#ifndef SQLITE_OMIT_AUTOVACUUM
6982 if( pCheck->pBt->autoVacuum ){
6983 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
6984 }
6985#endif
drh45b1fac2008-07-04 17:52:42 +00006986 if( n>pCheck->pBt->usableSize/4-2 ){
drh2e38c322004-09-03 18:38:44 +00006987 checkAppendMsg(pCheck, zContext,
6988 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00006989 N--;
6990 }else{
6991 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00006992 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00006993#ifndef SQLITE_OMIT_AUTOVACUUM
6994 if( pCheck->pBt->autoVacuum ){
6995 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
6996 }
6997#endif
6998 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00006999 }
7000 N -= n;
drh30e58752002-03-02 20:41:57 +00007001 }
drh30e58752002-03-02 20:41:57 +00007002 }
danielk1977afcdd022004-10-31 16:25:42 +00007003#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00007004 else{
7005 /* If this database supports auto-vacuum and iPage is not the last
7006 ** page in this overflow list, check that the pointer-map entry for
7007 ** the following page matches iPage.
7008 */
7009 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00007010 i = get4byte(pOvflData);
danielk1977687566d2004-11-02 12:56:41 +00007011 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
7012 }
danielk1977afcdd022004-10-31 16:25:42 +00007013 }
7014#endif
danielk19773b8a05f2007-03-19 17:44:26 +00007015 iPage = get4byte(pOvflData);
7016 sqlite3PagerUnref(pOvflPage);
drh5eddca62001-06-30 21:53:53 +00007017 }
7018}
drhb7f91642004-10-31 02:22:47 +00007019#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00007020
drhb7f91642004-10-31 02:22:47 +00007021#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007022/*
7023** Do various sanity checks on a single page of a tree. Return
7024** the tree depth. Root pages return 0. Parents of root pages
7025** return 1, and so forth.
7026**
7027** These checks are done:
7028**
7029** 1. Make sure that cells and freeblocks do not overlap
7030** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00007031** NO 2. Make sure cell keys are in order.
7032** NO 3. Make sure no key is less than or equal to zLowerBound.
7033** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00007034** 5. Check the integrity of overflow pages.
7035** 6. Recursively call checkTreePage on all children.
7036** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00007037** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00007038** the root of the tree.
7039*/
7040static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00007041 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00007042 int iPage, /* Page number of the page to check */
drh74161702006-02-24 02:53:49 +00007043 char *zParentContext /* Parent context */
drh5eddca62001-06-30 21:53:53 +00007044){
7045 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00007046 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00007047 int hdr, cellStart;
7048 int nCell;
drhda200cc2004-05-09 11:51:38 +00007049 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00007050 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00007051 int usableSize;
drh5eddca62001-06-30 21:53:53 +00007052 char zContext[100];
shane0af3f892008-11-12 04:55:34 +00007053 char *hit = 0;
drh5eddca62001-06-30 21:53:53 +00007054
drh5bb3eb92007-05-04 13:15:55 +00007055 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
danielk1977ef73ee92004-11-06 12:26:07 +00007056
drh5eddca62001-06-30 21:53:53 +00007057 /* Check that the page exists
7058 */
drhd9cb6ac2005-10-20 07:28:17 +00007059 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00007060 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00007061 if( iPage==0 ) return 0;
7062 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh16a9b832007-05-05 18:39:25 +00007063 if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drhe43ba702008-12-05 22:40:08 +00007064 if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
drh2e38c322004-09-03 18:38:44 +00007065 checkAppendMsg(pCheck, zContext,
7066 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00007067 return 0;
7068 }
danielk197771d5d2c2008-09-29 11:49:47 +00007069 if( (rc = sqlite3BtreeInitPage(pPage))!=0 ){
drh64022502009-01-09 14:11:04 +00007070 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
drh16a9b832007-05-05 18:39:25 +00007071 checkAppendMsg(pCheck, zContext,
7072 "sqlite3BtreeInitPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00007073 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00007074 return 0;
7075 }
7076
7077 /* Check out all the cells.
7078 */
7079 depth = 0;
drh1dcdbc02007-01-27 02:24:54 +00007080 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
drh6f11bef2004-05-13 01:12:56 +00007081 u8 *pCell;
danielk197789d40042008-11-17 14:20:56 +00007082 u32 sz;
drh6f11bef2004-05-13 01:12:56 +00007083 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00007084
7085 /* Check payload overflow pages
7086 */
drh5bb3eb92007-05-04 13:15:55 +00007087 sqlite3_snprintf(sizeof(zContext), zContext,
7088 "On tree page %d cell %d: ", iPage, i);
danielk19771cc5ed82007-05-16 17:28:43 +00007089 pCell = findCell(pPage,i);
drh16a9b832007-05-05 18:39:25 +00007090 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00007091 sz = info.nData;
drhf49661a2008-12-10 16:45:50 +00007092 if( !pPage->intKey ) sz += (int)info.nKey;
drh72365832007-03-06 15:53:44 +00007093 assert( sz==info.nPayload );
drh6f11bef2004-05-13 01:12:56 +00007094 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00007095 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00007096 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
7097#ifndef SQLITE_OMIT_AUTOVACUUM
7098 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00007099 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00007100 }
7101#endif
7102 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00007103 }
7104
7105 /* Check sanity of left child page.
7106 */
drhda200cc2004-05-09 11:51:38 +00007107 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00007108 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00007109#ifndef SQLITE_OMIT_AUTOVACUUM
7110 if( pBt->autoVacuum ){
7111 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
7112 }
7113#endif
danielk197762c14b32008-11-19 09:05:26 +00007114 d2 = checkTreePage(pCheck, pgno, zContext);
drhda200cc2004-05-09 11:51:38 +00007115 if( i>0 && d2!=depth ){
7116 checkAppendMsg(pCheck, zContext, "Child page depth differs");
7117 }
7118 depth = d2;
drh5eddca62001-06-30 21:53:53 +00007119 }
drh5eddca62001-06-30 21:53:53 +00007120 }
drhda200cc2004-05-09 11:51:38 +00007121 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00007122 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh5bb3eb92007-05-04 13:15:55 +00007123 sqlite3_snprintf(sizeof(zContext), zContext,
7124 "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00007125#ifndef SQLITE_OMIT_AUTOVACUUM
7126 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00007127 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00007128 }
7129#endif
danielk197762c14b32008-11-19 09:05:26 +00007130 checkTreePage(pCheck, pgno, zContext);
drhda200cc2004-05-09 11:51:38 +00007131 }
drh5eddca62001-06-30 21:53:53 +00007132
7133 /* Check for complete coverage of the page
7134 */
drhda200cc2004-05-09 11:51:38 +00007135 data = pPage->aData;
7136 hdr = pPage->hdrOffset;
drhf7141992008-06-19 00:16:08 +00007137 hit = sqlite3PageMalloc( pBt->pageSize );
drhc890fec2008-08-01 20:10:08 +00007138 if( hit==0 ){
7139 pCheck->mallocFailed = 1;
7140 }else{
shane5780ebd2008-11-11 17:36:30 +00007141 u16 contentOffset = get2byte(&data[hdr+5]);
7142 if (contentOffset > usableSize) {
7143 checkAppendMsg(pCheck, 0,
7144 "Corruption detected in header on page %d",iPage,0);
shane0af3f892008-11-12 04:55:34 +00007145 goto check_page_abort;
shane5780ebd2008-11-11 17:36:30 +00007146 }
7147 memset(hit+contentOffset, 0, usableSize-contentOffset);
7148 memset(hit, 1, contentOffset);
drh2e38c322004-09-03 18:38:44 +00007149 nCell = get2byte(&data[hdr+3]);
7150 cellStart = hdr + 12 - 4*pPage->leaf;
7151 for(i=0; i<nCell; i++){
7152 int pc = get2byte(&data[cellStart+i*2]);
danielk1977daca5432008-08-25 11:57:16 +00007153 u16 size = 1024;
drh2e38c322004-09-03 18:38:44 +00007154 int j;
danielk1977daca5432008-08-25 11:57:16 +00007155 if( pc<=usableSize ){
7156 size = cellSizePtr(pPage, &data[pc]);
7157 }
danielk19777701e812005-01-10 12:59:51 +00007158 if( (pc+size-1)>=usableSize || pc<0 ){
7159 checkAppendMsg(pCheck, 0,
7160 "Corruption detected in cell %d on page %d",i,iPage,0);
7161 }else{
7162 for(j=pc+size-1; j>=pc; j--) hit[j]++;
7163 }
drh2e38c322004-09-03 18:38:44 +00007164 }
7165 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
7166 cnt++){
7167 int size = get2byte(&data[i+2]);
7168 int j;
danielk19777701e812005-01-10 12:59:51 +00007169 if( (i+size-1)>=usableSize || i<0 ){
7170 checkAppendMsg(pCheck, 0,
7171 "Corruption detected in cell %d on page %d",i,iPage,0);
7172 }else{
7173 for(j=i+size-1; j>=i; j--) hit[j]++;
7174 }
drh2e38c322004-09-03 18:38:44 +00007175 i = get2byte(&data[i]);
7176 }
7177 for(i=cnt=0; i<usableSize; i++){
7178 if( hit[i]==0 ){
7179 cnt++;
7180 }else if( hit[i]>1 ){
7181 checkAppendMsg(pCheck, 0,
7182 "Multiple uses for byte %d of page %d", i, iPage);
7183 break;
7184 }
7185 }
7186 if( cnt!=data[hdr+7] ){
7187 checkAppendMsg(pCheck, 0,
7188 "Fragmented space is %d byte reported as %d on page %d",
7189 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00007190 }
7191 }
shane0af3f892008-11-12 04:55:34 +00007192check_page_abort:
7193 if (hit) sqlite3PageFree(hit);
drh6019e162001-07-02 17:51:45 +00007194
drh4b70f112004-05-02 21:12:19 +00007195 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00007196 return depth+1;
drh5eddca62001-06-30 21:53:53 +00007197}
drhb7f91642004-10-31 02:22:47 +00007198#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00007199
drhb7f91642004-10-31 02:22:47 +00007200#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007201/*
7202** This routine does a complete check of the given BTree file. aRoot[] is
7203** an array of pages numbers were each page number is the root page of
7204** a table. nRoot is the number of entries in aRoot.
7205**
drhc890fec2008-08-01 20:10:08 +00007206** Write the number of error seen in *pnErr. Except for some memory
drhe43ba702008-12-05 22:40:08 +00007207** allocation errors, an error message held in memory obtained from
drhc890fec2008-08-01 20:10:08 +00007208** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
drhe43ba702008-12-05 22:40:08 +00007209** returned. If a memory allocation error occurs, NULL is returned.
drh5eddca62001-06-30 21:53:53 +00007210*/
drh1dcdbc02007-01-27 02:24:54 +00007211char *sqlite3BtreeIntegrityCheck(
7212 Btree *p, /* The btree to be checked */
7213 int *aRoot, /* An array of root pages numbers for individual trees */
7214 int nRoot, /* Number of entries in aRoot[] */
7215 int mxErr, /* Stop reporting errors after this many */
7216 int *pnErr /* Write number of errors seen to this variable */
7217){
danielk197789d40042008-11-17 14:20:56 +00007218 Pgno i;
drh5eddca62001-06-30 21:53:53 +00007219 int nRef;
drhaaab5722002-02-19 13:39:21 +00007220 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00007221 BtShared *pBt = p->pBt;
drhf089aa42008-07-08 19:34:06 +00007222 char zErr[100];
drh5eddca62001-06-30 21:53:53 +00007223
drhd677b3d2007-08-20 22:48:41 +00007224 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00007225 pBt->db = p->db;
danielk19773b8a05f2007-03-19 17:44:26 +00007226 nRef = sqlite3PagerRefcount(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00007227 if( lockBtreeWithRetry(p)!=SQLITE_OK ){
drhc890fec2008-08-01 20:10:08 +00007228 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00007229 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00007230 return sqlite3DbStrDup(0, "cannot acquire a read lock on the database");
drhefc251d2001-07-01 22:12:01 +00007231 }
drh5eddca62001-06-30 21:53:53 +00007232 sCheck.pBt = pBt;
7233 sCheck.pPager = pBt->pPager;
danielk197789d40042008-11-17 14:20:56 +00007234 sCheck.nPage = pagerPagecount(sCheck.pBt);
drh1dcdbc02007-01-27 02:24:54 +00007235 sCheck.mxErr = mxErr;
7236 sCheck.nErr = 0;
drhc890fec2008-08-01 20:10:08 +00007237 sCheck.mallocFailed = 0;
drh1dcdbc02007-01-27 02:24:54 +00007238 *pnErr = 0;
drh0de8c112002-07-06 16:32:14 +00007239 if( sCheck.nPage==0 ){
7240 unlockBtreeIfUnused(pBt);
drhd677b3d2007-08-20 22:48:41 +00007241 sqlite3BtreeLeave(p);
drh0de8c112002-07-06 16:32:14 +00007242 return 0;
7243 }
drhe5ae5732008-06-15 02:51:47 +00007244 sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00007245 if( !sCheck.anRef ){
7246 unlockBtreeIfUnused(pBt);
drh1dcdbc02007-01-27 02:24:54 +00007247 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00007248 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00007249 return 0;
danielk1977ac245ec2005-01-14 13:50:11 +00007250 }
drhda200cc2004-05-09 11:51:38 +00007251 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00007252 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00007253 if( i<=sCheck.nPage ){
7254 sCheck.anRef[i] = 1;
7255 }
drhf089aa42008-07-08 19:34:06 +00007256 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
drh5eddca62001-06-30 21:53:53 +00007257
7258 /* Check the integrity of the freelist
7259 */
drha34b6762004-05-07 13:30:42 +00007260 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
7261 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00007262
7263 /* Check all the tables.
7264 */
danielk197789d40042008-11-17 14:20:56 +00007265 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
drh4ff6dfa2002-03-03 23:06:00 +00007266 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00007267#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00007268 if( pBt->autoVacuum && aRoot[i]>1 ){
7269 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
7270 }
7271#endif
danielk197762c14b32008-11-19 09:05:26 +00007272 checkTreePage(&sCheck, aRoot[i], "List of tree roots: ");
drh5eddca62001-06-30 21:53:53 +00007273 }
7274
7275 /* Make sure every page in the file is referenced
7276 */
drh1dcdbc02007-01-27 02:24:54 +00007277 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00007278#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00007279 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00007280 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00007281 }
danielk1977afcdd022004-10-31 16:25:42 +00007282#else
7283 /* If the database supports auto-vacuum, make sure no tables contain
7284 ** references to pointer-map pages.
7285 */
7286 if( sCheck.anRef[i]==0 &&
danielk1977266664d2006-02-10 08:24:21 +00007287 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00007288 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
7289 }
7290 if( sCheck.anRef[i]!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00007291 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00007292 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
7293 }
7294#endif
drh5eddca62001-06-30 21:53:53 +00007295 }
7296
drh64022502009-01-09 14:11:04 +00007297 /* Make sure this analysis did not leave any unref() pages.
7298 ** This is an internal consistency check; an integrity check
7299 ** of the integrity check.
drh5eddca62001-06-30 21:53:53 +00007300 */
drh5e00f6c2001-09-13 13:46:56 +00007301 unlockBtreeIfUnused(pBt);
drh64022502009-01-09 14:11:04 +00007302 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
drh2e38c322004-09-03 18:38:44 +00007303 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00007304 "Outstanding page count goes from %d to %d during this analysis",
danielk19773b8a05f2007-03-19 17:44:26 +00007305 nRef, sqlite3PagerRefcount(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00007306 );
drh5eddca62001-06-30 21:53:53 +00007307 }
7308
7309 /* Clean up and report errors.
7310 */
drhd677b3d2007-08-20 22:48:41 +00007311 sqlite3BtreeLeave(p);
drh17435752007-08-16 04:30:38 +00007312 sqlite3_free(sCheck.anRef);
drhc890fec2008-08-01 20:10:08 +00007313 if( sCheck.mallocFailed ){
7314 sqlite3StrAccumReset(&sCheck.errMsg);
7315 *pnErr = sCheck.nErr+1;
7316 return 0;
7317 }
drh1dcdbc02007-01-27 02:24:54 +00007318 *pnErr = sCheck.nErr;
drhf089aa42008-07-08 19:34:06 +00007319 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
7320 return sqlite3StrAccumFinish(&sCheck.errMsg);
drh5eddca62001-06-30 21:53:53 +00007321}
drhb7f91642004-10-31 02:22:47 +00007322#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00007323
drh73509ee2003-04-06 20:44:45 +00007324/*
7325** Return the full pathname of the underlying database file.
drhd0679ed2007-08-28 22:24:34 +00007326**
7327** The pager filename is invariant as long as the pager is
7328** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +00007329*/
danielk1977aef0bf62005-12-30 16:28:01 +00007330const char *sqlite3BtreeGetFilename(Btree *p){
7331 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007332 return sqlite3PagerFilename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00007333}
7334
7335/*
danielk19775865e3d2004-06-14 06:03:57 +00007336** Return the pathname of the journal file for this database. The return
7337** value of this routine is the same regardless of whether the journal file
7338** has been created or not.
drhd0679ed2007-08-28 22:24:34 +00007339**
7340** The pager journal filename is invariant as long as the pager is
7341** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00007342*/
danielk1977aef0bf62005-12-30 16:28:01 +00007343const char *sqlite3BtreeGetJournalname(Btree *p){
7344 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007345 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00007346}
7347
danielk19771d850a72004-05-31 08:26:49 +00007348/*
7349** Return non-zero if a transaction is active.
7350*/
danielk1977aef0bf62005-12-30 16:28:01 +00007351int sqlite3BtreeIsInTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00007352 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00007353 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00007354}
7355
7356/*
danielk19772372c2b2006-06-27 16:34:56 +00007357** Return non-zero if a read (or write) transaction is active.
7358*/
7359int sqlite3BtreeIsInReadTrans(Btree *p){
drh64022502009-01-09 14:11:04 +00007360 assert( p );
drhe5fe6902007-12-07 18:55:28 +00007361 assert( sqlite3_mutex_held(p->db->mutex) );
drh64022502009-01-09 14:11:04 +00007362 return p->inTrans!=TRANS_NONE;
danielk19772372c2b2006-06-27 16:34:56 +00007363}
7364
danielk197704103022009-02-03 16:51:24 +00007365int sqlite3BtreeIsInBackup(Btree *p){
7366 assert( p );
7367 assert( sqlite3_mutex_held(p->db->mutex) );
7368 return p->nBackup!=0;
7369}
7370
danielk19772372c2b2006-06-27 16:34:56 +00007371/*
danielk1977da184232006-01-05 11:34:32 +00007372** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +00007373** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +00007374** purposes (for example, to store a high-level schema associated with
7375** the shared-btree). The btree layer manages reference counting issues.
7376**
7377** The first time this is called on a shared-btree, nBytes bytes of memory
7378** are allocated, zeroed, and returned to the caller. For each subsequent
7379** call the nBytes parameter is ignored and a pointer to the same blob
7380** of memory returned.
7381**
danielk1977171bfed2008-06-23 09:50:50 +00007382** If the nBytes parameter is 0 and the blob of memory has not yet been
7383** allocated, a null pointer is returned. If the blob has already been
7384** allocated, it is returned as normal.
7385**
danielk1977da184232006-01-05 11:34:32 +00007386** Just before the shared-btree is closed, the function passed as the
7387** xFree argument when the memory allocation was made is invoked on the
drh17435752007-08-16 04:30:38 +00007388** blob of allocated memory. This function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +00007389** on the memory, the btree layer does that.
7390*/
7391void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
7392 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +00007393 sqlite3BtreeEnter(p);
danielk1977171bfed2008-06-23 09:50:50 +00007394 if( !pBt->pSchema && nBytes ){
drh17435752007-08-16 04:30:38 +00007395 pBt->pSchema = sqlite3MallocZero(nBytes);
danielk1977da184232006-01-05 11:34:32 +00007396 pBt->xFreeSchema = xFree;
7397 }
drh27641702007-08-22 02:56:42 +00007398 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00007399 return pBt->pSchema;
7400}
7401
danielk1977c87d34d2006-01-06 13:00:28 +00007402/*
danielk1977404ca072009-03-16 13:19:36 +00007403** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
7404** btree as the argument handle holds an exclusive lock on the
7405** sqlite_master table. Otherwise SQLITE_OK.
danielk1977c87d34d2006-01-06 13:00:28 +00007406*/
7407int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +00007408 int rc;
drhe5fe6902007-12-07 18:55:28 +00007409 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +00007410 sqlite3BtreeEnter(p);
danielk1977404ca072009-03-16 13:19:36 +00007411 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
7412 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
drh27641702007-08-22 02:56:42 +00007413 sqlite3BtreeLeave(p);
7414 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +00007415}
7416
drha154dcd2006-03-22 22:10:07 +00007417
7418#ifndef SQLITE_OMIT_SHARED_CACHE
7419/*
7420** Obtain a lock on the table whose root page is iTab. The
7421** lock is a write lock if isWritelock is true or a read lock
7422** if it is false.
7423*/
danielk1977c00da102006-01-07 13:21:04 +00007424int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00007425 int rc = SQLITE_OK;
drh6a9ad3d2008-04-02 16:29:30 +00007426 if( p->sharable ){
7427 u8 lockType = READ_LOCK + isWriteLock;
7428 assert( READ_LOCK+1==WRITE_LOCK );
7429 assert( isWriteLock==0 || isWriteLock==1 );
7430 sqlite3BtreeEnter(p);
drhc25eabe2009-02-24 18:57:31 +00007431 rc = querySharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00007432 if( rc==SQLITE_OK ){
drhc25eabe2009-02-24 18:57:31 +00007433 rc = setSharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00007434 }
7435 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +00007436 }
7437 return rc;
7438}
drha154dcd2006-03-22 22:10:07 +00007439#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00007440
danielk1977b4e9af92007-05-01 17:49:49 +00007441#ifndef SQLITE_OMIT_INCRBLOB
7442/*
7443** Argument pCsr must be a cursor opened for writing on an
7444** INTKEY table currently pointing at a valid table entry.
7445** This function modifies the data stored as part of that entry.
7446** Only the data content may only be modified, it is not possible
7447** to change the length of the data stored.
7448*/
danielk1977dcbb5d32007-05-04 18:36:44 +00007449int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
danielk1977404ca072009-03-16 13:19:36 +00007450 int rc;
7451
drh1fee73e2007-08-29 04:00:57 +00007452 assert( cursorHoldsMutex(pCsr) );
drhe5fe6902007-12-07 18:55:28 +00007453 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00007454 assert(pCsr->isIncrblobHandle);
danielk19773588ceb2008-06-10 17:30:26 +00007455
drha3460582008-07-11 21:02:53 +00007456 restoreCursorPosition(pCsr);
danielk19773588ceb2008-06-10 17:30:26 +00007457 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
7458 if( pCsr->eState!=CURSOR_VALID ){
7459 return SQLITE_ABORT;
danielk1977dcbb5d32007-05-04 18:36:44 +00007460 }
7461
danielk1977d04417962007-05-02 13:16:30 +00007462 /* Check some preconditions:
danielk1977dcbb5d32007-05-04 18:36:44 +00007463 ** (a) the cursor is open for writing,
7464 ** (b) there is no read-lock on the table being modified and
7465 ** (c) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00007466 */
danielk1977d04417962007-05-02 13:16:30 +00007467 if( !pCsr->wrFlag ){
danielk1977dcbb5d32007-05-04 18:36:44 +00007468 return SQLITE_READONLY;
danielk1977d04417962007-05-02 13:16:30 +00007469 }
drhd0679ed2007-08-28 22:24:34 +00007470 assert( !pCsr->pBt->readOnly
7471 && pCsr->pBt->inTransaction==TRANS_WRITE );
danielk1977404ca072009-03-16 13:19:36 +00007472 rc = checkForReadConflicts(pCsr->pBtree, pCsr->pgnoRoot, pCsr, 0);
7473 if( rc!=SQLITE_OK ){
7474 /* The table pCur points to has a read lock */
7475 assert( rc==SQLITE_LOCKED_SHAREDCACHE );
7476 return rc;
danielk1977d04417962007-05-02 13:16:30 +00007477 }
danielk197771d5d2c2008-09-29 11:49:47 +00007478 if( pCsr->eState==CURSOR_INVALID || !pCsr->apPage[pCsr->iPage]->intKey ){
danielk1977d04417962007-05-02 13:16:30 +00007479 return SQLITE_ERROR;
danielk1977b4e9af92007-05-01 17:49:49 +00007480 }
7481
danielk19779f8d6402007-05-02 17:48:45 +00007482 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00007483}
danielk19772dec9702007-05-02 16:48:37 +00007484
7485/*
7486** Set a flag on this cursor to cache the locations of pages from the
danielk1977da107192007-05-04 08:32:13 +00007487** overflow list for the current row. This is used by cursors opened
7488** for incremental blob IO only.
7489**
7490** This function sets a flag only. The actual page location cache
7491** (stored in BtCursor.aOverflow[]) is allocated and used by function
7492** accessPayload() (the worker function for sqlite3BtreeData() and
7493** sqlite3BtreePutData()).
danielk19772dec9702007-05-02 16:48:37 +00007494*/
7495void sqlite3BtreeCacheOverflow(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00007496 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00007497 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00007498 assert(!pCur->isIncrblobHandle);
danielk19772dec9702007-05-02 16:48:37 +00007499 assert(!pCur->aOverflow);
danielk1977dcbb5d32007-05-04 18:36:44 +00007500 pCur->isIncrblobHandle = 1;
danielk19772dec9702007-05-02 16:48:37 +00007501}
danielk1977b4e9af92007-05-01 17:49:49 +00007502#endif