blob: 75090d002bc06d644e0c94e32837943225c0d4c0 [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*************************************************************************
drhe43ba702008-12-05 22:40:08 +000012** $Id: btree.c,v 1.545 2008/12/05 22:40:08 drh Exp $
drh8b2f49b2001-06-08 00:21:52 +000013**
14** This file implements a external (disk-based) database using BTrees.
drha3152892007-05-05 11:48:52 +000015** See the header comment on "btreeInt.h" for additional information.
16** Including a description of file format and an overview of operation.
drha059ad02001-04-17 20:09:11 +000017*/
drha3152892007-05-05 11:48:52 +000018#include "btreeInt.h"
paulb95a8862003-04-01 21:16:41 +000019
drh8c42ca92001-06-22 19:15:00 +000020/*
drha3152892007-05-05 11:48:52 +000021** The header string that appears at the beginning of every
22** SQLite database.
drh556b2a22005-06-14 16:04:05 +000023*/
drh556b2a22005-06-14 16:04:05 +000024static const char zMagicHeader[] = SQLITE_FILE_HEADER;
drh08ed44e2001-04-29 23:32:55 +000025
drh8c42ca92001-06-22 19:15:00 +000026/*
drha3152892007-05-05 11:48:52 +000027** Set this global variable to 1 to enable tracing using the TRACE
28** macro.
drh615ae552005-01-16 23:21:00 +000029*/
drhe8f52c52008-07-12 14:52:20 +000030#if 0
mlcreech3a00f902008-03-04 17:45:01 +000031int sqlite3BtreeTrace=0; /* True to enable tracing */
drhe8f52c52008-07-12 14:52:20 +000032# define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
33#else
34# define TRACE(X)
drh615ae552005-01-16 23:21:00 +000035#endif
drh615ae552005-01-16 23:21:00 +000036
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){
danielk197789d40042008-11-17 14:20:56 +0000438 int nPagesPerMapPage;
439 Pgno iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +0000440 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000441 nPagesPerMapPage = (pBt->usableSize/5)+1;
442 iPtrMap = (pgno-2)/nPagesPerMapPage;
443 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +0000444 if( ret==PENDING_BYTE_PAGE(pBt) ){
445 ret++;
446 }
447 return ret;
448}
danielk1977a19df672004-11-03 11:37:07 +0000449
danielk1977afcdd022004-10-31 16:25:42 +0000450/*
danielk1977afcdd022004-10-31 16:25:42 +0000451** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000452**
453** This routine updates the pointer map entry for page number 'key'
454** so that it maps to type 'eType' and parent page number 'pgno'.
455** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000456*/
danielk1977aef0bf62005-12-30 16:28:01 +0000457static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
danielk19773b8a05f2007-03-19 17:44:26 +0000458 DbPage *pDbPage; /* The pointer map page */
459 u8 *pPtrmap; /* The pointer map data */
460 Pgno iPtrmap; /* The pointer map page number */
461 int offset; /* Offset in pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000462 int rc;
463
drh1fee73e2007-08-29 04:00:57 +0000464 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977266664d2006-02-10 08:24:21 +0000465 /* The master-journal page number must never be used as a pointer map page */
466 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
467
danielk1977ac11ee62005-01-15 12:45:51 +0000468 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000469 if( key==0 ){
drh49285702005-09-17 15:20:26 +0000470 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000471 }
danielk1977266664d2006-02-10 08:24:21 +0000472 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000473 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977687566d2004-11-02 12:56:41 +0000474 if( rc!=SQLITE_OK ){
danielk1977afcdd022004-10-31 16:25:42 +0000475 return rc;
476 }
danielk19778c666b12008-07-18 09:34:57 +0000477 offset = PTRMAP_PTROFFSET(iPtrmap, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000478 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000479
drh615ae552005-01-16 23:21:00 +0000480 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
481 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
danielk19773b8a05f2007-03-19 17:44:26 +0000482 rc = sqlite3PagerWrite(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000483 if( rc==SQLITE_OK ){
484 pPtrmap[offset] = eType;
485 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000486 }
danielk1977afcdd022004-10-31 16:25:42 +0000487 }
488
danielk19773b8a05f2007-03-19 17:44:26 +0000489 sqlite3PagerUnref(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000490 return rc;
danielk1977afcdd022004-10-31 16:25:42 +0000491}
492
493/*
494** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000495**
496** This routine retrieves the pointer map entry for page 'key', writing
497** the type and parent page number to *pEType and *pPgno respectively.
498** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000499*/
danielk1977aef0bf62005-12-30 16:28:01 +0000500static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +0000501 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000502 int iPtrmap; /* Pointer map page index */
503 u8 *pPtrmap; /* Pointer map page data */
504 int offset; /* Offset of entry in pointer map */
505 int rc;
506
drh1fee73e2007-08-29 04:00:57 +0000507 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000508
danielk1977266664d2006-02-10 08:24:21 +0000509 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000510 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000511 if( rc!=0 ){
512 return rc;
513 }
danielk19773b8a05f2007-03-19 17:44:26 +0000514 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000515
danielk19778c666b12008-07-18 09:34:57 +0000516 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drh43617e92006-03-06 20:55:46 +0000517 assert( pEType!=0 );
518 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +0000519 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000520
danielk19773b8a05f2007-03-19 17:44:26 +0000521 sqlite3PagerUnref(pDbPage);
drh49285702005-09-17 15:20:26 +0000522 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000523 return SQLITE_OK;
524}
525
danielk197785d90ca2008-07-19 14:25:15 +0000526#else /* if defined SQLITE_OMIT_AUTOVACUUM */
527 #define ptrmapPut(w,x,y,z) SQLITE_OK
528 #define ptrmapGet(w,x,y,z) SQLITE_OK
529 #define ptrmapPutOvfl(y,z) SQLITE_OK
530#endif
danielk1977afcdd022004-10-31 16:25:42 +0000531
drh0d316a42002-08-11 20:10:47 +0000532/*
drh271efa52004-05-30 19:19:05 +0000533** Given a btree page and a cell index (0 means the first cell on
534** the page, 1 means the second cell, and so forth) return a pointer
535** to the cell content.
536**
537** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000538*/
drh1688c862008-07-18 02:44:17 +0000539#define findCell(P,I) \
540 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
drh43605152004-05-29 21:46:49 +0000541
542/*
drh93a960a2008-07-10 00:32:42 +0000543** This a more complex version of findCell() that works for
drh43605152004-05-29 21:46:49 +0000544** pages that do contain overflow cells. See insert
545*/
546static u8 *findOverflowCell(MemPage *pPage, int iCell){
547 int i;
drh1fee73e2007-08-29 04:00:57 +0000548 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +0000549 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000550 int k;
551 struct _OvflCell *pOvfl;
552 pOvfl = &pPage->aOvfl[i];
553 k = pOvfl->idx;
554 if( k<=iCell ){
555 if( k==iCell ){
556 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000557 }
558 iCell--;
559 }
560 }
danielk19771cc5ed82007-05-16 17:28:43 +0000561 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000562}
563
564/*
565** Parse a cell content block and fill in the CellInfo structure. There
drh16a9b832007-05-05 18:39:25 +0000566** are two versions of this function. sqlite3BtreeParseCell() takes a
567** cell index as the second argument and sqlite3BtreeParseCellPtr()
568** takes a pointer to the body of the cell as its second argument.
danielk19771cc5ed82007-05-16 17:28:43 +0000569**
570** Within this file, the parseCell() macro can be called instead of
571** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
drh43605152004-05-29 21:46:49 +0000572*/
drh16a9b832007-05-05 18:39:25 +0000573void sqlite3BtreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000574 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000575 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000576 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000577){
drh271efa52004-05-30 19:19:05 +0000578 int n; /* Number bytes in cell content header */
579 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000580
drh1fee73e2007-08-29 04:00:57 +0000581 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000582
drh43605152004-05-29 21:46:49 +0000583 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000584 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000585 n = pPage->childPtrSize;
586 assert( n==4-4*pPage->leaf );
drh504b6982006-01-22 21:52:56 +0000587 if( pPage->intKey ){
drh79df1f42008-07-18 00:57:33 +0000588 if( pPage->hasData ){
589 n += getVarint32(&pCell[n], nPayload);
590 }else{
591 nPayload = 0;
592 }
593 n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
594 pInfo->nData = nPayload;
drh504b6982006-01-22 21:52:56 +0000595 }else{
drh79df1f42008-07-18 00:57:33 +0000596 pInfo->nData = 0;
597 n += getVarint32(&pCell[n], nPayload);
598 pInfo->nKey = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000599 }
drh72365832007-03-06 15:53:44 +0000600 pInfo->nPayload = nPayload;
drh504b6982006-01-22 21:52:56 +0000601 pInfo->nHeader = n;
drh79df1f42008-07-18 00:57:33 +0000602 if( likely(nPayload<=pPage->maxLocal) ){
drh271efa52004-05-30 19:19:05 +0000603 /* This is the (easy) common case where the entire payload fits
604 ** on the local page. No overflow is required.
605 */
606 int nSize; /* Total size of cell content in bytes */
drh79df1f42008-07-18 00:57:33 +0000607 nSize = nPayload + n;
drh6f11bef2004-05-13 01:12:56 +0000608 pInfo->nLocal = nPayload;
609 pInfo->iOverflow = 0;
drh79df1f42008-07-18 00:57:33 +0000610 if( (nSize & ~3)==0 ){
drh271efa52004-05-30 19:19:05 +0000611 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000612 }
drh271efa52004-05-30 19:19:05 +0000613 pInfo->nSize = nSize;
drh6f11bef2004-05-13 01:12:56 +0000614 }else{
drh271efa52004-05-30 19:19:05 +0000615 /* If the payload will not fit completely on the local page, we have
616 ** to decide how much to store locally and how much to spill onto
617 ** overflow pages. The strategy is to minimize the amount of unused
618 ** space on overflow pages while keeping the amount of local storage
619 ** in between minLocal and maxLocal.
620 **
621 ** Warning: changing the way overflow payload is distributed in any
622 ** way will result in an incompatible file format.
623 */
624 int minLocal; /* Minimum amount of payload held locally */
625 int maxLocal; /* Maximum amount of payload held locally */
626 int surplus; /* Overflow payload available for local storage */
627
628 minLocal = pPage->minLocal;
629 maxLocal = pPage->maxLocal;
630 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000631 if( surplus <= maxLocal ){
632 pInfo->nLocal = surplus;
633 }else{
634 pInfo->nLocal = minLocal;
635 }
636 pInfo->iOverflow = pInfo->nLocal + n;
637 pInfo->nSize = pInfo->iOverflow + 4;
638 }
drh3aac2dd2004-04-26 14:10:20 +0000639}
danielk19771cc5ed82007-05-16 17:28:43 +0000640#define parseCell(pPage, iCell, pInfo) \
641 sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
drh16a9b832007-05-05 18:39:25 +0000642void sqlite3BtreeParseCell(
drh43605152004-05-29 21:46:49 +0000643 MemPage *pPage, /* Page containing the cell */
644 int iCell, /* The cell index. First cell is 0 */
645 CellInfo *pInfo /* Fill in this structure */
646){
danielk19771cc5ed82007-05-16 17:28:43 +0000647 parseCell(pPage, iCell, pInfo);
drh43605152004-05-29 21:46:49 +0000648}
drh3aac2dd2004-04-26 14:10:20 +0000649
650/*
drh43605152004-05-29 21:46:49 +0000651** Compute the total number of bytes that a Cell needs in the cell
652** data area of the btree-page. The return number includes the cell
653** data header and the local payload, but not any overflow page or
654** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000655*/
danielk1977bc6ada42004-06-30 08:20:16 +0000656#ifndef NDEBUG
drha9121e42008-02-19 14:59:35 +0000657static u16 cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000658 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000659 sqlite3BtreeParseCell(pPage, iCell, &info);
drh43605152004-05-29 21:46:49 +0000660 return info.nSize;
661}
danielk1977bc6ada42004-06-30 08:20:16 +0000662#endif
drha9121e42008-02-19 14:59:35 +0000663static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
drh43605152004-05-29 21:46:49 +0000664 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000665 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000666 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000667}
668
danielk197779a40da2005-01-16 08:00:01 +0000669#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +0000670/*
danielk197726836652005-01-17 01:33:13 +0000671** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +0000672** to an overflow page, insert an entry into the pointer-map
673** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +0000674*/
danielk197726836652005-01-17 01:33:13 +0000675static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
drhfa67c3c2008-07-11 02:21:40 +0000676 CellInfo info;
677 assert( pCell!=0 );
678 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
679 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
680 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
681 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
682 return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +0000683 }
danielk197779a40da2005-01-16 08:00:01 +0000684 return SQLITE_OK;
danielk1977ac11ee62005-01-15 12:45:51 +0000685}
danielk197726836652005-01-17 01:33:13 +0000686/*
687** If the cell with index iCell on page pPage contains a pointer
688** to an overflow page, insert an entry into the pointer-map
689** for the overflow page.
690*/
691static int ptrmapPutOvfl(MemPage *pPage, int iCell){
692 u8 *pCell;
drh1fee73e2007-08-29 04:00:57 +0000693 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197726836652005-01-17 01:33:13 +0000694 pCell = findOverflowCell(pPage, iCell);
695 return ptrmapPutOvflPtr(pPage, pCell);
696}
danielk197779a40da2005-01-16 08:00:01 +0000697#endif
698
danielk1977ac11ee62005-01-15 12:45:51 +0000699
drhda200cc2004-05-09 11:51:38 +0000700/*
drh72f82862001-05-24 21:06:34 +0000701** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +0000702** end of the page and all free space is collected into one
703** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +0000704** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +0000705*/
shane0af3f892008-11-12 04:55:34 +0000706static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000707 int i; /* Loop counter */
708 int pc; /* Address of a i-th cell */
709 int addr; /* Offset of first byte after cell pointer array */
710 int hdr; /* Offset to the page header */
711 int size; /* Size of a cell */
712 int usableSize; /* Number of usable bytes on a page */
713 int cellOffset; /* Offset to the cell pointer array */
drh281b21d2008-08-22 12:57:08 +0000714 int cbrk; /* Offset to the cell content area */
drh43605152004-05-29 21:46:49 +0000715 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +0000716 unsigned char *data; /* The page data */
717 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +0000718
danielk19773b8a05f2007-03-19 17:44:26 +0000719 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000720 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +0000721 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000722 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +0000723 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh26b79942007-11-28 16:19:56 +0000724 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
drh43605152004-05-29 21:46:49 +0000725 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +0000726 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000727 cellOffset = pPage->cellOffset;
728 nCell = pPage->nCell;
729 assert( nCell==get2byte(&data[hdr+3]) );
730 usableSize = pPage->pBt->usableSize;
drh281b21d2008-08-22 12:57:08 +0000731 cbrk = get2byte(&data[hdr+5]);
732 memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
733 cbrk = usableSize;
drh43605152004-05-29 21:46:49 +0000734 for(i=0; i<nCell; i++){
735 u8 *pAddr; /* The i-th cell pointer */
736 pAddr = &data[cellOffset + i*2];
737 pc = get2byte(pAddr);
shanedcc50b72008-11-13 18:29:50 +0000738 if( pc>=usableSize ){
shane0af3f892008-11-12 04:55:34 +0000739 return SQLITE_CORRUPT_BKPT;
740 }
drh43605152004-05-29 21:46:49 +0000741 size = cellSizePtr(pPage, &temp[pc]);
drh281b21d2008-08-22 12:57:08 +0000742 cbrk -= size;
danielk19770d065412008-11-12 18:21:36 +0000743 if( cbrk<cellOffset+2*nCell || pc+size>usableSize ){
shane0af3f892008-11-12 04:55:34 +0000744 return SQLITE_CORRUPT_BKPT;
745 }
danielk19770d065412008-11-12 18:21:36 +0000746 assert( cbrk+size<=usableSize && cbrk>=0 );
drh281b21d2008-08-22 12:57:08 +0000747 memcpy(&data[cbrk], &temp[pc], size);
748 put2byte(pAddr, cbrk);
drh2af926b2001-05-15 00:39:25 +0000749 }
drh281b21d2008-08-22 12:57:08 +0000750 assert( cbrk>=cellOffset+2*nCell );
751 put2byte(&data[hdr+5], cbrk);
drh43605152004-05-29 21:46:49 +0000752 data[hdr+1] = 0;
753 data[hdr+2] = 0;
754 data[hdr+7] = 0;
755 addr = cellOffset+2*nCell;
drh281b21d2008-08-22 12:57:08 +0000756 memset(&data[addr], 0, cbrk-addr);
drhc5053fb2008-11-27 02:22:10 +0000757 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977360e6342008-11-12 08:49:51 +0000758 if( cbrk-addr!=pPage->nFree ){
759 return SQLITE_CORRUPT_BKPT;
760 }
shane0af3f892008-11-12 04:55:34 +0000761 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +0000762}
763
drha059ad02001-04-17 20:09:11 +0000764/*
drh43605152004-05-29 21:46:49 +0000765** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +0000766**
drh9e572e62004-04-23 23:43:10 +0000767** Return the index into pPage->aData[] of the first byte of
drhfa67c3c2008-07-11 02:21:40 +0000768** the new allocation. The caller guarantees that there is enough
769** space. This routine will never fail.
drh2af926b2001-05-15 00:39:25 +0000770**
drh72f82862001-05-24 21:06:34 +0000771** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000772** nBytes of contiguous free space, then this routine automatically
773** calls defragementPage() to consolidate all free space before
774** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000775*/
drh9e572e62004-04-23 23:43:10 +0000776static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +0000777 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +0000778 int size;
drh24cd67e2004-05-10 16:18:47 +0000779 int nFrag;
drh43605152004-05-29 21:46:49 +0000780 int top;
781 int nCell;
782 int cellOffset;
drh9e572e62004-04-23 23:43:10 +0000783 unsigned char *data;
drh43605152004-05-29 21:46:49 +0000784
drh9e572e62004-04-23 23:43:10 +0000785 data = pPage->aData;
danielk19773b8a05f2007-03-19 17:44:26 +0000786 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000787 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +0000788 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa67c3c2008-07-11 02:21:40 +0000789 assert( nByte>=0 ); /* Minimum cell size is 4 */
790 assert( pPage->nFree>=nByte );
791 assert( pPage->nOverflow==0 );
drh43605152004-05-29 21:46:49 +0000792 pPage->nFree -= nByte;
drh9e572e62004-04-23 23:43:10 +0000793 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000794
795 nFrag = data[hdr+7];
796 if( nFrag<60 ){
797 /* Search the freelist looking for a slot big enough to satisfy the
798 ** space request. */
799 addr = hdr+1;
800 while( (pc = get2byte(&data[addr]))>0 ){
801 size = get2byte(&data[pc+2]);
802 if( size>=nByte ){
803 if( size<nByte+4 ){
804 memcpy(&data[addr], &data[pc], 2);
805 data[hdr+7] = nFrag + size - nByte;
806 return pc;
807 }else{
808 put2byte(&data[pc+2], size-nByte);
809 return pc + size - nByte;
810 }
811 }
812 addr = pc;
drh9e572e62004-04-23 23:43:10 +0000813 }
814 }
drh43605152004-05-29 21:46:49 +0000815
816 /* Allocate memory from the gap in between the cell pointer array
817 ** and the cell content area.
818 */
819 top = get2byte(&data[hdr+5]);
820 nCell = get2byte(&data[hdr+3]);
821 cellOffset = pPage->cellOffset;
822 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
danielk1977474b7cc2008-07-09 11:49:46 +0000823 defragmentPage(pPage);
drh43605152004-05-29 21:46:49 +0000824 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +0000825 }
drh43605152004-05-29 21:46:49 +0000826 top -= nByte;
827 assert( cellOffset + 2*nCell <= top );
828 put2byte(&data[hdr+5], top);
drhc5053fb2008-11-27 02:22:10 +0000829 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +0000830 return top;
drh7e3b0a02001-04-28 16:52:40 +0000831}
832
833/*
drh9e572e62004-04-23 23:43:10 +0000834** Return a section of the pPage->aData to the freelist.
835** The first byte of the new free block is pPage->aDisk[start]
836** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +0000837**
838** Most of the effort here is involved in coalesing adjacent
839** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000840*/
shanedcc50b72008-11-13 18:29:50 +0000841static int freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +0000842 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +0000843 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +0000844
drh9e572e62004-04-23 23:43:10 +0000845 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +0000846 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000847 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +0000848 assert( (start + size)<=pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +0000849 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh34004ce2008-07-11 16:15:17 +0000850 assert( size>=0 ); /* Minimum cell size is 4 */
drh9e572e62004-04-23 23:43:10 +0000851
drhfcce93f2006-02-22 03:08:32 +0000852#ifdef SQLITE_SECURE_DELETE
853 /* Overwrite deleted information with zeros when the SECURE_DELETE
854 ** option is enabled at compile-time */
855 memset(&data[start], 0, size);
856#endif
857
drh9e572e62004-04-23 23:43:10 +0000858 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +0000859 hdr = pPage->hdrOffset;
860 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +0000861 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +0000862 assert( pbegin<=pPage->pBt->usableSize-4 );
shanedcc50b72008-11-13 18:29:50 +0000863 if( pbegin<=addr ) {
864 return SQLITE_CORRUPT_BKPT;
865 }
drh3aac2dd2004-04-26 14:10:20 +0000866 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +0000867 }
shanedcc50b72008-11-13 18:29:50 +0000868 if ( pbegin>pPage->pBt->usableSize-4 ) {
869 return SQLITE_CORRUPT_BKPT;
870 }
drh3aac2dd2004-04-26 14:10:20 +0000871 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +0000872 put2byte(&data[addr], start);
873 put2byte(&data[start], pbegin);
874 put2byte(&data[start+2], size);
drh2af926b2001-05-15 00:39:25 +0000875 pPage->nFree += size;
drh9e572e62004-04-23 23:43:10 +0000876
877 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +0000878 addr = pPage->hdrOffset + 1;
879 while( (pbegin = get2byte(&data[addr]))>0 ){
drh9e572e62004-04-23 23:43:10 +0000880 int pnext, psize;
drh3aac2dd2004-04-26 14:10:20 +0000881 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +0000882 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +0000883 pnext = get2byte(&data[pbegin]);
884 psize = get2byte(&data[pbegin+2]);
885 if( pbegin + psize + 3 >= pnext && pnext>0 ){
886 int frag = pnext - (pbegin+psize);
shanedcc50b72008-11-13 18:29:50 +0000887 if( (frag<0) || (frag>data[pPage->hdrOffset+7]) ){
888 return SQLITE_CORRUPT_BKPT;
889 }
drh43605152004-05-29 21:46:49 +0000890 data[pPage->hdrOffset+7] -= frag;
drh9e572e62004-04-23 23:43:10 +0000891 put2byte(&data[pbegin], get2byte(&data[pnext]));
892 put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
893 }else{
drh3aac2dd2004-04-26 14:10:20 +0000894 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +0000895 }
896 }
drh7e3b0a02001-04-28 16:52:40 +0000897
drh43605152004-05-29 21:46:49 +0000898 /* If the cell content area begins with a freeblock, remove it. */
899 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
900 int top;
901 pbegin = get2byte(&data[hdr+1]);
902 memcpy(&data[hdr+1], &data[pbegin], 2);
903 top = get2byte(&data[hdr+5]);
904 put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
drh4b70f112004-05-02 21:12:19 +0000905 }
drhc5053fb2008-11-27 02:22:10 +0000906 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
shanedcc50b72008-11-13 18:29:50 +0000907 return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +0000908}
909
910/*
drh271efa52004-05-30 19:19:05 +0000911** Decode the flags byte (the first byte of the header) for a page
912** and initialize fields of the MemPage structure accordingly.
drh44845222008-07-17 18:39:57 +0000913**
914** Only the following combinations are supported. Anything different
915** indicates a corrupt database files:
916**
917** PTF_ZERODATA
918** PTF_ZERODATA | PTF_LEAF
919** PTF_LEAFDATA | PTF_INTKEY
920** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
drh271efa52004-05-30 19:19:05 +0000921*/
drh44845222008-07-17 18:39:57 +0000922static int decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +0000923 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +0000924
925 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +0000926 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh44845222008-07-17 18:39:57 +0000927 pPage->leaf = flagByte>>3; assert( PTF_LEAF == 1<<3 );
928 flagByte &= ~PTF_LEAF;
929 pPage->childPtrSize = 4-4*pPage->leaf;
drh271efa52004-05-30 19:19:05 +0000930 pBt = pPage->pBt;
drh44845222008-07-17 18:39:57 +0000931 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
932 pPage->intKey = 1;
933 pPage->hasData = pPage->leaf;
drh271efa52004-05-30 19:19:05 +0000934 pPage->maxLocal = pBt->maxLeaf;
935 pPage->minLocal = pBt->minLeaf;
drh44845222008-07-17 18:39:57 +0000936 }else if( flagByte==PTF_ZERODATA ){
937 pPage->intKey = 0;
938 pPage->hasData = 0;
drh271efa52004-05-30 19:19:05 +0000939 pPage->maxLocal = pBt->maxLocal;
940 pPage->minLocal = pBt->minLocal;
drh44845222008-07-17 18:39:57 +0000941 }else{
942 return SQLITE_CORRUPT_BKPT;
drh271efa52004-05-30 19:19:05 +0000943 }
drh44845222008-07-17 18:39:57 +0000944 return SQLITE_OK;
drh271efa52004-05-30 19:19:05 +0000945}
946
947/*
drh7e3b0a02001-04-28 16:52:40 +0000948** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000949**
950** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +0000951** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +0000952** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
953** guarantee that the page is well-formed. It only shows that
954** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000955*/
danielk197771d5d2c2008-09-29 11:49:47 +0000956int sqlite3BtreeInitPage(MemPage *pPage){
drh2af926b2001-05-15 00:39:25 +0000957
danielk197771d5d2c2008-09-29 11:49:47 +0000958 assert( pPage->pBt!=0 );
959 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +0000960 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +0000961 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
962 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +0000963
964 if( !pPage->isInit ){
965 int pc; /* Address of a freeblock within pPage->aData[] */
966 int hdr; /* Offset to beginning of page header */
967 u8 *data; /* Equal to pPage->aData */
968 BtShared *pBt; /* The main btree structure */
969 int usableSize; /* Amount of usable space on each page */
970 int cellOffset; /* Offset from start of page to first cell pointer */
971 int nFree; /* Number of unused bytes on the page */
972 int top; /* First byte of the cell content area */
973
974 pBt = pPage->pBt;
975
danielk1977eaa06f62008-09-18 17:34:44 +0000976 hdr = pPage->hdrOffset;
977 data = pPage->aData;
978 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
979 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
980 pPage->maskPage = pBt->pageSize - 1;
981 pPage->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +0000982 usableSize = pBt->usableSize;
983 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
984 top = get2byte(&data[hdr+5]);
985 pPage->nCell = get2byte(&data[hdr+3]);
986 if( pPage->nCell>MX_CELL(pBt) ){
987 /* To many cells for a single page. The page must be corrupt */
988 return SQLITE_CORRUPT_BKPT;
989 }
danielk1977eaa06f62008-09-18 17:34:44 +0000990
991 /* Compute the total free space on the page */
992 pc = get2byte(&data[hdr+1]);
993 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
994 while( pc>0 ){
995 int next, size;
996 if( pc>usableSize-4 ){
997 /* Free block is off the page */
998 return SQLITE_CORRUPT_BKPT;
999 }
1000 next = get2byte(&data[pc]);
1001 size = get2byte(&data[pc+2]);
1002 if( next>0 && next<=pc+size+3 ){
1003 /* Free blocks must be in accending order */
1004 return SQLITE_CORRUPT_BKPT;
1005 }
1006 nFree += size;
1007 pc = next;
1008 }
1009 pPage->nFree = nFree;
1010 if( nFree>=usableSize ){
1011 /* Free space cannot exceed total page size */
drh49285702005-09-17 15:20:26 +00001012 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001013 }
drh9e572e62004-04-23 23:43:10 +00001014
drh1688c862008-07-18 02:44:17 +00001015#if 0
1016 /* Check that all the offsets in the cell offset array are within range.
1017 **
1018 ** Omitting this consistency check and using the pPage->maskPage mask
1019 ** to prevent overrunning the page buffer in findCell() results in a
1020 ** 2.5% performance gain.
1021 */
1022 {
1023 u8 *pOff; /* Iterator used to check all cell offsets are in range */
1024 u8 *pEnd; /* Pointer to end of cell offset array */
1025 u8 mask; /* Mask of bits that must be zero in MSB of cell offsets */
1026 mask = ~(((u8)(pBt->pageSize>>8))-1);
1027 pEnd = &data[cellOffset + pPage->nCell*2];
1028 for(pOff=&data[cellOffset]; pOff!=pEnd && !((*pOff)&mask); pOff+=2);
1029 if( pOff!=pEnd ){
1030 return SQLITE_CORRUPT_BKPT;
1031 }
danielk1977e16535f2008-06-11 18:15:29 +00001032 }
drh1688c862008-07-18 02:44:17 +00001033#endif
danielk1977e16535f2008-06-11 18:15:29 +00001034
danielk197771d5d2c2008-09-29 11:49:47 +00001035 pPage->isInit = 1;
1036 }
drh9e572e62004-04-23 23:43:10 +00001037 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001038}
1039
1040/*
drh8b2f49b2001-06-08 00:21:52 +00001041** Set up a raw page so that it looks like a database page holding
1042** no entries.
drhbd03cae2001-06-02 02:40:57 +00001043*/
drh9e572e62004-04-23 23:43:10 +00001044static void zeroPage(MemPage *pPage, int flags){
1045 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001046 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00001047 int hdr = pPage->hdrOffset;
drh9e572e62004-04-23 23:43:10 +00001048 int first;
1049
danielk19773b8a05f2007-03-19 17:44:26 +00001050 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drhbf4bca52007-09-06 22:19:14 +00001051 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1052 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +00001053 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00001054 assert( sqlite3_mutex_held(pBt->mutex) );
drh1af4a6e2008-07-18 03:32:51 +00001055 /*memset(&data[hdr], 0, pBt->usableSize - hdr);*/
drh9e572e62004-04-23 23:43:10 +00001056 data[hdr] = flags;
drh43605152004-05-29 21:46:49 +00001057 first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
1058 memset(&data[hdr+1], 0, 4);
1059 data[hdr+7] = 0;
1060 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +00001061 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +00001062 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +00001063 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +00001064 pPage->cellOffset = first;
1065 pPage->nOverflow = 0;
drh1688c862008-07-18 02:44:17 +00001066 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
1067 pPage->maskPage = pBt->pageSize - 1;
drh43605152004-05-29 21:46:49 +00001068 pPage->nCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001069 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00001070}
1071
drh897a8202008-09-18 01:08:15 +00001072
1073/*
1074** Convert a DbPage obtained from the pager into a MemPage used by
1075** the btree layer.
1076*/
1077static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
1078 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
1079 pPage->aData = sqlite3PagerGetData(pDbPage);
1080 pPage->pDbPage = pDbPage;
1081 pPage->pBt = pBt;
1082 pPage->pgno = pgno;
1083 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
1084 return pPage;
1085}
1086
drhbd03cae2001-06-02 02:40:57 +00001087/*
drh3aac2dd2004-04-26 14:10:20 +00001088** Get a page from the pager. Initialize the MemPage.pBt and
1089** MemPage.aData elements if needed.
drh538f5702007-04-13 02:14:30 +00001090**
1091** If the noContent flag is set, it means that we do not care about
1092** the content of the page at this time. So do not go to the disk
1093** to fetch the content. Just fill in the content with zeros for now.
1094** If in the future we call sqlite3PagerWrite() on this page, that
1095** means we have started to be concerned about content and the disk
1096** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00001097*/
drh16a9b832007-05-05 18:39:25 +00001098int sqlite3BtreeGetPage(
1099 BtShared *pBt, /* The btree */
1100 Pgno pgno, /* Number of the page to fetch */
1101 MemPage **ppPage, /* Return the page in this parameter */
1102 int noContent /* Do not load page content if true */
1103){
drh3aac2dd2004-04-26 14:10:20 +00001104 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001105 DbPage *pDbPage;
1106
drh1fee73e2007-08-29 04:00:57 +00001107 assert( sqlite3_mutex_held(pBt->mutex) );
drh538f5702007-04-13 02:14:30 +00001108 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
drh3aac2dd2004-04-26 14:10:20 +00001109 if( rc ) return rc;
drh897a8202008-09-18 01:08:15 +00001110 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
drh3aac2dd2004-04-26 14:10:20 +00001111 return SQLITE_OK;
1112}
1113
1114/*
danielk197789d40042008-11-17 14:20:56 +00001115** Return the size of the database file in pages. If there is any kind of
1116** error, return ((unsigned int)-1).
danielk197767fd7a92008-09-10 17:53:35 +00001117*/
danielk197789d40042008-11-17 14:20:56 +00001118static Pgno pagerPagecount(BtShared *pBt){
1119 int nPage = -1;
danielk197767fd7a92008-09-10 17:53:35 +00001120 int rc;
danielk197789d40042008-11-17 14:20:56 +00001121 assert( pBt->pPage1 );
1122 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1123 assert( rc==SQLITE_OK || nPage==-1 );
1124 return (Pgno)nPage;
danielk197767fd7a92008-09-10 17:53:35 +00001125}
1126
1127/*
drhde647132004-05-07 17:57:49 +00001128** Get a page from the pager and initialize it. This routine
1129** is just a convenience wrapper around separate calls to
drh16a9b832007-05-05 18:39:25 +00001130** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
drhde647132004-05-07 17:57:49 +00001131*/
1132static int getAndInitPage(
danielk1977aef0bf62005-12-30 16:28:01 +00001133 BtShared *pBt, /* The database file */
drhde647132004-05-07 17:57:49 +00001134 Pgno pgno, /* Number of the page to get */
danielk197771d5d2c2008-09-29 11:49:47 +00001135 MemPage **ppPage /* Write the page pointer here */
drhde647132004-05-07 17:57:49 +00001136){
1137 int rc;
drh897a8202008-09-18 01:08:15 +00001138 DbPage *pDbPage;
1139 MemPage *pPage;
1140
drh1fee73e2007-08-29 04:00:57 +00001141 assert( sqlite3_mutex_held(pBt->mutex) );
drh897a8202008-09-18 01:08:15 +00001142 if( pgno==0 ){
drh49285702005-09-17 15:20:26 +00001143 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001144 }
danielk19779f580ad2008-09-10 14:45:57 +00001145
drh897a8202008-09-18 01:08:15 +00001146 /* It is often the case that the page we want is already in cache.
1147 ** If so, get it directly. This saves us from having to call
1148 ** pagerPagecount() to make sure pgno is within limits, which results
1149 ** in a measureable performance improvements.
1150 */
1151 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
1152 if( pDbPage ){
1153 /* Page is already in cache */
1154 *ppPage = pPage = btreePageFromDbPage(pDbPage, pgno, pBt);
1155 rc = SQLITE_OK;
1156 }else{
1157 /* Page not in cache. Acquire it. */
danielk197789d40042008-11-17 14:20:56 +00001158 if( pgno>pagerPagecount(pBt) ){
drh897a8202008-09-18 01:08:15 +00001159 return SQLITE_CORRUPT_BKPT;
1160 }
1161 rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
1162 if( rc ) return rc;
1163 pPage = *ppPage;
1164 }
danielk197771d5d2c2008-09-29 11:49:47 +00001165 if( !pPage->isInit ){
1166 rc = sqlite3BtreeInitPage(pPage);
drh897a8202008-09-18 01:08:15 +00001167 }
1168 if( rc!=SQLITE_OK ){
1169 releasePage(pPage);
1170 *ppPage = 0;
1171 }
drhde647132004-05-07 17:57:49 +00001172 return rc;
1173}
1174
1175/*
drh3aac2dd2004-04-26 14:10:20 +00001176** Release a MemPage. This should be called once for each prior
drh16a9b832007-05-05 18:39:25 +00001177** call to sqlite3BtreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +00001178*/
drh4b70f112004-05-02 21:12:19 +00001179static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001180 if( pPage ){
1181 assert( pPage->aData );
1182 assert( pPage->pBt );
drhbf4bca52007-09-06 22:19:14 +00001183 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1184 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
drh1fee73e2007-08-29 04:00:57 +00001185 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001186 sqlite3PagerUnref(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00001187 }
1188}
1189
1190/*
drha6abd042004-06-09 17:37:22 +00001191** During a rollback, when the pager reloads information into the cache
1192** so that the cache is restored to its original state at the start of
1193** the transaction, for each page restored this routine is called.
1194**
1195** This routine needs to reset the extra data section at the end of the
1196** page to agree with the restored data.
1197*/
danielk1977eaa06f62008-09-18 17:34:44 +00001198static void pageReinit(DbPage *pData){
drh07d183d2005-05-01 22:52:42 +00001199 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00001200 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
danielk197771d5d2c2008-09-29 11:49:47 +00001201 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00001202 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00001203 pPage->isInit = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001204 if( sqlite3PagerPageRefcount(pData)>0 ){
1205 sqlite3BtreeInitPage(pPage);
1206 }
drha6abd042004-06-09 17:37:22 +00001207 }
1208}
1209
1210/*
drhe5fe6902007-12-07 18:55:28 +00001211** Invoke the busy handler for a btree.
1212*/
danielk19771ceedd32008-11-19 10:22:33 +00001213static int btreeInvokeBusyHandler(void *pArg){
drhe5fe6902007-12-07 18:55:28 +00001214 BtShared *pBt = (BtShared*)pArg;
1215 assert( pBt->db );
1216 assert( sqlite3_mutex_held(pBt->db->mutex) );
1217 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
1218}
1219
1220/*
drhad3e0102004-09-03 23:32:18 +00001221** Open a database file.
1222**
drh382c0242001-10-06 16:33:02 +00001223** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001224** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001225** database file will be deleted when sqlite3BtreeClose() is called.
drhe53831d2007-08-17 01:14:38 +00001226** If zFilename is ":memory:" then an in-memory database is created
1227** that is automatically destroyed when it is closed.
drha059ad02001-04-17 20:09:11 +00001228*/
drh23e11ca2004-05-04 17:27:28 +00001229int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001230 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00001231 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001232 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00001233 int flags, /* Options */
1234 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00001235){
drhd677b3d2007-08-20 22:48:41 +00001236 sqlite3_vfs *pVfs; /* The VFS to use for this btree */
drhe53831d2007-08-17 01:14:38 +00001237 BtShared *pBt = 0; /* Shared part of btree structure */
danielk1977aef0bf62005-12-30 16:28:01 +00001238 Btree *p; /* Handle to return */
danielk1977dddbcdc2007-04-26 14:42:34 +00001239 int rc = SQLITE_OK;
drh90f5ecb2004-07-22 01:19:35 +00001240 int nReserve;
1241 unsigned char zDbHeader[100];
danielk1977aef0bf62005-12-30 16:28:01 +00001242
1243 /* Set the variable isMemdb to true for an in-memory database, or
1244 ** false for a file-based database. This symbol is only required if
1245 ** either of the shared-data or autovacuum features are compiled
1246 ** into the library.
1247 */
1248#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
1249 #ifdef SQLITE_OMIT_MEMORYDB
drh980b1a72006-08-16 16:42:48 +00001250 const int isMemdb = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00001251 #else
drh980b1a72006-08-16 16:42:48 +00001252 const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
danielk1977aef0bf62005-12-30 16:28:01 +00001253 #endif
1254#endif
1255
drhe5fe6902007-12-07 18:55:28 +00001256 assert( db!=0 );
1257 assert( sqlite3_mutex_held(db->mutex) );
drh153c62c2007-08-24 03:51:33 +00001258
drhe5fe6902007-12-07 18:55:28 +00001259 pVfs = db->pVfs;
drh17435752007-08-16 04:30:38 +00001260 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00001261 if( !p ){
1262 return SQLITE_NOMEM;
1263 }
1264 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00001265 p->db = db;
danielk1977aef0bf62005-12-30 16:28:01 +00001266
drh198bf392006-01-06 21:52:49 +00001267#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001268 /*
1269 ** If this Btree is a candidate for shared cache, try to find an
1270 ** existing BtShared object that we can share with
1271 */
drh34004ce2008-07-11 16:15:17 +00001272 if( isMemdb==0
drhe5fe6902007-12-07 18:55:28 +00001273 && (db->flags & SQLITE_Vtab)==0
drhe53831d2007-08-17 01:14:38 +00001274 && zFilename && zFilename[0]
drhe53831d2007-08-17 01:14:38 +00001275 ){
danielk1977502b4e02008-09-02 14:07:24 +00001276 if( sqlite3GlobalConfig.sharedCacheEnabled ){
danielk1977adfb9b02007-09-17 07:02:56 +00001277 int nFullPathname = pVfs->mxPathname+1;
drhe5ae5732008-06-15 02:51:47 +00001278 char *zFullPathname = sqlite3Malloc(nFullPathname);
drhff0587c2007-08-29 17:43:19 +00001279 sqlite3_mutex *mutexShared;
1280 p->sharable = 1;
drh34004ce2008-07-11 16:15:17 +00001281 db->flags |= SQLITE_SharedCache;
drhff0587c2007-08-29 17:43:19 +00001282 if( !zFullPathname ){
1283 sqlite3_free(p);
1284 return SQLITE_NOMEM;
1285 }
danielk1977adfb9b02007-09-17 07:02:56 +00001286 sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
danielk197759f8c082008-06-18 17:09:10 +00001287 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhff0587c2007-08-29 17:43:19 +00001288 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001289 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
drhff0587c2007-08-29 17:43:19 +00001290 assert( pBt->nRef>0 );
1291 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
1292 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
1293 p->pBt = pBt;
1294 pBt->nRef++;
1295 break;
1296 }
1297 }
1298 sqlite3_mutex_leave(mutexShared);
1299 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00001300 }
drhff0587c2007-08-29 17:43:19 +00001301#ifdef SQLITE_DEBUG
1302 else{
1303 /* In debug mode, we mark all persistent databases as sharable
1304 ** even when they are not. This exercises the locking code and
1305 ** gives more opportunity for asserts(sqlite3_mutex_held())
1306 ** statements to find locking problems.
1307 */
1308 p->sharable = 1;
1309 }
1310#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001311 }
1312#endif
drha059ad02001-04-17 20:09:11 +00001313 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00001314 /*
1315 ** The following asserts make sure that structures used by the btree are
1316 ** the right size. This is to guard against size changes that result
1317 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00001318 */
drhe53831d2007-08-17 01:14:38 +00001319 assert( sizeof(i64)==8 || sizeof(i64)==4 );
1320 assert( sizeof(u64)==8 || sizeof(u64)==4 );
1321 assert( sizeof(u32)==4 );
1322 assert( sizeof(u16)==2 );
1323 assert( sizeof(Pgno)==4 );
1324
1325 pBt = sqlite3MallocZero( sizeof(*pBt) );
1326 if( pBt==0 ){
1327 rc = SQLITE_NOMEM;
1328 goto btree_open_out;
1329 }
danielk197771d5d2c2008-09-29 11:49:47 +00001330 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
drh33f4e022007-09-03 15:19:34 +00001331 EXTRA_SIZE, flags, vfsFlags);
drhe53831d2007-08-17 01:14:38 +00001332 if( rc==SQLITE_OK ){
1333 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
1334 }
1335 if( rc!=SQLITE_OK ){
1336 goto btree_open_out;
1337 }
danielk19771ceedd32008-11-19 10:22:33 +00001338 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
drhe53831d2007-08-17 01:14:38 +00001339 p->pBt = pBt;
1340
drhe53831d2007-08-17 01:14:38 +00001341 sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
1342 pBt->pCursor = 0;
1343 pBt->pPage1 = 0;
1344 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
1345 pBt->pageSize = get2byte(&zDbHeader[16]);
1346 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1347 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00001348 pBt->pageSize = 0;
1349 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drhe53831d2007-08-17 01:14:38 +00001350#ifndef SQLITE_OMIT_AUTOVACUUM
1351 /* If the magic name ":memory:" will create an in-memory database, then
1352 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
1353 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
1354 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
1355 ** regular file-name. In this case the auto-vacuum applies as per normal.
1356 */
1357 if( zFilename && !isMemdb ){
1358 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
1359 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
1360 }
1361#endif
1362 nReserve = 0;
1363 }else{
1364 nReserve = zDbHeader[20];
drhe53831d2007-08-17 01:14:38 +00001365 pBt->pageSizeFixed = 1;
1366#ifndef SQLITE_OMIT_AUTOVACUUM
1367 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1368 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
1369#endif
1370 }
1371 pBt->usableSize = pBt->pageSize - nReserve;
1372 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
danielk1977a1644fd2007-08-29 12:31:25 +00001373 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drhe53831d2007-08-17 01:14:38 +00001374
1375#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1376 /* Add the new BtShared object to the linked list sharable BtShareds.
1377 */
1378 if( p->sharable ){
1379 sqlite3_mutex *mutexShared;
1380 pBt->nRef = 1;
danielk197759f8c082008-06-18 17:09:10 +00001381 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
danielk1977075c23a2008-09-01 18:34:20 +00001382 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
danielk197759f8c082008-06-18 17:09:10 +00001383 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
drh3285db22007-09-03 22:00:39 +00001384 if( pBt->mutex==0 ){
1385 rc = SQLITE_NOMEM;
drhe5fe6902007-12-07 18:55:28 +00001386 db->mallocFailed = 0;
drh3285db22007-09-03 22:00:39 +00001387 goto btree_open_out;
1388 }
drhff0587c2007-08-29 17:43:19 +00001389 }
drhe53831d2007-08-17 01:14:38 +00001390 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001391 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
1392 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
drhe53831d2007-08-17 01:14:38 +00001393 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00001394 }
drheee46cf2004-11-06 00:02:48 +00001395#endif
drh90f5ecb2004-07-22 01:19:35 +00001396 }
danielk1977aef0bf62005-12-30 16:28:01 +00001397
drhcfed7bc2006-03-13 14:28:05 +00001398#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001399 /* If the new Btree uses a sharable pBtShared, then link the new
1400 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00001401 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00001402 */
drhe53831d2007-08-17 01:14:38 +00001403 if( p->sharable ){
1404 int i;
1405 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00001406 for(i=0; i<db->nDb; i++){
1407 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00001408 while( pSib->pPrev ){ pSib = pSib->pPrev; }
1409 if( p->pBt<pSib->pBt ){
1410 p->pNext = pSib;
1411 p->pPrev = 0;
1412 pSib->pPrev = p;
1413 }else{
drhabddb0c2007-08-20 13:14:28 +00001414 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
drhe53831d2007-08-17 01:14:38 +00001415 pSib = pSib->pNext;
1416 }
1417 p->pNext = pSib->pNext;
1418 p->pPrev = pSib;
1419 if( p->pNext ){
1420 p->pNext->pPrev = p;
1421 }
1422 pSib->pNext = p;
1423 }
1424 break;
1425 }
1426 }
danielk1977aef0bf62005-12-30 16:28:01 +00001427 }
danielk1977aef0bf62005-12-30 16:28:01 +00001428#endif
1429 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00001430
1431btree_open_out:
1432 if( rc!=SQLITE_OK ){
1433 if( pBt && pBt->pPager ){
1434 sqlite3PagerClose(pBt->pPager);
1435 }
drh17435752007-08-16 04:30:38 +00001436 sqlite3_free(pBt);
1437 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00001438 *ppBtree = 0;
1439 }
1440 return rc;
drha059ad02001-04-17 20:09:11 +00001441}
1442
1443/*
drhe53831d2007-08-17 01:14:38 +00001444** Decrement the BtShared.nRef counter. When it reaches zero,
1445** remove the BtShared structure from the sharing list. Return
1446** true if the BtShared.nRef counter reaches zero and return
1447** false if it is still positive.
1448*/
1449static int removeFromSharingList(BtShared *pBt){
1450#ifndef SQLITE_OMIT_SHARED_CACHE
1451 sqlite3_mutex *pMaster;
1452 BtShared *pList;
1453 int removed = 0;
1454
drhd677b3d2007-08-20 22:48:41 +00001455 assert( sqlite3_mutex_notheld(pBt->mutex) );
danielk197759f8c082008-06-18 17:09:10 +00001456 pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhe53831d2007-08-17 01:14:38 +00001457 sqlite3_mutex_enter(pMaster);
1458 pBt->nRef--;
1459 if( pBt->nRef<=0 ){
drh78f82d12008-09-02 00:52:52 +00001460 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
1461 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
drhe53831d2007-08-17 01:14:38 +00001462 }else{
drh78f82d12008-09-02 00:52:52 +00001463 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
drh34004ce2008-07-11 16:15:17 +00001464 while( ALWAYS(pList) && pList->pNext!=pBt ){
drhe53831d2007-08-17 01:14:38 +00001465 pList=pList->pNext;
1466 }
drh34004ce2008-07-11 16:15:17 +00001467 if( ALWAYS(pList) ){
drhe53831d2007-08-17 01:14:38 +00001468 pList->pNext = pBt->pNext;
1469 }
1470 }
drh3285db22007-09-03 22:00:39 +00001471 if( SQLITE_THREADSAFE ){
1472 sqlite3_mutex_free(pBt->mutex);
1473 }
drhe53831d2007-08-17 01:14:38 +00001474 removed = 1;
1475 }
1476 sqlite3_mutex_leave(pMaster);
1477 return removed;
1478#else
1479 return 1;
1480#endif
1481}
1482
1483/*
drhf7141992008-06-19 00:16:08 +00001484** Make sure pBt->pTmpSpace points to an allocation of
1485** MX_CELL_SIZE(pBt) bytes.
1486*/
1487static void allocateTempSpace(BtShared *pBt){
1488 if( !pBt->pTmpSpace ){
1489 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
1490 }
1491}
1492
1493/*
1494** Free the pBt->pTmpSpace allocation
1495*/
1496static void freeTempSpace(BtShared *pBt){
1497 sqlite3PageFree( pBt->pTmpSpace);
1498 pBt->pTmpSpace = 0;
1499}
1500
1501/*
drha059ad02001-04-17 20:09:11 +00001502** Close an open database and invalidate all cursors.
1503*/
danielk1977aef0bf62005-12-30 16:28:01 +00001504int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00001505 BtShared *pBt = p->pBt;
1506 BtCursor *pCur;
1507
danielk1977aef0bf62005-12-30 16:28:01 +00001508 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00001509 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00001510 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00001511 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00001512 pCur = pBt->pCursor;
1513 while( pCur ){
1514 BtCursor *pTmp = pCur;
1515 pCur = pCur->pNext;
1516 if( pTmp->pBtree==p ){
1517 sqlite3BtreeCloseCursor(pTmp);
1518 }
drha059ad02001-04-17 20:09:11 +00001519 }
danielk1977aef0bf62005-12-30 16:28:01 +00001520
danielk19778d34dfd2006-01-24 16:37:57 +00001521 /* Rollback any active transaction and free the handle structure.
1522 ** The call to sqlite3BtreeRollback() drops any table-locks held by
1523 ** this handle.
1524 */
danielk1977b597f742006-01-15 11:39:18 +00001525 sqlite3BtreeRollback(p);
drhe53831d2007-08-17 01:14:38 +00001526 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001527
danielk1977aef0bf62005-12-30 16:28:01 +00001528 /* If there are still other outstanding references to the shared-btree
1529 ** structure, return now. The remainder of this procedure cleans
1530 ** up the shared-btree.
1531 */
drhe53831d2007-08-17 01:14:38 +00001532 assert( p->wantToLock==0 && p->locked==0 );
1533 if( !p->sharable || removeFromSharingList(pBt) ){
1534 /* The pBt is no longer on the sharing list, so we can access
1535 ** it without having to hold the mutex.
1536 **
1537 ** Clean out and delete the BtShared object.
1538 */
1539 assert( !pBt->pCursor );
drhe53831d2007-08-17 01:14:38 +00001540 sqlite3PagerClose(pBt->pPager);
1541 if( pBt->xFreeSchema && pBt->pSchema ){
1542 pBt->xFreeSchema(pBt->pSchema);
1543 }
1544 sqlite3_free(pBt->pSchema);
drhf7141992008-06-19 00:16:08 +00001545 freeTempSpace(pBt);
drh65bbf292008-06-19 01:03:17 +00001546 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00001547 }
1548
drhe53831d2007-08-17 01:14:38 +00001549#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00001550 assert( p->wantToLock==0 );
1551 assert( p->locked==0 );
1552 if( p->pPrev ) p->pPrev->pNext = p->pNext;
1553 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00001554#endif
1555
drhe53831d2007-08-17 01:14:38 +00001556 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00001557 return SQLITE_OK;
1558}
1559
1560/*
drhda47d772002-12-02 04:25:19 +00001561** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001562**
1563** The maximum number of cache pages is set to the absolute
1564** value of mxPage. If mxPage is negative, the pager will
1565** operate asynchronously - it will not stop to do fsync()s
1566** to insure data is written to the disk surface before
1567** continuing. Transactions still work if synchronous is off,
1568** and the database cannot be corrupted if this program
1569** crashes. But if the operating system crashes or there is
1570** an abrupt power failure when synchronous is off, the database
1571** could be left in an inconsistent and unrecoverable state.
1572** Synchronous is on by default so database corruption is not
1573** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001574*/
danielk1977aef0bf62005-12-30 16:28:01 +00001575int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
1576 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001577 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001578 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001579 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00001580 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00001581 return SQLITE_OK;
1582}
1583
1584/*
drh973b6e32003-02-12 14:09:42 +00001585** Change the way data is synced to disk in order to increase or decrease
1586** how well the database resists damage due to OS crashes and power
1587** failures. Level 1 is the same as asynchronous (no syncs() occur and
1588** there is a high probability of damage) Level 2 is the default. There
1589** is a very low but non-zero probability of damage. Level 3 reduces the
1590** probability of damage to near zero but with a write performance reduction.
1591*/
danielk197793758c82005-01-21 08:13:14 +00001592#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drhac530b12006-02-11 01:25:50 +00001593int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
danielk1977aef0bf62005-12-30 16:28:01 +00001594 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001595 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001596 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001597 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
drhd677b3d2007-08-20 22:48:41 +00001598 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00001599 return SQLITE_OK;
1600}
danielk197793758c82005-01-21 08:13:14 +00001601#endif
drh973b6e32003-02-12 14:09:42 +00001602
drh2c8997b2005-08-27 16:36:48 +00001603/*
1604** Return TRUE if the given btree is set to safety level 1. In other
1605** words, return TRUE if no sync() occurs on the disk files.
1606*/
danielk1977aef0bf62005-12-30 16:28:01 +00001607int sqlite3BtreeSyncDisabled(Btree *p){
1608 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001609 int rc;
drhe5fe6902007-12-07 18:55:28 +00001610 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001611 sqlite3BtreeEnter(p);
drhd0679ed2007-08-28 22:24:34 +00001612 assert( pBt && pBt->pPager );
drhd677b3d2007-08-20 22:48:41 +00001613 rc = sqlite3PagerNosync(pBt->pPager);
1614 sqlite3BtreeLeave(p);
1615 return rc;
drh2c8997b2005-08-27 16:36:48 +00001616}
1617
danielk1977576ec6b2005-01-21 11:55:25 +00001618#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00001619/*
drh90f5ecb2004-07-22 01:19:35 +00001620** Change the default pages size and the number of reserved bytes per page.
drh06f50212004-11-02 14:24:33 +00001621**
1622** The page size must be a power of 2 between 512 and 65536. If the page
1623** size supplied does not meet this constraint then the page size is not
1624** changed.
1625**
1626** Page sizes are constrained to be a power of two so that the region
1627** of the database file used for locking (beginning at PENDING_BYTE,
1628** the first byte past the 1GB boundary, 0x40000000) needs to occur
1629** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001630**
1631** If parameter nReserve is less than zero, then the number of reserved
1632** bytes per page is left unchanged.
drh90f5ecb2004-07-22 01:19:35 +00001633*/
danielk1977aef0bf62005-12-30 16:28:01 +00001634int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
danielk1977a1644fd2007-08-29 12:31:25 +00001635 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00001636 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001637 sqlite3BtreeEnter(p);
drh90f5ecb2004-07-22 01:19:35 +00001638 if( pBt->pageSizeFixed ){
drhd677b3d2007-08-20 22:48:41 +00001639 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00001640 return SQLITE_READONLY;
1641 }
1642 if( nReserve<0 ){
1643 nReserve = pBt->pageSize - pBt->usableSize;
1644 }
drh06f50212004-11-02 14:24:33 +00001645 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
1646 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00001647 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00001648 assert( !pBt->pPage1 && !pBt->pCursor );
danielk1977a1644fd2007-08-29 12:31:25 +00001649 pBt->pageSize = pageSize;
drhf7141992008-06-19 00:16:08 +00001650 freeTempSpace(pBt);
danielk1977a1644fd2007-08-29 12:31:25 +00001651 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001652 }
1653 pBt->usableSize = pBt->pageSize - nReserve;
drhd677b3d2007-08-20 22:48:41 +00001654 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00001655 return rc;
drh90f5ecb2004-07-22 01:19:35 +00001656}
1657
1658/*
1659** Return the currently defined page size
1660*/
danielk1977aef0bf62005-12-30 16:28:01 +00001661int sqlite3BtreeGetPageSize(Btree *p){
1662 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00001663}
danielk1977aef0bf62005-12-30 16:28:01 +00001664int sqlite3BtreeGetReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00001665 int n;
1666 sqlite3BtreeEnter(p);
1667 n = p->pBt->pageSize - p->pBt->usableSize;
1668 sqlite3BtreeLeave(p);
1669 return n;
drh2011d5f2004-07-22 02:40:37 +00001670}
drhf8e632b2007-05-08 14:51:36 +00001671
1672/*
1673** Set the maximum page count for a database if mxPage is positive.
1674** No changes are made if mxPage is 0 or negative.
1675** Regardless of the value of mxPage, return the maximum page count.
1676*/
1677int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00001678 int n;
1679 sqlite3BtreeEnter(p);
1680 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
1681 sqlite3BtreeLeave(p);
1682 return n;
drhf8e632b2007-05-08 14:51:36 +00001683}
danielk1977576ec6b2005-01-21 11:55:25 +00001684#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00001685
1686/*
danielk1977951af802004-11-05 15:45:09 +00001687** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
1688** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
1689** is disabled. The default value for the auto-vacuum property is
1690** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
1691*/
danielk1977aef0bf62005-12-30 16:28:01 +00001692int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00001693#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001694 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00001695#else
danielk1977dddbcdc2007-04-26 14:42:34 +00001696 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001697 int rc = SQLITE_OK;
danielk1977dddbcdc2007-04-26 14:42:34 +00001698 int av = (autoVacuum?1:0);
drhd677b3d2007-08-20 22:48:41 +00001699
1700 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00001701 if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00001702 rc = SQLITE_READONLY;
1703 }else{
1704 pBt->autoVacuum = av;
danielk1977951af802004-11-05 15:45:09 +00001705 }
drhd677b3d2007-08-20 22:48:41 +00001706 sqlite3BtreeLeave(p);
1707 return rc;
danielk1977951af802004-11-05 15:45:09 +00001708#endif
1709}
1710
1711/*
1712** Return the value of the 'auto-vacuum' property. If auto-vacuum is
1713** enabled 1 is returned. Otherwise 0.
1714*/
danielk1977aef0bf62005-12-30 16:28:01 +00001715int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00001716#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00001717 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00001718#else
drhd677b3d2007-08-20 22:48:41 +00001719 int rc;
1720 sqlite3BtreeEnter(p);
1721 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00001722 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
1723 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
1724 BTREE_AUTOVACUUM_INCR
1725 );
drhd677b3d2007-08-20 22:48:41 +00001726 sqlite3BtreeLeave(p);
1727 return rc;
danielk1977951af802004-11-05 15:45:09 +00001728#endif
1729}
1730
1731
1732/*
drha34b6762004-05-07 13:30:42 +00001733** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001734** also acquire a readlock on that file.
1735**
1736** SQLITE_OK is returned on success. If the file is not a
1737** well-formed database file, then SQLITE_CORRUPT is returned.
1738** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00001739** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00001740*/
danielk1977aef0bf62005-12-30 16:28:01 +00001741static int lockBtree(BtShared *pBt){
danielk1977f653d782008-03-20 11:04:21 +00001742 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001743 MemPage *pPage1;
danielk197793f7af92008-05-09 16:57:50 +00001744 int nPage;
drhd677b3d2007-08-20 22:48:41 +00001745
drh1fee73e2007-08-29 04:00:57 +00001746 assert( sqlite3_mutex_held(pBt->mutex) );
drha34b6762004-05-07 13:30:42 +00001747 if( pBt->pPage1 ) return SQLITE_OK;
drh16a9b832007-05-05 18:39:25 +00001748 rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00001749 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00001750
1751 /* Do some checking to help insure the file we opened really is
1752 ** a valid database file.
1753 */
danielk1977ad0132d2008-06-07 08:58:22 +00001754 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1755 if( rc!=SQLITE_OK ){
danielk197793f7af92008-05-09 16:57:50 +00001756 goto page1_init_failed;
1757 }else if( nPage>0 ){
danielk1977f653d782008-03-20 11:04:21 +00001758 int pageSize;
1759 int usableSize;
drhb6f41482004-05-14 01:58:11 +00001760 u8 *page1 = pPage1->aData;
danielk1977ad0132d2008-06-07 08:58:22 +00001761 rc = SQLITE_NOTADB;
drhb6f41482004-05-14 01:58:11 +00001762 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001763 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001764 }
drh309169a2007-04-24 17:27:51 +00001765 if( page1[18]>1 ){
1766 pBt->readOnly = 1;
1767 }
1768 if( page1[19]>1 ){
drhb6f41482004-05-14 01:58:11 +00001769 goto page1_init_failed;
1770 }
drhe5ae5732008-06-15 02:51:47 +00001771
1772 /* The maximum embedded fraction must be exactly 25%. And the minimum
1773 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
1774 ** The original design allowed these amounts to vary, but as of
1775 ** version 3.6.0, we require them to be fixed.
1776 */
1777 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
1778 goto page1_init_failed;
1779 }
drh07d183d2005-05-01 22:52:42 +00001780 pageSize = get2byte(&page1[16]);
drh7dc385e2007-09-06 23:39:36 +00001781 if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
1782 (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
1783 ){
drh07d183d2005-05-01 22:52:42 +00001784 goto page1_init_failed;
1785 }
1786 assert( (pageSize & 7)==0 );
danielk1977f653d782008-03-20 11:04:21 +00001787 usableSize = pageSize - page1[20];
1788 if( pageSize!=pBt->pageSize ){
1789 /* After reading the first page of the database assuming a page size
1790 ** of BtShared.pageSize, we have discovered that the page-size is
1791 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
1792 ** zero and return SQLITE_OK. The caller will call this function
1793 ** again with the correct page-size.
1794 */
1795 releasePage(pPage1);
1796 pBt->usableSize = usableSize;
1797 pBt->pageSize = pageSize;
drhf7141992008-06-19 00:16:08 +00001798 freeTempSpace(pBt);
danielk1977f653d782008-03-20 11:04:21 +00001799 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
1800 return SQLITE_OK;
1801 }
1802 if( usableSize<500 ){
drhb6f41482004-05-14 01:58:11 +00001803 goto page1_init_failed;
1804 }
danielk1977f653d782008-03-20 11:04:21 +00001805 pBt->pageSize = pageSize;
1806 pBt->usableSize = usableSize;
drh057cd3a2005-02-15 16:23:02 +00001807#ifndef SQLITE_OMIT_AUTOVACUUM
1808 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00001809 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00001810#endif
drh306dc212001-05-21 13:45:10 +00001811 }
drhb6f41482004-05-14 01:58:11 +00001812
1813 /* maxLocal is the maximum amount of payload to store locally for
1814 ** a cell. Make sure it is small enough so that at least minFanout
1815 ** cells can will fit on one page. We assume a 10-byte page header.
1816 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001817 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001818 ** 4-byte child pointer
1819 ** 9-byte nKey value
1820 ** 4-byte nData value
1821 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001822 ** So a cell consists of a 2-byte poiner, a header which is as much as
1823 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1824 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001825 */
drhe5ae5732008-06-15 02:51:47 +00001826 pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
1827 pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
drh43605152004-05-29 21:46:49 +00001828 pBt->maxLeaf = pBt->usableSize - 35;
drhe5ae5732008-06-15 02:51:47 +00001829 pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
drh2e38c322004-09-03 18:38:44 +00001830 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00001831 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001832 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001833
drh72f82862001-05-24 21:06:34 +00001834page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001835 releasePage(pPage1);
1836 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001837 return rc;
drh306dc212001-05-21 13:45:10 +00001838}
1839
1840/*
drhb8ef32c2005-03-14 02:01:49 +00001841** This routine works like lockBtree() except that it also invokes the
1842** busy callback if there is lock contention.
1843*/
danielk1977aef0bf62005-12-30 16:28:01 +00001844static int lockBtreeWithRetry(Btree *pRef){
drhb8ef32c2005-03-14 02:01:49 +00001845 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00001846
drh1fee73e2007-08-29 04:00:57 +00001847 assert( sqlite3BtreeHoldsMutex(pRef) );
danielk1977aef0bf62005-12-30 16:28:01 +00001848 if( pRef->inTrans==TRANS_NONE ){
1849 u8 inTransaction = pRef->pBt->inTransaction;
1850 btreeIntegrity(pRef);
1851 rc = sqlite3BtreeBeginTrans(pRef, 0);
1852 pRef->pBt->inTransaction = inTransaction;
1853 pRef->inTrans = TRANS_NONE;
1854 if( rc==SQLITE_OK ){
1855 pRef->pBt->nTransaction--;
1856 }
1857 btreeIntegrity(pRef);
drhb8ef32c2005-03-14 02:01:49 +00001858 }
1859 return rc;
1860}
1861
1862
1863/*
drhb8ca3072001-12-05 00:21:20 +00001864** If there are no outstanding cursors and we are not in the middle
1865** of a transaction but there is a read lock on the database, then
1866** this routine unrefs the first page of the database file which
1867** has the effect of releasing the read lock.
1868**
1869** If there are any outstanding cursors, this routine is a no-op.
1870**
1871** If there is a transaction in progress, this routine is a no-op.
1872*/
danielk1977aef0bf62005-12-30 16:28:01 +00001873static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00001874 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00001875 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00001876 if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
drhde4fcfd2008-01-19 23:50:26 +00001877 assert( pBt->pPage1->aData );
1878#if 0
drh24c9a2e2007-01-05 02:00:47 +00001879 if( pBt->pPage1->aData==0 ){
1880 MemPage *pPage = pBt->pPage1;
drhbf4bca52007-09-06 22:19:14 +00001881 pPage->aData = sqlite3PagerGetData(pPage->pDbPage);
drh24c9a2e2007-01-05 02:00:47 +00001882 pPage->pBt = pBt;
1883 pPage->pgno = 1;
1884 }
drhde4fcfd2008-01-19 23:50:26 +00001885#endif
drh24c9a2e2007-01-05 02:00:47 +00001886 releasePage(pBt->pPage1);
drh51c6d962004-06-06 00:42:25 +00001887 }
drh3aac2dd2004-04-26 14:10:20 +00001888 pBt->pPage1 = 0;
drh3aac2dd2004-04-26 14:10:20 +00001889 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001890 }
1891}
1892
1893/*
drh9e572e62004-04-23 23:43:10 +00001894** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00001895** file.
drh8b2f49b2001-06-08 00:21:52 +00001896*/
danielk1977aef0bf62005-12-30 16:28:01 +00001897static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00001898 MemPage *pP1;
1899 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00001900 int rc;
danielk1977ad0132d2008-06-07 08:58:22 +00001901 int nPage;
drhd677b3d2007-08-20 22:48:41 +00001902
drh1fee73e2007-08-29 04:00:57 +00001903 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977ad0132d2008-06-07 08:58:22 +00001904 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1905 if( rc!=SQLITE_OK || nPage>0 ){
1906 return rc;
1907 }
drh3aac2dd2004-04-26 14:10:20 +00001908 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00001909 assert( pP1!=0 );
1910 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00001911 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00001912 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00001913 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
1914 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00001915 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00001916 data[18] = 1;
1917 data[19] = 1;
drhb6f41482004-05-14 01:58:11 +00001918 data[20] = pBt->pageSize - pBt->usableSize;
drhe5ae5732008-06-15 02:51:47 +00001919 data[21] = 64;
1920 data[22] = 32;
1921 data[23] = 32;
drhb6f41482004-05-14 01:58:11 +00001922 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00001923 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00001924 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00001925#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00001926 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00001927 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00001928 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00001929 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00001930#endif
drh8b2f49b2001-06-08 00:21:52 +00001931 return SQLITE_OK;
1932}
1933
1934/*
danielk1977ee5741e2004-05-31 10:01:34 +00001935** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00001936** is started if the second argument is nonzero, otherwise a read-
1937** transaction. If the second argument is 2 or more and exclusive
1938** transaction is started, meaning that no other process is allowed
1939** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00001940** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00001941** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00001942**
danielk1977ee5741e2004-05-31 10:01:34 +00001943** A write-transaction must be started before attempting any
1944** changes to the database. None of the following routines
1945** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00001946**
drh23e11ca2004-05-04 17:27:28 +00001947** sqlite3BtreeCreateTable()
1948** sqlite3BtreeCreateIndex()
1949** sqlite3BtreeClearTable()
1950** sqlite3BtreeDropTable()
1951** sqlite3BtreeInsert()
1952** sqlite3BtreeDelete()
1953** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00001954**
drhb8ef32c2005-03-14 02:01:49 +00001955** If an initial attempt to acquire the lock fails because of lock contention
1956** and the database was previously unlocked, then invoke the busy handler
1957** if there is one. But if there was previously a read-lock, do not
1958** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
1959** returned when there is already a read-lock in order to avoid a deadlock.
1960**
1961** Suppose there are two processes A and B. A has a read lock and B has
1962** a reserved lock. B tries to promote to exclusive but is blocked because
1963** of A's read lock. A tries to promote to reserved but is blocked by B.
1964** One or the other of the two processes must give way or there can be
1965** no progress. By returning SQLITE_BUSY and not invoking the busy callback
1966** when A already has a read lock, we encourage A to give up and let B
1967** proceed.
drha059ad02001-04-17 20:09:11 +00001968*/
danielk1977aef0bf62005-12-30 16:28:01 +00001969int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
1970 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00001971 int rc = SQLITE_OK;
1972
drhd677b3d2007-08-20 22:48:41 +00001973 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00001974 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00001975 btreeIntegrity(p);
1976
danielk1977ee5741e2004-05-31 10:01:34 +00001977 /* If the btree is already in a write-transaction, or it
1978 ** is already in a read-transaction and a read-transaction
1979 ** is requested, this is a no-op.
1980 */
danielk1977aef0bf62005-12-30 16:28:01 +00001981 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00001982 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00001983 }
drhb8ef32c2005-03-14 02:01:49 +00001984
1985 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00001986 if( pBt->readOnly && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00001987 rc = SQLITE_READONLY;
1988 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00001989 }
1990
danielk1977aef0bf62005-12-30 16:28:01 +00001991 /* If another database handle has already opened a write transaction
1992 ** on this shared-btree structure and a second write transaction is
1993 ** requested, return SQLITE_BUSY.
1994 */
1995 if( pBt->inTransaction==TRANS_WRITE && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00001996 rc = SQLITE_BUSY;
1997 goto trans_begun;
danielk1977aef0bf62005-12-30 16:28:01 +00001998 }
1999
danielk1977641b0f42007-12-21 04:47:25 +00002000#ifndef SQLITE_OMIT_SHARED_CACHE
2001 if( wrflag>1 ){
2002 BtLock *pIter;
2003 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
2004 if( pIter->pBtree!=p ){
2005 rc = SQLITE_BUSY;
2006 goto trans_begun;
2007 }
2008 }
2009 }
2010#endif
2011
drhb8ef32c2005-03-14 02:01:49 +00002012 do {
drh8a9c17f2008-05-02 14:23:54 +00002013 if( pBt->pPage1==0 ){
2014 do{
2015 rc = lockBtree(pBt);
2016 }while( pBt->pPage1==0 && rc==SQLITE_OK );
drh8c42ca92001-06-22 19:15:00 +00002017 }
drh309169a2007-04-24 17:27:51 +00002018
drhb8ef32c2005-03-14 02:01:49 +00002019 if( rc==SQLITE_OK && wrflag ){
drh309169a2007-04-24 17:27:51 +00002020 if( pBt->readOnly ){
2021 rc = SQLITE_READONLY;
2022 }else{
2023 rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1);
2024 if( rc==SQLITE_OK ){
2025 rc = newDatabase(pBt);
2026 }
drhb8ef32c2005-03-14 02:01:49 +00002027 }
2028 }
2029
2030 if( rc==SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00002031 if( wrflag ) pBt->inStmt = 0;
2032 }else{
2033 unlockBtreeIfUnused(pBt);
2034 }
danielk1977aef0bf62005-12-30 16:28:01 +00002035 }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
danielk19771ceedd32008-11-19 10:22:33 +00002036 btreeInvokeBusyHandler(pBt) );
danielk1977aef0bf62005-12-30 16:28:01 +00002037
2038 if( rc==SQLITE_OK ){
2039 if( p->inTrans==TRANS_NONE ){
2040 pBt->nTransaction++;
2041 }
2042 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
2043 if( p->inTrans>pBt->inTransaction ){
2044 pBt->inTransaction = p->inTrans;
2045 }
danielk1977641b0f42007-12-21 04:47:25 +00002046#ifndef SQLITE_OMIT_SHARED_CACHE
2047 if( wrflag>1 ){
2048 assert( !pBt->pExclusive );
2049 pBt->pExclusive = p;
2050 }
2051#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002052 }
2053
drhd677b3d2007-08-20 22:48:41 +00002054
2055trans_begun:
danielk1977aef0bf62005-12-30 16:28:01 +00002056 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002057 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00002058 return rc;
drha059ad02001-04-17 20:09:11 +00002059}
2060
danielk1977687566d2004-11-02 12:56:41 +00002061#ifndef SQLITE_OMIT_AUTOVACUUM
2062
2063/*
2064** Set the pointer-map entries for all children of page pPage. Also, if
2065** pPage contains cells that point to overflow pages, set the pointer
2066** map entries for the overflow pages as well.
2067*/
2068static int setChildPtrmaps(MemPage *pPage){
2069 int i; /* Counter variable */
2070 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00002071 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00002072 BtShared *pBt = pPage->pBt;
danielk1977687566d2004-11-02 12:56:41 +00002073 int isInitOrig = pPage->isInit;
2074 Pgno pgno = pPage->pgno;
2075
drh1fee73e2007-08-29 04:00:57 +00002076 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197771d5d2c2008-09-29 11:49:47 +00002077 rc = sqlite3BtreeInitPage(pPage);
danielk19772df71c72007-05-24 07:22:42 +00002078 if( rc!=SQLITE_OK ){
2079 goto set_child_ptrmaps_out;
2080 }
danielk1977687566d2004-11-02 12:56:41 +00002081 nCell = pPage->nCell;
2082
2083 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002084 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002085
danielk197726836652005-01-17 01:33:13 +00002086 rc = ptrmapPutOvflPtr(pPage, pCell);
2087 if( rc!=SQLITE_OK ){
2088 goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002089 }
danielk197726836652005-01-17 01:33:13 +00002090
danielk1977687566d2004-11-02 12:56:41 +00002091 if( !pPage->leaf ){
2092 Pgno childPgno = get4byte(pCell);
2093 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
danielk197700a696d2008-09-29 16:41:31 +00002094 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002095 }
2096 }
2097
2098 if( !pPage->leaf ){
2099 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
2100 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
2101 }
2102
2103set_child_ptrmaps_out:
2104 pPage->isInit = isInitOrig;
2105 return rc;
2106}
2107
2108/*
2109** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
2110** page, is a pointer to page iFrom. Modify this pointer so that it points to
2111** iTo. Parameter eType describes the type of pointer to be modified, as
2112** follows:
2113**
2114** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
2115** page of pPage.
2116**
2117** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
2118** page pointed to by one of the cells on pPage.
2119**
2120** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
2121** overflow page in the list.
2122*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00002123static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00002124 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00002125 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977687566d2004-11-02 12:56:41 +00002126 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00002127 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00002128 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00002129 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002130 }
danielk1977f78fc082004-11-02 14:40:32 +00002131 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00002132 }else{
2133 int isInitOrig = pPage->isInit;
2134 int i;
2135 int nCell;
2136
danielk197771d5d2c2008-09-29 11:49:47 +00002137 sqlite3BtreeInitPage(pPage);
danielk1977687566d2004-11-02 12:56:41 +00002138 nCell = pPage->nCell;
2139
danielk1977687566d2004-11-02 12:56:41 +00002140 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002141 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002142 if( eType==PTRMAP_OVERFLOW1 ){
2143 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00002144 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
danielk1977687566d2004-11-02 12:56:41 +00002145 if( info.iOverflow ){
2146 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
2147 put4byte(&pCell[info.iOverflow], iTo);
2148 break;
2149 }
2150 }
2151 }else{
2152 if( get4byte(pCell)==iFrom ){
2153 put4byte(pCell, iTo);
2154 break;
2155 }
2156 }
2157 }
2158
2159 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00002160 if( eType!=PTRMAP_BTREE ||
2161 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00002162 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002163 }
danielk1977687566d2004-11-02 12:56:41 +00002164 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
2165 }
2166
2167 pPage->isInit = isInitOrig;
2168 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002169 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002170}
2171
danielk1977003ba062004-11-04 02:57:33 +00002172
danielk19777701e812005-01-10 12:59:51 +00002173/*
2174** Move the open database page pDbPage to location iFreePage in the
2175** database. The pDbPage reference remains valid.
2176*/
danielk1977003ba062004-11-04 02:57:33 +00002177static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00002178 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00002179 MemPage *pDbPage, /* Open page to move */
2180 u8 eType, /* Pointer map 'type' entry for pDbPage */
2181 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
danielk19774c999992008-07-16 18:17:55 +00002182 Pgno iFreePage, /* The location to move pDbPage to */
2183 int isCommit
danielk1977003ba062004-11-04 02:57:33 +00002184){
2185 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
2186 Pgno iDbPage = pDbPage->pgno;
2187 Pager *pPager = pBt->pPager;
2188 int rc;
2189
danielk1977a0bf2652004-11-04 14:30:04 +00002190 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
2191 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00002192 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00002193 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00002194
drh85b623f2007-12-13 21:54:09 +00002195 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00002196 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
2197 iDbPage, iFreePage, iPtrPage, eType));
danielk19774c999992008-07-16 18:17:55 +00002198 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
danielk1977003ba062004-11-04 02:57:33 +00002199 if( rc!=SQLITE_OK ){
2200 return rc;
2201 }
2202 pDbPage->pgno = iFreePage;
2203
2204 /* If pDbPage was a btree-page, then it may have child pages and/or cells
2205 ** that point to overflow pages. The pointer map entries for all these
2206 ** pages need to be changed.
2207 **
2208 ** If pDbPage is an overflow page, then the first 4 bytes may store a
2209 ** pointer to a subsequent overflow page. If this is the case, then
2210 ** the pointer map needs to be updated for the subsequent overflow page.
2211 */
danielk1977a0bf2652004-11-04 14:30:04 +00002212 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00002213 rc = setChildPtrmaps(pDbPage);
2214 if( rc!=SQLITE_OK ){
2215 return rc;
2216 }
2217 }else{
2218 Pgno nextOvfl = get4byte(pDbPage->aData);
2219 if( nextOvfl!=0 ){
danielk1977003ba062004-11-04 02:57:33 +00002220 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
2221 if( rc!=SQLITE_OK ){
2222 return rc;
2223 }
2224 }
2225 }
2226
2227 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
2228 ** that it points at iFreePage. Also fix the pointer map entry for
2229 ** iPtrPage.
2230 */
danielk1977a0bf2652004-11-04 14:30:04 +00002231 if( eType!=PTRMAP_ROOTPAGE ){
drh16a9b832007-05-05 18:39:25 +00002232 rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00002233 if( rc!=SQLITE_OK ){
2234 return rc;
2235 }
danielk19773b8a05f2007-03-19 17:44:26 +00002236 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00002237 if( rc!=SQLITE_OK ){
2238 releasePage(pPtrPage);
2239 return rc;
2240 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002241 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00002242 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00002243 if( rc==SQLITE_OK ){
2244 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
2245 }
danielk1977003ba062004-11-04 02:57:33 +00002246 }
danielk1977003ba062004-11-04 02:57:33 +00002247 return rc;
2248}
2249
danielk1977dddbcdc2007-04-26 14:42:34 +00002250/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00002251static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00002252
2253/*
danielk1977dddbcdc2007-04-26 14:42:34 +00002254** Perform a single step of an incremental-vacuum. If successful,
2255** return SQLITE_OK. If there is no work to do (and therefore no
2256** point in calling this function again), return SQLITE_DONE.
2257**
2258** More specificly, this function attempts to re-organize the
2259** database so that the last page of the file currently in use
2260** is no longer in use.
2261**
2262** If the nFin parameter is non-zero, the implementation assumes
2263** that the caller will keep calling incrVacuumStep() until
2264** it returns SQLITE_DONE or an error, and that nFin is the
2265** number of pages the database file will contain after this
2266** process is complete.
2267*/
2268static int incrVacuumStep(BtShared *pBt, Pgno nFin){
2269 Pgno iLastPg; /* Last page in the database */
2270 Pgno nFreeList; /* Number of pages still on the free-list */
2271
drh1fee73e2007-08-29 04:00:57 +00002272 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977dddbcdc2007-04-26 14:42:34 +00002273 iLastPg = pBt->nTrunc;
2274 if( iLastPg==0 ){
danielk197789d40042008-11-17 14:20:56 +00002275 iLastPg = pagerPagecount(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00002276 }
2277
2278 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
2279 int rc;
2280 u8 eType;
2281 Pgno iPtrPage;
2282
2283 nFreeList = get4byte(&pBt->pPage1->aData[36]);
2284 if( nFreeList==0 || nFin==iLastPg ){
2285 return SQLITE_DONE;
2286 }
2287
2288 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
2289 if( rc!=SQLITE_OK ){
2290 return rc;
2291 }
2292 if( eType==PTRMAP_ROOTPAGE ){
2293 return SQLITE_CORRUPT_BKPT;
2294 }
2295
2296 if( eType==PTRMAP_FREEPAGE ){
2297 if( nFin==0 ){
2298 /* Remove the page from the files free-list. This is not required
danielk19774ef24492007-05-23 09:52:41 +00002299 ** if nFin is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00002300 ** truncated to zero after this function returns, so it doesn't
2301 ** matter if it still contains some garbage entries.
2302 */
2303 Pgno iFreePg;
2304 MemPage *pFreePg;
2305 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
2306 if( rc!=SQLITE_OK ){
2307 return rc;
2308 }
2309 assert( iFreePg==iLastPg );
2310 releasePage(pFreePg);
2311 }
2312 } else {
2313 Pgno iFreePg; /* Index of free page to move pLastPg to */
2314 MemPage *pLastPg;
2315
drh16a9b832007-05-05 18:39:25 +00002316 rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002317 if( rc!=SQLITE_OK ){
2318 return rc;
2319 }
2320
danielk1977b4626a32007-04-28 15:47:43 +00002321 /* If nFin is zero, this loop runs exactly once and page pLastPg
2322 ** is swapped with the first free page pulled off the free list.
2323 **
2324 ** On the other hand, if nFin is greater than zero, then keep
2325 ** looping until a free-page located within the first nFin pages
2326 ** of the file is found.
2327 */
danielk1977dddbcdc2007-04-26 14:42:34 +00002328 do {
2329 MemPage *pFreePg;
2330 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
2331 if( rc!=SQLITE_OK ){
2332 releasePage(pLastPg);
2333 return rc;
2334 }
2335 releasePage(pFreePg);
2336 }while( nFin!=0 && iFreePg>nFin );
2337 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00002338
2339 rc = sqlite3PagerWrite(pLastPg->pDbPage);
danielk1977662278e2007-11-05 15:30:12 +00002340 if( rc==SQLITE_OK ){
danielk19774c999992008-07-16 18:17:55 +00002341 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
danielk1977662278e2007-11-05 15:30:12 +00002342 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002343 releasePage(pLastPg);
2344 if( rc!=SQLITE_OK ){
2345 return rc;
danielk1977662278e2007-11-05 15:30:12 +00002346 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002347 }
2348 }
2349
2350 pBt->nTrunc = iLastPg - 1;
2351 while( pBt->nTrunc==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, pBt->nTrunc) ){
2352 pBt->nTrunc--;
2353 }
2354 return SQLITE_OK;
2355}
2356
2357/*
2358** A write-transaction must be opened before calling this function.
2359** It performs a single unit of work towards an incremental vacuum.
2360**
2361** If the incremental vacuum is finished after this function has run,
2362** SQLITE_DONE is returned. If it is not finished, but no error occured,
2363** SQLITE_OK is returned. Otherwise an SQLite error code.
2364*/
2365int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002366 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002367 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002368
2369 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002370 pBt->db = p->db;
danielk1977dddbcdc2007-04-26 14:42:34 +00002371 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
2372 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002373 rc = SQLITE_DONE;
2374 }else{
2375 invalidateAllOverflowCache(pBt);
2376 rc = incrVacuumStep(pBt, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002377 }
drhd677b3d2007-08-20 22:48:41 +00002378 sqlite3BtreeLeave(p);
2379 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002380}
2381
2382/*
danielk19773b8a05f2007-03-19 17:44:26 +00002383** This routine is called prior to sqlite3PagerCommit when a transaction
danielk1977687566d2004-11-02 12:56:41 +00002384** is commited for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00002385**
2386** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
2387** the database file should be truncated to during the commit process.
2388** i.e. the database has been reorganized so that only the first *pnTrunc
2389** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00002390*/
danielk197724168722007-04-02 05:07:47 +00002391static int autoVacuumCommit(BtShared *pBt, Pgno *pnTrunc){
danielk1977dddbcdc2007-04-26 14:42:34 +00002392 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002393 Pager *pPager = pBt->pPager;
drhf94a1732008-09-30 17:18:17 +00002394 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002395
drh1fee73e2007-08-29 04:00:57 +00002396 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00002397 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00002398 assert(pBt->autoVacuum);
2399 if( !pBt->incrVacuum ){
2400 Pgno nFin = 0;
danielk1977687566d2004-11-02 12:56:41 +00002401
danielk1977dddbcdc2007-04-26 14:42:34 +00002402 if( pBt->nTrunc==0 ){
2403 Pgno nFree;
2404 Pgno nPtrmap;
2405 const int pgsz = pBt->pageSize;
danielk197789d40042008-11-17 14:20:56 +00002406 Pgno nOrig = pagerPagecount(pBt);
danielk1977e5321f02007-04-27 07:05:44 +00002407
2408 if( PTRMAP_ISPAGE(pBt, nOrig) ){
2409 return SQLITE_CORRUPT_BKPT;
2410 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002411 if( nOrig==PENDING_BYTE_PAGE(pBt) ){
2412 nOrig--;
danielk1977687566d2004-11-02 12:56:41 +00002413 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002414 nFree = get4byte(&pBt->pPage1->aData[36]);
2415 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
2416 nFin = nOrig - nFree - nPtrmap;
2417 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
2418 nFin--;
danielk1977ac11ee62005-01-15 12:45:51 +00002419 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002420 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
2421 nFin--;
2422 }
2423 }
danielk1977687566d2004-11-02 12:56:41 +00002424
danielk1977dddbcdc2007-04-26 14:42:34 +00002425 while( rc==SQLITE_OK ){
2426 rc = incrVacuumStep(pBt, nFin);
2427 }
2428 if( rc==SQLITE_DONE ){
2429 assert(nFin==0 || pBt->nTrunc==0 || nFin<=pBt->nTrunc);
2430 rc = SQLITE_OK;
danielk19770ba32df2008-05-07 07:13:16 +00002431 if( pBt->nTrunc && nFin ){
drh67f80b62007-07-23 19:26:17 +00002432 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
danielk1977dddbcdc2007-04-26 14:42:34 +00002433 put4byte(&pBt->pPage1->aData[32], 0);
2434 put4byte(&pBt->pPage1->aData[36], 0);
2435 pBt->nTrunc = nFin;
2436 }
2437 }
2438 if( rc!=SQLITE_OK ){
2439 sqlite3PagerRollback(pPager);
2440 }
danielk1977687566d2004-11-02 12:56:41 +00002441 }
2442
danielk1977dddbcdc2007-04-26 14:42:34 +00002443 if( rc==SQLITE_OK ){
2444 *pnTrunc = pBt->nTrunc;
2445 pBt->nTrunc = 0;
2446 }
danielk19773b8a05f2007-03-19 17:44:26 +00002447 assert( nRef==sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002448 return rc;
2449}
danielk1977dddbcdc2007-04-26 14:42:34 +00002450
shane831c3292008-11-10 17:14:58 +00002451#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
danielk1977687566d2004-11-02 12:56:41 +00002452
2453/*
drh80e35f42007-03-30 14:06:34 +00002454** This routine does the first phase of a two-phase commit. This routine
2455** causes a rollback journal to be created (if it does not already exist)
2456** and populated with enough information so that if a power loss occurs
2457** the database can be restored to its original state by playing back
2458** the journal. Then the contents of the journal are flushed out to
2459** the disk. After the journal is safely on oxide, the changes to the
2460** database are written into the database file and flushed to oxide.
2461** At the end of this call, the rollback journal still exists on the
2462** disk and we are still holding all locks, so the transaction has not
2463** committed. See sqlite3BtreeCommit() for the second phase of the
2464** commit process.
2465**
2466** This call is a no-op if no write-transaction is currently active on pBt.
2467**
2468** Otherwise, sync the database file for the btree pBt. zMaster points to
2469** the name of a master journal file that should be written into the
2470** individual journal file, or is NULL, indicating no master journal file
2471** (single database transaction).
2472**
2473** When this is called, the master journal should already have been
2474** created, populated with this journal pointer and synced to disk.
2475**
2476** Once this is routine has returned, the only thing required to commit
2477** the write-transaction for this database file is to delete the journal.
2478*/
2479int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
2480 int rc = SQLITE_OK;
2481 if( p->inTrans==TRANS_WRITE ){
2482 BtShared *pBt = p->pBt;
2483 Pgno nTrunc = 0;
drhd677b3d2007-08-20 22:48:41 +00002484 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002485 pBt->db = p->db;
drh80e35f42007-03-30 14:06:34 +00002486#ifndef SQLITE_OMIT_AUTOVACUUM
2487 if( pBt->autoVacuum ){
2488 rc = autoVacuumCommit(pBt, &nTrunc);
2489 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002490 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002491 return rc;
2492 }
2493 }
2494#endif
danielk1977f653d782008-03-20 11:04:21 +00002495 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, nTrunc, 0);
drhd677b3d2007-08-20 22:48:41 +00002496 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002497 }
2498 return rc;
2499}
2500
2501/*
drh2aa679f2001-06-25 02:11:07 +00002502** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00002503**
drh6e345992007-03-30 11:12:08 +00002504** This routine implements the second phase of a 2-phase commit. The
2505** sqlite3BtreeSync() routine does the first phase and should be invoked
2506** prior to calling this routine. The sqlite3BtreeSync() routine did
2507** all the work of writing information out to disk and flushing the
2508** contents so that they are written onto the disk platter. All this
2509** routine has to do is delete or truncate the rollback journal
2510** (which causes the transaction to commit) and drop locks.
2511**
drh5e00f6c2001-09-13 13:46:56 +00002512** This will release the write lock on the database file. If there
2513** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002514*/
drh80e35f42007-03-30 14:06:34 +00002515int sqlite3BtreeCommitPhaseTwo(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002516 BtShared *pBt = p->pBt;
2517
drhd677b3d2007-08-20 22:48:41 +00002518 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002519 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00002520 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002521
2522 /* If the handle has a write-transaction open, commit the shared-btrees
2523 ** transaction and set the shared state to TRANS_READ.
2524 */
2525 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00002526 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002527 assert( pBt->inTransaction==TRANS_WRITE );
2528 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00002529 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
danielk19777f7bc662006-01-23 13:47:47 +00002530 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002531 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002532 return rc;
2533 }
danielk1977aef0bf62005-12-30 16:28:01 +00002534 pBt->inTransaction = TRANS_READ;
2535 pBt->inStmt = 0;
danielk1977ee5741e2004-05-31 10:01:34 +00002536 }
danielk19777f7bc662006-01-23 13:47:47 +00002537 unlockAllTables(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002538
2539 /* If the handle has any kind of transaction open, decrement the transaction
2540 ** count of the shared btree. If the transaction count reaches 0, set
2541 ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
2542 ** will unlock the pager.
2543 */
2544 if( p->inTrans!=TRANS_NONE ){
2545 pBt->nTransaction--;
2546 if( 0==pBt->nTransaction ){
2547 pBt->inTransaction = TRANS_NONE;
2548 }
2549 }
2550
2551 /* Set the handles current transaction state to TRANS_NONE and unlock
2552 ** the pager if this call closed the only read or write transaction.
2553 */
2554 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00002555 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002556
2557 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002558 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002559 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002560}
2561
drh80e35f42007-03-30 14:06:34 +00002562/*
2563** Do both phases of a commit.
2564*/
2565int sqlite3BtreeCommit(Btree *p){
2566 int rc;
drhd677b3d2007-08-20 22:48:41 +00002567 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00002568 rc = sqlite3BtreeCommitPhaseOne(p, 0);
2569 if( rc==SQLITE_OK ){
2570 rc = sqlite3BtreeCommitPhaseTwo(p);
2571 }
drhd677b3d2007-08-20 22:48:41 +00002572 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002573 return rc;
2574}
2575
danielk1977fbcd5852004-06-15 02:44:18 +00002576#ifndef NDEBUG
2577/*
2578** Return the number of write-cursors open on this handle. This is for use
2579** in assert() expressions, so it is only compiled if NDEBUG is not
2580** defined.
drhfb982642007-08-30 01:19:59 +00002581**
2582** For the purposes of this routine, a write-cursor is any cursor that
2583** is capable of writing to the databse. That means the cursor was
2584** originally opened for writing and the cursor has not be disabled
2585** by having its state changed to CURSOR_FAULT.
danielk1977fbcd5852004-06-15 02:44:18 +00002586*/
danielk1977aef0bf62005-12-30 16:28:01 +00002587static int countWriteCursors(BtShared *pBt){
danielk1977fbcd5852004-06-15 02:44:18 +00002588 BtCursor *pCur;
2589 int r = 0;
2590 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drhfb982642007-08-30 01:19:59 +00002591 if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
danielk1977fbcd5852004-06-15 02:44:18 +00002592 }
2593 return r;
2594}
2595#endif
2596
drhc39e0002004-05-07 23:50:57 +00002597/*
drhfb982642007-08-30 01:19:59 +00002598** This routine sets the state to CURSOR_FAULT and the error
2599** code to errCode for every cursor on BtShared that pBtree
2600** references.
2601**
2602** Every cursor is tripped, including cursors that belong
2603** to other database connections that happen to be sharing
2604** the cache with pBtree.
2605**
2606** This routine gets called when a rollback occurs.
2607** All cursors using the same cache must be tripped
2608** to prevent them from trying to use the btree after
2609** the rollback. The rollback may have deleted tables
2610** or moved root pages, so it is not sufficient to
2611** save the state of the cursor. The cursor must be
2612** invalidated.
2613*/
2614void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
2615 BtCursor *p;
2616 sqlite3BtreeEnter(pBtree);
2617 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
danielk1977bc2ca9e2008-11-13 14:28:28 +00002618 int i;
danielk1977be51a652008-10-08 17:58:48 +00002619 sqlite3BtreeClearCursor(p);
drhfb982642007-08-30 01:19:59 +00002620 p->eState = CURSOR_FAULT;
2621 p->skip = errCode;
danielk1977bc2ca9e2008-11-13 14:28:28 +00002622 for(i=0; i<=p->iPage; i++){
2623 releasePage(p->apPage[i]);
2624 p->apPage[i] = 0;
2625 }
drhfb982642007-08-30 01:19:59 +00002626 }
2627 sqlite3BtreeLeave(pBtree);
2628}
2629
2630/*
drhecdc7532001-09-23 02:35:53 +00002631** Rollback the transaction in progress. All cursors will be
2632** invalided by this operation. Any attempt to use a cursor
2633** that was open at the beginning of this operation will result
2634** in an error.
drh5e00f6c2001-09-13 13:46:56 +00002635**
2636** This will release the write lock on the database file. If there
2637** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002638*/
danielk1977aef0bf62005-12-30 16:28:01 +00002639int sqlite3BtreeRollback(Btree *p){
danielk19778d34dfd2006-01-24 16:37:57 +00002640 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002641 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00002642 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00002643
drhd677b3d2007-08-20 22:48:41 +00002644 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002645 pBt->db = p->db;
danielk19772b8c13e2006-01-24 14:21:24 +00002646 rc = saveAllCursors(pBt, 0, 0);
danielk19778d34dfd2006-01-24 16:37:57 +00002647#ifndef SQLITE_OMIT_SHARED_CACHE
danielk19772b8c13e2006-01-24 14:21:24 +00002648 if( rc!=SQLITE_OK ){
danielk19778d34dfd2006-01-24 16:37:57 +00002649 /* This is a horrible situation. An IO or malloc() error occured whilst
2650 ** trying to save cursor positions. If this is an automatic rollback (as
2651 ** the result of a constraint, malloc() failure or IO error) then
2652 ** the cache may be internally inconsistent (not contain valid trees) so
2653 ** we cannot simply return the error to the caller. Instead, abort
2654 ** all queries that may be using any of the cursors that failed to save.
2655 */
drhfb982642007-08-30 01:19:59 +00002656 sqlite3BtreeTripAllCursors(p, rc);
danielk19772b8c13e2006-01-24 14:21:24 +00002657 }
danielk19778d34dfd2006-01-24 16:37:57 +00002658#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002659 btreeIntegrity(p);
2660 unlockAllTables(p);
2661
2662 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00002663 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00002664
danielk1977dddbcdc2007-04-26 14:42:34 +00002665#ifndef SQLITE_OMIT_AUTOVACUUM
2666 pBt->nTrunc = 0;
2667#endif
2668
danielk19778d34dfd2006-01-24 16:37:57 +00002669 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00002670 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00002671 if( rc2!=SQLITE_OK ){
2672 rc = rc2;
2673 }
2674
drh24cd67e2004-05-10 16:18:47 +00002675 /* The rollback may have destroyed the pPage1->aData value. So
drh16a9b832007-05-05 18:39:25 +00002676 ** call sqlite3BtreeGetPage() on page 1 again to make
2677 ** sure pPage1->aData is set correctly. */
2678 if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh24cd67e2004-05-10 16:18:47 +00002679 releasePage(pPage1);
2680 }
danielk1977fbcd5852004-06-15 02:44:18 +00002681 assert( countWriteCursors(pBt)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002682 pBt->inTransaction = TRANS_READ;
drh24cd67e2004-05-10 16:18:47 +00002683 }
danielk1977aef0bf62005-12-30 16:28:01 +00002684
2685 if( p->inTrans!=TRANS_NONE ){
2686 assert( pBt->nTransaction>0 );
2687 pBt->nTransaction--;
2688 if( 0==pBt->nTransaction ){
2689 pBt->inTransaction = TRANS_NONE;
2690 }
2691 }
2692
2693 p->inTrans = TRANS_NONE;
danielk1977ee5741e2004-05-31 10:01:34 +00002694 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00002695 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002696
2697 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002698 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00002699 return rc;
2700}
2701
2702/*
drhab01f612004-05-22 02:55:23 +00002703** Start a statement subtransaction. The subtransaction can
2704** can be rolled back independently of the main transaction.
2705** You must start a transaction before starting a subtransaction.
2706** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00002707** commits or rolls back.
2708**
drhab01f612004-05-22 02:55:23 +00002709** Only one subtransaction may be active at a time. It is an error to try
2710** to start a new subtransaction if another subtransaction is already active.
2711**
2712** Statement subtransactions are used around individual SQL statements
2713** that are contained within a BEGIN...COMMIT block. If a constraint
2714** error occurs within the statement, the effect of that one statement
2715** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00002716*/
danielk1977aef0bf62005-12-30 16:28:01 +00002717int sqlite3BtreeBeginStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002718 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002719 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002720 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002721 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00002722 if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
drhd677b3d2007-08-20 22:48:41 +00002723 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
2724 }else{
2725 assert( pBt->inTransaction==TRANS_WRITE );
2726 rc = pBt->readOnly ? SQLITE_OK : sqlite3PagerStmtBegin(pBt->pPager);
2727 pBt->inStmt = 1;
drh0d65dc02002-02-03 00:56:09 +00002728 }
drhd677b3d2007-08-20 22:48:41 +00002729 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002730 return rc;
2731}
2732
2733
2734/*
drhab01f612004-05-22 02:55:23 +00002735** Commit the statment subtransaction currently in progress. If no
2736** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00002737*/
danielk1977aef0bf62005-12-30 16:28:01 +00002738int sqlite3BtreeCommitStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002739 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002740 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002741 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002742 pBt->db = p->db;
drh3aac2dd2004-04-26 14:10:20 +00002743 if( pBt->inStmt && !pBt->readOnly ){
danielk19773b8a05f2007-03-19 17:44:26 +00002744 rc = sqlite3PagerStmtCommit(pBt->pPager);
drh663fc632002-02-02 18:49:19 +00002745 }else{
2746 rc = SQLITE_OK;
2747 }
drh3aac2dd2004-04-26 14:10:20 +00002748 pBt->inStmt = 0;
drhd677b3d2007-08-20 22:48:41 +00002749 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002750 return rc;
2751}
2752
2753/*
drhab01f612004-05-22 02:55:23 +00002754** Rollback the active statement subtransaction. If no subtransaction
2755** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00002756**
drhab01f612004-05-22 02:55:23 +00002757** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00002758** to use a cursor that was open at the beginning of this operation
2759** will result in an error.
2760*/
danielk1977aef0bf62005-12-30 16:28:01 +00002761int sqlite3BtreeRollbackStmt(Btree *p){
danielk197797a227c2006-01-20 16:32:04 +00002762 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002763 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002764 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002765 pBt->db = p->db;
danielk197797a227c2006-01-20 16:32:04 +00002766 if( pBt->inStmt && !pBt->readOnly ){
danielk19773b8a05f2007-03-19 17:44:26 +00002767 rc = sqlite3PagerStmtRollback(pBt->pPager);
danielk197797a227c2006-01-20 16:32:04 +00002768 pBt->inStmt = 0;
2769 }
drhd677b3d2007-08-20 22:48:41 +00002770 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002771 return rc;
2772}
2773
2774/*
drh8b2f49b2001-06-08 00:21:52 +00002775** Create a new cursor for the BTree whose root is on the page
2776** iTable. The act of acquiring a cursor gets a read lock on
2777** the database file.
drh1bee3d72001-10-15 00:44:35 +00002778**
2779** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00002780** If wrFlag==1, then the cursor can be used for reading or for
2781** writing if other conditions for writing are also met. These
2782** are the conditions that must be met in order for writing to
2783** be allowed:
drh6446c4d2001-12-15 14:22:18 +00002784**
drhf74b8d92002-09-01 23:20:45 +00002785** 1: The cursor must have been opened with wrFlag==1
2786**
drhfe5d71d2007-03-19 11:54:10 +00002787** 2: Other database connections that share the same pager cache
2788** but which are not in the READ_UNCOMMITTED state may not have
2789** cursors open with wrFlag==0 on the same table. Otherwise
2790** the changes made by this write cursor would be visible to
2791** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00002792**
2793** 3: The database must be writable (not on read-only media)
2794**
2795** 4: There must be an active transaction.
2796**
drh6446c4d2001-12-15 14:22:18 +00002797** No checking is done to make sure that page iTable really is the
2798** root page of a b-tree. If it is not, then the cursor acquired
2799** will not work correctly.
danielk197771d5d2c2008-09-29 11:49:47 +00002800**
2801** It is assumed that the sqlite3BtreeCursorSize() bytes of memory
2802** pointed to by pCur have been zeroed by the caller.
drha059ad02001-04-17 20:09:11 +00002803*/
drhd677b3d2007-08-20 22:48:41 +00002804static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00002805 Btree *p, /* The btree */
2806 int iTable, /* Root page of table to open */
2807 int wrFlag, /* 1 to write. 0 read-only */
2808 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
2809 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00002810){
drha059ad02001-04-17 20:09:11 +00002811 int rc;
danielk197789d40042008-11-17 14:20:56 +00002812 Pgno nPage;
danielk1977aef0bf62005-12-30 16:28:01 +00002813 BtShared *pBt = p->pBt;
drhecdc7532001-09-23 02:35:53 +00002814
drh1fee73e2007-08-29 04:00:57 +00002815 assert( sqlite3BtreeHoldsMutex(p) );
drh8dcd7ca2004-08-08 19:43:29 +00002816 if( wrFlag ){
drh8dcd7ca2004-08-08 19:43:29 +00002817 if( pBt->readOnly ){
2818 return SQLITE_READONLY;
2819 }
danielk19773588ceb2008-06-10 17:30:26 +00002820 if( checkReadLocks(p, iTable, 0, 0) ){
drh8dcd7ca2004-08-08 19:43:29 +00002821 return SQLITE_LOCKED;
2822 }
drha0c9a112004-03-10 13:42:37 +00002823 }
danielk1977aef0bf62005-12-30 16:28:01 +00002824
drh4b70f112004-05-02 21:12:19 +00002825 if( pBt->pPage1==0 ){
danielk1977aef0bf62005-12-30 16:28:01 +00002826 rc = lockBtreeWithRetry(p);
drha059ad02001-04-17 20:09:11 +00002827 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00002828 return rc;
2829 }
drh1831f182007-04-24 17:35:59 +00002830 if( pBt->readOnly && wrFlag ){
2831 return SQLITE_READONLY;
2832 }
drha059ad02001-04-17 20:09:11 +00002833 }
drh8b2f49b2001-06-08 00:21:52 +00002834 pCur->pgnoRoot = (Pgno)iTable;
danielk197789d40042008-11-17 14:20:56 +00002835 rc = sqlite3PagerPagecount(pBt->pPager, (int *)&nPage);
2836 if( rc!=SQLITE_OK ){
2837 return rc;
2838 }
2839 if( iTable==1 && nPage==0 ){
drh24cd67e2004-05-10 16:18:47 +00002840 rc = SQLITE_EMPTY;
2841 goto create_cursor_exception;
2842 }
danielk197771d5d2c2008-09-29 11:49:47 +00002843 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
drhbd03cae2001-06-02 02:40:57 +00002844 if( rc!=SQLITE_OK ){
2845 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00002846 }
danielk1977aef0bf62005-12-30 16:28:01 +00002847
danielk1977aef0bf62005-12-30 16:28:01 +00002848 /* Now that no other errors can occur, finish filling in the BtCursor
2849 ** variables, link the cursor into the BtShared list and set *ppCur (the
2850 ** output argument to this function).
2851 */
drh1e968a02008-03-25 00:22:21 +00002852 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00002853 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00002854 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +00002855 pCur->wrFlag = wrFlag;
drha059ad02001-04-17 20:09:11 +00002856 pCur->pNext = pBt->pCursor;
2857 if( pCur->pNext ){
2858 pCur->pNext->pPrev = pCur;
2859 }
2860 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00002861 pCur->eState = CURSOR_INVALID;
drhbd03cae2001-06-02 02:40:57 +00002862
danielk1977aef0bf62005-12-30 16:28:01 +00002863 return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00002864
drhbd03cae2001-06-02 02:40:57 +00002865create_cursor_exception:
danielk197771d5d2c2008-09-29 11:49:47 +00002866 releasePage(pCur->apPage[0]);
drh5e00f6c2001-09-13 13:46:56 +00002867 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00002868 return rc;
drha059ad02001-04-17 20:09:11 +00002869}
drhd677b3d2007-08-20 22:48:41 +00002870int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00002871 Btree *p, /* The btree */
2872 int iTable, /* Root page of table to open */
2873 int wrFlag, /* 1 to write. 0 read-only */
2874 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
2875 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00002876){
2877 int rc;
2878 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002879 p->pBt->db = p->db;
danielk1977cd3e8f72008-03-25 09:47:35 +00002880 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
drhd677b3d2007-08-20 22:48:41 +00002881 sqlite3BtreeLeave(p);
2882 return rc;
2883}
danielk1977cd3e8f72008-03-25 09:47:35 +00002884int sqlite3BtreeCursorSize(){
2885 return sizeof(BtCursor);
2886}
2887
drhd677b3d2007-08-20 22:48:41 +00002888
drha059ad02001-04-17 20:09:11 +00002889
2890/*
drh5e00f6c2001-09-13 13:46:56 +00002891** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00002892** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00002893*/
drh3aac2dd2004-04-26 14:10:20 +00002894int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00002895 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00002896 if( pBtree ){
danielk197771d5d2c2008-09-29 11:49:47 +00002897 int i;
danielk1977cd3e8f72008-03-25 09:47:35 +00002898 BtShared *pBt = pCur->pBt;
2899 sqlite3BtreeEnter(pBtree);
2900 pBt->db = pBtree->db;
danielk1977be51a652008-10-08 17:58:48 +00002901 sqlite3BtreeClearCursor(pCur);
danielk1977cd3e8f72008-03-25 09:47:35 +00002902 if( pCur->pPrev ){
2903 pCur->pPrev->pNext = pCur->pNext;
2904 }else{
2905 pBt->pCursor = pCur->pNext;
2906 }
2907 if( pCur->pNext ){
2908 pCur->pNext->pPrev = pCur->pPrev;
2909 }
danielk197771d5d2c2008-09-29 11:49:47 +00002910 for(i=0; i<=pCur->iPage; i++){
2911 releasePage(pCur->apPage[i]);
2912 }
danielk1977cd3e8f72008-03-25 09:47:35 +00002913 unlockBtreeIfUnused(pBt);
2914 invalidateOverflowCache(pCur);
2915 /* sqlite3_free(pCur); */
2916 sqlite3BtreeLeave(pBtree);
drha059ad02001-04-17 20:09:11 +00002917 }
drh8c42ca92001-06-22 19:15:00 +00002918 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002919}
2920
drh7e3b0a02001-04-28 16:52:40 +00002921/*
drh5e2f8b92001-05-28 00:41:15 +00002922** Make a temporary cursor by filling in the fields of pTempCur.
2923** The temporary cursor is not on the cursor list for the Btree.
2924*/
drh16a9b832007-05-05 18:39:25 +00002925void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
danielk197771d5d2c2008-09-29 11:49:47 +00002926 int i;
drh1fee73e2007-08-29 04:00:57 +00002927 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00002928 memcpy(pTempCur, pCur, sizeof(BtCursor));
drh5e2f8b92001-05-28 00:41:15 +00002929 pTempCur->pNext = 0;
2930 pTempCur->pPrev = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00002931 for(i=0; i<=pTempCur->iPage; i++){
2932 sqlite3PagerRef(pTempCur->apPage[i]->pDbPage);
drhecdc7532001-09-23 02:35:53 +00002933 }
danielk197736e20932008-11-26 07:40:30 +00002934 assert( pTempCur->pKey==0 );
drh5e2f8b92001-05-28 00:41:15 +00002935}
2936
2937/*
drhbd03cae2001-06-02 02:40:57 +00002938** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00002939** function above.
2940*/
drh16a9b832007-05-05 18:39:25 +00002941void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
danielk197771d5d2c2008-09-29 11:49:47 +00002942 int i;
drh1fee73e2007-08-29 04:00:57 +00002943 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00002944 for(i=0; i<=pCur->iPage; i++){
2945 sqlite3PagerUnref(pCur->apPage[i]->pDbPage);
drhecdc7532001-09-23 02:35:53 +00002946 }
danielk197736e20932008-11-26 07:40:30 +00002947 sqlite3_free(pCur->pKey);
drh5e2f8b92001-05-28 00:41:15 +00002948}
2949
2950/*
drh86057612007-06-26 01:04:48 +00002951** Make sure the BtCursor* given in the argument has a valid
2952** BtCursor.info structure. If it is not already valid, call
danielk19771cc5ed82007-05-16 17:28:43 +00002953** sqlite3BtreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00002954**
2955** BtCursor.info is a cache of the information in the current cell.
drh16a9b832007-05-05 18:39:25 +00002956** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
drh86057612007-06-26 01:04:48 +00002957**
2958** 2007-06-25: There is a bug in some versions of MSVC that cause the
2959** compiler to crash when getCellInfo() is implemented as a macro.
2960** But there is a measureable speed advantage to using the macro on gcc
2961** (when less compiler optimizations like -Os or -O0 are used and the
2962** compiler is not doing agressive inlining.) So we use a real function
2963** for MSVC and a macro for everything else. Ticket #2457.
drh9188b382004-05-14 21:12:22 +00002964*/
drh9188b382004-05-14 21:12:22 +00002965#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00002966 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00002967 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00002968 int iPage = pCur->iPage;
drh51c6d962004-06-06 00:42:25 +00002969 memset(&info, 0, sizeof(info));
danielk197771d5d2c2008-09-29 11:49:47 +00002970 sqlite3BtreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
drh9188b382004-05-14 21:12:22 +00002971 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00002972 }
danielk19771cc5ed82007-05-16 17:28:43 +00002973#else
2974 #define assertCellInfo(x)
2975#endif
drh86057612007-06-26 01:04:48 +00002976#ifdef _MSC_VER
2977 /* Use a real function in MSVC to work around bugs in that compiler. */
2978 static void getCellInfo(BtCursor *pCur){
2979 if( pCur->info.nSize==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00002980 int iPage = pCur->iPage;
2981 sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
drha2c20e42008-03-29 16:01:04 +00002982 pCur->validNKey = 1;
drh86057612007-06-26 01:04:48 +00002983 }else{
2984 assertCellInfo(pCur);
2985 }
2986 }
2987#else /* if not _MSC_VER */
2988 /* Use a macro in all other compilers so that the function is inlined */
danielk197771d5d2c2008-09-29 11:49:47 +00002989#define getCellInfo(pCur) \
2990 if( pCur->info.nSize==0 ){ \
2991 int iPage = pCur->iPage; \
2992 sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
2993 pCur->validNKey = 1; \
2994 }else{ \
2995 assertCellInfo(pCur); \
drh86057612007-06-26 01:04:48 +00002996 }
2997#endif /* _MSC_VER */
drh9188b382004-05-14 21:12:22 +00002998
2999/*
drh3aac2dd2004-04-26 14:10:20 +00003000** Set *pSize to the size of the buffer needed to hold the value of
3001** the key for the current entry. If the cursor is not pointing
3002** to a valid entry, *pSize is set to 0.
3003**
drh4b70f112004-05-02 21:12:19 +00003004** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00003005** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00003006*/
drh4a1c3802004-05-12 15:15:47 +00003007int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drhd677b3d2007-08-20 22:48:41 +00003008 int rc;
3009
drh1fee73e2007-08-29 04:00:57 +00003010 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003011 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003012 if( rc==SQLITE_OK ){
3013 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3014 if( pCur->eState==CURSOR_INVALID ){
3015 *pSize = 0;
3016 }else{
drh86057612007-06-26 01:04:48 +00003017 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00003018 *pSize = pCur->info.nKey;
3019 }
drh72f82862001-05-24 21:06:34 +00003020 }
danielk1977da184232006-01-05 11:34:32 +00003021 return rc;
drha059ad02001-04-17 20:09:11 +00003022}
drh2af926b2001-05-15 00:39:25 +00003023
drh72f82862001-05-24 21:06:34 +00003024/*
drh0e1c19e2004-05-11 00:58:56 +00003025** Set *pSize to the number of bytes of data in the entry the
3026** cursor currently points to. Always return SQLITE_OK.
3027** Failure is not possible. If the cursor is not currently
3028** pointing to an entry (which can happen, for example, if
3029** the database is empty) then *pSize is set to 0.
3030*/
3031int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drhd677b3d2007-08-20 22:48:41 +00003032 int rc;
3033
drh1fee73e2007-08-29 04:00:57 +00003034 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003035 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003036 if( rc==SQLITE_OK ){
3037 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3038 if( pCur->eState==CURSOR_INVALID ){
3039 /* Not pointing at a valid entry - set *pSize to 0. */
3040 *pSize = 0;
3041 }else{
drh86057612007-06-26 01:04:48 +00003042 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00003043 *pSize = pCur->info.nData;
3044 }
drh0e1c19e2004-05-11 00:58:56 +00003045 }
danielk1977da184232006-01-05 11:34:32 +00003046 return rc;
drh0e1c19e2004-05-11 00:58:56 +00003047}
3048
3049/*
danielk1977d04417962007-05-02 13:16:30 +00003050** Given the page number of an overflow page in the database (parameter
3051** ovfl), this function finds the page number of the next page in the
3052** linked list of overflow pages. If possible, it uses the auto-vacuum
3053** pointer-map data instead of reading the content of page ovfl to do so.
3054**
3055** If an error occurs an SQLite error code is returned. Otherwise:
3056**
3057** Unless pPgnoNext is NULL, the page number of the next overflow
3058** page in the linked list is written to *pPgnoNext. If page ovfl
drh85b623f2007-12-13 21:54:09 +00003059** is the last page in its linked list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003060**
3061** If ppPage is not NULL, *ppPage is set to the MemPage* handle
3062** for page ovfl. The underlying pager page may have been requested
3063** with the noContent flag set, so the page data accessable via
3064** this handle may not be trusted.
3065*/
3066static int getOverflowPage(
3067 BtShared *pBt,
3068 Pgno ovfl, /* Overflow page */
3069 MemPage **ppPage, /* OUT: MemPage handle */
3070 Pgno *pPgnoNext /* OUT: Next overflow page number */
3071){
3072 Pgno next = 0;
3073 int rc;
3074
drh1fee73e2007-08-29 04:00:57 +00003075 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977d04417962007-05-02 13:16:30 +00003076 /* One of these must not be NULL. Otherwise, why call this function? */
3077 assert(ppPage || pPgnoNext);
3078
3079 /* If pPgnoNext is NULL, then this function is being called to obtain
3080 ** a MemPage* reference only. No page-data is required in this case.
3081 */
3082 if( !pPgnoNext ){
drh16a9b832007-05-05 18:39:25 +00003083 return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1);
danielk1977d04417962007-05-02 13:16:30 +00003084 }
3085
3086#ifndef SQLITE_OMIT_AUTOVACUUM
3087 /* Try to find the next page in the overflow list using the
3088 ** autovacuum pointer-map pages. Guess that the next page in
3089 ** the overflow list is page number (ovfl+1). If that guess turns
3090 ** out to be wrong, fall back to loading the data of page
3091 ** number ovfl to determine the next page number.
3092 */
3093 if( pBt->autoVacuum ){
3094 Pgno pgno;
3095 Pgno iGuess = ovfl+1;
3096 u8 eType;
3097
3098 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
3099 iGuess++;
3100 }
3101
danielk197789d40042008-11-17 14:20:56 +00003102 if( iGuess<=pagerPagecount(pBt) ){
danielk1977d04417962007-05-02 13:16:30 +00003103 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
3104 if( rc!=SQLITE_OK ){
3105 return rc;
3106 }
3107 if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
3108 next = iGuess;
3109 }
3110 }
3111 }
3112#endif
3113
3114 if( next==0 || ppPage ){
3115 MemPage *pPage = 0;
3116
drh16a9b832007-05-05 18:39:25 +00003117 rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0);
danielk1977d04417962007-05-02 13:16:30 +00003118 assert(rc==SQLITE_OK || pPage==0);
3119 if( next==0 && rc==SQLITE_OK ){
3120 next = get4byte(pPage->aData);
3121 }
3122
3123 if( ppPage ){
3124 *ppPage = pPage;
3125 }else{
3126 releasePage(pPage);
3127 }
3128 }
3129 *pPgnoNext = next;
3130
3131 return rc;
3132}
3133
danielk1977da107192007-05-04 08:32:13 +00003134/*
3135** Copy data from a buffer to a page, or from a page to a buffer.
3136**
3137** pPayload is a pointer to data stored on database page pDbPage.
3138** If argument eOp is false, then nByte bytes of data are copied
3139** from pPayload to the buffer pointed at by pBuf. If eOp is true,
3140** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
3141** of data are copied from the buffer pBuf to pPayload.
3142**
3143** SQLITE_OK is returned on success, otherwise an error code.
3144*/
3145static int copyPayload(
3146 void *pPayload, /* Pointer to page data */
3147 void *pBuf, /* Pointer to buffer */
3148 int nByte, /* Number of bytes to copy */
3149 int eOp, /* 0 -> copy from page, 1 -> copy to page */
3150 DbPage *pDbPage /* Page containing pPayload */
3151){
3152 if( eOp ){
3153 /* Copy data from buffer to page (a write operation) */
3154 int rc = sqlite3PagerWrite(pDbPage);
3155 if( rc!=SQLITE_OK ){
3156 return rc;
3157 }
3158 memcpy(pPayload, pBuf, nByte);
3159 }else{
3160 /* Copy data from page to buffer (a read operation) */
3161 memcpy(pBuf, pPayload, nByte);
3162 }
3163 return SQLITE_OK;
3164}
danielk1977d04417962007-05-02 13:16:30 +00003165
3166/*
danielk19779f8d6402007-05-02 17:48:45 +00003167** This function is used to read or overwrite payload information
3168** for the entry that the pCur cursor is pointing to. If the eOp
3169** parameter is 0, this is a read operation (data copied into
3170** buffer pBuf). If it is non-zero, a write (data copied from
3171** buffer pBuf).
3172**
3173** A total of "amt" bytes are read or written beginning at "offset".
3174** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00003175**
3176** This routine does not make a distinction between key and data.
danielk19779f8d6402007-05-02 17:48:45 +00003177** It just reads or writes bytes from the payload area. Data might
3178** appear on the main page or be scattered out on multiple overflow
3179** pages.
danielk1977da107192007-05-04 08:32:13 +00003180**
danielk1977dcbb5d32007-05-04 18:36:44 +00003181** If the BtCursor.isIncrblobHandle flag is set, and the current
danielk1977da107192007-05-04 08:32:13 +00003182** cursor entry uses one or more overflow pages, this function
3183** allocates space for and lazily popluates the overflow page-list
3184** cache array (BtCursor.aOverflow). Subsequent calls use this
3185** cache to make seeking to the supplied offset more efficient.
3186**
3187** Once an overflow page-list cache has been allocated, it may be
3188** invalidated if some other cursor writes to the same table, or if
3189** the cursor is moved to a different row. Additionally, in auto-vacuum
3190** mode, the following events may invalidate an overflow page-list cache.
3191**
3192** * An incremental vacuum,
3193** * A commit in auto_vacuum="full" mode,
3194** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00003195*/
danielk19779f8d6402007-05-02 17:48:45 +00003196static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00003197 BtCursor *pCur, /* Cursor pointing to entry to read from */
danielk197789d40042008-11-17 14:20:56 +00003198 u32 offset, /* Begin reading this far into payload */
3199 u32 amt, /* Read this many bytes */
drh3aac2dd2004-04-26 14:10:20 +00003200 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00003201 int skipKey, /* offset begins at data if this is true */
3202 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00003203){
3204 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00003205 int rc = SQLITE_OK;
drhfa1a98a2004-05-14 19:08:17 +00003206 u32 nKey;
danielk19772dec9702007-05-02 16:48:37 +00003207 int iIdx = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003208 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
danielk19770d065412008-11-12 18:21:36 +00003209 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
drh3aac2dd2004-04-26 14:10:20 +00003210
danielk1977da107192007-05-04 08:32:13 +00003211 assert( pPage );
danielk1977da184232006-01-05 11:34:32 +00003212 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003213 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh1fee73e2007-08-29 04:00:57 +00003214 assert( cursorHoldsMutex(pCur) );
danielk1977da107192007-05-04 08:32:13 +00003215
drh86057612007-06-26 01:04:48 +00003216 getCellInfo(pCur);
drh366fda62006-01-13 02:35:09 +00003217 aPayload = pCur->info.pCell + pCur->info.nHeader;
danielk1977da107192007-05-04 08:32:13 +00003218 nKey = (pPage->intKey ? 0 : pCur->info.nKey);
3219
drh3aac2dd2004-04-26 14:10:20 +00003220 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003221 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00003222 }
danielk19770d065412008-11-12 18:21:36 +00003223 if( offset+amt > nKey+pCur->info.nData
3224 || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
3225 ){
danielk1977da107192007-05-04 08:32:13 +00003226 /* Trying to read or write past the end of the data is an error */
danielk197767fd7a92008-09-10 17:53:35 +00003227 return SQLITE_CORRUPT_BKPT;
drh3aac2dd2004-04-26 14:10:20 +00003228 }
danielk1977da107192007-05-04 08:32:13 +00003229
3230 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00003231 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00003232 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00003233 if( a+offset>pCur->info.nLocal ){
3234 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00003235 }
danielk1977da107192007-05-04 08:32:13 +00003236 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00003237 offset = 0;
drha34b6762004-05-07 13:30:42 +00003238 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00003239 amt -= a;
drhdd793422001-06-28 01:54:48 +00003240 }else{
drhfa1a98a2004-05-14 19:08:17 +00003241 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00003242 }
danielk1977da107192007-05-04 08:32:13 +00003243
3244 if( rc==SQLITE_OK && amt>0 ){
danielk197789d40042008-11-17 14:20:56 +00003245 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
danielk1977da107192007-05-04 08:32:13 +00003246 Pgno nextPage;
3247
drhfa1a98a2004-05-14 19:08:17 +00003248 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00003249
danielk19772dec9702007-05-02 16:48:37 +00003250#ifndef SQLITE_OMIT_INCRBLOB
danielk1977dcbb5d32007-05-04 18:36:44 +00003251 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
danielk1977da107192007-05-04 08:32:13 +00003252 ** has not been allocated, allocate it now. The array is sized at
3253 ** one entry for each overflow page in the overflow chain. The
3254 ** page number of the first overflow page is stored in aOverflow[0],
3255 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
3256 ** (the cache is lazily populated).
3257 */
danielk1977dcbb5d32007-05-04 18:36:44 +00003258 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
danielk19772dec9702007-05-02 16:48:37 +00003259 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
drh17435752007-08-16 04:30:38 +00003260 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
danielk19772dec9702007-05-02 16:48:37 +00003261 if( nOvfl && !pCur->aOverflow ){
danielk1977da107192007-05-04 08:32:13 +00003262 rc = SQLITE_NOMEM;
danielk19772dec9702007-05-02 16:48:37 +00003263 }
3264 }
danielk1977da107192007-05-04 08:32:13 +00003265
3266 /* If the overflow page-list cache has been allocated and the
3267 ** entry for the first required overflow page is valid, skip
3268 ** directly to it.
3269 */
danielk19772dec9702007-05-02 16:48:37 +00003270 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
3271 iIdx = (offset/ovflSize);
3272 nextPage = pCur->aOverflow[iIdx];
3273 offset = (offset%ovflSize);
3274 }
3275#endif
danielk1977da107192007-05-04 08:32:13 +00003276
3277 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
3278
3279#ifndef SQLITE_OMIT_INCRBLOB
3280 /* If required, populate the overflow page-list cache. */
3281 if( pCur->aOverflow ){
3282 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
3283 pCur->aOverflow[iIdx] = nextPage;
3284 }
3285#endif
3286
danielk1977d04417962007-05-02 13:16:30 +00003287 if( offset>=ovflSize ){
3288 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00003289 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00003290 ** data is not required. So first try to lookup the overflow
3291 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00003292 ** function.
danielk1977d04417962007-05-02 13:16:30 +00003293 */
danielk19772dec9702007-05-02 16:48:37 +00003294#ifndef SQLITE_OMIT_INCRBLOB
danielk1977da107192007-05-04 08:32:13 +00003295 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
3296 nextPage = pCur->aOverflow[iIdx+1];
3297 } else
danielk19772dec9702007-05-02 16:48:37 +00003298#endif
danielk1977da107192007-05-04 08:32:13 +00003299 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
danielk1977da107192007-05-04 08:32:13 +00003300 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00003301 }else{
danielk19779f8d6402007-05-02 17:48:45 +00003302 /* Need to read this page properly. It contains some of the
3303 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00003304 */
3305 DbPage *pDbPage;
danielk1977cfe9a692004-06-16 12:00:29 +00003306 int a = amt;
danielk1977d04417962007-05-02 13:16:30 +00003307 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
danielk1977da107192007-05-04 08:32:13 +00003308 if( rc==SQLITE_OK ){
3309 aPayload = sqlite3PagerGetData(pDbPage);
3310 nextPage = get4byte(aPayload);
3311 if( a + offset > ovflSize ){
3312 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00003313 }
danielk1977da107192007-05-04 08:32:13 +00003314 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
3315 sqlite3PagerUnref(pDbPage);
3316 offset = 0;
3317 amt -= a;
3318 pBuf += a;
danielk19779f8d6402007-05-02 17:48:45 +00003319 }
danielk1977cfe9a692004-06-16 12:00:29 +00003320 }
drh2af926b2001-05-15 00:39:25 +00003321 }
drh2af926b2001-05-15 00:39:25 +00003322 }
danielk1977cfe9a692004-06-16 12:00:29 +00003323
danielk1977da107192007-05-04 08:32:13 +00003324 if( rc==SQLITE_OK && amt>0 ){
drh49285702005-09-17 15:20:26 +00003325 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00003326 }
danielk1977da107192007-05-04 08:32:13 +00003327 return rc;
drh2af926b2001-05-15 00:39:25 +00003328}
3329
drh72f82862001-05-24 21:06:34 +00003330/*
drh3aac2dd2004-04-26 14:10:20 +00003331** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003332** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003333** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00003334**
drh3aac2dd2004-04-26 14:10:20 +00003335** Return SQLITE_OK on success or an error code if anything goes
3336** wrong. An error is returned if "offset+amt" is larger than
3337** the available payload.
drh72f82862001-05-24 21:06:34 +00003338*/
drha34b6762004-05-07 13:30:42 +00003339int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003340 int rc;
3341
drh1fee73e2007-08-29 04:00:57 +00003342 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003343 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003344 if( rc==SQLITE_OK ){
3345 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003346 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3347 if( pCur->apPage[0]->intKey ){
danielk1977da184232006-01-05 11:34:32 +00003348 return SQLITE_CORRUPT_BKPT;
3349 }
danielk197771d5d2c2008-09-29 11:49:47 +00003350 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh16a9b832007-05-05 18:39:25 +00003351 rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
drh6575a222005-03-10 17:06:34 +00003352 }
danielk1977da184232006-01-05 11:34:32 +00003353 return rc;
drh3aac2dd2004-04-26 14:10:20 +00003354}
3355
3356/*
drh3aac2dd2004-04-26 14:10:20 +00003357** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003358** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003359** begins at "offset".
3360**
3361** Return SQLITE_OK on success or an error code if anything goes
3362** wrong. An error is returned if "offset+amt" is larger than
3363** the available payload.
drh72f82862001-05-24 21:06:34 +00003364*/
drh3aac2dd2004-04-26 14:10:20 +00003365int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003366 int rc;
3367
danielk19773588ceb2008-06-10 17:30:26 +00003368#ifndef SQLITE_OMIT_INCRBLOB
3369 if ( pCur->eState==CURSOR_INVALID ){
3370 return SQLITE_ABORT;
3371 }
3372#endif
3373
drh1fee73e2007-08-29 04:00:57 +00003374 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003375 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003376 if( rc==SQLITE_OK ){
3377 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003378 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3379 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh16a9b832007-05-05 18:39:25 +00003380 rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
danielk1977da184232006-01-05 11:34:32 +00003381 }
3382 return rc;
drh2af926b2001-05-15 00:39:25 +00003383}
3384
drh72f82862001-05-24 21:06:34 +00003385/*
drh0e1c19e2004-05-11 00:58:56 +00003386** Return a pointer to payload information from the entry that the
3387** pCur cursor is pointing to. The pointer is to the beginning of
3388** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00003389** skipKey==1. The number of bytes of available key/data is written
3390** into *pAmt. If *pAmt==0, then the value returned will not be
3391** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00003392**
3393** This routine is an optimization. It is common for the entire key
3394** and data to fit on the local page and for there to be no overflow
3395** pages. When that is so, this routine can be used to access the
3396** key and data without making a copy. If the key and/or data spills
drh16a9b832007-05-05 18:39:25 +00003397** onto overflow pages, then accessPayload() must be used to reassembly
drh0e1c19e2004-05-11 00:58:56 +00003398** the key/data and copy it into a preallocated buffer.
3399**
3400** The pointer returned by this routine looks directly into the cached
3401** page of the database. The data might change or move the next time
3402** any btree routine is called.
3403*/
3404static const unsigned char *fetchPayload(
3405 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00003406 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00003407 int skipKey /* read beginning at data if this is true */
3408){
3409 unsigned char *aPayload;
3410 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00003411 u32 nKey;
danielk197789d40042008-11-17 14:20:56 +00003412 u32 nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003413
danielk197771d5d2c2008-09-29 11:49:47 +00003414 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
danielk1977da184232006-01-05 11:34:32 +00003415 assert( pCur->eState==CURSOR_VALID );
drh1fee73e2007-08-29 04:00:57 +00003416 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00003417 pPage = pCur->apPage[pCur->iPage];
3418 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh86057612007-06-26 01:04:48 +00003419 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00003420 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00003421 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00003422 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00003423 nKey = 0;
3424 }else{
3425 nKey = pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00003426 }
drh0e1c19e2004-05-11 00:58:56 +00003427 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003428 aPayload += nKey;
3429 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00003430 }else{
drhfa1a98a2004-05-14 19:08:17 +00003431 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00003432 if( nLocal>nKey ){
3433 nLocal = nKey;
3434 }
drh0e1c19e2004-05-11 00:58:56 +00003435 }
drhe51c44f2004-05-30 20:46:09 +00003436 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003437 return aPayload;
3438}
3439
3440
3441/*
drhe51c44f2004-05-30 20:46:09 +00003442** For the entry that cursor pCur is point to, return as
3443** many bytes of the key or data as are available on the local
3444** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00003445**
3446** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00003447** or be destroyed on the next call to any Btree routine,
3448** including calls from other threads against the same cache.
3449** Hence, a mutex on the BtShared should be held prior to calling
3450** this routine.
drh0e1c19e2004-05-11 00:58:56 +00003451**
3452** These routines is used to get quick access to key and data
3453** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00003454*/
drhe51c44f2004-05-30 20:46:09 +00003455const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
drh1fee73e2007-08-29 04:00:57 +00003456 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003457 if( pCur->eState==CURSOR_VALID ){
3458 return (const void*)fetchPayload(pCur, pAmt, 0);
3459 }
3460 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003461}
drhe51c44f2004-05-30 20:46:09 +00003462const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
drh1fee73e2007-08-29 04:00:57 +00003463 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003464 if( pCur->eState==CURSOR_VALID ){
3465 return (const void*)fetchPayload(pCur, pAmt, 1);
3466 }
3467 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003468}
3469
3470
3471/*
drh8178a752003-01-05 21:41:40 +00003472** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00003473** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00003474*/
drh3aac2dd2004-04-26 14:10:20 +00003475static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00003476 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003477 int i = pCur->iPage;
drh72f82862001-05-24 21:06:34 +00003478 MemPage *pNewPage;
drhd0679ed2007-08-28 22:24:34 +00003479 BtShared *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00003480
drh1fee73e2007-08-29 04:00:57 +00003481 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003482 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003483 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
3484 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
3485 return SQLITE_CORRUPT_BKPT;
3486 }
3487 rc = getAndInitPage(pBt, newPgno, &pNewPage);
drh6019e162001-07-02 17:51:45 +00003488 if( rc ) return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003489 pCur->apPage[i+1] = pNewPage;
3490 pCur->aiIdx[i+1] = 0;
3491 pCur->iPage++;
3492
drh271efa52004-05-30 19:19:05 +00003493 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003494 pCur->validNKey = 0;
drh4be295b2003-12-16 03:44:47 +00003495 if( pNewPage->nCell<1 ){
drh49285702005-09-17 15:20:26 +00003496 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00003497 }
drh72f82862001-05-24 21:06:34 +00003498 return SQLITE_OK;
3499}
3500
danielk1977bf93c562008-09-29 15:53:25 +00003501#ifndef NDEBUG
3502/*
3503** Page pParent is an internal (non-leaf) tree page. This function
3504** asserts that page number iChild is the left-child if the iIdx'th
3505** cell in page pParent. Or, if iIdx is equal to the total number of
3506** cells in pParent, that page number iChild is the right-child of
3507** the page.
3508*/
3509static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
3510 assert( iIdx<=pParent->nCell );
3511 if( iIdx==pParent->nCell ){
3512 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
3513 }else{
3514 assert( get4byte(findCell(pParent, iIdx))==iChild );
3515 }
3516}
3517#else
3518# define assertParentIndex(x,y,z)
3519#endif
3520
drh72f82862001-05-24 21:06:34 +00003521/*
drh5e2f8b92001-05-28 00:41:15 +00003522** Move the cursor up to the parent page.
3523**
3524** pCur->idx is set to the cell index that contains the pointer
3525** to the page we are coming from. If we are coming from the
3526** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00003527** the largest cell index.
drh72f82862001-05-24 21:06:34 +00003528*/
drh16a9b832007-05-05 18:39:25 +00003529void sqlite3BtreeMoveToParent(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00003530 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003531 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003532 assert( pCur->iPage>0 );
3533 assert( pCur->apPage[pCur->iPage] );
danielk1977bf93c562008-09-29 15:53:25 +00003534 assertParentIndex(
3535 pCur->apPage[pCur->iPage-1],
3536 pCur->aiIdx[pCur->iPage-1],
3537 pCur->apPage[pCur->iPage]->pgno
3538 );
danielk197771d5d2c2008-09-29 11:49:47 +00003539 releasePage(pCur->apPage[pCur->iPage]);
3540 pCur->iPage--;
drh271efa52004-05-30 19:19:05 +00003541 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003542 pCur->validNKey = 0;
drh72f82862001-05-24 21:06:34 +00003543}
3544
3545/*
3546** Move the cursor to the root page
3547*/
drh5e2f8b92001-05-28 00:41:15 +00003548static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00003549 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00003550 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003551 Btree *p = pCur->pBtree;
3552 BtShared *pBt = p->pBt;
drhbd03cae2001-06-02 02:40:57 +00003553
drh1fee73e2007-08-29 04:00:57 +00003554 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +00003555 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
3556 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
3557 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
3558 if( pCur->eState>=CURSOR_REQUIRESEEK ){
3559 if( pCur->eState==CURSOR_FAULT ){
3560 return pCur->skip;
3561 }
danielk1977be51a652008-10-08 17:58:48 +00003562 sqlite3BtreeClearCursor(pCur);
drhbf700f32007-03-31 02:36:44 +00003563 }
danielk197771d5d2c2008-09-29 11:49:47 +00003564
3565 if( pCur->iPage>=0 ){
3566 int i;
3567 for(i=1; i<=pCur->iPage; i++){
3568 releasePage(pCur->apPage[i]);
danielk1977d9f6c532008-09-19 16:39:38 +00003569 }
drh777e4c42006-01-13 04:31:58 +00003570 }else{
3571 if(
danielk197771d5d2c2008-09-29 11:49:47 +00003572 SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]))
drh777e4c42006-01-13 04:31:58 +00003573 ){
3574 pCur->eState = CURSOR_INVALID;
3575 return rc;
3576 }
drhc39e0002004-05-07 23:50:57 +00003577 }
danielk197771d5d2c2008-09-29 11:49:47 +00003578
3579 pRoot = pCur->apPage[0];
3580 assert( pRoot->pgno==pCur->pgnoRoot );
3581 pCur->iPage = 0;
3582 pCur->aiIdx[0] = 0;
drh271efa52004-05-30 19:19:05 +00003583 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003584 pCur->atLast = 0;
3585 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003586
drh8856d6a2004-04-29 14:42:46 +00003587 if( pRoot->nCell==0 && !pRoot->leaf ){
3588 Pgno subpage;
3589 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00003590 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00003591 assert( subpage>0 );
danielk1977da184232006-01-05 11:34:32 +00003592 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00003593 rc = moveToChild(pCur, subpage);
danielk197771d5d2c2008-09-29 11:49:47 +00003594 }else{
3595 pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
drh8856d6a2004-04-29 14:42:46 +00003596 }
3597 return rc;
drh72f82862001-05-24 21:06:34 +00003598}
drh2af926b2001-05-15 00:39:25 +00003599
drh5e2f8b92001-05-28 00:41:15 +00003600/*
3601** Move the cursor down to the left-most leaf entry beneath the
3602** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00003603**
3604** The left-most leaf is the one with the smallest key - the first
3605** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00003606*/
3607static int moveToLeftmost(BtCursor *pCur){
3608 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00003609 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00003610 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00003611
drh1fee73e2007-08-29 04:00:57 +00003612 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003613 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003614 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
3615 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
3616 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
drh8178a752003-01-05 21:41:40 +00003617 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00003618 }
drhd677b3d2007-08-20 22:48:41 +00003619 return rc;
drh5e2f8b92001-05-28 00:41:15 +00003620}
3621
drh2dcc9aa2002-12-04 13:40:25 +00003622/*
3623** Move the cursor down to the right-most leaf entry beneath the
3624** page to which it is currently pointing. Notice the difference
3625** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
3626** finds the left-most entry beneath the *entry* whereas moveToRightmost()
3627** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00003628**
3629** The right-most entry is the one with the largest key - the last
3630** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00003631*/
3632static int moveToRightmost(BtCursor *pCur){
3633 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00003634 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00003635 MemPage *pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003636
drh1fee73e2007-08-29 04:00:57 +00003637 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003638 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003639 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
drh43605152004-05-29 21:46:49 +00003640 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
danielk197771d5d2c2008-09-29 11:49:47 +00003641 pCur->aiIdx[pCur->iPage] = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00003642 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003643 }
drhd677b3d2007-08-20 22:48:41 +00003644 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00003645 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
drhd677b3d2007-08-20 22:48:41 +00003646 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003647 pCur->validNKey = 0;
drhd677b3d2007-08-20 22:48:41 +00003648 }
danielk1977518002e2008-09-05 05:02:46 +00003649 return rc;
drh2dcc9aa2002-12-04 13:40:25 +00003650}
3651
drh5e00f6c2001-09-13 13:46:56 +00003652/* Move the cursor to the first entry in the table. Return SQLITE_OK
3653** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003654** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00003655*/
drh3aac2dd2004-04-26 14:10:20 +00003656int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00003657 int rc;
drhd677b3d2007-08-20 22:48:41 +00003658
drh1fee73e2007-08-29 04:00:57 +00003659 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003660 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00003661 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003662 if( rc==SQLITE_OK ){
3663 if( pCur->eState==CURSOR_INVALID ){
danielk197771d5d2c2008-09-29 11:49:47 +00003664 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00003665 *pRes = 1;
3666 rc = SQLITE_OK;
3667 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00003668 assert( pCur->apPage[pCur->iPage]->nCell>0 );
drhd677b3d2007-08-20 22:48:41 +00003669 *pRes = 0;
3670 rc = moveToLeftmost(pCur);
3671 }
drh5e00f6c2001-09-13 13:46:56 +00003672 }
drh5e00f6c2001-09-13 13:46:56 +00003673 return rc;
3674}
drh5e2f8b92001-05-28 00:41:15 +00003675
drh9562b552002-02-19 15:00:07 +00003676/* Move the cursor to the last entry in the table. Return SQLITE_OK
3677** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003678** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00003679*/
drh3aac2dd2004-04-26 14:10:20 +00003680int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00003681 int rc;
drhd677b3d2007-08-20 22:48:41 +00003682
drh1fee73e2007-08-29 04:00:57 +00003683 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003684 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh9562b552002-02-19 15:00:07 +00003685 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003686 if( rc==SQLITE_OK ){
3687 if( CURSOR_INVALID==pCur->eState ){
danielk197771d5d2c2008-09-29 11:49:47 +00003688 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00003689 *pRes = 1;
3690 }else{
3691 assert( pCur->eState==CURSOR_VALID );
3692 *pRes = 0;
3693 rc = moveToRightmost(pCur);
drha2c20e42008-03-29 16:01:04 +00003694 getCellInfo(pCur);
3695 pCur->atLast = rc==SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003696 }
drh9562b552002-02-19 15:00:07 +00003697 }
drh9562b552002-02-19 15:00:07 +00003698 return rc;
3699}
3700
drhe14006d2008-03-25 17:23:32 +00003701/* Move the cursor so that it points to an entry near the key
drhe63d9992008-08-13 19:11:48 +00003702** specified by pIdxKey or intKey. Return a success code.
drh72f82862001-05-24 21:06:34 +00003703**
drhe63d9992008-08-13 19:11:48 +00003704** For INTKEY tables, the intKey parameter is used. pIdxKey
3705** must be NULL. For index tables, pIdxKey is used and intKey
3706** is ignored.
drh3aac2dd2004-04-26 14:10:20 +00003707**
drh5e2f8b92001-05-28 00:41:15 +00003708** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00003709** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00003710** were present. The cursor might point to an entry that comes
3711** before or after the key.
3712**
drhbd03cae2001-06-02 02:40:57 +00003713** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00003714** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00003715** this value is as follows:
3716**
3717** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00003718** is smaller than pKey or if the table is empty
3719** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00003720**
3721** *pRes==0 The cursor is left pointing at an entry that
3722** exactly matches pKey.
3723**
3724** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00003725** is larger than pKey.
drhd677b3d2007-08-20 22:48:41 +00003726**
drha059ad02001-04-17 20:09:11 +00003727*/
drhe63d9992008-08-13 19:11:48 +00003728int sqlite3BtreeMovetoUnpacked(
3729 BtCursor *pCur, /* The cursor to be moved */
3730 UnpackedRecord *pIdxKey, /* Unpacked index key */
3731 i64 intKey, /* The table key */
3732 int biasRight, /* If true, bias the search to the high end */
3733 int *pRes /* Write search results here */
drhe4d90812007-03-29 05:51:49 +00003734){
drh72f82862001-05-24 21:06:34 +00003735 int rc;
drhd677b3d2007-08-20 22:48:41 +00003736
drh1fee73e2007-08-29 04:00:57 +00003737 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003738 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drha2c20e42008-03-29 16:01:04 +00003739
3740 /* If the cursor is already positioned at the point we are trying
3741 ** to move to, then just return without doing any work */
danielk197771d5d2c2008-09-29 11:49:47 +00003742 if( pCur->eState==CURSOR_VALID && pCur->validNKey
3743 && pCur->apPage[0]->intKey
3744 ){
drhe63d9992008-08-13 19:11:48 +00003745 if( pCur->info.nKey==intKey ){
drha2c20e42008-03-29 16:01:04 +00003746 *pRes = 0;
3747 return SQLITE_OK;
3748 }
drhe63d9992008-08-13 19:11:48 +00003749 if( pCur->atLast && pCur->info.nKey<intKey ){
drha2c20e42008-03-29 16:01:04 +00003750 *pRes = -1;
3751 return SQLITE_OK;
3752 }
3753 }
3754
drh5e2f8b92001-05-28 00:41:15 +00003755 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003756 if( rc ){
3757 return rc;
3758 }
danielk197771d5d2c2008-09-29 11:49:47 +00003759 assert( pCur->apPage[pCur->iPage] );
3760 assert( pCur->apPage[pCur->iPage]->isInit );
danielk1977da184232006-01-05 11:34:32 +00003761 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00003762 *pRes = -1;
danielk197771d5d2c2008-09-29 11:49:47 +00003763 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhc39e0002004-05-07 23:50:57 +00003764 return SQLITE_OK;
3765 }
danielk197771d5d2c2008-09-29 11:49:47 +00003766 assert( pCur->apPage[0]->intKey || pIdxKey );
drh14684382006-11-30 13:05:29 +00003767 for(;;){
drh72f82862001-05-24 21:06:34 +00003768 int lwr, upr;
3769 Pgno chldPg;
danielk197771d5d2c2008-09-29 11:49:47 +00003770 MemPage *pPage = pCur->apPage[pCur->iPage];
drh1a844c32002-12-04 22:29:28 +00003771 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00003772 lwr = 0;
3773 upr = pPage->nCell-1;
drhe63d9992008-08-13 19:11:48 +00003774 if( !pPage->intKey && pIdxKey==0 ){
drh1e968a02008-03-25 00:22:21 +00003775 rc = SQLITE_CORRUPT_BKPT;
3776 goto moveto_finish;
drh4eec4c12005-01-21 00:22:37 +00003777 }
drhe4d90812007-03-29 05:51:49 +00003778 if( biasRight ){
danielk197771d5d2c2008-09-29 11:49:47 +00003779 pCur->aiIdx[pCur->iPage] = upr;
drhe4d90812007-03-29 05:51:49 +00003780 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00003781 pCur->aiIdx[pCur->iPage] = (upr+lwr)/2;
drhe4d90812007-03-29 05:51:49 +00003782 }
drhf1d68b32007-03-29 04:43:26 +00003783 if( lwr<=upr ) for(;;){
danielk197713adf8a2004-06-03 16:08:41 +00003784 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00003785 i64 nCellKey;
danielk197771d5d2c2008-09-29 11:49:47 +00003786 int idx = pCur->aiIdx[pCur->iPage];
drh366fda62006-01-13 02:35:09 +00003787 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003788 pCur->validNKey = 1;
drh3aac2dd2004-04-26 14:10:20 +00003789 if( pPage->intKey ){
drh777e4c42006-01-13 04:31:58 +00003790 u8 *pCell;
danielk197771d5d2c2008-09-29 11:49:47 +00003791 pCell = findCell(pPage, idx) + pPage->childPtrSize;
drhd172f862006-01-12 15:01:15 +00003792 if( pPage->hasData ){
danielk1977bab45c62006-01-16 15:14:27 +00003793 u32 dummy;
shane3f8d5cf2008-04-24 19:15:09 +00003794 pCell += getVarint32(pCell, dummy);
drhd172f862006-01-12 15:01:15 +00003795 }
drha2c20e42008-03-29 16:01:04 +00003796 getVarint(pCell, (u64*)&nCellKey);
drhe63d9992008-08-13 19:11:48 +00003797 if( nCellKey==intKey ){
drh3aac2dd2004-04-26 14:10:20 +00003798 c = 0;
drhe63d9992008-08-13 19:11:48 +00003799 }else if( nCellKey<intKey ){
drh41eb9e92008-04-02 18:33:07 +00003800 c = -1;
3801 }else{
drhe63d9992008-08-13 19:11:48 +00003802 assert( nCellKey>intKey );
drh41eb9e92008-04-02 18:33:07 +00003803 c = +1;
drh3aac2dd2004-04-26 14:10:20 +00003804 }
drh3aac2dd2004-04-26 14:10:20 +00003805 }else{
drhe51c44f2004-05-30 20:46:09 +00003806 int available;
danielk197713adf8a2004-06-03 16:08:41 +00003807 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drh366fda62006-01-13 02:35:09 +00003808 nCellKey = pCur->info.nKey;
drhe51c44f2004-05-30 20:46:09 +00003809 if( available>=nCellKey ){
drhe63d9992008-08-13 19:11:48 +00003810 c = sqlite3VdbeRecordCompare(nCellKey, pCellKey, pIdxKey);
drhe51c44f2004-05-30 20:46:09 +00003811 }else{
drhfacf0302008-06-17 15:12:00 +00003812 pCellKey = sqlite3Malloc( nCellKey );
danielk19776507ecb2008-03-25 09:56:44 +00003813 if( pCellKey==0 ){
3814 rc = SQLITE_NOMEM;
3815 goto moveto_finish;
3816 }
danielk197713adf8a2004-06-03 16:08:41 +00003817 rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
drhe63d9992008-08-13 19:11:48 +00003818 c = sqlite3VdbeRecordCompare(nCellKey, pCellKey, pIdxKey);
drhfacf0302008-06-17 15:12:00 +00003819 sqlite3_free(pCellKey);
drh1e968a02008-03-25 00:22:21 +00003820 if( rc ) goto moveto_finish;
drhe51c44f2004-05-30 20:46:09 +00003821 }
drh3aac2dd2004-04-26 14:10:20 +00003822 }
drh72f82862001-05-24 21:06:34 +00003823 if( c==0 ){
drha2c20e42008-03-29 16:01:04 +00003824 pCur->info.nKey = nCellKey;
drh44845222008-07-17 18:39:57 +00003825 if( pPage->intKey && !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00003826 lwr = idx;
drhfc70e6f2004-05-12 21:11:27 +00003827 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00003828 break;
3829 }else{
drh8b18dd42004-05-12 19:18:15 +00003830 if( pRes ) *pRes = 0;
drh1e968a02008-03-25 00:22:21 +00003831 rc = SQLITE_OK;
3832 goto moveto_finish;
drh8b18dd42004-05-12 19:18:15 +00003833 }
drh72f82862001-05-24 21:06:34 +00003834 }
3835 if( c<0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003836 lwr = idx+1;
drh72f82862001-05-24 21:06:34 +00003837 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00003838 upr = idx-1;
drh72f82862001-05-24 21:06:34 +00003839 }
drhf1d68b32007-03-29 04:43:26 +00003840 if( lwr>upr ){
drha2c20e42008-03-29 16:01:04 +00003841 pCur->info.nKey = nCellKey;
drhf1d68b32007-03-29 04:43:26 +00003842 break;
3843 }
danielk197771d5d2c2008-09-29 11:49:47 +00003844 pCur->aiIdx[pCur->iPage] = (lwr+upr)/2;
drh72f82862001-05-24 21:06:34 +00003845 }
3846 assert( lwr==upr+1 );
danielk197771d5d2c2008-09-29 11:49:47 +00003847 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00003848 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00003849 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00003850 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00003851 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00003852 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00003853 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00003854 }
3855 if( chldPg==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003856 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh72f82862001-05-24 21:06:34 +00003857 if( pRes ) *pRes = c;
drh1e968a02008-03-25 00:22:21 +00003858 rc = SQLITE_OK;
3859 goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00003860 }
danielk197771d5d2c2008-09-29 11:49:47 +00003861 pCur->aiIdx[pCur->iPage] = lwr;
drh271efa52004-05-30 19:19:05 +00003862 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003863 pCur->validNKey = 0;
drh8178a752003-01-05 21:41:40 +00003864 rc = moveToChild(pCur, chldPg);
drh1e968a02008-03-25 00:22:21 +00003865 if( rc ) goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00003866 }
drh1e968a02008-03-25 00:22:21 +00003867moveto_finish:
drhe63d9992008-08-13 19:11:48 +00003868 return rc;
3869}
3870
3871/*
3872** In this version of BtreeMoveto, pKey is a packed index record
3873** such as is generated by the OP_MakeRecord opcode. Unpack the
3874** record and then call BtreeMovetoUnpacked() to do the work.
3875*/
3876int sqlite3BtreeMoveto(
3877 BtCursor *pCur, /* Cursor open on the btree to be searched */
3878 const void *pKey, /* Packed key if the btree is an index */
3879 i64 nKey, /* Integer key for tables. Size of pKey for indices */
3880 int bias, /* Bias search to the high end */
3881 int *pRes /* Write search results here */
3882){
3883 int rc; /* Status code */
3884 UnpackedRecord *pIdxKey; /* Unpacked index key */
drh23f79d02008-08-20 22:06:47 +00003885 UnpackedRecord aSpace[16]; /* Temp space for pIdxKey - to avoid a malloc */
drhe63d9992008-08-13 19:11:48 +00003886
drhe14006d2008-03-25 17:23:32 +00003887 if( pKey ){
drhe63d9992008-08-13 19:11:48 +00003888 pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, nKey, pKey,
drh23f79d02008-08-20 22:06:47 +00003889 aSpace, sizeof(aSpace));
drhe63d9992008-08-13 19:11:48 +00003890 if( pIdxKey==0 ) return SQLITE_NOMEM;
3891 }else{
3892 pIdxKey = 0;
3893 }
3894 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
3895 if( pKey ){
3896 sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
drhe14006d2008-03-25 17:23:32 +00003897 }
drh1e968a02008-03-25 00:22:21 +00003898 return rc;
drh72f82862001-05-24 21:06:34 +00003899}
3900
drhd677b3d2007-08-20 22:48:41 +00003901
drh72f82862001-05-24 21:06:34 +00003902/*
drhc39e0002004-05-07 23:50:57 +00003903** Return TRUE if the cursor is not pointing at an entry of the table.
3904**
3905** TRUE will be returned after a call to sqlite3BtreeNext() moves
3906** past the last entry in the table or sqlite3BtreePrev() moves past
3907** the first entry. TRUE is also returned if the table is empty.
3908*/
3909int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00003910 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
3911 ** have been deleted? This API will need to change to return an error code
3912 ** as well as the boolean result value.
3913 */
3914 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00003915}
3916
3917/*
drhb21c8cd2007-08-21 19:33:56 +00003918** Return the database connection handle for a cursor.
3919*/
3920sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){
drhe5fe6902007-12-07 18:55:28 +00003921 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
3922 return pCur->pBtree->db;
drhb21c8cd2007-08-21 19:33:56 +00003923}
3924
3925/*
drhbd03cae2001-06-02 02:40:57 +00003926** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00003927** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00003928** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00003929** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00003930*/
drhd094db12008-04-03 21:46:57 +00003931int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00003932 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003933 int idx;
danielk197797a227c2006-01-20 16:32:04 +00003934 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00003935
drh1fee73e2007-08-29 04:00:57 +00003936 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003937 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003938 if( rc!=SQLITE_OK ){
3939 return rc;
3940 }
drh8c4d3a62007-04-06 01:03:32 +00003941 assert( pRes!=0 );
drh8c4d3a62007-04-06 01:03:32 +00003942 if( CURSOR_INVALID==pCur->eState ){
3943 *pRes = 1;
3944 return SQLITE_OK;
3945 }
danielk1977da184232006-01-05 11:34:32 +00003946 if( pCur->skip>0 ){
3947 pCur->skip = 0;
3948 *pRes = 0;
3949 return SQLITE_OK;
3950 }
3951 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00003952
danielk197771d5d2c2008-09-29 11:49:47 +00003953 pPage = pCur->apPage[pCur->iPage];
3954 idx = ++pCur->aiIdx[pCur->iPage];
3955 assert( pPage->isInit );
3956 assert( idx<=pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00003957
drh271efa52004-05-30 19:19:05 +00003958 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003959 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003960 if( idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00003961 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003962 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00003963 if( rc ) return rc;
3964 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003965 *pRes = 0;
3966 return rc;
drh72f82862001-05-24 21:06:34 +00003967 }
drh5e2f8b92001-05-28 00:41:15 +00003968 do{
danielk197771d5d2c2008-09-29 11:49:47 +00003969 if( pCur->iPage==0 ){
drh8c1238a2003-01-02 14:43:55 +00003970 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00003971 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00003972 return SQLITE_OK;
3973 }
drh16a9b832007-05-05 18:39:25 +00003974 sqlite3BtreeMoveToParent(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00003975 pPage = pCur->apPage[pCur->iPage];
3976 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00003977 *pRes = 0;
drh44845222008-07-17 18:39:57 +00003978 if( pPage->intKey ){
drh8b18dd42004-05-12 19:18:15 +00003979 rc = sqlite3BtreeNext(pCur, pRes);
3980 }else{
3981 rc = SQLITE_OK;
3982 }
3983 return rc;
drh8178a752003-01-05 21:41:40 +00003984 }
3985 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00003986 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00003987 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00003988 }
drh5e2f8b92001-05-28 00:41:15 +00003989 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003990 return rc;
drh72f82862001-05-24 21:06:34 +00003991}
drhd677b3d2007-08-20 22:48:41 +00003992
drh72f82862001-05-24 21:06:34 +00003993
drh3b7511c2001-05-26 13:15:44 +00003994/*
drh2dcc9aa2002-12-04 13:40:25 +00003995** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00003996** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00003997** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00003998** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00003999*/
drhd094db12008-04-03 21:46:57 +00004000int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00004001 int rc;
drh8178a752003-01-05 21:41:40 +00004002 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00004003
drh1fee73e2007-08-29 04:00:57 +00004004 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004005 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004006 if( rc!=SQLITE_OK ){
4007 return rc;
4008 }
drha2c20e42008-03-29 16:01:04 +00004009 pCur->atLast = 0;
drh8c4d3a62007-04-06 01:03:32 +00004010 if( CURSOR_INVALID==pCur->eState ){
4011 *pRes = 1;
4012 return SQLITE_OK;
4013 }
danielk1977da184232006-01-05 11:34:32 +00004014 if( pCur->skip<0 ){
4015 pCur->skip = 0;
4016 *pRes = 0;
4017 return SQLITE_OK;
4018 }
4019 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00004020
danielk197771d5d2c2008-09-29 11:49:47 +00004021 pPage = pCur->apPage[pCur->iPage];
4022 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00004023 if( !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00004024 int idx = pCur->aiIdx[pCur->iPage];
4025 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
drhd677b3d2007-08-20 22:48:41 +00004026 if( rc ){
4027 return rc;
4028 }
drh2dcc9aa2002-12-04 13:40:25 +00004029 rc = moveToRightmost(pCur);
4030 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004031 while( pCur->aiIdx[pCur->iPage]==0 ){
4032 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00004033 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00004034 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00004035 return SQLITE_OK;
4036 }
drh16a9b832007-05-05 18:39:25 +00004037 sqlite3BtreeMoveToParent(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00004038 }
drh271efa52004-05-30 19:19:05 +00004039 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004040 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004041
4042 pCur->aiIdx[pCur->iPage]--;
4043 pPage = pCur->apPage[pCur->iPage];
drh44845222008-07-17 18:39:57 +00004044 if( pPage->intKey && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00004045 rc = sqlite3BtreePrevious(pCur, pRes);
4046 }else{
4047 rc = SQLITE_OK;
4048 }
drh2dcc9aa2002-12-04 13:40:25 +00004049 }
drh8178a752003-01-05 21:41:40 +00004050 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00004051 return rc;
4052}
4053
4054/*
drh3b7511c2001-05-26 13:15:44 +00004055** Allocate a new page from the database file.
4056**
danielk19773b8a05f2007-03-19 17:44:26 +00004057** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00004058** has already been called on the new page.) The new page has also
4059** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00004060** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00004061**
4062** SQLITE_OK is returned on success. Any other return value indicates
4063** an error. *ppPage and *pPgno are undefined in the event of an error.
danielk19773b8a05f2007-03-19 17:44:26 +00004064** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00004065**
drh199e3cf2002-07-18 11:01:47 +00004066** If the "nearby" parameter is not 0, then a (feeble) effort is made to
4067** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00004068** attempt to keep related pages close to each other in the database file,
4069** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00004070**
4071** If the "exact" parameter is not 0, and the page-number nearby exists
4072** anywhere on the free-list, then it is guarenteed to be returned. This
4073** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00004074*/
drh4f0c5872007-03-26 22:05:01 +00004075static int allocateBtreePage(
danielk1977aef0bf62005-12-30 16:28:01 +00004076 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00004077 MemPage **ppPage,
4078 Pgno *pPgno,
4079 Pgno nearby,
4080 u8 exact
4081){
drh3aac2dd2004-04-26 14:10:20 +00004082 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00004083 int rc;
drh3aac2dd2004-04-26 14:10:20 +00004084 int n; /* Number of pages on the freelist */
4085 int k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00004086 MemPage *pTrunk = 0;
4087 MemPage *pPrevTrunk = 0;
drh30e58752002-03-02 20:41:57 +00004088
drh1fee73e2007-08-29 04:00:57 +00004089 assert( sqlite3_mutex_held(pBt->mutex) );
drh3aac2dd2004-04-26 14:10:20 +00004090 pPage1 = pBt->pPage1;
4091 n = get4byte(&pPage1->aData[36]);
4092 if( n>0 ){
drh91025292004-05-03 19:49:32 +00004093 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00004094 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004095 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
4096
4097 /* If the 'exact' parameter was true and a query of the pointer-map
4098 ** shows that the page 'nearby' is somewhere on the free-list, then
4099 ** the entire-list will be searched for that page.
4100 */
4101#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197789d40042008-11-17 14:20:56 +00004102 if( exact && nearby<=pagerPagecount(pBt) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004103 u8 eType;
4104 assert( nearby>0 );
4105 assert( pBt->autoVacuum );
4106 rc = ptrmapGet(pBt, nearby, &eType, 0);
4107 if( rc ) return rc;
4108 if( eType==PTRMAP_FREEPAGE ){
4109 searchList = 1;
4110 }
4111 *pPgno = nearby;
4112 }
4113#endif
4114
4115 /* Decrement the free-list count by 1. Set iTrunk to the index of the
4116 ** first free-list trunk page. iPrevTrunk is initially 1.
4117 */
danielk19773b8a05f2007-03-19 17:44:26 +00004118 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00004119 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004120 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004121
4122 /* The code within this loop is run only once if the 'searchList' variable
4123 ** is not true. Otherwise, it runs once for each trunk-page on the
4124 ** free-list until the page 'nearby' is located.
4125 */
4126 do {
4127 pPrevTrunk = pTrunk;
4128 if( pPrevTrunk ){
4129 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00004130 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004131 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00004132 }
drh16a9b832007-05-05 18:39:25 +00004133 rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004134 if( rc ){
drhd3627af2006-12-18 18:34:51 +00004135 pTrunk = 0;
4136 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004137 }
4138
4139 k = get4byte(&pTrunk->aData[4]);
4140 if( k==0 && !searchList ){
4141 /* The trunk has no leaves and the list is not being searched.
4142 ** So extract the trunk page itself and use it as the newly
4143 ** allocated page */
4144 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00004145 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004146 if( rc ){
4147 goto end_allocate_page;
4148 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004149 *pPgno = iTrunk;
4150 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4151 *ppPage = pTrunk;
4152 pTrunk = 0;
4153 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh45b1fac2008-07-04 17:52:42 +00004154 }else if( k>pBt->usableSize/4 - 2 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004155 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00004156 rc = SQLITE_CORRUPT_BKPT;
4157 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004158#ifndef SQLITE_OMIT_AUTOVACUUM
4159 }else if( searchList && nearby==iTrunk ){
4160 /* The list is being searched and this trunk page is the page
4161 ** to allocate, regardless of whether it has leaves.
4162 */
4163 assert( *pPgno==iTrunk );
4164 *ppPage = pTrunk;
4165 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00004166 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004167 if( rc ){
4168 goto end_allocate_page;
4169 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004170 if( k==0 ){
4171 if( !pPrevTrunk ){
4172 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4173 }else{
4174 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
4175 }
4176 }else{
4177 /* The trunk page is required by the caller but it contains
4178 ** pointers to free-list leaves. The first leaf becomes a trunk
4179 ** page in this case.
4180 */
4181 MemPage *pNewTrunk;
4182 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh16a9b832007-05-05 18:39:25 +00004183 rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004184 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00004185 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004186 }
danielk19773b8a05f2007-03-19 17:44:26 +00004187 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004188 if( rc!=SQLITE_OK ){
4189 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00004190 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004191 }
4192 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
4193 put4byte(&pNewTrunk->aData[4], k-1);
4194 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00004195 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004196 if( !pPrevTrunk ){
drhc5053fb2008-11-27 02:22:10 +00004197 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
danielk1977cb1a7eb2004-11-05 12:27:02 +00004198 put4byte(&pPage1->aData[32], iNewTrunk);
4199 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00004200 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004201 if( rc ){
4202 goto end_allocate_page;
4203 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004204 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
4205 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004206 }
4207 pTrunk = 0;
4208 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
4209#endif
4210 }else{
4211 /* Extract a leaf from the trunk */
4212 int closest;
4213 Pgno iPage;
4214 unsigned char *aData = pTrunk->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00004215 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004216 if( rc ){
4217 goto end_allocate_page;
4218 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004219 if( nearby>0 ){
4220 int i, dist;
4221 closest = 0;
4222 dist = get4byte(&aData[8]) - nearby;
4223 if( dist<0 ) dist = -dist;
4224 for(i=1; i<k; i++){
4225 int d2 = get4byte(&aData[8+i*4]) - nearby;
4226 if( d2<0 ) d2 = -d2;
4227 if( d2<dist ){
4228 closest = i;
4229 dist = d2;
4230 }
4231 }
4232 }else{
4233 closest = 0;
4234 }
4235
4236 iPage = get4byte(&aData[8+closest*4]);
4237 if( !searchList || iPage==nearby ){
danielk197789d40042008-11-17 14:20:56 +00004238 Pgno nPage;
shane1f9e6aa2008-06-09 19:27:11 +00004239 *pPgno = iPage;
danielk197789d40042008-11-17 14:20:56 +00004240 nPage = pagerPagecount(pBt);
danielk1977ad0132d2008-06-07 08:58:22 +00004241 if( *pPgno>nPage ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004242 /* Free page off the end of the file */
danielk197743e377a2008-05-05 12:09:32 +00004243 rc = SQLITE_CORRUPT_BKPT;
4244 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004245 }
4246 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
4247 ": %d more free pages\n",
4248 *pPgno, closest+1, k, pTrunk->pgno, n-1));
4249 if( closest<k-1 ){
4250 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
4251 }
4252 put4byte(&aData[4], k-1);
drhc5053fb2008-11-27 02:22:10 +00004253 assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
drh16a9b832007-05-05 18:39:25 +00004254 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004255 if( rc==SQLITE_OK ){
drh538f5702007-04-13 02:14:30 +00004256 sqlite3PagerDontRollback((*ppPage)->pDbPage);
danielk19773b8a05f2007-03-19 17:44:26 +00004257 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004258 if( rc!=SQLITE_OK ){
4259 releasePage(*ppPage);
4260 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004261 }
4262 searchList = 0;
4263 }
drhee696e22004-08-30 16:52:17 +00004264 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004265 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00004266 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004267 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00004268 }else{
drh3aac2dd2004-04-26 14:10:20 +00004269 /* There are no pages on the freelist, so create a new page at the
4270 ** end of the file */
danielk197789d40042008-11-17 14:20:56 +00004271 int nPage = pagerPagecount(pBt);
danielk1977ad0132d2008-06-07 08:58:22 +00004272 *pPgno = nPage + 1;
danielk1977afcdd022004-10-31 16:25:42 +00004273
4274#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00004275 if( pBt->nTrunc ){
4276 /* An incr-vacuum has already run within this transaction. So the
4277 ** page to allocate is not from the physical end of the file, but
4278 ** at pBt->nTrunc.
4279 */
4280 *pPgno = pBt->nTrunc+1;
4281 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
4282 (*pPgno)++;
4283 }
4284 }
danielk1977266664d2006-02-10 08:24:21 +00004285 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00004286 /* If *pPgno refers to a pointer-map page, allocate two new pages
4287 ** at the end of the file instead of one. The first allocated page
4288 ** becomes a new pointer-map page, the second is used by the caller.
4289 */
4290 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00004291 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977afcdd022004-10-31 16:25:42 +00004292 (*pPgno)++;
drh72190432008-01-31 14:54:43 +00004293 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
danielk1977afcdd022004-10-31 16:25:42 +00004294 }
danielk1977dddbcdc2007-04-26 14:42:34 +00004295 if( pBt->nTrunc ){
4296 pBt->nTrunc = *pPgno;
4297 }
danielk1977afcdd022004-10-31 16:25:42 +00004298#endif
4299
danielk1977599fcba2004-11-08 07:13:13 +00004300 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh16a9b832007-05-05 18:39:25 +00004301 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
drh3b7511c2001-05-26 13:15:44 +00004302 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00004303 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004304 if( rc!=SQLITE_OK ){
4305 releasePage(*ppPage);
4306 }
drh3a4c1412004-05-09 20:40:11 +00004307 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00004308 }
danielk1977599fcba2004-11-08 07:13:13 +00004309
4310 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00004311
4312end_allocate_page:
4313 releasePage(pTrunk);
4314 releasePage(pPrevTrunk);
danielk1977b247c212008-11-21 09:09:01 +00004315 if( rc==SQLITE_OK ){
4316 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
4317 releasePage(*ppPage);
4318 return SQLITE_CORRUPT_BKPT;
4319 }
4320 (*ppPage)->isInit = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00004321 }
drh3b7511c2001-05-26 13:15:44 +00004322 return rc;
4323}
4324
4325/*
drh3aac2dd2004-04-26 14:10:20 +00004326** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00004327**
danielk19773b8a05f2007-03-19 17:44:26 +00004328** sqlite3PagerUnref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00004329*/
drh3aac2dd2004-04-26 14:10:20 +00004330static int freePage(MemPage *pPage){
danielk1977aef0bf62005-12-30 16:28:01 +00004331 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00004332 MemPage *pPage1 = pBt->pPage1;
4333 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00004334
drh3aac2dd2004-04-26 14:10:20 +00004335 /* Prepare the page for freeing */
drh1fee73e2007-08-29 04:00:57 +00004336 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh3aac2dd2004-04-26 14:10:20 +00004337 assert( pPage->pgno>1 );
4338 pPage->isInit = 0;
drh3aac2dd2004-04-26 14:10:20 +00004339
drha34b6762004-05-07 13:30:42 +00004340 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00004341 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00004342 if( rc ) return rc;
4343 n = get4byte(&pPage1->aData[36]);
4344 put4byte(&pPage1->aData[36], n+1);
4345
drhfcce93f2006-02-22 03:08:32 +00004346#ifdef SQLITE_SECURE_DELETE
4347 /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
4348 ** always fully overwrite deleted information with zeros.
4349 */
danielk19773b8a05f2007-03-19 17:44:26 +00004350 rc = sqlite3PagerWrite(pPage->pDbPage);
drhfcce93f2006-02-22 03:08:32 +00004351 if( rc ) return rc;
4352 memset(pPage->aData, 0, pPage->pBt->pageSize);
4353#endif
4354
danielk1977687566d2004-11-02 12:56:41 +00004355 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00004356 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00004357 */
danielk197785d90ca2008-07-19 14:25:15 +00004358 if( ISAUTOVACUUM ){
danielk1977687566d2004-11-02 12:56:41 +00004359 rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
danielk1977a64a0352004-11-05 01:45:13 +00004360 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00004361 }
danielk1977687566d2004-11-02 12:56:41 +00004362
drh3aac2dd2004-04-26 14:10:20 +00004363 if( n==0 ){
4364 /* This is the first free page */
danielk19773b8a05f2007-03-19 17:44:26 +00004365 rc = sqlite3PagerWrite(pPage->pDbPage);
drhda200cc2004-05-09 11:51:38 +00004366 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004367 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00004368 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00004369 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00004370 }else{
4371 /* Other free pages already exist. Retrive the first trunk page
4372 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00004373 MemPage *pTrunk;
drh16a9b832007-05-05 18:39:25 +00004374 rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0);
drh3b7511c2001-05-26 13:15:44 +00004375 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004376 k = get4byte(&pTrunk->aData[4]);
drhee696e22004-08-30 16:52:17 +00004377 if( k>=pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00004378 /* The trunk is full. Turn the page being freed into a new
drh45b1fac2008-07-04 17:52:42 +00004379 ** trunk page with no leaves.
4380 **
4381 ** Note that the trunk page is not really full until it contains
4382 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
4383 ** coded. But due to a coding error in versions of SQLite prior to
4384 ** 3.6.0, databases with freelist trunk pages holding more than
4385 ** usableSize/4 - 8 entries will be reported as corrupt. In order
4386 ** to maintain backwards compatibility with older versions of SQLite,
4387 ** we will contain to restrict the number of entries to usableSize/4 - 8
4388 ** for now. At some point in the future (once everyone has upgraded
4389 ** to 3.6.0 or later) we should consider fixing the conditional above
4390 ** to read "usableSize/4-2" instead of "usableSize/4-8".
4391 */
danielk19773b8a05f2007-03-19 17:44:26 +00004392 rc = sqlite3PagerWrite(pPage->pDbPage);
drhb9ee4932007-09-07 14:32:06 +00004393 if( rc==SQLITE_OK ){
4394 put4byte(pPage->aData, pTrunk->pgno);
4395 put4byte(&pPage->aData[4], 0);
4396 put4byte(&pPage1->aData[32], pPage->pgno);
4397 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
4398 pPage->pgno, pTrunk->pgno));
4399 }
4400 }else if( k<0 ){
4401 rc = SQLITE_CORRUPT;
drh3aac2dd2004-04-26 14:10:20 +00004402 }else{
4403 /* Add the newly freed page as a leaf on the current trunk */
danielk19773b8a05f2007-03-19 17:44:26 +00004404 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00004405 if( rc==SQLITE_OK ){
4406 put4byte(&pTrunk->aData[4], k+1);
4407 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drhfcce93f2006-02-22 03:08:32 +00004408#ifndef SQLITE_SECURE_DELETE
danielk1977a1fa00d2008-08-27 15:16:33 +00004409 rc = sqlite3PagerDontWrite(pPage->pDbPage);
drhfcce93f2006-02-22 03:08:32 +00004410#endif
drhf5345442007-04-09 12:45:02 +00004411 }
drh3a4c1412004-05-09 20:40:11 +00004412 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00004413 }
4414 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00004415 }
drh3b7511c2001-05-26 13:15:44 +00004416 return rc;
4417}
4418
4419/*
drh3aac2dd2004-04-26 14:10:20 +00004420** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00004421*/
drh3aac2dd2004-04-26 14:10:20 +00004422static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00004423 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00004424 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00004425 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00004426 int rc;
drh94440812007-03-06 11:42:19 +00004427 int nOvfl;
4428 int ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00004429
drh1fee73e2007-08-29 04:00:57 +00004430 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh16a9b832007-05-05 18:39:25 +00004431 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004432 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00004433 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00004434 }
drh6f11bef2004-05-13 01:12:56 +00004435 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh94440812007-03-06 11:42:19 +00004436 ovflPageSize = pBt->usableSize - 4;
drh72365832007-03-06 15:53:44 +00004437 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
4438 assert( ovflPgno==0 || nOvfl>0 );
4439 while( nOvfl-- ){
drh3aac2dd2004-04-26 14:10:20 +00004440 MemPage *pOvfl;
danielk197789d40042008-11-17 14:20:56 +00004441 if( ovflPgno==0 || ovflPgno>pagerPagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00004442 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00004443 }
danielk19778c0a9592007-04-30 16:55:00 +00004444
4445 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno);
drh3b7511c2001-05-26 13:15:44 +00004446 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00004447 rc = freePage(pOvfl);
danielk19773b8a05f2007-03-19 17:44:26 +00004448 sqlite3PagerUnref(pOvfl->pDbPage);
danielk19776b456a22005-03-21 04:04:02 +00004449 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00004450 }
drh5e2f8b92001-05-28 00:41:15 +00004451 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00004452}
4453
4454/*
drh91025292004-05-03 19:49:32 +00004455** Create the byte sequence used to represent a cell on page pPage
4456** and write that byte sequence into pCell[]. Overflow pages are
4457** allocated and filled in as necessary. The calling procedure
4458** is responsible for making sure sufficient space has been allocated
4459** for pCell[].
4460**
4461** Note that pCell does not necessary need to point to the pPage->aData
4462** area. pCell might point to some temporary storage. The cell will
4463** be constructed in this temporary area then copied into pPage->aData
4464** later.
drh3b7511c2001-05-26 13:15:44 +00004465*/
4466static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00004467 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00004468 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00004469 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00004470 const void *pData,int nData, /* The data */
drhb026e052007-05-02 01:34:31 +00004471 int nZero, /* Extra zero bytes to append to pData */
drh4b70f112004-05-02 21:12:19 +00004472 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00004473){
drh3b7511c2001-05-26 13:15:44 +00004474 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00004475 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00004476 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00004477 int spaceLeft;
4478 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00004479 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00004480 unsigned char *pPrior;
4481 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00004482 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00004483 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00004484 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00004485 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00004486
drh1fee73e2007-08-29 04:00:57 +00004487 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00004488
drhc5053fb2008-11-27 02:22:10 +00004489 /* pPage is not necessarily writeable since pCell might be auxiliary
4490 ** buffer space that is separate from the pPage buffer area */
4491 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
4492 || sqlite3PagerIswriteable(pPage->pDbPage) );
4493
drh91025292004-05-03 19:49:32 +00004494 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00004495 nHeader = 0;
drh91025292004-05-03 19:49:32 +00004496 if( !pPage->leaf ){
4497 nHeader += 4;
4498 }
drh8b18dd42004-05-12 19:18:15 +00004499 if( pPage->hasData ){
drhb026e052007-05-02 01:34:31 +00004500 nHeader += putVarint(&pCell[nHeader], nData+nZero);
drh6f11bef2004-05-13 01:12:56 +00004501 }else{
drhb026e052007-05-02 01:34:31 +00004502 nData = nZero = 0;
drh91025292004-05-03 19:49:32 +00004503 }
drh6f11bef2004-05-13 01:12:56 +00004504 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh16a9b832007-05-05 18:39:25 +00004505 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004506 assert( info.nHeader==nHeader );
4507 assert( info.nKey==nKey );
danielk197789d40042008-11-17 14:20:56 +00004508 assert( info.nData==(u32)(nData+nZero) );
drh6f11bef2004-05-13 01:12:56 +00004509
4510 /* Fill in the payload */
drhb026e052007-05-02 01:34:31 +00004511 nPayload = nData + nZero;
drh3aac2dd2004-04-26 14:10:20 +00004512 if( pPage->intKey ){
4513 pSrc = pData;
4514 nSrc = nData;
drh91025292004-05-03 19:49:32 +00004515 nData = 0;
drh3aac2dd2004-04-26 14:10:20 +00004516 }else{
4517 nPayload += nKey;
4518 pSrc = pKey;
4519 nSrc = nKey;
4520 }
drh6f11bef2004-05-13 01:12:56 +00004521 *pnSize = info.nSize;
4522 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00004523 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00004524 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00004525
drh3b7511c2001-05-26 13:15:44 +00004526 while( nPayload>0 ){
4527 if( spaceLeft==0 ){
danielk1977b39f70b2007-05-17 18:28:11 +00004528 int isExact = 0;
danielk1977afcdd022004-10-31 16:25:42 +00004529#ifndef SQLITE_OMIT_AUTOVACUUM
4530 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00004531 if( pBt->autoVacuum ){
4532 do{
4533 pgnoOvfl++;
4534 } while(
4535 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
4536 );
danielk197789a4be82007-05-23 13:34:32 +00004537 if( pgnoOvfl>1 ){
danielk1977b39f70b2007-05-17 18:28:11 +00004538 /* isExact = 1; */
4539 }
4540 }
danielk1977afcdd022004-10-31 16:25:42 +00004541#endif
danielk1977b39f70b2007-05-17 18:28:11 +00004542 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, isExact);
danielk1977afcdd022004-10-31 16:25:42 +00004543#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00004544 /* If the database supports auto-vacuum, and the second or subsequent
4545 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00004546 ** for that page now.
4547 **
4548 ** If this is the first overflow page, then write a partial entry
4549 ** to the pointer-map. If we write nothing to this pointer-map slot,
4550 ** then the optimistic overflow chain processing in clearCell()
4551 ** may misinterpret the uninitialised values and delete the
4552 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00004553 */
danielk19774ef24492007-05-23 09:52:41 +00004554 if( pBt->autoVacuum && rc==SQLITE_OK ){
4555 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
4556 rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
danielk197789a4be82007-05-23 13:34:32 +00004557 if( rc ){
4558 releasePage(pOvfl);
4559 }
danielk1977afcdd022004-10-31 16:25:42 +00004560 }
4561#endif
drh3b7511c2001-05-26 13:15:44 +00004562 if( rc ){
drh9b171272004-05-08 02:03:22 +00004563 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00004564 return rc;
4565 }
drhc5053fb2008-11-27 02:22:10 +00004566
4567 /* If pToRelease is not zero than pPrior points into the data area
4568 ** of pToRelease. Make sure pToRelease is still writeable. */
4569 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
4570
4571 /* If pPrior is part of the data area of pPage, then make sure pPage
4572 ** is still writeable */
4573 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
4574 || sqlite3PagerIswriteable(pPage->pDbPage) );
4575
drh3aac2dd2004-04-26 14:10:20 +00004576 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00004577 releasePage(pToRelease);
4578 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00004579 pPrior = pOvfl->aData;
4580 put4byte(pPrior, 0);
4581 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00004582 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00004583 }
4584 n = nPayload;
4585 if( n>spaceLeft ) n = spaceLeft;
drhc5053fb2008-11-27 02:22:10 +00004586
4587 /* If pToRelease is not zero than pPayload points into the data area
4588 ** of pToRelease. Make sure pToRelease is still writeable. */
4589 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
4590
4591 /* If pPayload is part of the data area of pPage, then make sure pPage
4592 ** is still writeable */
4593 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
4594 || sqlite3PagerIswriteable(pPage->pDbPage) );
4595
drhb026e052007-05-02 01:34:31 +00004596 if( nSrc>0 ){
4597 if( n>nSrc ) n = nSrc;
4598 assert( pSrc );
4599 memcpy(pPayload, pSrc, n);
4600 }else{
4601 memset(pPayload, 0, n);
4602 }
drh3b7511c2001-05-26 13:15:44 +00004603 nPayload -= n;
drhde647132004-05-07 17:57:49 +00004604 pPayload += n;
drh9b171272004-05-08 02:03:22 +00004605 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00004606 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00004607 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00004608 if( nSrc==0 ){
4609 nSrc = nData;
4610 pSrc = pData;
4611 }
drhdd793422001-06-28 01:54:48 +00004612 }
drh9b171272004-05-08 02:03:22 +00004613 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00004614 return SQLITE_OK;
4615}
4616
drh14acc042001-06-10 19:56:58 +00004617/*
4618** Remove the i-th cell from pPage. This routine effects pPage only.
4619** The cell content is not freed or deallocated. It is assumed that
4620** the cell content has been copied someplace else. This routine just
4621** removes the reference to the cell from pPage.
4622**
4623** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00004624*/
shane0af3f892008-11-12 04:55:34 +00004625static int dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00004626 int i; /* Loop counter */
4627 int pc; /* Offset to cell content of cell being deleted */
4628 u8 *data; /* pPage->aData */
4629 u8 *ptr; /* Used to move bytes around within data[] */
shanedcc50b72008-11-13 18:29:50 +00004630 int rc; /* The return code */
drh43605152004-05-29 21:46:49 +00004631
drh8c42ca92001-06-22 19:15:00 +00004632 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00004633 assert( sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00004634 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00004635 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00004636 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00004637 ptr = &data[pPage->cellOffset + 2*idx];
shane0af3f892008-11-12 04:55:34 +00004638 pc = get2byte(ptr);
drhc5053fb2008-11-27 02:22:10 +00004639 if( (pc<pPage->hdrOffset+6+(pPage->leaf?0:4))
4640 || (pc+sz>pPage->pBt->usableSize) ){
shane0af3f892008-11-12 04:55:34 +00004641 return SQLITE_CORRUPT_BKPT;
4642 }
shanedcc50b72008-11-13 18:29:50 +00004643 rc = freeSpace(pPage, pc, sz);
4644 if( rc!=SQLITE_OK ){
4645 return rc;
4646 }
drh43605152004-05-29 21:46:49 +00004647 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
4648 ptr[0] = ptr[2];
4649 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00004650 }
4651 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00004652 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
4653 pPage->nFree += 2;
shane0af3f892008-11-12 04:55:34 +00004654 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004655}
4656
4657/*
4658** Insert a new cell on pPage at cell index "i". pCell points to the
4659** content of the cell.
4660**
4661** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00004662** will not fit, then make a copy of the cell content into pTemp if
4663** pTemp is not null. Regardless of pTemp, allocate a new entry
4664** in pPage->aOvfl[] and make it point to the cell content (either
4665** in pTemp or the original pCell) and also record its index.
4666** Allocating a new entry in pPage->aCell[] implies that
4667** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00004668**
4669** If nSkip is non-zero, then do not copy the first nSkip bytes of the
4670** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00004671** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00004672** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00004673*/
danielk1977e80463b2004-11-03 03:01:16 +00004674static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00004675 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00004676 int i, /* New cell becomes the i-th cell of the page */
4677 u8 *pCell, /* Content of the new cell */
4678 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00004679 u8 *pTemp, /* Temp storage space for pCell, if needed */
4680 u8 nSkip /* Do not write the first nSkip bytes of the cell */
drh24cd67e2004-05-10 16:18:47 +00004681){
drh43605152004-05-29 21:46:49 +00004682 int idx; /* Where to write new cell content in data[] */
4683 int j; /* Loop counter */
4684 int top; /* First byte of content for any cell in data[] */
4685 int end; /* First byte past the last cell pointer in data[] */
4686 int ins; /* Index in data[] where new cell pointer is inserted */
4687 int hdr; /* Offset into data[] of the page header */
4688 int cellOffset; /* Address of first cell pointer in data[] */
4689 u8 *data; /* The content of the whole page */
4690 u8 *ptr; /* Used for moving information around in data[] */
4691
4692 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
4693 assert( sz==cellSizePtr(pPage, pCell) );
drh1fee73e2007-08-29 04:00:57 +00004694 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +00004695 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00004696 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00004697 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004698 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00004699 }
drh43605152004-05-29 21:46:49 +00004700 j = pPage->nOverflow++;
danielk197789d40042008-11-17 14:20:56 +00004701 assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
drh43605152004-05-29 21:46:49 +00004702 pPage->aOvfl[j].pCell = pCell;
4703 pPage->aOvfl[j].idx = i;
4704 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00004705 }else{
danielk19776e465eb2007-08-21 13:11:00 +00004706 int rc = sqlite3PagerWrite(pPage->pDbPage);
4707 if( rc!=SQLITE_OK ){
4708 return rc;
4709 }
4710 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00004711 data = pPage->aData;
4712 hdr = pPage->hdrOffset;
4713 top = get2byte(&data[hdr+5]);
4714 cellOffset = pPage->cellOffset;
4715 end = cellOffset + 2*pPage->nCell + 2;
4716 ins = cellOffset + 2*i;
4717 if( end > top - sz ){
shane0af3f892008-11-12 04:55:34 +00004718 rc = defragmentPage(pPage);
4719 if( rc!=SQLITE_OK ){
4720 return rc;
4721 }
drh43605152004-05-29 21:46:49 +00004722 top = get2byte(&data[hdr+5]);
4723 assert( end + sz <= top );
4724 }
4725 idx = allocateSpace(pPage, sz);
4726 assert( idx>0 );
4727 assert( end <= get2byte(&data[hdr+5]) );
shane0af3f892008-11-12 04:55:34 +00004728 if (idx+sz > pPage->pBt->usableSize) {
shane34ac18d2008-11-11 22:18:20 +00004729 return SQLITE_CORRUPT_BKPT;
shane0af3f892008-11-12 04:55:34 +00004730 }
drh43605152004-05-29 21:46:49 +00004731 pPage->nCell++;
4732 pPage->nFree -= 2;
danielk1977a3ad5e72005-01-07 08:56:44 +00004733 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004734 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
4735 ptr[0] = ptr[-2];
4736 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00004737 }
drh43605152004-05-29 21:46:49 +00004738 put2byte(&data[ins], idx);
4739 put2byte(&data[hdr+3], pPage->nCell);
danielk1977a19df672004-11-03 11:37:07 +00004740#ifndef SQLITE_OMIT_AUTOVACUUM
4741 if( pPage->pBt->autoVacuum ){
4742 /* The cell may contain a pointer to an overflow page. If so, write
4743 ** the entry for the overflow page into the pointer map.
4744 */
4745 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00004746 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh72365832007-03-06 15:53:44 +00004747 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk1977a19df672004-11-03 11:37:07 +00004748 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
4749 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
danielk19776e465eb2007-08-21 13:11:00 +00004750 rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
danielk1977a19df672004-11-03 11:37:07 +00004751 if( rc!=SQLITE_OK ) return rc;
4752 }
4753 }
4754#endif
drh14acc042001-06-10 19:56:58 +00004755 }
danielk1977e80463b2004-11-03 03:01:16 +00004756
danielk1977e80463b2004-11-03 03:01:16 +00004757 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004758}
4759
4760/*
drhfa1a98a2004-05-14 19:08:17 +00004761** Add a list of cells to a page. The page should be initially empty.
4762** The cells are guaranteed to fit on the page.
4763*/
4764static void assemblePage(
4765 MemPage *pPage, /* The page to be assemblied */
4766 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00004767 u8 **apCell, /* Pointers to cell bodies */
drha9121e42008-02-19 14:59:35 +00004768 u16 *aSize /* Sizes of the cells */
drhfa1a98a2004-05-14 19:08:17 +00004769){
4770 int i; /* Loop counter */
4771 int totalSize; /* Total size of all cells */
4772 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00004773 int cellptr; /* Address of next cell pointer */
4774 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00004775 u8 *data; /* Data for the page */
4776
drh43605152004-05-29 21:46:49 +00004777 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00004778 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa1a98a2004-05-14 19:08:17 +00004779 totalSize = 0;
4780 for(i=0; i<nCell; i++){
4781 totalSize += aSize[i];
4782 }
drh43605152004-05-29 21:46:49 +00004783 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00004784 assert( pPage->nCell==0 );
drhc5053fb2008-11-27 02:22:10 +00004785 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00004786 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00004787 data = pPage->aData;
4788 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00004789 put2byte(&data[hdr+3], nCell);
drh09d0deb2005-08-02 17:13:09 +00004790 if( nCell ){
4791 cellbody = allocateSpace(pPage, totalSize);
4792 assert( cellbody>0 );
4793 assert( pPage->nFree >= 2*nCell );
4794 pPage->nFree -= 2*nCell;
4795 for(i=0; i<nCell; i++){
4796 put2byte(&data[cellptr], cellbody);
4797 memcpy(&data[cellbody], apCell[i], aSize[i]);
4798 cellptr += 2;
4799 cellbody += aSize[i];
4800 }
4801 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00004802 }
4803 pPage->nCell = nCell;
drhfa1a98a2004-05-14 19:08:17 +00004804}
4805
drh14acc042001-06-10 19:56:58 +00004806/*
drhc3b70572003-01-04 19:44:07 +00004807** The following parameters determine how many adjacent pages get involved
4808** in a balancing operation. NN is the number of neighbors on either side
4809** of the page that participate in the balancing operation. NB is the
4810** total number of pages that participate, including the target page and
4811** NN neighbors on either side.
4812**
4813** The minimum value of NN is 1 (of course). Increasing NN above 1
4814** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
4815** in exchange for a larger degradation in INSERT and UPDATE performance.
4816** The value of NN appears to give the best results overall.
4817*/
4818#define NN 1 /* Number of neighbors on either side of pPage */
4819#define NB (NN*2+1) /* Total pages involved in the balance */
4820
drh43605152004-05-29 21:46:49 +00004821/* Forward reference */
danielk197771d5d2c2008-09-29 11:49:47 +00004822static int balance(BtCursor*, int);
danielk1977ac245ec2005-01-14 13:50:11 +00004823
drh615ae552005-01-16 23:21:00 +00004824#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004825/*
4826** This version of balance() handles the common special case where
4827** a new entry is being inserted on the extreme right-end of the
4828** tree, in other words, when the new entry will become the largest
4829** entry in the tree.
4830**
4831** Instead of trying balance the 3 right-most leaf pages, just add
4832** a new page to the right-hand side and put the one new entry in
4833** that page. This leaves the right side of the tree somewhat
4834** unbalanced. But odds are that we will be inserting new entries
4835** at the end soon afterwards so the nearly empty page will quickly
4836** fill up. On average.
4837**
4838** pPage is the leaf page which is the right-most page in the tree.
4839** pParent is its parent. pPage must have a single overflow entry
4840** which is also the right-most entry on the page.
4841*/
danielk197771d5d2c2008-09-29 11:49:47 +00004842static int balance_quick(BtCursor *pCur){
danielk1977ac245ec2005-01-14 13:50:11 +00004843 int rc;
danielk1977eaa06f62008-09-18 17:34:44 +00004844 MemPage *pNew = 0;
danielk1977ac245ec2005-01-14 13:50:11 +00004845 Pgno pgnoNew;
4846 u8 *pCell;
drha9121e42008-02-19 14:59:35 +00004847 u16 szCell;
danielk1977ac245ec2005-01-14 13:50:11 +00004848 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00004849 MemPage *pPage = pCur->apPage[pCur->iPage];
4850 MemPage *pParent = pCur->apPage[pCur->iPage-1];
danielk1977aef0bf62005-12-30 16:28:01 +00004851 BtShared *pBt = pPage->pBt;
danielk197779a40da2005-01-16 08:00:01 +00004852 int parentIdx = pParent->nCell; /* pParent new divider cell index */
4853 int parentSize; /* Size of new divider cell */
4854 u8 parentCell[64]; /* Space for the new divider cell */
danielk1977ac245ec2005-01-14 13:50:11 +00004855
drh1fee73e2007-08-29 04:00:57 +00004856 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00004857
danielk1977ac245ec2005-01-14 13:50:11 +00004858 /* Allocate a new page. Insert the overflow cell from pPage
4859 ** into it. Then remove the overflow cell from pPage.
4860 */
drh4f0c5872007-03-26 22:05:01 +00004861 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk1977eaa06f62008-09-18 17:34:44 +00004862 if( rc==SQLITE_OK ){
4863 pCell = pPage->aOvfl[0].pCell;
4864 szCell = cellSizePtr(pPage, pCell);
drhc5053fb2008-11-27 02:22:10 +00004865 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
danielk1977eaa06f62008-09-18 17:34:44 +00004866 zeroPage(pNew, pPage->aData[0]);
4867 assemblePage(pNew, 1, &pCell, &szCell);
4868 pPage->nOverflow = 0;
4869
danielk1977eaa06f62008-09-18 17:34:44 +00004870 /* pPage is currently the right-child of pParent. Change this
4871 ** so that the right-child is the new page allocated above and
4872 ** pPage is the next-to-right child.
4873 **
4874 ** Ignore the return value of the call to fillInCell(). fillInCell()
4875 ** may only return other than SQLITE_OK if it is required to allocate
4876 ** one or more overflow pages. Since an internal table B-Tree cell
4877 ** may never spill over onto an overflow page (it is a maximum of
4878 ** 13 bytes in size), it is not neccessary to check the return code.
4879 **
4880 ** Similarly, the insertCell() function cannot fail if the page
4881 ** being inserted into is already writable and the cell does not
4882 ** contain an overflow pointer. So ignore this return code too.
4883 */
4884 assert( pPage->nCell>0 );
4885 pCell = findCell(pPage, pPage->nCell-1);
4886 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
4887 fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
4888 assert( parentSize<64 );
4889 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
4890 insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
4891 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
4892 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
4893
4894 /* If this is an auto-vacuum database, update the pointer map
4895 ** with entries for the new page, and any pointer from the
4896 ** cell on the page to an overflow page.
4897 */
4898 if( ISAUTOVACUUM ){
4899 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
4900 if( rc==SQLITE_OK ){
4901 rc = ptrmapPutOvfl(pNew, 0);
4902 }
danielk1977ac11ee62005-01-15 12:45:51 +00004903 }
danielk1977e08a3c42008-09-18 18:17:03 +00004904
4905 /* Release the reference to the new page. */
4906 releasePage(pNew);
danielk1977ac11ee62005-01-15 12:45:51 +00004907 }
4908
danielk1977eaa06f62008-09-18 17:34:44 +00004909 /* At this point the pPage->nFree variable is not set correctly with
4910 ** respect to the content of the page (because it was set to 0 by
4911 ** insertCell). So call sqlite3BtreeInitPage() to make sure it is
4912 ** correct.
4913 **
4914 ** This has to be done even if an error will be returned. Normally, if
4915 ** an error occurs during tree balancing, the contents of MemPage are
4916 ** not important, as they will be recalculated when the page is rolled
4917 ** back. But here, in balance_quick(), it is possible that pPage has
4918 ** not yet been marked dirty or written into the journal file. Therefore
4919 ** it will not be rolled back and so it is important to make sure that
4920 ** the page data and contents of MemPage are consistent.
4921 */
4922 pPage->isInit = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004923 sqlite3BtreeInitPage(pPage);
danielk1977eaa06f62008-09-18 17:34:44 +00004924
danielk1977e08a3c42008-09-18 18:17:03 +00004925 /* If everything else succeeded, balance the parent page, in
4926 ** case the divider cell inserted caused it to become overfull.
danielk197779a40da2005-01-16 08:00:01 +00004927 */
danielk1977eaa06f62008-09-18 17:34:44 +00004928 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00004929 releasePage(pPage);
4930 pCur->iPage--;
4931 rc = balance(pCur, 0);
danielk1977eaa06f62008-09-18 17:34:44 +00004932 }
4933 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004934}
drh615ae552005-01-16 23:21:00 +00004935#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00004936
drhc3b70572003-01-04 19:44:07 +00004937/*
drhab01f612004-05-22 02:55:23 +00004938** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00004939** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00004940** Usually NN siblings on either side of pPage is used in the balancing,
4941** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00004942** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00004943** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00004944** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00004945**
drh0c6cc4e2004-06-15 02:13:26 +00004946** The number of siblings of pPage might be increased or decreased by one or
4947** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00004948** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00004949** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00004950** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00004951** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00004952**
drh8b2f49b2001-06-08 00:21:52 +00004953** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00004954** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00004955** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00004956** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00004957**
drh8c42ca92001-06-22 19:15:00 +00004958** In the course of balancing the siblings of pPage, the parent of pPage
4959** might become overfull or underfull. If that happens, then this routine
4960** is called recursively on the parent.
4961**
drh5e00f6c2001-09-13 13:46:56 +00004962** If this routine fails for any reason, it might leave the database
4963** in a corrupted state. So if this routine fails, the database should
4964** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00004965*/
danielk197771d5d2c2008-09-29 11:49:47 +00004966static int balance_nonroot(BtCursor *pCur){
4967 MemPage *pPage; /* The over or underfull page to balance */
drh8b2f49b2001-06-08 00:21:52 +00004968 MemPage *pParent; /* The parent of pPage */
drh16a9b832007-05-05 18:39:25 +00004969 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00004970 int nCell = 0; /* Number of cells in apCell[] */
4971 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
drh8b2f49b2001-06-08 00:21:52 +00004972 int nOld; /* Number of pages in apOld[] */
4973 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00004974 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00004975 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00004976 int idx; /* Index of pPage in pParent->aCell[] */
4977 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00004978 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00004979 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00004980 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00004981 int usableSpace; /* Bytes in pPage beyond the header */
4982 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00004983 int subtotal; /* Subtotal of bytes in cells on one page */
drhe5ae5732008-06-15 02:51:47 +00004984 int iSpace1 = 0; /* First unused byte of aSpace1[] */
4985 int iSpace2 = 0; /* First unused byte of aSpace2[] */
drhfacf0302008-06-17 15:12:00 +00004986 int szScratch; /* Size of scratch memory requested */
drhc3b70572003-01-04 19:44:07 +00004987 MemPage *apOld[NB]; /* pPage and up to two siblings */
4988 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00004989 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00004990 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
4991 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drh4b70f112004-05-02 21:12:19 +00004992 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00004993 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
4994 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00004995 u8 **apCell = 0; /* All cells begin balanced */
drha9121e42008-02-19 14:59:35 +00004996 u16 *szCell; /* Local size of all cells in apCell[] */
drhe5ae5732008-06-15 02:51:47 +00004997 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
4998 u8 *aSpace1; /* Space for copies of dividers cells before balance */
4999 u8 *aSpace2 = 0; /* Space for overflow dividers cells after balance */
danielk1977ac11ee62005-01-15 12:45:51 +00005000 u8 *aFrom = 0;
drh8b2f49b2001-06-08 00:21:52 +00005001
danielk197771d5d2c2008-09-29 11:49:47 +00005002 pPage = pCur->apPage[pCur->iPage];
drh1fee73e2007-08-29 04:00:57 +00005003 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf94a1732008-09-30 17:18:17 +00005004 VVA_ONLY( pCur->pagesShuffled = 1 );
drhd677b3d2007-08-20 22:48:41 +00005005
drh14acc042001-06-10 19:56:58 +00005006 /*
drh43605152004-05-29 21:46:49 +00005007 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00005008 */
danielk197771d5d2c2008-09-29 11:49:47 +00005009 assert( pCur->iPage>0 );
5010 assert( pPage->isInit );
danielk19776e465eb2007-08-21 13:11:00 +00005011 assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 );
drh4b70f112004-05-02 21:12:19 +00005012 pBt = pPage->pBt;
danielk197771d5d2c2008-09-29 11:49:47 +00005013 pParent = pCur->apPage[pCur->iPage-1];
drh43605152004-05-29 21:46:49 +00005014 assert( pParent );
danielk19773b8a05f2007-03-19 17:44:26 +00005015 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
danielk197707cb5602006-01-20 10:55:05 +00005016 return rc;
5017 }
danielk1977474b7cc2008-07-09 11:49:46 +00005018
drh43605152004-05-29 21:46:49 +00005019 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00005020
drh615ae552005-01-16 23:21:00 +00005021#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00005022 /*
5023 ** A special case: If a new entry has just been inserted into a
5024 ** table (that is, a btree with integer keys and all data at the leaves)
drh09d0deb2005-08-02 17:13:09 +00005025 ** and the new entry is the right-most entry in the tree (it has the
drhf222e712005-01-14 22:55:49 +00005026 ** largest key) then use the special balance_quick() routine for
5027 ** balancing. balance_quick() is much faster and results in a tighter
5028 ** packing of data in the common case.
5029 */
danielk1977ac245ec2005-01-14 13:50:11 +00005030 if( pPage->leaf &&
5031 pPage->intKey &&
danielk1977ac245ec2005-01-14 13:50:11 +00005032 pPage->nOverflow==1 &&
5033 pPage->aOvfl[0].idx==pPage->nCell &&
danielk197771d5d2c2008-09-29 11:49:47 +00005034 pParent->pgno!=1 &&
danielk1977ac245ec2005-01-14 13:50:11 +00005035 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
5036 ){
drh44845222008-07-17 18:39:57 +00005037 assert( pPage->intKey );
danielk1977ac11ee62005-01-15 12:45:51 +00005038 /*
5039 ** TODO: Check the siblings to the left of pPage. It may be that
5040 ** they are not full and no new page is required.
5041 */
danielk197771d5d2c2008-09-29 11:49:47 +00005042 return balance_quick(pCur);
danielk1977ac245ec2005-01-14 13:50:11 +00005043 }
5044#endif
5045
danielk19776e465eb2007-08-21 13:11:00 +00005046 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){
5047 return rc;
5048 }
5049
drh2e38c322004-09-03 18:38:44 +00005050 /*
drh4b70f112004-05-02 21:12:19 +00005051 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00005052 ** to pPage. The "idx" variable is the index of that cell. If pPage
5053 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00005054 */
danielk1977bf93c562008-09-29 15:53:25 +00005055 idx = pCur->aiIdx[pCur->iPage-1];
5056 assertParentIndex(pParent, idx, pPage->pgno);
drh8b2f49b2001-06-08 00:21:52 +00005057
5058 /*
drh14acc042001-06-10 19:56:58 +00005059 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00005060 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00005061 */
drh14acc042001-06-10 19:56:58 +00005062 nOld = nNew = 0;
drh14acc042001-06-10 19:56:58 +00005063
5064 /*
drh4b70f112004-05-02 21:12:19 +00005065 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00005066 ** the siblings. An attempt is made to find NN siblings on either
5067 ** side of pPage. More siblings are taken from one side, however, if
5068 ** pPage there are fewer than NN siblings on the other side. If pParent
5069 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00005070 */
drhc3b70572003-01-04 19:44:07 +00005071 nxDiv = idx - NN;
5072 if( nxDiv + NB > pParent->nCell ){
5073 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00005074 }
drhc3b70572003-01-04 19:44:07 +00005075 if( nxDiv<0 ){
5076 nxDiv = 0;
5077 }
drh8b2f49b2001-06-08 00:21:52 +00005078 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00005079 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00005080 if( k<pParent->nCell ){
danielk19771cc5ed82007-05-16 17:28:43 +00005081 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00005082 nDiv++;
drha34b6762004-05-07 13:30:42 +00005083 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00005084 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00005085 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00005086 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00005087 }else{
5088 break;
drh8b2f49b2001-06-08 00:21:52 +00005089 }
danielk197771d5d2c2008-09-29 11:49:47 +00005090 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i]);
drh6019e162001-07-02 17:51:45 +00005091 if( rc ) goto balance_cleanup;
danielk197771d5d2c2008-09-29 11:49:47 +00005092 /* apOld[i]->idxParent = k; */
drh91025292004-05-03 19:49:32 +00005093 apCopy[i] = 0;
5094 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00005095 nOld++;
danielk1977634f2982005-03-28 08:44:07 +00005096 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
drh8b2f49b2001-06-08 00:21:52 +00005097 }
5098
drha9121e42008-02-19 14:59:35 +00005099 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00005100 ** alignment */
drha9121e42008-02-19 14:59:35 +00005101 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00005102
drh8b2f49b2001-06-08 00:21:52 +00005103 /*
danielk1977634f2982005-03-28 08:44:07 +00005104 ** Allocate space for memory structures
5105 */
drhfacf0302008-06-17 15:12:00 +00005106 szScratch =
drha9121e42008-02-19 14:59:35 +00005107 nMaxCells*sizeof(u8*) /* apCell */
5108 + nMaxCells*sizeof(u16) /* szCell */
5109 + (ROUND8(sizeof(MemPage))+pBt->pageSize)*NB /* aCopy */
drhe5ae5732008-06-15 02:51:47 +00005110 + pBt->pageSize /* aSpace1 */
drhfacf0302008-06-17 15:12:00 +00005111 + (ISAUTOVACUUM ? nMaxCells : 0); /* aFrom */
5112 apCell = sqlite3ScratchMalloc( szScratch );
danielk1977634f2982005-03-28 08:44:07 +00005113 if( apCell==0 ){
5114 rc = SQLITE_NOMEM;
5115 goto balance_cleanup;
5116 }
drha9121e42008-02-19 14:59:35 +00005117 szCell = (u16*)&apCell[nMaxCells];
danielk1977634f2982005-03-28 08:44:07 +00005118 aCopy[0] = (u8*)&szCell[nMaxCells];
drhc96d8532005-05-03 12:30:33 +00005119 assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00005120 for(i=1; i<NB; i++){
drhc96d8532005-05-03 12:30:33 +00005121 aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
5122 assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00005123 }
drhe5ae5732008-06-15 02:51:47 +00005124 aSpace1 = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
5125 assert( ((aSpace1 - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk197785d90ca2008-07-19 14:25:15 +00005126 if( ISAUTOVACUUM ){
drhe5ae5732008-06-15 02:51:47 +00005127 aFrom = &aSpace1[pBt->pageSize];
danielk1977634f2982005-03-28 08:44:07 +00005128 }
drhfacf0302008-06-17 15:12:00 +00005129 aSpace2 = sqlite3PageMalloc(pBt->pageSize);
drhe5ae5732008-06-15 02:51:47 +00005130 if( aSpace2==0 ){
5131 rc = SQLITE_NOMEM;
5132 goto balance_cleanup;
5133 }
danielk1977634f2982005-03-28 08:44:07 +00005134
5135 /*
drh14acc042001-06-10 19:56:58 +00005136 ** Make copies of the content of pPage and its siblings into aOld[].
5137 ** The rest of this function will use data from the copies rather
5138 ** that the original pages since the original pages will be in the
5139 ** process of being overwritten.
5140 */
5141 for(i=0; i<nOld; i++){
drhbf4bca52007-09-06 22:19:14 +00005142 MemPage *p = apCopy[i] = (MemPage*)aCopy[i];
5143 memcpy(p, apOld[i], sizeof(MemPage));
5144 p->aData = (void*)&p[1];
5145 memcpy(p->aData, apOld[i]->aData, pBt->pageSize);
drh14acc042001-06-10 19:56:58 +00005146 }
5147
5148 /*
5149 ** Load pointers to all cells on sibling pages and the divider cells
5150 ** into the local apCell[] array. Make copies of the divider cells
drhe5ae5732008-06-15 02:51:47 +00005151 ** into space obtained form aSpace1[] and remove the the divider Cells
drhb6f41482004-05-14 01:58:11 +00005152 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00005153 **
5154 ** If the siblings are on leaf pages, then the child pointers of the
5155 ** divider cells are stripped from the cells before they are copied
drhe5ae5732008-06-15 02:51:47 +00005156 ** into aSpace1[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00005157 ** child pointers. If siblings are not leaves, then all cell in
5158 ** apCell[] include child pointers. Either way, all cells in apCell[]
5159 ** are alike.
drh96f5b762004-05-16 16:24:36 +00005160 **
5161 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
5162 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00005163 */
5164 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00005165 leafCorrection = pPage->leaf*4;
drh44845222008-07-17 18:39:57 +00005166 leafData = pPage->hasData;
drh8b2f49b2001-06-08 00:21:52 +00005167 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00005168 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00005169 int limit = pOld->nCell+pOld->nOverflow;
5170 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00005171 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00005172 apCell[nCell] = findOverflowCell(pOld, j);
5173 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk197785d90ca2008-07-19 14:25:15 +00005174 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005175 int a;
5176 aFrom[nCell] = i;
5177 for(a=0; a<pOld->nOverflow; a++){
5178 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
5179 aFrom[nCell] = 0xFF;
5180 break;
5181 }
5182 }
5183 }
drh14acc042001-06-10 19:56:58 +00005184 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00005185 }
5186 if( i<nOld-1 ){
drha9121e42008-02-19 14:59:35 +00005187 u16 sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00005188 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00005189 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
5190 ** are duplicates of keys on the child pages. We need to remove
5191 ** the divider cells from pParent, but the dividers cells are not
5192 ** added to apCell[] because they are duplicates of child cells.
5193 */
drh8b18dd42004-05-12 19:18:15 +00005194 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00005195 }else{
drhb6f41482004-05-14 01:58:11 +00005196 u8 *pTemp;
danielk1977634f2982005-03-28 08:44:07 +00005197 assert( nCell<nMaxCells );
drhb6f41482004-05-14 01:58:11 +00005198 szCell[nCell] = sz;
drhe5ae5732008-06-15 02:51:47 +00005199 pTemp = &aSpace1[iSpace1];
5200 iSpace1 += sz;
5201 assert( sz<=pBt->pageSize/4 );
5202 assert( iSpace1<=pBt->pageSize );
drhb6f41482004-05-14 01:58:11 +00005203 memcpy(pTemp, apDiv[i], sz);
5204 apCell[nCell] = pTemp+leafCorrection;
danielk197785d90ca2008-07-19 14:25:15 +00005205 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005206 aFrom[nCell] = 0xFF;
5207 }
drhb6f41482004-05-14 01:58:11 +00005208 dropCell(pParent, nxDiv, sz);
drh8b18dd42004-05-12 19:18:15 +00005209 szCell[nCell] -= leafCorrection;
drh43605152004-05-29 21:46:49 +00005210 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00005211 if( !pOld->leaf ){
5212 assert( leafCorrection==0 );
5213 /* The right pointer of the child page pOld becomes the left
5214 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00005215 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00005216 }else{
5217 assert( leafCorrection==4 );
danielk197739c96042007-05-12 10:41:47 +00005218 if( szCell[nCell]<4 ){
5219 /* Do not allow any cells smaller than 4 bytes. */
5220 szCell[nCell] = 4;
5221 }
drh8b18dd42004-05-12 19:18:15 +00005222 }
5223 nCell++;
drh4b70f112004-05-02 21:12:19 +00005224 }
drh8b2f49b2001-06-08 00:21:52 +00005225 }
5226 }
5227
5228 /*
drh6019e162001-07-02 17:51:45 +00005229 ** Figure out the number of pages needed to hold all nCell cells.
5230 ** Store this number in "k". Also compute szNew[] which is the total
5231 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00005232 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00005233 ** cntNew[k] should equal nCell.
5234 **
drh96f5b762004-05-16 16:24:36 +00005235 ** Values computed by this block:
5236 **
5237 ** k: The total number of sibling pages
5238 ** szNew[i]: Spaced used on the i-th sibling page.
5239 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
5240 ** the right of the i-th sibling page.
5241 ** usableSpace: Number of bytes of space available on each sibling.
5242 **
drh8b2f49b2001-06-08 00:21:52 +00005243 */
drh43605152004-05-29 21:46:49 +00005244 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00005245 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00005246 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00005247 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00005248 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00005249 szNew[k] = subtotal - szCell[i];
5250 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00005251 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00005252 subtotal = 0;
5253 k++;
5254 }
5255 }
5256 szNew[k] = subtotal;
5257 cntNew[k] = nCell;
5258 k++;
drh96f5b762004-05-16 16:24:36 +00005259
5260 /*
5261 ** The packing computed by the previous block is biased toward the siblings
5262 ** on the left side. The left siblings are always nearly full, while the
5263 ** right-most sibling might be nearly empty. This block of code attempts
5264 ** to adjust the packing of siblings to get a better balance.
5265 **
5266 ** This adjustment is more than an optimization. The packing above might
5267 ** be so out of balance as to be illegal. For example, the right-most
5268 ** sibling might be completely empty. This adjustment is not optional.
5269 */
drh6019e162001-07-02 17:51:45 +00005270 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00005271 int szRight = szNew[i]; /* Size of sibling on the right */
5272 int szLeft = szNew[i-1]; /* Size of sibling on the left */
5273 int r; /* Index of right-most cell in left sibling */
5274 int d; /* Index of first cell to the left of right sibling */
5275
5276 r = cntNew[i-1] - 1;
5277 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00005278 assert( d<nMaxCells );
5279 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00005280 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
5281 szRight += szCell[d] + 2;
5282 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00005283 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00005284 r = cntNew[i-1] - 1;
5285 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00005286 }
drh96f5b762004-05-16 16:24:36 +00005287 szNew[i] = szRight;
5288 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00005289 }
drh09d0deb2005-08-02 17:13:09 +00005290
5291 /* Either we found one or more cells (cntnew[0])>0) or we are the
5292 ** a virtual root page. A virtual root page is when the real root
5293 ** page is page 1 and we are the only child of that page.
5294 */
5295 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00005296
5297 /*
drh6b308672002-07-08 02:16:37 +00005298 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00005299 */
drh4b70f112004-05-02 21:12:19 +00005300 assert( pPage->pgno>1 );
5301 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00005302 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00005303 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00005304 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00005305 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00005306 pgnoNew[i] = pgnoOld[i];
5307 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00005308 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00005309 nNew++;
danielk197728129562005-01-11 10:25:06 +00005310 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00005311 }else{
drh7aa8f852006-03-28 00:24:44 +00005312 assert( i>0 );
drh4f0c5872007-03-26 22:05:01 +00005313 rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
drh6b308672002-07-08 02:16:37 +00005314 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00005315 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00005316 nNew++;
drh6b308672002-07-08 02:16:37 +00005317 }
drh8b2f49b2001-06-08 00:21:52 +00005318 }
5319
danielk1977299b1872004-11-22 10:02:10 +00005320 /* Free any old pages that were not reused as new pages.
5321 */
5322 while( i<nOld ){
5323 rc = freePage(apOld[i]);
5324 if( rc ) goto balance_cleanup;
5325 releasePage(apOld[i]);
5326 apOld[i] = 0;
5327 i++;
5328 }
5329
drh8b2f49b2001-06-08 00:21:52 +00005330 /*
drhf9ffac92002-03-02 19:00:31 +00005331 ** Put the new pages in accending order. This helps to
5332 ** keep entries in the disk file in order so that a scan
5333 ** of the table is a linear scan through the file. That
5334 ** in turn helps the operating system to deliver pages
5335 ** from the disk more rapidly.
5336 **
5337 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00005338 ** n is never more than NB (a small constant), that should
5339 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00005340 **
drhc3b70572003-01-04 19:44:07 +00005341 ** When NB==3, this one optimization makes the database
5342 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00005343 */
5344 for(i=0; i<k-1; i++){
5345 int minV = pgnoNew[i];
5346 int minI = i;
5347 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00005348 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00005349 minI = j;
5350 minV = pgnoNew[j];
5351 }
5352 }
5353 if( minI>i ){
5354 int t;
5355 MemPage *pT;
5356 t = pgnoNew[i];
5357 pT = apNew[i];
5358 pgnoNew[i] = pgnoNew[minI];
5359 apNew[i] = apNew[minI];
5360 pgnoNew[minI] = t;
5361 apNew[minI] = pT;
5362 }
5363 }
drha2fce642004-06-05 00:01:44 +00005364 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00005365 pgnoOld[0],
5366 nOld>=2 ? pgnoOld[1] : 0,
5367 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00005368 pgnoNew[0], szNew[0],
5369 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
5370 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00005371 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
5372 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00005373
drhf9ffac92002-03-02 19:00:31 +00005374 /*
drh14acc042001-06-10 19:56:58 +00005375 ** Evenly distribute the data in apCell[] across the new pages.
5376 ** Insert divider cells into pParent as necessary.
5377 */
5378 j = 0;
5379 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00005380 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00005381 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00005382 assert( j<nMaxCells );
drh4b70f112004-05-02 21:12:19 +00005383 assert( pNew->pgno==pgnoNew[i] );
drh10131482008-07-11 03:34:09 +00005384 zeroPage(pNew, pageFlags);
drhfa1a98a2004-05-14 19:08:17 +00005385 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00005386 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00005387 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00005388
danielk1977ac11ee62005-01-15 12:45:51 +00005389 /* If this is an auto-vacuum database, update the pointer map entries
5390 ** that point to the siblings that were rearranged. These can be: left
5391 ** children of cells, the right-child of the page, or overflow pages
5392 ** pointed to by cells.
5393 */
danielk197785d90ca2008-07-19 14:25:15 +00005394 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005395 for(k=j; k<cntNew[i]; k++){
danielk1977634f2982005-03-28 08:44:07 +00005396 assert( k<nMaxCells );
danielk1977ac11ee62005-01-15 12:45:51 +00005397 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
danielk197779a40da2005-01-16 08:00:01 +00005398 rc = ptrmapPutOvfl(pNew, k-j);
danielk197787c52b52008-07-19 11:49:07 +00005399 if( rc==SQLITE_OK && leafCorrection==0 ){
5400 rc = ptrmapPut(pBt, get4byte(apCell[k]), PTRMAP_BTREE, pNew->pgno);
5401 }
danielk197779a40da2005-01-16 08:00:01 +00005402 if( rc!=SQLITE_OK ){
5403 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00005404 }
5405 }
5406 }
5407 }
danielk1977ac11ee62005-01-15 12:45:51 +00005408
5409 j = cntNew[i];
5410
5411 /* If the sibling page assembled above was not the right-most sibling,
5412 ** insert a divider cell into the parent page.
5413 */
drh14acc042001-06-10 19:56:58 +00005414 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00005415 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00005416 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00005417 int sz;
danielk1977634f2982005-03-28 08:44:07 +00005418
5419 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00005420 pCell = apCell[j];
5421 sz = szCell[j] + leafCorrection;
drhe5ae5732008-06-15 02:51:47 +00005422 pTemp = &aSpace2[iSpace2];
drh4b70f112004-05-02 21:12:19 +00005423 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00005424 memcpy(&pNew->aData[8], pCell, 4);
danielk197785d90ca2008-07-19 14:25:15 +00005425 if( ISAUTOVACUUM
danielk197787c52b52008-07-19 11:49:07 +00005426 && (aFrom[j]==0xFF || apCopy[aFrom[j]]->pgno!=pNew->pgno)
5427 ){
5428 rc = ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno);
5429 if( rc!=SQLITE_OK ){
5430 goto balance_cleanup;
5431 }
5432 }
drh8b18dd42004-05-12 19:18:15 +00005433 }else if( leafData ){
drhfd131da2007-08-07 17:13:03 +00005434 /* If the tree is a leaf-data tree, and the siblings are leaves,
danielk1977ac11ee62005-01-15 12:45:51 +00005435 ** then there is no divider cell in apCell[]. Instead, the divider
5436 ** cell consists of the integer key for the right-most cell of
5437 ** the sibling-page assembled above only.
5438 */
drh6f11bef2004-05-13 01:12:56 +00005439 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00005440 j--;
drh16a9b832007-05-05 18:39:25 +00005441 sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
drhe5ae5732008-06-15 02:51:47 +00005442 pCell = pTemp;
drhb026e052007-05-02 01:34:31 +00005443 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
drh8b18dd42004-05-12 19:18:15 +00005444 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00005445 }else{
5446 pCell -= 4;
danielk19774aeff622007-05-12 09:30:47 +00005447 /* Obscure case for non-leaf-data trees: If the cell at pCell was
drh85b623f2007-12-13 21:54:09 +00005448 ** previously stored on a leaf node, and its reported size was 4
danielk19774aeff622007-05-12 09:30:47 +00005449 ** bytes, then it may actually be smaller than this
5450 ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
drh85b623f2007-12-13 21:54:09 +00005451 ** any cell). But it is important to pass the correct size to
danielk19774aeff622007-05-12 09:30:47 +00005452 ** insertCell(), so reparse the cell now.
5453 **
5454 ** Note that this can never happen in an SQLite data file, as all
5455 ** cells are at least 4 bytes. It only happens in b-trees used
5456 ** to evaluate "IN (SELECT ...)" and similar clauses.
5457 */
5458 if( szCell[j]==4 ){
5459 assert(leafCorrection==4);
5460 sz = cellSizePtr(pParent, pCell);
5461 }
drh4b70f112004-05-02 21:12:19 +00005462 }
drhe5ae5732008-06-15 02:51:47 +00005463 iSpace2 += sz;
5464 assert( sz<=pBt->pageSize/4 );
5465 assert( iSpace2<=pBt->pageSize );
danielk1977a3ad5e72005-01-07 08:56:44 +00005466 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
danielk1977e80463b2004-11-03 03:01:16 +00005467 if( rc!=SQLITE_OK ) goto balance_cleanup;
drhc5053fb2008-11-27 02:22:10 +00005468 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
drh43605152004-05-29 21:46:49 +00005469 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
danielk197785d90ca2008-07-19 14:25:15 +00005470
danielk1977ac11ee62005-01-15 12:45:51 +00005471 /* If this is an auto-vacuum database, and not a leaf-data tree,
5472 ** then update the pointer map with an entry for the overflow page
5473 ** that the cell just inserted points to (if any).
5474 */
danielk197785d90ca2008-07-19 14:25:15 +00005475 if( ISAUTOVACUUM && !leafData ){
danielk197779a40da2005-01-16 08:00:01 +00005476 rc = ptrmapPutOvfl(pParent, nxDiv);
5477 if( rc!=SQLITE_OK ){
5478 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00005479 }
5480 }
drh14acc042001-06-10 19:56:58 +00005481 j++;
5482 nxDiv++;
5483 }
danielk197787c52b52008-07-19 11:49:07 +00005484
danielk197787c52b52008-07-19 11:49:07 +00005485 /* Set the pointer-map entry for the new sibling page. */
danielk197785d90ca2008-07-19 14:25:15 +00005486 if( ISAUTOVACUUM ){
danielk197787c52b52008-07-19 11:49:07 +00005487 rc = ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno);
5488 if( rc!=SQLITE_OK ){
5489 goto balance_cleanup;
5490 }
5491 }
drh14acc042001-06-10 19:56:58 +00005492 }
drh6019e162001-07-02 17:51:45 +00005493 assert( j==nCell );
drh7aa8f852006-03-28 00:24:44 +00005494 assert( nOld>0 );
5495 assert( nNew>0 );
drh4b70f112004-05-02 21:12:19 +00005496 if( (pageFlags & PTF_LEAF)==0 ){
danielk197787c52b52008-07-19 11:49:07 +00005497 u8 *zChild = &apCopy[nOld-1]->aData[8];
5498 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
danielk197785d90ca2008-07-19 14:25:15 +00005499 if( ISAUTOVACUUM ){
danielk197787c52b52008-07-19 11:49:07 +00005500 rc = ptrmapPut(pBt, get4byte(zChild), PTRMAP_BTREE, apNew[nNew-1]->pgno);
5501 if( rc!=SQLITE_OK ){
5502 goto balance_cleanup;
5503 }
5504 }
drh14acc042001-06-10 19:56:58 +00005505 }
drhc5053fb2008-11-27 02:22:10 +00005506 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
drh43605152004-05-29 21:46:49 +00005507 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00005508 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00005509 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00005510 }else{
5511 /* Right-most sibling is the left child of the first entry in pParent
5512 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00005513 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00005514 }
5515
5516 /*
drh3a4c1412004-05-09 20:40:11 +00005517 ** Balance the parent page. Note that the current page (pPage) might
danielk1977ac11ee62005-01-15 12:45:51 +00005518 ** have been added to the freelist so it might no longer be initialized.
drh3a4c1412004-05-09 20:40:11 +00005519 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00005520 */
danielk197771d5d2c2008-09-29 11:49:47 +00005521 assert( pParent->isInit );
drhfacf0302008-06-17 15:12:00 +00005522 sqlite3ScratchFree(apCell);
drhe5ae5732008-06-15 02:51:47 +00005523 apCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005524 releasePage(pPage);
5525 pCur->iPage--;
5526 rc = balance(pCur, 0);
drhda200cc2004-05-09 11:51:38 +00005527
drh8b2f49b2001-06-08 00:21:52 +00005528 /*
drh14acc042001-06-10 19:56:58 +00005529 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00005530 */
drh14acc042001-06-10 19:56:58 +00005531balance_cleanup:
drhfacf0302008-06-17 15:12:00 +00005532 sqlite3PageFree(aSpace2);
5533 sqlite3ScratchFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00005534 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00005535 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00005536 }
drh14acc042001-06-10 19:56:58 +00005537 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00005538 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00005539 }
drh9bf9e9c2008-12-05 20:01:43 +00005540 pPage->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00005541
danielk197771d5d2c2008-09-29 11:49:47 +00005542 /* releasePage(pParent); */
drh3a4c1412004-05-09 20:40:11 +00005543 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
5544 pPage->pgno, nOld, nNew, nCell));
danielk1977eaa06f62008-09-18 17:34:44 +00005545
drh8b2f49b2001-06-08 00:21:52 +00005546 return rc;
5547}
5548
5549/*
drh43605152004-05-29 21:46:49 +00005550** This routine is called for the root page of a btree when the root
5551** page contains no cells. This is an opportunity to make the tree
5552** shallower by one level.
5553*/
danielk197771d5d2c2008-09-29 11:49:47 +00005554static int balance_shallower(BtCursor *pCur){
5555 MemPage *pPage; /* Root page of B-Tree */
drh43605152004-05-29 21:46:49 +00005556 MemPage *pChild; /* The only child page of pPage */
5557 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00005558 int rc = SQLITE_OK; /* Return code from subprocedures */
danielk1977aef0bf62005-12-30 16:28:01 +00005559 BtShared *pBt; /* The main BTree structure */
drh2e38c322004-09-03 18:38:44 +00005560 int mxCellPerPage; /* Maximum number of cells per page */
5561 u8 **apCell; /* All cells from pages being balanced */
drha9121e42008-02-19 14:59:35 +00005562 u16 *szCell; /* Local size of all cells */
drh43605152004-05-29 21:46:49 +00005563
danielk197771d5d2c2008-09-29 11:49:47 +00005564 assert( pCur->iPage==0 );
5565 pPage = pCur->apPage[0];
5566
drh43605152004-05-29 21:46:49 +00005567 assert( pPage->nCell==0 );
drh1fee73e2007-08-29 04:00:57 +00005568 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh2e38c322004-09-03 18:38:44 +00005569 pBt = pPage->pBt;
5570 mxCellPerPage = MX_CELL(pBt);
drhe5ae5732008-06-15 02:51:47 +00005571 apCell = sqlite3Malloc( mxCellPerPage*(sizeof(u8*)+sizeof(u16)) );
drh2e38c322004-09-03 18:38:44 +00005572 if( apCell==0 ) return SQLITE_NOMEM;
drha9121e42008-02-19 14:59:35 +00005573 szCell = (u16*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00005574 if( pPage->leaf ){
5575 /* The table is completely empty */
5576 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
5577 }else{
5578 /* The root page is empty but has one child. Transfer the
5579 ** information from that one child into the root page if it
5580 ** will fit. This reduces the depth of the tree by one.
5581 **
5582 ** If the root page is page 1, it has less space available than
5583 ** its child (due to the 100 byte header that occurs at the beginning
5584 ** of the database fle), so it might not be able to hold all of the
5585 ** information currently contained in the child. If this is the
5586 ** case, then do not do the transfer. Leave page 1 empty except
5587 ** for the right-pointer to the child page. The child page becomes
5588 ** the virtual root of the tree.
5589 */
drhf94a1732008-09-30 17:18:17 +00005590 VVA_ONLY( pCur->pagesShuffled = 1 );
drh43605152004-05-29 21:46:49 +00005591 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5592 assert( pgnoChild>0 );
danielk197789d40042008-11-17 14:20:56 +00005593 assert( pgnoChild<=pagerPagecount(pPage->pBt) );
drh16a9b832007-05-05 18:39:25 +00005594 rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
drh2e38c322004-09-03 18:38:44 +00005595 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005596 if( pPage->pgno==1 ){
danielk197771d5d2c2008-09-29 11:49:47 +00005597 rc = sqlite3BtreeInitPage(pChild);
drh2e38c322004-09-03 18:38:44 +00005598 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005599 assert( pChild->nOverflow==0 );
5600 if( pChild->nFree>=100 ){
5601 /* The child information will fit on the root page, so do the
5602 ** copy */
5603 int i;
5604 zeroPage(pPage, pChild->aData[0]);
5605 for(i=0; i<pChild->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00005606 apCell[i] = findCell(pChild,i);
drh43605152004-05-29 21:46:49 +00005607 szCell[i] = cellSizePtr(pChild, apCell[i]);
5608 }
5609 assemblePage(pPage, pChild->nCell, apCell, szCell);
danielk1977ae825582004-11-23 09:06:55 +00005610 /* Copy the right-pointer of the child to the parent. */
drhc5053fb2008-11-27 02:22:10 +00005611 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977ae825582004-11-23 09:06:55 +00005612 put4byte(&pPage->aData[pPage->hdrOffset+8],
5613 get4byte(&pChild->aData[pChild->hdrOffset+8]));
drh9bf9e9c2008-12-05 20:01:43 +00005614 rc = freePage(pChild);
drh43605152004-05-29 21:46:49 +00005615 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
5616 }else{
5617 /* The child has more information that will fit on the root.
5618 ** The tree is already balanced. Do nothing. */
5619 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
5620 }
5621 }else{
5622 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
5623 pPage->isInit = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005624 rc = sqlite3BtreeInitPage(pPage);
drh43605152004-05-29 21:46:49 +00005625 assert( rc==SQLITE_OK );
5626 freePage(pChild);
5627 TRACE(("BALANCE: transfer child %d into root %d\n",
5628 pChild->pgno, pPage->pgno));
5629 }
danielk1977ac11ee62005-01-15 12:45:51 +00005630 assert( pPage->nOverflow==0 );
shane831c3292008-11-10 17:14:58 +00005631#ifndef SQLITE_OMIT_AUTOVACUUM
drh9bf9e9c2008-12-05 20:01:43 +00005632 if( ISAUTOVACUUM && rc==SQLITE_OK ){
danielk197700a696d2008-09-29 16:41:31 +00005633 rc = setChildPtrmaps(pPage);
danielk1977ac11ee62005-01-15 12:45:51 +00005634 }
shane831c3292008-11-10 17:14:58 +00005635#endif
drh43605152004-05-29 21:46:49 +00005636 releasePage(pChild);
5637 }
drh2e38c322004-09-03 18:38:44 +00005638end_shallow_balance:
drh17435752007-08-16 04:30:38 +00005639 sqlite3_free(apCell);
drh2e38c322004-09-03 18:38:44 +00005640 return rc;
drh43605152004-05-29 21:46:49 +00005641}
5642
5643
5644/*
5645** The root page is overfull
5646**
5647** When this happens, Create a new child page and copy the
5648** contents of the root into the child. Then make the root
5649** page an empty page with rightChild pointing to the new
5650** child. Finally, call balance_internal() on the new child
5651** to cause it to split.
5652*/
danielk197771d5d2c2008-09-29 11:49:47 +00005653static int balance_deeper(BtCursor *pCur){
drh43605152004-05-29 21:46:49 +00005654 int rc; /* Return value from subprocedures */
danielk197771d5d2c2008-09-29 11:49:47 +00005655 MemPage *pPage; /* Pointer to the root page */
drh43605152004-05-29 21:46:49 +00005656 MemPage *pChild; /* Pointer to a new child page */
5657 Pgno pgnoChild; /* Page number of the new child page */
danielk1977aef0bf62005-12-30 16:28:01 +00005658 BtShared *pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00005659 int usableSize; /* Total usable size of a page */
5660 u8 *data; /* Content of the parent page */
5661 u8 *cdata; /* Content of the child page */
5662 int hdr; /* Offset to page header in parent */
drh281b21d2008-08-22 12:57:08 +00005663 int cbrk; /* Offset to content of first cell in parent */
drh43605152004-05-29 21:46:49 +00005664
danielk197771d5d2c2008-09-29 11:49:47 +00005665 assert( pCur->iPage==0 );
5666 assert( pCur->apPage[0]->nOverflow>0 );
5667
drhf94a1732008-09-30 17:18:17 +00005668 VVA_ONLY( pCur->pagesShuffled = 1 );
danielk197771d5d2c2008-09-29 11:49:47 +00005669 pPage = pCur->apPage[0];
drh43605152004-05-29 21:46:49 +00005670 pBt = pPage->pBt;
drh1fee73e2007-08-29 04:00:57 +00005671 assert( sqlite3_mutex_held(pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00005672 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh4f0c5872007-03-26 22:05:01 +00005673 rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
drh43605152004-05-29 21:46:49 +00005674 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00005675 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
drh43605152004-05-29 21:46:49 +00005676 usableSize = pBt->usableSize;
5677 data = pPage->aData;
5678 hdr = pPage->hdrOffset;
drh281b21d2008-08-22 12:57:08 +00005679 cbrk = get2byte(&data[hdr+5]);
drh43605152004-05-29 21:46:49 +00005680 cdata = pChild->aData;
5681 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
drh281b21d2008-08-22 12:57:08 +00005682 memcpy(&cdata[cbrk], &data[cbrk], usableSize-cbrk);
danielk1977bc2ca9e2008-11-13 14:28:28 +00005683
5684 assert( pChild->isInit==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00005685 rc = sqlite3BtreeInitPage(pChild);
5686 if( rc==SQLITE_OK ){
5687 int nCopy = pPage->nOverflow*sizeof(pPage->aOvfl[0]);
5688 memcpy(pChild->aOvfl, pPage->aOvfl, nCopy);
5689 pChild->nOverflow = pPage->nOverflow;
5690 if( pChild->nOverflow ){
5691 pChild->nFree = 0;
5692 }
5693 assert( pChild->nCell==pPage->nCell );
drhc5053fb2008-11-27 02:22:10 +00005694 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00005695 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
5696 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
5697 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
5698 if( ISAUTOVACUUM ){
danielk197771d5d2c2008-09-29 11:49:47 +00005699 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
shane831c3292008-11-10 17:14:58 +00005700#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197771d5d2c2008-09-29 11:49:47 +00005701 if( rc==SQLITE_OK ){
danielk197700a696d2008-09-29 16:41:31 +00005702 rc = setChildPtrmaps(pChild);
danielk1977ac11ee62005-01-15 12:45:51 +00005703 }
shane831c3292008-11-10 17:14:58 +00005704#endif
danielk1977ac11ee62005-01-15 12:45:51 +00005705 }
danielk197787c52b52008-07-19 11:49:07 +00005706 }
danielk19776b456a22005-03-21 04:04:02 +00005707
danielk197771d5d2c2008-09-29 11:49:47 +00005708 if( rc==SQLITE_OK ){
5709 pCur->iPage++;
5710 pCur->apPage[1] = pChild;
danielk1977bf93c562008-09-29 15:53:25 +00005711 pCur->aiIdx[0] = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005712 rc = balance_nonroot(pCur);
5713 }else{
5714 releasePage(pChild);
5715 }
5716
drh43605152004-05-29 21:46:49 +00005717 return rc;
5718}
5719
5720/*
danielk197771d5d2c2008-09-29 11:49:47 +00005721** The page that pCur currently points to has just been modified in
5722** some way. This function figures out if this modification means the
5723** tree needs to be balanced, and if so calls the appropriate balancing
5724** routine.
5725**
5726** Parameter isInsert is true if a new cell was just inserted into the
5727** page, or false otherwise.
drh43605152004-05-29 21:46:49 +00005728*/
danielk197771d5d2c2008-09-29 11:49:47 +00005729static int balance(BtCursor *pCur, int isInsert){
drh43605152004-05-29 21:46:49 +00005730 int rc = SQLITE_OK;
danielk197771d5d2c2008-09-29 11:49:47 +00005731 MemPage *pPage = pCur->apPage[pCur->iPage];
5732
drh1fee73e2007-08-29 04:00:57 +00005733 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197771d5d2c2008-09-29 11:49:47 +00005734 if( pCur->iPage==0 ){
danielk19776e465eb2007-08-21 13:11:00 +00005735 rc = sqlite3PagerWrite(pPage->pDbPage);
5736 if( rc==SQLITE_OK && pPage->nOverflow>0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00005737 rc = balance_deeper(pCur);
drh9bf9e9c2008-12-05 20:01:43 +00005738 assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
drh43605152004-05-29 21:46:49 +00005739 }
danielk1977687566d2004-11-02 12:56:41 +00005740 if( rc==SQLITE_OK && pPage->nCell==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00005741 rc = balance_shallower(pCur);
drh9bf9e9c2008-12-05 20:01:43 +00005742 assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
drh43605152004-05-29 21:46:49 +00005743 }
5744 }else{
danielk1977ac245ec2005-01-14 13:50:11 +00005745 if( pPage->nOverflow>0 ||
danielk197771d5d2c2008-09-29 11:49:47 +00005746 (!isInsert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
5747 rc = balance_nonroot(pCur);
drh9bf9e9c2008-12-05 20:01:43 +00005748 assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
drh43605152004-05-29 21:46:49 +00005749 }
5750 }
5751 return rc;
5752}
5753
5754/*
drh8dcd7ca2004-08-08 19:43:29 +00005755** This routine checks all cursors that point to table pgnoRoot.
drh980b1a72006-08-16 16:42:48 +00005756** If any of those cursors were opened with wrFlag==0 in a different
5757** database connection (a database connection that shares the pager
5758** cache with the current connection) and that other connection
5759** is not in the ReadUncommmitted state, then this routine returns
5760** SQLITE_LOCKED.
danielk1977299b1872004-11-22 10:02:10 +00005761**
danielk19773588ceb2008-06-10 17:30:26 +00005762** As well as cursors with wrFlag==0, cursors with wrFlag==1 and
5763** isIncrblobHandle==1 are also considered 'read' cursors. Incremental
5764** blob cursors are used for both reading and writing.
5765**
5766** When pgnoRoot is the root page of an intkey table, this function is also
5767** responsible for invalidating incremental blob cursors when the table row
5768** on which they are opened is deleted or modified. Cursors are invalidated
5769** according to the following rules:
5770**
5771** 1) When BtreeClearTable() is called to completely delete the contents
5772** of a B-Tree table, pExclude is set to zero and parameter iRow is
5773** set to non-zero. In this case all incremental blob cursors open
5774** on the table rooted at pgnoRoot are invalidated.
5775**
5776** 2) When BtreeInsert(), BtreeDelete() or BtreePutData() is called to
5777** modify a table row via an SQL statement, pExclude is set to the
5778** write cursor used to do the modification and parameter iRow is set
5779** to the integer row id of the B-Tree entry being modified. Unless
5780** pExclude is itself an incremental blob cursor, then all incremental
5781** blob cursors open on row iRow of the B-Tree are invalidated.
5782**
5783** 3) If both pExclude and iRow are set to zero, no incremental blob
5784** cursors are invalidated.
drhf74b8d92002-09-01 23:20:45 +00005785*/
danielk19773588ceb2008-06-10 17:30:26 +00005786static int checkReadLocks(
5787 Btree *pBtree,
5788 Pgno pgnoRoot,
5789 BtCursor *pExclude,
5790 i64 iRow
5791){
danielk1977299b1872004-11-22 10:02:10 +00005792 BtCursor *p;
drh980b1a72006-08-16 16:42:48 +00005793 BtShared *pBt = pBtree->pBt;
drhe5fe6902007-12-07 18:55:28 +00005794 sqlite3 *db = pBtree->db;
drh1fee73e2007-08-29 04:00:57 +00005795 assert( sqlite3BtreeHoldsMutex(pBtree) );
danielk1977299b1872004-11-22 10:02:10 +00005796 for(p=pBt->pCursor; p; p=p->pNext){
drh980b1a72006-08-16 16:42:48 +00005797 if( p==pExclude ) continue;
drh980b1a72006-08-16 16:42:48 +00005798 if( p->pgnoRoot!=pgnoRoot ) continue;
danielk19773588ceb2008-06-10 17:30:26 +00005799#ifndef SQLITE_OMIT_INCRBLOB
5800 if( p->isIncrblobHandle && (
5801 (!pExclude && iRow)
5802 || (pExclude && !pExclude->isIncrblobHandle && p->info.nKey==iRow)
5803 )){
5804 p->eState = CURSOR_INVALID;
5805 }
5806#endif
5807 if( p->eState!=CURSOR_VALID ) continue;
5808 if( p->wrFlag==0
5809#ifndef SQLITE_OMIT_INCRBLOB
5810 || p->isIncrblobHandle
5811#endif
5812 ){
drhe5fe6902007-12-07 18:55:28 +00005813 sqlite3 *dbOther = p->pBtree->db;
drh980b1a72006-08-16 16:42:48 +00005814 if( dbOther==0 ||
5815 (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
5816 return SQLITE_LOCKED;
5817 }
danielk1977299b1872004-11-22 10:02:10 +00005818 }
5819 }
drhf74b8d92002-09-01 23:20:45 +00005820 return SQLITE_OK;
5821}
5822
5823/*
drh3b7511c2001-05-26 13:15:44 +00005824** Insert a new record into the BTree. The key is given by (pKey,nKey)
5825** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00005826** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00005827** is left pointing at a random location.
5828**
5829** For an INTKEY table, only the nKey value of the key is used. pKey is
5830** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00005831*/
drh3aac2dd2004-04-26 14:10:20 +00005832int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00005833 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00005834 const void *pKey, i64 nKey, /* The key of the new record */
drhe4d90812007-03-29 05:51:49 +00005835 const void *pData, int nData, /* The data of the new record */
drhb026e052007-05-02 01:34:31 +00005836 int nZero, /* Number of extra 0 bytes to append to data */
drhe4d90812007-03-29 05:51:49 +00005837 int appendBias /* True if this is likely an append */
drh3b7511c2001-05-26 13:15:44 +00005838){
drh3b7511c2001-05-26 13:15:44 +00005839 int rc;
5840 int loc;
drh14acc042001-06-10 19:56:58 +00005841 int szNew;
danielk197771d5d2c2008-09-29 11:49:47 +00005842 int idx;
drh3b7511c2001-05-26 13:15:44 +00005843 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00005844 Btree *p = pCur->pBtree;
5845 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00005846 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00005847 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00005848
drh1fee73e2007-08-29 04:00:57 +00005849 assert( cursorHoldsMutex(pCur) );
danielk1977aef0bf62005-12-30 16:28:01 +00005850 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005851 /* Must start a transaction before doing an insert */
drhd677b3d2007-08-20 22:48:41 +00005852 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drhd677b3d2007-08-20 22:48:41 +00005853 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005854 }
drhf74b8d92002-09-01 23:20:45 +00005855 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00005856 if( !pCur->wrFlag ){
5857 return SQLITE_PERM; /* Cursor not open for writing */
5858 }
danielk19773588ceb2008-06-10 17:30:26 +00005859 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, nKey) ){
drhf74b8d92002-09-01 23:20:45 +00005860 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5861 }
drhfb982642007-08-30 01:19:59 +00005862 if( pCur->eState==CURSOR_FAULT ){
5863 return pCur->skip;
5864 }
danielk1977da184232006-01-05 11:34:32 +00005865
5866 /* Save the positions of any other cursors open on this table */
danielk1977be51a652008-10-08 17:58:48 +00005867 sqlite3BtreeClearCursor(pCur);
danielk19772e94d4d2006-01-09 05:36:27 +00005868 if(
danielk19772e94d4d2006-01-09 05:36:27 +00005869 SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
drhe63d9992008-08-13 19:11:48 +00005870 SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
danielk19772e94d4d2006-01-09 05:36:27 +00005871 ){
danielk1977da184232006-01-05 11:34:32 +00005872 return rc;
5873 }
5874
danielk197771d5d2c2008-09-29 11:49:47 +00005875 pPage = pCur->apPage[pCur->iPage];
drh4a1c3802004-05-12 15:15:47 +00005876 assert( pPage->intKey || nKey>=0 );
drh44845222008-07-17 18:39:57 +00005877 assert( pPage->leaf || !pPage->intKey );
drh3a4c1412004-05-09 20:40:11 +00005878 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
5879 pCur->pgnoRoot, nKey, nData, pPage->pgno,
5880 loc==0 ? "overwrite" : "new entry"));
danielk197771d5d2c2008-09-29 11:49:47 +00005881 assert( pPage->isInit );
danielk197752ae7242008-03-25 14:24:56 +00005882 allocateTempSpace(pBt);
5883 newCell = pBt->pTmpSpace;
drh2e38c322004-09-03 18:38:44 +00005884 if( newCell==0 ) return SQLITE_NOMEM;
drhb026e052007-05-02 01:34:31 +00005885 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
drh2e38c322004-09-03 18:38:44 +00005886 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00005887 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00005888 assert( szNew<=MX_CELL_SIZE(pBt) );
danielk197771d5d2c2008-09-29 11:49:47 +00005889 idx = pCur->aiIdx[pCur->iPage];
danielk1977da184232006-01-05 11:34:32 +00005890 if( loc==0 && CURSOR_VALID==pCur->eState ){
drha9121e42008-02-19 14:59:35 +00005891 u16 szOld;
danielk197771d5d2c2008-09-29 11:49:47 +00005892 assert( idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00005893 rc = sqlite3PagerWrite(pPage->pDbPage);
5894 if( rc ){
5895 goto end_insert;
5896 }
danielk197771d5d2c2008-09-29 11:49:47 +00005897 oldCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00005898 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005899 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00005900 }
drh43605152004-05-29 21:46:49 +00005901 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00005902 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00005903 if( rc ) goto end_insert;
shane0af3f892008-11-12 04:55:34 +00005904 rc = dropCell(pPage, idx, szOld);
5905 if( rc!=SQLITE_OK ) {
5906 goto end_insert;
5907 }
drh7c717f72001-06-24 20:39:41 +00005908 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00005909 assert( pPage->leaf );
danielk197771d5d2c2008-09-29 11:49:47 +00005910 idx = ++pCur->aiIdx[pCur->iPage];
drh271efa52004-05-30 19:19:05 +00005911 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00005912 pCur->validNKey = 0;
drh14acc042001-06-10 19:56:58 +00005913 }else{
drh4b70f112004-05-02 21:12:19 +00005914 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00005915 }
danielk197771d5d2c2008-09-29 11:49:47 +00005916 rc = insertCell(pPage, idx, newCell, szNew, 0, 0);
drh9bf9e9c2008-12-05 20:01:43 +00005917 if( rc==SQLITE_OK ){
5918 rc = balance(pCur, 1);
5919 }
5920
5921 /* Must make sure nOverflow is reset to zero even if the balance()
5922 ** fails. Internal data structure corruption will result otherwise. */
5923 assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
5924 pPage->nOverflow = 0;
5925
danielk1977299b1872004-11-22 10:02:10 +00005926 if( rc==SQLITE_OK ){
5927 moveToRoot(pCur);
5928 }
drh2e38c322004-09-03 18:38:44 +00005929end_insert:
drh5e2f8b92001-05-28 00:41:15 +00005930 return rc;
5931}
5932
5933/*
drh4b70f112004-05-02 21:12:19 +00005934** Delete the entry that the cursor is pointing to. The cursor
drhf94a1732008-09-30 17:18:17 +00005935** is left pointing at a arbitrary location.
drh3b7511c2001-05-26 13:15:44 +00005936*/
drh3aac2dd2004-04-26 14:10:20 +00005937int sqlite3BtreeDelete(BtCursor *pCur){
danielk197771d5d2c2008-09-29 11:49:47 +00005938 MemPage *pPage = pCur->apPage[pCur->iPage];
5939 int idx;
drh4b70f112004-05-02 21:12:19 +00005940 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00005941 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00005942 Pgno pgnoChild = 0;
drhd677b3d2007-08-20 22:48:41 +00005943 Btree *p = pCur->pBtree;
5944 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005945
drh1fee73e2007-08-29 04:00:57 +00005946 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00005947 assert( pPage->isInit );
danielk1977aef0bf62005-12-30 16:28:01 +00005948 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005949 /* Must start a transaction before doing a delete */
drhd677b3d2007-08-20 22:48:41 +00005950 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drhd677b3d2007-08-20 22:48:41 +00005951 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005952 }
drhf74b8d92002-09-01 23:20:45 +00005953 assert( !pBt->readOnly );
drhfb982642007-08-30 01:19:59 +00005954 if( pCur->eState==CURSOR_FAULT ){
5955 return pCur->skip;
5956 }
danielk197771d5d2c2008-09-29 11:49:47 +00005957 if( pCur->aiIdx[pCur->iPage]>=pPage->nCell ){
drhbd03cae2001-06-02 02:40:57 +00005958 return SQLITE_ERROR; /* The cursor is not pointing to anything */
5959 }
drhecdc7532001-09-23 02:35:53 +00005960 if( !pCur->wrFlag ){
5961 return SQLITE_PERM; /* Did not open this cursor for writing */
5962 }
danielk19773588ceb2008-06-10 17:30:26 +00005963 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, pCur->info.nKey) ){
drhf74b8d92002-09-01 23:20:45 +00005964 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5965 }
danielk1977da184232006-01-05 11:34:32 +00005966
5967 /* Restore the current cursor position (a no-op if the cursor is not in
5968 ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors
danielk19773b8a05f2007-03-19 17:44:26 +00005969 ** open on the same table. Then call sqlite3PagerWrite() on the page
danielk1977da184232006-01-05 11:34:32 +00005970 ** that the entry will be deleted from.
5971 */
5972 if(
drha3460582008-07-11 21:02:53 +00005973 (rc = restoreCursorPosition(pCur))!=0 ||
drhd1167392006-01-23 13:00:35 +00005974 (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
danielk19773b8a05f2007-03-19 17:44:26 +00005975 (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
danielk1977da184232006-01-05 11:34:32 +00005976 ){
5977 return rc;
5978 }
danielk1977e6efa742004-11-10 11:55:10 +00005979
drh85b623f2007-12-13 21:54:09 +00005980 /* Locate the cell within its page and leave pCell pointing to the
danielk1977e6efa742004-11-10 11:55:10 +00005981 ** data. The clearCell() call frees any overflow pages associated with the
5982 ** cell. The cell itself is still intact.
5983 */
danielk197771d5d2c2008-09-29 11:49:47 +00005984 idx = pCur->aiIdx[pCur->iPage];
5985 pCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00005986 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005987 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005988 }
danielk197728129562005-01-11 10:25:06 +00005989 rc = clearCell(pPage, pCell);
drhd677b3d2007-08-20 22:48:41 +00005990 if( rc ){
drhd677b3d2007-08-20 22:48:41 +00005991 return rc;
5992 }
danielk1977e6efa742004-11-10 11:55:10 +00005993
drh4b70f112004-05-02 21:12:19 +00005994 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00005995 /*
drh5e00f6c2001-09-13 13:46:56 +00005996 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00005997 ** do something we will leave a hole on an internal page.
5998 ** We have to fill the hole by moving in a cell from a leaf. The
5999 ** next Cell after the one to be deleted is guaranteed to exist and
danielk1977299b1872004-11-22 10:02:10 +00006000 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00006001 */
drh14acc042001-06-10 19:56:58 +00006002 BtCursor leafCur;
danielk197771d5d2c2008-09-29 11:49:47 +00006003 MemPage *pLeafPage;
danielk197771d5d2c2008-09-29 11:49:47 +00006004
drh4b70f112004-05-02 21:12:19 +00006005 unsigned char *pNext;
danielk1977299b1872004-11-22 10:02:10 +00006006 int notUsed;
danielk19776b456a22005-03-21 04:04:02 +00006007 unsigned char *tempCell = 0;
drh44845222008-07-17 18:39:57 +00006008 assert( !pPage->intKey );
drh16a9b832007-05-05 18:39:25 +00006009 sqlite3BtreeGetTempCursor(pCur, &leafCur);
danielk1977299b1872004-11-22 10:02:10 +00006010 rc = sqlite3BtreeNext(&leafCur, &notUsed);
danielk19776b456a22005-03-21 04:04:02 +00006011 if( rc==SQLITE_OK ){
danielk19772f78fc62008-09-30 09:31:45 +00006012 assert( leafCur.aiIdx[leafCur.iPage]==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00006013 pLeafPage = leafCur.apPage[leafCur.iPage];
danielk197771d5d2c2008-09-29 11:49:47 +00006014 rc = sqlite3PagerWrite(pLeafPage->pDbPage);
danielk19776b456a22005-03-21 04:04:02 +00006015 }
6016 if( rc==SQLITE_OK ){
danielk19772f78fc62008-09-30 09:31:45 +00006017 int leafCursorInvalid = 0;
drha9121e42008-02-19 14:59:35 +00006018 u16 szNext;
danielk19776b456a22005-03-21 04:04:02 +00006019 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
danielk197771d5d2c2008-09-29 11:49:47 +00006020 pCur->pgnoRoot, pPage->pgno, pLeafPage->pgno));
6021 dropCell(pPage, idx, cellSizePtr(pPage, pCell));
danielk19772f78fc62008-09-30 09:31:45 +00006022 pNext = findCell(pLeafPage, 0);
danielk197771d5d2c2008-09-29 11:49:47 +00006023 szNext = cellSizePtr(pLeafPage, pNext);
danielk19776b456a22005-03-21 04:04:02 +00006024 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
danielk197752ae7242008-03-25 14:24:56 +00006025 allocateTempSpace(pBt);
6026 tempCell = pBt->pTmpSpace;
danielk19776b456a22005-03-21 04:04:02 +00006027 if( tempCell==0 ){
6028 rc = SQLITE_NOMEM;
6029 }
danielk19778ea1cfa2008-01-01 06:19:02 +00006030 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00006031 rc = insertCell(pPage, idx, pNext-4, szNext+4, tempCell, 0);
danielk19778ea1cfa2008-01-01 06:19:02 +00006032 }
danielk19772f78fc62008-09-30 09:31:45 +00006033
drhf94a1732008-09-30 17:18:17 +00006034
6035 /* The "if" statement in the next code block is critical. The
6036 ** slightest error in that statement would allow SQLite to operate
6037 ** correctly most of the time but produce very rare failures. To
6038 ** guard against this, the following macros help to verify that
6039 ** the "if" statement is well tested.
6040 */
6041 testcase( pPage->nOverflow==0 && pPage->nFree<pBt->usableSize*2/3
6042 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6043 testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3
6044 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6045 testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3+1
6046 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6047 testcase( pPage->nOverflow>0 && pPage->nFree<=pBt->usableSize*2/3
6048 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6049 testcase( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3))
6050 && pLeafPage->nFree+2+szNext == pBt->usableSize*2/3 );
6051
6052
danielk19772f78fc62008-09-30 09:31:45 +00006053 if( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3)) &&
6054 (pLeafPage->nFree+2+szNext > pBt->usableSize*2/3)
6055 ){
drhf94a1732008-09-30 17:18:17 +00006056 /* This branch is taken if the internal node is now either overflowing
6057 ** or underfull and the leaf node will be underfull after the just cell
danielk19772f78fc62008-09-30 09:31:45 +00006058 ** copied to the internal node is deleted from it. This is a special
6059 ** case because the call to balance() to correct the internal node
6060 ** may change the tree structure and invalidate the contents of
6061 ** the leafCur.apPage[] and leafCur.aiIdx[] arrays, which will be
6062 ** used by the balance() required to correct the underfull leaf
6063 ** node.
6064 **
6065 ** The formula used in the expression above are based on facets of
6066 ** the SQLite file-format that do not change over time.
6067 */
drhf94a1732008-09-30 17:18:17 +00006068 testcase( pPage->nFree==pBt->usableSize*2/3+1 );
6069 testcase( pLeafPage->nFree+2+szNext==pBt->usableSize*2/3+1 );
danielk19772f78fc62008-09-30 09:31:45 +00006070 leafCursorInvalid = 1;
6071 }
6072
danielk19778ea1cfa2008-01-01 06:19:02 +00006073 if( rc==SQLITE_OK ){
drhc5053fb2008-11-27 02:22:10 +00006074 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00006075 put4byte(findOverflowCell(pPage, idx), pgnoChild);
drhf94a1732008-09-30 17:18:17 +00006076 VVA_ONLY( pCur->pagesShuffled = 0 );
danielk197771d5d2c2008-09-29 11:49:47 +00006077 rc = balance(pCur, 0);
danielk19778ea1cfa2008-01-01 06:19:02 +00006078 }
danielk19772f78fc62008-09-30 09:31:45 +00006079
6080 if( rc==SQLITE_OK && leafCursorInvalid ){
6081 /* The leaf-node is now underfull and so the tree needs to be
6082 ** rebalanced. However, the balance() operation on the internal
6083 ** node above may have modified the structure of the B-Tree and
6084 ** so the current contents of leafCur.apPage[] and leafCur.aiIdx[]
6085 ** may not be trusted.
6086 **
6087 ** It is not possible to copy the ancestry from pCur, as the same
6088 ** balance() call has invalidated the pCur->apPage[] and aiIdx[]
6089 ** arrays.
drh7b682802008-09-30 14:06:28 +00006090 **
6091 ** The call to saveCursorPosition() below internally saves the
6092 ** key that leafCur is currently pointing to. Currently, there
6093 ** are two copies of that key in the tree - one here on the leaf
6094 ** page and one on some internal node in the tree. The copy on
6095 ** the leaf node is always the next key in tree-order after the
6096 ** copy on the internal node. So, the call to sqlite3BtreeNext()
6097 ** calls restoreCursorPosition() to point the cursor to the copy
6098 ** stored on the internal node, then advances to the next entry,
6099 ** which happens to be the copy of the key on the internal node.
danielk1977a69fda22008-09-30 16:48:10 +00006100 ** Net effect: leafCur is pointing back to the duplicate cell
6101 ** that needs to be removed, and the leafCur.apPage[] and
6102 ** leafCur.aiIdx[] arrays are correct.
danielk19772f78fc62008-09-30 09:31:45 +00006103 */
drhf94a1732008-09-30 17:18:17 +00006104 VVA_ONLY( Pgno leafPgno = pLeafPage->pgno );
danielk19772f78fc62008-09-30 09:31:45 +00006105 rc = saveCursorPosition(&leafCur);
6106 if( rc==SQLITE_OK ){
6107 rc = sqlite3BtreeNext(&leafCur, &notUsed);
6108 }
6109 pLeafPage = leafCur.apPage[leafCur.iPage];
6110 assert( pLeafPage->pgno==leafPgno );
6111 assert( leafCur.aiIdx[leafCur.iPage]==0 );
6112 }
6113
danielk19770cd1bbd2008-11-26 07:25:52 +00006114 if( SQLITE_OK==rc
6115 && SQLITE_OK==(rc = sqlite3PagerWrite(pLeafPage->pDbPage))
6116 ){
danielk19772f78fc62008-09-30 09:31:45 +00006117 dropCell(pLeafPage, 0, szNext);
drhf94a1732008-09-30 17:18:17 +00006118 VVA_ONLY( leafCur.pagesShuffled = 0 );
danielk197771d5d2c2008-09-29 11:49:47 +00006119 rc = balance(&leafCur, 0);
drhf94a1732008-09-30 17:18:17 +00006120 assert( leafCursorInvalid || !leafCur.pagesShuffled
6121 || !pCur->pagesShuffled );
danielk19778ea1cfa2008-01-01 06:19:02 +00006122 }
danielk19776b456a22005-03-21 04:04:02 +00006123 }
drh16a9b832007-05-05 18:39:25 +00006124 sqlite3BtreeReleaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00006125 }else{
danielk1977299b1872004-11-22 10:02:10 +00006126 TRACE(("DELETE: table=%d delete from leaf %d\n",
6127 pCur->pgnoRoot, pPage->pgno));
shanedcc50b72008-11-13 18:29:50 +00006128 rc = dropCell(pPage, idx, cellSizePtr(pPage, pCell));
6129 if( rc==SQLITE_OK ){
6130 rc = balance(pCur, 0);
6131 }
drh5e2f8b92001-05-28 00:41:15 +00006132 }
danielk19776b456a22005-03-21 04:04:02 +00006133 if( rc==SQLITE_OK ){
6134 moveToRoot(pCur);
6135 }
drh5e2f8b92001-05-28 00:41:15 +00006136 return rc;
drh3b7511c2001-05-26 13:15:44 +00006137}
drh8b2f49b2001-06-08 00:21:52 +00006138
6139/*
drhc6b52df2002-01-04 03:09:29 +00006140** Create a new BTree table. Write into *piTable the page
6141** number for the root page of the new table.
6142**
drhab01f612004-05-22 02:55:23 +00006143** The type of type is determined by the flags parameter. Only the
6144** following values of flags are currently in use. Other values for
6145** flags might not work:
6146**
6147** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
6148** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00006149*/
drhd677b3d2007-08-20 22:48:41 +00006150static int btreeCreateTable(Btree *p, int *piTable, int flags){
danielk1977aef0bf62005-12-30 16:28:01 +00006151 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006152 MemPage *pRoot;
6153 Pgno pgnoRoot;
6154 int rc;
drhd677b3d2007-08-20 22:48:41 +00006155
drh1fee73e2007-08-29 04:00:57 +00006156 assert( sqlite3BtreeHoldsMutex(p) );
danielk1977aef0bf62005-12-30 16:28:01 +00006157 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00006158 /* Must start a transaction first */
drhd677b3d2007-08-20 22:48:41 +00006159 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
6160 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006161 }
danielk197728129562005-01-11 10:25:06 +00006162 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00006163
danielk1977003ba062004-11-04 02:57:33 +00006164#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00006165 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00006166 if( rc ){
6167 return rc;
6168 }
danielk1977003ba062004-11-04 02:57:33 +00006169#else
danielk1977687566d2004-11-02 12:56:41 +00006170 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00006171 Pgno pgnoMove; /* Move a page here to make room for the root-page */
6172 MemPage *pPageMove; /* The page to move to. */
6173
danielk197720713f32007-05-03 11:43:33 +00006174 /* Creating a new table may probably require moving an existing database
6175 ** to make room for the new tables root page. In case this page turns
6176 ** out to be an overflow page, delete all overflow page-map caches
6177 ** held by open cursors.
6178 */
danielk197792d4d7a2007-05-04 12:05:56 +00006179 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00006180
danielk1977003ba062004-11-04 02:57:33 +00006181 /* Read the value of meta[3] from the database to determine where the
6182 ** root page of the new table should go. meta[3] is the largest root-page
6183 ** created so far, so the new root-page is (meta[3]+1).
6184 */
danielk1977aef0bf62005-12-30 16:28:01 +00006185 rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
drhd677b3d2007-08-20 22:48:41 +00006186 if( rc!=SQLITE_OK ){
6187 return rc;
6188 }
danielk1977003ba062004-11-04 02:57:33 +00006189 pgnoRoot++;
6190
danielk1977599fcba2004-11-08 07:13:13 +00006191 /* The new root-page may not be allocated on a pointer-map page, or the
6192 ** PENDING_BYTE page.
6193 */
drh72190432008-01-31 14:54:43 +00006194 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00006195 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00006196 pgnoRoot++;
6197 }
6198 assert( pgnoRoot>=3 );
6199
6200 /* Allocate a page. The page that currently resides at pgnoRoot will
6201 ** be moved to the allocated page (unless the allocated page happens
6202 ** to reside at pgnoRoot).
6203 */
drh4f0c5872007-03-26 22:05:01 +00006204 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00006205 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00006206 return rc;
6207 }
danielk1977003ba062004-11-04 02:57:33 +00006208
6209 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00006210 /* pgnoRoot is the page that will be used for the root-page of
6211 ** the new table (assuming an error did not occur). But we were
6212 ** allocated pgnoMove. If required (i.e. if it was not allocated
6213 ** by extending the file), the current page at position pgnoMove
6214 ** is already journaled.
6215 */
danielk1977003ba062004-11-04 02:57:33 +00006216 u8 eType;
6217 Pgno iPtrPage;
6218
6219 releasePage(pPageMove);
danielk1977f35843b2007-04-07 15:03:17 +00006220
6221 /* Move the page currently at pgnoRoot to pgnoMove. */
drh16a9b832007-05-05 18:39:25 +00006222 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006223 if( rc!=SQLITE_OK ){
6224 return rc;
6225 }
6226 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drhccae6022005-02-26 17:31:26 +00006227 if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00006228 releasePage(pRoot);
6229 return rc;
6230 }
drhccae6022005-02-26 17:31:26 +00006231 assert( eType!=PTRMAP_ROOTPAGE );
6232 assert( eType!=PTRMAP_FREEPAGE );
danielk19773b8a05f2007-03-19 17:44:26 +00006233 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk19775fd057a2005-03-09 13:09:43 +00006234 if( rc!=SQLITE_OK ){
6235 releasePage(pRoot);
6236 return rc;
6237 }
danielk19774c999992008-07-16 18:17:55 +00006238 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
danielk1977003ba062004-11-04 02:57:33 +00006239 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00006240
6241 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00006242 if( rc!=SQLITE_OK ){
6243 return rc;
6244 }
drh16a9b832007-05-05 18:39:25 +00006245 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006246 if( rc!=SQLITE_OK ){
6247 return rc;
6248 }
danielk19773b8a05f2007-03-19 17:44:26 +00006249 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00006250 if( rc!=SQLITE_OK ){
6251 releasePage(pRoot);
6252 return rc;
6253 }
6254 }else{
6255 pRoot = pPageMove;
6256 }
6257
danielk197742741be2005-01-08 12:42:39 +00006258 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00006259 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
6260 if( rc ){
6261 releasePage(pRoot);
6262 return rc;
6263 }
danielk1977aef0bf62005-12-30 16:28:01 +00006264 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00006265 if( rc ){
6266 releasePage(pRoot);
6267 return rc;
6268 }
danielk197742741be2005-01-08 12:42:39 +00006269
danielk1977003ba062004-11-04 02:57:33 +00006270 }else{
drh4f0c5872007-03-26 22:05:01 +00006271 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00006272 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00006273 }
6274#endif
danielk19773b8a05f2007-03-19 17:44:26 +00006275 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhde647132004-05-07 17:57:49 +00006276 zeroPage(pRoot, flags | PTF_LEAF);
danielk19773b8a05f2007-03-19 17:44:26 +00006277 sqlite3PagerUnref(pRoot->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00006278 *piTable = (int)pgnoRoot;
6279 return SQLITE_OK;
6280}
drhd677b3d2007-08-20 22:48:41 +00006281int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
6282 int rc;
6283 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006284 p->pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006285 rc = btreeCreateTable(p, piTable, flags);
6286 sqlite3BtreeLeave(p);
6287 return rc;
6288}
drh8b2f49b2001-06-08 00:21:52 +00006289
6290/*
6291** Erase the given database page and all its children. Return
6292** the page to the freelist.
6293*/
drh4b70f112004-05-02 21:12:19 +00006294static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00006295 BtShared *pBt, /* The BTree that contains the table */
drh4b70f112004-05-02 21:12:19 +00006296 Pgno pgno, /* Page number to clear */
danielk1977c7af4842008-10-27 13:59:33 +00006297 int freePageFlag, /* Deallocate page if true */
6298 int *pnChange
drh4b70f112004-05-02 21:12:19 +00006299){
danielk19776b456a22005-03-21 04:04:02 +00006300 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00006301 int rc;
drh4b70f112004-05-02 21:12:19 +00006302 unsigned char *pCell;
6303 int i;
drh8b2f49b2001-06-08 00:21:52 +00006304
drh1fee73e2007-08-29 04:00:57 +00006305 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197789d40042008-11-17 14:20:56 +00006306 if( pgno>pagerPagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00006307 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00006308 }
6309
danielk197771d5d2c2008-09-29 11:49:47 +00006310 rc = getAndInitPage(pBt, pgno, &pPage);
danielk19776b456a22005-03-21 04:04:02 +00006311 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00006312 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00006313 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00006314 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00006315 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00006316 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006317 }
drh4b70f112004-05-02 21:12:19 +00006318 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00006319 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006320 }
drha34b6762004-05-07 13:30:42 +00006321 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00006322 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00006323 if( rc ) goto cleardatabasepage_out;
danielk1977c7af4842008-10-27 13:59:33 +00006324 }else if( pnChange ){
6325 assert( pPage->intKey );
6326 *pnChange += pPage->nCell;
drh2aa679f2001-06-25 02:11:07 +00006327 }
6328 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00006329 rc = freePage(pPage);
danielk19773b8a05f2007-03-19 17:44:26 +00006330 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
drh3a4c1412004-05-09 20:40:11 +00006331 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00006332 }
danielk19776b456a22005-03-21 04:04:02 +00006333
6334cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00006335 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00006336 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006337}
6338
6339/*
drhab01f612004-05-22 02:55:23 +00006340** Delete all information from a single table in the database. iTable is
6341** the page number of the root of the table. After this routine returns,
6342** the root page is empty, but still exists.
6343**
6344** This routine will fail with SQLITE_LOCKED if there are any open
6345** read cursors on the table. Open write cursors are moved to the
6346** root of the table.
danielk1977c7af4842008-10-27 13:59:33 +00006347**
6348** If pnChange is not NULL, then table iTable must be an intkey table. The
6349** integer value pointed to by pnChange is incremented by the number of
6350** entries in the table.
drh8b2f49b2001-06-08 00:21:52 +00006351*/
danielk1977c7af4842008-10-27 13:59:33 +00006352int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
drh8b2f49b2001-06-08 00:21:52 +00006353 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00006354 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00006355 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006356 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00006357 if( p->inTrans!=TRANS_WRITE ){
drhd677b3d2007-08-20 22:48:41 +00006358 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
danielk19773588ceb2008-06-10 17:30:26 +00006359 }else if( (rc = checkReadLocks(p, iTable, 0, 1))!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00006360 /* nothing to do */
6361 }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
6362 /* nothing to do */
6363 }else{
danielk197762c14b32008-11-19 09:05:26 +00006364 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
drh8b2f49b2001-06-08 00:21:52 +00006365 }
drhd677b3d2007-08-20 22:48:41 +00006366 sqlite3BtreeLeave(p);
6367 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006368}
6369
6370/*
6371** Erase all information in a table and add the root of the table to
6372** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00006373** page 1) is never added to the freelist.
6374**
6375** This routine will fail with SQLITE_LOCKED if there are any open
6376** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00006377**
6378** If AUTOVACUUM is enabled and the page at iTable is not the last
6379** root page in the database file, then the last root page
6380** in the database file is moved into the slot formerly occupied by
6381** iTable and that last slot formerly occupied by the last root page
6382** is added to the freelist instead of iTable. In this say, all
6383** root pages are kept at the beginning of the database file, which
6384** is necessary for AUTOVACUUM to work right. *piMoved is set to the
6385** page number that used to be the last root page in the file before
6386** the move. If no page gets moved, *piMoved is set to 0.
6387** The last root page is recorded in meta[3] and the value of
6388** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00006389*/
danielk197789d40042008-11-17 14:20:56 +00006390static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00006391 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00006392 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00006393 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00006394
drh1fee73e2007-08-29 04:00:57 +00006395 assert( sqlite3BtreeHoldsMutex(p) );
danielk1977aef0bf62005-12-30 16:28:01 +00006396 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00006397 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00006398 }
danielk1977a0bf2652004-11-04 14:30:04 +00006399
danielk1977e6efa742004-11-10 11:55:10 +00006400 /* It is illegal to drop a table if any cursors are open on the
6401 ** database. This is because in auto-vacuum mode the backend may
6402 ** need to move another root-page to fill a gap left by the deleted
6403 ** root page. If an open cursor was using this page a problem would
6404 ** occur.
6405 */
6406 if( pBt->pCursor ){
6407 return SQLITE_LOCKED;
drh5df72a52002-06-06 23:16:05 +00006408 }
danielk1977a0bf2652004-11-04 14:30:04 +00006409
drh16a9b832007-05-05 18:39:25 +00006410 rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00006411 if( rc ) return rc;
danielk1977c7af4842008-10-27 13:59:33 +00006412 rc = sqlite3BtreeClearTable(p, iTable, 0);
danielk19776b456a22005-03-21 04:04:02 +00006413 if( rc ){
6414 releasePage(pPage);
6415 return rc;
6416 }
danielk1977a0bf2652004-11-04 14:30:04 +00006417
drh205f48e2004-11-05 00:43:11 +00006418 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00006419
drh4b70f112004-05-02 21:12:19 +00006420 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00006421#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00006422 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00006423 releasePage(pPage);
6424#else
6425 if( pBt->autoVacuum ){
6426 Pgno maxRootPgno;
danielk1977aef0bf62005-12-30 16:28:01 +00006427 rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006428 if( rc!=SQLITE_OK ){
6429 releasePage(pPage);
6430 return rc;
6431 }
6432
6433 if( iTable==maxRootPgno ){
6434 /* If the table being dropped is the table with the largest root-page
6435 ** number in the database, put the root page on the free list.
6436 */
6437 rc = freePage(pPage);
6438 releasePage(pPage);
6439 if( rc!=SQLITE_OK ){
6440 return rc;
6441 }
6442 }else{
6443 /* The table being dropped does not have the largest root-page
6444 ** number in the database. So move the page that does into the
6445 ** gap left by the deleted root-page.
6446 */
6447 MemPage *pMove;
6448 releasePage(pPage);
drh16a9b832007-05-05 18:39:25 +00006449 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006450 if( rc!=SQLITE_OK ){
6451 return rc;
6452 }
danielk19774c999992008-07-16 18:17:55 +00006453 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006454 releasePage(pMove);
6455 if( rc!=SQLITE_OK ){
6456 return rc;
6457 }
drh16a9b832007-05-05 18:39:25 +00006458 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006459 if( rc!=SQLITE_OK ){
6460 return rc;
6461 }
6462 rc = freePage(pMove);
6463 releasePage(pMove);
6464 if( rc!=SQLITE_OK ){
6465 return rc;
6466 }
6467 *piMoved = maxRootPgno;
6468 }
6469
danielk1977599fcba2004-11-08 07:13:13 +00006470 /* Set the new 'max-root-page' value in the database header. This
6471 ** is the old value less one, less one more if that happens to
6472 ** be a root-page number, less one again if that is the
6473 ** PENDING_BYTE_PAGE.
6474 */
danielk197787a6e732004-11-05 12:58:25 +00006475 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00006476 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
6477 maxRootPgno--;
6478 }
danielk1977266664d2006-02-10 08:24:21 +00006479 if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00006480 maxRootPgno--;
6481 }
danielk1977599fcba2004-11-08 07:13:13 +00006482 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
6483
danielk1977aef0bf62005-12-30 16:28:01 +00006484 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006485 }else{
6486 rc = freePage(pPage);
6487 releasePage(pPage);
6488 }
6489#endif
drh2aa679f2001-06-25 02:11:07 +00006490 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00006491 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00006492 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00006493 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00006494 }
drh8b2f49b2001-06-08 00:21:52 +00006495 return rc;
6496}
drhd677b3d2007-08-20 22:48:41 +00006497int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
6498 int rc;
6499 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006500 p->pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006501 rc = btreeDropTable(p, iTable, piMoved);
6502 sqlite3BtreeLeave(p);
6503 return rc;
6504}
drh8b2f49b2001-06-08 00:21:52 +00006505
drh001bbcb2003-03-19 03:14:00 +00006506
drh8b2f49b2001-06-08 00:21:52 +00006507/*
drh23e11ca2004-05-04 17:27:28 +00006508** Read the meta-information out of a database file. Meta[0]
6509** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00006510** through meta[15] are available for use by higher layers. Meta[0]
6511** is read-only, the others are read/write.
6512**
6513** The schema layer numbers meta values differently. At the schema
6514** layer (and the SetCookie and ReadCookie opcodes) the number of
6515** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00006516*/
danielk1977aef0bf62005-12-30 16:28:01 +00006517int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
danielk19773b8a05f2007-03-19 17:44:26 +00006518 DbPage *pDbPage;
drh8b2f49b2001-06-08 00:21:52 +00006519 int rc;
drh4b70f112004-05-02 21:12:19 +00006520 unsigned char *pP1;
danielk1977aef0bf62005-12-30 16:28:01 +00006521 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006522
drhd677b3d2007-08-20 22:48:41 +00006523 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006524 pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006525
danielk1977da184232006-01-05 11:34:32 +00006526 /* Reading a meta-data value requires a read-lock on page 1 (and hence
6527 ** the sqlite_master table. We grab this lock regardless of whether or
6528 ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
6529 ** 1 is treated as a special case by queryTableLock() and lockTable()).
6530 */
6531 rc = queryTableLock(p, 1, READ_LOCK);
6532 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00006533 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00006534 return rc;
6535 }
6536
drh23e11ca2004-05-04 17:27:28 +00006537 assert( idx>=0 && idx<=15 );
danielk1977d9f6c532008-09-19 16:39:38 +00006538 if( pBt->pPage1 ){
6539 /* The b-tree is already holding a reference to page 1 of the database
6540 ** file. In this case the required meta-data value can be read directly
6541 ** from the page data of this reference. This is slightly faster than
6542 ** requesting a new reference from the pager layer.
6543 */
6544 pP1 = (unsigned char *)pBt->pPage1->aData;
6545 }else{
6546 /* The b-tree does not have a reference to page 1 of the database file.
6547 ** Obtain one from the pager layer.
6548 */
danielk1977ea897302008-09-19 15:10:58 +00006549 rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
6550 if( rc ){
6551 sqlite3BtreeLeave(p);
6552 return rc;
6553 }
6554 pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
drhd677b3d2007-08-20 22:48:41 +00006555 }
drh23e11ca2004-05-04 17:27:28 +00006556 *pMeta = get4byte(&pP1[36 + idx*4]);
danielk1977ea897302008-09-19 15:10:58 +00006557
danielk1977d9f6c532008-09-19 16:39:38 +00006558 /* If the b-tree is not holding a reference to page 1, then one was
6559 ** requested from the pager layer in the above block. Release it now.
6560 */
danielk1977ea897302008-09-19 15:10:58 +00006561 if( !pBt->pPage1 ){
6562 sqlite3PagerUnref(pDbPage);
6563 }
drhae157872004-08-14 19:20:09 +00006564
danielk1977599fcba2004-11-08 07:13:13 +00006565 /* If autovacuumed is disabled in this build but we are trying to
6566 ** access an autovacuumed database, then make the database readonly.
6567 */
danielk1977003ba062004-11-04 02:57:33 +00006568#ifdef SQLITE_OMIT_AUTOVACUUM
drhae157872004-08-14 19:20:09 +00006569 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00006570#endif
drhae157872004-08-14 19:20:09 +00006571
danielk1977da184232006-01-05 11:34:32 +00006572 /* Grab the read-lock on page 1. */
6573 rc = lockTable(p, 1, READ_LOCK);
drhd677b3d2007-08-20 22:48:41 +00006574 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00006575 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006576}
6577
6578/*
drh23e11ca2004-05-04 17:27:28 +00006579** Write meta-information back into the database. Meta[0] is
6580** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00006581*/
danielk1977aef0bf62005-12-30 16:28:01 +00006582int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
6583 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00006584 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00006585 int rc;
drh23e11ca2004-05-04 17:27:28 +00006586 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00006587 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006588 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00006589 if( p->inTrans!=TRANS_WRITE ){
drhd677b3d2007-08-20 22:48:41 +00006590 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
6591 }else{
6592 assert( pBt->pPage1!=0 );
6593 pP1 = pBt->pPage1->aData;
6594 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6595 if( rc==SQLITE_OK ){
6596 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +00006597#ifndef SQLITE_OMIT_AUTOVACUUM
drhd677b3d2007-08-20 22:48:41 +00006598 if( idx==7 ){
6599 assert( pBt->autoVacuum || iMeta==0 );
6600 assert( iMeta==0 || iMeta==1 );
6601 pBt->incrVacuum = iMeta;
6602 }
danielk19774152e672007-09-12 17:01:45 +00006603#endif
drhd677b3d2007-08-20 22:48:41 +00006604 }
drh5df72a52002-06-06 23:16:05 +00006605 }
drhd677b3d2007-08-20 22:48:41 +00006606 sqlite3BtreeLeave(p);
6607 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006608}
drh8c42ca92001-06-22 19:15:00 +00006609
drhf328bc82004-05-10 23:29:49 +00006610/*
6611** Return the flag byte at the beginning of the page that the cursor
6612** is currently pointing to.
6613*/
6614int sqlite3BtreeFlags(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00006615 /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
drha3460582008-07-11 21:02:53 +00006616 ** restoreCursorPosition() here.
danielk1977da184232006-01-05 11:34:32 +00006617 */
danielk1977e448dc42008-01-02 11:50:51 +00006618 MemPage *pPage;
drha3460582008-07-11 21:02:53 +00006619 restoreCursorPosition(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00006620 pPage = pCur->apPage[pCur->iPage];
drh1fee73e2007-08-29 04:00:57 +00006621 assert( cursorHoldsMutex(pCur) );
drhd0679ed2007-08-28 22:24:34 +00006622 assert( pPage->pBt==pCur->pBt );
drhf328bc82004-05-10 23:29:49 +00006623 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
6624}
6625
drhdd793422001-06-28 01:54:48 +00006626
drhdd793422001-06-28 01:54:48 +00006627/*
drh5eddca62001-06-30 21:53:53 +00006628** Return the pager associated with a BTree. This routine is used for
6629** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00006630*/
danielk1977aef0bf62005-12-30 16:28:01 +00006631Pager *sqlite3BtreePager(Btree *p){
6632 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00006633}
drh5eddca62001-06-30 21:53:53 +00006634
drhb7f91642004-10-31 02:22:47 +00006635#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006636/*
6637** Append a message to the error message string.
6638*/
drh2e38c322004-09-03 18:38:44 +00006639static void checkAppendMsg(
6640 IntegrityCk *pCheck,
6641 char *zMsg1,
6642 const char *zFormat,
6643 ...
6644){
6645 va_list ap;
drh1dcdbc02007-01-27 02:24:54 +00006646 if( !pCheck->mxErr ) return;
6647 pCheck->mxErr--;
6648 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00006649 va_start(ap, zFormat);
drhf089aa42008-07-08 19:34:06 +00006650 if( pCheck->errMsg.nChar ){
6651 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
drh5eddca62001-06-30 21:53:53 +00006652 }
drhf089aa42008-07-08 19:34:06 +00006653 if( zMsg1 ){
6654 sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
6655 }
6656 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
6657 va_end(ap);
drhc890fec2008-08-01 20:10:08 +00006658 if( pCheck->errMsg.mallocFailed ){
6659 pCheck->mallocFailed = 1;
6660 }
drh5eddca62001-06-30 21:53:53 +00006661}
drhb7f91642004-10-31 02:22:47 +00006662#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006663
drhb7f91642004-10-31 02:22:47 +00006664#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006665/*
6666** Add 1 to the reference count for page iPage. If this is the second
6667** reference to the page, add an error message to pCheck->zErrMsg.
6668** Return 1 if there are 2 ore more references to the page and 0 if
6669** if this is the first reference to the page.
6670**
6671** Also check that the page number is in bounds.
6672*/
danielk197789d40042008-11-17 14:20:56 +00006673static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00006674 if( iPage==0 ) return 1;
danielk197789d40042008-11-17 14:20:56 +00006675 if( iPage>pCheck->nPage ){
drh2e38c322004-09-03 18:38:44 +00006676 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006677 return 1;
6678 }
6679 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00006680 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006681 return 1;
6682 }
6683 return (pCheck->anRef[iPage]++)>1;
6684}
6685
danielk1977afcdd022004-10-31 16:25:42 +00006686#ifndef SQLITE_OMIT_AUTOVACUUM
6687/*
6688** Check that the entry in the pointer-map for page iChild maps to
6689** page iParent, pointer type ptrType. If not, append an error message
6690** to pCheck.
6691*/
6692static void checkPtrmap(
6693 IntegrityCk *pCheck, /* Integrity check context */
6694 Pgno iChild, /* Child page number */
6695 u8 eType, /* Expected pointer map type */
6696 Pgno iParent, /* Expected pointer map parent page number */
6697 char *zContext /* Context description (used for error msg) */
6698){
6699 int rc;
6700 u8 ePtrmapType;
6701 Pgno iPtrmapParent;
6702
6703 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
6704 if( rc!=SQLITE_OK ){
drhe43ba702008-12-05 22:40:08 +00006705 if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
danielk1977afcdd022004-10-31 16:25:42 +00006706 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
6707 return;
6708 }
6709
6710 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
6711 checkAppendMsg(pCheck, zContext,
6712 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
6713 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
6714 }
6715}
6716#endif
6717
drh5eddca62001-06-30 21:53:53 +00006718/*
6719** Check the integrity of the freelist or of an overflow page list.
6720** Verify that the number of pages on the list is N.
6721*/
drh30e58752002-03-02 20:41:57 +00006722static void checkList(
6723 IntegrityCk *pCheck, /* Integrity checking context */
6724 int isFreeList, /* True for a freelist. False for overflow page list */
6725 int iPage, /* Page number for first page in the list */
6726 int N, /* Expected number of pages in the list */
6727 char *zContext /* Context for error messages */
6728){
6729 int i;
drh3a4c1412004-05-09 20:40:11 +00006730 int expected = N;
6731 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00006732 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00006733 DbPage *pOvflPage;
6734 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00006735 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00006736 checkAppendMsg(pCheck, zContext,
6737 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00006738 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00006739 break;
6740 }
6741 if( checkRef(pCheck, iPage, zContext) ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00006742 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
drh2e38c322004-09-03 18:38:44 +00006743 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006744 break;
6745 }
danielk19773b8a05f2007-03-19 17:44:26 +00006746 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00006747 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00006748 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00006749#ifndef SQLITE_OMIT_AUTOVACUUM
6750 if( pCheck->pBt->autoVacuum ){
6751 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
6752 }
6753#endif
drh45b1fac2008-07-04 17:52:42 +00006754 if( n>pCheck->pBt->usableSize/4-2 ){
drh2e38c322004-09-03 18:38:44 +00006755 checkAppendMsg(pCheck, zContext,
6756 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00006757 N--;
6758 }else{
6759 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00006760 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00006761#ifndef SQLITE_OMIT_AUTOVACUUM
6762 if( pCheck->pBt->autoVacuum ){
6763 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
6764 }
6765#endif
6766 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00006767 }
6768 N -= n;
drh30e58752002-03-02 20:41:57 +00006769 }
drh30e58752002-03-02 20:41:57 +00006770 }
danielk1977afcdd022004-10-31 16:25:42 +00006771#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006772 else{
6773 /* If this database supports auto-vacuum and iPage is not the last
6774 ** page in this overflow list, check that the pointer-map entry for
6775 ** the following page matches iPage.
6776 */
6777 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00006778 i = get4byte(pOvflData);
danielk1977687566d2004-11-02 12:56:41 +00006779 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
6780 }
danielk1977afcdd022004-10-31 16:25:42 +00006781 }
6782#endif
danielk19773b8a05f2007-03-19 17:44:26 +00006783 iPage = get4byte(pOvflData);
6784 sqlite3PagerUnref(pOvflPage);
drh5eddca62001-06-30 21:53:53 +00006785 }
6786}
drhb7f91642004-10-31 02:22:47 +00006787#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006788
drhb7f91642004-10-31 02:22:47 +00006789#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006790/*
6791** Do various sanity checks on a single page of a tree. Return
6792** the tree depth. Root pages return 0. Parents of root pages
6793** return 1, and so forth.
6794**
6795** These checks are done:
6796**
6797** 1. Make sure that cells and freeblocks do not overlap
6798** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00006799** NO 2. Make sure cell keys are in order.
6800** NO 3. Make sure no key is less than or equal to zLowerBound.
6801** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00006802** 5. Check the integrity of overflow pages.
6803** 6. Recursively call checkTreePage on all children.
6804** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00006805** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00006806** the root of the tree.
6807*/
6808static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00006809 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00006810 int iPage, /* Page number of the page to check */
drh74161702006-02-24 02:53:49 +00006811 char *zParentContext /* Parent context */
drh5eddca62001-06-30 21:53:53 +00006812){
6813 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00006814 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00006815 int hdr, cellStart;
6816 int nCell;
drhda200cc2004-05-09 11:51:38 +00006817 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00006818 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00006819 int usableSize;
drh5eddca62001-06-30 21:53:53 +00006820 char zContext[100];
shane0af3f892008-11-12 04:55:34 +00006821 char *hit = 0;
drh5eddca62001-06-30 21:53:53 +00006822
drh5bb3eb92007-05-04 13:15:55 +00006823 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
danielk1977ef73ee92004-11-06 12:26:07 +00006824
drh5eddca62001-06-30 21:53:53 +00006825 /* Check that the page exists
6826 */
drhd9cb6ac2005-10-20 07:28:17 +00006827 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00006828 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00006829 if( iPage==0 ) return 0;
6830 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh16a9b832007-05-05 18:39:25 +00006831 if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drhe43ba702008-12-05 22:40:08 +00006832 if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
drh2e38c322004-09-03 18:38:44 +00006833 checkAppendMsg(pCheck, zContext,
6834 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00006835 return 0;
6836 }
danielk197771d5d2c2008-09-29 11:49:47 +00006837 if( (rc = sqlite3BtreeInitPage(pPage))!=0 ){
drhe43ba702008-12-05 22:40:08 +00006838 if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
drh16a9b832007-05-05 18:39:25 +00006839 checkAppendMsg(pCheck, zContext,
6840 "sqlite3BtreeInitPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00006841 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00006842 return 0;
6843 }
6844
6845 /* Check out all the cells.
6846 */
6847 depth = 0;
drh1dcdbc02007-01-27 02:24:54 +00006848 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
drh6f11bef2004-05-13 01:12:56 +00006849 u8 *pCell;
danielk197789d40042008-11-17 14:20:56 +00006850 u32 sz;
drh6f11bef2004-05-13 01:12:56 +00006851 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00006852
6853 /* Check payload overflow pages
6854 */
drh5bb3eb92007-05-04 13:15:55 +00006855 sqlite3_snprintf(sizeof(zContext), zContext,
6856 "On tree page %d cell %d: ", iPage, i);
danielk19771cc5ed82007-05-16 17:28:43 +00006857 pCell = findCell(pPage,i);
drh16a9b832007-05-05 18:39:25 +00006858 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00006859 sz = info.nData;
6860 if( !pPage->intKey ) sz += info.nKey;
drh72365832007-03-06 15:53:44 +00006861 assert( sz==info.nPayload );
drh6f11bef2004-05-13 01:12:56 +00006862 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00006863 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00006864 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
6865#ifndef SQLITE_OMIT_AUTOVACUUM
6866 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006867 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00006868 }
6869#endif
6870 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00006871 }
6872
6873 /* Check sanity of left child page.
6874 */
drhda200cc2004-05-09 11:51:38 +00006875 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006876 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00006877#ifndef SQLITE_OMIT_AUTOVACUUM
6878 if( pBt->autoVacuum ){
6879 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
6880 }
6881#endif
danielk197762c14b32008-11-19 09:05:26 +00006882 d2 = checkTreePage(pCheck, pgno, zContext);
drhda200cc2004-05-09 11:51:38 +00006883 if( i>0 && d2!=depth ){
6884 checkAppendMsg(pCheck, zContext, "Child page depth differs");
6885 }
6886 depth = d2;
drh5eddca62001-06-30 21:53:53 +00006887 }
drh5eddca62001-06-30 21:53:53 +00006888 }
drhda200cc2004-05-09 11:51:38 +00006889 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006890 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh5bb3eb92007-05-04 13:15:55 +00006891 sqlite3_snprintf(sizeof(zContext), zContext,
6892 "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00006893#ifndef SQLITE_OMIT_AUTOVACUUM
6894 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006895 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00006896 }
6897#endif
danielk197762c14b32008-11-19 09:05:26 +00006898 checkTreePage(pCheck, pgno, zContext);
drhda200cc2004-05-09 11:51:38 +00006899 }
drh5eddca62001-06-30 21:53:53 +00006900
6901 /* Check for complete coverage of the page
6902 */
drhda200cc2004-05-09 11:51:38 +00006903 data = pPage->aData;
6904 hdr = pPage->hdrOffset;
drhf7141992008-06-19 00:16:08 +00006905 hit = sqlite3PageMalloc( pBt->pageSize );
drhc890fec2008-08-01 20:10:08 +00006906 if( hit==0 ){
6907 pCheck->mallocFailed = 1;
6908 }else{
shane5780ebd2008-11-11 17:36:30 +00006909 u16 contentOffset = get2byte(&data[hdr+5]);
6910 if (contentOffset > usableSize) {
6911 checkAppendMsg(pCheck, 0,
6912 "Corruption detected in header on page %d",iPage,0);
shane0af3f892008-11-12 04:55:34 +00006913 goto check_page_abort;
shane5780ebd2008-11-11 17:36:30 +00006914 }
6915 memset(hit+contentOffset, 0, usableSize-contentOffset);
6916 memset(hit, 1, contentOffset);
drh2e38c322004-09-03 18:38:44 +00006917 nCell = get2byte(&data[hdr+3]);
6918 cellStart = hdr + 12 - 4*pPage->leaf;
6919 for(i=0; i<nCell; i++){
6920 int pc = get2byte(&data[cellStart+i*2]);
danielk1977daca5432008-08-25 11:57:16 +00006921 u16 size = 1024;
drh2e38c322004-09-03 18:38:44 +00006922 int j;
danielk1977daca5432008-08-25 11:57:16 +00006923 if( pc<=usableSize ){
6924 size = cellSizePtr(pPage, &data[pc]);
6925 }
danielk19777701e812005-01-10 12:59:51 +00006926 if( (pc+size-1)>=usableSize || pc<0 ){
6927 checkAppendMsg(pCheck, 0,
6928 "Corruption detected in cell %d on page %d",i,iPage,0);
6929 }else{
6930 for(j=pc+size-1; j>=pc; j--) hit[j]++;
6931 }
drh2e38c322004-09-03 18:38:44 +00006932 }
6933 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
6934 cnt++){
6935 int size = get2byte(&data[i+2]);
6936 int j;
danielk19777701e812005-01-10 12:59:51 +00006937 if( (i+size-1)>=usableSize || i<0 ){
6938 checkAppendMsg(pCheck, 0,
6939 "Corruption detected in cell %d on page %d",i,iPage,0);
6940 }else{
6941 for(j=i+size-1; j>=i; j--) hit[j]++;
6942 }
drh2e38c322004-09-03 18:38:44 +00006943 i = get2byte(&data[i]);
6944 }
6945 for(i=cnt=0; i<usableSize; i++){
6946 if( hit[i]==0 ){
6947 cnt++;
6948 }else if( hit[i]>1 ){
6949 checkAppendMsg(pCheck, 0,
6950 "Multiple uses for byte %d of page %d", i, iPage);
6951 break;
6952 }
6953 }
6954 if( cnt!=data[hdr+7] ){
6955 checkAppendMsg(pCheck, 0,
6956 "Fragmented space is %d byte reported as %d on page %d",
6957 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00006958 }
6959 }
shane0af3f892008-11-12 04:55:34 +00006960check_page_abort:
6961 if (hit) sqlite3PageFree(hit);
drh6019e162001-07-02 17:51:45 +00006962
drh4b70f112004-05-02 21:12:19 +00006963 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00006964 return depth+1;
drh5eddca62001-06-30 21:53:53 +00006965}
drhb7f91642004-10-31 02:22:47 +00006966#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006967
drhb7f91642004-10-31 02:22:47 +00006968#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006969/*
6970** This routine does a complete check of the given BTree file. aRoot[] is
6971** an array of pages numbers were each page number is the root page of
6972** a table. nRoot is the number of entries in aRoot.
6973**
drhc890fec2008-08-01 20:10:08 +00006974** Write the number of error seen in *pnErr. Except for some memory
drhe43ba702008-12-05 22:40:08 +00006975** allocation errors, an error message held in memory obtained from
drhc890fec2008-08-01 20:10:08 +00006976** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
drhe43ba702008-12-05 22:40:08 +00006977** returned. If a memory allocation error occurs, NULL is returned.
drh5eddca62001-06-30 21:53:53 +00006978*/
drh1dcdbc02007-01-27 02:24:54 +00006979char *sqlite3BtreeIntegrityCheck(
6980 Btree *p, /* The btree to be checked */
6981 int *aRoot, /* An array of root pages numbers for individual trees */
6982 int nRoot, /* Number of entries in aRoot[] */
6983 int mxErr, /* Stop reporting errors after this many */
6984 int *pnErr /* Write number of errors seen to this variable */
6985){
danielk197789d40042008-11-17 14:20:56 +00006986 Pgno i;
drh5eddca62001-06-30 21:53:53 +00006987 int nRef;
drhaaab5722002-02-19 13:39:21 +00006988 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00006989 BtShared *pBt = p->pBt;
drhf089aa42008-07-08 19:34:06 +00006990 char zErr[100];
drh5eddca62001-06-30 21:53:53 +00006991
drhd677b3d2007-08-20 22:48:41 +00006992 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006993 pBt->db = p->db;
danielk19773b8a05f2007-03-19 17:44:26 +00006994 nRef = sqlite3PagerRefcount(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00006995 if( lockBtreeWithRetry(p)!=SQLITE_OK ){
drhc890fec2008-08-01 20:10:08 +00006996 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00006997 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00006998 return sqlite3DbStrDup(0, "cannot acquire a read lock on the database");
drhefc251d2001-07-01 22:12:01 +00006999 }
drh5eddca62001-06-30 21:53:53 +00007000 sCheck.pBt = pBt;
7001 sCheck.pPager = pBt->pPager;
danielk197789d40042008-11-17 14:20:56 +00007002 sCheck.nPage = pagerPagecount(sCheck.pBt);
drh1dcdbc02007-01-27 02:24:54 +00007003 sCheck.mxErr = mxErr;
7004 sCheck.nErr = 0;
drhc890fec2008-08-01 20:10:08 +00007005 sCheck.mallocFailed = 0;
drh1dcdbc02007-01-27 02:24:54 +00007006 *pnErr = 0;
danielk1977e5321f02007-04-27 07:05:44 +00007007#ifndef SQLITE_OMIT_AUTOVACUUM
7008 if( pBt->nTrunc!=0 ){
7009 sCheck.nPage = pBt->nTrunc;
7010 }
7011#endif
drh0de8c112002-07-06 16:32:14 +00007012 if( sCheck.nPage==0 ){
7013 unlockBtreeIfUnused(pBt);
drhd677b3d2007-08-20 22:48:41 +00007014 sqlite3BtreeLeave(p);
drh0de8c112002-07-06 16:32:14 +00007015 return 0;
7016 }
drhe5ae5732008-06-15 02:51:47 +00007017 sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00007018 if( !sCheck.anRef ){
7019 unlockBtreeIfUnused(pBt);
drh1dcdbc02007-01-27 02:24:54 +00007020 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00007021 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00007022 return 0;
danielk1977ac245ec2005-01-14 13:50:11 +00007023 }
drhda200cc2004-05-09 11:51:38 +00007024 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00007025 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00007026 if( i<=sCheck.nPage ){
7027 sCheck.anRef[i] = 1;
7028 }
drhf089aa42008-07-08 19:34:06 +00007029 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
drh5eddca62001-06-30 21:53:53 +00007030
7031 /* Check the integrity of the freelist
7032 */
drha34b6762004-05-07 13:30:42 +00007033 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
7034 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00007035
7036 /* Check all the tables.
7037 */
danielk197789d40042008-11-17 14:20:56 +00007038 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
drh4ff6dfa2002-03-03 23:06:00 +00007039 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00007040#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00007041 if( pBt->autoVacuum && aRoot[i]>1 ){
7042 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
7043 }
7044#endif
danielk197762c14b32008-11-19 09:05:26 +00007045 checkTreePage(&sCheck, aRoot[i], "List of tree roots: ");
drh5eddca62001-06-30 21:53:53 +00007046 }
7047
7048 /* Make sure every page in the file is referenced
7049 */
drh1dcdbc02007-01-27 02:24:54 +00007050 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00007051#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00007052 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00007053 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00007054 }
danielk1977afcdd022004-10-31 16:25:42 +00007055#else
7056 /* If the database supports auto-vacuum, make sure no tables contain
7057 ** references to pointer-map pages.
7058 */
7059 if( sCheck.anRef[i]==0 &&
danielk1977266664d2006-02-10 08:24:21 +00007060 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00007061 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
7062 }
7063 if( sCheck.anRef[i]!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00007064 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00007065 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
7066 }
7067#endif
drh5eddca62001-06-30 21:53:53 +00007068 }
7069
7070 /* Make sure this analysis did not leave any unref() pages
7071 */
drh5e00f6c2001-09-13 13:46:56 +00007072 unlockBtreeIfUnused(pBt);
danielk19773b8a05f2007-03-19 17:44:26 +00007073 if( nRef != sqlite3PagerRefcount(pBt->pPager) ){
drh2e38c322004-09-03 18:38:44 +00007074 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00007075 "Outstanding page count goes from %d to %d during this analysis",
danielk19773b8a05f2007-03-19 17:44:26 +00007076 nRef, sqlite3PagerRefcount(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00007077 );
drh5eddca62001-06-30 21:53:53 +00007078 }
7079
7080 /* Clean up and report errors.
7081 */
drhd677b3d2007-08-20 22:48:41 +00007082 sqlite3BtreeLeave(p);
drh17435752007-08-16 04:30:38 +00007083 sqlite3_free(sCheck.anRef);
drhc890fec2008-08-01 20:10:08 +00007084 if( sCheck.mallocFailed ){
7085 sqlite3StrAccumReset(&sCheck.errMsg);
7086 *pnErr = sCheck.nErr+1;
7087 return 0;
7088 }
drh1dcdbc02007-01-27 02:24:54 +00007089 *pnErr = sCheck.nErr;
drhf089aa42008-07-08 19:34:06 +00007090 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
7091 return sqlite3StrAccumFinish(&sCheck.errMsg);
drh5eddca62001-06-30 21:53:53 +00007092}
drhb7f91642004-10-31 02:22:47 +00007093#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00007094
drh73509ee2003-04-06 20:44:45 +00007095/*
7096** Return the full pathname of the underlying database file.
drhd0679ed2007-08-28 22:24:34 +00007097**
7098** The pager filename is invariant as long as the pager is
7099** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +00007100*/
danielk1977aef0bf62005-12-30 16:28:01 +00007101const char *sqlite3BtreeGetFilename(Btree *p){
7102 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007103 return sqlite3PagerFilename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00007104}
7105
7106/*
danielk19775865e3d2004-06-14 06:03:57 +00007107** Return the pathname of the directory that contains the database file.
drhd0679ed2007-08-28 22:24:34 +00007108**
7109** The pager directory name is invariant as long as the pager is
7110** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00007111*/
danielk1977aef0bf62005-12-30 16:28:01 +00007112const char *sqlite3BtreeGetDirname(Btree *p){
7113 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007114 return sqlite3PagerDirname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00007115}
7116
7117/*
7118** Return the pathname of the journal file for this database. The return
7119** value of this routine is the same regardless of whether the journal file
7120** has been created or not.
drhd0679ed2007-08-28 22:24:34 +00007121**
7122** The pager journal filename is invariant as long as the pager is
7123** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00007124*/
danielk1977aef0bf62005-12-30 16:28:01 +00007125const char *sqlite3BtreeGetJournalname(Btree *p){
7126 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007127 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00007128}
7129
drhb7f91642004-10-31 02:22:47 +00007130#ifndef SQLITE_OMIT_VACUUM
danielk19775865e3d2004-06-14 06:03:57 +00007131/*
drhf7c57532003-04-25 13:22:51 +00007132** Copy the complete content of pBtFrom into pBtTo. A transaction
7133** must be active for both files.
7134**
danielk1977f653d782008-03-20 11:04:21 +00007135** The size of file pTo may be reduced by this operation.
7136** If anything goes wrong, the transaction on pTo is rolled back.
7137**
7138** If successful, CommitPhaseOne() may be called on pTo before returning.
7139** The caller should finish committing the transaction on pTo by calling
7140** sqlite3BtreeCommit().
drh73509ee2003-04-06 20:44:45 +00007141*/
drhd677b3d2007-08-20 22:48:41 +00007142static int btreeCopyFile(Btree *pTo, Btree *pFrom){
drhf7c57532003-04-25 13:22:51 +00007143 int rc = SQLITE_OK;
danielk1977f653d782008-03-20 11:04:21 +00007144 Pgno i;
7145
7146 Pgno nFromPage; /* Number of pages in pFrom */
7147 Pgno nToPage; /* Number of pages in pTo */
7148 Pgno nNewPage; /* Number of pages in pTo after the copy */
7149
7150 Pgno iSkip; /* Pending byte page in pTo */
7151 int nToPageSize; /* Page size of pTo in bytes */
7152 int nFromPageSize; /* Page size of pFrom in bytes */
drhf7c57532003-04-25 13:22:51 +00007153
danielk1977aef0bf62005-12-30 16:28:01 +00007154 BtShared *pBtTo = pTo->pBt;
7155 BtShared *pBtFrom = pFrom->pBt;
drhe5fe6902007-12-07 18:55:28 +00007156 pBtTo->db = pTo->db;
7157 pBtFrom->db = pFrom->db;
danielk1977f653d782008-03-20 11:04:21 +00007158
7159 nToPageSize = pBtTo->pageSize;
7160 nFromPageSize = pBtFrom->pageSize;
danielk1977aef0bf62005-12-30 16:28:01 +00007161
7162 if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
danielk1977ee5741e2004-05-31 10:01:34 +00007163 return SQLITE_ERROR;
7164 }
danielk1977f653d782008-03-20 11:04:21 +00007165 if( pBtTo->pCursor ){
7166 return SQLITE_BUSY;
drhf7c57532003-04-25 13:22:51 +00007167 }
drh538f5702007-04-13 02:14:30 +00007168
danielk197789d40042008-11-17 14:20:56 +00007169 nToPage = pagerPagecount(pBtTo);
7170 nFromPage = pagerPagecount(pBtFrom);
danielk1977f653d782008-03-20 11:04:21 +00007171 iSkip = PENDING_BYTE_PAGE(pBtTo);
7172
7173 /* Variable nNewPage is the number of pages required to store the
7174 ** contents of pFrom using the current page-size of pTo.
drh538f5702007-04-13 02:14:30 +00007175 */
danielk1977f653d782008-03-20 11:04:21 +00007176 nNewPage = ((i64)nFromPage * (i64)nFromPageSize + (i64)nToPageSize - 1) /
7177 (i64)nToPageSize;
7178
7179 for(i=1; rc==SQLITE_OK && (i<=nToPage || i<=nNewPage); i++){
7180
7181 /* Journal the original page.
7182 **
7183 ** iSkip is the page number of the locking page (PENDING_BYTE_PAGE)
7184 ** in database *pTo (before the copy). This page is never written
7185 ** into the journal file. Unless i==iSkip or the page was not
7186 ** present in pTo before the copy operation, journal page i from pTo.
7187 */
7188 if( i!=iSkip && i<=nToPage ){
danielk19774abd5442008-05-05 15:26:50 +00007189 DbPage *pDbPage = 0;
danielk1977f653d782008-03-20 11:04:21 +00007190 rc = sqlite3PagerGet(pBtTo->pPager, i, &pDbPage);
danielk19774abd5442008-05-05 15:26:50 +00007191 if( rc==SQLITE_OK ){
7192 rc = sqlite3PagerWrite(pDbPage);
danielk1977df2566a2008-05-07 19:11:03 +00007193 if( rc==SQLITE_OK && i>nFromPage ){
7194 /* Yeah. It seems wierd to call DontWrite() right after Write(). But
7195 ** that is because the names of those procedures do not exactly
7196 ** represent what they do. Write() really means "put this page in the
7197 ** rollback journal and mark it as dirty so that it will be written
7198 ** to the database file later." DontWrite() undoes the second part of
7199 ** that and prevents the page from being written to the database. The
7200 ** page is still on the rollback journal, though. And that is the
7201 ** whole point of this block: to put pages on the rollback journal.
7202 */
danielk1977a1fa00d2008-08-27 15:16:33 +00007203 rc = sqlite3PagerDontWrite(pDbPage);
danielk1977df2566a2008-05-07 19:11:03 +00007204 }
7205 sqlite3PagerUnref(pDbPage);
danielk1977f653d782008-03-20 11:04:21 +00007206 }
danielk1977f653d782008-03-20 11:04:21 +00007207 }
7208
7209 /* Overwrite the data in page i of the target database */
7210 if( rc==SQLITE_OK && i!=iSkip && i<=nNewPage ){
7211
7212 DbPage *pToPage = 0;
7213 sqlite3_int64 iOff;
7214
7215 rc = sqlite3PagerGet(pBtTo->pPager, i, &pToPage);
7216 if( rc==SQLITE_OK ){
7217 rc = sqlite3PagerWrite(pToPage);
7218 }
7219
7220 for(
7221 iOff=(i-1)*nToPageSize;
7222 rc==SQLITE_OK && iOff<i*nToPageSize;
7223 iOff += nFromPageSize
7224 ){
7225 DbPage *pFromPage = 0;
7226 Pgno iFrom = (iOff/nFromPageSize)+1;
7227
7228 if( iFrom==PENDING_BYTE_PAGE(pBtFrom) ){
7229 continue;
7230 }
7231
7232 rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
7233 if( rc==SQLITE_OK ){
7234 char *zTo = sqlite3PagerGetData(pToPage);
7235 char *zFrom = sqlite3PagerGetData(pFromPage);
7236 int nCopy;
7237
7238 if( nFromPageSize>=nToPageSize ){
7239 zFrom += ((i-1)*nToPageSize - ((iFrom-1)*nFromPageSize));
7240 nCopy = nToPageSize;
7241 }else{
7242 zTo += (((iFrom-1)*nFromPageSize) - (i-1)*nToPageSize);
7243 nCopy = nFromPageSize;
7244 }
7245
7246 memcpy(zTo, zFrom, nCopy);
danielk19772f78fc62008-09-30 09:31:45 +00007247 sqlite3PagerUnref(pFromPage);
danielk1977f653d782008-03-20 11:04:21 +00007248 }
7249 }
7250
danielk1977eaa06f62008-09-18 17:34:44 +00007251 if( pToPage ){
7252 MemPage *p = (MemPage *)sqlite3PagerGetExtra(pToPage);
7253 p->isInit = 0;
7254 sqlite3PagerUnref(pToPage);
7255 }
danielk1977f653d782008-03-20 11:04:21 +00007256 }
drh2e6d11b2003-04-25 15:37:57 +00007257 }
danielk1977f653d782008-03-20 11:04:21 +00007258
7259 /* If things have worked so far, the database file may need to be
7260 ** truncated. The complex part is that it may need to be truncated to
7261 ** a size that is not an integer multiple of nToPageSize - the current
7262 ** page size used by the pager associated with B-Tree pTo.
7263 **
7264 ** For example, say the page-size of pTo is 2048 bytes and the original
7265 ** number of pages is 5 (10 KB file). If pFrom has a page size of 1024
7266 ** bytes and 9 pages, then the file needs to be truncated to 9KB.
7267 */
7268 if( rc==SQLITE_OK ){
7269 if( nFromPageSize!=nToPageSize ){
7270 sqlite3_file *pFile = sqlite3PagerFile(pBtTo->pPager);
7271 i64 iSize = (i64)nFromPageSize * (i64)nFromPage;
7272 i64 iNow = (i64)((nToPage>nNewPage)?nToPage:nNewPage) * (i64)nToPageSize;
7273 i64 iPending = ((i64)PENDING_BYTE_PAGE(pBtTo)-1) *(i64)nToPageSize;
7274
7275 assert( iSize<=iNow );
7276
7277 /* Commit phase one syncs the journal file associated with pTo
7278 ** containing the original data. It does not sync the database file
7279 ** itself. After doing this it is safe to use OsTruncate() and other
7280 ** file APIs on the database file directly.
7281 */
7282 pBtTo->db = pTo->db;
7283 rc = sqlite3PagerCommitPhaseOne(pBtTo->pPager, 0, 0, 1);
7284 if( iSize<iNow && rc==SQLITE_OK ){
7285 rc = sqlite3OsTruncate(pFile, iSize);
7286 }
7287
7288 /* The loop that copied data from database pFrom to pTo did not
7289 ** populate the locking page of database pTo. If the page-size of
7290 ** pFrom is smaller than that of pTo, this means some data will
7291 ** not have been copied.
7292 **
7293 ** This block copies the missing data from database pFrom to pTo
7294 ** using file APIs. This is safe because at this point we know that
7295 ** all of the original data from pTo has been synced into the
7296 ** journal file. At this point it would be safe to do anything at
7297 ** all to the database file except truncate it to zero bytes.
7298 */
7299 if( rc==SQLITE_OK && nFromPageSize<nToPageSize && iSize>iPending){
7300 i64 iOff;
7301 for(
7302 iOff=iPending;
7303 rc==SQLITE_OK && iOff<(iPending+nToPageSize);
7304 iOff += nFromPageSize
7305 ){
7306 DbPage *pFromPage = 0;
7307 Pgno iFrom = (iOff/nFromPageSize)+1;
7308
7309 if( iFrom==PENDING_BYTE_PAGE(pBtFrom) || iFrom>nFromPage ){
7310 continue;
7311 }
7312
7313 rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
7314 if( rc==SQLITE_OK ){
7315 char *zFrom = sqlite3PagerGetData(pFromPage);
danielk197706249db2008-08-23 16:17:55 +00007316 rc = sqlite3OsWrite(pFile, zFrom, nFromPageSize, iOff);
danielk1977f653d782008-03-20 11:04:21 +00007317 sqlite3PagerUnref(pFromPage);
7318 }
7319 }
7320 }
7321
7322 /* Sync the database file */
7323 if( rc==SQLITE_OK ){
7324 rc = sqlite3PagerSync(pBtTo->pPager);
7325 }
7326 }else{
7327 rc = sqlite3PagerTruncate(pBtTo->pPager, nNewPage);
7328 }
7329 if( rc==SQLITE_OK ){
7330 pBtTo->pageSizeFixed = 0;
7331 }
drh2e6d11b2003-04-25 15:37:57 +00007332 }
drh538f5702007-04-13 02:14:30 +00007333
drhf7c57532003-04-25 13:22:51 +00007334 if( rc ){
danielk1977aef0bf62005-12-30 16:28:01 +00007335 sqlite3BtreeRollback(pTo);
drhf7c57532003-04-25 13:22:51 +00007336 }
danielk1977f653d782008-03-20 11:04:21 +00007337
drhf7c57532003-04-25 13:22:51 +00007338 return rc;
drh73509ee2003-04-06 20:44:45 +00007339}
drhd677b3d2007-08-20 22:48:41 +00007340int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
7341 int rc;
7342 sqlite3BtreeEnter(pTo);
7343 sqlite3BtreeEnter(pFrom);
7344 rc = btreeCopyFile(pTo, pFrom);
7345 sqlite3BtreeLeave(pFrom);
7346 sqlite3BtreeLeave(pTo);
7347 return rc;
7348}
7349
drhb7f91642004-10-31 02:22:47 +00007350#endif /* SQLITE_OMIT_VACUUM */
danielk19771d850a72004-05-31 08:26:49 +00007351
7352/*
7353** Return non-zero if a transaction is active.
7354*/
danielk1977aef0bf62005-12-30 16:28:01 +00007355int sqlite3BtreeIsInTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00007356 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00007357 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00007358}
7359
7360/*
7361** Return non-zero if a statement transaction is active.
7362*/
danielk1977aef0bf62005-12-30 16:28:01 +00007363int sqlite3BtreeIsInStmt(Btree *p){
drh1fee73e2007-08-29 04:00:57 +00007364 assert( sqlite3BtreeHoldsMutex(p) );
danielk1977aef0bf62005-12-30 16:28:01 +00007365 return (p->pBt && p->pBt->inStmt);
danielk19771d850a72004-05-31 08:26:49 +00007366}
danielk197713adf8a2004-06-03 16:08:41 +00007367
7368/*
danielk19772372c2b2006-06-27 16:34:56 +00007369** Return non-zero if a read (or write) transaction is active.
7370*/
7371int sqlite3BtreeIsInReadTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00007372 assert( sqlite3_mutex_held(p->db->mutex) );
danielk19772372c2b2006-06-27 16:34:56 +00007373 return (p && (p->inTrans!=TRANS_NONE));
7374}
7375
7376/*
danielk1977da184232006-01-05 11:34:32 +00007377** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +00007378** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +00007379** purposes (for example, to store a high-level schema associated with
7380** the shared-btree). The btree layer manages reference counting issues.
7381**
7382** The first time this is called on a shared-btree, nBytes bytes of memory
7383** are allocated, zeroed, and returned to the caller. For each subsequent
7384** call the nBytes parameter is ignored and a pointer to the same blob
7385** of memory returned.
7386**
danielk1977171bfed2008-06-23 09:50:50 +00007387** If the nBytes parameter is 0 and the blob of memory has not yet been
7388** allocated, a null pointer is returned. If the blob has already been
7389** allocated, it is returned as normal.
7390**
danielk1977da184232006-01-05 11:34:32 +00007391** Just before the shared-btree is closed, the function passed as the
7392** xFree argument when the memory allocation was made is invoked on the
drh17435752007-08-16 04:30:38 +00007393** blob of allocated memory. This function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +00007394** on the memory, the btree layer does that.
7395*/
7396void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
7397 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +00007398 sqlite3BtreeEnter(p);
danielk1977171bfed2008-06-23 09:50:50 +00007399 if( !pBt->pSchema && nBytes ){
drh17435752007-08-16 04:30:38 +00007400 pBt->pSchema = sqlite3MallocZero(nBytes);
danielk1977da184232006-01-05 11:34:32 +00007401 pBt->xFreeSchema = xFree;
7402 }
drh27641702007-08-22 02:56:42 +00007403 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00007404 return pBt->pSchema;
7405}
7406
danielk1977c87d34d2006-01-06 13:00:28 +00007407/*
7408** Return true if another user of the same shared btree as the argument
7409** handle holds an exclusive lock on the sqlite_master table.
7410*/
7411int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +00007412 int rc;
drhe5fe6902007-12-07 18:55:28 +00007413 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +00007414 sqlite3BtreeEnter(p);
7415 rc = (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
7416 sqlite3BtreeLeave(p);
7417 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +00007418}
7419
drha154dcd2006-03-22 22:10:07 +00007420
7421#ifndef SQLITE_OMIT_SHARED_CACHE
7422/*
7423** Obtain a lock on the table whose root page is iTab. The
7424** lock is a write lock if isWritelock is true or a read lock
7425** if it is false.
7426*/
danielk1977c00da102006-01-07 13:21:04 +00007427int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00007428 int rc = SQLITE_OK;
drh6a9ad3d2008-04-02 16:29:30 +00007429 if( p->sharable ){
7430 u8 lockType = READ_LOCK + isWriteLock;
7431 assert( READ_LOCK+1==WRITE_LOCK );
7432 assert( isWriteLock==0 || isWriteLock==1 );
7433 sqlite3BtreeEnter(p);
7434 rc = queryTableLock(p, iTab, lockType);
7435 if( rc==SQLITE_OK ){
7436 rc = lockTable(p, iTab, lockType);
7437 }
7438 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +00007439 }
7440 return rc;
7441}
drha154dcd2006-03-22 22:10:07 +00007442#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00007443
danielk1977b4e9af92007-05-01 17:49:49 +00007444#ifndef SQLITE_OMIT_INCRBLOB
7445/*
7446** Argument pCsr must be a cursor opened for writing on an
7447** INTKEY table currently pointing at a valid table entry.
7448** This function modifies the data stored as part of that entry.
7449** Only the data content may only be modified, it is not possible
7450** to change the length of the data stored.
7451*/
danielk1977dcbb5d32007-05-04 18:36:44 +00007452int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
drh1fee73e2007-08-29 04:00:57 +00007453 assert( cursorHoldsMutex(pCsr) );
drhe5fe6902007-12-07 18:55:28 +00007454 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00007455 assert(pCsr->isIncrblobHandle);
danielk19773588ceb2008-06-10 17:30:26 +00007456
drha3460582008-07-11 21:02:53 +00007457 restoreCursorPosition(pCsr);
danielk19773588ceb2008-06-10 17:30:26 +00007458 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
7459 if( pCsr->eState!=CURSOR_VALID ){
7460 return SQLITE_ABORT;
danielk1977dcbb5d32007-05-04 18:36:44 +00007461 }
7462
danielk1977d04417962007-05-02 13:16:30 +00007463 /* Check some preconditions:
danielk1977dcbb5d32007-05-04 18:36:44 +00007464 ** (a) the cursor is open for writing,
7465 ** (b) there is no read-lock on the table being modified and
7466 ** (c) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00007467 */
danielk1977d04417962007-05-02 13:16:30 +00007468 if( !pCsr->wrFlag ){
danielk1977dcbb5d32007-05-04 18:36:44 +00007469 return SQLITE_READONLY;
danielk1977d04417962007-05-02 13:16:30 +00007470 }
drhd0679ed2007-08-28 22:24:34 +00007471 assert( !pCsr->pBt->readOnly
7472 && pCsr->pBt->inTransaction==TRANS_WRITE );
danielk19773588ceb2008-06-10 17:30:26 +00007473 if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr, 0) ){
danielk1977d04417962007-05-02 13:16:30 +00007474 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
7475 }
danielk197771d5d2c2008-09-29 11:49:47 +00007476 if( pCsr->eState==CURSOR_INVALID || !pCsr->apPage[pCsr->iPage]->intKey ){
danielk1977d04417962007-05-02 13:16:30 +00007477 return SQLITE_ERROR;
danielk1977b4e9af92007-05-01 17:49:49 +00007478 }
7479
danielk19779f8d6402007-05-02 17:48:45 +00007480 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00007481}
danielk19772dec9702007-05-02 16:48:37 +00007482
7483/*
7484** Set a flag on this cursor to cache the locations of pages from the
danielk1977da107192007-05-04 08:32:13 +00007485** overflow list for the current row. This is used by cursors opened
7486** for incremental blob IO only.
7487**
7488** This function sets a flag only. The actual page location cache
7489** (stored in BtCursor.aOverflow[]) is allocated and used by function
7490** accessPayload() (the worker function for sqlite3BtreeData() and
7491** sqlite3BtreePutData()).
danielk19772dec9702007-05-02 16:48:37 +00007492*/
7493void sqlite3BtreeCacheOverflow(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00007494 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00007495 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00007496 assert(!pCur->isIncrblobHandle);
danielk19772dec9702007-05-02 16:48:37 +00007497 assert(!pCur->aOverflow);
danielk1977dcbb5d32007-05-04 18:36:44 +00007498 pCur->isIncrblobHandle = 1;
danielk19772dec9702007-05-02 16:48:37 +00007499}
danielk1977b4e9af92007-05-01 17:49:49 +00007500#endif