blob: 8392772e4dcd81e6d0910432b3cfc852cedbd8aa [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*************************************************************************
shanedcc50b72008-11-13 18:29:50 +000012** $Id: btree.c,v 1.536 2008/11/13 18:29:51 shane 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
drhf94a1732008-09-30 17:18:17 +000037/*
38** Sometimes we need a small amount of code such as a variable initialization
39** to setup for a later assert() statement. We do not want this code to
40** appear when assert() is disabled. The following macro is therefore
41** used to contain that setup code. The "VVA" acronym stands for
42** "Verification, Validation, and Accreditation". In other words, the
43** code within VVA_ONLY() will only run during verification processes.
44*/
45#ifndef NDEBUG
46# define VVA_ONLY(X) X
47#else
48# define VVA_ONLY(X)
49#endif
50
drh86f8c192007-08-22 00:39:19 +000051
52
drhe53831d2007-08-17 01:14:38 +000053#ifndef SQLITE_OMIT_SHARED_CACHE
54/*
danielk1977502b4e02008-09-02 14:07:24 +000055** A list of BtShared objects that are eligible for participation
56** in shared cache. This variable has file scope during normal builds,
57** but the test harness needs to access it so we make it global for
58** test builds.
drhe53831d2007-08-17 01:14:38 +000059*/
60#ifdef SQLITE_TEST
drh78f82d12008-09-02 00:52:52 +000061BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
drhe53831d2007-08-17 01:14:38 +000062#else
drh78f82d12008-09-02 00:52:52 +000063static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
drhe53831d2007-08-17 01:14:38 +000064#endif
drhe53831d2007-08-17 01:14:38 +000065#endif /* SQLITE_OMIT_SHARED_CACHE */
66
67#ifndef SQLITE_OMIT_SHARED_CACHE
68/*
69** Enable or disable the shared pager and schema features.
70**
71** This routine has no effect on existing database connections.
72** The shared cache setting effects only future calls to
73** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
74*/
75int sqlite3_enable_shared_cache(int enable){
danielk1977502b4e02008-09-02 14:07:24 +000076 sqlite3GlobalConfig.sharedCacheEnabled = enable;
drhe53831d2007-08-17 01:14:38 +000077 return SQLITE_OK;
78}
79#endif
80
drhd677b3d2007-08-20 22:48:41 +000081
drh615ae552005-01-16 23:21:00 +000082/*
drh66cbd152004-09-01 16:12:25 +000083** Forward declaration
84*/
danielk19773588ceb2008-06-10 17:30:26 +000085static int checkReadLocks(Btree*, Pgno, BtCursor*, i64);
drh66cbd152004-09-01 16:12:25 +000086
danielk1977aef0bf62005-12-30 16:28:01 +000087
88#ifdef SQLITE_OMIT_SHARED_CACHE
89 /*
90 ** The functions queryTableLock(), lockTable() and unlockAllTables()
91 ** manipulate entries in the BtShared.pLock linked list used to store
92 ** shared-cache table level locks. If the library is compiled with the
93 ** shared-cache feature disabled, then there is only ever one user
danielk1977da184232006-01-05 11:34:32 +000094 ** of each BtShared structure and so this locking is not necessary.
95 ** So define the lock related functions as no-ops.
danielk1977aef0bf62005-12-30 16:28:01 +000096 */
97 #define queryTableLock(a,b,c) SQLITE_OK
98 #define lockTable(a,b,c) SQLITE_OK
danielk1977da184232006-01-05 11:34:32 +000099 #define unlockAllTables(a)
drhe53831d2007-08-17 01:14:38 +0000100#endif
danielk1977aef0bf62005-12-30 16:28:01 +0000101
drhe53831d2007-08-17 01:14:38 +0000102#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977da184232006-01-05 11:34:32 +0000103/*
danielk1977aef0bf62005-12-30 16:28:01 +0000104** Query to see if btree handle p may obtain a lock of type eLock
105** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
106** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
danielk1977c87d34d2006-01-06 13:00:28 +0000107** SQLITE_LOCKED if not.
danielk1977aef0bf62005-12-30 16:28:01 +0000108*/
109static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
110 BtShared *pBt = p->pBt;
111 BtLock *pIter;
112
drh1fee73e2007-08-29 04:00:57 +0000113 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000114 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
115 assert( p->db!=0 );
drhd677b3d2007-08-20 22:48:41 +0000116
danielk1977da184232006-01-05 11:34:32 +0000117 /* This is a no-op if the shared-cache is not enabled */
drhe53831d2007-08-17 01:14:38 +0000118 if( !p->sharable ){
danielk1977da184232006-01-05 11:34:32 +0000119 return SQLITE_OK;
120 }
121
danielk1977641b0f42007-12-21 04:47:25 +0000122 /* If some other connection is holding an exclusive lock, the
123 ** requested lock may not be obtained.
124 */
125 if( pBt->pExclusive && pBt->pExclusive!=p ){
126 return SQLITE_LOCKED;
127 }
128
danielk1977da184232006-01-05 11:34:32 +0000129 /* This (along with lockTable()) is where the ReadUncommitted flag is
130 ** dealt with. If the caller is querying for a read-lock and the flag is
131 ** set, it is unconditionally granted - even if there are write-locks
132 ** on the table. If a write-lock is requested, the ReadUncommitted flag
133 ** is not considered.
134 **
135 ** In function lockTable(), if a read-lock is demanded and the
136 ** ReadUncommitted flag is set, no entry is added to the locks list
137 ** (BtShared.pLock).
138 **
139 ** To summarize: If the ReadUncommitted flag is set, then read cursors do
140 ** not create or respect table locks. The locking procedure for a
141 ** write-cursor does not change.
142 */
143 if(
drhe5fe6902007-12-07 18:55:28 +0000144 0==(p->db->flags&SQLITE_ReadUncommitted) ||
danielk1977da184232006-01-05 11:34:32 +0000145 eLock==WRITE_LOCK ||
drh47ded162006-01-06 01:42:58 +0000146 iTab==MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000147 ){
148 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
149 if( pIter->pBtree!=p && pIter->iTable==iTab &&
150 (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
danielk1977c87d34d2006-01-06 13:00:28 +0000151 return SQLITE_LOCKED;
danielk1977da184232006-01-05 11:34:32 +0000152 }
danielk1977aef0bf62005-12-30 16:28:01 +0000153 }
154 }
155 return SQLITE_OK;
156}
drhe53831d2007-08-17 01:14:38 +0000157#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000158
drhe53831d2007-08-17 01:14:38 +0000159#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000160/*
161** Add a lock on the table with root-page iTable to the shared-btree used
162** by Btree handle p. Parameter eLock must be either READ_LOCK or
163** WRITE_LOCK.
164**
165** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
166** SQLITE_NOMEM may also be returned.
167*/
168static int lockTable(Btree *p, Pgno iTable, u8 eLock){
169 BtShared *pBt = p->pBt;
170 BtLock *pLock = 0;
171 BtLock *pIter;
172
drh1fee73e2007-08-29 04:00:57 +0000173 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000174 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
175 assert( p->db!=0 );
drhd677b3d2007-08-20 22:48:41 +0000176
danielk1977da184232006-01-05 11:34:32 +0000177 /* This is a no-op if the shared-cache is not enabled */
drhe53831d2007-08-17 01:14:38 +0000178 if( !p->sharable ){
danielk1977da184232006-01-05 11:34:32 +0000179 return SQLITE_OK;
180 }
181
danielk1977aef0bf62005-12-30 16:28:01 +0000182 assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
183
danielk1977da184232006-01-05 11:34:32 +0000184 /* If the read-uncommitted flag is set and a read-lock is requested,
185 ** return early without adding an entry to the BtShared.pLock list. See
186 ** comment in function queryTableLock() for more info on handling
187 ** the ReadUncommitted flag.
188 */
189 if(
drhe5fe6902007-12-07 18:55:28 +0000190 (p->db->flags&SQLITE_ReadUncommitted) &&
danielk1977da184232006-01-05 11:34:32 +0000191 (eLock==READ_LOCK) &&
drh47ded162006-01-06 01:42:58 +0000192 iTable!=MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000193 ){
194 return SQLITE_OK;
195 }
196
danielk1977aef0bf62005-12-30 16:28:01 +0000197 /* First search the list for an existing lock on this table. */
198 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
199 if( pIter->iTable==iTable && pIter->pBtree==p ){
200 pLock = pIter;
201 break;
202 }
203 }
204
205 /* If the above search did not find a BtLock struct associating Btree p
206 ** with table iTable, allocate one and link it into the list.
207 */
208 if( !pLock ){
drh17435752007-08-16 04:30:38 +0000209 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
danielk1977aef0bf62005-12-30 16:28:01 +0000210 if( !pLock ){
211 return SQLITE_NOMEM;
212 }
213 pLock->iTable = iTable;
214 pLock->pBtree = p;
215 pLock->pNext = pBt->pLock;
216 pBt->pLock = pLock;
217 }
218
219 /* Set the BtLock.eLock variable to the maximum of the current lock
220 ** and the requested lock. This means if a write-lock was already held
221 ** and a read-lock requested, we don't incorrectly downgrade the lock.
222 */
223 assert( WRITE_LOCK>READ_LOCK );
danielk19775118b912005-12-30 16:31:53 +0000224 if( eLock>pLock->eLock ){
225 pLock->eLock = eLock;
226 }
danielk1977aef0bf62005-12-30 16:28:01 +0000227
228 return SQLITE_OK;
229}
drhe53831d2007-08-17 01:14:38 +0000230#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000231
drhe53831d2007-08-17 01:14:38 +0000232#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000233/*
234** Release all the table locks (locks obtained via calls to the lockTable()
235** procedure) held by Btree handle p.
236*/
237static void unlockAllTables(Btree *p){
danielk1977641b0f42007-12-21 04:47:25 +0000238 BtShared *pBt = p->pBt;
239 BtLock **ppIter = &pBt->pLock;
danielk1977da184232006-01-05 11:34:32 +0000240
drh1fee73e2007-08-29 04:00:57 +0000241 assert( sqlite3BtreeHoldsMutex(p) );
drhe53831d2007-08-17 01:14:38 +0000242 assert( p->sharable || 0==*ppIter );
danielk1977da184232006-01-05 11:34:32 +0000243
danielk1977aef0bf62005-12-30 16:28:01 +0000244 while( *ppIter ){
245 BtLock *pLock = *ppIter;
danielk1977641b0f42007-12-21 04:47:25 +0000246 assert( pBt->pExclusive==0 || pBt->pExclusive==pLock->pBtree );
danielk1977aef0bf62005-12-30 16:28:01 +0000247 if( pLock->pBtree==p ){
248 *ppIter = pLock->pNext;
drh17435752007-08-16 04:30:38 +0000249 sqlite3_free(pLock);
danielk1977aef0bf62005-12-30 16:28:01 +0000250 }else{
251 ppIter = &pLock->pNext;
252 }
253 }
danielk1977641b0f42007-12-21 04:47:25 +0000254
255 if( pBt->pExclusive==p ){
256 pBt->pExclusive = 0;
257 }
danielk1977aef0bf62005-12-30 16:28:01 +0000258}
259#endif /* SQLITE_OMIT_SHARED_CACHE */
260
drh980b1a72006-08-16 16:42:48 +0000261static void releasePage(MemPage *pPage); /* Forward reference */
262
drh1fee73e2007-08-29 04:00:57 +0000263/*
264** Verify that the cursor holds a mutex on the BtShared
265*/
266#ifndef NDEBUG
267static int cursorHoldsMutex(BtCursor *p){
drhff0587c2007-08-29 17:43:19 +0000268 return sqlite3_mutex_held(p->pBt->mutex);
drh1fee73e2007-08-29 04:00:57 +0000269}
270#endif
271
272
danielk197792d4d7a2007-05-04 12:05:56 +0000273#ifndef SQLITE_OMIT_INCRBLOB
274/*
275** Invalidate the overflow page-list cache for cursor pCur, if any.
276*/
277static void invalidateOverflowCache(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000278 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000279 sqlite3_free(pCur->aOverflow);
danielk197792d4d7a2007-05-04 12:05:56 +0000280 pCur->aOverflow = 0;
281}
282
283/*
284** Invalidate the overflow page-list cache for all cursors opened
285** on the shared btree structure pBt.
286*/
287static void invalidateAllOverflowCache(BtShared *pBt){
288 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000289 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +0000290 for(p=pBt->pCursor; p; p=p->pNext){
291 invalidateOverflowCache(p);
292 }
293}
294#else
295 #define invalidateOverflowCache(x)
296 #define invalidateAllOverflowCache(x)
297#endif
298
drh980b1a72006-08-16 16:42:48 +0000299/*
300** Save the current cursor position in the variables BtCursor.nKey
301** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
302*/
303static int saveCursorPosition(BtCursor *pCur){
304 int rc;
305
306 assert( CURSOR_VALID==pCur->eState );
307 assert( 0==pCur->pKey );
drh1fee73e2007-08-29 04:00:57 +0000308 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000309
310 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
311
312 /* If this is an intKey table, then the above call to BtreeKeySize()
313 ** stores the integer key in pCur->nKey. In this case this value is
314 ** all that is required. Otherwise, if pCur is not open on an intKey
315 ** table, then malloc space for and store the pCur->nKey bytes of key
316 ** data.
317 */
danielk197771d5d2c2008-09-29 11:49:47 +0000318 if( rc==SQLITE_OK && 0==pCur->apPage[0]->intKey){
drhe5ae5732008-06-15 02:51:47 +0000319 void *pKey = sqlite3Malloc(pCur->nKey);
drh980b1a72006-08-16 16:42:48 +0000320 if( pKey ){
321 rc = sqlite3BtreeKey(pCur, 0, pCur->nKey, pKey);
322 if( rc==SQLITE_OK ){
323 pCur->pKey = pKey;
324 }else{
drh17435752007-08-16 04:30:38 +0000325 sqlite3_free(pKey);
drh980b1a72006-08-16 16:42:48 +0000326 }
327 }else{
328 rc = SQLITE_NOMEM;
329 }
330 }
danielk197771d5d2c2008-09-29 11:49:47 +0000331 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
drh980b1a72006-08-16 16:42:48 +0000332
333 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +0000334 int i;
335 for(i=0; i<=pCur->iPage; i++){
336 releasePage(pCur->apPage[i]);
337 pCur->apPage[i] = 0;
338 }
339 pCur->iPage = -1;
drh980b1a72006-08-16 16:42:48 +0000340 pCur->eState = CURSOR_REQUIRESEEK;
341 }
342
danielk197792d4d7a2007-05-04 12:05:56 +0000343 invalidateOverflowCache(pCur);
drh980b1a72006-08-16 16:42:48 +0000344 return rc;
345}
346
347/*
348** Save the positions of all cursors except pExcept open on the table
349** with root-page iRoot. Usually, this is called just before cursor
350** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
351*/
352static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
353 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000354 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +0000355 assert( pExcept==0 || pExcept->pBt==pBt );
drh980b1a72006-08-16 16:42:48 +0000356 for(p=pBt->pCursor; p; p=p->pNext){
357 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
358 p->eState==CURSOR_VALID ){
359 int rc = saveCursorPosition(p);
360 if( SQLITE_OK!=rc ){
361 return rc;
362 }
363 }
364 }
365 return SQLITE_OK;
366}
367
368/*
drhbf700f32007-03-31 02:36:44 +0000369** Clear the current cursor position.
370*/
danielk1977be51a652008-10-08 17:58:48 +0000371void sqlite3BtreeClearCursor(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000372 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000373 sqlite3_free(pCur->pKey);
drhbf700f32007-03-31 02:36:44 +0000374 pCur->pKey = 0;
375 pCur->eState = CURSOR_INVALID;
376}
377
378/*
drh980b1a72006-08-16 16:42:48 +0000379** Restore the cursor to the position it was in (or as close to as possible)
380** when saveCursorPosition() was called. Note that this call deletes the
381** saved position info stored by saveCursorPosition(), so there can be
drha3460582008-07-11 21:02:53 +0000382** at most one effective restoreCursorPosition() call after each
drh980b1a72006-08-16 16:42:48 +0000383** saveCursorPosition().
drh980b1a72006-08-16 16:42:48 +0000384*/
drha3460582008-07-11 21:02:53 +0000385int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +0000386 int rc;
drh1fee73e2007-08-29 04:00:57 +0000387 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +0000388 assert( pCur->eState>=CURSOR_REQUIRESEEK );
389 if( pCur->eState==CURSOR_FAULT ){
390 return pCur->skip;
391 }
drh980b1a72006-08-16 16:42:48 +0000392 pCur->eState = CURSOR_INVALID;
drhe63d9992008-08-13 19:11:48 +0000393 rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skip);
drh980b1a72006-08-16 16:42:48 +0000394 if( rc==SQLITE_OK ){
drh17435752007-08-16 04:30:38 +0000395 sqlite3_free(pCur->pKey);
drh980b1a72006-08-16 16:42:48 +0000396 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +0000397 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drh980b1a72006-08-16 16:42:48 +0000398 }
399 return rc;
400}
401
drha3460582008-07-11 21:02:53 +0000402#define restoreCursorPosition(p) \
drhfb982642007-08-30 01:19:59 +0000403 (p->eState>=CURSOR_REQUIRESEEK ? \
drha3460582008-07-11 21:02:53 +0000404 sqlite3BtreeRestoreCursorPosition(p) : \
drh16a9b832007-05-05 18:39:25 +0000405 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +0000406
drha3460582008-07-11 21:02:53 +0000407/*
408** Determine whether or not a cursor has moved from the position it
drhdfe88ec2008-11-03 20:55:06 +0000409** was last placed at. Cursors can move when the row they are pointing
drha3460582008-07-11 21:02:53 +0000410** at is deleted out from under them.
411**
412** This routine returns an error code if something goes wrong. The
413** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
414*/
415int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
416 int rc;
417
418 rc = restoreCursorPosition(pCur);
419 if( rc ){
420 *pHasMoved = 1;
421 return rc;
422 }
423 if( pCur->eState!=CURSOR_VALID || pCur->skip!=0 ){
424 *pHasMoved = 1;
425 }else{
426 *pHasMoved = 0;
427 }
428 return SQLITE_OK;
429}
430
danielk1977599fcba2004-11-08 07:13:13 +0000431#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000432/*
drha3152892007-05-05 11:48:52 +0000433** Given a page number of a regular database page, return the page
434** number for the pointer-map page that contains the entry for the
435** input page number.
danielk1977afcdd022004-10-31 16:25:42 +0000436*/
danielk1977266664d2006-02-10 08:24:21 +0000437static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
drhd677b3d2007-08-20 22:48:41 +0000438 int nPagesPerMapPage, iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +0000439 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000440 nPagesPerMapPage = (pBt->usableSize/5)+1;
441 iPtrMap = (pgno-2)/nPagesPerMapPage;
442 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +0000443 if( ret==PENDING_BYTE_PAGE(pBt) ){
444 ret++;
445 }
446 return ret;
447}
danielk1977a19df672004-11-03 11:37:07 +0000448
danielk1977afcdd022004-10-31 16:25:42 +0000449/*
danielk1977afcdd022004-10-31 16:25:42 +0000450** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000451**
452** This routine updates the pointer map entry for page number 'key'
453** so that it maps to type 'eType' and parent page number 'pgno'.
454** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000455*/
danielk1977aef0bf62005-12-30 16:28:01 +0000456static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
danielk19773b8a05f2007-03-19 17:44:26 +0000457 DbPage *pDbPage; /* The pointer map page */
458 u8 *pPtrmap; /* The pointer map data */
459 Pgno iPtrmap; /* The pointer map page number */
460 int offset; /* Offset in pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000461 int rc;
462
drh1fee73e2007-08-29 04:00:57 +0000463 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977266664d2006-02-10 08:24:21 +0000464 /* The master-journal page number must never be used as a pointer map page */
465 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
466
danielk1977ac11ee62005-01-15 12:45:51 +0000467 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000468 if( key==0 ){
drh49285702005-09-17 15:20:26 +0000469 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000470 }
danielk1977266664d2006-02-10 08:24:21 +0000471 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000472 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977687566d2004-11-02 12:56:41 +0000473 if( rc!=SQLITE_OK ){
danielk1977afcdd022004-10-31 16:25:42 +0000474 return rc;
475 }
danielk19778c666b12008-07-18 09:34:57 +0000476 offset = PTRMAP_PTROFFSET(iPtrmap, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000477 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000478
drh615ae552005-01-16 23:21:00 +0000479 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
480 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
danielk19773b8a05f2007-03-19 17:44:26 +0000481 rc = sqlite3PagerWrite(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000482 if( rc==SQLITE_OK ){
483 pPtrmap[offset] = eType;
484 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000485 }
danielk1977afcdd022004-10-31 16:25:42 +0000486 }
487
danielk19773b8a05f2007-03-19 17:44:26 +0000488 sqlite3PagerUnref(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000489 return rc;
danielk1977afcdd022004-10-31 16:25:42 +0000490}
491
492/*
493** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000494**
495** This routine retrieves the pointer map entry for page 'key', writing
496** the type and parent page number to *pEType and *pPgno respectively.
497** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000498*/
danielk1977aef0bf62005-12-30 16:28:01 +0000499static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +0000500 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000501 int iPtrmap; /* Pointer map page index */
502 u8 *pPtrmap; /* Pointer map page data */
503 int offset; /* Offset of entry in pointer map */
504 int rc;
505
drh1fee73e2007-08-29 04:00:57 +0000506 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000507
danielk1977266664d2006-02-10 08:24:21 +0000508 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000509 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000510 if( rc!=0 ){
511 return rc;
512 }
danielk19773b8a05f2007-03-19 17:44:26 +0000513 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000514
danielk19778c666b12008-07-18 09:34:57 +0000515 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drh43617e92006-03-06 20:55:46 +0000516 assert( pEType!=0 );
517 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +0000518 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000519
danielk19773b8a05f2007-03-19 17:44:26 +0000520 sqlite3PagerUnref(pDbPage);
drh49285702005-09-17 15:20:26 +0000521 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000522 return SQLITE_OK;
523}
524
danielk197785d90ca2008-07-19 14:25:15 +0000525#else /* if defined SQLITE_OMIT_AUTOVACUUM */
526 #define ptrmapPut(w,x,y,z) SQLITE_OK
527 #define ptrmapGet(w,x,y,z) SQLITE_OK
528 #define ptrmapPutOvfl(y,z) SQLITE_OK
529#endif
danielk1977afcdd022004-10-31 16:25:42 +0000530
drh0d316a42002-08-11 20:10:47 +0000531/*
drh271efa52004-05-30 19:19:05 +0000532** Given a btree page and a cell index (0 means the first cell on
533** the page, 1 means the second cell, and so forth) return a pointer
534** to the cell content.
535**
536** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000537*/
drh1688c862008-07-18 02:44:17 +0000538#define findCell(P,I) \
539 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
drh43605152004-05-29 21:46:49 +0000540
541/*
drh93a960a2008-07-10 00:32:42 +0000542** This a more complex version of findCell() that works for
drh43605152004-05-29 21:46:49 +0000543** pages that do contain overflow cells. See insert
544*/
545static u8 *findOverflowCell(MemPage *pPage, int iCell){
546 int i;
drh1fee73e2007-08-29 04:00:57 +0000547 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +0000548 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000549 int k;
550 struct _OvflCell *pOvfl;
551 pOvfl = &pPage->aOvfl[i];
552 k = pOvfl->idx;
553 if( k<=iCell ){
554 if( k==iCell ){
555 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000556 }
557 iCell--;
558 }
559 }
danielk19771cc5ed82007-05-16 17:28:43 +0000560 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000561}
562
563/*
564** Parse a cell content block and fill in the CellInfo structure. There
drh16a9b832007-05-05 18:39:25 +0000565** are two versions of this function. sqlite3BtreeParseCell() takes a
566** cell index as the second argument and sqlite3BtreeParseCellPtr()
567** takes a pointer to the body of the cell as its second argument.
danielk19771cc5ed82007-05-16 17:28:43 +0000568**
569** Within this file, the parseCell() macro can be called instead of
570** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
drh43605152004-05-29 21:46:49 +0000571*/
drh16a9b832007-05-05 18:39:25 +0000572void sqlite3BtreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000573 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000574 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000575 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000576){
drh271efa52004-05-30 19:19:05 +0000577 int n; /* Number bytes in cell content header */
578 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000579
drh1fee73e2007-08-29 04:00:57 +0000580 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000581
drh43605152004-05-29 21:46:49 +0000582 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000583 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000584 n = pPage->childPtrSize;
585 assert( n==4-4*pPage->leaf );
drh504b6982006-01-22 21:52:56 +0000586 if( pPage->intKey ){
drh79df1f42008-07-18 00:57:33 +0000587 if( pPage->hasData ){
588 n += getVarint32(&pCell[n], nPayload);
589 }else{
590 nPayload = 0;
591 }
592 n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
593 pInfo->nData = nPayload;
drh504b6982006-01-22 21:52:56 +0000594 }else{
drh79df1f42008-07-18 00:57:33 +0000595 pInfo->nData = 0;
596 n += getVarint32(&pCell[n], nPayload);
597 pInfo->nKey = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000598 }
drh72365832007-03-06 15:53:44 +0000599 pInfo->nPayload = nPayload;
drh504b6982006-01-22 21:52:56 +0000600 pInfo->nHeader = n;
drh79df1f42008-07-18 00:57:33 +0000601 if( likely(nPayload<=pPage->maxLocal) ){
drh271efa52004-05-30 19:19:05 +0000602 /* This is the (easy) common case where the entire payload fits
603 ** on the local page. No overflow is required.
604 */
605 int nSize; /* Total size of cell content in bytes */
drh79df1f42008-07-18 00:57:33 +0000606 nSize = nPayload + n;
drh6f11bef2004-05-13 01:12:56 +0000607 pInfo->nLocal = nPayload;
608 pInfo->iOverflow = 0;
drh79df1f42008-07-18 00:57:33 +0000609 if( (nSize & ~3)==0 ){
drh271efa52004-05-30 19:19:05 +0000610 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000611 }
drh271efa52004-05-30 19:19:05 +0000612 pInfo->nSize = nSize;
drh6f11bef2004-05-13 01:12:56 +0000613 }else{
drh271efa52004-05-30 19:19:05 +0000614 /* If the payload will not fit completely on the local page, we have
615 ** to decide how much to store locally and how much to spill onto
616 ** overflow pages. The strategy is to minimize the amount of unused
617 ** space on overflow pages while keeping the amount of local storage
618 ** in between minLocal and maxLocal.
619 **
620 ** Warning: changing the way overflow payload is distributed in any
621 ** way will result in an incompatible file format.
622 */
623 int minLocal; /* Minimum amount of payload held locally */
624 int maxLocal; /* Maximum amount of payload held locally */
625 int surplus; /* Overflow payload available for local storage */
626
627 minLocal = pPage->minLocal;
628 maxLocal = pPage->maxLocal;
629 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000630 if( surplus <= maxLocal ){
631 pInfo->nLocal = surplus;
632 }else{
633 pInfo->nLocal = minLocal;
634 }
635 pInfo->iOverflow = pInfo->nLocal + n;
636 pInfo->nSize = pInfo->iOverflow + 4;
637 }
drh3aac2dd2004-04-26 14:10:20 +0000638}
danielk19771cc5ed82007-05-16 17:28:43 +0000639#define parseCell(pPage, iCell, pInfo) \
640 sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
drh16a9b832007-05-05 18:39:25 +0000641void sqlite3BtreeParseCell(
drh43605152004-05-29 21:46:49 +0000642 MemPage *pPage, /* Page containing the cell */
643 int iCell, /* The cell index. First cell is 0 */
644 CellInfo *pInfo /* Fill in this structure */
645){
danielk19771cc5ed82007-05-16 17:28:43 +0000646 parseCell(pPage, iCell, pInfo);
drh43605152004-05-29 21:46:49 +0000647}
drh3aac2dd2004-04-26 14:10:20 +0000648
649/*
drh43605152004-05-29 21:46:49 +0000650** Compute the total number of bytes that a Cell needs in the cell
651** data area of the btree-page. The return number includes the cell
652** data header and the local payload, but not any overflow page or
653** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000654*/
danielk1977bc6ada42004-06-30 08:20:16 +0000655#ifndef NDEBUG
drha9121e42008-02-19 14:59:35 +0000656static u16 cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000657 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000658 sqlite3BtreeParseCell(pPage, iCell, &info);
drh43605152004-05-29 21:46:49 +0000659 return info.nSize;
660}
danielk1977bc6ada42004-06-30 08:20:16 +0000661#endif
drha9121e42008-02-19 14:59:35 +0000662static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
drh43605152004-05-29 21:46:49 +0000663 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000664 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000665 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000666}
667
danielk197779a40da2005-01-16 08:00:01 +0000668#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +0000669/*
danielk197726836652005-01-17 01:33:13 +0000670** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +0000671** to an overflow page, insert an entry into the pointer-map
672** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +0000673*/
danielk197726836652005-01-17 01:33:13 +0000674static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
drhfa67c3c2008-07-11 02:21:40 +0000675 CellInfo info;
676 assert( pCell!=0 );
677 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
678 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
679 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
680 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
681 return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +0000682 }
danielk197779a40da2005-01-16 08:00:01 +0000683 return SQLITE_OK;
danielk1977ac11ee62005-01-15 12:45:51 +0000684}
danielk197726836652005-01-17 01:33:13 +0000685/*
686** If the cell with index iCell on page pPage contains a pointer
687** to an overflow page, insert an entry into the pointer-map
688** for the overflow page.
689*/
690static int ptrmapPutOvfl(MemPage *pPage, int iCell){
691 u8 *pCell;
drh1fee73e2007-08-29 04:00:57 +0000692 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197726836652005-01-17 01:33:13 +0000693 pCell = findOverflowCell(pPage, iCell);
694 return ptrmapPutOvflPtr(pPage, pCell);
695}
danielk197779a40da2005-01-16 08:00:01 +0000696#endif
697
danielk1977ac11ee62005-01-15 12:45:51 +0000698
drhda200cc2004-05-09 11:51:38 +0000699/*
drh72f82862001-05-24 21:06:34 +0000700** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +0000701** end of the page and all free space is collected into one
702** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +0000703** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +0000704*/
shane0af3f892008-11-12 04:55:34 +0000705static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000706 int i; /* Loop counter */
707 int pc; /* Address of a i-th cell */
708 int addr; /* Offset of first byte after cell pointer array */
709 int hdr; /* Offset to the page header */
710 int size; /* Size of a cell */
711 int usableSize; /* Number of usable bytes on a page */
712 int cellOffset; /* Offset to the cell pointer array */
drh281b21d2008-08-22 12:57:08 +0000713 int cbrk; /* Offset to the cell content area */
drh43605152004-05-29 21:46:49 +0000714 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +0000715 unsigned char *data; /* The page data */
716 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +0000717
danielk19773b8a05f2007-03-19 17:44:26 +0000718 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000719 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +0000720 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000721 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +0000722 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh26b79942007-11-28 16:19:56 +0000723 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
drh43605152004-05-29 21:46:49 +0000724 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +0000725 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000726 cellOffset = pPage->cellOffset;
727 nCell = pPage->nCell;
728 assert( nCell==get2byte(&data[hdr+3]) );
729 usableSize = pPage->pBt->usableSize;
drh281b21d2008-08-22 12:57:08 +0000730 cbrk = get2byte(&data[hdr+5]);
731 memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
732 cbrk = usableSize;
drh43605152004-05-29 21:46:49 +0000733 for(i=0; i<nCell; i++){
734 u8 *pAddr; /* The i-th cell pointer */
735 pAddr = &data[cellOffset + i*2];
736 pc = get2byte(pAddr);
shanedcc50b72008-11-13 18:29:50 +0000737 if( pc>=usableSize ){
shane0af3f892008-11-12 04:55:34 +0000738 return SQLITE_CORRUPT_BKPT;
739 }
drh43605152004-05-29 21:46:49 +0000740 size = cellSizePtr(pPage, &temp[pc]);
drh281b21d2008-08-22 12:57:08 +0000741 cbrk -= size;
danielk19770d065412008-11-12 18:21:36 +0000742 if( cbrk<cellOffset+2*nCell || pc+size>usableSize ){
shane0af3f892008-11-12 04:55:34 +0000743 return SQLITE_CORRUPT_BKPT;
744 }
danielk19770d065412008-11-12 18:21:36 +0000745 assert( cbrk+size<=usableSize && cbrk>=0 );
drh281b21d2008-08-22 12:57:08 +0000746 memcpy(&data[cbrk], &temp[pc], size);
747 put2byte(pAddr, cbrk);
drh2af926b2001-05-15 00:39:25 +0000748 }
drh281b21d2008-08-22 12:57:08 +0000749 assert( cbrk>=cellOffset+2*nCell );
750 put2byte(&data[hdr+5], cbrk);
drh43605152004-05-29 21:46:49 +0000751 data[hdr+1] = 0;
752 data[hdr+2] = 0;
753 data[hdr+7] = 0;
754 addr = cellOffset+2*nCell;
drh281b21d2008-08-22 12:57:08 +0000755 memset(&data[addr], 0, cbrk-addr);
danielk1977360e6342008-11-12 08:49:51 +0000756 if( cbrk-addr!=pPage->nFree ){
757 return SQLITE_CORRUPT_BKPT;
758 }
shane0af3f892008-11-12 04:55:34 +0000759 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +0000760}
761
drha059ad02001-04-17 20:09:11 +0000762/*
drh43605152004-05-29 21:46:49 +0000763** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +0000764**
drh9e572e62004-04-23 23:43:10 +0000765** Return the index into pPage->aData[] of the first byte of
drhfa67c3c2008-07-11 02:21:40 +0000766** the new allocation. The caller guarantees that there is enough
767** space. This routine will never fail.
drh2af926b2001-05-15 00:39:25 +0000768**
drh72f82862001-05-24 21:06:34 +0000769** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000770** nBytes of contiguous free space, then this routine automatically
771** calls defragementPage() to consolidate all free space before
772** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000773*/
drh9e572e62004-04-23 23:43:10 +0000774static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +0000775 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +0000776 int size;
drh24cd67e2004-05-10 16:18:47 +0000777 int nFrag;
drh43605152004-05-29 21:46:49 +0000778 int top;
779 int nCell;
780 int cellOffset;
drh9e572e62004-04-23 23:43:10 +0000781 unsigned char *data;
drh43605152004-05-29 21:46:49 +0000782
drh9e572e62004-04-23 23:43:10 +0000783 data = pPage->aData;
danielk19773b8a05f2007-03-19 17:44:26 +0000784 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000785 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +0000786 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa67c3c2008-07-11 02:21:40 +0000787 assert( nByte>=0 ); /* Minimum cell size is 4 */
788 assert( pPage->nFree>=nByte );
789 assert( pPage->nOverflow==0 );
drh43605152004-05-29 21:46:49 +0000790 pPage->nFree -= nByte;
drh9e572e62004-04-23 23:43:10 +0000791 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000792
793 nFrag = data[hdr+7];
794 if( nFrag<60 ){
795 /* Search the freelist looking for a slot big enough to satisfy the
796 ** space request. */
797 addr = hdr+1;
798 while( (pc = get2byte(&data[addr]))>0 ){
799 size = get2byte(&data[pc+2]);
800 if( size>=nByte ){
801 if( size<nByte+4 ){
802 memcpy(&data[addr], &data[pc], 2);
803 data[hdr+7] = nFrag + size - nByte;
804 return pc;
805 }else{
806 put2byte(&data[pc+2], size-nByte);
807 return pc + size - nByte;
808 }
809 }
810 addr = pc;
drh9e572e62004-04-23 23:43:10 +0000811 }
812 }
drh43605152004-05-29 21:46:49 +0000813
814 /* Allocate memory from the gap in between the cell pointer array
815 ** and the cell content area.
816 */
817 top = get2byte(&data[hdr+5]);
818 nCell = get2byte(&data[hdr+3]);
819 cellOffset = pPage->cellOffset;
820 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
danielk1977474b7cc2008-07-09 11:49:46 +0000821 defragmentPage(pPage);
drh43605152004-05-29 21:46:49 +0000822 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +0000823 }
drh43605152004-05-29 21:46:49 +0000824 top -= nByte;
825 assert( cellOffset + 2*nCell <= top );
826 put2byte(&data[hdr+5], top);
827 return top;
drh7e3b0a02001-04-28 16:52:40 +0000828}
829
830/*
drh9e572e62004-04-23 23:43:10 +0000831** Return a section of the pPage->aData to the freelist.
832** The first byte of the new free block is pPage->aDisk[start]
833** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +0000834**
835** Most of the effort here is involved in coalesing adjacent
836** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000837*/
shanedcc50b72008-11-13 18:29:50 +0000838static int freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +0000839 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +0000840 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +0000841
drh9e572e62004-04-23 23:43:10 +0000842 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +0000843 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000844 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +0000845 assert( (start + size)<=pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +0000846 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh34004ce2008-07-11 16:15:17 +0000847 assert( size>=0 ); /* Minimum cell size is 4 */
drh9e572e62004-04-23 23:43:10 +0000848
drhfcce93f2006-02-22 03:08:32 +0000849#ifdef SQLITE_SECURE_DELETE
850 /* Overwrite deleted information with zeros when the SECURE_DELETE
851 ** option is enabled at compile-time */
852 memset(&data[start], 0, size);
853#endif
854
drh9e572e62004-04-23 23:43:10 +0000855 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +0000856 hdr = pPage->hdrOffset;
857 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +0000858 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +0000859 assert( pbegin<=pPage->pBt->usableSize-4 );
shanedcc50b72008-11-13 18:29:50 +0000860 if( pbegin<=addr ) {
861 return SQLITE_CORRUPT_BKPT;
862 }
drh3aac2dd2004-04-26 14:10:20 +0000863 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +0000864 }
shanedcc50b72008-11-13 18:29:50 +0000865 if ( pbegin>pPage->pBt->usableSize-4 ) {
866 return SQLITE_CORRUPT_BKPT;
867 }
drh3aac2dd2004-04-26 14:10:20 +0000868 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +0000869 put2byte(&data[addr], start);
870 put2byte(&data[start], pbegin);
871 put2byte(&data[start+2], size);
drh2af926b2001-05-15 00:39:25 +0000872 pPage->nFree += size;
drh9e572e62004-04-23 23:43:10 +0000873
874 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +0000875 addr = pPage->hdrOffset + 1;
876 while( (pbegin = get2byte(&data[addr]))>0 ){
drh9e572e62004-04-23 23:43:10 +0000877 int pnext, psize;
drh3aac2dd2004-04-26 14:10:20 +0000878 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +0000879 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +0000880 pnext = get2byte(&data[pbegin]);
881 psize = get2byte(&data[pbegin+2]);
882 if( pbegin + psize + 3 >= pnext && pnext>0 ){
883 int frag = pnext - (pbegin+psize);
shanedcc50b72008-11-13 18:29:50 +0000884 if( (frag<0) || (frag>data[pPage->hdrOffset+7]) ){
885 return SQLITE_CORRUPT_BKPT;
886 }
drh43605152004-05-29 21:46:49 +0000887 data[pPage->hdrOffset+7] -= frag;
drh9e572e62004-04-23 23:43:10 +0000888 put2byte(&data[pbegin], get2byte(&data[pnext]));
889 put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
890 }else{
drh3aac2dd2004-04-26 14:10:20 +0000891 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +0000892 }
893 }
drh7e3b0a02001-04-28 16:52:40 +0000894
drh43605152004-05-29 21:46:49 +0000895 /* If the cell content area begins with a freeblock, remove it. */
896 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
897 int top;
898 pbegin = get2byte(&data[hdr+1]);
899 memcpy(&data[hdr+1], &data[pbegin], 2);
900 top = get2byte(&data[hdr+5]);
901 put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
drh4b70f112004-05-02 21:12:19 +0000902 }
shanedcc50b72008-11-13 18:29:50 +0000903 return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +0000904}
905
906/*
drh271efa52004-05-30 19:19:05 +0000907** Decode the flags byte (the first byte of the header) for a page
908** and initialize fields of the MemPage structure accordingly.
drh44845222008-07-17 18:39:57 +0000909**
910** Only the following combinations are supported. Anything different
911** indicates a corrupt database files:
912**
913** PTF_ZERODATA
914** PTF_ZERODATA | PTF_LEAF
915** PTF_LEAFDATA | PTF_INTKEY
916** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
drh271efa52004-05-30 19:19:05 +0000917*/
drh44845222008-07-17 18:39:57 +0000918static int decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +0000919 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +0000920
921 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +0000922 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh44845222008-07-17 18:39:57 +0000923 pPage->leaf = flagByte>>3; assert( PTF_LEAF == 1<<3 );
924 flagByte &= ~PTF_LEAF;
925 pPage->childPtrSize = 4-4*pPage->leaf;
drh271efa52004-05-30 19:19:05 +0000926 pBt = pPage->pBt;
drh44845222008-07-17 18:39:57 +0000927 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
928 pPage->intKey = 1;
929 pPage->hasData = pPage->leaf;
drh271efa52004-05-30 19:19:05 +0000930 pPage->maxLocal = pBt->maxLeaf;
931 pPage->minLocal = pBt->minLeaf;
drh44845222008-07-17 18:39:57 +0000932 }else if( flagByte==PTF_ZERODATA ){
933 pPage->intKey = 0;
934 pPage->hasData = 0;
drh271efa52004-05-30 19:19:05 +0000935 pPage->maxLocal = pBt->maxLocal;
936 pPage->minLocal = pBt->minLocal;
drh44845222008-07-17 18:39:57 +0000937 }else{
938 return SQLITE_CORRUPT_BKPT;
drh271efa52004-05-30 19:19:05 +0000939 }
drh44845222008-07-17 18:39:57 +0000940 return SQLITE_OK;
drh271efa52004-05-30 19:19:05 +0000941}
942
943/*
drh7e3b0a02001-04-28 16:52:40 +0000944** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000945**
946** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +0000947** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +0000948** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
949** guarantee that the page is well-formed. It only shows that
950** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000951*/
danielk197771d5d2c2008-09-29 11:49:47 +0000952int sqlite3BtreeInitPage(MemPage *pPage){
drh2af926b2001-05-15 00:39:25 +0000953
danielk197771d5d2c2008-09-29 11:49:47 +0000954 assert( pPage->pBt!=0 );
955 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +0000956 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +0000957 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
958 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +0000959
960 if( !pPage->isInit ){
961 int pc; /* Address of a freeblock within pPage->aData[] */
962 int hdr; /* Offset to beginning of page header */
963 u8 *data; /* Equal to pPage->aData */
964 BtShared *pBt; /* The main btree structure */
965 int usableSize; /* Amount of usable space on each page */
966 int cellOffset; /* Offset from start of page to first cell pointer */
967 int nFree; /* Number of unused bytes on the page */
968 int top; /* First byte of the cell content area */
969
970 pBt = pPage->pBt;
971
danielk1977eaa06f62008-09-18 17:34:44 +0000972 hdr = pPage->hdrOffset;
973 data = pPage->aData;
974 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
975 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
976 pPage->maskPage = pBt->pageSize - 1;
977 pPage->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +0000978 usableSize = pBt->usableSize;
979 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
980 top = get2byte(&data[hdr+5]);
981 pPage->nCell = get2byte(&data[hdr+3]);
982 if( pPage->nCell>MX_CELL(pBt) ){
983 /* To many cells for a single page. The page must be corrupt */
984 return SQLITE_CORRUPT_BKPT;
985 }
danielk1977eaa06f62008-09-18 17:34:44 +0000986
987 /* Compute the total free space on the page */
988 pc = get2byte(&data[hdr+1]);
989 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
990 while( pc>0 ){
991 int next, size;
992 if( pc>usableSize-4 ){
993 /* Free block is off the page */
994 return SQLITE_CORRUPT_BKPT;
995 }
996 next = get2byte(&data[pc]);
997 size = get2byte(&data[pc+2]);
998 if( next>0 && next<=pc+size+3 ){
999 /* Free blocks must be in accending order */
1000 return SQLITE_CORRUPT_BKPT;
1001 }
1002 nFree += size;
1003 pc = next;
1004 }
1005 pPage->nFree = nFree;
1006 if( nFree>=usableSize ){
1007 /* Free space cannot exceed total page size */
drh49285702005-09-17 15:20:26 +00001008 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001009 }
drh9e572e62004-04-23 23:43:10 +00001010
drh1688c862008-07-18 02:44:17 +00001011#if 0
1012 /* Check that all the offsets in the cell offset array are within range.
1013 **
1014 ** Omitting this consistency check and using the pPage->maskPage mask
1015 ** to prevent overrunning the page buffer in findCell() results in a
1016 ** 2.5% performance gain.
1017 */
1018 {
1019 u8 *pOff; /* Iterator used to check all cell offsets are in range */
1020 u8 *pEnd; /* Pointer to end of cell offset array */
1021 u8 mask; /* Mask of bits that must be zero in MSB of cell offsets */
1022 mask = ~(((u8)(pBt->pageSize>>8))-1);
1023 pEnd = &data[cellOffset + pPage->nCell*2];
1024 for(pOff=&data[cellOffset]; pOff!=pEnd && !((*pOff)&mask); pOff+=2);
1025 if( pOff!=pEnd ){
1026 return SQLITE_CORRUPT_BKPT;
1027 }
danielk1977e16535f2008-06-11 18:15:29 +00001028 }
drh1688c862008-07-18 02:44:17 +00001029#endif
danielk1977e16535f2008-06-11 18:15:29 +00001030
danielk197771d5d2c2008-09-29 11:49:47 +00001031 pPage->isInit = 1;
1032 }
drh9e572e62004-04-23 23:43:10 +00001033 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001034}
1035
1036/*
drh8b2f49b2001-06-08 00:21:52 +00001037** Set up a raw page so that it looks like a database page holding
1038** no entries.
drhbd03cae2001-06-02 02:40:57 +00001039*/
drh9e572e62004-04-23 23:43:10 +00001040static void zeroPage(MemPage *pPage, int flags){
1041 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001042 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00001043 int hdr = pPage->hdrOffset;
drh9e572e62004-04-23 23:43:10 +00001044 int first;
1045
danielk19773b8a05f2007-03-19 17:44:26 +00001046 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drhbf4bca52007-09-06 22:19:14 +00001047 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1048 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +00001049 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00001050 assert( sqlite3_mutex_held(pBt->mutex) );
drh1af4a6e2008-07-18 03:32:51 +00001051 /*memset(&data[hdr], 0, pBt->usableSize - hdr);*/
drh9e572e62004-04-23 23:43:10 +00001052 data[hdr] = flags;
drh43605152004-05-29 21:46:49 +00001053 first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
1054 memset(&data[hdr+1], 0, 4);
1055 data[hdr+7] = 0;
1056 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +00001057 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +00001058 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +00001059 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +00001060 pPage->cellOffset = first;
1061 pPage->nOverflow = 0;
drh1688c862008-07-18 02:44:17 +00001062 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
1063 pPage->maskPage = pBt->pageSize - 1;
drh43605152004-05-29 21:46:49 +00001064 pPage->nCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001065 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00001066}
1067
drh897a8202008-09-18 01:08:15 +00001068
1069/*
1070** Convert a DbPage obtained from the pager into a MemPage used by
1071** the btree layer.
1072*/
1073static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
1074 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
1075 pPage->aData = sqlite3PagerGetData(pDbPage);
1076 pPage->pDbPage = pDbPage;
1077 pPage->pBt = pBt;
1078 pPage->pgno = pgno;
1079 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
1080 return pPage;
1081}
1082
drhbd03cae2001-06-02 02:40:57 +00001083/*
drh3aac2dd2004-04-26 14:10:20 +00001084** Get a page from the pager. Initialize the MemPage.pBt and
1085** MemPage.aData elements if needed.
drh538f5702007-04-13 02:14:30 +00001086**
1087** If the noContent flag is set, it means that we do not care about
1088** the content of the page at this time. So do not go to the disk
1089** to fetch the content. Just fill in the content with zeros for now.
1090** If in the future we call sqlite3PagerWrite() on this page, that
1091** means we have started to be concerned about content and the disk
1092** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00001093*/
drh16a9b832007-05-05 18:39:25 +00001094int sqlite3BtreeGetPage(
1095 BtShared *pBt, /* The btree */
1096 Pgno pgno, /* Number of the page to fetch */
1097 MemPage **ppPage, /* Return the page in this parameter */
1098 int noContent /* Do not load page content if true */
1099){
drh3aac2dd2004-04-26 14:10:20 +00001100 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001101 DbPage *pDbPage;
1102
drh1fee73e2007-08-29 04:00:57 +00001103 assert( sqlite3_mutex_held(pBt->mutex) );
drh538f5702007-04-13 02:14:30 +00001104 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
drh3aac2dd2004-04-26 14:10:20 +00001105 if( rc ) return rc;
drh897a8202008-09-18 01:08:15 +00001106 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
drh3aac2dd2004-04-26 14:10:20 +00001107 return SQLITE_OK;
1108}
1109
1110/*
danielk197767fd7a92008-09-10 17:53:35 +00001111** Return the size of the database file in pages. Or return -1 if
1112** there is any kind of error.
1113*/
1114static int pagerPagecount(Pager *pPager){
1115 int rc;
1116 int nPage;
1117 rc = sqlite3PagerPagecount(pPager, &nPage);
1118 return (rc==SQLITE_OK?nPage:-1);
1119}
1120
1121/*
drhde647132004-05-07 17:57:49 +00001122** Get a page from the pager and initialize it. This routine
1123** is just a convenience wrapper around separate calls to
drh16a9b832007-05-05 18:39:25 +00001124** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
drhde647132004-05-07 17:57:49 +00001125*/
1126static int getAndInitPage(
danielk1977aef0bf62005-12-30 16:28:01 +00001127 BtShared *pBt, /* The database file */
drhde647132004-05-07 17:57:49 +00001128 Pgno pgno, /* Number of the page to get */
danielk197771d5d2c2008-09-29 11:49:47 +00001129 MemPage **ppPage /* Write the page pointer here */
drhde647132004-05-07 17:57:49 +00001130){
1131 int rc;
drh897a8202008-09-18 01:08:15 +00001132 DbPage *pDbPage;
1133 MemPage *pPage;
1134
drh1fee73e2007-08-29 04:00:57 +00001135 assert( sqlite3_mutex_held(pBt->mutex) );
drh897a8202008-09-18 01:08:15 +00001136 if( pgno==0 ){
drh49285702005-09-17 15:20:26 +00001137 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001138 }
danielk19779f580ad2008-09-10 14:45:57 +00001139
drh897a8202008-09-18 01:08:15 +00001140 /* It is often the case that the page we want is already in cache.
1141 ** If so, get it directly. This saves us from having to call
1142 ** pagerPagecount() to make sure pgno is within limits, which results
1143 ** in a measureable performance improvements.
1144 */
1145 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
1146 if( pDbPage ){
1147 /* Page is already in cache */
1148 *ppPage = pPage = btreePageFromDbPage(pDbPage, pgno, pBt);
1149 rc = SQLITE_OK;
1150 }else{
1151 /* Page not in cache. Acquire it. */
1152 if( pgno>pagerPagecount(pBt->pPager) ){
1153 return SQLITE_CORRUPT_BKPT;
1154 }
1155 rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
1156 if( rc ) return rc;
1157 pPage = *ppPage;
1158 }
danielk197771d5d2c2008-09-29 11:49:47 +00001159 if( !pPage->isInit ){
1160 rc = sqlite3BtreeInitPage(pPage);
drh897a8202008-09-18 01:08:15 +00001161 }
1162 if( rc!=SQLITE_OK ){
1163 releasePage(pPage);
1164 *ppPage = 0;
1165 }
drhde647132004-05-07 17:57:49 +00001166 return rc;
1167}
1168
1169/*
drh3aac2dd2004-04-26 14:10:20 +00001170** Release a MemPage. This should be called once for each prior
drh16a9b832007-05-05 18:39:25 +00001171** call to sqlite3BtreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +00001172*/
drh4b70f112004-05-02 21:12:19 +00001173static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001174 if( pPage ){
1175 assert( pPage->aData );
1176 assert( pPage->pBt );
drhbf4bca52007-09-06 22:19:14 +00001177 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1178 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
drh1fee73e2007-08-29 04:00:57 +00001179 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001180 sqlite3PagerUnref(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00001181 }
1182}
1183
1184/*
drha6abd042004-06-09 17:37:22 +00001185** During a rollback, when the pager reloads information into the cache
1186** so that the cache is restored to its original state at the start of
1187** the transaction, for each page restored this routine is called.
1188**
1189** This routine needs to reset the extra data section at the end of the
1190** page to agree with the restored data.
1191*/
danielk1977eaa06f62008-09-18 17:34:44 +00001192static void pageReinit(DbPage *pData){
drh07d183d2005-05-01 22:52:42 +00001193 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00001194 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
danielk197771d5d2c2008-09-29 11:49:47 +00001195 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00001196 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00001197 pPage->isInit = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001198 if( sqlite3PagerPageRefcount(pData)>0 ){
1199 sqlite3BtreeInitPage(pPage);
1200 }
drha6abd042004-06-09 17:37:22 +00001201 }
1202}
1203
1204/*
drhe5fe6902007-12-07 18:55:28 +00001205** Invoke the busy handler for a btree.
1206*/
1207static int sqlite3BtreeInvokeBusyHandler(void *pArg, int n){
1208 BtShared *pBt = (BtShared*)pArg;
1209 assert( pBt->db );
1210 assert( sqlite3_mutex_held(pBt->db->mutex) );
1211 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
1212}
1213
1214/*
drhad3e0102004-09-03 23:32:18 +00001215** Open a database file.
1216**
drh382c0242001-10-06 16:33:02 +00001217** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001218** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001219** database file will be deleted when sqlite3BtreeClose() is called.
drhe53831d2007-08-17 01:14:38 +00001220** If zFilename is ":memory:" then an in-memory database is created
1221** that is automatically destroyed when it is closed.
drha059ad02001-04-17 20:09:11 +00001222*/
drh23e11ca2004-05-04 17:27:28 +00001223int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001224 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00001225 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001226 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00001227 int flags, /* Options */
1228 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00001229){
drhd677b3d2007-08-20 22:48:41 +00001230 sqlite3_vfs *pVfs; /* The VFS to use for this btree */
drhe53831d2007-08-17 01:14:38 +00001231 BtShared *pBt = 0; /* Shared part of btree structure */
danielk1977aef0bf62005-12-30 16:28:01 +00001232 Btree *p; /* Handle to return */
danielk1977dddbcdc2007-04-26 14:42:34 +00001233 int rc = SQLITE_OK;
drh90f5ecb2004-07-22 01:19:35 +00001234 int nReserve;
1235 unsigned char zDbHeader[100];
danielk1977aef0bf62005-12-30 16:28:01 +00001236
1237 /* Set the variable isMemdb to true for an in-memory database, or
1238 ** false for a file-based database. This symbol is only required if
1239 ** either of the shared-data or autovacuum features are compiled
1240 ** into the library.
1241 */
1242#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
1243 #ifdef SQLITE_OMIT_MEMORYDB
drh980b1a72006-08-16 16:42:48 +00001244 const int isMemdb = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00001245 #else
drh980b1a72006-08-16 16:42:48 +00001246 const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
danielk1977aef0bf62005-12-30 16:28:01 +00001247 #endif
1248#endif
1249
drhe5fe6902007-12-07 18:55:28 +00001250 assert( db!=0 );
1251 assert( sqlite3_mutex_held(db->mutex) );
drh153c62c2007-08-24 03:51:33 +00001252
drhe5fe6902007-12-07 18:55:28 +00001253 pVfs = db->pVfs;
drh17435752007-08-16 04:30:38 +00001254 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00001255 if( !p ){
1256 return SQLITE_NOMEM;
1257 }
1258 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00001259 p->db = db;
danielk1977aef0bf62005-12-30 16:28:01 +00001260
drh198bf392006-01-06 21:52:49 +00001261#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001262 /*
1263 ** If this Btree is a candidate for shared cache, try to find an
1264 ** existing BtShared object that we can share with
1265 */
drh34004ce2008-07-11 16:15:17 +00001266 if( isMemdb==0
drhe5fe6902007-12-07 18:55:28 +00001267 && (db->flags & SQLITE_Vtab)==0
drhe53831d2007-08-17 01:14:38 +00001268 && zFilename && zFilename[0]
drhe53831d2007-08-17 01:14:38 +00001269 ){
danielk1977502b4e02008-09-02 14:07:24 +00001270 if( sqlite3GlobalConfig.sharedCacheEnabled ){
danielk1977adfb9b02007-09-17 07:02:56 +00001271 int nFullPathname = pVfs->mxPathname+1;
drhe5ae5732008-06-15 02:51:47 +00001272 char *zFullPathname = sqlite3Malloc(nFullPathname);
drhff0587c2007-08-29 17:43:19 +00001273 sqlite3_mutex *mutexShared;
1274 p->sharable = 1;
drh34004ce2008-07-11 16:15:17 +00001275 db->flags |= SQLITE_SharedCache;
drhff0587c2007-08-29 17:43:19 +00001276 if( !zFullPathname ){
1277 sqlite3_free(p);
1278 return SQLITE_NOMEM;
1279 }
danielk1977adfb9b02007-09-17 07:02:56 +00001280 sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
danielk197759f8c082008-06-18 17:09:10 +00001281 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhff0587c2007-08-29 17:43:19 +00001282 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001283 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
drhff0587c2007-08-29 17:43:19 +00001284 assert( pBt->nRef>0 );
1285 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
1286 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
1287 p->pBt = pBt;
1288 pBt->nRef++;
1289 break;
1290 }
1291 }
1292 sqlite3_mutex_leave(mutexShared);
1293 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00001294 }
drhff0587c2007-08-29 17:43:19 +00001295#ifdef SQLITE_DEBUG
1296 else{
1297 /* In debug mode, we mark all persistent databases as sharable
1298 ** even when they are not. This exercises the locking code and
1299 ** gives more opportunity for asserts(sqlite3_mutex_held())
1300 ** statements to find locking problems.
1301 */
1302 p->sharable = 1;
1303 }
1304#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001305 }
1306#endif
drha059ad02001-04-17 20:09:11 +00001307 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00001308 /*
1309 ** The following asserts make sure that structures used by the btree are
1310 ** the right size. This is to guard against size changes that result
1311 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00001312 */
drhe53831d2007-08-17 01:14:38 +00001313 assert( sizeof(i64)==8 || sizeof(i64)==4 );
1314 assert( sizeof(u64)==8 || sizeof(u64)==4 );
1315 assert( sizeof(u32)==4 );
1316 assert( sizeof(u16)==2 );
1317 assert( sizeof(Pgno)==4 );
1318
1319 pBt = sqlite3MallocZero( sizeof(*pBt) );
1320 if( pBt==0 ){
1321 rc = SQLITE_NOMEM;
1322 goto btree_open_out;
1323 }
drhe5fe6902007-12-07 18:55:28 +00001324 pBt->busyHdr.xFunc = sqlite3BtreeInvokeBusyHandler;
1325 pBt->busyHdr.pArg = pBt;
danielk197771d5d2c2008-09-29 11:49:47 +00001326 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
drh33f4e022007-09-03 15:19:34 +00001327 EXTRA_SIZE, flags, vfsFlags);
drhe53831d2007-08-17 01:14:38 +00001328 if( rc==SQLITE_OK ){
1329 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
1330 }
1331 if( rc!=SQLITE_OK ){
1332 goto btree_open_out;
1333 }
drhe5fe6902007-12-07 18:55:28 +00001334 sqlite3PagerSetBusyhandler(pBt->pPager, &pBt->busyHdr);
drhe53831d2007-08-17 01:14:38 +00001335 p->pBt = pBt;
1336
drhe53831d2007-08-17 01:14:38 +00001337 sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
1338 pBt->pCursor = 0;
1339 pBt->pPage1 = 0;
1340 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
1341 pBt->pageSize = get2byte(&zDbHeader[16]);
1342 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1343 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00001344 pBt->pageSize = 0;
1345 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drhe53831d2007-08-17 01:14:38 +00001346#ifndef SQLITE_OMIT_AUTOVACUUM
1347 /* If the magic name ":memory:" will create an in-memory database, then
1348 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
1349 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
1350 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
1351 ** regular file-name. In this case the auto-vacuum applies as per normal.
1352 */
1353 if( zFilename && !isMemdb ){
1354 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
1355 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
1356 }
1357#endif
1358 nReserve = 0;
1359 }else{
1360 nReserve = zDbHeader[20];
drhe53831d2007-08-17 01:14:38 +00001361 pBt->pageSizeFixed = 1;
1362#ifndef SQLITE_OMIT_AUTOVACUUM
1363 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1364 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
1365#endif
1366 }
1367 pBt->usableSize = pBt->pageSize - nReserve;
1368 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
danielk1977a1644fd2007-08-29 12:31:25 +00001369 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drhe53831d2007-08-17 01:14:38 +00001370
1371#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1372 /* Add the new BtShared object to the linked list sharable BtShareds.
1373 */
1374 if( p->sharable ){
1375 sqlite3_mutex *mutexShared;
1376 pBt->nRef = 1;
danielk197759f8c082008-06-18 17:09:10 +00001377 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
danielk1977075c23a2008-09-01 18:34:20 +00001378 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
danielk197759f8c082008-06-18 17:09:10 +00001379 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
drh3285db22007-09-03 22:00:39 +00001380 if( pBt->mutex==0 ){
1381 rc = SQLITE_NOMEM;
drhe5fe6902007-12-07 18:55:28 +00001382 db->mallocFailed = 0;
drh3285db22007-09-03 22:00:39 +00001383 goto btree_open_out;
1384 }
drhff0587c2007-08-29 17:43:19 +00001385 }
drhe53831d2007-08-17 01:14:38 +00001386 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001387 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
1388 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
drhe53831d2007-08-17 01:14:38 +00001389 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00001390 }
drheee46cf2004-11-06 00:02:48 +00001391#endif
drh90f5ecb2004-07-22 01:19:35 +00001392 }
danielk1977aef0bf62005-12-30 16:28:01 +00001393
drhcfed7bc2006-03-13 14:28:05 +00001394#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001395 /* If the new Btree uses a sharable pBtShared, then link the new
1396 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00001397 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00001398 */
drhe53831d2007-08-17 01:14:38 +00001399 if( p->sharable ){
1400 int i;
1401 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00001402 for(i=0; i<db->nDb; i++){
1403 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00001404 while( pSib->pPrev ){ pSib = pSib->pPrev; }
1405 if( p->pBt<pSib->pBt ){
1406 p->pNext = pSib;
1407 p->pPrev = 0;
1408 pSib->pPrev = p;
1409 }else{
drhabddb0c2007-08-20 13:14:28 +00001410 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
drhe53831d2007-08-17 01:14:38 +00001411 pSib = pSib->pNext;
1412 }
1413 p->pNext = pSib->pNext;
1414 p->pPrev = pSib;
1415 if( p->pNext ){
1416 p->pNext->pPrev = p;
1417 }
1418 pSib->pNext = p;
1419 }
1420 break;
1421 }
1422 }
danielk1977aef0bf62005-12-30 16:28:01 +00001423 }
danielk1977aef0bf62005-12-30 16:28:01 +00001424#endif
1425 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00001426
1427btree_open_out:
1428 if( rc!=SQLITE_OK ){
1429 if( pBt && pBt->pPager ){
1430 sqlite3PagerClose(pBt->pPager);
1431 }
drh17435752007-08-16 04:30:38 +00001432 sqlite3_free(pBt);
1433 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00001434 *ppBtree = 0;
1435 }
1436 return rc;
drha059ad02001-04-17 20:09:11 +00001437}
1438
1439/*
drhe53831d2007-08-17 01:14:38 +00001440** Decrement the BtShared.nRef counter. When it reaches zero,
1441** remove the BtShared structure from the sharing list. Return
1442** true if the BtShared.nRef counter reaches zero and return
1443** false if it is still positive.
1444*/
1445static int removeFromSharingList(BtShared *pBt){
1446#ifndef SQLITE_OMIT_SHARED_CACHE
1447 sqlite3_mutex *pMaster;
1448 BtShared *pList;
1449 int removed = 0;
1450
drhd677b3d2007-08-20 22:48:41 +00001451 assert( sqlite3_mutex_notheld(pBt->mutex) );
danielk197759f8c082008-06-18 17:09:10 +00001452 pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhe53831d2007-08-17 01:14:38 +00001453 sqlite3_mutex_enter(pMaster);
1454 pBt->nRef--;
1455 if( pBt->nRef<=0 ){
drh78f82d12008-09-02 00:52:52 +00001456 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
1457 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
drhe53831d2007-08-17 01:14:38 +00001458 }else{
drh78f82d12008-09-02 00:52:52 +00001459 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
drh34004ce2008-07-11 16:15:17 +00001460 while( ALWAYS(pList) && pList->pNext!=pBt ){
drhe53831d2007-08-17 01:14:38 +00001461 pList=pList->pNext;
1462 }
drh34004ce2008-07-11 16:15:17 +00001463 if( ALWAYS(pList) ){
drhe53831d2007-08-17 01:14:38 +00001464 pList->pNext = pBt->pNext;
1465 }
1466 }
drh3285db22007-09-03 22:00:39 +00001467 if( SQLITE_THREADSAFE ){
1468 sqlite3_mutex_free(pBt->mutex);
1469 }
drhe53831d2007-08-17 01:14:38 +00001470 removed = 1;
1471 }
1472 sqlite3_mutex_leave(pMaster);
1473 return removed;
1474#else
1475 return 1;
1476#endif
1477}
1478
1479/*
drhf7141992008-06-19 00:16:08 +00001480** Make sure pBt->pTmpSpace points to an allocation of
1481** MX_CELL_SIZE(pBt) bytes.
1482*/
1483static void allocateTempSpace(BtShared *pBt){
1484 if( !pBt->pTmpSpace ){
1485 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
1486 }
1487}
1488
1489/*
1490** Free the pBt->pTmpSpace allocation
1491*/
1492static void freeTempSpace(BtShared *pBt){
1493 sqlite3PageFree( pBt->pTmpSpace);
1494 pBt->pTmpSpace = 0;
1495}
1496
1497/*
drha059ad02001-04-17 20:09:11 +00001498** Close an open database and invalidate all cursors.
1499*/
danielk1977aef0bf62005-12-30 16:28:01 +00001500int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00001501 BtShared *pBt = p->pBt;
1502 BtCursor *pCur;
1503
danielk1977aef0bf62005-12-30 16:28:01 +00001504 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00001505 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00001506 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00001507 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00001508 pCur = pBt->pCursor;
1509 while( pCur ){
1510 BtCursor *pTmp = pCur;
1511 pCur = pCur->pNext;
1512 if( pTmp->pBtree==p ){
1513 sqlite3BtreeCloseCursor(pTmp);
1514 }
drha059ad02001-04-17 20:09:11 +00001515 }
danielk1977aef0bf62005-12-30 16:28:01 +00001516
danielk19778d34dfd2006-01-24 16:37:57 +00001517 /* Rollback any active transaction and free the handle structure.
1518 ** The call to sqlite3BtreeRollback() drops any table-locks held by
1519 ** this handle.
1520 */
danielk1977b597f742006-01-15 11:39:18 +00001521 sqlite3BtreeRollback(p);
drhe53831d2007-08-17 01:14:38 +00001522 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001523
danielk1977aef0bf62005-12-30 16:28:01 +00001524 /* If there are still other outstanding references to the shared-btree
1525 ** structure, return now. The remainder of this procedure cleans
1526 ** up the shared-btree.
1527 */
drhe53831d2007-08-17 01:14:38 +00001528 assert( p->wantToLock==0 && p->locked==0 );
1529 if( !p->sharable || removeFromSharingList(pBt) ){
1530 /* The pBt is no longer on the sharing list, so we can access
1531 ** it without having to hold the mutex.
1532 **
1533 ** Clean out and delete the BtShared object.
1534 */
1535 assert( !pBt->pCursor );
drhe53831d2007-08-17 01:14:38 +00001536 sqlite3PagerClose(pBt->pPager);
1537 if( pBt->xFreeSchema && pBt->pSchema ){
1538 pBt->xFreeSchema(pBt->pSchema);
1539 }
1540 sqlite3_free(pBt->pSchema);
drhf7141992008-06-19 00:16:08 +00001541 freeTempSpace(pBt);
drh65bbf292008-06-19 01:03:17 +00001542 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00001543 }
1544
drhe53831d2007-08-17 01:14:38 +00001545#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00001546 assert( p->wantToLock==0 );
1547 assert( p->locked==0 );
1548 if( p->pPrev ) p->pPrev->pNext = p->pNext;
1549 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00001550#endif
1551
drhe53831d2007-08-17 01:14:38 +00001552 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00001553 return SQLITE_OK;
1554}
1555
1556/*
drhda47d772002-12-02 04:25:19 +00001557** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001558**
1559** The maximum number of cache pages is set to the absolute
1560** value of mxPage. If mxPage is negative, the pager will
1561** operate asynchronously - it will not stop to do fsync()s
1562** to insure data is written to the disk surface before
1563** continuing. Transactions still work if synchronous is off,
1564** and the database cannot be corrupted if this program
1565** crashes. But if the operating system crashes or there is
1566** an abrupt power failure when synchronous is off, the database
1567** could be left in an inconsistent and unrecoverable state.
1568** Synchronous is on by default so database corruption is not
1569** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001570*/
danielk1977aef0bf62005-12-30 16:28:01 +00001571int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
1572 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001573 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001574 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001575 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00001576 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00001577 return SQLITE_OK;
1578}
1579
1580/*
drh973b6e32003-02-12 14:09:42 +00001581** Change the way data is synced to disk in order to increase or decrease
1582** how well the database resists damage due to OS crashes and power
1583** failures. Level 1 is the same as asynchronous (no syncs() occur and
1584** there is a high probability of damage) Level 2 is the default. There
1585** is a very low but non-zero probability of damage. Level 3 reduces the
1586** probability of damage to near zero but with a write performance reduction.
1587*/
danielk197793758c82005-01-21 08:13:14 +00001588#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drhac530b12006-02-11 01:25:50 +00001589int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
danielk1977aef0bf62005-12-30 16:28:01 +00001590 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001591 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001592 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001593 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
drhd677b3d2007-08-20 22:48:41 +00001594 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00001595 return SQLITE_OK;
1596}
danielk197793758c82005-01-21 08:13:14 +00001597#endif
drh973b6e32003-02-12 14:09:42 +00001598
drh2c8997b2005-08-27 16:36:48 +00001599/*
1600** Return TRUE if the given btree is set to safety level 1. In other
1601** words, return TRUE if no sync() occurs on the disk files.
1602*/
danielk1977aef0bf62005-12-30 16:28:01 +00001603int sqlite3BtreeSyncDisabled(Btree *p){
1604 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001605 int rc;
drhe5fe6902007-12-07 18:55:28 +00001606 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001607 sqlite3BtreeEnter(p);
drhd0679ed2007-08-28 22:24:34 +00001608 assert( pBt && pBt->pPager );
drhd677b3d2007-08-20 22:48:41 +00001609 rc = sqlite3PagerNosync(pBt->pPager);
1610 sqlite3BtreeLeave(p);
1611 return rc;
drh2c8997b2005-08-27 16:36:48 +00001612}
1613
danielk1977576ec6b2005-01-21 11:55:25 +00001614#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00001615/*
drh90f5ecb2004-07-22 01:19:35 +00001616** Change the default pages size and the number of reserved bytes per page.
drh06f50212004-11-02 14:24:33 +00001617**
1618** The page size must be a power of 2 between 512 and 65536. If the page
1619** size supplied does not meet this constraint then the page size is not
1620** changed.
1621**
1622** Page sizes are constrained to be a power of two so that the region
1623** of the database file used for locking (beginning at PENDING_BYTE,
1624** the first byte past the 1GB boundary, 0x40000000) needs to occur
1625** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001626**
1627** If parameter nReserve is less than zero, then the number of reserved
1628** bytes per page is left unchanged.
drh90f5ecb2004-07-22 01:19:35 +00001629*/
danielk1977aef0bf62005-12-30 16:28:01 +00001630int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
danielk1977a1644fd2007-08-29 12:31:25 +00001631 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00001632 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001633 sqlite3BtreeEnter(p);
drh90f5ecb2004-07-22 01:19:35 +00001634 if( pBt->pageSizeFixed ){
drhd677b3d2007-08-20 22:48:41 +00001635 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00001636 return SQLITE_READONLY;
1637 }
1638 if( nReserve<0 ){
1639 nReserve = pBt->pageSize - pBt->usableSize;
1640 }
drh06f50212004-11-02 14:24:33 +00001641 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
1642 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00001643 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00001644 assert( !pBt->pPage1 && !pBt->pCursor );
danielk1977a1644fd2007-08-29 12:31:25 +00001645 pBt->pageSize = pageSize;
drhf7141992008-06-19 00:16:08 +00001646 freeTempSpace(pBt);
danielk1977a1644fd2007-08-29 12:31:25 +00001647 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001648 }
1649 pBt->usableSize = pBt->pageSize - nReserve;
drhd677b3d2007-08-20 22:48:41 +00001650 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00001651 return rc;
drh90f5ecb2004-07-22 01:19:35 +00001652}
1653
1654/*
1655** Return the currently defined page size
1656*/
danielk1977aef0bf62005-12-30 16:28:01 +00001657int sqlite3BtreeGetPageSize(Btree *p){
1658 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00001659}
danielk1977aef0bf62005-12-30 16:28:01 +00001660int sqlite3BtreeGetReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00001661 int n;
1662 sqlite3BtreeEnter(p);
1663 n = p->pBt->pageSize - p->pBt->usableSize;
1664 sqlite3BtreeLeave(p);
1665 return n;
drh2011d5f2004-07-22 02:40:37 +00001666}
drhf8e632b2007-05-08 14:51:36 +00001667
1668/*
1669** Set the maximum page count for a database if mxPage is positive.
1670** No changes are made if mxPage is 0 or negative.
1671** Regardless of the value of mxPage, return the maximum page count.
1672*/
1673int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00001674 int n;
1675 sqlite3BtreeEnter(p);
1676 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
1677 sqlite3BtreeLeave(p);
1678 return n;
drhf8e632b2007-05-08 14:51:36 +00001679}
danielk1977576ec6b2005-01-21 11:55:25 +00001680#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00001681
1682/*
danielk1977951af802004-11-05 15:45:09 +00001683** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
1684** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
1685** is disabled. The default value for the auto-vacuum property is
1686** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
1687*/
danielk1977aef0bf62005-12-30 16:28:01 +00001688int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00001689#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001690 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00001691#else
danielk1977dddbcdc2007-04-26 14:42:34 +00001692 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001693 int rc = SQLITE_OK;
danielk1977dddbcdc2007-04-26 14:42:34 +00001694 int av = (autoVacuum?1:0);
drhd677b3d2007-08-20 22:48:41 +00001695
1696 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00001697 if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00001698 rc = SQLITE_READONLY;
1699 }else{
1700 pBt->autoVacuum = av;
danielk1977951af802004-11-05 15:45:09 +00001701 }
drhd677b3d2007-08-20 22:48:41 +00001702 sqlite3BtreeLeave(p);
1703 return rc;
danielk1977951af802004-11-05 15:45:09 +00001704#endif
1705}
1706
1707/*
1708** Return the value of the 'auto-vacuum' property. If auto-vacuum is
1709** enabled 1 is returned. Otherwise 0.
1710*/
danielk1977aef0bf62005-12-30 16:28:01 +00001711int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00001712#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00001713 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00001714#else
drhd677b3d2007-08-20 22:48:41 +00001715 int rc;
1716 sqlite3BtreeEnter(p);
1717 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00001718 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
1719 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
1720 BTREE_AUTOVACUUM_INCR
1721 );
drhd677b3d2007-08-20 22:48:41 +00001722 sqlite3BtreeLeave(p);
1723 return rc;
danielk1977951af802004-11-05 15:45:09 +00001724#endif
1725}
1726
1727
1728/*
drha34b6762004-05-07 13:30:42 +00001729** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001730** also acquire a readlock on that file.
1731**
1732** SQLITE_OK is returned on success. If the file is not a
1733** well-formed database file, then SQLITE_CORRUPT is returned.
1734** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00001735** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00001736*/
danielk1977aef0bf62005-12-30 16:28:01 +00001737static int lockBtree(BtShared *pBt){
danielk1977f653d782008-03-20 11:04:21 +00001738 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001739 MemPage *pPage1;
danielk197793f7af92008-05-09 16:57:50 +00001740 int nPage;
drhd677b3d2007-08-20 22:48:41 +00001741
drh1fee73e2007-08-29 04:00:57 +00001742 assert( sqlite3_mutex_held(pBt->mutex) );
drha34b6762004-05-07 13:30:42 +00001743 if( pBt->pPage1 ) return SQLITE_OK;
drh16a9b832007-05-05 18:39:25 +00001744 rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00001745 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00001746
1747 /* Do some checking to help insure the file we opened really is
1748 ** a valid database file.
1749 */
danielk1977ad0132d2008-06-07 08:58:22 +00001750 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1751 if( rc!=SQLITE_OK ){
danielk197793f7af92008-05-09 16:57:50 +00001752 goto page1_init_failed;
1753 }else if( nPage>0 ){
danielk1977f653d782008-03-20 11:04:21 +00001754 int pageSize;
1755 int usableSize;
drhb6f41482004-05-14 01:58:11 +00001756 u8 *page1 = pPage1->aData;
danielk1977ad0132d2008-06-07 08:58:22 +00001757 rc = SQLITE_NOTADB;
drhb6f41482004-05-14 01:58:11 +00001758 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001759 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001760 }
drh309169a2007-04-24 17:27:51 +00001761 if( page1[18]>1 ){
1762 pBt->readOnly = 1;
1763 }
1764 if( page1[19]>1 ){
drhb6f41482004-05-14 01:58:11 +00001765 goto page1_init_failed;
1766 }
drhe5ae5732008-06-15 02:51:47 +00001767
1768 /* The maximum embedded fraction must be exactly 25%. And the minimum
1769 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
1770 ** The original design allowed these amounts to vary, but as of
1771 ** version 3.6.0, we require them to be fixed.
1772 */
1773 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
1774 goto page1_init_failed;
1775 }
drh07d183d2005-05-01 22:52:42 +00001776 pageSize = get2byte(&page1[16]);
drh7dc385e2007-09-06 23:39:36 +00001777 if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
1778 (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
1779 ){
drh07d183d2005-05-01 22:52:42 +00001780 goto page1_init_failed;
1781 }
1782 assert( (pageSize & 7)==0 );
danielk1977f653d782008-03-20 11:04:21 +00001783 usableSize = pageSize - page1[20];
1784 if( pageSize!=pBt->pageSize ){
1785 /* After reading the first page of the database assuming a page size
1786 ** of BtShared.pageSize, we have discovered that the page-size is
1787 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
1788 ** zero and return SQLITE_OK. The caller will call this function
1789 ** again with the correct page-size.
1790 */
1791 releasePage(pPage1);
1792 pBt->usableSize = usableSize;
1793 pBt->pageSize = pageSize;
drhf7141992008-06-19 00:16:08 +00001794 freeTempSpace(pBt);
danielk1977f653d782008-03-20 11:04:21 +00001795 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
1796 return SQLITE_OK;
1797 }
1798 if( usableSize<500 ){
drhb6f41482004-05-14 01:58:11 +00001799 goto page1_init_failed;
1800 }
danielk1977f653d782008-03-20 11:04:21 +00001801 pBt->pageSize = pageSize;
1802 pBt->usableSize = usableSize;
drh057cd3a2005-02-15 16:23:02 +00001803#ifndef SQLITE_OMIT_AUTOVACUUM
1804 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00001805 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00001806#endif
drh306dc212001-05-21 13:45:10 +00001807 }
drhb6f41482004-05-14 01:58:11 +00001808
1809 /* maxLocal is the maximum amount of payload to store locally for
1810 ** a cell. Make sure it is small enough so that at least minFanout
1811 ** cells can will fit on one page. We assume a 10-byte page header.
1812 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001813 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001814 ** 4-byte child pointer
1815 ** 9-byte nKey value
1816 ** 4-byte nData value
1817 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001818 ** So a cell consists of a 2-byte poiner, a header which is as much as
1819 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1820 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001821 */
drhe5ae5732008-06-15 02:51:47 +00001822 pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
1823 pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
drh43605152004-05-29 21:46:49 +00001824 pBt->maxLeaf = pBt->usableSize - 35;
drhe5ae5732008-06-15 02:51:47 +00001825 pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
drh2e38c322004-09-03 18:38:44 +00001826 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00001827 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001828 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001829
drh72f82862001-05-24 21:06:34 +00001830page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001831 releasePage(pPage1);
1832 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001833 return rc;
drh306dc212001-05-21 13:45:10 +00001834}
1835
1836/*
drhb8ef32c2005-03-14 02:01:49 +00001837** This routine works like lockBtree() except that it also invokes the
1838** busy callback if there is lock contention.
1839*/
danielk1977aef0bf62005-12-30 16:28:01 +00001840static int lockBtreeWithRetry(Btree *pRef){
drhb8ef32c2005-03-14 02:01:49 +00001841 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00001842
drh1fee73e2007-08-29 04:00:57 +00001843 assert( sqlite3BtreeHoldsMutex(pRef) );
danielk1977aef0bf62005-12-30 16:28:01 +00001844 if( pRef->inTrans==TRANS_NONE ){
1845 u8 inTransaction = pRef->pBt->inTransaction;
1846 btreeIntegrity(pRef);
1847 rc = sqlite3BtreeBeginTrans(pRef, 0);
1848 pRef->pBt->inTransaction = inTransaction;
1849 pRef->inTrans = TRANS_NONE;
1850 if( rc==SQLITE_OK ){
1851 pRef->pBt->nTransaction--;
1852 }
1853 btreeIntegrity(pRef);
drhb8ef32c2005-03-14 02:01:49 +00001854 }
1855 return rc;
1856}
1857
1858
1859/*
drhb8ca3072001-12-05 00:21:20 +00001860** If there are no outstanding cursors and we are not in the middle
1861** of a transaction but there is a read lock on the database, then
1862** this routine unrefs the first page of the database file which
1863** has the effect of releasing the read lock.
1864**
1865** If there are any outstanding cursors, this routine is a no-op.
1866**
1867** If there is a transaction in progress, this routine is a no-op.
1868*/
danielk1977aef0bf62005-12-30 16:28:01 +00001869static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00001870 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00001871 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00001872 if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
drhde4fcfd2008-01-19 23:50:26 +00001873 assert( pBt->pPage1->aData );
1874#if 0
drh24c9a2e2007-01-05 02:00:47 +00001875 if( pBt->pPage1->aData==0 ){
1876 MemPage *pPage = pBt->pPage1;
drhbf4bca52007-09-06 22:19:14 +00001877 pPage->aData = sqlite3PagerGetData(pPage->pDbPage);
drh24c9a2e2007-01-05 02:00:47 +00001878 pPage->pBt = pBt;
1879 pPage->pgno = 1;
1880 }
drhde4fcfd2008-01-19 23:50:26 +00001881#endif
drh24c9a2e2007-01-05 02:00:47 +00001882 releasePage(pBt->pPage1);
drh51c6d962004-06-06 00:42:25 +00001883 }
drh3aac2dd2004-04-26 14:10:20 +00001884 pBt->pPage1 = 0;
drh3aac2dd2004-04-26 14:10:20 +00001885 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001886 }
1887}
1888
1889/*
drh9e572e62004-04-23 23:43:10 +00001890** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00001891** file.
drh8b2f49b2001-06-08 00:21:52 +00001892*/
danielk1977aef0bf62005-12-30 16:28:01 +00001893static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00001894 MemPage *pP1;
1895 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00001896 int rc;
danielk1977ad0132d2008-06-07 08:58:22 +00001897 int nPage;
drhd677b3d2007-08-20 22:48:41 +00001898
drh1fee73e2007-08-29 04:00:57 +00001899 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977ad0132d2008-06-07 08:58:22 +00001900 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1901 if( rc!=SQLITE_OK || nPage>0 ){
1902 return rc;
1903 }
drh3aac2dd2004-04-26 14:10:20 +00001904 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00001905 assert( pP1!=0 );
1906 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00001907 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00001908 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00001909 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
1910 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00001911 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00001912 data[18] = 1;
1913 data[19] = 1;
drhb6f41482004-05-14 01:58:11 +00001914 data[20] = pBt->pageSize - pBt->usableSize;
drhe5ae5732008-06-15 02:51:47 +00001915 data[21] = 64;
1916 data[22] = 32;
1917 data[23] = 32;
drhb6f41482004-05-14 01:58:11 +00001918 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00001919 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00001920 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00001921#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00001922 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00001923 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00001924 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00001925 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00001926#endif
drh8b2f49b2001-06-08 00:21:52 +00001927 return SQLITE_OK;
1928}
1929
1930/*
danielk1977ee5741e2004-05-31 10:01:34 +00001931** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00001932** is started if the second argument is nonzero, otherwise a read-
1933** transaction. If the second argument is 2 or more and exclusive
1934** transaction is started, meaning that no other process is allowed
1935** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00001936** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00001937** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00001938**
danielk1977ee5741e2004-05-31 10:01:34 +00001939** A write-transaction must be started before attempting any
1940** changes to the database. None of the following routines
1941** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00001942**
drh23e11ca2004-05-04 17:27:28 +00001943** sqlite3BtreeCreateTable()
1944** sqlite3BtreeCreateIndex()
1945** sqlite3BtreeClearTable()
1946** sqlite3BtreeDropTable()
1947** sqlite3BtreeInsert()
1948** sqlite3BtreeDelete()
1949** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00001950**
drhb8ef32c2005-03-14 02:01:49 +00001951** If an initial attempt to acquire the lock fails because of lock contention
1952** and the database was previously unlocked, then invoke the busy handler
1953** if there is one. But if there was previously a read-lock, do not
1954** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
1955** returned when there is already a read-lock in order to avoid a deadlock.
1956**
1957** Suppose there are two processes A and B. A has a read lock and B has
1958** a reserved lock. B tries to promote to exclusive but is blocked because
1959** of A's read lock. A tries to promote to reserved but is blocked by B.
1960** One or the other of the two processes must give way or there can be
1961** no progress. By returning SQLITE_BUSY and not invoking the busy callback
1962** when A already has a read lock, we encourage A to give up and let B
1963** proceed.
drha059ad02001-04-17 20:09:11 +00001964*/
danielk1977aef0bf62005-12-30 16:28:01 +00001965int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
1966 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00001967 int rc = SQLITE_OK;
1968
drhd677b3d2007-08-20 22:48:41 +00001969 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00001970 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00001971 btreeIntegrity(p);
1972
danielk1977ee5741e2004-05-31 10:01:34 +00001973 /* If the btree is already in a write-transaction, or it
1974 ** is already in a read-transaction and a read-transaction
1975 ** is requested, this is a no-op.
1976 */
danielk1977aef0bf62005-12-30 16:28:01 +00001977 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00001978 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00001979 }
drhb8ef32c2005-03-14 02:01:49 +00001980
1981 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00001982 if( pBt->readOnly && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00001983 rc = SQLITE_READONLY;
1984 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00001985 }
1986
danielk1977aef0bf62005-12-30 16:28:01 +00001987 /* If another database handle has already opened a write transaction
1988 ** on this shared-btree structure and a second write transaction is
1989 ** requested, return SQLITE_BUSY.
1990 */
1991 if( pBt->inTransaction==TRANS_WRITE && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00001992 rc = SQLITE_BUSY;
1993 goto trans_begun;
danielk1977aef0bf62005-12-30 16:28:01 +00001994 }
1995
danielk1977641b0f42007-12-21 04:47:25 +00001996#ifndef SQLITE_OMIT_SHARED_CACHE
1997 if( wrflag>1 ){
1998 BtLock *pIter;
1999 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
2000 if( pIter->pBtree!=p ){
2001 rc = SQLITE_BUSY;
2002 goto trans_begun;
2003 }
2004 }
2005 }
2006#endif
2007
drhb8ef32c2005-03-14 02:01:49 +00002008 do {
drh8a9c17f2008-05-02 14:23:54 +00002009 if( pBt->pPage1==0 ){
2010 do{
2011 rc = lockBtree(pBt);
2012 }while( pBt->pPage1==0 && rc==SQLITE_OK );
drh8c42ca92001-06-22 19:15:00 +00002013 }
drh309169a2007-04-24 17:27:51 +00002014
drhb8ef32c2005-03-14 02:01:49 +00002015 if( rc==SQLITE_OK && wrflag ){
drh309169a2007-04-24 17:27:51 +00002016 if( pBt->readOnly ){
2017 rc = SQLITE_READONLY;
2018 }else{
2019 rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1);
2020 if( rc==SQLITE_OK ){
2021 rc = newDatabase(pBt);
2022 }
drhb8ef32c2005-03-14 02:01:49 +00002023 }
2024 }
2025
2026 if( rc==SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00002027 if( wrflag ) pBt->inStmt = 0;
2028 }else{
2029 unlockBtreeIfUnused(pBt);
2030 }
danielk1977aef0bf62005-12-30 16:28:01 +00002031 }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
drhe5fe6902007-12-07 18:55:28 +00002032 sqlite3BtreeInvokeBusyHandler(pBt, 0) );
danielk1977aef0bf62005-12-30 16:28:01 +00002033
2034 if( rc==SQLITE_OK ){
2035 if( p->inTrans==TRANS_NONE ){
2036 pBt->nTransaction++;
2037 }
2038 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
2039 if( p->inTrans>pBt->inTransaction ){
2040 pBt->inTransaction = p->inTrans;
2041 }
danielk1977641b0f42007-12-21 04:47:25 +00002042#ifndef SQLITE_OMIT_SHARED_CACHE
2043 if( wrflag>1 ){
2044 assert( !pBt->pExclusive );
2045 pBt->pExclusive = p;
2046 }
2047#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002048 }
2049
drhd677b3d2007-08-20 22:48:41 +00002050
2051trans_begun:
danielk1977aef0bf62005-12-30 16:28:01 +00002052 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002053 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00002054 return rc;
drha059ad02001-04-17 20:09:11 +00002055}
2056
danielk1977687566d2004-11-02 12:56:41 +00002057#ifndef SQLITE_OMIT_AUTOVACUUM
2058
2059/*
2060** Set the pointer-map entries for all children of page pPage. Also, if
2061** pPage contains cells that point to overflow pages, set the pointer
2062** map entries for the overflow pages as well.
2063*/
2064static int setChildPtrmaps(MemPage *pPage){
2065 int i; /* Counter variable */
2066 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00002067 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00002068 BtShared *pBt = pPage->pBt;
danielk1977687566d2004-11-02 12:56:41 +00002069 int isInitOrig = pPage->isInit;
2070 Pgno pgno = pPage->pgno;
2071
drh1fee73e2007-08-29 04:00:57 +00002072 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197771d5d2c2008-09-29 11:49:47 +00002073 rc = sqlite3BtreeInitPage(pPage);
danielk19772df71c72007-05-24 07:22:42 +00002074 if( rc!=SQLITE_OK ){
2075 goto set_child_ptrmaps_out;
2076 }
danielk1977687566d2004-11-02 12:56:41 +00002077 nCell = pPage->nCell;
2078
2079 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002080 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002081
danielk197726836652005-01-17 01:33:13 +00002082 rc = ptrmapPutOvflPtr(pPage, pCell);
2083 if( rc!=SQLITE_OK ){
2084 goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002085 }
danielk197726836652005-01-17 01:33:13 +00002086
danielk1977687566d2004-11-02 12:56:41 +00002087 if( !pPage->leaf ){
2088 Pgno childPgno = get4byte(pCell);
2089 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
danielk197700a696d2008-09-29 16:41:31 +00002090 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002091 }
2092 }
2093
2094 if( !pPage->leaf ){
2095 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
2096 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
2097 }
2098
2099set_child_ptrmaps_out:
2100 pPage->isInit = isInitOrig;
2101 return rc;
2102}
2103
2104/*
2105** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
2106** page, is a pointer to page iFrom. Modify this pointer so that it points to
2107** iTo. Parameter eType describes the type of pointer to be modified, as
2108** follows:
2109**
2110** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
2111** page of pPage.
2112**
2113** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
2114** page pointed to by one of the cells on pPage.
2115**
2116** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
2117** overflow page in the list.
2118*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00002119static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00002120 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk1977687566d2004-11-02 12:56:41 +00002121 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00002122 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00002123 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00002124 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002125 }
danielk1977f78fc082004-11-02 14:40:32 +00002126 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00002127 }else{
2128 int isInitOrig = pPage->isInit;
2129 int i;
2130 int nCell;
2131
danielk197771d5d2c2008-09-29 11:49:47 +00002132 sqlite3BtreeInitPage(pPage);
danielk1977687566d2004-11-02 12:56:41 +00002133 nCell = pPage->nCell;
2134
danielk1977687566d2004-11-02 12:56:41 +00002135 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002136 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002137 if( eType==PTRMAP_OVERFLOW1 ){
2138 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00002139 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
danielk1977687566d2004-11-02 12:56:41 +00002140 if( info.iOverflow ){
2141 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
2142 put4byte(&pCell[info.iOverflow], iTo);
2143 break;
2144 }
2145 }
2146 }else{
2147 if( get4byte(pCell)==iFrom ){
2148 put4byte(pCell, iTo);
2149 break;
2150 }
2151 }
2152 }
2153
2154 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00002155 if( eType!=PTRMAP_BTREE ||
2156 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00002157 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002158 }
danielk1977687566d2004-11-02 12:56:41 +00002159 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
2160 }
2161
2162 pPage->isInit = isInitOrig;
2163 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002164 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002165}
2166
danielk1977003ba062004-11-04 02:57:33 +00002167
danielk19777701e812005-01-10 12:59:51 +00002168/*
2169** Move the open database page pDbPage to location iFreePage in the
2170** database. The pDbPage reference remains valid.
2171*/
danielk1977003ba062004-11-04 02:57:33 +00002172static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00002173 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00002174 MemPage *pDbPage, /* Open page to move */
2175 u8 eType, /* Pointer map 'type' entry for pDbPage */
2176 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
danielk19774c999992008-07-16 18:17:55 +00002177 Pgno iFreePage, /* The location to move pDbPage to */
2178 int isCommit
danielk1977003ba062004-11-04 02:57:33 +00002179){
2180 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
2181 Pgno iDbPage = pDbPage->pgno;
2182 Pager *pPager = pBt->pPager;
2183 int rc;
2184
danielk1977a0bf2652004-11-04 14:30:04 +00002185 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
2186 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00002187 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00002188 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00002189
drh85b623f2007-12-13 21:54:09 +00002190 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00002191 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
2192 iDbPage, iFreePage, iPtrPage, eType));
danielk19774c999992008-07-16 18:17:55 +00002193 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
danielk1977003ba062004-11-04 02:57:33 +00002194 if( rc!=SQLITE_OK ){
2195 return rc;
2196 }
2197 pDbPage->pgno = iFreePage;
2198
2199 /* If pDbPage was a btree-page, then it may have child pages and/or cells
2200 ** that point to overflow pages. The pointer map entries for all these
2201 ** pages need to be changed.
2202 **
2203 ** If pDbPage is an overflow page, then the first 4 bytes may store a
2204 ** pointer to a subsequent overflow page. If this is the case, then
2205 ** the pointer map needs to be updated for the subsequent overflow page.
2206 */
danielk1977a0bf2652004-11-04 14:30:04 +00002207 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00002208 rc = setChildPtrmaps(pDbPage);
2209 if( rc!=SQLITE_OK ){
2210 return rc;
2211 }
2212 }else{
2213 Pgno nextOvfl = get4byte(pDbPage->aData);
2214 if( nextOvfl!=0 ){
danielk1977003ba062004-11-04 02:57:33 +00002215 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
2216 if( rc!=SQLITE_OK ){
2217 return rc;
2218 }
2219 }
2220 }
2221
2222 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
2223 ** that it points at iFreePage. Also fix the pointer map entry for
2224 ** iPtrPage.
2225 */
danielk1977a0bf2652004-11-04 14:30:04 +00002226 if( eType!=PTRMAP_ROOTPAGE ){
drh16a9b832007-05-05 18:39:25 +00002227 rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00002228 if( rc!=SQLITE_OK ){
2229 return rc;
2230 }
danielk19773b8a05f2007-03-19 17:44:26 +00002231 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00002232 if( rc!=SQLITE_OK ){
2233 releasePage(pPtrPage);
2234 return rc;
2235 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002236 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00002237 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00002238 if( rc==SQLITE_OK ){
2239 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
2240 }
danielk1977003ba062004-11-04 02:57:33 +00002241 }
danielk1977003ba062004-11-04 02:57:33 +00002242 return rc;
2243}
2244
danielk1977dddbcdc2007-04-26 14:42:34 +00002245/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00002246static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00002247
2248/*
danielk1977dddbcdc2007-04-26 14:42:34 +00002249** Perform a single step of an incremental-vacuum. If successful,
2250** return SQLITE_OK. If there is no work to do (and therefore no
2251** point in calling this function again), return SQLITE_DONE.
2252**
2253** More specificly, this function attempts to re-organize the
2254** database so that the last page of the file currently in use
2255** is no longer in use.
2256**
2257** If the nFin parameter is non-zero, the implementation assumes
2258** that the caller will keep calling incrVacuumStep() until
2259** it returns SQLITE_DONE or an error, and that nFin is the
2260** number of pages the database file will contain after this
2261** process is complete.
2262*/
2263static int incrVacuumStep(BtShared *pBt, Pgno nFin){
2264 Pgno iLastPg; /* Last page in the database */
2265 Pgno nFreeList; /* Number of pages still on the free-list */
2266
drh1fee73e2007-08-29 04:00:57 +00002267 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977dddbcdc2007-04-26 14:42:34 +00002268 iLastPg = pBt->nTrunc;
2269 if( iLastPg==0 ){
danielk1977ad0132d2008-06-07 08:58:22 +00002270 iLastPg = pagerPagecount(pBt->pPager);
danielk1977dddbcdc2007-04-26 14:42:34 +00002271 }
2272
2273 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
2274 int rc;
2275 u8 eType;
2276 Pgno iPtrPage;
2277
2278 nFreeList = get4byte(&pBt->pPage1->aData[36]);
2279 if( nFreeList==0 || nFin==iLastPg ){
2280 return SQLITE_DONE;
2281 }
2282
2283 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
2284 if( rc!=SQLITE_OK ){
2285 return rc;
2286 }
2287 if( eType==PTRMAP_ROOTPAGE ){
2288 return SQLITE_CORRUPT_BKPT;
2289 }
2290
2291 if( eType==PTRMAP_FREEPAGE ){
2292 if( nFin==0 ){
2293 /* Remove the page from the files free-list. This is not required
danielk19774ef24492007-05-23 09:52:41 +00002294 ** if nFin is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00002295 ** truncated to zero after this function returns, so it doesn't
2296 ** matter if it still contains some garbage entries.
2297 */
2298 Pgno iFreePg;
2299 MemPage *pFreePg;
2300 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
2301 if( rc!=SQLITE_OK ){
2302 return rc;
2303 }
2304 assert( iFreePg==iLastPg );
2305 releasePage(pFreePg);
2306 }
2307 } else {
2308 Pgno iFreePg; /* Index of free page to move pLastPg to */
2309 MemPage *pLastPg;
2310
drh16a9b832007-05-05 18:39:25 +00002311 rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002312 if( rc!=SQLITE_OK ){
2313 return rc;
2314 }
2315
danielk1977b4626a32007-04-28 15:47:43 +00002316 /* If nFin is zero, this loop runs exactly once and page pLastPg
2317 ** is swapped with the first free page pulled off the free list.
2318 **
2319 ** On the other hand, if nFin is greater than zero, then keep
2320 ** looping until a free-page located within the first nFin pages
2321 ** of the file is found.
2322 */
danielk1977dddbcdc2007-04-26 14:42:34 +00002323 do {
2324 MemPage *pFreePg;
2325 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
2326 if( rc!=SQLITE_OK ){
2327 releasePage(pLastPg);
2328 return rc;
2329 }
2330 releasePage(pFreePg);
2331 }while( nFin!=0 && iFreePg>nFin );
2332 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00002333
2334 rc = sqlite3PagerWrite(pLastPg->pDbPage);
danielk1977662278e2007-11-05 15:30:12 +00002335 if( rc==SQLITE_OK ){
danielk19774c999992008-07-16 18:17:55 +00002336 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
danielk1977662278e2007-11-05 15:30:12 +00002337 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002338 releasePage(pLastPg);
2339 if( rc!=SQLITE_OK ){
2340 return rc;
danielk1977662278e2007-11-05 15:30:12 +00002341 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002342 }
2343 }
2344
2345 pBt->nTrunc = iLastPg - 1;
2346 while( pBt->nTrunc==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, pBt->nTrunc) ){
2347 pBt->nTrunc--;
2348 }
2349 return SQLITE_OK;
2350}
2351
2352/*
2353** A write-transaction must be opened before calling this function.
2354** It performs a single unit of work towards an incremental vacuum.
2355**
2356** If the incremental vacuum is finished after this function has run,
2357** SQLITE_DONE is returned. If it is not finished, but no error occured,
2358** SQLITE_OK is returned. Otherwise an SQLite error code.
2359*/
2360int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002361 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002362 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002363
2364 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002365 pBt->db = p->db;
danielk1977dddbcdc2007-04-26 14:42:34 +00002366 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
2367 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002368 rc = SQLITE_DONE;
2369 }else{
2370 invalidateAllOverflowCache(pBt);
2371 rc = incrVacuumStep(pBt, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002372 }
drhd677b3d2007-08-20 22:48:41 +00002373 sqlite3BtreeLeave(p);
2374 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002375}
2376
2377/*
danielk19773b8a05f2007-03-19 17:44:26 +00002378** This routine is called prior to sqlite3PagerCommit when a transaction
danielk1977687566d2004-11-02 12:56:41 +00002379** is commited for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00002380**
2381** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
2382** the database file should be truncated to during the commit process.
2383** i.e. the database has been reorganized so that only the first *pnTrunc
2384** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00002385*/
danielk197724168722007-04-02 05:07:47 +00002386static int autoVacuumCommit(BtShared *pBt, Pgno *pnTrunc){
danielk1977dddbcdc2007-04-26 14:42:34 +00002387 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002388 Pager *pPager = pBt->pPager;
drhf94a1732008-09-30 17:18:17 +00002389 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002390
drh1fee73e2007-08-29 04:00:57 +00002391 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00002392 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00002393 assert(pBt->autoVacuum);
2394 if( !pBt->incrVacuum ){
2395 Pgno nFin = 0;
danielk1977687566d2004-11-02 12:56:41 +00002396
danielk1977dddbcdc2007-04-26 14:42:34 +00002397 if( pBt->nTrunc==0 ){
2398 Pgno nFree;
2399 Pgno nPtrmap;
2400 const int pgsz = pBt->pageSize;
danielk1977ad0132d2008-06-07 08:58:22 +00002401 int nOrig = pagerPagecount(pBt->pPager);
danielk1977e5321f02007-04-27 07:05:44 +00002402
2403 if( PTRMAP_ISPAGE(pBt, nOrig) ){
2404 return SQLITE_CORRUPT_BKPT;
2405 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002406 if( nOrig==PENDING_BYTE_PAGE(pBt) ){
2407 nOrig--;
danielk1977687566d2004-11-02 12:56:41 +00002408 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002409 nFree = get4byte(&pBt->pPage1->aData[36]);
2410 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
2411 nFin = nOrig - nFree - nPtrmap;
2412 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
2413 nFin--;
danielk1977ac11ee62005-01-15 12:45:51 +00002414 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002415 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
2416 nFin--;
2417 }
2418 }
danielk1977687566d2004-11-02 12:56:41 +00002419
danielk1977dddbcdc2007-04-26 14:42:34 +00002420 while( rc==SQLITE_OK ){
2421 rc = incrVacuumStep(pBt, nFin);
2422 }
2423 if( rc==SQLITE_DONE ){
2424 assert(nFin==0 || pBt->nTrunc==0 || nFin<=pBt->nTrunc);
2425 rc = SQLITE_OK;
danielk19770ba32df2008-05-07 07:13:16 +00002426 if( pBt->nTrunc && nFin ){
drh67f80b62007-07-23 19:26:17 +00002427 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
danielk1977dddbcdc2007-04-26 14:42:34 +00002428 put4byte(&pBt->pPage1->aData[32], 0);
2429 put4byte(&pBt->pPage1->aData[36], 0);
2430 pBt->nTrunc = nFin;
2431 }
2432 }
2433 if( rc!=SQLITE_OK ){
2434 sqlite3PagerRollback(pPager);
2435 }
danielk1977687566d2004-11-02 12:56:41 +00002436 }
2437
danielk1977dddbcdc2007-04-26 14:42:34 +00002438 if( rc==SQLITE_OK ){
2439 *pnTrunc = pBt->nTrunc;
2440 pBt->nTrunc = 0;
2441 }
danielk19773b8a05f2007-03-19 17:44:26 +00002442 assert( nRef==sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002443 return rc;
2444}
danielk1977dddbcdc2007-04-26 14:42:34 +00002445
shane831c3292008-11-10 17:14:58 +00002446#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
danielk1977687566d2004-11-02 12:56:41 +00002447
2448/*
drh80e35f42007-03-30 14:06:34 +00002449** This routine does the first phase of a two-phase commit. This routine
2450** causes a rollback journal to be created (if it does not already exist)
2451** and populated with enough information so that if a power loss occurs
2452** the database can be restored to its original state by playing back
2453** the journal. Then the contents of the journal are flushed out to
2454** the disk. After the journal is safely on oxide, the changes to the
2455** database are written into the database file and flushed to oxide.
2456** At the end of this call, the rollback journal still exists on the
2457** disk and we are still holding all locks, so the transaction has not
2458** committed. See sqlite3BtreeCommit() for the second phase of the
2459** commit process.
2460**
2461** This call is a no-op if no write-transaction is currently active on pBt.
2462**
2463** Otherwise, sync the database file for the btree pBt. zMaster points to
2464** the name of a master journal file that should be written into the
2465** individual journal file, or is NULL, indicating no master journal file
2466** (single database transaction).
2467**
2468** When this is called, the master journal should already have been
2469** created, populated with this journal pointer and synced to disk.
2470**
2471** Once this is routine has returned, the only thing required to commit
2472** the write-transaction for this database file is to delete the journal.
2473*/
2474int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
2475 int rc = SQLITE_OK;
2476 if( p->inTrans==TRANS_WRITE ){
2477 BtShared *pBt = p->pBt;
2478 Pgno nTrunc = 0;
drhd677b3d2007-08-20 22:48:41 +00002479 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002480 pBt->db = p->db;
drh80e35f42007-03-30 14:06:34 +00002481#ifndef SQLITE_OMIT_AUTOVACUUM
2482 if( pBt->autoVacuum ){
2483 rc = autoVacuumCommit(pBt, &nTrunc);
2484 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002485 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002486 return rc;
2487 }
2488 }
2489#endif
danielk1977f653d782008-03-20 11:04:21 +00002490 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, nTrunc, 0);
drhd677b3d2007-08-20 22:48:41 +00002491 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002492 }
2493 return rc;
2494}
2495
2496/*
drh2aa679f2001-06-25 02:11:07 +00002497** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00002498**
drh6e345992007-03-30 11:12:08 +00002499** This routine implements the second phase of a 2-phase commit. The
2500** sqlite3BtreeSync() routine does the first phase and should be invoked
2501** prior to calling this routine. The sqlite3BtreeSync() routine did
2502** all the work of writing information out to disk and flushing the
2503** contents so that they are written onto the disk platter. All this
2504** routine has to do is delete or truncate the rollback journal
2505** (which causes the transaction to commit) and drop locks.
2506**
drh5e00f6c2001-09-13 13:46:56 +00002507** This will release the write lock on the database file. If there
2508** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002509*/
drh80e35f42007-03-30 14:06:34 +00002510int sqlite3BtreeCommitPhaseTwo(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002511 BtShared *pBt = p->pBt;
2512
drhd677b3d2007-08-20 22:48:41 +00002513 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002514 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00002515 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002516
2517 /* If the handle has a write-transaction open, commit the shared-btrees
2518 ** transaction and set the shared state to TRANS_READ.
2519 */
2520 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00002521 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002522 assert( pBt->inTransaction==TRANS_WRITE );
2523 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00002524 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
danielk19777f7bc662006-01-23 13:47:47 +00002525 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002526 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002527 return rc;
2528 }
danielk1977aef0bf62005-12-30 16:28:01 +00002529 pBt->inTransaction = TRANS_READ;
2530 pBt->inStmt = 0;
danielk1977ee5741e2004-05-31 10:01:34 +00002531 }
danielk19777f7bc662006-01-23 13:47:47 +00002532 unlockAllTables(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002533
2534 /* If the handle has any kind of transaction open, decrement the transaction
2535 ** count of the shared btree. If the transaction count reaches 0, set
2536 ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
2537 ** will unlock the pager.
2538 */
2539 if( p->inTrans!=TRANS_NONE ){
2540 pBt->nTransaction--;
2541 if( 0==pBt->nTransaction ){
2542 pBt->inTransaction = TRANS_NONE;
2543 }
2544 }
2545
2546 /* Set the handles current transaction state to TRANS_NONE and unlock
2547 ** the pager if this call closed the only read or write transaction.
2548 */
2549 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00002550 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002551
2552 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002553 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002554 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002555}
2556
drh80e35f42007-03-30 14:06:34 +00002557/*
2558** Do both phases of a commit.
2559*/
2560int sqlite3BtreeCommit(Btree *p){
2561 int rc;
drhd677b3d2007-08-20 22:48:41 +00002562 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00002563 rc = sqlite3BtreeCommitPhaseOne(p, 0);
2564 if( rc==SQLITE_OK ){
2565 rc = sqlite3BtreeCommitPhaseTwo(p);
2566 }
drhd677b3d2007-08-20 22:48:41 +00002567 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002568 return rc;
2569}
2570
danielk1977fbcd5852004-06-15 02:44:18 +00002571#ifndef NDEBUG
2572/*
2573** Return the number of write-cursors open on this handle. This is for use
2574** in assert() expressions, so it is only compiled if NDEBUG is not
2575** defined.
drhfb982642007-08-30 01:19:59 +00002576**
2577** For the purposes of this routine, a write-cursor is any cursor that
2578** is capable of writing to the databse. That means the cursor was
2579** originally opened for writing and the cursor has not be disabled
2580** by having its state changed to CURSOR_FAULT.
danielk1977fbcd5852004-06-15 02:44:18 +00002581*/
danielk1977aef0bf62005-12-30 16:28:01 +00002582static int countWriteCursors(BtShared *pBt){
danielk1977fbcd5852004-06-15 02:44:18 +00002583 BtCursor *pCur;
2584 int r = 0;
2585 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drhfb982642007-08-30 01:19:59 +00002586 if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
danielk1977fbcd5852004-06-15 02:44:18 +00002587 }
2588 return r;
2589}
2590#endif
2591
drhc39e0002004-05-07 23:50:57 +00002592/*
drhfb982642007-08-30 01:19:59 +00002593** This routine sets the state to CURSOR_FAULT and the error
2594** code to errCode for every cursor on BtShared that pBtree
2595** references.
2596**
2597** Every cursor is tripped, including cursors that belong
2598** to other database connections that happen to be sharing
2599** the cache with pBtree.
2600**
2601** This routine gets called when a rollback occurs.
2602** All cursors using the same cache must be tripped
2603** to prevent them from trying to use the btree after
2604** the rollback. The rollback may have deleted tables
2605** or moved root pages, so it is not sufficient to
2606** save the state of the cursor. The cursor must be
2607** invalidated.
2608*/
2609void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
2610 BtCursor *p;
2611 sqlite3BtreeEnter(pBtree);
2612 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
danielk1977bc2ca9e2008-11-13 14:28:28 +00002613 int i;
danielk1977be51a652008-10-08 17:58:48 +00002614 sqlite3BtreeClearCursor(p);
drhfb982642007-08-30 01:19:59 +00002615 p->eState = CURSOR_FAULT;
2616 p->skip = errCode;
danielk1977bc2ca9e2008-11-13 14:28:28 +00002617 for(i=0; i<=p->iPage; i++){
2618 releasePage(p->apPage[i]);
2619 p->apPage[i] = 0;
2620 }
drhfb982642007-08-30 01:19:59 +00002621 }
2622 sqlite3BtreeLeave(pBtree);
2623}
2624
2625/*
drhecdc7532001-09-23 02:35:53 +00002626** Rollback the transaction in progress. All cursors will be
2627** invalided by this operation. Any attempt to use a cursor
2628** that was open at the beginning of this operation will result
2629** in an error.
drh5e00f6c2001-09-13 13:46:56 +00002630**
2631** This will release the write lock on the database file. If there
2632** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002633*/
danielk1977aef0bf62005-12-30 16:28:01 +00002634int sqlite3BtreeRollback(Btree *p){
danielk19778d34dfd2006-01-24 16:37:57 +00002635 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002636 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00002637 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00002638
drhd677b3d2007-08-20 22:48:41 +00002639 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002640 pBt->db = p->db;
danielk19772b8c13e2006-01-24 14:21:24 +00002641 rc = saveAllCursors(pBt, 0, 0);
danielk19778d34dfd2006-01-24 16:37:57 +00002642#ifndef SQLITE_OMIT_SHARED_CACHE
danielk19772b8c13e2006-01-24 14:21:24 +00002643 if( rc!=SQLITE_OK ){
danielk19778d34dfd2006-01-24 16:37:57 +00002644 /* This is a horrible situation. An IO or malloc() error occured whilst
2645 ** trying to save cursor positions. If this is an automatic rollback (as
2646 ** the result of a constraint, malloc() failure or IO error) then
2647 ** the cache may be internally inconsistent (not contain valid trees) so
2648 ** we cannot simply return the error to the caller. Instead, abort
2649 ** all queries that may be using any of the cursors that failed to save.
2650 */
drhfb982642007-08-30 01:19:59 +00002651 sqlite3BtreeTripAllCursors(p, rc);
danielk19772b8c13e2006-01-24 14:21:24 +00002652 }
danielk19778d34dfd2006-01-24 16:37:57 +00002653#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002654 btreeIntegrity(p);
2655 unlockAllTables(p);
2656
2657 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00002658 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00002659
danielk1977dddbcdc2007-04-26 14:42:34 +00002660#ifndef SQLITE_OMIT_AUTOVACUUM
2661 pBt->nTrunc = 0;
2662#endif
2663
danielk19778d34dfd2006-01-24 16:37:57 +00002664 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00002665 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00002666 if( rc2!=SQLITE_OK ){
2667 rc = rc2;
2668 }
2669
drh24cd67e2004-05-10 16:18:47 +00002670 /* The rollback may have destroyed the pPage1->aData value. So
drh16a9b832007-05-05 18:39:25 +00002671 ** call sqlite3BtreeGetPage() on page 1 again to make
2672 ** sure pPage1->aData is set correctly. */
2673 if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh24cd67e2004-05-10 16:18:47 +00002674 releasePage(pPage1);
2675 }
danielk1977fbcd5852004-06-15 02:44:18 +00002676 assert( countWriteCursors(pBt)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002677 pBt->inTransaction = TRANS_READ;
drh24cd67e2004-05-10 16:18:47 +00002678 }
danielk1977aef0bf62005-12-30 16:28:01 +00002679
2680 if( p->inTrans!=TRANS_NONE ){
2681 assert( pBt->nTransaction>0 );
2682 pBt->nTransaction--;
2683 if( 0==pBt->nTransaction ){
2684 pBt->inTransaction = TRANS_NONE;
2685 }
2686 }
2687
2688 p->inTrans = TRANS_NONE;
danielk1977ee5741e2004-05-31 10:01:34 +00002689 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00002690 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002691
2692 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002693 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00002694 return rc;
2695}
2696
2697/*
drhab01f612004-05-22 02:55:23 +00002698** Start a statement subtransaction. The subtransaction can
2699** can be rolled back independently of the main transaction.
2700** You must start a transaction before starting a subtransaction.
2701** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00002702** commits or rolls back.
2703**
drhab01f612004-05-22 02:55:23 +00002704** Only one subtransaction may be active at a time. It is an error to try
2705** to start a new subtransaction if another subtransaction is already active.
2706**
2707** Statement subtransactions are used around individual SQL statements
2708** that are contained within a BEGIN...COMMIT block. If a constraint
2709** error occurs within the statement, the effect of that one statement
2710** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00002711*/
danielk1977aef0bf62005-12-30 16:28:01 +00002712int sqlite3BtreeBeginStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002713 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002714 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002715 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002716 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00002717 if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
drhd677b3d2007-08-20 22:48:41 +00002718 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
2719 }else{
2720 assert( pBt->inTransaction==TRANS_WRITE );
2721 rc = pBt->readOnly ? SQLITE_OK : sqlite3PagerStmtBegin(pBt->pPager);
2722 pBt->inStmt = 1;
drh0d65dc02002-02-03 00:56:09 +00002723 }
drhd677b3d2007-08-20 22:48:41 +00002724 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002725 return rc;
2726}
2727
2728
2729/*
drhab01f612004-05-22 02:55:23 +00002730** Commit the statment subtransaction currently in progress. If no
2731** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00002732*/
danielk1977aef0bf62005-12-30 16:28:01 +00002733int sqlite3BtreeCommitStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002734 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002735 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002736 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002737 pBt->db = p->db;
drh3aac2dd2004-04-26 14:10:20 +00002738 if( pBt->inStmt && !pBt->readOnly ){
danielk19773b8a05f2007-03-19 17:44:26 +00002739 rc = sqlite3PagerStmtCommit(pBt->pPager);
drh663fc632002-02-02 18:49:19 +00002740 }else{
2741 rc = SQLITE_OK;
2742 }
drh3aac2dd2004-04-26 14:10:20 +00002743 pBt->inStmt = 0;
drhd677b3d2007-08-20 22:48:41 +00002744 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002745 return rc;
2746}
2747
2748/*
drhab01f612004-05-22 02:55:23 +00002749** Rollback the active statement subtransaction. If no subtransaction
2750** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00002751**
drhab01f612004-05-22 02:55:23 +00002752** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00002753** to use a cursor that was open at the beginning of this operation
2754** will result in an error.
2755*/
danielk1977aef0bf62005-12-30 16:28:01 +00002756int sqlite3BtreeRollbackStmt(Btree *p){
danielk197797a227c2006-01-20 16:32:04 +00002757 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002758 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002759 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002760 pBt->db = p->db;
danielk197797a227c2006-01-20 16:32:04 +00002761 if( pBt->inStmt && !pBt->readOnly ){
danielk19773b8a05f2007-03-19 17:44:26 +00002762 rc = sqlite3PagerStmtRollback(pBt->pPager);
danielk197797a227c2006-01-20 16:32:04 +00002763 pBt->inStmt = 0;
2764 }
drhd677b3d2007-08-20 22:48:41 +00002765 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002766 return rc;
2767}
2768
2769/*
drh8b2f49b2001-06-08 00:21:52 +00002770** Create a new cursor for the BTree whose root is on the page
2771** iTable. The act of acquiring a cursor gets a read lock on
2772** the database file.
drh1bee3d72001-10-15 00:44:35 +00002773**
2774** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00002775** If wrFlag==1, then the cursor can be used for reading or for
2776** writing if other conditions for writing are also met. These
2777** are the conditions that must be met in order for writing to
2778** be allowed:
drh6446c4d2001-12-15 14:22:18 +00002779**
drhf74b8d92002-09-01 23:20:45 +00002780** 1: The cursor must have been opened with wrFlag==1
2781**
drhfe5d71d2007-03-19 11:54:10 +00002782** 2: Other database connections that share the same pager cache
2783** but which are not in the READ_UNCOMMITTED state may not have
2784** cursors open with wrFlag==0 on the same table. Otherwise
2785** the changes made by this write cursor would be visible to
2786** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00002787**
2788** 3: The database must be writable (not on read-only media)
2789**
2790** 4: There must be an active transaction.
2791**
drh6446c4d2001-12-15 14:22:18 +00002792** No checking is done to make sure that page iTable really is the
2793** root page of a b-tree. If it is not, then the cursor acquired
2794** will not work correctly.
danielk197771d5d2c2008-09-29 11:49:47 +00002795**
2796** It is assumed that the sqlite3BtreeCursorSize() bytes of memory
2797** pointed to by pCur have been zeroed by the caller.
drha059ad02001-04-17 20:09:11 +00002798*/
drhd677b3d2007-08-20 22:48:41 +00002799static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00002800 Btree *p, /* The btree */
2801 int iTable, /* Root page of table to open */
2802 int wrFlag, /* 1 to write. 0 read-only */
2803 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
2804 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00002805){
drha059ad02001-04-17 20:09:11 +00002806 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002807 BtShared *pBt = p->pBt;
drhecdc7532001-09-23 02:35:53 +00002808
drh1fee73e2007-08-29 04:00:57 +00002809 assert( sqlite3BtreeHoldsMutex(p) );
drh8dcd7ca2004-08-08 19:43:29 +00002810 if( wrFlag ){
drh8dcd7ca2004-08-08 19:43:29 +00002811 if( pBt->readOnly ){
2812 return SQLITE_READONLY;
2813 }
danielk19773588ceb2008-06-10 17:30:26 +00002814 if( checkReadLocks(p, iTable, 0, 0) ){
drh8dcd7ca2004-08-08 19:43:29 +00002815 return SQLITE_LOCKED;
2816 }
drha0c9a112004-03-10 13:42:37 +00002817 }
danielk1977aef0bf62005-12-30 16:28:01 +00002818
drh4b70f112004-05-02 21:12:19 +00002819 if( pBt->pPage1==0 ){
danielk1977aef0bf62005-12-30 16:28:01 +00002820 rc = lockBtreeWithRetry(p);
drha059ad02001-04-17 20:09:11 +00002821 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00002822 return rc;
2823 }
drh1831f182007-04-24 17:35:59 +00002824 if( pBt->readOnly && wrFlag ){
2825 return SQLITE_READONLY;
2826 }
drha059ad02001-04-17 20:09:11 +00002827 }
drh8b2f49b2001-06-08 00:21:52 +00002828 pCur->pgnoRoot = (Pgno)iTable;
danielk1977ad0132d2008-06-07 08:58:22 +00002829 if( iTable==1 && pagerPagecount(pBt->pPager)==0 ){
drh24cd67e2004-05-10 16:18:47 +00002830 rc = SQLITE_EMPTY;
2831 goto create_cursor_exception;
2832 }
danielk197771d5d2c2008-09-29 11:49:47 +00002833 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
drhbd03cae2001-06-02 02:40:57 +00002834 if( rc!=SQLITE_OK ){
2835 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00002836 }
danielk1977aef0bf62005-12-30 16:28:01 +00002837
danielk1977aef0bf62005-12-30 16:28:01 +00002838 /* Now that no other errors can occur, finish filling in the BtCursor
2839 ** variables, link the cursor into the BtShared list and set *ppCur (the
2840 ** output argument to this function).
2841 */
drh1e968a02008-03-25 00:22:21 +00002842 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00002843 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00002844 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +00002845 pCur->wrFlag = wrFlag;
drha059ad02001-04-17 20:09:11 +00002846 pCur->pNext = pBt->pCursor;
2847 if( pCur->pNext ){
2848 pCur->pNext->pPrev = pCur;
2849 }
2850 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00002851 pCur->eState = CURSOR_INVALID;
drhbd03cae2001-06-02 02:40:57 +00002852
danielk1977aef0bf62005-12-30 16:28:01 +00002853 return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00002854
drhbd03cae2001-06-02 02:40:57 +00002855create_cursor_exception:
danielk197771d5d2c2008-09-29 11:49:47 +00002856 releasePage(pCur->apPage[0]);
drh5e00f6c2001-09-13 13:46:56 +00002857 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00002858 return rc;
drha059ad02001-04-17 20:09:11 +00002859}
drhd677b3d2007-08-20 22:48:41 +00002860int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00002861 Btree *p, /* The btree */
2862 int iTable, /* Root page of table to open */
2863 int wrFlag, /* 1 to write. 0 read-only */
2864 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
2865 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00002866){
2867 int rc;
2868 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002869 p->pBt->db = p->db;
danielk1977cd3e8f72008-03-25 09:47:35 +00002870 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
drhd677b3d2007-08-20 22:48:41 +00002871 sqlite3BtreeLeave(p);
2872 return rc;
2873}
danielk1977cd3e8f72008-03-25 09:47:35 +00002874int sqlite3BtreeCursorSize(){
2875 return sizeof(BtCursor);
2876}
2877
drhd677b3d2007-08-20 22:48:41 +00002878
drha059ad02001-04-17 20:09:11 +00002879
2880/*
drh5e00f6c2001-09-13 13:46:56 +00002881** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00002882** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00002883*/
drh3aac2dd2004-04-26 14:10:20 +00002884int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00002885 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00002886 if( pBtree ){
danielk197771d5d2c2008-09-29 11:49:47 +00002887 int i;
danielk1977cd3e8f72008-03-25 09:47:35 +00002888 BtShared *pBt = pCur->pBt;
2889 sqlite3BtreeEnter(pBtree);
2890 pBt->db = pBtree->db;
danielk1977be51a652008-10-08 17:58:48 +00002891 sqlite3BtreeClearCursor(pCur);
danielk1977cd3e8f72008-03-25 09:47:35 +00002892 if( pCur->pPrev ){
2893 pCur->pPrev->pNext = pCur->pNext;
2894 }else{
2895 pBt->pCursor = pCur->pNext;
2896 }
2897 if( pCur->pNext ){
2898 pCur->pNext->pPrev = pCur->pPrev;
2899 }
danielk197771d5d2c2008-09-29 11:49:47 +00002900 for(i=0; i<=pCur->iPage; i++){
2901 releasePage(pCur->apPage[i]);
2902 }
danielk1977cd3e8f72008-03-25 09:47:35 +00002903 unlockBtreeIfUnused(pBt);
2904 invalidateOverflowCache(pCur);
2905 /* sqlite3_free(pCur); */
2906 sqlite3BtreeLeave(pBtree);
drha059ad02001-04-17 20:09:11 +00002907 }
drh8c42ca92001-06-22 19:15:00 +00002908 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002909}
2910
drh7e3b0a02001-04-28 16:52:40 +00002911/*
drh5e2f8b92001-05-28 00:41:15 +00002912** Make a temporary cursor by filling in the fields of pTempCur.
2913** The temporary cursor is not on the cursor list for the Btree.
2914*/
drh16a9b832007-05-05 18:39:25 +00002915void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
danielk197771d5d2c2008-09-29 11:49:47 +00002916 int i;
drh1fee73e2007-08-29 04:00:57 +00002917 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00002918 memcpy(pTempCur, pCur, sizeof(BtCursor));
drh5e2f8b92001-05-28 00:41:15 +00002919 pTempCur->pNext = 0;
2920 pTempCur->pPrev = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00002921 for(i=0; i<=pTempCur->iPage; i++){
2922 sqlite3PagerRef(pTempCur->apPage[i]->pDbPage);
drhecdc7532001-09-23 02:35:53 +00002923 }
drh5e2f8b92001-05-28 00:41:15 +00002924}
2925
2926/*
drhbd03cae2001-06-02 02:40:57 +00002927** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00002928** function above.
2929*/
drh16a9b832007-05-05 18:39:25 +00002930void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
danielk197771d5d2c2008-09-29 11:49:47 +00002931 int i;
drh1fee73e2007-08-29 04:00:57 +00002932 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00002933 for(i=0; i<=pCur->iPage; i++){
2934 sqlite3PagerUnref(pCur->apPage[i]->pDbPage);
drhecdc7532001-09-23 02:35:53 +00002935 }
drh5e2f8b92001-05-28 00:41:15 +00002936}
2937
2938/*
drh86057612007-06-26 01:04:48 +00002939** Make sure the BtCursor* given in the argument has a valid
2940** BtCursor.info structure. If it is not already valid, call
danielk19771cc5ed82007-05-16 17:28:43 +00002941** sqlite3BtreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00002942**
2943** BtCursor.info is a cache of the information in the current cell.
drh16a9b832007-05-05 18:39:25 +00002944** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
drh86057612007-06-26 01:04:48 +00002945**
2946** 2007-06-25: There is a bug in some versions of MSVC that cause the
2947** compiler to crash when getCellInfo() is implemented as a macro.
2948** But there is a measureable speed advantage to using the macro on gcc
2949** (when less compiler optimizations like -Os or -O0 are used and the
2950** compiler is not doing agressive inlining.) So we use a real function
2951** for MSVC and a macro for everything else. Ticket #2457.
drh9188b382004-05-14 21:12:22 +00002952*/
drh9188b382004-05-14 21:12:22 +00002953#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00002954 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00002955 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00002956 int iPage = pCur->iPage;
drh51c6d962004-06-06 00:42:25 +00002957 memset(&info, 0, sizeof(info));
danielk197771d5d2c2008-09-29 11:49:47 +00002958 sqlite3BtreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
drh9188b382004-05-14 21:12:22 +00002959 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00002960 }
danielk19771cc5ed82007-05-16 17:28:43 +00002961#else
2962 #define assertCellInfo(x)
2963#endif
drh86057612007-06-26 01:04:48 +00002964#ifdef _MSC_VER
2965 /* Use a real function in MSVC to work around bugs in that compiler. */
2966 static void getCellInfo(BtCursor *pCur){
2967 if( pCur->info.nSize==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00002968 int iPage = pCur->iPage;
2969 sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
drha2c20e42008-03-29 16:01:04 +00002970 pCur->validNKey = 1;
drh86057612007-06-26 01:04:48 +00002971 }else{
2972 assertCellInfo(pCur);
2973 }
2974 }
2975#else /* if not _MSC_VER */
2976 /* Use a macro in all other compilers so that the function is inlined */
danielk197771d5d2c2008-09-29 11:49:47 +00002977#define getCellInfo(pCur) \
2978 if( pCur->info.nSize==0 ){ \
2979 int iPage = pCur->iPage; \
2980 sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
2981 pCur->validNKey = 1; \
2982 }else{ \
2983 assertCellInfo(pCur); \
drh86057612007-06-26 01:04:48 +00002984 }
2985#endif /* _MSC_VER */
drh9188b382004-05-14 21:12:22 +00002986
2987/*
drh3aac2dd2004-04-26 14:10:20 +00002988** Set *pSize to the size of the buffer needed to hold the value of
2989** the key for the current entry. If the cursor is not pointing
2990** to a valid entry, *pSize is set to 0.
2991**
drh4b70f112004-05-02 21:12:19 +00002992** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00002993** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00002994*/
drh4a1c3802004-05-12 15:15:47 +00002995int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drhd677b3d2007-08-20 22:48:41 +00002996 int rc;
2997
drh1fee73e2007-08-29 04:00:57 +00002998 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00002999 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003000 if( rc==SQLITE_OK ){
3001 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3002 if( pCur->eState==CURSOR_INVALID ){
3003 *pSize = 0;
3004 }else{
drh86057612007-06-26 01:04:48 +00003005 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00003006 *pSize = pCur->info.nKey;
3007 }
drh72f82862001-05-24 21:06:34 +00003008 }
danielk1977da184232006-01-05 11:34:32 +00003009 return rc;
drha059ad02001-04-17 20:09:11 +00003010}
drh2af926b2001-05-15 00:39:25 +00003011
drh72f82862001-05-24 21:06:34 +00003012/*
drh0e1c19e2004-05-11 00:58:56 +00003013** Set *pSize to the number of bytes of data in the entry the
3014** cursor currently points to. Always return SQLITE_OK.
3015** Failure is not possible. If the cursor is not currently
3016** pointing to an entry (which can happen, for example, if
3017** the database is empty) then *pSize is set to 0.
3018*/
3019int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drhd677b3d2007-08-20 22:48:41 +00003020 int rc;
3021
drh1fee73e2007-08-29 04:00:57 +00003022 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003023 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003024 if( rc==SQLITE_OK ){
3025 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3026 if( pCur->eState==CURSOR_INVALID ){
3027 /* Not pointing at a valid entry - set *pSize to 0. */
3028 *pSize = 0;
3029 }else{
drh86057612007-06-26 01:04:48 +00003030 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00003031 *pSize = pCur->info.nData;
3032 }
drh0e1c19e2004-05-11 00:58:56 +00003033 }
danielk1977da184232006-01-05 11:34:32 +00003034 return rc;
drh0e1c19e2004-05-11 00:58:56 +00003035}
3036
3037/*
danielk1977d04417962007-05-02 13:16:30 +00003038** Given the page number of an overflow page in the database (parameter
3039** ovfl), this function finds the page number of the next page in the
3040** linked list of overflow pages. If possible, it uses the auto-vacuum
3041** pointer-map data instead of reading the content of page ovfl to do so.
3042**
3043** If an error occurs an SQLite error code is returned. Otherwise:
3044**
3045** Unless pPgnoNext is NULL, the page number of the next overflow
3046** page in the linked list is written to *pPgnoNext. If page ovfl
drh85b623f2007-12-13 21:54:09 +00003047** is the last page in its linked list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003048**
3049** If ppPage is not NULL, *ppPage is set to the MemPage* handle
3050** for page ovfl. The underlying pager page may have been requested
3051** with the noContent flag set, so the page data accessable via
3052** this handle may not be trusted.
3053*/
3054static int getOverflowPage(
3055 BtShared *pBt,
3056 Pgno ovfl, /* Overflow page */
3057 MemPage **ppPage, /* OUT: MemPage handle */
3058 Pgno *pPgnoNext /* OUT: Next overflow page number */
3059){
3060 Pgno next = 0;
3061 int rc;
3062
drh1fee73e2007-08-29 04:00:57 +00003063 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977d04417962007-05-02 13:16:30 +00003064 /* One of these must not be NULL. Otherwise, why call this function? */
3065 assert(ppPage || pPgnoNext);
3066
3067 /* If pPgnoNext is NULL, then this function is being called to obtain
3068 ** a MemPage* reference only. No page-data is required in this case.
3069 */
3070 if( !pPgnoNext ){
drh16a9b832007-05-05 18:39:25 +00003071 return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1);
danielk1977d04417962007-05-02 13:16:30 +00003072 }
3073
3074#ifndef SQLITE_OMIT_AUTOVACUUM
3075 /* Try to find the next page in the overflow list using the
3076 ** autovacuum pointer-map pages. Guess that the next page in
3077 ** the overflow list is page number (ovfl+1). If that guess turns
3078 ** out to be wrong, fall back to loading the data of page
3079 ** number ovfl to determine the next page number.
3080 */
3081 if( pBt->autoVacuum ){
3082 Pgno pgno;
3083 Pgno iGuess = ovfl+1;
3084 u8 eType;
3085
3086 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
3087 iGuess++;
3088 }
3089
danielk1977ad0132d2008-06-07 08:58:22 +00003090 if( iGuess<=pagerPagecount(pBt->pPager) ){
danielk1977d04417962007-05-02 13:16:30 +00003091 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
3092 if( rc!=SQLITE_OK ){
3093 return rc;
3094 }
3095 if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
3096 next = iGuess;
3097 }
3098 }
3099 }
3100#endif
3101
3102 if( next==0 || ppPage ){
3103 MemPage *pPage = 0;
3104
drh16a9b832007-05-05 18:39:25 +00003105 rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0);
danielk1977d04417962007-05-02 13:16:30 +00003106 assert(rc==SQLITE_OK || pPage==0);
3107 if( next==0 && rc==SQLITE_OK ){
3108 next = get4byte(pPage->aData);
3109 }
3110
3111 if( ppPage ){
3112 *ppPage = pPage;
3113 }else{
3114 releasePage(pPage);
3115 }
3116 }
3117 *pPgnoNext = next;
3118
3119 return rc;
3120}
3121
danielk1977da107192007-05-04 08:32:13 +00003122/*
3123** Copy data from a buffer to a page, or from a page to a buffer.
3124**
3125** pPayload is a pointer to data stored on database page pDbPage.
3126** If argument eOp is false, then nByte bytes of data are copied
3127** from pPayload to the buffer pointed at by pBuf. If eOp is true,
3128** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
3129** of data are copied from the buffer pBuf to pPayload.
3130**
3131** SQLITE_OK is returned on success, otherwise an error code.
3132*/
3133static int copyPayload(
3134 void *pPayload, /* Pointer to page data */
3135 void *pBuf, /* Pointer to buffer */
3136 int nByte, /* Number of bytes to copy */
3137 int eOp, /* 0 -> copy from page, 1 -> copy to page */
3138 DbPage *pDbPage /* Page containing pPayload */
3139){
3140 if( eOp ){
3141 /* Copy data from buffer to page (a write operation) */
3142 int rc = sqlite3PagerWrite(pDbPage);
3143 if( rc!=SQLITE_OK ){
3144 return rc;
3145 }
3146 memcpy(pPayload, pBuf, nByte);
3147 }else{
3148 /* Copy data from page to buffer (a read operation) */
3149 memcpy(pBuf, pPayload, nByte);
3150 }
3151 return SQLITE_OK;
3152}
danielk1977d04417962007-05-02 13:16:30 +00003153
3154/*
danielk19779f8d6402007-05-02 17:48:45 +00003155** This function is used to read or overwrite payload information
3156** for the entry that the pCur cursor is pointing to. If the eOp
3157** parameter is 0, this is a read operation (data copied into
3158** buffer pBuf). If it is non-zero, a write (data copied from
3159** buffer pBuf).
3160**
3161** A total of "amt" bytes are read or written beginning at "offset".
3162** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00003163**
3164** This routine does not make a distinction between key and data.
danielk19779f8d6402007-05-02 17:48:45 +00003165** It just reads or writes bytes from the payload area. Data might
3166** appear on the main page or be scattered out on multiple overflow
3167** pages.
danielk1977da107192007-05-04 08:32:13 +00003168**
danielk1977dcbb5d32007-05-04 18:36:44 +00003169** If the BtCursor.isIncrblobHandle flag is set, and the current
danielk1977da107192007-05-04 08:32:13 +00003170** cursor entry uses one or more overflow pages, this function
3171** allocates space for and lazily popluates the overflow page-list
3172** cache array (BtCursor.aOverflow). Subsequent calls use this
3173** cache to make seeking to the supplied offset more efficient.
3174**
3175** Once an overflow page-list cache has been allocated, it may be
3176** invalidated if some other cursor writes to the same table, or if
3177** the cursor is moved to a different row. Additionally, in auto-vacuum
3178** mode, the following events may invalidate an overflow page-list cache.
3179**
3180** * An incremental vacuum,
3181** * A commit in auto_vacuum="full" mode,
3182** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00003183*/
danielk19779f8d6402007-05-02 17:48:45 +00003184static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00003185 BtCursor *pCur, /* Cursor pointing to entry to read from */
3186 int offset, /* Begin reading this far into payload */
3187 int amt, /* Read this many bytes */
3188 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00003189 int skipKey, /* offset begins at data if this is true */
3190 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00003191){
3192 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00003193 int rc = SQLITE_OK;
drhfa1a98a2004-05-14 19:08:17 +00003194 u32 nKey;
danielk19772dec9702007-05-02 16:48:37 +00003195 int iIdx = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003196 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
danielk19770d065412008-11-12 18:21:36 +00003197 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
drh3aac2dd2004-04-26 14:10:20 +00003198
danielk1977da107192007-05-04 08:32:13 +00003199 assert( pPage );
danielk1977da184232006-01-05 11:34:32 +00003200 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003201 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
danielk1977da107192007-05-04 08:32:13 +00003202 assert( offset>=0 );
drh1fee73e2007-08-29 04:00:57 +00003203 assert( cursorHoldsMutex(pCur) );
danielk1977da107192007-05-04 08:32:13 +00003204
drh86057612007-06-26 01:04:48 +00003205 getCellInfo(pCur);
drh366fda62006-01-13 02:35:09 +00003206 aPayload = pCur->info.pCell + pCur->info.nHeader;
danielk1977da107192007-05-04 08:32:13 +00003207 nKey = (pPage->intKey ? 0 : pCur->info.nKey);
3208
drh3aac2dd2004-04-26 14:10:20 +00003209 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003210 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00003211 }
danielk19770d065412008-11-12 18:21:36 +00003212 if( offset+amt > nKey+pCur->info.nData
3213 || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
3214 ){
danielk1977da107192007-05-04 08:32:13 +00003215 /* Trying to read or write past the end of the data is an error */
danielk197767fd7a92008-09-10 17:53:35 +00003216 return SQLITE_CORRUPT_BKPT;
drh3aac2dd2004-04-26 14:10:20 +00003217 }
danielk1977da107192007-05-04 08:32:13 +00003218
3219 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00003220 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00003221 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00003222 if( a+offset>pCur->info.nLocal ){
3223 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00003224 }
danielk1977da107192007-05-04 08:32:13 +00003225 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00003226 offset = 0;
drha34b6762004-05-07 13:30:42 +00003227 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00003228 amt -= a;
drhdd793422001-06-28 01:54:48 +00003229 }else{
drhfa1a98a2004-05-14 19:08:17 +00003230 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00003231 }
danielk1977da107192007-05-04 08:32:13 +00003232
3233 if( rc==SQLITE_OK && amt>0 ){
3234 const int ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
3235 Pgno nextPage;
3236
drhfa1a98a2004-05-14 19:08:17 +00003237 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00003238
danielk19772dec9702007-05-02 16:48:37 +00003239#ifndef SQLITE_OMIT_INCRBLOB
danielk1977dcbb5d32007-05-04 18:36:44 +00003240 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
danielk1977da107192007-05-04 08:32:13 +00003241 ** has not been allocated, allocate it now. The array is sized at
3242 ** one entry for each overflow page in the overflow chain. The
3243 ** page number of the first overflow page is stored in aOverflow[0],
3244 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
3245 ** (the cache is lazily populated).
3246 */
danielk1977dcbb5d32007-05-04 18:36:44 +00003247 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
danielk19772dec9702007-05-02 16:48:37 +00003248 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
drh17435752007-08-16 04:30:38 +00003249 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
danielk19772dec9702007-05-02 16:48:37 +00003250 if( nOvfl && !pCur->aOverflow ){
danielk1977da107192007-05-04 08:32:13 +00003251 rc = SQLITE_NOMEM;
danielk19772dec9702007-05-02 16:48:37 +00003252 }
3253 }
danielk1977da107192007-05-04 08:32:13 +00003254
3255 /* If the overflow page-list cache has been allocated and the
3256 ** entry for the first required overflow page is valid, skip
3257 ** directly to it.
3258 */
danielk19772dec9702007-05-02 16:48:37 +00003259 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
3260 iIdx = (offset/ovflSize);
3261 nextPage = pCur->aOverflow[iIdx];
3262 offset = (offset%ovflSize);
3263 }
3264#endif
danielk1977da107192007-05-04 08:32:13 +00003265
3266 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
3267
3268#ifndef SQLITE_OMIT_INCRBLOB
3269 /* If required, populate the overflow page-list cache. */
3270 if( pCur->aOverflow ){
3271 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
3272 pCur->aOverflow[iIdx] = nextPage;
3273 }
3274#endif
3275
danielk1977d04417962007-05-02 13:16:30 +00003276 if( offset>=ovflSize ){
3277 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00003278 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00003279 ** data is not required. So first try to lookup the overflow
3280 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00003281 ** function.
danielk1977d04417962007-05-02 13:16:30 +00003282 */
danielk19772dec9702007-05-02 16:48:37 +00003283#ifndef SQLITE_OMIT_INCRBLOB
danielk1977da107192007-05-04 08:32:13 +00003284 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
3285 nextPage = pCur->aOverflow[iIdx+1];
3286 } else
danielk19772dec9702007-05-02 16:48:37 +00003287#endif
danielk1977da107192007-05-04 08:32:13 +00003288 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
danielk1977da107192007-05-04 08:32:13 +00003289 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00003290 }else{
danielk19779f8d6402007-05-02 17:48:45 +00003291 /* Need to read this page properly. It contains some of the
3292 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00003293 */
3294 DbPage *pDbPage;
danielk1977cfe9a692004-06-16 12:00:29 +00003295 int a = amt;
danielk1977d04417962007-05-02 13:16:30 +00003296 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
danielk1977da107192007-05-04 08:32:13 +00003297 if( rc==SQLITE_OK ){
3298 aPayload = sqlite3PagerGetData(pDbPage);
3299 nextPage = get4byte(aPayload);
3300 if( a + offset > ovflSize ){
3301 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00003302 }
danielk1977da107192007-05-04 08:32:13 +00003303 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
3304 sqlite3PagerUnref(pDbPage);
3305 offset = 0;
3306 amt -= a;
3307 pBuf += a;
danielk19779f8d6402007-05-02 17:48:45 +00003308 }
danielk1977cfe9a692004-06-16 12:00:29 +00003309 }
drh2af926b2001-05-15 00:39:25 +00003310 }
drh2af926b2001-05-15 00:39:25 +00003311 }
danielk1977cfe9a692004-06-16 12:00:29 +00003312
danielk1977da107192007-05-04 08:32:13 +00003313 if( rc==SQLITE_OK && amt>0 ){
drh49285702005-09-17 15:20:26 +00003314 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00003315 }
danielk1977da107192007-05-04 08:32:13 +00003316 return rc;
drh2af926b2001-05-15 00:39:25 +00003317}
3318
drh72f82862001-05-24 21:06:34 +00003319/*
drh3aac2dd2004-04-26 14:10:20 +00003320** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003321** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003322** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00003323**
drh3aac2dd2004-04-26 14:10:20 +00003324** Return SQLITE_OK on success or an error code if anything goes
3325** wrong. An error is returned if "offset+amt" is larger than
3326** the available payload.
drh72f82862001-05-24 21:06:34 +00003327*/
drha34b6762004-05-07 13:30:42 +00003328int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003329 int rc;
3330
drh1fee73e2007-08-29 04:00:57 +00003331 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003332 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003333 if( rc==SQLITE_OK ){
3334 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003335 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3336 if( pCur->apPage[0]->intKey ){
danielk1977da184232006-01-05 11:34:32 +00003337 return SQLITE_CORRUPT_BKPT;
3338 }
danielk197771d5d2c2008-09-29 11:49:47 +00003339 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh16a9b832007-05-05 18:39:25 +00003340 rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
drh6575a222005-03-10 17:06:34 +00003341 }
danielk1977da184232006-01-05 11:34:32 +00003342 return rc;
drh3aac2dd2004-04-26 14:10:20 +00003343}
3344
3345/*
drh3aac2dd2004-04-26 14:10:20 +00003346** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003347** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003348** begins at "offset".
3349**
3350** Return SQLITE_OK on success or an error code if anything goes
3351** wrong. An error is returned if "offset+amt" is larger than
3352** the available payload.
drh72f82862001-05-24 21:06:34 +00003353*/
drh3aac2dd2004-04-26 14:10:20 +00003354int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003355 int rc;
3356
danielk19773588ceb2008-06-10 17:30:26 +00003357#ifndef SQLITE_OMIT_INCRBLOB
3358 if ( pCur->eState==CURSOR_INVALID ){
3359 return SQLITE_ABORT;
3360 }
3361#endif
3362
drh1fee73e2007-08-29 04:00:57 +00003363 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003364 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003365 if( rc==SQLITE_OK ){
3366 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003367 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3368 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh16a9b832007-05-05 18:39:25 +00003369 rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
danielk1977da184232006-01-05 11:34:32 +00003370 }
3371 return rc;
drh2af926b2001-05-15 00:39:25 +00003372}
3373
drh72f82862001-05-24 21:06:34 +00003374/*
drh0e1c19e2004-05-11 00:58:56 +00003375** Return a pointer to payload information from the entry that the
3376** pCur cursor is pointing to. The pointer is to the beginning of
3377** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00003378** skipKey==1. The number of bytes of available key/data is written
3379** into *pAmt. If *pAmt==0, then the value returned will not be
3380** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00003381**
3382** This routine is an optimization. It is common for the entire key
3383** and data to fit on the local page and for there to be no overflow
3384** pages. When that is so, this routine can be used to access the
3385** key and data without making a copy. If the key and/or data spills
drh16a9b832007-05-05 18:39:25 +00003386** onto overflow pages, then accessPayload() must be used to reassembly
drh0e1c19e2004-05-11 00:58:56 +00003387** the key/data and copy it into a preallocated buffer.
3388**
3389** The pointer returned by this routine looks directly into the cached
3390** page of the database. The data might change or move the next time
3391** any btree routine is called.
3392*/
3393static const unsigned char *fetchPayload(
3394 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00003395 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00003396 int skipKey /* read beginning at data if this is true */
3397){
3398 unsigned char *aPayload;
3399 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00003400 u32 nKey;
3401 int nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003402
danielk197771d5d2c2008-09-29 11:49:47 +00003403 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
danielk1977da184232006-01-05 11:34:32 +00003404 assert( pCur->eState==CURSOR_VALID );
drh1fee73e2007-08-29 04:00:57 +00003405 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00003406 pPage = pCur->apPage[pCur->iPage];
3407 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh86057612007-06-26 01:04:48 +00003408 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00003409 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00003410 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00003411 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00003412 nKey = 0;
3413 }else{
3414 nKey = pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00003415 }
drh0e1c19e2004-05-11 00:58:56 +00003416 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003417 aPayload += nKey;
3418 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00003419 }else{
drhfa1a98a2004-05-14 19:08:17 +00003420 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00003421 if( nLocal>nKey ){
3422 nLocal = nKey;
3423 }
drh0e1c19e2004-05-11 00:58:56 +00003424 }
drhe51c44f2004-05-30 20:46:09 +00003425 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003426 return aPayload;
3427}
3428
3429
3430/*
drhe51c44f2004-05-30 20:46:09 +00003431** For the entry that cursor pCur is point to, return as
3432** many bytes of the key or data as are available on the local
3433** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00003434**
3435** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00003436** or be destroyed on the next call to any Btree routine,
3437** including calls from other threads against the same cache.
3438** Hence, a mutex on the BtShared should be held prior to calling
3439** this routine.
drh0e1c19e2004-05-11 00:58:56 +00003440**
3441** These routines is used to get quick access to key and data
3442** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00003443*/
drhe51c44f2004-05-30 20:46:09 +00003444const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
drh1fee73e2007-08-29 04:00:57 +00003445 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003446 if( pCur->eState==CURSOR_VALID ){
3447 return (const void*)fetchPayload(pCur, pAmt, 0);
3448 }
3449 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003450}
drhe51c44f2004-05-30 20:46:09 +00003451const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
drh1fee73e2007-08-29 04:00:57 +00003452 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003453 if( pCur->eState==CURSOR_VALID ){
3454 return (const void*)fetchPayload(pCur, pAmt, 1);
3455 }
3456 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003457}
3458
3459
3460/*
drh8178a752003-01-05 21:41:40 +00003461** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00003462** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00003463*/
drh3aac2dd2004-04-26 14:10:20 +00003464static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00003465 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003466 int i = pCur->iPage;
drh72f82862001-05-24 21:06:34 +00003467 MemPage *pNewPage;
drhd0679ed2007-08-28 22:24:34 +00003468 BtShared *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00003469
drh1fee73e2007-08-29 04:00:57 +00003470 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003471 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003472 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
3473 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
3474 return SQLITE_CORRUPT_BKPT;
3475 }
3476 rc = getAndInitPage(pBt, newPgno, &pNewPage);
drh6019e162001-07-02 17:51:45 +00003477 if( rc ) return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003478 pCur->apPage[i+1] = pNewPage;
3479 pCur->aiIdx[i+1] = 0;
3480 pCur->iPage++;
3481
drh271efa52004-05-30 19:19:05 +00003482 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003483 pCur->validNKey = 0;
drh4be295b2003-12-16 03:44:47 +00003484 if( pNewPage->nCell<1 ){
drh49285702005-09-17 15:20:26 +00003485 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00003486 }
drh72f82862001-05-24 21:06:34 +00003487 return SQLITE_OK;
3488}
3489
danielk1977bf93c562008-09-29 15:53:25 +00003490#ifndef NDEBUG
3491/*
3492** Page pParent is an internal (non-leaf) tree page. This function
3493** asserts that page number iChild is the left-child if the iIdx'th
3494** cell in page pParent. Or, if iIdx is equal to the total number of
3495** cells in pParent, that page number iChild is the right-child of
3496** the page.
3497*/
3498static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
3499 assert( iIdx<=pParent->nCell );
3500 if( iIdx==pParent->nCell ){
3501 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
3502 }else{
3503 assert( get4byte(findCell(pParent, iIdx))==iChild );
3504 }
3505}
3506#else
3507# define assertParentIndex(x,y,z)
3508#endif
3509
drh72f82862001-05-24 21:06:34 +00003510/*
drh5e2f8b92001-05-28 00:41:15 +00003511** Move the cursor up to the parent page.
3512**
3513** pCur->idx is set to the cell index that contains the pointer
3514** to the page we are coming from. If we are coming from the
3515** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00003516** the largest cell index.
drh72f82862001-05-24 21:06:34 +00003517*/
drh16a9b832007-05-05 18:39:25 +00003518void sqlite3BtreeMoveToParent(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00003519 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003520 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003521 assert( pCur->iPage>0 );
3522 assert( pCur->apPage[pCur->iPage] );
danielk1977bf93c562008-09-29 15:53:25 +00003523 assertParentIndex(
3524 pCur->apPage[pCur->iPage-1],
3525 pCur->aiIdx[pCur->iPage-1],
3526 pCur->apPage[pCur->iPage]->pgno
3527 );
danielk197771d5d2c2008-09-29 11:49:47 +00003528 releasePage(pCur->apPage[pCur->iPage]);
3529 pCur->iPage--;
drh271efa52004-05-30 19:19:05 +00003530 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003531 pCur->validNKey = 0;
drh72f82862001-05-24 21:06:34 +00003532}
3533
3534/*
3535** Move the cursor to the root page
3536*/
drh5e2f8b92001-05-28 00:41:15 +00003537static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00003538 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00003539 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003540 Btree *p = pCur->pBtree;
3541 BtShared *pBt = p->pBt;
drhbd03cae2001-06-02 02:40:57 +00003542
drh1fee73e2007-08-29 04:00:57 +00003543 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +00003544 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
3545 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
3546 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
3547 if( pCur->eState>=CURSOR_REQUIRESEEK ){
3548 if( pCur->eState==CURSOR_FAULT ){
3549 return pCur->skip;
3550 }
danielk1977be51a652008-10-08 17:58:48 +00003551 sqlite3BtreeClearCursor(pCur);
drhbf700f32007-03-31 02:36:44 +00003552 }
danielk197771d5d2c2008-09-29 11:49:47 +00003553
3554 if( pCur->iPage>=0 ){
3555 int i;
3556 for(i=1; i<=pCur->iPage; i++){
3557 releasePage(pCur->apPage[i]);
danielk1977d9f6c532008-09-19 16:39:38 +00003558 }
drh777e4c42006-01-13 04:31:58 +00003559 }else{
3560 if(
danielk197771d5d2c2008-09-29 11:49:47 +00003561 SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]))
drh777e4c42006-01-13 04:31:58 +00003562 ){
3563 pCur->eState = CURSOR_INVALID;
3564 return rc;
3565 }
drhc39e0002004-05-07 23:50:57 +00003566 }
danielk197771d5d2c2008-09-29 11:49:47 +00003567
3568 pRoot = pCur->apPage[0];
3569 assert( pRoot->pgno==pCur->pgnoRoot );
3570 pCur->iPage = 0;
3571 pCur->aiIdx[0] = 0;
drh271efa52004-05-30 19:19:05 +00003572 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003573 pCur->atLast = 0;
3574 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003575
drh8856d6a2004-04-29 14:42:46 +00003576 if( pRoot->nCell==0 && !pRoot->leaf ){
3577 Pgno subpage;
3578 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00003579 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00003580 assert( subpage>0 );
danielk1977da184232006-01-05 11:34:32 +00003581 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00003582 rc = moveToChild(pCur, subpage);
danielk197771d5d2c2008-09-29 11:49:47 +00003583 }else{
3584 pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
drh8856d6a2004-04-29 14:42:46 +00003585 }
3586 return rc;
drh72f82862001-05-24 21:06:34 +00003587}
drh2af926b2001-05-15 00:39:25 +00003588
drh5e2f8b92001-05-28 00:41:15 +00003589/*
3590** Move the cursor down to the left-most leaf entry beneath the
3591** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00003592**
3593** The left-most leaf is the one with the smallest key - the first
3594** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00003595*/
3596static int moveToLeftmost(BtCursor *pCur){
3597 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00003598 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00003599 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00003600
drh1fee73e2007-08-29 04:00:57 +00003601 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003602 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003603 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
3604 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
3605 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
drh8178a752003-01-05 21:41:40 +00003606 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00003607 }
drhd677b3d2007-08-20 22:48:41 +00003608 return rc;
drh5e2f8b92001-05-28 00:41:15 +00003609}
3610
drh2dcc9aa2002-12-04 13:40:25 +00003611/*
3612** Move the cursor down to the right-most leaf entry beneath the
3613** page to which it is currently pointing. Notice the difference
3614** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
3615** finds the left-most entry beneath the *entry* whereas moveToRightmost()
3616** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00003617**
3618** The right-most entry is the one with the largest key - the last
3619** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00003620*/
3621static int moveToRightmost(BtCursor *pCur){
3622 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00003623 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00003624 MemPage *pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003625
drh1fee73e2007-08-29 04:00:57 +00003626 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003627 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003628 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
drh43605152004-05-29 21:46:49 +00003629 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
danielk197771d5d2c2008-09-29 11:49:47 +00003630 pCur->aiIdx[pCur->iPage] = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00003631 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003632 }
drhd677b3d2007-08-20 22:48:41 +00003633 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00003634 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
drhd677b3d2007-08-20 22:48:41 +00003635 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003636 pCur->validNKey = 0;
drhd677b3d2007-08-20 22:48:41 +00003637 }
danielk1977518002e2008-09-05 05:02:46 +00003638 return rc;
drh2dcc9aa2002-12-04 13:40:25 +00003639}
3640
drh5e00f6c2001-09-13 13:46:56 +00003641/* Move the cursor to the first entry in the table. Return SQLITE_OK
3642** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003643** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00003644*/
drh3aac2dd2004-04-26 14:10:20 +00003645int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00003646 int rc;
drhd677b3d2007-08-20 22:48:41 +00003647
drh1fee73e2007-08-29 04:00:57 +00003648 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003649 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00003650 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003651 if( rc==SQLITE_OK ){
3652 if( pCur->eState==CURSOR_INVALID ){
danielk197771d5d2c2008-09-29 11:49:47 +00003653 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00003654 *pRes = 1;
3655 rc = SQLITE_OK;
3656 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00003657 assert( pCur->apPage[pCur->iPage]->nCell>0 );
drhd677b3d2007-08-20 22:48:41 +00003658 *pRes = 0;
3659 rc = moveToLeftmost(pCur);
3660 }
drh5e00f6c2001-09-13 13:46:56 +00003661 }
drh5e00f6c2001-09-13 13:46:56 +00003662 return rc;
3663}
drh5e2f8b92001-05-28 00:41:15 +00003664
drh9562b552002-02-19 15:00:07 +00003665/* Move the cursor to the last entry in the table. Return SQLITE_OK
3666** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003667** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00003668*/
drh3aac2dd2004-04-26 14:10:20 +00003669int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00003670 int rc;
drhd677b3d2007-08-20 22:48:41 +00003671
drh1fee73e2007-08-29 04:00:57 +00003672 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003673 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh9562b552002-02-19 15:00:07 +00003674 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003675 if( rc==SQLITE_OK ){
3676 if( CURSOR_INVALID==pCur->eState ){
danielk197771d5d2c2008-09-29 11:49:47 +00003677 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00003678 *pRes = 1;
3679 }else{
3680 assert( pCur->eState==CURSOR_VALID );
3681 *pRes = 0;
3682 rc = moveToRightmost(pCur);
drha2c20e42008-03-29 16:01:04 +00003683 getCellInfo(pCur);
3684 pCur->atLast = rc==SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003685 }
drh9562b552002-02-19 15:00:07 +00003686 }
drh9562b552002-02-19 15:00:07 +00003687 return rc;
3688}
3689
drhe14006d2008-03-25 17:23:32 +00003690/* Move the cursor so that it points to an entry near the key
drhe63d9992008-08-13 19:11:48 +00003691** specified by pIdxKey or intKey. Return a success code.
drh72f82862001-05-24 21:06:34 +00003692**
drhe63d9992008-08-13 19:11:48 +00003693** For INTKEY tables, the intKey parameter is used. pIdxKey
3694** must be NULL. For index tables, pIdxKey is used and intKey
3695** is ignored.
drh3aac2dd2004-04-26 14:10:20 +00003696**
drh5e2f8b92001-05-28 00:41:15 +00003697** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00003698** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00003699** were present. The cursor might point to an entry that comes
3700** before or after the key.
3701**
drhbd03cae2001-06-02 02:40:57 +00003702** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00003703** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00003704** this value is as follows:
3705**
3706** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00003707** is smaller than pKey or if the table is empty
3708** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00003709**
3710** *pRes==0 The cursor is left pointing at an entry that
3711** exactly matches pKey.
3712**
3713** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00003714** is larger than pKey.
drhd677b3d2007-08-20 22:48:41 +00003715**
drha059ad02001-04-17 20:09:11 +00003716*/
drhe63d9992008-08-13 19:11:48 +00003717int sqlite3BtreeMovetoUnpacked(
3718 BtCursor *pCur, /* The cursor to be moved */
3719 UnpackedRecord *pIdxKey, /* Unpacked index key */
3720 i64 intKey, /* The table key */
3721 int biasRight, /* If true, bias the search to the high end */
3722 int *pRes /* Write search results here */
drhe4d90812007-03-29 05:51:49 +00003723){
drh72f82862001-05-24 21:06:34 +00003724 int rc;
drhd677b3d2007-08-20 22:48:41 +00003725
drh1fee73e2007-08-29 04:00:57 +00003726 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003727 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drha2c20e42008-03-29 16:01:04 +00003728
3729 /* If the cursor is already positioned at the point we are trying
3730 ** to move to, then just return without doing any work */
danielk197771d5d2c2008-09-29 11:49:47 +00003731 if( pCur->eState==CURSOR_VALID && pCur->validNKey
3732 && pCur->apPage[0]->intKey
3733 ){
drhe63d9992008-08-13 19:11:48 +00003734 if( pCur->info.nKey==intKey ){
drha2c20e42008-03-29 16:01:04 +00003735 *pRes = 0;
3736 return SQLITE_OK;
3737 }
drhe63d9992008-08-13 19:11:48 +00003738 if( pCur->atLast && pCur->info.nKey<intKey ){
drha2c20e42008-03-29 16:01:04 +00003739 *pRes = -1;
3740 return SQLITE_OK;
3741 }
3742 }
3743
drh5e2f8b92001-05-28 00:41:15 +00003744 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003745 if( rc ){
3746 return rc;
3747 }
danielk197771d5d2c2008-09-29 11:49:47 +00003748 assert( pCur->apPage[pCur->iPage] );
3749 assert( pCur->apPage[pCur->iPage]->isInit );
danielk1977da184232006-01-05 11:34:32 +00003750 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00003751 *pRes = -1;
danielk197771d5d2c2008-09-29 11:49:47 +00003752 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhc39e0002004-05-07 23:50:57 +00003753 return SQLITE_OK;
3754 }
danielk197771d5d2c2008-09-29 11:49:47 +00003755 assert( pCur->apPage[0]->intKey || pIdxKey );
drh14684382006-11-30 13:05:29 +00003756 for(;;){
drh72f82862001-05-24 21:06:34 +00003757 int lwr, upr;
3758 Pgno chldPg;
danielk197771d5d2c2008-09-29 11:49:47 +00003759 MemPage *pPage = pCur->apPage[pCur->iPage];
drh1a844c32002-12-04 22:29:28 +00003760 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00003761 lwr = 0;
3762 upr = pPage->nCell-1;
drhe63d9992008-08-13 19:11:48 +00003763 if( !pPage->intKey && pIdxKey==0 ){
drh1e968a02008-03-25 00:22:21 +00003764 rc = SQLITE_CORRUPT_BKPT;
3765 goto moveto_finish;
drh4eec4c12005-01-21 00:22:37 +00003766 }
drhe4d90812007-03-29 05:51:49 +00003767 if( biasRight ){
danielk197771d5d2c2008-09-29 11:49:47 +00003768 pCur->aiIdx[pCur->iPage] = upr;
drhe4d90812007-03-29 05:51:49 +00003769 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00003770 pCur->aiIdx[pCur->iPage] = (upr+lwr)/2;
drhe4d90812007-03-29 05:51:49 +00003771 }
drhf1d68b32007-03-29 04:43:26 +00003772 if( lwr<=upr ) for(;;){
danielk197713adf8a2004-06-03 16:08:41 +00003773 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00003774 i64 nCellKey;
danielk197771d5d2c2008-09-29 11:49:47 +00003775 int idx = pCur->aiIdx[pCur->iPage];
drh366fda62006-01-13 02:35:09 +00003776 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003777 pCur->validNKey = 1;
drh3aac2dd2004-04-26 14:10:20 +00003778 if( pPage->intKey ){
drh777e4c42006-01-13 04:31:58 +00003779 u8 *pCell;
danielk197771d5d2c2008-09-29 11:49:47 +00003780 pCell = findCell(pPage, idx) + pPage->childPtrSize;
drhd172f862006-01-12 15:01:15 +00003781 if( pPage->hasData ){
danielk1977bab45c62006-01-16 15:14:27 +00003782 u32 dummy;
shane3f8d5cf2008-04-24 19:15:09 +00003783 pCell += getVarint32(pCell, dummy);
drhd172f862006-01-12 15:01:15 +00003784 }
drha2c20e42008-03-29 16:01:04 +00003785 getVarint(pCell, (u64*)&nCellKey);
drhe63d9992008-08-13 19:11:48 +00003786 if( nCellKey==intKey ){
drh3aac2dd2004-04-26 14:10:20 +00003787 c = 0;
drhe63d9992008-08-13 19:11:48 +00003788 }else if( nCellKey<intKey ){
drh41eb9e92008-04-02 18:33:07 +00003789 c = -1;
3790 }else{
drhe63d9992008-08-13 19:11:48 +00003791 assert( nCellKey>intKey );
drh41eb9e92008-04-02 18:33:07 +00003792 c = +1;
drh3aac2dd2004-04-26 14:10:20 +00003793 }
drh3aac2dd2004-04-26 14:10:20 +00003794 }else{
drhe51c44f2004-05-30 20:46:09 +00003795 int available;
danielk197713adf8a2004-06-03 16:08:41 +00003796 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drh366fda62006-01-13 02:35:09 +00003797 nCellKey = pCur->info.nKey;
drhe51c44f2004-05-30 20:46:09 +00003798 if( available>=nCellKey ){
drhe63d9992008-08-13 19:11:48 +00003799 c = sqlite3VdbeRecordCompare(nCellKey, pCellKey, pIdxKey);
drhe51c44f2004-05-30 20:46:09 +00003800 }else{
drhfacf0302008-06-17 15:12:00 +00003801 pCellKey = sqlite3Malloc( nCellKey );
danielk19776507ecb2008-03-25 09:56:44 +00003802 if( pCellKey==0 ){
3803 rc = SQLITE_NOMEM;
3804 goto moveto_finish;
3805 }
danielk197713adf8a2004-06-03 16:08:41 +00003806 rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
drhe63d9992008-08-13 19:11:48 +00003807 c = sqlite3VdbeRecordCompare(nCellKey, pCellKey, pIdxKey);
drhfacf0302008-06-17 15:12:00 +00003808 sqlite3_free(pCellKey);
drh1e968a02008-03-25 00:22:21 +00003809 if( rc ) goto moveto_finish;
drhe51c44f2004-05-30 20:46:09 +00003810 }
drh3aac2dd2004-04-26 14:10:20 +00003811 }
drh72f82862001-05-24 21:06:34 +00003812 if( c==0 ){
drha2c20e42008-03-29 16:01:04 +00003813 pCur->info.nKey = nCellKey;
drh44845222008-07-17 18:39:57 +00003814 if( pPage->intKey && !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00003815 lwr = idx;
drhfc70e6f2004-05-12 21:11:27 +00003816 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00003817 break;
3818 }else{
drh8b18dd42004-05-12 19:18:15 +00003819 if( pRes ) *pRes = 0;
drh1e968a02008-03-25 00:22:21 +00003820 rc = SQLITE_OK;
3821 goto moveto_finish;
drh8b18dd42004-05-12 19:18:15 +00003822 }
drh72f82862001-05-24 21:06:34 +00003823 }
3824 if( c<0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003825 lwr = idx+1;
drh72f82862001-05-24 21:06:34 +00003826 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00003827 upr = idx-1;
drh72f82862001-05-24 21:06:34 +00003828 }
drhf1d68b32007-03-29 04:43:26 +00003829 if( lwr>upr ){
drha2c20e42008-03-29 16:01:04 +00003830 pCur->info.nKey = nCellKey;
drhf1d68b32007-03-29 04:43:26 +00003831 break;
3832 }
danielk197771d5d2c2008-09-29 11:49:47 +00003833 pCur->aiIdx[pCur->iPage] = (lwr+upr)/2;
drh72f82862001-05-24 21:06:34 +00003834 }
3835 assert( lwr==upr+1 );
danielk197771d5d2c2008-09-29 11:49:47 +00003836 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00003837 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00003838 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00003839 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00003840 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00003841 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00003842 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00003843 }
3844 if( chldPg==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003845 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh72f82862001-05-24 21:06:34 +00003846 if( pRes ) *pRes = c;
drh1e968a02008-03-25 00:22:21 +00003847 rc = SQLITE_OK;
3848 goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00003849 }
danielk197771d5d2c2008-09-29 11:49:47 +00003850 pCur->aiIdx[pCur->iPage] = lwr;
drh271efa52004-05-30 19:19:05 +00003851 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003852 pCur->validNKey = 0;
drh8178a752003-01-05 21:41:40 +00003853 rc = moveToChild(pCur, chldPg);
drh1e968a02008-03-25 00:22:21 +00003854 if( rc ) goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00003855 }
drh1e968a02008-03-25 00:22:21 +00003856moveto_finish:
drhe63d9992008-08-13 19:11:48 +00003857 return rc;
3858}
3859
3860/*
3861** In this version of BtreeMoveto, pKey is a packed index record
3862** such as is generated by the OP_MakeRecord opcode. Unpack the
3863** record and then call BtreeMovetoUnpacked() to do the work.
3864*/
3865int sqlite3BtreeMoveto(
3866 BtCursor *pCur, /* Cursor open on the btree to be searched */
3867 const void *pKey, /* Packed key if the btree is an index */
3868 i64 nKey, /* Integer key for tables. Size of pKey for indices */
3869 int bias, /* Bias search to the high end */
3870 int *pRes /* Write search results here */
3871){
3872 int rc; /* Status code */
3873 UnpackedRecord *pIdxKey; /* Unpacked index key */
drh23f79d02008-08-20 22:06:47 +00003874 UnpackedRecord aSpace[16]; /* Temp space for pIdxKey - to avoid a malloc */
drhe63d9992008-08-13 19:11:48 +00003875
drhe14006d2008-03-25 17:23:32 +00003876 if( pKey ){
drhe63d9992008-08-13 19:11:48 +00003877 pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, nKey, pKey,
drh23f79d02008-08-20 22:06:47 +00003878 aSpace, sizeof(aSpace));
drhe63d9992008-08-13 19:11:48 +00003879 if( pIdxKey==0 ) return SQLITE_NOMEM;
3880 }else{
3881 pIdxKey = 0;
3882 }
3883 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
3884 if( pKey ){
3885 sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
drhe14006d2008-03-25 17:23:32 +00003886 }
drh1e968a02008-03-25 00:22:21 +00003887 return rc;
drh72f82862001-05-24 21:06:34 +00003888}
3889
drhd677b3d2007-08-20 22:48:41 +00003890
drh72f82862001-05-24 21:06:34 +00003891/*
drhc39e0002004-05-07 23:50:57 +00003892** Return TRUE if the cursor is not pointing at an entry of the table.
3893**
3894** TRUE will be returned after a call to sqlite3BtreeNext() moves
3895** past the last entry in the table or sqlite3BtreePrev() moves past
3896** the first entry. TRUE is also returned if the table is empty.
3897*/
3898int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00003899 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
3900 ** have been deleted? This API will need to change to return an error code
3901 ** as well as the boolean result value.
3902 */
3903 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00003904}
3905
3906/*
drhb21c8cd2007-08-21 19:33:56 +00003907** Return the database connection handle for a cursor.
3908*/
3909sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){
drhe5fe6902007-12-07 18:55:28 +00003910 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
3911 return pCur->pBtree->db;
drhb21c8cd2007-08-21 19:33:56 +00003912}
3913
3914/*
drhbd03cae2001-06-02 02:40:57 +00003915** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00003916** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00003917** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00003918** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00003919*/
drhd094db12008-04-03 21:46:57 +00003920int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00003921 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003922 int idx;
danielk197797a227c2006-01-20 16:32:04 +00003923 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00003924
drh1fee73e2007-08-29 04:00:57 +00003925 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003926 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003927 if( rc!=SQLITE_OK ){
3928 return rc;
3929 }
drh8c4d3a62007-04-06 01:03:32 +00003930 assert( pRes!=0 );
drh8c4d3a62007-04-06 01:03:32 +00003931 if( CURSOR_INVALID==pCur->eState ){
3932 *pRes = 1;
3933 return SQLITE_OK;
3934 }
danielk1977da184232006-01-05 11:34:32 +00003935 if( pCur->skip>0 ){
3936 pCur->skip = 0;
3937 *pRes = 0;
3938 return SQLITE_OK;
3939 }
3940 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00003941
danielk197771d5d2c2008-09-29 11:49:47 +00003942 pPage = pCur->apPage[pCur->iPage];
3943 idx = ++pCur->aiIdx[pCur->iPage];
3944 assert( pPage->isInit );
3945 assert( idx<=pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00003946
drh271efa52004-05-30 19:19:05 +00003947 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003948 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003949 if( idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00003950 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003951 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00003952 if( rc ) return rc;
3953 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003954 *pRes = 0;
3955 return rc;
drh72f82862001-05-24 21:06:34 +00003956 }
drh5e2f8b92001-05-28 00:41:15 +00003957 do{
danielk197771d5d2c2008-09-29 11:49:47 +00003958 if( pCur->iPage==0 ){
drh8c1238a2003-01-02 14:43:55 +00003959 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00003960 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00003961 return SQLITE_OK;
3962 }
drh16a9b832007-05-05 18:39:25 +00003963 sqlite3BtreeMoveToParent(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00003964 pPage = pCur->apPage[pCur->iPage];
3965 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00003966 *pRes = 0;
drh44845222008-07-17 18:39:57 +00003967 if( pPage->intKey ){
drh8b18dd42004-05-12 19:18:15 +00003968 rc = sqlite3BtreeNext(pCur, pRes);
3969 }else{
3970 rc = SQLITE_OK;
3971 }
3972 return rc;
drh8178a752003-01-05 21:41:40 +00003973 }
3974 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00003975 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00003976 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00003977 }
drh5e2f8b92001-05-28 00:41:15 +00003978 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003979 return rc;
drh72f82862001-05-24 21:06:34 +00003980}
drhd677b3d2007-08-20 22:48:41 +00003981
drh72f82862001-05-24 21:06:34 +00003982
drh3b7511c2001-05-26 13:15:44 +00003983/*
drh2dcc9aa2002-12-04 13:40:25 +00003984** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00003985** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00003986** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00003987** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00003988*/
drhd094db12008-04-03 21:46:57 +00003989int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00003990 int rc;
drh8178a752003-01-05 21:41:40 +00003991 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00003992
drh1fee73e2007-08-29 04:00:57 +00003993 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003994 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003995 if( rc!=SQLITE_OK ){
3996 return rc;
3997 }
drha2c20e42008-03-29 16:01:04 +00003998 pCur->atLast = 0;
drh8c4d3a62007-04-06 01:03:32 +00003999 if( CURSOR_INVALID==pCur->eState ){
4000 *pRes = 1;
4001 return SQLITE_OK;
4002 }
danielk1977da184232006-01-05 11:34:32 +00004003 if( pCur->skip<0 ){
4004 pCur->skip = 0;
4005 *pRes = 0;
4006 return SQLITE_OK;
4007 }
4008 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00004009
danielk197771d5d2c2008-09-29 11:49:47 +00004010 pPage = pCur->apPage[pCur->iPage];
4011 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00004012 if( !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00004013 int idx = pCur->aiIdx[pCur->iPage];
4014 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
drhd677b3d2007-08-20 22:48:41 +00004015 if( rc ){
4016 return rc;
4017 }
drh2dcc9aa2002-12-04 13:40:25 +00004018 rc = moveToRightmost(pCur);
4019 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004020 while( pCur->aiIdx[pCur->iPage]==0 ){
4021 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00004022 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00004023 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00004024 return SQLITE_OK;
4025 }
drh16a9b832007-05-05 18:39:25 +00004026 sqlite3BtreeMoveToParent(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00004027 }
drh271efa52004-05-30 19:19:05 +00004028 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004029 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004030
4031 pCur->aiIdx[pCur->iPage]--;
4032 pPage = pCur->apPage[pCur->iPage];
drh44845222008-07-17 18:39:57 +00004033 if( pPage->intKey && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00004034 rc = sqlite3BtreePrevious(pCur, pRes);
4035 }else{
4036 rc = SQLITE_OK;
4037 }
drh2dcc9aa2002-12-04 13:40:25 +00004038 }
drh8178a752003-01-05 21:41:40 +00004039 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00004040 return rc;
4041}
4042
4043/*
drh3b7511c2001-05-26 13:15:44 +00004044** Allocate a new page from the database file.
4045**
danielk19773b8a05f2007-03-19 17:44:26 +00004046** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00004047** has already been called on the new page.) The new page has also
4048** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00004049** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00004050**
4051** SQLITE_OK is returned on success. Any other return value indicates
4052** an error. *ppPage and *pPgno are undefined in the event of an error.
danielk19773b8a05f2007-03-19 17:44:26 +00004053** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00004054**
drh199e3cf2002-07-18 11:01:47 +00004055** If the "nearby" parameter is not 0, then a (feeble) effort is made to
4056** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00004057** attempt to keep related pages close to each other in the database file,
4058** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00004059**
4060** If the "exact" parameter is not 0, and the page-number nearby exists
4061** anywhere on the free-list, then it is guarenteed to be returned. This
4062** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00004063*/
drh4f0c5872007-03-26 22:05:01 +00004064static int allocateBtreePage(
danielk1977aef0bf62005-12-30 16:28:01 +00004065 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00004066 MemPage **ppPage,
4067 Pgno *pPgno,
4068 Pgno nearby,
4069 u8 exact
4070){
drh3aac2dd2004-04-26 14:10:20 +00004071 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00004072 int rc;
drh3aac2dd2004-04-26 14:10:20 +00004073 int n; /* Number of pages on the freelist */
4074 int k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00004075 MemPage *pTrunk = 0;
4076 MemPage *pPrevTrunk = 0;
drh30e58752002-03-02 20:41:57 +00004077
drh1fee73e2007-08-29 04:00:57 +00004078 assert( sqlite3_mutex_held(pBt->mutex) );
drh3aac2dd2004-04-26 14:10:20 +00004079 pPage1 = pBt->pPage1;
4080 n = get4byte(&pPage1->aData[36]);
4081 if( n>0 ){
drh91025292004-05-03 19:49:32 +00004082 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00004083 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004084 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
4085
4086 /* If the 'exact' parameter was true and a query of the pointer-map
4087 ** shows that the page 'nearby' is somewhere on the free-list, then
4088 ** the entire-list will be searched for that page.
4089 */
4090#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ad0132d2008-06-07 08:58:22 +00004091 if( exact && nearby<=pagerPagecount(pBt->pPager) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004092 u8 eType;
4093 assert( nearby>0 );
4094 assert( pBt->autoVacuum );
4095 rc = ptrmapGet(pBt, nearby, &eType, 0);
4096 if( rc ) return rc;
4097 if( eType==PTRMAP_FREEPAGE ){
4098 searchList = 1;
4099 }
4100 *pPgno = nearby;
4101 }
4102#endif
4103
4104 /* Decrement the free-list count by 1. Set iTrunk to the index of the
4105 ** first free-list trunk page. iPrevTrunk is initially 1.
4106 */
danielk19773b8a05f2007-03-19 17:44:26 +00004107 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00004108 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004109 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004110
4111 /* The code within this loop is run only once if the 'searchList' variable
4112 ** is not true. Otherwise, it runs once for each trunk-page on the
4113 ** free-list until the page 'nearby' is located.
4114 */
4115 do {
4116 pPrevTrunk = pTrunk;
4117 if( pPrevTrunk ){
4118 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00004119 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004120 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00004121 }
drh16a9b832007-05-05 18:39:25 +00004122 rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004123 if( rc ){
drhd3627af2006-12-18 18:34:51 +00004124 pTrunk = 0;
4125 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004126 }
4127
4128 k = get4byte(&pTrunk->aData[4]);
4129 if( k==0 && !searchList ){
4130 /* The trunk has no leaves and the list is not being searched.
4131 ** So extract the trunk page itself and use it as the newly
4132 ** allocated page */
4133 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00004134 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004135 if( rc ){
4136 goto end_allocate_page;
4137 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004138 *pPgno = iTrunk;
4139 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4140 *ppPage = pTrunk;
4141 pTrunk = 0;
4142 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh45b1fac2008-07-04 17:52:42 +00004143 }else if( k>pBt->usableSize/4 - 2 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004144 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00004145 rc = SQLITE_CORRUPT_BKPT;
4146 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004147#ifndef SQLITE_OMIT_AUTOVACUUM
4148 }else if( searchList && nearby==iTrunk ){
4149 /* The list is being searched and this trunk page is the page
4150 ** to allocate, regardless of whether it has leaves.
4151 */
4152 assert( *pPgno==iTrunk );
4153 *ppPage = pTrunk;
4154 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00004155 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004156 if( rc ){
4157 goto end_allocate_page;
4158 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004159 if( k==0 ){
4160 if( !pPrevTrunk ){
4161 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4162 }else{
4163 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
4164 }
4165 }else{
4166 /* The trunk page is required by the caller but it contains
4167 ** pointers to free-list leaves. The first leaf becomes a trunk
4168 ** page in this case.
4169 */
4170 MemPage *pNewTrunk;
4171 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh16a9b832007-05-05 18:39:25 +00004172 rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004173 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00004174 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004175 }
danielk19773b8a05f2007-03-19 17:44:26 +00004176 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004177 if( rc!=SQLITE_OK ){
4178 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00004179 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004180 }
4181 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
4182 put4byte(&pNewTrunk->aData[4], k-1);
4183 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00004184 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004185 if( !pPrevTrunk ){
4186 put4byte(&pPage1->aData[32], iNewTrunk);
4187 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00004188 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004189 if( rc ){
4190 goto end_allocate_page;
4191 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004192 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
4193 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004194 }
4195 pTrunk = 0;
4196 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
4197#endif
4198 }else{
4199 /* Extract a leaf from the trunk */
4200 int closest;
4201 Pgno iPage;
4202 unsigned char *aData = pTrunk->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00004203 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004204 if( rc ){
4205 goto end_allocate_page;
4206 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004207 if( nearby>0 ){
4208 int i, dist;
4209 closest = 0;
4210 dist = get4byte(&aData[8]) - nearby;
4211 if( dist<0 ) dist = -dist;
4212 for(i=1; i<k; i++){
4213 int d2 = get4byte(&aData[8+i*4]) - nearby;
4214 if( d2<0 ) d2 = -d2;
4215 if( d2<dist ){
4216 closest = i;
4217 dist = d2;
4218 }
4219 }
4220 }else{
4221 closest = 0;
4222 }
4223
4224 iPage = get4byte(&aData[8+closest*4]);
4225 if( !searchList || iPage==nearby ){
danielk1977ad0132d2008-06-07 08:58:22 +00004226 int nPage;
shane1f9e6aa2008-06-09 19:27:11 +00004227 *pPgno = iPage;
danielk1977ad0132d2008-06-07 08:58:22 +00004228 nPage = pagerPagecount(pBt->pPager);
4229 if( *pPgno>nPage ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004230 /* Free page off the end of the file */
danielk197743e377a2008-05-05 12:09:32 +00004231 rc = SQLITE_CORRUPT_BKPT;
4232 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004233 }
4234 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
4235 ": %d more free pages\n",
4236 *pPgno, closest+1, k, pTrunk->pgno, n-1));
4237 if( closest<k-1 ){
4238 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
4239 }
4240 put4byte(&aData[4], k-1);
drh16a9b832007-05-05 18:39:25 +00004241 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004242 if( rc==SQLITE_OK ){
drh538f5702007-04-13 02:14:30 +00004243 sqlite3PagerDontRollback((*ppPage)->pDbPage);
danielk19773b8a05f2007-03-19 17:44:26 +00004244 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004245 if( rc!=SQLITE_OK ){
4246 releasePage(*ppPage);
4247 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004248 }
4249 searchList = 0;
4250 }
drhee696e22004-08-30 16:52:17 +00004251 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004252 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00004253 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004254 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00004255 }else{
drh3aac2dd2004-04-26 14:10:20 +00004256 /* There are no pages on the freelist, so create a new page at the
4257 ** end of the file */
danielk1977ad0132d2008-06-07 08:58:22 +00004258 int nPage = pagerPagecount(pBt->pPager);
4259 *pPgno = nPage + 1;
danielk1977afcdd022004-10-31 16:25:42 +00004260
4261#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00004262 if( pBt->nTrunc ){
4263 /* An incr-vacuum has already run within this transaction. So the
4264 ** page to allocate is not from the physical end of the file, but
4265 ** at pBt->nTrunc.
4266 */
4267 *pPgno = pBt->nTrunc+1;
4268 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
4269 (*pPgno)++;
4270 }
4271 }
danielk1977266664d2006-02-10 08:24:21 +00004272 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00004273 /* If *pPgno refers to a pointer-map page, allocate two new pages
4274 ** at the end of the file instead of one. The first allocated page
4275 ** becomes a new pointer-map page, the second is used by the caller.
4276 */
4277 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00004278 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977afcdd022004-10-31 16:25:42 +00004279 (*pPgno)++;
drh72190432008-01-31 14:54:43 +00004280 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
danielk1977afcdd022004-10-31 16:25:42 +00004281 }
danielk1977dddbcdc2007-04-26 14:42:34 +00004282 if( pBt->nTrunc ){
4283 pBt->nTrunc = *pPgno;
4284 }
danielk1977afcdd022004-10-31 16:25:42 +00004285#endif
4286
danielk1977599fcba2004-11-08 07:13:13 +00004287 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh16a9b832007-05-05 18:39:25 +00004288 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
drh3b7511c2001-05-26 13:15:44 +00004289 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00004290 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004291 if( rc!=SQLITE_OK ){
4292 releasePage(*ppPage);
4293 }
drh3a4c1412004-05-09 20:40:11 +00004294 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00004295 }
danielk1977599fcba2004-11-08 07:13:13 +00004296
4297 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00004298
4299end_allocate_page:
4300 releasePage(pTrunk);
4301 releasePage(pPrevTrunk);
danielk197771d5d2c2008-09-29 11:49:47 +00004302 if( rc==SQLITE_OK && sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
4303 releasePage(*ppPage);
4304 return SQLITE_CORRUPT_BKPT;
danielk1977eaa06f62008-09-18 17:34:44 +00004305 }
drh3b7511c2001-05-26 13:15:44 +00004306 return rc;
4307}
4308
4309/*
drh3aac2dd2004-04-26 14:10:20 +00004310** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00004311**
danielk19773b8a05f2007-03-19 17:44:26 +00004312** sqlite3PagerUnref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00004313*/
drh3aac2dd2004-04-26 14:10:20 +00004314static int freePage(MemPage *pPage){
danielk1977aef0bf62005-12-30 16:28:01 +00004315 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00004316 MemPage *pPage1 = pBt->pPage1;
4317 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00004318
drh3aac2dd2004-04-26 14:10:20 +00004319 /* Prepare the page for freeing */
drh1fee73e2007-08-29 04:00:57 +00004320 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh3aac2dd2004-04-26 14:10:20 +00004321 assert( pPage->pgno>1 );
4322 pPage->isInit = 0;
drh3aac2dd2004-04-26 14:10:20 +00004323
drha34b6762004-05-07 13:30:42 +00004324 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00004325 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00004326 if( rc ) return rc;
4327 n = get4byte(&pPage1->aData[36]);
4328 put4byte(&pPage1->aData[36], n+1);
4329
drhfcce93f2006-02-22 03:08:32 +00004330#ifdef SQLITE_SECURE_DELETE
4331 /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
4332 ** always fully overwrite deleted information with zeros.
4333 */
danielk19773b8a05f2007-03-19 17:44:26 +00004334 rc = sqlite3PagerWrite(pPage->pDbPage);
drhfcce93f2006-02-22 03:08:32 +00004335 if( rc ) return rc;
4336 memset(pPage->aData, 0, pPage->pBt->pageSize);
4337#endif
4338
danielk1977687566d2004-11-02 12:56:41 +00004339 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00004340 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00004341 */
danielk197785d90ca2008-07-19 14:25:15 +00004342 if( ISAUTOVACUUM ){
danielk1977687566d2004-11-02 12:56:41 +00004343 rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
danielk1977a64a0352004-11-05 01:45:13 +00004344 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00004345 }
danielk1977687566d2004-11-02 12:56:41 +00004346
drh3aac2dd2004-04-26 14:10:20 +00004347 if( n==0 ){
4348 /* This is the first free page */
danielk19773b8a05f2007-03-19 17:44:26 +00004349 rc = sqlite3PagerWrite(pPage->pDbPage);
drhda200cc2004-05-09 11:51:38 +00004350 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004351 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00004352 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00004353 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00004354 }else{
4355 /* Other free pages already exist. Retrive the first trunk page
4356 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00004357 MemPage *pTrunk;
drh16a9b832007-05-05 18:39:25 +00004358 rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0);
drh3b7511c2001-05-26 13:15:44 +00004359 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004360 k = get4byte(&pTrunk->aData[4]);
drhee696e22004-08-30 16:52:17 +00004361 if( k>=pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00004362 /* The trunk is full. Turn the page being freed into a new
drh45b1fac2008-07-04 17:52:42 +00004363 ** trunk page with no leaves.
4364 **
4365 ** Note that the trunk page is not really full until it contains
4366 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
4367 ** coded. But due to a coding error in versions of SQLite prior to
4368 ** 3.6.0, databases with freelist trunk pages holding more than
4369 ** usableSize/4 - 8 entries will be reported as corrupt. In order
4370 ** to maintain backwards compatibility with older versions of SQLite,
4371 ** we will contain to restrict the number of entries to usableSize/4 - 8
4372 ** for now. At some point in the future (once everyone has upgraded
4373 ** to 3.6.0 or later) we should consider fixing the conditional above
4374 ** to read "usableSize/4-2" instead of "usableSize/4-8".
4375 */
danielk19773b8a05f2007-03-19 17:44:26 +00004376 rc = sqlite3PagerWrite(pPage->pDbPage);
drhb9ee4932007-09-07 14:32:06 +00004377 if( rc==SQLITE_OK ){
4378 put4byte(pPage->aData, pTrunk->pgno);
4379 put4byte(&pPage->aData[4], 0);
4380 put4byte(&pPage1->aData[32], pPage->pgno);
4381 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
4382 pPage->pgno, pTrunk->pgno));
4383 }
4384 }else if( k<0 ){
4385 rc = SQLITE_CORRUPT;
drh3aac2dd2004-04-26 14:10:20 +00004386 }else{
4387 /* Add the newly freed page as a leaf on the current trunk */
danielk19773b8a05f2007-03-19 17:44:26 +00004388 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00004389 if( rc==SQLITE_OK ){
4390 put4byte(&pTrunk->aData[4], k+1);
4391 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drhfcce93f2006-02-22 03:08:32 +00004392#ifndef SQLITE_SECURE_DELETE
danielk1977a1fa00d2008-08-27 15:16:33 +00004393 rc = sqlite3PagerDontWrite(pPage->pDbPage);
drhfcce93f2006-02-22 03:08:32 +00004394#endif
drhf5345442007-04-09 12:45:02 +00004395 }
drh3a4c1412004-05-09 20:40:11 +00004396 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00004397 }
4398 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00004399 }
drh3b7511c2001-05-26 13:15:44 +00004400 return rc;
4401}
4402
4403/*
drh3aac2dd2004-04-26 14:10:20 +00004404** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00004405*/
drh3aac2dd2004-04-26 14:10:20 +00004406static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00004407 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00004408 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00004409 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00004410 int rc;
drh94440812007-03-06 11:42:19 +00004411 int nOvfl;
4412 int ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00004413
drh1fee73e2007-08-29 04:00:57 +00004414 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh16a9b832007-05-05 18:39:25 +00004415 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004416 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00004417 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00004418 }
drh6f11bef2004-05-13 01:12:56 +00004419 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh94440812007-03-06 11:42:19 +00004420 ovflPageSize = pBt->usableSize - 4;
drh72365832007-03-06 15:53:44 +00004421 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
4422 assert( ovflPgno==0 || nOvfl>0 );
4423 while( nOvfl-- ){
drh3aac2dd2004-04-26 14:10:20 +00004424 MemPage *pOvfl;
danielk1977ad0132d2008-06-07 08:58:22 +00004425 if( ovflPgno==0 || ovflPgno>pagerPagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00004426 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00004427 }
danielk19778c0a9592007-04-30 16:55:00 +00004428
4429 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno);
drh3b7511c2001-05-26 13:15:44 +00004430 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00004431 rc = freePage(pOvfl);
danielk19773b8a05f2007-03-19 17:44:26 +00004432 sqlite3PagerUnref(pOvfl->pDbPage);
danielk19776b456a22005-03-21 04:04:02 +00004433 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00004434 }
drh5e2f8b92001-05-28 00:41:15 +00004435 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00004436}
4437
4438/*
drh91025292004-05-03 19:49:32 +00004439** Create the byte sequence used to represent a cell on page pPage
4440** and write that byte sequence into pCell[]. Overflow pages are
4441** allocated and filled in as necessary. The calling procedure
4442** is responsible for making sure sufficient space has been allocated
4443** for pCell[].
4444**
4445** Note that pCell does not necessary need to point to the pPage->aData
4446** area. pCell might point to some temporary storage. The cell will
4447** be constructed in this temporary area then copied into pPage->aData
4448** later.
drh3b7511c2001-05-26 13:15:44 +00004449*/
4450static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00004451 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00004452 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00004453 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00004454 const void *pData,int nData, /* The data */
drhb026e052007-05-02 01:34:31 +00004455 int nZero, /* Extra zero bytes to append to pData */
drh4b70f112004-05-02 21:12:19 +00004456 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00004457){
drh3b7511c2001-05-26 13:15:44 +00004458 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00004459 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00004460 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00004461 int spaceLeft;
4462 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00004463 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00004464 unsigned char *pPrior;
4465 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00004466 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00004467 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00004468 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00004469 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00004470
drh1fee73e2007-08-29 04:00:57 +00004471 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00004472
drh91025292004-05-03 19:49:32 +00004473 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00004474 nHeader = 0;
drh91025292004-05-03 19:49:32 +00004475 if( !pPage->leaf ){
4476 nHeader += 4;
4477 }
drh8b18dd42004-05-12 19:18:15 +00004478 if( pPage->hasData ){
drhb026e052007-05-02 01:34:31 +00004479 nHeader += putVarint(&pCell[nHeader], nData+nZero);
drh6f11bef2004-05-13 01:12:56 +00004480 }else{
drhb026e052007-05-02 01:34:31 +00004481 nData = nZero = 0;
drh91025292004-05-03 19:49:32 +00004482 }
drh6f11bef2004-05-13 01:12:56 +00004483 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh16a9b832007-05-05 18:39:25 +00004484 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004485 assert( info.nHeader==nHeader );
4486 assert( info.nKey==nKey );
drhb026e052007-05-02 01:34:31 +00004487 assert( info.nData==nData+nZero );
drh6f11bef2004-05-13 01:12:56 +00004488
4489 /* Fill in the payload */
drhb026e052007-05-02 01:34:31 +00004490 nPayload = nData + nZero;
drh3aac2dd2004-04-26 14:10:20 +00004491 if( pPage->intKey ){
4492 pSrc = pData;
4493 nSrc = nData;
drh91025292004-05-03 19:49:32 +00004494 nData = 0;
drh3aac2dd2004-04-26 14:10:20 +00004495 }else{
4496 nPayload += nKey;
4497 pSrc = pKey;
4498 nSrc = nKey;
4499 }
drh6f11bef2004-05-13 01:12:56 +00004500 *pnSize = info.nSize;
4501 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00004502 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00004503 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00004504
drh3b7511c2001-05-26 13:15:44 +00004505 while( nPayload>0 ){
4506 if( spaceLeft==0 ){
danielk1977b39f70b2007-05-17 18:28:11 +00004507 int isExact = 0;
danielk1977afcdd022004-10-31 16:25:42 +00004508#ifndef SQLITE_OMIT_AUTOVACUUM
4509 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00004510 if( pBt->autoVacuum ){
4511 do{
4512 pgnoOvfl++;
4513 } while(
4514 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
4515 );
danielk197789a4be82007-05-23 13:34:32 +00004516 if( pgnoOvfl>1 ){
danielk1977b39f70b2007-05-17 18:28:11 +00004517 /* isExact = 1; */
4518 }
4519 }
danielk1977afcdd022004-10-31 16:25:42 +00004520#endif
danielk1977b39f70b2007-05-17 18:28:11 +00004521 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, isExact);
danielk1977afcdd022004-10-31 16:25:42 +00004522#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00004523 /* If the database supports auto-vacuum, and the second or subsequent
4524 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00004525 ** for that page now.
4526 **
4527 ** If this is the first overflow page, then write a partial entry
4528 ** to the pointer-map. If we write nothing to this pointer-map slot,
4529 ** then the optimistic overflow chain processing in clearCell()
4530 ** may misinterpret the uninitialised values and delete the
4531 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00004532 */
danielk19774ef24492007-05-23 09:52:41 +00004533 if( pBt->autoVacuum && rc==SQLITE_OK ){
4534 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
4535 rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
danielk197789a4be82007-05-23 13:34:32 +00004536 if( rc ){
4537 releasePage(pOvfl);
4538 }
danielk1977afcdd022004-10-31 16:25:42 +00004539 }
4540#endif
drh3b7511c2001-05-26 13:15:44 +00004541 if( rc ){
drh9b171272004-05-08 02:03:22 +00004542 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00004543 return rc;
4544 }
drh3aac2dd2004-04-26 14:10:20 +00004545 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00004546 releasePage(pToRelease);
4547 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00004548 pPrior = pOvfl->aData;
4549 put4byte(pPrior, 0);
4550 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00004551 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00004552 }
4553 n = nPayload;
4554 if( n>spaceLeft ) n = spaceLeft;
drhb026e052007-05-02 01:34:31 +00004555 if( nSrc>0 ){
4556 if( n>nSrc ) n = nSrc;
4557 assert( pSrc );
4558 memcpy(pPayload, pSrc, n);
4559 }else{
4560 memset(pPayload, 0, n);
4561 }
drh3b7511c2001-05-26 13:15:44 +00004562 nPayload -= n;
drhde647132004-05-07 17:57:49 +00004563 pPayload += n;
drh9b171272004-05-08 02:03:22 +00004564 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00004565 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00004566 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00004567 if( nSrc==0 ){
4568 nSrc = nData;
4569 pSrc = pData;
4570 }
drhdd793422001-06-28 01:54:48 +00004571 }
drh9b171272004-05-08 02:03:22 +00004572 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00004573 return SQLITE_OK;
4574}
4575
drh14acc042001-06-10 19:56:58 +00004576/*
4577** Remove the i-th cell from pPage. This routine effects pPage only.
4578** The cell content is not freed or deallocated. It is assumed that
4579** the cell content has been copied someplace else. This routine just
4580** removes the reference to the cell from pPage.
4581**
4582** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00004583*/
shane0af3f892008-11-12 04:55:34 +00004584static int dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00004585 int i; /* Loop counter */
4586 int pc; /* Offset to cell content of cell being deleted */
4587 u8 *data; /* pPage->aData */
4588 u8 *ptr; /* Used to move bytes around within data[] */
shanedcc50b72008-11-13 18:29:50 +00004589 int rc; /* The return code */
drh43605152004-05-29 21:46:49 +00004590
drh8c42ca92001-06-22 19:15:00 +00004591 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00004592 assert( sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00004593 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00004594 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00004595 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00004596 ptr = &data[pPage->cellOffset + 2*idx];
shane0af3f892008-11-12 04:55:34 +00004597 pc = get2byte(ptr);
shanedcc50b72008-11-13 18:29:50 +00004598 if ( (pc<pPage->hdrOffset+6+(pPage->leaf?0:4)) || (pc+sz>pPage->pBt->usableSize) ) {
shane0af3f892008-11-12 04:55:34 +00004599 return SQLITE_CORRUPT_BKPT;
4600 }
shanedcc50b72008-11-13 18:29:50 +00004601 rc = freeSpace(pPage, pc, sz);
4602 if( rc!=SQLITE_OK ){
4603 return rc;
4604 }
drh43605152004-05-29 21:46:49 +00004605 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
4606 ptr[0] = ptr[2];
4607 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00004608 }
4609 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00004610 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
4611 pPage->nFree += 2;
shane0af3f892008-11-12 04:55:34 +00004612 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004613}
4614
4615/*
4616** Insert a new cell on pPage at cell index "i". pCell points to the
4617** content of the cell.
4618**
4619** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00004620** will not fit, then make a copy of the cell content into pTemp if
4621** pTemp is not null. Regardless of pTemp, allocate a new entry
4622** in pPage->aOvfl[] and make it point to the cell content (either
4623** in pTemp or the original pCell) and also record its index.
4624** Allocating a new entry in pPage->aCell[] implies that
4625** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00004626**
4627** If nSkip is non-zero, then do not copy the first nSkip bytes of the
4628** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00004629** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00004630** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00004631*/
danielk1977e80463b2004-11-03 03:01:16 +00004632static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00004633 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00004634 int i, /* New cell becomes the i-th cell of the page */
4635 u8 *pCell, /* Content of the new cell */
4636 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00004637 u8 *pTemp, /* Temp storage space for pCell, if needed */
4638 u8 nSkip /* Do not write the first nSkip bytes of the cell */
drh24cd67e2004-05-10 16:18:47 +00004639){
drh43605152004-05-29 21:46:49 +00004640 int idx; /* Where to write new cell content in data[] */
4641 int j; /* Loop counter */
4642 int top; /* First byte of content for any cell in data[] */
4643 int end; /* First byte past the last cell pointer in data[] */
4644 int ins; /* Index in data[] where new cell pointer is inserted */
4645 int hdr; /* Offset into data[] of the page header */
4646 int cellOffset; /* Address of first cell pointer in data[] */
4647 u8 *data; /* The content of the whole page */
4648 u8 *ptr; /* Used for moving information around in data[] */
4649
4650 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
4651 assert( sz==cellSizePtr(pPage, pCell) );
drh1fee73e2007-08-29 04:00:57 +00004652 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +00004653 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00004654 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00004655 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004656 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00004657 }
drh43605152004-05-29 21:46:49 +00004658 j = pPage->nOverflow++;
4659 assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
4660 pPage->aOvfl[j].pCell = pCell;
4661 pPage->aOvfl[j].idx = i;
4662 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00004663 }else{
danielk19776e465eb2007-08-21 13:11:00 +00004664 int rc = sqlite3PagerWrite(pPage->pDbPage);
4665 if( rc!=SQLITE_OK ){
4666 return rc;
4667 }
4668 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00004669 data = pPage->aData;
4670 hdr = pPage->hdrOffset;
4671 top = get2byte(&data[hdr+5]);
4672 cellOffset = pPage->cellOffset;
4673 end = cellOffset + 2*pPage->nCell + 2;
4674 ins = cellOffset + 2*i;
4675 if( end > top - sz ){
shane0af3f892008-11-12 04:55:34 +00004676 rc = defragmentPage(pPage);
4677 if( rc!=SQLITE_OK ){
4678 return rc;
4679 }
drh43605152004-05-29 21:46:49 +00004680 top = get2byte(&data[hdr+5]);
4681 assert( end + sz <= top );
4682 }
4683 idx = allocateSpace(pPage, sz);
4684 assert( idx>0 );
4685 assert( end <= get2byte(&data[hdr+5]) );
shane0af3f892008-11-12 04:55:34 +00004686 if (idx+sz > pPage->pBt->usableSize) {
shane34ac18d2008-11-11 22:18:20 +00004687 return SQLITE_CORRUPT_BKPT;
shane0af3f892008-11-12 04:55:34 +00004688 }
drh43605152004-05-29 21:46:49 +00004689 pPage->nCell++;
4690 pPage->nFree -= 2;
danielk1977a3ad5e72005-01-07 08:56:44 +00004691 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004692 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
4693 ptr[0] = ptr[-2];
4694 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00004695 }
drh43605152004-05-29 21:46:49 +00004696 put2byte(&data[ins], idx);
4697 put2byte(&data[hdr+3], pPage->nCell);
danielk1977a19df672004-11-03 11:37:07 +00004698#ifndef SQLITE_OMIT_AUTOVACUUM
4699 if( pPage->pBt->autoVacuum ){
4700 /* The cell may contain a pointer to an overflow page. If so, write
4701 ** the entry for the overflow page into the pointer map.
4702 */
4703 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00004704 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh72365832007-03-06 15:53:44 +00004705 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk1977a19df672004-11-03 11:37:07 +00004706 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
4707 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
danielk19776e465eb2007-08-21 13:11:00 +00004708 rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
danielk1977a19df672004-11-03 11:37:07 +00004709 if( rc!=SQLITE_OK ) return rc;
4710 }
4711 }
4712#endif
drh14acc042001-06-10 19:56:58 +00004713 }
danielk1977e80463b2004-11-03 03:01:16 +00004714
danielk1977e80463b2004-11-03 03:01:16 +00004715 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004716}
4717
4718/*
drhfa1a98a2004-05-14 19:08:17 +00004719** Add a list of cells to a page. The page should be initially empty.
4720** The cells are guaranteed to fit on the page.
4721*/
4722static void assemblePage(
4723 MemPage *pPage, /* The page to be assemblied */
4724 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00004725 u8 **apCell, /* Pointers to cell bodies */
drha9121e42008-02-19 14:59:35 +00004726 u16 *aSize /* Sizes of the cells */
drhfa1a98a2004-05-14 19:08:17 +00004727){
4728 int i; /* Loop counter */
4729 int totalSize; /* Total size of all cells */
4730 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00004731 int cellptr; /* Address of next cell pointer */
4732 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00004733 u8 *data; /* Data for the page */
4734
drh43605152004-05-29 21:46:49 +00004735 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00004736 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa1a98a2004-05-14 19:08:17 +00004737 totalSize = 0;
4738 for(i=0; i<nCell; i++){
4739 totalSize += aSize[i];
4740 }
drh43605152004-05-29 21:46:49 +00004741 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00004742 assert( pPage->nCell==0 );
drh43605152004-05-29 21:46:49 +00004743 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00004744 data = pPage->aData;
4745 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00004746 put2byte(&data[hdr+3], nCell);
drh09d0deb2005-08-02 17:13:09 +00004747 if( nCell ){
4748 cellbody = allocateSpace(pPage, totalSize);
4749 assert( cellbody>0 );
4750 assert( pPage->nFree >= 2*nCell );
4751 pPage->nFree -= 2*nCell;
4752 for(i=0; i<nCell; i++){
4753 put2byte(&data[cellptr], cellbody);
4754 memcpy(&data[cellbody], apCell[i], aSize[i]);
4755 cellptr += 2;
4756 cellbody += aSize[i];
4757 }
4758 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00004759 }
4760 pPage->nCell = nCell;
drhfa1a98a2004-05-14 19:08:17 +00004761}
4762
drh14acc042001-06-10 19:56:58 +00004763/*
drhc3b70572003-01-04 19:44:07 +00004764** The following parameters determine how many adjacent pages get involved
4765** in a balancing operation. NN is the number of neighbors on either side
4766** of the page that participate in the balancing operation. NB is the
4767** total number of pages that participate, including the target page and
4768** NN neighbors on either side.
4769**
4770** The minimum value of NN is 1 (of course). Increasing NN above 1
4771** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
4772** in exchange for a larger degradation in INSERT and UPDATE performance.
4773** The value of NN appears to give the best results overall.
4774*/
4775#define NN 1 /* Number of neighbors on either side of pPage */
4776#define NB (NN*2+1) /* Total pages involved in the balance */
4777
drh43605152004-05-29 21:46:49 +00004778/* Forward reference */
danielk197771d5d2c2008-09-29 11:49:47 +00004779static int balance(BtCursor*, int);
danielk1977ac245ec2005-01-14 13:50:11 +00004780
drh615ae552005-01-16 23:21:00 +00004781#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004782/*
4783** This version of balance() handles the common special case where
4784** a new entry is being inserted on the extreme right-end of the
4785** tree, in other words, when the new entry will become the largest
4786** entry in the tree.
4787**
4788** Instead of trying balance the 3 right-most leaf pages, just add
4789** a new page to the right-hand side and put the one new entry in
4790** that page. This leaves the right side of the tree somewhat
4791** unbalanced. But odds are that we will be inserting new entries
4792** at the end soon afterwards so the nearly empty page will quickly
4793** fill up. On average.
4794**
4795** pPage is the leaf page which is the right-most page in the tree.
4796** pParent is its parent. pPage must have a single overflow entry
4797** which is also the right-most entry on the page.
4798*/
danielk197771d5d2c2008-09-29 11:49:47 +00004799static int balance_quick(BtCursor *pCur){
danielk1977ac245ec2005-01-14 13:50:11 +00004800 int rc;
danielk1977eaa06f62008-09-18 17:34:44 +00004801 MemPage *pNew = 0;
danielk1977ac245ec2005-01-14 13:50:11 +00004802 Pgno pgnoNew;
4803 u8 *pCell;
drha9121e42008-02-19 14:59:35 +00004804 u16 szCell;
danielk1977ac245ec2005-01-14 13:50:11 +00004805 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00004806 MemPage *pPage = pCur->apPage[pCur->iPage];
4807 MemPage *pParent = pCur->apPage[pCur->iPage-1];
danielk1977aef0bf62005-12-30 16:28:01 +00004808 BtShared *pBt = pPage->pBt;
danielk197779a40da2005-01-16 08:00:01 +00004809 int parentIdx = pParent->nCell; /* pParent new divider cell index */
4810 int parentSize; /* Size of new divider cell */
4811 u8 parentCell[64]; /* Space for the new divider cell */
danielk1977ac245ec2005-01-14 13:50:11 +00004812
drh1fee73e2007-08-29 04:00:57 +00004813 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00004814
danielk1977ac245ec2005-01-14 13:50:11 +00004815 /* Allocate a new page. Insert the overflow cell from pPage
4816 ** into it. Then remove the overflow cell from pPage.
4817 */
drh4f0c5872007-03-26 22:05:01 +00004818 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk1977eaa06f62008-09-18 17:34:44 +00004819 if( rc==SQLITE_OK ){
4820 pCell = pPage->aOvfl[0].pCell;
4821 szCell = cellSizePtr(pPage, pCell);
4822 zeroPage(pNew, pPage->aData[0]);
4823 assemblePage(pNew, 1, &pCell, &szCell);
4824 pPage->nOverflow = 0;
4825
danielk1977eaa06f62008-09-18 17:34:44 +00004826 /* pPage is currently the right-child of pParent. Change this
4827 ** so that the right-child is the new page allocated above and
4828 ** pPage is the next-to-right child.
4829 **
4830 ** Ignore the return value of the call to fillInCell(). fillInCell()
4831 ** may only return other than SQLITE_OK if it is required to allocate
4832 ** one or more overflow pages. Since an internal table B-Tree cell
4833 ** may never spill over onto an overflow page (it is a maximum of
4834 ** 13 bytes in size), it is not neccessary to check the return code.
4835 **
4836 ** Similarly, the insertCell() function cannot fail if the page
4837 ** being inserted into is already writable and the cell does not
4838 ** contain an overflow pointer. So ignore this return code too.
4839 */
4840 assert( pPage->nCell>0 );
4841 pCell = findCell(pPage, pPage->nCell-1);
4842 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
4843 fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
4844 assert( parentSize<64 );
4845 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
4846 insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
4847 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
4848 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
4849
4850 /* If this is an auto-vacuum database, update the pointer map
4851 ** with entries for the new page, and any pointer from the
4852 ** cell on the page to an overflow page.
4853 */
4854 if( ISAUTOVACUUM ){
4855 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
4856 if( rc==SQLITE_OK ){
4857 rc = ptrmapPutOvfl(pNew, 0);
4858 }
danielk1977ac11ee62005-01-15 12:45:51 +00004859 }
danielk1977e08a3c42008-09-18 18:17:03 +00004860
4861 /* Release the reference to the new page. */
4862 releasePage(pNew);
danielk1977ac11ee62005-01-15 12:45:51 +00004863 }
4864
danielk1977eaa06f62008-09-18 17:34:44 +00004865 /* At this point the pPage->nFree variable is not set correctly with
4866 ** respect to the content of the page (because it was set to 0 by
4867 ** insertCell). So call sqlite3BtreeInitPage() to make sure it is
4868 ** correct.
4869 **
4870 ** This has to be done even if an error will be returned. Normally, if
4871 ** an error occurs during tree balancing, the contents of MemPage are
4872 ** not important, as they will be recalculated when the page is rolled
4873 ** back. But here, in balance_quick(), it is possible that pPage has
4874 ** not yet been marked dirty or written into the journal file. Therefore
4875 ** it will not be rolled back and so it is important to make sure that
4876 ** the page data and contents of MemPage are consistent.
4877 */
4878 pPage->isInit = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004879 sqlite3BtreeInitPage(pPage);
danielk1977eaa06f62008-09-18 17:34:44 +00004880
danielk1977e08a3c42008-09-18 18:17:03 +00004881 /* If everything else succeeded, balance the parent page, in
4882 ** case the divider cell inserted caused it to become overfull.
danielk197779a40da2005-01-16 08:00:01 +00004883 */
danielk1977eaa06f62008-09-18 17:34:44 +00004884 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00004885 releasePage(pPage);
4886 pCur->iPage--;
4887 rc = balance(pCur, 0);
danielk1977eaa06f62008-09-18 17:34:44 +00004888 }
4889 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004890}
drh615ae552005-01-16 23:21:00 +00004891#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00004892
drhc3b70572003-01-04 19:44:07 +00004893/*
drhab01f612004-05-22 02:55:23 +00004894** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00004895** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00004896** Usually NN siblings on either side of pPage is used in the balancing,
4897** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00004898** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00004899** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00004900** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00004901**
drh0c6cc4e2004-06-15 02:13:26 +00004902** The number of siblings of pPage might be increased or decreased by one or
4903** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00004904** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00004905** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00004906** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00004907** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00004908**
drh8b2f49b2001-06-08 00:21:52 +00004909** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00004910** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00004911** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00004912** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00004913**
drh8c42ca92001-06-22 19:15:00 +00004914** In the course of balancing the siblings of pPage, the parent of pPage
4915** might become overfull or underfull. If that happens, then this routine
4916** is called recursively on the parent.
4917**
drh5e00f6c2001-09-13 13:46:56 +00004918** If this routine fails for any reason, it might leave the database
4919** in a corrupted state. So if this routine fails, the database should
4920** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00004921*/
danielk197771d5d2c2008-09-29 11:49:47 +00004922static int balance_nonroot(BtCursor *pCur){
4923 MemPage *pPage; /* The over or underfull page to balance */
drh8b2f49b2001-06-08 00:21:52 +00004924 MemPage *pParent; /* The parent of pPage */
drh16a9b832007-05-05 18:39:25 +00004925 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00004926 int nCell = 0; /* Number of cells in apCell[] */
4927 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
drh8b2f49b2001-06-08 00:21:52 +00004928 int nOld; /* Number of pages in apOld[] */
4929 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00004930 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00004931 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00004932 int idx; /* Index of pPage in pParent->aCell[] */
4933 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00004934 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00004935 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00004936 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00004937 int usableSpace; /* Bytes in pPage beyond the header */
4938 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00004939 int subtotal; /* Subtotal of bytes in cells on one page */
drhe5ae5732008-06-15 02:51:47 +00004940 int iSpace1 = 0; /* First unused byte of aSpace1[] */
4941 int iSpace2 = 0; /* First unused byte of aSpace2[] */
drhfacf0302008-06-17 15:12:00 +00004942 int szScratch; /* Size of scratch memory requested */
drhc3b70572003-01-04 19:44:07 +00004943 MemPage *apOld[NB]; /* pPage and up to two siblings */
4944 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00004945 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00004946 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
4947 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drh4b70f112004-05-02 21:12:19 +00004948 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00004949 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
4950 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00004951 u8 **apCell = 0; /* All cells begin balanced */
drha9121e42008-02-19 14:59:35 +00004952 u16 *szCell; /* Local size of all cells in apCell[] */
drhe5ae5732008-06-15 02:51:47 +00004953 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
4954 u8 *aSpace1; /* Space for copies of dividers cells before balance */
4955 u8 *aSpace2 = 0; /* Space for overflow dividers cells after balance */
danielk1977ac11ee62005-01-15 12:45:51 +00004956 u8 *aFrom = 0;
drh8b2f49b2001-06-08 00:21:52 +00004957
danielk197771d5d2c2008-09-29 11:49:47 +00004958 pPage = pCur->apPage[pCur->iPage];
drh1fee73e2007-08-29 04:00:57 +00004959 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf94a1732008-09-30 17:18:17 +00004960 VVA_ONLY( pCur->pagesShuffled = 1 );
drhd677b3d2007-08-20 22:48:41 +00004961
drh14acc042001-06-10 19:56:58 +00004962 /*
drh43605152004-05-29 21:46:49 +00004963 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00004964 */
danielk197771d5d2c2008-09-29 11:49:47 +00004965 assert( pCur->iPage>0 );
4966 assert( pPage->isInit );
danielk19776e465eb2007-08-21 13:11:00 +00004967 assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 );
drh4b70f112004-05-02 21:12:19 +00004968 pBt = pPage->pBt;
danielk197771d5d2c2008-09-29 11:49:47 +00004969 pParent = pCur->apPage[pCur->iPage-1];
drh43605152004-05-29 21:46:49 +00004970 assert( pParent );
danielk19773b8a05f2007-03-19 17:44:26 +00004971 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
danielk197707cb5602006-01-20 10:55:05 +00004972 return rc;
4973 }
danielk1977474b7cc2008-07-09 11:49:46 +00004974
drh43605152004-05-29 21:46:49 +00004975 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00004976
drh615ae552005-01-16 23:21:00 +00004977#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004978 /*
4979 ** A special case: If a new entry has just been inserted into a
4980 ** table (that is, a btree with integer keys and all data at the leaves)
drh09d0deb2005-08-02 17:13:09 +00004981 ** and the new entry is the right-most entry in the tree (it has the
drhf222e712005-01-14 22:55:49 +00004982 ** largest key) then use the special balance_quick() routine for
4983 ** balancing. balance_quick() is much faster and results in a tighter
4984 ** packing of data in the common case.
4985 */
danielk1977ac245ec2005-01-14 13:50:11 +00004986 if( pPage->leaf &&
4987 pPage->intKey &&
danielk1977ac245ec2005-01-14 13:50:11 +00004988 pPage->nOverflow==1 &&
4989 pPage->aOvfl[0].idx==pPage->nCell &&
danielk197771d5d2c2008-09-29 11:49:47 +00004990 pParent->pgno!=1 &&
danielk1977ac245ec2005-01-14 13:50:11 +00004991 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
4992 ){
drh44845222008-07-17 18:39:57 +00004993 assert( pPage->intKey );
danielk1977ac11ee62005-01-15 12:45:51 +00004994 /*
4995 ** TODO: Check the siblings to the left of pPage. It may be that
4996 ** they are not full and no new page is required.
4997 */
danielk197771d5d2c2008-09-29 11:49:47 +00004998 return balance_quick(pCur);
danielk1977ac245ec2005-01-14 13:50:11 +00004999 }
5000#endif
5001
danielk19776e465eb2007-08-21 13:11:00 +00005002 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){
5003 return rc;
5004 }
5005
drh2e38c322004-09-03 18:38:44 +00005006 /*
drh4b70f112004-05-02 21:12:19 +00005007 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00005008 ** to pPage. The "idx" variable is the index of that cell. If pPage
5009 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00005010 */
danielk1977bf93c562008-09-29 15:53:25 +00005011 idx = pCur->aiIdx[pCur->iPage-1];
5012 assertParentIndex(pParent, idx, pPage->pgno);
drh8b2f49b2001-06-08 00:21:52 +00005013
5014 /*
drh14acc042001-06-10 19:56:58 +00005015 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00005016 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00005017 */
drh14acc042001-06-10 19:56:58 +00005018 nOld = nNew = 0;
drh14acc042001-06-10 19:56:58 +00005019
5020 /*
drh4b70f112004-05-02 21:12:19 +00005021 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00005022 ** the siblings. An attempt is made to find NN siblings on either
5023 ** side of pPage. More siblings are taken from one side, however, if
5024 ** pPage there are fewer than NN siblings on the other side. If pParent
5025 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00005026 */
drhc3b70572003-01-04 19:44:07 +00005027 nxDiv = idx - NN;
5028 if( nxDiv + NB > pParent->nCell ){
5029 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00005030 }
drhc3b70572003-01-04 19:44:07 +00005031 if( nxDiv<0 ){
5032 nxDiv = 0;
5033 }
drh8b2f49b2001-06-08 00:21:52 +00005034 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00005035 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00005036 if( k<pParent->nCell ){
danielk19771cc5ed82007-05-16 17:28:43 +00005037 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00005038 nDiv++;
drha34b6762004-05-07 13:30:42 +00005039 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00005040 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00005041 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00005042 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00005043 }else{
5044 break;
drh8b2f49b2001-06-08 00:21:52 +00005045 }
danielk197771d5d2c2008-09-29 11:49:47 +00005046 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i]);
drh6019e162001-07-02 17:51:45 +00005047 if( rc ) goto balance_cleanup;
danielk197771d5d2c2008-09-29 11:49:47 +00005048 /* apOld[i]->idxParent = k; */
drh91025292004-05-03 19:49:32 +00005049 apCopy[i] = 0;
5050 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00005051 nOld++;
danielk1977634f2982005-03-28 08:44:07 +00005052 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
drh8b2f49b2001-06-08 00:21:52 +00005053 }
5054
drha9121e42008-02-19 14:59:35 +00005055 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00005056 ** alignment */
drha9121e42008-02-19 14:59:35 +00005057 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00005058
drh8b2f49b2001-06-08 00:21:52 +00005059 /*
danielk1977634f2982005-03-28 08:44:07 +00005060 ** Allocate space for memory structures
5061 */
drhfacf0302008-06-17 15:12:00 +00005062 szScratch =
drha9121e42008-02-19 14:59:35 +00005063 nMaxCells*sizeof(u8*) /* apCell */
5064 + nMaxCells*sizeof(u16) /* szCell */
5065 + (ROUND8(sizeof(MemPage))+pBt->pageSize)*NB /* aCopy */
drhe5ae5732008-06-15 02:51:47 +00005066 + pBt->pageSize /* aSpace1 */
drhfacf0302008-06-17 15:12:00 +00005067 + (ISAUTOVACUUM ? nMaxCells : 0); /* aFrom */
5068 apCell = sqlite3ScratchMalloc( szScratch );
danielk1977634f2982005-03-28 08:44:07 +00005069 if( apCell==0 ){
5070 rc = SQLITE_NOMEM;
5071 goto balance_cleanup;
5072 }
drha9121e42008-02-19 14:59:35 +00005073 szCell = (u16*)&apCell[nMaxCells];
danielk1977634f2982005-03-28 08:44:07 +00005074 aCopy[0] = (u8*)&szCell[nMaxCells];
drhc96d8532005-05-03 12:30:33 +00005075 assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00005076 for(i=1; i<NB; i++){
drhc96d8532005-05-03 12:30:33 +00005077 aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
5078 assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00005079 }
drhe5ae5732008-06-15 02:51:47 +00005080 aSpace1 = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
5081 assert( ((aSpace1 - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk197785d90ca2008-07-19 14:25:15 +00005082 if( ISAUTOVACUUM ){
drhe5ae5732008-06-15 02:51:47 +00005083 aFrom = &aSpace1[pBt->pageSize];
danielk1977634f2982005-03-28 08:44:07 +00005084 }
drhfacf0302008-06-17 15:12:00 +00005085 aSpace2 = sqlite3PageMalloc(pBt->pageSize);
drhe5ae5732008-06-15 02:51:47 +00005086 if( aSpace2==0 ){
5087 rc = SQLITE_NOMEM;
5088 goto balance_cleanup;
5089 }
danielk1977634f2982005-03-28 08:44:07 +00005090
5091 /*
drh14acc042001-06-10 19:56:58 +00005092 ** Make copies of the content of pPage and its siblings into aOld[].
5093 ** The rest of this function will use data from the copies rather
5094 ** that the original pages since the original pages will be in the
5095 ** process of being overwritten.
5096 */
5097 for(i=0; i<nOld; i++){
drhbf4bca52007-09-06 22:19:14 +00005098 MemPage *p = apCopy[i] = (MemPage*)aCopy[i];
5099 memcpy(p, apOld[i], sizeof(MemPage));
5100 p->aData = (void*)&p[1];
5101 memcpy(p->aData, apOld[i]->aData, pBt->pageSize);
drh14acc042001-06-10 19:56:58 +00005102 }
5103
5104 /*
5105 ** Load pointers to all cells on sibling pages and the divider cells
5106 ** into the local apCell[] array. Make copies of the divider cells
drhe5ae5732008-06-15 02:51:47 +00005107 ** into space obtained form aSpace1[] and remove the the divider Cells
drhb6f41482004-05-14 01:58:11 +00005108 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00005109 **
5110 ** If the siblings are on leaf pages, then the child pointers of the
5111 ** divider cells are stripped from the cells before they are copied
drhe5ae5732008-06-15 02:51:47 +00005112 ** into aSpace1[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00005113 ** child pointers. If siblings are not leaves, then all cell in
5114 ** apCell[] include child pointers. Either way, all cells in apCell[]
5115 ** are alike.
drh96f5b762004-05-16 16:24:36 +00005116 **
5117 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
5118 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00005119 */
5120 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00005121 leafCorrection = pPage->leaf*4;
drh44845222008-07-17 18:39:57 +00005122 leafData = pPage->hasData;
drh8b2f49b2001-06-08 00:21:52 +00005123 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00005124 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00005125 int limit = pOld->nCell+pOld->nOverflow;
5126 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00005127 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00005128 apCell[nCell] = findOverflowCell(pOld, j);
5129 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk197785d90ca2008-07-19 14:25:15 +00005130 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005131 int a;
5132 aFrom[nCell] = i;
5133 for(a=0; a<pOld->nOverflow; a++){
5134 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
5135 aFrom[nCell] = 0xFF;
5136 break;
5137 }
5138 }
5139 }
drh14acc042001-06-10 19:56:58 +00005140 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00005141 }
5142 if( i<nOld-1 ){
drha9121e42008-02-19 14:59:35 +00005143 u16 sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00005144 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00005145 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
5146 ** are duplicates of keys on the child pages. We need to remove
5147 ** the divider cells from pParent, but the dividers cells are not
5148 ** added to apCell[] because they are duplicates of child cells.
5149 */
drh8b18dd42004-05-12 19:18:15 +00005150 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00005151 }else{
drhb6f41482004-05-14 01:58:11 +00005152 u8 *pTemp;
danielk1977634f2982005-03-28 08:44:07 +00005153 assert( nCell<nMaxCells );
drhb6f41482004-05-14 01:58:11 +00005154 szCell[nCell] = sz;
drhe5ae5732008-06-15 02:51:47 +00005155 pTemp = &aSpace1[iSpace1];
5156 iSpace1 += sz;
5157 assert( sz<=pBt->pageSize/4 );
5158 assert( iSpace1<=pBt->pageSize );
drhb6f41482004-05-14 01:58:11 +00005159 memcpy(pTemp, apDiv[i], sz);
5160 apCell[nCell] = pTemp+leafCorrection;
danielk197785d90ca2008-07-19 14:25:15 +00005161 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005162 aFrom[nCell] = 0xFF;
5163 }
drhb6f41482004-05-14 01:58:11 +00005164 dropCell(pParent, nxDiv, sz);
drh8b18dd42004-05-12 19:18:15 +00005165 szCell[nCell] -= leafCorrection;
drh43605152004-05-29 21:46:49 +00005166 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00005167 if( !pOld->leaf ){
5168 assert( leafCorrection==0 );
5169 /* The right pointer of the child page pOld becomes the left
5170 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00005171 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00005172 }else{
5173 assert( leafCorrection==4 );
danielk197739c96042007-05-12 10:41:47 +00005174 if( szCell[nCell]<4 ){
5175 /* Do not allow any cells smaller than 4 bytes. */
5176 szCell[nCell] = 4;
5177 }
drh8b18dd42004-05-12 19:18:15 +00005178 }
5179 nCell++;
drh4b70f112004-05-02 21:12:19 +00005180 }
drh8b2f49b2001-06-08 00:21:52 +00005181 }
5182 }
5183
5184 /*
drh6019e162001-07-02 17:51:45 +00005185 ** Figure out the number of pages needed to hold all nCell cells.
5186 ** Store this number in "k". Also compute szNew[] which is the total
5187 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00005188 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00005189 ** cntNew[k] should equal nCell.
5190 **
drh96f5b762004-05-16 16:24:36 +00005191 ** Values computed by this block:
5192 **
5193 ** k: The total number of sibling pages
5194 ** szNew[i]: Spaced used on the i-th sibling page.
5195 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
5196 ** the right of the i-th sibling page.
5197 ** usableSpace: Number of bytes of space available on each sibling.
5198 **
drh8b2f49b2001-06-08 00:21:52 +00005199 */
drh43605152004-05-29 21:46:49 +00005200 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00005201 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00005202 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00005203 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00005204 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00005205 szNew[k] = subtotal - szCell[i];
5206 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00005207 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00005208 subtotal = 0;
5209 k++;
5210 }
5211 }
5212 szNew[k] = subtotal;
5213 cntNew[k] = nCell;
5214 k++;
drh96f5b762004-05-16 16:24:36 +00005215
5216 /*
5217 ** The packing computed by the previous block is biased toward the siblings
5218 ** on the left side. The left siblings are always nearly full, while the
5219 ** right-most sibling might be nearly empty. This block of code attempts
5220 ** to adjust the packing of siblings to get a better balance.
5221 **
5222 ** This adjustment is more than an optimization. The packing above might
5223 ** be so out of balance as to be illegal. For example, the right-most
5224 ** sibling might be completely empty. This adjustment is not optional.
5225 */
drh6019e162001-07-02 17:51:45 +00005226 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00005227 int szRight = szNew[i]; /* Size of sibling on the right */
5228 int szLeft = szNew[i-1]; /* Size of sibling on the left */
5229 int r; /* Index of right-most cell in left sibling */
5230 int d; /* Index of first cell to the left of right sibling */
5231
5232 r = cntNew[i-1] - 1;
5233 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00005234 assert( d<nMaxCells );
5235 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00005236 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
5237 szRight += szCell[d] + 2;
5238 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00005239 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00005240 r = cntNew[i-1] - 1;
5241 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00005242 }
drh96f5b762004-05-16 16:24:36 +00005243 szNew[i] = szRight;
5244 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00005245 }
drh09d0deb2005-08-02 17:13:09 +00005246
5247 /* Either we found one or more cells (cntnew[0])>0) or we are the
5248 ** a virtual root page. A virtual root page is when the real root
5249 ** page is page 1 and we are the only child of that page.
5250 */
5251 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00005252
5253 /*
drh6b308672002-07-08 02:16:37 +00005254 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00005255 */
drh4b70f112004-05-02 21:12:19 +00005256 assert( pPage->pgno>1 );
5257 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00005258 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00005259 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00005260 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00005261 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00005262 pgnoNew[i] = pgnoOld[i];
5263 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00005264 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00005265 nNew++;
danielk197728129562005-01-11 10:25:06 +00005266 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00005267 }else{
drh7aa8f852006-03-28 00:24:44 +00005268 assert( i>0 );
drh4f0c5872007-03-26 22:05:01 +00005269 rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
drh6b308672002-07-08 02:16:37 +00005270 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00005271 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00005272 nNew++;
drh6b308672002-07-08 02:16:37 +00005273 }
drh8b2f49b2001-06-08 00:21:52 +00005274 }
5275
danielk1977299b1872004-11-22 10:02:10 +00005276 /* Free any old pages that were not reused as new pages.
5277 */
5278 while( i<nOld ){
5279 rc = freePage(apOld[i]);
5280 if( rc ) goto balance_cleanup;
5281 releasePage(apOld[i]);
5282 apOld[i] = 0;
5283 i++;
5284 }
5285
drh8b2f49b2001-06-08 00:21:52 +00005286 /*
drhf9ffac92002-03-02 19:00:31 +00005287 ** Put the new pages in accending order. This helps to
5288 ** keep entries in the disk file in order so that a scan
5289 ** of the table is a linear scan through the file. That
5290 ** in turn helps the operating system to deliver pages
5291 ** from the disk more rapidly.
5292 **
5293 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00005294 ** n is never more than NB (a small constant), that should
5295 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00005296 **
drhc3b70572003-01-04 19:44:07 +00005297 ** When NB==3, this one optimization makes the database
5298 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00005299 */
5300 for(i=0; i<k-1; i++){
5301 int minV = pgnoNew[i];
5302 int minI = i;
5303 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00005304 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00005305 minI = j;
5306 minV = pgnoNew[j];
5307 }
5308 }
5309 if( minI>i ){
5310 int t;
5311 MemPage *pT;
5312 t = pgnoNew[i];
5313 pT = apNew[i];
5314 pgnoNew[i] = pgnoNew[minI];
5315 apNew[i] = apNew[minI];
5316 pgnoNew[minI] = t;
5317 apNew[minI] = pT;
5318 }
5319 }
drha2fce642004-06-05 00:01:44 +00005320 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00005321 pgnoOld[0],
5322 nOld>=2 ? pgnoOld[1] : 0,
5323 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00005324 pgnoNew[0], szNew[0],
5325 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
5326 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00005327 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
5328 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00005329
drhf9ffac92002-03-02 19:00:31 +00005330 /*
drh14acc042001-06-10 19:56:58 +00005331 ** Evenly distribute the data in apCell[] across the new pages.
5332 ** Insert divider cells into pParent as necessary.
5333 */
5334 j = 0;
5335 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00005336 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00005337 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00005338 assert( j<nMaxCells );
drh4b70f112004-05-02 21:12:19 +00005339 assert( pNew->pgno==pgnoNew[i] );
drh10131482008-07-11 03:34:09 +00005340 zeroPage(pNew, pageFlags);
drhfa1a98a2004-05-14 19:08:17 +00005341 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00005342 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00005343 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00005344
danielk1977ac11ee62005-01-15 12:45:51 +00005345 /* If this is an auto-vacuum database, update the pointer map entries
5346 ** that point to the siblings that were rearranged. These can be: left
5347 ** children of cells, the right-child of the page, or overflow pages
5348 ** pointed to by cells.
5349 */
danielk197785d90ca2008-07-19 14:25:15 +00005350 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005351 for(k=j; k<cntNew[i]; k++){
danielk1977634f2982005-03-28 08:44:07 +00005352 assert( k<nMaxCells );
danielk1977ac11ee62005-01-15 12:45:51 +00005353 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
danielk197779a40da2005-01-16 08:00:01 +00005354 rc = ptrmapPutOvfl(pNew, k-j);
danielk197787c52b52008-07-19 11:49:07 +00005355 if( rc==SQLITE_OK && leafCorrection==0 ){
5356 rc = ptrmapPut(pBt, get4byte(apCell[k]), PTRMAP_BTREE, pNew->pgno);
5357 }
danielk197779a40da2005-01-16 08:00:01 +00005358 if( rc!=SQLITE_OK ){
5359 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00005360 }
5361 }
5362 }
5363 }
danielk1977ac11ee62005-01-15 12:45:51 +00005364
5365 j = cntNew[i];
5366
5367 /* If the sibling page assembled above was not the right-most sibling,
5368 ** insert a divider cell into the parent page.
5369 */
drh14acc042001-06-10 19:56:58 +00005370 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00005371 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00005372 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00005373 int sz;
danielk1977634f2982005-03-28 08:44:07 +00005374
5375 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00005376 pCell = apCell[j];
5377 sz = szCell[j] + leafCorrection;
drhe5ae5732008-06-15 02:51:47 +00005378 pTemp = &aSpace2[iSpace2];
drh4b70f112004-05-02 21:12:19 +00005379 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00005380 memcpy(&pNew->aData[8], pCell, 4);
danielk197785d90ca2008-07-19 14:25:15 +00005381 if( ISAUTOVACUUM
danielk197787c52b52008-07-19 11:49:07 +00005382 && (aFrom[j]==0xFF || apCopy[aFrom[j]]->pgno!=pNew->pgno)
5383 ){
5384 rc = ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno);
5385 if( rc!=SQLITE_OK ){
5386 goto balance_cleanup;
5387 }
5388 }
drh8b18dd42004-05-12 19:18:15 +00005389 }else if( leafData ){
drhfd131da2007-08-07 17:13:03 +00005390 /* If the tree is a leaf-data tree, and the siblings are leaves,
danielk1977ac11ee62005-01-15 12:45:51 +00005391 ** then there is no divider cell in apCell[]. Instead, the divider
5392 ** cell consists of the integer key for the right-most cell of
5393 ** the sibling-page assembled above only.
5394 */
drh6f11bef2004-05-13 01:12:56 +00005395 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00005396 j--;
drh16a9b832007-05-05 18:39:25 +00005397 sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
drhe5ae5732008-06-15 02:51:47 +00005398 pCell = pTemp;
drhb026e052007-05-02 01:34:31 +00005399 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
drh8b18dd42004-05-12 19:18:15 +00005400 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00005401 }else{
5402 pCell -= 4;
danielk19774aeff622007-05-12 09:30:47 +00005403 /* Obscure case for non-leaf-data trees: If the cell at pCell was
drh85b623f2007-12-13 21:54:09 +00005404 ** previously stored on a leaf node, and its reported size was 4
danielk19774aeff622007-05-12 09:30:47 +00005405 ** bytes, then it may actually be smaller than this
5406 ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
drh85b623f2007-12-13 21:54:09 +00005407 ** any cell). But it is important to pass the correct size to
danielk19774aeff622007-05-12 09:30:47 +00005408 ** insertCell(), so reparse the cell now.
5409 **
5410 ** Note that this can never happen in an SQLite data file, as all
5411 ** cells are at least 4 bytes. It only happens in b-trees used
5412 ** to evaluate "IN (SELECT ...)" and similar clauses.
5413 */
5414 if( szCell[j]==4 ){
5415 assert(leafCorrection==4);
5416 sz = cellSizePtr(pParent, pCell);
5417 }
drh4b70f112004-05-02 21:12:19 +00005418 }
drhe5ae5732008-06-15 02:51:47 +00005419 iSpace2 += sz;
5420 assert( sz<=pBt->pageSize/4 );
5421 assert( iSpace2<=pBt->pageSize );
danielk1977a3ad5e72005-01-07 08:56:44 +00005422 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
danielk1977e80463b2004-11-03 03:01:16 +00005423 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh43605152004-05-29 21:46:49 +00005424 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
danielk197785d90ca2008-07-19 14:25:15 +00005425
danielk1977ac11ee62005-01-15 12:45:51 +00005426 /* If this is an auto-vacuum database, and not a leaf-data tree,
5427 ** then update the pointer map with an entry for the overflow page
5428 ** that the cell just inserted points to (if any).
5429 */
danielk197785d90ca2008-07-19 14:25:15 +00005430 if( ISAUTOVACUUM && !leafData ){
danielk197779a40da2005-01-16 08:00:01 +00005431 rc = ptrmapPutOvfl(pParent, nxDiv);
5432 if( rc!=SQLITE_OK ){
5433 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00005434 }
5435 }
drh14acc042001-06-10 19:56:58 +00005436 j++;
5437 nxDiv++;
5438 }
danielk197787c52b52008-07-19 11:49:07 +00005439
danielk197787c52b52008-07-19 11:49:07 +00005440 /* Set the pointer-map entry for the new sibling page. */
danielk197785d90ca2008-07-19 14:25:15 +00005441 if( ISAUTOVACUUM ){
danielk197787c52b52008-07-19 11:49:07 +00005442 rc = ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno);
5443 if( rc!=SQLITE_OK ){
5444 goto balance_cleanup;
5445 }
5446 }
drh14acc042001-06-10 19:56:58 +00005447 }
drh6019e162001-07-02 17:51:45 +00005448 assert( j==nCell );
drh7aa8f852006-03-28 00:24:44 +00005449 assert( nOld>0 );
5450 assert( nNew>0 );
drh4b70f112004-05-02 21:12:19 +00005451 if( (pageFlags & PTF_LEAF)==0 ){
danielk197787c52b52008-07-19 11:49:07 +00005452 u8 *zChild = &apCopy[nOld-1]->aData[8];
5453 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
danielk197785d90ca2008-07-19 14:25:15 +00005454 if( ISAUTOVACUUM ){
danielk197787c52b52008-07-19 11:49:07 +00005455 rc = ptrmapPut(pBt, get4byte(zChild), PTRMAP_BTREE, apNew[nNew-1]->pgno);
5456 if( rc!=SQLITE_OK ){
5457 goto balance_cleanup;
5458 }
5459 }
drh14acc042001-06-10 19:56:58 +00005460 }
drh43605152004-05-29 21:46:49 +00005461 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00005462 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00005463 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00005464 }else{
5465 /* Right-most sibling is the left child of the first entry in pParent
5466 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00005467 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00005468 }
5469
5470 /*
drh3a4c1412004-05-09 20:40:11 +00005471 ** Balance the parent page. Note that the current page (pPage) might
danielk1977ac11ee62005-01-15 12:45:51 +00005472 ** have been added to the freelist so it might no longer be initialized.
drh3a4c1412004-05-09 20:40:11 +00005473 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00005474 */
danielk197771d5d2c2008-09-29 11:49:47 +00005475 assert( pParent->isInit );
drhfacf0302008-06-17 15:12:00 +00005476 sqlite3ScratchFree(apCell);
drhe5ae5732008-06-15 02:51:47 +00005477 apCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005478 releasePage(pPage);
5479 pCur->iPage--;
5480 rc = balance(pCur, 0);
drhda200cc2004-05-09 11:51:38 +00005481
drh8b2f49b2001-06-08 00:21:52 +00005482 /*
drh14acc042001-06-10 19:56:58 +00005483 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00005484 */
drh14acc042001-06-10 19:56:58 +00005485balance_cleanup:
drhfacf0302008-06-17 15:12:00 +00005486 sqlite3PageFree(aSpace2);
5487 sqlite3ScratchFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00005488 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00005489 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00005490 }
drh14acc042001-06-10 19:56:58 +00005491 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00005492 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00005493 }
danielk1977eaa06f62008-09-18 17:34:44 +00005494
danielk197771d5d2c2008-09-29 11:49:47 +00005495 /* releasePage(pParent); */
drh3a4c1412004-05-09 20:40:11 +00005496 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
5497 pPage->pgno, nOld, nNew, nCell));
danielk1977eaa06f62008-09-18 17:34:44 +00005498
drh8b2f49b2001-06-08 00:21:52 +00005499 return rc;
5500}
5501
5502/*
drh43605152004-05-29 21:46:49 +00005503** This routine is called for the root page of a btree when the root
5504** page contains no cells. This is an opportunity to make the tree
5505** shallower by one level.
5506*/
danielk197771d5d2c2008-09-29 11:49:47 +00005507static int balance_shallower(BtCursor *pCur){
5508 MemPage *pPage; /* Root page of B-Tree */
drh43605152004-05-29 21:46:49 +00005509 MemPage *pChild; /* The only child page of pPage */
5510 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00005511 int rc = SQLITE_OK; /* Return code from subprocedures */
danielk1977aef0bf62005-12-30 16:28:01 +00005512 BtShared *pBt; /* The main BTree structure */
drh2e38c322004-09-03 18:38:44 +00005513 int mxCellPerPage; /* Maximum number of cells per page */
5514 u8 **apCell; /* All cells from pages being balanced */
drha9121e42008-02-19 14:59:35 +00005515 u16 *szCell; /* Local size of all cells */
drh43605152004-05-29 21:46:49 +00005516
danielk197771d5d2c2008-09-29 11:49:47 +00005517 assert( pCur->iPage==0 );
5518 pPage = pCur->apPage[0];
5519
drh43605152004-05-29 21:46:49 +00005520 assert( pPage->nCell==0 );
drh1fee73e2007-08-29 04:00:57 +00005521 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh2e38c322004-09-03 18:38:44 +00005522 pBt = pPage->pBt;
5523 mxCellPerPage = MX_CELL(pBt);
drhe5ae5732008-06-15 02:51:47 +00005524 apCell = sqlite3Malloc( mxCellPerPage*(sizeof(u8*)+sizeof(u16)) );
drh2e38c322004-09-03 18:38:44 +00005525 if( apCell==0 ) return SQLITE_NOMEM;
drha9121e42008-02-19 14:59:35 +00005526 szCell = (u16*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00005527 if( pPage->leaf ){
5528 /* The table is completely empty */
5529 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
5530 }else{
5531 /* The root page is empty but has one child. Transfer the
5532 ** information from that one child into the root page if it
5533 ** will fit. This reduces the depth of the tree by one.
5534 **
5535 ** If the root page is page 1, it has less space available than
5536 ** its child (due to the 100 byte header that occurs at the beginning
5537 ** of the database fle), so it might not be able to hold all of the
5538 ** information currently contained in the child. If this is the
5539 ** case, then do not do the transfer. Leave page 1 empty except
5540 ** for the right-pointer to the child page. The child page becomes
5541 ** the virtual root of the tree.
5542 */
drhf94a1732008-09-30 17:18:17 +00005543 VVA_ONLY( pCur->pagesShuffled = 1 );
drh43605152004-05-29 21:46:49 +00005544 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5545 assert( pgnoChild>0 );
danielk1977ad0132d2008-06-07 08:58:22 +00005546 assert( pgnoChild<=pagerPagecount(pPage->pBt->pPager) );
drh16a9b832007-05-05 18:39:25 +00005547 rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
drh2e38c322004-09-03 18:38:44 +00005548 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005549 if( pPage->pgno==1 ){
danielk197771d5d2c2008-09-29 11:49:47 +00005550 rc = sqlite3BtreeInitPage(pChild);
drh2e38c322004-09-03 18:38:44 +00005551 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005552 assert( pChild->nOverflow==0 );
5553 if( pChild->nFree>=100 ){
5554 /* The child information will fit on the root page, so do the
5555 ** copy */
5556 int i;
5557 zeroPage(pPage, pChild->aData[0]);
5558 for(i=0; i<pChild->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00005559 apCell[i] = findCell(pChild,i);
drh43605152004-05-29 21:46:49 +00005560 szCell[i] = cellSizePtr(pChild, apCell[i]);
5561 }
5562 assemblePage(pPage, pChild->nCell, apCell, szCell);
danielk1977ae825582004-11-23 09:06:55 +00005563 /* Copy the right-pointer of the child to the parent. */
5564 put4byte(&pPage->aData[pPage->hdrOffset+8],
5565 get4byte(&pChild->aData[pChild->hdrOffset+8]));
drh43605152004-05-29 21:46:49 +00005566 freePage(pChild);
5567 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
5568 }else{
5569 /* The child has more information that will fit on the root.
5570 ** The tree is already balanced. Do nothing. */
5571 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
5572 }
5573 }else{
5574 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
5575 pPage->isInit = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005576 rc = sqlite3BtreeInitPage(pPage);
drh43605152004-05-29 21:46:49 +00005577 assert( rc==SQLITE_OK );
5578 freePage(pChild);
5579 TRACE(("BALANCE: transfer child %d into root %d\n",
5580 pChild->pgno, pPage->pgno));
5581 }
danielk1977ac11ee62005-01-15 12:45:51 +00005582 assert( pPage->nOverflow==0 );
shane831c3292008-11-10 17:14:58 +00005583#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197785d90ca2008-07-19 14:25:15 +00005584 if( ISAUTOVACUUM ){
danielk197700a696d2008-09-29 16:41:31 +00005585 rc = setChildPtrmaps(pPage);
danielk1977ac11ee62005-01-15 12:45:51 +00005586 }
shane831c3292008-11-10 17:14:58 +00005587#endif
drh43605152004-05-29 21:46:49 +00005588 releasePage(pChild);
5589 }
drh2e38c322004-09-03 18:38:44 +00005590end_shallow_balance:
drh17435752007-08-16 04:30:38 +00005591 sqlite3_free(apCell);
drh2e38c322004-09-03 18:38:44 +00005592 return rc;
drh43605152004-05-29 21:46:49 +00005593}
5594
5595
5596/*
5597** The root page is overfull
5598**
5599** When this happens, Create a new child page and copy the
5600** contents of the root into the child. Then make the root
5601** page an empty page with rightChild pointing to the new
5602** child. Finally, call balance_internal() on the new child
5603** to cause it to split.
5604*/
danielk197771d5d2c2008-09-29 11:49:47 +00005605static int balance_deeper(BtCursor *pCur){
drh43605152004-05-29 21:46:49 +00005606 int rc; /* Return value from subprocedures */
danielk197771d5d2c2008-09-29 11:49:47 +00005607 MemPage *pPage; /* Pointer to the root page */
drh43605152004-05-29 21:46:49 +00005608 MemPage *pChild; /* Pointer to a new child page */
5609 Pgno pgnoChild; /* Page number of the new child page */
danielk1977aef0bf62005-12-30 16:28:01 +00005610 BtShared *pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00005611 int usableSize; /* Total usable size of a page */
5612 u8 *data; /* Content of the parent page */
5613 u8 *cdata; /* Content of the child page */
5614 int hdr; /* Offset to page header in parent */
drh281b21d2008-08-22 12:57:08 +00005615 int cbrk; /* Offset to content of first cell in parent */
drh43605152004-05-29 21:46:49 +00005616
danielk197771d5d2c2008-09-29 11:49:47 +00005617 assert( pCur->iPage==0 );
5618 assert( pCur->apPage[0]->nOverflow>0 );
5619
drhf94a1732008-09-30 17:18:17 +00005620 VVA_ONLY( pCur->pagesShuffled = 1 );
danielk197771d5d2c2008-09-29 11:49:47 +00005621 pPage = pCur->apPage[0];
drh43605152004-05-29 21:46:49 +00005622 pBt = pPage->pBt;
drh1fee73e2007-08-29 04:00:57 +00005623 assert( sqlite3_mutex_held(pBt->mutex) );
drh4f0c5872007-03-26 22:05:01 +00005624 rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
drh43605152004-05-29 21:46:49 +00005625 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00005626 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
drh43605152004-05-29 21:46:49 +00005627 usableSize = pBt->usableSize;
5628 data = pPage->aData;
5629 hdr = pPage->hdrOffset;
drh281b21d2008-08-22 12:57:08 +00005630 cbrk = get2byte(&data[hdr+5]);
drh43605152004-05-29 21:46:49 +00005631 cdata = pChild->aData;
5632 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
drh281b21d2008-08-22 12:57:08 +00005633 memcpy(&cdata[cbrk], &data[cbrk], usableSize-cbrk);
danielk1977bc2ca9e2008-11-13 14:28:28 +00005634
5635 assert( pChild->isInit==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00005636 rc = sqlite3BtreeInitPage(pChild);
5637 if( rc==SQLITE_OK ){
5638 int nCopy = pPage->nOverflow*sizeof(pPage->aOvfl[0]);
5639 memcpy(pChild->aOvfl, pPage->aOvfl, nCopy);
5640 pChild->nOverflow = pPage->nOverflow;
5641 if( pChild->nOverflow ){
5642 pChild->nFree = 0;
5643 }
5644 assert( pChild->nCell==pPage->nCell );
5645 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
5646 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
5647 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
5648 if( ISAUTOVACUUM ){
danielk197771d5d2c2008-09-29 11:49:47 +00005649 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
shane831c3292008-11-10 17:14:58 +00005650#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197771d5d2c2008-09-29 11:49:47 +00005651 if( rc==SQLITE_OK ){
danielk197700a696d2008-09-29 16:41:31 +00005652 rc = setChildPtrmaps(pChild);
danielk1977ac11ee62005-01-15 12:45:51 +00005653 }
shane831c3292008-11-10 17:14:58 +00005654#endif
danielk1977ac11ee62005-01-15 12:45:51 +00005655 }
danielk197787c52b52008-07-19 11:49:07 +00005656 }
danielk19776b456a22005-03-21 04:04:02 +00005657
danielk197771d5d2c2008-09-29 11:49:47 +00005658 if( rc==SQLITE_OK ){
5659 pCur->iPage++;
5660 pCur->apPage[1] = pChild;
danielk1977bf93c562008-09-29 15:53:25 +00005661 pCur->aiIdx[0] = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005662 rc = balance_nonroot(pCur);
5663 }else{
5664 releasePage(pChild);
5665 }
5666
drh43605152004-05-29 21:46:49 +00005667 return rc;
5668}
5669
5670/*
danielk197771d5d2c2008-09-29 11:49:47 +00005671** The page that pCur currently points to has just been modified in
5672** some way. This function figures out if this modification means the
5673** tree needs to be balanced, and if so calls the appropriate balancing
5674** routine.
5675**
5676** Parameter isInsert is true if a new cell was just inserted into the
5677** page, or false otherwise.
drh43605152004-05-29 21:46:49 +00005678*/
danielk197771d5d2c2008-09-29 11:49:47 +00005679static int balance(BtCursor *pCur, int isInsert){
drh43605152004-05-29 21:46:49 +00005680 int rc = SQLITE_OK;
danielk197771d5d2c2008-09-29 11:49:47 +00005681 MemPage *pPage = pCur->apPage[pCur->iPage];
5682
drh1fee73e2007-08-29 04:00:57 +00005683 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197771d5d2c2008-09-29 11:49:47 +00005684 if( pCur->iPage==0 ){
danielk19776e465eb2007-08-21 13:11:00 +00005685 rc = sqlite3PagerWrite(pPage->pDbPage);
5686 if( rc==SQLITE_OK && pPage->nOverflow>0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00005687 rc = balance_deeper(pCur);
drh43605152004-05-29 21:46:49 +00005688 }
danielk1977687566d2004-11-02 12:56:41 +00005689 if( rc==SQLITE_OK && pPage->nCell==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00005690 rc = balance_shallower(pCur);
drh43605152004-05-29 21:46:49 +00005691 }
5692 }else{
danielk1977ac245ec2005-01-14 13:50:11 +00005693 if( pPage->nOverflow>0 ||
danielk197771d5d2c2008-09-29 11:49:47 +00005694 (!isInsert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
5695 rc = balance_nonroot(pCur);
drh43605152004-05-29 21:46:49 +00005696 }
5697 }
5698 return rc;
5699}
5700
5701/*
drh8dcd7ca2004-08-08 19:43:29 +00005702** This routine checks all cursors that point to table pgnoRoot.
drh980b1a72006-08-16 16:42:48 +00005703** If any of those cursors were opened with wrFlag==0 in a different
5704** database connection (a database connection that shares the pager
5705** cache with the current connection) and that other connection
5706** is not in the ReadUncommmitted state, then this routine returns
5707** SQLITE_LOCKED.
danielk1977299b1872004-11-22 10:02:10 +00005708**
danielk19773588ceb2008-06-10 17:30:26 +00005709** As well as cursors with wrFlag==0, cursors with wrFlag==1 and
5710** isIncrblobHandle==1 are also considered 'read' cursors. Incremental
5711** blob cursors are used for both reading and writing.
5712**
5713** When pgnoRoot is the root page of an intkey table, this function is also
5714** responsible for invalidating incremental blob cursors when the table row
5715** on which they are opened is deleted or modified. Cursors are invalidated
5716** according to the following rules:
5717**
5718** 1) When BtreeClearTable() is called to completely delete the contents
5719** of a B-Tree table, pExclude is set to zero and parameter iRow is
5720** set to non-zero. In this case all incremental blob cursors open
5721** on the table rooted at pgnoRoot are invalidated.
5722**
5723** 2) When BtreeInsert(), BtreeDelete() or BtreePutData() is called to
5724** modify a table row via an SQL statement, pExclude is set to the
5725** write cursor used to do the modification and parameter iRow is set
5726** to the integer row id of the B-Tree entry being modified. Unless
5727** pExclude is itself an incremental blob cursor, then all incremental
5728** blob cursors open on row iRow of the B-Tree are invalidated.
5729**
5730** 3) If both pExclude and iRow are set to zero, no incremental blob
5731** cursors are invalidated.
drhf74b8d92002-09-01 23:20:45 +00005732*/
danielk19773588ceb2008-06-10 17:30:26 +00005733static int checkReadLocks(
5734 Btree *pBtree,
5735 Pgno pgnoRoot,
5736 BtCursor *pExclude,
5737 i64 iRow
5738){
danielk1977299b1872004-11-22 10:02:10 +00005739 BtCursor *p;
drh980b1a72006-08-16 16:42:48 +00005740 BtShared *pBt = pBtree->pBt;
drhe5fe6902007-12-07 18:55:28 +00005741 sqlite3 *db = pBtree->db;
drh1fee73e2007-08-29 04:00:57 +00005742 assert( sqlite3BtreeHoldsMutex(pBtree) );
danielk1977299b1872004-11-22 10:02:10 +00005743 for(p=pBt->pCursor; p; p=p->pNext){
drh980b1a72006-08-16 16:42:48 +00005744 if( p==pExclude ) continue;
drh980b1a72006-08-16 16:42:48 +00005745 if( p->pgnoRoot!=pgnoRoot ) continue;
danielk19773588ceb2008-06-10 17:30:26 +00005746#ifndef SQLITE_OMIT_INCRBLOB
5747 if( p->isIncrblobHandle && (
5748 (!pExclude && iRow)
5749 || (pExclude && !pExclude->isIncrblobHandle && p->info.nKey==iRow)
5750 )){
5751 p->eState = CURSOR_INVALID;
5752 }
5753#endif
5754 if( p->eState!=CURSOR_VALID ) continue;
5755 if( p->wrFlag==0
5756#ifndef SQLITE_OMIT_INCRBLOB
5757 || p->isIncrblobHandle
5758#endif
5759 ){
drhe5fe6902007-12-07 18:55:28 +00005760 sqlite3 *dbOther = p->pBtree->db;
drh980b1a72006-08-16 16:42:48 +00005761 if( dbOther==0 ||
5762 (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
5763 return SQLITE_LOCKED;
5764 }
danielk1977299b1872004-11-22 10:02:10 +00005765 }
5766 }
drhf74b8d92002-09-01 23:20:45 +00005767 return SQLITE_OK;
5768}
5769
5770/*
drh3b7511c2001-05-26 13:15:44 +00005771** Insert a new record into the BTree. The key is given by (pKey,nKey)
5772** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00005773** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00005774** is left pointing at a random location.
5775**
5776** For an INTKEY table, only the nKey value of the key is used. pKey is
5777** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00005778*/
drh3aac2dd2004-04-26 14:10:20 +00005779int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00005780 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00005781 const void *pKey, i64 nKey, /* The key of the new record */
drhe4d90812007-03-29 05:51:49 +00005782 const void *pData, int nData, /* The data of the new record */
drhb026e052007-05-02 01:34:31 +00005783 int nZero, /* Number of extra 0 bytes to append to data */
drhe4d90812007-03-29 05:51:49 +00005784 int appendBias /* True if this is likely an append */
drh3b7511c2001-05-26 13:15:44 +00005785){
drh3b7511c2001-05-26 13:15:44 +00005786 int rc;
5787 int loc;
drh14acc042001-06-10 19:56:58 +00005788 int szNew;
danielk197771d5d2c2008-09-29 11:49:47 +00005789 int idx;
drh3b7511c2001-05-26 13:15:44 +00005790 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00005791 Btree *p = pCur->pBtree;
5792 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00005793 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00005794 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00005795
drh1fee73e2007-08-29 04:00:57 +00005796 assert( cursorHoldsMutex(pCur) );
danielk1977aef0bf62005-12-30 16:28:01 +00005797 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005798 /* Must start a transaction before doing an insert */
drhd677b3d2007-08-20 22:48:41 +00005799 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drhd677b3d2007-08-20 22:48:41 +00005800 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005801 }
drhf74b8d92002-09-01 23:20:45 +00005802 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00005803 if( !pCur->wrFlag ){
5804 return SQLITE_PERM; /* Cursor not open for writing */
5805 }
danielk19773588ceb2008-06-10 17:30:26 +00005806 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, nKey) ){
drhf74b8d92002-09-01 23:20:45 +00005807 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5808 }
drhfb982642007-08-30 01:19:59 +00005809 if( pCur->eState==CURSOR_FAULT ){
5810 return pCur->skip;
5811 }
danielk1977da184232006-01-05 11:34:32 +00005812
5813 /* Save the positions of any other cursors open on this table */
danielk1977be51a652008-10-08 17:58:48 +00005814 sqlite3BtreeClearCursor(pCur);
danielk19772e94d4d2006-01-09 05:36:27 +00005815 if(
danielk19772e94d4d2006-01-09 05:36:27 +00005816 SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
drhe63d9992008-08-13 19:11:48 +00005817 SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
danielk19772e94d4d2006-01-09 05:36:27 +00005818 ){
danielk1977da184232006-01-05 11:34:32 +00005819 return rc;
5820 }
5821
danielk197771d5d2c2008-09-29 11:49:47 +00005822 pPage = pCur->apPage[pCur->iPage];
drh4a1c3802004-05-12 15:15:47 +00005823 assert( pPage->intKey || nKey>=0 );
drh44845222008-07-17 18:39:57 +00005824 assert( pPage->leaf || !pPage->intKey );
drh3a4c1412004-05-09 20:40:11 +00005825 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
5826 pCur->pgnoRoot, nKey, nData, pPage->pgno,
5827 loc==0 ? "overwrite" : "new entry"));
danielk197771d5d2c2008-09-29 11:49:47 +00005828 assert( pPage->isInit );
danielk197752ae7242008-03-25 14:24:56 +00005829 allocateTempSpace(pBt);
5830 newCell = pBt->pTmpSpace;
drh2e38c322004-09-03 18:38:44 +00005831 if( newCell==0 ) return SQLITE_NOMEM;
drhb026e052007-05-02 01:34:31 +00005832 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
drh2e38c322004-09-03 18:38:44 +00005833 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00005834 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00005835 assert( szNew<=MX_CELL_SIZE(pBt) );
danielk197771d5d2c2008-09-29 11:49:47 +00005836 idx = pCur->aiIdx[pCur->iPage];
danielk1977da184232006-01-05 11:34:32 +00005837 if( loc==0 && CURSOR_VALID==pCur->eState ){
drha9121e42008-02-19 14:59:35 +00005838 u16 szOld;
danielk197771d5d2c2008-09-29 11:49:47 +00005839 assert( idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00005840 rc = sqlite3PagerWrite(pPage->pDbPage);
5841 if( rc ){
5842 goto end_insert;
5843 }
danielk197771d5d2c2008-09-29 11:49:47 +00005844 oldCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00005845 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005846 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00005847 }
drh43605152004-05-29 21:46:49 +00005848 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00005849 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00005850 if( rc ) goto end_insert;
shane0af3f892008-11-12 04:55:34 +00005851 rc = dropCell(pPage, idx, szOld);
5852 if( rc!=SQLITE_OK ) {
5853 goto end_insert;
5854 }
drh7c717f72001-06-24 20:39:41 +00005855 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00005856 assert( pPage->leaf );
danielk197771d5d2c2008-09-29 11:49:47 +00005857 idx = ++pCur->aiIdx[pCur->iPage];
drh271efa52004-05-30 19:19:05 +00005858 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00005859 pCur->validNKey = 0;
drh14acc042001-06-10 19:56:58 +00005860 }else{
drh4b70f112004-05-02 21:12:19 +00005861 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00005862 }
danielk197771d5d2c2008-09-29 11:49:47 +00005863 rc = insertCell(pPage, idx, newCell, szNew, 0, 0);
danielk1977e80463b2004-11-03 03:01:16 +00005864 if( rc!=SQLITE_OK ) goto end_insert;
danielk197771d5d2c2008-09-29 11:49:47 +00005865 rc = balance(pCur, 1);
danielk1977299b1872004-11-22 10:02:10 +00005866 if( rc==SQLITE_OK ){
5867 moveToRoot(pCur);
5868 }
drh2e38c322004-09-03 18:38:44 +00005869end_insert:
drh5e2f8b92001-05-28 00:41:15 +00005870 return rc;
5871}
5872
5873/*
drh4b70f112004-05-02 21:12:19 +00005874** Delete the entry that the cursor is pointing to. The cursor
drhf94a1732008-09-30 17:18:17 +00005875** is left pointing at a arbitrary location.
drh3b7511c2001-05-26 13:15:44 +00005876*/
drh3aac2dd2004-04-26 14:10:20 +00005877int sqlite3BtreeDelete(BtCursor *pCur){
danielk197771d5d2c2008-09-29 11:49:47 +00005878 MemPage *pPage = pCur->apPage[pCur->iPage];
5879 int idx;
drh4b70f112004-05-02 21:12:19 +00005880 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00005881 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00005882 Pgno pgnoChild = 0;
drhd677b3d2007-08-20 22:48:41 +00005883 Btree *p = pCur->pBtree;
5884 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005885
drh1fee73e2007-08-29 04:00:57 +00005886 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00005887 assert( pPage->isInit );
danielk1977aef0bf62005-12-30 16:28:01 +00005888 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005889 /* Must start a transaction before doing a delete */
drhd677b3d2007-08-20 22:48:41 +00005890 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drhd677b3d2007-08-20 22:48:41 +00005891 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005892 }
drhf74b8d92002-09-01 23:20:45 +00005893 assert( !pBt->readOnly );
drhfb982642007-08-30 01:19:59 +00005894 if( pCur->eState==CURSOR_FAULT ){
5895 return pCur->skip;
5896 }
danielk197771d5d2c2008-09-29 11:49:47 +00005897 if( pCur->aiIdx[pCur->iPage]>=pPage->nCell ){
drhbd03cae2001-06-02 02:40:57 +00005898 return SQLITE_ERROR; /* The cursor is not pointing to anything */
5899 }
drhecdc7532001-09-23 02:35:53 +00005900 if( !pCur->wrFlag ){
5901 return SQLITE_PERM; /* Did not open this cursor for writing */
5902 }
danielk19773588ceb2008-06-10 17:30:26 +00005903 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, pCur->info.nKey) ){
drhf74b8d92002-09-01 23:20:45 +00005904 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5905 }
danielk1977da184232006-01-05 11:34:32 +00005906
5907 /* Restore the current cursor position (a no-op if the cursor is not in
5908 ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors
danielk19773b8a05f2007-03-19 17:44:26 +00005909 ** open on the same table. Then call sqlite3PagerWrite() on the page
danielk1977da184232006-01-05 11:34:32 +00005910 ** that the entry will be deleted from.
5911 */
5912 if(
drha3460582008-07-11 21:02:53 +00005913 (rc = restoreCursorPosition(pCur))!=0 ||
drhd1167392006-01-23 13:00:35 +00005914 (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
danielk19773b8a05f2007-03-19 17:44:26 +00005915 (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
danielk1977da184232006-01-05 11:34:32 +00005916 ){
5917 return rc;
5918 }
danielk1977e6efa742004-11-10 11:55:10 +00005919
drh85b623f2007-12-13 21:54:09 +00005920 /* Locate the cell within its page and leave pCell pointing to the
danielk1977e6efa742004-11-10 11:55:10 +00005921 ** data. The clearCell() call frees any overflow pages associated with the
5922 ** cell. The cell itself is still intact.
5923 */
danielk197771d5d2c2008-09-29 11:49:47 +00005924 idx = pCur->aiIdx[pCur->iPage];
5925 pCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00005926 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005927 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005928 }
danielk197728129562005-01-11 10:25:06 +00005929 rc = clearCell(pPage, pCell);
drhd677b3d2007-08-20 22:48:41 +00005930 if( rc ){
drhd677b3d2007-08-20 22:48:41 +00005931 return rc;
5932 }
danielk1977e6efa742004-11-10 11:55:10 +00005933
drh4b70f112004-05-02 21:12:19 +00005934 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00005935 /*
drh5e00f6c2001-09-13 13:46:56 +00005936 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00005937 ** do something we will leave a hole on an internal page.
5938 ** We have to fill the hole by moving in a cell from a leaf. The
5939 ** next Cell after the one to be deleted is guaranteed to exist and
danielk1977299b1872004-11-22 10:02:10 +00005940 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00005941 */
drh14acc042001-06-10 19:56:58 +00005942 BtCursor leafCur;
danielk197771d5d2c2008-09-29 11:49:47 +00005943 MemPage *pLeafPage;
danielk197771d5d2c2008-09-29 11:49:47 +00005944
drh4b70f112004-05-02 21:12:19 +00005945 unsigned char *pNext;
danielk1977299b1872004-11-22 10:02:10 +00005946 int notUsed;
danielk19776b456a22005-03-21 04:04:02 +00005947 unsigned char *tempCell = 0;
drh44845222008-07-17 18:39:57 +00005948 assert( !pPage->intKey );
drh16a9b832007-05-05 18:39:25 +00005949 sqlite3BtreeGetTempCursor(pCur, &leafCur);
danielk1977299b1872004-11-22 10:02:10 +00005950 rc = sqlite3BtreeNext(&leafCur, &notUsed);
danielk19776b456a22005-03-21 04:04:02 +00005951 if( rc==SQLITE_OK ){
danielk19772f78fc62008-09-30 09:31:45 +00005952 assert( leafCur.aiIdx[leafCur.iPage]==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00005953 pLeafPage = leafCur.apPage[leafCur.iPage];
danielk197771d5d2c2008-09-29 11:49:47 +00005954 rc = sqlite3PagerWrite(pLeafPage->pDbPage);
danielk19776b456a22005-03-21 04:04:02 +00005955 }
5956 if( rc==SQLITE_OK ){
danielk19772f78fc62008-09-30 09:31:45 +00005957 int leafCursorInvalid = 0;
drha9121e42008-02-19 14:59:35 +00005958 u16 szNext;
danielk19776b456a22005-03-21 04:04:02 +00005959 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
danielk197771d5d2c2008-09-29 11:49:47 +00005960 pCur->pgnoRoot, pPage->pgno, pLeafPage->pgno));
5961 dropCell(pPage, idx, cellSizePtr(pPage, pCell));
danielk19772f78fc62008-09-30 09:31:45 +00005962 pNext = findCell(pLeafPage, 0);
danielk197771d5d2c2008-09-29 11:49:47 +00005963 szNext = cellSizePtr(pLeafPage, pNext);
danielk19776b456a22005-03-21 04:04:02 +00005964 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
danielk197752ae7242008-03-25 14:24:56 +00005965 allocateTempSpace(pBt);
5966 tempCell = pBt->pTmpSpace;
danielk19776b456a22005-03-21 04:04:02 +00005967 if( tempCell==0 ){
5968 rc = SQLITE_NOMEM;
5969 }
danielk19778ea1cfa2008-01-01 06:19:02 +00005970 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00005971 rc = insertCell(pPage, idx, pNext-4, szNext+4, tempCell, 0);
danielk19778ea1cfa2008-01-01 06:19:02 +00005972 }
danielk19772f78fc62008-09-30 09:31:45 +00005973
drhf94a1732008-09-30 17:18:17 +00005974
5975 /* The "if" statement in the next code block is critical. The
5976 ** slightest error in that statement would allow SQLite to operate
5977 ** correctly most of the time but produce very rare failures. To
5978 ** guard against this, the following macros help to verify that
5979 ** the "if" statement is well tested.
5980 */
5981 testcase( pPage->nOverflow==0 && pPage->nFree<pBt->usableSize*2/3
5982 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
5983 testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3
5984 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
5985 testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3+1
5986 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
5987 testcase( pPage->nOverflow>0 && pPage->nFree<=pBt->usableSize*2/3
5988 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
5989 testcase( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3))
5990 && pLeafPage->nFree+2+szNext == pBt->usableSize*2/3 );
5991
5992
danielk19772f78fc62008-09-30 09:31:45 +00005993 if( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3)) &&
5994 (pLeafPage->nFree+2+szNext > pBt->usableSize*2/3)
5995 ){
drhf94a1732008-09-30 17:18:17 +00005996 /* This branch is taken if the internal node is now either overflowing
5997 ** or underfull and the leaf node will be underfull after the just cell
danielk19772f78fc62008-09-30 09:31:45 +00005998 ** copied to the internal node is deleted from it. This is a special
5999 ** case because the call to balance() to correct the internal node
6000 ** may change the tree structure and invalidate the contents of
6001 ** the leafCur.apPage[] and leafCur.aiIdx[] arrays, which will be
6002 ** used by the balance() required to correct the underfull leaf
6003 ** node.
6004 **
6005 ** The formula used in the expression above are based on facets of
6006 ** the SQLite file-format that do not change over time.
6007 */
drhf94a1732008-09-30 17:18:17 +00006008 testcase( pPage->nFree==pBt->usableSize*2/3+1 );
6009 testcase( pLeafPage->nFree+2+szNext==pBt->usableSize*2/3+1 );
danielk19772f78fc62008-09-30 09:31:45 +00006010 leafCursorInvalid = 1;
6011 }
6012
danielk19778ea1cfa2008-01-01 06:19:02 +00006013 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00006014 put4byte(findOverflowCell(pPage, idx), pgnoChild);
drhf94a1732008-09-30 17:18:17 +00006015 VVA_ONLY( pCur->pagesShuffled = 0 );
danielk197771d5d2c2008-09-29 11:49:47 +00006016 rc = balance(pCur, 0);
danielk19778ea1cfa2008-01-01 06:19:02 +00006017 }
danielk19772f78fc62008-09-30 09:31:45 +00006018
6019 if( rc==SQLITE_OK && leafCursorInvalid ){
6020 /* The leaf-node is now underfull and so the tree needs to be
6021 ** rebalanced. However, the balance() operation on the internal
6022 ** node above may have modified the structure of the B-Tree and
6023 ** so the current contents of leafCur.apPage[] and leafCur.aiIdx[]
6024 ** may not be trusted.
6025 **
6026 ** It is not possible to copy the ancestry from pCur, as the same
6027 ** balance() call has invalidated the pCur->apPage[] and aiIdx[]
6028 ** arrays.
drh7b682802008-09-30 14:06:28 +00006029 **
6030 ** The call to saveCursorPosition() below internally saves the
6031 ** key that leafCur is currently pointing to. Currently, there
6032 ** are two copies of that key in the tree - one here on the leaf
6033 ** page and one on some internal node in the tree. The copy on
6034 ** the leaf node is always the next key in tree-order after the
6035 ** copy on the internal node. So, the call to sqlite3BtreeNext()
6036 ** calls restoreCursorPosition() to point the cursor to the copy
6037 ** stored on the internal node, then advances to the next entry,
6038 ** which happens to be the copy of the key on the internal node.
danielk1977a69fda22008-09-30 16:48:10 +00006039 ** Net effect: leafCur is pointing back to the duplicate cell
6040 ** that needs to be removed, and the leafCur.apPage[] and
6041 ** leafCur.aiIdx[] arrays are correct.
danielk19772f78fc62008-09-30 09:31:45 +00006042 */
drhf94a1732008-09-30 17:18:17 +00006043 VVA_ONLY( Pgno leafPgno = pLeafPage->pgno );
danielk19772f78fc62008-09-30 09:31:45 +00006044 rc = saveCursorPosition(&leafCur);
6045 if( rc==SQLITE_OK ){
6046 rc = sqlite3BtreeNext(&leafCur, &notUsed);
6047 }
6048 pLeafPage = leafCur.apPage[leafCur.iPage];
6049 assert( pLeafPage->pgno==leafPgno );
6050 assert( leafCur.aiIdx[leafCur.iPage]==0 );
6051 }
6052
danielk19778ea1cfa2008-01-01 06:19:02 +00006053 if( rc==SQLITE_OK ){
danielk19772f78fc62008-09-30 09:31:45 +00006054 dropCell(pLeafPage, 0, szNext);
drhf94a1732008-09-30 17:18:17 +00006055 VVA_ONLY( leafCur.pagesShuffled = 0 );
danielk197771d5d2c2008-09-29 11:49:47 +00006056 rc = balance(&leafCur, 0);
drhf94a1732008-09-30 17:18:17 +00006057 assert( leafCursorInvalid || !leafCur.pagesShuffled
6058 || !pCur->pagesShuffled );
danielk19778ea1cfa2008-01-01 06:19:02 +00006059 }
danielk19776b456a22005-03-21 04:04:02 +00006060 }
drh16a9b832007-05-05 18:39:25 +00006061 sqlite3BtreeReleaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00006062 }else{
danielk1977299b1872004-11-22 10:02:10 +00006063 TRACE(("DELETE: table=%d delete from leaf %d\n",
6064 pCur->pgnoRoot, pPage->pgno));
shanedcc50b72008-11-13 18:29:50 +00006065 rc = dropCell(pPage, idx, cellSizePtr(pPage, pCell));
6066 if( rc==SQLITE_OK ){
6067 rc = balance(pCur, 0);
6068 }
drh5e2f8b92001-05-28 00:41:15 +00006069 }
danielk19776b456a22005-03-21 04:04:02 +00006070 if( rc==SQLITE_OK ){
6071 moveToRoot(pCur);
6072 }
drh5e2f8b92001-05-28 00:41:15 +00006073 return rc;
drh3b7511c2001-05-26 13:15:44 +00006074}
drh8b2f49b2001-06-08 00:21:52 +00006075
6076/*
drhc6b52df2002-01-04 03:09:29 +00006077** Create a new BTree table. Write into *piTable the page
6078** number for the root page of the new table.
6079**
drhab01f612004-05-22 02:55:23 +00006080** The type of type is determined by the flags parameter. Only the
6081** following values of flags are currently in use. Other values for
6082** flags might not work:
6083**
6084** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
6085** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00006086*/
drhd677b3d2007-08-20 22:48:41 +00006087static int btreeCreateTable(Btree *p, int *piTable, int flags){
danielk1977aef0bf62005-12-30 16:28:01 +00006088 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006089 MemPage *pRoot;
6090 Pgno pgnoRoot;
6091 int rc;
drhd677b3d2007-08-20 22:48:41 +00006092
drh1fee73e2007-08-29 04:00:57 +00006093 assert( sqlite3BtreeHoldsMutex(p) );
danielk1977aef0bf62005-12-30 16:28:01 +00006094 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00006095 /* Must start a transaction first */
drhd677b3d2007-08-20 22:48:41 +00006096 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
6097 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006098 }
danielk197728129562005-01-11 10:25:06 +00006099 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00006100
danielk1977003ba062004-11-04 02:57:33 +00006101#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00006102 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00006103 if( rc ){
6104 return rc;
6105 }
danielk1977003ba062004-11-04 02:57:33 +00006106#else
danielk1977687566d2004-11-02 12:56:41 +00006107 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00006108 Pgno pgnoMove; /* Move a page here to make room for the root-page */
6109 MemPage *pPageMove; /* The page to move to. */
6110
danielk197720713f32007-05-03 11:43:33 +00006111 /* Creating a new table may probably require moving an existing database
6112 ** to make room for the new tables root page. In case this page turns
6113 ** out to be an overflow page, delete all overflow page-map caches
6114 ** held by open cursors.
6115 */
danielk197792d4d7a2007-05-04 12:05:56 +00006116 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00006117
danielk1977003ba062004-11-04 02:57:33 +00006118 /* Read the value of meta[3] from the database to determine where the
6119 ** root page of the new table should go. meta[3] is the largest root-page
6120 ** created so far, so the new root-page is (meta[3]+1).
6121 */
danielk1977aef0bf62005-12-30 16:28:01 +00006122 rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
drhd677b3d2007-08-20 22:48:41 +00006123 if( rc!=SQLITE_OK ){
6124 return rc;
6125 }
danielk1977003ba062004-11-04 02:57:33 +00006126 pgnoRoot++;
6127
danielk1977599fcba2004-11-08 07:13:13 +00006128 /* The new root-page may not be allocated on a pointer-map page, or the
6129 ** PENDING_BYTE page.
6130 */
drh72190432008-01-31 14:54:43 +00006131 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00006132 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00006133 pgnoRoot++;
6134 }
6135 assert( pgnoRoot>=3 );
6136
6137 /* Allocate a page. The page that currently resides at pgnoRoot will
6138 ** be moved to the allocated page (unless the allocated page happens
6139 ** to reside at pgnoRoot).
6140 */
drh4f0c5872007-03-26 22:05:01 +00006141 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00006142 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00006143 return rc;
6144 }
danielk1977003ba062004-11-04 02:57:33 +00006145
6146 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00006147 /* pgnoRoot is the page that will be used for the root-page of
6148 ** the new table (assuming an error did not occur). But we were
6149 ** allocated pgnoMove. If required (i.e. if it was not allocated
6150 ** by extending the file), the current page at position pgnoMove
6151 ** is already journaled.
6152 */
danielk1977003ba062004-11-04 02:57:33 +00006153 u8 eType;
6154 Pgno iPtrPage;
6155
6156 releasePage(pPageMove);
danielk1977f35843b2007-04-07 15:03:17 +00006157
6158 /* Move the page currently at pgnoRoot to pgnoMove. */
drh16a9b832007-05-05 18:39:25 +00006159 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006160 if( rc!=SQLITE_OK ){
6161 return rc;
6162 }
6163 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drhccae6022005-02-26 17:31:26 +00006164 if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00006165 releasePage(pRoot);
6166 return rc;
6167 }
drhccae6022005-02-26 17:31:26 +00006168 assert( eType!=PTRMAP_ROOTPAGE );
6169 assert( eType!=PTRMAP_FREEPAGE );
danielk19773b8a05f2007-03-19 17:44:26 +00006170 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk19775fd057a2005-03-09 13:09:43 +00006171 if( rc!=SQLITE_OK ){
6172 releasePage(pRoot);
6173 return rc;
6174 }
danielk19774c999992008-07-16 18:17:55 +00006175 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
danielk1977003ba062004-11-04 02:57:33 +00006176 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00006177
6178 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00006179 if( rc!=SQLITE_OK ){
6180 return rc;
6181 }
drh16a9b832007-05-05 18:39:25 +00006182 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006183 if( rc!=SQLITE_OK ){
6184 return rc;
6185 }
danielk19773b8a05f2007-03-19 17:44:26 +00006186 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00006187 if( rc!=SQLITE_OK ){
6188 releasePage(pRoot);
6189 return rc;
6190 }
6191 }else{
6192 pRoot = pPageMove;
6193 }
6194
danielk197742741be2005-01-08 12:42:39 +00006195 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00006196 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
6197 if( rc ){
6198 releasePage(pRoot);
6199 return rc;
6200 }
danielk1977aef0bf62005-12-30 16:28:01 +00006201 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00006202 if( rc ){
6203 releasePage(pRoot);
6204 return rc;
6205 }
danielk197742741be2005-01-08 12:42:39 +00006206
danielk1977003ba062004-11-04 02:57:33 +00006207 }else{
drh4f0c5872007-03-26 22:05:01 +00006208 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00006209 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00006210 }
6211#endif
danielk19773b8a05f2007-03-19 17:44:26 +00006212 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhde647132004-05-07 17:57:49 +00006213 zeroPage(pRoot, flags | PTF_LEAF);
danielk19773b8a05f2007-03-19 17:44:26 +00006214 sqlite3PagerUnref(pRoot->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00006215 *piTable = (int)pgnoRoot;
6216 return SQLITE_OK;
6217}
drhd677b3d2007-08-20 22:48:41 +00006218int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
6219 int rc;
6220 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006221 p->pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006222 rc = btreeCreateTable(p, piTable, flags);
6223 sqlite3BtreeLeave(p);
6224 return rc;
6225}
drh8b2f49b2001-06-08 00:21:52 +00006226
6227/*
6228** Erase the given database page and all its children. Return
6229** the page to the freelist.
6230*/
drh4b70f112004-05-02 21:12:19 +00006231static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00006232 BtShared *pBt, /* The BTree that contains the table */
drh4b70f112004-05-02 21:12:19 +00006233 Pgno pgno, /* Page number to clear */
6234 MemPage *pParent, /* Parent page. NULL for the root */
danielk1977c7af4842008-10-27 13:59:33 +00006235 int freePageFlag, /* Deallocate page if true */
6236 int *pnChange
drh4b70f112004-05-02 21:12:19 +00006237){
danielk19776b456a22005-03-21 04:04:02 +00006238 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00006239 int rc;
drh4b70f112004-05-02 21:12:19 +00006240 unsigned char *pCell;
6241 int i;
drh8b2f49b2001-06-08 00:21:52 +00006242
drh1fee73e2007-08-29 04:00:57 +00006243 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977ad0132d2008-06-07 08:58:22 +00006244 if( pgno>pagerPagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00006245 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00006246 }
6247
danielk197771d5d2c2008-09-29 11:49:47 +00006248 rc = getAndInitPage(pBt, pgno, &pPage);
danielk19776b456a22005-03-21 04:04:02 +00006249 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00006250 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00006251 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00006252 if( !pPage->leaf ){
danielk1977c7af4842008-10-27 13:59:33 +00006253 rc = clearDatabasePage(pBt, get4byte(pCell), pPage, 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00006254 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006255 }
drh4b70f112004-05-02 21:12:19 +00006256 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00006257 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006258 }
drha34b6762004-05-07 13:30:42 +00006259 if( !pPage->leaf ){
danielk1977c7af4842008-10-27 13:59:33 +00006260 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage, 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00006261 if( rc ) goto cleardatabasepage_out;
danielk1977c7af4842008-10-27 13:59:33 +00006262 }else if( pnChange ){
6263 assert( pPage->intKey );
6264 *pnChange += pPage->nCell;
drh2aa679f2001-06-25 02:11:07 +00006265 }
6266 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00006267 rc = freePage(pPage);
danielk19773b8a05f2007-03-19 17:44:26 +00006268 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
drh3a4c1412004-05-09 20:40:11 +00006269 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00006270 }
danielk19776b456a22005-03-21 04:04:02 +00006271
6272cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00006273 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00006274 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006275}
6276
6277/*
drhab01f612004-05-22 02:55:23 +00006278** Delete all information from a single table in the database. iTable is
6279** the page number of the root of the table. After this routine returns,
6280** the root page is empty, but still exists.
6281**
6282** This routine will fail with SQLITE_LOCKED if there are any open
6283** read cursors on the table. Open write cursors are moved to the
6284** root of the table.
danielk1977c7af4842008-10-27 13:59:33 +00006285**
6286** If pnChange is not NULL, then table iTable must be an intkey table. The
6287** integer value pointed to by pnChange is incremented by the number of
6288** entries in the table.
drh8b2f49b2001-06-08 00:21:52 +00006289*/
danielk1977c7af4842008-10-27 13:59:33 +00006290int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
drh8b2f49b2001-06-08 00:21:52 +00006291 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00006292 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00006293 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006294 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00006295 if( p->inTrans!=TRANS_WRITE ){
drhd677b3d2007-08-20 22:48:41 +00006296 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
danielk19773588ceb2008-06-10 17:30:26 +00006297 }else if( (rc = checkReadLocks(p, iTable, 0, 1))!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00006298 /* nothing to do */
6299 }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
6300 /* nothing to do */
6301 }else{
danielk1977c7af4842008-10-27 13:59:33 +00006302 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0, pnChange);
drh8b2f49b2001-06-08 00:21:52 +00006303 }
drhd677b3d2007-08-20 22:48:41 +00006304 sqlite3BtreeLeave(p);
6305 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006306}
6307
6308/*
6309** Erase all information in a table and add the root of the table to
6310** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00006311** page 1) is never added to the freelist.
6312**
6313** This routine will fail with SQLITE_LOCKED if there are any open
6314** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00006315**
6316** If AUTOVACUUM is enabled and the page at iTable is not the last
6317** root page in the database file, then the last root page
6318** in the database file is moved into the slot formerly occupied by
6319** iTable and that last slot formerly occupied by the last root page
6320** is added to the freelist instead of iTable. In this say, all
6321** root pages are kept at the beginning of the database file, which
6322** is necessary for AUTOVACUUM to work right. *piMoved is set to the
6323** page number that used to be the last root page in the file before
6324** the move. If no page gets moved, *piMoved is set to 0.
6325** The last root page is recorded in meta[3] and the value of
6326** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00006327*/
drhd677b3d2007-08-20 22:48:41 +00006328static int btreeDropTable(Btree *p, int iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00006329 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00006330 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00006331 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00006332
drh1fee73e2007-08-29 04:00:57 +00006333 assert( sqlite3BtreeHoldsMutex(p) );
danielk1977aef0bf62005-12-30 16:28:01 +00006334 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00006335 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00006336 }
danielk1977a0bf2652004-11-04 14:30:04 +00006337
danielk1977e6efa742004-11-10 11:55:10 +00006338 /* It is illegal to drop a table if any cursors are open on the
6339 ** database. This is because in auto-vacuum mode the backend may
6340 ** need to move another root-page to fill a gap left by the deleted
6341 ** root page. If an open cursor was using this page a problem would
6342 ** occur.
6343 */
6344 if( pBt->pCursor ){
6345 return SQLITE_LOCKED;
drh5df72a52002-06-06 23:16:05 +00006346 }
danielk1977a0bf2652004-11-04 14:30:04 +00006347
drh16a9b832007-05-05 18:39:25 +00006348 rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00006349 if( rc ) return rc;
danielk1977c7af4842008-10-27 13:59:33 +00006350 rc = sqlite3BtreeClearTable(p, iTable, 0);
danielk19776b456a22005-03-21 04:04:02 +00006351 if( rc ){
6352 releasePage(pPage);
6353 return rc;
6354 }
danielk1977a0bf2652004-11-04 14:30:04 +00006355
drh205f48e2004-11-05 00:43:11 +00006356 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00006357
drh4b70f112004-05-02 21:12:19 +00006358 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00006359#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00006360 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00006361 releasePage(pPage);
6362#else
6363 if( pBt->autoVacuum ){
6364 Pgno maxRootPgno;
danielk1977aef0bf62005-12-30 16:28:01 +00006365 rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006366 if( rc!=SQLITE_OK ){
6367 releasePage(pPage);
6368 return rc;
6369 }
6370
6371 if( iTable==maxRootPgno ){
6372 /* If the table being dropped is the table with the largest root-page
6373 ** number in the database, put the root page on the free list.
6374 */
6375 rc = freePage(pPage);
6376 releasePage(pPage);
6377 if( rc!=SQLITE_OK ){
6378 return rc;
6379 }
6380 }else{
6381 /* The table being dropped does not have the largest root-page
6382 ** number in the database. So move the page that does into the
6383 ** gap left by the deleted root-page.
6384 */
6385 MemPage *pMove;
6386 releasePage(pPage);
drh16a9b832007-05-05 18:39:25 +00006387 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006388 if( rc!=SQLITE_OK ){
6389 return rc;
6390 }
danielk19774c999992008-07-16 18:17:55 +00006391 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006392 releasePage(pMove);
6393 if( rc!=SQLITE_OK ){
6394 return rc;
6395 }
drh16a9b832007-05-05 18:39:25 +00006396 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006397 if( rc!=SQLITE_OK ){
6398 return rc;
6399 }
6400 rc = freePage(pMove);
6401 releasePage(pMove);
6402 if( rc!=SQLITE_OK ){
6403 return rc;
6404 }
6405 *piMoved = maxRootPgno;
6406 }
6407
danielk1977599fcba2004-11-08 07:13:13 +00006408 /* Set the new 'max-root-page' value in the database header. This
6409 ** is the old value less one, less one more if that happens to
6410 ** be a root-page number, less one again if that is the
6411 ** PENDING_BYTE_PAGE.
6412 */
danielk197787a6e732004-11-05 12:58:25 +00006413 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00006414 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
6415 maxRootPgno--;
6416 }
danielk1977266664d2006-02-10 08:24:21 +00006417 if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00006418 maxRootPgno--;
6419 }
danielk1977599fcba2004-11-08 07:13:13 +00006420 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
6421
danielk1977aef0bf62005-12-30 16:28:01 +00006422 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006423 }else{
6424 rc = freePage(pPage);
6425 releasePage(pPage);
6426 }
6427#endif
drh2aa679f2001-06-25 02:11:07 +00006428 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00006429 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00006430 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00006431 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00006432 }
drh8b2f49b2001-06-08 00:21:52 +00006433 return rc;
6434}
drhd677b3d2007-08-20 22:48:41 +00006435int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
6436 int rc;
6437 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006438 p->pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006439 rc = btreeDropTable(p, iTable, piMoved);
6440 sqlite3BtreeLeave(p);
6441 return rc;
6442}
drh8b2f49b2001-06-08 00:21:52 +00006443
drh001bbcb2003-03-19 03:14:00 +00006444
drh8b2f49b2001-06-08 00:21:52 +00006445/*
drh23e11ca2004-05-04 17:27:28 +00006446** Read the meta-information out of a database file. Meta[0]
6447** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00006448** through meta[15] are available for use by higher layers. Meta[0]
6449** is read-only, the others are read/write.
6450**
6451** The schema layer numbers meta values differently. At the schema
6452** layer (and the SetCookie and ReadCookie opcodes) the number of
6453** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00006454*/
danielk1977aef0bf62005-12-30 16:28:01 +00006455int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
danielk19773b8a05f2007-03-19 17:44:26 +00006456 DbPage *pDbPage;
drh8b2f49b2001-06-08 00:21:52 +00006457 int rc;
drh4b70f112004-05-02 21:12:19 +00006458 unsigned char *pP1;
danielk1977aef0bf62005-12-30 16:28:01 +00006459 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006460
drhd677b3d2007-08-20 22:48:41 +00006461 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006462 pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006463
danielk1977da184232006-01-05 11:34:32 +00006464 /* Reading a meta-data value requires a read-lock on page 1 (and hence
6465 ** the sqlite_master table. We grab this lock regardless of whether or
6466 ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
6467 ** 1 is treated as a special case by queryTableLock() and lockTable()).
6468 */
6469 rc = queryTableLock(p, 1, READ_LOCK);
6470 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00006471 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00006472 return rc;
6473 }
6474
drh23e11ca2004-05-04 17:27:28 +00006475 assert( idx>=0 && idx<=15 );
danielk1977d9f6c532008-09-19 16:39:38 +00006476 if( pBt->pPage1 ){
6477 /* The b-tree is already holding a reference to page 1 of the database
6478 ** file. In this case the required meta-data value can be read directly
6479 ** from the page data of this reference. This is slightly faster than
6480 ** requesting a new reference from the pager layer.
6481 */
6482 pP1 = (unsigned char *)pBt->pPage1->aData;
6483 }else{
6484 /* The b-tree does not have a reference to page 1 of the database file.
6485 ** Obtain one from the pager layer.
6486 */
danielk1977ea897302008-09-19 15:10:58 +00006487 rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
6488 if( rc ){
6489 sqlite3BtreeLeave(p);
6490 return rc;
6491 }
6492 pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
drhd677b3d2007-08-20 22:48:41 +00006493 }
drh23e11ca2004-05-04 17:27:28 +00006494 *pMeta = get4byte(&pP1[36 + idx*4]);
danielk1977ea897302008-09-19 15:10:58 +00006495
danielk1977d9f6c532008-09-19 16:39:38 +00006496 /* If the b-tree is not holding a reference to page 1, then one was
6497 ** requested from the pager layer in the above block. Release it now.
6498 */
danielk1977ea897302008-09-19 15:10:58 +00006499 if( !pBt->pPage1 ){
6500 sqlite3PagerUnref(pDbPage);
6501 }
drhae157872004-08-14 19:20:09 +00006502
danielk1977599fcba2004-11-08 07:13:13 +00006503 /* If autovacuumed is disabled in this build but we are trying to
6504 ** access an autovacuumed database, then make the database readonly.
6505 */
danielk1977003ba062004-11-04 02:57:33 +00006506#ifdef SQLITE_OMIT_AUTOVACUUM
drhae157872004-08-14 19:20:09 +00006507 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00006508#endif
drhae157872004-08-14 19:20:09 +00006509
danielk1977da184232006-01-05 11:34:32 +00006510 /* Grab the read-lock on page 1. */
6511 rc = lockTable(p, 1, READ_LOCK);
drhd677b3d2007-08-20 22:48:41 +00006512 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00006513 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006514}
6515
6516/*
drh23e11ca2004-05-04 17:27:28 +00006517** Write meta-information back into the database. Meta[0] is
6518** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00006519*/
danielk1977aef0bf62005-12-30 16:28:01 +00006520int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
6521 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00006522 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00006523 int rc;
drh23e11ca2004-05-04 17:27:28 +00006524 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00006525 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006526 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00006527 if( p->inTrans!=TRANS_WRITE ){
drhd677b3d2007-08-20 22:48:41 +00006528 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
6529 }else{
6530 assert( pBt->pPage1!=0 );
6531 pP1 = pBt->pPage1->aData;
6532 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6533 if( rc==SQLITE_OK ){
6534 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +00006535#ifndef SQLITE_OMIT_AUTOVACUUM
drhd677b3d2007-08-20 22:48:41 +00006536 if( idx==7 ){
6537 assert( pBt->autoVacuum || iMeta==0 );
6538 assert( iMeta==0 || iMeta==1 );
6539 pBt->incrVacuum = iMeta;
6540 }
danielk19774152e672007-09-12 17:01:45 +00006541#endif
drhd677b3d2007-08-20 22:48:41 +00006542 }
drh5df72a52002-06-06 23:16:05 +00006543 }
drhd677b3d2007-08-20 22:48:41 +00006544 sqlite3BtreeLeave(p);
6545 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006546}
drh8c42ca92001-06-22 19:15:00 +00006547
drhf328bc82004-05-10 23:29:49 +00006548/*
6549** Return the flag byte at the beginning of the page that the cursor
6550** is currently pointing to.
6551*/
6552int sqlite3BtreeFlags(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00006553 /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
drha3460582008-07-11 21:02:53 +00006554 ** restoreCursorPosition() here.
danielk1977da184232006-01-05 11:34:32 +00006555 */
danielk1977e448dc42008-01-02 11:50:51 +00006556 MemPage *pPage;
drha3460582008-07-11 21:02:53 +00006557 restoreCursorPosition(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00006558 pPage = pCur->apPage[pCur->iPage];
drh1fee73e2007-08-29 04:00:57 +00006559 assert( cursorHoldsMutex(pCur) );
drhd0679ed2007-08-28 22:24:34 +00006560 assert( pPage->pBt==pCur->pBt );
drhf328bc82004-05-10 23:29:49 +00006561 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
6562}
6563
drhdd793422001-06-28 01:54:48 +00006564
drhdd793422001-06-28 01:54:48 +00006565/*
drh5eddca62001-06-30 21:53:53 +00006566** Return the pager associated with a BTree. This routine is used for
6567** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00006568*/
danielk1977aef0bf62005-12-30 16:28:01 +00006569Pager *sqlite3BtreePager(Btree *p){
6570 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00006571}
drh5eddca62001-06-30 21:53:53 +00006572
drhb7f91642004-10-31 02:22:47 +00006573#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006574/*
6575** Append a message to the error message string.
6576*/
drh2e38c322004-09-03 18:38:44 +00006577static void checkAppendMsg(
6578 IntegrityCk *pCheck,
6579 char *zMsg1,
6580 const char *zFormat,
6581 ...
6582){
6583 va_list ap;
drh1dcdbc02007-01-27 02:24:54 +00006584 if( !pCheck->mxErr ) return;
6585 pCheck->mxErr--;
6586 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00006587 va_start(ap, zFormat);
drhf089aa42008-07-08 19:34:06 +00006588 if( pCheck->errMsg.nChar ){
6589 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
drh5eddca62001-06-30 21:53:53 +00006590 }
drhf089aa42008-07-08 19:34:06 +00006591 if( zMsg1 ){
6592 sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
6593 }
6594 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
6595 va_end(ap);
drhc890fec2008-08-01 20:10:08 +00006596 if( pCheck->errMsg.mallocFailed ){
6597 pCheck->mallocFailed = 1;
6598 }
drh5eddca62001-06-30 21:53:53 +00006599}
drhb7f91642004-10-31 02:22:47 +00006600#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006601
drhb7f91642004-10-31 02:22:47 +00006602#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006603/*
6604** Add 1 to the reference count for page iPage. If this is the second
6605** reference to the page, add an error message to pCheck->zErrMsg.
6606** Return 1 if there are 2 ore more references to the page and 0 if
6607** if this is the first reference to the page.
6608**
6609** Also check that the page number is in bounds.
6610*/
drhaaab5722002-02-19 13:39:21 +00006611static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00006612 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00006613 if( iPage>pCheck->nPage || iPage<0 ){
drh2e38c322004-09-03 18:38:44 +00006614 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006615 return 1;
6616 }
6617 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00006618 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006619 return 1;
6620 }
6621 return (pCheck->anRef[iPage]++)>1;
6622}
6623
danielk1977afcdd022004-10-31 16:25:42 +00006624#ifndef SQLITE_OMIT_AUTOVACUUM
6625/*
6626** Check that the entry in the pointer-map for page iChild maps to
6627** page iParent, pointer type ptrType. If not, append an error message
6628** to pCheck.
6629*/
6630static void checkPtrmap(
6631 IntegrityCk *pCheck, /* Integrity check context */
6632 Pgno iChild, /* Child page number */
6633 u8 eType, /* Expected pointer map type */
6634 Pgno iParent, /* Expected pointer map parent page number */
6635 char *zContext /* Context description (used for error msg) */
6636){
6637 int rc;
6638 u8 ePtrmapType;
6639 Pgno iPtrmapParent;
6640
6641 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
6642 if( rc!=SQLITE_OK ){
6643 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
6644 return;
6645 }
6646
6647 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
6648 checkAppendMsg(pCheck, zContext,
6649 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
6650 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
6651 }
6652}
6653#endif
6654
drh5eddca62001-06-30 21:53:53 +00006655/*
6656** Check the integrity of the freelist or of an overflow page list.
6657** Verify that the number of pages on the list is N.
6658*/
drh30e58752002-03-02 20:41:57 +00006659static void checkList(
6660 IntegrityCk *pCheck, /* Integrity checking context */
6661 int isFreeList, /* True for a freelist. False for overflow page list */
6662 int iPage, /* Page number for first page in the list */
6663 int N, /* Expected number of pages in the list */
6664 char *zContext /* Context for error messages */
6665){
6666 int i;
drh3a4c1412004-05-09 20:40:11 +00006667 int expected = N;
6668 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00006669 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00006670 DbPage *pOvflPage;
6671 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00006672 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00006673 checkAppendMsg(pCheck, zContext,
6674 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00006675 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00006676 break;
6677 }
6678 if( checkRef(pCheck, iPage, zContext) ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00006679 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
drh2e38c322004-09-03 18:38:44 +00006680 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006681 break;
6682 }
danielk19773b8a05f2007-03-19 17:44:26 +00006683 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00006684 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00006685 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00006686#ifndef SQLITE_OMIT_AUTOVACUUM
6687 if( pCheck->pBt->autoVacuum ){
6688 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
6689 }
6690#endif
drh45b1fac2008-07-04 17:52:42 +00006691 if( n>pCheck->pBt->usableSize/4-2 ){
drh2e38c322004-09-03 18:38:44 +00006692 checkAppendMsg(pCheck, zContext,
6693 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00006694 N--;
6695 }else{
6696 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00006697 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00006698#ifndef SQLITE_OMIT_AUTOVACUUM
6699 if( pCheck->pBt->autoVacuum ){
6700 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
6701 }
6702#endif
6703 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00006704 }
6705 N -= n;
drh30e58752002-03-02 20:41:57 +00006706 }
drh30e58752002-03-02 20:41:57 +00006707 }
danielk1977afcdd022004-10-31 16:25:42 +00006708#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006709 else{
6710 /* If this database supports auto-vacuum and iPage is not the last
6711 ** page in this overflow list, check that the pointer-map entry for
6712 ** the following page matches iPage.
6713 */
6714 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00006715 i = get4byte(pOvflData);
danielk1977687566d2004-11-02 12:56:41 +00006716 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
6717 }
danielk1977afcdd022004-10-31 16:25:42 +00006718 }
6719#endif
danielk19773b8a05f2007-03-19 17:44:26 +00006720 iPage = get4byte(pOvflData);
6721 sqlite3PagerUnref(pOvflPage);
drh5eddca62001-06-30 21:53:53 +00006722 }
6723}
drhb7f91642004-10-31 02:22:47 +00006724#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006725
drhb7f91642004-10-31 02:22:47 +00006726#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006727/*
6728** Do various sanity checks on a single page of a tree. Return
6729** the tree depth. Root pages return 0. Parents of root pages
6730** return 1, and so forth.
6731**
6732** These checks are done:
6733**
6734** 1. Make sure that cells and freeblocks do not overlap
6735** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00006736** NO 2. Make sure cell keys are in order.
6737** NO 3. Make sure no key is less than or equal to zLowerBound.
6738** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00006739** 5. Check the integrity of overflow pages.
6740** 6. Recursively call checkTreePage on all children.
6741** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00006742** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00006743** the root of the tree.
6744*/
6745static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00006746 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00006747 int iPage, /* Page number of the page to check */
6748 MemPage *pParent, /* Parent page */
drh74161702006-02-24 02:53:49 +00006749 char *zParentContext /* Parent context */
drh5eddca62001-06-30 21:53:53 +00006750){
6751 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00006752 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00006753 int hdr, cellStart;
6754 int nCell;
drhda200cc2004-05-09 11:51:38 +00006755 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00006756 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00006757 int usableSize;
drh5eddca62001-06-30 21:53:53 +00006758 char zContext[100];
shane0af3f892008-11-12 04:55:34 +00006759 char *hit = 0;
drh5eddca62001-06-30 21:53:53 +00006760
drh5bb3eb92007-05-04 13:15:55 +00006761 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
danielk1977ef73ee92004-11-06 12:26:07 +00006762
drh5eddca62001-06-30 21:53:53 +00006763 /* Check that the page exists
6764 */
drhd9cb6ac2005-10-20 07:28:17 +00006765 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00006766 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00006767 if( iPage==0 ) return 0;
6768 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh16a9b832007-05-05 18:39:25 +00006769 if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drh2e38c322004-09-03 18:38:44 +00006770 checkAppendMsg(pCheck, zContext,
6771 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00006772 return 0;
6773 }
danielk197771d5d2c2008-09-29 11:49:47 +00006774 if( (rc = sqlite3BtreeInitPage(pPage))!=0 ){
drh16a9b832007-05-05 18:39:25 +00006775 checkAppendMsg(pCheck, zContext,
6776 "sqlite3BtreeInitPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00006777 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00006778 return 0;
6779 }
6780
6781 /* Check out all the cells.
6782 */
6783 depth = 0;
drh1dcdbc02007-01-27 02:24:54 +00006784 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
drh6f11bef2004-05-13 01:12:56 +00006785 u8 *pCell;
6786 int sz;
6787 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00006788
6789 /* Check payload overflow pages
6790 */
drh5bb3eb92007-05-04 13:15:55 +00006791 sqlite3_snprintf(sizeof(zContext), zContext,
6792 "On tree page %d cell %d: ", iPage, i);
danielk19771cc5ed82007-05-16 17:28:43 +00006793 pCell = findCell(pPage,i);
drh16a9b832007-05-05 18:39:25 +00006794 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00006795 sz = info.nData;
6796 if( !pPage->intKey ) sz += info.nKey;
drh72365832007-03-06 15:53:44 +00006797 assert( sz==info.nPayload );
drh6f11bef2004-05-13 01:12:56 +00006798 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00006799 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00006800 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
6801#ifndef SQLITE_OMIT_AUTOVACUUM
6802 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006803 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00006804 }
6805#endif
6806 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00006807 }
6808
6809 /* Check sanity of left child page.
6810 */
drhda200cc2004-05-09 11:51:38 +00006811 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006812 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00006813#ifndef SQLITE_OMIT_AUTOVACUUM
6814 if( pBt->autoVacuum ){
6815 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
6816 }
6817#endif
drh74161702006-02-24 02:53:49 +00006818 d2 = checkTreePage(pCheck,pgno,pPage,zContext);
drhda200cc2004-05-09 11:51:38 +00006819 if( i>0 && d2!=depth ){
6820 checkAppendMsg(pCheck, zContext, "Child page depth differs");
6821 }
6822 depth = d2;
drh5eddca62001-06-30 21:53:53 +00006823 }
drh5eddca62001-06-30 21:53:53 +00006824 }
drhda200cc2004-05-09 11:51:38 +00006825 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006826 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh5bb3eb92007-05-04 13:15:55 +00006827 sqlite3_snprintf(sizeof(zContext), zContext,
6828 "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00006829#ifndef SQLITE_OMIT_AUTOVACUUM
6830 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006831 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00006832 }
6833#endif
drh74161702006-02-24 02:53:49 +00006834 checkTreePage(pCheck, pgno, pPage, zContext);
drhda200cc2004-05-09 11:51:38 +00006835 }
drh5eddca62001-06-30 21:53:53 +00006836
6837 /* Check for complete coverage of the page
6838 */
drhda200cc2004-05-09 11:51:38 +00006839 data = pPage->aData;
6840 hdr = pPage->hdrOffset;
drhf7141992008-06-19 00:16:08 +00006841 hit = sqlite3PageMalloc( pBt->pageSize );
drhc890fec2008-08-01 20:10:08 +00006842 if( hit==0 ){
6843 pCheck->mallocFailed = 1;
6844 }else{
shane5780ebd2008-11-11 17:36:30 +00006845 u16 contentOffset = get2byte(&data[hdr+5]);
6846 if (contentOffset > usableSize) {
6847 checkAppendMsg(pCheck, 0,
6848 "Corruption detected in header on page %d",iPage,0);
shane0af3f892008-11-12 04:55:34 +00006849 goto check_page_abort;
shane5780ebd2008-11-11 17:36:30 +00006850 }
6851 memset(hit+contentOffset, 0, usableSize-contentOffset);
6852 memset(hit, 1, contentOffset);
drh2e38c322004-09-03 18:38:44 +00006853 nCell = get2byte(&data[hdr+3]);
6854 cellStart = hdr + 12 - 4*pPage->leaf;
6855 for(i=0; i<nCell; i++){
6856 int pc = get2byte(&data[cellStart+i*2]);
danielk1977daca5432008-08-25 11:57:16 +00006857 u16 size = 1024;
drh2e38c322004-09-03 18:38:44 +00006858 int j;
danielk1977daca5432008-08-25 11:57:16 +00006859 if( pc<=usableSize ){
6860 size = cellSizePtr(pPage, &data[pc]);
6861 }
danielk19777701e812005-01-10 12:59:51 +00006862 if( (pc+size-1)>=usableSize || pc<0 ){
6863 checkAppendMsg(pCheck, 0,
6864 "Corruption detected in cell %d on page %d",i,iPage,0);
6865 }else{
6866 for(j=pc+size-1; j>=pc; j--) hit[j]++;
6867 }
drh2e38c322004-09-03 18:38:44 +00006868 }
6869 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
6870 cnt++){
6871 int size = get2byte(&data[i+2]);
6872 int j;
danielk19777701e812005-01-10 12:59:51 +00006873 if( (i+size-1)>=usableSize || i<0 ){
6874 checkAppendMsg(pCheck, 0,
6875 "Corruption detected in cell %d on page %d",i,iPage,0);
6876 }else{
6877 for(j=i+size-1; j>=i; j--) hit[j]++;
6878 }
drh2e38c322004-09-03 18:38:44 +00006879 i = get2byte(&data[i]);
6880 }
6881 for(i=cnt=0; i<usableSize; i++){
6882 if( hit[i]==0 ){
6883 cnt++;
6884 }else if( hit[i]>1 ){
6885 checkAppendMsg(pCheck, 0,
6886 "Multiple uses for byte %d of page %d", i, iPage);
6887 break;
6888 }
6889 }
6890 if( cnt!=data[hdr+7] ){
6891 checkAppendMsg(pCheck, 0,
6892 "Fragmented space is %d byte reported as %d on page %d",
6893 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00006894 }
6895 }
shane0af3f892008-11-12 04:55:34 +00006896check_page_abort:
6897 if (hit) sqlite3PageFree(hit);
drh6019e162001-07-02 17:51:45 +00006898
drh4b70f112004-05-02 21:12:19 +00006899 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00006900 return depth+1;
drh5eddca62001-06-30 21:53:53 +00006901}
drhb7f91642004-10-31 02:22:47 +00006902#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006903
drhb7f91642004-10-31 02:22:47 +00006904#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006905/*
6906** This routine does a complete check of the given BTree file. aRoot[] is
6907** an array of pages numbers were each page number is the root page of
6908** a table. nRoot is the number of entries in aRoot.
6909**
drhc890fec2008-08-01 20:10:08 +00006910** Write the number of error seen in *pnErr. Except for some memory
6911** allocation errors, nn error message is held in memory obtained from
6912** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
6913** returned.
drh5eddca62001-06-30 21:53:53 +00006914*/
drh1dcdbc02007-01-27 02:24:54 +00006915char *sqlite3BtreeIntegrityCheck(
6916 Btree *p, /* The btree to be checked */
6917 int *aRoot, /* An array of root pages numbers for individual trees */
6918 int nRoot, /* Number of entries in aRoot[] */
6919 int mxErr, /* Stop reporting errors after this many */
6920 int *pnErr /* Write number of errors seen to this variable */
6921){
drh5eddca62001-06-30 21:53:53 +00006922 int i;
6923 int nRef;
drhaaab5722002-02-19 13:39:21 +00006924 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00006925 BtShared *pBt = p->pBt;
drhf089aa42008-07-08 19:34:06 +00006926 char zErr[100];
drh5eddca62001-06-30 21:53:53 +00006927
drhd677b3d2007-08-20 22:48:41 +00006928 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006929 pBt->db = p->db;
danielk19773b8a05f2007-03-19 17:44:26 +00006930 nRef = sqlite3PagerRefcount(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00006931 if( lockBtreeWithRetry(p)!=SQLITE_OK ){
drhc890fec2008-08-01 20:10:08 +00006932 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00006933 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00006934 return sqlite3DbStrDup(0, "cannot acquire a read lock on the database");
drhefc251d2001-07-01 22:12:01 +00006935 }
drh5eddca62001-06-30 21:53:53 +00006936 sCheck.pBt = pBt;
6937 sCheck.pPager = pBt->pPager;
danielk1977ad0132d2008-06-07 08:58:22 +00006938 sCheck.nPage = pagerPagecount(sCheck.pPager);
drh1dcdbc02007-01-27 02:24:54 +00006939 sCheck.mxErr = mxErr;
6940 sCheck.nErr = 0;
drhc890fec2008-08-01 20:10:08 +00006941 sCheck.mallocFailed = 0;
drh1dcdbc02007-01-27 02:24:54 +00006942 *pnErr = 0;
danielk1977e5321f02007-04-27 07:05:44 +00006943#ifndef SQLITE_OMIT_AUTOVACUUM
6944 if( pBt->nTrunc!=0 ){
6945 sCheck.nPage = pBt->nTrunc;
6946 }
6947#endif
drh0de8c112002-07-06 16:32:14 +00006948 if( sCheck.nPage==0 ){
6949 unlockBtreeIfUnused(pBt);
drhd677b3d2007-08-20 22:48:41 +00006950 sqlite3BtreeLeave(p);
drh0de8c112002-07-06 16:32:14 +00006951 return 0;
6952 }
drhe5ae5732008-06-15 02:51:47 +00006953 sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00006954 if( !sCheck.anRef ){
6955 unlockBtreeIfUnused(pBt);
drh1dcdbc02007-01-27 02:24:54 +00006956 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00006957 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00006958 return 0;
danielk1977ac245ec2005-01-14 13:50:11 +00006959 }
drhda200cc2004-05-09 11:51:38 +00006960 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00006961 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00006962 if( i<=sCheck.nPage ){
6963 sCheck.anRef[i] = 1;
6964 }
drhf089aa42008-07-08 19:34:06 +00006965 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
drh5eddca62001-06-30 21:53:53 +00006966
6967 /* Check the integrity of the freelist
6968 */
drha34b6762004-05-07 13:30:42 +00006969 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
6970 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00006971
6972 /* Check all the tables.
6973 */
drh1dcdbc02007-01-27 02:24:54 +00006974 for(i=0; i<nRoot && sCheck.mxErr; i++){
drh4ff6dfa2002-03-03 23:06:00 +00006975 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00006976#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006977 if( pBt->autoVacuum && aRoot[i]>1 ){
6978 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
6979 }
6980#endif
drh74161702006-02-24 02:53:49 +00006981 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ");
drh5eddca62001-06-30 21:53:53 +00006982 }
6983
6984 /* Make sure every page in the file is referenced
6985 */
drh1dcdbc02007-01-27 02:24:54 +00006986 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00006987#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00006988 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00006989 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00006990 }
danielk1977afcdd022004-10-31 16:25:42 +00006991#else
6992 /* If the database supports auto-vacuum, make sure no tables contain
6993 ** references to pointer-map pages.
6994 */
6995 if( sCheck.anRef[i]==0 &&
danielk1977266664d2006-02-10 08:24:21 +00006996 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006997 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
6998 }
6999 if( sCheck.anRef[i]!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00007000 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00007001 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
7002 }
7003#endif
drh5eddca62001-06-30 21:53:53 +00007004 }
7005
7006 /* Make sure this analysis did not leave any unref() pages
7007 */
drh5e00f6c2001-09-13 13:46:56 +00007008 unlockBtreeIfUnused(pBt);
danielk19773b8a05f2007-03-19 17:44:26 +00007009 if( nRef != sqlite3PagerRefcount(pBt->pPager) ){
drh2e38c322004-09-03 18:38:44 +00007010 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00007011 "Outstanding page count goes from %d to %d during this analysis",
danielk19773b8a05f2007-03-19 17:44:26 +00007012 nRef, sqlite3PagerRefcount(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00007013 );
drh5eddca62001-06-30 21:53:53 +00007014 }
7015
7016 /* Clean up and report errors.
7017 */
drhd677b3d2007-08-20 22:48:41 +00007018 sqlite3BtreeLeave(p);
drh17435752007-08-16 04:30:38 +00007019 sqlite3_free(sCheck.anRef);
drhc890fec2008-08-01 20:10:08 +00007020 if( sCheck.mallocFailed ){
7021 sqlite3StrAccumReset(&sCheck.errMsg);
7022 *pnErr = sCheck.nErr+1;
7023 return 0;
7024 }
drh1dcdbc02007-01-27 02:24:54 +00007025 *pnErr = sCheck.nErr;
drhf089aa42008-07-08 19:34:06 +00007026 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
7027 return sqlite3StrAccumFinish(&sCheck.errMsg);
drh5eddca62001-06-30 21:53:53 +00007028}
drhb7f91642004-10-31 02:22:47 +00007029#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00007030
drh73509ee2003-04-06 20:44:45 +00007031/*
7032** Return the full pathname of the underlying database file.
drhd0679ed2007-08-28 22:24:34 +00007033**
7034** The pager filename is invariant as long as the pager is
7035** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +00007036*/
danielk1977aef0bf62005-12-30 16:28:01 +00007037const char *sqlite3BtreeGetFilename(Btree *p){
7038 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007039 return sqlite3PagerFilename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00007040}
7041
7042/*
danielk19775865e3d2004-06-14 06:03:57 +00007043** Return the pathname of the directory that contains the database file.
drhd0679ed2007-08-28 22:24:34 +00007044**
7045** The pager directory name is invariant as long as the pager is
7046** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00007047*/
danielk1977aef0bf62005-12-30 16:28:01 +00007048const char *sqlite3BtreeGetDirname(Btree *p){
7049 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007050 return sqlite3PagerDirname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00007051}
7052
7053/*
7054** Return the pathname of the journal file for this database. The return
7055** value of this routine is the same regardless of whether the journal file
7056** has been created or not.
drhd0679ed2007-08-28 22:24:34 +00007057**
7058** The pager journal filename is invariant as long as the pager is
7059** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00007060*/
danielk1977aef0bf62005-12-30 16:28:01 +00007061const char *sqlite3BtreeGetJournalname(Btree *p){
7062 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007063 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00007064}
7065
drhb7f91642004-10-31 02:22:47 +00007066#ifndef SQLITE_OMIT_VACUUM
danielk19775865e3d2004-06-14 06:03:57 +00007067/*
drhf7c57532003-04-25 13:22:51 +00007068** Copy the complete content of pBtFrom into pBtTo. A transaction
7069** must be active for both files.
7070**
danielk1977f653d782008-03-20 11:04:21 +00007071** The size of file pTo may be reduced by this operation.
7072** If anything goes wrong, the transaction on pTo is rolled back.
7073**
7074** If successful, CommitPhaseOne() may be called on pTo before returning.
7075** The caller should finish committing the transaction on pTo by calling
7076** sqlite3BtreeCommit().
drh73509ee2003-04-06 20:44:45 +00007077*/
drhd677b3d2007-08-20 22:48:41 +00007078static int btreeCopyFile(Btree *pTo, Btree *pFrom){
drhf7c57532003-04-25 13:22:51 +00007079 int rc = SQLITE_OK;
danielk1977f653d782008-03-20 11:04:21 +00007080 Pgno i;
7081
7082 Pgno nFromPage; /* Number of pages in pFrom */
7083 Pgno nToPage; /* Number of pages in pTo */
7084 Pgno nNewPage; /* Number of pages in pTo after the copy */
7085
7086 Pgno iSkip; /* Pending byte page in pTo */
7087 int nToPageSize; /* Page size of pTo in bytes */
7088 int nFromPageSize; /* Page size of pFrom in bytes */
drhf7c57532003-04-25 13:22:51 +00007089
danielk1977aef0bf62005-12-30 16:28:01 +00007090 BtShared *pBtTo = pTo->pBt;
7091 BtShared *pBtFrom = pFrom->pBt;
drhe5fe6902007-12-07 18:55:28 +00007092 pBtTo->db = pTo->db;
7093 pBtFrom->db = pFrom->db;
danielk1977f653d782008-03-20 11:04:21 +00007094
7095 nToPageSize = pBtTo->pageSize;
7096 nFromPageSize = pBtFrom->pageSize;
danielk1977aef0bf62005-12-30 16:28:01 +00007097
7098 if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
danielk1977ee5741e2004-05-31 10:01:34 +00007099 return SQLITE_ERROR;
7100 }
danielk1977f653d782008-03-20 11:04:21 +00007101 if( pBtTo->pCursor ){
7102 return SQLITE_BUSY;
drhf7c57532003-04-25 13:22:51 +00007103 }
drh538f5702007-04-13 02:14:30 +00007104
danielk1977ad0132d2008-06-07 08:58:22 +00007105 nToPage = pagerPagecount(pBtTo->pPager);
7106 nFromPage = pagerPagecount(pBtFrom->pPager);
danielk1977f653d782008-03-20 11:04:21 +00007107 iSkip = PENDING_BYTE_PAGE(pBtTo);
7108
7109 /* Variable nNewPage is the number of pages required to store the
7110 ** contents of pFrom using the current page-size of pTo.
drh538f5702007-04-13 02:14:30 +00007111 */
danielk1977f653d782008-03-20 11:04:21 +00007112 nNewPage = ((i64)nFromPage * (i64)nFromPageSize + (i64)nToPageSize - 1) /
7113 (i64)nToPageSize;
7114
7115 for(i=1; rc==SQLITE_OK && (i<=nToPage || i<=nNewPage); i++){
7116
7117 /* Journal the original page.
7118 **
7119 ** iSkip is the page number of the locking page (PENDING_BYTE_PAGE)
7120 ** in database *pTo (before the copy). This page is never written
7121 ** into the journal file. Unless i==iSkip or the page was not
7122 ** present in pTo before the copy operation, journal page i from pTo.
7123 */
7124 if( i!=iSkip && i<=nToPage ){
danielk19774abd5442008-05-05 15:26:50 +00007125 DbPage *pDbPage = 0;
danielk1977f653d782008-03-20 11:04:21 +00007126 rc = sqlite3PagerGet(pBtTo->pPager, i, &pDbPage);
danielk19774abd5442008-05-05 15:26:50 +00007127 if( rc==SQLITE_OK ){
7128 rc = sqlite3PagerWrite(pDbPage);
danielk1977df2566a2008-05-07 19:11:03 +00007129 if( rc==SQLITE_OK && i>nFromPage ){
7130 /* Yeah. It seems wierd to call DontWrite() right after Write(). But
7131 ** that is because the names of those procedures do not exactly
7132 ** represent what they do. Write() really means "put this page in the
7133 ** rollback journal and mark it as dirty so that it will be written
7134 ** to the database file later." DontWrite() undoes the second part of
7135 ** that and prevents the page from being written to the database. The
7136 ** page is still on the rollback journal, though. And that is the
7137 ** whole point of this block: to put pages on the rollback journal.
7138 */
danielk1977a1fa00d2008-08-27 15:16:33 +00007139 rc = sqlite3PagerDontWrite(pDbPage);
danielk1977df2566a2008-05-07 19:11:03 +00007140 }
7141 sqlite3PagerUnref(pDbPage);
danielk1977f653d782008-03-20 11:04:21 +00007142 }
danielk1977f653d782008-03-20 11:04:21 +00007143 }
7144
7145 /* Overwrite the data in page i of the target database */
7146 if( rc==SQLITE_OK && i!=iSkip && i<=nNewPage ){
7147
7148 DbPage *pToPage = 0;
7149 sqlite3_int64 iOff;
7150
7151 rc = sqlite3PagerGet(pBtTo->pPager, i, &pToPage);
7152 if( rc==SQLITE_OK ){
7153 rc = sqlite3PagerWrite(pToPage);
7154 }
7155
7156 for(
7157 iOff=(i-1)*nToPageSize;
7158 rc==SQLITE_OK && iOff<i*nToPageSize;
7159 iOff += nFromPageSize
7160 ){
7161 DbPage *pFromPage = 0;
7162 Pgno iFrom = (iOff/nFromPageSize)+1;
7163
7164 if( iFrom==PENDING_BYTE_PAGE(pBtFrom) ){
7165 continue;
7166 }
7167
7168 rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
7169 if( rc==SQLITE_OK ){
7170 char *zTo = sqlite3PagerGetData(pToPage);
7171 char *zFrom = sqlite3PagerGetData(pFromPage);
7172 int nCopy;
7173
7174 if( nFromPageSize>=nToPageSize ){
7175 zFrom += ((i-1)*nToPageSize - ((iFrom-1)*nFromPageSize));
7176 nCopy = nToPageSize;
7177 }else{
7178 zTo += (((iFrom-1)*nFromPageSize) - (i-1)*nToPageSize);
7179 nCopy = nFromPageSize;
7180 }
7181
7182 memcpy(zTo, zFrom, nCopy);
danielk19772f78fc62008-09-30 09:31:45 +00007183 sqlite3PagerUnref(pFromPage);
danielk1977f653d782008-03-20 11:04:21 +00007184 }
7185 }
7186
danielk1977eaa06f62008-09-18 17:34:44 +00007187 if( pToPage ){
7188 MemPage *p = (MemPage *)sqlite3PagerGetExtra(pToPage);
7189 p->isInit = 0;
7190 sqlite3PagerUnref(pToPage);
7191 }
danielk1977f653d782008-03-20 11:04:21 +00007192 }
drh2e6d11b2003-04-25 15:37:57 +00007193 }
danielk1977f653d782008-03-20 11:04:21 +00007194
7195 /* If things have worked so far, the database file may need to be
7196 ** truncated. The complex part is that it may need to be truncated to
7197 ** a size that is not an integer multiple of nToPageSize - the current
7198 ** page size used by the pager associated with B-Tree pTo.
7199 **
7200 ** For example, say the page-size of pTo is 2048 bytes and the original
7201 ** number of pages is 5 (10 KB file). If pFrom has a page size of 1024
7202 ** bytes and 9 pages, then the file needs to be truncated to 9KB.
7203 */
7204 if( rc==SQLITE_OK ){
7205 if( nFromPageSize!=nToPageSize ){
7206 sqlite3_file *pFile = sqlite3PagerFile(pBtTo->pPager);
7207 i64 iSize = (i64)nFromPageSize * (i64)nFromPage;
7208 i64 iNow = (i64)((nToPage>nNewPage)?nToPage:nNewPage) * (i64)nToPageSize;
7209 i64 iPending = ((i64)PENDING_BYTE_PAGE(pBtTo)-1) *(i64)nToPageSize;
7210
7211 assert( iSize<=iNow );
7212
7213 /* Commit phase one syncs the journal file associated with pTo
7214 ** containing the original data. It does not sync the database file
7215 ** itself. After doing this it is safe to use OsTruncate() and other
7216 ** file APIs on the database file directly.
7217 */
7218 pBtTo->db = pTo->db;
7219 rc = sqlite3PagerCommitPhaseOne(pBtTo->pPager, 0, 0, 1);
7220 if( iSize<iNow && rc==SQLITE_OK ){
7221 rc = sqlite3OsTruncate(pFile, iSize);
7222 }
7223
7224 /* The loop that copied data from database pFrom to pTo did not
7225 ** populate the locking page of database pTo. If the page-size of
7226 ** pFrom is smaller than that of pTo, this means some data will
7227 ** not have been copied.
7228 **
7229 ** This block copies the missing data from database pFrom to pTo
7230 ** using file APIs. This is safe because at this point we know that
7231 ** all of the original data from pTo has been synced into the
7232 ** journal file. At this point it would be safe to do anything at
7233 ** all to the database file except truncate it to zero bytes.
7234 */
7235 if( rc==SQLITE_OK && nFromPageSize<nToPageSize && iSize>iPending){
7236 i64 iOff;
7237 for(
7238 iOff=iPending;
7239 rc==SQLITE_OK && iOff<(iPending+nToPageSize);
7240 iOff += nFromPageSize
7241 ){
7242 DbPage *pFromPage = 0;
7243 Pgno iFrom = (iOff/nFromPageSize)+1;
7244
7245 if( iFrom==PENDING_BYTE_PAGE(pBtFrom) || iFrom>nFromPage ){
7246 continue;
7247 }
7248
7249 rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
7250 if( rc==SQLITE_OK ){
7251 char *zFrom = sqlite3PagerGetData(pFromPage);
danielk197706249db2008-08-23 16:17:55 +00007252 rc = sqlite3OsWrite(pFile, zFrom, nFromPageSize, iOff);
danielk1977f653d782008-03-20 11:04:21 +00007253 sqlite3PagerUnref(pFromPage);
7254 }
7255 }
7256 }
7257
7258 /* Sync the database file */
7259 if( rc==SQLITE_OK ){
7260 rc = sqlite3PagerSync(pBtTo->pPager);
7261 }
7262 }else{
7263 rc = sqlite3PagerTruncate(pBtTo->pPager, nNewPage);
7264 }
7265 if( rc==SQLITE_OK ){
7266 pBtTo->pageSizeFixed = 0;
7267 }
drh2e6d11b2003-04-25 15:37:57 +00007268 }
drh538f5702007-04-13 02:14:30 +00007269
drhf7c57532003-04-25 13:22:51 +00007270 if( rc ){
danielk1977aef0bf62005-12-30 16:28:01 +00007271 sqlite3BtreeRollback(pTo);
drhf7c57532003-04-25 13:22:51 +00007272 }
danielk1977f653d782008-03-20 11:04:21 +00007273
drhf7c57532003-04-25 13:22:51 +00007274 return rc;
drh73509ee2003-04-06 20:44:45 +00007275}
drhd677b3d2007-08-20 22:48:41 +00007276int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
7277 int rc;
7278 sqlite3BtreeEnter(pTo);
7279 sqlite3BtreeEnter(pFrom);
7280 rc = btreeCopyFile(pTo, pFrom);
7281 sqlite3BtreeLeave(pFrom);
7282 sqlite3BtreeLeave(pTo);
7283 return rc;
7284}
7285
drhb7f91642004-10-31 02:22:47 +00007286#endif /* SQLITE_OMIT_VACUUM */
danielk19771d850a72004-05-31 08:26:49 +00007287
7288/*
7289** Return non-zero if a transaction is active.
7290*/
danielk1977aef0bf62005-12-30 16:28:01 +00007291int sqlite3BtreeIsInTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00007292 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00007293 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00007294}
7295
7296/*
7297** Return non-zero if a statement transaction is active.
7298*/
danielk1977aef0bf62005-12-30 16:28:01 +00007299int sqlite3BtreeIsInStmt(Btree *p){
drh1fee73e2007-08-29 04:00:57 +00007300 assert( sqlite3BtreeHoldsMutex(p) );
danielk1977aef0bf62005-12-30 16:28:01 +00007301 return (p->pBt && p->pBt->inStmt);
danielk19771d850a72004-05-31 08:26:49 +00007302}
danielk197713adf8a2004-06-03 16:08:41 +00007303
7304/*
danielk19772372c2b2006-06-27 16:34:56 +00007305** Return non-zero if a read (or write) transaction is active.
7306*/
7307int sqlite3BtreeIsInReadTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00007308 assert( sqlite3_mutex_held(p->db->mutex) );
danielk19772372c2b2006-06-27 16:34:56 +00007309 return (p && (p->inTrans!=TRANS_NONE));
7310}
7311
7312/*
danielk1977da184232006-01-05 11:34:32 +00007313** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +00007314** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +00007315** purposes (for example, to store a high-level schema associated with
7316** the shared-btree). The btree layer manages reference counting issues.
7317**
7318** The first time this is called on a shared-btree, nBytes bytes of memory
7319** are allocated, zeroed, and returned to the caller. For each subsequent
7320** call the nBytes parameter is ignored and a pointer to the same blob
7321** of memory returned.
7322**
danielk1977171bfed2008-06-23 09:50:50 +00007323** If the nBytes parameter is 0 and the blob of memory has not yet been
7324** allocated, a null pointer is returned. If the blob has already been
7325** allocated, it is returned as normal.
7326**
danielk1977da184232006-01-05 11:34:32 +00007327** Just before the shared-btree is closed, the function passed as the
7328** xFree argument when the memory allocation was made is invoked on the
drh17435752007-08-16 04:30:38 +00007329** blob of allocated memory. This function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +00007330** on the memory, the btree layer does that.
7331*/
7332void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
7333 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +00007334 sqlite3BtreeEnter(p);
danielk1977171bfed2008-06-23 09:50:50 +00007335 if( !pBt->pSchema && nBytes ){
drh17435752007-08-16 04:30:38 +00007336 pBt->pSchema = sqlite3MallocZero(nBytes);
danielk1977da184232006-01-05 11:34:32 +00007337 pBt->xFreeSchema = xFree;
7338 }
drh27641702007-08-22 02:56:42 +00007339 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00007340 return pBt->pSchema;
7341}
7342
danielk1977c87d34d2006-01-06 13:00:28 +00007343/*
7344** Return true if another user of the same shared btree as the argument
7345** handle holds an exclusive lock on the sqlite_master table.
7346*/
7347int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +00007348 int rc;
drhe5fe6902007-12-07 18:55:28 +00007349 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +00007350 sqlite3BtreeEnter(p);
7351 rc = (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
7352 sqlite3BtreeLeave(p);
7353 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +00007354}
7355
drha154dcd2006-03-22 22:10:07 +00007356
7357#ifndef SQLITE_OMIT_SHARED_CACHE
7358/*
7359** Obtain a lock on the table whose root page is iTab. The
7360** lock is a write lock if isWritelock is true or a read lock
7361** if it is false.
7362*/
danielk1977c00da102006-01-07 13:21:04 +00007363int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00007364 int rc = SQLITE_OK;
drh6a9ad3d2008-04-02 16:29:30 +00007365 if( p->sharable ){
7366 u8 lockType = READ_LOCK + isWriteLock;
7367 assert( READ_LOCK+1==WRITE_LOCK );
7368 assert( isWriteLock==0 || isWriteLock==1 );
7369 sqlite3BtreeEnter(p);
7370 rc = queryTableLock(p, iTab, lockType);
7371 if( rc==SQLITE_OK ){
7372 rc = lockTable(p, iTab, lockType);
7373 }
7374 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +00007375 }
7376 return rc;
7377}
drha154dcd2006-03-22 22:10:07 +00007378#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00007379
danielk1977b4e9af92007-05-01 17:49:49 +00007380#ifndef SQLITE_OMIT_INCRBLOB
7381/*
7382** Argument pCsr must be a cursor opened for writing on an
7383** INTKEY table currently pointing at a valid table entry.
7384** This function modifies the data stored as part of that entry.
7385** Only the data content may only be modified, it is not possible
7386** to change the length of the data stored.
7387*/
danielk1977dcbb5d32007-05-04 18:36:44 +00007388int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
drh1fee73e2007-08-29 04:00:57 +00007389 assert( cursorHoldsMutex(pCsr) );
drhe5fe6902007-12-07 18:55:28 +00007390 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00007391 assert(pCsr->isIncrblobHandle);
danielk19773588ceb2008-06-10 17:30:26 +00007392
drha3460582008-07-11 21:02:53 +00007393 restoreCursorPosition(pCsr);
danielk19773588ceb2008-06-10 17:30:26 +00007394 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
7395 if( pCsr->eState!=CURSOR_VALID ){
7396 return SQLITE_ABORT;
danielk1977dcbb5d32007-05-04 18:36:44 +00007397 }
7398
danielk1977d04417962007-05-02 13:16:30 +00007399 /* Check some preconditions:
danielk1977dcbb5d32007-05-04 18:36:44 +00007400 ** (a) the cursor is open for writing,
7401 ** (b) there is no read-lock on the table being modified and
7402 ** (c) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00007403 */
danielk1977d04417962007-05-02 13:16:30 +00007404 if( !pCsr->wrFlag ){
danielk1977dcbb5d32007-05-04 18:36:44 +00007405 return SQLITE_READONLY;
danielk1977d04417962007-05-02 13:16:30 +00007406 }
drhd0679ed2007-08-28 22:24:34 +00007407 assert( !pCsr->pBt->readOnly
7408 && pCsr->pBt->inTransaction==TRANS_WRITE );
danielk19773588ceb2008-06-10 17:30:26 +00007409 if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr, 0) ){
danielk1977d04417962007-05-02 13:16:30 +00007410 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
7411 }
danielk197771d5d2c2008-09-29 11:49:47 +00007412 if( pCsr->eState==CURSOR_INVALID || !pCsr->apPage[pCsr->iPage]->intKey ){
danielk1977d04417962007-05-02 13:16:30 +00007413 return SQLITE_ERROR;
danielk1977b4e9af92007-05-01 17:49:49 +00007414 }
7415
danielk19779f8d6402007-05-02 17:48:45 +00007416 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00007417}
danielk19772dec9702007-05-02 16:48:37 +00007418
7419/*
7420** Set a flag on this cursor to cache the locations of pages from the
danielk1977da107192007-05-04 08:32:13 +00007421** overflow list for the current row. This is used by cursors opened
7422** for incremental blob IO only.
7423**
7424** This function sets a flag only. The actual page location cache
7425** (stored in BtCursor.aOverflow[]) is allocated and used by function
7426** accessPayload() (the worker function for sqlite3BtreeData() and
7427** sqlite3BtreePutData()).
danielk19772dec9702007-05-02 16:48:37 +00007428*/
7429void sqlite3BtreeCacheOverflow(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00007430 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00007431 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00007432 assert(!pCur->isIncrblobHandle);
danielk19772dec9702007-05-02 16:48:37 +00007433 assert(!pCur->aOverflow);
danielk1977dcbb5d32007-05-04 18:36:44 +00007434 pCur->isIncrblobHandle = 1;
danielk19772dec9702007-05-02 16:48:37 +00007435}
danielk1977b4e9af92007-05-01 17:49:49 +00007436#endif