blob: 18529495c208c4ceafbef09908e2bd70c3eff27e [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*************************************************************************
drhc25eabe2009-02-24 18:57:31 +000012** $Id: btree.c,v 1.569 2009/02/24 18:57:32 drh 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*/
danielk19773588ceb2008-06-10 17:30:26 +000071static int checkReadLocks(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 */
112 if( pBt->pExclusive && pBt->pExclusive!=p ){
113 return SQLITE_LOCKED;
114 }
115
drhc25eabe2009-02-24 18:57:31 +0000116 /* This (along with setSharedCacheTableLock()) is where
117 ** the ReadUncommitted flag is dealt with.
118 ** If the caller is querying for a read-lock on any table
drhc74d0b1d2009-02-24 16:18:05 +0000119 ** other than the sqlite_master table (table 1) and if the ReadUncommitted
120 ** flag is set, then the lock granted even if there are write-locks
danielk1977da184232006-01-05 11:34:32 +0000121 ** on the table. If a write-lock is requested, the ReadUncommitted flag
122 ** is not considered.
123 **
drhc25eabe2009-02-24 18:57:31 +0000124 ** In function setSharedCacheTableLock(), if a read-lock is demanded and the
danielk1977da184232006-01-05 11:34:32 +0000125 ** ReadUncommitted flag is set, no entry is added to the locks list
126 ** (BtShared.pLock).
127 **
drhc74d0b1d2009-02-24 16:18:05 +0000128 ** To summarize: If the ReadUncommitted flag is set, then read cursors
129 ** on non-schema tables do not create or respect table locks. The locking
130 ** procedure for a write-cursor does not change.
danielk1977da184232006-01-05 11:34:32 +0000131 */
132 if(
drhe5fe6902007-12-07 18:55:28 +0000133 0==(p->db->flags&SQLITE_ReadUncommitted) ||
danielk1977da184232006-01-05 11:34:32 +0000134 eLock==WRITE_LOCK ||
drh47ded162006-01-06 01:42:58 +0000135 iTab==MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000136 ){
137 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
138 if( pIter->pBtree!=p && pIter->iTable==iTab &&
139 (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
danielk1977c87d34d2006-01-06 13:00:28 +0000140 return SQLITE_LOCKED;
danielk1977da184232006-01-05 11:34:32 +0000141 }
danielk1977aef0bf62005-12-30 16:28:01 +0000142 }
143 }
144 return SQLITE_OK;
145}
drhe53831d2007-08-17 01:14:38 +0000146#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000147
drhe53831d2007-08-17 01:14:38 +0000148#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000149/*
150** Add a lock on the table with root-page iTable to the shared-btree used
151** by Btree handle p. Parameter eLock must be either READ_LOCK or
152** WRITE_LOCK.
153**
154** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
155** SQLITE_NOMEM may also be returned.
156*/
drhc25eabe2009-02-24 18:57:31 +0000157static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
danielk1977aef0bf62005-12-30 16:28:01 +0000158 BtShared *pBt = p->pBt;
159 BtLock *pLock = 0;
160 BtLock *pIter;
161
drh1fee73e2007-08-29 04:00:57 +0000162 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000163 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
164 assert( p->db!=0 );
drhd677b3d2007-08-20 22:48:41 +0000165
danielk1977da184232006-01-05 11:34:32 +0000166 /* This is a no-op if the shared-cache is not enabled */
drhe53831d2007-08-17 01:14:38 +0000167 if( !p->sharable ){
danielk1977da184232006-01-05 11:34:32 +0000168 return SQLITE_OK;
169 }
170
drhc25eabe2009-02-24 18:57:31 +0000171 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
danielk1977aef0bf62005-12-30 16:28:01 +0000172
drhc74d0b1d2009-02-24 16:18:05 +0000173 /* If the read-uncommitted flag is set and a read-lock is requested on
174 ** a non-schema table, then the lock is always granted. Return early
175 ** without adding an entry to the BtShared.pLock list. See
drhc25eabe2009-02-24 18:57:31 +0000176 ** comment in function querySharedCacheTableLock() for more info
177 ** on handling the ReadUncommitted flag.
danielk1977da184232006-01-05 11:34:32 +0000178 */
179 if(
drhe5fe6902007-12-07 18:55:28 +0000180 (p->db->flags&SQLITE_ReadUncommitted) &&
danielk1977da184232006-01-05 11:34:32 +0000181 (eLock==READ_LOCK) &&
drh47ded162006-01-06 01:42:58 +0000182 iTable!=MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000183 ){
184 return SQLITE_OK;
185 }
186
danielk1977aef0bf62005-12-30 16:28:01 +0000187 /* First search the list for an existing lock on this table. */
188 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
189 if( pIter->iTable==iTable && pIter->pBtree==p ){
190 pLock = pIter;
191 break;
192 }
193 }
194
195 /* If the above search did not find a BtLock struct associating Btree p
196 ** with table iTable, allocate one and link it into the list.
197 */
198 if( !pLock ){
drh17435752007-08-16 04:30:38 +0000199 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
danielk1977aef0bf62005-12-30 16:28:01 +0000200 if( !pLock ){
201 return SQLITE_NOMEM;
202 }
203 pLock->iTable = iTable;
204 pLock->pBtree = p;
205 pLock->pNext = pBt->pLock;
206 pBt->pLock = pLock;
207 }
208
209 /* Set the BtLock.eLock variable to the maximum of the current lock
210 ** and the requested lock. This means if a write-lock was already held
211 ** and a read-lock requested, we don't incorrectly downgrade the lock.
212 */
213 assert( WRITE_LOCK>READ_LOCK );
danielk19775118b912005-12-30 16:31:53 +0000214 if( eLock>pLock->eLock ){
215 pLock->eLock = eLock;
216 }
danielk1977aef0bf62005-12-30 16:28:01 +0000217
218 return SQLITE_OK;
219}
drhe53831d2007-08-17 01:14:38 +0000220#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000221
drhe53831d2007-08-17 01:14:38 +0000222#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000223/*
drhc25eabe2009-02-24 18:57:31 +0000224** Release all the table locks (locks obtained via calls to
225** the setSharedCacheTableLock() procedure) held by Btree handle p.
danielk1977aef0bf62005-12-30 16:28:01 +0000226*/
drhc25eabe2009-02-24 18:57:31 +0000227static void clearAllSharedCacheTableLocks(Btree *p){
danielk1977641b0f42007-12-21 04:47:25 +0000228 BtShared *pBt = p->pBt;
229 BtLock **ppIter = &pBt->pLock;
danielk1977da184232006-01-05 11:34:32 +0000230
drh1fee73e2007-08-29 04:00:57 +0000231 assert( sqlite3BtreeHoldsMutex(p) );
drhe53831d2007-08-17 01:14:38 +0000232 assert( p->sharable || 0==*ppIter );
danielk1977da184232006-01-05 11:34:32 +0000233
danielk1977aef0bf62005-12-30 16:28:01 +0000234 while( *ppIter ){
235 BtLock *pLock = *ppIter;
danielk1977641b0f42007-12-21 04:47:25 +0000236 assert( pBt->pExclusive==0 || pBt->pExclusive==pLock->pBtree );
danielk1977aef0bf62005-12-30 16:28:01 +0000237 if( pLock->pBtree==p ){
238 *ppIter = pLock->pNext;
drh17435752007-08-16 04:30:38 +0000239 sqlite3_free(pLock);
danielk1977aef0bf62005-12-30 16:28:01 +0000240 }else{
241 ppIter = &pLock->pNext;
242 }
243 }
danielk1977641b0f42007-12-21 04:47:25 +0000244
245 if( pBt->pExclusive==p ){
246 pBt->pExclusive = 0;
247 }
danielk1977aef0bf62005-12-30 16:28:01 +0000248}
249#endif /* SQLITE_OMIT_SHARED_CACHE */
250
drh980b1a72006-08-16 16:42:48 +0000251static void releasePage(MemPage *pPage); /* Forward reference */
252
drh1fee73e2007-08-29 04:00:57 +0000253/*
254** Verify that the cursor holds a mutex on the BtShared
255*/
256#ifndef NDEBUG
257static int cursorHoldsMutex(BtCursor *p){
drhff0587c2007-08-29 17:43:19 +0000258 return sqlite3_mutex_held(p->pBt->mutex);
drh1fee73e2007-08-29 04:00:57 +0000259}
260#endif
261
262
danielk197792d4d7a2007-05-04 12:05:56 +0000263#ifndef SQLITE_OMIT_INCRBLOB
264/*
265** Invalidate the overflow page-list cache for cursor pCur, if any.
266*/
267static void invalidateOverflowCache(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000268 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000269 sqlite3_free(pCur->aOverflow);
danielk197792d4d7a2007-05-04 12:05:56 +0000270 pCur->aOverflow = 0;
271}
272
273/*
274** Invalidate the overflow page-list cache for all cursors opened
275** on the shared btree structure pBt.
276*/
277static void invalidateAllOverflowCache(BtShared *pBt){
278 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000279 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +0000280 for(p=pBt->pCursor; p; p=p->pNext){
281 invalidateOverflowCache(p);
282 }
283}
284#else
285 #define invalidateOverflowCache(x)
286 #define invalidateAllOverflowCache(x)
287#endif
288
drh980b1a72006-08-16 16:42:48 +0000289/*
danielk1977bea2a942009-01-20 17:06:27 +0000290** Set bit pgno of the BtShared.pHasContent bitvec. This is called
291** when a page that previously contained data becomes a free-list leaf
292** page.
293**
294** The BtShared.pHasContent bitvec exists to work around an obscure
295** bug caused by the interaction of two useful IO optimizations surrounding
296** free-list leaf pages:
297**
298** 1) When all data is deleted from a page and the page becomes
299** a free-list leaf page, the page is not written to the database
300** (as free-list leaf pages contain no meaningful data). Sometimes
301** such a page is not even journalled (as it will not be modified,
302** why bother journalling it?).
303**
304** 2) When a free-list leaf page is reused, its content is not read
305** from the database or written to the journal file (why should it
306** be, if it is not at all meaningful?).
307**
308** By themselves, these optimizations work fine and provide a handy
309** performance boost to bulk delete or insert operations. However, if
310** a page is moved to the free-list and then reused within the same
311** transaction, a problem comes up. If the page is not journalled when
312** it is moved to the free-list and it is also not journalled when it
313** is extracted from the free-list and reused, then the original data
314** may be lost. In the event of a rollback, it may not be possible
315** to restore the database to its original configuration.
316**
317** The solution is the BtShared.pHasContent bitvec. Whenever a page is
318** moved to become a free-list leaf page, the corresponding bit is
319** set in the bitvec. Whenever a leaf page is extracted from the free-list,
320** optimization 2 above is ommitted if the corresponding bit is already
321** set in BtShared.pHasContent. The contents of the bitvec are cleared
322** at the end of every transaction.
323*/
324static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
325 int rc = SQLITE_OK;
326 if( !pBt->pHasContent ){
327 int nPage;
328 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
329 if( rc==SQLITE_OK ){
330 pBt->pHasContent = sqlite3BitvecCreate((u32)nPage);
331 if( !pBt->pHasContent ){
332 rc = SQLITE_NOMEM;
333 }
334 }
335 }
336 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
337 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
338 }
339 return rc;
340}
341
342/*
343** Query the BtShared.pHasContent vector.
344**
345** This function is called when a free-list leaf page is removed from the
346** free-list for reuse. It returns false if it is safe to retrieve the
347** page from the pager layer with the 'no-content' flag set. True otherwise.
348*/
349static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
350 Bitvec *p = pBt->pHasContent;
351 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
352}
353
354/*
355** Clear (destroy) the BtShared.pHasContent bitvec. This should be
356** invoked at the conclusion of each write-transaction.
357*/
358static void btreeClearHasContent(BtShared *pBt){
359 sqlite3BitvecDestroy(pBt->pHasContent);
360 pBt->pHasContent = 0;
361}
362
363/*
drh980b1a72006-08-16 16:42:48 +0000364** Save the current cursor position in the variables BtCursor.nKey
365** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
366*/
367static int saveCursorPosition(BtCursor *pCur){
368 int rc;
369
370 assert( CURSOR_VALID==pCur->eState );
371 assert( 0==pCur->pKey );
drh1fee73e2007-08-29 04:00:57 +0000372 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000373
374 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
375
376 /* If this is an intKey table, then the above call to BtreeKeySize()
377 ** stores the integer key in pCur->nKey. In this case this value is
378 ** all that is required. Otherwise, if pCur is not open on an intKey
379 ** table, then malloc space for and store the pCur->nKey bytes of key
380 ** data.
381 */
danielk197771d5d2c2008-09-29 11:49:47 +0000382 if( rc==SQLITE_OK && 0==pCur->apPage[0]->intKey){
drhf49661a2008-12-10 16:45:50 +0000383 void *pKey = sqlite3Malloc( (int)pCur->nKey );
drh980b1a72006-08-16 16:42:48 +0000384 if( pKey ){
drhf49661a2008-12-10 16:45:50 +0000385 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
drh980b1a72006-08-16 16:42:48 +0000386 if( rc==SQLITE_OK ){
387 pCur->pKey = pKey;
388 }else{
drh17435752007-08-16 04:30:38 +0000389 sqlite3_free(pKey);
drh980b1a72006-08-16 16:42:48 +0000390 }
391 }else{
392 rc = SQLITE_NOMEM;
393 }
394 }
danielk197771d5d2c2008-09-29 11:49:47 +0000395 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
drh980b1a72006-08-16 16:42:48 +0000396
397 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +0000398 int i;
399 for(i=0; i<=pCur->iPage; i++){
400 releasePage(pCur->apPage[i]);
401 pCur->apPage[i] = 0;
402 }
403 pCur->iPage = -1;
drh980b1a72006-08-16 16:42:48 +0000404 pCur->eState = CURSOR_REQUIRESEEK;
405 }
406
danielk197792d4d7a2007-05-04 12:05:56 +0000407 invalidateOverflowCache(pCur);
drh980b1a72006-08-16 16:42:48 +0000408 return rc;
409}
410
411/*
412** Save the positions of all cursors except pExcept open on the table
413** with root-page iRoot. Usually, this is called just before cursor
414** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
415*/
416static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
417 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000418 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +0000419 assert( pExcept==0 || pExcept->pBt==pBt );
drh980b1a72006-08-16 16:42:48 +0000420 for(p=pBt->pCursor; p; p=p->pNext){
421 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
422 p->eState==CURSOR_VALID ){
423 int rc = saveCursorPosition(p);
424 if( SQLITE_OK!=rc ){
425 return rc;
426 }
427 }
428 }
429 return SQLITE_OK;
430}
431
432/*
drhbf700f32007-03-31 02:36:44 +0000433** Clear the current cursor position.
434*/
danielk1977be51a652008-10-08 17:58:48 +0000435void sqlite3BtreeClearCursor(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000436 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000437 sqlite3_free(pCur->pKey);
drhbf700f32007-03-31 02:36:44 +0000438 pCur->pKey = 0;
439 pCur->eState = CURSOR_INVALID;
440}
441
442/*
drh980b1a72006-08-16 16:42:48 +0000443** Restore the cursor to the position it was in (or as close to as possible)
444** when saveCursorPosition() was called. Note that this call deletes the
445** saved position info stored by saveCursorPosition(), so there can be
drha3460582008-07-11 21:02:53 +0000446** at most one effective restoreCursorPosition() call after each
drh980b1a72006-08-16 16:42:48 +0000447** saveCursorPosition().
drh980b1a72006-08-16 16:42:48 +0000448*/
drha3460582008-07-11 21:02:53 +0000449int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +0000450 int rc;
drh1fee73e2007-08-29 04:00:57 +0000451 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +0000452 assert( pCur->eState>=CURSOR_REQUIRESEEK );
453 if( pCur->eState==CURSOR_FAULT ){
454 return pCur->skip;
455 }
drh980b1a72006-08-16 16:42:48 +0000456 pCur->eState = CURSOR_INVALID;
drhe63d9992008-08-13 19:11:48 +0000457 rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skip);
drh980b1a72006-08-16 16:42:48 +0000458 if( rc==SQLITE_OK ){
drh17435752007-08-16 04:30:38 +0000459 sqlite3_free(pCur->pKey);
drh980b1a72006-08-16 16:42:48 +0000460 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +0000461 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drh980b1a72006-08-16 16:42:48 +0000462 }
463 return rc;
464}
465
drha3460582008-07-11 21:02:53 +0000466#define restoreCursorPosition(p) \
drhfb982642007-08-30 01:19:59 +0000467 (p->eState>=CURSOR_REQUIRESEEK ? \
drha3460582008-07-11 21:02:53 +0000468 sqlite3BtreeRestoreCursorPosition(p) : \
drh16a9b832007-05-05 18:39:25 +0000469 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +0000470
drha3460582008-07-11 21:02:53 +0000471/*
472** Determine whether or not a cursor has moved from the position it
drhdfe88ec2008-11-03 20:55:06 +0000473** was last placed at. Cursors can move when the row they are pointing
drha3460582008-07-11 21:02:53 +0000474** at is deleted out from under them.
475**
476** This routine returns an error code if something goes wrong. The
477** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
478*/
479int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
480 int rc;
481
482 rc = restoreCursorPosition(pCur);
483 if( rc ){
484 *pHasMoved = 1;
485 return rc;
486 }
487 if( pCur->eState!=CURSOR_VALID || pCur->skip!=0 ){
488 *pHasMoved = 1;
489 }else{
490 *pHasMoved = 0;
491 }
492 return SQLITE_OK;
493}
494
danielk1977599fcba2004-11-08 07:13:13 +0000495#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000496/*
drha3152892007-05-05 11:48:52 +0000497** Given a page number of a regular database page, return the page
498** number for the pointer-map page that contains the entry for the
499** input page number.
danielk1977afcdd022004-10-31 16:25:42 +0000500*/
danielk1977266664d2006-02-10 08:24:21 +0000501static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
danielk197789d40042008-11-17 14:20:56 +0000502 int nPagesPerMapPage;
503 Pgno iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +0000504 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000505 nPagesPerMapPage = (pBt->usableSize/5)+1;
506 iPtrMap = (pgno-2)/nPagesPerMapPage;
507 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +0000508 if( ret==PENDING_BYTE_PAGE(pBt) ){
509 ret++;
510 }
511 return ret;
512}
danielk1977a19df672004-11-03 11:37:07 +0000513
danielk1977afcdd022004-10-31 16:25:42 +0000514/*
danielk1977afcdd022004-10-31 16:25:42 +0000515** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000516**
517** This routine updates the pointer map entry for page number 'key'
518** so that it maps to type 'eType' and parent page number 'pgno'.
519** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000520*/
danielk1977aef0bf62005-12-30 16:28:01 +0000521static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
danielk19773b8a05f2007-03-19 17:44:26 +0000522 DbPage *pDbPage; /* The pointer map page */
523 u8 *pPtrmap; /* The pointer map data */
524 Pgno iPtrmap; /* The pointer map page number */
525 int offset; /* Offset in pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000526 int rc;
527
drh1fee73e2007-08-29 04:00:57 +0000528 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977266664d2006-02-10 08:24:21 +0000529 /* The master-journal page number must never be used as a pointer map page */
530 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
531
danielk1977ac11ee62005-01-15 12:45:51 +0000532 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000533 if( key==0 ){
drh49285702005-09-17 15:20:26 +0000534 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000535 }
danielk1977266664d2006-02-10 08:24:21 +0000536 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000537 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977687566d2004-11-02 12:56:41 +0000538 if( rc!=SQLITE_OK ){
danielk1977afcdd022004-10-31 16:25:42 +0000539 return rc;
540 }
danielk19778c666b12008-07-18 09:34:57 +0000541 offset = PTRMAP_PTROFFSET(iPtrmap, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000542 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000543
drh615ae552005-01-16 23:21:00 +0000544 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
545 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
danielk19773b8a05f2007-03-19 17:44:26 +0000546 rc = sqlite3PagerWrite(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000547 if( rc==SQLITE_OK ){
548 pPtrmap[offset] = eType;
549 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000550 }
danielk1977afcdd022004-10-31 16:25:42 +0000551 }
552
danielk19773b8a05f2007-03-19 17:44:26 +0000553 sqlite3PagerUnref(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000554 return rc;
danielk1977afcdd022004-10-31 16:25:42 +0000555}
556
557/*
558** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000559**
560** This routine retrieves the pointer map entry for page 'key', writing
561** the type and parent page number to *pEType and *pPgno respectively.
562** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000563*/
danielk1977aef0bf62005-12-30 16:28:01 +0000564static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +0000565 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000566 int iPtrmap; /* Pointer map page index */
567 u8 *pPtrmap; /* Pointer map page data */
568 int offset; /* Offset of entry in pointer map */
569 int rc;
570
drh1fee73e2007-08-29 04:00:57 +0000571 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000572
danielk1977266664d2006-02-10 08:24:21 +0000573 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000574 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000575 if( rc!=0 ){
576 return rc;
577 }
danielk19773b8a05f2007-03-19 17:44:26 +0000578 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000579
danielk19778c666b12008-07-18 09:34:57 +0000580 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drh43617e92006-03-06 20:55:46 +0000581 assert( pEType!=0 );
582 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +0000583 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000584
danielk19773b8a05f2007-03-19 17:44:26 +0000585 sqlite3PagerUnref(pDbPage);
drh49285702005-09-17 15:20:26 +0000586 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000587 return SQLITE_OK;
588}
589
danielk197785d90ca2008-07-19 14:25:15 +0000590#else /* if defined SQLITE_OMIT_AUTOVACUUM */
591 #define ptrmapPut(w,x,y,z) SQLITE_OK
592 #define ptrmapGet(w,x,y,z) SQLITE_OK
593 #define ptrmapPutOvfl(y,z) SQLITE_OK
594#endif
danielk1977afcdd022004-10-31 16:25:42 +0000595
drh0d316a42002-08-11 20:10:47 +0000596/*
drh271efa52004-05-30 19:19:05 +0000597** Given a btree page and a cell index (0 means the first cell on
598** the page, 1 means the second cell, and so forth) return a pointer
599** to the cell content.
600**
601** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000602*/
drh1688c862008-07-18 02:44:17 +0000603#define findCell(P,I) \
604 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
drh43605152004-05-29 21:46:49 +0000605
606/*
drh93a960a2008-07-10 00:32:42 +0000607** This a more complex version of findCell() that works for
drh43605152004-05-29 21:46:49 +0000608** pages that do contain overflow cells. See insert
609*/
610static u8 *findOverflowCell(MemPage *pPage, int iCell){
611 int i;
drh1fee73e2007-08-29 04:00:57 +0000612 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +0000613 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000614 int k;
615 struct _OvflCell *pOvfl;
616 pOvfl = &pPage->aOvfl[i];
617 k = pOvfl->idx;
618 if( k<=iCell ){
619 if( k==iCell ){
620 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000621 }
622 iCell--;
623 }
624 }
danielk19771cc5ed82007-05-16 17:28:43 +0000625 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000626}
627
628/*
629** Parse a cell content block and fill in the CellInfo structure. There
drh16a9b832007-05-05 18:39:25 +0000630** are two versions of this function. sqlite3BtreeParseCell() takes a
631** cell index as the second argument and sqlite3BtreeParseCellPtr()
632** takes a pointer to the body of the cell as its second argument.
danielk19771cc5ed82007-05-16 17:28:43 +0000633**
634** Within this file, the parseCell() macro can be called instead of
635** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
drh43605152004-05-29 21:46:49 +0000636*/
drh16a9b832007-05-05 18:39:25 +0000637void sqlite3BtreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000638 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000639 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000640 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000641){
drhf49661a2008-12-10 16:45:50 +0000642 u16 n; /* Number bytes in cell content header */
drh271efa52004-05-30 19:19:05 +0000643 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000644
drh1fee73e2007-08-29 04:00:57 +0000645 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000646
drh43605152004-05-29 21:46:49 +0000647 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000648 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000649 n = pPage->childPtrSize;
650 assert( n==4-4*pPage->leaf );
drh504b6982006-01-22 21:52:56 +0000651 if( pPage->intKey ){
drh79df1f42008-07-18 00:57:33 +0000652 if( pPage->hasData ){
653 n += getVarint32(&pCell[n], nPayload);
654 }else{
655 nPayload = 0;
656 }
drh1bd10f82008-12-10 21:19:56 +0000657 n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
drh79df1f42008-07-18 00:57:33 +0000658 pInfo->nData = nPayload;
drh504b6982006-01-22 21:52:56 +0000659 }else{
drh79df1f42008-07-18 00:57:33 +0000660 pInfo->nData = 0;
661 n += getVarint32(&pCell[n], nPayload);
662 pInfo->nKey = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000663 }
drh72365832007-03-06 15:53:44 +0000664 pInfo->nPayload = nPayload;
drh504b6982006-01-22 21:52:56 +0000665 pInfo->nHeader = n;
drh79df1f42008-07-18 00:57:33 +0000666 if( likely(nPayload<=pPage->maxLocal) ){
drh271efa52004-05-30 19:19:05 +0000667 /* This is the (easy) common case where the entire payload fits
668 ** on the local page. No overflow is required.
669 */
670 int nSize; /* Total size of cell content in bytes */
drh79df1f42008-07-18 00:57:33 +0000671 nSize = nPayload + n;
drhf49661a2008-12-10 16:45:50 +0000672 pInfo->nLocal = (u16)nPayload;
drh6f11bef2004-05-13 01:12:56 +0000673 pInfo->iOverflow = 0;
drh79df1f42008-07-18 00:57:33 +0000674 if( (nSize & ~3)==0 ){
drh271efa52004-05-30 19:19:05 +0000675 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000676 }
drh1bd10f82008-12-10 21:19:56 +0000677 pInfo->nSize = (u16)nSize;
drh6f11bef2004-05-13 01:12:56 +0000678 }else{
drh271efa52004-05-30 19:19:05 +0000679 /* If the payload will not fit completely on the local page, we have
680 ** to decide how much to store locally and how much to spill onto
681 ** overflow pages. The strategy is to minimize the amount of unused
682 ** space on overflow pages while keeping the amount of local storage
683 ** in between minLocal and maxLocal.
684 **
685 ** Warning: changing the way overflow payload is distributed in any
686 ** way will result in an incompatible file format.
687 */
688 int minLocal; /* Minimum amount of payload held locally */
689 int maxLocal; /* Maximum amount of payload held locally */
690 int surplus; /* Overflow payload available for local storage */
691
692 minLocal = pPage->minLocal;
693 maxLocal = pPage->maxLocal;
694 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000695 if( surplus <= maxLocal ){
drhf49661a2008-12-10 16:45:50 +0000696 pInfo->nLocal = (u16)surplus;
drh6f11bef2004-05-13 01:12:56 +0000697 }else{
drhf49661a2008-12-10 16:45:50 +0000698 pInfo->nLocal = (u16)minLocal;
drh6f11bef2004-05-13 01:12:56 +0000699 }
drhf49661a2008-12-10 16:45:50 +0000700 pInfo->iOverflow = (u16)(pInfo->nLocal + n);
drh6f11bef2004-05-13 01:12:56 +0000701 pInfo->nSize = pInfo->iOverflow + 4;
702 }
drh3aac2dd2004-04-26 14:10:20 +0000703}
danielk19771cc5ed82007-05-16 17:28:43 +0000704#define parseCell(pPage, iCell, pInfo) \
705 sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
drh16a9b832007-05-05 18:39:25 +0000706void sqlite3BtreeParseCell(
drh43605152004-05-29 21:46:49 +0000707 MemPage *pPage, /* Page containing the cell */
708 int iCell, /* The cell index. First cell is 0 */
709 CellInfo *pInfo /* Fill in this structure */
710){
danielk19771cc5ed82007-05-16 17:28:43 +0000711 parseCell(pPage, iCell, pInfo);
drh43605152004-05-29 21:46:49 +0000712}
drh3aac2dd2004-04-26 14:10:20 +0000713
714/*
drh43605152004-05-29 21:46:49 +0000715** Compute the total number of bytes that a Cell needs in the cell
716** data area of the btree-page. The return number includes the cell
717** data header and the local payload, but not any overflow page or
718** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000719*/
danielk1977bc6ada42004-06-30 08:20:16 +0000720#ifndef NDEBUG
drha9121e42008-02-19 14:59:35 +0000721static u16 cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000722 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000723 sqlite3BtreeParseCell(pPage, iCell, &info);
drh43605152004-05-29 21:46:49 +0000724 return info.nSize;
725}
danielk1977bc6ada42004-06-30 08:20:16 +0000726#endif
drha9121e42008-02-19 14:59:35 +0000727static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
drh43605152004-05-29 21:46:49 +0000728 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000729 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000730 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000731}
732
danielk197779a40da2005-01-16 08:00:01 +0000733#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +0000734/*
danielk197726836652005-01-17 01:33:13 +0000735** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +0000736** to an overflow page, insert an entry into the pointer-map
737** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +0000738*/
danielk197726836652005-01-17 01:33:13 +0000739static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
drhfa67c3c2008-07-11 02:21:40 +0000740 CellInfo info;
741 assert( pCell!=0 );
742 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
743 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
744 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
745 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
746 return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +0000747 }
danielk197779a40da2005-01-16 08:00:01 +0000748 return SQLITE_OK;
danielk1977ac11ee62005-01-15 12:45:51 +0000749}
danielk197726836652005-01-17 01:33:13 +0000750/*
751** If the cell with index iCell on page pPage contains a pointer
752** to an overflow page, insert an entry into the pointer-map
753** for the overflow page.
754*/
755static int ptrmapPutOvfl(MemPage *pPage, int iCell){
756 u8 *pCell;
drh1fee73e2007-08-29 04:00:57 +0000757 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197726836652005-01-17 01:33:13 +0000758 pCell = findOverflowCell(pPage, iCell);
759 return ptrmapPutOvflPtr(pPage, pCell);
760}
danielk197779a40da2005-01-16 08:00:01 +0000761#endif
762
danielk1977ac11ee62005-01-15 12:45:51 +0000763
drhda200cc2004-05-09 11:51:38 +0000764/*
drh72f82862001-05-24 21:06:34 +0000765** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +0000766** end of the page and all free space is collected into one
767** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +0000768** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +0000769*/
shane0af3f892008-11-12 04:55:34 +0000770static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000771 int i; /* Loop counter */
772 int pc; /* Address of a i-th cell */
773 int addr; /* Offset of first byte after cell pointer array */
774 int hdr; /* Offset to the page header */
775 int size; /* Size of a cell */
776 int usableSize; /* Number of usable bytes on a page */
777 int cellOffset; /* Offset to the cell pointer array */
drh281b21d2008-08-22 12:57:08 +0000778 int cbrk; /* Offset to the cell content area */
drh43605152004-05-29 21:46:49 +0000779 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +0000780 unsigned char *data; /* The page data */
781 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +0000782
danielk19773b8a05f2007-03-19 17:44:26 +0000783 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000784 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +0000785 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000786 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +0000787 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh26b79942007-11-28 16:19:56 +0000788 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
drh43605152004-05-29 21:46:49 +0000789 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +0000790 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000791 cellOffset = pPage->cellOffset;
792 nCell = pPage->nCell;
793 assert( nCell==get2byte(&data[hdr+3]) );
794 usableSize = pPage->pBt->usableSize;
drh281b21d2008-08-22 12:57:08 +0000795 cbrk = get2byte(&data[hdr+5]);
796 memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
797 cbrk = usableSize;
drh43605152004-05-29 21:46:49 +0000798 for(i=0; i<nCell; i++){
799 u8 *pAddr; /* The i-th cell pointer */
800 pAddr = &data[cellOffset + i*2];
801 pc = get2byte(pAddr);
shanedcc50b72008-11-13 18:29:50 +0000802 if( pc>=usableSize ){
shane0af3f892008-11-12 04:55:34 +0000803 return SQLITE_CORRUPT_BKPT;
804 }
drh43605152004-05-29 21:46:49 +0000805 size = cellSizePtr(pPage, &temp[pc]);
drh281b21d2008-08-22 12:57:08 +0000806 cbrk -= size;
danielk19770d065412008-11-12 18:21:36 +0000807 if( cbrk<cellOffset+2*nCell || pc+size>usableSize ){
shane0af3f892008-11-12 04:55:34 +0000808 return SQLITE_CORRUPT_BKPT;
809 }
danielk19770d065412008-11-12 18:21:36 +0000810 assert( cbrk+size<=usableSize && cbrk>=0 );
drh281b21d2008-08-22 12:57:08 +0000811 memcpy(&data[cbrk], &temp[pc], size);
812 put2byte(pAddr, cbrk);
drh2af926b2001-05-15 00:39:25 +0000813 }
drh281b21d2008-08-22 12:57:08 +0000814 assert( cbrk>=cellOffset+2*nCell );
815 put2byte(&data[hdr+5], cbrk);
drh43605152004-05-29 21:46:49 +0000816 data[hdr+1] = 0;
817 data[hdr+2] = 0;
818 data[hdr+7] = 0;
819 addr = cellOffset+2*nCell;
drh281b21d2008-08-22 12:57:08 +0000820 memset(&data[addr], 0, cbrk-addr);
drhc5053fb2008-11-27 02:22:10 +0000821 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977360e6342008-11-12 08:49:51 +0000822 if( cbrk-addr!=pPage->nFree ){
823 return SQLITE_CORRUPT_BKPT;
824 }
shane0af3f892008-11-12 04:55:34 +0000825 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +0000826}
827
drha059ad02001-04-17 20:09:11 +0000828/*
drh43605152004-05-29 21:46:49 +0000829** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +0000830**
drh9e572e62004-04-23 23:43:10 +0000831** Return the index into pPage->aData[] of the first byte of
drhfa67c3c2008-07-11 02:21:40 +0000832** the new allocation. The caller guarantees that there is enough
833** space. This routine will never fail.
drh2af926b2001-05-15 00:39:25 +0000834**
drh72f82862001-05-24 21:06:34 +0000835** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000836** nBytes of contiguous free space, then this routine automatically
837** calls defragementPage() to consolidate all free space before
838** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000839*/
drh9e572e62004-04-23 23:43:10 +0000840static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +0000841 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +0000842 int size;
drh24cd67e2004-05-10 16:18:47 +0000843 int nFrag;
drh43605152004-05-29 21:46:49 +0000844 int top;
845 int nCell;
846 int cellOffset;
drh9e572e62004-04-23 23:43:10 +0000847 unsigned char *data;
drh43605152004-05-29 21:46:49 +0000848
drh9e572e62004-04-23 23:43:10 +0000849 data = pPage->aData;
danielk19773b8a05f2007-03-19 17:44:26 +0000850 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000851 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +0000852 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa67c3c2008-07-11 02:21:40 +0000853 assert( nByte>=0 ); /* Minimum cell size is 4 */
854 assert( pPage->nFree>=nByte );
855 assert( pPage->nOverflow==0 );
drhf49661a2008-12-10 16:45:50 +0000856 pPage->nFree -= (u16)nByte;
drh9e572e62004-04-23 23:43:10 +0000857 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000858
859 nFrag = data[hdr+7];
860 if( nFrag<60 ){
861 /* Search the freelist looking for a slot big enough to satisfy the
862 ** space request. */
863 addr = hdr+1;
864 while( (pc = get2byte(&data[addr]))>0 ){
865 size = get2byte(&data[pc+2]);
866 if( size>=nByte ){
drhf49661a2008-12-10 16:45:50 +0000867 int x = size - nByte;
drh43605152004-05-29 21:46:49 +0000868 if( size<nByte+4 ){
869 memcpy(&data[addr], &data[pc], 2);
drhf49661a2008-12-10 16:45:50 +0000870 data[hdr+7] = (u8)(nFrag + x);
drh43605152004-05-29 21:46:49 +0000871 return pc;
872 }else{
drhf49661a2008-12-10 16:45:50 +0000873 put2byte(&data[pc+2], x);
874 return pc + x;
drh43605152004-05-29 21:46:49 +0000875 }
876 }
877 addr = pc;
drh9e572e62004-04-23 23:43:10 +0000878 }
879 }
drh43605152004-05-29 21:46:49 +0000880
881 /* Allocate memory from the gap in between the cell pointer array
882 ** and the cell content area.
883 */
884 top = get2byte(&data[hdr+5]);
885 nCell = get2byte(&data[hdr+3]);
886 cellOffset = pPage->cellOffset;
887 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
danielk1977474b7cc2008-07-09 11:49:46 +0000888 defragmentPage(pPage);
drh43605152004-05-29 21:46:49 +0000889 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +0000890 }
drh43605152004-05-29 21:46:49 +0000891 top -= nByte;
892 assert( cellOffset + 2*nCell <= top );
893 put2byte(&data[hdr+5], top);
drhc5053fb2008-11-27 02:22:10 +0000894 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +0000895 return top;
drh7e3b0a02001-04-28 16:52:40 +0000896}
897
898/*
drh9e572e62004-04-23 23:43:10 +0000899** Return a section of the pPage->aData to the freelist.
900** The first byte of the new free block is pPage->aDisk[start]
901** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +0000902**
903** Most of the effort here is involved in coalesing adjacent
904** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000905*/
shanedcc50b72008-11-13 18:29:50 +0000906static int freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +0000907 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +0000908 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +0000909
drh9e572e62004-04-23 23:43:10 +0000910 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +0000911 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000912 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +0000913 assert( (start + size)<=pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +0000914 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh34004ce2008-07-11 16:15:17 +0000915 assert( size>=0 ); /* Minimum cell size is 4 */
drh9e572e62004-04-23 23:43:10 +0000916
drhfcce93f2006-02-22 03:08:32 +0000917#ifdef SQLITE_SECURE_DELETE
918 /* Overwrite deleted information with zeros when the SECURE_DELETE
919 ** option is enabled at compile-time */
920 memset(&data[start], 0, size);
921#endif
922
drh9e572e62004-04-23 23:43:10 +0000923 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +0000924 hdr = pPage->hdrOffset;
925 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +0000926 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +0000927 assert( pbegin<=pPage->pBt->usableSize-4 );
shanedcc50b72008-11-13 18:29:50 +0000928 if( pbegin<=addr ) {
929 return SQLITE_CORRUPT_BKPT;
930 }
drh3aac2dd2004-04-26 14:10:20 +0000931 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +0000932 }
shanedcc50b72008-11-13 18:29:50 +0000933 if ( pbegin>pPage->pBt->usableSize-4 ) {
934 return SQLITE_CORRUPT_BKPT;
935 }
drh3aac2dd2004-04-26 14:10:20 +0000936 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +0000937 put2byte(&data[addr], start);
938 put2byte(&data[start], pbegin);
939 put2byte(&data[start+2], size);
drhf49661a2008-12-10 16:45:50 +0000940 pPage->nFree += (u16)size;
drh9e572e62004-04-23 23:43:10 +0000941
942 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +0000943 addr = pPage->hdrOffset + 1;
944 while( (pbegin = get2byte(&data[addr]))>0 ){
drhf49661a2008-12-10 16:45:50 +0000945 int pnext, psize, x;
drh3aac2dd2004-04-26 14:10:20 +0000946 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +0000947 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +0000948 pnext = get2byte(&data[pbegin]);
949 psize = get2byte(&data[pbegin+2]);
950 if( pbegin + psize + 3 >= pnext && pnext>0 ){
951 int frag = pnext - (pbegin+psize);
drhf49661a2008-12-10 16:45:50 +0000952 if( (frag<0) || (frag>(int)data[pPage->hdrOffset+7]) ){
shanedcc50b72008-11-13 18:29:50 +0000953 return SQLITE_CORRUPT_BKPT;
954 }
drhf49661a2008-12-10 16:45:50 +0000955 data[pPage->hdrOffset+7] -= (u8)frag;
956 x = get2byte(&data[pnext]);
957 put2byte(&data[pbegin], x);
958 x = pnext + get2byte(&data[pnext+2]) - pbegin;
959 put2byte(&data[pbegin+2], x);
drh9e572e62004-04-23 23:43:10 +0000960 }else{
drh3aac2dd2004-04-26 14:10:20 +0000961 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +0000962 }
963 }
drh7e3b0a02001-04-28 16:52:40 +0000964
drh43605152004-05-29 21:46:49 +0000965 /* If the cell content area begins with a freeblock, remove it. */
966 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
967 int top;
968 pbegin = get2byte(&data[hdr+1]);
969 memcpy(&data[hdr+1], &data[pbegin], 2);
drhf49661a2008-12-10 16:45:50 +0000970 top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
971 put2byte(&data[hdr+5], top);
drh4b70f112004-05-02 21:12:19 +0000972 }
drhc5053fb2008-11-27 02:22:10 +0000973 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
shanedcc50b72008-11-13 18:29:50 +0000974 return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +0000975}
976
977/*
drh271efa52004-05-30 19:19:05 +0000978** Decode the flags byte (the first byte of the header) for a page
979** and initialize fields of the MemPage structure accordingly.
drh44845222008-07-17 18:39:57 +0000980**
981** Only the following combinations are supported. Anything different
982** indicates a corrupt database files:
983**
984** PTF_ZERODATA
985** PTF_ZERODATA | PTF_LEAF
986** PTF_LEAFDATA | PTF_INTKEY
987** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
drh271efa52004-05-30 19:19:05 +0000988*/
drh44845222008-07-17 18:39:57 +0000989static int decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +0000990 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +0000991
992 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +0000993 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +0000994 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
drh44845222008-07-17 18:39:57 +0000995 flagByte &= ~PTF_LEAF;
996 pPage->childPtrSize = 4-4*pPage->leaf;
drh271efa52004-05-30 19:19:05 +0000997 pBt = pPage->pBt;
drh44845222008-07-17 18:39:57 +0000998 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
999 pPage->intKey = 1;
1000 pPage->hasData = pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001001 pPage->maxLocal = pBt->maxLeaf;
1002 pPage->minLocal = pBt->minLeaf;
drh44845222008-07-17 18:39:57 +00001003 }else if( flagByte==PTF_ZERODATA ){
1004 pPage->intKey = 0;
1005 pPage->hasData = 0;
drh271efa52004-05-30 19:19:05 +00001006 pPage->maxLocal = pBt->maxLocal;
1007 pPage->minLocal = pBt->minLocal;
drh44845222008-07-17 18:39:57 +00001008 }else{
1009 return SQLITE_CORRUPT_BKPT;
drh271efa52004-05-30 19:19:05 +00001010 }
drh44845222008-07-17 18:39:57 +00001011 return SQLITE_OK;
drh271efa52004-05-30 19:19:05 +00001012}
1013
1014/*
drh7e3b0a02001-04-28 16:52:40 +00001015** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +00001016**
1017** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +00001018** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +00001019** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1020** guarantee that the page is well-formed. It only shows that
1021** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001022*/
danielk197771d5d2c2008-09-29 11:49:47 +00001023int sqlite3BtreeInitPage(MemPage *pPage){
drh2af926b2001-05-15 00:39:25 +00001024
danielk197771d5d2c2008-09-29 11:49:47 +00001025 assert( pPage->pBt!=0 );
1026 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001027 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +00001028 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1029 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00001030
1031 if( !pPage->isInit ){
drhf49661a2008-12-10 16:45:50 +00001032 u16 pc; /* Address of a freeblock within pPage->aData[] */
1033 u8 hdr; /* Offset to beginning of page header */
danielk197771d5d2c2008-09-29 11:49:47 +00001034 u8 *data; /* Equal to pPage->aData */
1035 BtShared *pBt; /* The main btree structure */
drhf49661a2008-12-10 16:45:50 +00001036 u16 usableSize; /* Amount of usable space on each page */
1037 u16 cellOffset; /* Offset from start of page to first cell pointer */
1038 u16 nFree; /* Number of unused bytes on the page */
1039 u16 top; /* First byte of the cell content area */
danielk197771d5d2c2008-09-29 11:49:47 +00001040
1041 pBt = pPage->pBt;
1042
danielk1977eaa06f62008-09-18 17:34:44 +00001043 hdr = pPage->hdrOffset;
1044 data = pPage->aData;
1045 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
1046 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
1047 pPage->maskPage = pBt->pageSize - 1;
1048 pPage->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00001049 usableSize = pBt->usableSize;
1050 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
1051 top = get2byte(&data[hdr+5]);
1052 pPage->nCell = get2byte(&data[hdr+3]);
1053 if( pPage->nCell>MX_CELL(pBt) ){
1054 /* To many cells for a single page. The page must be corrupt */
1055 return SQLITE_CORRUPT_BKPT;
1056 }
danielk1977eaa06f62008-09-18 17:34:44 +00001057
1058 /* Compute the total free space on the page */
1059 pc = get2byte(&data[hdr+1]);
1060 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
1061 while( pc>0 ){
drh1bd10f82008-12-10 21:19:56 +00001062 u16 next, size;
danielk1977eaa06f62008-09-18 17:34:44 +00001063 if( pc>usableSize-4 ){
1064 /* Free block is off the page */
1065 return SQLITE_CORRUPT_BKPT;
1066 }
1067 next = get2byte(&data[pc]);
1068 size = get2byte(&data[pc+2]);
1069 if( next>0 && next<=pc+size+3 ){
1070 /* Free blocks must be in accending order */
1071 return SQLITE_CORRUPT_BKPT;
1072 }
1073 nFree += size;
1074 pc = next;
1075 }
drhf49661a2008-12-10 16:45:50 +00001076 pPage->nFree = (u16)nFree;
danielk1977eaa06f62008-09-18 17:34:44 +00001077 if( nFree>=usableSize ){
1078 /* Free space cannot exceed total page size */
drh49285702005-09-17 15:20:26 +00001079 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001080 }
drh9e572e62004-04-23 23:43:10 +00001081
drh1688c862008-07-18 02:44:17 +00001082#if 0
1083 /* Check that all the offsets in the cell offset array are within range.
1084 **
1085 ** Omitting this consistency check and using the pPage->maskPage mask
1086 ** to prevent overrunning the page buffer in findCell() results in a
1087 ** 2.5% performance gain.
1088 */
1089 {
1090 u8 *pOff; /* Iterator used to check all cell offsets are in range */
1091 u8 *pEnd; /* Pointer to end of cell offset array */
1092 u8 mask; /* Mask of bits that must be zero in MSB of cell offsets */
1093 mask = ~(((u8)(pBt->pageSize>>8))-1);
1094 pEnd = &data[cellOffset + pPage->nCell*2];
1095 for(pOff=&data[cellOffset]; pOff!=pEnd && !((*pOff)&mask); pOff+=2);
1096 if( pOff!=pEnd ){
1097 return SQLITE_CORRUPT_BKPT;
1098 }
danielk1977e16535f2008-06-11 18:15:29 +00001099 }
drh1688c862008-07-18 02:44:17 +00001100#endif
danielk1977e16535f2008-06-11 18:15:29 +00001101
danielk197771d5d2c2008-09-29 11:49:47 +00001102 pPage->isInit = 1;
1103 }
drh9e572e62004-04-23 23:43:10 +00001104 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001105}
1106
1107/*
drh8b2f49b2001-06-08 00:21:52 +00001108** Set up a raw page so that it looks like a database page holding
1109** no entries.
drhbd03cae2001-06-02 02:40:57 +00001110*/
drh9e572e62004-04-23 23:43:10 +00001111static void zeroPage(MemPage *pPage, int flags){
1112 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001113 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00001114 u8 hdr = pPage->hdrOffset;
1115 u16 first;
drh9e572e62004-04-23 23:43:10 +00001116
danielk19773b8a05f2007-03-19 17:44:26 +00001117 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drhbf4bca52007-09-06 22:19:14 +00001118 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1119 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +00001120 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00001121 assert( sqlite3_mutex_held(pBt->mutex) );
drh1af4a6e2008-07-18 03:32:51 +00001122 /*memset(&data[hdr], 0, pBt->usableSize - hdr);*/
drh1bd10f82008-12-10 21:19:56 +00001123 data[hdr] = (char)flags;
1124 first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
drh43605152004-05-29 21:46:49 +00001125 memset(&data[hdr+1], 0, 4);
1126 data[hdr+7] = 0;
1127 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +00001128 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +00001129 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +00001130 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +00001131 pPage->cellOffset = first;
1132 pPage->nOverflow = 0;
drh1688c862008-07-18 02:44:17 +00001133 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
1134 pPage->maskPage = pBt->pageSize - 1;
drh43605152004-05-29 21:46:49 +00001135 pPage->nCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001136 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00001137}
1138
drh897a8202008-09-18 01:08:15 +00001139
1140/*
1141** Convert a DbPage obtained from the pager into a MemPage used by
1142** the btree layer.
1143*/
1144static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
1145 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
1146 pPage->aData = sqlite3PagerGetData(pDbPage);
1147 pPage->pDbPage = pDbPage;
1148 pPage->pBt = pBt;
1149 pPage->pgno = pgno;
1150 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
1151 return pPage;
1152}
1153
drhbd03cae2001-06-02 02:40:57 +00001154/*
drh3aac2dd2004-04-26 14:10:20 +00001155** Get a page from the pager. Initialize the MemPage.pBt and
1156** MemPage.aData elements if needed.
drh538f5702007-04-13 02:14:30 +00001157**
1158** If the noContent flag is set, it means that we do not care about
1159** the content of the page at this time. So do not go to the disk
1160** to fetch the content. Just fill in the content with zeros for now.
1161** If in the future we call sqlite3PagerWrite() on this page, that
1162** means we have started to be concerned about content and the disk
1163** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00001164*/
drh16a9b832007-05-05 18:39:25 +00001165int sqlite3BtreeGetPage(
1166 BtShared *pBt, /* The btree */
1167 Pgno pgno, /* Number of the page to fetch */
1168 MemPage **ppPage, /* Return the page in this parameter */
1169 int noContent /* Do not load page content if true */
1170){
drh3aac2dd2004-04-26 14:10:20 +00001171 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001172 DbPage *pDbPage;
1173
drh1fee73e2007-08-29 04:00:57 +00001174 assert( sqlite3_mutex_held(pBt->mutex) );
drh538f5702007-04-13 02:14:30 +00001175 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
drh3aac2dd2004-04-26 14:10:20 +00001176 if( rc ) return rc;
drh897a8202008-09-18 01:08:15 +00001177 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
drh3aac2dd2004-04-26 14:10:20 +00001178 return SQLITE_OK;
1179}
1180
1181/*
danielk1977bea2a942009-01-20 17:06:27 +00001182** Retrieve a page from the pager cache. If the requested page is not
1183** already in the pager cache return NULL. Initialize the MemPage.pBt and
1184** MemPage.aData elements if needed.
1185*/
1186static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
1187 DbPage *pDbPage;
1188 assert( sqlite3_mutex_held(pBt->mutex) );
1189 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
1190 if( pDbPage ){
1191 return btreePageFromDbPage(pDbPage, pgno, pBt);
1192 }
1193 return 0;
1194}
1195
1196/*
danielk197789d40042008-11-17 14:20:56 +00001197** Return the size of the database file in pages. If there is any kind of
1198** error, return ((unsigned int)-1).
danielk197767fd7a92008-09-10 17:53:35 +00001199*/
danielk197789d40042008-11-17 14:20:56 +00001200static Pgno pagerPagecount(BtShared *pBt){
1201 int nPage = -1;
danielk197767fd7a92008-09-10 17:53:35 +00001202 int rc;
danielk197789d40042008-11-17 14:20:56 +00001203 assert( pBt->pPage1 );
1204 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1205 assert( rc==SQLITE_OK || nPage==-1 );
1206 return (Pgno)nPage;
danielk197767fd7a92008-09-10 17:53:35 +00001207}
1208
1209/*
drhde647132004-05-07 17:57:49 +00001210** Get a page from the pager and initialize it. This routine
1211** is just a convenience wrapper around separate calls to
drh16a9b832007-05-05 18:39:25 +00001212** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
drhde647132004-05-07 17:57:49 +00001213*/
1214static int getAndInitPage(
danielk1977aef0bf62005-12-30 16:28:01 +00001215 BtShared *pBt, /* The database file */
drhde647132004-05-07 17:57:49 +00001216 Pgno pgno, /* Number of the page to get */
danielk197771d5d2c2008-09-29 11:49:47 +00001217 MemPage **ppPage /* Write the page pointer here */
drhde647132004-05-07 17:57:49 +00001218){
1219 int rc;
drh897a8202008-09-18 01:08:15 +00001220 MemPage *pPage;
1221
drh1fee73e2007-08-29 04:00:57 +00001222 assert( sqlite3_mutex_held(pBt->mutex) );
drh897a8202008-09-18 01:08:15 +00001223 if( pgno==0 ){
drh49285702005-09-17 15:20:26 +00001224 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001225 }
danielk19779f580ad2008-09-10 14:45:57 +00001226
drh897a8202008-09-18 01:08:15 +00001227 /* It is often the case that the page we want is already in cache.
1228 ** If so, get it directly. This saves us from having to call
1229 ** pagerPagecount() to make sure pgno is within limits, which results
1230 ** in a measureable performance improvements.
1231 */
danielk1977bea2a942009-01-20 17:06:27 +00001232 *ppPage = pPage = btreePageLookup(pBt, pgno);
1233 if( pPage ){
drh897a8202008-09-18 01:08:15 +00001234 /* Page is already in cache */
drh897a8202008-09-18 01:08:15 +00001235 rc = SQLITE_OK;
1236 }else{
1237 /* Page not in cache. Acquire it. */
danielk197789d40042008-11-17 14:20:56 +00001238 if( pgno>pagerPagecount(pBt) ){
drh897a8202008-09-18 01:08:15 +00001239 return SQLITE_CORRUPT_BKPT;
1240 }
1241 rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
1242 if( rc ) return rc;
1243 pPage = *ppPage;
1244 }
danielk197771d5d2c2008-09-29 11:49:47 +00001245 if( !pPage->isInit ){
1246 rc = sqlite3BtreeInitPage(pPage);
drh897a8202008-09-18 01:08:15 +00001247 }
1248 if( rc!=SQLITE_OK ){
1249 releasePage(pPage);
1250 *ppPage = 0;
1251 }
drhde647132004-05-07 17:57:49 +00001252 return rc;
1253}
1254
1255/*
drh3aac2dd2004-04-26 14:10:20 +00001256** Release a MemPage. This should be called once for each prior
drh16a9b832007-05-05 18:39:25 +00001257** call to sqlite3BtreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +00001258*/
drh4b70f112004-05-02 21:12:19 +00001259static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001260 if( pPage ){
drh30df0092008-12-23 15:58:06 +00001261 assert( pPage->nOverflow==0 || sqlite3PagerPageRefcount(pPage->pDbPage)>1 );
drh3aac2dd2004-04-26 14:10:20 +00001262 assert( pPage->aData );
1263 assert( pPage->pBt );
drhbf4bca52007-09-06 22:19:14 +00001264 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1265 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
drh1fee73e2007-08-29 04:00:57 +00001266 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001267 sqlite3PagerUnref(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00001268 }
1269}
1270
1271/*
drha6abd042004-06-09 17:37:22 +00001272** During a rollback, when the pager reloads information into the cache
1273** so that the cache is restored to its original state at the start of
1274** the transaction, for each page restored this routine is called.
1275**
1276** This routine needs to reset the extra data section at the end of the
1277** page to agree with the restored data.
1278*/
danielk1977eaa06f62008-09-18 17:34:44 +00001279static void pageReinit(DbPage *pData){
drh07d183d2005-05-01 22:52:42 +00001280 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00001281 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
danielk197771d5d2c2008-09-29 11:49:47 +00001282 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00001283 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00001284 pPage->isInit = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001285 if( sqlite3PagerPageRefcount(pData)>0 ){
1286 sqlite3BtreeInitPage(pPage);
1287 }
drha6abd042004-06-09 17:37:22 +00001288 }
1289}
1290
1291/*
drhe5fe6902007-12-07 18:55:28 +00001292** Invoke the busy handler for a btree.
1293*/
danielk19771ceedd32008-11-19 10:22:33 +00001294static int btreeInvokeBusyHandler(void *pArg){
drhe5fe6902007-12-07 18:55:28 +00001295 BtShared *pBt = (BtShared*)pArg;
1296 assert( pBt->db );
1297 assert( sqlite3_mutex_held(pBt->db->mutex) );
1298 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
1299}
1300
1301/*
drhad3e0102004-09-03 23:32:18 +00001302** Open a database file.
1303**
drh382c0242001-10-06 16:33:02 +00001304** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001305** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001306** database file will be deleted when sqlite3BtreeClose() is called.
drhe53831d2007-08-17 01:14:38 +00001307** If zFilename is ":memory:" then an in-memory database is created
1308** that is automatically destroyed when it is closed.
drha059ad02001-04-17 20:09:11 +00001309*/
drh23e11ca2004-05-04 17:27:28 +00001310int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001311 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00001312 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001313 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00001314 int flags, /* Options */
1315 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00001316){
drhd677b3d2007-08-20 22:48:41 +00001317 sqlite3_vfs *pVfs; /* The VFS to use for this btree */
drhe53831d2007-08-17 01:14:38 +00001318 BtShared *pBt = 0; /* Shared part of btree structure */
danielk1977aef0bf62005-12-30 16:28:01 +00001319 Btree *p; /* Handle to return */
danielk1977dddbcdc2007-04-26 14:42:34 +00001320 int rc = SQLITE_OK;
drhf49661a2008-12-10 16:45:50 +00001321 u8 nReserve;
drh90f5ecb2004-07-22 01:19:35 +00001322 unsigned char zDbHeader[100];
danielk1977aef0bf62005-12-30 16:28:01 +00001323
1324 /* Set the variable isMemdb to true for an in-memory database, or
1325 ** false for a file-based database. This symbol is only required if
1326 ** either of the shared-data or autovacuum features are compiled
1327 ** into the library.
1328 */
1329#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
1330 #ifdef SQLITE_OMIT_MEMORYDB
drh980b1a72006-08-16 16:42:48 +00001331 const int isMemdb = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00001332 #else
drh980b1a72006-08-16 16:42:48 +00001333 const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
danielk1977aef0bf62005-12-30 16:28:01 +00001334 #endif
1335#endif
1336
drhe5fe6902007-12-07 18:55:28 +00001337 assert( db!=0 );
1338 assert( sqlite3_mutex_held(db->mutex) );
drh153c62c2007-08-24 03:51:33 +00001339
drhe5fe6902007-12-07 18:55:28 +00001340 pVfs = db->pVfs;
drh17435752007-08-16 04:30:38 +00001341 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00001342 if( !p ){
1343 return SQLITE_NOMEM;
1344 }
1345 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00001346 p->db = db;
danielk1977aef0bf62005-12-30 16:28:01 +00001347
drh198bf392006-01-06 21:52:49 +00001348#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001349 /*
1350 ** If this Btree is a candidate for shared cache, try to find an
1351 ** existing BtShared object that we can share with
1352 */
drh34004ce2008-07-11 16:15:17 +00001353 if( isMemdb==0
drhe5fe6902007-12-07 18:55:28 +00001354 && (db->flags & SQLITE_Vtab)==0
drhe53831d2007-08-17 01:14:38 +00001355 && zFilename && zFilename[0]
drhe53831d2007-08-17 01:14:38 +00001356 ){
danielk1977502b4e02008-09-02 14:07:24 +00001357 if( sqlite3GlobalConfig.sharedCacheEnabled ){
danielk1977adfb9b02007-09-17 07:02:56 +00001358 int nFullPathname = pVfs->mxPathname+1;
drhe5ae5732008-06-15 02:51:47 +00001359 char *zFullPathname = sqlite3Malloc(nFullPathname);
drhff0587c2007-08-29 17:43:19 +00001360 sqlite3_mutex *mutexShared;
1361 p->sharable = 1;
drh34004ce2008-07-11 16:15:17 +00001362 db->flags |= SQLITE_SharedCache;
drhff0587c2007-08-29 17:43:19 +00001363 if( !zFullPathname ){
1364 sqlite3_free(p);
1365 return SQLITE_NOMEM;
1366 }
danielk1977adfb9b02007-09-17 07:02:56 +00001367 sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
danielk197759f8c082008-06-18 17:09:10 +00001368 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhff0587c2007-08-29 17:43:19 +00001369 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001370 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
drhff0587c2007-08-29 17:43:19 +00001371 assert( pBt->nRef>0 );
1372 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
1373 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
1374 p->pBt = pBt;
1375 pBt->nRef++;
1376 break;
1377 }
1378 }
1379 sqlite3_mutex_leave(mutexShared);
1380 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00001381 }
drhff0587c2007-08-29 17:43:19 +00001382#ifdef SQLITE_DEBUG
1383 else{
1384 /* In debug mode, we mark all persistent databases as sharable
1385 ** even when they are not. This exercises the locking code and
1386 ** gives more opportunity for asserts(sqlite3_mutex_held())
1387 ** statements to find locking problems.
1388 */
1389 p->sharable = 1;
1390 }
1391#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001392 }
1393#endif
drha059ad02001-04-17 20:09:11 +00001394 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00001395 /*
1396 ** The following asserts make sure that structures used by the btree are
1397 ** the right size. This is to guard against size changes that result
1398 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00001399 */
drhe53831d2007-08-17 01:14:38 +00001400 assert( sizeof(i64)==8 || sizeof(i64)==4 );
1401 assert( sizeof(u64)==8 || sizeof(u64)==4 );
1402 assert( sizeof(u32)==4 );
1403 assert( sizeof(u16)==2 );
1404 assert( sizeof(Pgno)==4 );
1405
1406 pBt = sqlite3MallocZero( sizeof(*pBt) );
1407 if( pBt==0 ){
1408 rc = SQLITE_NOMEM;
1409 goto btree_open_out;
1410 }
danielk197771d5d2c2008-09-29 11:49:47 +00001411 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
drh33f4e022007-09-03 15:19:34 +00001412 EXTRA_SIZE, flags, vfsFlags);
drhe53831d2007-08-17 01:14:38 +00001413 if( rc==SQLITE_OK ){
1414 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
1415 }
1416 if( rc!=SQLITE_OK ){
1417 goto btree_open_out;
1418 }
danielk19771ceedd32008-11-19 10:22:33 +00001419 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
drhe53831d2007-08-17 01:14:38 +00001420 p->pBt = pBt;
1421
drhe53831d2007-08-17 01:14:38 +00001422 sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
1423 pBt->pCursor = 0;
1424 pBt->pPage1 = 0;
1425 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
1426 pBt->pageSize = get2byte(&zDbHeader[16]);
1427 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1428 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00001429 pBt->pageSize = 0;
1430 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drhe53831d2007-08-17 01:14:38 +00001431#ifndef SQLITE_OMIT_AUTOVACUUM
1432 /* If the magic name ":memory:" will create an in-memory database, then
1433 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
1434 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
1435 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
1436 ** regular file-name. In this case the auto-vacuum applies as per normal.
1437 */
1438 if( zFilename && !isMemdb ){
1439 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
1440 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
1441 }
1442#endif
1443 nReserve = 0;
1444 }else{
1445 nReserve = zDbHeader[20];
drhe53831d2007-08-17 01:14:38 +00001446 pBt->pageSizeFixed = 1;
1447#ifndef SQLITE_OMIT_AUTOVACUUM
1448 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1449 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
1450#endif
1451 }
1452 pBt->usableSize = pBt->pageSize - nReserve;
1453 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
danielk1977a1644fd2007-08-29 12:31:25 +00001454 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drhe53831d2007-08-17 01:14:38 +00001455
1456#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1457 /* Add the new BtShared object to the linked list sharable BtShareds.
1458 */
1459 if( p->sharable ){
1460 sqlite3_mutex *mutexShared;
1461 pBt->nRef = 1;
danielk197759f8c082008-06-18 17:09:10 +00001462 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
danielk1977075c23a2008-09-01 18:34:20 +00001463 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
danielk197759f8c082008-06-18 17:09:10 +00001464 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
drh3285db22007-09-03 22:00:39 +00001465 if( pBt->mutex==0 ){
1466 rc = SQLITE_NOMEM;
drhe5fe6902007-12-07 18:55:28 +00001467 db->mallocFailed = 0;
drh3285db22007-09-03 22:00:39 +00001468 goto btree_open_out;
1469 }
drhff0587c2007-08-29 17:43:19 +00001470 }
drhe53831d2007-08-17 01:14:38 +00001471 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001472 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
1473 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
drhe53831d2007-08-17 01:14:38 +00001474 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00001475 }
drheee46cf2004-11-06 00:02:48 +00001476#endif
drh90f5ecb2004-07-22 01:19:35 +00001477 }
danielk1977aef0bf62005-12-30 16:28:01 +00001478
drhcfed7bc2006-03-13 14:28:05 +00001479#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001480 /* If the new Btree uses a sharable pBtShared, then link the new
1481 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00001482 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00001483 */
drhe53831d2007-08-17 01:14:38 +00001484 if( p->sharable ){
1485 int i;
1486 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00001487 for(i=0; i<db->nDb; i++){
1488 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00001489 while( pSib->pPrev ){ pSib = pSib->pPrev; }
1490 if( p->pBt<pSib->pBt ){
1491 p->pNext = pSib;
1492 p->pPrev = 0;
1493 pSib->pPrev = p;
1494 }else{
drhabddb0c2007-08-20 13:14:28 +00001495 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
drhe53831d2007-08-17 01:14:38 +00001496 pSib = pSib->pNext;
1497 }
1498 p->pNext = pSib->pNext;
1499 p->pPrev = pSib;
1500 if( p->pNext ){
1501 p->pNext->pPrev = p;
1502 }
1503 pSib->pNext = p;
1504 }
1505 break;
1506 }
1507 }
danielk1977aef0bf62005-12-30 16:28:01 +00001508 }
danielk1977aef0bf62005-12-30 16:28:01 +00001509#endif
1510 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00001511
1512btree_open_out:
1513 if( rc!=SQLITE_OK ){
1514 if( pBt && pBt->pPager ){
1515 sqlite3PagerClose(pBt->pPager);
1516 }
drh17435752007-08-16 04:30:38 +00001517 sqlite3_free(pBt);
1518 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00001519 *ppBtree = 0;
1520 }
1521 return rc;
drha059ad02001-04-17 20:09:11 +00001522}
1523
1524/*
drhe53831d2007-08-17 01:14:38 +00001525** Decrement the BtShared.nRef counter. When it reaches zero,
1526** remove the BtShared structure from the sharing list. Return
1527** true if the BtShared.nRef counter reaches zero and return
1528** false if it is still positive.
1529*/
1530static int removeFromSharingList(BtShared *pBt){
1531#ifndef SQLITE_OMIT_SHARED_CACHE
1532 sqlite3_mutex *pMaster;
1533 BtShared *pList;
1534 int removed = 0;
1535
drhd677b3d2007-08-20 22:48:41 +00001536 assert( sqlite3_mutex_notheld(pBt->mutex) );
danielk197759f8c082008-06-18 17:09:10 +00001537 pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhe53831d2007-08-17 01:14:38 +00001538 sqlite3_mutex_enter(pMaster);
1539 pBt->nRef--;
1540 if( pBt->nRef<=0 ){
drh78f82d12008-09-02 00:52:52 +00001541 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
1542 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
drhe53831d2007-08-17 01:14:38 +00001543 }else{
drh78f82d12008-09-02 00:52:52 +00001544 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
drh34004ce2008-07-11 16:15:17 +00001545 while( ALWAYS(pList) && pList->pNext!=pBt ){
drhe53831d2007-08-17 01:14:38 +00001546 pList=pList->pNext;
1547 }
drh34004ce2008-07-11 16:15:17 +00001548 if( ALWAYS(pList) ){
drhe53831d2007-08-17 01:14:38 +00001549 pList->pNext = pBt->pNext;
1550 }
1551 }
drh3285db22007-09-03 22:00:39 +00001552 if( SQLITE_THREADSAFE ){
1553 sqlite3_mutex_free(pBt->mutex);
1554 }
drhe53831d2007-08-17 01:14:38 +00001555 removed = 1;
1556 }
1557 sqlite3_mutex_leave(pMaster);
1558 return removed;
1559#else
1560 return 1;
1561#endif
1562}
1563
1564/*
drhf7141992008-06-19 00:16:08 +00001565** Make sure pBt->pTmpSpace points to an allocation of
1566** MX_CELL_SIZE(pBt) bytes.
1567*/
1568static void allocateTempSpace(BtShared *pBt){
1569 if( !pBt->pTmpSpace ){
1570 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
1571 }
1572}
1573
1574/*
1575** Free the pBt->pTmpSpace allocation
1576*/
1577static void freeTempSpace(BtShared *pBt){
1578 sqlite3PageFree( pBt->pTmpSpace);
1579 pBt->pTmpSpace = 0;
1580}
1581
1582/*
drha059ad02001-04-17 20:09:11 +00001583** Close an open database and invalidate all cursors.
1584*/
danielk1977aef0bf62005-12-30 16:28:01 +00001585int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00001586 BtShared *pBt = p->pBt;
1587 BtCursor *pCur;
1588
danielk1977aef0bf62005-12-30 16:28:01 +00001589 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00001590 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00001591 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00001592 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00001593 pCur = pBt->pCursor;
1594 while( pCur ){
1595 BtCursor *pTmp = pCur;
1596 pCur = pCur->pNext;
1597 if( pTmp->pBtree==p ){
1598 sqlite3BtreeCloseCursor(pTmp);
1599 }
drha059ad02001-04-17 20:09:11 +00001600 }
danielk1977aef0bf62005-12-30 16:28:01 +00001601
danielk19778d34dfd2006-01-24 16:37:57 +00001602 /* Rollback any active transaction and free the handle structure.
1603 ** The call to sqlite3BtreeRollback() drops any table-locks held by
1604 ** this handle.
1605 */
danielk1977b597f742006-01-15 11:39:18 +00001606 sqlite3BtreeRollback(p);
drhe53831d2007-08-17 01:14:38 +00001607 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001608
danielk1977aef0bf62005-12-30 16:28:01 +00001609 /* If there are still other outstanding references to the shared-btree
1610 ** structure, return now. The remainder of this procedure cleans
1611 ** up the shared-btree.
1612 */
drhe53831d2007-08-17 01:14:38 +00001613 assert( p->wantToLock==0 && p->locked==0 );
1614 if( !p->sharable || removeFromSharingList(pBt) ){
1615 /* The pBt is no longer on the sharing list, so we can access
1616 ** it without having to hold the mutex.
1617 **
1618 ** Clean out and delete the BtShared object.
1619 */
1620 assert( !pBt->pCursor );
drhe53831d2007-08-17 01:14:38 +00001621 sqlite3PagerClose(pBt->pPager);
1622 if( pBt->xFreeSchema && pBt->pSchema ){
1623 pBt->xFreeSchema(pBt->pSchema);
1624 }
1625 sqlite3_free(pBt->pSchema);
drhf7141992008-06-19 00:16:08 +00001626 freeTempSpace(pBt);
drh65bbf292008-06-19 01:03:17 +00001627 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00001628 }
1629
drhe53831d2007-08-17 01:14:38 +00001630#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00001631 assert( p->wantToLock==0 );
1632 assert( p->locked==0 );
1633 if( p->pPrev ) p->pPrev->pNext = p->pNext;
1634 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00001635#endif
1636
drhe53831d2007-08-17 01:14:38 +00001637 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00001638 return SQLITE_OK;
1639}
1640
1641/*
drhda47d772002-12-02 04:25:19 +00001642** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001643**
1644** The maximum number of cache pages is set to the absolute
1645** value of mxPage. If mxPage is negative, the pager will
1646** operate asynchronously - it will not stop to do fsync()s
1647** to insure data is written to the disk surface before
1648** continuing. Transactions still work if synchronous is off,
1649** and the database cannot be corrupted if this program
1650** crashes. But if the operating system crashes or there is
1651** an abrupt power failure when synchronous is off, the database
1652** could be left in an inconsistent and unrecoverable state.
1653** Synchronous is on by default so database corruption is not
1654** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001655*/
danielk1977aef0bf62005-12-30 16:28:01 +00001656int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
1657 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001658 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001659 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001660 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00001661 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00001662 return SQLITE_OK;
1663}
1664
1665/*
drh973b6e32003-02-12 14:09:42 +00001666** Change the way data is synced to disk in order to increase or decrease
1667** how well the database resists damage due to OS crashes and power
1668** failures. Level 1 is the same as asynchronous (no syncs() occur and
1669** there is a high probability of damage) Level 2 is the default. There
1670** is a very low but non-zero probability of damage. Level 3 reduces the
1671** probability of damage to near zero but with a write performance reduction.
1672*/
danielk197793758c82005-01-21 08:13:14 +00001673#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drhac530b12006-02-11 01:25:50 +00001674int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
danielk1977aef0bf62005-12-30 16:28:01 +00001675 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001676 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001677 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001678 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
drhd677b3d2007-08-20 22:48:41 +00001679 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00001680 return SQLITE_OK;
1681}
danielk197793758c82005-01-21 08:13:14 +00001682#endif
drh973b6e32003-02-12 14:09:42 +00001683
drh2c8997b2005-08-27 16:36:48 +00001684/*
1685** Return TRUE if the given btree is set to safety level 1. In other
1686** words, return TRUE if no sync() occurs on the disk files.
1687*/
danielk1977aef0bf62005-12-30 16:28:01 +00001688int sqlite3BtreeSyncDisabled(Btree *p){
1689 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001690 int rc;
drhe5fe6902007-12-07 18:55:28 +00001691 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001692 sqlite3BtreeEnter(p);
drhd0679ed2007-08-28 22:24:34 +00001693 assert( pBt && pBt->pPager );
drhd677b3d2007-08-20 22:48:41 +00001694 rc = sqlite3PagerNosync(pBt->pPager);
1695 sqlite3BtreeLeave(p);
1696 return rc;
drh2c8997b2005-08-27 16:36:48 +00001697}
1698
danielk1977576ec6b2005-01-21 11:55:25 +00001699#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00001700/*
drh90f5ecb2004-07-22 01:19:35 +00001701** Change the default pages size and the number of reserved bytes per page.
drh06f50212004-11-02 14:24:33 +00001702**
1703** The page size must be a power of 2 between 512 and 65536. If the page
1704** size supplied does not meet this constraint then the page size is not
1705** changed.
1706**
1707** Page sizes are constrained to be a power of two so that the region
1708** of the database file used for locking (beginning at PENDING_BYTE,
1709** the first byte past the 1GB boundary, 0x40000000) needs to occur
1710** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001711**
1712** If parameter nReserve is less than zero, then the number of reserved
1713** bytes per page is left unchanged.
drh90f5ecb2004-07-22 01:19:35 +00001714*/
danielk1977aef0bf62005-12-30 16:28:01 +00001715int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
danielk1977a1644fd2007-08-29 12:31:25 +00001716 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00001717 BtShared *pBt = p->pBt;
drhf49661a2008-12-10 16:45:50 +00001718 assert( nReserve>=-1 && nReserve<=255 );
drhd677b3d2007-08-20 22:48:41 +00001719 sqlite3BtreeEnter(p);
drh90f5ecb2004-07-22 01:19:35 +00001720 if( pBt->pageSizeFixed ){
drhd677b3d2007-08-20 22:48:41 +00001721 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00001722 return SQLITE_READONLY;
1723 }
1724 if( nReserve<0 ){
1725 nReserve = pBt->pageSize - pBt->usableSize;
1726 }
drhf49661a2008-12-10 16:45:50 +00001727 assert( nReserve>=0 && nReserve<=255 );
drh06f50212004-11-02 14:24:33 +00001728 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
1729 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00001730 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00001731 assert( !pBt->pPage1 && !pBt->pCursor );
drh1bd10f82008-12-10 21:19:56 +00001732 pBt->pageSize = (u16)pageSize;
drhf7141992008-06-19 00:16:08 +00001733 freeTempSpace(pBt);
danielk1977a1644fd2007-08-29 12:31:25 +00001734 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001735 }
drhf49661a2008-12-10 16:45:50 +00001736 pBt->usableSize = pBt->pageSize - (u16)nReserve;
drhd677b3d2007-08-20 22:48:41 +00001737 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00001738 return rc;
drh90f5ecb2004-07-22 01:19:35 +00001739}
1740
1741/*
1742** Return the currently defined page size
1743*/
danielk1977aef0bf62005-12-30 16:28:01 +00001744int sqlite3BtreeGetPageSize(Btree *p){
1745 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00001746}
danielk1977aef0bf62005-12-30 16:28:01 +00001747int sqlite3BtreeGetReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00001748 int n;
1749 sqlite3BtreeEnter(p);
1750 n = p->pBt->pageSize - p->pBt->usableSize;
1751 sqlite3BtreeLeave(p);
1752 return n;
drh2011d5f2004-07-22 02:40:37 +00001753}
drhf8e632b2007-05-08 14:51:36 +00001754
1755/*
1756** Set the maximum page count for a database if mxPage is positive.
1757** No changes are made if mxPage is 0 or negative.
1758** Regardless of the value of mxPage, return the maximum page count.
1759*/
1760int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00001761 int n;
1762 sqlite3BtreeEnter(p);
1763 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
1764 sqlite3BtreeLeave(p);
1765 return n;
drhf8e632b2007-05-08 14:51:36 +00001766}
danielk1977576ec6b2005-01-21 11:55:25 +00001767#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00001768
1769/*
danielk1977951af802004-11-05 15:45:09 +00001770** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
1771** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
1772** is disabled. The default value for the auto-vacuum property is
1773** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
1774*/
danielk1977aef0bf62005-12-30 16:28:01 +00001775int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00001776#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001777 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00001778#else
danielk1977dddbcdc2007-04-26 14:42:34 +00001779 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001780 int rc = SQLITE_OK;
drh076d4662009-02-18 20:31:18 +00001781 u8 av = (u8)autoVacuum;
drhd677b3d2007-08-20 22:48:41 +00001782
1783 sqlite3BtreeEnter(p);
drh076d4662009-02-18 20:31:18 +00001784 if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00001785 rc = SQLITE_READONLY;
1786 }else{
drh076d4662009-02-18 20:31:18 +00001787 pBt->autoVacuum = av ?1:0;
1788 pBt->incrVacuum = av==2 ?1:0;
danielk1977951af802004-11-05 15:45:09 +00001789 }
drhd677b3d2007-08-20 22:48:41 +00001790 sqlite3BtreeLeave(p);
1791 return rc;
danielk1977951af802004-11-05 15:45:09 +00001792#endif
1793}
1794
1795/*
1796** Return the value of the 'auto-vacuum' property. If auto-vacuum is
1797** enabled 1 is returned. Otherwise 0.
1798*/
danielk1977aef0bf62005-12-30 16:28:01 +00001799int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00001800#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00001801 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00001802#else
drhd677b3d2007-08-20 22:48:41 +00001803 int rc;
1804 sqlite3BtreeEnter(p);
1805 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00001806 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
1807 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
1808 BTREE_AUTOVACUUM_INCR
1809 );
drhd677b3d2007-08-20 22:48:41 +00001810 sqlite3BtreeLeave(p);
1811 return rc;
danielk1977951af802004-11-05 15:45:09 +00001812#endif
1813}
1814
1815
1816/*
drha34b6762004-05-07 13:30:42 +00001817** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001818** also acquire a readlock on that file.
1819**
1820** SQLITE_OK is returned on success. If the file is not a
1821** well-formed database file, then SQLITE_CORRUPT is returned.
1822** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00001823** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00001824*/
danielk1977aef0bf62005-12-30 16:28:01 +00001825static int lockBtree(BtShared *pBt){
danielk1977f653d782008-03-20 11:04:21 +00001826 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001827 MemPage *pPage1;
danielk197793f7af92008-05-09 16:57:50 +00001828 int nPage;
drhd677b3d2007-08-20 22:48:41 +00001829
drh1fee73e2007-08-29 04:00:57 +00001830 assert( sqlite3_mutex_held(pBt->mutex) );
drha34b6762004-05-07 13:30:42 +00001831 if( pBt->pPage1 ) return SQLITE_OK;
drh16a9b832007-05-05 18:39:25 +00001832 rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00001833 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00001834
1835 /* Do some checking to help insure the file we opened really is
1836 ** a valid database file.
1837 */
danielk1977ad0132d2008-06-07 08:58:22 +00001838 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1839 if( rc!=SQLITE_OK ){
danielk197793f7af92008-05-09 16:57:50 +00001840 goto page1_init_failed;
1841 }else if( nPage>0 ){
danielk1977f653d782008-03-20 11:04:21 +00001842 int pageSize;
1843 int usableSize;
drhb6f41482004-05-14 01:58:11 +00001844 u8 *page1 = pPage1->aData;
danielk1977ad0132d2008-06-07 08:58:22 +00001845 rc = SQLITE_NOTADB;
drhb6f41482004-05-14 01:58:11 +00001846 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001847 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001848 }
drh309169a2007-04-24 17:27:51 +00001849 if( page1[18]>1 ){
1850 pBt->readOnly = 1;
1851 }
1852 if( page1[19]>1 ){
drhb6f41482004-05-14 01:58:11 +00001853 goto page1_init_failed;
1854 }
drhe5ae5732008-06-15 02:51:47 +00001855
1856 /* The maximum embedded fraction must be exactly 25%. And the minimum
1857 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
1858 ** The original design allowed these amounts to vary, but as of
1859 ** version 3.6.0, we require them to be fixed.
1860 */
1861 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
1862 goto page1_init_failed;
1863 }
drh07d183d2005-05-01 22:52:42 +00001864 pageSize = get2byte(&page1[16]);
drh7dc385e2007-09-06 23:39:36 +00001865 if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
1866 (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
1867 ){
drh07d183d2005-05-01 22:52:42 +00001868 goto page1_init_failed;
1869 }
1870 assert( (pageSize & 7)==0 );
danielk1977f653d782008-03-20 11:04:21 +00001871 usableSize = pageSize - page1[20];
1872 if( pageSize!=pBt->pageSize ){
1873 /* After reading the first page of the database assuming a page size
1874 ** of BtShared.pageSize, we have discovered that the page-size is
1875 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
1876 ** zero and return SQLITE_OK. The caller will call this function
1877 ** again with the correct page-size.
1878 */
1879 releasePage(pPage1);
drhf49661a2008-12-10 16:45:50 +00001880 pBt->usableSize = (u16)usableSize;
1881 pBt->pageSize = (u16)pageSize;
drhf7141992008-06-19 00:16:08 +00001882 freeTempSpace(pBt);
danielk1977f653d782008-03-20 11:04:21 +00001883 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
1884 return SQLITE_OK;
1885 }
1886 if( usableSize<500 ){
drhb6f41482004-05-14 01:58:11 +00001887 goto page1_init_failed;
1888 }
drh1bd10f82008-12-10 21:19:56 +00001889 pBt->pageSize = (u16)pageSize;
1890 pBt->usableSize = (u16)usableSize;
drh057cd3a2005-02-15 16:23:02 +00001891#ifndef SQLITE_OMIT_AUTOVACUUM
1892 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00001893 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00001894#endif
drh306dc212001-05-21 13:45:10 +00001895 }
drhb6f41482004-05-14 01:58:11 +00001896
1897 /* maxLocal is the maximum amount of payload to store locally for
1898 ** a cell. Make sure it is small enough so that at least minFanout
1899 ** cells can will fit on one page. We assume a 10-byte page header.
1900 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001901 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001902 ** 4-byte child pointer
1903 ** 9-byte nKey value
1904 ** 4-byte nData value
1905 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001906 ** So a cell consists of a 2-byte poiner, a header which is as much as
1907 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1908 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001909 */
drhe5ae5732008-06-15 02:51:47 +00001910 pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
1911 pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
drh43605152004-05-29 21:46:49 +00001912 pBt->maxLeaf = pBt->usableSize - 35;
drhe5ae5732008-06-15 02:51:47 +00001913 pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
drh2e38c322004-09-03 18:38:44 +00001914 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00001915 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001916 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001917
drh72f82862001-05-24 21:06:34 +00001918page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001919 releasePage(pPage1);
1920 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001921 return rc;
drh306dc212001-05-21 13:45:10 +00001922}
1923
1924/*
drhb8ef32c2005-03-14 02:01:49 +00001925** This routine works like lockBtree() except that it also invokes the
1926** busy callback if there is lock contention.
1927*/
danielk1977aef0bf62005-12-30 16:28:01 +00001928static int lockBtreeWithRetry(Btree *pRef){
drhb8ef32c2005-03-14 02:01:49 +00001929 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00001930
drh1fee73e2007-08-29 04:00:57 +00001931 assert( sqlite3BtreeHoldsMutex(pRef) );
danielk1977aef0bf62005-12-30 16:28:01 +00001932 if( pRef->inTrans==TRANS_NONE ){
1933 u8 inTransaction = pRef->pBt->inTransaction;
1934 btreeIntegrity(pRef);
1935 rc = sqlite3BtreeBeginTrans(pRef, 0);
1936 pRef->pBt->inTransaction = inTransaction;
1937 pRef->inTrans = TRANS_NONE;
1938 if( rc==SQLITE_OK ){
1939 pRef->pBt->nTransaction--;
1940 }
1941 btreeIntegrity(pRef);
drhb8ef32c2005-03-14 02:01:49 +00001942 }
1943 return rc;
1944}
1945
1946
1947/*
drhb8ca3072001-12-05 00:21:20 +00001948** If there are no outstanding cursors and we are not in the middle
1949** of a transaction but there is a read lock on the database, then
1950** this routine unrefs the first page of the database file which
1951** has the effect of releasing the read lock.
1952**
1953** If there are any outstanding cursors, this routine is a no-op.
1954**
1955** If there is a transaction in progress, this routine is a no-op.
1956*/
danielk1977aef0bf62005-12-30 16:28:01 +00001957static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00001958 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00001959 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00001960 if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
drhde4fcfd2008-01-19 23:50:26 +00001961 assert( pBt->pPage1->aData );
1962#if 0
drh24c9a2e2007-01-05 02:00:47 +00001963 if( pBt->pPage1->aData==0 ){
1964 MemPage *pPage = pBt->pPage1;
drhbf4bca52007-09-06 22:19:14 +00001965 pPage->aData = sqlite3PagerGetData(pPage->pDbPage);
drh24c9a2e2007-01-05 02:00:47 +00001966 pPage->pBt = pBt;
1967 pPage->pgno = 1;
1968 }
drhde4fcfd2008-01-19 23:50:26 +00001969#endif
drh24c9a2e2007-01-05 02:00:47 +00001970 releasePage(pBt->pPage1);
drh51c6d962004-06-06 00:42:25 +00001971 }
drh3aac2dd2004-04-26 14:10:20 +00001972 pBt->pPage1 = 0;
drh3aac2dd2004-04-26 14:10:20 +00001973 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001974 }
1975}
1976
1977/*
drh9e572e62004-04-23 23:43:10 +00001978** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00001979** file.
drh8b2f49b2001-06-08 00:21:52 +00001980*/
danielk1977aef0bf62005-12-30 16:28:01 +00001981static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00001982 MemPage *pP1;
1983 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00001984 int rc;
danielk1977ad0132d2008-06-07 08:58:22 +00001985 int nPage;
drhd677b3d2007-08-20 22:48:41 +00001986
drh1fee73e2007-08-29 04:00:57 +00001987 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977ad0132d2008-06-07 08:58:22 +00001988 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1989 if( rc!=SQLITE_OK || nPage>0 ){
1990 return rc;
1991 }
drh3aac2dd2004-04-26 14:10:20 +00001992 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00001993 assert( pP1!=0 );
1994 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00001995 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00001996 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00001997 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
1998 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00001999 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00002000 data[18] = 1;
2001 data[19] = 1;
drhf49661a2008-12-10 16:45:50 +00002002 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
2003 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
drhe5ae5732008-06-15 02:51:47 +00002004 data[21] = 64;
2005 data[22] = 32;
2006 data[23] = 32;
drhb6f41482004-05-14 01:58:11 +00002007 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00002008 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00002009 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00002010#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002011 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00002012 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00002013 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00002014 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00002015#endif
drh8b2f49b2001-06-08 00:21:52 +00002016 return SQLITE_OK;
2017}
2018
2019/*
danielk1977ee5741e2004-05-31 10:01:34 +00002020** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00002021** is started if the second argument is nonzero, otherwise a read-
2022** transaction. If the second argument is 2 or more and exclusive
2023** transaction is started, meaning that no other process is allowed
2024** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00002025** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00002026** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00002027**
danielk1977ee5741e2004-05-31 10:01:34 +00002028** A write-transaction must be started before attempting any
2029** changes to the database. None of the following routines
2030** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00002031**
drh23e11ca2004-05-04 17:27:28 +00002032** sqlite3BtreeCreateTable()
2033** sqlite3BtreeCreateIndex()
2034** sqlite3BtreeClearTable()
2035** sqlite3BtreeDropTable()
2036** sqlite3BtreeInsert()
2037** sqlite3BtreeDelete()
2038** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00002039**
drhb8ef32c2005-03-14 02:01:49 +00002040** If an initial attempt to acquire the lock fails because of lock contention
2041** and the database was previously unlocked, then invoke the busy handler
2042** if there is one. But if there was previously a read-lock, do not
2043** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
2044** returned when there is already a read-lock in order to avoid a deadlock.
2045**
2046** Suppose there are two processes A and B. A has a read lock and B has
2047** a reserved lock. B tries to promote to exclusive but is blocked because
2048** of A's read lock. A tries to promote to reserved but is blocked by B.
2049** One or the other of the two processes must give way or there can be
2050** no progress. By returning SQLITE_BUSY and not invoking the busy callback
2051** when A already has a read lock, we encourage A to give up and let B
2052** proceed.
drha059ad02001-04-17 20:09:11 +00002053*/
danielk1977aef0bf62005-12-30 16:28:01 +00002054int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
2055 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00002056 int rc = SQLITE_OK;
2057
drhd677b3d2007-08-20 22:48:41 +00002058 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002059 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00002060 btreeIntegrity(p);
2061
danielk1977ee5741e2004-05-31 10:01:34 +00002062 /* If the btree is already in a write-transaction, or it
2063 ** is already in a read-transaction and a read-transaction
2064 ** is requested, this is a no-op.
2065 */
danielk1977aef0bf62005-12-30 16:28:01 +00002066 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00002067 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002068 }
drhb8ef32c2005-03-14 02:01:49 +00002069
2070 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00002071 if( pBt->readOnly && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00002072 rc = SQLITE_READONLY;
2073 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002074 }
2075
danielk1977aef0bf62005-12-30 16:28:01 +00002076 /* If another database handle has already opened a write transaction
2077 ** on this shared-btree structure and a second write transaction is
2078 ** requested, return SQLITE_BUSY.
2079 */
2080 if( pBt->inTransaction==TRANS_WRITE && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00002081 rc = SQLITE_BUSY;
2082 goto trans_begun;
danielk1977aef0bf62005-12-30 16:28:01 +00002083 }
2084
danielk1977641b0f42007-12-21 04:47:25 +00002085#ifndef SQLITE_OMIT_SHARED_CACHE
2086 if( wrflag>1 ){
2087 BtLock *pIter;
2088 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
2089 if( pIter->pBtree!=p ){
2090 rc = SQLITE_BUSY;
2091 goto trans_begun;
2092 }
2093 }
2094 }
2095#endif
2096
drhb8ef32c2005-03-14 02:01:49 +00002097 do {
drh8a9c17f2008-05-02 14:23:54 +00002098 if( pBt->pPage1==0 ){
2099 do{
2100 rc = lockBtree(pBt);
2101 }while( pBt->pPage1==0 && rc==SQLITE_OK );
drh8c42ca92001-06-22 19:15:00 +00002102 }
drh309169a2007-04-24 17:27:51 +00002103
drhb8ef32c2005-03-14 02:01:49 +00002104 if( rc==SQLITE_OK && wrflag ){
drh309169a2007-04-24 17:27:51 +00002105 if( pBt->readOnly ){
2106 rc = SQLITE_READONLY;
2107 }else{
danielk1977bea2a942009-01-20 17:06:27 +00002108 rc = sqlite3PagerBegin(pBt->pPager, wrflag>1);
drh309169a2007-04-24 17:27:51 +00002109 if( rc==SQLITE_OK ){
2110 rc = newDatabase(pBt);
2111 }
drhb8ef32c2005-03-14 02:01:49 +00002112 }
2113 }
2114
2115 if( rc==SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00002116 if( wrflag ) pBt->inStmt = 0;
2117 }else{
2118 unlockBtreeIfUnused(pBt);
2119 }
danielk1977aef0bf62005-12-30 16:28:01 +00002120 }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
danielk19771ceedd32008-11-19 10:22:33 +00002121 btreeInvokeBusyHandler(pBt) );
danielk1977aef0bf62005-12-30 16:28:01 +00002122
2123 if( rc==SQLITE_OK ){
2124 if( p->inTrans==TRANS_NONE ){
2125 pBt->nTransaction++;
2126 }
2127 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
2128 if( p->inTrans>pBt->inTransaction ){
2129 pBt->inTransaction = p->inTrans;
2130 }
danielk1977641b0f42007-12-21 04:47:25 +00002131#ifndef SQLITE_OMIT_SHARED_CACHE
2132 if( wrflag>1 ){
2133 assert( !pBt->pExclusive );
2134 pBt->pExclusive = p;
2135 }
2136#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002137 }
2138
drhd677b3d2007-08-20 22:48:41 +00002139
2140trans_begun:
danielk1977fd7f0452008-12-17 17:30:26 +00002141 if( rc==SQLITE_OK && wrflag ){
danielk197712dd5492008-12-18 15:45:07 +00002142 /* This call makes sure that the pager has the correct number of
2143 ** open savepoints. If the second parameter is greater than 0 and
2144 ** the sub-journal is not already open, then it will be opened here.
2145 */
danielk1977fd7f0452008-12-17 17:30:26 +00002146 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
2147 }
danielk197712dd5492008-12-18 15:45:07 +00002148
danielk1977aef0bf62005-12-30 16:28:01 +00002149 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002150 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00002151 return rc;
drha059ad02001-04-17 20:09:11 +00002152}
2153
danielk1977687566d2004-11-02 12:56:41 +00002154#ifndef SQLITE_OMIT_AUTOVACUUM
2155
2156/*
2157** Set the pointer-map entries for all children of page pPage. Also, if
2158** pPage contains cells that point to overflow pages, set the pointer
2159** map entries for the overflow pages as well.
2160*/
2161static int setChildPtrmaps(MemPage *pPage){
2162 int i; /* Counter variable */
2163 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00002164 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00002165 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00002166 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002167 Pgno pgno = pPage->pgno;
2168
drh1fee73e2007-08-29 04:00:57 +00002169 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197771d5d2c2008-09-29 11:49:47 +00002170 rc = sqlite3BtreeInitPage(pPage);
danielk19772df71c72007-05-24 07:22:42 +00002171 if( rc!=SQLITE_OK ){
2172 goto set_child_ptrmaps_out;
2173 }
danielk1977687566d2004-11-02 12:56:41 +00002174 nCell = pPage->nCell;
2175
2176 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002177 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002178
danielk197726836652005-01-17 01:33:13 +00002179 rc = ptrmapPutOvflPtr(pPage, pCell);
2180 if( rc!=SQLITE_OK ){
2181 goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002182 }
danielk197726836652005-01-17 01:33:13 +00002183
danielk1977687566d2004-11-02 12:56:41 +00002184 if( !pPage->leaf ){
2185 Pgno childPgno = get4byte(pCell);
2186 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
danielk197700a696d2008-09-29 16:41:31 +00002187 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002188 }
2189 }
2190
2191 if( !pPage->leaf ){
2192 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
2193 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
2194 }
2195
2196set_child_ptrmaps_out:
2197 pPage->isInit = isInitOrig;
2198 return rc;
2199}
2200
2201/*
2202** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
2203** page, is a pointer to page iFrom. Modify this pointer so that it points to
2204** iTo. Parameter eType describes the type of pointer to be modified, as
2205** follows:
2206**
2207** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
2208** page of pPage.
2209**
2210** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
2211** page pointed to by one of the cells on pPage.
2212**
2213** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
2214** overflow page in the list.
2215*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00002216static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00002217 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00002218 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977687566d2004-11-02 12:56:41 +00002219 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00002220 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00002221 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00002222 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002223 }
danielk1977f78fc082004-11-02 14:40:32 +00002224 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00002225 }else{
drhf49661a2008-12-10 16:45:50 +00002226 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002227 int i;
2228 int nCell;
2229
danielk197771d5d2c2008-09-29 11:49:47 +00002230 sqlite3BtreeInitPage(pPage);
danielk1977687566d2004-11-02 12:56:41 +00002231 nCell = pPage->nCell;
2232
danielk1977687566d2004-11-02 12:56:41 +00002233 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002234 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002235 if( eType==PTRMAP_OVERFLOW1 ){
2236 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00002237 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
danielk1977687566d2004-11-02 12:56:41 +00002238 if( info.iOverflow ){
2239 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
2240 put4byte(&pCell[info.iOverflow], iTo);
2241 break;
2242 }
2243 }
2244 }else{
2245 if( get4byte(pCell)==iFrom ){
2246 put4byte(pCell, iTo);
2247 break;
2248 }
2249 }
2250 }
2251
2252 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00002253 if( eType!=PTRMAP_BTREE ||
2254 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00002255 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002256 }
danielk1977687566d2004-11-02 12:56:41 +00002257 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
2258 }
2259
2260 pPage->isInit = isInitOrig;
2261 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002262 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002263}
2264
danielk1977003ba062004-11-04 02:57:33 +00002265
danielk19777701e812005-01-10 12:59:51 +00002266/*
2267** Move the open database page pDbPage to location iFreePage in the
2268** database. The pDbPage reference remains valid.
2269*/
danielk1977003ba062004-11-04 02:57:33 +00002270static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00002271 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00002272 MemPage *pDbPage, /* Open page to move */
2273 u8 eType, /* Pointer map 'type' entry for pDbPage */
2274 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
danielk19774c999992008-07-16 18:17:55 +00002275 Pgno iFreePage, /* The location to move pDbPage to */
2276 int isCommit
danielk1977003ba062004-11-04 02:57:33 +00002277){
2278 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
2279 Pgno iDbPage = pDbPage->pgno;
2280 Pager *pPager = pBt->pPager;
2281 int rc;
2282
danielk1977a0bf2652004-11-04 14:30:04 +00002283 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
2284 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00002285 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00002286 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00002287
drh85b623f2007-12-13 21:54:09 +00002288 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00002289 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
2290 iDbPage, iFreePage, iPtrPage, eType));
danielk19774c999992008-07-16 18:17:55 +00002291 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
danielk1977003ba062004-11-04 02:57:33 +00002292 if( rc!=SQLITE_OK ){
2293 return rc;
2294 }
2295 pDbPage->pgno = iFreePage;
2296
2297 /* If pDbPage was a btree-page, then it may have child pages and/or cells
2298 ** that point to overflow pages. The pointer map entries for all these
2299 ** pages need to be changed.
2300 **
2301 ** If pDbPage is an overflow page, then the first 4 bytes may store a
2302 ** pointer to a subsequent overflow page. If this is the case, then
2303 ** the pointer map needs to be updated for the subsequent overflow page.
2304 */
danielk1977a0bf2652004-11-04 14:30:04 +00002305 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00002306 rc = setChildPtrmaps(pDbPage);
2307 if( rc!=SQLITE_OK ){
2308 return rc;
2309 }
2310 }else{
2311 Pgno nextOvfl = get4byte(pDbPage->aData);
2312 if( nextOvfl!=0 ){
danielk1977003ba062004-11-04 02:57:33 +00002313 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
2314 if( rc!=SQLITE_OK ){
2315 return rc;
2316 }
2317 }
2318 }
2319
2320 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
2321 ** that it points at iFreePage. Also fix the pointer map entry for
2322 ** iPtrPage.
2323 */
danielk1977a0bf2652004-11-04 14:30:04 +00002324 if( eType!=PTRMAP_ROOTPAGE ){
drh16a9b832007-05-05 18:39:25 +00002325 rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00002326 if( rc!=SQLITE_OK ){
2327 return rc;
2328 }
danielk19773b8a05f2007-03-19 17:44:26 +00002329 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00002330 if( rc!=SQLITE_OK ){
2331 releasePage(pPtrPage);
2332 return rc;
2333 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002334 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00002335 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00002336 if( rc==SQLITE_OK ){
2337 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
2338 }
danielk1977003ba062004-11-04 02:57:33 +00002339 }
danielk1977003ba062004-11-04 02:57:33 +00002340 return rc;
2341}
2342
danielk1977dddbcdc2007-04-26 14:42:34 +00002343/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00002344static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00002345
2346/*
danielk1977dddbcdc2007-04-26 14:42:34 +00002347** Perform a single step of an incremental-vacuum. If successful,
2348** return SQLITE_OK. If there is no work to do (and therefore no
2349** point in calling this function again), return SQLITE_DONE.
2350**
2351** More specificly, this function attempts to re-organize the
2352** database so that the last page of the file currently in use
2353** is no longer in use.
2354**
2355** If the nFin parameter is non-zero, the implementation assumes
2356** that the caller will keep calling incrVacuumStep() until
2357** it returns SQLITE_DONE or an error, and that nFin is the
2358** number of pages the database file will contain after this
2359** process is complete.
2360*/
danielk19773460d192008-12-27 15:23:13 +00002361static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
danielk1977dddbcdc2007-04-26 14:42:34 +00002362 Pgno nFreeList; /* Number of pages still on the free-list */
2363
drh1fee73e2007-08-29 04:00:57 +00002364 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977dddbcdc2007-04-26 14:42:34 +00002365
2366 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
2367 int rc;
2368 u8 eType;
2369 Pgno iPtrPage;
2370
2371 nFreeList = get4byte(&pBt->pPage1->aData[36]);
2372 if( nFreeList==0 || nFin==iLastPg ){
2373 return SQLITE_DONE;
2374 }
2375
2376 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
2377 if( rc!=SQLITE_OK ){
2378 return rc;
2379 }
2380 if( eType==PTRMAP_ROOTPAGE ){
2381 return SQLITE_CORRUPT_BKPT;
2382 }
2383
2384 if( eType==PTRMAP_FREEPAGE ){
2385 if( nFin==0 ){
2386 /* Remove the page from the files free-list. This is not required
danielk19774ef24492007-05-23 09:52:41 +00002387 ** if nFin is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00002388 ** truncated to zero after this function returns, so it doesn't
2389 ** matter if it still contains some garbage entries.
2390 */
2391 Pgno iFreePg;
2392 MemPage *pFreePg;
2393 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
2394 if( rc!=SQLITE_OK ){
2395 return rc;
2396 }
2397 assert( iFreePg==iLastPg );
2398 releasePage(pFreePg);
2399 }
2400 } else {
2401 Pgno iFreePg; /* Index of free page to move pLastPg to */
2402 MemPage *pLastPg;
2403
drh16a9b832007-05-05 18:39:25 +00002404 rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002405 if( rc!=SQLITE_OK ){
2406 return rc;
2407 }
2408
danielk1977b4626a32007-04-28 15:47:43 +00002409 /* If nFin is zero, this loop runs exactly once and page pLastPg
2410 ** is swapped with the first free page pulled off the free list.
2411 **
2412 ** On the other hand, if nFin is greater than zero, then keep
2413 ** looping until a free-page located within the first nFin pages
2414 ** of the file is found.
2415 */
danielk1977dddbcdc2007-04-26 14:42:34 +00002416 do {
2417 MemPage *pFreePg;
2418 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
2419 if( rc!=SQLITE_OK ){
2420 releasePage(pLastPg);
2421 return rc;
2422 }
2423 releasePage(pFreePg);
2424 }while( nFin!=0 && iFreePg>nFin );
2425 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00002426
2427 rc = sqlite3PagerWrite(pLastPg->pDbPage);
danielk1977662278e2007-11-05 15:30:12 +00002428 if( rc==SQLITE_OK ){
danielk19774c999992008-07-16 18:17:55 +00002429 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
danielk1977662278e2007-11-05 15:30:12 +00002430 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002431 releasePage(pLastPg);
2432 if( rc!=SQLITE_OK ){
2433 return rc;
danielk1977662278e2007-11-05 15:30:12 +00002434 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002435 }
2436 }
2437
danielk19773460d192008-12-27 15:23:13 +00002438 if( nFin==0 ){
2439 iLastPg--;
2440 while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
2441 iLastPg--;
2442 }
2443 sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
danielk1977dddbcdc2007-04-26 14:42:34 +00002444 }
2445 return SQLITE_OK;
2446}
2447
2448/*
2449** A write-transaction must be opened before calling this function.
2450** It performs a single unit of work towards an incremental vacuum.
2451**
2452** If the incremental vacuum is finished after this function has run,
2453** SQLITE_DONE is returned. If it is not finished, but no error occured,
2454** SQLITE_OK is returned. Otherwise an SQLite error code.
2455*/
2456int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002457 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002458 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002459
2460 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002461 pBt->db = p->db;
danielk1977dddbcdc2007-04-26 14:42:34 +00002462 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
2463 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002464 rc = SQLITE_DONE;
2465 }else{
2466 invalidateAllOverflowCache(pBt);
danielk1977bea2a942009-01-20 17:06:27 +00002467 rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt));
danielk1977dddbcdc2007-04-26 14:42:34 +00002468 }
drhd677b3d2007-08-20 22:48:41 +00002469 sqlite3BtreeLeave(p);
2470 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002471}
2472
2473/*
danielk19773b8a05f2007-03-19 17:44:26 +00002474** This routine is called prior to sqlite3PagerCommit when a transaction
danielk1977687566d2004-11-02 12:56:41 +00002475** is commited for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00002476**
2477** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
2478** the database file should be truncated to during the commit process.
2479** i.e. the database has been reorganized so that only the first *pnTrunc
2480** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00002481*/
danielk19773460d192008-12-27 15:23:13 +00002482static int autoVacuumCommit(BtShared *pBt){
danielk1977dddbcdc2007-04-26 14:42:34 +00002483 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002484 Pager *pPager = pBt->pPager;
drhf94a1732008-09-30 17:18:17 +00002485 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002486
drh1fee73e2007-08-29 04:00:57 +00002487 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00002488 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00002489 assert(pBt->autoVacuum);
2490 if( !pBt->incrVacuum ){
danielk19773460d192008-12-27 15:23:13 +00002491 Pgno nFin;
2492 Pgno nFree;
2493 Pgno nPtrmap;
2494 Pgno iFree;
2495 const int pgsz = pBt->pageSize;
2496 Pgno nOrig = pagerPagecount(pBt);
danielk1977687566d2004-11-02 12:56:41 +00002497
danielk19773460d192008-12-27 15:23:13 +00002498 if( PTRMAP_ISPAGE(pBt, nOrig) ){
2499 return SQLITE_CORRUPT_BKPT;
2500 }
2501 if( nOrig==PENDING_BYTE_PAGE(pBt) ){
2502 nOrig--;
2503 }
2504 nFree = get4byte(&pBt->pPage1->aData[36]);
2505 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
2506 nFin = nOrig - nFree - nPtrmap;
2507 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
2508 nFin--;
2509 }
2510 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
2511 nFin--;
danielk1977dddbcdc2007-04-26 14:42:34 +00002512 }
danielk1977687566d2004-11-02 12:56:41 +00002513
danielk19773460d192008-12-27 15:23:13 +00002514 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
2515 rc = incrVacuumStep(pBt, nFin, iFree);
danielk1977dddbcdc2007-04-26 14:42:34 +00002516 }
danielk19773460d192008-12-27 15:23:13 +00002517 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00002518 rc = SQLITE_OK;
danielk19773460d192008-12-27 15:23:13 +00002519 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
2520 put4byte(&pBt->pPage1->aData[32], 0);
2521 put4byte(&pBt->pPage1->aData[36], 0);
2522 sqlite3PagerTruncateImage(pBt->pPager, nFin);
danielk1977dddbcdc2007-04-26 14:42:34 +00002523 }
2524 if( rc!=SQLITE_OK ){
2525 sqlite3PagerRollback(pPager);
2526 }
danielk1977687566d2004-11-02 12:56:41 +00002527 }
2528
danielk19773b8a05f2007-03-19 17:44:26 +00002529 assert( nRef==sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002530 return rc;
2531}
danielk1977dddbcdc2007-04-26 14:42:34 +00002532
shane831c3292008-11-10 17:14:58 +00002533#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
danielk1977687566d2004-11-02 12:56:41 +00002534
2535/*
drh80e35f42007-03-30 14:06:34 +00002536** This routine does the first phase of a two-phase commit. This routine
2537** causes a rollback journal to be created (if it does not already exist)
2538** and populated with enough information so that if a power loss occurs
2539** the database can be restored to its original state by playing back
2540** the journal. Then the contents of the journal are flushed out to
2541** the disk. After the journal is safely on oxide, the changes to the
2542** database are written into the database file and flushed to oxide.
2543** At the end of this call, the rollback journal still exists on the
2544** disk and we are still holding all locks, so the transaction has not
2545** committed. See sqlite3BtreeCommit() for the second phase of the
2546** commit process.
2547**
2548** This call is a no-op if no write-transaction is currently active on pBt.
2549**
2550** Otherwise, sync the database file for the btree pBt. zMaster points to
2551** the name of a master journal file that should be written into the
2552** individual journal file, or is NULL, indicating no master journal file
2553** (single database transaction).
2554**
2555** When this is called, the master journal should already have been
2556** created, populated with this journal pointer and synced to disk.
2557**
2558** Once this is routine has returned, the only thing required to commit
2559** the write-transaction for this database file is to delete the journal.
2560*/
2561int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
2562 int rc = SQLITE_OK;
2563 if( p->inTrans==TRANS_WRITE ){
2564 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002565 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002566 pBt->db = p->db;
drh80e35f42007-03-30 14:06:34 +00002567#ifndef SQLITE_OMIT_AUTOVACUUM
2568 if( pBt->autoVacuum ){
danielk19773460d192008-12-27 15:23:13 +00002569 rc = autoVacuumCommit(pBt);
drh80e35f42007-03-30 14:06:34 +00002570 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002571 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002572 return rc;
2573 }
2574 }
2575#endif
drh49b9d332009-01-02 18:10:42 +00002576 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
drhd677b3d2007-08-20 22:48:41 +00002577 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002578 }
2579 return rc;
2580}
2581
2582/*
drh2aa679f2001-06-25 02:11:07 +00002583** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00002584**
drh6e345992007-03-30 11:12:08 +00002585** This routine implements the second phase of a 2-phase commit. The
2586** sqlite3BtreeSync() routine does the first phase and should be invoked
2587** prior to calling this routine. The sqlite3BtreeSync() routine did
2588** all the work of writing information out to disk and flushing the
2589** contents so that they are written onto the disk platter. All this
2590** routine has to do is delete or truncate the rollback journal
2591** (which causes the transaction to commit) and drop locks.
2592**
drh5e00f6c2001-09-13 13:46:56 +00002593** This will release the write lock on the database file. If there
2594** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002595*/
drh80e35f42007-03-30 14:06:34 +00002596int sqlite3BtreeCommitPhaseTwo(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002597 BtShared *pBt = p->pBt;
2598
drhd677b3d2007-08-20 22:48:41 +00002599 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002600 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00002601 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002602
2603 /* If the handle has a write-transaction open, commit the shared-btrees
2604 ** transaction and set the shared state to TRANS_READ.
2605 */
2606 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00002607 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002608 assert( pBt->inTransaction==TRANS_WRITE );
2609 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00002610 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
danielk19777f7bc662006-01-23 13:47:47 +00002611 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002612 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002613 return rc;
2614 }
danielk1977aef0bf62005-12-30 16:28:01 +00002615 pBt->inTransaction = TRANS_READ;
2616 pBt->inStmt = 0;
danielk1977ee5741e2004-05-31 10:01:34 +00002617 }
drhc25eabe2009-02-24 18:57:31 +00002618 clearAllSharedCacheTableLocks(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002619
2620 /* If the handle has any kind of transaction open, decrement the transaction
2621 ** count of the shared btree. If the transaction count reaches 0, set
2622 ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
2623 ** will unlock the pager.
2624 */
2625 if( p->inTrans!=TRANS_NONE ){
2626 pBt->nTransaction--;
2627 if( 0==pBt->nTransaction ){
2628 pBt->inTransaction = TRANS_NONE;
2629 }
2630 }
2631
2632 /* Set the handles current transaction state to TRANS_NONE and unlock
2633 ** the pager if this call closed the only read or write transaction.
2634 */
danielk1977bea2a942009-01-20 17:06:27 +00002635 btreeClearHasContent(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002636 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00002637 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002638
2639 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002640 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002641 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002642}
2643
drh80e35f42007-03-30 14:06:34 +00002644/*
2645** Do both phases of a commit.
2646*/
2647int sqlite3BtreeCommit(Btree *p){
2648 int rc;
drhd677b3d2007-08-20 22:48:41 +00002649 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00002650 rc = sqlite3BtreeCommitPhaseOne(p, 0);
2651 if( rc==SQLITE_OK ){
2652 rc = sqlite3BtreeCommitPhaseTwo(p);
2653 }
drhd677b3d2007-08-20 22:48:41 +00002654 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002655 return rc;
2656}
2657
danielk1977fbcd5852004-06-15 02:44:18 +00002658#ifndef NDEBUG
2659/*
2660** Return the number of write-cursors open on this handle. This is for use
2661** in assert() expressions, so it is only compiled if NDEBUG is not
2662** defined.
drhfb982642007-08-30 01:19:59 +00002663**
2664** For the purposes of this routine, a write-cursor is any cursor that
2665** is capable of writing to the databse. That means the cursor was
2666** originally opened for writing and the cursor has not be disabled
2667** by having its state changed to CURSOR_FAULT.
danielk1977fbcd5852004-06-15 02:44:18 +00002668*/
danielk1977aef0bf62005-12-30 16:28:01 +00002669static int countWriteCursors(BtShared *pBt){
danielk1977fbcd5852004-06-15 02:44:18 +00002670 BtCursor *pCur;
2671 int r = 0;
2672 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drhfb982642007-08-30 01:19:59 +00002673 if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
danielk1977fbcd5852004-06-15 02:44:18 +00002674 }
2675 return r;
2676}
2677#endif
2678
drhc39e0002004-05-07 23:50:57 +00002679/*
drhfb982642007-08-30 01:19:59 +00002680** This routine sets the state to CURSOR_FAULT and the error
2681** code to errCode for every cursor on BtShared that pBtree
2682** references.
2683**
2684** Every cursor is tripped, including cursors that belong
2685** to other database connections that happen to be sharing
2686** the cache with pBtree.
2687**
2688** This routine gets called when a rollback occurs.
2689** All cursors using the same cache must be tripped
2690** to prevent them from trying to use the btree after
2691** the rollback. The rollback may have deleted tables
2692** or moved root pages, so it is not sufficient to
2693** save the state of the cursor. The cursor must be
2694** invalidated.
2695*/
2696void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
2697 BtCursor *p;
2698 sqlite3BtreeEnter(pBtree);
2699 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
danielk1977bc2ca9e2008-11-13 14:28:28 +00002700 int i;
danielk1977be51a652008-10-08 17:58:48 +00002701 sqlite3BtreeClearCursor(p);
drhfb982642007-08-30 01:19:59 +00002702 p->eState = CURSOR_FAULT;
2703 p->skip = errCode;
danielk1977bc2ca9e2008-11-13 14:28:28 +00002704 for(i=0; i<=p->iPage; i++){
2705 releasePage(p->apPage[i]);
2706 p->apPage[i] = 0;
2707 }
drhfb982642007-08-30 01:19:59 +00002708 }
2709 sqlite3BtreeLeave(pBtree);
2710}
2711
2712/*
drhecdc7532001-09-23 02:35:53 +00002713** Rollback the transaction in progress. All cursors will be
2714** invalided by this operation. Any attempt to use a cursor
2715** that was open at the beginning of this operation will result
2716** in an error.
drh5e00f6c2001-09-13 13:46:56 +00002717**
2718** This will release the write lock on the database file. If there
2719** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002720*/
danielk1977aef0bf62005-12-30 16:28:01 +00002721int sqlite3BtreeRollback(Btree *p){
danielk19778d34dfd2006-01-24 16:37:57 +00002722 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002723 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00002724 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00002725
drhd677b3d2007-08-20 22:48:41 +00002726 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002727 pBt->db = p->db;
danielk19772b8c13e2006-01-24 14:21:24 +00002728 rc = saveAllCursors(pBt, 0, 0);
danielk19778d34dfd2006-01-24 16:37:57 +00002729#ifndef SQLITE_OMIT_SHARED_CACHE
danielk19772b8c13e2006-01-24 14:21:24 +00002730 if( rc!=SQLITE_OK ){
danielk19778d34dfd2006-01-24 16:37:57 +00002731 /* This is a horrible situation. An IO or malloc() error occured whilst
2732 ** trying to save cursor positions. If this is an automatic rollback (as
2733 ** the result of a constraint, malloc() failure or IO error) then
2734 ** the cache may be internally inconsistent (not contain valid trees) so
2735 ** we cannot simply return the error to the caller. Instead, abort
2736 ** all queries that may be using any of the cursors that failed to save.
2737 */
drhfb982642007-08-30 01:19:59 +00002738 sqlite3BtreeTripAllCursors(p, rc);
danielk19772b8c13e2006-01-24 14:21:24 +00002739 }
danielk19778d34dfd2006-01-24 16:37:57 +00002740#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002741 btreeIntegrity(p);
drhc25eabe2009-02-24 18:57:31 +00002742 clearAllSharedCacheTableLocks(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002743
2744 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00002745 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00002746
danielk19778d34dfd2006-01-24 16:37:57 +00002747 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00002748 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00002749 if( rc2!=SQLITE_OK ){
2750 rc = rc2;
2751 }
2752
drh24cd67e2004-05-10 16:18:47 +00002753 /* The rollback may have destroyed the pPage1->aData value. So
drh16a9b832007-05-05 18:39:25 +00002754 ** call sqlite3BtreeGetPage() on page 1 again to make
2755 ** sure pPage1->aData is set correctly. */
2756 if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh24cd67e2004-05-10 16:18:47 +00002757 releasePage(pPage1);
2758 }
danielk1977fbcd5852004-06-15 02:44:18 +00002759 assert( countWriteCursors(pBt)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002760 pBt->inTransaction = TRANS_READ;
drh24cd67e2004-05-10 16:18:47 +00002761 }
danielk1977aef0bf62005-12-30 16:28:01 +00002762
2763 if( p->inTrans!=TRANS_NONE ){
2764 assert( pBt->nTransaction>0 );
2765 pBt->nTransaction--;
2766 if( 0==pBt->nTransaction ){
2767 pBt->inTransaction = TRANS_NONE;
2768 }
2769 }
2770
danielk1977bea2a942009-01-20 17:06:27 +00002771 btreeClearHasContent(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002772 p->inTrans = TRANS_NONE;
danielk1977ee5741e2004-05-31 10:01:34 +00002773 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00002774 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002775
2776 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002777 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00002778 return rc;
2779}
2780
2781/*
drhab01f612004-05-22 02:55:23 +00002782** Start a statement subtransaction. The subtransaction can
2783** can be rolled back independently of the main transaction.
2784** You must start a transaction before starting a subtransaction.
2785** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00002786** commits or rolls back.
2787**
drhab01f612004-05-22 02:55:23 +00002788** Only one subtransaction may be active at a time. It is an error to try
2789** to start a new subtransaction if another subtransaction is already active.
2790**
2791** Statement subtransactions are used around individual SQL statements
2792** that are contained within a BEGIN...COMMIT block. If a constraint
2793** error occurs within the statement, the effect of that one statement
2794** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00002795*/
danielk1977aef0bf62005-12-30 16:28:01 +00002796int sqlite3BtreeBeginStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002797 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002798 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002799 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002800 pBt->db = p->db;
drh64022502009-01-09 14:11:04 +00002801 assert( p->inTrans==TRANS_WRITE );
2802 assert( !pBt->inStmt );
2803 assert( pBt->readOnly==0 );
2804 if( NEVER(p->inTrans!=TRANS_WRITE || pBt->inStmt || pBt->readOnly) ){
2805 rc = SQLITE_INTERNAL;
drhd677b3d2007-08-20 22:48:41 +00002806 }else{
2807 assert( pBt->inTransaction==TRANS_WRITE );
drh64022502009-01-09 14:11:04 +00002808 /* At the pager level, a statement transaction is a savepoint with
2809 ** an index greater than all savepoints created explicitly using
2810 ** SQL statements. It is illegal to open, release or rollback any
2811 ** such savepoints while the statement transaction savepoint is active.
2812 */
2813 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint+1);
drhd677b3d2007-08-20 22:48:41 +00002814 pBt->inStmt = 1;
drh0d65dc02002-02-03 00:56:09 +00002815 }
drhd677b3d2007-08-20 22:48:41 +00002816 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002817 return rc;
2818}
2819
drh663fc632002-02-02 18:49:19 +00002820/*
drhab01f612004-05-22 02:55:23 +00002821** Commit the statment subtransaction currently in progress. If no
2822** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00002823*/
danielk1977aef0bf62005-12-30 16:28:01 +00002824int sqlite3BtreeCommitStmt(Btree *p){
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( pBt->readOnly==0 );
2830 if( pBt->inStmt ){
danielk1977fd7f0452008-12-17 17:30:26 +00002831 int iStmtpoint = p->db->nSavepoint;
2832 rc = sqlite3PagerSavepoint(pBt->pPager, SAVEPOINT_RELEASE, iStmtpoint);
drh663fc632002-02-02 18:49:19 +00002833 }else{
2834 rc = SQLITE_OK;
2835 }
drh3aac2dd2004-04-26 14:10:20 +00002836 pBt->inStmt = 0;
drhd677b3d2007-08-20 22:48:41 +00002837 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002838 return rc;
2839}
2840
2841/*
drhab01f612004-05-22 02:55:23 +00002842** Rollback the active statement subtransaction. If no subtransaction
2843** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00002844**
drhab01f612004-05-22 02:55:23 +00002845** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00002846** to use a cursor that was open at the beginning of this operation
2847** will result in an error.
2848*/
danielk1977aef0bf62005-12-30 16:28:01 +00002849int sqlite3BtreeRollbackStmt(Btree *p){
danielk197797a227c2006-01-20 16:32:04 +00002850 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002851 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002852 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002853 pBt->db = p->db;
drh64022502009-01-09 14:11:04 +00002854 assert( pBt->readOnly==0 );
2855 if( pBt->inStmt ){
danielk1977fd7f0452008-12-17 17:30:26 +00002856 int iStmtpoint = p->db->nSavepoint;
2857 rc = sqlite3PagerSavepoint(pBt->pPager, SAVEPOINT_ROLLBACK, iStmtpoint);
2858 if( rc==SQLITE_OK ){
2859 rc = sqlite3PagerSavepoint(pBt->pPager, SAVEPOINT_RELEASE, iStmtpoint);
2860 }
danielk197797a227c2006-01-20 16:32:04 +00002861 pBt->inStmt = 0;
2862 }
drhd677b3d2007-08-20 22:48:41 +00002863 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002864 return rc;
2865}
2866
2867/*
danielk1977fd7f0452008-12-17 17:30:26 +00002868** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
2869** or SAVEPOINT_RELEASE. This function either releases or rolls back the
danielk197712dd5492008-12-18 15:45:07 +00002870** savepoint identified by parameter iSavepoint, depending on the value
2871** of op.
2872**
2873** Normally, iSavepoint is greater than or equal to zero. However, if op is
2874** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
2875** contents of the entire transaction are rolled back. This is different
2876** from a normal transaction rollback, as no locks are released and the
2877** transaction remains open.
danielk1977fd7f0452008-12-17 17:30:26 +00002878*/
2879int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
2880 int rc = SQLITE_OK;
2881 if( p && p->inTrans==TRANS_WRITE ){
2882 BtShared *pBt = p->pBt;
2883 assert( pBt->inStmt==0 );
2884 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
2885 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
2886 sqlite3BtreeEnter(p);
2887 pBt->db = p->db;
2888 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
drh9f0bbf92009-01-02 21:08:09 +00002889 if( rc==SQLITE_OK ){
2890 rc = newDatabase(pBt);
2891 }
danielk1977fd7f0452008-12-17 17:30:26 +00002892 sqlite3BtreeLeave(p);
2893 }
2894 return rc;
2895}
2896
2897/*
drh8b2f49b2001-06-08 00:21:52 +00002898** Create a new cursor for the BTree whose root is on the page
2899** iTable. The act of acquiring a cursor gets a read lock on
2900** the database file.
drh1bee3d72001-10-15 00:44:35 +00002901**
2902** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00002903** If wrFlag==1, then the cursor can be used for reading or for
2904** writing if other conditions for writing are also met. These
2905** are the conditions that must be met in order for writing to
2906** be allowed:
drh6446c4d2001-12-15 14:22:18 +00002907**
drhf74b8d92002-09-01 23:20:45 +00002908** 1: The cursor must have been opened with wrFlag==1
2909**
drhfe5d71d2007-03-19 11:54:10 +00002910** 2: Other database connections that share the same pager cache
2911** but which are not in the READ_UNCOMMITTED state may not have
2912** cursors open with wrFlag==0 on the same table. Otherwise
2913** the changes made by this write cursor would be visible to
2914** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00002915**
2916** 3: The database must be writable (not on read-only media)
2917**
2918** 4: There must be an active transaction.
2919**
drh6446c4d2001-12-15 14:22:18 +00002920** No checking is done to make sure that page iTable really is the
2921** root page of a b-tree. If it is not, then the cursor acquired
2922** will not work correctly.
danielk197771d5d2c2008-09-29 11:49:47 +00002923**
2924** It is assumed that the sqlite3BtreeCursorSize() bytes of memory
2925** pointed to by pCur have been zeroed by the caller.
drha059ad02001-04-17 20:09:11 +00002926*/
drhd677b3d2007-08-20 22:48:41 +00002927static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00002928 Btree *p, /* The btree */
2929 int iTable, /* Root page of table to open */
2930 int wrFlag, /* 1 to write. 0 read-only */
2931 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
2932 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00002933){
drha059ad02001-04-17 20:09:11 +00002934 int rc;
danielk197789d40042008-11-17 14:20:56 +00002935 Pgno nPage;
danielk1977aef0bf62005-12-30 16:28:01 +00002936 BtShared *pBt = p->pBt;
drhecdc7532001-09-23 02:35:53 +00002937
drh1fee73e2007-08-29 04:00:57 +00002938 assert( sqlite3BtreeHoldsMutex(p) );
drhf49661a2008-12-10 16:45:50 +00002939 assert( wrFlag==0 || wrFlag==1 );
drh8dcd7ca2004-08-08 19:43:29 +00002940 if( wrFlag ){
drh64022502009-01-09 14:11:04 +00002941 assert( !pBt->readOnly );
2942 if( NEVER(pBt->readOnly) ){
drh8dcd7ca2004-08-08 19:43:29 +00002943 return SQLITE_READONLY;
2944 }
danielk19773588ceb2008-06-10 17:30:26 +00002945 if( checkReadLocks(p, iTable, 0, 0) ){
drh8dcd7ca2004-08-08 19:43:29 +00002946 return SQLITE_LOCKED;
2947 }
drha0c9a112004-03-10 13:42:37 +00002948 }
danielk1977aef0bf62005-12-30 16:28:01 +00002949
drh4b70f112004-05-02 21:12:19 +00002950 if( pBt->pPage1==0 ){
danielk1977aef0bf62005-12-30 16:28:01 +00002951 rc = lockBtreeWithRetry(p);
drha059ad02001-04-17 20:09:11 +00002952 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00002953 return rc;
2954 }
2955 }
drh8b2f49b2001-06-08 00:21:52 +00002956 pCur->pgnoRoot = (Pgno)iTable;
danielk197789d40042008-11-17 14:20:56 +00002957 rc = sqlite3PagerPagecount(pBt->pPager, (int *)&nPage);
2958 if( rc!=SQLITE_OK ){
2959 return rc;
2960 }
2961 if( iTable==1 && nPage==0 ){
drh24cd67e2004-05-10 16:18:47 +00002962 rc = SQLITE_EMPTY;
2963 goto create_cursor_exception;
2964 }
danielk197771d5d2c2008-09-29 11:49:47 +00002965 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
drhbd03cae2001-06-02 02:40:57 +00002966 if( rc!=SQLITE_OK ){
2967 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00002968 }
danielk1977aef0bf62005-12-30 16:28:01 +00002969
danielk1977aef0bf62005-12-30 16:28:01 +00002970 /* Now that no other errors can occur, finish filling in the BtCursor
2971 ** variables, link the cursor into the BtShared list and set *ppCur (the
2972 ** output argument to this function).
2973 */
drh1e968a02008-03-25 00:22:21 +00002974 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00002975 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00002976 pCur->pBt = pBt;
drhf49661a2008-12-10 16:45:50 +00002977 pCur->wrFlag = (u8)wrFlag;
drha059ad02001-04-17 20:09:11 +00002978 pCur->pNext = pBt->pCursor;
2979 if( pCur->pNext ){
2980 pCur->pNext->pPrev = pCur;
2981 }
2982 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00002983 pCur->eState = CURSOR_INVALID;
drhbd03cae2001-06-02 02:40:57 +00002984
danielk1977aef0bf62005-12-30 16:28:01 +00002985 return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00002986
drhbd03cae2001-06-02 02:40:57 +00002987create_cursor_exception:
danielk197771d5d2c2008-09-29 11:49:47 +00002988 releasePage(pCur->apPage[0]);
drh5e00f6c2001-09-13 13:46:56 +00002989 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00002990 return rc;
drha059ad02001-04-17 20:09:11 +00002991}
drhd677b3d2007-08-20 22:48:41 +00002992int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00002993 Btree *p, /* The btree */
2994 int iTable, /* Root page of table to open */
2995 int wrFlag, /* 1 to write. 0 read-only */
2996 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
2997 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00002998){
2999 int rc;
3000 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00003001 p->pBt->db = p->db;
danielk1977cd3e8f72008-03-25 09:47:35 +00003002 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
drhd677b3d2007-08-20 22:48:41 +00003003 sqlite3BtreeLeave(p);
3004 return rc;
3005}
danielk1977cd3e8f72008-03-25 09:47:35 +00003006int sqlite3BtreeCursorSize(){
3007 return sizeof(BtCursor);
3008}
3009
drhd677b3d2007-08-20 22:48:41 +00003010
drha059ad02001-04-17 20:09:11 +00003011
3012/*
drh5e00f6c2001-09-13 13:46:56 +00003013** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00003014** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00003015*/
drh3aac2dd2004-04-26 14:10:20 +00003016int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00003017 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00003018 if( pBtree ){
danielk197771d5d2c2008-09-29 11:49:47 +00003019 int i;
danielk1977cd3e8f72008-03-25 09:47:35 +00003020 BtShared *pBt = pCur->pBt;
3021 sqlite3BtreeEnter(pBtree);
3022 pBt->db = pBtree->db;
danielk1977be51a652008-10-08 17:58:48 +00003023 sqlite3BtreeClearCursor(pCur);
danielk1977cd3e8f72008-03-25 09:47:35 +00003024 if( pCur->pPrev ){
3025 pCur->pPrev->pNext = pCur->pNext;
3026 }else{
3027 pBt->pCursor = pCur->pNext;
3028 }
3029 if( pCur->pNext ){
3030 pCur->pNext->pPrev = pCur->pPrev;
3031 }
danielk197771d5d2c2008-09-29 11:49:47 +00003032 for(i=0; i<=pCur->iPage; i++){
3033 releasePage(pCur->apPage[i]);
3034 }
danielk1977cd3e8f72008-03-25 09:47:35 +00003035 unlockBtreeIfUnused(pBt);
3036 invalidateOverflowCache(pCur);
3037 /* sqlite3_free(pCur); */
3038 sqlite3BtreeLeave(pBtree);
drha059ad02001-04-17 20:09:11 +00003039 }
drh8c42ca92001-06-22 19:15:00 +00003040 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003041}
3042
drh7e3b0a02001-04-28 16:52:40 +00003043/*
drh5e2f8b92001-05-28 00:41:15 +00003044** Make a temporary cursor by filling in the fields of pTempCur.
3045** The temporary cursor is not on the cursor list for the Btree.
3046*/
drh16a9b832007-05-05 18:39:25 +00003047void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
danielk197771d5d2c2008-09-29 11:49:47 +00003048 int i;
drh1fee73e2007-08-29 04:00:57 +00003049 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00003050 memcpy(pTempCur, pCur, sizeof(BtCursor));
drh5e2f8b92001-05-28 00:41:15 +00003051 pTempCur->pNext = 0;
3052 pTempCur->pPrev = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003053 for(i=0; i<=pTempCur->iPage; i++){
3054 sqlite3PagerRef(pTempCur->apPage[i]->pDbPage);
drhecdc7532001-09-23 02:35:53 +00003055 }
danielk197736e20932008-11-26 07:40:30 +00003056 assert( pTempCur->pKey==0 );
drh5e2f8b92001-05-28 00:41:15 +00003057}
3058
3059/*
drhbd03cae2001-06-02 02:40:57 +00003060** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00003061** function above.
3062*/
drh16a9b832007-05-05 18:39:25 +00003063void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
danielk197771d5d2c2008-09-29 11:49:47 +00003064 int i;
drh1fee73e2007-08-29 04:00:57 +00003065 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00003066 for(i=0; i<=pCur->iPage; i++){
3067 sqlite3PagerUnref(pCur->apPage[i]->pDbPage);
drhecdc7532001-09-23 02:35:53 +00003068 }
danielk197736e20932008-11-26 07:40:30 +00003069 sqlite3_free(pCur->pKey);
drh5e2f8b92001-05-28 00:41:15 +00003070}
3071
3072/*
drh86057612007-06-26 01:04:48 +00003073** Make sure the BtCursor* given in the argument has a valid
3074** BtCursor.info structure. If it is not already valid, call
danielk19771cc5ed82007-05-16 17:28:43 +00003075** sqlite3BtreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00003076**
3077** BtCursor.info is a cache of the information in the current cell.
drh16a9b832007-05-05 18:39:25 +00003078** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
drh86057612007-06-26 01:04:48 +00003079**
3080** 2007-06-25: There is a bug in some versions of MSVC that cause the
3081** compiler to crash when getCellInfo() is implemented as a macro.
3082** But there is a measureable speed advantage to using the macro on gcc
3083** (when less compiler optimizations like -Os or -O0 are used and the
3084** compiler is not doing agressive inlining.) So we use a real function
3085** for MSVC and a macro for everything else. Ticket #2457.
drh9188b382004-05-14 21:12:22 +00003086*/
drh9188b382004-05-14 21:12:22 +00003087#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00003088 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00003089 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00003090 int iPage = pCur->iPage;
drh51c6d962004-06-06 00:42:25 +00003091 memset(&info, 0, sizeof(info));
danielk197771d5d2c2008-09-29 11:49:47 +00003092 sqlite3BtreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
drh9188b382004-05-14 21:12:22 +00003093 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00003094 }
danielk19771cc5ed82007-05-16 17:28:43 +00003095#else
3096 #define assertCellInfo(x)
3097#endif
drh86057612007-06-26 01:04:48 +00003098#ifdef _MSC_VER
3099 /* Use a real function in MSVC to work around bugs in that compiler. */
3100 static void getCellInfo(BtCursor *pCur){
3101 if( pCur->info.nSize==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003102 int iPage = pCur->iPage;
3103 sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
drha2c20e42008-03-29 16:01:04 +00003104 pCur->validNKey = 1;
drh86057612007-06-26 01:04:48 +00003105 }else{
3106 assertCellInfo(pCur);
3107 }
3108 }
3109#else /* if not _MSC_VER */
3110 /* Use a macro in all other compilers so that the function is inlined */
danielk197771d5d2c2008-09-29 11:49:47 +00003111#define getCellInfo(pCur) \
3112 if( pCur->info.nSize==0 ){ \
3113 int iPage = pCur->iPage; \
3114 sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
3115 pCur->validNKey = 1; \
3116 }else{ \
3117 assertCellInfo(pCur); \
drh86057612007-06-26 01:04:48 +00003118 }
3119#endif /* _MSC_VER */
drh9188b382004-05-14 21:12:22 +00003120
3121/*
drh3aac2dd2004-04-26 14:10:20 +00003122** Set *pSize to the size of the buffer needed to hold the value of
3123** the key for the current entry. If the cursor is not pointing
3124** to a valid entry, *pSize is set to 0.
3125**
drh4b70f112004-05-02 21:12:19 +00003126** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00003127** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00003128*/
drh4a1c3802004-05-12 15:15:47 +00003129int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drhd677b3d2007-08-20 22:48:41 +00003130 int rc;
3131
drh1fee73e2007-08-29 04:00:57 +00003132 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003133 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003134 if( rc==SQLITE_OK ){
3135 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3136 if( pCur->eState==CURSOR_INVALID ){
3137 *pSize = 0;
3138 }else{
drh86057612007-06-26 01:04:48 +00003139 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00003140 *pSize = pCur->info.nKey;
3141 }
drh72f82862001-05-24 21:06:34 +00003142 }
danielk1977da184232006-01-05 11:34:32 +00003143 return rc;
drha059ad02001-04-17 20:09:11 +00003144}
drh2af926b2001-05-15 00:39:25 +00003145
drh72f82862001-05-24 21:06:34 +00003146/*
drh0e1c19e2004-05-11 00:58:56 +00003147** Set *pSize to the number of bytes of data in the entry the
3148** cursor currently points to. Always return SQLITE_OK.
3149** Failure is not possible. If the cursor is not currently
3150** pointing to an entry (which can happen, for example, if
3151** the database is empty) then *pSize is set to 0.
3152*/
3153int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drhd677b3d2007-08-20 22:48:41 +00003154 int rc;
3155
drh1fee73e2007-08-29 04:00:57 +00003156 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003157 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003158 if( rc==SQLITE_OK ){
3159 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3160 if( pCur->eState==CURSOR_INVALID ){
3161 /* Not pointing at a valid entry - set *pSize to 0. */
3162 *pSize = 0;
3163 }else{
drh86057612007-06-26 01:04:48 +00003164 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00003165 *pSize = pCur->info.nData;
3166 }
drh0e1c19e2004-05-11 00:58:56 +00003167 }
danielk1977da184232006-01-05 11:34:32 +00003168 return rc;
drh0e1c19e2004-05-11 00:58:56 +00003169}
3170
3171/*
danielk1977d04417962007-05-02 13:16:30 +00003172** Given the page number of an overflow page in the database (parameter
3173** ovfl), this function finds the page number of the next page in the
3174** linked list of overflow pages. If possible, it uses the auto-vacuum
3175** pointer-map data instead of reading the content of page ovfl to do so.
3176**
3177** If an error occurs an SQLite error code is returned. Otherwise:
3178**
danielk1977bea2a942009-01-20 17:06:27 +00003179** The page number of the next overflow page in the linked list is
3180** written to *pPgnoNext. If page ovfl is the last page in its linked
3181** list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003182**
danielk1977bea2a942009-01-20 17:06:27 +00003183** If ppPage is not NULL, and a reference to the MemPage object corresponding
3184** to page number pOvfl was obtained, then *ppPage is set to point to that
3185** reference. It is the responsibility of the caller to call releasePage()
3186** on *ppPage to free the reference. In no reference was obtained (because
3187** the pointer-map was used to obtain the value for *pPgnoNext), then
3188** *ppPage is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003189*/
3190static int getOverflowPage(
3191 BtShared *pBt,
3192 Pgno ovfl, /* Overflow page */
danielk1977bea2a942009-01-20 17:06:27 +00003193 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
danielk1977d04417962007-05-02 13:16:30 +00003194 Pgno *pPgnoNext /* OUT: Next overflow page number */
3195){
3196 Pgno next = 0;
danielk1977bea2a942009-01-20 17:06:27 +00003197 MemPage *pPage = 0;
drh1bd10f82008-12-10 21:19:56 +00003198 int rc = SQLITE_OK;
danielk1977d04417962007-05-02 13:16:30 +00003199
drh1fee73e2007-08-29 04:00:57 +00003200 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bea2a942009-01-20 17:06:27 +00003201 assert(pPgnoNext);
danielk1977d04417962007-05-02 13:16:30 +00003202
3203#ifndef SQLITE_OMIT_AUTOVACUUM
3204 /* Try to find the next page in the overflow list using the
3205 ** autovacuum pointer-map pages. Guess that the next page in
3206 ** the overflow list is page number (ovfl+1). If that guess turns
3207 ** out to be wrong, fall back to loading the data of page
3208 ** number ovfl to determine the next page number.
3209 */
3210 if( pBt->autoVacuum ){
3211 Pgno pgno;
3212 Pgno iGuess = ovfl+1;
3213 u8 eType;
3214
3215 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
3216 iGuess++;
3217 }
3218
danielk197789d40042008-11-17 14:20:56 +00003219 if( iGuess<=pagerPagecount(pBt) ){
danielk1977d04417962007-05-02 13:16:30 +00003220 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
danielk1977bea2a942009-01-20 17:06:27 +00003221 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
danielk1977d04417962007-05-02 13:16:30 +00003222 next = iGuess;
danielk1977bea2a942009-01-20 17:06:27 +00003223 rc = SQLITE_DONE;
danielk1977d04417962007-05-02 13:16:30 +00003224 }
3225 }
3226 }
3227#endif
3228
danielk1977bea2a942009-01-20 17:06:27 +00003229 if( rc==SQLITE_OK ){
3230 rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, 0);
danielk1977d04417962007-05-02 13:16:30 +00003231 assert(rc==SQLITE_OK || pPage==0);
3232 if( next==0 && rc==SQLITE_OK ){
3233 next = get4byte(pPage->aData);
3234 }
danielk1977443c0592009-01-16 15:21:05 +00003235 }
danielk197745d68822009-01-16 16:23:38 +00003236
danielk1977bea2a942009-01-20 17:06:27 +00003237 *pPgnoNext = next;
3238 if( ppPage ){
3239 *ppPage = pPage;
3240 }else{
3241 releasePage(pPage);
3242 }
3243 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
danielk1977d04417962007-05-02 13:16:30 +00003244}
3245
danielk1977da107192007-05-04 08:32:13 +00003246/*
3247** Copy data from a buffer to a page, or from a page to a buffer.
3248**
3249** pPayload is a pointer to data stored on database page pDbPage.
3250** If argument eOp is false, then nByte bytes of data are copied
3251** from pPayload to the buffer pointed at by pBuf. If eOp is true,
3252** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
3253** of data are copied from the buffer pBuf to pPayload.
3254**
3255** SQLITE_OK is returned on success, otherwise an error code.
3256*/
3257static int copyPayload(
3258 void *pPayload, /* Pointer to page data */
3259 void *pBuf, /* Pointer to buffer */
3260 int nByte, /* Number of bytes to copy */
3261 int eOp, /* 0 -> copy from page, 1 -> copy to page */
3262 DbPage *pDbPage /* Page containing pPayload */
3263){
3264 if( eOp ){
3265 /* Copy data from buffer to page (a write operation) */
3266 int rc = sqlite3PagerWrite(pDbPage);
3267 if( rc!=SQLITE_OK ){
3268 return rc;
3269 }
3270 memcpy(pPayload, pBuf, nByte);
3271 }else{
3272 /* Copy data from page to buffer (a read operation) */
3273 memcpy(pBuf, pPayload, nByte);
3274 }
3275 return SQLITE_OK;
3276}
danielk1977d04417962007-05-02 13:16:30 +00003277
3278/*
danielk19779f8d6402007-05-02 17:48:45 +00003279** This function is used to read or overwrite payload information
3280** for the entry that the pCur cursor is pointing to. If the eOp
3281** parameter is 0, this is a read operation (data copied into
3282** buffer pBuf). If it is non-zero, a write (data copied from
3283** buffer pBuf).
3284**
3285** A total of "amt" bytes are read or written beginning at "offset".
3286** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00003287**
3288** This routine does not make a distinction between key and data.
danielk19779f8d6402007-05-02 17:48:45 +00003289** It just reads or writes bytes from the payload area. Data might
3290** appear on the main page or be scattered out on multiple overflow
3291** pages.
danielk1977da107192007-05-04 08:32:13 +00003292**
danielk1977dcbb5d32007-05-04 18:36:44 +00003293** If the BtCursor.isIncrblobHandle flag is set, and the current
danielk1977da107192007-05-04 08:32:13 +00003294** cursor entry uses one or more overflow pages, this function
3295** allocates space for and lazily popluates the overflow page-list
3296** cache array (BtCursor.aOverflow). Subsequent calls use this
3297** cache to make seeking to the supplied offset more efficient.
3298**
3299** Once an overflow page-list cache has been allocated, it may be
3300** invalidated if some other cursor writes to the same table, or if
3301** the cursor is moved to a different row. Additionally, in auto-vacuum
3302** mode, the following events may invalidate an overflow page-list cache.
3303**
3304** * An incremental vacuum,
3305** * A commit in auto_vacuum="full" mode,
3306** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00003307*/
danielk19779f8d6402007-05-02 17:48:45 +00003308static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00003309 BtCursor *pCur, /* Cursor pointing to entry to read from */
danielk197789d40042008-11-17 14:20:56 +00003310 u32 offset, /* Begin reading this far into payload */
3311 u32 amt, /* Read this many bytes */
drh3aac2dd2004-04-26 14:10:20 +00003312 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00003313 int skipKey, /* offset begins at data if this is true */
3314 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00003315){
3316 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00003317 int rc = SQLITE_OK;
drhfa1a98a2004-05-14 19:08:17 +00003318 u32 nKey;
danielk19772dec9702007-05-02 16:48:37 +00003319 int iIdx = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003320 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
danielk19770d065412008-11-12 18:21:36 +00003321 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
drh3aac2dd2004-04-26 14:10:20 +00003322
danielk1977da107192007-05-04 08:32:13 +00003323 assert( pPage );
danielk1977da184232006-01-05 11:34:32 +00003324 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003325 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh1fee73e2007-08-29 04:00:57 +00003326 assert( cursorHoldsMutex(pCur) );
danielk1977da107192007-05-04 08:32:13 +00003327
drh86057612007-06-26 01:04:48 +00003328 getCellInfo(pCur);
drh366fda62006-01-13 02:35:09 +00003329 aPayload = pCur->info.pCell + pCur->info.nHeader;
drhf49661a2008-12-10 16:45:50 +00003330 nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
danielk1977da107192007-05-04 08:32:13 +00003331
drh3aac2dd2004-04-26 14:10:20 +00003332 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003333 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00003334 }
danielk19770d065412008-11-12 18:21:36 +00003335 if( offset+amt > nKey+pCur->info.nData
3336 || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
3337 ){
danielk1977da107192007-05-04 08:32:13 +00003338 /* Trying to read or write past the end of the data is an error */
danielk197767fd7a92008-09-10 17:53:35 +00003339 return SQLITE_CORRUPT_BKPT;
drh3aac2dd2004-04-26 14:10:20 +00003340 }
danielk1977da107192007-05-04 08:32:13 +00003341
3342 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00003343 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00003344 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00003345 if( a+offset>pCur->info.nLocal ){
3346 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00003347 }
danielk1977da107192007-05-04 08:32:13 +00003348 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00003349 offset = 0;
drha34b6762004-05-07 13:30:42 +00003350 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00003351 amt -= a;
drhdd793422001-06-28 01:54:48 +00003352 }else{
drhfa1a98a2004-05-14 19:08:17 +00003353 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00003354 }
danielk1977da107192007-05-04 08:32:13 +00003355
3356 if( rc==SQLITE_OK && amt>0 ){
danielk197789d40042008-11-17 14:20:56 +00003357 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
danielk1977da107192007-05-04 08:32:13 +00003358 Pgno nextPage;
3359
drhfa1a98a2004-05-14 19:08:17 +00003360 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00003361
danielk19772dec9702007-05-02 16:48:37 +00003362#ifndef SQLITE_OMIT_INCRBLOB
danielk1977dcbb5d32007-05-04 18:36:44 +00003363 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
danielk1977da107192007-05-04 08:32:13 +00003364 ** has not been allocated, allocate it now. The array is sized at
3365 ** one entry for each overflow page in the overflow chain. The
3366 ** page number of the first overflow page is stored in aOverflow[0],
3367 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
3368 ** (the cache is lazily populated).
3369 */
danielk1977dcbb5d32007-05-04 18:36:44 +00003370 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
danielk19772dec9702007-05-02 16:48:37 +00003371 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
drh17435752007-08-16 04:30:38 +00003372 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
danielk19772dec9702007-05-02 16:48:37 +00003373 if( nOvfl && !pCur->aOverflow ){
danielk1977da107192007-05-04 08:32:13 +00003374 rc = SQLITE_NOMEM;
danielk19772dec9702007-05-02 16:48:37 +00003375 }
3376 }
danielk1977da107192007-05-04 08:32:13 +00003377
3378 /* If the overflow page-list cache has been allocated and the
3379 ** entry for the first required overflow page is valid, skip
3380 ** directly to it.
3381 */
danielk19772dec9702007-05-02 16:48:37 +00003382 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
3383 iIdx = (offset/ovflSize);
3384 nextPage = pCur->aOverflow[iIdx];
3385 offset = (offset%ovflSize);
3386 }
3387#endif
danielk1977da107192007-05-04 08:32:13 +00003388
3389 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
3390
3391#ifndef SQLITE_OMIT_INCRBLOB
3392 /* If required, populate the overflow page-list cache. */
3393 if( pCur->aOverflow ){
3394 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
3395 pCur->aOverflow[iIdx] = nextPage;
3396 }
3397#endif
3398
danielk1977d04417962007-05-02 13:16:30 +00003399 if( offset>=ovflSize ){
3400 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00003401 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00003402 ** data is not required. So first try to lookup the overflow
3403 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00003404 ** function.
danielk1977d04417962007-05-02 13:16:30 +00003405 */
danielk19772dec9702007-05-02 16:48:37 +00003406#ifndef SQLITE_OMIT_INCRBLOB
danielk1977da107192007-05-04 08:32:13 +00003407 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
3408 nextPage = pCur->aOverflow[iIdx+1];
3409 } else
danielk19772dec9702007-05-02 16:48:37 +00003410#endif
danielk1977da107192007-05-04 08:32:13 +00003411 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
danielk1977da107192007-05-04 08:32:13 +00003412 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00003413 }else{
danielk19779f8d6402007-05-02 17:48:45 +00003414 /* Need to read this page properly. It contains some of the
3415 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00003416 */
3417 DbPage *pDbPage;
danielk1977cfe9a692004-06-16 12:00:29 +00003418 int a = amt;
danielk1977d04417962007-05-02 13:16:30 +00003419 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
danielk1977da107192007-05-04 08:32:13 +00003420 if( rc==SQLITE_OK ){
3421 aPayload = sqlite3PagerGetData(pDbPage);
3422 nextPage = get4byte(aPayload);
3423 if( a + offset > ovflSize ){
3424 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00003425 }
danielk1977da107192007-05-04 08:32:13 +00003426 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
3427 sqlite3PagerUnref(pDbPage);
3428 offset = 0;
3429 amt -= a;
3430 pBuf += a;
danielk19779f8d6402007-05-02 17:48:45 +00003431 }
danielk1977cfe9a692004-06-16 12:00:29 +00003432 }
drh2af926b2001-05-15 00:39:25 +00003433 }
drh2af926b2001-05-15 00:39:25 +00003434 }
danielk1977cfe9a692004-06-16 12:00:29 +00003435
danielk1977da107192007-05-04 08:32:13 +00003436 if( rc==SQLITE_OK && amt>0 ){
drh49285702005-09-17 15:20:26 +00003437 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00003438 }
danielk1977da107192007-05-04 08:32:13 +00003439 return rc;
drh2af926b2001-05-15 00:39:25 +00003440}
3441
drh72f82862001-05-24 21:06:34 +00003442/*
drh3aac2dd2004-04-26 14:10:20 +00003443** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003444** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003445** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00003446**
drh3aac2dd2004-04-26 14:10:20 +00003447** Return SQLITE_OK on success or an error code if anything goes
3448** wrong. An error is returned if "offset+amt" is larger than
3449** the available payload.
drh72f82862001-05-24 21:06:34 +00003450*/
drha34b6762004-05-07 13:30:42 +00003451int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003452 int rc;
3453
drh1fee73e2007-08-29 04:00:57 +00003454 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003455 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003456 if( rc==SQLITE_OK ){
3457 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003458 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3459 if( pCur->apPage[0]->intKey ){
danielk1977da184232006-01-05 11:34:32 +00003460 return SQLITE_CORRUPT_BKPT;
3461 }
danielk197771d5d2c2008-09-29 11:49:47 +00003462 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh16a9b832007-05-05 18:39:25 +00003463 rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
drh6575a222005-03-10 17:06:34 +00003464 }
danielk1977da184232006-01-05 11:34:32 +00003465 return rc;
drh3aac2dd2004-04-26 14:10:20 +00003466}
3467
3468/*
drh3aac2dd2004-04-26 14:10:20 +00003469** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003470** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003471** begins at "offset".
3472**
3473** Return SQLITE_OK on success or an error code if anything goes
3474** wrong. An error is returned if "offset+amt" is larger than
3475** the available payload.
drh72f82862001-05-24 21:06:34 +00003476*/
drh3aac2dd2004-04-26 14:10:20 +00003477int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003478 int rc;
3479
danielk19773588ceb2008-06-10 17:30:26 +00003480#ifndef SQLITE_OMIT_INCRBLOB
3481 if ( pCur->eState==CURSOR_INVALID ){
3482 return SQLITE_ABORT;
3483 }
3484#endif
3485
drh1fee73e2007-08-29 04:00:57 +00003486 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003487 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003488 if( rc==SQLITE_OK ){
3489 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003490 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3491 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh16a9b832007-05-05 18:39:25 +00003492 rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
danielk1977da184232006-01-05 11:34:32 +00003493 }
3494 return rc;
drh2af926b2001-05-15 00:39:25 +00003495}
3496
drh72f82862001-05-24 21:06:34 +00003497/*
drh0e1c19e2004-05-11 00:58:56 +00003498** Return a pointer to payload information from the entry that the
3499** pCur cursor is pointing to. The pointer is to the beginning of
3500** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00003501** skipKey==1. The number of bytes of available key/data is written
3502** into *pAmt. If *pAmt==0, then the value returned will not be
3503** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00003504**
3505** This routine is an optimization. It is common for the entire key
3506** and data to fit on the local page and for there to be no overflow
3507** pages. When that is so, this routine can be used to access the
3508** key and data without making a copy. If the key and/or data spills
drh16a9b832007-05-05 18:39:25 +00003509** onto overflow pages, then accessPayload() must be used to reassembly
drh0e1c19e2004-05-11 00:58:56 +00003510** the key/data and copy it into a preallocated buffer.
3511**
3512** The pointer returned by this routine looks directly into the cached
3513** page of the database. The data might change or move the next time
3514** any btree routine is called.
3515*/
3516static const unsigned char *fetchPayload(
3517 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00003518 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00003519 int skipKey /* read beginning at data if this is true */
3520){
3521 unsigned char *aPayload;
3522 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00003523 u32 nKey;
danielk197789d40042008-11-17 14:20:56 +00003524 u32 nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003525
danielk197771d5d2c2008-09-29 11:49:47 +00003526 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
danielk1977da184232006-01-05 11:34:32 +00003527 assert( pCur->eState==CURSOR_VALID );
drh1fee73e2007-08-29 04:00:57 +00003528 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00003529 pPage = pCur->apPage[pCur->iPage];
3530 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh86057612007-06-26 01:04:48 +00003531 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00003532 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00003533 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00003534 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00003535 nKey = 0;
3536 }else{
drhf49661a2008-12-10 16:45:50 +00003537 nKey = (int)pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00003538 }
drh0e1c19e2004-05-11 00:58:56 +00003539 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003540 aPayload += nKey;
3541 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00003542 }else{
drhfa1a98a2004-05-14 19:08:17 +00003543 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00003544 if( nLocal>nKey ){
3545 nLocal = nKey;
3546 }
drh0e1c19e2004-05-11 00:58:56 +00003547 }
drhe51c44f2004-05-30 20:46:09 +00003548 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003549 return aPayload;
3550}
3551
3552
3553/*
drhe51c44f2004-05-30 20:46:09 +00003554** For the entry that cursor pCur is point to, return as
3555** many bytes of the key or data as are available on the local
3556** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00003557**
3558** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00003559** or be destroyed on the next call to any Btree routine,
3560** including calls from other threads against the same cache.
3561** Hence, a mutex on the BtShared should be held prior to calling
3562** this routine.
drh0e1c19e2004-05-11 00:58:56 +00003563**
3564** These routines is used to get quick access to key and data
3565** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00003566*/
drhe51c44f2004-05-30 20:46:09 +00003567const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
drh1fee73e2007-08-29 04:00:57 +00003568 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003569 if( pCur->eState==CURSOR_VALID ){
3570 return (const void*)fetchPayload(pCur, pAmt, 0);
3571 }
3572 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003573}
drhe51c44f2004-05-30 20:46:09 +00003574const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
drh1fee73e2007-08-29 04:00:57 +00003575 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003576 if( pCur->eState==CURSOR_VALID ){
3577 return (const void*)fetchPayload(pCur, pAmt, 1);
3578 }
3579 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003580}
3581
3582
3583/*
drh8178a752003-01-05 21:41:40 +00003584** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00003585** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00003586*/
drh3aac2dd2004-04-26 14:10:20 +00003587static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00003588 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003589 int i = pCur->iPage;
drh72f82862001-05-24 21:06:34 +00003590 MemPage *pNewPage;
drhd0679ed2007-08-28 22:24:34 +00003591 BtShared *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00003592
drh1fee73e2007-08-29 04:00:57 +00003593 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003594 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003595 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
3596 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
3597 return SQLITE_CORRUPT_BKPT;
3598 }
3599 rc = getAndInitPage(pBt, newPgno, &pNewPage);
drh6019e162001-07-02 17:51:45 +00003600 if( rc ) return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003601 pCur->apPage[i+1] = pNewPage;
3602 pCur->aiIdx[i+1] = 0;
3603 pCur->iPage++;
3604
drh271efa52004-05-30 19:19:05 +00003605 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003606 pCur->validNKey = 0;
drh4be295b2003-12-16 03:44:47 +00003607 if( pNewPage->nCell<1 ){
drh49285702005-09-17 15:20:26 +00003608 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00003609 }
drh72f82862001-05-24 21:06:34 +00003610 return SQLITE_OK;
3611}
3612
danielk1977bf93c562008-09-29 15:53:25 +00003613#ifndef NDEBUG
3614/*
3615** Page pParent is an internal (non-leaf) tree page. This function
3616** asserts that page number iChild is the left-child if the iIdx'th
3617** cell in page pParent. Or, if iIdx is equal to the total number of
3618** cells in pParent, that page number iChild is the right-child of
3619** the page.
3620*/
3621static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
3622 assert( iIdx<=pParent->nCell );
3623 if( iIdx==pParent->nCell ){
3624 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
3625 }else{
3626 assert( get4byte(findCell(pParent, iIdx))==iChild );
3627 }
3628}
3629#else
3630# define assertParentIndex(x,y,z)
3631#endif
3632
drh72f82862001-05-24 21:06:34 +00003633/*
drh5e2f8b92001-05-28 00:41:15 +00003634** Move the cursor up to the parent page.
3635**
3636** pCur->idx is set to the cell index that contains the pointer
3637** to the page we are coming from. If we are coming from the
3638** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00003639** the largest cell index.
drh72f82862001-05-24 21:06:34 +00003640*/
drh16a9b832007-05-05 18:39:25 +00003641void sqlite3BtreeMoveToParent(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00003642 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003643 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003644 assert( pCur->iPage>0 );
3645 assert( pCur->apPage[pCur->iPage] );
danielk1977bf93c562008-09-29 15:53:25 +00003646 assertParentIndex(
3647 pCur->apPage[pCur->iPage-1],
3648 pCur->aiIdx[pCur->iPage-1],
3649 pCur->apPage[pCur->iPage]->pgno
3650 );
danielk197771d5d2c2008-09-29 11:49:47 +00003651 releasePage(pCur->apPage[pCur->iPage]);
3652 pCur->iPage--;
drh271efa52004-05-30 19:19:05 +00003653 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003654 pCur->validNKey = 0;
drh72f82862001-05-24 21:06:34 +00003655}
3656
3657/*
3658** Move the cursor to the root page
3659*/
drh5e2f8b92001-05-28 00:41:15 +00003660static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00003661 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00003662 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003663 Btree *p = pCur->pBtree;
3664 BtShared *pBt = p->pBt;
drhbd03cae2001-06-02 02:40:57 +00003665
drh1fee73e2007-08-29 04:00:57 +00003666 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +00003667 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
3668 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
3669 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
3670 if( pCur->eState>=CURSOR_REQUIRESEEK ){
3671 if( pCur->eState==CURSOR_FAULT ){
3672 return pCur->skip;
3673 }
danielk1977be51a652008-10-08 17:58:48 +00003674 sqlite3BtreeClearCursor(pCur);
drhbf700f32007-03-31 02:36:44 +00003675 }
danielk197771d5d2c2008-09-29 11:49:47 +00003676
3677 if( pCur->iPage>=0 ){
3678 int i;
3679 for(i=1; i<=pCur->iPage; i++){
3680 releasePage(pCur->apPage[i]);
danielk1977d9f6c532008-09-19 16:39:38 +00003681 }
drh777e4c42006-01-13 04:31:58 +00003682 }else{
3683 if(
danielk197771d5d2c2008-09-29 11:49:47 +00003684 SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]))
drh777e4c42006-01-13 04:31:58 +00003685 ){
3686 pCur->eState = CURSOR_INVALID;
3687 return rc;
3688 }
drhc39e0002004-05-07 23:50:57 +00003689 }
danielk197771d5d2c2008-09-29 11:49:47 +00003690
3691 pRoot = pCur->apPage[0];
3692 assert( pRoot->pgno==pCur->pgnoRoot );
3693 pCur->iPage = 0;
3694 pCur->aiIdx[0] = 0;
drh271efa52004-05-30 19:19:05 +00003695 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003696 pCur->atLast = 0;
3697 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003698
drh8856d6a2004-04-29 14:42:46 +00003699 if( pRoot->nCell==0 && !pRoot->leaf ){
3700 Pgno subpage;
3701 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00003702 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00003703 assert( subpage>0 );
danielk1977da184232006-01-05 11:34:32 +00003704 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00003705 rc = moveToChild(pCur, subpage);
danielk197771d5d2c2008-09-29 11:49:47 +00003706 }else{
3707 pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
drh8856d6a2004-04-29 14:42:46 +00003708 }
3709 return rc;
drh72f82862001-05-24 21:06:34 +00003710}
drh2af926b2001-05-15 00:39:25 +00003711
drh5e2f8b92001-05-28 00:41:15 +00003712/*
3713** Move the cursor down to the left-most leaf entry beneath the
3714** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00003715**
3716** The left-most leaf is the one with the smallest key - the first
3717** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00003718*/
3719static int moveToLeftmost(BtCursor *pCur){
3720 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00003721 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00003722 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00003723
drh1fee73e2007-08-29 04:00:57 +00003724 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003725 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003726 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
3727 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
3728 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
drh8178a752003-01-05 21:41:40 +00003729 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00003730 }
drhd677b3d2007-08-20 22:48:41 +00003731 return rc;
drh5e2f8b92001-05-28 00:41:15 +00003732}
3733
drh2dcc9aa2002-12-04 13:40:25 +00003734/*
3735** Move the cursor down to the right-most leaf entry beneath the
3736** page to which it is currently pointing. Notice the difference
3737** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
3738** finds the left-most entry beneath the *entry* whereas moveToRightmost()
3739** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00003740**
3741** The right-most entry is the one with the largest key - the last
3742** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00003743*/
3744static int moveToRightmost(BtCursor *pCur){
3745 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00003746 int rc = SQLITE_OK;
drh1bd10f82008-12-10 21:19:56 +00003747 MemPage *pPage = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003748
drh1fee73e2007-08-29 04:00:57 +00003749 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003750 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003751 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
drh43605152004-05-29 21:46:49 +00003752 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
danielk197771d5d2c2008-09-29 11:49:47 +00003753 pCur->aiIdx[pCur->iPage] = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00003754 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003755 }
drhd677b3d2007-08-20 22:48:41 +00003756 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00003757 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
drhd677b3d2007-08-20 22:48:41 +00003758 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003759 pCur->validNKey = 0;
drhd677b3d2007-08-20 22:48:41 +00003760 }
danielk1977518002e2008-09-05 05:02:46 +00003761 return rc;
drh2dcc9aa2002-12-04 13:40:25 +00003762}
3763
drh5e00f6c2001-09-13 13:46:56 +00003764/* Move the cursor to the first entry in the table. Return SQLITE_OK
3765** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003766** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00003767*/
drh3aac2dd2004-04-26 14:10:20 +00003768int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00003769 int rc;
drhd677b3d2007-08-20 22:48:41 +00003770
drh1fee73e2007-08-29 04:00:57 +00003771 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003772 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00003773 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003774 if( rc==SQLITE_OK ){
3775 if( pCur->eState==CURSOR_INVALID ){
danielk197771d5d2c2008-09-29 11:49:47 +00003776 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00003777 *pRes = 1;
3778 rc = SQLITE_OK;
3779 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00003780 assert( pCur->apPage[pCur->iPage]->nCell>0 );
drhd677b3d2007-08-20 22:48:41 +00003781 *pRes = 0;
3782 rc = moveToLeftmost(pCur);
3783 }
drh5e00f6c2001-09-13 13:46:56 +00003784 }
drh5e00f6c2001-09-13 13:46:56 +00003785 return rc;
3786}
drh5e2f8b92001-05-28 00:41:15 +00003787
drh9562b552002-02-19 15:00:07 +00003788/* Move the cursor to the last entry in the table. Return SQLITE_OK
3789** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003790** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00003791*/
drh3aac2dd2004-04-26 14:10:20 +00003792int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00003793 int rc;
drhd677b3d2007-08-20 22:48:41 +00003794
drh1fee73e2007-08-29 04:00:57 +00003795 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003796 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh9562b552002-02-19 15:00:07 +00003797 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003798 if( rc==SQLITE_OK ){
3799 if( CURSOR_INVALID==pCur->eState ){
danielk197771d5d2c2008-09-29 11:49:47 +00003800 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00003801 *pRes = 1;
3802 }else{
3803 assert( pCur->eState==CURSOR_VALID );
3804 *pRes = 0;
3805 rc = moveToRightmost(pCur);
drha2c20e42008-03-29 16:01:04 +00003806 getCellInfo(pCur);
drhf49661a2008-12-10 16:45:50 +00003807 pCur->atLast = rc==SQLITE_OK ?1:0;
drhd677b3d2007-08-20 22:48:41 +00003808 }
drh9562b552002-02-19 15:00:07 +00003809 }
drh9562b552002-02-19 15:00:07 +00003810 return rc;
3811}
3812
drhe14006d2008-03-25 17:23:32 +00003813/* Move the cursor so that it points to an entry near the key
drhe63d9992008-08-13 19:11:48 +00003814** specified by pIdxKey or intKey. Return a success code.
drh72f82862001-05-24 21:06:34 +00003815**
drhe63d9992008-08-13 19:11:48 +00003816** For INTKEY tables, the intKey parameter is used. pIdxKey
3817** must be NULL. For index tables, pIdxKey is used and intKey
3818** is ignored.
drh3aac2dd2004-04-26 14:10:20 +00003819**
drh5e2f8b92001-05-28 00:41:15 +00003820** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00003821** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00003822** were present. The cursor might point to an entry that comes
3823** before or after the key.
3824**
drh64022502009-01-09 14:11:04 +00003825** An integer is written into *pRes which is the result of
3826** comparing the key with the entry to which the cursor is
3827** pointing. The meaning of the integer written into
3828** *pRes is as follows:
drhbd03cae2001-06-02 02:40:57 +00003829**
3830** *pRes<0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00003831** is smaller than intKey/pIdxKey or if the table is empty
drh1a844c32002-12-04 22:29:28 +00003832** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00003833**
3834** *pRes==0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00003835** exactly matches intKey/pIdxKey.
drhbd03cae2001-06-02 02:40:57 +00003836**
3837** *pRes>0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00003838** is larger than intKey/pIdxKey.
drhd677b3d2007-08-20 22:48:41 +00003839**
drha059ad02001-04-17 20:09:11 +00003840*/
drhe63d9992008-08-13 19:11:48 +00003841int sqlite3BtreeMovetoUnpacked(
3842 BtCursor *pCur, /* The cursor to be moved */
3843 UnpackedRecord *pIdxKey, /* Unpacked index key */
3844 i64 intKey, /* The table key */
3845 int biasRight, /* If true, bias the search to the high end */
3846 int *pRes /* Write search results here */
drhe4d90812007-03-29 05:51:49 +00003847){
drh72f82862001-05-24 21:06:34 +00003848 int rc;
drhd677b3d2007-08-20 22:48:41 +00003849
drh1fee73e2007-08-29 04:00:57 +00003850 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003851 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drha2c20e42008-03-29 16:01:04 +00003852
3853 /* If the cursor is already positioned at the point we are trying
3854 ** to move to, then just return without doing any work */
danielk197771d5d2c2008-09-29 11:49:47 +00003855 if( pCur->eState==CURSOR_VALID && pCur->validNKey
3856 && pCur->apPage[0]->intKey
3857 ){
drhe63d9992008-08-13 19:11:48 +00003858 if( pCur->info.nKey==intKey ){
drha2c20e42008-03-29 16:01:04 +00003859 *pRes = 0;
3860 return SQLITE_OK;
3861 }
drhe63d9992008-08-13 19:11:48 +00003862 if( pCur->atLast && pCur->info.nKey<intKey ){
drha2c20e42008-03-29 16:01:04 +00003863 *pRes = -1;
3864 return SQLITE_OK;
3865 }
3866 }
3867
drh5e2f8b92001-05-28 00:41:15 +00003868 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003869 if( rc ){
3870 return rc;
3871 }
danielk197771d5d2c2008-09-29 11:49:47 +00003872 assert( pCur->apPage[pCur->iPage] );
3873 assert( pCur->apPage[pCur->iPage]->isInit );
danielk1977da184232006-01-05 11:34:32 +00003874 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00003875 *pRes = -1;
danielk197771d5d2c2008-09-29 11:49:47 +00003876 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhc39e0002004-05-07 23:50:57 +00003877 return SQLITE_OK;
3878 }
danielk197771d5d2c2008-09-29 11:49:47 +00003879 assert( pCur->apPage[0]->intKey || pIdxKey );
drh14684382006-11-30 13:05:29 +00003880 for(;;){
drh72f82862001-05-24 21:06:34 +00003881 int lwr, upr;
3882 Pgno chldPg;
danielk197771d5d2c2008-09-29 11:49:47 +00003883 MemPage *pPage = pCur->apPage[pCur->iPage];
drh1a844c32002-12-04 22:29:28 +00003884 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00003885 lwr = 0;
3886 upr = pPage->nCell-1;
drh64022502009-01-09 14:11:04 +00003887 if( (!pPage->intKey && pIdxKey==0) || upr<0 ){
drh1e968a02008-03-25 00:22:21 +00003888 rc = SQLITE_CORRUPT_BKPT;
3889 goto moveto_finish;
drh4eec4c12005-01-21 00:22:37 +00003890 }
drhe4d90812007-03-29 05:51:49 +00003891 if( biasRight ){
drhf49661a2008-12-10 16:45:50 +00003892 pCur->aiIdx[pCur->iPage] = (u16)upr;
drhe4d90812007-03-29 05:51:49 +00003893 }else{
drhf49661a2008-12-10 16:45:50 +00003894 pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
drhe4d90812007-03-29 05:51:49 +00003895 }
drh64022502009-01-09 14:11:04 +00003896 for(;;){
danielk197713adf8a2004-06-03 16:08:41 +00003897 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00003898 i64 nCellKey;
danielk197771d5d2c2008-09-29 11:49:47 +00003899 int idx = pCur->aiIdx[pCur->iPage];
drh366fda62006-01-13 02:35:09 +00003900 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003901 pCur->validNKey = 1;
drh3aac2dd2004-04-26 14:10:20 +00003902 if( pPage->intKey ){
drh777e4c42006-01-13 04:31:58 +00003903 u8 *pCell;
danielk197771d5d2c2008-09-29 11:49:47 +00003904 pCell = findCell(pPage, idx) + pPage->childPtrSize;
drhd172f862006-01-12 15:01:15 +00003905 if( pPage->hasData ){
danielk1977bab45c62006-01-16 15:14:27 +00003906 u32 dummy;
shane3f8d5cf2008-04-24 19:15:09 +00003907 pCell += getVarint32(pCell, dummy);
drhd172f862006-01-12 15:01:15 +00003908 }
drha2c20e42008-03-29 16:01:04 +00003909 getVarint(pCell, (u64*)&nCellKey);
drhe63d9992008-08-13 19:11:48 +00003910 if( nCellKey==intKey ){
drh3aac2dd2004-04-26 14:10:20 +00003911 c = 0;
drhe63d9992008-08-13 19:11:48 +00003912 }else if( nCellKey<intKey ){
drh41eb9e92008-04-02 18:33:07 +00003913 c = -1;
3914 }else{
drhe63d9992008-08-13 19:11:48 +00003915 assert( nCellKey>intKey );
drh41eb9e92008-04-02 18:33:07 +00003916 c = +1;
drh3aac2dd2004-04-26 14:10:20 +00003917 }
drh3aac2dd2004-04-26 14:10:20 +00003918 }else{
drhe51c44f2004-05-30 20:46:09 +00003919 int available;
danielk197713adf8a2004-06-03 16:08:41 +00003920 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drh366fda62006-01-13 02:35:09 +00003921 nCellKey = pCur->info.nKey;
drhe51c44f2004-05-30 20:46:09 +00003922 if( available>=nCellKey ){
drhf49661a2008-12-10 16:45:50 +00003923 c = sqlite3VdbeRecordCompare((int)nCellKey, pCellKey, pIdxKey);
drhe51c44f2004-05-30 20:46:09 +00003924 }else{
drhf49661a2008-12-10 16:45:50 +00003925 pCellKey = sqlite3Malloc( (int)nCellKey );
danielk19776507ecb2008-03-25 09:56:44 +00003926 if( pCellKey==0 ){
3927 rc = SQLITE_NOMEM;
3928 goto moveto_finish;
3929 }
drhf49661a2008-12-10 16:45:50 +00003930 rc = sqlite3BtreeKey(pCur, 0, (int)nCellKey, (void*)pCellKey);
drh1bd10f82008-12-10 21:19:56 +00003931 c = sqlite3VdbeRecordCompare((int)nCellKey, pCellKey, pIdxKey);
drhfacf0302008-06-17 15:12:00 +00003932 sqlite3_free(pCellKey);
drh1e968a02008-03-25 00:22:21 +00003933 if( rc ) goto moveto_finish;
drhe51c44f2004-05-30 20:46:09 +00003934 }
drh3aac2dd2004-04-26 14:10:20 +00003935 }
drh72f82862001-05-24 21:06:34 +00003936 if( c==0 ){
drha2c20e42008-03-29 16:01:04 +00003937 pCur->info.nKey = nCellKey;
drh44845222008-07-17 18:39:57 +00003938 if( pPage->intKey && !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00003939 lwr = idx;
drhfc70e6f2004-05-12 21:11:27 +00003940 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00003941 break;
3942 }else{
drh64022502009-01-09 14:11:04 +00003943 *pRes = 0;
drh1e968a02008-03-25 00:22:21 +00003944 rc = SQLITE_OK;
3945 goto moveto_finish;
drh8b18dd42004-05-12 19:18:15 +00003946 }
drh72f82862001-05-24 21:06:34 +00003947 }
3948 if( c<0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003949 lwr = idx+1;
drh72f82862001-05-24 21:06:34 +00003950 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00003951 upr = idx-1;
drh72f82862001-05-24 21:06:34 +00003952 }
drhf1d68b32007-03-29 04:43:26 +00003953 if( lwr>upr ){
drha2c20e42008-03-29 16:01:04 +00003954 pCur->info.nKey = nCellKey;
drhf1d68b32007-03-29 04:43:26 +00003955 break;
3956 }
drhf49661a2008-12-10 16:45:50 +00003957 pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
drh72f82862001-05-24 21:06:34 +00003958 }
3959 assert( lwr==upr+1 );
danielk197771d5d2c2008-09-29 11:49:47 +00003960 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00003961 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00003962 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00003963 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00003964 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00003965 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00003966 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00003967 }
3968 if( chldPg==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003969 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh72f82862001-05-24 21:06:34 +00003970 if( pRes ) *pRes = c;
drh1e968a02008-03-25 00:22:21 +00003971 rc = SQLITE_OK;
3972 goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00003973 }
drhf49661a2008-12-10 16:45:50 +00003974 pCur->aiIdx[pCur->iPage] = (u16)lwr;
drh271efa52004-05-30 19:19:05 +00003975 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003976 pCur->validNKey = 0;
drh8178a752003-01-05 21:41:40 +00003977 rc = moveToChild(pCur, chldPg);
drh1e968a02008-03-25 00:22:21 +00003978 if( rc ) goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00003979 }
drh1e968a02008-03-25 00:22:21 +00003980moveto_finish:
drhe63d9992008-08-13 19:11:48 +00003981 return rc;
3982}
3983
3984/*
3985** In this version of BtreeMoveto, pKey is a packed index record
3986** such as is generated by the OP_MakeRecord opcode. Unpack the
3987** record and then call BtreeMovetoUnpacked() to do the work.
3988*/
3989int sqlite3BtreeMoveto(
3990 BtCursor *pCur, /* Cursor open on the btree to be searched */
3991 const void *pKey, /* Packed key if the btree is an index */
3992 i64 nKey, /* Integer key for tables. Size of pKey for indices */
3993 int bias, /* Bias search to the high end */
3994 int *pRes /* Write search results here */
3995){
3996 int rc; /* Status code */
3997 UnpackedRecord *pIdxKey; /* Unpacked index key */
drh23f79d02008-08-20 22:06:47 +00003998 UnpackedRecord aSpace[16]; /* Temp space for pIdxKey - to avoid a malloc */
drhe63d9992008-08-13 19:11:48 +00003999
drhe14006d2008-03-25 17:23:32 +00004000 if( pKey ){
drhf49661a2008-12-10 16:45:50 +00004001 assert( nKey==(i64)(int)nKey );
4002 pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
drh23f79d02008-08-20 22:06:47 +00004003 aSpace, sizeof(aSpace));
drhe63d9992008-08-13 19:11:48 +00004004 if( pIdxKey==0 ) return SQLITE_NOMEM;
4005 }else{
4006 pIdxKey = 0;
4007 }
4008 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
4009 if( pKey ){
4010 sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
drhe14006d2008-03-25 17:23:32 +00004011 }
drh1e968a02008-03-25 00:22:21 +00004012 return rc;
drh72f82862001-05-24 21:06:34 +00004013}
4014
drhd677b3d2007-08-20 22:48:41 +00004015
drh72f82862001-05-24 21:06:34 +00004016/*
drhc39e0002004-05-07 23:50:57 +00004017** Return TRUE if the cursor is not pointing at an entry of the table.
4018**
4019** TRUE will be returned after a call to sqlite3BtreeNext() moves
4020** past the last entry in the table or sqlite3BtreePrev() moves past
4021** the first entry. TRUE is also returned if the table is empty.
4022*/
4023int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00004024 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
4025 ** have been deleted? This API will need to change to return an error code
4026 ** as well as the boolean result value.
4027 */
4028 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00004029}
4030
4031/*
drhb21c8cd2007-08-21 19:33:56 +00004032** Return the database connection handle for a cursor.
4033*/
4034sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){
drhe5fe6902007-12-07 18:55:28 +00004035 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
4036 return pCur->pBtree->db;
drhb21c8cd2007-08-21 19:33:56 +00004037}
4038
4039/*
drhbd03cae2001-06-02 02:40:57 +00004040** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00004041** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00004042** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00004043** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00004044*/
drhd094db12008-04-03 21:46:57 +00004045int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00004046 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00004047 int idx;
danielk197797a227c2006-01-20 16:32:04 +00004048 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00004049
drh1fee73e2007-08-29 04:00:57 +00004050 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004051 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004052 if( rc!=SQLITE_OK ){
4053 return rc;
4054 }
drh8c4d3a62007-04-06 01:03:32 +00004055 assert( pRes!=0 );
drh8c4d3a62007-04-06 01:03:32 +00004056 if( CURSOR_INVALID==pCur->eState ){
4057 *pRes = 1;
4058 return SQLITE_OK;
4059 }
danielk1977da184232006-01-05 11:34:32 +00004060 if( pCur->skip>0 ){
4061 pCur->skip = 0;
4062 *pRes = 0;
4063 return SQLITE_OK;
4064 }
4065 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00004066
danielk197771d5d2c2008-09-29 11:49:47 +00004067 pPage = pCur->apPage[pCur->iPage];
4068 idx = ++pCur->aiIdx[pCur->iPage];
4069 assert( pPage->isInit );
4070 assert( idx<=pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00004071
drh271efa52004-05-30 19:19:05 +00004072 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004073 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004074 if( idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00004075 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004076 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00004077 if( rc ) return rc;
4078 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00004079 *pRes = 0;
4080 return rc;
drh72f82862001-05-24 21:06:34 +00004081 }
drh5e2f8b92001-05-28 00:41:15 +00004082 do{
danielk197771d5d2c2008-09-29 11:49:47 +00004083 if( pCur->iPage==0 ){
drh8c1238a2003-01-02 14:43:55 +00004084 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00004085 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00004086 return SQLITE_OK;
4087 }
drh16a9b832007-05-05 18:39:25 +00004088 sqlite3BtreeMoveToParent(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00004089 pPage = pCur->apPage[pCur->iPage];
4090 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00004091 *pRes = 0;
drh44845222008-07-17 18:39:57 +00004092 if( pPage->intKey ){
drh8b18dd42004-05-12 19:18:15 +00004093 rc = sqlite3BtreeNext(pCur, pRes);
4094 }else{
4095 rc = SQLITE_OK;
4096 }
4097 return rc;
drh8178a752003-01-05 21:41:40 +00004098 }
4099 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00004100 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00004101 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00004102 }
drh5e2f8b92001-05-28 00:41:15 +00004103 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00004104 return rc;
drh72f82862001-05-24 21:06:34 +00004105}
drhd677b3d2007-08-20 22:48:41 +00004106
drh72f82862001-05-24 21:06:34 +00004107
drh3b7511c2001-05-26 13:15:44 +00004108/*
drh2dcc9aa2002-12-04 13:40:25 +00004109** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00004110** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00004111** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00004112** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00004113*/
drhd094db12008-04-03 21:46:57 +00004114int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00004115 int rc;
drh8178a752003-01-05 21:41:40 +00004116 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00004117
drh1fee73e2007-08-29 04:00:57 +00004118 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004119 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004120 if( rc!=SQLITE_OK ){
4121 return rc;
4122 }
drha2c20e42008-03-29 16:01:04 +00004123 pCur->atLast = 0;
drh8c4d3a62007-04-06 01:03:32 +00004124 if( CURSOR_INVALID==pCur->eState ){
4125 *pRes = 1;
4126 return SQLITE_OK;
4127 }
danielk1977da184232006-01-05 11:34:32 +00004128 if( pCur->skip<0 ){
4129 pCur->skip = 0;
4130 *pRes = 0;
4131 return SQLITE_OK;
4132 }
4133 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00004134
danielk197771d5d2c2008-09-29 11:49:47 +00004135 pPage = pCur->apPage[pCur->iPage];
4136 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00004137 if( !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00004138 int idx = pCur->aiIdx[pCur->iPage];
4139 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
drhd677b3d2007-08-20 22:48:41 +00004140 if( rc ){
4141 return rc;
4142 }
drh2dcc9aa2002-12-04 13:40:25 +00004143 rc = moveToRightmost(pCur);
4144 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004145 while( pCur->aiIdx[pCur->iPage]==0 ){
4146 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00004147 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00004148 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00004149 return SQLITE_OK;
4150 }
drh16a9b832007-05-05 18:39:25 +00004151 sqlite3BtreeMoveToParent(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00004152 }
drh271efa52004-05-30 19:19:05 +00004153 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004154 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004155
4156 pCur->aiIdx[pCur->iPage]--;
4157 pPage = pCur->apPage[pCur->iPage];
drh44845222008-07-17 18:39:57 +00004158 if( pPage->intKey && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00004159 rc = sqlite3BtreePrevious(pCur, pRes);
4160 }else{
4161 rc = SQLITE_OK;
4162 }
drh2dcc9aa2002-12-04 13:40:25 +00004163 }
drh8178a752003-01-05 21:41:40 +00004164 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00004165 return rc;
4166}
4167
4168/*
drh3b7511c2001-05-26 13:15:44 +00004169** Allocate a new page from the database file.
4170**
danielk19773b8a05f2007-03-19 17:44:26 +00004171** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00004172** has already been called on the new page.) The new page has also
4173** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00004174** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00004175**
4176** SQLITE_OK is returned on success. Any other return value indicates
4177** an error. *ppPage and *pPgno are undefined in the event of an error.
danielk19773b8a05f2007-03-19 17:44:26 +00004178** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00004179**
drh199e3cf2002-07-18 11:01:47 +00004180** If the "nearby" parameter is not 0, then a (feeble) effort is made to
4181** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00004182** attempt to keep related pages close to each other in the database file,
4183** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00004184**
4185** If the "exact" parameter is not 0, and the page-number nearby exists
4186** anywhere on the free-list, then it is guarenteed to be returned. This
4187** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00004188*/
drh4f0c5872007-03-26 22:05:01 +00004189static int allocateBtreePage(
danielk1977aef0bf62005-12-30 16:28:01 +00004190 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00004191 MemPage **ppPage,
4192 Pgno *pPgno,
4193 Pgno nearby,
4194 u8 exact
4195){
drh3aac2dd2004-04-26 14:10:20 +00004196 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00004197 int rc;
drh3aac2dd2004-04-26 14:10:20 +00004198 int n; /* Number of pages on the freelist */
4199 int k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00004200 MemPage *pTrunk = 0;
4201 MemPage *pPrevTrunk = 0;
drh30e58752002-03-02 20:41:57 +00004202
drh1fee73e2007-08-29 04:00:57 +00004203 assert( sqlite3_mutex_held(pBt->mutex) );
drh3aac2dd2004-04-26 14:10:20 +00004204 pPage1 = pBt->pPage1;
4205 n = get4byte(&pPage1->aData[36]);
4206 if( n>0 ){
drh91025292004-05-03 19:49:32 +00004207 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00004208 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004209 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
4210
4211 /* If the 'exact' parameter was true and a query of the pointer-map
4212 ** shows that the page 'nearby' is somewhere on the free-list, then
4213 ** the entire-list will be searched for that page.
4214 */
4215#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197789d40042008-11-17 14:20:56 +00004216 if( exact && nearby<=pagerPagecount(pBt) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004217 u8 eType;
4218 assert( nearby>0 );
4219 assert( pBt->autoVacuum );
4220 rc = ptrmapGet(pBt, nearby, &eType, 0);
4221 if( rc ) return rc;
4222 if( eType==PTRMAP_FREEPAGE ){
4223 searchList = 1;
4224 }
4225 *pPgno = nearby;
4226 }
4227#endif
4228
4229 /* Decrement the free-list count by 1. Set iTrunk to the index of the
4230 ** first free-list trunk page. iPrevTrunk is initially 1.
4231 */
danielk19773b8a05f2007-03-19 17:44:26 +00004232 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00004233 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004234 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004235
4236 /* The code within this loop is run only once if the 'searchList' variable
4237 ** is not true. Otherwise, it runs once for each trunk-page on the
4238 ** free-list until the page 'nearby' is located.
4239 */
4240 do {
4241 pPrevTrunk = pTrunk;
4242 if( pPrevTrunk ){
4243 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00004244 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004245 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00004246 }
drh16a9b832007-05-05 18:39:25 +00004247 rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004248 if( rc ){
drhd3627af2006-12-18 18:34:51 +00004249 pTrunk = 0;
4250 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004251 }
4252
4253 k = get4byte(&pTrunk->aData[4]);
4254 if( k==0 && !searchList ){
4255 /* The trunk has no leaves and the list is not being searched.
4256 ** So extract the trunk page itself and use it as the newly
4257 ** allocated page */
4258 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00004259 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004260 if( rc ){
4261 goto end_allocate_page;
4262 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004263 *pPgno = iTrunk;
4264 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4265 *ppPage = pTrunk;
4266 pTrunk = 0;
4267 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh45b1fac2008-07-04 17:52:42 +00004268 }else if( k>pBt->usableSize/4 - 2 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004269 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00004270 rc = SQLITE_CORRUPT_BKPT;
4271 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004272#ifndef SQLITE_OMIT_AUTOVACUUM
4273 }else if( searchList && nearby==iTrunk ){
4274 /* The list is being searched and this trunk page is the page
4275 ** to allocate, regardless of whether it has leaves.
4276 */
4277 assert( *pPgno==iTrunk );
4278 *ppPage = pTrunk;
4279 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00004280 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004281 if( rc ){
4282 goto end_allocate_page;
4283 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004284 if( k==0 ){
4285 if( !pPrevTrunk ){
4286 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4287 }else{
4288 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
4289 }
4290 }else{
4291 /* The trunk page is required by the caller but it contains
4292 ** pointers to free-list leaves. The first leaf becomes a trunk
4293 ** page in this case.
4294 */
4295 MemPage *pNewTrunk;
4296 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh16a9b832007-05-05 18:39:25 +00004297 rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004298 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00004299 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004300 }
danielk19773b8a05f2007-03-19 17:44:26 +00004301 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004302 if( rc!=SQLITE_OK ){
4303 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00004304 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004305 }
4306 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
4307 put4byte(&pNewTrunk->aData[4], k-1);
4308 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00004309 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004310 if( !pPrevTrunk ){
drhc5053fb2008-11-27 02:22:10 +00004311 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
danielk1977cb1a7eb2004-11-05 12:27:02 +00004312 put4byte(&pPage1->aData[32], iNewTrunk);
4313 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00004314 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004315 if( rc ){
4316 goto end_allocate_page;
4317 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004318 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
4319 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004320 }
4321 pTrunk = 0;
4322 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
4323#endif
4324 }else{
4325 /* Extract a leaf from the trunk */
4326 int closest;
4327 Pgno iPage;
4328 unsigned char *aData = pTrunk->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00004329 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004330 if( rc ){
4331 goto end_allocate_page;
4332 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004333 if( nearby>0 ){
4334 int i, dist;
4335 closest = 0;
4336 dist = get4byte(&aData[8]) - nearby;
4337 if( dist<0 ) dist = -dist;
4338 for(i=1; i<k; i++){
4339 int d2 = get4byte(&aData[8+i*4]) - nearby;
4340 if( d2<0 ) d2 = -d2;
4341 if( d2<dist ){
4342 closest = i;
4343 dist = d2;
4344 }
4345 }
4346 }else{
4347 closest = 0;
4348 }
4349
4350 iPage = get4byte(&aData[8+closest*4]);
4351 if( !searchList || iPage==nearby ){
danielk1977bea2a942009-01-20 17:06:27 +00004352 int noContent;
danielk197789d40042008-11-17 14:20:56 +00004353 Pgno nPage;
shane1f9e6aa2008-06-09 19:27:11 +00004354 *pPgno = iPage;
danielk197789d40042008-11-17 14:20:56 +00004355 nPage = pagerPagecount(pBt);
danielk1977ad0132d2008-06-07 08:58:22 +00004356 if( *pPgno>nPage ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004357 /* Free page off the end of the file */
danielk197743e377a2008-05-05 12:09:32 +00004358 rc = SQLITE_CORRUPT_BKPT;
4359 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004360 }
4361 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
4362 ": %d more free pages\n",
4363 *pPgno, closest+1, k, pTrunk->pgno, n-1));
4364 if( closest<k-1 ){
4365 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
4366 }
4367 put4byte(&aData[4], k-1);
drhc5053fb2008-11-27 02:22:10 +00004368 assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
danielk1977bea2a942009-01-20 17:06:27 +00004369 noContent = !btreeGetHasContent(pBt, *pPgno);
4370 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, noContent);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004371 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00004372 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004373 if( rc!=SQLITE_OK ){
4374 releasePage(*ppPage);
4375 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004376 }
4377 searchList = 0;
4378 }
drhee696e22004-08-30 16:52:17 +00004379 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004380 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00004381 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004382 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00004383 }else{
drh3aac2dd2004-04-26 14:10:20 +00004384 /* There are no pages on the freelist, so create a new page at the
4385 ** end of the file */
danielk197789d40042008-11-17 14:20:56 +00004386 int nPage = pagerPagecount(pBt);
danielk1977ad0132d2008-06-07 08:58:22 +00004387 *pPgno = nPage + 1;
danielk1977afcdd022004-10-31 16:25:42 +00004388
danielk1977bea2a942009-01-20 17:06:27 +00004389 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
4390 (*pPgno)++;
4391 }
4392
danielk1977afcdd022004-10-31 16:25:42 +00004393#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977266664d2006-02-10 08:24:21 +00004394 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00004395 /* If *pPgno refers to a pointer-map page, allocate two new pages
4396 ** at the end of the file instead of one. The first allocated page
4397 ** becomes a new pointer-map page, the second is used by the caller.
4398 */
4399 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00004400 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977afcdd022004-10-31 16:25:42 +00004401 (*pPgno)++;
drh72190432008-01-31 14:54:43 +00004402 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
danielk1977afcdd022004-10-31 16:25:42 +00004403 }
4404#endif
4405
danielk1977599fcba2004-11-08 07:13:13 +00004406 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh16a9b832007-05-05 18:39:25 +00004407 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
drh3b7511c2001-05-26 13:15:44 +00004408 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00004409 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004410 if( rc!=SQLITE_OK ){
4411 releasePage(*ppPage);
4412 }
drh3a4c1412004-05-09 20:40:11 +00004413 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00004414 }
danielk1977599fcba2004-11-08 07:13:13 +00004415
4416 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00004417
4418end_allocate_page:
4419 releasePage(pTrunk);
4420 releasePage(pPrevTrunk);
danielk1977b247c212008-11-21 09:09:01 +00004421 if( rc==SQLITE_OK ){
4422 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
4423 releasePage(*ppPage);
4424 return SQLITE_CORRUPT_BKPT;
4425 }
4426 (*ppPage)->isInit = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00004427 }
drh3b7511c2001-05-26 13:15:44 +00004428 return rc;
4429}
4430
4431/*
danielk1977bea2a942009-01-20 17:06:27 +00004432** This function is used to add page iPage to the database file free-list.
4433** It is assumed that the page is not already a part of the free-list.
drh5e2f8b92001-05-28 00:41:15 +00004434**
danielk1977bea2a942009-01-20 17:06:27 +00004435** The value passed as the second argument to this function is optional.
4436** If the caller happens to have a pointer to the MemPage object
4437** corresponding to page iPage handy, it may pass it as the second value.
4438** Otherwise, it may pass NULL.
4439**
4440** If a pointer to a MemPage object is passed as the second argument,
4441** its reference count is not altered by this function.
drh3b7511c2001-05-26 13:15:44 +00004442*/
danielk1977bea2a942009-01-20 17:06:27 +00004443static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
4444 MemPage *pTrunk = 0; /* Free-list trunk page */
4445 Pgno iTrunk = 0; /* Page number of free-list trunk page */
4446 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
4447 MemPage *pPage; /* Page being freed. May be NULL. */
4448 int rc; /* Return Code */
4449 int nFree; /* Initial number of pages on free-list */
drh8b2f49b2001-06-08 00:21:52 +00004450
danielk1977bea2a942009-01-20 17:06:27 +00004451 assert( sqlite3_mutex_held(pBt->mutex) );
4452 assert( iPage>1 );
4453 assert( !pMemPage || pMemPage->pgno==iPage );
4454
4455 if( pMemPage ){
4456 pPage = pMemPage;
4457 sqlite3PagerRef(pPage->pDbPage);
4458 }else{
4459 pPage = btreePageLookup(pBt, iPage);
4460 }
drh3aac2dd2004-04-26 14:10:20 +00004461
drha34b6762004-05-07 13:30:42 +00004462 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00004463 rc = sqlite3PagerWrite(pPage1->pDbPage);
danielk1977bea2a942009-01-20 17:06:27 +00004464 if( rc ) goto freepage_out;
4465 nFree = get4byte(&pPage1->aData[36]);
4466 put4byte(&pPage1->aData[36], nFree+1);
drh3aac2dd2004-04-26 14:10:20 +00004467
drhfcce93f2006-02-22 03:08:32 +00004468#ifdef SQLITE_SECURE_DELETE
4469 /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
4470 ** always fully overwrite deleted information with zeros.
4471 */
danielk1977bea2a942009-01-20 17:06:27 +00004472 if( (!pPage && (rc = sqlite3BtreeGetPage(pBt, iPage, &pPage, 0)))
4473 || (rc = sqlite3PagerWrite(pPage->pDbPage))
4474 ){
4475 goto freepage_out;
4476 }
drhfcce93f2006-02-22 03:08:32 +00004477 memset(pPage->aData, 0, pPage->pBt->pageSize);
4478#endif
4479
danielk1977687566d2004-11-02 12:56:41 +00004480 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00004481 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00004482 */
danielk197785d90ca2008-07-19 14:25:15 +00004483 if( ISAUTOVACUUM ){
danielk1977bea2a942009-01-20 17:06:27 +00004484 rc = ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0);
4485 if( rc ) goto freepage_out;
danielk1977687566d2004-11-02 12:56:41 +00004486 }
danielk1977687566d2004-11-02 12:56:41 +00004487
danielk1977bea2a942009-01-20 17:06:27 +00004488 /* Now manipulate the actual database free-list structure. There are two
4489 ** possibilities. If the free-list is currently empty, or if the first
4490 ** trunk page in the free-list is full, then this page will become a
4491 ** new free-list trunk page. Otherwise, it will become a leaf of the
4492 ** first trunk page in the current free-list. This block tests if it
4493 ** is possible to add the page as a new free-list leaf.
4494 */
4495 if( nFree!=0 ){
4496 int nLeaf; /* Initial number of leaf cells on trunk page */
4497
4498 iTrunk = get4byte(&pPage1->aData[32]);
4499 rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
4500 if( rc!=SQLITE_OK ){
4501 goto freepage_out;
4502 }
4503
4504 nLeaf = get4byte(&pTrunk->aData[4]);
4505 if( nLeaf<0 ){
4506 rc = SQLITE_CORRUPT_BKPT;
4507 goto freepage_out;
4508 }
4509 if( nLeaf<pBt->usableSize/4 - 8 ){
4510 /* In this case there is room on the trunk page to insert the page
4511 ** being freed as a new leaf.
drh45b1fac2008-07-04 17:52:42 +00004512 **
4513 ** Note that the trunk page is not really full until it contains
4514 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
4515 ** coded. But due to a coding error in versions of SQLite prior to
4516 ** 3.6.0, databases with freelist trunk pages holding more than
4517 ** usableSize/4 - 8 entries will be reported as corrupt. In order
4518 ** to maintain backwards compatibility with older versions of SQLite,
4519 ** we will contain to restrict the number of entries to usableSize/4 - 8
4520 ** for now. At some point in the future (once everyone has upgraded
4521 ** to 3.6.0 or later) we should consider fixing the conditional above
4522 ** to read "usableSize/4-2" instead of "usableSize/4-8".
4523 */
danielk19773b8a05f2007-03-19 17:44:26 +00004524 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00004525 if( rc==SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00004526 put4byte(&pTrunk->aData[4], nLeaf+1);
4527 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
drhfcce93f2006-02-22 03:08:32 +00004528#ifndef SQLITE_SECURE_DELETE
danielk1977bea2a942009-01-20 17:06:27 +00004529 if( pPage ){
4530 sqlite3PagerDontWrite(pPage->pDbPage);
4531 }
drhfcce93f2006-02-22 03:08:32 +00004532#endif
danielk1977bea2a942009-01-20 17:06:27 +00004533 rc = btreeSetHasContent(pBt, iPage);
drhf5345442007-04-09 12:45:02 +00004534 }
drh3a4c1412004-05-09 20:40:11 +00004535 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
danielk1977bea2a942009-01-20 17:06:27 +00004536 goto freepage_out;
drh3aac2dd2004-04-26 14:10:20 +00004537 }
drh3b7511c2001-05-26 13:15:44 +00004538 }
danielk1977bea2a942009-01-20 17:06:27 +00004539
4540 /* If control flows to this point, then it was not possible to add the
4541 ** the page being freed as a leaf page of the first trunk in the free-list.
4542 ** Possibly because the free-list is empty, or possibly because the
4543 ** first trunk in the free-list is full. Either way, the page being freed
4544 ** will become the new first trunk page in the free-list.
4545 */
shane63207ab2009-02-04 01:49:30 +00004546 if( ((!pPage) && (0 != (rc = sqlite3BtreeGetPage(pBt, iPage, &pPage, 0))))
4547 || (0 != (rc = sqlite3PagerWrite(pPage->pDbPage)))
danielk1977bea2a942009-01-20 17:06:27 +00004548 ){
4549 goto freepage_out;
4550 }
4551 put4byte(pPage->aData, iTrunk);
4552 put4byte(&pPage->aData[4], 0);
4553 put4byte(&pPage1->aData[32], iPage);
4554 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
4555
4556freepage_out:
4557 if( pPage ){
4558 pPage->isInit = 0;
4559 }
4560 releasePage(pPage);
4561 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00004562 return rc;
4563}
danielk1977bea2a942009-01-20 17:06:27 +00004564static int freePage(MemPage *pPage){
4565 return freePage2(pPage->pBt, pPage, pPage->pgno);
4566}
drh3b7511c2001-05-26 13:15:44 +00004567
4568/*
drh3aac2dd2004-04-26 14:10:20 +00004569** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00004570*/
drh3aac2dd2004-04-26 14:10:20 +00004571static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00004572 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00004573 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00004574 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00004575 int rc;
drh94440812007-03-06 11:42:19 +00004576 int nOvfl;
shane63207ab2009-02-04 01:49:30 +00004577 u16 ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00004578
drh1fee73e2007-08-29 04:00:57 +00004579 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh16a9b832007-05-05 18:39:25 +00004580 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004581 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00004582 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00004583 }
drh6f11bef2004-05-13 01:12:56 +00004584 ovflPgno = get4byte(&pCell[info.iOverflow]);
shane63207ab2009-02-04 01:49:30 +00004585 assert( pBt->usableSize > 4 );
drh94440812007-03-06 11:42:19 +00004586 ovflPageSize = pBt->usableSize - 4;
drh72365832007-03-06 15:53:44 +00004587 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
4588 assert( ovflPgno==0 || nOvfl>0 );
4589 while( nOvfl-- ){
shane63207ab2009-02-04 01:49:30 +00004590 Pgno iNext = 0;
danielk1977bea2a942009-01-20 17:06:27 +00004591 MemPage *pOvfl = 0;
danielk197789d40042008-11-17 14:20:56 +00004592 if( ovflPgno==0 || ovflPgno>pagerPagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00004593 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00004594 }
danielk1977bea2a942009-01-20 17:06:27 +00004595 if( nOvfl ){
4596 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
4597 if( rc ) return rc;
4598 }
4599 rc = freePage2(pBt, pOvfl, ovflPgno);
4600 if( pOvfl ){
4601 sqlite3PagerUnref(pOvfl->pDbPage);
4602 }
drh3b7511c2001-05-26 13:15:44 +00004603 if( rc ) return rc;
danielk1977bea2a942009-01-20 17:06:27 +00004604 ovflPgno = iNext;
drh3b7511c2001-05-26 13:15:44 +00004605 }
drh5e2f8b92001-05-28 00:41:15 +00004606 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00004607}
4608
4609/*
drh91025292004-05-03 19:49:32 +00004610** Create the byte sequence used to represent a cell on page pPage
4611** and write that byte sequence into pCell[]. Overflow pages are
4612** allocated and filled in as necessary. The calling procedure
4613** is responsible for making sure sufficient space has been allocated
4614** for pCell[].
4615**
4616** Note that pCell does not necessary need to point to the pPage->aData
4617** area. pCell might point to some temporary storage. The cell will
4618** be constructed in this temporary area then copied into pPage->aData
4619** later.
drh3b7511c2001-05-26 13:15:44 +00004620*/
4621static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00004622 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00004623 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00004624 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00004625 const void *pData,int nData, /* The data */
drhb026e052007-05-02 01:34:31 +00004626 int nZero, /* Extra zero bytes to append to pData */
drh4b70f112004-05-02 21:12:19 +00004627 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00004628){
drh3b7511c2001-05-26 13:15:44 +00004629 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00004630 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00004631 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00004632 int spaceLeft;
4633 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00004634 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00004635 unsigned char *pPrior;
4636 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00004637 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00004638 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00004639 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00004640 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00004641
drh1fee73e2007-08-29 04:00:57 +00004642 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00004643
drhc5053fb2008-11-27 02:22:10 +00004644 /* pPage is not necessarily writeable since pCell might be auxiliary
4645 ** buffer space that is separate from the pPage buffer area */
4646 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
4647 || sqlite3PagerIswriteable(pPage->pDbPage) );
4648
drh91025292004-05-03 19:49:32 +00004649 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00004650 nHeader = 0;
drh91025292004-05-03 19:49:32 +00004651 if( !pPage->leaf ){
4652 nHeader += 4;
4653 }
drh8b18dd42004-05-12 19:18:15 +00004654 if( pPage->hasData ){
drhb026e052007-05-02 01:34:31 +00004655 nHeader += putVarint(&pCell[nHeader], nData+nZero);
drh6f11bef2004-05-13 01:12:56 +00004656 }else{
drhb026e052007-05-02 01:34:31 +00004657 nData = nZero = 0;
drh91025292004-05-03 19:49:32 +00004658 }
drh6f11bef2004-05-13 01:12:56 +00004659 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh16a9b832007-05-05 18:39:25 +00004660 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004661 assert( info.nHeader==nHeader );
4662 assert( info.nKey==nKey );
danielk197789d40042008-11-17 14:20:56 +00004663 assert( info.nData==(u32)(nData+nZero) );
drh6f11bef2004-05-13 01:12:56 +00004664
4665 /* Fill in the payload */
drhb026e052007-05-02 01:34:31 +00004666 nPayload = nData + nZero;
drh3aac2dd2004-04-26 14:10:20 +00004667 if( pPage->intKey ){
4668 pSrc = pData;
4669 nSrc = nData;
drh91025292004-05-03 19:49:32 +00004670 nData = 0;
drhf49661a2008-12-10 16:45:50 +00004671 }else{
drh20abac22009-01-28 20:21:17 +00004672 if( nKey>0x7fffffff || pKey==0 ){
4673 return SQLITE_CORRUPT;
4674 }
drhf49661a2008-12-10 16:45:50 +00004675 nPayload += (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00004676 pSrc = pKey;
drhf49661a2008-12-10 16:45:50 +00004677 nSrc = (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00004678 }
drh6f11bef2004-05-13 01:12:56 +00004679 *pnSize = info.nSize;
4680 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00004681 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00004682 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00004683
drh3b7511c2001-05-26 13:15:44 +00004684 while( nPayload>0 ){
4685 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00004686#ifndef SQLITE_OMIT_AUTOVACUUM
4687 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00004688 if( pBt->autoVacuum ){
4689 do{
4690 pgnoOvfl++;
4691 } while(
4692 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
4693 );
danielk1977b39f70b2007-05-17 18:28:11 +00004694 }
danielk1977afcdd022004-10-31 16:25:42 +00004695#endif
drhf49661a2008-12-10 16:45:50 +00004696 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00004697#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00004698 /* If the database supports auto-vacuum, and the second or subsequent
4699 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00004700 ** for that page now.
4701 **
4702 ** If this is the first overflow page, then write a partial entry
4703 ** to the pointer-map. If we write nothing to this pointer-map slot,
4704 ** then the optimistic overflow chain processing in clearCell()
4705 ** may misinterpret the uninitialised values and delete the
4706 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00004707 */
danielk19774ef24492007-05-23 09:52:41 +00004708 if( pBt->autoVacuum && rc==SQLITE_OK ){
4709 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
4710 rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
danielk197789a4be82007-05-23 13:34:32 +00004711 if( rc ){
4712 releasePage(pOvfl);
4713 }
danielk1977afcdd022004-10-31 16:25:42 +00004714 }
4715#endif
drh3b7511c2001-05-26 13:15:44 +00004716 if( rc ){
drh9b171272004-05-08 02:03:22 +00004717 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00004718 return rc;
4719 }
drhc5053fb2008-11-27 02:22:10 +00004720
4721 /* If pToRelease is not zero than pPrior points into the data area
4722 ** of pToRelease. Make sure pToRelease is still writeable. */
4723 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
4724
4725 /* If pPrior is part of the data area of pPage, then make sure pPage
4726 ** is still writeable */
4727 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
4728 || sqlite3PagerIswriteable(pPage->pDbPage) );
4729
drh3aac2dd2004-04-26 14:10:20 +00004730 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00004731 releasePage(pToRelease);
4732 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00004733 pPrior = pOvfl->aData;
4734 put4byte(pPrior, 0);
4735 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00004736 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00004737 }
4738 n = nPayload;
4739 if( n>spaceLeft ) n = spaceLeft;
drhc5053fb2008-11-27 02:22:10 +00004740
4741 /* If pToRelease is not zero than pPayload points into the data area
4742 ** of pToRelease. Make sure pToRelease is still writeable. */
4743 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
4744
4745 /* If pPayload is part of the data area of pPage, then make sure pPage
4746 ** is still writeable */
4747 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
4748 || sqlite3PagerIswriteable(pPage->pDbPage) );
4749
drhb026e052007-05-02 01:34:31 +00004750 if( nSrc>0 ){
4751 if( n>nSrc ) n = nSrc;
4752 assert( pSrc );
4753 memcpy(pPayload, pSrc, n);
4754 }else{
4755 memset(pPayload, 0, n);
4756 }
drh3b7511c2001-05-26 13:15:44 +00004757 nPayload -= n;
drhde647132004-05-07 17:57:49 +00004758 pPayload += n;
drh9b171272004-05-08 02:03:22 +00004759 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00004760 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00004761 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00004762 if( nSrc==0 ){
4763 nSrc = nData;
4764 pSrc = pData;
4765 }
drhdd793422001-06-28 01:54:48 +00004766 }
drh9b171272004-05-08 02:03:22 +00004767 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00004768 return SQLITE_OK;
4769}
4770
drh14acc042001-06-10 19:56:58 +00004771/*
4772** Remove the i-th cell from pPage. This routine effects pPage only.
4773** The cell content is not freed or deallocated. It is assumed that
4774** the cell content has been copied someplace else. This routine just
4775** removes the reference to the cell from pPage.
4776**
4777** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00004778*/
shane0af3f892008-11-12 04:55:34 +00004779static int dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00004780 int i; /* Loop counter */
4781 int pc; /* Offset to cell content of cell being deleted */
4782 u8 *data; /* pPage->aData */
4783 u8 *ptr; /* Used to move bytes around within data[] */
shanedcc50b72008-11-13 18:29:50 +00004784 int rc; /* The return code */
drh43605152004-05-29 21:46:49 +00004785
drh8c42ca92001-06-22 19:15:00 +00004786 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00004787 assert( sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00004788 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00004789 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00004790 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00004791 ptr = &data[pPage->cellOffset + 2*idx];
shane0af3f892008-11-12 04:55:34 +00004792 pc = get2byte(ptr);
drhc5053fb2008-11-27 02:22:10 +00004793 if( (pc<pPage->hdrOffset+6+(pPage->leaf?0:4))
4794 || (pc+sz>pPage->pBt->usableSize) ){
shane0af3f892008-11-12 04:55:34 +00004795 return SQLITE_CORRUPT_BKPT;
4796 }
shanedcc50b72008-11-13 18:29:50 +00004797 rc = freeSpace(pPage, pc, sz);
4798 if( rc!=SQLITE_OK ){
4799 return rc;
4800 }
drh43605152004-05-29 21:46:49 +00004801 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
4802 ptr[0] = ptr[2];
4803 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00004804 }
4805 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00004806 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
4807 pPage->nFree += 2;
shane0af3f892008-11-12 04:55:34 +00004808 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004809}
4810
4811/*
4812** Insert a new cell on pPage at cell index "i". pCell points to the
4813** content of the cell.
4814**
4815** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00004816** will not fit, then make a copy of the cell content into pTemp if
4817** pTemp is not null. Regardless of pTemp, allocate a new entry
4818** in pPage->aOvfl[] and make it point to the cell content (either
4819** in pTemp or the original pCell) and also record its index.
4820** Allocating a new entry in pPage->aCell[] implies that
4821** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00004822**
4823** If nSkip is non-zero, then do not copy the first nSkip bytes of the
4824** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00004825** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00004826** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00004827*/
danielk1977e80463b2004-11-03 03:01:16 +00004828static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00004829 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00004830 int i, /* New cell becomes the i-th cell of the page */
4831 u8 *pCell, /* Content of the new cell */
4832 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00004833 u8 *pTemp, /* Temp storage space for pCell, if needed */
4834 u8 nSkip /* Do not write the first nSkip bytes of the cell */
drh24cd67e2004-05-10 16:18:47 +00004835){
drh43605152004-05-29 21:46:49 +00004836 int idx; /* Where to write new cell content in data[] */
4837 int j; /* Loop counter */
4838 int top; /* First byte of content for any cell in data[] */
4839 int end; /* First byte past the last cell pointer in data[] */
4840 int ins; /* Index in data[] where new cell pointer is inserted */
4841 int hdr; /* Offset into data[] of the page header */
4842 int cellOffset; /* Address of first cell pointer in data[] */
4843 u8 *data; /* The content of the whole page */
4844 u8 *ptr; /* Used for moving information around in data[] */
4845
4846 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
drhf49661a2008-12-10 16:45:50 +00004847 assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
4848 assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
drh43605152004-05-29 21:46:49 +00004849 assert( sz==cellSizePtr(pPage, pCell) );
drh1fee73e2007-08-29 04:00:57 +00004850 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +00004851 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00004852 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00004853 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004854 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00004855 }
drh43605152004-05-29 21:46:49 +00004856 j = pPage->nOverflow++;
danielk197789d40042008-11-17 14:20:56 +00004857 assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
drh43605152004-05-29 21:46:49 +00004858 pPage->aOvfl[j].pCell = pCell;
drhf49661a2008-12-10 16:45:50 +00004859 pPage->aOvfl[j].idx = (u16)i;
drh43605152004-05-29 21:46:49 +00004860 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00004861 }else{
danielk19776e465eb2007-08-21 13:11:00 +00004862 int rc = sqlite3PagerWrite(pPage->pDbPage);
4863 if( rc!=SQLITE_OK ){
4864 return rc;
4865 }
4866 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00004867 data = pPage->aData;
4868 hdr = pPage->hdrOffset;
4869 top = get2byte(&data[hdr+5]);
4870 cellOffset = pPage->cellOffset;
4871 end = cellOffset + 2*pPage->nCell + 2;
4872 ins = cellOffset + 2*i;
4873 if( end > top - sz ){
shane0af3f892008-11-12 04:55:34 +00004874 rc = defragmentPage(pPage);
4875 if( rc!=SQLITE_OK ){
4876 return rc;
4877 }
drh43605152004-05-29 21:46:49 +00004878 top = get2byte(&data[hdr+5]);
4879 assert( end + sz <= top );
4880 }
4881 idx = allocateSpace(pPage, sz);
4882 assert( idx>0 );
4883 assert( end <= get2byte(&data[hdr+5]) );
shane0af3f892008-11-12 04:55:34 +00004884 if (idx+sz > pPage->pBt->usableSize) {
shane34ac18d2008-11-11 22:18:20 +00004885 return SQLITE_CORRUPT_BKPT;
shane0af3f892008-11-12 04:55:34 +00004886 }
drh43605152004-05-29 21:46:49 +00004887 pPage->nCell++;
4888 pPage->nFree -= 2;
danielk1977a3ad5e72005-01-07 08:56:44 +00004889 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004890 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
4891 ptr[0] = ptr[-2];
4892 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00004893 }
drh43605152004-05-29 21:46:49 +00004894 put2byte(&data[ins], idx);
4895 put2byte(&data[hdr+3], pPage->nCell);
danielk1977a19df672004-11-03 11:37:07 +00004896#ifndef SQLITE_OMIT_AUTOVACUUM
4897 if( pPage->pBt->autoVacuum ){
4898 /* The cell may contain a pointer to an overflow page. If so, write
4899 ** the entry for the overflow page into the pointer map.
4900 */
4901 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00004902 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh72365832007-03-06 15:53:44 +00004903 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk1977a19df672004-11-03 11:37:07 +00004904 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
4905 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
danielk19776e465eb2007-08-21 13:11:00 +00004906 rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
danielk1977a19df672004-11-03 11:37:07 +00004907 if( rc!=SQLITE_OK ) return rc;
4908 }
4909 }
4910#endif
drh14acc042001-06-10 19:56:58 +00004911 }
danielk1977e80463b2004-11-03 03:01:16 +00004912
danielk1977e80463b2004-11-03 03:01:16 +00004913 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004914}
4915
4916/*
drhfa1a98a2004-05-14 19:08:17 +00004917** Add a list of cells to a page. The page should be initially empty.
4918** The cells are guaranteed to fit on the page.
4919*/
4920static void assemblePage(
4921 MemPage *pPage, /* The page to be assemblied */
4922 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00004923 u8 **apCell, /* Pointers to cell bodies */
drha9121e42008-02-19 14:59:35 +00004924 u16 *aSize /* Sizes of the cells */
drhfa1a98a2004-05-14 19:08:17 +00004925){
4926 int i; /* Loop counter */
4927 int totalSize; /* Total size of all cells */
4928 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00004929 int cellptr; /* Address of next cell pointer */
4930 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00004931 u8 *data; /* Data for the page */
4932
drh43605152004-05-29 21:46:49 +00004933 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00004934 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00004935 assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
drhfa1a98a2004-05-14 19:08:17 +00004936 totalSize = 0;
4937 for(i=0; i<nCell; i++){
4938 totalSize += aSize[i];
4939 }
drh43605152004-05-29 21:46:49 +00004940 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00004941 assert( pPage->nCell==0 );
drhc5053fb2008-11-27 02:22:10 +00004942 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00004943 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00004944 data = pPage->aData;
4945 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00004946 put2byte(&data[hdr+3], nCell);
drh09d0deb2005-08-02 17:13:09 +00004947 if( nCell ){
4948 cellbody = allocateSpace(pPage, totalSize);
4949 assert( cellbody>0 );
4950 assert( pPage->nFree >= 2*nCell );
4951 pPage->nFree -= 2*nCell;
4952 for(i=0; i<nCell; i++){
4953 put2byte(&data[cellptr], cellbody);
4954 memcpy(&data[cellbody], apCell[i], aSize[i]);
4955 cellptr += 2;
4956 cellbody += aSize[i];
4957 }
4958 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00004959 }
drhf49661a2008-12-10 16:45:50 +00004960 pPage->nCell = (u16)nCell;
drhfa1a98a2004-05-14 19:08:17 +00004961}
4962
drh14acc042001-06-10 19:56:58 +00004963/*
drhc3b70572003-01-04 19:44:07 +00004964** The following parameters determine how many adjacent pages get involved
4965** in a balancing operation. NN is the number of neighbors on either side
4966** of the page that participate in the balancing operation. NB is the
4967** total number of pages that participate, including the target page and
4968** NN neighbors on either side.
4969**
4970** The minimum value of NN is 1 (of course). Increasing NN above 1
4971** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
4972** in exchange for a larger degradation in INSERT and UPDATE performance.
4973** The value of NN appears to give the best results overall.
4974*/
4975#define NN 1 /* Number of neighbors on either side of pPage */
4976#define NB (NN*2+1) /* Total pages involved in the balance */
4977
drh43605152004-05-29 21:46:49 +00004978/* Forward reference */
danielk197771d5d2c2008-09-29 11:49:47 +00004979static int balance(BtCursor*, int);
danielk1977ac245ec2005-01-14 13:50:11 +00004980
drh615ae552005-01-16 23:21:00 +00004981#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004982/*
4983** This version of balance() handles the common special case where
4984** a new entry is being inserted on the extreme right-end of the
4985** tree, in other words, when the new entry will become the largest
4986** entry in the tree.
4987**
4988** Instead of trying balance the 3 right-most leaf pages, just add
4989** a new page to the right-hand side and put the one new entry in
4990** that page. This leaves the right side of the tree somewhat
4991** unbalanced. But odds are that we will be inserting new entries
4992** at the end soon afterwards so the nearly empty page will quickly
4993** fill up. On average.
4994**
4995** pPage is the leaf page which is the right-most page in the tree.
4996** pParent is its parent. pPage must have a single overflow entry
4997** which is also the right-most entry on the page.
4998*/
danielk197771d5d2c2008-09-29 11:49:47 +00004999static int balance_quick(BtCursor *pCur){
danielk1977ac245ec2005-01-14 13:50:11 +00005000 int rc;
danielk1977eaa06f62008-09-18 17:34:44 +00005001 MemPage *pNew = 0;
danielk1977ac245ec2005-01-14 13:50:11 +00005002 Pgno pgnoNew;
5003 u8 *pCell;
drha9121e42008-02-19 14:59:35 +00005004 u16 szCell;
danielk1977ac245ec2005-01-14 13:50:11 +00005005 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00005006 MemPage *pPage = pCur->apPage[pCur->iPage];
5007 MemPage *pParent = pCur->apPage[pCur->iPage-1];
danielk1977aef0bf62005-12-30 16:28:01 +00005008 BtShared *pBt = pPage->pBt;
danielk197779a40da2005-01-16 08:00:01 +00005009 int parentIdx = pParent->nCell; /* pParent new divider cell index */
5010 int parentSize; /* Size of new divider cell */
5011 u8 parentCell[64]; /* Space for the new divider cell */
danielk1977ac245ec2005-01-14 13:50:11 +00005012
drh1fee73e2007-08-29 04:00:57 +00005013 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00005014
danielk1977ac245ec2005-01-14 13:50:11 +00005015 /* Allocate a new page. Insert the overflow cell from pPage
5016 ** into it. Then remove the overflow cell from pPage.
5017 */
drh4f0c5872007-03-26 22:05:01 +00005018 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk1977eaa06f62008-09-18 17:34:44 +00005019 if( rc==SQLITE_OK ){
5020 pCell = pPage->aOvfl[0].pCell;
5021 szCell = cellSizePtr(pPage, pCell);
drhc5053fb2008-11-27 02:22:10 +00005022 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
danielk1977eaa06f62008-09-18 17:34:44 +00005023 zeroPage(pNew, pPage->aData[0]);
5024 assemblePage(pNew, 1, &pCell, &szCell);
5025 pPage->nOverflow = 0;
5026
danielk1977eaa06f62008-09-18 17:34:44 +00005027 /* pPage is currently the right-child of pParent. Change this
5028 ** so that the right-child is the new page allocated above and
5029 ** pPage is the next-to-right child.
5030 **
5031 ** Ignore the return value of the call to fillInCell(). fillInCell()
5032 ** may only return other than SQLITE_OK if it is required to allocate
5033 ** one or more overflow pages. Since an internal table B-Tree cell
5034 ** may never spill over onto an overflow page (it is a maximum of
5035 ** 13 bytes in size), it is not neccessary to check the return code.
5036 **
5037 ** Similarly, the insertCell() function cannot fail if the page
5038 ** being inserted into is already writable and the cell does not
5039 ** contain an overflow pointer. So ignore this return code too.
5040 */
5041 assert( pPage->nCell>0 );
5042 pCell = findCell(pPage, pPage->nCell-1);
5043 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
5044 fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
5045 assert( parentSize<64 );
5046 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
5047 insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
5048 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
5049 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
5050
5051 /* If this is an auto-vacuum database, update the pointer map
5052 ** with entries for the new page, and any pointer from the
5053 ** cell on the page to an overflow page.
5054 */
5055 if( ISAUTOVACUUM ){
5056 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
5057 if( rc==SQLITE_OK ){
5058 rc = ptrmapPutOvfl(pNew, 0);
5059 }
danielk1977ac11ee62005-01-15 12:45:51 +00005060 }
danielk1977e08a3c42008-09-18 18:17:03 +00005061
5062 /* Release the reference to the new page. */
5063 releasePage(pNew);
danielk1977ac11ee62005-01-15 12:45:51 +00005064 }
5065
danielk1977eaa06f62008-09-18 17:34:44 +00005066 /* At this point the pPage->nFree variable is not set correctly with
5067 ** respect to the content of the page (because it was set to 0 by
5068 ** insertCell). So call sqlite3BtreeInitPage() to make sure it is
5069 ** correct.
5070 **
5071 ** This has to be done even if an error will be returned. Normally, if
5072 ** an error occurs during tree balancing, the contents of MemPage are
5073 ** not important, as they will be recalculated when the page is rolled
5074 ** back. But here, in balance_quick(), it is possible that pPage has
5075 ** not yet been marked dirty or written into the journal file. Therefore
5076 ** it will not be rolled back and so it is important to make sure that
5077 ** the page data and contents of MemPage are consistent.
5078 */
5079 pPage->isInit = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005080 sqlite3BtreeInitPage(pPage);
danielk1977a4124bd2008-12-23 10:37:47 +00005081 assert( pPage->nOverflow==0 );
danielk1977eaa06f62008-09-18 17:34:44 +00005082
danielk1977e08a3c42008-09-18 18:17:03 +00005083 /* If everything else succeeded, balance the parent page, in
5084 ** case the divider cell inserted caused it to become overfull.
danielk197779a40da2005-01-16 08:00:01 +00005085 */
danielk1977eaa06f62008-09-18 17:34:44 +00005086 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00005087 releasePage(pPage);
5088 pCur->iPage--;
5089 rc = balance(pCur, 0);
danielk1977eaa06f62008-09-18 17:34:44 +00005090 }
5091 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00005092}
drh615ae552005-01-16 23:21:00 +00005093#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00005094
drhc3b70572003-01-04 19:44:07 +00005095/*
drhab01f612004-05-22 02:55:23 +00005096** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00005097** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00005098** Usually NN siblings on either side of pPage is used in the balancing,
5099** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00005100** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00005101** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00005102** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00005103**
drh0c6cc4e2004-06-15 02:13:26 +00005104** The number of siblings of pPage might be increased or decreased by one or
5105** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00005106** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00005107** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00005108** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00005109** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00005110**
drh8b2f49b2001-06-08 00:21:52 +00005111** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00005112** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00005113** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00005114** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00005115**
drh8c42ca92001-06-22 19:15:00 +00005116** In the course of balancing the siblings of pPage, the parent of pPage
5117** might become overfull or underfull. If that happens, then this routine
5118** is called recursively on the parent.
5119**
drh5e00f6c2001-09-13 13:46:56 +00005120** If this routine fails for any reason, it might leave the database
5121** in a corrupted state. So if this routine fails, the database should
5122** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00005123*/
danielk197771d5d2c2008-09-29 11:49:47 +00005124static int balance_nonroot(BtCursor *pCur){
5125 MemPage *pPage; /* The over or underfull page to balance */
drh8b2f49b2001-06-08 00:21:52 +00005126 MemPage *pParent; /* The parent of pPage */
drh16a9b832007-05-05 18:39:25 +00005127 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00005128 int nCell = 0; /* Number of cells in apCell[] */
5129 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
danielk1977a4124bd2008-12-23 10:37:47 +00005130 int nOld = 0; /* Number of pages in apOld[] */
5131 int nNew = 0; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00005132 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00005133 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00005134 int idx; /* Index of pPage in pParent->aCell[] */
5135 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00005136 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00005137 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00005138 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00005139 int usableSpace; /* Bytes in pPage beyond the header */
5140 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00005141 int subtotal; /* Subtotal of bytes in cells on one page */
drhe5ae5732008-06-15 02:51:47 +00005142 int iSpace1 = 0; /* First unused byte of aSpace1[] */
5143 int iSpace2 = 0; /* First unused byte of aSpace2[] */
drhfacf0302008-06-17 15:12:00 +00005144 int szScratch; /* Size of scratch memory requested */
drhc3b70572003-01-04 19:44:07 +00005145 MemPage *apOld[NB]; /* pPage and up to two siblings */
5146 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00005147 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00005148 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
5149 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drh4b70f112004-05-02 21:12:19 +00005150 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00005151 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
5152 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00005153 u8 **apCell = 0; /* All cells begin balanced */
drha9121e42008-02-19 14:59:35 +00005154 u16 *szCell; /* Local size of all cells in apCell[] */
drhe5ae5732008-06-15 02:51:47 +00005155 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
5156 u8 *aSpace1; /* Space for copies of dividers cells before balance */
5157 u8 *aSpace2 = 0; /* Space for overflow dividers cells after balance */
danielk1977ac11ee62005-01-15 12:45:51 +00005158 u8 *aFrom = 0;
drh8b2f49b2001-06-08 00:21:52 +00005159
danielk197771d5d2c2008-09-29 11:49:47 +00005160 pPage = pCur->apPage[pCur->iPage];
drh1fee73e2007-08-29 04:00:57 +00005161 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf94a1732008-09-30 17:18:17 +00005162 VVA_ONLY( pCur->pagesShuffled = 1 );
drhd677b3d2007-08-20 22:48:41 +00005163
drh14acc042001-06-10 19:56:58 +00005164 /*
drh43605152004-05-29 21:46:49 +00005165 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00005166 */
danielk197771d5d2c2008-09-29 11:49:47 +00005167 assert( pCur->iPage>0 );
5168 assert( pPage->isInit );
danielk19776e465eb2007-08-21 13:11:00 +00005169 assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 );
drh4b70f112004-05-02 21:12:19 +00005170 pBt = pPage->pBt;
danielk197771d5d2c2008-09-29 11:49:47 +00005171 pParent = pCur->apPage[pCur->iPage-1];
drh43605152004-05-29 21:46:49 +00005172 assert( pParent );
danielk19773b8a05f2007-03-19 17:44:26 +00005173 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
danielk1977a4124bd2008-12-23 10:37:47 +00005174 goto balance_cleanup;
danielk197707cb5602006-01-20 10:55:05 +00005175 }
danielk1977474b7cc2008-07-09 11:49:46 +00005176
drh43605152004-05-29 21:46:49 +00005177 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00005178
drh615ae552005-01-16 23:21:00 +00005179#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00005180 /*
5181 ** A special case: If a new entry has just been inserted into a
5182 ** table (that is, a btree with integer keys and all data at the leaves)
drh09d0deb2005-08-02 17:13:09 +00005183 ** and the new entry is the right-most entry in the tree (it has the
drhf222e712005-01-14 22:55:49 +00005184 ** largest key) then use the special balance_quick() routine for
5185 ** balancing. balance_quick() is much faster and results in a tighter
5186 ** packing of data in the common case.
5187 */
danielk1977ac245ec2005-01-14 13:50:11 +00005188 if( pPage->leaf &&
5189 pPage->intKey &&
danielk1977ac245ec2005-01-14 13:50:11 +00005190 pPage->nOverflow==1 &&
5191 pPage->aOvfl[0].idx==pPage->nCell &&
danielk197771d5d2c2008-09-29 11:49:47 +00005192 pParent->pgno!=1 &&
danielk1977ac245ec2005-01-14 13:50:11 +00005193 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
5194 ){
drh44845222008-07-17 18:39:57 +00005195 assert( pPage->intKey );
danielk1977ac11ee62005-01-15 12:45:51 +00005196 /*
5197 ** TODO: Check the siblings to the left of pPage. It may be that
5198 ** they are not full and no new page is required.
5199 */
danielk197771d5d2c2008-09-29 11:49:47 +00005200 return balance_quick(pCur);
danielk1977ac245ec2005-01-14 13:50:11 +00005201 }
5202#endif
5203
danielk19776e465eb2007-08-21 13:11:00 +00005204 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){
danielk1977a4124bd2008-12-23 10:37:47 +00005205 goto balance_cleanup;
danielk19776e465eb2007-08-21 13:11:00 +00005206 }
5207
drh2e38c322004-09-03 18:38:44 +00005208 /*
drh4b70f112004-05-02 21:12:19 +00005209 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00005210 ** to pPage. The "idx" variable is the index of that cell. If pPage
5211 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00005212 */
danielk1977bf93c562008-09-29 15:53:25 +00005213 idx = pCur->aiIdx[pCur->iPage-1];
5214 assertParentIndex(pParent, idx, pPage->pgno);
drh8b2f49b2001-06-08 00:21:52 +00005215
5216 /*
drh4b70f112004-05-02 21:12:19 +00005217 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00005218 ** the siblings. An attempt is made to find NN siblings on either
5219 ** side of pPage. More siblings are taken from one side, however, if
5220 ** pPage there are fewer than NN siblings on the other side. If pParent
5221 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00005222 */
drhc3b70572003-01-04 19:44:07 +00005223 nxDiv = idx - NN;
5224 if( nxDiv + NB > pParent->nCell ){
5225 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00005226 }
drhc3b70572003-01-04 19:44:07 +00005227 if( nxDiv<0 ){
5228 nxDiv = 0;
5229 }
drh8b2f49b2001-06-08 00:21:52 +00005230 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00005231 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00005232 if( k<pParent->nCell ){
danielk19771cc5ed82007-05-16 17:28:43 +00005233 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00005234 nDiv++;
drha34b6762004-05-07 13:30:42 +00005235 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00005236 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00005237 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00005238 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00005239 }else{
5240 break;
drh8b2f49b2001-06-08 00:21:52 +00005241 }
danielk197771d5d2c2008-09-29 11:49:47 +00005242 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i]);
drh6019e162001-07-02 17:51:45 +00005243 if( rc ) goto balance_cleanup;
danielk197771d5d2c2008-09-29 11:49:47 +00005244 /* apOld[i]->idxParent = k; */
drh91025292004-05-03 19:49:32 +00005245 apCopy[i] = 0;
5246 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00005247 nOld++;
danielk1977634f2982005-03-28 08:44:07 +00005248 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
drh8b2f49b2001-06-08 00:21:52 +00005249 }
5250
drha9121e42008-02-19 14:59:35 +00005251 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00005252 ** alignment */
drha9121e42008-02-19 14:59:35 +00005253 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00005254
drh8b2f49b2001-06-08 00:21:52 +00005255 /*
danielk1977634f2982005-03-28 08:44:07 +00005256 ** Allocate space for memory structures
5257 */
drhfacf0302008-06-17 15:12:00 +00005258 szScratch =
drha9121e42008-02-19 14:59:35 +00005259 nMaxCells*sizeof(u8*) /* apCell */
5260 + nMaxCells*sizeof(u16) /* szCell */
5261 + (ROUND8(sizeof(MemPage))+pBt->pageSize)*NB /* aCopy */
drhe5ae5732008-06-15 02:51:47 +00005262 + pBt->pageSize /* aSpace1 */
drhfacf0302008-06-17 15:12:00 +00005263 + (ISAUTOVACUUM ? nMaxCells : 0); /* aFrom */
5264 apCell = sqlite3ScratchMalloc( szScratch );
danielk1977634f2982005-03-28 08:44:07 +00005265 if( apCell==0 ){
5266 rc = SQLITE_NOMEM;
5267 goto balance_cleanup;
5268 }
drha9121e42008-02-19 14:59:35 +00005269 szCell = (u16*)&apCell[nMaxCells];
danielk1977634f2982005-03-28 08:44:07 +00005270 aCopy[0] = (u8*)&szCell[nMaxCells];
drh66e80082008-12-16 13:46:29 +00005271 assert( ((aCopy[0] - (u8*)0) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00005272 for(i=1; i<NB; i++){
drhc96d8532005-05-03 12:30:33 +00005273 aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
drh66e80082008-12-16 13:46:29 +00005274 assert( ((aCopy[i] - (u8*)0) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00005275 }
drhe5ae5732008-06-15 02:51:47 +00005276 aSpace1 = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
drh66e80082008-12-16 13:46:29 +00005277 assert( ((aSpace1 - (u8*)0) & 7)==0 ); /* 8-byte alignment required */
danielk197785d90ca2008-07-19 14:25:15 +00005278 if( ISAUTOVACUUM ){
drhe5ae5732008-06-15 02:51:47 +00005279 aFrom = &aSpace1[pBt->pageSize];
danielk1977634f2982005-03-28 08:44:07 +00005280 }
drhfacf0302008-06-17 15:12:00 +00005281 aSpace2 = sqlite3PageMalloc(pBt->pageSize);
drhe5ae5732008-06-15 02:51:47 +00005282 if( aSpace2==0 ){
5283 rc = SQLITE_NOMEM;
5284 goto balance_cleanup;
5285 }
danielk1977634f2982005-03-28 08:44:07 +00005286
5287 /*
drh14acc042001-06-10 19:56:58 +00005288 ** Make copies of the content of pPage and its siblings into aOld[].
5289 ** The rest of this function will use data from the copies rather
5290 ** that the original pages since the original pages will be in the
5291 ** process of being overwritten.
5292 */
5293 for(i=0; i<nOld; i++){
drhbf4bca52007-09-06 22:19:14 +00005294 MemPage *p = apCopy[i] = (MemPage*)aCopy[i];
5295 memcpy(p, apOld[i], sizeof(MemPage));
5296 p->aData = (void*)&p[1];
5297 memcpy(p->aData, apOld[i]->aData, pBt->pageSize);
drh14acc042001-06-10 19:56:58 +00005298 }
5299
5300 /*
5301 ** Load pointers to all cells on sibling pages and the divider cells
5302 ** into the local apCell[] array. Make copies of the divider cells
drhe5ae5732008-06-15 02:51:47 +00005303 ** into space obtained form aSpace1[] and remove the the divider Cells
drhb6f41482004-05-14 01:58:11 +00005304 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00005305 **
5306 ** If the siblings are on leaf pages, then the child pointers of the
5307 ** divider cells are stripped from the cells before they are copied
drhe5ae5732008-06-15 02:51:47 +00005308 ** into aSpace1[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00005309 ** child pointers. If siblings are not leaves, then all cell in
5310 ** apCell[] include child pointers. Either way, all cells in apCell[]
5311 ** are alike.
drh96f5b762004-05-16 16:24:36 +00005312 **
5313 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
5314 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00005315 */
5316 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00005317 leafCorrection = pPage->leaf*4;
drh44845222008-07-17 18:39:57 +00005318 leafData = pPage->hasData;
drh8b2f49b2001-06-08 00:21:52 +00005319 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00005320 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00005321 int limit = pOld->nCell+pOld->nOverflow;
5322 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00005323 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00005324 apCell[nCell] = findOverflowCell(pOld, j);
5325 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk197785d90ca2008-07-19 14:25:15 +00005326 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005327 int a;
drhf49661a2008-12-10 16:45:50 +00005328 aFrom[nCell] = (u8)i; assert( i>=0 && i<6 );
danielk1977ac11ee62005-01-15 12:45:51 +00005329 for(a=0; a<pOld->nOverflow; a++){
5330 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
5331 aFrom[nCell] = 0xFF;
5332 break;
5333 }
5334 }
5335 }
drh14acc042001-06-10 19:56:58 +00005336 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00005337 }
5338 if( i<nOld-1 ){
drha9121e42008-02-19 14:59:35 +00005339 u16 sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00005340 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00005341 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
5342 ** are duplicates of keys on the child pages. We need to remove
5343 ** the divider cells from pParent, but the dividers cells are not
5344 ** added to apCell[] because they are duplicates of child cells.
5345 */
drh8b18dd42004-05-12 19:18:15 +00005346 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00005347 }else{
drhb6f41482004-05-14 01:58:11 +00005348 u8 *pTemp;
danielk1977634f2982005-03-28 08:44:07 +00005349 assert( nCell<nMaxCells );
drhb6f41482004-05-14 01:58:11 +00005350 szCell[nCell] = sz;
drhe5ae5732008-06-15 02:51:47 +00005351 pTemp = &aSpace1[iSpace1];
5352 iSpace1 += sz;
5353 assert( sz<=pBt->pageSize/4 );
5354 assert( iSpace1<=pBt->pageSize );
drhb6f41482004-05-14 01:58:11 +00005355 memcpy(pTemp, apDiv[i], sz);
5356 apCell[nCell] = pTemp+leafCorrection;
danielk197785d90ca2008-07-19 14:25:15 +00005357 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005358 aFrom[nCell] = 0xFF;
5359 }
drhb6f41482004-05-14 01:58:11 +00005360 dropCell(pParent, nxDiv, sz);
drhf49661a2008-12-10 16:45:50 +00005361 assert( leafCorrection==0 || leafCorrection==4 );
5362 szCell[nCell] -= (u16)leafCorrection;
drh43605152004-05-29 21:46:49 +00005363 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00005364 if( !pOld->leaf ){
5365 assert( leafCorrection==0 );
5366 /* The right pointer of the child page pOld becomes the left
5367 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00005368 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00005369 }else{
5370 assert( leafCorrection==4 );
danielk197739c96042007-05-12 10:41:47 +00005371 if( szCell[nCell]<4 ){
5372 /* Do not allow any cells smaller than 4 bytes. */
5373 szCell[nCell] = 4;
5374 }
drh8b18dd42004-05-12 19:18:15 +00005375 }
5376 nCell++;
drh4b70f112004-05-02 21:12:19 +00005377 }
drh8b2f49b2001-06-08 00:21:52 +00005378 }
5379 }
5380
5381 /*
drh6019e162001-07-02 17:51:45 +00005382 ** Figure out the number of pages needed to hold all nCell cells.
5383 ** Store this number in "k". Also compute szNew[] which is the total
5384 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00005385 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00005386 ** cntNew[k] should equal nCell.
5387 **
drh96f5b762004-05-16 16:24:36 +00005388 ** Values computed by this block:
5389 **
5390 ** k: The total number of sibling pages
5391 ** szNew[i]: Spaced used on the i-th sibling page.
5392 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
5393 ** the right of the i-th sibling page.
5394 ** usableSpace: Number of bytes of space available on each sibling.
5395 **
drh8b2f49b2001-06-08 00:21:52 +00005396 */
drh43605152004-05-29 21:46:49 +00005397 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00005398 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00005399 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00005400 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00005401 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00005402 szNew[k] = subtotal - szCell[i];
5403 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00005404 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00005405 subtotal = 0;
5406 k++;
5407 }
5408 }
5409 szNew[k] = subtotal;
5410 cntNew[k] = nCell;
5411 k++;
drh96f5b762004-05-16 16:24:36 +00005412
5413 /*
5414 ** The packing computed by the previous block is biased toward the siblings
5415 ** on the left side. The left siblings are always nearly full, while the
5416 ** right-most sibling might be nearly empty. This block of code attempts
5417 ** to adjust the packing of siblings to get a better balance.
5418 **
5419 ** This adjustment is more than an optimization. The packing above might
5420 ** be so out of balance as to be illegal. For example, the right-most
5421 ** sibling might be completely empty. This adjustment is not optional.
5422 */
drh6019e162001-07-02 17:51:45 +00005423 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00005424 int szRight = szNew[i]; /* Size of sibling on the right */
5425 int szLeft = szNew[i-1]; /* Size of sibling on the left */
5426 int r; /* Index of right-most cell in left sibling */
5427 int d; /* Index of first cell to the left of right sibling */
5428
5429 r = cntNew[i-1] - 1;
5430 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00005431 assert( d<nMaxCells );
5432 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00005433 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
5434 szRight += szCell[d] + 2;
5435 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00005436 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00005437 r = cntNew[i-1] - 1;
5438 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00005439 }
drh96f5b762004-05-16 16:24:36 +00005440 szNew[i] = szRight;
5441 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00005442 }
drh09d0deb2005-08-02 17:13:09 +00005443
5444 /* Either we found one or more cells (cntnew[0])>0) or we are the
5445 ** a virtual root page. A virtual root page is when the real root
5446 ** page is page 1 and we are the only child of that page.
5447 */
5448 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00005449
5450 /*
drh6b308672002-07-08 02:16:37 +00005451 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00005452 */
drh4b70f112004-05-02 21:12:19 +00005453 assert( pPage->pgno>1 );
5454 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00005455 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00005456 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00005457 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00005458 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00005459 pgnoNew[i] = pgnoOld[i];
5460 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00005461 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00005462 nNew++;
danielk197728129562005-01-11 10:25:06 +00005463 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00005464 }else{
drh7aa8f852006-03-28 00:24:44 +00005465 assert( i>0 );
drh4f0c5872007-03-26 22:05:01 +00005466 rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
drh6b308672002-07-08 02:16:37 +00005467 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00005468 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00005469 nNew++;
drh6b308672002-07-08 02:16:37 +00005470 }
drh8b2f49b2001-06-08 00:21:52 +00005471 }
5472
danielk1977299b1872004-11-22 10:02:10 +00005473 /* Free any old pages that were not reused as new pages.
5474 */
5475 while( i<nOld ){
5476 rc = freePage(apOld[i]);
5477 if( rc ) goto balance_cleanup;
5478 releasePage(apOld[i]);
5479 apOld[i] = 0;
5480 i++;
5481 }
5482
drh8b2f49b2001-06-08 00:21:52 +00005483 /*
drhf9ffac92002-03-02 19:00:31 +00005484 ** Put the new pages in accending order. This helps to
5485 ** keep entries in the disk file in order so that a scan
5486 ** of the table is a linear scan through the file. That
5487 ** in turn helps the operating system to deliver pages
5488 ** from the disk more rapidly.
5489 **
5490 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00005491 ** n is never more than NB (a small constant), that should
5492 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00005493 **
drhc3b70572003-01-04 19:44:07 +00005494 ** When NB==3, this one optimization makes the database
5495 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00005496 */
5497 for(i=0; i<k-1; i++){
5498 int minV = pgnoNew[i];
5499 int minI = i;
5500 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00005501 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00005502 minI = j;
5503 minV = pgnoNew[j];
5504 }
5505 }
5506 if( minI>i ){
5507 int t;
5508 MemPage *pT;
5509 t = pgnoNew[i];
5510 pT = apNew[i];
5511 pgnoNew[i] = pgnoNew[minI];
5512 apNew[i] = apNew[minI];
5513 pgnoNew[minI] = t;
5514 apNew[minI] = pT;
5515 }
5516 }
drha2fce642004-06-05 00:01:44 +00005517 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00005518 pgnoOld[0],
5519 nOld>=2 ? pgnoOld[1] : 0,
5520 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00005521 pgnoNew[0], szNew[0],
5522 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
5523 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00005524 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
5525 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00005526
drhf9ffac92002-03-02 19:00:31 +00005527 /*
drh14acc042001-06-10 19:56:58 +00005528 ** Evenly distribute the data in apCell[] across the new pages.
5529 ** Insert divider cells into pParent as necessary.
5530 */
5531 j = 0;
5532 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00005533 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00005534 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00005535 assert( j<nMaxCells );
drh4b70f112004-05-02 21:12:19 +00005536 assert( pNew->pgno==pgnoNew[i] );
drh10131482008-07-11 03:34:09 +00005537 zeroPage(pNew, pageFlags);
drhfa1a98a2004-05-14 19:08:17 +00005538 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00005539 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00005540 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00005541
danielk1977ac11ee62005-01-15 12:45:51 +00005542 /* If this is an auto-vacuum database, update the pointer map entries
5543 ** that point to the siblings that were rearranged. These can be: left
5544 ** children of cells, the right-child of the page, or overflow pages
5545 ** pointed to by cells.
5546 */
danielk197785d90ca2008-07-19 14:25:15 +00005547 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005548 for(k=j; k<cntNew[i]; k++){
danielk1977634f2982005-03-28 08:44:07 +00005549 assert( k<nMaxCells );
danielk1977ac11ee62005-01-15 12:45:51 +00005550 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
danielk197779a40da2005-01-16 08:00:01 +00005551 rc = ptrmapPutOvfl(pNew, k-j);
danielk197787c52b52008-07-19 11:49:07 +00005552 if( rc==SQLITE_OK && leafCorrection==0 ){
5553 rc = ptrmapPut(pBt, get4byte(apCell[k]), PTRMAP_BTREE, pNew->pgno);
5554 }
danielk197779a40da2005-01-16 08:00:01 +00005555 if( rc!=SQLITE_OK ){
5556 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00005557 }
5558 }
5559 }
5560 }
danielk1977ac11ee62005-01-15 12:45:51 +00005561
5562 j = cntNew[i];
5563
5564 /* If the sibling page assembled above was not the right-most sibling,
5565 ** insert a divider cell into the parent page.
5566 */
drh14acc042001-06-10 19:56:58 +00005567 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00005568 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00005569 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00005570 int sz;
danielk1977634f2982005-03-28 08:44:07 +00005571
5572 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00005573 pCell = apCell[j];
5574 sz = szCell[j] + leafCorrection;
drhe5ae5732008-06-15 02:51:47 +00005575 pTemp = &aSpace2[iSpace2];
drh4b70f112004-05-02 21:12:19 +00005576 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00005577 memcpy(&pNew->aData[8], pCell, 4);
danielk197785d90ca2008-07-19 14:25:15 +00005578 if( ISAUTOVACUUM
danielk197787c52b52008-07-19 11:49:07 +00005579 && (aFrom[j]==0xFF || apCopy[aFrom[j]]->pgno!=pNew->pgno)
5580 ){
5581 rc = ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno);
5582 if( rc!=SQLITE_OK ){
5583 goto balance_cleanup;
5584 }
5585 }
drh8b18dd42004-05-12 19:18:15 +00005586 }else if( leafData ){
drhfd131da2007-08-07 17:13:03 +00005587 /* If the tree is a leaf-data tree, and the siblings are leaves,
danielk1977ac11ee62005-01-15 12:45:51 +00005588 ** then there is no divider cell in apCell[]. Instead, the divider
5589 ** cell consists of the integer key for the right-most cell of
5590 ** the sibling-page assembled above only.
5591 */
drh6f11bef2004-05-13 01:12:56 +00005592 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00005593 j--;
drh16a9b832007-05-05 18:39:25 +00005594 sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
drhe5ae5732008-06-15 02:51:47 +00005595 pCell = pTemp;
drh20abac22009-01-28 20:21:17 +00005596 rc = fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
5597 if( rc!=SQLITE_OK ){
5598 goto balance_cleanup;
5599 }
drh8b18dd42004-05-12 19:18:15 +00005600 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00005601 }else{
5602 pCell -= 4;
danielk19774aeff622007-05-12 09:30:47 +00005603 /* Obscure case for non-leaf-data trees: If the cell at pCell was
drh85b623f2007-12-13 21:54:09 +00005604 ** previously stored on a leaf node, and its reported size was 4
danielk19774aeff622007-05-12 09:30:47 +00005605 ** bytes, then it may actually be smaller than this
5606 ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
drh85b623f2007-12-13 21:54:09 +00005607 ** any cell). But it is important to pass the correct size to
danielk19774aeff622007-05-12 09:30:47 +00005608 ** insertCell(), so reparse the cell now.
5609 **
5610 ** Note that this can never happen in an SQLite data file, as all
5611 ** cells are at least 4 bytes. It only happens in b-trees used
5612 ** to evaluate "IN (SELECT ...)" and similar clauses.
5613 */
5614 if( szCell[j]==4 ){
5615 assert(leafCorrection==4);
5616 sz = cellSizePtr(pParent, pCell);
5617 }
drh4b70f112004-05-02 21:12:19 +00005618 }
drhe5ae5732008-06-15 02:51:47 +00005619 iSpace2 += sz;
5620 assert( sz<=pBt->pageSize/4 );
5621 assert( iSpace2<=pBt->pageSize );
danielk1977a3ad5e72005-01-07 08:56:44 +00005622 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
danielk1977e80463b2004-11-03 03:01:16 +00005623 if( rc!=SQLITE_OK ) goto balance_cleanup;
drhc5053fb2008-11-27 02:22:10 +00005624 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
drh43605152004-05-29 21:46:49 +00005625 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
danielk197785d90ca2008-07-19 14:25:15 +00005626
danielk1977ac11ee62005-01-15 12:45:51 +00005627 /* If this is an auto-vacuum database, and not a leaf-data tree,
5628 ** then update the pointer map with an entry for the overflow page
5629 ** that the cell just inserted points to (if any).
5630 */
danielk197785d90ca2008-07-19 14:25:15 +00005631 if( ISAUTOVACUUM && !leafData ){
danielk197779a40da2005-01-16 08:00:01 +00005632 rc = ptrmapPutOvfl(pParent, nxDiv);
5633 if( rc!=SQLITE_OK ){
5634 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00005635 }
5636 }
drh14acc042001-06-10 19:56:58 +00005637 j++;
5638 nxDiv++;
5639 }
danielk197787c52b52008-07-19 11:49:07 +00005640
danielk197787c52b52008-07-19 11:49:07 +00005641 /* Set the pointer-map entry for the new sibling page. */
danielk197785d90ca2008-07-19 14:25:15 +00005642 if( ISAUTOVACUUM ){
danielk197787c52b52008-07-19 11:49:07 +00005643 rc = ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno);
5644 if( rc!=SQLITE_OK ){
5645 goto balance_cleanup;
5646 }
5647 }
drh14acc042001-06-10 19:56:58 +00005648 }
drh6019e162001-07-02 17:51:45 +00005649 assert( j==nCell );
drh7aa8f852006-03-28 00:24:44 +00005650 assert( nOld>0 );
5651 assert( nNew>0 );
drh4b70f112004-05-02 21:12:19 +00005652 if( (pageFlags & PTF_LEAF)==0 ){
danielk197787c52b52008-07-19 11:49:07 +00005653 u8 *zChild = &apCopy[nOld-1]->aData[8];
5654 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
danielk197785d90ca2008-07-19 14:25:15 +00005655 if( ISAUTOVACUUM ){
danielk197787c52b52008-07-19 11:49:07 +00005656 rc = ptrmapPut(pBt, get4byte(zChild), PTRMAP_BTREE, apNew[nNew-1]->pgno);
5657 if( rc!=SQLITE_OK ){
5658 goto balance_cleanup;
5659 }
5660 }
drh14acc042001-06-10 19:56:58 +00005661 }
drhc5053fb2008-11-27 02:22:10 +00005662 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
drh43605152004-05-29 21:46:49 +00005663 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00005664 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00005665 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00005666 }else{
5667 /* Right-most sibling is the left child of the first entry in pParent
5668 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00005669 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00005670 }
5671
5672 /*
drh3a4c1412004-05-09 20:40:11 +00005673 ** Balance the parent page. Note that the current page (pPage) might
danielk1977ac11ee62005-01-15 12:45:51 +00005674 ** have been added to the freelist so it might no longer be initialized.
drh3a4c1412004-05-09 20:40:11 +00005675 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00005676 */
danielk197771d5d2c2008-09-29 11:49:47 +00005677 assert( pParent->isInit );
drhfacf0302008-06-17 15:12:00 +00005678 sqlite3ScratchFree(apCell);
drhe5ae5732008-06-15 02:51:47 +00005679 apCell = 0;
danielk1977a4124bd2008-12-23 10:37:47 +00005680 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
5681 pPage->pgno, nOld, nNew, nCell));
5682 pPage->nOverflow = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005683 releasePage(pPage);
5684 pCur->iPage--;
5685 rc = balance(pCur, 0);
drhda200cc2004-05-09 11:51:38 +00005686
drh8b2f49b2001-06-08 00:21:52 +00005687 /*
drh14acc042001-06-10 19:56:58 +00005688 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00005689 */
drh14acc042001-06-10 19:56:58 +00005690balance_cleanup:
drhfacf0302008-06-17 15:12:00 +00005691 sqlite3PageFree(aSpace2);
5692 sqlite3ScratchFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00005693 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00005694 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00005695 }
drh14acc042001-06-10 19:56:58 +00005696 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00005697 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00005698 }
danielk1977a4124bd2008-12-23 10:37:47 +00005699 pCur->apPage[pCur->iPage]->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00005700
drh8b2f49b2001-06-08 00:21:52 +00005701 return rc;
5702}
5703
5704/*
drh43605152004-05-29 21:46:49 +00005705** This routine is called for the root page of a btree when the root
5706** page contains no cells. This is an opportunity to make the tree
5707** shallower by one level.
5708*/
danielk197771d5d2c2008-09-29 11:49:47 +00005709static int balance_shallower(BtCursor *pCur){
5710 MemPage *pPage; /* Root page of B-Tree */
drh43605152004-05-29 21:46:49 +00005711 MemPage *pChild; /* The only child page of pPage */
5712 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00005713 int rc = SQLITE_OK; /* Return code from subprocedures */
danielk1977aef0bf62005-12-30 16:28:01 +00005714 BtShared *pBt; /* The main BTree structure */
drh2e38c322004-09-03 18:38:44 +00005715 int mxCellPerPage; /* Maximum number of cells per page */
5716 u8 **apCell; /* All cells from pages being balanced */
drha9121e42008-02-19 14:59:35 +00005717 u16 *szCell; /* Local size of all cells */
drh43605152004-05-29 21:46:49 +00005718
danielk197771d5d2c2008-09-29 11:49:47 +00005719 assert( pCur->iPage==0 );
5720 pPage = pCur->apPage[0];
5721
drh43605152004-05-29 21:46:49 +00005722 assert( pPage->nCell==0 );
drh1fee73e2007-08-29 04:00:57 +00005723 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh2e38c322004-09-03 18:38:44 +00005724 pBt = pPage->pBt;
5725 mxCellPerPage = MX_CELL(pBt);
drhe5ae5732008-06-15 02:51:47 +00005726 apCell = sqlite3Malloc( mxCellPerPage*(sizeof(u8*)+sizeof(u16)) );
drh2e38c322004-09-03 18:38:44 +00005727 if( apCell==0 ) return SQLITE_NOMEM;
drha9121e42008-02-19 14:59:35 +00005728 szCell = (u16*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00005729 if( pPage->leaf ){
5730 /* The table is completely empty */
5731 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
5732 }else{
5733 /* The root page is empty but has one child. Transfer the
5734 ** information from that one child into the root page if it
5735 ** will fit. This reduces the depth of the tree by one.
5736 **
5737 ** If the root page is page 1, it has less space available than
5738 ** its child (due to the 100 byte header that occurs at the beginning
5739 ** of the database fle), so it might not be able to hold all of the
5740 ** information currently contained in the child. If this is the
5741 ** case, then do not do the transfer. Leave page 1 empty except
5742 ** for the right-pointer to the child page. The child page becomes
5743 ** the virtual root of the tree.
5744 */
drhf94a1732008-09-30 17:18:17 +00005745 VVA_ONLY( pCur->pagesShuffled = 1 );
drh43605152004-05-29 21:46:49 +00005746 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5747 assert( pgnoChild>0 );
danielk197789d40042008-11-17 14:20:56 +00005748 assert( pgnoChild<=pagerPagecount(pPage->pBt) );
drh16a9b832007-05-05 18:39:25 +00005749 rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
drh2e38c322004-09-03 18:38:44 +00005750 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005751 if( pPage->pgno==1 ){
danielk197771d5d2c2008-09-29 11:49:47 +00005752 rc = sqlite3BtreeInitPage(pChild);
drh2e38c322004-09-03 18:38:44 +00005753 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005754 assert( pChild->nOverflow==0 );
5755 if( pChild->nFree>=100 ){
5756 /* The child information will fit on the root page, so do the
5757 ** copy */
5758 int i;
5759 zeroPage(pPage, pChild->aData[0]);
5760 for(i=0; i<pChild->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00005761 apCell[i] = findCell(pChild,i);
drh43605152004-05-29 21:46:49 +00005762 szCell[i] = cellSizePtr(pChild, apCell[i]);
5763 }
5764 assemblePage(pPage, pChild->nCell, apCell, szCell);
danielk1977ae825582004-11-23 09:06:55 +00005765 /* Copy the right-pointer of the child to the parent. */
drhc5053fb2008-11-27 02:22:10 +00005766 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977ae825582004-11-23 09:06:55 +00005767 put4byte(&pPage->aData[pPage->hdrOffset+8],
5768 get4byte(&pChild->aData[pChild->hdrOffset+8]));
drh9bf9e9c2008-12-05 20:01:43 +00005769 rc = freePage(pChild);
drh43605152004-05-29 21:46:49 +00005770 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
5771 }else{
5772 /* The child has more information that will fit on the root.
5773 ** The tree is already balanced. Do nothing. */
5774 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
5775 }
5776 }else{
5777 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
5778 pPage->isInit = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005779 rc = sqlite3BtreeInitPage(pPage);
drh43605152004-05-29 21:46:49 +00005780 assert( rc==SQLITE_OK );
5781 freePage(pChild);
5782 TRACE(("BALANCE: transfer child %d into root %d\n",
5783 pChild->pgno, pPage->pgno));
5784 }
danielk1977ac11ee62005-01-15 12:45:51 +00005785 assert( pPage->nOverflow==0 );
shane831c3292008-11-10 17:14:58 +00005786#ifndef SQLITE_OMIT_AUTOVACUUM
drh9bf9e9c2008-12-05 20:01:43 +00005787 if( ISAUTOVACUUM && rc==SQLITE_OK ){
danielk197700a696d2008-09-29 16:41:31 +00005788 rc = setChildPtrmaps(pPage);
danielk1977ac11ee62005-01-15 12:45:51 +00005789 }
shane831c3292008-11-10 17:14:58 +00005790#endif
drh43605152004-05-29 21:46:49 +00005791 releasePage(pChild);
5792 }
drh2e38c322004-09-03 18:38:44 +00005793end_shallow_balance:
drh17435752007-08-16 04:30:38 +00005794 sqlite3_free(apCell);
drh2e38c322004-09-03 18:38:44 +00005795 return rc;
drh43605152004-05-29 21:46:49 +00005796}
5797
5798
5799/*
5800** The root page is overfull
5801**
5802** When this happens, Create a new child page and copy the
5803** contents of the root into the child. Then make the root
5804** page an empty page with rightChild pointing to the new
5805** child. Finally, call balance_internal() on the new child
5806** to cause it to split.
5807*/
danielk197771d5d2c2008-09-29 11:49:47 +00005808static int balance_deeper(BtCursor *pCur){
drh43605152004-05-29 21:46:49 +00005809 int rc; /* Return value from subprocedures */
danielk197771d5d2c2008-09-29 11:49:47 +00005810 MemPage *pPage; /* Pointer to the root page */
drh43605152004-05-29 21:46:49 +00005811 MemPage *pChild; /* Pointer to a new child page */
5812 Pgno pgnoChild; /* Page number of the new child page */
danielk1977aef0bf62005-12-30 16:28:01 +00005813 BtShared *pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00005814 int usableSize; /* Total usable size of a page */
5815 u8 *data; /* Content of the parent page */
5816 u8 *cdata; /* Content of the child page */
5817 int hdr; /* Offset to page header in parent */
drh281b21d2008-08-22 12:57:08 +00005818 int cbrk; /* Offset to content of first cell in parent */
drh43605152004-05-29 21:46:49 +00005819
danielk197771d5d2c2008-09-29 11:49:47 +00005820 assert( pCur->iPage==0 );
5821 assert( pCur->apPage[0]->nOverflow>0 );
5822
drhf94a1732008-09-30 17:18:17 +00005823 VVA_ONLY( pCur->pagesShuffled = 1 );
danielk197771d5d2c2008-09-29 11:49:47 +00005824 pPage = pCur->apPage[0];
drh43605152004-05-29 21:46:49 +00005825 pBt = pPage->pBt;
drh1fee73e2007-08-29 04:00:57 +00005826 assert( sqlite3_mutex_held(pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00005827 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh4f0c5872007-03-26 22:05:01 +00005828 rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
drh43605152004-05-29 21:46:49 +00005829 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00005830 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
drh43605152004-05-29 21:46:49 +00005831 usableSize = pBt->usableSize;
5832 data = pPage->aData;
5833 hdr = pPage->hdrOffset;
drh281b21d2008-08-22 12:57:08 +00005834 cbrk = get2byte(&data[hdr+5]);
drh43605152004-05-29 21:46:49 +00005835 cdata = pChild->aData;
5836 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
drh281b21d2008-08-22 12:57:08 +00005837 memcpy(&cdata[cbrk], &data[cbrk], usableSize-cbrk);
danielk1977bc2ca9e2008-11-13 14:28:28 +00005838
5839 assert( pChild->isInit==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00005840 rc = sqlite3BtreeInitPage(pChild);
5841 if( rc==SQLITE_OK ){
5842 int nCopy = pPage->nOverflow*sizeof(pPage->aOvfl[0]);
5843 memcpy(pChild->aOvfl, pPage->aOvfl, nCopy);
5844 pChild->nOverflow = pPage->nOverflow;
5845 if( pChild->nOverflow ){
5846 pChild->nFree = 0;
5847 }
5848 assert( pChild->nCell==pPage->nCell );
drhc5053fb2008-11-27 02:22:10 +00005849 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00005850 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
5851 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
5852 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
5853 if( ISAUTOVACUUM ){
danielk197771d5d2c2008-09-29 11:49:47 +00005854 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
shane831c3292008-11-10 17:14:58 +00005855#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197771d5d2c2008-09-29 11:49:47 +00005856 if( rc==SQLITE_OK ){
danielk197700a696d2008-09-29 16:41:31 +00005857 rc = setChildPtrmaps(pChild);
danielk1977ac11ee62005-01-15 12:45:51 +00005858 }
drh30df0092008-12-23 15:58:06 +00005859 if( rc ){
5860 pChild->nOverflow = 0;
5861 }
shane831c3292008-11-10 17:14:58 +00005862#endif
danielk1977ac11ee62005-01-15 12:45:51 +00005863 }
danielk197787c52b52008-07-19 11:49:07 +00005864 }
danielk19776b456a22005-03-21 04:04:02 +00005865
danielk197771d5d2c2008-09-29 11:49:47 +00005866 if( rc==SQLITE_OK ){
5867 pCur->iPage++;
5868 pCur->apPage[1] = pChild;
danielk1977bf93c562008-09-29 15:53:25 +00005869 pCur->aiIdx[0] = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005870 rc = balance_nonroot(pCur);
5871 }else{
5872 releasePage(pChild);
5873 }
5874
drh43605152004-05-29 21:46:49 +00005875 return rc;
5876}
5877
5878/*
danielk197771d5d2c2008-09-29 11:49:47 +00005879** The page that pCur currently points to has just been modified in
5880** some way. This function figures out if this modification means the
5881** tree needs to be balanced, and if so calls the appropriate balancing
5882** routine.
5883**
5884** Parameter isInsert is true if a new cell was just inserted into the
5885** page, or false otherwise.
drh43605152004-05-29 21:46:49 +00005886*/
danielk197771d5d2c2008-09-29 11:49:47 +00005887static int balance(BtCursor *pCur, int isInsert){
drh43605152004-05-29 21:46:49 +00005888 int rc = SQLITE_OK;
danielk197771d5d2c2008-09-29 11:49:47 +00005889 MemPage *pPage = pCur->apPage[pCur->iPage];
5890
drh1fee73e2007-08-29 04:00:57 +00005891 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197771d5d2c2008-09-29 11:49:47 +00005892 if( pCur->iPage==0 ){
danielk19776e465eb2007-08-21 13:11:00 +00005893 rc = sqlite3PagerWrite(pPage->pDbPage);
5894 if( rc==SQLITE_OK && pPage->nOverflow>0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00005895 rc = balance_deeper(pCur);
danielk1977a4124bd2008-12-23 10:37:47 +00005896 assert( pCur->apPage[0]==pPage );
drh9bf9e9c2008-12-05 20:01:43 +00005897 assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
drh43605152004-05-29 21:46:49 +00005898 }
danielk1977687566d2004-11-02 12:56:41 +00005899 if( rc==SQLITE_OK && pPage->nCell==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00005900 rc = balance_shallower(pCur);
danielk1977a4124bd2008-12-23 10:37:47 +00005901 assert( pCur->apPage[0]==pPage );
drh9bf9e9c2008-12-05 20:01:43 +00005902 assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
drh43605152004-05-29 21:46:49 +00005903 }
5904 }else{
danielk1977ac245ec2005-01-14 13:50:11 +00005905 if( pPage->nOverflow>0 ||
danielk197771d5d2c2008-09-29 11:49:47 +00005906 (!isInsert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
5907 rc = balance_nonroot(pCur);
drh43605152004-05-29 21:46:49 +00005908 }
5909 }
5910 return rc;
5911}
5912
5913/*
drh8dcd7ca2004-08-08 19:43:29 +00005914** This routine checks all cursors that point to table pgnoRoot.
drh980b1a72006-08-16 16:42:48 +00005915** If any of those cursors were opened with wrFlag==0 in a different
5916** database connection (a database connection that shares the pager
5917** cache with the current connection) and that other connection
5918** is not in the ReadUncommmitted state, then this routine returns
5919** SQLITE_LOCKED.
danielk1977299b1872004-11-22 10:02:10 +00005920**
danielk19773588ceb2008-06-10 17:30:26 +00005921** As well as cursors with wrFlag==0, cursors with wrFlag==1 and
5922** isIncrblobHandle==1 are also considered 'read' cursors. Incremental
5923** blob cursors are used for both reading and writing.
5924**
5925** When pgnoRoot is the root page of an intkey table, this function is also
5926** responsible for invalidating incremental blob cursors when the table row
5927** on which they are opened is deleted or modified. Cursors are invalidated
5928** according to the following rules:
5929**
5930** 1) When BtreeClearTable() is called to completely delete the contents
5931** of a B-Tree table, pExclude is set to zero and parameter iRow is
5932** set to non-zero. In this case all incremental blob cursors open
5933** on the table rooted at pgnoRoot are invalidated.
5934**
5935** 2) When BtreeInsert(), BtreeDelete() or BtreePutData() is called to
5936** modify a table row via an SQL statement, pExclude is set to the
5937** write cursor used to do the modification and parameter iRow is set
5938** to the integer row id of the B-Tree entry being modified. Unless
5939** pExclude is itself an incremental blob cursor, then all incremental
5940** blob cursors open on row iRow of the B-Tree are invalidated.
5941**
5942** 3) If both pExclude and iRow are set to zero, no incremental blob
5943** cursors are invalidated.
drhf74b8d92002-09-01 23:20:45 +00005944*/
danielk19773588ceb2008-06-10 17:30:26 +00005945static int checkReadLocks(
5946 Btree *pBtree,
5947 Pgno pgnoRoot,
5948 BtCursor *pExclude,
5949 i64 iRow
5950){
danielk1977299b1872004-11-22 10:02:10 +00005951 BtCursor *p;
drh980b1a72006-08-16 16:42:48 +00005952 BtShared *pBt = pBtree->pBt;
drhe5fe6902007-12-07 18:55:28 +00005953 sqlite3 *db = pBtree->db;
drh1fee73e2007-08-29 04:00:57 +00005954 assert( sqlite3BtreeHoldsMutex(pBtree) );
danielk1977299b1872004-11-22 10:02:10 +00005955 for(p=pBt->pCursor; p; p=p->pNext){
drh980b1a72006-08-16 16:42:48 +00005956 if( p==pExclude ) continue;
drh980b1a72006-08-16 16:42:48 +00005957 if( p->pgnoRoot!=pgnoRoot ) continue;
danielk19773588ceb2008-06-10 17:30:26 +00005958#ifndef SQLITE_OMIT_INCRBLOB
5959 if( p->isIncrblobHandle && (
5960 (!pExclude && iRow)
5961 || (pExclude && !pExclude->isIncrblobHandle && p->info.nKey==iRow)
5962 )){
5963 p->eState = CURSOR_INVALID;
5964 }
5965#endif
5966 if( p->eState!=CURSOR_VALID ) continue;
5967 if( p->wrFlag==0
5968#ifndef SQLITE_OMIT_INCRBLOB
5969 || p->isIncrblobHandle
5970#endif
5971 ){
drhe5fe6902007-12-07 18:55:28 +00005972 sqlite3 *dbOther = p->pBtree->db;
drh980b1a72006-08-16 16:42:48 +00005973 if( dbOther==0 ||
5974 (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
5975 return SQLITE_LOCKED;
5976 }
danielk1977299b1872004-11-22 10:02:10 +00005977 }
5978 }
drhf74b8d92002-09-01 23:20:45 +00005979 return SQLITE_OK;
5980}
5981
5982/*
drh3b7511c2001-05-26 13:15:44 +00005983** Insert a new record into the BTree. The key is given by (pKey,nKey)
5984** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00005985** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00005986** is left pointing at a random location.
5987**
5988** For an INTKEY table, only the nKey value of the key is used. pKey is
5989** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00005990*/
drh3aac2dd2004-04-26 14:10:20 +00005991int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00005992 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00005993 const void *pKey, i64 nKey, /* The key of the new record */
drhe4d90812007-03-29 05:51:49 +00005994 const void *pData, int nData, /* The data of the new record */
drhb026e052007-05-02 01:34:31 +00005995 int nZero, /* Number of extra 0 bytes to append to data */
drhe4d90812007-03-29 05:51:49 +00005996 int appendBias /* True if this is likely an append */
drh3b7511c2001-05-26 13:15:44 +00005997){
drh3b7511c2001-05-26 13:15:44 +00005998 int rc;
5999 int loc;
drh14acc042001-06-10 19:56:58 +00006000 int szNew;
danielk197771d5d2c2008-09-29 11:49:47 +00006001 int idx;
drh3b7511c2001-05-26 13:15:44 +00006002 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00006003 Btree *p = pCur->pBtree;
6004 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00006005 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00006006 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00006007
drh1fee73e2007-08-29 04:00:57 +00006008 assert( cursorHoldsMutex(pCur) );
drh64022502009-01-09 14:11:04 +00006009 assert( pBt->inTransaction==TRANS_WRITE );
drhf74b8d92002-09-01 23:20:45 +00006010 assert( !pBt->readOnly );
drh64022502009-01-09 14:11:04 +00006011 assert( pCur->wrFlag );
danielk19773588ceb2008-06-10 17:30:26 +00006012 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, nKey) ){
drhf74b8d92002-09-01 23:20:45 +00006013 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
6014 }
drhfb982642007-08-30 01:19:59 +00006015 if( pCur->eState==CURSOR_FAULT ){
6016 return pCur->skip;
6017 }
danielk1977da184232006-01-05 11:34:32 +00006018
6019 /* Save the positions of any other cursors open on this table */
danielk1977be51a652008-10-08 17:58:48 +00006020 sqlite3BtreeClearCursor(pCur);
danielk19772e94d4d2006-01-09 05:36:27 +00006021 if(
danielk19772e94d4d2006-01-09 05:36:27 +00006022 SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
drhe63d9992008-08-13 19:11:48 +00006023 SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
danielk19772e94d4d2006-01-09 05:36:27 +00006024 ){
danielk1977da184232006-01-05 11:34:32 +00006025 return rc;
6026 }
6027
danielk197771d5d2c2008-09-29 11:49:47 +00006028 pPage = pCur->apPage[pCur->iPage];
drh4a1c3802004-05-12 15:15:47 +00006029 assert( pPage->intKey || nKey>=0 );
drh44845222008-07-17 18:39:57 +00006030 assert( pPage->leaf || !pPage->intKey );
drh3a4c1412004-05-09 20:40:11 +00006031 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
6032 pCur->pgnoRoot, nKey, nData, pPage->pgno,
6033 loc==0 ? "overwrite" : "new entry"));
danielk197771d5d2c2008-09-29 11:49:47 +00006034 assert( pPage->isInit );
danielk197752ae7242008-03-25 14:24:56 +00006035 allocateTempSpace(pBt);
6036 newCell = pBt->pTmpSpace;
drh2e38c322004-09-03 18:38:44 +00006037 if( newCell==0 ) return SQLITE_NOMEM;
drhb026e052007-05-02 01:34:31 +00006038 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
drh2e38c322004-09-03 18:38:44 +00006039 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00006040 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00006041 assert( szNew<=MX_CELL_SIZE(pBt) );
danielk197771d5d2c2008-09-29 11:49:47 +00006042 idx = pCur->aiIdx[pCur->iPage];
danielk1977da184232006-01-05 11:34:32 +00006043 if( loc==0 && CURSOR_VALID==pCur->eState ){
drha9121e42008-02-19 14:59:35 +00006044 u16 szOld;
danielk197771d5d2c2008-09-29 11:49:47 +00006045 assert( idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00006046 rc = sqlite3PagerWrite(pPage->pDbPage);
6047 if( rc ){
6048 goto end_insert;
6049 }
danielk197771d5d2c2008-09-29 11:49:47 +00006050 oldCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00006051 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006052 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00006053 }
drh43605152004-05-29 21:46:49 +00006054 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00006055 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00006056 if( rc ) goto end_insert;
shane0af3f892008-11-12 04:55:34 +00006057 rc = dropCell(pPage, idx, szOld);
6058 if( rc!=SQLITE_OK ) {
6059 goto end_insert;
6060 }
drh7c717f72001-06-24 20:39:41 +00006061 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00006062 assert( pPage->leaf );
danielk197771d5d2c2008-09-29 11:49:47 +00006063 idx = ++pCur->aiIdx[pCur->iPage];
drh271efa52004-05-30 19:19:05 +00006064 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00006065 pCur->validNKey = 0;
drh14acc042001-06-10 19:56:58 +00006066 }else{
drh4b70f112004-05-02 21:12:19 +00006067 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00006068 }
danielk197771d5d2c2008-09-29 11:49:47 +00006069 rc = insertCell(pPage, idx, newCell, szNew, 0, 0);
drh9bf9e9c2008-12-05 20:01:43 +00006070 if( rc==SQLITE_OK ){
6071 rc = balance(pCur, 1);
6072 }
6073
6074 /* Must make sure nOverflow is reset to zero even if the balance()
6075 ** fails. Internal data structure corruption will result otherwise. */
danielk1977a4124bd2008-12-23 10:37:47 +00006076 pCur->apPage[pCur->iPage]->nOverflow = 0;
drh9bf9e9c2008-12-05 20:01:43 +00006077
danielk1977299b1872004-11-22 10:02:10 +00006078 if( rc==SQLITE_OK ){
6079 moveToRoot(pCur);
6080 }
drh2e38c322004-09-03 18:38:44 +00006081end_insert:
drh5e2f8b92001-05-28 00:41:15 +00006082 return rc;
6083}
6084
6085/*
drh4b70f112004-05-02 21:12:19 +00006086** Delete the entry that the cursor is pointing to. The cursor
drhf94a1732008-09-30 17:18:17 +00006087** is left pointing at a arbitrary location.
drh3b7511c2001-05-26 13:15:44 +00006088*/
drh3aac2dd2004-04-26 14:10:20 +00006089int sqlite3BtreeDelete(BtCursor *pCur){
danielk197771d5d2c2008-09-29 11:49:47 +00006090 MemPage *pPage = pCur->apPage[pCur->iPage];
6091 int idx;
drh4b70f112004-05-02 21:12:19 +00006092 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00006093 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00006094 Pgno pgnoChild = 0;
drhd677b3d2007-08-20 22:48:41 +00006095 Btree *p = pCur->pBtree;
6096 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006097
drh1fee73e2007-08-29 04:00:57 +00006098 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00006099 assert( pPage->isInit );
drh64022502009-01-09 14:11:04 +00006100 assert( pBt->inTransaction==TRANS_WRITE );
drhf74b8d92002-09-01 23:20:45 +00006101 assert( !pBt->readOnly );
drhfb982642007-08-30 01:19:59 +00006102 if( pCur->eState==CURSOR_FAULT ){
6103 return pCur->skip;
6104 }
drh64022502009-01-09 14:11:04 +00006105 if( NEVER(pCur->aiIdx[pCur->iPage]>=pPage->nCell) ){
drhbd03cae2001-06-02 02:40:57 +00006106 return SQLITE_ERROR; /* The cursor is not pointing to anything */
6107 }
drh64022502009-01-09 14:11:04 +00006108 assert( pCur->wrFlag );
danielk19773588ceb2008-06-10 17:30:26 +00006109 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, pCur->info.nKey) ){
drhf74b8d92002-09-01 23:20:45 +00006110 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
6111 }
danielk1977da184232006-01-05 11:34:32 +00006112
6113 /* Restore the current cursor position (a no-op if the cursor is not in
6114 ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors
danielk19773b8a05f2007-03-19 17:44:26 +00006115 ** open on the same table. Then call sqlite3PagerWrite() on the page
danielk1977da184232006-01-05 11:34:32 +00006116 ** that the entry will be deleted from.
6117 */
6118 if(
drha3460582008-07-11 21:02:53 +00006119 (rc = restoreCursorPosition(pCur))!=0 ||
drhd1167392006-01-23 13:00:35 +00006120 (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
danielk19773b8a05f2007-03-19 17:44:26 +00006121 (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
danielk1977da184232006-01-05 11:34:32 +00006122 ){
6123 return rc;
6124 }
danielk1977e6efa742004-11-10 11:55:10 +00006125
drh85b623f2007-12-13 21:54:09 +00006126 /* Locate the cell within its page and leave pCell pointing to the
danielk1977e6efa742004-11-10 11:55:10 +00006127 ** data. The clearCell() call frees any overflow pages associated with the
6128 ** cell. The cell itself is still intact.
6129 */
danielk197771d5d2c2008-09-29 11:49:47 +00006130 idx = pCur->aiIdx[pCur->iPage];
6131 pCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00006132 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006133 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00006134 }
danielk197728129562005-01-11 10:25:06 +00006135 rc = clearCell(pPage, pCell);
drhd677b3d2007-08-20 22:48:41 +00006136 if( rc ){
drhd677b3d2007-08-20 22:48:41 +00006137 return rc;
6138 }
danielk1977e6efa742004-11-10 11:55:10 +00006139
drh4b70f112004-05-02 21:12:19 +00006140 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00006141 /*
drh5e00f6c2001-09-13 13:46:56 +00006142 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00006143 ** do something we will leave a hole on an internal page.
6144 ** We have to fill the hole by moving in a cell from a leaf. The
6145 ** next Cell after the one to be deleted is guaranteed to exist and
danielk1977299b1872004-11-22 10:02:10 +00006146 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00006147 */
drh14acc042001-06-10 19:56:58 +00006148 BtCursor leafCur;
drh1bd10f82008-12-10 21:19:56 +00006149 MemPage *pLeafPage = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00006150
drh4b70f112004-05-02 21:12:19 +00006151 unsigned char *pNext;
danielk1977299b1872004-11-22 10:02:10 +00006152 int notUsed;
danielk19776b456a22005-03-21 04:04:02 +00006153 unsigned char *tempCell = 0;
drh44845222008-07-17 18:39:57 +00006154 assert( !pPage->intKey );
drh16a9b832007-05-05 18:39:25 +00006155 sqlite3BtreeGetTempCursor(pCur, &leafCur);
danielk1977299b1872004-11-22 10:02:10 +00006156 rc = sqlite3BtreeNext(&leafCur, &notUsed);
danielk19776b456a22005-03-21 04:04:02 +00006157 if( rc==SQLITE_OK ){
danielk19772f78fc62008-09-30 09:31:45 +00006158 assert( leafCur.aiIdx[leafCur.iPage]==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00006159 pLeafPage = leafCur.apPage[leafCur.iPage];
danielk197771d5d2c2008-09-29 11:49:47 +00006160 rc = sqlite3PagerWrite(pLeafPage->pDbPage);
danielk19776b456a22005-03-21 04:04:02 +00006161 }
6162 if( rc==SQLITE_OK ){
danielk19772f78fc62008-09-30 09:31:45 +00006163 int leafCursorInvalid = 0;
drha9121e42008-02-19 14:59:35 +00006164 u16 szNext;
danielk19776b456a22005-03-21 04:04:02 +00006165 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
danielk197771d5d2c2008-09-29 11:49:47 +00006166 pCur->pgnoRoot, pPage->pgno, pLeafPage->pgno));
6167 dropCell(pPage, idx, cellSizePtr(pPage, pCell));
danielk19772f78fc62008-09-30 09:31:45 +00006168 pNext = findCell(pLeafPage, 0);
danielk197771d5d2c2008-09-29 11:49:47 +00006169 szNext = cellSizePtr(pLeafPage, pNext);
danielk19776b456a22005-03-21 04:04:02 +00006170 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
danielk197752ae7242008-03-25 14:24:56 +00006171 allocateTempSpace(pBt);
6172 tempCell = pBt->pTmpSpace;
danielk19776b456a22005-03-21 04:04:02 +00006173 if( tempCell==0 ){
6174 rc = SQLITE_NOMEM;
6175 }
danielk19778ea1cfa2008-01-01 06:19:02 +00006176 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00006177 rc = insertCell(pPage, idx, pNext-4, szNext+4, tempCell, 0);
danielk19778ea1cfa2008-01-01 06:19:02 +00006178 }
danielk19772f78fc62008-09-30 09:31:45 +00006179
drhf94a1732008-09-30 17:18:17 +00006180
6181 /* The "if" statement in the next code block is critical. The
6182 ** slightest error in that statement would allow SQLite to operate
6183 ** correctly most of the time but produce very rare failures. To
6184 ** guard against this, the following macros help to verify that
6185 ** the "if" statement is well tested.
6186 */
6187 testcase( pPage->nOverflow==0 && pPage->nFree<pBt->usableSize*2/3
6188 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6189 testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3
6190 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6191 testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3+1
6192 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6193 testcase( pPage->nOverflow>0 && pPage->nFree<=pBt->usableSize*2/3
6194 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6195 testcase( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3))
6196 && pLeafPage->nFree+2+szNext == pBt->usableSize*2/3 );
6197
6198
danielk19772f78fc62008-09-30 09:31:45 +00006199 if( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3)) &&
6200 (pLeafPage->nFree+2+szNext > pBt->usableSize*2/3)
6201 ){
drhf94a1732008-09-30 17:18:17 +00006202 /* This branch is taken if the internal node is now either overflowing
6203 ** or underfull and the leaf node will be underfull after the just cell
danielk19772f78fc62008-09-30 09:31:45 +00006204 ** copied to the internal node is deleted from it. This is a special
6205 ** case because the call to balance() to correct the internal node
6206 ** may change the tree structure and invalidate the contents of
6207 ** the leafCur.apPage[] and leafCur.aiIdx[] arrays, which will be
6208 ** used by the balance() required to correct the underfull leaf
6209 ** node.
6210 **
6211 ** The formula used in the expression above are based on facets of
6212 ** the SQLite file-format that do not change over time.
6213 */
drhf94a1732008-09-30 17:18:17 +00006214 testcase( pPage->nFree==pBt->usableSize*2/3+1 );
6215 testcase( pLeafPage->nFree+2+szNext==pBt->usableSize*2/3+1 );
danielk19772f78fc62008-09-30 09:31:45 +00006216 leafCursorInvalid = 1;
6217 }
6218
danielk19778ea1cfa2008-01-01 06:19:02 +00006219 if( rc==SQLITE_OK ){
drhc5053fb2008-11-27 02:22:10 +00006220 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00006221 put4byte(findOverflowCell(pPage, idx), pgnoChild);
drhf94a1732008-09-30 17:18:17 +00006222 VVA_ONLY( pCur->pagesShuffled = 0 );
danielk197771d5d2c2008-09-29 11:49:47 +00006223 rc = balance(pCur, 0);
danielk19778ea1cfa2008-01-01 06:19:02 +00006224 }
danielk19772f78fc62008-09-30 09:31:45 +00006225
6226 if( rc==SQLITE_OK && leafCursorInvalid ){
6227 /* The leaf-node is now underfull and so the tree needs to be
6228 ** rebalanced. However, the balance() operation on the internal
6229 ** node above may have modified the structure of the B-Tree and
6230 ** so the current contents of leafCur.apPage[] and leafCur.aiIdx[]
6231 ** may not be trusted.
6232 **
6233 ** It is not possible to copy the ancestry from pCur, as the same
6234 ** balance() call has invalidated the pCur->apPage[] and aiIdx[]
6235 ** arrays.
drh7b682802008-09-30 14:06:28 +00006236 **
6237 ** The call to saveCursorPosition() below internally saves the
6238 ** key that leafCur is currently pointing to. Currently, there
6239 ** are two copies of that key in the tree - one here on the leaf
6240 ** page and one on some internal node in the tree. The copy on
6241 ** the leaf node is always the next key in tree-order after the
6242 ** copy on the internal node. So, the call to sqlite3BtreeNext()
6243 ** calls restoreCursorPosition() to point the cursor to the copy
6244 ** stored on the internal node, then advances to the next entry,
6245 ** which happens to be the copy of the key on the internal node.
danielk1977a69fda22008-09-30 16:48:10 +00006246 ** Net effect: leafCur is pointing back to the duplicate cell
6247 ** that needs to be removed, and the leafCur.apPage[] and
6248 ** leafCur.aiIdx[] arrays are correct.
danielk19772f78fc62008-09-30 09:31:45 +00006249 */
drhf94a1732008-09-30 17:18:17 +00006250 VVA_ONLY( Pgno leafPgno = pLeafPage->pgno );
danielk19772f78fc62008-09-30 09:31:45 +00006251 rc = saveCursorPosition(&leafCur);
6252 if( rc==SQLITE_OK ){
6253 rc = sqlite3BtreeNext(&leafCur, &notUsed);
6254 }
6255 pLeafPage = leafCur.apPage[leafCur.iPage];
6256 assert( pLeafPage->pgno==leafPgno );
6257 assert( leafCur.aiIdx[leafCur.iPage]==0 );
6258 }
6259
danielk19770cd1bbd2008-11-26 07:25:52 +00006260 if( SQLITE_OK==rc
6261 && SQLITE_OK==(rc = sqlite3PagerWrite(pLeafPage->pDbPage))
6262 ){
danielk19772f78fc62008-09-30 09:31:45 +00006263 dropCell(pLeafPage, 0, szNext);
drhf94a1732008-09-30 17:18:17 +00006264 VVA_ONLY( leafCur.pagesShuffled = 0 );
danielk197771d5d2c2008-09-29 11:49:47 +00006265 rc = balance(&leafCur, 0);
drhf94a1732008-09-30 17:18:17 +00006266 assert( leafCursorInvalid || !leafCur.pagesShuffled
6267 || !pCur->pagesShuffled );
danielk19778ea1cfa2008-01-01 06:19:02 +00006268 }
danielk19776b456a22005-03-21 04:04:02 +00006269 }
drh16a9b832007-05-05 18:39:25 +00006270 sqlite3BtreeReleaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00006271 }else{
danielk1977299b1872004-11-22 10:02:10 +00006272 TRACE(("DELETE: table=%d delete from leaf %d\n",
6273 pCur->pgnoRoot, pPage->pgno));
shanedcc50b72008-11-13 18:29:50 +00006274 rc = dropCell(pPage, idx, cellSizePtr(pPage, pCell));
6275 if( rc==SQLITE_OK ){
6276 rc = balance(pCur, 0);
6277 }
drh5e2f8b92001-05-28 00:41:15 +00006278 }
danielk19776b456a22005-03-21 04:04:02 +00006279 if( rc==SQLITE_OK ){
6280 moveToRoot(pCur);
6281 }
drh5e2f8b92001-05-28 00:41:15 +00006282 return rc;
drh3b7511c2001-05-26 13:15:44 +00006283}
drh8b2f49b2001-06-08 00:21:52 +00006284
6285/*
drhc6b52df2002-01-04 03:09:29 +00006286** Create a new BTree table. Write into *piTable the page
6287** number for the root page of the new table.
6288**
drhab01f612004-05-22 02:55:23 +00006289** The type of type is determined by the flags parameter. Only the
6290** following values of flags are currently in use. Other values for
6291** flags might not work:
6292**
6293** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
6294** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00006295*/
drhd677b3d2007-08-20 22:48:41 +00006296static int btreeCreateTable(Btree *p, int *piTable, int flags){
danielk1977aef0bf62005-12-30 16:28:01 +00006297 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006298 MemPage *pRoot;
6299 Pgno pgnoRoot;
6300 int rc;
drhd677b3d2007-08-20 22:48:41 +00006301
drh1fee73e2007-08-29 04:00:57 +00006302 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00006303 assert( pBt->inTransaction==TRANS_WRITE );
danielk197728129562005-01-11 10:25:06 +00006304 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00006305
danielk1977003ba062004-11-04 02:57:33 +00006306#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00006307 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00006308 if( rc ){
6309 return rc;
6310 }
danielk1977003ba062004-11-04 02:57:33 +00006311#else
danielk1977687566d2004-11-02 12:56:41 +00006312 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00006313 Pgno pgnoMove; /* Move a page here to make room for the root-page */
6314 MemPage *pPageMove; /* The page to move to. */
6315
danielk197720713f32007-05-03 11:43:33 +00006316 /* Creating a new table may probably require moving an existing database
6317 ** to make room for the new tables root page. In case this page turns
6318 ** out to be an overflow page, delete all overflow page-map caches
6319 ** held by open cursors.
6320 */
danielk197792d4d7a2007-05-04 12:05:56 +00006321 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00006322
danielk1977003ba062004-11-04 02:57:33 +00006323 /* Read the value of meta[3] from the database to determine where the
6324 ** root page of the new table should go. meta[3] is the largest root-page
6325 ** created so far, so the new root-page is (meta[3]+1).
6326 */
danielk1977aef0bf62005-12-30 16:28:01 +00006327 rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
drhd677b3d2007-08-20 22:48:41 +00006328 if( rc!=SQLITE_OK ){
6329 return rc;
6330 }
danielk1977003ba062004-11-04 02:57:33 +00006331 pgnoRoot++;
6332
danielk1977599fcba2004-11-08 07:13:13 +00006333 /* The new root-page may not be allocated on a pointer-map page, or the
6334 ** PENDING_BYTE page.
6335 */
drh72190432008-01-31 14:54:43 +00006336 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00006337 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00006338 pgnoRoot++;
6339 }
6340 assert( pgnoRoot>=3 );
6341
6342 /* Allocate a page. The page that currently resides at pgnoRoot will
6343 ** be moved to the allocated page (unless the allocated page happens
6344 ** to reside at pgnoRoot).
6345 */
drh4f0c5872007-03-26 22:05:01 +00006346 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00006347 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00006348 return rc;
6349 }
danielk1977003ba062004-11-04 02:57:33 +00006350
6351 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00006352 /* pgnoRoot is the page that will be used for the root-page of
6353 ** the new table (assuming an error did not occur). But we were
6354 ** allocated pgnoMove. If required (i.e. if it was not allocated
6355 ** by extending the file), the current page at position pgnoMove
6356 ** is already journaled.
6357 */
danielk1977003ba062004-11-04 02:57:33 +00006358 u8 eType;
6359 Pgno iPtrPage;
6360
6361 releasePage(pPageMove);
danielk1977f35843b2007-04-07 15:03:17 +00006362
6363 /* Move the page currently at pgnoRoot to pgnoMove. */
drh16a9b832007-05-05 18:39:25 +00006364 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006365 if( rc!=SQLITE_OK ){
6366 return rc;
6367 }
6368 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drhccae6022005-02-26 17:31:26 +00006369 if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00006370 releasePage(pRoot);
6371 return rc;
6372 }
drhccae6022005-02-26 17:31:26 +00006373 assert( eType!=PTRMAP_ROOTPAGE );
6374 assert( eType!=PTRMAP_FREEPAGE );
danielk19774c999992008-07-16 18:17:55 +00006375 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
danielk1977003ba062004-11-04 02:57:33 +00006376 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00006377
6378 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00006379 if( rc!=SQLITE_OK ){
6380 return rc;
6381 }
drh16a9b832007-05-05 18:39:25 +00006382 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006383 if( rc!=SQLITE_OK ){
6384 return rc;
6385 }
danielk19773b8a05f2007-03-19 17:44:26 +00006386 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00006387 if( rc!=SQLITE_OK ){
6388 releasePage(pRoot);
6389 return rc;
6390 }
6391 }else{
6392 pRoot = pPageMove;
6393 }
6394
danielk197742741be2005-01-08 12:42:39 +00006395 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00006396 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
6397 if( rc ){
6398 releasePage(pRoot);
6399 return rc;
6400 }
danielk1977aef0bf62005-12-30 16:28:01 +00006401 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00006402 if( rc ){
6403 releasePage(pRoot);
6404 return rc;
6405 }
danielk197742741be2005-01-08 12:42:39 +00006406
danielk1977003ba062004-11-04 02:57:33 +00006407 }else{
drh4f0c5872007-03-26 22:05:01 +00006408 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00006409 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00006410 }
6411#endif
danielk19773b8a05f2007-03-19 17:44:26 +00006412 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhde647132004-05-07 17:57:49 +00006413 zeroPage(pRoot, flags | PTF_LEAF);
danielk19773b8a05f2007-03-19 17:44:26 +00006414 sqlite3PagerUnref(pRoot->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00006415 *piTable = (int)pgnoRoot;
6416 return SQLITE_OK;
6417}
drhd677b3d2007-08-20 22:48:41 +00006418int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
6419 int rc;
6420 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006421 p->pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006422 rc = btreeCreateTable(p, piTable, flags);
6423 sqlite3BtreeLeave(p);
6424 return rc;
6425}
drh8b2f49b2001-06-08 00:21:52 +00006426
6427/*
6428** Erase the given database page and all its children. Return
6429** the page to the freelist.
6430*/
drh4b70f112004-05-02 21:12:19 +00006431static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00006432 BtShared *pBt, /* The BTree that contains the table */
drh4b70f112004-05-02 21:12:19 +00006433 Pgno pgno, /* Page number to clear */
danielk1977c7af4842008-10-27 13:59:33 +00006434 int freePageFlag, /* Deallocate page if true */
6435 int *pnChange
drh4b70f112004-05-02 21:12:19 +00006436){
danielk19776b456a22005-03-21 04:04:02 +00006437 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00006438 int rc;
drh4b70f112004-05-02 21:12:19 +00006439 unsigned char *pCell;
6440 int i;
drh8b2f49b2001-06-08 00:21:52 +00006441
drh1fee73e2007-08-29 04:00:57 +00006442 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197789d40042008-11-17 14:20:56 +00006443 if( pgno>pagerPagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00006444 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00006445 }
6446
danielk197771d5d2c2008-09-29 11:49:47 +00006447 rc = getAndInitPage(pBt, pgno, &pPage);
danielk19776b456a22005-03-21 04:04:02 +00006448 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00006449 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00006450 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00006451 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00006452 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00006453 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006454 }
drh4b70f112004-05-02 21:12:19 +00006455 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00006456 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006457 }
drha34b6762004-05-07 13:30:42 +00006458 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00006459 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00006460 if( rc ) goto cleardatabasepage_out;
danielk1977c7af4842008-10-27 13:59:33 +00006461 }else if( pnChange ){
6462 assert( pPage->intKey );
6463 *pnChange += pPage->nCell;
drh2aa679f2001-06-25 02:11:07 +00006464 }
6465 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00006466 rc = freePage(pPage);
danielk19773b8a05f2007-03-19 17:44:26 +00006467 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
drh3a4c1412004-05-09 20:40:11 +00006468 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00006469 }
danielk19776b456a22005-03-21 04:04:02 +00006470
6471cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00006472 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00006473 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006474}
6475
6476/*
drhab01f612004-05-22 02:55:23 +00006477** Delete all information from a single table in the database. iTable is
6478** the page number of the root of the table. After this routine returns,
6479** the root page is empty, but still exists.
6480**
6481** This routine will fail with SQLITE_LOCKED if there are any open
6482** read cursors on the table. Open write cursors are moved to the
6483** root of the table.
danielk1977c7af4842008-10-27 13:59:33 +00006484**
6485** If pnChange is not NULL, then table iTable must be an intkey table. The
6486** integer value pointed to by pnChange is incremented by the number of
6487** entries in the table.
drh8b2f49b2001-06-08 00:21:52 +00006488*/
danielk1977c7af4842008-10-27 13:59:33 +00006489int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
drh8b2f49b2001-06-08 00:21:52 +00006490 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00006491 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00006492 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006493 pBt->db = p->db;
drh64022502009-01-09 14:11:04 +00006494 assert( p->inTrans==TRANS_WRITE );
6495 if( (rc = checkReadLocks(p, iTable, 0, 1))!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00006496 /* nothing to do */
6497 }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
6498 /* nothing to do */
6499 }else{
danielk197762c14b32008-11-19 09:05:26 +00006500 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
drh8b2f49b2001-06-08 00:21:52 +00006501 }
drhd677b3d2007-08-20 22:48:41 +00006502 sqlite3BtreeLeave(p);
6503 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006504}
6505
6506/*
6507** Erase all information in a table and add the root of the table to
6508** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00006509** page 1) is never added to the freelist.
6510**
6511** This routine will fail with SQLITE_LOCKED if there are any open
6512** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00006513**
6514** If AUTOVACUUM is enabled and the page at iTable is not the last
6515** root page in the database file, then the last root page
6516** in the database file is moved into the slot formerly occupied by
6517** iTable and that last slot formerly occupied by the last root page
6518** is added to the freelist instead of iTable. In this say, all
6519** root pages are kept at the beginning of the database file, which
6520** is necessary for AUTOVACUUM to work right. *piMoved is set to the
6521** page number that used to be the last root page in the file before
6522** the move. If no page gets moved, *piMoved is set to 0.
6523** The last root page is recorded in meta[3] and the value of
6524** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00006525*/
danielk197789d40042008-11-17 14:20:56 +00006526static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00006527 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00006528 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00006529 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00006530
drh1fee73e2007-08-29 04:00:57 +00006531 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00006532 assert( p->inTrans==TRANS_WRITE );
danielk1977a0bf2652004-11-04 14:30:04 +00006533
danielk1977e6efa742004-11-10 11:55:10 +00006534 /* It is illegal to drop a table if any cursors are open on the
6535 ** database. This is because in auto-vacuum mode the backend may
6536 ** need to move another root-page to fill a gap left by the deleted
6537 ** root page. If an open cursor was using this page a problem would
6538 ** occur.
6539 */
6540 if( pBt->pCursor ){
6541 return SQLITE_LOCKED;
drh5df72a52002-06-06 23:16:05 +00006542 }
danielk1977a0bf2652004-11-04 14:30:04 +00006543
drh16a9b832007-05-05 18:39:25 +00006544 rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00006545 if( rc ) return rc;
danielk1977c7af4842008-10-27 13:59:33 +00006546 rc = sqlite3BtreeClearTable(p, iTable, 0);
danielk19776b456a22005-03-21 04:04:02 +00006547 if( rc ){
6548 releasePage(pPage);
6549 return rc;
6550 }
danielk1977a0bf2652004-11-04 14:30:04 +00006551
drh205f48e2004-11-05 00:43:11 +00006552 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00006553
drh4b70f112004-05-02 21:12:19 +00006554 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00006555#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00006556 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00006557 releasePage(pPage);
6558#else
6559 if( pBt->autoVacuum ){
6560 Pgno maxRootPgno;
danielk1977aef0bf62005-12-30 16:28:01 +00006561 rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006562 if( rc!=SQLITE_OK ){
6563 releasePage(pPage);
6564 return rc;
6565 }
6566
6567 if( iTable==maxRootPgno ){
6568 /* If the table being dropped is the table with the largest root-page
6569 ** number in the database, put the root page on the free list.
6570 */
6571 rc = freePage(pPage);
6572 releasePage(pPage);
6573 if( rc!=SQLITE_OK ){
6574 return rc;
6575 }
6576 }else{
6577 /* The table being dropped does not have the largest root-page
6578 ** number in the database. So move the page that does into the
6579 ** gap left by the deleted root-page.
6580 */
6581 MemPage *pMove;
6582 releasePage(pPage);
drh16a9b832007-05-05 18:39:25 +00006583 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006584 if( rc!=SQLITE_OK ){
6585 return rc;
6586 }
danielk19774c999992008-07-16 18:17:55 +00006587 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006588 releasePage(pMove);
6589 if( rc!=SQLITE_OK ){
6590 return rc;
6591 }
drh16a9b832007-05-05 18:39:25 +00006592 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006593 if( rc!=SQLITE_OK ){
6594 return rc;
6595 }
6596 rc = freePage(pMove);
6597 releasePage(pMove);
6598 if( rc!=SQLITE_OK ){
6599 return rc;
6600 }
6601 *piMoved = maxRootPgno;
6602 }
6603
danielk1977599fcba2004-11-08 07:13:13 +00006604 /* Set the new 'max-root-page' value in the database header. This
6605 ** is the old value less one, less one more if that happens to
6606 ** be a root-page number, less one again if that is the
6607 ** PENDING_BYTE_PAGE.
6608 */
danielk197787a6e732004-11-05 12:58:25 +00006609 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00006610 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
6611 maxRootPgno--;
6612 }
danielk1977266664d2006-02-10 08:24:21 +00006613 if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00006614 maxRootPgno--;
6615 }
danielk1977599fcba2004-11-08 07:13:13 +00006616 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
6617
danielk1977aef0bf62005-12-30 16:28:01 +00006618 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006619 }else{
6620 rc = freePage(pPage);
6621 releasePage(pPage);
6622 }
6623#endif
drh2aa679f2001-06-25 02:11:07 +00006624 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00006625 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00006626 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00006627 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00006628 }
drh8b2f49b2001-06-08 00:21:52 +00006629 return rc;
6630}
drhd677b3d2007-08-20 22:48:41 +00006631int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
6632 int rc;
6633 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006634 p->pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006635 rc = btreeDropTable(p, iTable, piMoved);
6636 sqlite3BtreeLeave(p);
6637 return rc;
6638}
drh8b2f49b2001-06-08 00:21:52 +00006639
drh001bbcb2003-03-19 03:14:00 +00006640
drh8b2f49b2001-06-08 00:21:52 +00006641/*
drh23e11ca2004-05-04 17:27:28 +00006642** Read the meta-information out of a database file. Meta[0]
6643** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00006644** through meta[15] are available for use by higher layers. Meta[0]
6645** is read-only, the others are read/write.
6646**
6647** The schema layer numbers meta values differently. At the schema
6648** layer (and the SetCookie and ReadCookie opcodes) the number of
6649** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00006650*/
danielk1977aef0bf62005-12-30 16:28:01 +00006651int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
drh1bd10f82008-12-10 21:19:56 +00006652 DbPage *pDbPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00006653 int rc;
drh4b70f112004-05-02 21:12:19 +00006654 unsigned char *pP1;
danielk1977aef0bf62005-12-30 16:28:01 +00006655 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006656
drhd677b3d2007-08-20 22:48:41 +00006657 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006658 pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006659
danielk1977da184232006-01-05 11:34:32 +00006660 /* Reading a meta-data value requires a read-lock on page 1 (and hence
6661 ** the sqlite_master table. We grab this lock regardless of whether or
6662 ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
drhc25eabe2009-02-24 18:57:31 +00006663 ** 1 is treated as a special case by querySharedCacheTableLock()
6664 ** and setSharedCacheTableLock()).
danielk1977da184232006-01-05 11:34:32 +00006665 */
drhc25eabe2009-02-24 18:57:31 +00006666 rc = querySharedCacheTableLock(p, 1, READ_LOCK);
danielk1977da184232006-01-05 11:34:32 +00006667 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00006668 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00006669 return rc;
6670 }
6671
drh23e11ca2004-05-04 17:27:28 +00006672 assert( idx>=0 && idx<=15 );
danielk1977d9f6c532008-09-19 16:39:38 +00006673 if( pBt->pPage1 ){
6674 /* The b-tree is already holding a reference to page 1 of the database
6675 ** file. In this case the required meta-data value can be read directly
6676 ** from the page data of this reference. This is slightly faster than
6677 ** requesting a new reference from the pager layer.
6678 */
6679 pP1 = (unsigned char *)pBt->pPage1->aData;
6680 }else{
6681 /* The b-tree does not have a reference to page 1 of the database file.
6682 ** Obtain one from the pager layer.
6683 */
danielk1977ea897302008-09-19 15:10:58 +00006684 rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
6685 if( rc ){
6686 sqlite3BtreeLeave(p);
6687 return rc;
6688 }
6689 pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
drhd677b3d2007-08-20 22:48:41 +00006690 }
drh23e11ca2004-05-04 17:27:28 +00006691 *pMeta = get4byte(&pP1[36 + idx*4]);
danielk1977ea897302008-09-19 15:10:58 +00006692
danielk1977d9f6c532008-09-19 16:39:38 +00006693 /* If the b-tree is not holding a reference to page 1, then one was
6694 ** requested from the pager layer in the above block. Release it now.
6695 */
danielk1977ea897302008-09-19 15:10:58 +00006696 if( !pBt->pPage1 ){
6697 sqlite3PagerUnref(pDbPage);
6698 }
drhae157872004-08-14 19:20:09 +00006699
danielk1977599fcba2004-11-08 07:13:13 +00006700 /* If autovacuumed is disabled in this build but we are trying to
6701 ** access an autovacuumed database, then make the database readonly.
6702 */
danielk1977003ba062004-11-04 02:57:33 +00006703#ifdef SQLITE_OMIT_AUTOVACUUM
drhae157872004-08-14 19:20:09 +00006704 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00006705#endif
drhae157872004-08-14 19:20:09 +00006706
danielk1977da184232006-01-05 11:34:32 +00006707 /* Grab the read-lock on page 1. */
drhc25eabe2009-02-24 18:57:31 +00006708 rc = setSharedCacheTableLock(p, 1, READ_LOCK);
drhd677b3d2007-08-20 22:48:41 +00006709 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00006710 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006711}
6712
6713/*
drh23e11ca2004-05-04 17:27:28 +00006714** Write meta-information back into the database. Meta[0] is
6715** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00006716*/
danielk1977aef0bf62005-12-30 16:28:01 +00006717int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
6718 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00006719 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00006720 int rc;
drh23e11ca2004-05-04 17:27:28 +00006721 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00006722 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006723 pBt->db = p->db;
drh64022502009-01-09 14:11:04 +00006724 assert( p->inTrans==TRANS_WRITE );
6725 assert( pBt->pPage1!=0 );
6726 pP1 = pBt->pPage1->aData;
6727 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6728 if( rc==SQLITE_OK ){
6729 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +00006730#ifndef SQLITE_OMIT_AUTOVACUUM
drh64022502009-01-09 14:11:04 +00006731 if( idx==7 ){
6732 assert( pBt->autoVacuum || iMeta==0 );
6733 assert( iMeta==0 || iMeta==1 );
6734 pBt->incrVacuum = (u8)iMeta;
drhd677b3d2007-08-20 22:48:41 +00006735 }
drh64022502009-01-09 14:11:04 +00006736#endif
drh5df72a52002-06-06 23:16:05 +00006737 }
drhd677b3d2007-08-20 22:48:41 +00006738 sqlite3BtreeLeave(p);
6739 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006740}
drh8c42ca92001-06-22 19:15:00 +00006741
drhf328bc82004-05-10 23:29:49 +00006742/*
6743** Return the flag byte at the beginning of the page that the cursor
6744** is currently pointing to.
6745*/
6746int sqlite3BtreeFlags(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00006747 /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
drha3460582008-07-11 21:02:53 +00006748 ** restoreCursorPosition() here.
danielk1977da184232006-01-05 11:34:32 +00006749 */
danielk1977e448dc42008-01-02 11:50:51 +00006750 MemPage *pPage;
drha3460582008-07-11 21:02:53 +00006751 restoreCursorPosition(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00006752 pPage = pCur->apPage[pCur->iPage];
drh1fee73e2007-08-29 04:00:57 +00006753 assert( cursorHoldsMutex(pCur) );
drh64022502009-01-09 14:11:04 +00006754 assert( pPage!=0 );
drhd0679ed2007-08-28 22:24:34 +00006755 assert( pPage->pBt==pCur->pBt );
drh64022502009-01-09 14:11:04 +00006756 return pPage->aData[pPage->hdrOffset];
drhf328bc82004-05-10 23:29:49 +00006757}
6758
danielk1977a5533162009-02-24 10:01:51 +00006759#ifndef SQLITE_OMIT_BTREECOUNT
6760/*
6761** The first argument, pCur, is a cursor opened on some b-tree. Count the
6762** number of entries in the b-tree and write the result to *pnEntry.
6763**
6764** SQLITE_OK is returned if the operation is successfully executed.
6765** Otherwise, if an error is encountered (i.e. an IO error or database
6766** corruption) an SQLite error code is returned.
6767*/
6768int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
6769 i64 nEntry = 0; /* Value to return in *pnEntry */
6770 int rc; /* Return code */
6771 rc = moveToRoot(pCur);
6772
6773 /* Unless an error occurs, the following loop runs one iteration for each
6774 ** page in the B-Tree structure (not including overflow pages).
6775 */
6776 while( rc==SQLITE_OK ){
6777 int iIdx; /* Index of child node in parent */
6778 MemPage *pPage; /* Current page of the b-tree */
6779
6780 /* If this is a leaf page or the tree is not an int-key tree, then
6781 ** this page contains countable entries. Increment the entry counter
6782 ** accordingly.
6783 */
6784 pPage = pCur->apPage[pCur->iPage];
6785 if( pPage->leaf || !pPage->intKey ){
6786 nEntry += pPage->nCell;
6787 }
6788
6789 /* pPage is a leaf node. This loop navigates the cursor so that it
6790 ** points to the first interior cell that it points to the parent of
6791 ** the next page in the tree that has not yet been visited. The
6792 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
6793 ** of the page, or to the number of cells in the page if the next page
6794 ** to visit is the right-child of its parent.
6795 **
6796 ** If all pages in the tree have been visited, return SQLITE_OK to the
6797 ** caller.
6798 */
6799 if( pPage->leaf ){
6800 do {
6801 if( pCur->iPage==0 ){
6802 /* All pages of the b-tree have been visited. Return successfully. */
6803 *pnEntry = nEntry;
6804 return SQLITE_OK;
6805 }
6806 sqlite3BtreeMoveToParent(pCur);
6807 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
6808
6809 pCur->aiIdx[pCur->iPage]++;
6810 pPage = pCur->apPage[pCur->iPage];
6811 }
6812
6813 /* Descend to the child node of the cell that the cursor currently
6814 ** points at. This is the right-child if (iIdx==pPage->nCell).
6815 */
6816 iIdx = pCur->aiIdx[pCur->iPage];
6817 if( iIdx==pPage->nCell ){
6818 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
6819 }else{
6820 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
6821 }
6822 }
6823
6824 /* An error has occured. Return an error code. */
6825 return rc;
6826}
6827#endif
drhdd793422001-06-28 01:54:48 +00006828
drhdd793422001-06-28 01:54:48 +00006829/*
drh5eddca62001-06-30 21:53:53 +00006830** Return the pager associated with a BTree. This routine is used for
6831** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00006832*/
danielk1977aef0bf62005-12-30 16:28:01 +00006833Pager *sqlite3BtreePager(Btree *p){
6834 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00006835}
drh5eddca62001-06-30 21:53:53 +00006836
drhb7f91642004-10-31 02:22:47 +00006837#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006838/*
6839** Append a message to the error message string.
6840*/
drh2e38c322004-09-03 18:38:44 +00006841static void checkAppendMsg(
6842 IntegrityCk *pCheck,
6843 char *zMsg1,
6844 const char *zFormat,
6845 ...
6846){
6847 va_list ap;
drh1dcdbc02007-01-27 02:24:54 +00006848 if( !pCheck->mxErr ) return;
6849 pCheck->mxErr--;
6850 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00006851 va_start(ap, zFormat);
drhf089aa42008-07-08 19:34:06 +00006852 if( pCheck->errMsg.nChar ){
6853 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
drh5eddca62001-06-30 21:53:53 +00006854 }
drhf089aa42008-07-08 19:34:06 +00006855 if( zMsg1 ){
6856 sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
6857 }
6858 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
6859 va_end(ap);
drhc890fec2008-08-01 20:10:08 +00006860 if( pCheck->errMsg.mallocFailed ){
6861 pCheck->mallocFailed = 1;
6862 }
drh5eddca62001-06-30 21:53:53 +00006863}
drhb7f91642004-10-31 02:22:47 +00006864#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006865
drhb7f91642004-10-31 02:22:47 +00006866#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006867/*
6868** Add 1 to the reference count for page iPage. If this is the second
6869** reference to the page, add an error message to pCheck->zErrMsg.
6870** Return 1 if there are 2 ore more references to the page and 0 if
6871** if this is the first reference to the page.
6872**
6873** Also check that the page number is in bounds.
6874*/
danielk197789d40042008-11-17 14:20:56 +00006875static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00006876 if( iPage==0 ) return 1;
danielk197789d40042008-11-17 14:20:56 +00006877 if( iPage>pCheck->nPage ){
drh2e38c322004-09-03 18:38:44 +00006878 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006879 return 1;
6880 }
6881 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00006882 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006883 return 1;
6884 }
6885 return (pCheck->anRef[iPage]++)>1;
6886}
6887
danielk1977afcdd022004-10-31 16:25:42 +00006888#ifndef SQLITE_OMIT_AUTOVACUUM
6889/*
6890** Check that the entry in the pointer-map for page iChild maps to
6891** page iParent, pointer type ptrType. If not, append an error message
6892** to pCheck.
6893*/
6894static void checkPtrmap(
6895 IntegrityCk *pCheck, /* Integrity check context */
6896 Pgno iChild, /* Child page number */
6897 u8 eType, /* Expected pointer map type */
6898 Pgno iParent, /* Expected pointer map parent page number */
6899 char *zContext /* Context description (used for error msg) */
6900){
6901 int rc;
6902 u8 ePtrmapType;
6903 Pgno iPtrmapParent;
6904
6905 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
6906 if( rc!=SQLITE_OK ){
drhe43ba702008-12-05 22:40:08 +00006907 if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
danielk1977afcdd022004-10-31 16:25:42 +00006908 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
6909 return;
6910 }
6911
6912 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
6913 checkAppendMsg(pCheck, zContext,
6914 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
6915 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
6916 }
6917}
6918#endif
6919
drh5eddca62001-06-30 21:53:53 +00006920/*
6921** Check the integrity of the freelist or of an overflow page list.
6922** Verify that the number of pages on the list is N.
6923*/
drh30e58752002-03-02 20:41:57 +00006924static void checkList(
6925 IntegrityCk *pCheck, /* Integrity checking context */
6926 int isFreeList, /* True for a freelist. False for overflow page list */
6927 int iPage, /* Page number for first page in the list */
6928 int N, /* Expected number of pages in the list */
6929 char *zContext /* Context for error messages */
6930){
6931 int i;
drh3a4c1412004-05-09 20:40:11 +00006932 int expected = N;
6933 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00006934 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00006935 DbPage *pOvflPage;
6936 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00006937 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00006938 checkAppendMsg(pCheck, zContext,
6939 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00006940 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00006941 break;
6942 }
6943 if( checkRef(pCheck, iPage, zContext) ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00006944 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
drh2e38c322004-09-03 18:38:44 +00006945 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006946 break;
6947 }
danielk19773b8a05f2007-03-19 17:44:26 +00006948 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00006949 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00006950 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00006951#ifndef SQLITE_OMIT_AUTOVACUUM
6952 if( pCheck->pBt->autoVacuum ){
6953 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
6954 }
6955#endif
drh45b1fac2008-07-04 17:52:42 +00006956 if( n>pCheck->pBt->usableSize/4-2 ){
drh2e38c322004-09-03 18:38:44 +00006957 checkAppendMsg(pCheck, zContext,
6958 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00006959 N--;
6960 }else{
6961 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00006962 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00006963#ifndef SQLITE_OMIT_AUTOVACUUM
6964 if( pCheck->pBt->autoVacuum ){
6965 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
6966 }
6967#endif
6968 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00006969 }
6970 N -= n;
drh30e58752002-03-02 20:41:57 +00006971 }
drh30e58752002-03-02 20:41:57 +00006972 }
danielk1977afcdd022004-10-31 16:25:42 +00006973#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006974 else{
6975 /* If this database supports auto-vacuum and iPage is not the last
6976 ** page in this overflow list, check that the pointer-map entry for
6977 ** the following page matches iPage.
6978 */
6979 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00006980 i = get4byte(pOvflData);
danielk1977687566d2004-11-02 12:56:41 +00006981 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
6982 }
danielk1977afcdd022004-10-31 16:25:42 +00006983 }
6984#endif
danielk19773b8a05f2007-03-19 17:44:26 +00006985 iPage = get4byte(pOvflData);
6986 sqlite3PagerUnref(pOvflPage);
drh5eddca62001-06-30 21:53:53 +00006987 }
6988}
drhb7f91642004-10-31 02:22:47 +00006989#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006990
drhb7f91642004-10-31 02:22:47 +00006991#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006992/*
6993** Do various sanity checks on a single page of a tree. Return
6994** the tree depth. Root pages return 0. Parents of root pages
6995** return 1, and so forth.
6996**
6997** These checks are done:
6998**
6999** 1. Make sure that cells and freeblocks do not overlap
7000** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00007001** NO 2. Make sure cell keys are in order.
7002** NO 3. Make sure no key is less than or equal to zLowerBound.
7003** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00007004** 5. Check the integrity of overflow pages.
7005** 6. Recursively call checkTreePage on all children.
7006** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00007007** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00007008** the root of the tree.
7009*/
7010static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00007011 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00007012 int iPage, /* Page number of the page to check */
drh74161702006-02-24 02:53:49 +00007013 char *zParentContext /* Parent context */
drh5eddca62001-06-30 21:53:53 +00007014){
7015 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00007016 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00007017 int hdr, cellStart;
7018 int nCell;
drhda200cc2004-05-09 11:51:38 +00007019 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00007020 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00007021 int usableSize;
drh5eddca62001-06-30 21:53:53 +00007022 char zContext[100];
shane0af3f892008-11-12 04:55:34 +00007023 char *hit = 0;
drh5eddca62001-06-30 21:53:53 +00007024
drh5bb3eb92007-05-04 13:15:55 +00007025 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
danielk1977ef73ee92004-11-06 12:26:07 +00007026
drh5eddca62001-06-30 21:53:53 +00007027 /* Check that the page exists
7028 */
drhd9cb6ac2005-10-20 07:28:17 +00007029 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00007030 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00007031 if( iPage==0 ) return 0;
7032 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh16a9b832007-05-05 18:39:25 +00007033 if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drhe43ba702008-12-05 22:40:08 +00007034 if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
drh2e38c322004-09-03 18:38:44 +00007035 checkAppendMsg(pCheck, zContext,
7036 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00007037 return 0;
7038 }
danielk197771d5d2c2008-09-29 11:49:47 +00007039 if( (rc = sqlite3BtreeInitPage(pPage))!=0 ){
drh64022502009-01-09 14:11:04 +00007040 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
drh16a9b832007-05-05 18:39:25 +00007041 checkAppendMsg(pCheck, zContext,
7042 "sqlite3BtreeInitPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00007043 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00007044 return 0;
7045 }
7046
7047 /* Check out all the cells.
7048 */
7049 depth = 0;
drh1dcdbc02007-01-27 02:24:54 +00007050 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
drh6f11bef2004-05-13 01:12:56 +00007051 u8 *pCell;
danielk197789d40042008-11-17 14:20:56 +00007052 u32 sz;
drh6f11bef2004-05-13 01:12:56 +00007053 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00007054
7055 /* Check payload overflow pages
7056 */
drh5bb3eb92007-05-04 13:15:55 +00007057 sqlite3_snprintf(sizeof(zContext), zContext,
7058 "On tree page %d cell %d: ", iPage, i);
danielk19771cc5ed82007-05-16 17:28:43 +00007059 pCell = findCell(pPage,i);
drh16a9b832007-05-05 18:39:25 +00007060 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00007061 sz = info.nData;
drhf49661a2008-12-10 16:45:50 +00007062 if( !pPage->intKey ) sz += (int)info.nKey;
drh72365832007-03-06 15:53:44 +00007063 assert( sz==info.nPayload );
drh6f11bef2004-05-13 01:12:56 +00007064 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00007065 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00007066 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
7067#ifndef SQLITE_OMIT_AUTOVACUUM
7068 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00007069 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00007070 }
7071#endif
7072 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00007073 }
7074
7075 /* Check sanity of left child page.
7076 */
drhda200cc2004-05-09 11:51:38 +00007077 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00007078 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00007079#ifndef SQLITE_OMIT_AUTOVACUUM
7080 if( pBt->autoVacuum ){
7081 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
7082 }
7083#endif
danielk197762c14b32008-11-19 09:05:26 +00007084 d2 = checkTreePage(pCheck, pgno, zContext);
drhda200cc2004-05-09 11:51:38 +00007085 if( i>0 && d2!=depth ){
7086 checkAppendMsg(pCheck, zContext, "Child page depth differs");
7087 }
7088 depth = d2;
drh5eddca62001-06-30 21:53:53 +00007089 }
drh5eddca62001-06-30 21:53:53 +00007090 }
drhda200cc2004-05-09 11:51:38 +00007091 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00007092 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh5bb3eb92007-05-04 13:15:55 +00007093 sqlite3_snprintf(sizeof(zContext), zContext,
7094 "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00007095#ifndef SQLITE_OMIT_AUTOVACUUM
7096 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00007097 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00007098 }
7099#endif
danielk197762c14b32008-11-19 09:05:26 +00007100 checkTreePage(pCheck, pgno, zContext);
drhda200cc2004-05-09 11:51:38 +00007101 }
drh5eddca62001-06-30 21:53:53 +00007102
7103 /* Check for complete coverage of the page
7104 */
drhda200cc2004-05-09 11:51:38 +00007105 data = pPage->aData;
7106 hdr = pPage->hdrOffset;
drhf7141992008-06-19 00:16:08 +00007107 hit = sqlite3PageMalloc( pBt->pageSize );
drhc890fec2008-08-01 20:10:08 +00007108 if( hit==0 ){
7109 pCheck->mallocFailed = 1;
7110 }else{
shane5780ebd2008-11-11 17:36:30 +00007111 u16 contentOffset = get2byte(&data[hdr+5]);
7112 if (contentOffset > usableSize) {
7113 checkAppendMsg(pCheck, 0,
7114 "Corruption detected in header on page %d",iPage,0);
shane0af3f892008-11-12 04:55:34 +00007115 goto check_page_abort;
shane5780ebd2008-11-11 17:36:30 +00007116 }
7117 memset(hit+contentOffset, 0, usableSize-contentOffset);
7118 memset(hit, 1, contentOffset);
drh2e38c322004-09-03 18:38:44 +00007119 nCell = get2byte(&data[hdr+3]);
7120 cellStart = hdr + 12 - 4*pPage->leaf;
7121 for(i=0; i<nCell; i++){
7122 int pc = get2byte(&data[cellStart+i*2]);
danielk1977daca5432008-08-25 11:57:16 +00007123 u16 size = 1024;
drh2e38c322004-09-03 18:38:44 +00007124 int j;
danielk1977daca5432008-08-25 11:57:16 +00007125 if( pc<=usableSize ){
7126 size = cellSizePtr(pPage, &data[pc]);
7127 }
danielk19777701e812005-01-10 12:59:51 +00007128 if( (pc+size-1)>=usableSize || pc<0 ){
7129 checkAppendMsg(pCheck, 0,
7130 "Corruption detected in cell %d on page %d",i,iPage,0);
7131 }else{
7132 for(j=pc+size-1; j>=pc; j--) hit[j]++;
7133 }
drh2e38c322004-09-03 18:38:44 +00007134 }
7135 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
7136 cnt++){
7137 int size = get2byte(&data[i+2]);
7138 int j;
danielk19777701e812005-01-10 12:59:51 +00007139 if( (i+size-1)>=usableSize || i<0 ){
7140 checkAppendMsg(pCheck, 0,
7141 "Corruption detected in cell %d on page %d",i,iPage,0);
7142 }else{
7143 for(j=i+size-1; j>=i; j--) hit[j]++;
7144 }
drh2e38c322004-09-03 18:38:44 +00007145 i = get2byte(&data[i]);
7146 }
7147 for(i=cnt=0; i<usableSize; i++){
7148 if( hit[i]==0 ){
7149 cnt++;
7150 }else if( hit[i]>1 ){
7151 checkAppendMsg(pCheck, 0,
7152 "Multiple uses for byte %d of page %d", i, iPage);
7153 break;
7154 }
7155 }
7156 if( cnt!=data[hdr+7] ){
7157 checkAppendMsg(pCheck, 0,
7158 "Fragmented space is %d byte reported as %d on page %d",
7159 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00007160 }
7161 }
shane0af3f892008-11-12 04:55:34 +00007162check_page_abort:
7163 if (hit) sqlite3PageFree(hit);
drh6019e162001-07-02 17:51:45 +00007164
drh4b70f112004-05-02 21:12:19 +00007165 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00007166 return depth+1;
drh5eddca62001-06-30 21:53:53 +00007167}
drhb7f91642004-10-31 02:22:47 +00007168#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00007169
drhb7f91642004-10-31 02:22:47 +00007170#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007171/*
7172** This routine does a complete check of the given BTree file. aRoot[] is
7173** an array of pages numbers were each page number is the root page of
7174** a table. nRoot is the number of entries in aRoot.
7175**
drhc890fec2008-08-01 20:10:08 +00007176** Write the number of error seen in *pnErr. Except for some memory
drhe43ba702008-12-05 22:40:08 +00007177** allocation errors, an error message held in memory obtained from
drhc890fec2008-08-01 20:10:08 +00007178** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
drhe43ba702008-12-05 22:40:08 +00007179** returned. If a memory allocation error occurs, NULL is returned.
drh5eddca62001-06-30 21:53:53 +00007180*/
drh1dcdbc02007-01-27 02:24:54 +00007181char *sqlite3BtreeIntegrityCheck(
7182 Btree *p, /* The btree to be checked */
7183 int *aRoot, /* An array of root pages numbers for individual trees */
7184 int nRoot, /* Number of entries in aRoot[] */
7185 int mxErr, /* Stop reporting errors after this many */
7186 int *pnErr /* Write number of errors seen to this variable */
7187){
danielk197789d40042008-11-17 14:20:56 +00007188 Pgno i;
drh5eddca62001-06-30 21:53:53 +00007189 int nRef;
drhaaab5722002-02-19 13:39:21 +00007190 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00007191 BtShared *pBt = p->pBt;
drhf089aa42008-07-08 19:34:06 +00007192 char zErr[100];
drh5eddca62001-06-30 21:53:53 +00007193
drhd677b3d2007-08-20 22:48:41 +00007194 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00007195 pBt->db = p->db;
danielk19773b8a05f2007-03-19 17:44:26 +00007196 nRef = sqlite3PagerRefcount(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00007197 if( lockBtreeWithRetry(p)!=SQLITE_OK ){
drhc890fec2008-08-01 20:10:08 +00007198 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00007199 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00007200 return sqlite3DbStrDup(0, "cannot acquire a read lock on the database");
drhefc251d2001-07-01 22:12:01 +00007201 }
drh5eddca62001-06-30 21:53:53 +00007202 sCheck.pBt = pBt;
7203 sCheck.pPager = pBt->pPager;
danielk197789d40042008-11-17 14:20:56 +00007204 sCheck.nPage = pagerPagecount(sCheck.pBt);
drh1dcdbc02007-01-27 02:24:54 +00007205 sCheck.mxErr = mxErr;
7206 sCheck.nErr = 0;
drhc890fec2008-08-01 20:10:08 +00007207 sCheck.mallocFailed = 0;
drh1dcdbc02007-01-27 02:24:54 +00007208 *pnErr = 0;
drh0de8c112002-07-06 16:32:14 +00007209 if( sCheck.nPage==0 ){
7210 unlockBtreeIfUnused(pBt);
drhd677b3d2007-08-20 22:48:41 +00007211 sqlite3BtreeLeave(p);
drh0de8c112002-07-06 16:32:14 +00007212 return 0;
7213 }
drhe5ae5732008-06-15 02:51:47 +00007214 sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00007215 if( !sCheck.anRef ){
7216 unlockBtreeIfUnused(pBt);
drh1dcdbc02007-01-27 02:24:54 +00007217 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00007218 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00007219 return 0;
danielk1977ac245ec2005-01-14 13:50:11 +00007220 }
drhda200cc2004-05-09 11:51:38 +00007221 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00007222 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00007223 if( i<=sCheck.nPage ){
7224 sCheck.anRef[i] = 1;
7225 }
drhf089aa42008-07-08 19:34:06 +00007226 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
drh5eddca62001-06-30 21:53:53 +00007227
7228 /* Check the integrity of the freelist
7229 */
drha34b6762004-05-07 13:30:42 +00007230 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
7231 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00007232
7233 /* Check all the tables.
7234 */
danielk197789d40042008-11-17 14:20:56 +00007235 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
drh4ff6dfa2002-03-03 23:06:00 +00007236 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00007237#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00007238 if( pBt->autoVacuum && aRoot[i]>1 ){
7239 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
7240 }
7241#endif
danielk197762c14b32008-11-19 09:05:26 +00007242 checkTreePage(&sCheck, aRoot[i], "List of tree roots: ");
drh5eddca62001-06-30 21:53:53 +00007243 }
7244
7245 /* Make sure every page in the file is referenced
7246 */
drh1dcdbc02007-01-27 02:24:54 +00007247 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00007248#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00007249 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00007250 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00007251 }
danielk1977afcdd022004-10-31 16:25:42 +00007252#else
7253 /* If the database supports auto-vacuum, make sure no tables contain
7254 ** references to pointer-map pages.
7255 */
7256 if( sCheck.anRef[i]==0 &&
danielk1977266664d2006-02-10 08:24:21 +00007257 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00007258 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
7259 }
7260 if( sCheck.anRef[i]!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00007261 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00007262 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
7263 }
7264#endif
drh5eddca62001-06-30 21:53:53 +00007265 }
7266
drh64022502009-01-09 14:11:04 +00007267 /* Make sure this analysis did not leave any unref() pages.
7268 ** This is an internal consistency check; an integrity check
7269 ** of the integrity check.
drh5eddca62001-06-30 21:53:53 +00007270 */
drh5e00f6c2001-09-13 13:46:56 +00007271 unlockBtreeIfUnused(pBt);
drh64022502009-01-09 14:11:04 +00007272 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
drh2e38c322004-09-03 18:38:44 +00007273 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00007274 "Outstanding page count goes from %d to %d during this analysis",
danielk19773b8a05f2007-03-19 17:44:26 +00007275 nRef, sqlite3PagerRefcount(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00007276 );
drh5eddca62001-06-30 21:53:53 +00007277 }
7278
7279 /* Clean up and report errors.
7280 */
drhd677b3d2007-08-20 22:48:41 +00007281 sqlite3BtreeLeave(p);
drh17435752007-08-16 04:30:38 +00007282 sqlite3_free(sCheck.anRef);
drhc890fec2008-08-01 20:10:08 +00007283 if( sCheck.mallocFailed ){
7284 sqlite3StrAccumReset(&sCheck.errMsg);
7285 *pnErr = sCheck.nErr+1;
7286 return 0;
7287 }
drh1dcdbc02007-01-27 02:24:54 +00007288 *pnErr = sCheck.nErr;
drhf089aa42008-07-08 19:34:06 +00007289 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
7290 return sqlite3StrAccumFinish(&sCheck.errMsg);
drh5eddca62001-06-30 21:53:53 +00007291}
drhb7f91642004-10-31 02:22:47 +00007292#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00007293
drh73509ee2003-04-06 20:44:45 +00007294/*
7295** Return the full pathname of the underlying database file.
drhd0679ed2007-08-28 22:24:34 +00007296**
7297** The pager filename is invariant as long as the pager is
7298** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +00007299*/
danielk1977aef0bf62005-12-30 16:28:01 +00007300const char *sqlite3BtreeGetFilename(Btree *p){
7301 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007302 return sqlite3PagerFilename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00007303}
7304
7305/*
danielk19775865e3d2004-06-14 06:03:57 +00007306** Return the pathname of the journal file for this database. The return
7307** value of this routine is the same regardless of whether the journal file
7308** has been created or not.
drhd0679ed2007-08-28 22:24:34 +00007309**
7310** The pager journal filename is invariant as long as the pager is
7311** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00007312*/
danielk1977aef0bf62005-12-30 16:28:01 +00007313const char *sqlite3BtreeGetJournalname(Btree *p){
7314 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007315 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00007316}
7317
danielk19771d850a72004-05-31 08:26:49 +00007318/*
7319** Return non-zero if a transaction is active.
7320*/
danielk1977aef0bf62005-12-30 16:28:01 +00007321int sqlite3BtreeIsInTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00007322 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00007323 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00007324}
7325
7326/*
7327** Return non-zero if a statement transaction is active.
7328*/
danielk1977aef0bf62005-12-30 16:28:01 +00007329int sqlite3BtreeIsInStmt(Btree *p){
drh1fee73e2007-08-29 04:00:57 +00007330 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00007331 return ALWAYS(p->pBt) && p->pBt->inStmt;
danielk19771d850a72004-05-31 08:26:49 +00007332}
danielk197713adf8a2004-06-03 16:08:41 +00007333
7334/*
danielk19772372c2b2006-06-27 16:34:56 +00007335** Return non-zero if a read (or write) transaction is active.
7336*/
7337int sqlite3BtreeIsInReadTrans(Btree *p){
drh64022502009-01-09 14:11:04 +00007338 assert( p );
drhe5fe6902007-12-07 18:55:28 +00007339 assert( sqlite3_mutex_held(p->db->mutex) );
drh64022502009-01-09 14:11:04 +00007340 return p->inTrans!=TRANS_NONE;
danielk19772372c2b2006-06-27 16:34:56 +00007341}
7342
danielk197704103022009-02-03 16:51:24 +00007343int sqlite3BtreeIsInBackup(Btree *p){
7344 assert( p );
7345 assert( sqlite3_mutex_held(p->db->mutex) );
7346 return p->nBackup!=0;
7347}
7348
danielk19772372c2b2006-06-27 16:34:56 +00007349/*
danielk1977da184232006-01-05 11:34:32 +00007350** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +00007351** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +00007352** purposes (for example, to store a high-level schema associated with
7353** the shared-btree). The btree layer manages reference counting issues.
7354**
7355** The first time this is called on a shared-btree, nBytes bytes of memory
7356** are allocated, zeroed, and returned to the caller. For each subsequent
7357** call the nBytes parameter is ignored and a pointer to the same blob
7358** of memory returned.
7359**
danielk1977171bfed2008-06-23 09:50:50 +00007360** If the nBytes parameter is 0 and the blob of memory has not yet been
7361** allocated, a null pointer is returned. If the blob has already been
7362** allocated, it is returned as normal.
7363**
danielk1977da184232006-01-05 11:34:32 +00007364** Just before the shared-btree is closed, the function passed as the
7365** xFree argument when the memory allocation was made is invoked on the
drh17435752007-08-16 04:30:38 +00007366** blob of allocated memory. This function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +00007367** on the memory, the btree layer does that.
7368*/
7369void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
7370 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +00007371 sqlite3BtreeEnter(p);
danielk1977171bfed2008-06-23 09:50:50 +00007372 if( !pBt->pSchema && nBytes ){
drh17435752007-08-16 04:30:38 +00007373 pBt->pSchema = sqlite3MallocZero(nBytes);
danielk1977da184232006-01-05 11:34:32 +00007374 pBt->xFreeSchema = xFree;
7375 }
drh27641702007-08-22 02:56:42 +00007376 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00007377 return pBt->pSchema;
7378}
7379
danielk1977c87d34d2006-01-06 13:00:28 +00007380/*
7381** Return true if another user of the same shared btree as the argument
7382** handle holds an exclusive lock on the sqlite_master table.
7383*/
7384int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +00007385 int rc;
drhe5fe6902007-12-07 18:55:28 +00007386 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +00007387 sqlite3BtreeEnter(p);
drhc25eabe2009-02-24 18:57:31 +00007388 rc = (querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
drh27641702007-08-22 02:56:42 +00007389 sqlite3BtreeLeave(p);
7390 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +00007391}
7392
drha154dcd2006-03-22 22:10:07 +00007393
7394#ifndef SQLITE_OMIT_SHARED_CACHE
7395/*
7396** Obtain a lock on the table whose root page is iTab. The
7397** lock is a write lock if isWritelock is true or a read lock
7398** if it is false.
7399*/
danielk1977c00da102006-01-07 13:21:04 +00007400int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00007401 int rc = SQLITE_OK;
drh6a9ad3d2008-04-02 16:29:30 +00007402 if( p->sharable ){
7403 u8 lockType = READ_LOCK + isWriteLock;
7404 assert( READ_LOCK+1==WRITE_LOCK );
7405 assert( isWriteLock==0 || isWriteLock==1 );
7406 sqlite3BtreeEnter(p);
drhc25eabe2009-02-24 18:57:31 +00007407 rc = querySharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00007408 if( rc==SQLITE_OK ){
drhc25eabe2009-02-24 18:57:31 +00007409 rc = setSharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00007410 }
7411 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +00007412 }
7413 return rc;
7414}
drha154dcd2006-03-22 22:10:07 +00007415#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00007416
danielk1977b4e9af92007-05-01 17:49:49 +00007417#ifndef SQLITE_OMIT_INCRBLOB
7418/*
7419** Argument pCsr must be a cursor opened for writing on an
7420** INTKEY table currently pointing at a valid table entry.
7421** This function modifies the data stored as part of that entry.
7422** Only the data content may only be modified, it is not possible
7423** to change the length of the data stored.
7424*/
danielk1977dcbb5d32007-05-04 18:36:44 +00007425int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
drh1fee73e2007-08-29 04:00:57 +00007426 assert( cursorHoldsMutex(pCsr) );
drhe5fe6902007-12-07 18:55:28 +00007427 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00007428 assert(pCsr->isIncrblobHandle);
danielk19773588ceb2008-06-10 17:30:26 +00007429
drha3460582008-07-11 21:02:53 +00007430 restoreCursorPosition(pCsr);
danielk19773588ceb2008-06-10 17:30:26 +00007431 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
7432 if( pCsr->eState!=CURSOR_VALID ){
7433 return SQLITE_ABORT;
danielk1977dcbb5d32007-05-04 18:36:44 +00007434 }
7435
danielk1977d04417962007-05-02 13:16:30 +00007436 /* Check some preconditions:
danielk1977dcbb5d32007-05-04 18:36:44 +00007437 ** (a) the cursor is open for writing,
7438 ** (b) there is no read-lock on the table being modified and
7439 ** (c) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00007440 */
danielk1977d04417962007-05-02 13:16:30 +00007441 if( !pCsr->wrFlag ){
danielk1977dcbb5d32007-05-04 18:36:44 +00007442 return SQLITE_READONLY;
danielk1977d04417962007-05-02 13:16:30 +00007443 }
drhd0679ed2007-08-28 22:24:34 +00007444 assert( !pCsr->pBt->readOnly
7445 && pCsr->pBt->inTransaction==TRANS_WRITE );
danielk19773588ceb2008-06-10 17:30:26 +00007446 if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr, 0) ){
danielk1977d04417962007-05-02 13:16:30 +00007447 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
7448 }
danielk197771d5d2c2008-09-29 11:49:47 +00007449 if( pCsr->eState==CURSOR_INVALID || !pCsr->apPage[pCsr->iPage]->intKey ){
danielk1977d04417962007-05-02 13:16:30 +00007450 return SQLITE_ERROR;
danielk1977b4e9af92007-05-01 17:49:49 +00007451 }
7452
danielk19779f8d6402007-05-02 17:48:45 +00007453 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00007454}
danielk19772dec9702007-05-02 16:48:37 +00007455
7456/*
7457** Set a flag on this cursor to cache the locations of pages from the
danielk1977da107192007-05-04 08:32:13 +00007458** overflow list for the current row. This is used by cursors opened
7459** for incremental blob IO only.
7460**
7461** This function sets a flag only. The actual page location cache
7462** (stored in BtCursor.aOverflow[]) is allocated and used by function
7463** accessPayload() (the worker function for sqlite3BtreeData() and
7464** sqlite3BtreePutData()).
danielk19772dec9702007-05-02 16:48:37 +00007465*/
7466void sqlite3BtreeCacheOverflow(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00007467 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00007468 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00007469 assert(!pCur->isIncrblobHandle);
danielk19772dec9702007-05-02 16:48:37 +00007470 assert(!pCur->aOverflow);
danielk1977dcbb5d32007-05-04 18:36:44 +00007471 pCur->isIncrblobHandle = 1;
danielk19772dec9702007-05-02 16:48:37 +00007472}
danielk1977b4e9af92007-05-01 17:49:49 +00007473#endif