blob: a51ed1b7826eed62afa21092ace0ba166cc4bbbe [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*************************************************************************
danielk197785d90ca2008-07-19 14:25:15 +000012** $Id: btree.c,v 1.491 2008/07/19 14:25:16 danielk1977 Exp $
drh8b2f49b2001-06-08 00:21:52 +000013**
14** This file implements a external (disk-based) database using BTrees.
drha3152892007-05-05 11:48:52 +000015** See the header comment on "btreeInt.h" for additional information.
16** Including a description of file format and an overview of operation.
drha059ad02001-04-17 20:09:11 +000017*/
drha3152892007-05-05 11:48:52 +000018#include "btreeInt.h"
paulb95a8862003-04-01 21:16:41 +000019
drh8c42ca92001-06-22 19:15:00 +000020/*
drha3152892007-05-05 11:48:52 +000021** The header string that appears at the beginning of every
22** SQLite database.
drh556b2a22005-06-14 16:04:05 +000023*/
drh556b2a22005-06-14 16:04:05 +000024static const char zMagicHeader[] = SQLITE_FILE_HEADER;
drh08ed44e2001-04-29 23:32:55 +000025
drh8c42ca92001-06-22 19:15:00 +000026/*
drha3152892007-05-05 11:48:52 +000027** Set this global variable to 1 to enable tracing using the TRACE
28** macro.
drh615ae552005-01-16 23:21:00 +000029*/
drhe8f52c52008-07-12 14:52:20 +000030#if 0
mlcreech3a00f902008-03-04 17:45:01 +000031int sqlite3BtreeTrace=0; /* True to enable tracing */
drhe8f52c52008-07-12 14:52:20 +000032# define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
33#else
34# define TRACE(X)
drh615ae552005-01-16 23:21:00 +000035#endif
drh615ae552005-01-16 23:21:00 +000036
drh86f8c192007-08-22 00:39:19 +000037
38
drhe53831d2007-08-17 01:14:38 +000039#ifndef SQLITE_OMIT_SHARED_CACHE
40/*
41** A flag to indicate whether or not shared cache is enabled. Also,
42** a list of BtShared objects that are eligible for participation
drhd677b3d2007-08-20 22:48:41 +000043** in shared cache. The variables have file scope during normal builds,
drh86f8c192007-08-22 00:39:19 +000044** but the test harness needs to access these variables so we make them
drhd677b3d2007-08-20 22:48:41 +000045** global for test builds.
drhe53831d2007-08-17 01:14:38 +000046*/
47#ifdef SQLITE_TEST
48BtShared *sqlite3SharedCacheList = 0;
49int sqlite3SharedCacheEnabled = 0;
50#else
51static BtShared *sqlite3SharedCacheList = 0;
52static int sqlite3SharedCacheEnabled = 0;
53#endif
drhe53831d2007-08-17 01:14:38 +000054#endif /* SQLITE_OMIT_SHARED_CACHE */
55
56#ifndef SQLITE_OMIT_SHARED_CACHE
57/*
58** Enable or disable the shared pager and schema features.
59**
60** This routine has no effect on existing database connections.
61** The shared cache setting effects only future calls to
62** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
63*/
64int sqlite3_enable_shared_cache(int enable){
65 sqlite3SharedCacheEnabled = enable;
66 return SQLITE_OK;
67}
68#endif
69
drhd677b3d2007-08-20 22:48:41 +000070
drh615ae552005-01-16 23:21:00 +000071/*
drh66cbd152004-09-01 16:12:25 +000072** Forward declaration
73*/
danielk19773588ceb2008-06-10 17:30:26 +000074static int checkReadLocks(Btree*, Pgno, BtCursor*, i64);
drh66cbd152004-09-01 16:12:25 +000075
danielk1977aef0bf62005-12-30 16:28:01 +000076
77#ifdef SQLITE_OMIT_SHARED_CACHE
78 /*
79 ** The functions queryTableLock(), lockTable() and unlockAllTables()
80 ** manipulate entries in the BtShared.pLock linked list used to store
81 ** shared-cache table level locks. If the library is compiled with the
82 ** shared-cache feature disabled, then there is only ever one user
danielk1977da184232006-01-05 11:34:32 +000083 ** of each BtShared structure and so this locking is not necessary.
84 ** So define the lock related functions as no-ops.
danielk1977aef0bf62005-12-30 16:28:01 +000085 */
86 #define queryTableLock(a,b,c) SQLITE_OK
87 #define lockTable(a,b,c) SQLITE_OK
danielk1977da184232006-01-05 11:34:32 +000088 #define unlockAllTables(a)
drhe53831d2007-08-17 01:14:38 +000089#endif
danielk1977aef0bf62005-12-30 16:28:01 +000090
drhe53831d2007-08-17 01:14:38 +000091#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977da184232006-01-05 11:34:32 +000092/*
danielk1977aef0bf62005-12-30 16:28:01 +000093** Query to see if btree handle p may obtain a lock of type eLock
94** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
95** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
danielk1977c87d34d2006-01-06 13:00:28 +000096** SQLITE_LOCKED if not.
danielk1977aef0bf62005-12-30 16:28:01 +000097*/
98static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
99 BtShared *pBt = p->pBt;
100 BtLock *pIter;
101
drh1fee73e2007-08-29 04:00:57 +0000102 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000103 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
104 assert( p->db!=0 );
drhd677b3d2007-08-20 22:48:41 +0000105
danielk1977da184232006-01-05 11:34:32 +0000106 /* This is a no-op if the shared-cache is not enabled */
drhe53831d2007-08-17 01:14:38 +0000107 if( !p->sharable ){
danielk1977da184232006-01-05 11:34:32 +0000108 return SQLITE_OK;
109 }
110
danielk1977641b0f42007-12-21 04:47:25 +0000111 /* If some other connection is holding an exclusive lock, the
112 ** requested lock may not be obtained.
113 */
114 if( pBt->pExclusive && pBt->pExclusive!=p ){
115 return SQLITE_LOCKED;
116 }
117
danielk1977da184232006-01-05 11:34:32 +0000118 /* This (along with lockTable()) is where the ReadUncommitted flag is
119 ** dealt with. If the caller is querying for a read-lock and the flag is
120 ** set, it is unconditionally granted - even if there are write-locks
121 ** on the table. If a write-lock is requested, the ReadUncommitted flag
122 ** is not considered.
123 **
124 ** In function lockTable(), if a read-lock is demanded and the
125 ** ReadUncommitted flag is set, no entry is added to the locks list
126 ** (BtShared.pLock).
127 **
128 ** To summarize: If the ReadUncommitted flag is set, then read cursors do
129 ** not create or respect table locks. The locking procedure for a
130 ** write-cursor does not change.
131 */
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*/
157static int lockTable(Btree *p, Pgno iTable, u8 eLock){
158 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
danielk1977aef0bf62005-12-30 16:28:01 +0000171 assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
172
danielk1977da184232006-01-05 11:34:32 +0000173 /* If the read-uncommitted flag is set and a read-lock is requested,
174 ** return early without adding an entry to the BtShared.pLock list. See
175 ** comment in function queryTableLock() for more info on handling
176 ** the ReadUncommitted flag.
177 */
178 if(
drhe5fe6902007-12-07 18:55:28 +0000179 (p->db->flags&SQLITE_ReadUncommitted) &&
danielk1977da184232006-01-05 11:34:32 +0000180 (eLock==READ_LOCK) &&
drh47ded162006-01-06 01:42:58 +0000181 iTable!=MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000182 ){
183 return SQLITE_OK;
184 }
185
danielk1977aef0bf62005-12-30 16:28:01 +0000186 /* First search the list for an existing lock on this table. */
187 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
188 if( pIter->iTable==iTable && pIter->pBtree==p ){
189 pLock = pIter;
190 break;
191 }
192 }
193
194 /* If the above search did not find a BtLock struct associating Btree p
195 ** with table iTable, allocate one and link it into the list.
196 */
197 if( !pLock ){
drh17435752007-08-16 04:30:38 +0000198 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
danielk1977aef0bf62005-12-30 16:28:01 +0000199 if( !pLock ){
200 return SQLITE_NOMEM;
201 }
202 pLock->iTable = iTable;
203 pLock->pBtree = p;
204 pLock->pNext = pBt->pLock;
205 pBt->pLock = pLock;
206 }
207
208 /* Set the BtLock.eLock variable to the maximum of the current lock
209 ** and the requested lock. This means if a write-lock was already held
210 ** and a read-lock requested, we don't incorrectly downgrade the lock.
211 */
212 assert( WRITE_LOCK>READ_LOCK );
danielk19775118b912005-12-30 16:31:53 +0000213 if( eLock>pLock->eLock ){
214 pLock->eLock = eLock;
215 }
danielk1977aef0bf62005-12-30 16:28:01 +0000216
217 return SQLITE_OK;
218}
drhe53831d2007-08-17 01:14:38 +0000219#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000220
drhe53831d2007-08-17 01:14:38 +0000221#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000222/*
223** Release all the table locks (locks obtained via calls to the lockTable()
224** procedure) held by Btree handle p.
225*/
226static void unlockAllTables(Btree *p){
danielk1977641b0f42007-12-21 04:47:25 +0000227 BtShared *pBt = p->pBt;
228 BtLock **ppIter = &pBt->pLock;
danielk1977da184232006-01-05 11:34:32 +0000229
drh1fee73e2007-08-29 04:00:57 +0000230 assert( sqlite3BtreeHoldsMutex(p) );
drhe53831d2007-08-17 01:14:38 +0000231 assert( p->sharable || 0==*ppIter );
danielk1977da184232006-01-05 11:34:32 +0000232
danielk1977aef0bf62005-12-30 16:28:01 +0000233 while( *ppIter ){
234 BtLock *pLock = *ppIter;
danielk1977641b0f42007-12-21 04:47:25 +0000235 assert( pBt->pExclusive==0 || pBt->pExclusive==pLock->pBtree );
danielk1977aef0bf62005-12-30 16:28:01 +0000236 if( pLock->pBtree==p ){
237 *ppIter = pLock->pNext;
drh17435752007-08-16 04:30:38 +0000238 sqlite3_free(pLock);
danielk1977aef0bf62005-12-30 16:28:01 +0000239 }else{
240 ppIter = &pLock->pNext;
241 }
242 }
danielk1977641b0f42007-12-21 04:47:25 +0000243
244 if( pBt->pExclusive==p ){
245 pBt->pExclusive = 0;
246 }
danielk1977aef0bf62005-12-30 16:28:01 +0000247}
248#endif /* SQLITE_OMIT_SHARED_CACHE */
249
drh980b1a72006-08-16 16:42:48 +0000250static void releasePage(MemPage *pPage); /* Forward reference */
251
drh1fee73e2007-08-29 04:00:57 +0000252/*
253** Verify that the cursor holds a mutex on the BtShared
254*/
255#ifndef NDEBUG
256static int cursorHoldsMutex(BtCursor *p){
drhff0587c2007-08-29 17:43:19 +0000257 return sqlite3_mutex_held(p->pBt->mutex);
drh1fee73e2007-08-29 04:00:57 +0000258}
259#endif
260
261
danielk197792d4d7a2007-05-04 12:05:56 +0000262#ifndef SQLITE_OMIT_INCRBLOB
263/*
264** Invalidate the overflow page-list cache for cursor pCur, if any.
265*/
266static void invalidateOverflowCache(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000267 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000268 sqlite3_free(pCur->aOverflow);
danielk197792d4d7a2007-05-04 12:05:56 +0000269 pCur->aOverflow = 0;
270}
271
272/*
273** Invalidate the overflow page-list cache for all cursors opened
274** on the shared btree structure pBt.
275*/
276static void invalidateAllOverflowCache(BtShared *pBt){
277 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000278 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +0000279 for(p=pBt->pCursor; p; p=p->pNext){
280 invalidateOverflowCache(p);
281 }
282}
283#else
284 #define invalidateOverflowCache(x)
285 #define invalidateAllOverflowCache(x)
286#endif
287
drh980b1a72006-08-16 16:42:48 +0000288/*
289** Save the current cursor position in the variables BtCursor.nKey
290** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
291*/
292static int saveCursorPosition(BtCursor *pCur){
293 int rc;
294
295 assert( CURSOR_VALID==pCur->eState );
296 assert( 0==pCur->pKey );
drh1fee73e2007-08-29 04:00:57 +0000297 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000298
299 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
300
301 /* If this is an intKey table, then the above call to BtreeKeySize()
302 ** stores the integer key in pCur->nKey. In this case this value is
303 ** all that is required. Otherwise, if pCur is not open on an intKey
304 ** table, then malloc space for and store the pCur->nKey bytes of key
305 ** data.
306 */
307 if( rc==SQLITE_OK && 0==pCur->pPage->intKey){
drhe5ae5732008-06-15 02:51:47 +0000308 void *pKey = sqlite3Malloc(pCur->nKey);
drh980b1a72006-08-16 16:42:48 +0000309 if( pKey ){
310 rc = sqlite3BtreeKey(pCur, 0, pCur->nKey, pKey);
311 if( rc==SQLITE_OK ){
312 pCur->pKey = pKey;
313 }else{
drh17435752007-08-16 04:30:38 +0000314 sqlite3_free(pKey);
drh980b1a72006-08-16 16:42:48 +0000315 }
316 }else{
317 rc = SQLITE_NOMEM;
318 }
319 }
320 assert( !pCur->pPage->intKey || !pCur->pKey );
321
322 if( rc==SQLITE_OK ){
323 releasePage(pCur->pPage);
324 pCur->pPage = 0;
325 pCur->eState = CURSOR_REQUIRESEEK;
326 }
327
danielk197792d4d7a2007-05-04 12:05:56 +0000328 invalidateOverflowCache(pCur);
drh980b1a72006-08-16 16:42:48 +0000329 return rc;
330}
331
332/*
333** Save the positions of all cursors except pExcept open on the table
334** with root-page iRoot. Usually, this is called just before cursor
335** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
336*/
337static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
338 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000339 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +0000340 assert( pExcept==0 || pExcept->pBt==pBt );
drh980b1a72006-08-16 16:42:48 +0000341 for(p=pBt->pCursor; p; p=p->pNext){
342 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
343 p->eState==CURSOR_VALID ){
344 int rc = saveCursorPosition(p);
345 if( SQLITE_OK!=rc ){
346 return rc;
347 }
348 }
349 }
350 return SQLITE_OK;
351}
352
353/*
drhbf700f32007-03-31 02:36:44 +0000354** Clear the current cursor position.
355*/
356static void clearCursorPosition(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000357 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000358 sqlite3_free(pCur->pKey);
drhbf700f32007-03-31 02:36:44 +0000359 pCur->pKey = 0;
360 pCur->eState = CURSOR_INVALID;
361}
362
363/*
drh980b1a72006-08-16 16:42:48 +0000364** Restore the cursor to the position it was in (or as close to as possible)
365** when saveCursorPosition() was called. Note that this call deletes the
366** saved position info stored by saveCursorPosition(), so there can be
drha3460582008-07-11 21:02:53 +0000367** at most one effective restoreCursorPosition() call after each
drh980b1a72006-08-16 16:42:48 +0000368** saveCursorPosition().
drh980b1a72006-08-16 16:42:48 +0000369*/
drha3460582008-07-11 21:02:53 +0000370int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +0000371 int rc;
drh1fee73e2007-08-29 04:00:57 +0000372 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +0000373 assert( pCur->eState>=CURSOR_REQUIRESEEK );
374 if( pCur->eState==CURSOR_FAULT ){
375 return pCur->skip;
376 }
drh980b1a72006-08-16 16:42:48 +0000377 pCur->eState = CURSOR_INVALID;
drhe14006d2008-03-25 17:23:32 +0000378 rc = sqlite3BtreeMoveto(pCur, pCur->pKey, 0, pCur->nKey, 0, &pCur->skip);
drh980b1a72006-08-16 16:42:48 +0000379 if( rc==SQLITE_OK ){
drh17435752007-08-16 04:30:38 +0000380 sqlite3_free(pCur->pKey);
drh980b1a72006-08-16 16:42:48 +0000381 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +0000382 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drh980b1a72006-08-16 16:42:48 +0000383 }
384 return rc;
385}
386
drha3460582008-07-11 21:02:53 +0000387#define restoreCursorPosition(p) \
drhfb982642007-08-30 01:19:59 +0000388 (p->eState>=CURSOR_REQUIRESEEK ? \
drha3460582008-07-11 21:02:53 +0000389 sqlite3BtreeRestoreCursorPosition(p) : \
drh16a9b832007-05-05 18:39:25 +0000390 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +0000391
drha3460582008-07-11 21:02:53 +0000392/*
393** Determine whether or not a cursor has moved from the position it
394** was last placed at. Cursor can move when the row they are pointing
395** at is deleted out from under them.
396**
397** This routine returns an error code if something goes wrong. The
398** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
399*/
400int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
401 int rc;
402
403 rc = restoreCursorPosition(pCur);
404 if( rc ){
405 *pHasMoved = 1;
406 return rc;
407 }
408 if( pCur->eState!=CURSOR_VALID || pCur->skip!=0 ){
409 *pHasMoved = 1;
410 }else{
411 *pHasMoved = 0;
412 }
413 return SQLITE_OK;
414}
415
danielk1977599fcba2004-11-08 07:13:13 +0000416#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000417/*
drha3152892007-05-05 11:48:52 +0000418** Given a page number of a regular database page, return the page
419** number for the pointer-map page that contains the entry for the
420** input page number.
danielk1977afcdd022004-10-31 16:25:42 +0000421*/
danielk1977266664d2006-02-10 08:24:21 +0000422static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
drhd677b3d2007-08-20 22:48:41 +0000423 int nPagesPerMapPage, iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +0000424 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000425 nPagesPerMapPage = (pBt->usableSize/5)+1;
426 iPtrMap = (pgno-2)/nPagesPerMapPage;
427 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +0000428 if( ret==PENDING_BYTE_PAGE(pBt) ){
429 ret++;
430 }
431 return ret;
432}
danielk1977a19df672004-11-03 11:37:07 +0000433
danielk1977afcdd022004-10-31 16:25:42 +0000434/*
danielk1977afcdd022004-10-31 16:25:42 +0000435** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000436**
437** This routine updates the pointer map entry for page number 'key'
438** so that it maps to type 'eType' and parent page number 'pgno'.
439** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000440*/
danielk1977aef0bf62005-12-30 16:28:01 +0000441static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
danielk19773b8a05f2007-03-19 17:44:26 +0000442 DbPage *pDbPage; /* The pointer map page */
443 u8 *pPtrmap; /* The pointer map data */
444 Pgno iPtrmap; /* The pointer map page number */
445 int offset; /* Offset in pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000446 int rc;
447
drh1fee73e2007-08-29 04:00:57 +0000448 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977266664d2006-02-10 08:24:21 +0000449 /* The master-journal page number must never be used as a pointer map page */
450 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
451
danielk1977ac11ee62005-01-15 12:45:51 +0000452 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000453 if( key==0 ){
drh49285702005-09-17 15:20:26 +0000454 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000455 }
danielk1977266664d2006-02-10 08:24:21 +0000456 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000457 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977687566d2004-11-02 12:56:41 +0000458 if( rc!=SQLITE_OK ){
danielk1977afcdd022004-10-31 16:25:42 +0000459 return rc;
460 }
danielk19778c666b12008-07-18 09:34:57 +0000461 offset = PTRMAP_PTROFFSET(iPtrmap, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000462 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000463
drh615ae552005-01-16 23:21:00 +0000464 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
465 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
danielk19773b8a05f2007-03-19 17:44:26 +0000466 rc = sqlite3PagerWrite(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000467 if( rc==SQLITE_OK ){
468 pPtrmap[offset] = eType;
469 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000470 }
danielk1977afcdd022004-10-31 16:25:42 +0000471 }
472
danielk19773b8a05f2007-03-19 17:44:26 +0000473 sqlite3PagerUnref(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000474 return rc;
danielk1977afcdd022004-10-31 16:25:42 +0000475}
476
477/*
478** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000479**
480** This routine retrieves the pointer map entry for page 'key', writing
481** the type and parent page number to *pEType and *pPgno respectively.
482** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000483*/
danielk1977aef0bf62005-12-30 16:28:01 +0000484static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +0000485 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000486 int iPtrmap; /* Pointer map page index */
487 u8 *pPtrmap; /* Pointer map page data */
488 int offset; /* Offset of entry in pointer map */
489 int rc;
490
drh1fee73e2007-08-29 04:00:57 +0000491 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000492
danielk1977266664d2006-02-10 08:24:21 +0000493 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000494 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000495 if( rc!=0 ){
496 return rc;
497 }
danielk19773b8a05f2007-03-19 17:44:26 +0000498 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000499
danielk19778c666b12008-07-18 09:34:57 +0000500 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drh43617e92006-03-06 20:55:46 +0000501 assert( pEType!=0 );
502 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +0000503 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000504
danielk19773b8a05f2007-03-19 17:44:26 +0000505 sqlite3PagerUnref(pDbPage);
drh49285702005-09-17 15:20:26 +0000506 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000507 return SQLITE_OK;
508}
509
danielk197785d90ca2008-07-19 14:25:15 +0000510#else /* if defined SQLITE_OMIT_AUTOVACUUM */
511 #define ptrmapPut(w,x,y,z) SQLITE_OK
512 #define ptrmapGet(w,x,y,z) SQLITE_OK
513 #define ptrmapPutOvfl(y,z) SQLITE_OK
514#endif
danielk1977afcdd022004-10-31 16:25:42 +0000515
drh0d316a42002-08-11 20:10:47 +0000516/*
drh271efa52004-05-30 19:19:05 +0000517** Given a btree page and a cell index (0 means the first cell on
518** the page, 1 means the second cell, and so forth) return a pointer
519** to the cell content.
520**
521** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000522*/
drh1688c862008-07-18 02:44:17 +0000523#define findCell(P,I) \
524 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
drh43605152004-05-29 21:46:49 +0000525
526/*
drh93a960a2008-07-10 00:32:42 +0000527** This a more complex version of findCell() that works for
drh43605152004-05-29 21:46:49 +0000528** pages that do contain overflow cells. See insert
529*/
530static u8 *findOverflowCell(MemPage *pPage, int iCell){
531 int i;
drh1fee73e2007-08-29 04:00:57 +0000532 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +0000533 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000534 int k;
535 struct _OvflCell *pOvfl;
536 pOvfl = &pPage->aOvfl[i];
537 k = pOvfl->idx;
538 if( k<=iCell ){
539 if( k==iCell ){
540 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000541 }
542 iCell--;
543 }
544 }
danielk19771cc5ed82007-05-16 17:28:43 +0000545 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000546}
547
548/*
549** Parse a cell content block and fill in the CellInfo structure. There
drh16a9b832007-05-05 18:39:25 +0000550** are two versions of this function. sqlite3BtreeParseCell() takes a
551** cell index as the second argument and sqlite3BtreeParseCellPtr()
552** takes a pointer to the body of the cell as its second argument.
danielk19771cc5ed82007-05-16 17:28:43 +0000553**
554** Within this file, the parseCell() macro can be called instead of
555** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
drh43605152004-05-29 21:46:49 +0000556*/
drh16a9b832007-05-05 18:39:25 +0000557void sqlite3BtreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000558 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000559 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000560 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000561){
drh271efa52004-05-30 19:19:05 +0000562 int n; /* Number bytes in cell content header */
563 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000564
drh1fee73e2007-08-29 04:00:57 +0000565 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000566
drh43605152004-05-29 21:46:49 +0000567 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000568 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000569 n = pPage->childPtrSize;
570 assert( n==4-4*pPage->leaf );
drh504b6982006-01-22 21:52:56 +0000571 if( pPage->intKey ){
drh79df1f42008-07-18 00:57:33 +0000572 if( pPage->hasData ){
573 n += getVarint32(&pCell[n], nPayload);
574 }else{
575 nPayload = 0;
576 }
577 n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
578 pInfo->nData = nPayload;
drh504b6982006-01-22 21:52:56 +0000579 }else{
drh79df1f42008-07-18 00:57:33 +0000580 pInfo->nData = 0;
581 n += getVarint32(&pCell[n], nPayload);
582 pInfo->nKey = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000583 }
drh72365832007-03-06 15:53:44 +0000584 pInfo->nPayload = nPayload;
drh504b6982006-01-22 21:52:56 +0000585 pInfo->nHeader = n;
drh79df1f42008-07-18 00:57:33 +0000586 if( likely(nPayload<=pPage->maxLocal) ){
drh271efa52004-05-30 19:19:05 +0000587 /* This is the (easy) common case where the entire payload fits
588 ** on the local page. No overflow is required.
589 */
590 int nSize; /* Total size of cell content in bytes */
drh79df1f42008-07-18 00:57:33 +0000591 nSize = nPayload + n;
drh6f11bef2004-05-13 01:12:56 +0000592 pInfo->nLocal = nPayload;
593 pInfo->iOverflow = 0;
drh79df1f42008-07-18 00:57:33 +0000594 if( (nSize & ~3)==0 ){
drh271efa52004-05-30 19:19:05 +0000595 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000596 }
drh271efa52004-05-30 19:19:05 +0000597 pInfo->nSize = nSize;
drh6f11bef2004-05-13 01:12:56 +0000598 }else{
drh271efa52004-05-30 19:19:05 +0000599 /* If the payload will not fit completely on the local page, we have
600 ** to decide how much to store locally and how much to spill onto
601 ** overflow pages. The strategy is to minimize the amount of unused
602 ** space on overflow pages while keeping the amount of local storage
603 ** in between minLocal and maxLocal.
604 **
605 ** Warning: changing the way overflow payload is distributed in any
606 ** way will result in an incompatible file format.
607 */
608 int minLocal; /* Minimum amount of payload held locally */
609 int maxLocal; /* Maximum amount of payload held locally */
610 int surplus; /* Overflow payload available for local storage */
611
612 minLocal = pPage->minLocal;
613 maxLocal = pPage->maxLocal;
614 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000615 if( surplus <= maxLocal ){
616 pInfo->nLocal = surplus;
617 }else{
618 pInfo->nLocal = minLocal;
619 }
620 pInfo->iOverflow = pInfo->nLocal + n;
621 pInfo->nSize = pInfo->iOverflow + 4;
622 }
drh3aac2dd2004-04-26 14:10:20 +0000623}
danielk19771cc5ed82007-05-16 17:28:43 +0000624#define parseCell(pPage, iCell, pInfo) \
625 sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
drh16a9b832007-05-05 18:39:25 +0000626void sqlite3BtreeParseCell(
drh43605152004-05-29 21:46:49 +0000627 MemPage *pPage, /* Page containing the cell */
628 int iCell, /* The cell index. First cell is 0 */
629 CellInfo *pInfo /* Fill in this structure */
630){
danielk19771cc5ed82007-05-16 17:28:43 +0000631 parseCell(pPage, iCell, pInfo);
drh43605152004-05-29 21:46:49 +0000632}
drh3aac2dd2004-04-26 14:10:20 +0000633
634/*
drh43605152004-05-29 21:46:49 +0000635** Compute the total number of bytes that a Cell needs in the cell
636** data area of the btree-page. The return number includes the cell
637** data header and the local payload, but not any overflow page or
638** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000639*/
danielk1977bc6ada42004-06-30 08:20:16 +0000640#ifndef NDEBUG
drha9121e42008-02-19 14:59:35 +0000641static u16 cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000642 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000643 sqlite3BtreeParseCell(pPage, iCell, &info);
drh43605152004-05-29 21:46:49 +0000644 return info.nSize;
645}
danielk1977bc6ada42004-06-30 08:20:16 +0000646#endif
drha9121e42008-02-19 14:59:35 +0000647static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
drh43605152004-05-29 21:46:49 +0000648 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000649 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000650 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000651}
652
danielk197779a40da2005-01-16 08:00:01 +0000653#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +0000654/*
danielk197726836652005-01-17 01:33:13 +0000655** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +0000656** to an overflow page, insert an entry into the pointer-map
657** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +0000658*/
danielk197726836652005-01-17 01:33:13 +0000659static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
drhfa67c3c2008-07-11 02:21:40 +0000660 CellInfo info;
661 assert( pCell!=0 );
662 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
663 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
664 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
665 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
666 return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +0000667 }
danielk197779a40da2005-01-16 08:00:01 +0000668 return SQLITE_OK;
danielk1977ac11ee62005-01-15 12:45:51 +0000669}
danielk197726836652005-01-17 01:33:13 +0000670/*
671** If the cell with index iCell on page pPage contains a pointer
672** to an overflow page, insert an entry into the pointer-map
673** for the overflow page.
674*/
675static int ptrmapPutOvfl(MemPage *pPage, int iCell){
676 u8 *pCell;
drh1fee73e2007-08-29 04:00:57 +0000677 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197726836652005-01-17 01:33:13 +0000678 pCell = findOverflowCell(pPage, iCell);
679 return ptrmapPutOvflPtr(pPage, pCell);
680}
danielk197779a40da2005-01-16 08:00:01 +0000681#endif
682
danielk1977ac11ee62005-01-15 12:45:51 +0000683
drhda200cc2004-05-09 11:51:38 +0000684/*
drh72f82862001-05-24 21:06:34 +0000685** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +0000686** end of the page and all free space is collected into one
687** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +0000688** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +0000689*/
danielk1977474b7cc2008-07-09 11:49:46 +0000690static void defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000691 int i; /* Loop counter */
692 int pc; /* Address of a i-th cell */
693 int addr; /* Offset of first byte after cell pointer array */
694 int hdr; /* Offset to the page header */
695 int size; /* Size of a cell */
696 int usableSize; /* Number of usable bytes on a page */
697 int cellOffset; /* Offset to the cell pointer array */
698 int brk; /* Offset to the cell content area */
699 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +0000700 unsigned char *data; /* The page data */
701 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +0000702
danielk19773b8a05f2007-03-19 17:44:26 +0000703 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000704 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +0000705 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000706 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +0000707 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh26b79942007-11-28 16:19:56 +0000708 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
drh43605152004-05-29 21:46:49 +0000709 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +0000710 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000711 cellOffset = pPage->cellOffset;
712 nCell = pPage->nCell;
713 assert( nCell==get2byte(&data[hdr+3]) );
714 usableSize = pPage->pBt->usableSize;
715 brk = get2byte(&data[hdr+5]);
716 memcpy(&temp[brk], &data[brk], usableSize - brk);
717 brk = usableSize;
718 for(i=0; i<nCell; i++){
719 u8 *pAddr; /* The i-th cell pointer */
720 pAddr = &data[cellOffset + i*2];
721 pc = get2byte(pAddr);
722 assert( pc<pPage->pBt->usableSize );
723 size = cellSizePtr(pPage, &temp[pc]);
724 brk -= size;
725 memcpy(&data[brk], &temp[pc], size);
726 put2byte(pAddr, brk);
drh2af926b2001-05-15 00:39:25 +0000727 }
drh43605152004-05-29 21:46:49 +0000728 assert( brk>=cellOffset+2*nCell );
729 put2byte(&data[hdr+5], brk);
730 data[hdr+1] = 0;
731 data[hdr+2] = 0;
732 data[hdr+7] = 0;
733 addr = cellOffset+2*nCell;
734 memset(&data[addr], 0, brk-addr);
drh365d68f2001-05-11 11:02:46 +0000735}
736
drha059ad02001-04-17 20:09:11 +0000737/*
drh43605152004-05-29 21:46:49 +0000738** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +0000739**
drh9e572e62004-04-23 23:43:10 +0000740** Return the index into pPage->aData[] of the first byte of
drhfa67c3c2008-07-11 02:21:40 +0000741** the new allocation. The caller guarantees that there is enough
742** space. This routine will never fail.
drh2af926b2001-05-15 00:39:25 +0000743**
drh72f82862001-05-24 21:06:34 +0000744** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000745** nBytes of contiguous free space, then this routine automatically
746** calls defragementPage() to consolidate all free space before
747** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000748*/
drh9e572e62004-04-23 23:43:10 +0000749static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +0000750 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +0000751 int size;
drh24cd67e2004-05-10 16:18:47 +0000752 int nFrag;
drh43605152004-05-29 21:46:49 +0000753 int top;
754 int nCell;
755 int cellOffset;
drh9e572e62004-04-23 23:43:10 +0000756 unsigned char *data;
drh43605152004-05-29 21:46:49 +0000757
drh9e572e62004-04-23 23:43:10 +0000758 data = pPage->aData;
danielk19773b8a05f2007-03-19 17:44:26 +0000759 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000760 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +0000761 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa67c3c2008-07-11 02:21:40 +0000762 assert( nByte>=0 ); /* Minimum cell size is 4 */
763 assert( pPage->nFree>=nByte );
764 assert( pPage->nOverflow==0 );
drh43605152004-05-29 21:46:49 +0000765 pPage->nFree -= nByte;
drh9e572e62004-04-23 23:43:10 +0000766 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000767
768 nFrag = data[hdr+7];
769 if( nFrag<60 ){
770 /* Search the freelist looking for a slot big enough to satisfy the
771 ** space request. */
772 addr = hdr+1;
773 while( (pc = get2byte(&data[addr]))>0 ){
774 size = get2byte(&data[pc+2]);
775 if( size>=nByte ){
776 if( size<nByte+4 ){
777 memcpy(&data[addr], &data[pc], 2);
778 data[hdr+7] = nFrag + size - nByte;
779 return pc;
780 }else{
781 put2byte(&data[pc+2], size-nByte);
782 return pc + size - nByte;
783 }
784 }
785 addr = pc;
drh9e572e62004-04-23 23:43:10 +0000786 }
787 }
drh43605152004-05-29 21:46:49 +0000788
789 /* Allocate memory from the gap in between the cell pointer array
790 ** and the cell content area.
791 */
792 top = get2byte(&data[hdr+5]);
793 nCell = get2byte(&data[hdr+3]);
794 cellOffset = pPage->cellOffset;
795 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
danielk1977474b7cc2008-07-09 11:49:46 +0000796 defragmentPage(pPage);
drh43605152004-05-29 21:46:49 +0000797 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +0000798 }
drh43605152004-05-29 21:46:49 +0000799 top -= nByte;
800 assert( cellOffset + 2*nCell <= top );
801 put2byte(&data[hdr+5], top);
802 return top;
drh7e3b0a02001-04-28 16:52:40 +0000803}
804
805/*
drh9e572e62004-04-23 23:43:10 +0000806** Return a section of the pPage->aData to the freelist.
807** The first byte of the new free block is pPage->aDisk[start]
808** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +0000809**
810** Most of the effort here is involved in coalesing adjacent
811** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000812*/
drh9e572e62004-04-23 23:43:10 +0000813static void freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +0000814 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +0000815 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +0000816
drh9e572e62004-04-23 23:43:10 +0000817 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +0000818 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000819 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +0000820 assert( (start + size)<=pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +0000821 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh34004ce2008-07-11 16:15:17 +0000822 assert( size>=0 ); /* Minimum cell size is 4 */
drh9e572e62004-04-23 23:43:10 +0000823
drhfcce93f2006-02-22 03:08:32 +0000824#ifdef SQLITE_SECURE_DELETE
825 /* Overwrite deleted information with zeros when the SECURE_DELETE
826 ** option is enabled at compile-time */
827 memset(&data[start], 0, size);
828#endif
829
drh9e572e62004-04-23 23:43:10 +0000830 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +0000831 hdr = pPage->hdrOffset;
832 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +0000833 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +0000834 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000835 assert( pbegin>addr );
836 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +0000837 }
drhb6f41482004-05-14 01:58:11 +0000838 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000839 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +0000840 put2byte(&data[addr], start);
841 put2byte(&data[start], pbegin);
842 put2byte(&data[start+2], size);
drh2af926b2001-05-15 00:39:25 +0000843 pPage->nFree += size;
drh9e572e62004-04-23 23:43:10 +0000844
845 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +0000846 addr = pPage->hdrOffset + 1;
847 while( (pbegin = get2byte(&data[addr]))>0 ){
drh9e572e62004-04-23 23:43:10 +0000848 int pnext, psize;
drh3aac2dd2004-04-26 14:10:20 +0000849 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +0000850 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +0000851 pnext = get2byte(&data[pbegin]);
852 psize = get2byte(&data[pbegin+2]);
853 if( pbegin + psize + 3 >= pnext && pnext>0 ){
854 int frag = pnext - (pbegin+psize);
drh43605152004-05-29 21:46:49 +0000855 assert( frag<=data[pPage->hdrOffset+7] );
856 data[pPage->hdrOffset+7] -= frag;
drh9e572e62004-04-23 23:43:10 +0000857 put2byte(&data[pbegin], get2byte(&data[pnext]));
858 put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
859 }else{
drh3aac2dd2004-04-26 14:10:20 +0000860 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +0000861 }
862 }
drh7e3b0a02001-04-28 16:52:40 +0000863
drh43605152004-05-29 21:46:49 +0000864 /* If the cell content area begins with a freeblock, remove it. */
865 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
866 int top;
867 pbegin = get2byte(&data[hdr+1]);
868 memcpy(&data[hdr+1], &data[pbegin], 2);
869 top = get2byte(&data[hdr+5]);
870 put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
drh4b70f112004-05-02 21:12:19 +0000871 }
drh4b70f112004-05-02 21:12:19 +0000872}
873
874/*
drh271efa52004-05-30 19:19:05 +0000875** Decode the flags byte (the first byte of the header) for a page
876** and initialize fields of the MemPage structure accordingly.
drh44845222008-07-17 18:39:57 +0000877**
878** Only the following combinations are supported. Anything different
879** indicates a corrupt database files:
880**
881** PTF_ZERODATA
882** PTF_ZERODATA | PTF_LEAF
883** PTF_LEAFDATA | PTF_INTKEY
884** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
drh271efa52004-05-30 19:19:05 +0000885*/
drh44845222008-07-17 18:39:57 +0000886static int decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +0000887 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +0000888
889 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +0000890 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh44845222008-07-17 18:39:57 +0000891 pPage->leaf = flagByte>>3; assert( PTF_LEAF == 1<<3 );
892 flagByte &= ~PTF_LEAF;
893 pPage->childPtrSize = 4-4*pPage->leaf;
drh271efa52004-05-30 19:19:05 +0000894 pBt = pPage->pBt;
drh44845222008-07-17 18:39:57 +0000895 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
896 pPage->intKey = 1;
897 pPage->hasData = pPage->leaf;
drh271efa52004-05-30 19:19:05 +0000898 pPage->maxLocal = pBt->maxLeaf;
899 pPage->minLocal = pBt->minLeaf;
drh44845222008-07-17 18:39:57 +0000900 }else if( flagByte==PTF_ZERODATA ){
901 pPage->intKey = 0;
902 pPage->hasData = 0;
drh271efa52004-05-30 19:19:05 +0000903 pPage->maxLocal = pBt->maxLocal;
904 pPage->minLocal = pBt->minLocal;
drh44845222008-07-17 18:39:57 +0000905 }else{
906 return SQLITE_CORRUPT_BKPT;
drh271efa52004-05-30 19:19:05 +0000907 }
drh44845222008-07-17 18:39:57 +0000908 return SQLITE_OK;
drh271efa52004-05-30 19:19:05 +0000909}
910
911/*
drh7e3b0a02001-04-28 16:52:40 +0000912** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000913**
drhbd03cae2001-06-02 02:40:57 +0000914** The pParent parameter must be a pointer to the MemPage which
drh9e572e62004-04-23 23:43:10 +0000915** is the parent of the page being initialized. The root of a
916** BTree has no parent and so for that page, pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000917**
drh72f82862001-05-24 21:06:34 +0000918** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +0000919** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +0000920** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
921** guarantee that the page is well-formed. It only shows that
922** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000923*/
drh16a9b832007-05-05 18:39:25 +0000924int sqlite3BtreeInitPage(
drh3aac2dd2004-04-26 14:10:20 +0000925 MemPage *pPage, /* The page to be initialized */
drh9e572e62004-04-23 23:43:10 +0000926 MemPage *pParent /* The parent. Might be NULL */
927){
drh271efa52004-05-30 19:19:05 +0000928 int pc; /* Address of a freeblock within pPage->aData[] */
drh271efa52004-05-30 19:19:05 +0000929 int hdr; /* Offset to beginning of page header */
930 u8 *data; /* Equal to pPage->aData */
danielk1977aef0bf62005-12-30 16:28:01 +0000931 BtShared *pBt; /* The main btree structure */
drh271efa52004-05-30 19:19:05 +0000932 int usableSize; /* Amount of usable space on each page */
933 int cellOffset; /* Offset from start of page to first cell pointer */
934 int nFree; /* Number of unused bytes on the page */
935 int top; /* First byte of the cell content area */
drh2af926b2001-05-15 00:39:25 +0000936
drh2e38c322004-09-03 18:38:44 +0000937 pBt = pPage->pBt;
938 assert( pBt!=0 );
939 assert( pParent==0 || pParent->pBt==pBt );
drh1fee73e2007-08-29 04:00:57 +0000940 assert( sqlite3_mutex_held(pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +0000941 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +0000942 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
943 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
drhee696e22004-08-30 16:52:17 +0000944 if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){
945 /* The parent page should never change unless the file is corrupt */
drh49285702005-09-17 15:20:26 +0000946 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000947 }
drh10617cd2004-05-14 15:27:27 +0000948 if( pPage->isInit ) return SQLITE_OK;
drhda200cc2004-05-09 11:51:38 +0000949 if( pPage->pParent==0 && pParent!=0 ){
950 pPage->pParent = pParent;
danielk19773b8a05f2007-03-19 17:44:26 +0000951 sqlite3PagerRef(pParent->pDbPage);
drh5e2f8b92001-05-28 00:41:15 +0000952 }
drhde647132004-05-07 17:57:49 +0000953 hdr = pPage->hdrOffset;
drha34b6762004-05-07 13:30:42 +0000954 data = pPage->aData;
drh44845222008-07-17 18:39:57 +0000955 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
drh1688c862008-07-18 02:44:17 +0000956 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
957 pPage->maskPage = pBt->pageSize - 1;
drh43605152004-05-29 21:46:49 +0000958 pPage->nOverflow = 0;
drhc8629a12004-05-08 20:07:40 +0000959 pPage->idxShift = 0;
drh2e38c322004-09-03 18:38:44 +0000960 usableSize = pBt->usableSize;
drh43605152004-05-29 21:46:49 +0000961 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
962 top = get2byte(&data[hdr+5]);
963 pPage->nCell = get2byte(&data[hdr+3]);
drh2e38c322004-09-03 18:38:44 +0000964 if( pPage->nCell>MX_CELL(pBt) ){
drhee696e22004-08-30 16:52:17 +0000965 /* To many cells for a single page. The page must be corrupt */
drh49285702005-09-17 15:20:26 +0000966 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000967 }
968 if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
969 /* All pages must have at least one cell, except for root pages */
drh49285702005-09-17 15:20:26 +0000970 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000971 }
drh9e572e62004-04-23 23:43:10 +0000972
973 /* Compute the total free space on the page */
drh9e572e62004-04-23 23:43:10 +0000974 pc = get2byte(&data[hdr+1]);
drh43605152004-05-29 21:46:49 +0000975 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
drh9e572e62004-04-23 23:43:10 +0000976 while( pc>0 ){
977 int next, size;
drhee696e22004-08-30 16:52:17 +0000978 if( pc>usableSize-4 ){
979 /* Free block is off the page */
drh49285702005-09-17 15:20:26 +0000980 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000981 }
drh9e572e62004-04-23 23:43:10 +0000982 next = get2byte(&data[pc]);
983 size = get2byte(&data[pc+2]);
drhee696e22004-08-30 16:52:17 +0000984 if( next>0 && next<=pc+size+3 ){
985 /* Free blocks must be in accending order */
drh49285702005-09-17 15:20:26 +0000986 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000987 }
drh3add3672004-05-15 00:29:24 +0000988 nFree += size;
drh9e572e62004-04-23 23:43:10 +0000989 pc = next;
990 }
drh3add3672004-05-15 00:29:24 +0000991 pPage->nFree = nFree;
drhee696e22004-08-30 16:52:17 +0000992 if( nFree>=usableSize ){
993 /* Free space cannot exceed total page size */
drh49285702005-09-17 15:20:26 +0000994 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000995 }
drh9e572e62004-04-23 23:43:10 +0000996
drh1688c862008-07-18 02:44:17 +0000997#if 0
998 /* Check that all the offsets in the cell offset array are within range.
999 **
1000 ** Omitting this consistency check and using the pPage->maskPage mask
1001 ** to prevent overrunning the page buffer in findCell() results in a
1002 ** 2.5% performance gain.
1003 */
1004 {
1005 u8 *pOff; /* Iterator used to check all cell offsets are in range */
1006 u8 *pEnd; /* Pointer to end of cell offset array */
1007 u8 mask; /* Mask of bits that must be zero in MSB of cell offsets */
1008 mask = ~(((u8)(pBt->pageSize>>8))-1);
1009 pEnd = &data[cellOffset + pPage->nCell*2];
1010 for(pOff=&data[cellOffset]; pOff!=pEnd && !((*pOff)&mask); pOff+=2);
1011 if( pOff!=pEnd ){
1012 return SQLITE_CORRUPT_BKPT;
1013 }
danielk1977e16535f2008-06-11 18:15:29 +00001014 }
drh1688c862008-07-18 02:44:17 +00001015#endif
danielk1977e16535f2008-06-11 18:15:29 +00001016
drhde647132004-05-07 17:57:49 +00001017 pPage->isInit = 1;
drh9e572e62004-04-23 23:43:10 +00001018 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001019}
1020
1021/*
drh8b2f49b2001-06-08 00:21:52 +00001022** Set up a raw page so that it looks like a database page holding
1023** no entries.
drhbd03cae2001-06-02 02:40:57 +00001024*/
drh9e572e62004-04-23 23:43:10 +00001025static void zeroPage(MemPage *pPage, int flags){
1026 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001027 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00001028 int hdr = pPage->hdrOffset;
drh9e572e62004-04-23 23:43:10 +00001029 int first;
1030
danielk19773b8a05f2007-03-19 17:44:26 +00001031 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drhbf4bca52007-09-06 22:19:14 +00001032 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1033 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +00001034 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00001035 assert( sqlite3_mutex_held(pBt->mutex) );
drh1af4a6e2008-07-18 03:32:51 +00001036 /*memset(&data[hdr], 0, pBt->usableSize - hdr);*/
drh9e572e62004-04-23 23:43:10 +00001037 data[hdr] = flags;
drh43605152004-05-29 21:46:49 +00001038 first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
1039 memset(&data[hdr+1], 0, 4);
1040 data[hdr+7] = 0;
1041 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +00001042 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +00001043 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +00001044 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +00001045 pPage->cellOffset = first;
1046 pPage->nOverflow = 0;
drh1688c862008-07-18 02:44:17 +00001047 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
1048 pPage->maskPage = pBt->pageSize - 1;
drhda200cc2004-05-09 11:51:38 +00001049 pPage->idxShift = 0;
drh43605152004-05-29 21:46:49 +00001050 pPage->nCell = 0;
drhda200cc2004-05-09 11:51:38 +00001051 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00001052}
1053
1054/*
drh3aac2dd2004-04-26 14:10:20 +00001055** Get a page from the pager. Initialize the MemPage.pBt and
1056** MemPage.aData elements if needed.
drh538f5702007-04-13 02:14:30 +00001057**
1058** If the noContent flag is set, it means that we do not care about
1059** the content of the page at this time. So do not go to the disk
1060** to fetch the content. Just fill in the content with zeros for now.
1061** If in the future we call sqlite3PagerWrite() on this page, that
1062** means we have started to be concerned about content and the disk
1063** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00001064*/
drh16a9b832007-05-05 18:39:25 +00001065int sqlite3BtreeGetPage(
1066 BtShared *pBt, /* The btree */
1067 Pgno pgno, /* Number of the page to fetch */
1068 MemPage **ppPage, /* Return the page in this parameter */
1069 int noContent /* Do not load page content if true */
1070){
drh3aac2dd2004-04-26 14:10:20 +00001071 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001072 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00001073 DbPage *pDbPage;
1074
drh1fee73e2007-08-29 04:00:57 +00001075 assert( sqlite3_mutex_held(pBt->mutex) );
drh538f5702007-04-13 02:14:30 +00001076 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
drh3aac2dd2004-04-26 14:10:20 +00001077 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001078 pPage = (MemPage *)sqlite3PagerGetExtra(pDbPage);
1079 pPage->aData = sqlite3PagerGetData(pDbPage);
1080 pPage->pDbPage = pDbPage;
drh3aac2dd2004-04-26 14:10:20 +00001081 pPage->pBt = pBt;
1082 pPage->pgno = pgno;
drhde647132004-05-07 17:57:49 +00001083 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
drh3aac2dd2004-04-26 14:10:20 +00001084 *ppPage = pPage;
1085 return SQLITE_OK;
1086}
1087
1088/*
drhde647132004-05-07 17:57:49 +00001089** Get a page from the pager and initialize it. This routine
1090** is just a convenience wrapper around separate calls to
drh16a9b832007-05-05 18:39:25 +00001091** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
drhde647132004-05-07 17:57:49 +00001092*/
1093static int getAndInitPage(
danielk1977aef0bf62005-12-30 16:28:01 +00001094 BtShared *pBt, /* The database file */
drhde647132004-05-07 17:57:49 +00001095 Pgno pgno, /* Number of the page to get */
1096 MemPage **ppPage, /* Write the page pointer here */
1097 MemPage *pParent /* Parent of the page */
1098){
1099 int rc;
drh1fee73e2007-08-29 04:00:57 +00001100 assert( sqlite3_mutex_held(pBt->mutex) );
drhee696e22004-08-30 16:52:17 +00001101 if( pgno==0 ){
drh49285702005-09-17 15:20:26 +00001102 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001103 }
drh16a9b832007-05-05 18:39:25 +00001104 rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
drh10617cd2004-05-14 15:27:27 +00001105 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
drh16a9b832007-05-05 18:39:25 +00001106 rc = sqlite3BtreeInitPage(*ppPage, pParent);
danielk197743e377a2008-05-05 12:09:32 +00001107 if( rc!=SQLITE_OK ){
1108 releasePage(*ppPage);
1109 *ppPage = 0;
1110 }
drhde647132004-05-07 17:57:49 +00001111 }
1112 return rc;
1113}
1114
1115/*
drh3aac2dd2004-04-26 14:10:20 +00001116** Release a MemPage. This should be called once for each prior
drh16a9b832007-05-05 18:39:25 +00001117** call to sqlite3BtreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +00001118*/
drh4b70f112004-05-02 21:12:19 +00001119static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001120 if( pPage ){
1121 assert( pPage->aData );
1122 assert( pPage->pBt );
drhbf4bca52007-09-06 22:19:14 +00001123 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1124 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
drh1fee73e2007-08-29 04:00:57 +00001125 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001126 sqlite3PagerUnref(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00001127 }
1128}
1129
1130/*
drh72f82862001-05-24 21:06:34 +00001131** This routine is called when the reference count for a page
1132** reaches zero. We need to unref the pParent pointer when that
1133** happens.
1134*/
danielk19773b8a05f2007-03-19 17:44:26 +00001135static void pageDestructor(DbPage *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +00001136 MemPage *pPage;
1137 assert( (pageSize & 7)==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001138 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
drh1fee73e2007-08-29 04:00:57 +00001139 assert( pPage->isInit==0 || sqlite3_mutex_held(pPage->pBt->mutex) );
drh72f82862001-05-24 21:06:34 +00001140 if( pPage->pParent ){
1141 MemPage *pParent = pPage->pParent;
drhd0679ed2007-08-28 22:24:34 +00001142 assert( pParent->pBt==pPage->pBt );
drh72f82862001-05-24 21:06:34 +00001143 pPage->pParent = 0;
drha34b6762004-05-07 13:30:42 +00001144 releasePage(pParent);
drh72f82862001-05-24 21:06:34 +00001145 }
drh3aac2dd2004-04-26 14:10:20 +00001146 pPage->isInit = 0;
drh72f82862001-05-24 21:06:34 +00001147}
1148
1149/*
drha6abd042004-06-09 17:37:22 +00001150** During a rollback, when the pager reloads information into the cache
1151** so that the cache is restored to its original state at the start of
1152** the transaction, for each page restored this routine is called.
1153**
1154** This routine needs to reset the extra data section at the end of the
1155** page to agree with the restored data.
1156*/
danielk19773b8a05f2007-03-19 17:44:26 +00001157static void pageReinit(DbPage *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +00001158 MemPage *pPage;
1159 assert( (pageSize & 7)==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001160 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
drha6abd042004-06-09 17:37:22 +00001161 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00001162 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00001163 pPage->isInit = 0;
drh16a9b832007-05-05 18:39:25 +00001164 sqlite3BtreeInitPage(pPage, pPage->pParent);
drha6abd042004-06-09 17:37:22 +00001165 }
1166}
1167
1168/*
drhe5fe6902007-12-07 18:55:28 +00001169** Invoke the busy handler for a btree.
1170*/
1171static int sqlite3BtreeInvokeBusyHandler(void *pArg, int n){
1172 BtShared *pBt = (BtShared*)pArg;
1173 assert( pBt->db );
1174 assert( sqlite3_mutex_held(pBt->db->mutex) );
1175 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
1176}
1177
1178/*
drhad3e0102004-09-03 23:32:18 +00001179** Open a database file.
1180**
drh382c0242001-10-06 16:33:02 +00001181** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001182** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001183** database file will be deleted when sqlite3BtreeClose() is called.
drhe53831d2007-08-17 01:14:38 +00001184** If zFilename is ":memory:" then an in-memory database is created
1185** that is automatically destroyed when it is closed.
drha059ad02001-04-17 20:09:11 +00001186*/
drh23e11ca2004-05-04 17:27:28 +00001187int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001188 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00001189 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001190 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00001191 int flags, /* Options */
1192 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00001193){
drhd677b3d2007-08-20 22:48:41 +00001194 sqlite3_vfs *pVfs; /* The VFS to use for this btree */
drhe53831d2007-08-17 01:14:38 +00001195 BtShared *pBt = 0; /* Shared part of btree structure */
danielk1977aef0bf62005-12-30 16:28:01 +00001196 Btree *p; /* Handle to return */
danielk1977dddbcdc2007-04-26 14:42:34 +00001197 int rc = SQLITE_OK;
drh90f5ecb2004-07-22 01:19:35 +00001198 int nReserve;
1199 unsigned char zDbHeader[100];
danielk1977aef0bf62005-12-30 16:28:01 +00001200
1201 /* Set the variable isMemdb to true for an in-memory database, or
1202 ** false for a file-based database. This symbol is only required if
1203 ** either of the shared-data or autovacuum features are compiled
1204 ** into the library.
1205 */
1206#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
1207 #ifdef SQLITE_OMIT_MEMORYDB
drh980b1a72006-08-16 16:42:48 +00001208 const int isMemdb = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00001209 #else
drh980b1a72006-08-16 16:42:48 +00001210 const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
danielk1977aef0bf62005-12-30 16:28:01 +00001211 #endif
1212#endif
1213
drhe5fe6902007-12-07 18:55:28 +00001214 assert( db!=0 );
1215 assert( sqlite3_mutex_held(db->mutex) );
drh153c62c2007-08-24 03:51:33 +00001216
drhe5fe6902007-12-07 18:55:28 +00001217 pVfs = db->pVfs;
drh17435752007-08-16 04:30:38 +00001218 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00001219 if( !p ){
1220 return SQLITE_NOMEM;
1221 }
1222 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00001223 p->db = db;
danielk1977aef0bf62005-12-30 16:28:01 +00001224
drh198bf392006-01-06 21:52:49 +00001225#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001226 /*
1227 ** If this Btree is a candidate for shared cache, try to find an
1228 ** existing BtShared object that we can share with
1229 */
drh34004ce2008-07-11 16:15:17 +00001230 if( isMemdb==0
drhe5fe6902007-12-07 18:55:28 +00001231 && (db->flags & SQLITE_Vtab)==0
drhe53831d2007-08-17 01:14:38 +00001232 && zFilename && zFilename[0]
drhe53831d2007-08-17 01:14:38 +00001233 ){
drhff0587c2007-08-29 17:43:19 +00001234 if( sqlite3SharedCacheEnabled ){
danielk1977adfb9b02007-09-17 07:02:56 +00001235 int nFullPathname = pVfs->mxPathname+1;
drhe5ae5732008-06-15 02:51:47 +00001236 char *zFullPathname = sqlite3Malloc(nFullPathname);
drhff0587c2007-08-29 17:43:19 +00001237 sqlite3_mutex *mutexShared;
1238 p->sharable = 1;
drh34004ce2008-07-11 16:15:17 +00001239 db->flags |= SQLITE_SharedCache;
drhff0587c2007-08-29 17:43:19 +00001240 if( !zFullPathname ){
1241 sqlite3_free(p);
1242 return SQLITE_NOMEM;
1243 }
danielk1977adfb9b02007-09-17 07:02:56 +00001244 sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
danielk197759f8c082008-06-18 17:09:10 +00001245 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhff0587c2007-08-29 17:43:19 +00001246 sqlite3_mutex_enter(mutexShared);
1247 for(pBt=sqlite3SharedCacheList; pBt; pBt=pBt->pNext){
1248 assert( pBt->nRef>0 );
1249 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
1250 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
1251 p->pBt = pBt;
1252 pBt->nRef++;
1253 break;
1254 }
1255 }
1256 sqlite3_mutex_leave(mutexShared);
1257 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00001258 }
drhff0587c2007-08-29 17:43:19 +00001259#ifdef SQLITE_DEBUG
1260 else{
1261 /* In debug mode, we mark all persistent databases as sharable
1262 ** even when they are not. This exercises the locking code and
1263 ** gives more opportunity for asserts(sqlite3_mutex_held())
1264 ** statements to find locking problems.
1265 */
1266 p->sharable = 1;
1267 }
1268#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001269 }
1270#endif
drha059ad02001-04-17 20:09:11 +00001271 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00001272 /*
1273 ** The following asserts make sure that structures used by the btree are
1274 ** the right size. This is to guard against size changes that result
1275 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00001276 */
drhe53831d2007-08-17 01:14:38 +00001277 assert( sizeof(i64)==8 || sizeof(i64)==4 );
1278 assert( sizeof(u64)==8 || sizeof(u64)==4 );
1279 assert( sizeof(u32)==4 );
1280 assert( sizeof(u16)==2 );
1281 assert( sizeof(Pgno)==4 );
1282
1283 pBt = sqlite3MallocZero( sizeof(*pBt) );
1284 if( pBt==0 ){
1285 rc = SQLITE_NOMEM;
1286 goto btree_open_out;
1287 }
drhe5fe6902007-12-07 18:55:28 +00001288 pBt->busyHdr.xFunc = sqlite3BtreeInvokeBusyHandler;
1289 pBt->busyHdr.pArg = pBt;
drh33f4e022007-09-03 15:19:34 +00001290 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
1291 EXTRA_SIZE, flags, vfsFlags);
drhe53831d2007-08-17 01:14:38 +00001292 if( rc==SQLITE_OK ){
1293 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
1294 }
1295 if( rc!=SQLITE_OK ){
1296 goto btree_open_out;
1297 }
drhe5fe6902007-12-07 18:55:28 +00001298 sqlite3PagerSetBusyhandler(pBt->pPager, &pBt->busyHdr);
drhe53831d2007-08-17 01:14:38 +00001299 p->pBt = pBt;
1300
1301 sqlite3PagerSetDestructor(pBt->pPager, pageDestructor);
1302 sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
1303 pBt->pCursor = 0;
1304 pBt->pPage1 = 0;
1305 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
1306 pBt->pageSize = get2byte(&zDbHeader[16]);
1307 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1308 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00001309 pBt->pageSize = 0;
1310 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drhe53831d2007-08-17 01:14:38 +00001311#ifndef SQLITE_OMIT_AUTOVACUUM
1312 /* If the magic name ":memory:" will create an in-memory database, then
1313 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
1314 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
1315 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
1316 ** regular file-name. In this case the auto-vacuum applies as per normal.
1317 */
1318 if( zFilename && !isMemdb ){
1319 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
1320 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
1321 }
1322#endif
1323 nReserve = 0;
1324 }else{
1325 nReserve = zDbHeader[20];
drhe53831d2007-08-17 01:14:38 +00001326 pBt->pageSizeFixed = 1;
1327#ifndef SQLITE_OMIT_AUTOVACUUM
1328 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1329 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
1330#endif
1331 }
1332 pBt->usableSize = pBt->pageSize - nReserve;
1333 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
danielk1977a1644fd2007-08-29 12:31:25 +00001334 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drhe53831d2007-08-17 01:14:38 +00001335
1336#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1337 /* Add the new BtShared object to the linked list sharable BtShareds.
1338 */
1339 if( p->sharable ){
1340 sqlite3_mutex *mutexShared;
1341 pBt->nRef = 1;
danielk197759f8c082008-06-18 17:09:10 +00001342 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
1343 if( SQLITE_THREADSAFE && sqlite3Config.bCoreMutex ){
1344 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
drh3285db22007-09-03 22:00:39 +00001345 if( pBt->mutex==0 ){
1346 rc = SQLITE_NOMEM;
drhe5fe6902007-12-07 18:55:28 +00001347 db->mallocFailed = 0;
drh3285db22007-09-03 22:00:39 +00001348 goto btree_open_out;
1349 }
drhff0587c2007-08-29 17:43:19 +00001350 }
drhe53831d2007-08-17 01:14:38 +00001351 sqlite3_mutex_enter(mutexShared);
1352 pBt->pNext = sqlite3SharedCacheList;
1353 sqlite3SharedCacheList = pBt;
1354 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00001355 }
drheee46cf2004-11-06 00:02:48 +00001356#endif
drh90f5ecb2004-07-22 01:19:35 +00001357 }
danielk1977aef0bf62005-12-30 16:28:01 +00001358
drhcfed7bc2006-03-13 14:28:05 +00001359#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001360 /* If the new Btree uses a sharable pBtShared, then link the new
1361 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00001362 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00001363 */
drhe53831d2007-08-17 01:14:38 +00001364 if( p->sharable ){
1365 int i;
1366 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00001367 for(i=0; i<db->nDb; i++){
1368 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00001369 while( pSib->pPrev ){ pSib = pSib->pPrev; }
1370 if( p->pBt<pSib->pBt ){
1371 p->pNext = pSib;
1372 p->pPrev = 0;
1373 pSib->pPrev = p;
1374 }else{
drhabddb0c2007-08-20 13:14:28 +00001375 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
drhe53831d2007-08-17 01:14:38 +00001376 pSib = pSib->pNext;
1377 }
1378 p->pNext = pSib->pNext;
1379 p->pPrev = pSib;
1380 if( p->pNext ){
1381 p->pNext->pPrev = p;
1382 }
1383 pSib->pNext = p;
1384 }
1385 break;
1386 }
1387 }
danielk1977aef0bf62005-12-30 16:28:01 +00001388 }
danielk1977aef0bf62005-12-30 16:28:01 +00001389#endif
1390 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00001391
1392btree_open_out:
1393 if( rc!=SQLITE_OK ){
1394 if( pBt && pBt->pPager ){
1395 sqlite3PagerClose(pBt->pPager);
1396 }
drh17435752007-08-16 04:30:38 +00001397 sqlite3_free(pBt);
1398 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00001399 *ppBtree = 0;
1400 }
1401 return rc;
drha059ad02001-04-17 20:09:11 +00001402}
1403
1404/*
drhe53831d2007-08-17 01:14:38 +00001405** Decrement the BtShared.nRef counter. When it reaches zero,
1406** remove the BtShared structure from the sharing list. Return
1407** true if the BtShared.nRef counter reaches zero and return
1408** false if it is still positive.
1409*/
1410static int removeFromSharingList(BtShared *pBt){
1411#ifndef SQLITE_OMIT_SHARED_CACHE
1412 sqlite3_mutex *pMaster;
1413 BtShared *pList;
1414 int removed = 0;
1415
drhd677b3d2007-08-20 22:48:41 +00001416 assert( sqlite3_mutex_notheld(pBt->mutex) );
danielk197759f8c082008-06-18 17:09:10 +00001417 pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhe53831d2007-08-17 01:14:38 +00001418 sqlite3_mutex_enter(pMaster);
1419 pBt->nRef--;
1420 if( pBt->nRef<=0 ){
1421 if( sqlite3SharedCacheList==pBt ){
1422 sqlite3SharedCacheList = pBt->pNext;
1423 }else{
1424 pList = sqlite3SharedCacheList;
drh34004ce2008-07-11 16:15:17 +00001425 while( ALWAYS(pList) && pList->pNext!=pBt ){
drhe53831d2007-08-17 01:14:38 +00001426 pList=pList->pNext;
1427 }
drh34004ce2008-07-11 16:15:17 +00001428 if( ALWAYS(pList) ){
drhe53831d2007-08-17 01:14:38 +00001429 pList->pNext = pBt->pNext;
1430 }
1431 }
drh3285db22007-09-03 22:00:39 +00001432 if( SQLITE_THREADSAFE ){
1433 sqlite3_mutex_free(pBt->mutex);
1434 }
drhe53831d2007-08-17 01:14:38 +00001435 removed = 1;
1436 }
1437 sqlite3_mutex_leave(pMaster);
1438 return removed;
1439#else
1440 return 1;
1441#endif
1442}
1443
1444/*
drhf7141992008-06-19 00:16:08 +00001445** Make sure pBt->pTmpSpace points to an allocation of
1446** MX_CELL_SIZE(pBt) bytes.
1447*/
1448static void allocateTempSpace(BtShared *pBt){
1449 if( !pBt->pTmpSpace ){
1450 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
1451 }
1452}
1453
1454/*
1455** Free the pBt->pTmpSpace allocation
1456*/
1457static void freeTempSpace(BtShared *pBt){
1458 sqlite3PageFree( pBt->pTmpSpace);
1459 pBt->pTmpSpace = 0;
1460}
1461
1462/*
drha059ad02001-04-17 20:09:11 +00001463** Close an open database and invalidate all cursors.
1464*/
danielk1977aef0bf62005-12-30 16:28:01 +00001465int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00001466 BtShared *pBt = p->pBt;
1467 BtCursor *pCur;
1468
danielk1977aef0bf62005-12-30 16:28:01 +00001469 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00001470 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00001471 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00001472 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00001473 pCur = pBt->pCursor;
1474 while( pCur ){
1475 BtCursor *pTmp = pCur;
1476 pCur = pCur->pNext;
1477 if( pTmp->pBtree==p ){
1478 sqlite3BtreeCloseCursor(pTmp);
1479 }
drha059ad02001-04-17 20:09:11 +00001480 }
danielk1977aef0bf62005-12-30 16:28:01 +00001481
danielk19778d34dfd2006-01-24 16:37:57 +00001482 /* Rollback any active transaction and free the handle structure.
1483 ** The call to sqlite3BtreeRollback() drops any table-locks held by
1484 ** this handle.
1485 */
danielk1977b597f742006-01-15 11:39:18 +00001486 sqlite3BtreeRollback(p);
drhe53831d2007-08-17 01:14:38 +00001487 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001488
danielk1977aef0bf62005-12-30 16:28:01 +00001489 /* If there are still other outstanding references to the shared-btree
1490 ** structure, return now. The remainder of this procedure cleans
1491 ** up the shared-btree.
1492 */
drhe53831d2007-08-17 01:14:38 +00001493 assert( p->wantToLock==0 && p->locked==0 );
1494 if( !p->sharable || removeFromSharingList(pBt) ){
1495 /* The pBt is no longer on the sharing list, so we can access
1496 ** it without having to hold the mutex.
1497 **
1498 ** Clean out and delete the BtShared object.
1499 */
1500 assert( !pBt->pCursor );
drhe53831d2007-08-17 01:14:38 +00001501 sqlite3PagerClose(pBt->pPager);
1502 if( pBt->xFreeSchema && pBt->pSchema ){
1503 pBt->xFreeSchema(pBt->pSchema);
1504 }
1505 sqlite3_free(pBt->pSchema);
drhf7141992008-06-19 00:16:08 +00001506 freeTempSpace(pBt);
drh65bbf292008-06-19 01:03:17 +00001507 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00001508 }
1509
drhe53831d2007-08-17 01:14:38 +00001510#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00001511 assert( p->wantToLock==0 );
1512 assert( p->locked==0 );
1513 if( p->pPrev ) p->pPrev->pNext = p->pNext;
1514 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00001515#endif
1516
drhe53831d2007-08-17 01:14:38 +00001517 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00001518 return SQLITE_OK;
1519}
1520
1521/*
drhda47d772002-12-02 04:25:19 +00001522** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001523**
1524** The maximum number of cache pages is set to the absolute
1525** value of mxPage. If mxPage is negative, the pager will
1526** operate asynchronously - it will not stop to do fsync()s
1527** to insure data is written to the disk surface before
1528** continuing. Transactions still work if synchronous is off,
1529** and the database cannot be corrupted if this program
1530** crashes. But if the operating system crashes or there is
1531** an abrupt power failure when synchronous is off, the database
1532** could be left in an inconsistent and unrecoverable state.
1533** Synchronous is on by default so database corruption is not
1534** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001535*/
danielk1977aef0bf62005-12-30 16:28:01 +00001536int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
1537 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001538 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001539 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001540 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00001541 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00001542 return SQLITE_OK;
1543}
1544
1545/*
drh973b6e32003-02-12 14:09:42 +00001546** Change the way data is synced to disk in order to increase or decrease
1547** how well the database resists damage due to OS crashes and power
1548** failures. Level 1 is the same as asynchronous (no syncs() occur and
1549** there is a high probability of damage) Level 2 is the default. There
1550** is a very low but non-zero probability of damage. Level 3 reduces the
1551** probability of damage to near zero but with a write performance reduction.
1552*/
danielk197793758c82005-01-21 08:13:14 +00001553#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drhac530b12006-02-11 01:25:50 +00001554int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
danielk1977aef0bf62005-12-30 16:28:01 +00001555 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001556 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001557 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001558 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
drhd677b3d2007-08-20 22:48:41 +00001559 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00001560 return SQLITE_OK;
1561}
danielk197793758c82005-01-21 08:13:14 +00001562#endif
drh973b6e32003-02-12 14:09:42 +00001563
drh2c8997b2005-08-27 16:36:48 +00001564/*
1565** Return TRUE if the given btree is set to safety level 1. In other
1566** words, return TRUE if no sync() occurs on the disk files.
1567*/
danielk1977aef0bf62005-12-30 16:28:01 +00001568int sqlite3BtreeSyncDisabled(Btree *p){
1569 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001570 int rc;
drhe5fe6902007-12-07 18:55:28 +00001571 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001572 sqlite3BtreeEnter(p);
drhd0679ed2007-08-28 22:24:34 +00001573 assert( pBt && pBt->pPager );
drhd677b3d2007-08-20 22:48:41 +00001574 rc = sqlite3PagerNosync(pBt->pPager);
1575 sqlite3BtreeLeave(p);
1576 return rc;
drh2c8997b2005-08-27 16:36:48 +00001577}
1578
danielk1977576ec6b2005-01-21 11:55:25 +00001579#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00001580/*
drh90f5ecb2004-07-22 01:19:35 +00001581** Change the default pages size and the number of reserved bytes per page.
drh06f50212004-11-02 14:24:33 +00001582**
1583** The page size must be a power of 2 between 512 and 65536. If the page
1584** size supplied does not meet this constraint then the page size is not
1585** changed.
1586**
1587** Page sizes are constrained to be a power of two so that the region
1588** of the database file used for locking (beginning at PENDING_BYTE,
1589** the first byte past the 1GB boundary, 0x40000000) needs to occur
1590** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001591**
1592** If parameter nReserve is less than zero, then the number of reserved
1593** bytes per page is left unchanged.
drh90f5ecb2004-07-22 01:19:35 +00001594*/
danielk1977aef0bf62005-12-30 16:28:01 +00001595int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
danielk1977a1644fd2007-08-29 12:31:25 +00001596 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00001597 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001598 sqlite3BtreeEnter(p);
drh90f5ecb2004-07-22 01:19:35 +00001599 if( pBt->pageSizeFixed ){
drhd677b3d2007-08-20 22:48:41 +00001600 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00001601 return SQLITE_READONLY;
1602 }
1603 if( nReserve<0 ){
1604 nReserve = pBt->pageSize - pBt->usableSize;
1605 }
drh06f50212004-11-02 14:24:33 +00001606 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
1607 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00001608 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00001609 assert( !pBt->pPage1 && !pBt->pCursor );
danielk1977a1644fd2007-08-29 12:31:25 +00001610 pBt->pageSize = pageSize;
drhf7141992008-06-19 00:16:08 +00001611 freeTempSpace(pBt);
danielk1977a1644fd2007-08-29 12:31:25 +00001612 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001613 }
1614 pBt->usableSize = pBt->pageSize - nReserve;
drhd677b3d2007-08-20 22:48:41 +00001615 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00001616 return rc;
drh90f5ecb2004-07-22 01:19:35 +00001617}
1618
1619/*
1620** Return the currently defined page size
1621*/
danielk1977aef0bf62005-12-30 16:28:01 +00001622int sqlite3BtreeGetPageSize(Btree *p){
1623 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00001624}
danielk1977aef0bf62005-12-30 16:28:01 +00001625int sqlite3BtreeGetReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00001626 int n;
1627 sqlite3BtreeEnter(p);
1628 n = p->pBt->pageSize - p->pBt->usableSize;
1629 sqlite3BtreeLeave(p);
1630 return n;
drh2011d5f2004-07-22 02:40:37 +00001631}
drhf8e632b2007-05-08 14:51:36 +00001632
1633/*
1634** Set the maximum page count for a database if mxPage is positive.
1635** No changes are made if mxPage is 0 or negative.
1636** Regardless of the value of mxPage, return the maximum page count.
1637*/
1638int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00001639 int n;
1640 sqlite3BtreeEnter(p);
1641 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
1642 sqlite3BtreeLeave(p);
1643 return n;
drhf8e632b2007-05-08 14:51:36 +00001644}
danielk1977576ec6b2005-01-21 11:55:25 +00001645#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00001646
1647/*
danielk1977951af802004-11-05 15:45:09 +00001648** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
1649** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
1650** is disabled. The default value for the auto-vacuum property is
1651** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
1652*/
danielk1977aef0bf62005-12-30 16:28:01 +00001653int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00001654#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001655 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00001656#else
danielk1977dddbcdc2007-04-26 14:42:34 +00001657 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001658 int rc = SQLITE_OK;
danielk1977dddbcdc2007-04-26 14:42:34 +00001659 int av = (autoVacuum?1:0);
drhd677b3d2007-08-20 22:48:41 +00001660
1661 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00001662 if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00001663 rc = SQLITE_READONLY;
1664 }else{
1665 pBt->autoVacuum = av;
danielk1977951af802004-11-05 15:45:09 +00001666 }
drhd677b3d2007-08-20 22:48:41 +00001667 sqlite3BtreeLeave(p);
1668 return rc;
danielk1977951af802004-11-05 15:45:09 +00001669#endif
1670}
1671
1672/*
1673** Return the value of the 'auto-vacuum' property. If auto-vacuum is
1674** enabled 1 is returned. Otherwise 0.
1675*/
danielk1977aef0bf62005-12-30 16:28:01 +00001676int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00001677#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00001678 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00001679#else
drhd677b3d2007-08-20 22:48:41 +00001680 int rc;
1681 sqlite3BtreeEnter(p);
1682 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00001683 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
1684 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
1685 BTREE_AUTOVACUUM_INCR
1686 );
drhd677b3d2007-08-20 22:48:41 +00001687 sqlite3BtreeLeave(p);
1688 return rc;
danielk1977951af802004-11-05 15:45:09 +00001689#endif
1690}
1691
1692
1693/*
drha34b6762004-05-07 13:30:42 +00001694** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001695** also acquire a readlock on that file.
1696**
1697** SQLITE_OK is returned on success. If the file is not a
1698** well-formed database file, then SQLITE_CORRUPT is returned.
1699** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00001700** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00001701*/
danielk1977aef0bf62005-12-30 16:28:01 +00001702static int lockBtree(BtShared *pBt){
danielk1977f653d782008-03-20 11:04:21 +00001703 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001704 MemPage *pPage1;
danielk197793f7af92008-05-09 16:57:50 +00001705 int nPage;
drhd677b3d2007-08-20 22:48:41 +00001706
drh1fee73e2007-08-29 04:00:57 +00001707 assert( sqlite3_mutex_held(pBt->mutex) );
drha34b6762004-05-07 13:30:42 +00001708 if( pBt->pPage1 ) return SQLITE_OK;
drh16a9b832007-05-05 18:39:25 +00001709 rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00001710 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00001711
1712 /* Do some checking to help insure the file we opened really is
1713 ** a valid database file.
1714 */
danielk1977ad0132d2008-06-07 08:58:22 +00001715 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1716 if( rc!=SQLITE_OK ){
danielk197793f7af92008-05-09 16:57:50 +00001717 goto page1_init_failed;
1718 }else if( nPage>0 ){
danielk1977f653d782008-03-20 11:04:21 +00001719 int pageSize;
1720 int usableSize;
drhb6f41482004-05-14 01:58:11 +00001721 u8 *page1 = pPage1->aData;
danielk1977ad0132d2008-06-07 08:58:22 +00001722 rc = SQLITE_NOTADB;
drhb6f41482004-05-14 01:58:11 +00001723 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001724 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001725 }
drh309169a2007-04-24 17:27:51 +00001726 if( page1[18]>1 ){
1727 pBt->readOnly = 1;
1728 }
1729 if( page1[19]>1 ){
drhb6f41482004-05-14 01:58:11 +00001730 goto page1_init_failed;
1731 }
drhe5ae5732008-06-15 02:51:47 +00001732
1733 /* The maximum embedded fraction must be exactly 25%. And the minimum
1734 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
1735 ** The original design allowed these amounts to vary, but as of
1736 ** version 3.6.0, we require them to be fixed.
1737 */
1738 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
1739 goto page1_init_failed;
1740 }
drh07d183d2005-05-01 22:52:42 +00001741 pageSize = get2byte(&page1[16]);
drh7dc385e2007-09-06 23:39:36 +00001742 if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
1743 (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
1744 ){
drh07d183d2005-05-01 22:52:42 +00001745 goto page1_init_failed;
1746 }
1747 assert( (pageSize & 7)==0 );
danielk1977f653d782008-03-20 11:04:21 +00001748 usableSize = pageSize - page1[20];
1749 if( pageSize!=pBt->pageSize ){
1750 /* After reading the first page of the database assuming a page size
1751 ** of BtShared.pageSize, we have discovered that the page-size is
1752 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
1753 ** zero and return SQLITE_OK. The caller will call this function
1754 ** again with the correct page-size.
1755 */
1756 releasePage(pPage1);
1757 pBt->usableSize = usableSize;
1758 pBt->pageSize = pageSize;
drhf7141992008-06-19 00:16:08 +00001759 freeTempSpace(pBt);
danielk1977f653d782008-03-20 11:04:21 +00001760 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
1761 return SQLITE_OK;
1762 }
1763 if( usableSize<500 ){
drhb6f41482004-05-14 01:58:11 +00001764 goto page1_init_failed;
1765 }
danielk1977f653d782008-03-20 11:04:21 +00001766 pBt->pageSize = pageSize;
1767 pBt->usableSize = usableSize;
drh057cd3a2005-02-15 16:23:02 +00001768#ifndef SQLITE_OMIT_AUTOVACUUM
1769 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00001770 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00001771#endif
drh306dc212001-05-21 13:45:10 +00001772 }
drhb6f41482004-05-14 01:58:11 +00001773
1774 /* maxLocal is the maximum amount of payload to store locally for
1775 ** a cell. Make sure it is small enough so that at least minFanout
1776 ** cells can will fit on one page. We assume a 10-byte page header.
1777 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001778 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001779 ** 4-byte child pointer
1780 ** 9-byte nKey value
1781 ** 4-byte nData value
1782 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001783 ** So a cell consists of a 2-byte poiner, a header which is as much as
1784 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1785 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001786 */
drhe5ae5732008-06-15 02:51:47 +00001787 pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
1788 pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
drh43605152004-05-29 21:46:49 +00001789 pBt->maxLeaf = pBt->usableSize - 35;
drhe5ae5732008-06-15 02:51:47 +00001790 pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
drh2e38c322004-09-03 18:38:44 +00001791 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00001792 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001793 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001794
drh72f82862001-05-24 21:06:34 +00001795page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001796 releasePage(pPage1);
1797 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001798 return rc;
drh306dc212001-05-21 13:45:10 +00001799}
1800
1801/*
drhb8ef32c2005-03-14 02:01:49 +00001802** This routine works like lockBtree() except that it also invokes the
1803** busy callback if there is lock contention.
1804*/
danielk1977aef0bf62005-12-30 16:28:01 +00001805static int lockBtreeWithRetry(Btree *pRef){
drhb8ef32c2005-03-14 02:01:49 +00001806 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00001807
drh1fee73e2007-08-29 04:00:57 +00001808 assert( sqlite3BtreeHoldsMutex(pRef) );
danielk1977aef0bf62005-12-30 16:28:01 +00001809 if( pRef->inTrans==TRANS_NONE ){
1810 u8 inTransaction = pRef->pBt->inTransaction;
1811 btreeIntegrity(pRef);
1812 rc = sqlite3BtreeBeginTrans(pRef, 0);
1813 pRef->pBt->inTransaction = inTransaction;
1814 pRef->inTrans = TRANS_NONE;
1815 if( rc==SQLITE_OK ){
1816 pRef->pBt->nTransaction--;
1817 }
1818 btreeIntegrity(pRef);
drhb8ef32c2005-03-14 02:01:49 +00001819 }
1820 return rc;
1821}
1822
1823
1824/*
drhb8ca3072001-12-05 00:21:20 +00001825** If there are no outstanding cursors and we are not in the middle
1826** of a transaction but there is a read lock on the database, then
1827** this routine unrefs the first page of the database file which
1828** has the effect of releasing the read lock.
1829**
1830** If there are any outstanding cursors, this routine is a no-op.
1831**
1832** If there is a transaction in progress, this routine is a no-op.
1833*/
danielk1977aef0bf62005-12-30 16:28:01 +00001834static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00001835 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00001836 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00001837 if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
drhde4fcfd2008-01-19 23:50:26 +00001838 assert( pBt->pPage1->aData );
1839#if 0
drh24c9a2e2007-01-05 02:00:47 +00001840 if( pBt->pPage1->aData==0 ){
1841 MemPage *pPage = pBt->pPage1;
drhbf4bca52007-09-06 22:19:14 +00001842 pPage->aData = sqlite3PagerGetData(pPage->pDbPage);
drh24c9a2e2007-01-05 02:00:47 +00001843 pPage->pBt = pBt;
1844 pPage->pgno = 1;
1845 }
drhde4fcfd2008-01-19 23:50:26 +00001846#endif
drh24c9a2e2007-01-05 02:00:47 +00001847 releasePage(pBt->pPage1);
drh51c6d962004-06-06 00:42:25 +00001848 }
drh3aac2dd2004-04-26 14:10:20 +00001849 pBt->pPage1 = 0;
drh3aac2dd2004-04-26 14:10:20 +00001850 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001851 }
1852}
1853
1854/*
drh9e572e62004-04-23 23:43:10 +00001855** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00001856** file.
drh8b2f49b2001-06-08 00:21:52 +00001857*/
danielk1977aef0bf62005-12-30 16:28:01 +00001858static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00001859 MemPage *pP1;
1860 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00001861 int rc;
danielk1977ad0132d2008-06-07 08:58:22 +00001862 int nPage;
drhd677b3d2007-08-20 22:48:41 +00001863
drh1fee73e2007-08-29 04:00:57 +00001864 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977ad0132d2008-06-07 08:58:22 +00001865 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1866 if( rc!=SQLITE_OK || nPage>0 ){
1867 return rc;
1868 }
drh3aac2dd2004-04-26 14:10:20 +00001869 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00001870 assert( pP1!=0 );
1871 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00001872 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00001873 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00001874 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
1875 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00001876 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00001877 data[18] = 1;
1878 data[19] = 1;
drhb6f41482004-05-14 01:58:11 +00001879 data[20] = pBt->pageSize - pBt->usableSize;
drhe5ae5732008-06-15 02:51:47 +00001880 data[21] = 64;
1881 data[22] = 32;
1882 data[23] = 32;
drhb6f41482004-05-14 01:58:11 +00001883 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00001884 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00001885 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00001886#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00001887 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00001888 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00001889 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00001890 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00001891#endif
drh8b2f49b2001-06-08 00:21:52 +00001892 return SQLITE_OK;
1893}
1894
1895/*
danielk1977ee5741e2004-05-31 10:01:34 +00001896** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00001897** is started if the second argument is nonzero, otherwise a read-
1898** transaction. If the second argument is 2 or more and exclusive
1899** transaction is started, meaning that no other process is allowed
1900** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00001901** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00001902** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00001903**
danielk1977ee5741e2004-05-31 10:01:34 +00001904** A write-transaction must be started before attempting any
1905** changes to the database. None of the following routines
1906** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00001907**
drh23e11ca2004-05-04 17:27:28 +00001908** sqlite3BtreeCreateTable()
1909** sqlite3BtreeCreateIndex()
1910** sqlite3BtreeClearTable()
1911** sqlite3BtreeDropTable()
1912** sqlite3BtreeInsert()
1913** sqlite3BtreeDelete()
1914** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00001915**
drhb8ef32c2005-03-14 02:01:49 +00001916** If an initial attempt to acquire the lock fails because of lock contention
1917** and the database was previously unlocked, then invoke the busy handler
1918** if there is one. But if there was previously a read-lock, do not
1919** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
1920** returned when there is already a read-lock in order to avoid a deadlock.
1921**
1922** Suppose there are two processes A and B. A has a read lock and B has
1923** a reserved lock. B tries to promote to exclusive but is blocked because
1924** of A's read lock. A tries to promote to reserved but is blocked by B.
1925** One or the other of the two processes must give way or there can be
1926** no progress. By returning SQLITE_BUSY and not invoking the busy callback
1927** when A already has a read lock, we encourage A to give up and let B
1928** proceed.
drha059ad02001-04-17 20:09:11 +00001929*/
danielk1977aef0bf62005-12-30 16:28:01 +00001930int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
1931 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00001932 int rc = SQLITE_OK;
1933
drhd677b3d2007-08-20 22:48:41 +00001934 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00001935 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00001936 btreeIntegrity(p);
1937
danielk1977ee5741e2004-05-31 10:01:34 +00001938 /* If the btree is already in a write-transaction, or it
1939 ** is already in a read-transaction and a read-transaction
1940 ** is requested, this is a no-op.
1941 */
danielk1977aef0bf62005-12-30 16:28:01 +00001942 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00001943 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00001944 }
drhb8ef32c2005-03-14 02:01:49 +00001945
1946 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00001947 if( pBt->readOnly && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00001948 rc = SQLITE_READONLY;
1949 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00001950 }
1951
danielk1977aef0bf62005-12-30 16:28:01 +00001952 /* If another database handle has already opened a write transaction
1953 ** on this shared-btree structure and a second write transaction is
1954 ** requested, return SQLITE_BUSY.
1955 */
1956 if( pBt->inTransaction==TRANS_WRITE && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00001957 rc = SQLITE_BUSY;
1958 goto trans_begun;
danielk1977aef0bf62005-12-30 16:28:01 +00001959 }
1960
danielk1977641b0f42007-12-21 04:47:25 +00001961#ifndef SQLITE_OMIT_SHARED_CACHE
1962 if( wrflag>1 ){
1963 BtLock *pIter;
1964 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
1965 if( pIter->pBtree!=p ){
1966 rc = SQLITE_BUSY;
1967 goto trans_begun;
1968 }
1969 }
1970 }
1971#endif
1972
drhb8ef32c2005-03-14 02:01:49 +00001973 do {
drh8a9c17f2008-05-02 14:23:54 +00001974 if( pBt->pPage1==0 ){
1975 do{
1976 rc = lockBtree(pBt);
1977 }while( pBt->pPage1==0 && rc==SQLITE_OK );
drh8c42ca92001-06-22 19:15:00 +00001978 }
drh309169a2007-04-24 17:27:51 +00001979
drhb8ef32c2005-03-14 02:01:49 +00001980 if( rc==SQLITE_OK && wrflag ){
drh309169a2007-04-24 17:27:51 +00001981 if( pBt->readOnly ){
1982 rc = SQLITE_READONLY;
1983 }else{
1984 rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1);
1985 if( rc==SQLITE_OK ){
1986 rc = newDatabase(pBt);
1987 }
drhb8ef32c2005-03-14 02:01:49 +00001988 }
1989 }
1990
1991 if( rc==SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00001992 if( wrflag ) pBt->inStmt = 0;
1993 }else{
1994 unlockBtreeIfUnused(pBt);
1995 }
danielk1977aef0bf62005-12-30 16:28:01 +00001996 }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
drhe5fe6902007-12-07 18:55:28 +00001997 sqlite3BtreeInvokeBusyHandler(pBt, 0) );
danielk1977aef0bf62005-12-30 16:28:01 +00001998
1999 if( rc==SQLITE_OK ){
2000 if( p->inTrans==TRANS_NONE ){
2001 pBt->nTransaction++;
2002 }
2003 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
2004 if( p->inTrans>pBt->inTransaction ){
2005 pBt->inTransaction = p->inTrans;
2006 }
danielk1977641b0f42007-12-21 04:47:25 +00002007#ifndef SQLITE_OMIT_SHARED_CACHE
2008 if( wrflag>1 ){
2009 assert( !pBt->pExclusive );
2010 pBt->pExclusive = p;
2011 }
2012#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002013 }
2014
drhd677b3d2007-08-20 22:48:41 +00002015
2016trans_begun:
danielk1977aef0bf62005-12-30 16:28:01 +00002017 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002018 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00002019 return rc;
drha059ad02001-04-17 20:09:11 +00002020}
2021
drh4a0611d2008-07-18 17:16:26 +00002022/*
2023** Return the size of the database file in pages. Or return -1 if
2024** there is any kind of error.
2025*/
2026static int pagerPagecount(Pager *pPager){
2027 int rc;
2028 int nPage;
2029 rc = sqlite3PagerPagecount(pPager, &nPage);
2030 return (rc==SQLITE_OK?nPage:-1);
2031}
2032
2033
danielk1977687566d2004-11-02 12:56:41 +00002034#ifndef SQLITE_OMIT_AUTOVACUUM
2035
2036/*
2037** Set the pointer-map entries for all children of page pPage. Also, if
2038** pPage contains cells that point to overflow pages, set the pointer
2039** map entries for the overflow pages as well.
2040*/
2041static int setChildPtrmaps(MemPage *pPage){
2042 int i; /* Counter variable */
2043 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00002044 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00002045 BtShared *pBt = pPage->pBt;
danielk1977687566d2004-11-02 12:56:41 +00002046 int isInitOrig = pPage->isInit;
2047 Pgno pgno = pPage->pgno;
2048
drh1fee73e2007-08-29 04:00:57 +00002049 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19772df71c72007-05-24 07:22:42 +00002050 rc = sqlite3BtreeInitPage(pPage, pPage->pParent);
2051 if( rc!=SQLITE_OK ){
2052 goto set_child_ptrmaps_out;
2053 }
danielk1977687566d2004-11-02 12:56:41 +00002054 nCell = pPage->nCell;
2055
2056 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002057 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002058
danielk197726836652005-01-17 01:33:13 +00002059 rc = ptrmapPutOvflPtr(pPage, pCell);
2060 if( rc!=SQLITE_OK ){
2061 goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002062 }
danielk197726836652005-01-17 01:33:13 +00002063
danielk1977687566d2004-11-02 12:56:41 +00002064 if( !pPage->leaf ){
2065 Pgno childPgno = get4byte(pCell);
2066 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
danielk19771bc71592008-07-08 17:13:59 +00002067 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002068 }
2069 }
2070
2071 if( !pPage->leaf ){
2072 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
2073 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
2074 }
2075
2076set_child_ptrmaps_out:
2077 pPage->isInit = isInitOrig;
2078 return rc;
2079}
2080
2081/*
2082** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
2083** page, is a pointer to page iFrom. Modify this pointer so that it points to
2084** iTo. Parameter eType describes the type of pointer to be modified, as
2085** follows:
2086**
2087** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
2088** page of pPage.
2089**
2090** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
2091** page pointed to by one of the cells on pPage.
2092**
2093** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
2094** overflow page in the list.
2095*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00002096static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00002097 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk1977687566d2004-11-02 12:56:41 +00002098 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00002099 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00002100 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00002101 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002102 }
danielk1977f78fc082004-11-02 14:40:32 +00002103 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00002104 }else{
2105 int isInitOrig = pPage->isInit;
2106 int i;
2107 int nCell;
2108
drh16a9b832007-05-05 18:39:25 +00002109 sqlite3BtreeInitPage(pPage, 0);
danielk1977687566d2004-11-02 12:56:41 +00002110 nCell = pPage->nCell;
2111
danielk1977687566d2004-11-02 12:56:41 +00002112 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002113 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002114 if( eType==PTRMAP_OVERFLOW1 ){
2115 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00002116 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
danielk1977687566d2004-11-02 12:56:41 +00002117 if( info.iOverflow ){
2118 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
2119 put4byte(&pCell[info.iOverflow], iTo);
2120 break;
2121 }
2122 }
2123 }else{
2124 if( get4byte(pCell)==iFrom ){
2125 put4byte(pCell, iTo);
2126 break;
2127 }
2128 }
2129 }
2130
2131 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00002132 if( eType!=PTRMAP_BTREE ||
2133 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00002134 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002135 }
danielk1977687566d2004-11-02 12:56:41 +00002136 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
2137 }
2138
2139 pPage->isInit = isInitOrig;
2140 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002141 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002142}
2143
danielk1977003ba062004-11-04 02:57:33 +00002144
danielk19777701e812005-01-10 12:59:51 +00002145/*
2146** Move the open database page pDbPage to location iFreePage in the
2147** database. The pDbPage reference remains valid.
2148*/
danielk1977003ba062004-11-04 02:57:33 +00002149static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00002150 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00002151 MemPage *pDbPage, /* Open page to move */
2152 u8 eType, /* Pointer map 'type' entry for pDbPage */
2153 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
danielk19774c999992008-07-16 18:17:55 +00002154 Pgno iFreePage, /* The location to move pDbPage to */
2155 int isCommit
danielk1977003ba062004-11-04 02:57:33 +00002156){
2157 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
2158 Pgno iDbPage = pDbPage->pgno;
2159 Pager *pPager = pBt->pPager;
2160 int rc;
2161
danielk1977a0bf2652004-11-04 14:30:04 +00002162 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
2163 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00002164 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00002165 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00002166
drh85b623f2007-12-13 21:54:09 +00002167 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00002168 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
2169 iDbPage, iFreePage, iPtrPage, eType));
danielk19774c999992008-07-16 18:17:55 +00002170 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
danielk1977003ba062004-11-04 02:57:33 +00002171 if( rc!=SQLITE_OK ){
2172 return rc;
2173 }
2174 pDbPage->pgno = iFreePage;
2175
2176 /* If pDbPage was a btree-page, then it may have child pages and/or cells
2177 ** that point to overflow pages. The pointer map entries for all these
2178 ** pages need to be changed.
2179 **
2180 ** If pDbPage is an overflow page, then the first 4 bytes may store a
2181 ** pointer to a subsequent overflow page. If this is the case, then
2182 ** the pointer map needs to be updated for the subsequent overflow page.
2183 */
danielk1977a0bf2652004-11-04 14:30:04 +00002184 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00002185 rc = setChildPtrmaps(pDbPage);
2186 if( rc!=SQLITE_OK ){
2187 return rc;
2188 }
2189 }else{
2190 Pgno nextOvfl = get4byte(pDbPage->aData);
2191 if( nextOvfl!=0 ){
danielk1977003ba062004-11-04 02:57:33 +00002192 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
2193 if( rc!=SQLITE_OK ){
2194 return rc;
2195 }
2196 }
2197 }
2198
2199 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
2200 ** that it points at iFreePage. Also fix the pointer map entry for
2201 ** iPtrPage.
2202 */
danielk1977a0bf2652004-11-04 14:30:04 +00002203 if( eType!=PTRMAP_ROOTPAGE ){
drh16a9b832007-05-05 18:39:25 +00002204 rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00002205 if( rc!=SQLITE_OK ){
2206 return rc;
2207 }
danielk19773b8a05f2007-03-19 17:44:26 +00002208 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00002209 if( rc!=SQLITE_OK ){
2210 releasePage(pPtrPage);
2211 return rc;
2212 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002213 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00002214 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00002215 if( rc==SQLITE_OK ){
2216 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
2217 }
danielk1977003ba062004-11-04 02:57:33 +00002218 }
danielk1977003ba062004-11-04 02:57:33 +00002219 return rc;
2220}
2221
danielk1977dddbcdc2007-04-26 14:42:34 +00002222/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00002223static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00002224
2225/*
danielk1977dddbcdc2007-04-26 14:42:34 +00002226** Perform a single step of an incremental-vacuum. If successful,
2227** return SQLITE_OK. If there is no work to do (and therefore no
2228** point in calling this function again), return SQLITE_DONE.
2229**
2230** More specificly, this function attempts to re-organize the
2231** database so that the last page of the file currently in use
2232** is no longer in use.
2233**
2234** If the nFin parameter is non-zero, the implementation assumes
2235** that the caller will keep calling incrVacuumStep() until
2236** it returns SQLITE_DONE or an error, and that nFin is the
2237** number of pages the database file will contain after this
2238** process is complete.
2239*/
2240static int incrVacuumStep(BtShared *pBt, Pgno nFin){
2241 Pgno iLastPg; /* Last page in the database */
2242 Pgno nFreeList; /* Number of pages still on the free-list */
2243
drh1fee73e2007-08-29 04:00:57 +00002244 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977dddbcdc2007-04-26 14:42:34 +00002245 iLastPg = pBt->nTrunc;
2246 if( iLastPg==0 ){
danielk1977ad0132d2008-06-07 08:58:22 +00002247 iLastPg = pagerPagecount(pBt->pPager);
danielk1977dddbcdc2007-04-26 14:42:34 +00002248 }
2249
2250 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
2251 int rc;
2252 u8 eType;
2253 Pgno iPtrPage;
2254
2255 nFreeList = get4byte(&pBt->pPage1->aData[36]);
2256 if( nFreeList==0 || nFin==iLastPg ){
2257 return SQLITE_DONE;
2258 }
2259
2260 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
2261 if( rc!=SQLITE_OK ){
2262 return rc;
2263 }
2264 if( eType==PTRMAP_ROOTPAGE ){
2265 return SQLITE_CORRUPT_BKPT;
2266 }
2267
2268 if( eType==PTRMAP_FREEPAGE ){
2269 if( nFin==0 ){
2270 /* Remove the page from the files free-list. This is not required
danielk19774ef24492007-05-23 09:52:41 +00002271 ** if nFin is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00002272 ** truncated to zero after this function returns, so it doesn't
2273 ** matter if it still contains some garbage entries.
2274 */
2275 Pgno iFreePg;
2276 MemPage *pFreePg;
2277 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
2278 if( rc!=SQLITE_OK ){
2279 return rc;
2280 }
2281 assert( iFreePg==iLastPg );
2282 releasePage(pFreePg);
2283 }
2284 } else {
2285 Pgno iFreePg; /* Index of free page to move pLastPg to */
2286 MemPage *pLastPg;
2287
drh16a9b832007-05-05 18:39:25 +00002288 rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002289 if( rc!=SQLITE_OK ){
2290 return rc;
2291 }
2292
danielk1977b4626a32007-04-28 15:47:43 +00002293 /* If nFin is zero, this loop runs exactly once and page pLastPg
2294 ** is swapped with the first free page pulled off the free list.
2295 **
2296 ** On the other hand, if nFin is greater than zero, then keep
2297 ** looping until a free-page located within the first nFin pages
2298 ** of the file is found.
2299 */
danielk1977dddbcdc2007-04-26 14:42:34 +00002300 do {
2301 MemPage *pFreePg;
2302 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
2303 if( rc!=SQLITE_OK ){
2304 releasePage(pLastPg);
2305 return rc;
2306 }
2307 releasePage(pFreePg);
2308 }while( nFin!=0 && iFreePg>nFin );
2309 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00002310
2311 rc = sqlite3PagerWrite(pLastPg->pDbPage);
danielk1977662278e2007-11-05 15:30:12 +00002312 if( rc==SQLITE_OK ){
danielk19774c999992008-07-16 18:17:55 +00002313 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
danielk1977662278e2007-11-05 15:30:12 +00002314 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002315 releasePage(pLastPg);
2316 if( rc!=SQLITE_OK ){
2317 return rc;
danielk1977662278e2007-11-05 15:30:12 +00002318 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002319 }
2320 }
2321
2322 pBt->nTrunc = iLastPg - 1;
2323 while( pBt->nTrunc==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, pBt->nTrunc) ){
2324 pBt->nTrunc--;
2325 }
2326 return SQLITE_OK;
2327}
2328
2329/*
2330** A write-transaction must be opened before calling this function.
2331** It performs a single unit of work towards an incremental vacuum.
2332**
2333** If the incremental vacuum is finished after this function has run,
2334** SQLITE_DONE is returned. If it is not finished, but no error occured,
2335** SQLITE_OK is returned. Otherwise an SQLite error code.
2336*/
2337int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002338 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002339 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002340
2341 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002342 pBt->db = p->db;
danielk1977dddbcdc2007-04-26 14:42:34 +00002343 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
2344 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002345 rc = SQLITE_DONE;
2346 }else{
2347 invalidateAllOverflowCache(pBt);
2348 rc = incrVacuumStep(pBt, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002349 }
drhd677b3d2007-08-20 22:48:41 +00002350 sqlite3BtreeLeave(p);
2351 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002352}
2353
2354/*
danielk19773b8a05f2007-03-19 17:44:26 +00002355** This routine is called prior to sqlite3PagerCommit when a transaction
danielk1977687566d2004-11-02 12:56:41 +00002356** is commited for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00002357**
2358** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
2359** the database file should be truncated to during the commit process.
2360** i.e. the database has been reorganized so that only the first *pnTrunc
2361** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00002362*/
danielk197724168722007-04-02 05:07:47 +00002363static int autoVacuumCommit(BtShared *pBt, Pgno *pnTrunc){
danielk1977dddbcdc2007-04-26 14:42:34 +00002364 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002365 Pager *pPager = pBt->pPager;
danielk1977687566d2004-11-02 12:56:41 +00002366#ifndef NDEBUG
danielk19773b8a05f2007-03-19 17:44:26 +00002367 int nRef = sqlite3PagerRefcount(pPager);
danielk1977687566d2004-11-02 12:56:41 +00002368#endif
2369
drh1fee73e2007-08-29 04:00:57 +00002370 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00002371 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00002372 assert(pBt->autoVacuum);
2373 if( !pBt->incrVacuum ){
2374 Pgno nFin = 0;
danielk1977687566d2004-11-02 12:56:41 +00002375
danielk1977dddbcdc2007-04-26 14:42:34 +00002376 if( pBt->nTrunc==0 ){
2377 Pgno nFree;
2378 Pgno nPtrmap;
2379 const int pgsz = pBt->pageSize;
danielk1977ad0132d2008-06-07 08:58:22 +00002380 int nOrig = pagerPagecount(pBt->pPager);
danielk1977e5321f02007-04-27 07:05:44 +00002381
2382 if( PTRMAP_ISPAGE(pBt, nOrig) ){
2383 return SQLITE_CORRUPT_BKPT;
2384 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002385 if( nOrig==PENDING_BYTE_PAGE(pBt) ){
2386 nOrig--;
danielk1977687566d2004-11-02 12:56:41 +00002387 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002388 nFree = get4byte(&pBt->pPage1->aData[36]);
2389 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
2390 nFin = nOrig - nFree - nPtrmap;
2391 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
2392 nFin--;
danielk1977ac11ee62005-01-15 12:45:51 +00002393 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002394 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
2395 nFin--;
2396 }
2397 }
danielk1977687566d2004-11-02 12:56:41 +00002398
danielk1977dddbcdc2007-04-26 14:42:34 +00002399 while( rc==SQLITE_OK ){
2400 rc = incrVacuumStep(pBt, nFin);
2401 }
2402 if( rc==SQLITE_DONE ){
2403 assert(nFin==0 || pBt->nTrunc==0 || nFin<=pBt->nTrunc);
2404 rc = SQLITE_OK;
danielk19770ba32df2008-05-07 07:13:16 +00002405 if( pBt->nTrunc && nFin ){
drh67f80b62007-07-23 19:26:17 +00002406 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
danielk1977dddbcdc2007-04-26 14:42:34 +00002407 put4byte(&pBt->pPage1->aData[32], 0);
2408 put4byte(&pBt->pPage1->aData[36], 0);
2409 pBt->nTrunc = nFin;
2410 }
2411 }
2412 if( rc!=SQLITE_OK ){
2413 sqlite3PagerRollback(pPager);
2414 }
danielk1977687566d2004-11-02 12:56:41 +00002415 }
2416
danielk1977dddbcdc2007-04-26 14:42:34 +00002417 if( rc==SQLITE_OK ){
2418 *pnTrunc = pBt->nTrunc;
2419 pBt->nTrunc = 0;
2420 }
danielk19773b8a05f2007-03-19 17:44:26 +00002421 assert( nRef==sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002422 return rc;
2423}
danielk1977dddbcdc2007-04-26 14:42:34 +00002424
danielk1977687566d2004-11-02 12:56:41 +00002425#endif
2426
2427/*
drh80e35f42007-03-30 14:06:34 +00002428** This routine does the first phase of a two-phase commit. This routine
2429** causes a rollback journal to be created (if it does not already exist)
2430** and populated with enough information so that if a power loss occurs
2431** the database can be restored to its original state by playing back
2432** the journal. Then the contents of the journal are flushed out to
2433** the disk. After the journal is safely on oxide, the changes to the
2434** database are written into the database file and flushed to oxide.
2435** At the end of this call, the rollback journal still exists on the
2436** disk and we are still holding all locks, so the transaction has not
2437** committed. See sqlite3BtreeCommit() for the second phase of the
2438** commit process.
2439**
2440** This call is a no-op if no write-transaction is currently active on pBt.
2441**
2442** Otherwise, sync the database file for the btree pBt. zMaster points to
2443** the name of a master journal file that should be written into the
2444** individual journal file, or is NULL, indicating no master journal file
2445** (single database transaction).
2446**
2447** When this is called, the master journal should already have been
2448** created, populated with this journal pointer and synced to disk.
2449**
2450** Once this is routine has returned, the only thing required to commit
2451** the write-transaction for this database file is to delete the journal.
2452*/
2453int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
2454 int rc = SQLITE_OK;
2455 if( p->inTrans==TRANS_WRITE ){
2456 BtShared *pBt = p->pBt;
2457 Pgno nTrunc = 0;
drhd677b3d2007-08-20 22:48:41 +00002458 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002459 pBt->db = p->db;
drh80e35f42007-03-30 14:06:34 +00002460#ifndef SQLITE_OMIT_AUTOVACUUM
2461 if( pBt->autoVacuum ){
2462 rc = autoVacuumCommit(pBt, &nTrunc);
2463 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002464 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002465 return rc;
2466 }
2467 }
2468#endif
danielk1977f653d782008-03-20 11:04:21 +00002469 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, nTrunc, 0);
drhd677b3d2007-08-20 22:48:41 +00002470 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002471 }
2472 return rc;
2473}
2474
2475/*
drh2aa679f2001-06-25 02:11:07 +00002476** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00002477**
drh6e345992007-03-30 11:12:08 +00002478** This routine implements the second phase of a 2-phase commit. The
2479** sqlite3BtreeSync() routine does the first phase and should be invoked
2480** prior to calling this routine. The sqlite3BtreeSync() routine did
2481** all the work of writing information out to disk and flushing the
2482** contents so that they are written onto the disk platter. All this
2483** routine has to do is delete or truncate the rollback journal
2484** (which causes the transaction to commit) and drop locks.
2485**
drh5e00f6c2001-09-13 13:46:56 +00002486** This will release the write lock on the database file. If there
2487** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002488*/
drh80e35f42007-03-30 14:06:34 +00002489int sqlite3BtreeCommitPhaseTwo(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002490 BtShared *pBt = p->pBt;
2491
drhd677b3d2007-08-20 22:48:41 +00002492 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002493 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00002494 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002495
2496 /* If the handle has a write-transaction open, commit the shared-btrees
2497 ** transaction and set the shared state to TRANS_READ.
2498 */
2499 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00002500 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002501 assert( pBt->inTransaction==TRANS_WRITE );
2502 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00002503 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
danielk19777f7bc662006-01-23 13:47:47 +00002504 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002505 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002506 return rc;
2507 }
danielk1977aef0bf62005-12-30 16:28:01 +00002508 pBt->inTransaction = TRANS_READ;
2509 pBt->inStmt = 0;
danielk1977ee5741e2004-05-31 10:01:34 +00002510 }
danielk19777f7bc662006-01-23 13:47:47 +00002511 unlockAllTables(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002512
2513 /* If the handle has any kind of transaction open, decrement the transaction
2514 ** count of the shared btree. If the transaction count reaches 0, set
2515 ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
2516 ** will unlock the pager.
2517 */
2518 if( p->inTrans!=TRANS_NONE ){
2519 pBt->nTransaction--;
2520 if( 0==pBt->nTransaction ){
2521 pBt->inTransaction = TRANS_NONE;
2522 }
2523 }
2524
2525 /* Set the handles current transaction state to TRANS_NONE and unlock
2526 ** the pager if this call closed the only read or write transaction.
2527 */
2528 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00002529 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002530
2531 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002532 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002533 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002534}
2535
drh80e35f42007-03-30 14:06:34 +00002536/*
2537** Do both phases of a commit.
2538*/
2539int sqlite3BtreeCommit(Btree *p){
2540 int rc;
drhd677b3d2007-08-20 22:48:41 +00002541 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00002542 rc = sqlite3BtreeCommitPhaseOne(p, 0);
2543 if( rc==SQLITE_OK ){
2544 rc = sqlite3BtreeCommitPhaseTwo(p);
2545 }
drhd677b3d2007-08-20 22:48:41 +00002546 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002547 return rc;
2548}
2549
danielk1977fbcd5852004-06-15 02:44:18 +00002550#ifndef NDEBUG
2551/*
2552** Return the number of write-cursors open on this handle. This is for use
2553** in assert() expressions, so it is only compiled if NDEBUG is not
2554** defined.
drhfb982642007-08-30 01:19:59 +00002555**
2556** For the purposes of this routine, a write-cursor is any cursor that
2557** is capable of writing to the databse. That means the cursor was
2558** originally opened for writing and the cursor has not be disabled
2559** by having its state changed to CURSOR_FAULT.
danielk1977fbcd5852004-06-15 02:44:18 +00002560*/
danielk1977aef0bf62005-12-30 16:28:01 +00002561static int countWriteCursors(BtShared *pBt){
danielk1977fbcd5852004-06-15 02:44:18 +00002562 BtCursor *pCur;
2563 int r = 0;
2564 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drhfb982642007-08-30 01:19:59 +00002565 if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
danielk1977fbcd5852004-06-15 02:44:18 +00002566 }
2567 return r;
2568}
2569#endif
2570
drhc39e0002004-05-07 23:50:57 +00002571/*
drhfb982642007-08-30 01:19:59 +00002572** This routine sets the state to CURSOR_FAULT and the error
2573** code to errCode for every cursor on BtShared that pBtree
2574** references.
2575**
2576** Every cursor is tripped, including cursors that belong
2577** to other database connections that happen to be sharing
2578** the cache with pBtree.
2579**
2580** This routine gets called when a rollback occurs.
2581** All cursors using the same cache must be tripped
2582** to prevent them from trying to use the btree after
2583** the rollback. The rollback may have deleted tables
2584** or moved root pages, so it is not sufficient to
2585** save the state of the cursor. The cursor must be
2586** invalidated.
2587*/
2588void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
2589 BtCursor *p;
2590 sqlite3BtreeEnter(pBtree);
2591 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
2592 clearCursorPosition(p);
2593 p->eState = CURSOR_FAULT;
2594 p->skip = errCode;
2595 }
2596 sqlite3BtreeLeave(pBtree);
2597}
2598
2599/*
drhecdc7532001-09-23 02:35:53 +00002600** Rollback the transaction in progress. All cursors will be
2601** invalided by this operation. Any attempt to use a cursor
2602** that was open at the beginning of this operation will result
2603** in an error.
drh5e00f6c2001-09-13 13:46:56 +00002604**
2605** This will release the write lock on the database file. If there
2606** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002607*/
danielk1977aef0bf62005-12-30 16:28:01 +00002608int sqlite3BtreeRollback(Btree *p){
danielk19778d34dfd2006-01-24 16:37:57 +00002609 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002610 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00002611 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00002612
drhd677b3d2007-08-20 22:48:41 +00002613 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002614 pBt->db = p->db;
danielk19772b8c13e2006-01-24 14:21:24 +00002615 rc = saveAllCursors(pBt, 0, 0);
danielk19778d34dfd2006-01-24 16:37:57 +00002616#ifndef SQLITE_OMIT_SHARED_CACHE
danielk19772b8c13e2006-01-24 14:21:24 +00002617 if( rc!=SQLITE_OK ){
danielk19778d34dfd2006-01-24 16:37:57 +00002618 /* This is a horrible situation. An IO or malloc() error occured whilst
2619 ** trying to save cursor positions. If this is an automatic rollback (as
2620 ** the result of a constraint, malloc() failure or IO error) then
2621 ** the cache may be internally inconsistent (not contain valid trees) so
2622 ** we cannot simply return the error to the caller. Instead, abort
2623 ** all queries that may be using any of the cursors that failed to save.
2624 */
drhfb982642007-08-30 01:19:59 +00002625 sqlite3BtreeTripAllCursors(p, rc);
danielk19772b8c13e2006-01-24 14:21:24 +00002626 }
danielk19778d34dfd2006-01-24 16:37:57 +00002627#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002628 btreeIntegrity(p);
2629 unlockAllTables(p);
2630
2631 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00002632 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00002633
danielk1977dddbcdc2007-04-26 14:42:34 +00002634#ifndef SQLITE_OMIT_AUTOVACUUM
2635 pBt->nTrunc = 0;
2636#endif
2637
danielk19778d34dfd2006-01-24 16:37:57 +00002638 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00002639 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00002640 if( rc2!=SQLITE_OK ){
2641 rc = rc2;
2642 }
2643
drh24cd67e2004-05-10 16:18:47 +00002644 /* The rollback may have destroyed the pPage1->aData value. So
drh16a9b832007-05-05 18:39:25 +00002645 ** call sqlite3BtreeGetPage() on page 1 again to make
2646 ** sure pPage1->aData is set correctly. */
2647 if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh24cd67e2004-05-10 16:18:47 +00002648 releasePage(pPage1);
2649 }
danielk1977fbcd5852004-06-15 02:44:18 +00002650 assert( countWriteCursors(pBt)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002651 pBt->inTransaction = TRANS_READ;
drh24cd67e2004-05-10 16:18:47 +00002652 }
danielk1977aef0bf62005-12-30 16:28:01 +00002653
2654 if( p->inTrans!=TRANS_NONE ){
2655 assert( pBt->nTransaction>0 );
2656 pBt->nTransaction--;
2657 if( 0==pBt->nTransaction ){
2658 pBt->inTransaction = TRANS_NONE;
2659 }
2660 }
2661
2662 p->inTrans = TRANS_NONE;
danielk1977ee5741e2004-05-31 10:01:34 +00002663 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00002664 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002665
2666 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002667 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00002668 return rc;
2669}
2670
2671/*
drhab01f612004-05-22 02:55:23 +00002672** Start a statement subtransaction. The subtransaction can
2673** can be rolled back independently of the main transaction.
2674** You must start a transaction before starting a subtransaction.
2675** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00002676** commits or rolls back.
2677**
drhab01f612004-05-22 02:55:23 +00002678** Only one subtransaction may be active at a time. It is an error to try
2679** to start a new subtransaction if another subtransaction is already active.
2680**
2681** Statement subtransactions are used around individual SQL statements
2682** that are contained within a BEGIN...COMMIT block. If a constraint
2683** error occurs within the statement, the effect of that one statement
2684** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00002685*/
danielk1977aef0bf62005-12-30 16:28:01 +00002686int sqlite3BtreeBeginStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002687 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002688 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002689 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002690 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00002691 if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
drhd677b3d2007-08-20 22:48:41 +00002692 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
2693 }else{
2694 assert( pBt->inTransaction==TRANS_WRITE );
2695 rc = pBt->readOnly ? SQLITE_OK : sqlite3PagerStmtBegin(pBt->pPager);
2696 pBt->inStmt = 1;
drh0d65dc02002-02-03 00:56:09 +00002697 }
drhd677b3d2007-08-20 22:48:41 +00002698 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002699 return rc;
2700}
2701
2702
2703/*
drhab01f612004-05-22 02:55:23 +00002704** Commit the statment subtransaction currently in progress. If no
2705** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00002706*/
danielk1977aef0bf62005-12-30 16:28:01 +00002707int sqlite3BtreeCommitStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002708 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002709 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002710 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002711 pBt->db = p->db;
drh3aac2dd2004-04-26 14:10:20 +00002712 if( pBt->inStmt && !pBt->readOnly ){
danielk19773b8a05f2007-03-19 17:44:26 +00002713 rc = sqlite3PagerStmtCommit(pBt->pPager);
drh663fc632002-02-02 18:49:19 +00002714 }else{
2715 rc = SQLITE_OK;
2716 }
drh3aac2dd2004-04-26 14:10:20 +00002717 pBt->inStmt = 0;
drhd677b3d2007-08-20 22:48:41 +00002718 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002719 return rc;
2720}
2721
2722/*
drhab01f612004-05-22 02:55:23 +00002723** Rollback the active statement subtransaction. If no subtransaction
2724** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00002725**
drhab01f612004-05-22 02:55:23 +00002726** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00002727** to use a cursor that was open at the beginning of this operation
2728** will result in an error.
2729*/
danielk1977aef0bf62005-12-30 16:28:01 +00002730int sqlite3BtreeRollbackStmt(Btree *p){
danielk197797a227c2006-01-20 16:32:04 +00002731 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002732 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002733 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002734 pBt->db = p->db;
danielk197797a227c2006-01-20 16:32:04 +00002735 if( pBt->inStmt && !pBt->readOnly ){
danielk19773b8a05f2007-03-19 17:44:26 +00002736 rc = sqlite3PagerStmtRollback(pBt->pPager);
danielk197797a227c2006-01-20 16:32:04 +00002737 pBt->inStmt = 0;
2738 }
drhd677b3d2007-08-20 22:48:41 +00002739 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002740 return rc;
2741}
2742
2743/*
drh8b2f49b2001-06-08 00:21:52 +00002744** Create a new cursor for the BTree whose root is on the page
2745** iTable. The act of acquiring a cursor gets a read lock on
2746** the database file.
drh1bee3d72001-10-15 00:44:35 +00002747**
2748** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00002749** If wrFlag==1, then the cursor can be used for reading or for
2750** writing if other conditions for writing are also met. These
2751** are the conditions that must be met in order for writing to
2752** be allowed:
drh6446c4d2001-12-15 14:22:18 +00002753**
drhf74b8d92002-09-01 23:20:45 +00002754** 1: The cursor must have been opened with wrFlag==1
2755**
drhfe5d71d2007-03-19 11:54:10 +00002756** 2: Other database connections that share the same pager cache
2757** but which are not in the READ_UNCOMMITTED state may not have
2758** cursors open with wrFlag==0 on the same table. Otherwise
2759** the changes made by this write cursor would be visible to
2760** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00002761**
2762** 3: The database must be writable (not on read-only media)
2763**
2764** 4: There must be an active transaction.
2765**
drh6446c4d2001-12-15 14:22:18 +00002766** No checking is done to make sure that page iTable really is the
2767** root page of a b-tree. If it is not, then the cursor acquired
2768** will not work correctly.
drha059ad02001-04-17 20:09:11 +00002769*/
drhd677b3d2007-08-20 22:48:41 +00002770static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00002771 Btree *p, /* The btree */
2772 int iTable, /* Root page of table to open */
2773 int wrFlag, /* 1 to write. 0 read-only */
2774 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
2775 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00002776){
drha059ad02001-04-17 20:09:11 +00002777 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002778 BtShared *pBt = p->pBt;
drhecdc7532001-09-23 02:35:53 +00002779
drh1fee73e2007-08-29 04:00:57 +00002780 assert( sqlite3BtreeHoldsMutex(p) );
drh8dcd7ca2004-08-08 19:43:29 +00002781 if( wrFlag ){
drh8dcd7ca2004-08-08 19:43:29 +00002782 if( pBt->readOnly ){
2783 return SQLITE_READONLY;
2784 }
danielk19773588ceb2008-06-10 17:30:26 +00002785 if( checkReadLocks(p, iTable, 0, 0) ){
drh8dcd7ca2004-08-08 19:43:29 +00002786 return SQLITE_LOCKED;
2787 }
drha0c9a112004-03-10 13:42:37 +00002788 }
danielk1977aef0bf62005-12-30 16:28:01 +00002789
drh4b70f112004-05-02 21:12:19 +00002790 if( pBt->pPage1==0 ){
danielk1977aef0bf62005-12-30 16:28:01 +00002791 rc = lockBtreeWithRetry(p);
drha059ad02001-04-17 20:09:11 +00002792 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00002793 return rc;
2794 }
drh1831f182007-04-24 17:35:59 +00002795 if( pBt->readOnly && wrFlag ){
2796 return SQLITE_READONLY;
2797 }
drha059ad02001-04-17 20:09:11 +00002798 }
drh8b2f49b2001-06-08 00:21:52 +00002799 pCur->pgnoRoot = (Pgno)iTable;
danielk1977ad0132d2008-06-07 08:58:22 +00002800 if( iTable==1 && pagerPagecount(pBt->pPager)==0 ){
drh24cd67e2004-05-10 16:18:47 +00002801 rc = SQLITE_EMPTY;
2802 goto create_cursor_exception;
2803 }
drhde647132004-05-07 17:57:49 +00002804 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
drhbd03cae2001-06-02 02:40:57 +00002805 if( rc!=SQLITE_OK ){
2806 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00002807 }
danielk1977aef0bf62005-12-30 16:28:01 +00002808
danielk1977aef0bf62005-12-30 16:28:01 +00002809 /* Now that no other errors can occur, finish filling in the BtCursor
2810 ** variables, link the cursor into the BtShared list and set *ppCur (the
2811 ** output argument to this function).
2812 */
drh1e968a02008-03-25 00:22:21 +00002813 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00002814 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00002815 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +00002816 pCur->wrFlag = wrFlag;
drha059ad02001-04-17 20:09:11 +00002817 pCur->pNext = pBt->pCursor;
2818 if( pCur->pNext ){
2819 pCur->pNext->pPrev = pCur;
2820 }
2821 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00002822 pCur->eState = CURSOR_INVALID;
drhbd03cae2001-06-02 02:40:57 +00002823
danielk1977aef0bf62005-12-30 16:28:01 +00002824 return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00002825
drhbd03cae2001-06-02 02:40:57 +00002826create_cursor_exception:
drha3460582008-07-11 21:02:53 +00002827 releasePage(pCur->pPage);
drh5e00f6c2001-09-13 13:46:56 +00002828 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00002829 return rc;
drha059ad02001-04-17 20:09:11 +00002830}
drhd677b3d2007-08-20 22:48:41 +00002831int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00002832 Btree *p, /* The btree */
2833 int iTable, /* Root page of table to open */
2834 int wrFlag, /* 1 to write. 0 read-only */
2835 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
2836 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00002837){
2838 int rc;
2839 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002840 p->pBt->db = p->db;
danielk1977cd3e8f72008-03-25 09:47:35 +00002841 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
drhd677b3d2007-08-20 22:48:41 +00002842 sqlite3BtreeLeave(p);
2843 return rc;
2844}
danielk1977cd3e8f72008-03-25 09:47:35 +00002845int sqlite3BtreeCursorSize(){
2846 return sizeof(BtCursor);
2847}
2848
drhd677b3d2007-08-20 22:48:41 +00002849
drha059ad02001-04-17 20:09:11 +00002850
2851/*
drh5e00f6c2001-09-13 13:46:56 +00002852** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00002853** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00002854*/
drh3aac2dd2004-04-26 14:10:20 +00002855int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00002856 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00002857 if( pBtree ){
2858 BtShared *pBt = pCur->pBt;
2859 sqlite3BtreeEnter(pBtree);
2860 pBt->db = pBtree->db;
2861 clearCursorPosition(pCur);
2862 if( pCur->pPrev ){
2863 pCur->pPrev->pNext = pCur->pNext;
2864 }else{
2865 pBt->pCursor = pCur->pNext;
2866 }
2867 if( pCur->pNext ){
2868 pCur->pNext->pPrev = pCur->pPrev;
2869 }
2870 releasePage(pCur->pPage);
2871 unlockBtreeIfUnused(pBt);
2872 invalidateOverflowCache(pCur);
2873 /* sqlite3_free(pCur); */
2874 sqlite3BtreeLeave(pBtree);
drha059ad02001-04-17 20:09:11 +00002875 }
drh8c42ca92001-06-22 19:15:00 +00002876 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002877}
2878
drh7e3b0a02001-04-28 16:52:40 +00002879/*
drh5e2f8b92001-05-28 00:41:15 +00002880** Make a temporary cursor by filling in the fields of pTempCur.
2881** The temporary cursor is not on the cursor list for the Btree.
2882*/
drh16a9b832007-05-05 18:39:25 +00002883void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh1fee73e2007-08-29 04:00:57 +00002884 assert( cursorHoldsMutex(pCur) );
drh5e2f8b92001-05-28 00:41:15 +00002885 memcpy(pTempCur, pCur, sizeof(*pCur));
2886 pTempCur->pNext = 0;
2887 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00002888 if( pTempCur->pPage ){
danielk19773b8a05f2007-03-19 17:44:26 +00002889 sqlite3PagerRef(pTempCur->pPage->pDbPage);
drhecdc7532001-09-23 02:35:53 +00002890 }
drh5e2f8b92001-05-28 00:41:15 +00002891}
2892
2893/*
drhbd03cae2001-06-02 02:40:57 +00002894** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00002895** function above.
2896*/
drh16a9b832007-05-05 18:39:25 +00002897void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00002898 assert( cursorHoldsMutex(pCur) );
drhecdc7532001-09-23 02:35:53 +00002899 if( pCur->pPage ){
danielk19773b8a05f2007-03-19 17:44:26 +00002900 sqlite3PagerUnref(pCur->pPage->pDbPage);
drhecdc7532001-09-23 02:35:53 +00002901 }
drh5e2f8b92001-05-28 00:41:15 +00002902}
2903
2904/*
drh86057612007-06-26 01:04:48 +00002905** Make sure the BtCursor* given in the argument has a valid
2906** BtCursor.info structure. If it is not already valid, call
danielk19771cc5ed82007-05-16 17:28:43 +00002907** sqlite3BtreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00002908**
2909** BtCursor.info is a cache of the information in the current cell.
drh16a9b832007-05-05 18:39:25 +00002910** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
drh86057612007-06-26 01:04:48 +00002911**
2912** 2007-06-25: There is a bug in some versions of MSVC that cause the
2913** compiler to crash when getCellInfo() is implemented as a macro.
2914** But there is a measureable speed advantage to using the macro on gcc
2915** (when less compiler optimizations like -Os or -O0 are used and the
2916** compiler is not doing agressive inlining.) So we use a real function
2917** for MSVC and a macro for everything else. Ticket #2457.
drh9188b382004-05-14 21:12:22 +00002918*/
drh9188b382004-05-14 21:12:22 +00002919#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00002920 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00002921 CellInfo info;
drh51c6d962004-06-06 00:42:25 +00002922 memset(&info, 0, sizeof(info));
drh16a9b832007-05-05 18:39:25 +00002923 sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &info);
drh9188b382004-05-14 21:12:22 +00002924 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00002925 }
danielk19771cc5ed82007-05-16 17:28:43 +00002926#else
2927 #define assertCellInfo(x)
2928#endif
drh86057612007-06-26 01:04:48 +00002929#ifdef _MSC_VER
2930 /* Use a real function in MSVC to work around bugs in that compiler. */
2931 static void getCellInfo(BtCursor *pCur){
2932 if( pCur->info.nSize==0 ){
2933 sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info);
drha2c20e42008-03-29 16:01:04 +00002934 pCur->validNKey = 1;
drh86057612007-06-26 01:04:48 +00002935 }else{
2936 assertCellInfo(pCur);
2937 }
2938 }
2939#else /* if not _MSC_VER */
2940 /* Use a macro in all other compilers so that the function is inlined */
2941#define getCellInfo(pCur) \
2942 if( pCur->info.nSize==0 ){ \
danielk19771cc5ed82007-05-16 17:28:43 +00002943 sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info); \
drha2c20e42008-03-29 16:01:04 +00002944 pCur->validNKey = 1; \
drh86057612007-06-26 01:04:48 +00002945 }else{ \
2946 assertCellInfo(pCur); \
2947 }
2948#endif /* _MSC_VER */
drh9188b382004-05-14 21:12:22 +00002949
2950/*
drh3aac2dd2004-04-26 14:10:20 +00002951** Set *pSize to the size of the buffer needed to hold the value of
2952** the key for the current entry. If the cursor is not pointing
2953** to a valid entry, *pSize is set to 0.
2954**
drh4b70f112004-05-02 21:12:19 +00002955** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00002956** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00002957*/
drh4a1c3802004-05-12 15:15:47 +00002958int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drhd677b3d2007-08-20 22:48:41 +00002959 int rc;
2960
drh1fee73e2007-08-29 04:00:57 +00002961 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00002962 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00002963 if( rc==SQLITE_OK ){
2964 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
2965 if( pCur->eState==CURSOR_INVALID ){
2966 *pSize = 0;
2967 }else{
drh86057612007-06-26 01:04:48 +00002968 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00002969 *pSize = pCur->info.nKey;
2970 }
drh72f82862001-05-24 21:06:34 +00002971 }
danielk1977da184232006-01-05 11:34:32 +00002972 return rc;
drha059ad02001-04-17 20:09:11 +00002973}
drh2af926b2001-05-15 00:39:25 +00002974
drh72f82862001-05-24 21:06:34 +00002975/*
drh0e1c19e2004-05-11 00:58:56 +00002976** Set *pSize to the number of bytes of data in the entry the
2977** cursor currently points to. Always return SQLITE_OK.
2978** Failure is not possible. If the cursor is not currently
2979** pointing to an entry (which can happen, for example, if
2980** the database is empty) then *pSize is set to 0.
2981*/
2982int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drhd677b3d2007-08-20 22:48:41 +00002983 int rc;
2984
drh1fee73e2007-08-29 04:00:57 +00002985 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00002986 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00002987 if( rc==SQLITE_OK ){
2988 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
2989 if( pCur->eState==CURSOR_INVALID ){
2990 /* Not pointing at a valid entry - set *pSize to 0. */
2991 *pSize = 0;
2992 }else{
drh86057612007-06-26 01:04:48 +00002993 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00002994 *pSize = pCur->info.nData;
2995 }
drh0e1c19e2004-05-11 00:58:56 +00002996 }
danielk1977da184232006-01-05 11:34:32 +00002997 return rc;
drh0e1c19e2004-05-11 00:58:56 +00002998}
2999
3000/*
danielk1977d04417962007-05-02 13:16:30 +00003001** Given the page number of an overflow page in the database (parameter
3002** ovfl), this function finds the page number of the next page in the
3003** linked list of overflow pages. If possible, it uses the auto-vacuum
3004** pointer-map data instead of reading the content of page ovfl to do so.
3005**
3006** If an error occurs an SQLite error code is returned. Otherwise:
3007**
3008** Unless pPgnoNext is NULL, the page number of the next overflow
3009** page in the linked list is written to *pPgnoNext. If page ovfl
drh85b623f2007-12-13 21:54:09 +00003010** is the last page in its linked list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003011**
3012** If ppPage is not NULL, *ppPage is set to the MemPage* handle
3013** for page ovfl. The underlying pager page may have been requested
3014** with the noContent flag set, so the page data accessable via
3015** this handle may not be trusted.
3016*/
3017static int getOverflowPage(
3018 BtShared *pBt,
3019 Pgno ovfl, /* Overflow page */
3020 MemPage **ppPage, /* OUT: MemPage handle */
3021 Pgno *pPgnoNext /* OUT: Next overflow page number */
3022){
3023 Pgno next = 0;
3024 int rc;
3025
drh1fee73e2007-08-29 04:00:57 +00003026 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977d04417962007-05-02 13:16:30 +00003027 /* One of these must not be NULL. Otherwise, why call this function? */
3028 assert(ppPage || pPgnoNext);
3029
3030 /* If pPgnoNext is NULL, then this function is being called to obtain
3031 ** a MemPage* reference only. No page-data is required in this case.
3032 */
3033 if( !pPgnoNext ){
drh16a9b832007-05-05 18:39:25 +00003034 return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1);
danielk1977d04417962007-05-02 13:16:30 +00003035 }
3036
3037#ifndef SQLITE_OMIT_AUTOVACUUM
3038 /* Try to find the next page in the overflow list using the
3039 ** autovacuum pointer-map pages. Guess that the next page in
3040 ** the overflow list is page number (ovfl+1). If that guess turns
3041 ** out to be wrong, fall back to loading the data of page
3042 ** number ovfl to determine the next page number.
3043 */
3044 if( pBt->autoVacuum ){
3045 Pgno pgno;
3046 Pgno iGuess = ovfl+1;
3047 u8 eType;
3048
3049 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
3050 iGuess++;
3051 }
3052
danielk1977ad0132d2008-06-07 08:58:22 +00003053 if( iGuess<=pagerPagecount(pBt->pPager) ){
danielk1977d04417962007-05-02 13:16:30 +00003054 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
3055 if( rc!=SQLITE_OK ){
3056 return rc;
3057 }
3058 if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
3059 next = iGuess;
3060 }
3061 }
3062 }
3063#endif
3064
3065 if( next==0 || ppPage ){
3066 MemPage *pPage = 0;
3067
drh16a9b832007-05-05 18:39:25 +00003068 rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0);
danielk1977d04417962007-05-02 13:16:30 +00003069 assert(rc==SQLITE_OK || pPage==0);
3070 if( next==0 && rc==SQLITE_OK ){
3071 next = get4byte(pPage->aData);
3072 }
3073
3074 if( ppPage ){
3075 *ppPage = pPage;
3076 }else{
3077 releasePage(pPage);
3078 }
3079 }
3080 *pPgnoNext = next;
3081
3082 return rc;
3083}
3084
danielk1977da107192007-05-04 08:32:13 +00003085/*
3086** Copy data from a buffer to a page, or from a page to a buffer.
3087**
3088** pPayload is a pointer to data stored on database page pDbPage.
3089** If argument eOp is false, then nByte bytes of data are copied
3090** from pPayload to the buffer pointed at by pBuf. If eOp is true,
3091** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
3092** of data are copied from the buffer pBuf to pPayload.
3093**
3094** SQLITE_OK is returned on success, otherwise an error code.
3095*/
3096static int copyPayload(
3097 void *pPayload, /* Pointer to page data */
3098 void *pBuf, /* Pointer to buffer */
3099 int nByte, /* Number of bytes to copy */
3100 int eOp, /* 0 -> copy from page, 1 -> copy to page */
3101 DbPage *pDbPage /* Page containing pPayload */
3102){
3103 if( eOp ){
3104 /* Copy data from buffer to page (a write operation) */
3105 int rc = sqlite3PagerWrite(pDbPage);
3106 if( rc!=SQLITE_OK ){
3107 return rc;
3108 }
3109 memcpy(pPayload, pBuf, nByte);
3110 }else{
3111 /* Copy data from page to buffer (a read operation) */
3112 memcpy(pBuf, pPayload, nByte);
3113 }
3114 return SQLITE_OK;
3115}
danielk1977d04417962007-05-02 13:16:30 +00003116
3117/*
danielk19779f8d6402007-05-02 17:48:45 +00003118** This function is used to read or overwrite payload information
3119** for the entry that the pCur cursor is pointing to. If the eOp
3120** parameter is 0, this is a read operation (data copied into
3121** buffer pBuf). If it is non-zero, a write (data copied from
3122** buffer pBuf).
3123**
3124** A total of "amt" bytes are read or written beginning at "offset".
3125** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00003126**
3127** This routine does not make a distinction between key and data.
danielk19779f8d6402007-05-02 17:48:45 +00003128** It just reads or writes bytes from the payload area. Data might
3129** appear on the main page or be scattered out on multiple overflow
3130** pages.
danielk1977da107192007-05-04 08:32:13 +00003131**
danielk1977dcbb5d32007-05-04 18:36:44 +00003132** If the BtCursor.isIncrblobHandle flag is set, and the current
danielk1977da107192007-05-04 08:32:13 +00003133** cursor entry uses one or more overflow pages, this function
3134** allocates space for and lazily popluates the overflow page-list
3135** cache array (BtCursor.aOverflow). Subsequent calls use this
3136** cache to make seeking to the supplied offset more efficient.
3137**
3138** Once an overflow page-list cache has been allocated, it may be
3139** invalidated if some other cursor writes to the same table, or if
3140** the cursor is moved to a different row. Additionally, in auto-vacuum
3141** mode, the following events may invalidate an overflow page-list cache.
3142**
3143** * An incremental vacuum,
3144** * A commit in auto_vacuum="full" mode,
3145** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00003146*/
danielk19779f8d6402007-05-02 17:48:45 +00003147static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00003148 BtCursor *pCur, /* Cursor pointing to entry to read from */
3149 int offset, /* Begin reading this far into payload */
3150 int amt, /* Read this many bytes */
3151 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00003152 int skipKey, /* offset begins at data if this is true */
3153 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00003154){
3155 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00003156 int rc = SQLITE_OK;
drhfa1a98a2004-05-14 19:08:17 +00003157 u32 nKey;
danielk19772dec9702007-05-02 16:48:37 +00003158 int iIdx = 0;
drhd0679ed2007-08-28 22:24:34 +00003159 MemPage *pPage = pCur->pPage; /* Btree page of current cursor entry */
drh51f015e2007-10-16 19:45:29 +00003160 BtShared *pBt; /* Btree this cursor belongs to */
drh3aac2dd2004-04-26 14:10:20 +00003161
danielk1977da107192007-05-04 08:32:13 +00003162 assert( pPage );
danielk1977da184232006-01-05 11:34:32 +00003163 assert( pCur->eState==CURSOR_VALID );
drh3aac2dd2004-04-26 14:10:20 +00003164 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
danielk1977da107192007-05-04 08:32:13 +00003165 assert( offset>=0 );
drh1fee73e2007-08-29 04:00:57 +00003166 assert( cursorHoldsMutex(pCur) );
danielk1977da107192007-05-04 08:32:13 +00003167
drh86057612007-06-26 01:04:48 +00003168 getCellInfo(pCur);
drh366fda62006-01-13 02:35:09 +00003169 aPayload = pCur->info.pCell + pCur->info.nHeader;
danielk1977da107192007-05-04 08:32:13 +00003170 nKey = (pPage->intKey ? 0 : pCur->info.nKey);
3171
drh3aac2dd2004-04-26 14:10:20 +00003172 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003173 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00003174 }
drhfa1a98a2004-05-14 19:08:17 +00003175 if( offset+amt > nKey+pCur->info.nData ){
danielk1977da107192007-05-04 08:32:13 +00003176 /* Trying to read or write past the end of the data is an error */
drha34b6762004-05-07 13:30:42 +00003177 return SQLITE_ERROR;
drh3aac2dd2004-04-26 14:10:20 +00003178 }
danielk1977da107192007-05-04 08:32:13 +00003179
3180 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00003181 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00003182 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00003183 if( a+offset>pCur->info.nLocal ){
3184 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00003185 }
danielk1977da107192007-05-04 08:32:13 +00003186 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00003187 offset = 0;
drha34b6762004-05-07 13:30:42 +00003188 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00003189 amt -= a;
drhdd793422001-06-28 01:54:48 +00003190 }else{
drhfa1a98a2004-05-14 19:08:17 +00003191 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00003192 }
danielk1977da107192007-05-04 08:32:13 +00003193
drh51f015e2007-10-16 19:45:29 +00003194 pBt = pCur->pBt;
danielk1977da107192007-05-04 08:32:13 +00003195 if( rc==SQLITE_OK && amt>0 ){
3196 const int ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
3197 Pgno nextPage;
3198
drhfa1a98a2004-05-14 19:08:17 +00003199 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00003200
danielk19772dec9702007-05-02 16:48:37 +00003201#ifndef SQLITE_OMIT_INCRBLOB
danielk1977dcbb5d32007-05-04 18:36:44 +00003202 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
danielk1977da107192007-05-04 08:32:13 +00003203 ** has not been allocated, allocate it now. The array is sized at
3204 ** one entry for each overflow page in the overflow chain. The
3205 ** page number of the first overflow page is stored in aOverflow[0],
3206 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
3207 ** (the cache is lazily populated).
3208 */
danielk1977dcbb5d32007-05-04 18:36:44 +00003209 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
danielk19772dec9702007-05-02 16:48:37 +00003210 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
drh17435752007-08-16 04:30:38 +00003211 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
danielk19772dec9702007-05-02 16:48:37 +00003212 if( nOvfl && !pCur->aOverflow ){
danielk1977da107192007-05-04 08:32:13 +00003213 rc = SQLITE_NOMEM;
danielk19772dec9702007-05-02 16:48:37 +00003214 }
3215 }
danielk1977da107192007-05-04 08:32:13 +00003216
3217 /* If the overflow page-list cache has been allocated and the
3218 ** entry for the first required overflow page is valid, skip
3219 ** directly to it.
3220 */
danielk19772dec9702007-05-02 16:48:37 +00003221 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
3222 iIdx = (offset/ovflSize);
3223 nextPage = pCur->aOverflow[iIdx];
3224 offset = (offset%ovflSize);
3225 }
3226#endif
danielk1977da107192007-05-04 08:32:13 +00003227
3228 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
3229
3230#ifndef SQLITE_OMIT_INCRBLOB
3231 /* If required, populate the overflow page-list cache. */
3232 if( pCur->aOverflow ){
3233 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
3234 pCur->aOverflow[iIdx] = nextPage;
3235 }
3236#endif
3237
danielk1977d04417962007-05-02 13:16:30 +00003238 if( offset>=ovflSize ){
3239 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00003240 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00003241 ** data is not required. So first try to lookup the overflow
3242 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00003243 ** function.
danielk1977d04417962007-05-02 13:16:30 +00003244 */
danielk19772dec9702007-05-02 16:48:37 +00003245#ifndef SQLITE_OMIT_INCRBLOB
danielk1977da107192007-05-04 08:32:13 +00003246 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
3247 nextPage = pCur->aOverflow[iIdx+1];
3248 } else
danielk19772dec9702007-05-02 16:48:37 +00003249#endif
danielk1977da107192007-05-04 08:32:13 +00003250 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
danielk1977da107192007-05-04 08:32:13 +00003251 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00003252 }else{
danielk19779f8d6402007-05-02 17:48:45 +00003253 /* Need to read this page properly. It contains some of the
3254 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00003255 */
3256 DbPage *pDbPage;
danielk1977cfe9a692004-06-16 12:00:29 +00003257 int a = amt;
danielk1977d04417962007-05-02 13:16:30 +00003258 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
danielk1977da107192007-05-04 08:32:13 +00003259 if( rc==SQLITE_OK ){
3260 aPayload = sqlite3PagerGetData(pDbPage);
3261 nextPage = get4byte(aPayload);
3262 if( a + offset > ovflSize ){
3263 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00003264 }
danielk1977da107192007-05-04 08:32:13 +00003265 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
3266 sqlite3PagerUnref(pDbPage);
3267 offset = 0;
3268 amt -= a;
3269 pBuf += a;
danielk19779f8d6402007-05-02 17:48:45 +00003270 }
danielk1977cfe9a692004-06-16 12:00:29 +00003271 }
drh2af926b2001-05-15 00:39:25 +00003272 }
drh2af926b2001-05-15 00:39:25 +00003273 }
danielk1977cfe9a692004-06-16 12:00:29 +00003274
danielk1977da107192007-05-04 08:32:13 +00003275 if( rc==SQLITE_OK && amt>0 ){
drh49285702005-09-17 15:20:26 +00003276 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00003277 }
danielk1977da107192007-05-04 08:32:13 +00003278 return rc;
drh2af926b2001-05-15 00:39:25 +00003279}
3280
drh72f82862001-05-24 21:06:34 +00003281/*
drh3aac2dd2004-04-26 14:10:20 +00003282** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003283** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003284** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00003285**
drh3aac2dd2004-04-26 14:10:20 +00003286** Return SQLITE_OK on success or an error code if anything goes
3287** wrong. An error is returned if "offset+amt" is larger than
3288** the available payload.
drh72f82862001-05-24 21:06:34 +00003289*/
drha34b6762004-05-07 13:30:42 +00003290int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003291 int rc;
3292
drh1fee73e2007-08-29 04:00:57 +00003293 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003294 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003295 if( rc==SQLITE_OK ){
3296 assert( pCur->eState==CURSOR_VALID );
3297 assert( pCur->pPage!=0 );
3298 if( pCur->pPage->intKey ){
3299 return SQLITE_CORRUPT_BKPT;
3300 }
3301 assert( pCur->pPage->intKey==0 );
3302 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh16a9b832007-05-05 18:39:25 +00003303 rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
drh6575a222005-03-10 17:06:34 +00003304 }
danielk1977da184232006-01-05 11:34:32 +00003305 return rc;
drh3aac2dd2004-04-26 14:10:20 +00003306}
3307
3308/*
drh3aac2dd2004-04-26 14:10:20 +00003309** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003310** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003311** begins at "offset".
3312**
3313** Return SQLITE_OK on success or an error code if anything goes
3314** wrong. An error is returned if "offset+amt" is larger than
3315** the available payload.
drh72f82862001-05-24 21:06:34 +00003316*/
drh3aac2dd2004-04-26 14:10:20 +00003317int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003318 int rc;
3319
danielk19773588ceb2008-06-10 17:30:26 +00003320#ifndef SQLITE_OMIT_INCRBLOB
3321 if ( pCur->eState==CURSOR_INVALID ){
3322 return SQLITE_ABORT;
3323 }
3324#endif
3325
drh1fee73e2007-08-29 04:00:57 +00003326 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003327 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003328 if( rc==SQLITE_OK ){
3329 assert( pCur->eState==CURSOR_VALID );
3330 assert( pCur->pPage!=0 );
3331 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh16a9b832007-05-05 18:39:25 +00003332 rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
danielk1977da184232006-01-05 11:34:32 +00003333 }
3334 return rc;
drh2af926b2001-05-15 00:39:25 +00003335}
3336
drh72f82862001-05-24 21:06:34 +00003337/*
drh0e1c19e2004-05-11 00:58:56 +00003338** Return a pointer to payload information from the entry that the
3339** pCur cursor is pointing to. The pointer is to the beginning of
3340** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00003341** skipKey==1. The number of bytes of available key/data is written
3342** into *pAmt. If *pAmt==0, then the value returned will not be
3343** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00003344**
3345** This routine is an optimization. It is common for the entire key
3346** and data to fit on the local page and for there to be no overflow
3347** pages. When that is so, this routine can be used to access the
3348** key and data without making a copy. If the key and/or data spills
drh16a9b832007-05-05 18:39:25 +00003349** onto overflow pages, then accessPayload() must be used to reassembly
drh0e1c19e2004-05-11 00:58:56 +00003350** the key/data and copy it into a preallocated buffer.
3351**
3352** The pointer returned by this routine looks directly into the cached
3353** page of the database. The data might change or move the next time
3354** any btree routine is called.
3355*/
3356static const unsigned char *fetchPayload(
3357 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00003358 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00003359 int skipKey /* read beginning at data if this is true */
3360){
3361 unsigned char *aPayload;
3362 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00003363 u32 nKey;
3364 int nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003365
3366 assert( pCur!=0 && pCur->pPage!=0 );
danielk1977da184232006-01-05 11:34:32 +00003367 assert( pCur->eState==CURSOR_VALID );
drh1fee73e2007-08-29 04:00:57 +00003368 assert( cursorHoldsMutex(pCur) );
drh0e1c19e2004-05-11 00:58:56 +00003369 pPage = pCur->pPage;
drh0e1c19e2004-05-11 00:58:56 +00003370 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh86057612007-06-26 01:04:48 +00003371 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00003372 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00003373 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00003374 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00003375 nKey = 0;
3376 }else{
3377 nKey = pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00003378 }
drh0e1c19e2004-05-11 00:58:56 +00003379 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003380 aPayload += nKey;
3381 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00003382 }else{
drhfa1a98a2004-05-14 19:08:17 +00003383 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00003384 if( nLocal>nKey ){
3385 nLocal = nKey;
3386 }
drh0e1c19e2004-05-11 00:58:56 +00003387 }
drhe51c44f2004-05-30 20:46:09 +00003388 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003389 return aPayload;
3390}
3391
3392
3393/*
drhe51c44f2004-05-30 20:46:09 +00003394** For the entry that cursor pCur is point to, return as
3395** many bytes of the key or data as are available on the local
3396** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00003397**
3398** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00003399** or be destroyed on the next call to any Btree routine,
3400** including calls from other threads against the same cache.
3401** Hence, a mutex on the BtShared should be held prior to calling
3402** this routine.
drh0e1c19e2004-05-11 00:58:56 +00003403**
3404** These routines is used to get quick access to key and data
3405** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00003406*/
drhe51c44f2004-05-30 20:46:09 +00003407const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
drh1fee73e2007-08-29 04:00:57 +00003408 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003409 if( pCur->eState==CURSOR_VALID ){
3410 return (const void*)fetchPayload(pCur, pAmt, 0);
3411 }
3412 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003413}
drhe51c44f2004-05-30 20:46:09 +00003414const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
drh1fee73e2007-08-29 04:00:57 +00003415 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003416 if( pCur->eState==CURSOR_VALID ){
3417 return (const void*)fetchPayload(pCur, pAmt, 1);
3418 }
3419 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003420}
3421
3422
3423/*
drh8178a752003-01-05 21:41:40 +00003424** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00003425** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00003426*/
drh3aac2dd2004-04-26 14:10:20 +00003427static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00003428 int rc;
3429 MemPage *pNewPage;
drh3aac2dd2004-04-26 14:10:20 +00003430 MemPage *pOldPage;
drhd0679ed2007-08-28 22:24:34 +00003431 BtShared *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00003432
drh1fee73e2007-08-29 04:00:57 +00003433 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003434 assert( pCur->eState==CURSOR_VALID );
drhde647132004-05-07 17:57:49 +00003435 rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00003436 if( rc ) return rc;
drh428ae8c2003-01-04 16:48:09 +00003437 pNewPage->idxParent = pCur->idx;
drh3aac2dd2004-04-26 14:10:20 +00003438 pOldPage = pCur->pPage;
3439 pOldPage->idxShift = 0;
3440 releasePage(pOldPage);
drh72f82862001-05-24 21:06:34 +00003441 pCur->pPage = pNewPage;
3442 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00003443 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003444 pCur->validNKey = 0;
drh4be295b2003-12-16 03:44:47 +00003445 if( pNewPage->nCell<1 ){
drh49285702005-09-17 15:20:26 +00003446 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00003447 }
drh72f82862001-05-24 21:06:34 +00003448 return SQLITE_OK;
3449}
3450
3451/*
drh8856d6a2004-04-29 14:42:46 +00003452** Return true if the page is the virtual root of its table.
3453**
3454** The virtual root page is the root page for most tables. But
3455** for the table rooted on page 1, sometime the real root page
3456** is empty except for the right-pointer. In such cases the
3457** virtual root page is the page that the right-pointer of page
3458** 1 is pointing to.
3459*/
drh16a9b832007-05-05 18:39:25 +00003460int sqlite3BtreeIsRootPage(MemPage *pPage){
drhd677b3d2007-08-20 22:48:41 +00003461 MemPage *pParent;
3462
drh1fee73e2007-08-29 04:00:57 +00003463 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00003464 pParent = pPage->pParent;
drhda200cc2004-05-09 11:51:38 +00003465 if( pParent==0 ) return 1;
3466 if( pParent->pgno>1 ) return 0;
3467 if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
drh8856d6a2004-04-29 14:42:46 +00003468 return 0;
3469}
3470
3471/*
drh5e2f8b92001-05-28 00:41:15 +00003472** Move the cursor up to the parent page.
3473**
3474** pCur->idx is set to the cell index that contains the pointer
3475** to the page we are coming from. If we are coming from the
3476** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00003477** the largest cell index.
drh72f82862001-05-24 21:06:34 +00003478*/
drh16a9b832007-05-05 18:39:25 +00003479void sqlite3BtreeMoveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00003480 MemPage *pParent;
drh8178a752003-01-05 21:41:40 +00003481 MemPage *pPage;
drh428ae8c2003-01-04 16:48:09 +00003482 int idxParent;
drh3aac2dd2004-04-26 14:10:20 +00003483
drh1fee73e2007-08-29 04:00:57 +00003484 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003485 assert( pCur->eState==CURSOR_VALID );
drh8178a752003-01-05 21:41:40 +00003486 pPage = pCur->pPage;
3487 assert( pPage!=0 );
drh16a9b832007-05-05 18:39:25 +00003488 assert( !sqlite3BtreeIsRootPage(pPage) );
drh8178a752003-01-05 21:41:40 +00003489 pParent = pPage->pParent;
3490 assert( pParent!=0 );
3491 idxParent = pPage->idxParent;
danielk19773b8a05f2007-03-19 17:44:26 +00003492 sqlite3PagerRef(pParent->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00003493 releasePage(pPage);
drh72f82862001-05-24 21:06:34 +00003494 pCur->pPage = pParent;
drh271efa52004-05-30 19:19:05 +00003495 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003496 pCur->validNKey = 0;
drh428ae8c2003-01-04 16:48:09 +00003497 assert( pParent->idxShift==0 );
drh43605152004-05-29 21:46:49 +00003498 pCur->idx = idxParent;
drh72f82862001-05-24 21:06:34 +00003499}
3500
3501/*
3502** Move the cursor to the root page
3503*/
drh5e2f8b92001-05-28 00:41:15 +00003504static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00003505 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00003506 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003507 Btree *p = pCur->pBtree;
3508 BtShared *pBt = p->pBt;
drhbd03cae2001-06-02 02:40:57 +00003509
drh1fee73e2007-08-29 04:00:57 +00003510 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +00003511 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
3512 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
3513 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
3514 if( pCur->eState>=CURSOR_REQUIRESEEK ){
3515 if( pCur->eState==CURSOR_FAULT ){
3516 return pCur->skip;
3517 }
drhbf700f32007-03-31 02:36:44 +00003518 clearCursorPosition(pCur);
3519 }
drh777e4c42006-01-13 04:31:58 +00003520 pRoot = pCur->pPage;
danielk197797a227c2006-01-20 16:32:04 +00003521 if( pRoot && pRoot->pgno==pCur->pgnoRoot ){
drh777e4c42006-01-13 04:31:58 +00003522 assert( pRoot->isInit );
3523 }else{
3524 if(
3525 SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0))
3526 ){
3527 pCur->eState = CURSOR_INVALID;
3528 return rc;
3529 }
3530 releasePage(pCur->pPage);
drh777e4c42006-01-13 04:31:58 +00003531 pCur->pPage = pRoot;
drhc39e0002004-05-07 23:50:57 +00003532 }
drh72f82862001-05-24 21:06:34 +00003533 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00003534 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003535 pCur->atLast = 0;
3536 pCur->validNKey = 0;
drh8856d6a2004-04-29 14:42:46 +00003537 if( pRoot->nCell==0 && !pRoot->leaf ){
3538 Pgno subpage;
3539 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00003540 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00003541 assert( subpage>0 );
danielk1977da184232006-01-05 11:34:32 +00003542 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00003543 rc = moveToChild(pCur, subpage);
drh8856d6a2004-04-29 14:42:46 +00003544 }
danielk1977da184232006-01-05 11:34:32 +00003545 pCur->eState = ((pCur->pPage->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
drh8856d6a2004-04-29 14:42:46 +00003546 return rc;
drh72f82862001-05-24 21:06:34 +00003547}
drh2af926b2001-05-15 00:39:25 +00003548
drh5e2f8b92001-05-28 00:41:15 +00003549/*
3550** Move the cursor down to the left-most leaf entry beneath the
3551** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00003552**
3553** The left-most leaf is the one with the smallest key - the first
3554** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00003555*/
3556static int moveToLeftmost(BtCursor *pCur){
3557 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00003558 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00003559 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00003560
drh1fee73e2007-08-29 04:00:57 +00003561 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003562 assert( pCur->eState==CURSOR_VALID );
drhd677b3d2007-08-20 22:48:41 +00003563 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
drha34b6762004-05-07 13:30:42 +00003564 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
danielk19771cc5ed82007-05-16 17:28:43 +00003565 pgno = get4byte(findCell(pPage, pCur->idx));
drh8178a752003-01-05 21:41:40 +00003566 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00003567 }
drhd677b3d2007-08-20 22:48:41 +00003568 return rc;
drh5e2f8b92001-05-28 00:41:15 +00003569}
3570
drh2dcc9aa2002-12-04 13:40:25 +00003571/*
3572** Move the cursor down to the right-most leaf entry beneath the
3573** page to which it is currently pointing. Notice the difference
3574** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
3575** finds the left-most entry beneath the *entry* whereas moveToRightmost()
3576** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00003577**
3578** The right-most entry is the one with the largest key - the last
3579** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00003580*/
3581static int moveToRightmost(BtCursor *pCur){
3582 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00003583 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00003584 MemPage *pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003585
drh1fee73e2007-08-29 04:00:57 +00003586 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003587 assert( pCur->eState==CURSOR_VALID );
drhd677b3d2007-08-20 22:48:41 +00003588 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
drh43605152004-05-29 21:46:49 +00003589 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh3aac2dd2004-04-26 14:10:20 +00003590 pCur->idx = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00003591 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003592 }
drhd677b3d2007-08-20 22:48:41 +00003593 if( rc==SQLITE_OK ){
3594 pCur->idx = pPage->nCell - 1;
3595 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003596 pCur->validNKey = 0;
drhd677b3d2007-08-20 22:48:41 +00003597 }
drh2dcc9aa2002-12-04 13:40:25 +00003598 return SQLITE_OK;
3599}
3600
drh5e00f6c2001-09-13 13:46:56 +00003601/* Move the cursor to the first entry in the table. Return SQLITE_OK
3602** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003603** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00003604*/
drh3aac2dd2004-04-26 14:10:20 +00003605int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00003606 int rc;
drhd677b3d2007-08-20 22:48:41 +00003607
drh1fee73e2007-08-29 04:00:57 +00003608 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003609 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00003610 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003611 if( rc==SQLITE_OK ){
3612 if( pCur->eState==CURSOR_INVALID ){
3613 assert( pCur->pPage->nCell==0 );
3614 *pRes = 1;
3615 rc = SQLITE_OK;
3616 }else{
3617 assert( pCur->pPage->nCell>0 );
3618 *pRes = 0;
3619 rc = moveToLeftmost(pCur);
3620 }
drh5e00f6c2001-09-13 13:46:56 +00003621 }
drh5e00f6c2001-09-13 13:46:56 +00003622 return rc;
3623}
drh5e2f8b92001-05-28 00:41:15 +00003624
drh9562b552002-02-19 15:00:07 +00003625/* Move the cursor to the last entry in the table. Return SQLITE_OK
3626** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003627** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00003628*/
drh3aac2dd2004-04-26 14:10:20 +00003629int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00003630 int rc;
drhd677b3d2007-08-20 22:48:41 +00003631
drh1fee73e2007-08-29 04:00:57 +00003632 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003633 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh9562b552002-02-19 15:00:07 +00003634 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003635 if( rc==SQLITE_OK ){
3636 if( CURSOR_INVALID==pCur->eState ){
3637 assert( pCur->pPage->nCell==0 );
3638 *pRes = 1;
3639 }else{
3640 assert( pCur->eState==CURSOR_VALID );
3641 *pRes = 0;
3642 rc = moveToRightmost(pCur);
drha2c20e42008-03-29 16:01:04 +00003643 getCellInfo(pCur);
3644 pCur->atLast = rc==SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003645 }
drh9562b552002-02-19 15:00:07 +00003646 }
drh9562b552002-02-19 15:00:07 +00003647 return rc;
3648}
3649
drhe14006d2008-03-25 17:23:32 +00003650/* Move the cursor so that it points to an entry near the key
3651** specified by pKey/nKey/pUnKey. Return a success code.
drh72f82862001-05-24 21:06:34 +00003652**
drhe14006d2008-03-25 17:23:32 +00003653** For INTKEY tables, only the nKey parameter is used. pKey
3654** and pUnKey must be NULL. For index tables, either pUnKey
3655** must point to a key that has already been unpacked, or else
3656** pKey/nKey describes a blob containing the key.
drh3aac2dd2004-04-26 14:10:20 +00003657**
drh5e2f8b92001-05-28 00:41:15 +00003658** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00003659** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00003660** were present. The cursor might point to an entry that comes
3661** before or after the key.
3662**
drhbd03cae2001-06-02 02:40:57 +00003663** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00003664** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00003665** this value is as follows:
3666**
3667** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00003668** is smaller than pKey or if the table is empty
3669** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00003670**
3671** *pRes==0 The cursor is left pointing at an entry that
3672** exactly matches pKey.
3673**
3674** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00003675** is larger than pKey.
drhd677b3d2007-08-20 22:48:41 +00003676**
drha059ad02001-04-17 20:09:11 +00003677*/
drhe4d90812007-03-29 05:51:49 +00003678int sqlite3BtreeMoveto(
3679 BtCursor *pCur, /* The cursor to be moved */
3680 const void *pKey, /* The key content for indices. Not used by tables */
drhe14006d2008-03-25 17:23:32 +00003681 UnpackedRecord *pUnKey,/* Unpacked version of pKey */
drhe4d90812007-03-29 05:51:49 +00003682 i64 nKey, /* Size of pKey. Or the key for tables */
3683 int biasRight, /* If true, bias the search to the high end */
3684 int *pRes /* Search result flag */
3685){
drh72f82862001-05-24 21:06:34 +00003686 int rc;
drh1e968a02008-03-25 00:22:21 +00003687 char aSpace[200];
drhd677b3d2007-08-20 22:48:41 +00003688
drh1fee73e2007-08-29 04:00:57 +00003689 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003690 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drha2c20e42008-03-29 16:01:04 +00003691
3692 /* If the cursor is already positioned at the point we are trying
3693 ** to move to, then just return without doing any work */
3694 if( pCur->eState==CURSOR_VALID && pCur->validNKey && pCur->pPage->intKey ){
3695 if( pCur->info.nKey==nKey ){
3696 *pRes = 0;
3697 return SQLITE_OK;
3698 }
3699 if( pCur->atLast && pCur->info.nKey<nKey ){
3700 *pRes = -1;
3701 return SQLITE_OK;
3702 }
3703 }
3704
3705
drh5e2f8b92001-05-28 00:41:15 +00003706 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003707 if( rc ){
3708 return rc;
3709 }
drhc39e0002004-05-07 23:50:57 +00003710 assert( pCur->pPage );
3711 assert( pCur->pPage->isInit );
danielk1977da184232006-01-05 11:34:32 +00003712 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00003713 *pRes = -1;
drhc39e0002004-05-07 23:50:57 +00003714 assert( pCur->pPage->nCell==0 );
3715 return SQLITE_OK;
3716 }
drh1e968a02008-03-25 00:22:21 +00003717 if( pCur->pPage->intKey ){
drhe14006d2008-03-25 17:23:32 +00003718 /* We are given an SQL table to search. The key is the integer
3719 ** rowid contained in nKey. pKey and pUnKey should both be NULL */
3720 assert( pUnKey==0 );
3721 assert( pKey==0 );
3722 }else if( pUnKey==0 ){
3723 /* We are to search an SQL index using a key encoded as a blob.
3724 ** The blob is found at pKey and is nKey bytes in length. Unpack
3725 ** this key so that we can use it. */
3726 assert( pKey!=0 );
3727 pUnKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, nKey, pKey,
drh1e968a02008-03-25 00:22:21 +00003728 aSpace, sizeof(aSpace));
drhe14006d2008-03-25 17:23:32 +00003729 if( pUnKey==0 ) return SQLITE_NOMEM;
3730 }else{
3731 /* We are to search an SQL index using a key that is already unpacked
3732 ** and handed to us in pUnKey. */
3733 assert( pKey==0 );
drh1e968a02008-03-25 00:22:21 +00003734 }
drh14684382006-11-30 13:05:29 +00003735 for(;;){
drh72f82862001-05-24 21:06:34 +00003736 int lwr, upr;
3737 Pgno chldPg;
3738 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00003739 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00003740 lwr = 0;
3741 upr = pPage->nCell-1;
drhe14006d2008-03-25 17:23:32 +00003742 if( !pPage->intKey && pUnKey==0 ){
drh1e968a02008-03-25 00:22:21 +00003743 rc = SQLITE_CORRUPT_BKPT;
3744 goto moveto_finish;
drh4eec4c12005-01-21 00:22:37 +00003745 }
drhe4d90812007-03-29 05:51:49 +00003746 if( biasRight ){
3747 pCur->idx = upr;
3748 }else{
3749 pCur->idx = (upr+lwr)/2;
3750 }
drhf1d68b32007-03-29 04:43:26 +00003751 if( lwr<=upr ) for(;;){
danielk197713adf8a2004-06-03 16:08:41 +00003752 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00003753 i64 nCellKey;
drh366fda62006-01-13 02:35:09 +00003754 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003755 pCur->validNKey = 1;
drh3aac2dd2004-04-26 14:10:20 +00003756 if( pPage->intKey ){
drh777e4c42006-01-13 04:31:58 +00003757 u8 *pCell;
danielk19771cc5ed82007-05-16 17:28:43 +00003758 pCell = findCell(pPage, pCur->idx) + pPage->childPtrSize;
drhd172f862006-01-12 15:01:15 +00003759 if( pPage->hasData ){
danielk1977bab45c62006-01-16 15:14:27 +00003760 u32 dummy;
shane3f8d5cf2008-04-24 19:15:09 +00003761 pCell += getVarint32(pCell, dummy);
drhd172f862006-01-12 15:01:15 +00003762 }
drha2c20e42008-03-29 16:01:04 +00003763 getVarint(pCell, (u64*)&nCellKey);
drh41eb9e92008-04-02 18:33:07 +00003764 if( nCellKey==nKey ){
drh3aac2dd2004-04-26 14:10:20 +00003765 c = 0;
drh41eb9e92008-04-02 18:33:07 +00003766 }else if( nCellKey<nKey ){
3767 c = -1;
3768 }else{
3769 assert( nCellKey>nKey );
3770 c = +1;
drh3aac2dd2004-04-26 14:10:20 +00003771 }
drh3aac2dd2004-04-26 14:10:20 +00003772 }else{
drhe51c44f2004-05-30 20:46:09 +00003773 int available;
danielk197713adf8a2004-06-03 16:08:41 +00003774 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drh366fda62006-01-13 02:35:09 +00003775 nCellKey = pCur->info.nKey;
drhe51c44f2004-05-30 20:46:09 +00003776 if( available>=nCellKey ){
drhe14006d2008-03-25 17:23:32 +00003777 c = sqlite3VdbeRecordCompare(nCellKey, pCellKey, pUnKey);
drhe51c44f2004-05-30 20:46:09 +00003778 }else{
drhfacf0302008-06-17 15:12:00 +00003779 pCellKey = sqlite3Malloc( nCellKey );
danielk19776507ecb2008-03-25 09:56:44 +00003780 if( pCellKey==0 ){
3781 rc = SQLITE_NOMEM;
3782 goto moveto_finish;
3783 }
danielk197713adf8a2004-06-03 16:08:41 +00003784 rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
drhe14006d2008-03-25 17:23:32 +00003785 c = sqlite3VdbeRecordCompare(nCellKey, pCellKey, pUnKey);
drhfacf0302008-06-17 15:12:00 +00003786 sqlite3_free(pCellKey);
drh1e968a02008-03-25 00:22:21 +00003787 if( rc ) goto moveto_finish;
drhe51c44f2004-05-30 20:46:09 +00003788 }
drh3aac2dd2004-04-26 14:10:20 +00003789 }
drh72f82862001-05-24 21:06:34 +00003790 if( c==0 ){
drha2c20e42008-03-29 16:01:04 +00003791 pCur->info.nKey = nCellKey;
drh44845222008-07-17 18:39:57 +00003792 if( pPage->intKey && !pPage->leaf ){
drhfc70e6f2004-05-12 21:11:27 +00003793 lwr = pCur->idx;
3794 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00003795 break;
3796 }else{
drh8b18dd42004-05-12 19:18:15 +00003797 if( pRes ) *pRes = 0;
drh1e968a02008-03-25 00:22:21 +00003798 rc = SQLITE_OK;
3799 goto moveto_finish;
drh8b18dd42004-05-12 19:18:15 +00003800 }
drh72f82862001-05-24 21:06:34 +00003801 }
3802 if( c<0 ){
3803 lwr = pCur->idx+1;
3804 }else{
3805 upr = pCur->idx-1;
3806 }
drhf1d68b32007-03-29 04:43:26 +00003807 if( lwr>upr ){
drha2c20e42008-03-29 16:01:04 +00003808 pCur->info.nKey = nCellKey;
drhf1d68b32007-03-29 04:43:26 +00003809 break;
3810 }
3811 pCur->idx = (lwr+upr)/2;
drh72f82862001-05-24 21:06:34 +00003812 }
3813 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00003814 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00003815 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00003816 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00003817 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00003818 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00003819 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00003820 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00003821 }
3822 if( chldPg==0 ){
drhc39e0002004-05-07 23:50:57 +00003823 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00003824 if( pRes ) *pRes = c;
drh1e968a02008-03-25 00:22:21 +00003825 rc = SQLITE_OK;
3826 goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00003827 }
drh428ae8c2003-01-04 16:48:09 +00003828 pCur->idx = lwr;
drh271efa52004-05-30 19:19:05 +00003829 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003830 pCur->validNKey = 0;
drh8178a752003-01-05 21:41:40 +00003831 rc = moveToChild(pCur, chldPg);
drh1e968a02008-03-25 00:22:21 +00003832 if( rc ) goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00003833 }
drh1e968a02008-03-25 00:22:21 +00003834moveto_finish:
drhe14006d2008-03-25 17:23:32 +00003835 if( pKey ){
3836 /* If we created our own unpacked key at the top of this
3837 ** procedure, then destroy that key before returning. */
3838 sqlite3VdbeDeleteUnpackedRecord(pUnKey);
3839 }
drh1e968a02008-03-25 00:22:21 +00003840 return rc;
drh72f82862001-05-24 21:06:34 +00003841}
3842
drhd677b3d2007-08-20 22:48:41 +00003843
drh72f82862001-05-24 21:06:34 +00003844/*
drhc39e0002004-05-07 23:50:57 +00003845** Return TRUE if the cursor is not pointing at an entry of the table.
3846**
3847** TRUE will be returned after a call to sqlite3BtreeNext() moves
3848** past the last entry in the table or sqlite3BtreePrev() moves past
3849** the first entry. TRUE is also returned if the table is empty.
3850*/
3851int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00003852 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
3853 ** have been deleted? This API will need to change to return an error code
3854 ** as well as the boolean result value.
3855 */
3856 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00003857}
3858
3859/*
drhb21c8cd2007-08-21 19:33:56 +00003860** Return the database connection handle for a cursor.
3861*/
3862sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){
drhe5fe6902007-12-07 18:55:28 +00003863 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
3864 return pCur->pBtree->db;
drhb21c8cd2007-08-21 19:33:56 +00003865}
3866
3867/*
drhbd03cae2001-06-02 02:40:57 +00003868** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00003869** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00003870** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00003871** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00003872*/
drhd094db12008-04-03 21:46:57 +00003873int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00003874 int rc;
danielk197797a227c2006-01-20 16:32:04 +00003875 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00003876
drh1fee73e2007-08-29 04:00:57 +00003877 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003878 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003879 if( rc!=SQLITE_OK ){
3880 return rc;
3881 }
drh8c4d3a62007-04-06 01:03:32 +00003882 assert( pRes!=0 );
3883 pPage = pCur->pPage;
3884 if( CURSOR_INVALID==pCur->eState ){
3885 *pRes = 1;
3886 return SQLITE_OK;
3887 }
danielk1977da184232006-01-05 11:34:32 +00003888 if( pCur->skip>0 ){
3889 pCur->skip = 0;
3890 *pRes = 0;
3891 return SQLITE_OK;
3892 }
3893 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00003894
drh8178a752003-01-05 21:41:40 +00003895 assert( pPage->isInit );
drh8178a752003-01-05 21:41:40 +00003896 assert( pCur->idx<pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00003897
drh72f82862001-05-24 21:06:34 +00003898 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00003899 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003900 pCur->validNKey = 0;
drh8178a752003-01-05 21:41:40 +00003901 if( pCur->idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00003902 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003903 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00003904 if( rc ) return rc;
3905 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003906 *pRes = 0;
3907 return rc;
drh72f82862001-05-24 21:06:34 +00003908 }
drh5e2f8b92001-05-28 00:41:15 +00003909 do{
drh16a9b832007-05-05 18:39:25 +00003910 if( sqlite3BtreeIsRootPage(pPage) ){
drh8c1238a2003-01-02 14:43:55 +00003911 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00003912 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00003913 return SQLITE_OK;
3914 }
drh16a9b832007-05-05 18:39:25 +00003915 sqlite3BtreeMoveToParent(pCur);
drh8178a752003-01-05 21:41:40 +00003916 pPage = pCur->pPage;
3917 }while( pCur->idx>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00003918 *pRes = 0;
drh44845222008-07-17 18:39:57 +00003919 if( pPage->intKey ){
drh8b18dd42004-05-12 19:18:15 +00003920 rc = sqlite3BtreeNext(pCur, pRes);
3921 }else{
3922 rc = SQLITE_OK;
3923 }
3924 return rc;
drh8178a752003-01-05 21:41:40 +00003925 }
3926 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00003927 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00003928 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00003929 }
drh5e2f8b92001-05-28 00:41:15 +00003930 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003931 return rc;
drh72f82862001-05-24 21:06:34 +00003932}
drhd677b3d2007-08-20 22:48:41 +00003933
drh72f82862001-05-24 21:06:34 +00003934
drh3b7511c2001-05-26 13:15:44 +00003935/*
drh2dcc9aa2002-12-04 13:40:25 +00003936** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00003937** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00003938** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00003939** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00003940*/
drhd094db12008-04-03 21:46:57 +00003941int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00003942 int rc;
3943 Pgno pgno;
drh8178a752003-01-05 21:41:40 +00003944 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00003945
drh1fee73e2007-08-29 04:00:57 +00003946 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003947 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003948 if( rc!=SQLITE_OK ){
3949 return rc;
3950 }
drha2c20e42008-03-29 16:01:04 +00003951 pCur->atLast = 0;
drh8c4d3a62007-04-06 01:03:32 +00003952 if( CURSOR_INVALID==pCur->eState ){
3953 *pRes = 1;
3954 return SQLITE_OK;
3955 }
danielk1977da184232006-01-05 11:34:32 +00003956 if( pCur->skip<0 ){
3957 pCur->skip = 0;
3958 *pRes = 0;
3959 return SQLITE_OK;
3960 }
3961 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00003962
drh8178a752003-01-05 21:41:40 +00003963 pPage = pCur->pPage;
drh8178a752003-01-05 21:41:40 +00003964 assert( pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00003965 assert( pCur->idx>=0 );
drha34b6762004-05-07 13:30:42 +00003966 if( !pPage->leaf ){
danielk19771cc5ed82007-05-16 17:28:43 +00003967 pgno = get4byte( findCell(pPage, pCur->idx) );
drh8178a752003-01-05 21:41:40 +00003968 rc = moveToChild(pCur, pgno);
drhd677b3d2007-08-20 22:48:41 +00003969 if( rc ){
3970 return rc;
3971 }
drh2dcc9aa2002-12-04 13:40:25 +00003972 rc = moveToRightmost(pCur);
3973 }else{
3974 while( pCur->idx==0 ){
drh16a9b832007-05-05 18:39:25 +00003975 if( sqlite3BtreeIsRootPage(pPage) ){
danielk1977da184232006-01-05 11:34:32 +00003976 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00003977 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00003978 return SQLITE_OK;
3979 }
drh16a9b832007-05-05 18:39:25 +00003980 sqlite3BtreeMoveToParent(pCur);
drh8178a752003-01-05 21:41:40 +00003981 pPage = pCur->pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003982 }
3983 pCur->idx--;
drh271efa52004-05-30 19:19:05 +00003984 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003985 pCur->validNKey = 0;
drh44845222008-07-17 18:39:57 +00003986 if( pPage->intKey && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00003987 rc = sqlite3BtreePrevious(pCur, pRes);
3988 }else{
3989 rc = SQLITE_OK;
3990 }
drh2dcc9aa2002-12-04 13:40:25 +00003991 }
drh8178a752003-01-05 21:41:40 +00003992 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003993 return rc;
3994}
3995
3996/*
drh3b7511c2001-05-26 13:15:44 +00003997** Allocate a new page from the database file.
3998**
danielk19773b8a05f2007-03-19 17:44:26 +00003999** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00004000** has already been called on the new page.) The new page has also
4001** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00004002** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00004003**
4004** SQLITE_OK is returned on success. Any other return value indicates
4005** an error. *ppPage and *pPgno are undefined in the event of an error.
danielk19773b8a05f2007-03-19 17:44:26 +00004006** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00004007**
drh199e3cf2002-07-18 11:01:47 +00004008** If the "nearby" parameter is not 0, then a (feeble) effort is made to
4009** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00004010** attempt to keep related pages close to each other in the database file,
4011** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00004012**
4013** If the "exact" parameter is not 0, and the page-number nearby exists
4014** anywhere on the free-list, then it is guarenteed to be returned. This
4015** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00004016*/
drh4f0c5872007-03-26 22:05:01 +00004017static int allocateBtreePage(
danielk1977aef0bf62005-12-30 16:28:01 +00004018 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00004019 MemPage **ppPage,
4020 Pgno *pPgno,
4021 Pgno nearby,
4022 u8 exact
4023){
drh3aac2dd2004-04-26 14:10:20 +00004024 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00004025 int rc;
drh3aac2dd2004-04-26 14:10:20 +00004026 int n; /* Number of pages on the freelist */
4027 int k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00004028 MemPage *pTrunk = 0;
4029 MemPage *pPrevTrunk = 0;
drh30e58752002-03-02 20:41:57 +00004030
drh1fee73e2007-08-29 04:00:57 +00004031 assert( sqlite3_mutex_held(pBt->mutex) );
drh3aac2dd2004-04-26 14:10:20 +00004032 pPage1 = pBt->pPage1;
4033 n = get4byte(&pPage1->aData[36]);
4034 if( n>0 ){
drh91025292004-05-03 19:49:32 +00004035 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00004036 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004037 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
4038
4039 /* If the 'exact' parameter was true and a query of the pointer-map
4040 ** shows that the page 'nearby' is somewhere on the free-list, then
4041 ** the entire-list will be searched for that page.
4042 */
4043#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ad0132d2008-06-07 08:58:22 +00004044 if( exact && nearby<=pagerPagecount(pBt->pPager) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004045 u8 eType;
4046 assert( nearby>0 );
4047 assert( pBt->autoVacuum );
4048 rc = ptrmapGet(pBt, nearby, &eType, 0);
4049 if( rc ) return rc;
4050 if( eType==PTRMAP_FREEPAGE ){
4051 searchList = 1;
4052 }
4053 *pPgno = nearby;
4054 }
4055#endif
4056
4057 /* Decrement the free-list count by 1. Set iTrunk to the index of the
4058 ** first free-list trunk page. iPrevTrunk is initially 1.
4059 */
danielk19773b8a05f2007-03-19 17:44:26 +00004060 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00004061 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004062 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004063
4064 /* The code within this loop is run only once if the 'searchList' variable
4065 ** is not true. Otherwise, it runs once for each trunk-page on the
4066 ** free-list until the page 'nearby' is located.
4067 */
4068 do {
4069 pPrevTrunk = pTrunk;
4070 if( pPrevTrunk ){
4071 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00004072 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004073 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00004074 }
drh16a9b832007-05-05 18:39:25 +00004075 rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004076 if( rc ){
drhd3627af2006-12-18 18:34:51 +00004077 pTrunk = 0;
4078 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004079 }
4080
4081 k = get4byte(&pTrunk->aData[4]);
4082 if( k==0 && !searchList ){
4083 /* The trunk has no leaves and the list is not being searched.
4084 ** So extract the trunk page itself and use it as the newly
4085 ** allocated page */
4086 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00004087 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004088 if( rc ){
4089 goto end_allocate_page;
4090 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004091 *pPgno = iTrunk;
4092 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4093 *ppPage = pTrunk;
4094 pTrunk = 0;
4095 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh45b1fac2008-07-04 17:52:42 +00004096 }else if( k>pBt->usableSize/4 - 2 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004097 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00004098 rc = SQLITE_CORRUPT_BKPT;
4099 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004100#ifndef SQLITE_OMIT_AUTOVACUUM
4101 }else if( searchList && nearby==iTrunk ){
4102 /* The list is being searched and this trunk page is the page
4103 ** to allocate, regardless of whether it has leaves.
4104 */
4105 assert( *pPgno==iTrunk );
4106 *ppPage = pTrunk;
4107 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00004108 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004109 if( rc ){
4110 goto end_allocate_page;
4111 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004112 if( k==0 ){
4113 if( !pPrevTrunk ){
4114 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4115 }else{
4116 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
4117 }
4118 }else{
4119 /* The trunk page is required by the caller but it contains
4120 ** pointers to free-list leaves. The first leaf becomes a trunk
4121 ** page in this case.
4122 */
4123 MemPage *pNewTrunk;
4124 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh16a9b832007-05-05 18:39:25 +00004125 rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004126 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00004127 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004128 }
danielk19773b8a05f2007-03-19 17:44:26 +00004129 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004130 if( rc!=SQLITE_OK ){
4131 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00004132 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004133 }
4134 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
4135 put4byte(&pNewTrunk->aData[4], k-1);
4136 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00004137 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004138 if( !pPrevTrunk ){
4139 put4byte(&pPage1->aData[32], iNewTrunk);
4140 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00004141 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004142 if( rc ){
4143 goto end_allocate_page;
4144 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004145 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
4146 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004147 }
4148 pTrunk = 0;
4149 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
4150#endif
4151 }else{
4152 /* Extract a leaf from the trunk */
4153 int closest;
4154 Pgno iPage;
4155 unsigned char *aData = pTrunk->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00004156 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004157 if( rc ){
4158 goto end_allocate_page;
4159 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004160 if( nearby>0 ){
4161 int i, dist;
4162 closest = 0;
4163 dist = get4byte(&aData[8]) - nearby;
4164 if( dist<0 ) dist = -dist;
4165 for(i=1; i<k; i++){
4166 int d2 = get4byte(&aData[8+i*4]) - nearby;
4167 if( d2<0 ) d2 = -d2;
4168 if( d2<dist ){
4169 closest = i;
4170 dist = d2;
4171 }
4172 }
4173 }else{
4174 closest = 0;
4175 }
4176
4177 iPage = get4byte(&aData[8+closest*4]);
4178 if( !searchList || iPage==nearby ){
danielk1977ad0132d2008-06-07 08:58:22 +00004179 int nPage;
shane1f9e6aa2008-06-09 19:27:11 +00004180 *pPgno = iPage;
danielk1977ad0132d2008-06-07 08:58:22 +00004181 nPage = pagerPagecount(pBt->pPager);
4182 if( *pPgno>nPage ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004183 /* Free page off the end of the file */
danielk197743e377a2008-05-05 12:09:32 +00004184 rc = SQLITE_CORRUPT_BKPT;
4185 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004186 }
4187 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
4188 ": %d more free pages\n",
4189 *pPgno, closest+1, k, pTrunk->pgno, n-1));
4190 if( closest<k-1 ){
4191 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
4192 }
4193 put4byte(&aData[4], k-1);
drh16a9b832007-05-05 18:39:25 +00004194 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004195 if( rc==SQLITE_OK ){
drh538f5702007-04-13 02:14:30 +00004196 sqlite3PagerDontRollback((*ppPage)->pDbPage);
danielk19773b8a05f2007-03-19 17:44:26 +00004197 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004198 if( rc!=SQLITE_OK ){
4199 releasePage(*ppPage);
4200 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004201 }
4202 searchList = 0;
4203 }
drhee696e22004-08-30 16:52:17 +00004204 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004205 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00004206 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004207 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00004208 }else{
drh3aac2dd2004-04-26 14:10:20 +00004209 /* There are no pages on the freelist, so create a new page at the
4210 ** end of the file */
danielk1977ad0132d2008-06-07 08:58:22 +00004211 int nPage = pagerPagecount(pBt->pPager);
4212 *pPgno = nPage + 1;
danielk1977afcdd022004-10-31 16:25:42 +00004213
4214#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00004215 if( pBt->nTrunc ){
4216 /* An incr-vacuum has already run within this transaction. So the
4217 ** page to allocate is not from the physical end of the file, but
4218 ** at pBt->nTrunc.
4219 */
4220 *pPgno = pBt->nTrunc+1;
4221 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
4222 (*pPgno)++;
4223 }
4224 }
danielk1977266664d2006-02-10 08:24:21 +00004225 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00004226 /* If *pPgno refers to a pointer-map page, allocate two new pages
4227 ** at the end of the file instead of one. The first allocated page
4228 ** becomes a new pointer-map page, the second is used by the caller.
4229 */
4230 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00004231 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977afcdd022004-10-31 16:25:42 +00004232 (*pPgno)++;
drh72190432008-01-31 14:54:43 +00004233 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
danielk1977afcdd022004-10-31 16:25:42 +00004234 }
danielk1977dddbcdc2007-04-26 14:42:34 +00004235 if( pBt->nTrunc ){
4236 pBt->nTrunc = *pPgno;
4237 }
danielk1977afcdd022004-10-31 16:25:42 +00004238#endif
4239
danielk1977599fcba2004-11-08 07:13:13 +00004240 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh16a9b832007-05-05 18:39:25 +00004241 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
drh3b7511c2001-05-26 13:15:44 +00004242 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00004243 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004244 if( rc!=SQLITE_OK ){
4245 releasePage(*ppPage);
4246 }
drh3a4c1412004-05-09 20:40:11 +00004247 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00004248 }
danielk1977599fcba2004-11-08 07:13:13 +00004249
4250 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00004251
4252end_allocate_page:
4253 releasePage(pTrunk);
4254 releasePage(pPrevTrunk);
drh3b7511c2001-05-26 13:15:44 +00004255 return rc;
4256}
4257
4258/*
drh3aac2dd2004-04-26 14:10:20 +00004259** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00004260**
danielk19773b8a05f2007-03-19 17:44:26 +00004261** sqlite3PagerUnref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00004262*/
drh3aac2dd2004-04-26 14:10:20 +00004263static int freePage(MemPage *pPage){
danielk1977aef0bf62005-12-30 16:28:01 +00004264 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00004265 MemPage *pPage1 = pBt->pPage1;
4266 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00004267
drh3aac2dd2004-04-26 14:10:20 +00004268 /* Prepare the page for freeing */
drh1fee73e2007-08-29 04:00:57 +00004269 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh3aac2dd2004-04-26 14:10:20 +00004270 assert( pPage->pgno>1 );
4271 pPage->isInit = 0;
4272 releasePage(pPage->pParent);
4273 pPage->pParent = 0;
4274
drha34b6762004-05-07 13:30:42 +00004275 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00004276 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00004277 if( rc ) return rc;
4278 n = get4byte(&pPage1->aData[36]);
4279 put4byte(&pPage1->aData[36], n+1);
4280
drhfcce93f2006-02-22 03:08:32 +00004281#ifdef SQLITE_SECURE_DELETE
4282 /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
4283 ** always fully overwrite deleted information with zeros.
4284 */
danielk19773b8a05f2007-03-19 17:44:26 +00004285 rc = sqlite3PagerWrite(pPage->pDbPage);
drhfcce93f2006-02-22 03:08:32 +00004286 if( rc ) return rc;
4287 memset(pPage->aData, 0, pPage->pBt->pageSize);
4288#endif
4289
danielk1977687566d2004-11-02 12:56:41 +00004290 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00004291 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00004292 */
danielk197785d90ca2008-07-19 14:25:15 +00004293 if( ISAUTOVACUUM ){
danielk1977687566d2004-11-02 12:56:41 +00004294 rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
danielk1977a64a0352004-11-05 01:45:13 +00004295 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00004296 }
danielk1977687566d2004-11-02 12:56:41 +00004297
drh3aac2dd2004-04-26 14:10:20 +00004298 if( n==0 ){
4299 /* This is the first free page */
danielk19773b8a05f2007-03-19 17:44:26 +00004300 rc = sqlite3PagerWrite(pPage->pDbPage);
drhda200cc2004-05-09 11:51:38 +00004301 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004302 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00004303 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00004304 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00004305 }else{
4306 /* Other free pages already exist. Retrive the first trunk page
4307 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00004308 MemPage *pTrunk;
drh16a9b832007-05-05 18:39:25 +00004309 rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0);
drh3b7511c2001-05-26 13:15:44 +00004310 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004311 k = get4byte(&pTrunk->aData[4]);
drhee696e22004-08-30 16:52:17 +00004312 if( k>=pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00004313 /* The trunk is full. Turn the page being freed into a new
drh45b1fac2008-07-04 17:52:42 +00004314 ** trunk page with no leaves.
4315 **
4316 ** Note that the trunk page is not really full until it contains
4317 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
4318 ** coded. But due to a coding error in versions of SQLite prior to
4319 ** 3.6.0, databases with freelist trunk pages holding more than
4320 ** usableSize/4 - 8 entries will be reported as corrupt. In order
4321 ** to maintain backwards compatibility with older versions of SQLite,
4322 ** we will contain to restrict the number of entries to usableSize/4 - 8
4323 ** for now. At some point in the future (once everyone has upgraded
4324 ** to 3.6.0 or later) we should consider fixing the conditional above
4325 ** to read "usableSize/4-2" instead of "usableSize/4-8".
4326 */
danielk19773b8a05f2007-03-19 17:44:26 +00004327 rc = sqlite3PagerWrite(pPage->pDbPage);
drhb9ee4932007-09-07 14:32:06 +00004328 if( rc==SQLITE_OK ){
4329 put4byte(pPage->aData, pTrunk->pgno);
4330 put4byte(&pPage->aData[4], 0);
4331 put4byte(&pPage1->aData[32], pPage->pgno);
4332 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
4333 pPage->pgno, pTrunk->pgno));
4334 }
4335 }else if( k<0 ){
4336 rc = SQLITE_CORRUPT;
drh3aac2dd2004-04-26 14:10:20 +00004337 }else{
4338 /* Add the newly freed page as a leaf on the current trunk */
danielk19773b8a05f2007-03-19 17:44:26 +00004339 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00004340 if( rc==SQLITE_OK ){
4341 put4byte(&pTrunk->aData[4], k+1);
4342 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drhfcce93f2006-02-22 03:08:32 +00004343#ifndef SQLITE_SECURE_DELETE
drh538f5702007-04-13 02:14:30 +00004344 sqlite3PagerDontWrite(pPage->pDbPage);
drhfcce93f2006-02-22 03:08:32 +00004345#endif
drhf5345442007-04-09 12:45:02 +00004346 }
drh3a4c1412004-05-09 20:40:11 +00004347 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00004348 }
4349 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00004350 }
drh3b7511c2001-05-26 13:15:44 +00004351 return rc;
4352}
4353
4354/*
drh3aac2dd2004-04-26 14:10:20 +00004355** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00004356*/
drh3aac2dd2004-04-26 14:10:20 +00004357static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00004358 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00004359 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00004360 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00004361 int rc;
drh94440812007-03-06 11:42:19 +00004362 int nOvfl;
4363 int ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00004364
drh1fee73e2007-08-29 04:00:57 +00004365 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh16a9b832007-05-05 18:39:25 +00004366 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004367 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00004368 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00004369 }
drh6f11bef2004-05-13 01:12:56 +00004370 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh94440812007-03-06 11:42:19 +00004371 ovflPageSize = pBt->usableSize - 4;
drh72365832007-03-06 15:53:44 +00004372 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
4373 assert( ovflPgno==0 || nOvfl>0 );
4374 while( nOvfl-- ){
drh3aac2dd2004-04-26 14:10:20 +00004375 MemPage *pOvfl;
danielk1977ad0132d2008-06-07 08:58:22 +00004376 if( ovflPgno==0 || ovflPgno>pagerPagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00004377 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00004378 }
danielk19778c0a9592007-04-30 16:55:00 +00004379
4380 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno);
drh3b7511c2001-05-26 13:15:44 +00004381 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00004382 rc = freePage(pOvfl);
danielk19773b8a05f2007-03-19 17:44:26 +00004383 sqlite3PagerUnref(pOvfl->pDbPage);
danielk19776b456a22005-03-21 04:04:02 +00004384 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00004385 }
drh5e2f8b92001-05-28 00:41:15 +00004386 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00004387}
4388
4389/*
drh91025292004-05-03 19:49:32 +00004390** Create the byte sequence used to represent a cell on page pPage
4391** and write that byte sequence into pCell[]. Overflow pages are
4392** allocated and filled in as necessary. The calling procedure
4393** is responsible for making sure sufficient space has been allocated
4394** for pCell[].
4395**
4396** Note that pCell does not necessary need to point to the pPage->aData
4397** area. pCell might point to some temporary storage. The cell will
4398** be constructed in this temporary area then copied into pPage->aData
4399** later.
drh3b7511c2001-05-26 13:15:44 +00004400*/
4401static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00004402 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00004403 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00004404 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00004405 const void *pData,int nData, /* The data */
drhb026e052007-05-02 01:34:31 +00004406 int nZero, /* Extra zero bytes to append to pData */
drh4b70f112004-05-02 21:12:19 +00004407 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00004408){
drh3b7511c2001-05-26 13:15:44 +00004409 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00004410 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00004411 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00004412 int spaceLeft;
4413 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00004414 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00004415 unsigned char *pPrior;
4416 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00004417 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00004418 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00004419 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00004420 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00004421
drh1fee73e2007-08-29 04:00:57 +00004422 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00004423
drh91025292004-05-03 19:49:32 +00004424 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00004425 nHeader = 0;
drh91025292004-05-03 19:49:32 +00004426 if( !pPage->leaf ){
4427 nHeader += 4;
4428 }
drh8b18dd42004-05-12 19:18:15 +00004429 if( pPage->hasData ){
drhb026e052007-05-02 01:34:31 +00004430 nHeader += putVarint(&pCell[nHeader], nData+nZero);
drh6f11bef2004-05-13 01:12:56 +00004431 }else{
drhb026e052007-05-02 01:34:31 +00004432 nData = nZero = 0;
drh91025292004-05-03 19:49:32 +00004433 }
drh6f11bef2004-05-13 01:12:56 +00004434 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh16a9b832007-05-05 18:39:25 +00004435 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004436 assert( info.nHeader==nHeader );
4437 assert( info.nKey==nKey );
drhb026e052007-05-02 01:34:31 +00004438 assert( info.nData==nData+nZero );
drh6f11bef2004-05-13 01:12:56 +00004439
4440 /* Fill in the payload */
drhb026e052007-05-02 01:34:31 +00004441 nPayload = nData + nZero;
drh3aac2dd2004-04-26 14:10:20 +00004442 if( pPage->intKey ){
4443 pSrc = pData;
4444 nSrc = nData;
drh91025292004-05-03 19:49:32 +00004445 nData = 0;
drh3aac2dd2004-04-26 14:10:20 +00004446 }else{
4447 nPayload += nKey;
4448 pSrc = pKey;
4449 nSrc = nKey;
4450 }
drh6f11bef2004-05-13 01:12:56 +00004451 *pnSize = info.nSize;
4452 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00004453 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00004454 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00004455
drh3b7511c2001-05-26 13:15:44 +00004456 while( nPayload>0 ){
4457 if( spaceLeft==0 ){
danielk1977b39f70b2007-05-17 18:28:11 +00004458 int isExact = 0;
danielk1977afcdd022004-10-31 16:25:42 +00004459#ifndef SQLITE_OMIT_AUTOVACUUM
4460 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00004461 if( pBt->autoVacuum ){
4462 do{
4463 pgnoOvfl++;
4464 } while(
4465 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
4466 );
danielk197789a4be82007-05-23 13:34:32 +00004467 if( pgnoOvfl>1 ){
danielk1977b39f70b2007-05-17 18:28:11 +00004468 /* isExact = 1; */
4469 }
4470 }
danielk1977afcdd022004-10-31 16:25:42 +00004471#endif
danielk1977b39f70b2007-05-17 18:28:11 +00004472 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, isExact);
danielk1977afcdd022004-10-31 16:25:42 +00004473#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00004474 /* If the database supports auto-vacuum, and the second or subsequent
4475 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00004476 ** for that page now.
4477 **
4478 ** If this is the first overflow page, then write a partial entry
4479 ** to the pointer-map. If we write nothing to this pointer-map slot,
4480 ** then the optimistic overflow chain processing in clearCell()
4481 ** may misinterpret the uninitialised values and delete the
4482 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00004483 */
danielk19774ef24492007-05-23 09:52:41 +00004484 if( pBt->autoVacuum && rc==SQLITE_OK ){
4485 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
4486 rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
danielk197789a4be82007-05-23 13:34:32 +00004487 if( rc ){
4488 releasePage(pOvfl);
4489 }
danielk1977afcdd022004-10-31 16:25:42 +00004490 }
4491#endif
drh3b7511c2001-05-26 13:15:44 +00004492 if( rc ){
drh9b171272004-05-08 02:03:22 +00004493 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00004494 return rc;
4495 }
drh3aac2dd2004-04-26 14:10:20 +00004496 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00004497 releasePage(pToRelease);
4498 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00004499 pPrior = pOvfl->aData;
4500 put4byte(pPrior, 0);
4501 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00004502 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00004503 }
4504 n = nPayload;
4505 if( n>spaceLeft ) n = spaceLeft;
drhb026e052007-05-02 01:34:31 +00004506 if( nSrc>0 ){
4507 if( n>nSrc ) n = nSrc;
4508 assert( pSrc );
4509 memcpy(pPayload, pSrc, n);
4510 }else{
4511 memset(pPayload, 0, n);
4512 }
drh3b7511c2001-05-26 13:15:44 +00004513 nPayload -= n;
drhde647132004-05-07 17:57:49 +00004514 pPayload += n;
drh9b171272004-05-08 02:03:22 +00004515 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00004516 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00004517 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00004518 if( nSrc==0 ){
4519 nSrc = nData;
4520 pSrc = pData;
4521 }
drhdd793422001-06-28 01:54:48 +00004522 }
drh9b171272004-05-08 02:03:22 +00004523 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00004524 return SQLITE_OK;
4525}
4526
4527/*
drhbd03cae2001-06-02 02:40:57 +00004528** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00004529** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00004530** pointer in the third argument.
danielk197787c52b52008-07-19 11:49:07 +00004531**
4532** If the final argument, updatePtrmap, is non-zero and the database
4533** is an auto-vacuum database, then the pointer-map entry for pgno
4534** is updated.
drhbd03cae2001-06-02 02:40:57 +00004535*/
danielk197787c52b52008-07-19 11:49:07 +00004536static int reparentPage(
4537 BtShared *pBt, /* B-Tree structure */
4538 Pgno pgno, /* Page number of child being adopted */
4539 MemPage *pNewParent, /* New parent of pgno */
4540 int idx, /* Index of child page pgno in pNewParent */
4541 int updatePtrmap /* If true, update pointer-map for pgno */
4542){
drhbd03cae2001-06-02 02:40:57 +00004543 MemPage *pThis;
danielk19773b8a05f2007-03-19 17:44:26 +00004544 DbPage *pDbPage;
drhbd03cae2001-06-02 02:40:57 +00004545
drh1fee73e2007-08-29 04:00:57 +00004546 assert( sqlite3_mutex_held(pBt->mutex) );
drh43617e92006-03-06 20:55:46 +00004547 assert( pNewParent!=0 );
danielk1977afcdd022004-10-31 16:25:42 +00004548 if( pgno==0 ) return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00004549 assert( pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00004550 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
4551 if( pDbPage ){
4552 pThis = (MemPage *)sqlite3PagerGetExtra(pDbPage);
drhda200cc2004-05-09 11:51:38 +00004553 if( pThis->isInit ){
drhbf4bca52007-09-06 22:19:14 +00004554 assert( pThis->aData==sqlite3PagerGetData(pDbPage) );
drhda200cc2004-05-09 11:51:38 +00004555 if( pThis->pParent!=pNewParent ){
danielk19773b8a05f2007-03-19 17:44:26 +00004556 if( pThis->pParent ) sqlite3PagerUnref(pThis->pParent->pDbPage);
drhda200cc2004-05-09 11:51:38 +00004557 pThis->pParent = pNewParent;
danielk19773b8a05f2007-03-19 17:44:26 +00004558 sqlite3PagerRef(pNewParent->pDbPage);
drhda200cc2004-05-09 11:51:38 +00004559 }
4560 pThis->idxParent = idx;
drhdd793422001-06-28 01:54:48 +00004561 }
danielk19773b8a05f2007-03-19 17:44:26 +00004562 sqlite3PagerUnref(pDbPage);
drhbd03cae2001-06-02 02:40:57 +00004563 }
danielk1977afcdd022004-10-31 16:25:42 +00004564
danielk197785d90ca2008-07-19 14:25:15 +00004565 if( ISAUTOVACUUM && updatePtrmap ){
danielk1977afcdd022004-10-31 16:25:42 +00004566 return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
4567 }
danielk197787c52b52008-07-19 11:49:07 +00004568
4569#ifndef NDEBUG
4570 /* If the updatePtrmap flag was clear, assert that the entry in the
4571 ** pointer-map is already correct.
4572 */
danielk197785d90ca2008-07-19 14:25:15 +00004573 if( ISAUTOVACUUM ){
danielk197787c52b52008-07-19 11:49:07 +00004574 u8 eType;
4575 Pgno ii;
4576 ptrmapGet(pBt, pgno, &eType, &ii);
4577 assert( ii==pNewParent->pgno && eType==PTRMAP_BTREE );
4578 }
4579#endif
4580
danielk1977afcdd022004-10-31 16:25:42 +00004581 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00004582}
4583
danielk1977ac11ee62005-01-15 12:45:51 +00004584
4585
drhbd03cae2001-06-02 02:40:57 +00004586/*
drh4b70f112004-05-02 21:12:19 +00004587** Change the pParent pointer of all children of pPage to point back
4588** to pPage.
4589**
drhbd03cae2001-06-02 02:40:57 +00004590** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00004591** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00004592**
4593** This routine gets called after you memcpy() one page into
4594** another.
danielk197787c52b52008-07-19 11:49:07 +00004595**
4596** If updatePtrmap is true, then the pointer-map entries for all child
4597** pages of pPage are updated.
drhbd03cae2001-06-02 02:40:57 +00004598*/
danielk197787c52b52008-07-19 11:49:07 +00004599static int reparentChildPages(MemPage *pPage, int updatePtrmap){
danielk1977afcdd022004-10-31 16:25:42 +00004600 int rc = SQLITE_OK;
drh1fee73e2007-08-29 04:00:57 +00004601 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197787c52b52008-07-19 11:49:07 +00004602 if( !pPage->leaf ){
4603 int i;
4604 BtShared *pBt = pPage->pBt;
4605 Pgno iRight = get4byte(&pPage->aData[pPage->hdrOffset+8]);
danielk1977afcdd022004-10-31 16:25:42 +00004606
danielk197787c52b52008-07-19 11:49:07 +00004607 for(i=0; i<pPage->nCell; i++){
4608 u8 *pCell = findCell(pPage, i);
4609 rc = reparentPage(pBt, get4byte(pCell), pPage, i, updatePtrmap);
4610 if( rc!=SQLITE_OK ) return rc;
4611 }
4612 rc = reparentPage(pBt, iRight, pPage, i, updatePtrmap);
4613 pPage->idxShift = 0;
drhbd03cae2001-06-02 02:40:57 +00004614 }
danielk1977afcdd022004-10-31 16:25:42 +00004615 return rc;
drh14acc042001-06-10 19:56:58 +00004616}
4617
4618/*
4619** Remove the i-th cell from pPage. This routine effects pPage only.
4620** The cell content is not freed or deallocated. It is assumed that
4621** the cell content has been copied someplace else. This routine just
4622** removes the reference to the cell from pPage.
4623**
4624** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00004625*/
drh4b70f112004-05-02 21:12:19 +00004626static void dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00004627 int i; /* Loop counter */
4628 int pc; /* Offset to cell content of cell being deleted */
4629 u8 *data; /* pPage->aData */
4630 u8 *ptr; /* Used to move bytes around within data[] */
4631
drh8c42ca92001-06-22 19:15:00 +00004632 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00004633 assert( sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00004634 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00004635 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00004636 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00004637 ptr = &data[pPage->cellOffset + 2*idx];
4638 pc = get2byte(ptr);
4639 assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
drhde647132004-05-07 17:57:49 +00004640 freeSpace(pPage, pc, sz);
drh43605152004-05-29 21:46:49 +00004641 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
4642 ptr[0] = ptr[2];
4643 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00004644 }
4645 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00004646 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
4647 pPage->nFree += 2;
drh428ae8c2003-01-04 16:48:09 +00004648 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00004649}
4650
4651/*
4652** Insert a new cell on pPage at cell index "i". pCell points to the
4653** content of the cell.
4654**
4655** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00004656** will not fit, then make a copy of the cell content into pTemp if
4657** pTemp is not null. Regardless of pTemp, allocate a new entry
4658** in pPage->aOvfl[] and make it point to the cell content (either
4659** in pTemp or the original pCell) and also record its index.
4660** Allocating a new entry in pPage->aCell[] implies that
4661** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00004662**
4663** If nSkip is non-zero, then do not copy the first nSkip bytes of the
4664** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00004665** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00004666** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00004667*/
danielk1977e80463b2004-11-03 03:01:16 +00004668static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00004669 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00004670 int i, /* New cell becomes the i-th cell of the page */
4671 u8 *pCell, /* Content of the new cell */
4672 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00004673 u8 *pTemp, /* Temp storage space for pCell, if needed */
4674 u8 nSkip /* Do not write the first nSkip bytes of the cell */
drh24cd67e2004-05-10 16:18:47 +00004675){
drh43605152004-05-29 21:46:49 +00004676 int idx; /* Where to write new cell content in data[] */
4677 int j; /* Loop counter */
4678 int top; /* First byte of content for any cell in data[] */
4679 int end; /* First byte past the last cell pointer in data[] */
4680 int ins; /* Index in data[] where new cell pointer is inserted */
4681 int hdr; /* Offset into data[] of the page header */
4682 int cellOffset; /* Address of first cell pointer in data[] */
4683 u8 *data; /* The content of the whole page */
4684 u8 *ptr; /* Used for moving information around in data[] */
4685
4686 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
4687 assert( sz==cellSizePtr(pPage, pCell) );
drh1fee73e2007-08-29 04:00:57 +00004688 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +00004689 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00004690 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00004691 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004692 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00004693 }
drh43605152004-05-29 21:46:49 +00004694 j = pPage->nOverflow++;
4695 assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
4696 pPage->aOvfl[j].pCell = pCell;
4697 pPage->aOvfl[j].idx = i;
4698 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00004699 }else{
danielk19776e465eb2007-08-21 13:11:00 +00004700 int rc = sqlite3PagerWrite(pPage->pDbPage);
4701 if( rc!=SQLITE_OK ){
4702 return rc;
4703 }
4704 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00004705 data = pPage->aData;
4706 hdr = pPage->hdrOffset;
4707 top = get2byte(&data[hdr+5]);
4708 cellOffset = pPage->cellOffset;
4709 end = cellOffset + 2*pPage->nCell + 2;
4710 ins = cellOffset + 2*i;
4711 if( end > top - sz ){
danielk1977474b7cc2008-07-09 11:49:46 +00004712 defragmentPage(pPage);
drh43605152004-05-29 21:46:49 +00004713 top = get2byte(&data[hdr+5]);
4714 assert( end + sz <= top );
4715 }
4716 idx = allocateSpace(pPage, sz);
4717 assert( idx>0 );
4718 assert( end <= get2byte(&data[hdr+5]) );
4719 pPage->nCell++;
4720 pPage->nFree -= 2;
danielk1977a3ad5e72005-01-07 08:56:44 +00004721 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004722 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
4723 ptr[0] = ptr[-2];
4724 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00004725 }
drh43605152004-05-29 21:46:49 +00004726 put2byte(&data[ins], idx);
4727 put2byte(&data[hdr+3], pPage->nCell);
4728 pPage->idxShift = 1;
danielk1977a19df672004-11-03 11:37:07 +00004729#ifndef SQLITE_OMIT_AUTOVACUUM
4730 if( pPage->pBt->autoVacuum ){
4731 /* The cell may contain a pointer to an overflow page. If so, write
4732 ** the entry for the overflow page into the pointer map.
4733 */
4734 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00004735 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh72365832007-03-06 15:53:44 +00004736 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk1977a19df672004-11-03 11:37:07 +00004737 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
4738 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
danielk19776e465eb2007-08-21 13:11:00 +00004739 rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
danielk1977a19df672004-11-03 11:37:07 +00004740 if( rc!=SQLITE_OK ) return rc;
4741 }
4742 }
4743#endif
drh14acc042001-06-10 19:56:58 +00004744 }
danielk1977e80463b2004-11-03 03:01:16 +00004745
danielk1977e80463b2004-11-03 03:01:16 +00004746 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004747}
4748
4749/*
drhfa1a98a2004-05-14 19:08:17 +00004750** Add a list of cells to a page. The page should be initially empty.
4751** The cells are guaranteed to fit on the page.
4752*/
4753static void assemblePage(
4754 MemPage *pPage, /* The page to be assemblied */
4755 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00004756 u8 **apCell, /* Pointers to cell bodies */
drha9121e42008-02-19 14:59:35 +00004757 u16 *aSize /* Sizes of the cells */
drhfa1a98a2004-05-14 19:08:17 +00004758){
4759 int i; /* Loop counter */
4760 int totalSize; /* Total size of all cells */
4761 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00004762 int cellptr; /* Address of next cell pointer */
4763 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00004764 u8 *data; /* Data for the page */
4765
drh43605152004-05-29 21:46:49 +00004766 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00004767 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa1a98a2004-05-14 19:08:17 +00004768 totalSize = 0;
4769 for(i=0; i<nCell; i++){
4770 totalSize += aSize[i];
4771 }
drh43605152004-05-29 21:46:49 +00004772 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00004773 assert( pPage->nCell==0 );
drh43605152004-05-29 21:46:49 +00004774 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00004775 data = pPage->aData;
4776 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00004777 put2byte(&data[hdr+3], nCell);
drh09d0deb2005-08-02 17:13:09 +00004778 if( nCell ){
4779 cellbody = allocateSpace(pPage, totalSize);
4780 assert( cellbody>0 );
4781 assert( pPage->nFree >= 2*nCell );
4782 pPage->nFree -= 2*nCell;
4783 for(i=0; i<nCell; i++){
4784 put2byte(&data[cellptr], cellbody);
4785 memcpy(&data[cellbody], apCell[i], aSize[i]);
4786 cellptr += 2;
4787 cellbody += aSize[i];
4788 }
4789 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00004790 }
4791 pPage->nCell = nCell;
drhfa1a98a2004-05-14 19:08:17 +00004792}
4793
drh14acc042001-06-10 19:56:58 +00004794/*
drhc3b70572003-01-04 19:44:07 +00004795** The following parameters determine how many adjacent pages get involved
4796** in a balancing operation. NN is the number of neighbors on either side
4797** of the page that participate in the balancing operation. NB is the
4798** total number of pages that participate, including the target page and
4799** NN neighbors on either side.
4800**
4801** The minimum value of NN is 1 (of course). Increasing NN above 1
4802** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
4803** in exchange for a larger degradation in INSERT and UPDATE performance.
4804** The value of NN appears to give the best results overall.
4805*/
4806#define NN 1 /* Number of neighbors on either side of pPage */
4807#define NB (NN*2+1) /* Total pages involved in the balance */
4808
drh43605152004-05-29 21:46:49 +00004809/* Forward reference */
danielk1977ac245ec2005-01-14 13:50:11 +00004810static int balance(MemPage*, int);
4811
drh615ae552005-01-16 23:21:00 +00004812#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004813/*
4814** This version of balance() handles the common special case where
4815** a new entry is being inserted on the extreme right-end of the
4816** tree, in other words, when the new entry will become the largest
4817** entry in the tree.
4818**
4819** Instead of trying balance the 3 right-most leaf pages, just add
4820** a new page to the right-hand side and put the one new entry in
4821** that page. This leaves the right side of the tree somewhat
4822** unbalanced. But odds are that we will be inserting new entries
4823** at the end soon afterwards so the nearly empty page will quickly
4824** fill up. On average.
4825**
4826** pPage is the leaf page which is the right-most page in the tree.
4827** pParent is its parent. pPage must have a single overflow entry
4828** which is also the right-most entry on the page.
4829*/
danielk1977ac245ec2005-01-14 13:50:11 +00004830static int balance_quick(MemPage *pPage, MemPage *pParent){
4831 int rc;
4832 MemPage *pNew;
4833 Pgno pgnoNew;
4834 u8 *pCell;
drha9121e42008-02-19 14:59:35 +00004835 u16 szCell;
danielk1977ac245ec2005-01-14 13:50:11 +00004836 CellInfo info;
danielk1977aef0bf62005-12-30 16:28:01 +00004837 BtShared *pBt = pPage->pBt;
danielk197779a40da2005-01-16 08:00:01 +00004838 int parentIdx = pParent->nCell; /* pParent new divider cell index */
4839 int parentSize; /* Size of new divider cell */
4840 u8 parentCell[64]; /* Space for the new divider cell */
danielk1977ac245ec2005-01-14 13:50:11 +00004841
drh1fee73e2007-08-29 04:00:57 +00004842 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00004843
danielk1977ac245ec2005-01-14 13:50:11 +00004844 /* Allocate a new page. Insert the overflow cell from pPage
4845 ** into it. Then remove the overflow cell from pPage.
4846 */
drh4f0c5872007-03-26 22:05:01 +00004847 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk1977ac245ec2005-01-14 13:50:11 +00004848 if( rc!=SQLITE_OK ){
4849 return rc;
4850 }
4851 pCell = pPage->aOvfl[0].pCell;
4852 szCell = cellSizePtr(pPage, pCell);
4853 zeroPage(pNew, pPage->aData[0]);
4854 assemblePage(pNew, 1, &pCell, &szCell);
4855 pPage->nOverflow = 0;
4856
danielk197779a40da2005-01-16 08:00:01 +00004857 /* Set the parent of the newly allocated page to pParent. */
4858 pNew->pParent = pParent;
danielk19773b8a05f2007-03-19 17:44:26 +00004859 sqlite3PagerRef(pParent->pDbPage);
danielk197779a40da2005-01-16 08:00:01 +00004860
danielk1977ac245ec2005-01-14 13:50:11 +00004861 /* pPage is currently the right-child of pParent. Change this
4862 ** so that the right-child is the new page allocated above and
danielk197779a40da2005-01-16 08:00:01 +00004863 ** pPage is the next-to-right child.
danielk1977474b7cc2008-07-09 11:49:46 +00004864 **
4865 ** Ignore the return value of the call to fillInCell(). fillInCell()
4866 ** may only return other than SQLITE_OK if it is required to allocate
4867 ** one or more overflow pages. Since an internal table B-Tree cell
4868 ** may never spill over onto an overflow page (it is a maximum of
4869 ** 13 bytes in size), it is not neccessary to check the return code.
4870 **
4871 ** Similarly, the insertCell() function cannot fail if the page
4872 ** being inserted into is already writable and the cell does not
4873 ** contain an overflow pointer. So ignore this return code too.
danielk1977ac245ec2005-01-14 13:50:11 +00004874 */
danielk1977ac11ee62005-01-15 12:45:51 +00004875 assert( pPage->nCell>0 );
danielk19771cc5ed82007-05-16 17:28:43 +00004876 pCell = findCell(pPage, pPage->nCell-1);
drh16a9b832007-05-05 18:39:25 +00004877 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
danielk1977474b7cc2008-07-09 11:49:46 +00004878 fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
danielk1977ac245ec2005-01-14 13:50:11 +00004879 assert( parentSize<64 );
danielk1977474b7cc2008-07-09 11:49:46 +00004880 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
4881 insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
danielk1977ac245ec2005-01-14 13:50:11 +00004882 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
4883 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
4884
danielk197779a40da2005-01-16 08:00:01 +00004885 /* If this is an auto-vacuum database, update the pointer map
4886 ** with entries for the new page, and any pointer from the
4887 ** cell on the page to an overflow page.
4888 */
danielk197785d90ca2008-07-19 14:25:15 +00004889 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00004890 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
danielk1977deb403e2007-05-24 09:20:16 +00004891 if( rc==SQLITE_OK ){
4892 rc = ptrmapPutOvfl(pNew, 0);
danielk1977ac11ee62005-01-15 12:45:51 +00004893 }
danielk197779a40da2005-01-16 08:00:01 +00004894 if( rc!=SQLITE_OK ){
danielk1977deb403e2007-05-24 09:20:16 +00004895 releasePage(pNew);
danielk197779a40da2005-01-16 08:00:01 +00004896 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00004897 }
4898 }
4899
danielk197779a40da2005-01-16 08:00:01 +00004900 /* Release the reference to the new page and balance the parent page,
4901 ** in case the divider cell inserted caused it to become overfull.
4902 */
danielk1977ac245ec2005-01-14 13:50:11 +00004903 releasePage(pNew);
4904 return balance(pParent, 0);
4905}
drh615ae552005-01-16 23:21:00 +00004906#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00004907
drhc3b70572003-01-04 19:44:07 +00004908/*
drhab01f612004-05-22 02:55:23 +00004909** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00004910** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00004911** Usually NN siblings on either side of pPage is used in the balancing,
4912** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00004913** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00004914** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00004915** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00004916**
drh0c6cc4e2004-06-15 02:13:26 +00004917** The number of siblings of pPage might be increased or decreased by one or
4918** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00004919** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00004920** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00004921** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00004922** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00004923**
drh8b2f49b2001-06-08 00:21:52 +00004924** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00004925** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00004926** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00004927** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00004928**
drh8c42ca92001-06-22 19:15:00 +00004929** In the course of balancing the siblings of pPage, the parent of pPage
4930** might become overfull or underfull. If that happens, then this routine
4931** is called recursively on the parent.
4932**
drh5e00f6c2001-09-13 13:46:56 +00004933** If this routine fails for any reason, it might leave the database
4934** in a corrupted state. So if this routine fails, the database should
4935** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00004936*/
drh43605152004-05-29 21:46:49 +00004937static int balance_nonroot(MemPage *pPage){
drh8b2f49b2001-06-08 00:21:52 +00004938 MemPage *pParent; /* The parent of pPage */
drh16a9b832007-05-05 18:39:25 +00004939 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00004940 int nCell = 0; /* Number of cells in apCell[] */
4941 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
drh8b2f49b2001-06-08 00:21:52 +00004942 int nOld; /* Number of pages in apOld[] */
4943 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00004944 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00004945 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00004946 int idx; /* Index of pPage in pParent->aCell[] */
4947 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00004948 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00004949 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00004950 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00004951 int usableSpace; /* Bytes in pPage beyond the header */
4952 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00004953 int subtotal; /* Subtotal of bytes in cells on one page */
drhe5ae5732008-06-15 02:51:47 +00004954 int iSpace1 = 0; /* First unused byte of aSpace1[] */
4955 int iSpace2 = 0; /* First unused byte of aSpace2[] */
drhfacf0302008-06-17 15:12:00 +00004956 int szScratch; /* Size of scratch memory requested */
drhc3b70572003-01-04 19:44:07 +00004957 MemPage *apOld[NB]; /* pPage and up to two siblings */
4958 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00004959 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00004960 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
4961 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drh4b70f112004-05-02 21:12:19 +00004962 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00004963 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
4964 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00004965 u8 **apCell = 0; /* All cells begin balanced */
drha9121e42008-02-19 14:59:35 +00004966 u16 *szCell; /* Local size of all cells in apCell[] */
drhe5ae5732008-06-15 02:51:47 +00004967 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
4968 u8 *aSpace1; /* Space for copies of dividers cells before balance */
4969 u8 *aSpace2 = 0; /* Space for overflow dividers cells after balance */
danielk1977ac11ee62005-01-15 12:45:51 +00004970 u8 *aFrom = 0;
drh8b2f49b2001-06-08 00:21:52 +00004971
drh1fee73e2007-08-29 04:00:57 +00004972 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00004973
drh14acc042001-06-10 19:56:58 +00004974 /*
drh43605152004-05-29 21:46:49 +00004975 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00004976 */
drh3a4c1412004-05-09 20:40:11 +00004977 assert( pPage->isInit );
danielk19776e465eb2007-08-21 13:11:00 +00004978 assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 );
drh4b70f112004-05-02 21:12:19 +00004979 pBt = pPage->pBt;
drh14acc042001-06-10 19:56:58 +00004980 pParent = pPage->pParent;
drh43605152004-05-29 21:46:49 +00004981 assert( pParent );
danielk19773b8a05f2007-03-19 17:44:26 +00004982 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
danielk197707cb5602006-01-20 10:55:05 +00004983 return rc;
4984 }
danielk1977474b7cc2008-07-09 11:49:46 +00004985
drh43605152004-05-29 21:46:49 +00004986 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00004987
drh615ae552005-01-16 23:21:00 +00004988#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004989 /*
4990 ** A special case: If a new entry has just been inserted into a
4991 ** table (that is, a btree with integer keys and all data at the leaves)
drh09d0deb2005-08-02 17:13:09 +00004992 ** and the new entry is the right-most entry in the tree (it has the
drhf222e712005-01-14 22:55:49 +00004993 ** largest key) then use the special balance_quick() routine for
4994 ** balancing. balance_quick() is much faster and results in a tighter
4995 ** packing of data in the common case.
4996 */
danielk1977ac245ec2005-01-14 13:50:11 +00004997 if( pPage->leaf &&
4998 pPage->intKey &&
danielk1977ac245ec2005-01-14 13:50:11 +00004999 pPage->nOverflow==1 &&
5000 pPage->aOvfl[0].idx==pPage->nCell &&
danielk1977ac11ee62005-01-15 12:45:51 +00005001 pPage->pParent->pgno!=1 &&
danielk1977ac245ec2005-01-14 13:50:11 +00005002 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
5003 ){
drh44845222008-07-17 18:39:57 +00005004 assert( pPage->intKey );
danielk1977ac11ee62005-01-15 12:45:51 +00005005 /*
5006 ** TODO: Check the siblings to the left of pPage. It may be that
5007 ** they are not full and no new page is required.
5008 */
danielk1977ac245ec2005-01-14 13:50:11 +00005009 return balance_quick(pPage, pParent);
5010 }
5011#endif
5012
danielk19776e465eb2007-08-21 13:11:00 +00005013 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){
5014 return rc;
5015 }
5016
drh2e38c322004-09-03 18:38:44 +00005017 /*
drh4b70f112004-05-02 21:12:19 +00005018 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00005019 ** to pPage. The "idx" variable is the index of that cell. If pPage
5020 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00005021 */
drhbb49aba2003-01-04 18:53:27 +00005022 if( pParent->idxShift ){
drha34b6762004-05-07 13:30:42 +00005023 Pgno pgno;
drh4b70f112004-05-02 21:12:19 +00005024 pgno = pPage->pgno;
danielk19773b8a05f2007-03-19 17:44:26 +00005025 assert( pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbb49aba2003-01-04 18:53:27 +00005026 for(idx=0; idx<pParent->nCell; idx++){
danielk19771cc5ed82007-05-16 17:28:43 +00005027 if( get4byte(findCell(pParent, idx))==pgno ){
drhbb49aba2003-01-04 18:53:27 +00005028 break;
5029 }
drh8b2f49b2001-06-08 00:21:52 +00005030 }
drh4b70f112004-05-02 21:12:19 +00005031 assert( idx<pParent->nCell
drh43605152004-05-29 21:46:49 +00005032 || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
drhbb49aba2003-01-04 18:53:27 +00005033 }else{
5034 idx = pPage->idxParent;
drh8b2f49b2001-06-08 00:21:52 +00005035 }
drh8b2f49b2001-06-08 00:21:52 +00005036
5037 /*
drh14acc042001-06-10 19:56:58 +00005038 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00005039 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00005040 */
drh14acc042001-06-10 19:56:58 +00005041 nOld = nNew = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00005042 sqlite3PagerRef(pParent->pDbPage);
drh14acc042001-06-10 19:56:58 +00005043
5044 /*
drh4b70f112004-05-02 21:12:19 +00005045 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00005046 ** the siblings. An attempt is made to find NN siblings on either
5047 ** side of pPage. More siblings are taken from one side, however, if
5048 ** pPage there are fewer than NN siblings on the other side. If pParent
5049 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00005050 */
drhc3b70572003-01-04 19:44:07 +00005051 nxDiv = idx - NN;
5052 if( nxDiv + NB > pParent->nCell ){
5053 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00005054 }
drhc3b70572003-01-04 19:44:07 +00005055 if( nxDiv<0 ){
5056 nxDiv = 0;
5057 }
drh8b2f49b2001-06-08 00:21:52 +00005058 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00005059 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00005060 if( k<pParent->nCell ){
danielk19771cc5ed82007-05-16 17:28:43 +00005061 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00005062 nDiv++;
drha34b6762004-05-07 13:30:42 +00005063 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00005064 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00005065 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00005066 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00005067 }else{
5068 break;
drh8b2f49b2001-06-08 00:21:52 +00005069 }
drhde647132004-05-07 17:57:49 +00005070 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00005071 if( rc ) goto balance_cleanup;
drh428ae8c2003-01-04 16:48:09 +00005072 apOld[i]->idxParent = k;
drh91025292004-05-03 19:49:32 +00005073 apCopy[i] = 0;
5074 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00005075 nOld++;
danielk1977634f2982005-03-28 08:44:07 +00005076 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
drh8b2f49b2001-06-08 00:21:52 +00005077 }
5078
drha9121e42008-02-19 14:59:35 +00005079 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00005080 ** alignment */
drha9121e42008-02-19 14:59:35 +00005081 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00005082
drh8b2f49b2001-06-08 00:21:52 +00005083 /*
danielk1977634f2982005-03-28 08:44:07 +00005084 ** Allocate space for memory structures
5085 */
drhfacf0302008-06-17 15:12:00 +00005086 szScratch =
drha9121e42008-02-19 14:59:35 +00005087 nMaxCells*sizeof(u8*) /* apCell */
5088 + nMaxCells*sizeof(u16) /* szCell */
5089 + (ROUND8(sizeof(MemPage))+pBt->pageSize)*NB /* aCopy */
drhe5ae5732008-06-15 02:51:47 +00005090 + pBt->pageSize /* aSpace1 */
drhfacf0302008-06-17 15:12:00 +00005091 + (ISAUTOVACUUM ? nMaxCells : 0); /* aFrom */
5092 apCell = sqlite3ScratchMalloc( szScratch );
danielk1977634f2982005-03-28 08:44:07 +00005093 if( apCell==0 ){
5094 rc = SQLITE_NOMEM;
5095 goto balance_cleanup;
5096 }
drha9121e42008-02-19 14:59:35 +00005097 szCell = (u16*)&apCell[nMaxCells];
danielk1977634f2982005-03-28 08:44:07 +00005098 aCopy[0] = (u8*)&szCell[nMaxCells];
drhc96d8532005-05-03 12:30:33 +00005099 assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00005100 for(i=1; i<NB; i++){
drhc96d8532005-05-03 12:30:33 +00005101 aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
5102 assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00005103 }
drhe5ae5732008-06-15 02:51:47 +00005104 aSpace1 = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
5105 assert( ((aSpace1 - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk197785d90ca2008-07-19 14:25:15 +00005106 if( ISAUTOVACUUM ){
drhe5ae5732008-06-15 02:51:47 +00005107 aFrom = &aSpace1[pBt->pageSize];
danielk1977634f2982005-03-28 08:44:07 +00005108 }
drhfacf0302008-06-17 15:12:00 +00005109 aSpace2 = sqlite3PageMalloc(pBt->pageSize);
drhe5ae5732008-06-15 02:51:47 +00005110 if( aSpace2==0 ){
5111 rc = SQLITE_NOMEM;
5112 goto balance_cleanup;
5113 }
danielk1977634f2982005-03-28 08:44:07 +00005114
5115 /*
drh14acc042001-06-10 19:56:58 +00005116 ** Make copies of the content of pPage and its siblings into aOld[].
5117 ** The rest of this function will use data from the copies rather
5118 ** that the original pages since the original pages will be in the
5119 ** process of being overwritten.
5120 */
5121 for(i=0; i<nOld; i++){
drhbf4bca52007-09-06 22:19:14 +00005122 MemPage *p = apCopy[i] = (MemPage*)aCopy[i];
5123 memcpy(p, apOld[i], sizeof(MemPage));
5124 p->aData = (void*)&p[1];
5125 memcpy(p->aData, apOld[i]->aData, pBt->pageSize);
drh14acc042001-06-10 19:56:58 +00005126 }
5127
5128 /*
5129 ** Load pointers to all cells on sibling pages and the divider cells
5130 ** into the local apCell[] array. Make copies of the divider cells
drhe5ae5732008-06-15 02:51:47 +00005131 ** into space obtained form aSpace1[] and remove the the divider Cells
drhb6f41482004-05-14 01:58:11 +00005132 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00005133 **
5134 ** If the siblings are on leaf pages, then the child pointers of the
5135 ** divider cells are stripped from the cells before they are copied
drhe5ae5732008-06-15 02:51:47 +00005136 ** into aSpace1[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00005137 ** child pointers. If siblings are not leaves, then all cell in
5138 ** apCell[] include child pointers. Either way, all cells in apCell[]
5139 ** are alike.
drh96f5b762004-05-16 16:24:36 +00005140 **
5141 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
5142 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00005143 */
5144 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00005145 leafCorrection = pPage->leaf*4;
drh44845222008-07-17 18:39:57 +00005146 leafData = pPage->hasData;
drh8b2f49b2001-06-08 00:21:52 +00005147 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00005148 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00005149 int limit = pOld->nCell+pOld->nOverflow;
5150 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00005151 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00005152 apCell[nCell] = findOverflowCell(pOld, j);
5153 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk197785d90ca2008-07-19 14:25:15 +00005154 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005155 int a;
5156 aFrom[nCell] = i;
5157 for(a=0; a<pOld->nOverflow; a++){
5158 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
5159 aFrom[nCell] = 0xFF;
5160 break;
5161 }
5162 }
5163 }
drh14acc042001-06-10 19:56:58 +00005164 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00005165 }
5166 if( i<nOld-1 ){
drha9121e42008-02-19 14:59:35 +00005167 u16 sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00005168 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00005169 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
5170 ** are duplicates of keys on the child pages. We need to remove
5171 ** the divider cells from pParent, but the dividers cells are not
5172 ** added to apCell[] because they are duplicates of child cells.
5173 */
drh8b18dd42004-05-12 19:18:15 +00005174 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00005175 }else{
drhb6f41482004-05-14 01:58:11 +00005176 u8 *pTemp;
danielk1977634f2982005-03-28 08:44:07 +00005177 assert( nCell<nMaxCells );
drhb6f41482004-05-14 01:58:11 +00005178 szCell[nCell] = sz;
drhe5ae5732008-06-15 02:51:47 +00005179 pTemp = &aSpace1[iSpace1];
5180 iSpace1 += sz;
5181 assert( sz<=pBt->pageSize/4 );
5182 assert( iSpace1<=pBt->pageSize );
drhb6f41482004-05-14 01:58:11 +00005183 memcpy(pTemp, apDiv[i], sz);
5184 apCell[nCell] = pTemp+leafCorrection;
danielk197785d90ca2008-07-19 14:25:15 +00005185 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005186 aFrom[nCell] = 0xFF;
5187 }
drhb6f41482004-05-14 01:58:11 +00005188 dropCell(pParent, nxDiv, sz);
drh8b18dd42004-05-12 19:18:15 +00005189 szCell[nCell] -= leafCorrection;
drh43605152004-05-29 21:46:49 +00005190 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00005191 if( !pOld->leaf ){
5192 assert( leafCorrection==0 );
5193 /* The right pointer of the child page pOld becomes the left
5194 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00005195 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00005196 }else{
5197 assert( leafCorrection==4 );
danielk197739c96042007-05-12 10:41:47 +00005198 if( szCell[nCell]<4 ){
5199 /* Do not allow any cells smaller than 4 bytes. */
5200 szCell[nCell] = 4;
5201 }
drh8b18dd42004-05-12 19:18:15 +00005202 }
5203 nCell++;
drh4b70f112004-05-02 21:12:19 +00005204 }
drh8b2f49b2001-06-08 00:21:52 +00005205 }
5206 }
5207
5208 /*
drh6019e162001-07-02 17:51:45 +00005209 ** Figure out the number of pages needed to hold all nCell cells.
5210 ** Store this number in "k". Also compute szNew[] which is the total
5211 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00005212 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00005213 ** cntNew[k] should equal nCell.
5214 **
drh96f5b762004-05-16 16:24:36 +00005215 ** Values computed by this block:
5216 **
5217 ** k: The total number of sibling pages
5218 ** szNew[i]: Spaced used on the i-th sibling page.
5219 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
5220 ** the right of the i-th sibling page.
5221 ** usableSpace: Number of bytes of space available on each sibling.
5222 **
drh8b2f49b2001-06-08 00:21:52 +00005223 */
drh43605152004-05-29 21:46:49 +00005224 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00005225 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00005226 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00005227 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00005228 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00005229 szNew[k] = subtotal - szCell[i];
5230 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00005231 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00005232 subtotal = 0;
5233 k++;
5234 }
5235 }
5236 szNew[k] = subtotal;
5237 cntNew[k] = nCell;
5238 k++;
drh96f5b762004-05-16 16:24:36 +00005239
5240 /*
5241 ** The packing computed by the previous block is biased toward the siblings
5242 ** on the left side. The left siblings are always nearly full, while the
5243 ** right-most sibling might be nearly empty. This block of code attempts
5244 ** to adjust the packing of siblings to get a better balance.
5245 **
5246 ** This adjustment is more than an optimization. The packing above might
5247 ** be so out of balance as to be illegal. For example, the right-most
5248 ** sibling might be completely empty. This adjustment is not optional.
5249 */
drh6019e162001-07-02 17:51:45 +00005250 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00005251 int szRight = szNew[i]; /* Size of sibling on the right */
5252 int szLeft = szNew[i-1]; /* Size of sibling on the left */
5253 int r; /* Index of right-most cell in left sibling */
5254 int d; /* Index of first cell to the left of right sibling */
5255
5256 r = cntNew[i-1] - 1;
5257 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00005258 assert( d<nMaxCells );
5259 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00005260 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
5261 szRight += szCell[d] + 2;
5262 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00005263 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00005264 r = cntNew[i-1] - 1;
5265 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00005266 }
drh96f5b762004-05-16 16:24:36 +00005267 szNew[i] = szRight;
5268 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00005269 }
drh09d0deb2005-08-02 17:13:09 +00005270
5271 /* Either we found one or more cells (cntnew[0])>0) or we are the
5272 ** a virtual root page. A virtual root page is when the real root
5273 ** page is page 1 and we are the only child of that page.
5274 */
5275 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00005276
5277 /*
drh6b308672002-07-08 02:16:37 +00005278 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00005279 */
drh4b70f112004-05-02 21:12:19 +00005280 assert( pPage->pgno>1 );
5281 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00005282 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00005283 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00005284 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00005285 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00005286 pgnoNew[i] = pgnoOld[i];
5287 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00005288 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00005289 nNew++;
danielk197728129562005-01-11 10:25:06 +00005290 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00005291 }else{
drh7aa8f852006-03-28 00:24:44 +00005292 assert( i>0 );
drh4f0c5872007-03-26 22:05:01 +00005293 rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
drh6b308672002-07-08 02:16:37 +00005294 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00005295 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00005296 nNew++;
drh6b308672002-07-08 02:16:37 +00005297 }
drh8b2f49b2001-06-08 00:21:52 +00005298 }
5299
danielk1977299b1872004-11-22 10:02:10 +00005300 /* Free any old pages that were not reused as new pages.
5301 */
5302 while( i<nOld ){
5303 rc = freePage(apOld[i]);
5304 if( rc ) goto balance_cleanup;
5305 releasePage(apOld[i]);
5306 apOld[i] = 0;
5307 i++;
5308 }
5309
drh8b2f49b2001-06-08 00:21:52 +00005310 /*
drhf9ffac92002-03-02 19:00:31 +00005311 ** Put the new pages in accending order. This helps to
5312 ** keep entries in the disk file in order so that a scan
5313 ** of the table is a linear scan through the file. That
5314 ** in turn helps the operating system to deliver pages
5315 ** from the disk more rapidly.
5316 **
5317 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00005318 ** n is never more than NB (a small constant), that should
5319 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00005320 **
drhc3b70572003-01-04 19:44:07 +00005321 ** When NB==3, this one optimization makes the database
5322 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00005323 */
5324 for(i=0; i<k-1; i++){
5325 int minV = pgnoNew[i];
5326 int minI = i;
5327 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00005328 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00005329 minI = j;
5330 minV = pgnoNew[j];
5331 }
5332 }
5333 if( minI>i ){
5334 int t;
5335 MemPage *pT;
5336 t = pgnoNew[i];
5337 pT = apNew[i];
5338 pgnoNew[i] = pgnoNew[minI];
5339 apNew[i] = apNew[minI];
5340 pgnoNew[minI] = t;
5341 apNew[minI] = pT;
5342 }
5343 }
drha2fce642004-06-05 00:01:44 +00005344 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00005345 pgnoOld[0],
5346 nOld>=2 ? pgnoOld[1] : 0,
5347 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00005348 pgnoNew[0], szNew[0],
5349 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
5350 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00005351 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
5352 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00005353
drhf9ffac92002-03-02 19:00:31 +00005354 /*
drh14acc042001-06-10 19:56:58 +00005355 ** Evenly distribute the data in apCell[] across the new pages.
5356 ** Insert divider cells into pParent as necessary.
5357 */
5358 j = 0;
5359 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00005360 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00005361 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00005362 assert( j<nMaxCells );
drh4b70f112004-05-02 21:12:19 +00005363 assert( pNew->pgno==pgnoNew[i] );
drh10131482008-07-11 03:34:09 +00005364 zeroPage(pNew, pageFlags);
drhfa1a98a2004-05-14 19:08:17 +00005365 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00005366 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00005367 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00005368
danielk1977ac11ee62005-01-15 12:45:51 +00005369 /* If this is an auto-vacuum database, update the pointer map entries
5370 ** that point to the siblings that were rearranged. These can be: left
5371 ** children of cells, the right-child of the page, or overflow pages
5372 ** pointed to by cells.
5373 */
danielk197785d90ca2008-07-19 14:25:15 +00005374 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005375 for(k=j; k<cntNew[i]; k++){
danielk1977634f2982005-03-28 08:44:07 +00005376 assert( k<nMaxCells );
danielk1977ac11ee62005-01-15 12:45:51 +00005377 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
danielk197779a40da2005-01-16 08:00:01 +00005378 rc = ptrmapPutOvfl(pNew, k-j);
danielk197787c52b52008-07-19 11:49:07 +00005379 if( rc==SQLITE_OK && leafCorrection==0 ){
5380 rc = ptrmapPut(pBt, get4byte(apCell[k]), PTRMAP_BTREE, pNew->pgno);
5381 }
danielk197779a40da2005-01-16 08:00:01 +00005382 if( rc!=SQLITE_OK ){
5383 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00005384 }
5385 }
5386 }
5387 }
danielk1977ac11ee62005-01-15 12:45:51 +00005388
5389 j = cntNew[i];
5390
5391 /* If the sibling page assembled above was not the right-most sibling,
5392 ** insert a divider cell into the parent page.
5393 */
drh14acc042001-06-10 19:56:58 +00005394 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00005395 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00005396 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00005397 int sz;
danielk1977634f2982005-03-28 08:44:07 +00005398
5399 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00005400 pCell = apCell[j];
5401 sz = szCell[j] + leafCorrection;
drhe5ae5732008-06-15 02:51:47 +00005402 pTemp = &aSpace2[iSpace2];
drh4b70f112004-05-02 21:12:19 +00005403 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00005404 memcpy(&pNew->aData[8], pCell, 4);
danielk197785d90ca2008-07-19 14:25:15 +00005405 if( ISAUTOVACUUM
danielk197787c52b52008-07-19 11:49:07 +00005406 && (aFrom[j]==0xFF || apCopy[aFrom[j]]->pgno!=pNew->pgno)
5407 ){
5408 rc = ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno);
5409 if( rc!=SQLITE_OK ){
5410 goto balance_cleanup;
5411 }
5412 }
drh8b18dd42004-05-12 19:18:15 +00005413 }else if( leafData ){
drhfd131da2007-08-07 17:13:03 +00005414 /* If the tree is a leaf-data tree, and the siblings are leaves,
danielk1977ac11ee62005-01-15 12:45:51 +00005415 ** then there is no divider cell in apCell[]. Instead, the divider
5416 ** cell consists of the integer key for the right-most cell of
5417 ** the sibling-page assembled above only.
5418 */
drh6f11bef2004-05-13 01:12:56 +00005419 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00005420 j--;
drh16a9b832007-05-05 18:39:25 +00005421 sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
drhe5ae5732008-06-15 02:51:47 +00005422 pCell = pTemp;
drhb026e052007-05-02 01:34:31 +00005423 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
drh8b18dd42004-05-12 19:18:15 +00005424 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00005425 }else{
5426 pCell -= 4;
danielk19774aeff622007-05-12 09:30:47 +00005427 /* Obscure case for non-leaf-data trees: If the cell at pCell was
drh85b623f2007-12-13 21:54:09 +00005428 ** previously stored on a leaf node, and its reported size was 4
danielk19774aeff622007-05-12 09:30:47 +00005429 ** bytes, then it may actually be smaller than this
5430 ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
drh85b623f2007-12-13 21:54:09 +00005431 ** any cell). But it is important to pass the correct size to
danielk19774aeff622007-05-12 09:30:47 +00005432 ** insertCell(), so reparse the cell now.
5433 **
5434 ** Note that this can never happen in an SQLite data file, as all
5435 ** cells are at least 4 bytes. It only happens in b-trees used
5436 ** to evaluate "IN (SELECT ...)" and similar clauses.
5437 */
5438 if( szCell[j]==4 ){
5439 assert(leafCorrection==4);
5440 sz = cellSizePtr(pParent, pCell);
5441 }
drh4b70f112004-05-02 21:12:19 +00005442 }
drhe5ae5732008-06-15 02:51:47 +00005443 iSpace2 += sz;
5444 assert( sz<=pBt->pageSize/4 );
5445 assert( iSpace2<=pBt->pageSize );
danielk1977a3ad5e72005-01-07 08:56:44 +00005446 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
danielk1977e80463b2004-11-03 03:01:16 +00005447 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh43605152004-05-29 21:46:49 +00005448 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
danielk197785d90ca2008-07-19 14:25:15 +00005449
danielk1977ac11ee62005-01-15 12:45:51 +00005450 /* If this is an auto-vacuum database, and not a leaf-data tree,
5451 ** then update the pointer map with an entry for the overflow page
5452 ** that the cell just inserted points to (if any).
5453 */
danielk197785d90ca2008-07-19 14:25:15 +00005454 if( ISAUTOVACUUM && !leafData ){
danielk197779a40da2005-01-16 08:00:01 +00005455 rc = ptrmapPutOvfl(pParent, nxDiv);
5456 if( rc!=SQLITE_OK ){
5457 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00005458 }
5459 }
drh14acc042001-06-10 19:56:58 +00005460 j++;
5461 nxDiv++;
5462 }
danielk197787c52b52008-07-19 11:49:07 +00005463
danielk197787c52b52008-07-19 11:49:07 +00005464 /* Set the pointer-map entry for the new sibling page. */
danielk197785d90ca2008-07-19 14:25:15 +00005465 if( ISAUTOVACUUM ){
danielk197787c52b52008-07-19 11:49:07 +00005466 rc = ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno);
5467 if( rc!=SQLITE_OK ){
5468 goto balance_cleanup;
5469 }
5470 }
drh14acc042001-06-10 19:56:58 +00005471 }
drh6019e162001-07-02 17:51:45 +00005472 assert( j==nCell );
drh7aa8f852006-03-28 00:24:44 +00005473 assert( nOld>0 );
5474 assert( nNew>0 );
drh4b70f112004-05-02 21:12:19 +00005475 if( (pageFlags & PTF_LEAF)==0 ){
danielk197787c52b52008-07-19 11:49:07 +00005476 u8 *zChild = &apCopy[nOld-1]->aData[8];
5477 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
danielk197785d90ca2008-07-19 14:25:15 +00005478 if( ISAUTOVACUUM ){
danielk197787c52b52008-07-19 11:49:07 +00005479 rc = ptrmapPut(pBt, get4byte(zChild), PTRMAP_BTREE, apNew[nNew-1]->pgno);
5480 if( rc!=SQLITE_OK ){
5481 goto balance_cleanup;
5482 }
5483 }
drh14acc042001-06-10 19:56:58 +00005484 }
drh43605152004-05-29 21:46:49 +00005485 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00005486 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00005487 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00005488 }else{
5489 /* Right-most sibling is the left child of the first entry in pParent
5490 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00005491 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00005492 }
5493
5494 /*
5495 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00005496 */
5497 for(i=0; i<nNew; i++){
danielk197787c52b52008-07-19 11:49:07 +00005498 rc = reparentChildPages(apNew[i], 0);
danielk1977afcdd022004-10-31 16:25:42 +00005499 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00005500 }
danielk197787c52b52008-07-19 11:49:07 +00005501 rc = reparentChildPages(pParent, 0);
danielk1977afcdd022004-10-31 16:25:42 +00005502 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00005503
5504 /*
drh3a4c1412004-05-09 20:40:11 +00005505 ** Balance the parent page. Note that the current page (pPage) might
danielk1977ac11ee62005-01-15 12:45:51 +00005506 ** have been added to the freelist so it might no longer be initialized.
drh3a4c1412004-05-09 20:40:11 +00005507 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00005508 */
drhda200cc2004-05-09 11:51:38 +00005509 assert( pParent->isInit );
drhfacf0302008-06-17 15:12:00 +00005510 sqlite3ScratchFree(apCell);
drhe5ae5732008-06-15 02:51:47 +00005511 apCell = 0;
danielk1977ac245ec2005-01-14 13:50:11 +00005512 rc = balance(pParent, 0);
drhda200cc2004-05-09 11:51:38 +00005513
drh8b2f49b2001-06-08 00:21:52 +00005514 /*
drh14acc042001-06-10 19:56:58 +00005515 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00005516 */
drh14acc042001-06-10 19:56:58 +00005517balance_cleanup:
drhfacf0302008-06-17 15:12:00 +00005518 sqlite3PageFree(aSpace2);
5519 sqlite3ScratchFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00005520 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00005521 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00005522 }
drh14acc042001-06-10 19:56:58 +00005523 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00005524 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00005525 }
drh91025292004-05-03 19:49:32 +00005526 releasePage(pParent);
drh3a4c1412004-05-09 20:40:11 +00005527 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
5528 pPage->pgno, nOld, nNew, nCell));
drh8b2f49b2001-06-08 00:21:52 +00005529 return rc;
5530}
5531
5532/*
drh43605152004-05-29 21:46:49 +00005533** This routine is called for the root page of a btree when the root
5534** page contains no cells. This is an opportunity to make the tree
5535** shallower by one level.
5536*/
5537static int balance_shallower(MemPage *pPage){
5538 MemPage *pChild; /* The only child page of pPage */
5539 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00005540 int rc = SQLITE_OK; /* Return code from subprocedures */
danielk1977aef0bf62005-12-30 16:28:01 +00005541 BtShared *pBt; /* The main BTree structure */
drh2e38c322004-09-03 18:38:44 +00005542 int mxCellPerPage; /* Maximum number of cells per page */
5543 u8 **apCell; /* All cells from pages being balanced */
drha9121e42008-02-19 14:59:35 +00005544 u16 *szCell; /* Local size of all cells */
drh43605152004-05-29 21:46:49 +00005545
5546 assert( pPage->pParent==0 );
5547 assert( pPage->nCell==0 );
drh1fee73e2007-08-29 04:00:57 +00005548 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh2e38c322004-09-03 18:38:44 +00005549 pBt = pPage->pBt;
5550 mxCellPerPage = MX_CELL(pBt);
drhe5ae5732008-06-15 02:51:47 +00005551 apCell = sqlite3Malloc( mxCellPerPage*(sizeof(u8*)+sizeof(u16)) );
drh2e38c322004-09-03 18:38:44 +00005552 if( apCell==0 ) return SQLITE_NOMEM;
drha9121e42008-02-19 14:59:35 +00005553 szCell = (u16*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00005554 if( pPage->leaf ){
5555 /* The table is completely empty */
5556 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
5557 }else{
5558 /* The root page is empty but has one child. Transfer the
5559 ** information from that one child into the root page if it
5560 ** will fit. This reduces the depth of the tree by one.
5561 **
5562 ** If the root page is page 1, it has less space available than
5563 ** its child (due to the 100 byte header that occurs at the beginning
5564 ** of the database fle), so it might not be able to hold all of the
5565 ** information currently contained in the child. If this is the
5566 ** case, then do not do the transfer. Leave page 1 empty except
5567 ** for the right-pointer to the child page. The child page becomes
5568 ** the virtual root of the tree.
5569 */
5570 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5571 assert( pgnoChild>0 );
danielk1977ad0132d2008-06-07 08:58:22 +00005572 assert( pgnoChild<=pagerPagecount(pPage->pBt->pPager) );
drh16a9b832007-05-05 18:39:25 +00005573 rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
drh2e38c322004-09-03 18:38:44 +00005574 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005575 if( pPage->pgno==1 ){
drh16a9b832007-05-05 18:39:25 +00005576 rc = sqlite3BtreeInitPage(pChild, pPage);
drh2e38c322004-09-03 18:38:44 +00005577 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005578 assert( pChild->nOverflow==0 );
5579 if( pChild->nFree>=100 ){
5580 /* The child information will fit on the root page, so do the
5581 ** copy */
5582 int i;
5583 zeroPage(pPage, pChild->aData[0]);
5584 for(i=0; i<pChild->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00005585 apCell[i] = findCell(pChild,i);
drh43605152004-05-29 21:46:49 +00005586 szCell[i] = cellSizePtr(pChild, apCell[i]);
5587 }
5588 assemblePage(pPage, pChild->nCell, apCell, szCell);
danielk1977ae825582004-11-23 09:06:55 +00005589 /* Copy the right-pointer of the child to the parent. */
5590 put4byte(&pPage->aData[pPage->hdrOffset+8],
5591 get4byte(&pChild->aData[pChild->hdrOffset+8]));
drh43605152004-05-29 21:46:49 +00005592 freePage(pChild);
5593 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
5594 }else{
5595 /* The child has more information that will fit on the root.
5596 ** The tree is already balanced. Do nothing. */
5597 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
5598 }
5599 }else{
5600 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
5601 pPage->isInit = 0;
5602 pPage->pParent = 0;
drh16a9b832007-05-05 18:39:25 +00005603 rc = sqlite3BtreeInitPage(pPage, 0);
drh43605152004-05-29 21:46:49 +00005604 assert( rc==SQLITE_OK );
5605 freePage(pChild);
5606 TRACE(("BALANCE: transfer child %d into root %d\n",
5607 pChild->pgno, pPage->pgno));
5608 }
danielk197787c52b52008-07-19 11:49:07 +00005609 rc = reparentChildPages(pPage, 1);
danielk1977ac11ee62005-01-15 12:45:51 +00005610 assert( pPage->nOverflow==0 );
danielk197785d90ca2008-07-19 14:25:15 +00005611 if( ISAUTOVACUUM ){
danielk1977aac0a382005-01-16 11:07:06 +00005612 int i;
danielk1977ac11ee62005-01-15 12:45:51 +00005613 for(i=0; i<pPage->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00005614 rc = ptrmapPutOvfl(pPage, i);
5615 if( rc!=SQLITE_OK ){
5616 goto end_shallow_balance;
danielk1977ac11ee62005-01-15 12:45:51 +00005617 }
5618 }
5619 }
drh43605152004-05-29 21:46:49 +00005620 releasePage(pChild);
5621 }
drh2e38c322004-09-03 18:38:44 +00005622end_shallow_balance:
drh17435752007-08-16 04:30:38 +00005623 sqlite3_free(apCell);
drh2e38c322004-09-03 18:38:44 +00005624 return rc;
drh43605152004-05-29 21:46:49 +00005625}
5626
5627
5628/*
5629** The root page is overfull
5630**
5631** When this happens, Create a new child page and copy the
5632** contents of the root into the child. Then make the root
5633** page an empty page with rightChild pointing to the new
5634** child. Finally, call balance_internal() on the new child
5635** to cause it to split.
5636*/
5637static int balance_deeper(MemPage *pPage){
5638 int rc; /* Return value from subprocedures */
5639 MemPage *pChild; /* Pointer to a new child page */
5640 Pgno pgnoChild; /* Page number of the new child page */
danielk1977aef0bf62005-12-30 16:28:01 +00005641 BtShared *pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00005642 int usableSize; /* Total usable size of a page */
5643 u8 *data; /* Content of the parent page */
5644 u8 *cdata; /* Content of the child page */
5645 int hdr; /* Offset to page header in parent */
5646 int brk; /* Offset to content of first cell in parent */
5647
5648 assert( pPage->pParent==0 );
5649 assert( pPage->nOverflow>0 );
5650 pBt = pPage->pBt;
drh1fee73e2007-08-29 04:00:57 +00005651 assert( sqlite3_mutex_held(pBt->mutex) );
drh4f0c5872007-03-26 22:05:01 +00005652 rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
drh43605152004-05-29 21:46:49 +00005653 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00005654 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
drh43605152004-05-29 21:46:49 +00005655 usableSize = pBt->usableSize;
5656 data = pPage->aData;
5657 hdr = pPage->hdrOffset;
5658 brk = get2byte(&data[hdr+5]);
5659 cdata = pChild->aData;
5660 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
5661 memcpy(&cdata[brk], &data[brk], usableSize-brk);
drh10131482008-07-11 03:34:09 +00005662 if( pChild->isInit ) return SQLITE_CORRUPT;
drh16a9b832007-05-05 18:39:25 +00005663 rc = sqlite3BtreeInitPage(pChild, pPage);
danielk19776b456a22005-03-21 04:04:02 +00005664 if( rc ) goto balancedeeper_out;
drh43605152004-05-29 21:46:49 +00005665 memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
5666 pChild->nOverflow = pPage->nOverflow;
5667 if( pChild->nOverflow ){
5668 pChild->nFree = 0;
5669 }
5670 assert( pChild->nCell==pPage->nCell );
5671 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
5672 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
5673 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
danielk197785d90ca2008-07-19 14:25:15 +00005674 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005675 int i;
5676 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
danielk19776b456a22005-03-21 04:04:02 +00005677 if( rc ) goto balancedeeper_out;
danielk1977ac11ee62005-01-15 12:45:51 +00005678 for(i=0; i<pChild->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00005679 rc = ptrmapPutOvfl(pChild, i);
5680 if( rc!=SQLITE_OK ){
danielk1977474b7cc2008-07-09 11:49:46 +00005681 goto balancedeeper_out;
danielk1977ac11ee62005-01-15 12:45:51 +00005682 }
5683 }
danielk197787c52b52008-07-19 11:49:07 +00005684 rc = reparentChildPages(pChild, 1);
danielk1977ac11ee62005-01-15 12:45:51 +00005685 }
danielk197787c52b52008-07-19 11:49:07 +00005686 if( rc==SQLITE_OK ){
5687 rc = balance_nonroot(pChild);
5688 }
danielk19776b456a22005-03-21 04:04:02 +00005689
5690balancedeeper_out:
drh43605152004-05-29 21:46:49 +00005691 releasePage(pChild);
5692 return rc;
5693}
5694
5695/*
5696** Decide if the page pPage needs to be balanced. If balancing is
5697** required, call the appropriate balancing routine.
5698*/
danielk1977ac245ec2005-01-14 13:50:11 +00005699static int balance(MemPage *pPage, int insert){
drh43605152004-05-29 21:46:49 +00005700 int rc = SQLITE_OK;
drh1fee73e2007-08-29 04:00:57 +00005701 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +00005702 if( pPage->pParent==0 ){
danielk19776e465eb2007-08-21 13:11:00 +00005703 rc = sqlite3PagerWrite(pPage->pDbPage);
5704 if( rc==SQLITE_OK && pPage->nOverflow>0 ){
drh43605152004-05-29 21:46:49 +00005705 rc = balance_deeper(pPage);
5706 }
danielk1977687566d2004-11-02 12:56:41 +00005707 if( rc==SQLITE_OK && pPage->nCell==0 ){
drh43605152004-05-29 21:46:49 +00005708 rc = balance_shallower(pPage);
5709 }
5710 }else{
danielk1977ac245ec2005-01-14 13:50:11 +00005711 if( pPage->nOverflow>0 ||
5712 (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
drh43605152004-05-29 21:46:49 +00005713 rc = balance_nonroot(pPage);
5714 }
5715 }
5716 return rc;
5717}
5718
5719/*
drh8dcd7ca2004-08-08 19:43:29 +00005720** This routine checks all cursors that point to table pgnoRoot.
drh980b1a72006-08-16 16:42:48 +00005721** If any of those cursors were opened with wrFlag==0 in a different
5722** database connection (a database connection that shares the pager
5723** cache with the current connection) and that other connection
5724** is not in the ReadUncommmitted state, then this routine returns
5725** SQLITE_LOCKED.
danielk1977299b1872004-11-22 10:02:10 +00005726**
danielk19773588ceb2008-06-10 17:30:26 +00005727** As well as cursors with wrFlag==0, cursors with wrFlag==1 and
5728** isIncrblobHandle==1 are also considered 'read' cursors. Incremental
5729** blob cursors are used for both reading and writing.
5730**
5731** When pgnoRoot is the root page of an intkey table, this function is also
5732** responsible for invalidating incremental blob cursors when the table row
5733** on which they are opened is deleted or modified. Cursors are invalidated
5734** according to the following rules:
5735**
5736** 1) When BtreeClearTable() is called to completely delete the contents
5737** of a B-Tree table, pExclude is set to zero and parameter iRow is
5738** set to non-zero. In this case all incremental blob cursors open
5739** on the table rooted at pgnoRoot are invalidated.
5740**
5741** 2) When BtreeInsert(), BtreeDelete() or BtreePutData() is called to
5742** modify a table row via an SQL statement, pExclude is set to the
5743** write cursor used to do the modification and parameter iRow is set
5744** to the integer row id of the B-Tree entry being modified. Unless
5745** pExclude is itself an incremental blob cursor, then all incremental
5746** blob cursors open on row iRow of the B-Tree are invalidated.
5747**
5748** 3) If both pExclude and iRow are set to zero, no incremental blob
5749** cursors are invalidated.
drhf74b8d92002-09-01 23:20:45 +00005750*/
danielk19773588ceb2008-06-10 17:30:26 +00005751static int checkReadLocks(
5752 Btree *pBtree,
5753 Pgno pgnoRoot,
5754 BtCursor *pExclude,
5755 i64 iRow
5756){
danielk1977299b1872004-11-22 10:02:10 +00005757 BtCursor *p;
drh980b1a72006-08-16 16:42:48 +00005758 BtShared *pBt = pBtree->pBt;
drhe5fe6902007-12-07 18:55:28 +00005759 sqlite3 *db = pBtree->db;
drh1fee73e2007-08-29 04:00:57 +00005760 assert( sqlite3BtreeHoldsMutex(pBtree) );
danielk1977299b1872004-11-22 10:02:10 +00005761 for(p=pBt->pCursor; p; p=p->pNext){
drh980b1a72006-08-16 16:42:48 +00005762 if( p==pExclude ) continue;
drh980b1a72006-08-16 16:42:48 +00005763 if( p->pgnoRoot!=pgnoRoot ) continue;
danielk19773588ceb2008-06-10 17:30:26 +00005764#ifndef SQLITE_OMIT_INCRBLOB
5765 if( p->isIncrblobHandle && (
5766 (!pExclude && iRow)
5767 || (pExclude && !pExclude->isIncrblobHandle && p->info.nKey==iRow)
5768 )){
5769 p->eState = CURSOR_INVALID;
5770 }
5771#endif
5772 if( p->eState!=CURSOR_VALID ) continue;
5773 if( p->wrFlag==0
5774#ifndef SQLITE_OMIT_INCRBLOB
5775 || p->isIncrblobHandle
5776#endif
5777 ){
drhe5fe6902007-12-07 18:55:28 +00005778 sqlite3 *dbOther = p->pBtree->db;
drh980b1a72006-08-16 16:42:48 +00005779 if( dbOther==0 ||
5780 (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
5781 return SQLITE_LOCKED;
5782 }
danielk1977299b1872004-11-22 10:02:10 +00005783 }
5784 }
drhf74b8d92002-09-01 23:20:45 +00005785 return SQLITE_OK;
5786}
5787
5788/*
drh3b7511c2001-05-26 13:15:44 +00005789** Insert a new record into the BTree. The key is given by (pKey,nKey)
5790** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00005791** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00005792** is left pointing at a random location.
5793**
5794** For an INTKEY table, only the nKey value of the key is used. pKey is
5795** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00005796*/
drh3aac2dd2004-04-26 14:10:20 +00005797int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00005798 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00005799 const void *pKey, i64 nKey, /* The key of the new record */
drhe4d90812007-03-29 05:51:49 +00005800 const void *pData, int nData, /* The data of the new record */
drhb026e052007-05-02 01:34:31 +00005801 int nZero, /* Number of extra 0 bytes to append to data */
drhe4d90812007-03-29 05:51:49 +00005802 int appendBias /* True if this is likely an append */
drh3b7511c2001-05-26 13:15:44 +00005803){
drh3b7511c2001-05-26 13:15:44 +00005804 int rc;
5805 int loc;
drh14acc042001-06-10 19:56:58 +00005806 int szNew;
drh3b7511c2001-05-26 13:15:44 +00005807 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00005808 Btree *p = pCur->pBtree;
5809 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00005810 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00005811 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00005812
drh1fee73e2007-08-29 04:00:57 +00005813 assert( cursorHoldsMutex(pCur) );
danielk1977aef0bf62005-12-30 16:28:01 +00005814 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005815 /* Must start a transaction before doing an insert */
drhd677b3d2007-08-20 22:48:41 +00005816 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drhd677b3d2007-08-20 22:48:41 +00005817 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005818 }
drhf74b8d92002-09-01 23:20:45 +00005819 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00005820 if( !pCur->wrFlag ){
5821 return SQLITE_PERM; /* Cursor not open for writing */
5822 }
danielk19773588ceb2008-06-10 17:30:26 +00005823 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, nKey) ){
drhf74b8d92002-09-01 23:20:45 +00005824 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5825 }
drhfb982642007-08-30 01:19:59 +00005826 if( pCur->eState==CURSOR_FAULT ){
5827 return pCur->skip;
5828 }
danielk1977da184232006-01-05 11:34:32 +00005829
5830 /* Save the positions of any other cursors open on this table */
drhbf700f32007-03-31 02:36:44 +00005831 clearCursorPosition(pCur);
danielk19772e94d4d2006-01-09 05:36:27 +00005832 if(
danielk19772e94d4d2006-01-09 05:36:27 +00005833 SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
drhe14006d2008-03-25 17:23:32 +00005834 SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, 0, nKey, appendBias, &loc))
danielk19772e94d4d2006-01-09 05:36:27 +00005835 ){
danielk1977da184232006-01-05 11:34:32 +00005836 return rc;
5837 }
5838
drh14acc042001-06-10 19:56:58 +00005839 pPage = pCur->pPage;
drh4a1c3802004-05-12 15:15:47 +00005840 assert( pPage->intKey || nKey>=0 );
drh44845222008-07-17 18:39:57 +00005841 assert( pPage->leaf || !pPage->intKey );
drh3a4c1412004-05-09 20:40:11 +00005842 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
5843 pCur->pgnoRoot, nKey, nData, pPage->pgno,
5844 loc==0 ? "overwrite" : "new entry"));
drh7aa128d2002-06-21 13:09:16 +00005845 assert( pPage->isInit );
danielk197752ae7242008-03-25 14:24:56 +00005846 allocateTempSpace(pBt);
5847 newCell = pBt->pTmpSpace;
drh2e38c322004-09-03 18:38:44 +00005848 if( newCell==0 ) return SQLITE_NOMEM;
drhb026e052007-05-02 01:34:31 +00005849 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
drh2e38c322004-09-03 18:38:44 +00005850 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00005851 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00005852 assert( szNew<=MX_CELL_SIZE(pBt) );
danielk1977da184232006-01-05 11:34:32 +00005853 if( loc==0 && CURSOR_VALID==pCur->eState ){
drha9121e42008-02-19 14:59:35 +00005854 u16 szOld;
drha34b6762004-05-07 13:30:42 +00005855 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00005856 rc = sqlite3PagerWrite(pPage->pDbPage);
5857 if( rc ){
5858 goto end_insert;
5859 }
danielk19771cc5ed82007-05-16 17:28:43 +00005860 oldCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00005861 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005862 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00005863 }
drh43605152004-05-29 21:46:49 +00005864 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00005865 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00005866 if( rc ) goto end_insert;
drh4b70f112004-05-02 21:12:19 +00005867 dropCell(pPage, pCur->idx, szOld);
drh7c717f72001-06-24 20:39:41 +00005868 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00005869 assert( pPage->leaf );
drh14acc042001-06-10 19:56:58 +00005870 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00005871 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00005872 pCur->validNKey = 0;
drh14acc042001-06-10 19:56:58 +00005873 }else{
drh4b70f112004-05-02 21:12:19 +00005874 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00005875 }
danielk1977a3ad5e72005-01-07 08:56:44 +00005876 rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
danielk1977e80463b2004-11-03 03:01:16 +00005877 if( rc!=SQLITE_OK ) goto end_insert;
danielk1977ac245ec2005-01-14 13:50:11 +00005878 rc = balance(pPage, 1);
danielk1977299b1872004-11-22 10:02:10 +00005879 if( rc==SQLITE_OK ){
5880 moveToRoot(pCur);
5881 }
drh2e38c322004-09-03 18:38:44 +00005882end_insert:
drh5e2f8b92001-05-28 00:41:15 +00005883 return rc;
5884}
5885
5886/*
drh4b70f112004-05-02 21:12:19 +00005887** Delete the entry that the cursor is pointing to. The cursor
5888** is left pointing at a random location.
drh3b7511c2001-05-26 13:15:44 +00005889*/
drh3aac2dd2004-04-26 14:10:20 +00005890int sqlite3BtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00005891 MemPage *pPage = pCur->pPage;
drh4b70f112004-05-02 21:12:19 +00005892 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00005893 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00005894 Pgno pgnoChild = 0;
drhd677b3d2007-08-20 22:48:41 +00005895 Btree *p = pCur->pBtree;
5896 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005897
drh1fee73e2007-08-29 04:00:57 +00005898 assert( cursorHoldsMutex(pCur) );
drh7aa128d2002-06-21 13:09:16 +00005899 assert( pPage->isInit );
danielk1977aef0bf62005-12-30 16:28:01 +00005900 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005901 /* Must start a transaction before doing a delete */
drhd677b3d2007-08-20 22:48:41 +00005902 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drhd677b3d2007-08-20 22:48:41 +00005903 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005904 }
drhf74b8d92002-09-01 23:20:45 +00005905 assert( !pBt->readOnly );
drhfb982642007-08-30 01:19:59 +00005906 if( pCur->eState==CURSOR_FAULT ){
5907 return pCur->skip;
5908 }
drhbd03cae2001-06-02 02:40:57 +00005909 if( pCur->idx >= pPage->nCell ){
5910 return SQLITE_ERROR; /* The cursor is not pointing to anything */
5911 }
drhecdc7532001-09-23 02:35:53 +00005912 if( !pCur->wrFlag ){
5913 return SQLITE_PERM; /* Did not open this cursor for writing */
5914 }
danielk19773588ceb2008-06-10 17:30:26 +00005915 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, pCur->info.nKey) ){
drhf74b8d92002-09-01 23:20:45 +00005916 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5917 }
danielk1977da184232006-01-05 11:34:32 +00005918
5919 /* Restore the current cursor position (a no-op if the cursor is not in
5920 ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors
danielk19773b8a05f2007-03-19 17:44:26 +00005921 ** open on the same table. Then call sqlite3PagerWrite() on the page
danielk1977da184232006-01-05 11:34:32 +00005922 ** that the entry will be deleted from.
5923 */
5924 if(
drha3460582008-07-11 21:02:53 +00005925 (rc = restoreCursorPosition(pCur))!=0 ||
drhd1167392006-01-23 13:00:35 +00005926 (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
danielk19773b8a05f2007-03-19 17:44:26 +00005927 (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
danielk1977da184232006-01-05 11:34:32 +00005928 ){
5929 return rc;
5930 }
danielk1977e6efa742004-11-10 11:55:10 +00005931
drh85b623f2007-12-13 21:54:09 +00005932 /* Locate the cell within its page and leave pCell pointing to the
danielk1977e6efa742004-11-10 11:55:10 +00005933 ** data. The clearCell() call frees any overflow pages associated with the
5934 ** cell. The cell itself is still intact.
5935 */
danielk19771cc5ed82007-05-16 17:28:43 +00005936 pCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00005937 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005938 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005939 }
danielk197728129562005-01-11 10:25:06 +00005940 rc = clearCell(pPage, pCell);
drhd677b3d2007-08-20 22:48:41 +00005941 if( rc ){
drhd677b3d2007-08-20 22:48:41 +00005942 return rc;
5943 }
danielk1977e6efa742004-11-10 11:55:10 +00005944
drh4b70f112004-05-02 21:12:19 +00005945 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00005946 /*
drh5e00f6c2001-09-13 13:46:56 +00005947 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00005948 ** do something we will leave a hole on an internal page.
5949 ** We have to fill the hole by moving in a cell from a leaf. The
5950 ** next Cell after the one to be deleted is guaranteed to exist and
danielk1977299b1872004-11-22 10:02:10 +00005951 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00005952 */
drh14acc042001-06-10 19:56:58 +00005953 BtCursor leafCur;
drh4b70f112004-05-02 21:12:19 +00005954 unsigned char *pNext;
danielk1977299b1872004-11-22 10:02:10 +00005955 int notUsed;
danielk19776b456a22005-03-21 04:04:02 +00005956 unsigned char *tempCell = 0;
drh44845222008-07-17 18:39:57 +00005957 assert( !pPage->intKey );
drh16a9b832007-05-05 18:39:25 +00005958 sqlite3BtreeGetTempCursor(pCur, &leafCur);
danielk1977299b1872004-11-22 10:02:10 +00005959 rc = sqlite3BtreeNext(&leafCur, &notUsed);
danielk19776b456a22005-03-21 04:04:02 +00005960 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00005961 rc = sqlite3PagerWrite(leafCur.pPage->pDbPage);
danielk19776b456a22005-03-21 04:04:02 +00005962 }
5963 if( rc==SQLITE_OK ){
drha9121e42008-02-19 14:59:35 +00005964 u16 szNext;
danielk19776b456a22005-03-21 04:04:02 +00005965 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
5966 pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
5967 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
danielk19771cc5ed82007-05-16 17:28:43 +00005968 pNext = findCell(leafCur.pPage, leafCur.idx);
danielk19776b456a22005-03-21 04:04:02 +00005969 szNext = cellSizePtr(leafCur.pPage, pNext);
5970 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
danielk197752ae7242008-03-25 14:24:56 +00005971 allocateTempSpace(pBt);
5972 tempCell = pBt->pTmpSpace;
danielk19776b456a22005-03-21 04:04:02 +00005973 if( tempCell==0 ){
5974 rc = SQLITE_NOMEM;
5975 }
danielk19778ea1cfa2008-01-01 06:19:02 +00005976 if( rc==SQLITE_OK ){
5977 rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
5978 }
5979 if( rc==SQLITE_OK ){
5980 put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
5981 rc = balance(pPage, 0);
5982 }
5983 if( rc==SQLITE_OK ){
5984 dropCell(leafCur.pPage, leafCur.idx, szNext);
5985 rc = balance(leafCur.pPage, 0);
5986 }
danielk19776b456a22005-03-21 04:04:02 +00005987 }
drh16a9b832007-05-05 18:39:25 +00005988 sqlite3BtreeReleaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00005989 }else{
danielk1977299b1872004-11-22 10:02:10 +00005990 TRACE(("DELETE: table=%d delete from leaf %d\n",
5991 pCur->pgnoRoot, pPage->pgno));
5992 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
danielk1977ac245ec2005-01-14 13:50:11 +00005993 rc = balance(pPage, 0);
drh5e2f8b92001-05-28 00:41:15 +00005994 }
danielk19776b456a22005-03-21 04:04:02 +00005995 if( rc==SQLITE_OK ){
5996 moveToRoot(pCur);
5997 }
drh5e2f8b92001-05-28 00:41:15 +00005998 return rc;
drh3b7511c2001-05-26 13:15:44 +00005999}
drh8b2f49b2001-06-08 00:21:52 +00006000
6001/*
drhc6b52df2002-01-04 03:09:29 +00006002** Create a new BTree table. Write into *piTable the page
6003** number for the root page of the new table.
6004**
drhab01f612004-05-22 02:55:23 +00006005** The type of type is determined by the flags parameter. Only the
6006** following values of flags are currently in use. Other values for
6007** flags might not work:
6008**
6009** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
6010** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00006011*/
drhd677b3d2007-08-20 22:48:41 +00006012static int btreeCreateTable(Btree *p, int *piTable, int flags){
danielk1977aef0bf62005-12-30 16:28:01 +00006013 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006014 MemPage *pRoot;
6015 Pgno pgnoRoot;
6016 int rc;
drhd677b3d2007-08-20 22:48:41 +00006017
drh1fee73e2007-08-29 04:00:57 +00006018 assert( sqlite3BtreeHoldsMutex(p) );
danielk1977aef0bf62005-12-30 16:28:01 +00006019 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00006020 /* Must start a transaction first */
drhd677b3d2007-08-20 22:48:41 +00006021 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
6022 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006023 }
danielk197728129562005-01-11 10:25:06 +00006024 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00006025
danielk1977003ba062004-11-04 02:57:33 +00006026#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00006027 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00006028 if( rc ){
6029 return rc;
6030 }
danielk1977003ba062004-11-04 02:57:33 +00006031#else
danielk1977687566d2004-11-02 12:56:41 +00006032 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00006033 Pgno pgnoMove; /* Move a page here to make room for the root-page */
6034 MemPage *pPageMove; /* The page to move to. */
6035
danielk197720713f32007-05-03 11:43:33 +00006036 /* Creating a new table may probably require moving an existing database
6037 ** to make room for the new tables root page. In case this page turns
6038 ** out to be an overflow page, delete all overflow page-map caches
6039 ** held by open cursors.
6040 */
danielk197792d4d7a2007-05-04 12:05:56 +00006041 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00006042
danielk1977003ba062004-11-04 02:57:33 +00006043 /* Read the value of meta[3] from the database to determine where the
6044 ** root page of the new table should go. meta[3] is the largest root-page
6045 ** created so far, so the new root-page is (meta[3]+1).
6046 */
danielk1977aef0bf62005-12-30 16:28:01 +00006047 rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
drhd677b3d2007-08-20 22:48:41 +00006048 if( rc!=SQLITE_OK ){
6049 return rc;
6050 }
danielk1977003ba062004-11-04 02:57:33 +00006051 pgnoRoot++;
6052
danielk1977599fcba2004-11-08 07:13:13 +00006053 /* The new root-page may not be allocated on a pointer-map page, or the
6054 ** PENDING_BYTE page.
6055 */
drh72190432008-01-31 14:54:43 +00006056 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00006057 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00006058 pgnoRoot++;
6059 }
6060 assert( pgnoRoot>=3 );
6061
6062 /* Allocate a page. The page that currently resides at pgnoRoot will
6063 ** be moved to the allocated page (unless the allocated page happens
6064 ** to reside at pgnoRoot).
6065 */
drh4f0c5872007-03-26 22:05:01 +00006066 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00006067 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00006068 return rc;
6069 }
danielk1977003ba062004-11-04 02:57:33 +00006070
6071 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00006072 /* pgnoRoot is the page that will be used for the root-page of
6073 ** the new table (assuming an error did not occur). But we were
6074 ** allocated pgnoMove. If required (i.e. if it was not allocated
6075 ** by extending the file), the current page at position pgnoMove
6076 ** is already journaled.
6077 */
danielk1977003ba062004-11-04 02:57:33 +00006078 u8 eType;
6079 Pgno iPtrPage;
6080
6081 releasePage(pPageMove);
danielk1977f35843b2007-04-07 15:03:17 +00006082
6083 /* Move the page currently at pgnoRoot to pgnoMove. */
drh16a9b832007-05-05 18:39:25 +00006084 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006085 if( rc!=SQLITE_OK ){
6086 return rc;
6087 }
6088 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drhccae6022005-02-26 17:31:26 +00006089 if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00006090 releasePage(pRoot);
6091 return rc;
6092 }
drhccae6022005-02-26 17:31:26 +00006093 assert( eType!=PTRMAP_ROOTPAGE );
6094 assert( eType!=PTRMAP_FREEPAGE );
danielk19773b8a05f2007-03-19 17:44:26 +00006095 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk19775fd057a2005-03-09 13:09:43 +00006096 if( rc!=SQLITE_OK ){
6097 releasePage(pRoot);
6098 return rc;
6099 }
danielk19774c999992008-07-16 18:17:55 +00006100 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
danielk1977003ba062004-11-04 02:57:33 +00006101 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00006102
6103 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00006104 if( rc!=SQLITE_OK ){
6105 return rc;
6106 }
drh16a9b832007-05-05 18:39:25 +00006107 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006108 if( rc!=SQLITE_OK ){
6109 return rc;
6110 }
danielk19773b8a05f2007-03-19 17:44:26 +00006111 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00006112 if( rc!=SQLITE_OK ){
6113 releasePage(pRoot);
6114 return rc;
6115 }
6116 }else{
6117 pRoot = pPageMove;
6118 }
6119
danielk197742741be2005-01-08 12:42:39 +00006120 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00006121 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
6122 if( rc ){
6123 releasePage(pRoot);
6124 return rc;
6125 }
danielk1977aef0bf62005-12-30 16:28:01 +00006126 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00006127 if( rc ){
6128 releasePage(pRoot);
6129 return rc;
6130 }
danielk197742741be2005-01-08 12:42:39 +00006131
danielk1977003ba062004-11-04 02:57:33 +00006132 }else{
drh4f0c5872007-03-26 22:05:01 +00006133 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00006134 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00006135 }
6136#endif
danielk19773b8a05f2007-03-19 17:44:26 +00006137 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhde647132004-05-07 17:57:49 +00006138 zeroPage(pRoot, flags | PTF_LEAF);
danielk19773b8a05f2007-03-19 17:44:26 +00006139 sqlite3PagerUnref(pRoot->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00006140 *piTable = (int)pgnoRoot;
6141 return SQLITE_OK;
6142}
drhd677b3d2007-08-20 22:48:41 +00006143int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
6144 int rc;
6145 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006146 p->pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006147 rc = btreeCreateTable(p, piTable, flags);
6148 sqlite3BtreeLeave(p);
6149 return rc;
6150}
drh8b2f49b2001-06-08 00:21:52 +00006151
6152/*
6153** Erase the given database page and all its children. Return
6154** the page to the freelist.
6155*/
drh4b70f112004-05-02 21:12:19 +00006156static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00006157 BtShared *pBt, /* The BTree that contains the table */
drh4b70f112004-05-02 21:12:19 +00006158 Pgno pgno, /* Page number to clear */
6159 MemPage *pParent, /* Parent page. NULL for the root */
6160 int freePageFlag /* Deallocate page if true */
6161){
danielk19776b456a22005-03-21 04:04:02 +00006162 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00006163 int rc;
drh4b70f112004-05-02 21:12:19 +00006164 unsigned char *pCell;
6165 int i;
drh8b2f49b2001-06-08 00:21:52 +00006166
drh1fee73e2007-08-29 04:00:57 +00006167 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977ad0132d2008-06-07 08:58:22 +00006168 if( pgno>pagerPagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00006169 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00006170 }
6171
drhde647132004-05-07 17:57:49 +00006172 rc = getAndInitPage(pBt, pgno, &pPage, pParent);
danielk19776b456a22005-03-21 04:04:02 +00006173 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00006174 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00006175 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00006176 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006177 rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00006178 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006179 }
drh4b70f112004-05-02 21:12:19 +00006180 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00006181 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006182 }
drha34b6762004-05-07 13:30:42 +00006183 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006184 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00006185 if( rc ) goto cleardatabasepage_out;
drh2aa679f2001-06-25 02:11:07 +00006186 }
6187 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00006188 rc = freePage(pPage);
danielk19773b8a05f2007-03-19 17:44:26 +00006189 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
drh3a4c1412004-05-09 20:40:11 +00006190 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00006191 }
danielk19776b456a22005-03-21 04:04:02 +00006192
6193cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00006194 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00006195 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006196}
6197
6198/*
drhab01f612004-05-22 02:55:23 +00006199** Delete all information from a single table in the database. iTable is
6200** the page number of the root of the table. After this routine returns,
6201** the root page is empty, but still exists.
6202**
6203** This routine will fail with SQLITE_LOCKED if there are any open
6204** read cursors on the table. Open write cursors are moved to the
6205** root of the table.
drh8b2f49b2001-06-08 00:21:52 +00006206*/
danielk1977aef0bf62005-12-30 16:28:01 +00006207int sqlite3BtreeClearTable(Btree *p, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00006208 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00006209 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00006210 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006211 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00006212 if( p->inTrans!=TRANS_WRITE ){
drhd677b3d2007-08-20 22:48:41 +00006213 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
danielk19773588ceb2008-06-10 17:30:26 +00006214 }else if( (rc = checkReadLocks(p, iTable, 0, 1))!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00006215 /* nothing to do */
6216 }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
6217 /* nothing to do */
6218 }else{
6219 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
drh8b2f49b2001-06-08 00:21:52 +00006220 }
drhd677b3d2007-08-20 22:48:41 +00006221 sqlite3BtreeLeave(p);
6222 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006223}
6224
6225/*
6226** Erase all information in a table and add the root of the table to
6227** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00006228** page 1) is never added to the freelist.
6229**
6230** This routine will fail with SQLITE_LOCKED if there are any open
6231** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00006232**
6233** If AUTOVACUUM is enabled and the page at iTable is not the last
6234** root page in the database file, then the last root page
6235** in the database file is moved into the slot formerly occupied by
6236** iTable and that last slot formerly occupied by the last root page
6237** is added to the freelist instead of iTable. In this say, all
6238** root pages are kept at the beginning of the database file, which
6239** is necessary for AUTOVACUUM to work right. *piMoved is set to the
6240** page number that used to be the last root page in the file before
6241** the move. If no page gets moved, *piMoved is set to 0.
6242** The last root page is recorded in meta[3] and the value of
6243** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00006244*/
drhd677b3d2007-08-20 22:48:41 +00006245static int btreeDropTable(Btree *p, int iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00006246 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00006247 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00006248 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00006249
drh1fee73e2007-08-29 04:00:57 +00006250 assert( sqlite3BtreeHoldsMutex(p) );
danielk1977aef0bf62005-12-30 16:28:01 +00006251 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00006252 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00006253 }
danielk1977a0bf2652004-11-04 14:30:04 +00006254
danielk1977e6efa742004-11-10 11:55:10 +00006255 /* It is illegal to drop a table if any cursors are open on the
6256 ** database. This is because in auto-vacuum mode the backend may
6257 ** need to move another root-page to fill a gap left by the deleted
6258 ** root page. If an open cursor was using this page a problem would
6259 ** occur.
6260 */
6261 if( pBt->pCursor ){
6262 return SQLITE_LOCKED;
drh5df72a52002-06-06 23:16:05 +00006263 }
danielk1977a0bf2652004-11-04 14:30:04 +00006264
drh16a9b832007-05-05 18:39:25 +00006265 rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00006266 if( rc ) return rc;
danielk1977aef0bf62005-12-30 16:28:01 +00006267 rc = sqlite3BtreeClearTable(p, iTable);
danielk19776b456a22005-03-21 04:04:02 +00006268 if( rc ){
6269 releasePage(pPage);
6270 return rc;
6271 }
danielk1977a0bf2652004-11-04 14:30:04 +00006272
drh205f48e2004-11-05 00:43:11 +00006273 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00006274
drh4b70f112004-05-02 21:12:19 +00006275 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00006276#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00006277 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00006278 releasePage(pPage);
6279#else
6280 if( pBt->autoVacuum ){
6281 Pgno maxRootPgno;
danielk1977aef0bf62005-12-30 16:28:01 +00006282 rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006283 if( rc!=SQLITE_OK ){
6284 releasePage(pPage);
6285 return rc;
6286 }
6287
6288 if( iTable==maxRootPgno ){
6289 /* If the table being dropped is the table with the largest root-page
6290 ** number in the database, put the root page on the free list.
6291 */
6292 rc = freePage(pPage);
6293 releasePage(pPage);
6294 if( rc!=SQLITE_OK ){
6295 return rc;
6296 }
6297 }else{
6298 /* The table being dropped does not have the largest root-page
6299 ** number in the database. So move the page that does into the
6300 ** gap left by the deleted root-page.
6301 */
6302 MemPage *pMove;
6303 releasePage(pPage);
drh16a9b832007-05-05 18:39:25 +00006304 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006305 if( rc!=SQLITE_OK ){
6306 return rc;
6307 }
danielk19774c999992008-07-16 18:17:55 +00006308 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006309 releasePage(pMove);
6310 if( rc!=SQLITE_OK ){
6311 return rc;
6312 }
drh16a9b832007-05-05 18:39:25 +00006313 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006314 if( rc!=SQLITE_OK ){
6315 return rc;
6316 }
6317 rc = freePage(pMove);
6318 releasePage(pMove);
6319 if( rc!=SQLITE_OK ){
6320 return rc;
6321 }
6322 *piMoved = maxRootPgno;
6323 }
6324
danielk1977599fcba2004-11-08 07:13:13 +00006325 /* Set the new 'max-root-page' value in the database header. This
6326 ** is the old value less one, less one more if that happens to
6327 ** be a root-page number, less one again if that is the
6328 ** PENDING_BYTE_PAGE.
6329 */
danielk197787a6e732004-11-05 12:58:25 +00006330 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00006331 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
6332 maxRootPgno--;
6333 }
danielk1977266664d2006-02-10 08:24:21 +00006334 if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00006335 maxRootPgno--;
6336 }
danielk1977599fcba2004-11-08 07:13:13 +00006337 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
6338
danielk1977aef0bf62005-12-30 16:28:01 +00006339 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006340 }else{
6341 rc = freePage(pPage);
6342 releasePage(pPage);
6343 }
6344#endif
drh2aa679f2001-06-25 02:11:07 +00006345 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00006346 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00006347 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00006348 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00006349 }
drh8b2f49b2001-06-08 00:21:52 +00006350 return rc;
6351}
drhd677b3d2007-08-20 22:48:41 +00006352int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
6353 int rc;
6354 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006355 p->pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006356 rc = btreeDropTable(p, iTable, piMoved);
6357 sqlite3BtreeLeave(p);
6358 return rc;
6359}
drh8b2f49b2001-06-08 00:21:52 +00006360
drh001bbcb2003-03-19 03:14:00 +00006361
drh8b2f49b2001-06-08 00:21:52 +00006362/*
drh23e11ca2004-05-04 17:27:28 +00006363** Read the meta-information out of a database file. Meta[0]
6364** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00006365** through meta[15] are available for use by higher layers. Meta[0]
6366** is read-only, the others are read/write.
6367**
6368** The schema layer numbers meta values differently. At the schema
6369** layer (and the SetCookie and ReadCookie opcodes) the number of
6370** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00006371*/
danielk1977aef0bf62005-12-30 16:28:01 +00006372int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
danielk19773b8a05f2007-03-19 17:44:26 +00006373 DbPage *pDbPage;
drh8b2f49b2001-06-08 00:21:52 +00006374 int rc;
drh4b70f112004-05-02 21:12:19 +00006375 unsigned char *pP1;
danielk1977aef0bf62005-12-30 16:28:01 +00006376 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006377
drhd677b3d2007-08-20 22:48:41 +00006378 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006379 pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006380
danielk1977da184232006-01-05 11:34:32 +00006381 /* Reading a meta-data value requires a read-lock on page 1 (and hence
6382 ** the sqlite_master table. We grab this lock regardless of whether or
6383 ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
6384 ** 1 is treated as a special case by queryTableLock() and lockTable()).
6385 */
6386 rc = queryTableLock(p, 1, READ_LOCK);
6387 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00006388 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00006389 return rc;
6390 }
6391
drh23e11ca2004-05-04 17:27:28 +00006392 assert( idx>=0 && idx<=15 );
danielk19773b8a05f2007-03-19 17:44:26 +00006393 rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
drhd677b3d2007-08-20 22:48:41 +00006394 if( rc ){
6395 sqlite3BtreeLeave(p);
6396 return rc;
6397 }
danielk19773b8a05f2007-03-19 17:44:26 +00006398 pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
drh23e11ca2004-05-04 17:27:28 +00006399 *pMeta = get4byte(&pP1[36 + idx*4]);
danielk19773b8a05f2007-03-19 17:44:26 +00006400 sqlite3PagerUnref(pDbPage);
drhae157872004-08-14 19:20:09 +00006401
danielk1977599fcba2004-11-08 07:13:13 +00006402 /* If autovacuumed is disabled in this build but we are trying to
6403 ** access an autovacuumed database, then make the database readonly.
6404 */
danielk1977003ba062004-11-04 02:57:33 +00006405#ifdef SQLITE_OMIT_AUTOVACUUM
drhae157872004-08-14 19:20:09 +00006406 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00006407#endif
drhae157872004-08-14 19:20:09 +00006408
danielk1977da184232006-01-05 11:34:32 +00006409 /* Grab the read-lock on page 1. */
6410 rc = lockTable(p, 1, READ_LOCK);
drhd677b3d2007-08-20 22:48:41 +00006411 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00006412 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006413}
6414
6415/*
drh23e11ca2004-05-04 17:27:28 +00006416** Write meta-information back into the database. Meta[0] is
6417** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00006418*/
danielk1977aef0bf62005-12-30 16:28:01 +00006419int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
6420 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00006421 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00006422 int rc;
drh23e11ca2004-05-04 17:27:28 +00006423 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00006424 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006425 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00006426 if( p->inTrans!=TRANS_WRITE ){
drhd677b3d2007-08-20 22:48:41 +00006427 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
6428 }else{
6429 assert( pBt->pPage1!=0 );
6430 pP1 = pBt->pPage1->aData;
6431 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6432 if( rc==SQLITE_OK ){
6433 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +00006434#ifndef SQLITE_OMIT_AUTOVACUUM
drhd677b3d2007-08-20 22:48:41 +00006435 if( idx==7 ){
6436 assert( pBt->autoVacuum || iMeta==0 );
6437 assert( iMeta==0 || iMeta==1 );
6438 pBt->incrVacuum = iMeta;
6439 }
danielk19774152e672007-09-12 17:01:45 +00006440#endif
drhd677b3d2007-08-20 22:48:41 +00006441 }
drh5df72a52002-06-06 23:16:05 +00006442 }
drhd677b3d2007-08-20 22:48:41 +00006443 sqlite3BtreeLeave(p);
6444 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006445}
drh8c42ca92001-06-22 19:15:00 +00006446
drhf328bc82004-05-10 23:29:49 +00006447/*
6448** Return the flag byte at the beginning of the page that the cursor
6449** is currently pointing to.
6450*/
6451int sqlite3BtreeFlags(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00006452 /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
drha3460582008-07-11 21:02:53 +00006453 ** restoreCursorPosition() here.
danielk1977da184232006-01-05 11:34:32 +00006454 */
danielk1977e448dc42008-01-02 11:50:51 +00006455 MemPage *pPage;
drha3460582008-07-11 21:02:53 +00006456 restoreCursorPosition(pCur);
danielk1977e448dc42008-01-02 11:50:51 +00006457 pPage = pCur->pPage;
drh1fee73e2007-08-29 04:00:57 +00006458 assert( cursorHoldsMutex(pCur) );
drhd0679ed2007-08-28 22:24:34 +00006459 assert( pPage->pBt==pCur->pBt );
drhf328bc82004-05-10 23:29:49 +00006460 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
6461}
6462
drhdd793422001-06-28 01:54:48 +00006463
drhdd793422001-06-28 01:54:48 +00006464/*
drh5eddca62001-06-30 21:53:53 +00006465** Return the pager associated with a BTree. This routine is used for
6466** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00006467*/
danielk1977aef0bf62005-12-30 16:28:01 +00006468Pager *sqlite3BtreePager(Btree *p){
6469 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00006470}
drh5eddca62001-06-30 21:53:53 +00006471
drhb7f91642004-10-31 02:22:47 +00006472#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006473/*
6474** Append a message to the error message string.
6475*/
drh2e38c322004-09-03 18:38:44 +00006476static void checkAppendMsg(
6477 IntegrityCk *pCheck,
6478 char *zMsg1,
6479 const char *zFormat,
6480 ...
6481){
6482 va_list ap;
drh1dcdbc02007-01-27 02:24:54 +00006483 if( !pCheck->mxErr ) return;
6484 pCheck->mxErr--;
6485 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00006486 va_start(ap, zFormat);
drhf089aa42008-07-08 19:34:06 +00006487 if( pCheck->errMsg.nChar ){
6488 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
drh5eddca62001-06-30 21:53:53 +00006489 }
drhf089aa42008-07-08 19:34:06 +00006490 if( zMsg1 ){
6491 sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
6492 }
6493 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
6494 va_end(ap);
drh5eddca62001-06-30 21:53:53 +00006495}
drhb7f91642004-10-31 02:22:47 +00006496#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006497
drhb7f91642004-10-31 02:22:47 +00006498#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006499/*
6500** Add 1 to the reference count for page iPage. If this is the second
6501** reference to the page, add an error message to pCheck->zErrMsg.
6502** Return 1 if there are 2 ore more references to the page and 0 if
6503** if this is the first reference to the page.
6504**
6505** Also check that the page number is in bounds.
6506*/
drhaaab5722002-02-19 13:39:21 +00006507static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00006508 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00006509 if( iPage>pCheck->nPage || iPage<0 ){
drh2e38c322004-09-03 18:38:44 +00006510 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006511 return 1;
6512 }
6513 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00006514 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006515 return 1;
6516 }
6517 return (pCheck->anRef[iPage]++)>1;
6518}
6519
danielk1977afcdd022004-10-31 16:25:42 +00006520#ifndef SQLITE_OMIT_AUTOVACUUM
6521/*
6522** Check that the entry in the pointer-map for page iChild maps to
6523** page iParent, pointer type ptrType. If not, append an error message
6524** to pCheck.
6525*/
6526static void checkPtrmap(
6527 IntegrityCk *pCheck, /* Integrity check context */
6528 Pgno iChild, /* Child page number */
6529 u8 eType, /* Expected pointer map type */
6530 Pgno iParent, /* Expected pointer map parent page number */
6531 char *zContext /* Context description (used for error msg) */
6532){
6533 int rc;
6534 u8 ePtrmapType;
6535 Pgno iPtrmapParent;
6536
6537 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
6538 if( rc!=SQLITE_OK ){
6539 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
6540 return;
6541 }
6542
6543 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
6544 checkAppendMsg(pCheck, zContext,
6545 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
6546 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
6547 }
6548}
6549#endif
6550
drh5eddca62001-06-30 21:53:53 +00006551/*
6552** Check the integrity of the freelist or of an overflow page list.
6553** Verify that the number of pages on the list is N.
6554*/
drh30e58752002-03-02 20:41:57 +00006555static void checkList(
6556 IntegrityCk *pCheck, /* Integrity checking context */
6557 int isFreeList, /* True for a freelist. False for overflow page list */
6558 int iPage, /* Page number for first page in the list */
6559 int N, /* Expected number of pages in the list */
6560 char *zContext /* Context for error messages */
6561){
6562 int i;
drh3a4c1412004-05-09 20:40:11 +00006563 int expected = N;
6564 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00006565 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00006566 DbPage *pOvflPage;
6567 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00006568 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00006569 checkAppendMsg(pCheck, zContext,
6570 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00006571 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00006572 break;
6573 }
6574 if( checkRef(pCheck, iPage, zContext) ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00006575 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
drh2e38c322004-09-03 18:38:44 +00006576 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006577 break;
6578 }
danielk19773b8a05f2007-03-19 17:44:26 +00006579 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00006580 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00006581 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00006582#ifndef SQLITE_OMIT_AUTOVACUUM
6583 if( pCheck->pBt->autoVacuum ){
6584 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
6585 }
6586#endif
drh45b1fac2008-07-04 17:52:42 +00006587 if( n>pCheck->pBt->usableSize/4-2 ){
drh2e38c322004-09-03 18:38:44 +00006588 checkAppendMsg(pCheck, zContext,
6589 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00006590 N--;
6591 }else{
6592 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00006593 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00006594#ifndef SQLITE_OMIT_AUTOVACUUM
6595 if( pCheck->pBt->autoVacuum ){
6596 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
6597 }
6598#endif
6599 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00006600 }
6601 N -= n;
drh30e58752002-03-02 20:41:57 +00006602 }
drh30e58752002-03-02 20:41:57 +00006603 }
danielk1977afcdd022004-10-31 16:25:42 +00006604#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006605 else{
6606 /* If this database supports auto-vacuum and iPage is not the last
6607 ** page in this overflow list, check that the pointer-map entry for
6608 ** the following page matches iPage.
6609 */
6610 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00006611 i = get4byte(pOvflData);
danielk1977687566d2004-11-02 12:56:41 +00006612 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
6613 }
danielk1977afcdd022004-10-31 16:25:42 +00006614 }
6615#endif
danielk19773b8a05f2007-03-19 17:44:26 +00006616 iPage = get4byte(pOvflData);
6617 sqlite3PagerUnref(pOvflPage);
drh5eddca62001-06-30 21:53:53 +00006618 }
6619}
drhb7f91642004-10-31 02:22:47 +00006620#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006621
drhb7f91642004-10-31 02:22:47 +00006622#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006623/*
6624** Do various sanity checks on a single page of a tree. Return
6625** the tree depth. Root pages return 0. Parents of root pages
6626** return 1, and so forth.
6627**
6628** These checks are done:
6629**
6630** 1. Make sure that cells and freeblocks do not overlap
6631** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00006632** NO 2. Make sure cell keys are in order.
6633** NO 3. Make sure no key is less than or equal to zLowerBound.
6634** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00006635** 5. Check the integrity of overflow pages.
6636** 6. Recursively call checkTreePage on all children.
6637** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00006638** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00006639** the root of the tree.
6640*/
6641static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00006642 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00006643 int iPage, /* Page number of the page to check */
6644 MemPage *pParent, /* Parent page */
drh74161702006-02-24 02:53:49 +00006645 char *zParentContext /* Parent context */
drh5eddca62001-06-30 21:53:53 +00006646){
6647 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00006648 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00006649 int hdr, cellStart;
6650 int nCell;
drhda200cc2004-05-09 11:51:38 +00006651 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00006652 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00006653 int usableSize;
drh5eddca62001-06-30 21:53:53 +00006654 char zContext[100];
drh2e38c322004-09-03 18:38:44 +00006655 char *hit;
drh5eddca62001-06-30 21:53:53 +00006656
drh5bb3eb92007-05-04 13:15:55 +00006657 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
danielk1977ef73ee92004-11-06 12:26:07 +00006658
drh5eddca62001-06-30 21:53:53 +00006659 /* Check that the page exists
6660 */
drhd9cb6ac2005-10-20 07:28:17 +00006661 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00006662 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00006663 if( iPage==0 ) return 0;
6664 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh16a9b832007-05-05 18:39:25 +00006665 if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drh2e38c322004-09-03 18:38:44 +00006666 checkAppendMsg(pCheck, zContext,
6667 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00006668 return 0;
6669 }
drh16a9b832007-05-05 18:39:25 +00006670 if( (rc = sqlite3BtreeInitPage(pPage, pParent))!=0 ){
6671 checkAppendMsg(pCheck, zContext,
6672 "sqlite3BtreeInitPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00006673 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00006674 return 0;
6675 }
6676
6677 /* Check out all the cells.
6678 */
6679 depth = 0;
drh1dcdbc02007-01-27 02:24:54 +00006680 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
drh6f11bef2004-05-13 01:12:56 +00006681 u8 *pCell;
6682 int sz;
6683 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00006684
6685 /* Check payload overflow pages
6686 */
drh5bb3eb92007-05-04 13:15:55 +00006687 sqlite3_snprintf(sizeof(zContext), zContext,
6688 "On tree page %d cell %d: ", iPage, i);
danielk19771cc5ed82007-05-16 17:28:43 +00006689 pCell = findCell(pPage,i);
drh16a9b832007-05-05 18:39:25 +00006690 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00006691 sz = info.nData;
6692 if( !pPage->intKey ) sz += info.nKey;
drh72365832007-03-06 15:53:44 +00006693 assert( sz==info.nPayload );
drh6f11bef2004-05-13 01:12:56 +00006694 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00006695 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00006696 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
6697#ifndef SQLITE_OMIT_AUTOVACUUM
6698 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006699 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00006700 }
6701#endif
6702 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00006703 }
6704
6705 /* Check sanity of left child page.
6706 */
drhda200cc2004-05-09 11:51:38 +00006707 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006708 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00006709#ifndef SQLITE_OMIT_AUTOVACUUM
6710 if( pBt->autoVacuum ){
6711 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
6712 }
6713#endif
drh74161702006-02-24 02:53:49 +00006714 d2 = checkTreePage(pCheck,pgno,pPage,zContext);
drhda200cc2004-05-09 11:51:38 +00006715 if( i>0 && d2!=depth ){
6716 checkAppendMsg(pCheck, zContext, "Child page depth differs");
6717 }
6718 depth = d2;
drh5eddca62001-06-30 21:53:53 +00006719 }
drh5eddca62001-06-30 21:53:53 +00006720 }
drhda200cc2004-05-09 11:51:38 +00006721 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006722 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh5bb3eb92007-05-04 13:15:55 +00006723 sqlite3_snprintf(sizeof(zContext), zContext,
6724 "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00006725#ifndef SQLITE_OMIT_AUTOVACUUM
6726 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006727 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00006728 }
6729#endif
drh74161702006-02-24 02:53:49 +00006730 checkTreePage(pCheck, pgno, pPage, zContext);
drhda200cc2004-05-09 11:51:38 +00006731 }
drh5eddca62001-06-30 21:53:53 +00006732
6733 /* Check for complete coverage of the page
6734 */
drhda200cc2004-05-09 11:51:38 +00006735 data = pPage->aData;
6736 hdr = pPage->hdrOffset;
drhf7141992008-06-19 00:16:08 +00006737 hit = sqlite3PageMalloc( pBt->pageSize );
drh2e38c322004-09-03 18:38:44 +00006738 if( hit ){
drhf7141992008-06-19 00:16:08 +00006739 memset(hit, 0, usableSize );
drh2e38c322004-09-03 18:38:44 +00006740 memset(hit, 1, get2byte(&data[hdr+5]));
6741 nCell = get2byte(&data[hdr+3]);
6742 cellStart = hdr + 12 - 4*pPage->leaf;
6743 for(i=0; i<nCell; i++){
6744 int pc = get2byte(&data[cellStart+i*2]);
drha9121e42008-02-19 14:59:35 +00006745 u16 size = cellSizePtr(pPage, &data[pc]);
drh2e38c322004-09-03 18:38:44 +00006746 int j;
danielk19777701e812005-01-10 12:59:51 +00006747 if( (pc+size-1)>=usableSize || pc<0 ){
6748 checkAppendMsg(pCheck, 0,
6749 "Corruption detected in cell %d on page %d",i,iPage,0);
6750 }else{
6751 for(j=pc+size-1; j>=pc; j--) hit[j]++;
6752 }
drh2e38c322004-09-03 18:38:44 +00006753 }
6754 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
6755 cnt++){
6756 int size = get2byte(&data[i+2]);
6757 int j;
danielk19777701e812005-01-10 12:59:51 +00006758 if( (i+size-1)>=usableSize || i<0 ){
6759 checkAppendMsg(pCheck, 0,
6760 "Corruption detected in cell %d on page %d",i,iPage,0);
6761 }else{
6762 for(j=i+size-1; j>=i; j--) hit[j]++;
6763 }
drh2e38c322004-09-03 18:38:44 +00006764 i = get2byte(&data[i]);
6765 }
6766 for(i=cnt=0; i<usableSize; i++){
6767 if( hit[i]==0 ){
6768 cnt++;
6769 }else if( hit[i]>1 ){
6770 checkAppendMsg(pCheck, 0,
6771 "Multiple uses for byte %d of page %d", i, iPage);
6772 break;
6773 }
6774 }
6775 if( cnt!=data[hdr+7] ){
6776 checkAppendMsg(pCheck, 0,
6777 "Fragmented space is %d byte reported as %d on page %d",
6778 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00006779 }
6780 }
drhf7141992008-06-19 00:16:08 +00006781 sqlite3PageFree(hit);
drh6019e162001-07-02 17:51:45 +00006782
drh4b70f112004-05-02 21:12:19 +00006783 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00006784 return depth+1;
drh5eddca62001-06-30 21:53:53 +00006785}
drhb7f91642004-10-31 02:22:47 +00006786#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006787
drhb7f91642004-10-31 02:22:47 +00006788#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006789/*
6790** This routine does a complete check of the given BTree file. aRoot[] is
6791** an array of pages numbers were each page number is the root page of
6792** a table. nRoot is the number of entries in aRoot.
6793**
6794** If everything checks out, this routine returns NULL. If something is
6795** amiss, an error message is written into memory obtained from malloc()
6796** and a pointer to that error message is returned. The calling function
6797** is responsible for freeing the error message when it is done.
6798*/
drh1dcdbc02007-01-27 02:24:54 +00006799char *sqlite3BtreeIntegrityCheck(
6800 Btree *p, /* The btree to be checked */
6801 int *aRoot, /* An array of root pages numbers for individual trees */
6802 int nRoot, /* Number of entries in aRoot[] */
6803 int mxErr, /* Stop reporting errors after this many */
6804 int *pnErr /* Write number of errors seen to this variable */
6805){
drh5eddca62001-06-30 21:53:53 +00006806 int i;
6807 int nRef;
drhaaab5722002-02-19 13:39:21 +00006808 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00006809 BtShared *pBt = p->pBt;
drhf089aa42008-07-08 19:34:06 +00006810 char zErr[100];
drh5eddca62001-06-30 21:53:53 +00006811
drhd677b3d2007-08-20 22:48:41 +00006812 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006813 pBt->db = p->db;
danielk19773b8a05f2007-03-19 17:44:26 +00006814 nRef = sqlite3PagerRefcount(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00006815 if( lockBtreeWithRetry(p)!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00006816 sqlite3BtreeLeave(p);
drh17435752007-08-16 04:30:38 +00006817 return sqlite3StrDup("Unable to acquire a read lock on the database");
drhefc251d2001-07-01 22:12:01 +00006818 }
drh5eddca62001-06-30 21:53:53 +00006819 sCheck.pBt = pBt;
6820 sCheck.pPager = pBt->pPager;
danielk1977ad0132d2008-06-07 08:58:22 +00006821 sCheck.nPage = pagerPagecount(sCheck.pPager);
drh1dcdbc02007-01-27 02:24:54 +00006822 sCheck.mxErr = mxErr;
6823 sCheck.nErr = 0;
6824 *pnErr = 0;
danielk1977e5321f02007-04-27 07:05:44 +00006825#ifndef SQLITE_OMIT_AUTOVACUUM
6826 if( pBt->nTrunc!=0 ){
6827 sCheck.nPage = pBt->nTrunc;
6828 }
6829#endif
drh0de8c112002-07-06 16:32:14 +00006830 if( sCheck.nPage==0 ){
6831 unlockBtreeIfUnused(pBt);
drhd677b3d2007-08-20 22:48:41 +00006832 sqlite3BtreeLeave(p);
drh0de8c112002-07-06 16:32:14 +00006833 return 0;
6834 }
drhe5ae5732008-06-15 02:51:47 +00006835 sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00006836 if( !sCheck.anRef ){
6837 unlockBtreeIfUnused(pBt);
drh1dcdbc02007-01-27 02:24:54 +00006838 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00006839 sqlite3BtreeLeave(p);
drhe5fe6902007-12-07 18:55:28 +00006840 return sqlite3MPrintf(p->db, "Unable to malloc %d bytes",
danielk1977ac245ec2005-01-14 13:50:11 +00006841 (sCheck.nPage+1)*sizeof(sCheck.anRef[0]));
6842 }
drhda200cc2004-05-09 11:51:38 +00006843 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00006844 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00006845 if( i<=sCheck.nPage ){
6846 sCheck.anRef[i] = 1;
6847 }
drhf089aa42008-07-08 19:34:06 +00006848 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
drh5eddca62001-06-30 21:53:53 +00006849
6850 /* Check the integrity of the freelist
6851 */
drha34b6762004-05-07 13:30:42 +00006852 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
6853 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00006854
6855 /* Check all the tables.
6856 */
drh1dcdbc02007-01-27 02:24:54 +00006857 for(i=0; i<nRoot && sCheck.mxErr; i++){
drh4ff6dfa2002-03-03 23:06:00 +00006858 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00006859#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006860 if( pBt->autoVacuum && aRoot[i]>1 ){
6861 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
6862 }
6863#endif
drh74161702006-02-24 02:53:49 +00006864 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ");
drh5eddca62001-06-30 21:53:53 +00006865 }
6866
6867 /* Make sure every page in the file is referenced
6868 */
drh1dcdbc02007-01-27 02:24:54 +00006869 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00006870#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00006871 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00006872 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00006873 }
danielk1977afcdd022004-10-31 16:25:42 +00006874#else
6875 /* If the database supports auto-vacuum, make sure no tables contain
6876 ** references to pointer-map pages.
6877 */
6878 if( sCheck.anRef[i]==0 &&
danielk1977266664d2006-02-10 08:24:21 +00006879 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006880 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
6881 }
6882 if( sCheck.anRef[i]!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00006883 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006884 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
6885 }
6886#endif
drh5eddca62001-06-30 21:53:53 +00006887 }
6888
6889 /* Make sure this analysis did not leave any unref() pages
6890 */
drh5e00f6c2001-09-13 13:46:56 +00006891 unlockBtreeIfUnused(pBt);
danielk19773b8a05f2007-03-19 17:44:26 +00006892 if( nRef != sqlite3PagerRefcount(pBt->pPager) ){
drh2e38c322004-09-03 18:38:44 +00006893 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00006894 "Outstanding page count goes from %d to %d during this analysis",
danielk19773b8a05f2007-03-19 17:44:26 +00006895 nRef, sqlite3PagerRefcount(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00006896 );
drh5eddca62001-06-30 21:53:53 +00006897 }
6898
6899 /* Clean up and report errors.
6900 */
drhd677b3d2007-08-20 22:48:41 +00006901 sqlite3BtreeLeave(p);
drh17435752007-08-16 04:30:38 +00006902 sqlite3_free(sCheck.anRef);
drh1dcdbc02007-01-27 02:24:54 +00006903 *pnErr = sCheck.nErr;
drhf089aa42008-07-08 19:34:06 +00006904 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
6905 return sqlite3StrAccumFinish(&sCheck.errMsg);
drh5eddca62001-06-30 21:53:53 +00006906}
drhb7f91642004-10-31 02:22:47 +00006907#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00006908
drh73509ee2003-04-06 20:44:45 +00006909/*
6910** Return the full pathname of the underlying database file.
drhd0679ed2007-08-28 22:24:34 +00006911**
6912** The pager filename is invariant as long as the pager is
6913** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +00006914*/
danielk1977aef0bf62005-12-30 16:28:01 +00006915const char *sqlite3BtreeGetFilename(Btree *p){
6916 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00006917 return sqlite3PagerFilename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00006918}
6919
6920/*
danielk19775865e3d2004-06-14 06:03:57 +00006921** Return the pathname of the directory that contains the database file.
drhd0679ed2007-08-28 22:24:34 +00006922**
6923** The pager directory name is invariant as long as the pager is
6924** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00006925*/
danielk1977aef0bf62005-12-30 16:28:01 +00006926const char *sqlite3BtreeGetDirname(Btree *p){
6927 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00006928 return sqlite3PagerDirname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006929}
6930
6931/*
6932** Return the pathname of the journal file for this database. The return
6933** value of this routine is the same regardless of whether the journal file
6934** has been created or not.
drhd0679ed2007-08-28 22:24:34 +00006935**
6936** The pager journal filename is invariant as long as the pager is
6937** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00006938*/
danielk1977aef0bf62005-12-30 16:28:01 +00006939const char *sqlite3BtreeGetJournalname(Btree *p){
6940 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00006941 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006942}
6943
drhb7f91642004-10-31 02:22:47 +00006944#ifndef SQLITE_OMIT_VACUUM
danielk19775865e3d2004-06-14 06:03:57 +00006945/*
drhf7c57532003-04-25 13:22:51 +00006946** Copy the complete content of pBtFrom into pBtTo. A transaction
6947** must be active for both files.
6948**
danielk1977f653d782008-03-20 11:04:21 +00006949** The size of file pTo may be reduced by this operation.
6950** If anything goes wrong, the transaction on pTo is rolled back.
6951**
6952** If successful, CommitPhaseOne() may be called on pTo before returning.
6953** The caller should finish committing the transaction on pTo by calling
6954** sqlite3BtreeCommit().
drh73509ee2003-04-06 20:44:45 +00006955*/
drhd677b3d2007-08-20 22:48:41 +00006956static int btreeCopyFile(Btree *pTo, Btree *pFrom){
drhf7c57532003-04-25 13:22:51 +00006957 int rc = SQLITE_OK;
danielk1977f653d782008-03-20 11:04:21 +00006958 Pgno i;
6959
6960 Pgno nFromPage; /* Number of pages in pFrom */
6961 Pgno nToPage; /* Number of pages in pTo */
6962 Pgno nNewPage; /* Number of pages in pTo after the copy */
6963
6964 Pgno iSkip; /* Pending byte page in pTo */
6965 int nToPageSize; /* Page size of pTo in bytes */
6966 int nFromPageSize; /* Page size of pFrom in bytes */
drhf7c57532003-04-25 13:22:51 +00006967
danielk1977aef0bf62005-12-30 16:28:01 +00006968 BtShared *pBtTo = pTo->pBt;
6969 BtShared *pBtFrom = pFrom->pBt;
drhe5fe6902007-12-07 18:55:28 +00006970 pBtTo->db = pTo->db;
6971 pBtFrom->db = pFrom->db;
danielk1977f653d782008-03-20 11:04:21 +00006972
6973 nToPageSize = pBtTo->pageSize;
6974 nFromPageSize = pBtFrom->pageSize;
danielk1977aef0bf62005-12-30 16:28:01 +00006975
6976 if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
danielk1977ee5741e2004-05-31 10:01:34 +00006977 return SQLITE_ERROR;
6978 }
danielk1977f653d782008-03-20 11:04:21 +00006979 if( pBtTo->pCursor ){
6980 return SQLITE_BUSY;
drhf7c57532003-04-25 13:22:51 +00006981 }
drh538f5702007-04-13 02:14:30 +00006982
danielk1977ad0132d2008-06-07 08:58:22 +00006983 nToPage = pagerPagecount(pBtTo->pPager);
6984 nFromPage = pagerPagecount(pBtFrom->pPager);
danielk1977f653d782008-03-20 11:04:21 +00006985 iSkip = PENDING_BYTE_PAGE(pBtTo);
6986
6987 /* Variable nNewPage is the number of pages required to store the
6988 ** contents of pFrom using the current page-size of pTo.
drh538f5702007-04-13 02:14:30 +00006989 */
danielk1977f653d782008-03-20 11:04:21 +00006990 nNewPage = ((i64)nFromPage * (i64)nFromPageSize + (i64)nToPageSize - 1) /
6991 (i64)nToPageSize;
6992
6993 for(i=1; rc==SQLITE_OK && (i<=nToPage || i<=nNewPage); i++){
6994
6995 /* Journal the original page.
6996 **
6997 ** iSkip is the page number of the locking page (PENDING_BYTE_PAGE)
6998 ** in database *pTo (before the copy). This page is never written
6999 ** into the journal file. Unless i==iSkip or the page was not
7000 ** present in pTo before the copy operation, journal page i from pTo.
7001 */
7002 if( i!=iSkip && i<=nToPage ){
danielk19774abd5442008-05-05 15:26:50 +00007003 DbPage *pDbPage = 0;
danielk1977f653d782008-03-20 11:04:21 +00007004 rc = sqlite3PagerGet(pBtTo->pPager, i, &pDbPage);
danielk19774abd5442008-05-05 15:26:50 +00007005 if( rc==SQLITE_OK ){
7006 rc = sqlite3PagerWrite(pDbPage);
danielk1977df2566a2008-05-07 19:11:03 +00007007 if( rc==SQLITE_OK && i>nFromPage ){
7008 /* Yeah. It seems wierd to call DontWrite() right after Write(). But
7009 ** that is because the names of those procedures do not exactly
7010 ** represent what they do. Write() really means "put this page in the
7011 ** rollback journal and mark it as dirty so that it will be written
7012 ** to the database file later." DontWrite() undoes the second part of
7013 ** that and prevents the page from being written to the database. The
7014 ** page is still on the rollback journal, though. And that is the
7015 ** whole point of this block: to put pages on the rollback journal.
7016 */
7017 sqlite3PagerDontWrite(pDbPage);
7018 }
7019 sqlite3PagerUnref(pDbPage);
danielk1977f653d782008-03-20 11:04:21 +00007020 }
danielk1977f653d782008-03-20 11:04:21 +00007021 }
7022
7023 /* Overwrite the data in page i of the target database */
7024 if( rc==SQLITE_OK && i!=iSkip && i<=nNewPage ){
7025
7026 DbPage *pToPage = 0;
7027 sqlite3_int64 iOff;
7028
7029 rc = sqlite3PagerGet(pBtTo->pPager, i, &pToPage);
7030 if( rc==SQLITE_OK ){
7031 rc = sqlite3PagerWrite(pToPage);
7032 }
7033
7034 for(
7035 iOff=(i-1)*nToPageSize;
7036 rc==SQLITE_OK && iOff<i*nToPageSize;
7037 iOff += nFromPageSize
7038 ){
7039 DbPage *pFromPage = 0;
7040 Pgno iFrom = (iOff/nFromPageSize)+1;
7041
7042 if( iFrom==PENDING_BYTE_PAGE(pBtFrom) ){
7043 continue;
7044 }
7045
7046 rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
7047 if( rc==SQLITE_OK ){
7048 char *zTo = sqlite3PagerGetData(pToPage);
7049 char *zFrom = sqlite3PagerGetData(pFromPage);
7050 int nCopy;
7051
7052 if( nFromPageSize>=nToPageSize ){
7053 zFrom += ((i-1)*nToPageSize - ((iFrom-1)*nFromPageSize));
7054 nCopy = nToPageSize;
7055 }else{
7056 zTo += (((iFrom-1)*nFromPageSize) - (i-1)*nToPageSize);
7057 nCopy = nFromPageSize;
7058 }
7059
7060 memcpy(zTo, zFrom, nCopy);
7061 sqlite3PagerUnref(pFromPage);
7062 }
7063 }
7064
7065 if( pToPage ) sqlite3PagerUnref(pToPage);
7066 }
drh2e6d11b2003-04-25 15:37:57 +00007067 }
danielk1977f653d782008-03-20 11:04:21 +00007068
7069 /* If things have worked so far, the database file may need to be
7070 ** truncated. The complex part is that it may need to be truncated to
7071 ** a size that is not an integer multiple of nToPageSize - the current
7072 ** page size used by the pager associated with B-Tree pTo.
7073 **
7074 ** For example, say the page-size of pTo is 2048 bytes and the original
7075 ** number of pages is 5 (10 KB file). If pFrom has a page size of 1024
7076 ** bytes and 9 pages, then the file needs to be truncated to 9KB.
7077 */
7078 if( rc==SQLITE_OK ){
7079 if( nFromPageSize!=nToPageSize ){
7080 sqlite3_file *pFile = sqlite3PagerFile(pBtTo->pPager);
7081 i64 iSize = (i64)nFromPageSize * (i64)nFromPage;
7082 i64 iNow = (i64)((nToPage>nNewPage)?nToPage:nNewPage) * (i64)nToPageSize;
7083 i64 iPending = ((i64)PENDING_BYTE_PAGE(pBtTo)-1) *(i64)nToPageSize;
7084
7085 assert( iSize<=iNow );
7086
7087 /* Commit phase one syncs the journal file associated with pTo
7088 ** containing the original data. It does not sync the database file
7089 ** itself. After doing this it is safe to use OsTruncate() and other
7090 ** file APIs on the database file directly.
7091 */
7092 pBtTo->db = pTo->db;
7093 rc = sqlite3PagerCommitPhaseOne(pBtTo->pPager, 0, 0, 1);
7094 if( iSize<iNow && rc==SQLITE_OK ){
7095 rc = sqlite3OsTruncate(pFile, iSize);
7096 }
7097
7098 /* The loop that copied data from database pFrom to pTo did not
7099 ** populate the locking page of database pTo. If the page-size of
7100 ** pFrom is smaller than that of pTo, this means some data will
7101 ** not have been copied.
7102 **
7103 ** This block copies the missing data from database pFrom to pTo
7104 ** using file APIs. This is safe because at this point we know that
7105 ** all of the original data from pTo has been synced into the
7106 ** journal file. At this point it would be safe to do anything at
7107 ** all to the database file except truncate it to zero bytes.
7108 */
7109 if( rc==SQLITE_OK && nFromPageSize<nToPageSize && iSize>iPending){
7110 i64 iOff;
7111 for(
7112 iOff=iPending;
7113 rc==SQLITE_OK && iOff<(iPending+nToPageSize);
7114 iOff += nFromPageSize
7115 ){
7116 DbPage *pFromPage = 0;
7117 Pgno iFrom = (iOff/nFromPageSize)+1;
7118
7119 if( iFrom==PENDING_BYTE_PAGE(pBtFrom) || iFrom>nFromPage ){
7120 continue;
7121 }
7122
7123 rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
7124 if( rc==SQLITE_OK ){
7125 char *zFrom = sqlite3PagerGetData(pFromPage);
7126 rc = sqlite3OsWrite(pFile, zFrom, nFromPageSize, iOff);
7127 sqlite3PagerUnref(pFromPage);
7128 }
7129 }
7130 }
7131
7132 /* Sync the database file */
7133 if( rc==SQLITE_OK ){
7134 rc = sqlite3PagerSync(pBtTo->pPager);
7135 }
7136 }else{
7137 rc = sqlite3PagerTruncate(pBtTo->pPager, nNewPage);
7138 }
7139 if( rc==SQLITE_OK ){
7140 pBtTo->pageSizeFixed = 0;
7141 }
drh2e6d11b2003-04-25 15:37:57 +00007142 }
drh538f5702007-04-13 02:14:30 +00007143
drhf7c57532003-04-25 13:22:51 +00007144 if( rc ){
danielk1977aef0bf62005-12-30 16:28:01 +00007145 sqlite3BtreeRollback(pTo);
drhf7c57532003-04-25 13:22:51 +00007146 }
danielk1977f653d782008-03-20 11:04:21 +00007147
drhf7c57532003-04-25 13:22:51 +00007148 return rc;
drh73509ee2003-04-06 20:44:45 +00007149}
drhd677b3d2007-08-20 22:48:41 +00007150int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
7151 int rc;
7152 sqlite3BtreeEnter(pTo);
7153 sqlite3BtreeEnter(pFrom);
7154 rc = btreeCopyFile(pTo, pFrom);
7155 sqlite3BtreeLeave(pFrom);
7156 sqlite3BtreeLeave(pTo);
7157 return rc;
7158}
7159
drhb7f91642004-10-31 02:22:47 +00007160#endif /* SQLITE_OMIT_VACUUM */
danielk19771d850a72004-05-31 08:26:49 +00007161
7162/*
7163** Return non-zero if a transaction is active.
7164*/
danielk1977aef0bf62005-12-30 16:28:01 +00007165int sqlite3BtreeIsInTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00007166 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00007167 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00007168}
7169
7170/*
7171** Return non-zero if a statement transaction is active.
7172*/
danielk1977aef0bf62005-12-30 16:28:01 +00007173int sqlite3BtreeIsInStmt(Btree *p){
drh1fee73e2007-08-29 04:00:57 +00007174 assert( sqlite3BtreeHoldsMutex(p) );
danielk1977aef0bf62005-12-30 16:28:01 +00007175 return (p->pBt && p->pBt->inStmt);
danielk19771d850a72004-05-31 08:26:49 +00007176}
danielk197713adf8a2004-06-03 16:08:41 +00007177
7178/*
danielk19772372c2b2006-06-27 16:34:56 +00007179** Return non-zero if a read (or write) transaction is active.
7180*/
7181int sqlite3BtreeIsInReadTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00007182 assert( sqlite3_mutex_held(p->db->mutex) );
danielk19772372c2b2006-06-27 16:34:56 +00007183 return (p && (p->inTrans!=TRANS_NONE));
7184}
7185
7186/*
danielk1977da184232006-01-05 11:34:32 +00007187** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +00007188** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +00007189** purposes (for example, to store a high-level schema associated with
7190** the shared-btree). The btree layer manages reference counting issues.
7191**
7192** The first time this is called on a shared-btree, nBytes bytes of memory
7193** are allocated, zeroed, and returned to the caller. For each subsequent
7194** call the nBytes parameter is ignored and a pointer to the same blob
7195** of memory returned.
7196**
danielk1977171bfed2008-06-23 09:50:50 +00007197** If the nBytes parameter is 0 and the blob of memory has not yet been
7198** allocated, a null pointer is returned. If the blob has already been
7199** allocated, it is returned as normal.
7200**
danielk1977da184232006-01-05 11:34:32 +00007201** Just before the shared-btree is closed, the function passed as the
7202** xFree argument when the memory allocation was made is invoked on the
drh17435752007-08-16 04:30:38 +00007203** blob of allocated memory. This function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +00007204** on the memory, the btree layer does that.
7205*/
7206void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
7207 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +00007208 sqlite3BtreeEnter(p);
danielk1977171bfed2008-06-23 09:50:50 +00007209 if( !pBt->pSchema && nBytes ){
drh17435752007-08-16 04:30:38 +00007210 pBt->pSchema = sqlite3MallocZero(nBytes);
danielk1977da184232006-01-05 11:34:32 +00007211 pBt->xFreeSchema = xFree;
7212 }
drh27641702007-08-22 02:56:42 +00007213 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00007214 return pBt->pSchema;
7215}
7216
danielk1977c87d34d2006-01-06 13:00:28 +00007217/*
7218** Return true if another user of the same shared btree as the argument
7219** handle holds an exclusive lock on the sqlite_master table.
7220*/
7221int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +00007222 int rc;
drhe5fe6902007-12-07 18:55:28 +00007223 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +00007224 sqlite3BtreeEnter(p);
7225 rc = (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
7226 sqlite3BtreeLeave(p);
7227 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +00007228}
7229
drha154dcd2006-03-22 22:10:07 +00007230
7231#ifndef SQLITE_OMIT_SHARED_CACHE
7232/*
7233** Obtain a lock on the table whose root page is iTab. The
7234** lock is a write lock if isWritelock is true or a read lock
7235** if it is false.
7236*/
danielk1977c00da102006-01-07 13:21:04 +00007237int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00007238 int rc = SQLITE_OK;
drh6a9ad3d2008-04-02 16:29:30 +00007239 if( p->sharable ){
7240 u8 lockType = READ_LOCK + isWriteLock;
7241 assert( READ_LOCK+1==WRITE_LOCK );
7242 assert( isWriteLock==0 || isWriteLock==1 );
7243 sqlite3BtreeEnter(p);
7244 rc = queryTableLock(p, iTab, lockType);
7245 if( rc==SQLITE_OK ){
7246 rc = lockTable(p, iTab, lockType);
7247 }
7248 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +00007249 }
7250 return rc;
7251}
drha154dcd2006-03-22 22:10:07 +00007252#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00007253
danielk1977b4e9af92007-05-01 17:49:49 +00007254#ifndef SQLITE_OMIT_INCRBLOB
7255/*
7256** Argument pCsr must be a cursor opened for writing on an
7257** INTKEY table currently pointing at a valid table entry.
7258** This function modifies the data stored as part of that entry.
7259** Only the data content may only be modified, it is not possible
7260** to change the length of the data stored.
7261*/
danielk1977dcbb5d32007-05-04 18:36:44 +00007262int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
drh1fee73e2007-08-29 04:00:57 +00007263 assert( cursorHoldsMutex(pCsr) );
drhe5fe6902007-12-07 18:55:28 +00007264 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00007265 assert(pCsr->isIncrblobHandle);
danielk19773588ceb2008-06-10 17:30:26 +00007266
drha3460582008-07-11 21:02:53 +00007267 restoreCursorPosition(pCsr);
danielk19773588ceb2008-06-10 17:30:26 +00007268 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
7269 if( pCsr->eState!=CURSOR_VALID ){
7270 return SQLITE_ABORT;
danielk1977dcbb5d32007-05-04 18:36:44 +00007271 }
7272
danielk1977d04417962007-05-02 13:16:30 +00007273 /* Check some preconditions:
danielk1977dcbb5d32007-05-04 18:36:44 +00007274 ** (a) the cursor is open for writing,
7275 ** (b) there is no read-lock on the table being modified and
7276 ** (c) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00007277 */
danielk1977d04417962007-05-02 13:16:30 +00007278 if( !pCsr->wrFlag ){
danielk1977dcbb5d32007-05-04 18:36:44 +00007279 return SQLITE_READONLY;
danielk1977d04417962007-05-02 13:16:30 +00007280 }
drhd0679ed2007-08-28 22:24:34 +00007281 assert( !pCsr->pBt->readOnly
7282 && pCsr->pBt->inTransaction==TRANS_WRITE );
danielk19773588ceb2008-06-10 17:30:26 +00007283 if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr, 0) ){
danielk1977d04417962007-05-02 13:16:30 +00007284 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
7285 }
7286 if( pCsr->eState==CURSOR_INVALID || !pCsr->pPage->intKey ){
7287 return SQLITE_ERROR;
danielk1977b4e9af92007-05-01 17:49:49 +00007288 }
7289
danielk19779f8d6402007-05-02 17:48:45 +00007290 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00007291}
danielk19772dec9702007-05-02 16:48:37 +00007292
7293/*
7294** Set a flag on this cursor to cache the locations of pages from the
danielk1977da107192007-05-04 08:32:13 +00007295** overflow list for the current row. This is used by cursors opened
7296** for incremental blob IO only.
7297**
7298** This function sets a flag only. The actual page location cache
7299** (stored in BtCursor.aOverflow[]) is allocated and used by function
7300** accessPayload() (the worker function for sqlite3BtreeData() and
7301** sqlite3BtreePutData()).
danielk19772dec9702007-05-02 16:48:37 +00007302*/
7303void sqlite3BtreeCacheOverflow(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00007304 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00007305 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00007306 assert(!pCur->isIncrblobHandle);
danielk19772dec9702007-05-02 16:48:37 +00007307 assert(!pCur->aOverflow);
danielk1977dcbb5d32007-05-04 18:36:44 +00007308 pCur->isIncrblobHandle = 1;
danielk19772dec9702007-05-02 16:48:37 +00007309}
danielk1977b4e9af92007-05-01 17:49:49 +00007310#endif