blob: 48a7dee002fc3e1bb397995521ccf466543318c6 [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*************************************************************************
danielk197712dd5492008-12-18 15:45:07 +000012** $Id: btree.c,v 1.550 2008/12/18 15:45:07 danielk1977 Exp $
drh8b2f49b2001-06-08 00:21:52 +000013**
14** This file implements a external (disk-based) database using BTrees.
drha3152892007-05-05 11:48:52 +000015** See the header comment on "btreeInt.h" for additional information.
16** Including a description of file format and an overview of operation.
drha059ad02001-04-17 20:09:11 +000017*/
drha3152892007-05-05 11:48:52 +000018#include "btreeInt.h"
paulb95a8862003-04-01 21:16:41 +000019
drh8c42ca92001-06-22 19:15:00 +000020/*
drha3152892007-05-05 11:48:52 +000021** The header string that appears at the beginning of every
22** SQLite database.
drh556b2a22005-06-14 16:04:05 +000023*/
drh556b2a22005-06-14 16:04:05 +000024static const char zMagicHeader[] = SQLITE_FILE_HEADER;
drh08ed44e2001-04-29 23:32:55 +000025
drh8c42ca92001-06-22 19:15:00 +000026/*
drha3152892007-05-05 11:48:52 +000027** Set this global variable to 1 to enable tracing using the TRACE
28** macro.
drh615ae552005-01-16 23:21:00 +000029*/
drhe8f52c52008-07-12 14:52:20 +000030#if 0
mlcreech3a00f902008-03-04 17:45:01 +000031int sqlite3BtreeTrace=0; /* True to enable tracing */
drhe8f52c52008-07-12 14:52:20 +000032# define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
33#else
34# define TRACE(X)
drh615ae552005-01-16 23:21:00 +000035#endif
drh615ae552005-01-16 23:21:00 +000036
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){
drhf49661a2008-12-10 16:45:50 +0000319 void *pKey = sqlite3Malloc( (int)pCur->nKey );
drh980b1a72006-08-16 16:42:48 +0000320 if( pKey ){
drhf49661a2008-12-10 16:45:50 +0000321 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
drh980b1a72006-08-16 16:42:48 +0000322 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){
drhf49661a2008-12-10 16:45:50 +0000578 u16 n; /* Number bytes in cell content header */
drh271efa52004-05-30 19:19:05 +0000579 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 }
drh1bd10f82008-12-10 21:19:56 +0000593 n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
drh79df1f42008-07-18 00:57:33 +0000594 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;
drhf49661a2008-12-10 16:45:50 +0000608 pInfo->nLocal = (u16)nPayload;
drh6f11bef2004-05-13 01:12:56 +0000609 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 }
drh1bd10f82008-12-10 21:19:56 +0000613 pInfo->nSize = (u16)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 ){
drhf49661a2008-12-10 16:45:50 +0000632 pInfo->nLocal = (u16)surplus;
drh6f11bef2004-05-13 01:12:56 +0000633 }else{
drhf49661a2008-12-10 16:45:50 +0000634 pInfo->nLocal = (u16)minLocal;
drh6f11bef2004-05-13 01:12:56 +0000635 }
drhf49661a2008-12-10 16:45:50 +0000636 pInfo->iOverflow = (u16)(pInfo->nLocal + n);
drh6f11bef2004-05-13 01:12:56 +0000637 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 );
drhf49661a2008-12-10 16:45:50 +0000792 pPage->nFree -= (u16)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 ){
drhf49661a2008-12-10 16:45:50 +0000803 int x = size - nByte;
drh43605152004-05-29 21:46:49 +0000804 if( size<nByte+4 ){
805 memcpy(&data[addr], &data[pc], 2);
drhf49661a2008-12-10 16:45:50 +0000806 data[hdr+7] = (u8)(nFrag + x);
drh43605152004-05-29 21:46:49 +0000807 return pc;
808 }else{
drhf49661a2008-12-10 16:45:50 +0000809 put2byte(&data[pc+2], x);
810 return pc + x;
drh43605152004-05-29 21:46:49 +0000811 }
812 }
813 addr = pc;
drh9e572e62004-04-23 23:43:10 +0000814 }
815 }
drh43605152004-05-29 21:46:49 +0000816
817 /* Allocate memory from the gap in between the cell pointer array
818 ** and the cell content area.
819 */
820 top = get2byte(&data[hdr+5]);
821 nCell = get2byte(&data[hdr+3]);
822 cellOffset = pPage->cellOffset;
823 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
danielk1977474b7cc2008-07-09 11:49:46 +0000824 defragmentPage(pPage);
drh43605152004-05-29 21:46:49 +0000825 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +0000826 }
drh43605152004-05-29 21:46:49 +0000827 top -= nByte;
828 assert( cellOffset + 2*nCell <= top );
829 put2byte(&data[hdr+5], top);
drhc5053fb2008-11-27 02:22:10 +0000830 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +0000831 return top;
drh7e3b0a02001-04-28 16:52:40 +0000832}
833
834/*
drh9e572e62004-04-23 23:43:10 +0000835** Return a section of the pPage->aData to the freelist.
836** The first byte of the new free block is pPage->aDisk[start]
837** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +0000838**
839** Most of the effort here is involved in coalesing adjacent
840** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000841*/
shanedcc50b72008-11-13 18:29:50 +0000842static int freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +0000843 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +0000844 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +0000845
drh9e572e62004-04-23 23:43:10 +0000846 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +0000847 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000848 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +0000849 assert( (start + size)<=pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +0000850 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh34004ce2008-07-11 16:15:17 +0000851 assert( size>=0 ); /* Minimum cell size is 4 */
drh9e572e62004-04-23 23:43:10 +0000852
drhfcce93f2006-02-22 03:08:32 +0000853#ifdef SQLITE_SECURE_DELETE
854 /* Overwrite deleted information with zeros when the SECURE_DELETE
855 ** option is enabled at compile-time */
856 memset(&data[start], 0, size);
857#endif
858
drh9e572e62004-04-23 23:43:10 +0000859 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +0000860 hdr = pPage->hdrOffset;
861 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +0000862 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +0000863 assert( pbegin<=pPage->pBt->usableSize-4 );
shanedcc50b72008-11-13 18:29:50 +0000864 if( pbegin<=addr ) {
865 return SQLITE_CORRUPT_BKPT;
866 }
drh3aac2dd2004-04-26 14:10:20 +0000867 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +0000868 }
shanedcc50b72008-11-13 18:29:50 +0000869 if ( pbegin>pPage->pBt->usableSize-4 ) {
870 return SQLITE_CORRUPT_BKPT;
871 }
drh3aac2dd2004-04-26 14:10:20 +0000872 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +0000873 put2byte(&data[addr], start);
874 put2byte(&data[start], pbegin);
875 put2byte(&data[start+2], size);
drhf49661a2008-12-10 16:45:50 +0000876 pPage->nFree += (u16)size;
drh9e572e62004-04-23 23:43:10 +0000877
878 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +0000879 addr = pPage->hdrOffset + 1;
880 while( (pbegin = get2byte(&data[addr]))>0 ){
drhf49661a2008-12-10 16:45:50 +0000881 int pnext, psize, x;
drh3aac2dd2004-04-26 14:10:20 +0000882 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +0000883 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +0000884 pnext = get2byte(&data[pbegin]);
885 psize = get2byte(&data[pbegin+2]);
886 if( pbegin + psize + 3 >= pnext && pnext>0 ){
887 int frag = pnext - (pbegin+psize);
drhf49661a2008-12-10 16:45:50 +0000888 if( (frag<0) || (frag>(int)data[pPage->hdrOffset+7]) ){
shanedcc50b72008-11-13 18:29:50 +0000889 return SQLITE_CORRUPT_BKPT;
890 }
drhf49661a2008-12-10 16:45:50 +0000891 data[pPage->hdrOffset+7] -= (u8)frag;
892 x = get2byte(&data[pnext]);
893 put2byte(&data[pbegin], x);
894 x = pnext + get2byte(&data[pnext+2]) - pbegin;
895 put2byte(&data[pbegin+2], x);
drh9e572e62004-04-23 23:43:10 +0000896 }else{
drh3aac2dd2004-04-26 14:10:20 +0000897 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +0000898 }
899 }
drh7e3b0a02001-04-28 16:52:40 +0000900
drh43605152004-05-29 21:46:49 +0000901 /* If the cell content area begins with a freeblock, remove it. */
902 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
903 int top;
904 pbegin = get2byte(&data[hdr+1]);
905 memcpy(&data[hdr+1], &data[pbegin], 2);
drhf49661a2008-12-10 16:45:50 +0000906 top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
907 put2byte(&data[hdr+5], top);
drh4b70f112004-05-02 21:12:19 +0000908 }
drhc5053fb2008-11-27 02:22:10 +0000909 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
shanedcc50b72008-11-13 18:29:50 +0000910 return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +0000911}
912
913/*
drh271efa52004-05-30 19:19:05 +0000914** Decode the flags byte (the first byte of the header) for a page
915** and initialize fields of the MemPage structure accordingly.
drh44845222008-07-17 18:39:57 +0000916**
917** Only the following combinations are supported. Anything different
918** indicates a corrupt database files:
919**
920** PTF_ZERODATA
921** PTF_ZERODATA | PTF_LEAF
922** PTF_LEAFDATA | PTF_INTKEY
923** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
drh271efa52004-05-30 19:19:05 +0000924*/
drh44845222008-07-17 18:39:57 +0000925static int decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +0000926 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +0000927
928 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +0000929 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +0000930 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
drh44845222008-07-17 18:39:57 +0000931 flagByte &= ~PTF_LEAF;
932 pPage->childPtrSize = 4-4*pPage->leaf;
drh271efa52004-05-30 19:19:05 +0000933 pBt = pPage->pBt;
drh44845222008-07-17 18:39:57 +0000934 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
935 pPage->intKey = 1;
936 pPage->hasData = pPage->leaf;
drh271efa52004-05-30 19:19:05 +0000937 pPage->maxLocal = pBt->maxLeaf;
938 pPage->minLocal = pBt->minLeaf;
drh44845222008-07-17 18:39:57 +0000939 }else if( flagByte==PTF_ZERODATA ){
940 pPage->intKey = 0;
941 pPage->hasData = 0;
drh271efa52004-05-30 19:19:05 +0000942 pPage->maxLocal = pBt->maxLocal;
943 pPage->minLocal = pBt->minLocal;
drh44845222008-07-17 18:39:57 +0000944 }else{
945 return SQLITE_CORRUPT_BKPT;
drh271efa52004-05-30 19:19:05 +0000946 }
drh44845222008-07-17 18:39:57 +0000947 return SQLITE_OK;
drh271efa52004-05-30 19:19:05 +0000948}
949
950/*
drh7e3b0a02001-04-28 16:52:40 +0000951** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000952**
953** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +0000954** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +0000955** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
956** guarantee that the page is well-formed. It only shows that
957** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000958*/
danielk197771d5d2c2008-09-29 11:49:47 +0000959int sqlite3BtreeInitPage(MemPage *pPage){
drh2af926b2001-05-15 00:39:25 +0000960
danielk197771d5d2c2008-09-29 11:49:47 +0000961 assert( pPage->pBt!=0 );
962 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +0000963 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +0000964 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
965 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +0000966
967 if( !pPage->isInit ){
drhf49661a2008-12-10 16:45:50 +0000968 u16 pc; /* Address of a freeblock within pPage->aData[] */
969 u8 hdr; /* Offset to beginning of page header */
danielk197771d5d2c2008-09-29 11:49:47 +0000970 u8 *data; /* Equal to pPage->aData */
971 BtShared *pBt; /* The main btree structure */
drhf49661a2008-12-10 16:45:50 +0000972 u16 usableSize; /* Amount of usable space on each page */
973 u16 cellOffset; /* Offset from start of page to first cell pointer */
974 u16 nFree; /* Number of unused bytes on the page */
975 u16 top; /* First byte of the cell content area */
danielk197771d5d2c2008-09-29 11:49:47 +0000976
977 pBt = pPage->pBt;
978
danielk1977eaa06f62008-09-18 17:34:44 +0000979 hdr = pPage->hdrOffset;
980 data = pPage->aData;
981 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
982 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
983 pPage->maskPage = pBt->pageSize - 1;
984 pPage->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +0000985 usableSize = pBt->usableSize;
986 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
987 top = get2byte(&data[hdr+5]);
988 pPage->nCell = get2byte(&data[hdr+3]);
989 if( pPage->nCell>MX_CELL(pBt) ){
990 /* To many cells for a single page. The page must be corrupt */
991 return SQLITE_CORRUPT_BKPT;
992 }
danielk1977eaa06f62008-09-18 17:34:44 +0000993
994 /* Compute the total free space on the page */
995 pc = get2byte(&data[hdr+1]);
996 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
997 while( pc>0 ){
drh1bd10f82008-12-10 21:19:56 +0000998 u16 next, size;
danielk1977eaa06f62008-09-18 17:34:44 +0000999 if( pc>usableSize-4 ){
1000 /* Free block is off the page */
1001 return SQLITE_CORRUPT_BKPT;
1002 }
1003 next = get2byte(&data[pc]);
1004 size = get2byte(&data[pc+2]);
1005 if( next>0 && next<=pc+size+3 ){
1006 /* Free blocks must be in accending order */
1007 return SQLITE_CORRUPT_BKPT;
1008 }
1009 nFree += size;
1010 pc = next;
1011 }
drhf49661a2008-12-10 16:45:50 +00001012 pPage->nFree = (u16)nFree;
danielk1977eaa06f62008-09-18 17:34:44 +00001013 if( nFree>=usableSize ){
1014 /* Free space cannot exceed total page size */
drh49285702005-09-17 15:20:26 +00001015 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001016 }
drh9e572e62004-04-23 23:43:10 +00001017
drh1688c862008-07-18 02:44:17 +00001018#if 0
1019 /* Check that all the offsets in the cell offset array are within range.
1020 **
1021 ** Omitting this consistency check and using the pPage->maskPage mask
1022 ** to prevent overrunning the page buffer in findCell() results in a
1023 ** 2.5% performance gain.
1024 */
1025 {
1026 u8 *pOff; /* Iterator used to check all cell offsets are in range */
1027 u8 *pEnd; /* Pointer to end of cell offset array */
1028 u8 mask; /* Mask of bits that must be zero in MSB of cell offsets */
1029 mask = ~(((u8)(pBt->pageSize>>8))-1);
1030 pEnd = &data[cellOffset + pPage->nCell*2];
1031 for(pOff=&data[cellOffset]; pOff!=pEnd && !((*pOff)&mask); pOff+=2);
1032 if( pOff!=pEnd ){
1033 return SQLITE_CORRUPT_BKPT;
1034 }
danielk1977e16535f2008-06-11 18:15:29 +00001035 }
drh1688c862008-07-18 02:44:17 +00001036#endif
danielk1977e16535f2008-06-11 18:15:29 +00001037
danielk197771d5d2c2008-09-29 11:49:47 +00001038 pPage->isInit = 1;
1039 }
drh9e572e62004-04-23 23:43:10 +00001040 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001041}
1042
1043/*
drh8b2f49b2001-06-08 00:21:52 +00001044** Set up a raw page so that it looks like a database page holding
1045** no entries.
drhbd03cae2001-06-02 02:40:57 +00001046*/
drh9e572e62004-04-23 23:43:10 +00001047static void zeroPage(MemPage *pPage, int flags){
1048 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001049 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00001050 u8 hdr = pPage->hdrOffset;
1051 u16 first;
drh9e572e62004-04-23 23:43:10 +00001052
danielk19773b8a05f2007-03-19 17:44:26 +00001053 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drhbf4bca52007-09-06 22:19:14 +00001054 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1055 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +00001056 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00001057 assert( sqlite3_mutex_held(pBt->mutex) );
drh1af4a6e2008-07-18 03:32:51 +00001058 /*memset(&data[hdr], 0, pBt->usableSize - hdr);*/
drh1bd10f82008-12-10 21:19:56 +00001059 data[hdr] = (char)flags;
1060 first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
drh43605152004-05-29 21:46:49 +00001061 memset(&data[hdr+1], 0, 4);
1062 data[hdr+7] = 0;
1063 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +00001064 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +00001065 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +00001066 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +00001067 pPage->cellOffset = first;
1068 pPage->nOverflow = 0;
drh1688c862008-07-18 02:44:17 +00001069 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
1070 pPage->maskPage = pBt->pageSize - 1;
drh43605152004-05-29 21:46:49 +00001071 pPage->nCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001072 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00001073}
1074
drh897a8202008-09-18 01:08:15 +00001075
1076/*
1077** Convert a DbPage obtained from the pager into a MemPage used by
1078** the btree layer.
1079*/
1080static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
1081 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
1082 pPage->aData = sqlite3PagerGetData(pDbPage);
1083 pPage->pDbPage = pDbPage;
1084 pPage->pBt = pBt;
1085 pPage->pgno = pgno;
1086 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
1087 return pPage;
1088}
1089
drhbd03cae2001-06-02 02:40:57 +00001090/*
drh3aac2dd2004-04-26 14:10:20 +00001091** Get a page from the pager. Initialize the MemPage.pBt and
1092** MemPage.aData elements if needed.
drh538f5702007-04-13 02:14:30 +00001093**
1094** If the noContent flag is set, it means that we do not care about
1095** the content of the page at this time. So do not go to the disk
1096** to fetch the content. Just fill in the content with zeros for now.
1097** If in the future we call sqlite3PagerWrite() on this page, that
1098** means we have started to be concerned about content and the disk
1099** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00001100*/
drh16a9b832007-05-05 18:39:25 +00001101int sqlite3BtreeGetPage(
1102 BtShared *pBt, /* The btree */
1103 Pgno pgno, /* Number of the page to fetch */
1104 MemPage **ppPage, /* Return the page in this parameter */
1105 int noContent /* Do not load page content if true */
1106){
drh3aac2dd2004-04-26 14:10:20 +00001107 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001108 DbPage *pDbPage;
1109
drh1fee73e2007-08-29 04:00:57 +00001110 assert( sqlite3_mutex_held(pBt->mutex) );
drh538f5702007-04-13 02:14:30 +00001111 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
drh3aac2dd2004-04-26 14:10:20 +00001112 if( rc ) return rc;
drh897a8202008-09-18 01:08:15 +00001113 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
drh3aac2dd2004-04-26 14:10:20 +00001114 return SQLITE_OK;
1115}
1116
1117/*
danielk197789d40042008-11-17 14:20:56 +00001118** Return the size of the database file in pages. If there is any kind of
1119** error, return ((unsigned int)-1).
danielk197767fd7a92008-09-10 17:53:35 +00001120*/
danielk197789d40042008-11-17 14:20:56 +00001121static Pgno pagerPagecount(BtShared *pBt){
1122 int nPage = -1;
danielk197767fd7a92008-09-10 17:53:35 +00001123 int rc;
danielk197789d40042008-11-17 14:20:56 +00001124 assert( pBt->pPage1 );
1125 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1126 assert( rc==SQLITE_OK || nPage==-1 );
1127 return (Pgno)nPage;
danielk197767fd7a92008-09-10 17:53:35 +00001128}
1129
1130/*
drhde647132004-05-07 17:57:49 +00001131** Get a page from the pager and initialize it. This routine
1132** is just a convenience wrapper around separate calls to
drh16a9b832007-05-05 18:39:25 +00001133** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
drhde647132004-05-07 17:57:49 +00001134*/
1135static int getAndInitPage(
danielk1977aef0bf62005-12-30 16:28:01 +00001136 BtShared *pBt, /* The database file */
drhde647132004-05-07 17:57:49 +00001137 Pgno pgno, /* Number of the page to get */
danielk197771d5d2c2008-09-29 11:49:47 +00001138 MemPage **ppPage /* Write the page pointer here */
drhde647132004-05-07 17:57:49 +00001139){
1140 int rc;
drh897a8202008-09-18 01:08:15 +00001141 DbPage *pDbPage;
1142 MemPage *pPage;
1143
drh1fee73e2007-08-29 04:00:57 +00001144 assert( sqlite3_mutex_held(pBt->mutex) );
drh897a8202008-09-18 01:08:15 +00001145 if( pgno==0 ){
drh49285702005-09-17 15:20:26 +00001146 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001147 }
danielk19779f580ad2008-09-10 14:45:57 +00001148
drh897a8202008-09-18 01:08:15 +00001149 /* It is often the case that the page we want is already in cache.
1150 ** If so, get it directly. This saves us from having to call
1151 ** pagerPagecount() to make sure pgno is within limits, which results
1152 ** in a measureable performance improvements.
1153 */
1154 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
1155 if( pDbPage ){
1156 /* Page is already in cache */
1157 *ppPage = pPage = btreePageFromDbPage(pDbPage, pgno, pBt);
1158 rc = SQLITE_OK;
1159 }else{
1160 /* Page not in cache. Acquire it. */
danielk197789d40042008-11-17 14:20:56 +00001161 if( pgno>pagerPagecount(pBt) ){
drh897a8202008-09-18 01:08:15 +00001162 return SQLITE_CORRUPT_BKPT;
1163 }
1164 rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
1165 if( rc ) return rc;
1166 pPage = *ppPage;
1167 }
danielk197771d5d2c2008-09-29 11:49:47 +00001168 if( !pPage->isInit ){
1169 rc = sqlite3BtreeInitPage(pPage);
drh897a8202008-09-18 01:08:15 +00001170 }
1171 if( rc!=SQLITE_OK ){
1172 releasePage(pPage);
1173 *ppPage = 0;
1174 }
drhde647132004-05-07 17:57:49 +00001175 return rc;
1176}
1177
1178/*
drh3aac2dd2004-04-26 14:10:20 +00001179** Release a MemPage. This should be called once for each prior
drh16a9b832007-05-05 18:39:25 +00001180** call to sqlite3BtreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +00001181*/
drh4b70f112004-05-02 21:12:19 +00001182static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001183 if( pPage ){
1184 assert( pPage->aData );
1185 assert( pPage->pBt );
drhbf4bca52007-09-06 22:19:14 +00001186 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1187 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
drh1fee73e2007-08-29 04:00:57 +00001188 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001189 sqlite3PagerUnref(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00001190 }
1191}
1192
1193/*
drha6abd042004-06-09 17:37:22 +00001194** During a rollback, when the pager reloads information into the cache
1195** so that the cache is restored to its original state at the start of
1196** the transaction, for each page restored this routine is called.
1197**
1198** This routine needs to reset the extra data section at the end of the
1199** page to agree with the restored data.
1200*/
danielk1977eaa06f62008-09-18 17:34:44 +00001201static void pageReinit(DbPage *pData){
drh07d183d2005-05-01 22:52:42 +00001202 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00001203 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
danielk197771d5d2c2008-09-29 11:49:47 +00001204 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00001205 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00001206 pPage->isInit = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001207 if( sqlite3PagerPageRefcount(pData)>0 ){
1208 sqlite3BtreeInitPage(pPage);
1209 }
drha6abd042004-06-09 17:37:22 +00001210 }
1211}
1212
1213/*
drhe5fe6902007-12-07 18:55:28 +00001214** Invoke the busy handler for a btree.
1215*/
danielk19771ceedd32008-11-19 10:22:33 +00001216static int btreeInvokeBusyHandler(void *pArg){
drhe5fe6902007-12-07 18:55:28 +00001217 BtShared *pBt = (BtShared*)pArg;
1218 assert( pBt->db );
1219 assert( sqlite3_mutex_held(pBt->db->mutex) );
1220 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
1221}
1222
1223/*
drhad3e0102004-09-03 23:32:18 +00001224** Open a database file.
1225**
drh382c0242001-10-06 16:33:02 +00001226** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001227** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001228** database file will be deleted when sqlite3BtreeClose() is called.
drhe53831d2007-08-17 01:14:38 +00001229** If zFilename is ":memory:" then an in-memory database is created
1230** that is automatically destroyed when it is closed.
drha059ad02001-04-17 20:09:11 +00001231*/
drh23e11ca2004-05-04 17:27:28 +00001232int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001233 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00001234 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001235 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00001236 int flags, /* Options */
1237 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00001238){
drhd677b3d2007-08-20 22:48:41 +00001239 sqlite3_vfs *pVfs; /* The VFS to use for this btree */
drhe53831d2007-08-17 01:14:38 +00001240 BtShared *pBt = 0; /* Shared part of btree structure */
danielk1977aef0bf62005-12-30 16:28:01 +00001241 Btree *p; /* Handle to return */
danielk1977dddbcdc2007-04-26 14:42:34 +00001242 int rc = SQLITE_OK;
drhf49661a2008-12-10 16:45:50 +00001243 u8 nReserve;
drh90f5ecb2004-07-22 01:19:35 +00001244 unsigned char zDbHeader[100];
danielk1977aef0bf62005-12-30 16:28:01 +00001245
1246 /* Set the variable isMemdb to true for an in-memory database, or
1247 ** false for a file-based database. This symbol is only required if
1248 ** either of the shared-data or autovacuum features are compiled
1249 ** into the library.
1250 */
1251#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
1252 #ifdef SQLITE_OMIT_MEMORYDB
drh980b1a72006-08-16 16:42:48 +00001253 const int isMemdb = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00001254 #else
drh980b1a72006-08-16 16:42:48 +00001255 const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
danielk1977aef0bf62005-12-30 16:28:01 +00001256 #endif
1257#endif
1258
drhe5fe6902007-12-07 18:55:28 +00001259 assert( db!=0 );
1260 assert( sqlite3_mutex_held(db->mutex) );
drh153c62c2007-08-24 03:51:33 +00001261
drhe5fe6902007-12-07 18:55:28 +00001262 pVfs = db->pVfs;
drh17435752007-08-16 04:30:38 +00001263 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00001264 if( !p ){
1265 return SQLITE_NOMEM;
1266 }
1267 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00001268 p->db = db;
danielk1977aef0bf62005-12-30 16:28:01 +00001269
drh198bf392006-01-06 21:52:49 +00001270#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001271 /*
1272 ** If this Btree is a candidate for shared cache, try to find an
1273 ** existing BtShared object that we can share with
1274 */
drh34004ce2008-07-11 16:15:17 +00001275 if( isMemdb==0
drhe5fe6902007-12-07 18:55:28 +00001276 && (db->flags & SQLITE_Vtab)==0
drhe53831d2007-08-17 01:14:38 +00001277 && zFilename && zFilename[0]
drhe53831d2007-08-17 01:14:38 +00001278 ){
danielk1977502b4e02008-09-02 14:07:24 +00001279 if( sqlite3GlobalConfig.sharedCacheEnabled ){
danielk1977adfb9b02007-09-17 07:02:56 +00001280 int nFullPathname = pVfs->mxPathname+1;
drhe5ae5732008-06-15 02:51:47 +00001281 char *zFullPathname = sqlite3Malloc(nFullPathname);
drhff0587c2007-08-29 17:43:19 +00001282 sqlite3_mutex *mutexShared;
1283 p->sharable = 1;
drh34004ce2008-07-11 16:15:17 +00001284 db->flags |= SQLITE_SharedCache;
drhff0587c2007-08-29 17:43:19 +00001285 if( !zFullPathname ){
1286 sqlite3_free(p);
1287 return SQLITE_NOMEM;
1288 }
danielk1977adfb9b02007-09-17 07:02:56 +00001289 sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
danielk197759f8c082008-06-18 17:09:10 +00001290 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhff0587c2007-08-29 17:43:19 +00001291 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001292 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
drhff0587c2007-08-29 17:43:19 +00001293 assert( pBt->nRef>0 );
1294 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
1295 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
1296 p->pBt = pBt;
1297 pBt->nRef++;
1298 break;
1299 }
1300 }
1301 sqlite3_mutex_leave(mutexShared);
1302 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00001303 }
drhff0587c2007-08-29 17:43:19 +00001304#ifdef SQLITE_DEBUG
1305 else{
1306 /* In debug mode, we mark all persistent databases as sharable
1307 ** even when they are not. This exercises the locking code and
1308 ** gives more opportunity for asserts(sqlite3_mutex_held())
1309 ** statements to find locking problems.
1310 */
1311 p->sharable = 1;
1312 }
1313#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001314 }
1315#endif
drha059ad02001-04-17 20:09:11 +00001316 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00001317 /*
1318 ** The following asserts make sure that structures used by the btree are
1319 ** the right size. This is to guard against size changes that result
1320 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00001321 */
drhe53831d2007-08-17 01:14:38 +00001322 assert( sizeof(i64)==8 || sizeof(i64)==4 );
1323 assert( sizeof(u64)==8 || sizeof(u64)==4 );
1324 assert( sizeof(u32)==4 );
1325 assert( sizeof(u16)==2 );
1326 assert( sizeof(Pgno)==4 );
1327
1328 pBt = sqlite3MallocZero( sizeof(*pBt) );
1329 if( pBt==0 ){
1330 rc = SQLITE_NOMEM;
1331 goto btree_open_out;
1332 }
danielk197771d5d2c2008-09-29 11:49:47 +00001333 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
drh33f4e022007-09-03 15:19:34 +00001334 EXTRA_SIZE, flags, vfsFlags);
drhe53831d2007-08-17 01:14:38 +00001335 if( rc==SQLITE_OK ){
1336 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
1337 }
1338 if( rc!=SQLITE_OK ){
1339 goto btree_open_out;
1340 }
danielk19771ceedd32008-11-19 10:22:33 +00001341 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
drhe53831d2007-08-17 01:14:38 +00001342 p->pBt = pBt;
1343
drhe53831d2007-08-17 01:14:38 +00001344 sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
1345 pBt->pCursor = 0;
1346 pBt->pPage1 = 0;
1347 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
1348 pBt->pageSize = get2byte(&zDbHeader[16]);
1349 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1350 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00001351 pBt->pageSize = 0;
1352 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drhe53831d2007-08-17 01:14:38 +00001353#ifndef SQLITE_OMIT_AUTOVACUUM
1354 /* If the magic name ":memory:" will create an in-memory database, then
1355 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
1356 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
1357 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
1358 ** regular file-name. In this case the auto-vacuum applies as per normal.
1359 */
1360 if( zFilename && !isMemdb ){
1361 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
1362 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
1363 }
1364#endif
1365 nReserve = 0;
1366 }else{
1367 nReserve = zDbHeader[20];
drhe53831d2007-08-17 01:14:38 +00001368 pBt->pageSizeFixed = 1;
1369#ifndef SQLITE_OMIT_AUTOVACUUM
1370 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1371 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
1372#endif
1373 }
1374 pBt->usableSize = pBt->pageSize - nReserve;
1375 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
danielk1977a1644fd2007-08-29 12:31:25 +00001376 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drhe53831d2007-08-17 01:14:38 +00001377
1378#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1379 /* Add the new BtShared object to the linked list sharable BtShareds.
1380 */
1381 if( p->sharable ){
1382 sqlite3_mutex *mutexShared;
1383 pBt->nRef = 1;
danielk197759f8c082008-06-18 17:09:10 +00001384 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
danielk1977075c23a2008-09-01 18:34:20 +00001385 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
danielk197759f8c082008-06-18 17:09:10 +00001386 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
drh3285db22007-09-03 22:00:39 +00001387 if( pBt->mutex==0 ){
1388 rc = SQLITE_NOMEM;
drhe5fe6902007-12-07 18:55:28 +00001389 db->mallocFailed = 0;
drh3285db22007-09-03 22:00:39 +00001390 goto btree_open_out;
1391 }
drhff0587c2007-08-29 17:43:19 +00001392 }
drhe53831d2007-08-17 01:14:38 +00001393 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001394 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
1395 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
drhe53831d2007-08-17 01:14:38 +00001396 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00001397 }
drheee46cf2004-11-06 00:02:48 +00001398#endif
drh90f5ecb2004-07-22 01:19:35 +00001399 }
danielk1977aef0bf62005-12-30 16:28:01 +00001400
drhcfed7bc2006-03-13 14:28:05 +00001401#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001402 /* If the new Btree uses a sharable pBtShared, then link the new
1403 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00001404 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00001405 */
drhe53831d2007-08-17 01:14:38 +00001406 if( p->sharable ){
1407 int i;
1408 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00001409 for(i=0; i<db->nDb; i++){
1410 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00001411 while( pSib->pPrev ){ pSib = pSib->pPrev; }
1412 if( p->pBt<pSib->pBt ){
1413 p->pNext = pSib;
1414 p->pPrev = 0;
1415 pSib->pPrev = p;
1416 }else{
drhabddb0c2007-08-20 13:14:28 +00001417 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
drhe53831d2007-08-17 01:14:38 +00001418 pSib = pSib->pNext;
1419 }
1420 p->pNext = pSib->pNext;
1421 p->pPrev = pSib;
1422 if( p->pNext ){
1423 p->pNext->pPrev = p;
1424 }
1425 pSib->pNext = p;
1426 }
1427 break;
1428 }
1429 }
danielk1977aef0bf62005-12-30 16:28:01 +00001430 }
danielk1977aef0bf62005-12-30 16:28:01 +00001431#endif
1432 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00001433
1434btree_open_out:
1435 if( rc!=SQLITE_OK ){
1436 if( pBt && pBt->pPager ){
1437 sqlite3PagerClose(pBt->pPager);
1438 }
drh17435752007-08-16 04:30:38 +00001439 sqlite3_free(pBt);
1440 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00001441 *ppBtree = 0;
1442 }
1443 return rc;
drha059ad02001-04-17 20:09:11 +00001444}
1445
1446/*
drhe53831d2007-08-17 01:14:38 +00001447** Decrement the BtShared.nRef counter. When it reaches zero,
1448** remove the BtShared structure from the sharing list. Return
1449** true if the BtShared.nRef counter reaches zero and return
1450** false if it is still positive.
1451*/
1452static int removeFromSharingList(BtShared *pBt){
1453#ifndef SQLITE_OMIT_SHARED_CACHE
1454 sqlite3_mutex *pMaster;
1455 BtShared *pList;
1456 int removed = 0;
1457
drhd677b3d2007-08-20 22:48:41 +00001458 assert( sqlite3_mutex_notheld(pBt->mutex) );
danielk197759f8c082008-06-18 17:09:10 +00001459 pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhe53831d2007-08-17 01:14:38 +00001460 sqlite3_mutex_enter(pMaster);
1461 pBt->nRef--;
1462 if( pBt->nRef<=0 ){
drh78f82d12008-09-02 00:52:52 +00001463 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
1464 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
drhe53831d2007-08-17 01:14:38 +00001465 }else{
drh78f82d12008-09-02 00:52:52 +00001466 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
drh34004ce2008-07-11 16:15:17 +00001467 while( ALWAYS(pList) && pList->pNext!=pBt ){
drhe53831d2007-08-17 01:14:38 +00001468 pList=pList->pNext;
1469 }
drh34004ce2008-07-11 16:15:17 +00001470 if( ALWAYS(pList) ){
drhe53831d2007-08-17 01:14:38 +00001471 pList->pNext = pBt->pNext;
1472 }
1473 }
drh3285db22007-09-03 22:00:39 +00001474 if( SQLITE_THREADSAFE ){
1475 sqlite3_mutex_free(pBt->mutex);
1476 }
drhe53831d2007-08-17 01:14:38 +00001477 removed = 1;
1478 }
1479 sqlite3_mutex_leave(pMaster);
1480 return removed;
1481#else
1482 return 1;
1483#endif
1484}
1485
1486/*
drhf7141992008-06-19 00:16:08 +00001487** Make sure pBt->pTmpSpace points to an allocation of
1488** MX_CELL_SIZE(pBt) bytes.
1489*/
1490static void allocateTempSpace(BtShared *pBt){
1491 if( !pBt->pTmpSpace ){
1492 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
1493 }
1494}
1495
1496/*
1497** Free the pBt->pTmpSpace allocation
1498*/
1499static void freeTempSpace(BtShared *pBt){
1500 sqlite3PageFree( pBt->pTmpSpace);
1501 pBt->pTmpSpace = 0;
1502}
1503
1504/*
drha059ad02001-04-17 20:09:11 +00001505** Close an open database and invalidate all cursors.
1506*/
danielk1977aef0bf62005-12-30 16:28:01 +00001507int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00001508 BtShared *pBt = p->pBt;
1509 BtCursor *pCur;
1510
danielk1977aef0bf62005-12-30 16:28:01 +00001511 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00001512 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00001513 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00001514 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00001515 pCur = pBt->pCursor;
1516 while( pCur ){
1517 BtCursor *pTmp = pCur;
1518 pCur = pCur->pNext;
1519 if( pTmp->pBtree==p ){
1520 sqlite3BtreeCloseCursor(pTmp);
1521 }
drha059ad02001-04-17 20:09:11 +00001522 }
danielk1977aef0bf62005-12-30 16:28:01 +00001523
danielk19778d34dfd2006-01-24 16:37:57 +00001524 /* Rollback any active transaction and free the handle structure.
1525 ** The call to sqlite3BtreeRollback() drops any table-locks held by
1526 ** this handle.
1527 */
danielk1977b597f742006-01-15 11:39:18 +00001528 sqlite3BtreeRollback(p);
drhe53831d2007-08-17 01:14:38 +00001529 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001530
danielk1977aef0bf62005-12-30 16:28:01 +00001531 /* If there are still other outstanding references to the shared-btree
1532 ** structure, return now. The remainder of this procedure cleans
1533 ** up the shared-btree.
1534 */
drhe53831d2007-08-17 01:14:38 +00001535 assert( p->wantToLock==0 && p->locked==0 );
1536 if( !p->sharable || removeFromSharingList(pBt) ){
1537 /* The pBt is no longer on the sharing list, so we can access
1538 ** it without having to hold the mutex.
1539 **
1540 ** Clean out and delete the BtShared object.
1541 */
1542 assert( !pBt->pCursor );
drhe53831d2007-08-17 01:14:38 +00001543 sqlite3PagerClose(pBt->pPager);
1544 if( pBt->xFreeSchema && pBt->pSchema ){
1545 pBt->xFreeSchema(pBt->pSchema);
1546 }
1547 sqlite3_free(pBt->pSchema);
drhf7141992008-06-19 00:16:08 +00001548 freeTempSpace(pBt);
drh65bbf292008-06-19 01:03:17 +00001549 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00001550 }
1551
drhe53831d2007-08-17 01:14:38 +00001552#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00001553 assert( p->wantToLock==0 );
1554 assert( p->locked==0 );
1555 if( p->pPrev ) p->pPrev->pNext = p->pNext;
1556 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00001557#endif
1558
drhe53831d2007-08-17 01:14:38 +00001559 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00001560 return SQLITE_OK;
1561}
1562
1563/*
drhda47d772002-12-02 04:25:19 +00001564** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001565**
1566** The maximum number of cache pages is set to the absolute
1567** value of mxPage. If mxPage is negative, the pager will
1568** operate asynchronously - it will not stop to do fsync()s
1569** to insure data is written to the disk surface before
1570** continuing. Transactions still work if synchronous is off,
1571** and the database cannot be corrupted if this program
1572** crashes. But if the operating system crashes or there is
1573** an abrupt power failure when synchronous is off, the database
1574** could be left in an inconsistent and unrecoverable state.
1575** Synchronous is on by default so database corruption is not
1576** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001577*/
danielk1977aef0bf62005-12-30 16:28:01 +00001578int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
1579 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001580 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001581 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001582 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00001583 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00001584 return SQLITE_OK;
1585}
1586
1587/*
drh973b6e32003-02-12 14:09:42 +00001588** Change the way data is synced to disk in order to increase or decrease
1589** how well the database resists damage due to OS crashes and power
1590** failures. Level 1 is the same as asynchronous (no syncs() occur and
1591** there is a high probability of damage) Level 2 is the default. There
1592** is a very low but non-zero probability of damage. Level 3 reduces the
1593** probability of damage to near zero but with a write performance reduction.
1594*/
danielk197793758c82005-01-21 08:13:14 +00001595#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drhac530b12006-02-11 01:25:50 +00001596int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
danielk1977aef0bf62005-12-30 16:28:01 +00001597 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001598 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001599 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001600 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
drhd677b3d2007-08-20 22:48:41 +00001601 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00001602 return SQLITE_OK;
1603}
danielk197793758c82005-01-21 08:13:14 +00001604#endif
drh973b6e32003-02-12 14:09:42 +00001605
drh2c8997b2005-08-27 16:36:48 +00001606/*
1607** Return TRUE if the given btree is set to safety level 1. In other
1608** words, return TRUE if no sync() occurs on the disk files.
1609*/
danielk1977aef0bf62005-12-30 16:28:01 +00001610int sqlite3BtreeSyncDisabled(Btree *p){
1611 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001612 int rc;
drhe5fe6902007-12-07 18:55:28 +00001613 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001614 sqlite3BtreeEnter(p);
drhd0679ed2007-08-28 22:24:34 +00001615 assert( pBt && pBt->pPager );
drhd677b3d2007-08-20 22:48:41 +00001616 rc = sqlite3PagerNosync(pBt->pPager);
1617 sqlite3BtreeLeave(p);
1618 return rc;
drh2c8997b2005-08-27 16:36:48 +00001619}
1620
danielk1977576ec6b2005-01-21 11:55:25 +00001621#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00001622/*
drh90f5ecb2004-07-22 01:19:35 +00001623** Change the default pages size and the number of reserved bytes per page.
drh06f50212004-11-02 14:24:33 +00001624**
1625** The page size must be a power of 2 between 512 and 65536. If the page
1626** size supplied does not meet this constraint then the page size is not
1627** changed.
1628**
1629** Page sizes are constrained to be a power of two so that the region
1630** of the database file used for locking (beginning at PENDING_BYTE,
1631** the first byte past the 1GB boundary, 0x40000000) needs to occur
1632** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001633**
1634** If parameter nReserve is less than zero, then the number of reserved
1635** bytes per page is left unchanged.
drh90f5ecb2004-07-22 01:19:35 +00001636*/
danielk1977aef0bf62005-12-30 16:28:01 +00001637int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
danielk1977a1644fd2007-08-29 12:31:25 +00001638 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00001639 BtShared *pBt = p->pBt;
drhf49661a2008-12-10 16:45:50 +00001640 assert( nReserve>=-1 && nReserve<=255 );
drhd677b3d2007-08-20 22:48:41 +00001641 sqlite3BtreeEnter(p);
drh90f5ecb2004-07-22 01:19:35 +00001642 if( pBt->pageSizeFixed ){
drhd677b3d2007-08-20 22:48:41 +00001643 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00001644 return SQLITE_READONLY;
1645 }
1646 if( nReserve<0 ){
1647 nReserve = pBt->pageSize - pBt->usableSize;
1648 }
drhf49661a2008-12-10 16:45:50 +00001649 assert( nReserve>=0 && nReserve<=255 );
drh06f50212004-11-02 14:24:33 +00001650 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
1651 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00001652 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00001653 assert( !pBt->pPage1 && !pBt->pCursor );
drh1bd10f82008-12-10 21:19:56 +00001654 pBt->pageSize = (u16)pageSize;
drhf7141992008-06-19 00:16:08 +00001655 freeTempSpace(pBt);
danielk1977a1644fd2007-08-29 12:31:25 +00001656 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001657 }
drhf49661a2008-12-10 16:45:50 +00001658 pBt->usableSize = pBt->pageSize - (u16)nReserve;
drhd677b3d2007-08-20 22:48:41 +00001659 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00001660 return rc;
drh90f5ecb2004-07-22 01:19:35 +00001661}
1662
1663/*
1664** Return the currently defined page size
1665*/
danielk1977aef0bf62005-12-30 16:28:01 +00001666int sqlite3BtreeGetPageSize(Btree *p){
1667 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00001668}
danielk1977aef0bf62005-12-30 16:28:01 +00001669int sqlite3BtreeGetReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00001670 int n;
1671 sqlite3BtreeEnter(p);
1672 n = p->pBt->pageSize - p->pBt->usableSize;
1673 sqlite3BtreeLeave(p);
1674 return n;
drh2011d5f2004-07-22 02:40:37 +00001675}
drhf8e632b2007-05-08 14:51:36 +00001676
1677/*
1678** Set the maximum page count for a database if mxPage is positive.
1679** No changes are made if mxPage is 0 or negative.
1680** Regardless of the value of mxPage, return the maximum page count.
1681*/
1682int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00001683 int n;
1684 sqlite3BtreeEnter(p);
1685 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
1686 sqlite3BtreeLeave(p);
1687 return n;
drhf8e632b2007-05-08 14:51:36 +00001688}
danielk1977576ec6b2005-01-21 11:55:25 +00001689#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00001690
1691/*
danielk1977951af802004-11-05 15:45:09 +00001692** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
1693** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
1694** is disabled. The default value for the auto-vacuum property is
1695** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
1696*/
danielk1977aef0bf62005-12-30 16:28:01 +00001697int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00001698#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001699 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00001700#else
danielk1977dddbcdc2007-04-26 14:42:34 +00001701 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001702 int rc = SQLITE_OK;
drhf49661a2008-12-10 16:45:50 +00001703 u8 av = autoVacuum ?1:0;
drhd677b3d2007-08-20 22:48:41 +00001704
1705 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00001706 if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00001707 rc = SQLITE_READONLY;
1708 }else{
1709 pBt->autoVacuum = av;
danielk1977951af802004-11-05 15:45:09 +00001710 }
drhd677b3d2007-08-20 22:48:41 +00001711 sqlite3BtreeLeave(p);
1712 return rc;
danielk1977951af802004-11-05 15:45:09 +00001713#endif
1714}
1715
1716/*
1717** Return the value of the 'auto-vacuum' property. If auto-vacuum is
1718** enabled 1 is returned. Otherwise 0.
1719*/
danielk1977aef0bf62005-12-30 16:28:01 +00001720int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00001721#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00001722 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00001723#else
drhd677b3d2007-08-20 22:48:41 +00001724 int rc;
1725 sqlite3BtreeEnter(p);
1726 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00001727 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
1728 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
1729 BTREE_AUTOVACUUM_INCR
1730 );
drhd677b3d2007-08-20 22:48:41 +00001731 sqlite3BtreeLeave(p);
1732 return rc;
danielk1977951af802004-11-05 15:45:09 +00001733#endif
1734}
1735
1736
1737/*
drha34b6762004-05-07 13:30:42 +00001738** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001739** also acquire a readlock on that file.
1740**
1741** SQLITE_OK is returned on success. If the file is not a
1742** well-formed database file, then SQLITE_CORRUPT is returned.
1743** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00001744** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00001745*/
danielk1977aef0bf62005-12-30 16:28:01 +00001746static int lockBtree(BtShared *pBt){
danielk1977f653d782008-03-20 11:04:21 +00001747 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001748 MemPage *pPage1;
danielk197793f7af92008-05-09 16:57:50 +00001749 int nPage;
drhd677b3d2007-08-20 22:48:41 +00001750
drh1fee73e2007-08-29 04:00:57 +00001751 assert( sqlite3_mutex_held(pBt->mutex) );
drha34b6762004-05-07 13:30:42 +00001752 if( pBt->pPage1 ) return SQLITE_OK;
drh16a9b832007-05-05 18:39:25 +00001753 rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00001754 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00001755
1756 /* Do some checking to help insure the file we opened really is
1757 ** a valid database file.
1758 */
danielk1977ad0132d2008-06-07 08:58:22 +00001759 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1760 if( rc!=SQLITE_OK ){
danielk197793f7af92008-05-09 16:57:50 +00001761 goto page1_init_failed;
1762 }else if( nPage>0 ){
danielk1977f653d782008-03-20 11:04:21 +00001763 int pageSize;
1764 int usableSize;
drhb6f41482004-05-14 01:58:11 +00001765 u8 *page1 = pPage1->aData;
danielk1977ad0132d2008-06-07 08:58:22 +00001766 rc = SQLITE_NOTADB;
drhb6f41482004-05-14 01:58:11 +00001767 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001768 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001769 }
drh309169a2007-04-24 17:27:51 +00001770 if( page1[18]>1 ){
1771 pBt->readOnly = 1;
1772 }
1773 if( page1[19]>1 ){
drhb6f41482004-05-14 01:58:11 +00001774 goto page1_init_failed;
1775 }
drhe5ae5732008-06-15 02:51:47 +00001776
1777 /* The maximum embedded fraction must be exactly 25%. And the minimum
1778 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
1779 ** The original design allowed these amounts to vary, but as of
1780 ** version 3.6.0, we require them to be fixed.
1781 */
1782 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
1783 goto page1_init_failed;
1784 }
drh07d183d2005-05-01 22:52:42 +00001785 pageSize = get2byte(&page1[16]);
drh7dc385e2007-09-06 23:39:36 +00001786 if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
1787 (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
1788 ){
drh07d183d2005-05-01 22:52:42 +00001789 goto page1_init_failed;
1790 }
1791 assert( (pageSize & 7)==0 );
danielk1977f653d782008-03-20 11:04:21 +00001792 usableSize = pageSize - page1[20];
1793 if( pageSize!=pBt->pageSize ){
1794 /* After reading the first page of the database assuming a page size
1795 ** of BtShared.pageSize, we have discovered that the page-size is
1796 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
1797 ** zero and return SQLITE_OK. The caller will call this function
1798 ** again with the correct page-size.
1799 */
1800 releasePage(pPage1);
drhf49661a2008-12-10 16:45:50 +00001801 pBt->usableSize = (u16)usableSize;
1802 pBt->pageSize = (u16)pageSize;
drhf7141992008-06-19 00:16:08 +00001803 freeTempSpace(pBt);
danielk1977f653d782008-03-20 11:04:21 +00001804 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
1805 return SQLITE_OK;
1806 }
1807 if( usableSize<500 ){
drhb6f41482004-05-14 01:58:11 +00001808 goto page1_init_failed;
1809 }
drh1bd10f82008-12-10 21:19:56 +00001810 pBt->pageSize = (u16)pageSize;
1811 pBt->usableSize = (u16)usableSize;
drh057cd3a2005-02-15 16:23:02 +00001812#ifndef SQLITE_OMIT_AUTOVACUUM
1813 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00001814 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00001815#endif
drh306dc212001-05-21 13:45:10 +00001816 }
drhb6f41482004-05-14 01:58:11 +00001817
1818 /* maxLocal is the maximum amount of payload to store locally for
1819 ** a cell. Make sure it is small enough so that at least minFanout
1820 ** cells can will fit on one page. We assume a 10-byte page header.
1821 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001822 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001823 ** 4-byte child pointer
1824 ** 9-byte nKey value
1825 ** 4-byte nData value
1826 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001827 ** So a cell consists of a 2-byte poiner, a header which is as much as
1828 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1829 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001830 */
drhe5ae5732008-06-15 02:51:47 +00001831 pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
1832 pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
drh43605152004-05-29 21:46:49 +00001833 pBt->maxLeaf = pBt->usableSize - 35;
drhe5ae5732008-06-15 02:51:47 +00001834 pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
drh2e38c322004-09-03 18:38:44 +00001835 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00001836 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001837 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001838
drh72f82862001-05-24 21:06:34 +00001839page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001840 releasePage(pPage1);
1841 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001842 return rc;
drh306dc212001-05-21 13:45:10 +00001843}
1844
1845/*
drhb8ef32c2005-03-14 02:01:49 +00001846** This routine works like lockBtree() except that it also invokes the
1847** busy callback if there is lock contention.
1848*/
danielk1977aef0bf62005-12-30 16:28:01 +00001849static int lockBtreeWithRetry(Btree *pRef){
drhb8ef32c2005-03-14 02:01:49 +00001850 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00001851
drh1fee73e2007-08-29 04:00:57 +00001852 assert( sqlite3BtreeHoldsMutex(pRef) );
danielk1977aef0bf62005-12-30 16:28:01 +00001853 if( pRef->inTrans==TRANS_NONE ){
1854 u8 inTransaction = pRef->pBt->inTransaction;
1855 btreeIntegrity(pRef);
1856 rc = sqlite3BtreeBeginTrans(pRef, 0);
1857 pRef->pBt->inTransaction = inTransaction;
1858 pRef->inTrans = TRANS_NONE;
1859 if( rc==SQLITE_OK ){
1860 pRef->pBt->nTransaction--;
1861 }
1862 btreeIntegrity(pRef);
drhb8ef32c2005-03-14 02:01:49 +00001863 }
1864 return rc;
1865}
1866
1867
1868/*
drhb8ca3072001-12-05 00:21:20 +00001869** If there are no outstanding cursors and we are not in the middle
1870** of a transaction but there is a read lock on the database, then
1871** this routine unrefs the first page of the database file which
1872** has the effect of releasing the read lock.
1873**
1874** If there are any outstanding cursors, this routine is a no-op.
1875**
1876** If there is a transaction in progress, this routine is a no-op.
1877*/
danielk1977aef0bf62005-12-30 16:28:01 +00001878static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00001879 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00001880 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00001881 if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
drhde4fcfd2008-01-19 23:50:26 +00001882 assert( pBt->pPage1->aData );
1883#if 0
drh24c9a2e2007-01-05 02:00:47 +00001884 if( pBt->pPage1->aData==0 ){
1885 MemPage *pPage = pBt->pPage1;
drhbf4bca52007-09-06 22:19:14 +00001886 pPage->aData = sqlite3PagerGetData(pPage->pDbPage);
drh24c9a2e2007-01-05 02:00:47 +00001887 pPage->pBt = pBt;
1888 pPage->pgno = 1;
1889 }
drhde4fcfd2008-01-19 23:50:26 +00001890#endif
drh24c9a2e2007-01-05 02:00:47 +00001891 releasePage(pBt->pPage1);
drh51c6d962004-06-06 00:42:25 +00001892 }
drh3aac2dd2004-04-26 14:10:20 +00001893 pBt->pPage1 = 0;
drh3aac2dd2004-04-26 14:10:20 +00001894 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001895 }
1896}
1897
1898/*
drh9e572e62004-04-23 23:43:10 +00001899** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00001900** file.
drh8b2f49b2001-06-08 00:21:52 +00001901*/
danielk1977aef0bf62005-12-30 16:28:01 +00001902static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00001903 MemPage *pP1;
1904 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00001905 int rc;
danielk1977ad0132d2008-06-07 08:58:22 +00001906 int nPage;
drhd677b3d2007-08-20 22:48:41 +00001907
drh1fee73e2007-08-29 04:00:57 +00001908 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977ad0132d2008-06-07 08:58:22 +00001909 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1910 if( rc!=SQLITE_OK || nPage>0 ){
1911 return rc;
1912 }
drh3aac2dd2004-04-26 14:10:20 +00001913 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00001914 assert( pP1!=0 );
1915 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00001916 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00001917 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00001918 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
1919 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00001920 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00001921 data[18] = 1;
1922 data[19] = 1;
drhf49661a2008-12-10 16:45:50 +00001923 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
1924 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
drhe5ae5732008-06-15 02:51:47 +00001925 data[21] = 64;
1926 data[22] = 32;
1927 data[23] = 32;
drhb6f41482004-05-14 01:58:11 +00001928 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00001929 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00001930 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00001931#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00001932 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00001933 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00001934 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00001935 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00001936#endif
drh8b2f49b2001-06-08 00:21:52 +00001937 return SQLITE_OK;
1938}
1939
1940/*
danielk1977ee5741e2004-05-31 10:01:34 +00001941** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00001942** is started if the second argument is nonzero, otherwise a read-
1943** transaction. If the second argument is 2 or more and exclusive
1944** transaction is started, meaning that no other process is allowed
1945** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00001946** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00001947** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00001948**
danielk1977ee5741e2004-05-31 10:01:34 +00001949** A write-transaction must be started before attempting any
1950** changes to the database. None of the following routines
1951** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00001952**
drh23e11ca2004-05-04 17:27:28 +00001953** sqlite3BtreeCreateTable()
1954** sqlite3BtreeCreateIndex()
1955** sqlite3BtreeClearTable()
1956** sqlite3BtreeDropTable()
1957** sqlite3BtreeInsert()
1958** sqlite3BtreeDelete()
1959** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00001960**
drhb8ef32c2005-03-14 02:01:49 +00001961** If an initial attempt to acquire the lock fails because of lock contention
1962** and the database was previously unlocked, then invoke the busy handler
1963** if there is one. But if there was previously a read-lock, do not
1964** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
1965** returned when there is already a read-lock in order to avoid a deadlock.
1966**
1967** Suppose there are two processes A and B. A has a read lock and B has
1968** a reserved lock. B tries to promote to exclusive but is blocked because
1969** of A's read lock. A tries to promote to reserved but is blocked by B.
1970** One or the other of the two processes must give way or there can be
1971** no progress. By returning SQLITE_BUSY and not invoking the busy callback
1972** when A already has a read lock, we encourage A to give up and let B
1973** proceed.
drha059ad02001-04-17 20:09:11 +00001974*/
danielk1977aef0bf62005-12-30 16:28:01 +00001975int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
1976 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00001977 int rc = SQLITE_OK;
1978
drhd677b3d2007-08-20 22:48:41 +00001979 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00001980 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00001981 btreeIntegrity(p);
1982
danielk1977ee5741e2004-05-31 10:01:34 +00001983 /* If the btree is already in a write-transaction, or it
1984 ** is already in a read-transaction and a read-transaction
1985 ** is requested, this is a no-op.
1986 */
danielk1977aef0bf62005-12-30 16:28:01 +00001987 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00001988 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00001989 }
drhb8ef32c2005-03-14 02:01:49 +00001990
1991 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00001992 if( pBt->readOnly && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00001993 rc = SQLITE_READONLY;
1994 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00001995 }
1996
danielk1977aef0bf62005-12-30 16:28:01 +00001997 /* If another database handle has already opened a write transaction
1998 ** on this shared-btree structure and a second write transaction is
1999 ** requested, return SQLITE_BUSY.
2000 */
2001 if( pBt->inTransaction==TRANS_WRITE && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00002002 rc = SQLITE_BUSY;
2003 goto trans_begun;
danielk1977aef0bf62005-12-30 16:28:01 +00002004 }
2005
danielk1977641b0f42007-12-21 04:47:25 +00002006#ifndef SQLITE_OMIT_SHARED_CACHE
2007 if( wrflag>1 ){
2008 BtLock *pIter;
2009 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
2010 if( pIter->pBtree!=p ){
2011 rc = SQLITE_BUSY;
2012 goto trans_begun;
2013 }
2014 }
2015 }
2016#endif
2017
drhb8ef32c2005-03-14 02:01:49 +00002018 do {
drh8a9c17f2008-05-02 14:23:54 +00002019 if( pBt->pPage1==0 ){
2020 do{
2021 rc = lockBtree(pBt);
2022 }while( pBt->pPage1==0 && rc==SQLITE_OK );
drh8c42ca92001-06-22 19:15:00 +00002023 }
drh309169a2007-04-24 17:27:51 +00002024
drhb8ef32c2005-03-14 02:01:49 +00002025 if( rc==SQLITE_OK && wrflag ){
drh309169a2007-04-24 17:27:51 +00002026 if( pBt->readOnly ){
2027 rc = SQLITE_READONLY;
2028 }else{
2029 rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1);
2030 if( rc==SQLITE_OK ){
2031 rc = newDatabase(pBt);
2032 }
drhb8ef32c2005-03-14 02:01:49 +00002033 }
2034 }
2035
2036 if( rc==SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00002037 if( wrflag ) pBt->inStmt = 0;
2038 }else{
2039 unlockBtreeIfUnused(pBt);
2040 }
danielk1977aef0bf62005-12-30 16:28:01 +00002041 }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
danielk19771ceedd32008-11-19 10:22:33 +00002042 btreeInvokeBusyHandler(pBt) );
danielk1977aef0bf62005-12-30 16:28:01 +00002043
2044 if( rc==SQLITE_OK ){
2045 if( p->inTrans==TRANS_NONE ){
2046 pBt->nTransaction++;
2047 }
2048 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
2049 if( p->inTrans>pBt->inTransaction ){
2050 pBt->inTransaction = p->inTrans;
2051 }
danielk1977641b0f42007-12-21 04:47:25 +00002052#ifndef SQLITE_OMIT_SHARED_CACHE
2053 if( wrflag>1 ){
2054 assert( !pBt->pExclusive );
2055 pBt->pExclusive = p;
2056 }
2057#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002058 }
2059
drhd677b3d2007-08-20 22:48:41 +00002060
2061trans_begun:
danielk1977fd7f0452008-12-17 17:30:26 +00002062 if( rc==SQLITE_OK && wrflag ){
danielk197712dd5492008-12-18 15:45:07 +00002063 /* This call makes sure that the pager has the correct number of
2064 ** open savepoints. If the second parameter is greater than 0 and
2065 ** the sub-journal is not already open, then it will be opened here.
2066 */
danielk1977fd7f0452008-12-17 17:30:26 +00002067 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
2068 }
danielk197712dd5492008-12-18 15:45:07 +00002069
danielk1977aef0bf62005-12-30 16:28:01 +00002070 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002071 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00002072 return rc;
drha059ad02001-04-17 20:09:11 +00002073}
2074
danielk1977687566d2004-11-02 12:56:41 +00002075#ifndef SQLITE_OMIT_AUTOVACUUM
2076
2077/*
2078** Set the pointer-map entries for all children of page pPage. Also, if
2079** pPage contains cells that point to overflow pages, set the pointer
2080** map entries for the overflow pages as well.
2081*/
2082static int setChildPtrmaps(MemPage *pPage){
2083 int i; /* Counter variable */
2084 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00002085 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00002086 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00002087 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002088 Pgno pgno = pPage->pgno;
2089
drh1fee73e2007-08-29 04:00:57 +00002090 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197771d5d2c2008-09-29 11:49:47 +00002091 rc = sqlite3BtreeInitPage(pPage);
danielk19772df71c72007-05-24 07:22:42 +00002092 if( rc!=SQLITE_OK ){
2093 goto set_child_ptrmaps_out;
2094 }
danielk1977687566d2004-11-02 12:56:41 +00002095 nCell = pPage->nCell;
2096
2097 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002098 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002099
danielk197726836652005-01-17 01:33:13 +00002100 rc = ptrmapPutOvflPtr(pPage, pCell);
2101 if( rc!=SQLITE_OK ){
2102 goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002103 }
danielk197726836652005-01-17 01:33:13 +00002104
danielk1977687566d2004-11-02 12:56:41 +00002105 if( !pPage->leaf ){
2106 Pgno childPgno = get4byte(pCell);
2107 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
danielk197700a696d2008-09-29 16:41:31 +00002108 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002109 }
2110 }
2111
2112 if( !pPage->leaf ){
2113 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
2114 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
2115 }
2116
2117set_child_ptrmaps_out:
2118 pPage->isInit = isInitOrig;
2119 return rc;
2120}
2121
2122/*
2123** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
2124** page, is a pointer to page iFrom. Modify this pointer so that it points to
2125** iTo. Parameter eType describes the type of pointer to be modified, as
2126** follows:
2127**
2128** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
2129** page of pPage.
2130**
2131** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
2132** page pointed to by one of the cells on pPage.
2133**
2134** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
2135** overflow page in the list.
2136*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00002137static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00002138 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00002139 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977687566d2004-11-02 12:56:41 +00002140 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00002141 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00002142 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00002143 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002144 }
danielk1977f78fc082004-11-02 14:40:32 +00002145 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00002146 }else{
drhf49661a2008-12-10 16:45:50 +00002147 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002148 int i;
2149 int nCell;
2150
danielk197771d5d2c2008-09-29 11:49:47 +00002151 sqlite3BtreeInitPage(pPage);
danielk1977687566d2004-11-02 12:56:41 +00002152 nCell = pPage->nCell;
2153
danielk1977687566d2004-11-02 12:56:41 +00002154 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002155 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002156 if( eType==PTRMAP_OVERFLOW1 ){
2157 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00002158 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
danielk1977687566d2004-11-02 12:56:41 +00002159 if( info.iOverflow ){
2160 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
2161 put4byte(&pCell[info.iOverflow], iTo);
2162 break;
2163 }
2164 }
2165 }else{
2166 if( get4byte(pCell)==iFrom ){
2167 put4byte(pCell, iTo);
2168 break;
2169 }
2170 }
2171 }
2172
2173 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00002174 if( eType!=PTRMAP_BTREE ||
2175 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00002176 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002177 }
danielk1977687566d2004-11-02 12:56:41 +00002178 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
2179 }
2180
2181 pPage->isInit = isInitOrig;
2182 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002183 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002184}
2185
danielk1977003ba062004-11-04 02:57:33 +00002186
danielk19777701e812005-01-10 12:59:51 +00002187/*
2188** Move the open database page pDbPage to location iFreePage in the
2189** database. The pDbPage reference remains valid.
2190*/
danielk1977003ba062004-11-04 02:57:33 +00002191static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00002192 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00002193 MemPage *pDbPage, /* Open page to move */
2194 u8 eType, /* Pointer map 'type' entry for pDbPage */
2195 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
danielk19774c999992008-07-16 18:17:55 +00002196 Pgno iFreePage, /* The location to move pDbPage to */
2197 int isCommit
danielk1977003ba062004-11-04 02:57:33 +00002198){
2199 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
2200 Pgno iDbPage = pDbPage->pgno;
2201 Pager *pPager = pBt->pPager;
2202 int rc;
2203
danielk1977a0bf2652004-11-04 14:30:04 +00002204 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
2205 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00002206 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00002207 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00002208
drh85b623f2007-12-13 21:54:09 +00002209 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00002210 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
2211 iDbPage, iFreePage, iPtrPage, eType));
danielk19774c999992008-07-16 18:17:55 +00002212 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
danielk1977003ba062004-11-04 02:57:33 +00002213 if( rc!=SQLITE_OK ){
2214 return rc;
2215 }
2216 pDbPage->pgno = iFreePage;
2217
2218 /* If pDbPage was a btree-page, then it may have child pages and/or cells
2219 ** that point to overflow pages. The pointer map entries for all these
2220 ** pages need to be changed.
2221 **
2222 ** If pDbPage is an overflow page, then the first 4 bytes may store a
2223 ** pointer to a subsequent overflow page. If this is the case, then
2224 ** the pointer map needs to be updated for the subsequent overflow page.
2225 */
danielk1977a0bf2652004-11-04 14:30:04 +00002226 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00002227 rc = setChildPtrmaps(pDbPage);
2228 if( rc!=SQLITE_OK ){
2229 return rc;
2230 }
2231 }else{
2232 Pgno nextOvfl = get4byte(pDbPage->aData);
2233 if( nextOvfl!=0 ){
danielk1977003ba062004-11-04 02:57:33 +00002234 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
2235 if( rc!=SQLITE_OK ){
2236 return rc;
2237 }
2238 }
2239 }
2240
2241 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
2242 ** that it points at iFreePage. Also fix the pointer map entry for
2243 ** iPtrPage.
2244 */
danielk1977a0bf2652004-11-04 14:30:04 +00002245 if( eType!=PTRMAP_ROOTPAGE ){
drh16a9b832007-05-05 18:39:25 +00002246 rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00002247 if( rc!=SQLITE_OK ){
2248 return rc;
2249 }
danielk19773b8a05f2007-03-19 17:44:26 +00002250 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00002251 if( rc!=SQLITE_OK ){
2252 releasePage(pPtrPage);
2253 return rc;
2254 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002255 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00002256 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00002257 if( rc==SQLITE_OK ){
2258 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
2259 }
danielk1977003ba062004-11-04 02:57:33 +00002260 }
danielk1977003ba062004-11-04 02:57:33 +00002261 return rc;
2262}
2263
danielk1977dddbcdc2007-04-26 14:42:34 +00002264/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00002265static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00002266
2267/*
danielk1977dddbcdc2007-04-26 14:42:34 +00002268** Perform a single step of an incremental-vacuum. If successful,
2269** return SQLITE_OK. If there is no work to do (and therefore no
2270** point in calling this function again), return SQLITE_DONE.
2271**
2272** More specificly, this function attempts to re-organize the
2273** database so that the last page of the file currently in use
2274** is no longer in use.
2275**
2276** If the nFin parameter is non-zero, the implementation assumes
2277** that the caller will keep calling incrVacuumStep() until
2278** it returns SQLITE_DONE or an error, and that nFin is the
2279** number of pages the database file will contain after this
2280** process is complete.
2281*/
2282static int incrVacuumStep(BtShared *pBt, Pgno nFin){
2283 Pgno iLastPg; /* Last page in the database */
2284 Pgno nFreeList; /* Number of pages still on the free-list */
2285
drh1fee73e2007-08-29 04:00:57 +00002286 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977dddbcdc2007-04-26 14:42:34 +00002287 iLastPg = pBt->nTrunc;
2288 if( iLastPg==0 ){
danielk197789d40042008-11-17 14:20:56 +00002289 iLastPg = pagerPagecount(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00002290 }
2291
2292 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
2293 int rc;
2294 u8 eType;
2295 Pgno iPtrPage;
2296
2297 nFreeList = get4byte(&pBt->pPage1->aData[36]);
2298 if( nFreeList==0 || nFin==iLastPg ){
2299 return SQLITE_DONE;
2300 }
2301
2302 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
2303 if( rc!=SQLITE_OK ){
2304 return rc;
2305 }
2306 if( eType==PTRMAP_ROOTPAGE ){
2307 return SQLITE_CORRUPT_BKPT;
2308 }
2309
2310 if( eType==PTRMAP_FREEPAGE ){
2311 if( nFin==0 ){
2312 /* Remove the page from the files free-list. This is not required
danielk19774ef24492007-05-23 09:52:41 +00002313 ** if nFin is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00002314 ** truncated to zero after this function returns, so it doesn't
2315 ** matter if it still contains some garbage entries.
2316 */
2317 Pgno iFreePg;
2318 MemPage *pFreePg;
2319 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
2320 if( rc!=SQLITE_OK ){
2321 return rc;
2322 }
2323 assert( iFreePg==iLastPg );
2324 releasePage(pFreePg);
2325 }
2326 } else {
2327 Pgno iFreePg; /* Index of free page to move pLastPg to */
2328 MemPage *pLastPg;
2329
drh16a9b832007-05-05 18:39:25 +00002330 rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002331 if( rc!=SQLITE_OK ){
2332 return rc;
2333 }
2334
danielk1977b4626a32007-04-28 15:47:43 +00002335 /* If nFin is zero, this loop runs exactly once and page pLastPg
2336 ** is swapped with the first free page pulled off the free list.
2337 **
2338 ** On the other hand, if nFin is greater than zero, then keep
2339 ** looping until a free-page located within the first nFin pages
2340 ** of the file is found.
2341 */
danielk1977dddbcdc2007-04-26 14:42:34 +00002342 do {
2343 MemPage *pFreePg;
2344 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
2345 if( rc!=SQLITE_OK ){
2346 releasePage(pLastPg);
2347 return rc;
2348 }
2349 releasePage(pFreePg);
2350 }while( nFin!=0 && iFreePg>nFin );
2351 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00002352
2353 rc = sqlite3PagerWrite(pLastPg->pDbPage);
danielk1977662278e2007-11-05 15:30:12 +00002354 if( rc==SQLITE_OK ){
danielk19774c999992008-07-16 18:17:55 +00002355 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
danielk1977662278e2007-11-05 15:30:12 +00002356 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002357 releasePage(pLastPg);
2358 if( rc!=SQLITE_OK ){
2359 return rc;
danielk1977662278e2007-11-05 15:30:12 +00002360 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002361 }
2362 }
2363
2364 pBt->nTrunc = iLastPg - 1;
2365 while( pBt->nTrunc==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, pBt->nTrunc) ){
2366 pBt->nTrunc--;
2367 }
2368 return SQLITE_OK;
2369}
2370
2371/*
2372** A write-transaction must be opened before calling this function.
2373** It performs a single unit of work towards an incremental vacuum.
2374**
2375** If the incremental vacuum is finished after this function has run,
2376** SQLITE_DONE is returned. If it is not finished, but no error occured,
2377** SQLITE_OK is returned. Otherwise an SQLite error code.
2378*/
2379int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002380 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002381 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002382
2383 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002384 pBt->db = p->db;
danielk1977dddbcdc2007-04-26 14:42:34 +00002385 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
2386 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002387 rc = SQLITE_DONE;
2388 }else{
2389 invalidateAllOverflowCache(pBt);
2390 rc = incrVacuumStep(pBt, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002391 }
drhd677b3d2007-08-20 22:48:41 +00002392 sqlite3BtreeLeave(p);
2393 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002394}
2395
2396/*
danielk19773b8a05f2007-03-19 17:44:26 +00002397** This routine is called prior to sqlite3PagerCommit when a transaction
danielk1977687566d2004-11-02 12:56:41 +00002398** is commited for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00002399**
2400** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
2401** the database file should be truncated to during the commit process.
2402** i.e. the database has been reorganized so that only the first *pnTrunc
2403** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00002404*/
danielk197724168722007-04-02 05:07:47 +00002405static int autoVacuumCommit(BtShared *pBt, Pgno *pnTrunc){
danielk1977dddbcdc2007-04-26 14:42:34 +00002406 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002407 Pager *pPager = pBt->pPager;
drhf94a1732008-09-30 17:18:17 +00002408 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002409
drh1fee73e2007-08-29 04:00:57 +00002410 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00002411 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00002412 assert(pBt->autoVacuum);
2413 if( !pBt->incrVacuum ){
2414 Pgno nFin = 0;
danielk1977687566d2004-11-02 12:56:41 +00002415
danielk1977dddbcdc2007-04-26 14:42:34 +00002416 if( pBt->nTrunc==0 ){
2417 Pgno nFree;
2418 Pgno nPtrmap;
2419 const int pgsz = pBt->pageSize;
danielk197789d40042008-11-17 14:20:56 +00002420 Pgno nOrig = pagerPagecount(pBt);
danielk1977e5321f02007-04-27 07:05:44 +00002421
2422 if( PTRMAP_ISPAGE(pBt, nOrig) ){
2423 return SQLITE_CORRUPT_BKPT;
2424 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002425 if( nOrig==PENDING_BYTE_PAGE(pBt) ){
2426 nOrig--;
danielk1977687566d2004-11-02 12:56:41 +00002427 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002428 nFree = get4byte(&pBt->pPage1->aData[36]);
2429 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
2430 nFin = nOrig - nFree - nPtrmap;
2431 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
2432 nFin--;
danielk1977ac11ee62005-01-15 12:45:51 +00002433 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002434 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
2435 nFin--;
2436 }
2437 }
danielk1977687566d2004-11-02 12:56:41 +00002438
danielk1977dddbcdc2007-04-26 14:42:34 +00002439 while( rc==SQLITE_OK ){
2440 rc = incrVacuumStep(pBt, nFin);
2441 }
2442 if( rc==SQLITE_DONE ){
2443 assert(nFin==0 || pBt->nTrunc==0 || nFin<=pBt->nTrunc);
2444 rc = SQLITE_OK;
danielk19770ba32df2008-05-07 07:13:16 +00002445 if( pBt->nTrunc && nFin ){
drh67f80b62007-07-23 19:26:17 +00002446 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
danielk1977dddbcdc2007-04-26 14:42:34 +00002447 put4byte(&pBt->pPage1->aData[32], 0);
2448 put4byte(&pBt->pPage1->aData[36], 0);
2449 pBt->nTrunc = nFin;
2450 }
2451 }
2452 if( rc!=SQLITE_OK ){
2453 sqlite3PagerRollback(pPager);
2454 }
danielk1977687566d2004-11-02 12:56:41 +00002455 }
2456
danielk1977dddbcdc2007-04-26 14:42:34 +00002457 if( rc==SQLITE_OK ){
2458 *pnTrunc = pBt->nTrunc;
2459 pBt->nTrunc = 0;
2460 }
danielk19773b8a05f2007-03-19 17:44:26 +00002461 assert( nRef==sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002462 return rc;
2463}
danielk1977dddbcdc2007-04-26 14:42:34 +00002464
shane831c3292008-11-10 17:14:58 +00002465#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
danielk1977687566d2004-11-02 12:56:41 +00002466
2467/*
drh80e35f42007-03-30 14:06:34 +00002468** This routine does the first phase of a two-phase commit. This routine
2469** causes a rollback journal to be created (if it does not already exist)
2470** and populated with enough information so that if a power loss occurs
2471** the database can be restored to its original state by playing back
2472** the journal. Then the contents of the journal are flushed out to
2473** the disk. After the journal is safely on oxide, the changes to the
2474** database are written into the database file and flushed to oxide.
2475** At the end of this call, the rollback journal still exists on the
2476** disk and we are still holding all locks, so the transaction has not
2477** committed. See sqlite3BtreeCommit() for the second phase of the
2478** commit process.
2479**
2480** This call is a no-op if no write-transaction is currently active on pBt.
2481**
2482** Otherwise, sync the database file for the btree pBt. zMaster points to
2483** the name of a master journal file that should be written into the
2484** individual journal file, or is NULL, indicating no master journal file
2485** (single database transaction).
2486**
2487** When this is called, the master journal should already have been
2488** created, populated with this journal pointer and synced to disk.
2489**
2490** Once this is routine has returned, the only thing required to commit
2491** the write-transaction for this database file is to delete the journal.
2492*/
2493int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
2494 int rc = SQLITE_OK;
2495 if( p->inTrans==TRANS_WRITE ){
2496 BtShared *pBt = p->pBt;
2497 Pgno nTrunc = 0;
drhd677b3d2007-08-20 22:48:41 +00002498 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002499 pBt->db = p->db;
drh80e35f42007-03-30 14:06:34 +00002500#ifndef SQLITE_OMIT_AUTOVACUUM
2501 if( pBt->autoVacuum ){
2502 rc = autoVacuumCommit(pBt, &nTrunc);
2503 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002504 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002505 return rc;
2506 }
2507 }
2508#endif
danielk1977f653d782008-03-20 11:04:21 +00002509 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, nTrunc, 0);
drhd677b3d2007-08-20 22:48:41 +00002510 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002511 }
2512 return rc;
2513}
2514
2515/*
drh2aa679f2001-06-25 02:11:07 +00002516** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00002517**
drh6e345992007-03-30 11:12:08 +00002518** This routine implements the second phase of a 2-phase commit. The
2519** sqlite3BtreeSync() routine does the first phase and should be invoked
2520** prior to calling this routine. The sqlite3BtreeSync() routine did
2521** all the work of writing information out to disk and flushing the
2522** contents so that they are written onto the disk platter. All this
2523** routine has to do is delete or truncate the rollback journal
2524** (which causes the transaction to commit) and drop locks.
2525**
drh5e00f6c2001-09-13 13:46:56 +00002526** This will release the write lock on the database file. If there
2527** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002528*/
drh80e35f42007-03-30 14:06:34 +00002529int sqlite3BtreeCommitPhaseTwo(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002530 BtShared *pBt = p->pBt;
2531
drhd677b3d2007-08-20 22:48:41 +00002532 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002533 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00002534 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002535
2536 /* If the handle has a write-transaction open, commit the shared-btrees
2537 ** transaction and set the shared state to TRANS_READ.
2538 */
2539 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00002540 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002541 assert( pBt->inTransaction==TRANS_WRITE );
2542 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00002543 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
danielk19777f7bc662006-01-23 13:47:47 +00002544 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002545 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002546 return rc;
2547 }
danielk1977aef0bf62005-12-30 16:28:01 +00002548 pBt->inTransaction = TRANS_READ;
2549 pBt->inStmt = 0;
danielk1977ee5741e2004-05-31 10:01:34 +00002550 }
danielk19777f7bc662006-01-23 13:47:47 +00002551 unlockAllTables(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002552
2553 /* If the handle has any kind of transaction open, decrement the transaction
2554 ** count of the shared btree. If the transaction count reaches 0, set
2555 ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
2556 ** will unlock the pager.
2557 */
2558 if( p->inTrans!=TRANS_NONE ){
2559 pBt->nTransaction--;
2560 if( 0==pBt->nTransaction ){
2561 pBt->inTransaction = TRANS_NONE;
2562 }
2563 }
2564
2565 /* Set the handles current transaction state to TRANS_NONE and unlock
2566 ** the pager if this call closed the only read or write transaction.
2567 */
2568 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00002569 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002570
2571 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002572 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002573 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002574}
2575
drh80e35f42007-03-30 14:06:34 +00002576/*
2577** Do both phases of a commit.
2578*/
2579int sqlite3BtreeCommit(Btree *p){
2580 int rc;
drhd677b3d2007-08-20 22:48:41 +00002581 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00002582 rc = sqlite3BtreeCommitPhaseOne(p, 0);
2583 if( rc==SQLITE_OK ){
2584 rc = sqlite3BtreeCommitPhaseTwo(p);
2585 }
drhd677b3d2007-08-20 22:48:41 +00002586 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002587 return rc;
2588}
2589
danielk1977fbcd5852004-06-15 02:44:18 +00002590#ifndef NDEBUG
2591/*
2592** Return the number of write-cursors open on this handle. This is for use
2593** in assert() expressions, so it is only compiled if NDEBUG is not
2594** defined.
drhfb982642007-08-30 01:19:59 +00002595**
2596** For the purposes of this routine, a write-cursor is any cursor that
2597** is capable of writing to the databse. That means the cursor was
2598** originally opened for writing and the cursor has not be disabled
2599** by having its state changed to CURSOR_FAULT.
danielk1977fbcd5852004-06-15 02:44:18 +00002600*/
danielk1977aef0bf62005-12-30 16:28:01 +00002601static int countWriteCursors(BtShared *pBt){
danielk1977fbcd5852004-06-15 02:44:18 +00002602 BtCursor *pCur;
2603 int r = 0;
2604 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drhfb982642007-08-30 01:19:59 +00002605 if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
danielk1977fbcd5852004-06-15 02:44:18 +00002606 }
2607 return r;
2608}
2609#endif
2610
drhc39e0002004-05-07 23:50:57 +00002611/*
drhfb982642007-08-30 01:19:59 +00002612** This routine sets the state to CURSOR_FAULT and the error
2613** code to errCode for every cursor on BtShared that pBtree
2614** references.
2615**
2616** Every cursor is tripped, including cursors that belong
2617** to other database connections that happen to be sharing
2618** the cache with pBtree.
2619**
2620** This routine gets called when a rollback occurs.
2621** All cursors using the same cache must be tripped
2622** to prevent them from trying to use the btree after
2623** the rollback. The rollback may have deleted tables
2624** or moved root pages, so it is not sufficient to
2625** save the state of the cursor. The cursor must be
2626** invalidated.
2627*/
2628void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
2629 BtCursor *p;
2630 sqlite3BtreeEnter(pBtree);
2631 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
danielk1977bc2ca9e2008-11-13 14:28:28 +00002632 int i;
danielk1977be51a652008-10-08 17:58:48 +00002633 sqlite3BtreeClearCursor(p);
drhfb982642007-08-30 01:19:59 +00002634 p->eState = CURSOR_FAULT;
2635 p->skip = errCode;
danielk1977bc2ca9e2008-11-13 14:28:28 +00002636 for(i=0; i<=p->iPage; i++){
2637 releasePage(p->apPage[i]);
2638 p->apPage[i] = 0;
2639 }
drhfb982642007-08-30 01:19:59 +00002640 }
2641 sqlite3BtreeLeave(pBtree);
2642}
2643
2644/*
drhecdc7532001-09-23 02:35:53 +00002645** Rollback the transaction in progress. All cursors will be
2646** invalided by this operation. Any attempt to use a cursor
2647** that was open at the beginning of this operation will result
2648** in an error.
drh5e00f6c2001-09-13 13:46:56 +00002649**
2650** This will release the write lock on the database file. If there
2651** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002652*/
danielk1977aef0bf62005-12-30 16:28:01 +00002653int sqlite3BtreeRollback(Btree *p){
danielk19778d34dfd2006-01-24 16:37:57 +00002654 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002655 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00002656 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00002657
drhd677b3d2007-08-20 22:48:41 +00002658 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002659 pBt->db = p->db;
danielk19772b8c13e2006-01-24 14:21:24 +00002660 rc = saveAllCursors(pBt, 0, 0);
danielk19778d34dfd2006-01-24 16:37:57 +00002661#ifndef SQLITE_OMIT_SHARED_CACHE
danielk19772b8c13e2006-01-24 14:21:24 +00002662 if( rc!=SQLITE_OK ){
danielk19778d34dfd2006-01-24 16:37:57 +00002663 /* This is a horrible situation. An IO or malloc() error occured whilst
2664 ** trying to save cursor positions. If this is an automatic rollback (as
2665 ** the result of a constraint, malloc() failure or IO error) then
2666 ** the cache may be internally inconsistent (not contain valid trees) so
2667 ** we cannot simply return the error to the caller. Instead, abort
2668 ** all queries that may be using any of the cursors that failed to save.
2669 */
drhfb982642007-08-30 01:19:59 +00002670 sqlite3BtreeTripAllCursors(p, rc);
danielk19772b8c13e2006-01-24 14:21:24 +00002671 }
danielk19778d34dfd2006-01-24 16:37:57 +00002672#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002673 btreeIntegrity(p);
2674 unlockAllTables(p);
2675
2676 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00002677 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00002678
danielk1977dddbcdc2007-04-26 14:42:34 +00002679#ifndef SQLITE_OMIT_AUTOVACUUM
2680 pBt->nTrunc = 0;
2681#endif
2682
danielk19778d34dfd2006-01-24 16:37:57 +00002683 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00002684 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00002685 if( rc2!=SQLITE_OK ){
2686 rc = rc2;
2687 }
2688
drh24cd67e2004-05-10 16:18:47 +00002689 /* The rollback may have destroyed the pPage1->aData value. So
drh16a9b832007-05-05 18:39:25 +00002690 ** call sqlite3BtreeGetPage() on page 1 again to make
2691 ** sure pPage1->aData is set correctly. */
2692 if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh24cd67e2004-05-10 16:18:47 +00002693 releasePage(pPage1);
2694 }
danielk1977fbcd5852004-06-15 02:44:18 +00002695 assert( countWriteCursors(pBt)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002696 pBt->inTransaction = TRANS_READ;
drh24cd67e2004-05-10 16:18:47 +00002697 }
danielk1977aef0bf62005-12-30 16:28:01 +00002698
2699 if( p->inTrans!=TRANS_NONE ){
2700 assert( pBt->nTransaction>0 );
2701 pBt->nTransaction--;
2702 if( 0==pBt->nTransaction ){
2703 pBt->inTransaction = TRANS_NONE;
2704 }
2705 }
2706
2707 p->inTrans = TRANS_NONE;
danielk1977ee5741e2004-05-31 10:01:34 +00002708 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00002709 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002710
2711 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002712 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00002713 return rc;
2714}
2715
2716/*
drhab01f612004-05-22 02:55:23 +00002717** Start a statement subtransaction. The subtransaction can
2718** can be rolled back independently of the main transaction.
2719** You must start a transaction before starting a subtransaction.
2720** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00002721** commits or rolls back.
2722**
drhab01f612004-05-22 02:55:23 +00002723** Only one subtransaction may be active at a time. It is an error to try
2724** to start a new subtransaction if another subtransaction is already active.
2725**
2726** Statement subtransactions are used around individual SQL statements
2727** that are contained within a BEGIN...COMMIT block. If a constraint
2728** error occurs within the statement, the effect of that one statement
2729** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00002730*/
danielk1977aef0bf62005-12-30 16:28:01 +00002731int sqlite3BtreeBeginStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002732 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002733 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002734 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002735 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00002736 if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
drhd677b3d2007-08-20 22:48:41 +00002737 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
2738 }else{
2739 assert( pBt->inTransaction==TRANS_WRITE );
danielk1977fd7f0452008-12-17 17:30:26 +00002740 if( pBt->readOnly ){
2741 rc = SQLITE_OK;
2742 }else{
2743 /* At the pager level, a statement transaction is a savepoint with
2744 ** an index greater than all savepoints created explicitly using
2745 ** SQL statements. It is illegal to open, release or rollback any
2746 ** such savepoints while the statement transaction savepoint is active.
2747 */
danielk197712dd5492008-12-18 15:45:07 +00002748 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint+1);
danielk1977fd7f0452008-12-17 17:30:26 +00002749 }
drhd677b3d2007-08-20 22:48:41 +00002750 pBt->inStmt = 1;
drh0d65dc02002-02-03 00:56:09 +00002751 }
drhd677b3d2007-08-20 22:48:41 +00002752 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002753 return rc;
2754}
2755
drh663fc632002-02-02 18:49:19 +00002756/*
drhab01f612004-05-22 02:55:23 +00002757** Commit the statment subtransaction currently in progress. If no
2758** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00002759*/
danielk1977aef0bf62005-12-30 16:28:01 +00002760int sqlite3BtreeCommitStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002761 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002762 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002763 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002764 pBt->db = p->db;
drh3aac2dd2004-04-26 14:10:20 +00002765 if( pBt->inStmt && !pBt->readOnly ){
danielk1977fd7f0452008-12-17 17:30:26 +00002766 int iStmtpoint = p->db->nSavepoint;
2767 rc = sqlite3PagerSavepoint(pBt->pPager, SAVEPOINT_RELEASE, iStmtpoint);
drh663fc632002-02-02 18:49:19 +00002768 }else{
2769 rc = SQLITE_OK;
2770 }
drh3aac2dd2004-04-26 14:10:20 +00002771 pBt->inStmt = 0;
drhd677b3d2007-08-20 22:48:41 +00002772 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002773 return rc;
2774}
2775
2776/*
drhab01f612004-05-22 02:55:23 +00002777** Rollback the active statement subtransaction. If no subtransaction
2778** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00002779**
drhab01f612004-05-22 02:55:23 +00002780** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00002781** to use a cursor that was open at the beginning of this operation
2782** will result in an error.
2783*/
danielk1977aef0bf62005-12-30 16:28:01 +00002784int sqlite3BtreeRollbackStmt(Btree *p){
danielk197797a227c2006-01-20 16:32:04 +00002785 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002786 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002787 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002788 pBt->db = p->db;
danielk197797a227c2006-01-20 16:32:04 +00002789 if( pBt->inStmt && !pBt->readOnly ){
danielk1977fd7f0452008-12-17 17:30:26 +00002790 int iStmtpoint = p->db->nSavepoint;
2791 rc = sqlite3PagerSavepoint(pBt->pPager, SAVEPOINT_ROLLBACK, iStmtpoint);
2792 if( rc==SQLITE_OK ){
2793 rc = sqlite3PagerSavepoint(pBt->pPager, SAVEPOINT_RELEASE, iStmtpoint);
2794 }
danielk197797a227c2006-01-20 16:32:04 +00002795 pBt->inStmt = 0;
2796 }
drhd677b3d2007-08-20 22:48:41 +00002797 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002798 return rc;
2799}
2800
2801/*
danielk1977fd7f0452008-12-17 17:30:26 +00002802** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
2803** or SAVEPOINT_RELEASE. This function either releases or rolls back the
danielk197712dd5492008-12-18 15:45:07 +00002804** savepoint identified by parameter iSavepoint, depending on the value
2805** of op.
2806**
2807** Normally, iSavepoint is greater than or equal to zero. However, if op is
2808** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
2809** contents of the entire transaction are rolled back. This is different
2810** from a normal transaction rollback, as no locks are released and the
2811** transaction remains open.
danielk1977fd7f0452008-12-17 17:30:26 +00002812*/
2813int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
2814 int rc = SQLITE_OK;
2815 if( p && p->inTrans==TRANS_WRITE ){
2816 BtShared *pBt = p->pBt;
2817 assert( pBt->inStmt==0 );
2818 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
2819 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
2820 sqlite3BtreeEnter(p);
2821 pBt->db = p->db;
2822 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
2823 sqlite3BtreeLeave(p);
2824 }
2825 return rc;
2826}
2827
2828/*
drh8b2f49b2001-06-08 00:21:52 +00002829** Create a new cursor for the BTree whose root is on the page
2830** iTable. The act of acquiring a cursor gets a read lock on
2831** the database file.
drh1bee3d72001-10-15 00:44:35 +00002832**
2833** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00002834** If wrFlag==1, then the cursor can be used for reading or for
2835** writing if other conditions for writing are also met. These
2836** are the conditions that must be met in order for writing to
2837** be allowed:
drh6446c4d2001-12-15 14:22:18 +00002838**
drhf74b8d92002-09-01 23:20:45 +00002839** 1: The cursor must have been opened with wrFlag==1
2840**
drhfe5d71d2007-03-19 11:54:10 +00002841** 2: Other database connections that share the same pager cache
2842** but which are not in the READ_UNCOMMITTED state may not have
2843** cursors open with wrFlag==0 on the same table. Otherwise
2844** the changes made by this write cursor would be visible to
2845** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00002846**
2847** 3: The database must be writable (not on read-only media)
2848**
2849** 4: There must be an active transaction.
2850**
drh6446c4d2001-12-15 14:22:18 +00002851** No checking is done to make sure that page iTable really is the
2852** root page of a b-tree. If it is not, then the cursor acquired
2853** will not work correctly.
danielk197771d5d2c2008-09-29 11:49:47 +00002854**
2855** It is assumed that the sqlite3BtreeCursorSize() bytes of memory
2856** pointed to by pCur have been zeroed by the caller.
drha059ad02001-04-17 20:09:11 +00002857*/
drhd677b3d2007-08-20 22:48:41 +00002858static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00002859 Btree *p, /* The btree */
2860 int iTable, /* Root page of table to open */
2861 int wrFlag, /* 1 to write. 0 read-only */
2862 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
2863 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00002864){
drha059ad02001-04-17 20:09:11 +00002865 int rc;
danielk197789d40042008-11-17 14:20:56 +00002866 Pgno nPage;
danielk1977aef0bf62005-12-30 16:28:01 +00002867 BtShared *pBt = p->pBt;
drhecdc7532001-09-23 02:35:53 +00002868
drh1fee73e2007-08-29 04:00:57 +00002869 assert( sqlite3BtreeHoldsMutex(p) );
drhf49661a2008-12-10 16:45:50 +00002870 assert( wrFlag==0 || wrFlag==1 );
drh8dcd7ca2004-08-08 19:43:29 +00002871 if( wrFlag ){
drh8dcd7ca2004-08-08 19:43:29 +00002872 if( pBt->readOnly ){
2873 return SQLITE_READONLY;
2874 }
danielk19773588ceb2008-06-10 17:30:26 +00002875 if( checkReadLocks(p, iTable, 0, 0) ){
drh8dcd7ca2004-08-08 19:43:29 +00002876 return SQLITE_LOCKED;
2877 }
drha0c9a112004-03-10 13:42:37 +00002878 }
danielk1977aef0bf62005-12-30 16:28:01 +00002879
drh4b70f112004-05-02 21:12:19 +00002880 if( pBt->pPage1==0 ){
danielk1977aef0bf62005-12-30 16:28:01 +00002881 rc = lockBtreeWithRetry(p);
drha059ad02001-04-17 20:09:11 +00002882 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00002883 return rc;
2884 }
drh1831f182007-04-24 17:35:59 +00002885 if( pBt->readOnly && wrFlag ){
2886 return SQLITE_READONLY;
2887 }
drha059ad02001-04-17 20:09:11 +00002888 }
drh8b2f49b2001-06-08 00:21:52 +00002889 pCur->pgnoRoot = (Pgno)iTable;
danielk197789d40042008-11-17 14:20:56 +00002890 rc = sqlite3PagerPagecount(pBt->pPager, (int *)&nPage);
2891 if( rc!=SQLITE_OK ){
2892 return rc;
2893 }
2894 if( iTable==1 && nPage==0 ){
drh24cd67e2004-05-10 16:18:47 +00002895 rc = SQLITE_EMPTY;
2896 goto create_cursor_exception;
2897 }
danielk197771d5d2c2008-09-29 11:49:47 +00002898 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
drhbd03cae2001-06-02 02:40:57 +00002899 if( rc!=SQLITE_OK ){
2900 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00002901 }
danielk1977aef0bf62005-12-30 16:28:01 +00002902
danielk1977aef0bf62005-12-30 16:28:01 +00002903 /* Now that no other errors can occur, finish filling in the BtCursor
2904 ** variables, link the cursor into the BtShared list and set *ppCur (the
2905 ** output argument to this function).
2906 */
drh1e968a02008-03-25 00:22:21 +00002907 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00002908 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00002909 pCur->pBt = pBt;
drhf49661a2008-12-10 16:45:50 +00002910 pCur->wrFlag = (u8)wrFlag;
drha059ad02001-04-17 20:09:11 +00002911 pCur->pNext = pBt->pCursor;
2912 if( pCur->pNext ){
2913 pCur->pNext->pPrev = pCur;
2914 }
2915 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00002916 pCur->eState = CURSOR_INVALID;
drhbd03cae2001-06-02 02:40:57 +00002917
danielk1977aef0bf62005-12-30 16:28:01 +00002918 return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00002919
drhbd03cae2001-06-02 02:40:57 +00002920create_cursor_exception:
danielk197771d5d2c2008-09-29 11:49:47 +00002921 releasePage(pCur->apPage[0]);
drh5e00f6c2001-09-13 13:46:56 +00002922 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00002923 return rc;
drha059ad02001-04-17 20:09:11 +00002924}
drhd677b3d2007-08-20 22:48:41 +00002925int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00002926 Btree *p, /* The btree */
2927 int iTable, /* Root page of table to open */
2928 int wrFlag, /* 1 to write. 0 read-only */
2929 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
2930 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00002931){
2932 int rc;
2933 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002934 p->pBt->db = p->db;
danielk1977cd3e8f72008-03-25 09:47:35 +00002935 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
drhd677b3d2007-08-20 22:48:41 +00002936 sqlite3BtreeLeave(p);
2937 return rc;
2938}
danielk1977cd3e8f72008-03-25 09:47:35 +00002939int sqlite3BtreeCursorSize(){
2940 return sizeof(BtCursor);
2941}
2942
drhd677b3d2007-08-20 22:48:41 +00002943
drha059ad02001-04-17 20:09:11 +00002944
2945/*
drh5e00f6c2001-09-13 13:46:56 +00002946** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00002947** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00002948*/
drh3aac2dd2004-04-26 14:10:20 +00002949int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00002950 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00002951 if( pBtree ){
danielk197771d5d2c2008-09-29 11:49:47 +00002952 int i;
danielk1977cd3e8f72008-03-25 09:47:35 +00002953 BtShared *pBt = pCur->pBt;
2954 sqlite3BtreeEnter(pBtree);
2955 pBt->db = pBtree->db;
danielk1977be51a652008-10-08 17:58:48 +00002956 sqlite3BtreeClearCursor(pCur);
danielk1977cd3e8f72008-03-25 09:47:35 +00002957 if( pCur->pPrev ){
2958 pCur->pPrev->pNext = pCur->pNext;
2959 }else{
2960 pBt->pCursor = pCur->pNext;
2961 }
2962 if( pCur->pNext ){
2963 pCur->pNext->pPrev = pCur->pPrev;
2964 }
danielk197771d5d2c2008-09-29 11:49:47 +00002965 for(i=0; i<=pCur->iPage; i++){
2966 releasePage(pCur->apPage[i]);
2967 }
danielk1977cd3e8f72008-03-25 09:47:35 +00002968 unlockBtreeIfUnused(pBt);
2969 invalidateOverflowCache(pCur);
2970 /* sqlite3_free(pCur); */
2971 sqlite3BtreeLeave(pBtree);
drha059ad02001-04-17 20:09:11 +00002972 }
drh8c42ca92001-06-22 19:15:00 +00002973 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002974}
2975
drh7e3b0a02001-04-28 16:52:40 +00002976/*
drh5e2f8b92001-05-28 00:41:15 +00002977** Make a temporary cursor by filling in the fields of pTempCur.
2978** The temporary cursor is not on the cursor list for the Btree.
2979*/
drh16a9b832007-05-05 18:39:25 +00002980void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
danielk197771d5d2c2008-09-29 11:49:47 +00002981 int i;
drh1fee73e2007-08-29 04:00:57 +00002982 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00002983 memcpy(pTempCur, pCur, sizeof(BtCursor));
drh5e2f8b92001-05-28 00:41:15 +00002984 pTempCur->pNext = 0;
2985 pTempCur->pPrev = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00002986 for(i=0; i<=pTempCur->iPage; i++){
2987 sqlite3PagerRef(pTempCur->apPage[i]->pDbPage);
drhecdc7532001-09-23 02:35:53 +00002988 }
danielk197736e20932008-11-26 07:40:30 +00002989 assert( pTempCur->pKey==0 );
drh5e2f8b92001-05-28 00:41:15 +00002990}
2991
2992/*
drhbd03cae2001-06-02 02:40:57 +00002993** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00002994** function above.
2995*/
drh16a9b832007-05-05 18:39:25 +00002996void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
danielk197771d5d2c2008-09-29 11:49:47 +00002997 int i;
drh1fee73e2007-08-29 04:00:57 +00002998 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00002999 for(i=0; i<=pCur->iPage; i++){
3000 sqlite3PagerUnref(pCur->apPage[i]->pDbPage);
drhecdc7532001-09-23 02:35:53 +00003001 }
danielk197736e20932008-11-26 07:40:30 +00003002 sqlite3_free(pCur->pKey);
drh5e2f8b92001-05-28 00:41:15 +00003003}
3004
3005/*
drh86057612007-06-26 01:04:48 +00003006** Make sure the BtCursor* given in the argument has a valid
3007** BtCursor.info structure. If it is not already valid, call
danielk19771cc5ed82007-05-16 17:28:43 +00003008** sqlite3BtreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00003009**
3010** BtCursor.info is a cache of the information in the current cell.
drh16a9b832007-05-05 18:39:25 +00003011** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
drh86057612007-06-26 01:04:48 +00003012**
3013** 2007-06-25: There is a bug in some versions of MSVC that cause the
3014** compiler to crash when getCellInfo() is implemented as a macro.
3015** But there is a measureable speed advantage to using the macro on gcc
3016** (when less compiler optimizations like -Os or -O0 are used and the
3017** compiler is not doing agressive inlining.) So we use a real function
3018** for MSVC and a macro for everything else. Ticket #2457.
drh9188b382004-05-14 21:12:22 +00003019*/
drh9188b382004-05-14 21:12:22 +00003020#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00003021 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00003022 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00003023 int iPage = pCur->iPage;
drh51c6d962004-06-06 00:42:25 +00003024 memset(&info, 0, sizeof(info));
danielk197771d5d2c2008-09-29 11:49:47 +00003025 sqlite3BtreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
drh9188b382004-05-14 21:12:22 +00003026 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00003027 }
danielk19771cc5ed82007-05-16 17:28:43 +00003028#else
3029 #define assertCellInfo(x)
3030#endif
drh86057612007-06-26 01:04:48 +00003031#ifdef _MSC_VER
3032 /* Use a real function in MSVC to work around bugs in that compiler. */
3033 static void getCellInfo(BtCursor *pCur){
3034 if( pCur->info.nSize==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003035 int iPage = pCur->iPage;
3036 sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
drha2c20e42008-03-29 16:01:04 +00003037 pCur->validNKey = 1;
drh86057612007-06-26 01:04:48 +00003038 }else{
3039 assertCellInfo(pCur);
3040 }
3041 }
3042#else /* if not _MSC_VER */
3043 /* Use a macro in all other compilers so that the function is inlined */
danielk197771d5d2c2008-09-29 11:49:47 +00003044#define getCellInfo(pCur) \
3045 if( pCur->info.nSize==0 ){ \
3046 int iPage = pCur->iPage; \
3047 sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
3048 pCur->validNKey = 1; \
3049 }else{ \
3050 assertCellInfo(pCur); \
drh86057612007-06-26 01:04:48 +00003051 }
3052#endif /* _MSC_VER */
drh9188b382004-05-14 21:12:22 +00003053
3054/*
drh3aac2dd2004-04-26 14:10:20 +00003055** Set *pSize to the size of the buffer needed to hold the value of
3056** the key for the current entry. If the cursor is not pointing
3057** to a valid entry, *pSize is set to 0.
3058**
drh4b70f112004-05-02 21:12:19 +00003059** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00003060** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00003061*/
drh4a1c3802004-05-12 15:15:47 +00003062int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drhd677b3d2007-08-20 22:48:41 +00003063 int rc;
3064
drh1fee73e2007-08-29 04:00:57 +00003065 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003066 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003067 if( rc==SQLITE_OK ){
3068 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3069 if( pCur->eState==CURSOR_INVALID ){
3070 *pSize = 0;
3071 }else{
drh86057612007-06-26 01:04:48 +00003072 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00003073 *pSize = pCur->info.nKey;
3074 }
drh72f82862001-05-24 21:06:34 +00003075 }
danielk1977da184232006-01-05 11:34:32 +00003076 return rc;
drha059ad02001-04-17 20:09:11 +00003077}
drh2af926b2001-05-15 00:39:25 +00003078
drh72f82862001-05-24 21:06:34 +00003079/*
drh0e1c19e2004-05-11 00:58:56 +00003080** Set *pSize to the number of bytes of data in the entry the
3081** cursor currently points to. Always return SQLITE_OK.
3082** Failure is not possible. If the cursor is not currently
3083** pointing to an entry (which can happen, for example, if
3084** the database is empty) then *pSize is set to 0.
3085*/
3086int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drhd677b3d2007-08-20 22:48:41 +00003087 int rc;
3088
drh1fee73e2007-08-29 04:00:57 +00003089 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003090 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003091 if( rc==SQLITE_OK ){
3092 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3093 if( pCur->eState==CURSOR_INVALID ){
3094 /* Not pointing at a valid entry - set *pSize to 0. */
3095 *pSize = 0;
3096 }else{
drh86057612007-06-26 01:04:48 +00003097 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00003098 *pSize = pCur->info.nData;
3099 }
drh0e1c19e2004-05-11 00:58:56 +00003100 }
danielk1977da184232006-01-05 11:34:32 +00003101 return rc;
drh0e1c19e2004-05-11 00:58:56 +00003102}
3103
3104/*
danielk1977d04417962007-05-02 13:16:30 +00003105** Given the page number of an overflow page in the database (parameter
3106** ovfl), this function finds the page number of the next page in the
3107** linked list of overflow pages. If possible, it uses the auto-vacuum
3108** pointer-map data instead of reading the content of page ovfl to do so.
3109**
3110** If an error occurs an SQLite error code is returned. Otherwise:
3111**
3112** Unless pPgnoNext is NULL, the page number of the next overflow
3113** page in the linked list is written to *pPgnoNext. If page ovfl
drh85b623f2007-12-13 21:54:09 +00003114** is the last page in its linked list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003115**
3116** If ppPage is not NULL, *ppPage is set to the MemPage* handle
3117** for page ovfl. The underlying pager page may have been requested
3118** with the noContent flag set, so the page data accessable via
3119** this handle may not be trusted.
3120*/
3121static int getOverflowPage(
3122 BtShared *pBt,
3123 Pgno ovfl, /* Overflow page */
3124 MemPage **ppPage, /* OUT: MemPage handle */
3125 Pgno *pPgnoNext /* OUT: Next overflow page number */
3126){
3127 Pgno next = 0;
drh1bd10f82008-12-10 21:19:56 +00003128 int rc = SQLITE_OK;
danielk1977d04417962007-05-02 13:16:30 +00003129
drh1fee73e2007-08-29 04:00:57 +00003130 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977d04417962007-05-02 13:16:30 +00003131 /* One of these must not be NULL. Otherwise, why call this function? */
3132 assert(ppPage || pPgnoNext);
3133
3134 /* If pPgnoNext is NULL, then this function is being called to obtain
3135 ** a MemPage* reference only. No page-data is required in this case.
3136 */
3137 if( !pPgnoNext ){
drh16a9b832007-05-05 18:39:25 +00003138 return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1);
danielk1977d04417962007-05-02 13:16:30 +00003139 }
3140
3141#ifndef SQLITE_OMIT_AUTOVACUUM
3142 /* Try to find the next page in the overflow list using the
3143 ** autovacuum pointer-map pages. Guess that the next page in
3144 ** the overflow list is page number (ovfl+1). If that guess turns
3145 ** out to be wrong, fall back to loading the data of page
3146 ** number ovfl to determine the next page number.
3147 */
3148 if( pBt->autoVacuum ){
3149 Pgno pgno;
3150 Pgno iGuess = ovfl+1;
3151 u8 eType;
3152
3153 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
3154 iGuess++;
3155 }
3156
danielk197789d40042008-11-17 14:20:56 +00003157 if( iGuess<=pagerPagecount(pBt) ){
danielk1977d04417962007-05-02 13:16:30 +00003158 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
3159 if( rc!=SQLITE_OK ){
3160 return rc;
3161 }
3162 if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
3163 next = iGuess;
3164 }
3165 }
3166 }
3167#endif
3168
3169 if( next==0 || ppPage ){
3170 MemPage *pPage = 0;
3171
drh16a9b832007-05-05 18:39:25 +00003172 rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0);
danielk1977d04417962007-05-02 13:16:30 +00003173 assert(rc==SQLITE_OK || pPage==0);
3174 if( next==0 && rc==SQLITE_OK ){
3175 next = get4byte(pPage->aData);
3176 }
3177
3178 if( ppPage ){
3179 *ppPage = pPage;
3180 }else{
3181 releasePage(pPage);
3182 }
3183 }
3184 *pPgnoNext = next;
3185
3186 return rc;
3187}
3188
danielk1977da107192007-05-04 08:32:13 +00003189/*
3190** Copy data from a buffer to a page, or from a page to a buffer.
3191**
3192** pPayload is a pointer to data stored on database page pDbPage.
3193** If argument eOp is false, then nByte bytes of data are copied
3194** from pPayload to the buffer pointed at by pBuf. If eOp is true,
3195** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
3196** of data are copied from the buffer pBuf to pPayload.
3197**
3198** SQLITE_OK is returned on success, otherwise an error code.
3199*/
3200static int copyPayload(
3201 void *pPayload, /* Pointer to page data */
3202 void *pBuf, /* Pointer to buffer */
3203 int nByte, /* Number of bytes to copy */
3204 int eOp, /* 0 -> copy from page, 1 -> copy to page */
3205 DbPage *pDbPage /* Page containing pPayload */
3206){
3207 if( eOp ){
3208 /* Copy data from buffer to page (a write operation) */
3209 int rc = sqlite3PagerWrite(pDbPage);
3210 if( rc!=SQLITE_OK ){
3211 return rc;
3212 }
3213 memcpy(pPayload, pBuf, nByte);
3214 }else{
3215 /* Copy data from page to buffer (a read operation) */
3216 memcpy(pBuf, pPayload, nByte);
3217 }
3218 return SQLITE_OK;
3219}
danielk1977d04417962007-05-02 13:16:30 +00003220
3221/*
danielk19779f8d6402007-05-02 17:48:45 +00003222** This function is used to read or overwrite payload information
3223** for the entry that the pCur cursor is pointing to. If the eOp
3224** parameter is 0, this is a read operation (data copied into
3225** buffer pBuf). If it is non-zero, a write (data copied from
3226** buffer pBuf).
3227**
3228** A total of "amt" bytes are read or written beginning at "offset".
3229** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00003230**
3231** This routine does not make a distinction between key and data.
danielk19779f8d6402007-05-02 17:48:45 +00003232** It just reads or writes bytes from the payload area. Data might
3233** appear on the main page or be scattered out on multiple overflow
3234** pages.
danielk1977da107192007-05-04 08:32:13 +00003235**
danielk1977dcbb5d32007-05-04 18:36:44 +00003236** If the BtCursor.isIncrblobHandle flag is set, and the current
danielk1977da107192007-05-04 08:32:13 +00003237** cursor entry uses one or more overflow pages, this function
3238** allocates space for and lazily popluates the overflow page-list
3239** cache array (BtCursor.aOverflow). Subsequent calls use this
3240** cache to make seeking to the supplied offset more efficient.
3241**
3242** Once an overflow page-list cache has been allocated, it may be
3243** invalidated if some other cursor writes to the same table, or if
3244** the cursor is moved to a different row. Additionally, in auto-vacuum
3245** mode, the following events may invalidate an overflow page-list cache.
3246**
3247** * An incremental vacuum,
3248** * A commit in auto_vacuum="full" mode,
3249** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00003250*/
danielk19779f8d6402007-05-02 17:48:45 +00003251static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00003252 BtCursor *pCur, /* Cursor pointing to entry to read from */
danielk197789d40042008-11-17 14:20:56 +00003253 u32 offset, /* Begin reading this far into payload */
3254 u32 amt, /* Read this many bytes */
drh3aac2dd2004-04-26 14:10:20 +00003255 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00003256 int skipKey, /* offset begins at data if this is true */
3257 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00003258){
3259 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00003260 int rc = SQLITE_OK;
drhfa1a98a2004-05-14 19:08:17 +00003261 u32 nKey;
danielk19772dec9702007-05-02 16:48:37 +00003262 int iIdx = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003263 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
danielk19770d065412008-11-12 18:21:36 +00003264 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
drh3aac2dd2004-04-26 14:10:20 +00003265
danielk1977da107192007-05-04 08:32:13 +00003266 assert( pPage );
danielk1977da184232006-01-05 11:34:32 +00003267 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003268 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh1fee73e2007-08-29 04:00:57 +00003269 assert( cursorHoldsMutex(pCur) );
danielk1977da107192007-05-04 08:32:13 +00003270
drh86057612007-06-26 01:04:48 +00003271 getCellInfo(pCur);
drh366fda62006-01-13 02:35:09 +00003272 aPayload = pCur->info.pCell + pCur->info.nHeader;
drhf49661a2008-12-10 16:45:50 +00003273 nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
danielk1977da107192007-05-04 08:32:13 +00003274
drh3aac2dd2004-04-26 14:10:20 +00003275 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003276 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00003277 }
danielk19770d065412008-11-12 18:21:36 +00003278 if( offset+amt > nKey+pCur->info.nData
3279 || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
3280 ){
danielk1977da107192007-05-04 08:32:13 +00003281 /* Trying to read or write past the end of the data is an error */
danielk197767fd7a92008-09-10 17:53:35 +00003282 return SQLITE_CORRUPT_BKPT;
drh3aac2dd2004-04-26 14:10:20 +00003283 }
danielk1977da107192007-05-04 08:32:13 +00003284
3285 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00003286 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00003287 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00003288 if( a+offset>pCur->info.nLocal ){
3289 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00003290 }
danielk1977da107192007-05-04 08:32:13 +00003291 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00003292 offset = 0;
drha34b6762004-05-07 13:30:42 +00003293 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00003294 amt -= a;
drhdd793422001-06-28 01:54:48 +00003295 }else{
drhfa1a98a2004-05-14 19:08:17 +00003296 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00003297 }
danielk1977da107192007-05-04 08:32:13 +00003298
3299 if( rc==SQLITE_OK && amt>0 ){
danielk197789d40042008-11-17 14:20:56 +00003300 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
danielk1977da107192007-05-04 08:32:13 +00003301 Pgno nextPage;
3302
drhfa1a98a2004-05-14 19:08:17 +00003303 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00003304
danielk19772dec9702007-05-02 16:48:37 +00003305#ifndef SQLITE_OMIT_INCRBLOB
danielk1977dcbb5d32007-05-04 18:36:44 +00003306 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
danielk1977da107192007-05-04 08:32:13 +00003307 ** has not been allocated, allocate it now. The array is sized at
3308 ** one entry for each overflow page in the overflow chain. The
3309 ** page number of the first overflow page is stored in aOverflow[0],
3310 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
3311 ** (the cache is lazily populated).
3312 */
danielk1977dcbb5d32007-05-04 18:36:44 +00003313 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
danielk19772dec9702007-05-02 16:48:37 +00003314 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
drh17435752007-08-16 04:30:38 +00003315 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
danielk19772dec9702007-05-02 16:48:37 +00003316 if( nOvfl && !pCur->aOverflow ){
danielk1977da107192007-05-04 08:32:13 +00003317 rc = SQLITE_NOMEM;
danielk19772dec9702007-05-02 16:48:37 +00003318 }
3319 }
danielk1977da107192007-05-04 08:32:13 +00003320
3321 /* If the overflow page-list cache has been allocated and the
3322 ** entry for the first required overflow page is valid, skip
3323 ** directly to it.
3324 */
danielk19772dec9702007-05-02 16:48:37 +00003325 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
3326 iIdx = (offset/ovflSize);
3327 nextPage = pCur->aOverflow[iIdx];
3328 offset = (offset%ovflSize);
3329 }
3330#endif
danielk1977da107192007-05-04 08:32:13 +00003331
3332 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
3333
3334#ifndef SQLITE_OMIT_INCRBLOB
3335 /* If required, populate the overflow page-list cache. */
3336 if( pCur->aOverflow ){
3337 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
3338 pCur->aOverflow[iIdx] = nextPage;
3339 }
3340#endif
3341
danielk1977d04417962007-05-02 13:16:30 +00003342 if( offset>=ovflSize ){
3343 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00003344 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00003345 ** data is not required. So first try to lookup the overflow
3346 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00003347 ** function.
danielk1977d04417962007-05-02 13:16:30 +00003348 */
danielk19772dec9702007-05-02 16:48:37 +00003349#ifndef SQLITE_OMIT_INCRBLOB
danielk1977da107192007-05-04 08:32:13 +00003350 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
3351 nextPage = pCur->aOverflow[iIdx+1];
3352 } else
danielk19772dec9702007-05-02 16:48:37 +00003353#endif
danielk1977da107192007-05-04 08:32:13 +00003354 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
danielk1977da107192007-05-04 08:32:13 +00003355 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00003356 }else{
danielk19779f8d6402007-05-02 17:48:45 +00003357 /* Need to read this page properly. It contains some of the
3358 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00003359 */
3360 DbPage *pDbPage;
danielk1977cfe9a692004-06-16 12:00:29 +00003361 int a = amt;
danielk1977d04417962007-05-02 13:16:30 +00003362 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
danielk1977da107192007-05-04 08:32:13 +00003363 if( rc==SQLITE_OK ){
3364 aPayload = sqlite3PagerGetData(pDbPage);
3365 nextPage = get4byte(aPayload);
3366 if( a + offset > ovflSize ){
3367 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00003368 }
danielk1977da107192007-05-04 08:32:13 +00003369 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
3370 sqlite3PagerUnref(pDbPage);
3371 offset = 0;
3372 amt -= a;
3373 pBuf += a;
danielk19779f8d6402007-05-02 17:48:45 +00003374 }
danielk1977cfe9a692004-06-16 12:00:29 +00003375 }
drh2af926b2001-05-15 00:39:25 +00003376 }
drh2af926b2001-05-15 00:39:25 +00003377 }
danielk1977cfe9a692004-06-16 12:00:29 +00003378
danielk1977da107192007-05-04 08:32:13 +00003379 if( rc==SQLITE_OK && amt>0 ){
drh49285702005-09-17 15:20:26 +00003380 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00003381 }
danielk1977da107192007-05-04 08:32:13 +00003382 return rc;
drh2af926b2001-05-15 00:39:25 +00003383}
3384
drh72f82862001-05-24 21:06:34 +00003385/*
drh3aac2dd2004-04-26 14:10:20 +00003386** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003387** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003388** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00003389**
drh3aac2dd2004-04-26 14:10:20 +00003390** Return SQLITE_OK on success or an error code if anything goes
3391** wrong. An error is returned if "offset+amt" is larger than
3392** the available payload.
drh72f82862001-05-24 21:06:34 +00003393*/
drha34b6762004-05-07 13:30:42 +00003394int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003395 int rc;
3396
drh1fee73e2007-08-29 04:00:57 +00003397 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003398 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003399 if( rc==SQLITE_OK ){
3400 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003401 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3402 if( pCur->apPage[0]->intKey ){
danielk1977da184232006-01-05 11:34:32 +00003403 return SQLITE_CORRUPT_BKPT;
3404 }
danielk197771d5d2c2008-09-29 11:49:47 +00003405 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh16a9b832007-05-05 18:39:25 +00003406 rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
drh6575a222005-03-10 17:06:34 +00003407 }
danielk1977da184232006-01-05 11:34:32 +00003408 return rc;
drh3aac2dd2004-04-26 14:10:20 +00003409}
3410
3411/*
drh3aac2dd2004-04-26 14:10:20 +00003412** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003413** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003414** begins at "offset".
3415**
3416** Return SQLITE_OK on success or an error code if anything goes
3417** wrong. An error is returned if "offset+amt" is larger than
3418** the available payload.
drh72f82862001-05-24 21:06:34 +00003419*/
drh3aac2dd2004-04-26 14:10:20 +00003420int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003421 int rc;
3422
danielk19773588ceb2008-06-10 17:30:26 +00003423#ifndef SQLITE_OMIT_INCRBLOB
3424 if ( pCur->eState==CURSOR_INVALID ){
3425 return SQLITE_ABORT;
3426 }
3427#endif
3428
drh1fee73e2007-08-29 04:00:57 +00003429 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003430 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003431 if( rc==SQLITE_OK ){
3432 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003433 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3434 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh16a9b832007-05-05 18:39:25 +00003435 rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
danielk1977da184232006-01-05 11:34:32 +00003436 }
3437 return rc;
drh2af926b2001-05-15 00:39:25 +00003438}
3439
drh72f82862001-05-24 21:06:34 +00003440/*
drh0e1c19e2004-05-11 00:58:56 +00003441** Return a pointer to payload information from the entry that the
3442** pCur cursor is pointing to. The pointer is to the beginning of
3443** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00003444** skipKey==1. The number of bytes of available key/data is written
3445** into *pAmt. If *pAmt==0, then the value returned will not be
3446** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00003447**
3448** This routine is an optimization. It is common for the entire key
3449** and data to fit on the local page and for there to be no overflow
3450** pages. When that is so, this routine can be used to access the
3451** key and data without making a copy. If the key and/or data spills
drh16a9b832007-05-05 18:39:25 +00003452** onto overflow pages, then accessPayload() must be used to reassembly
drh0e1c19e2004-05-11 00:58:56 +00003453** the key/data and copy it into a preallocated buffer.
3454**
3455** The pointer returned by this routine looks directly into the cached
3456** page of the database. The data might change or move the next time
3457** any btree routine is called.
3458*/
3459static const unsigned char *fetchPayload(
3460 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00003461 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00003462 int skipKey /* read beginning at data if this is true */
3463){
3464 unsigned char *aPayload;
3465 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00003466 u32 nKey;
danielk197789d40042008-11-17 14:20:56 +00003467 u32 nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003468
danielk197771d5d2c2008-09-29 11:49:47 +00003469 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
danielk1977da184232006-01-05 11:34:32 +00003470 assert( pCur->eState==CURSOR_VALID );
drh1fee73e2007-08-29 04:00:57 +00003471 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00003472 pPage = pCur->apPage[pCur->iPage];
3473 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh86057612007-06-26 01:04:48 +00003474 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00003475 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00003476 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00003477 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00003478 nKey = 0;
3479 }else{
drhf49661a2008-12-10 16:45:50 +00003480 nKey = (int)pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00003481 }
drh0e1c19e2004-05-11 00:58:56 +00003482 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003483 aPayload += nKey;
3484 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00003485 }else{
drhfa1a98a2004-05-14 19:08:17 +00003486 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00003487 if( nLocal>nKey ){
3488 nLocal = nKey;
3489 }
drh0e1c19e2004-05-11 00:58:56 +00003490 }
drhe51c44f2004-05-30 20:46:09 +00003491 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003492 return aPayload;
3493}
3494
3495
3496/*
drhe51c44f2004-05-30 20:46:09 +00003497** For the entry that cursor pCur is point to, return as
3498** many bytes of the key or data as are available on the local
3499** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00003500**
3501** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00003502** or be destroyed on the next call to any Btree routine,
3503** including calls from other threads against the same cache.
3504** Hence, a mutex on the BtShared should be held prior to calling
3505** this routine.
drh0e1c19e2004-05-11 00:58:56 +00003506**
3507** These routines is used to get quick access to key and data
3508** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00003509*/
drhe51c44f2004-05-30 20:46:09 +00003510const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
drh1fee73e2007-08-29 04:00:57 +00003511 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003512 if( pCur->eState==CURSOR_VALID ){
3513 return (const void*)fetchPayload(pCur, pAmt, 0);
3514 }
3515 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003516}
drhe51c44f2004-05-30 20:46:09 +00003517const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
drh1fee73e2007-08-29 04:00:57 +00003518 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003519 if( pCur->eState==CURSOR_VALID ){
3520 return (const void*)fetchPayload(pCur, pAmt, 1);
3521 }
3522 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003523}
3524
3525
3526/*
drh8178a752003-01-05 21:41:40 +00003527** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00003528** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00003529*/
drh3aac2dd2004-04-26 14:10:20 +00003530static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00003531 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003532 int i = pCur->iPage;
drh72f82862001-05-24 21:06:34 +00003533 MemPage *pNewPage;
drhd0679ed2007-08-28 22:24:34 +00003534 BtShared *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00003535
drh1fee73e2007-08-29 04:00:57 +00003536 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003537 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003538 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
3539 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
3540 return SQLITE_CORRUPT_BKPT;
3541 }
3542 rc = getAndInitPage(pBt, newPgno, &pNewPage);
drh6019e162001-07-02 17:51:45 +00003543 if( rc ) return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003544 pCur->apPage[i+1] = pNewPage;
3545 pCur->aiIdx[i+1] = 0;
3546 pCur->iPage++;
3547
drh271efa52004-05-30 19:19:05 +00003548 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003549 pCur->validNKey = 0;
drh4be295b2003-12-16 03:44:47 +00003550 if( pNewPage->nCell<1 ){
drh49285702005-09-17 15:20:26 +00003551 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00003552 }
drh72f82862001-05-24 21:06:34 +00003553 return SQLITE_OK;
3554}
3555
danielk1977bf93c562008-09-29 15:53:25 +00003556#ifndef NDEBUG
3557/*
3558** Page pParent is an internal (non-leaf) tree page. This function
3559** asserts that page number iChild is the left-child if the iIdx'th
3560** cell in page pParent. Or, if iIdx is equal to the total number of
3561** cells in pParent, that page number iChild is the right-child of
3562** the page.
3563*/
3564static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
3565 assert( iIdx<=pParent->nCell );
3566 if( iIdx==pParent->nCell ){
3567 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
3568 }else{
3569 assert( get4byte(findCell(pParent, iIdx))==iChild );
3570 }
3571}
3572#else
3573# define assertParentIndex(x,y,z)
3574#endif
3575
drh72f82862001-05-24 21:06:34 +00003576/*
drh5e2f8b92001-05-28 00:41:15 +00003577** Move the cursor up to the parent page.
3578**
3579** pCur->idx is set to the cell index that contains the pointer
3580** to the page we are coming from. If we are coming from the
3581** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00003582** the largest cell index.
drh72f82862001-05-24 21:06:34 +00003583*/
drh16a9b832007-05-05 18:39:25 +00003584void sqlite3BtreeMoveToParent(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00003585 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003586 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003587 assert( pCur->iPage>0 );
3588 assert( pCur->apPage[pCur->iPage] );
danielk1977bf93c562008-09-29 15:53:25 +00003589 assertParentIndex(
3590 pCur->apPage[pCur->iPage-1],
3591 pCur->aiIdx[pCur->iPage-1],
3592 pCur->apPage[pCur->iPage]->pgno
3593 );
danielk197771d5d2c2008-09-29 11:49:47 +00003594 releasePage(pCur->apPage[pCur->iPage]);
3595 pCur->iPage--;
drh271efa52004-05-30 19:19:05 +00003596 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003597 pCur->validNKey = 0;
drh72f82862001-05-24 21:06:34 +00003598}
3599
3600/*
3601** Move the cursor to the root page
3602*/
drh5e2f8b92001-05-28 00:41:15 +00003603static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00003604 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00003605 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003606 Btree *p = pCur->pBtree;
3607 BtShared *pBt = p->pBt;
drhbd03cae2001-06-02 02:40:57 +00003608
drh1fee73e2007-08-29 04:00:57 +00003609 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +00003610 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
3611 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
3612 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
3613 if( pCur->eState>=CURSOR_REQUIRESEEK ){
3614 if( pCur->eState==CURSOR_FAULT ){
3615 return pCur->skip;
3616 }
danielk1977be51a652008-10-08 17:58:48 +00003617 sqlite3BtreeClearCursor(pCur);
drhbf700f32007-03-31 02:36:44 +00003618 }
danielk197771d5d2c2008-09-29 11:49:47 +00003619
3620 if( pCur->iPage>=0 ){
3621 int i;
3622 for(i=1; i<=pCur->iPage; i++){
3623 releasePage(pCur->apPage[i]);
danielk1977d9f6c532008-09-19 16:39:38 +00003624 }
drh777e4c42006-01-13 04:31:58 +00003625 }else{
3626 if(
danielk197771d5d2c2008-09-29 11:49:47 +00003627 SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]))
drh777e4c42006-01-13 04:31:58 +00003628 ){
3629 pCur->eState = CURSOR_INVALID;
3630 return rc;
3631 }
drhc39e0002004-05-07 23:50:57 +00003632 }
danielk197771d5d2c2008-09-29 11:49:47 +00003633
3634 pRoot = pCur->apPage[0];
3635 assert( pRoot->pgno==pCur->pgnoRoot );
3636 pCur->iPage = 0;
3637 pCur->aiIdx[0] = 0;
drh271efa52004-05-30 19:19:05 +00003638 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003639 pCur->atLast = 0;
3640 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003641
drh8856d6a2004-04-29 14:42:46 +00003642 if( pRoot->nCell==0 && !pRoot->leaf ){
3643 Pgno subpage;
3644 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00003645 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00003646 assert( subpage>0 );
danielk1977da184232006-01-05 11:34:32 +00003647 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00003648 rc = moveToChild(pCur, subpage);
danielk197771d5d2c2008-09-29 11:49:47 +00003649 }else{
3650 pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
drh8856d6a2004-04-29 14:42:46 +00003651 }
3652 return rc;
drh72f82862001-05-24 21:06:34 +00003653}
drh2af926b2001-05-15 00:39:25 +00003654
drh5e2f8b92001-05-28 00:41:15 +00003655/*
3656** Move the cursor down to the left-most leaf entry beneath the
3657** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00003658**
3659** The left-most leaf is the one with the smallest key - the first
3660** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00003661*/
3662static int moveToLeftmost(BtCursor *pCur){
3663 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00003664 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00003665 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00003666
drh1fee73e2007-08-29 04:00:57 +00003667 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003668 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003669 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
3670 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
3671 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
drh8178a752003-01-05 21:41:40 +00003672 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00003673 }
drhd677b3d2007-08-20 22:48:41 +00003674 return rc;
drh5e2f8b92001-05-28 00:41:15 +00003675}
3676
drh2dcc9aa2002-12-04 13:40:25 +00003677/*
3678** Move the cursor down to the right-most leaf entry beneath the
3679** page to which it is currently pointing. Notice the difference
3680** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
3681** finds the left-most entry beneath the *entry* whereas moveToRightmost()
3682** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00003683**
3684** The right-most entry is the one with the largest key - the last
3685** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00003686*/
3687static int moveToRightmost(BtCursor *pCur){
3688 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00003689 int rc = SQLITE_OK;
drh1bd10f82008-12-10 21:19:56 +00003690 MemPage *pPage = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003691
drh1fee73e2007-08-29 04:00:57 +00003692 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003693 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003694 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
drh43605152004-05-29 21:46:49 +00003695 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
danielk197771d5d2c2008-09-29 11:49:47 +00003696 pCur->aiIdx[pCur->iPage] = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00003697 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003698 }
drhd677b3d2007-08-20 22:48:41 +00003699 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00003700 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
drhd677b3d2007-08-20 22:48:41 +00003701 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003702 pCur->validNKey = 0;
drhd677b3d2007-08-20 22:48:41 +00003703 }
danielk1977518002e2008-09-05 05:02:46 +00003704 return rc;
drh2dcc9aa2002-12-04 13:40:25 +00003705}
3706
drh5e00f6c2001-09-13 13:46:56 +00003707/* Move the cursor to the first entry in the table. Return SQLITE_OK
3708** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003709** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00003710*/
drh3aac2dd2004-04-26 14:10:20 +00003711int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00003712 int rc;
drhd677b3d2007-08-20 22:48:41 +00003713
drh1fee73e2007-08-29 04:00:57 +00003714 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003715 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00003716 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003717 if( rc==SQLITE_OK ){
3718 if( pCur->eState==CURSOR_INVALID ){
danielk197771d5d2c2008-09-29 11:49:47 +00003719 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00003720 *pRes = 1;
3721 rc = SQLITE_OK;
3722 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00003723 assert( pCur->apPage[pCur->iPage]->nCell>0 );
drhd677b3d2007-08-20 22:48:41 +00003724 *pRes = 0;
3725 rc = moveToLeftmost(pCur);
3726 }
drh5e00f6c2001-09-13 13:46:56 +00003727 }
drh5e00f6c2001-09-13 13:46:56 +00003728 return rc;
3729}
drh5e2f8b92001-05-28 00:41:15 +00003730
drh9562b552002-02-19 15:00:07 +00003731/* Move the cursor to the last entry in the table. Return SQLITE_OK
3732** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003733** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00003734*/
drh3aac2dd2004-04-26 14:10:20 +00003735int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00003736 int rc;
drhd677b3d2007-08-20 22:48:41 +00003737
drh1fee73e2007-08-29 04:00:57 +00003738 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003739 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh9562b552002-02-19 15:00:07 +00003740 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003741 if( rc==SQLITE_OK ){
3742 if( CURSOR_INVALID==pCur->eState ){
danielk197771d5d2c2008-09-29 11:49:47 +00003743 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00003744 *pRes = 1;
3745 }else{
3746 assert( pCur->eState==CURSOR_VALID );
3747 *pRes = 0;
3748 rc = moveToRightmost(pCur);
drha2c20e42008-03-29 16:01:04 +00003749 getCellInfo(pCur);
drhf49661a2008-12-10 16:45:50 +00003750 pCur->atLast = rc==SQLITE_OK ?1:0;
drhd677b3d2007-08-20 22:48:41 +00003751 }
drh9562b552002-02-19 15:00:07 +00003752 }
drh9562b552002-02-19 15:00:07 +00003753 return rc;
3754}
3755
drhe14006d2008-03-25 17:23:32 +00003756/* Move the cursor so that it points to an entry near the key
drhe63d9992008-08-13 19:11:48 +00003757** specified by pIdxKey or intKey. Return a success code.
drh72f82862001-05-24 21:06:34 +00003758**
drhe63d9992008-08-13 19:11:48 +00003759** For INTKEY tables, the intKey parameter is used. pIdxKey
3760** must be NULL. For index tables, pIdxKey is used and intKey
3761** is ignored.
drh3aac2dd2004-04-26 14:10:20 +00003762**
drh5e2f8b92001-05-28 00:41:15 +00003763** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00003764** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00003765** were present. The cursor might point to an entry that comes
3766** before or after the key.
3767**
drhbd03cae2001-06-02 02:40:57 +00003768** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00003769** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00003770** this value is as follows:
3771**
3772** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00003773** is smaller than pKey or if the table is empty
3774** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00003775**
3776** *pRes==0 The cursor is left pointing at an entry that
3777** exactly matches pKey.
3778**
3779** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00003780** is larger than pKey.
drhd677b3d2007-08-20 22:48:41 +00003781**
drha059ad02001-04-17 20:09:11 +00003782*/
drhe63d9992008-08-13 19:11:48 +00003783int sqlite3BtreeMovetoUnpacked(
3784 BtCursor *pCur, /* The cursor to be moved */
3785 UnpackedRecord *pIdxKey, /* Unpacked index key */
3786 i64 intKey, /* The table key */
3787 int biasRight, /* If true, bias the search to the high end */
3788 int *pRes /* Write search results here */
drhe4d90812007-03-29 05:51:49 +00003789){
drh72f82862001-05-24 21:06:34 +00003790 int rc;
drhd677b3d2007-08-20 22:48:41 +00003791
drh1fee73e2007-08-29 04:00:57 +00003792 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003793 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drha2c20e42008-03-29 16:01:04 +00003794
3795 /* If the cursor is already positioned at the point we are trying
3796 ** to move to, then just return without doing any work */
danielk197771d5d2c2008-09-29 11:49:47 +00003797 if( pCur->eState==CURSOR_VALID && pCur->validNKey
3798 && pCur->apPage[0]->intKey
3799 ){
drhe63d9992008-08-13 19:11:48 +00003800 if( pCur->info.nKey==intKey ){
drha2c20e42008-03-29 16:01:04 +00003801 *pRes = 0;
3802 return SQLITE_OK;
3803 }
drhe63d9992008-08-13 19:11:48 +00003804 if( pCur->atLast && pCur->info.nKey<intKey ){
drha2c20e42008-03-29 16:01:04 +00003805 *pRes = -1;
3806 return SQLITE_OK;
3807 }
3808 }
3809
drh5e2f8b92001-05-28 00:41:15 +00003810 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003811 if( rc ){
3812 return rc;
3813 }
danielk197771d5d2c2008-09-29 11:49:47 +00003814 assert( pCur->apPage[pCur->iPage] );
3815 assert( pCur->apPage[pCur->iPage]->isInit );
danielk1977da184232006-01-05 11:34:32 +00003816 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00003817 *pRes = -1;
danielk197771d5d2c2008-09-29 11:49:47 +00003818 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhc39e0002004-05-07 23:50:57 +00003819 return SQLITE_OK;
3820 }
danielk197771d5d2c2008-09-29 11:49:47 +00003821 assert( pCur->apPage[0]->intKey || pIdxKey );
drh14684382006-11-30 13:05:29 +00003822 for(;;){
drh72f82862001-05-24 21:06:34 +00003823 int lwr, upr;
3824 Pgno chldPg;
danielk197771d5d2c2008-09-29 11:49:47 +00003825 MemPage *pPage = pCur->apPage[pCur->iPage];
drh1a844c32002-12-04 22:29:28 +00003826 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00003827 lwr = 0;
3828 upr = pPage->nCell-1;
drhe63d9992008-08-13 19:11:48 +00003829 if( !pPage->intKey && pIdxKey==0 ){
drh1e968a02008-03-25 00:22:21 +00003830 rc = SQLITE_CORRUPT_BKPT;
3831 goto moveto_finish;
drh4eec4c12005-01-21 00:22:37 +00003832 }
drhe4d90812007-03-29 05:51:49 +00003833 if( biasRight ){
drhf49661a2008-12-10 16:45:50 +00003834 pCur->aiIdx[pCur->iPage] = (u16)upr;
drhe4d90812007-03-29 05:51:49 +00003835 }else{
drhf49661a2008-12-10 16:45:50 +00003836 pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
drhe4d90812007-03-29 05:51:49 +00003837 }
drhf1d68b32007-03-29 04:43:26 +00003838 if( lwr<=upr ) for(;;){
danielk197713adf8a2004-06-03 16:08:41 +00003839 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00003840 i64 nCellKey;
danielk197771d5d2c2008-09-29 11:49:47 +00003841 int idx = pCur->aiIdx[pCur->iPage];
drh366fda62006-01-13 02:35:09 +00003842 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003843 pCur->validNKey = 1;
drh3aac2dd2004-04-26 14:10:20 +00003844 if( pPage->intKey ){
drh777e4c42006-01-13 04:31:58 +00003845 u8 *pCell;
danielk197771d5d2c2008-09-29 11:49:47 +00003846 pCell = findCell(pPage, idx) + pPage->childPtrSize;
drhd172f862006-01-12 15:01:15 +00003847 if( pPage->hasData ){
danielk1977bab45c62006-01-16 15:14:27 +00003848 u32 dummy;
shane3f8d5cf2008-04-24 19:15:09 +00003849 pCell += getVarint32(pCell, dummy);
drhd172f862006-01-12 15:01:15 +00003850 }
drha2c20e42008-03-29 16:01:04 +00003851 getVarint(pCell, (u64*)&nCellKey);
drhe63d9992008-08-13 19:11:48 +00003852 if( nCellKey==intKey ){
drh3aac2dd2004-04-26 14:10:20 +00003853 c = 0;
drhe63d9992008-08-13 19:11:48 +00003854 }else if( nCellKey<intKey ){
drh41eb9e92008-04-02 18:33:07 +00003855 c = -1;
3856 }else{
drhe63d9992008-08-13 19:11:48 +00003857 assert( nCellKey>intKey );
drh41eb9e92008-04-02 18:33:07 +00003858 c = +1;
drh3aac2dd2004-04-26 14:10:20 +00003859 }
drh3aac2dd2004-04-26 14:10:20 +00003860 }else{
drhe51c44f2004-05-30 20:46:09 +00003861 int available;
danielk197713adf8a2004-06-03 16:08:41 +00003862 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drh366fda62006-01-13 02:35:09 +00003863 nCellKey = pCur->info.nKey;
drhe51c44f2004-05-30 20:46:09 +00003864 if( available>=nCellKey ){
drhf49661a2008-12-10 16:45:50 +00003865 c = sqlite3VdbeRecordCompare((int)nCellKey, pCellKey, pIdxKey);
drhe51c44f2004-05-30 20:46:09 +00003866 }else{
drhf49661a2008-12-10 16:45:50 +00003867 pCellKey = sqlite3Malloc( (int)nCellKey );
danielk19776507ecb2008-03-25 09:56:44 +00003868 if( pCellKey==0 ){
3869 rc = SQLITE_NOMEM;
3870 goto moveto_finish;
3871 }
drhf49661a2008-12-10 16:45:50 +00003872 rc = sqlite3BtreeKey(pCur, 0, (int)nCellKey, (void*)pCellKey);
drh1bd10f82008-12-10 21:19:56 +00003873 c = sqlite3VdbeRecordCompare((int)nCellKey, pCellKey, pIdxKey);
drhfacf0302008-06-17 15:12:00 +00003874 sqlite3_free(pCellKey);
drh1e968a02008-03-25 00:22:21 +00003875 if( rc ) goto moveto_finish;
drhe51c44f2004-05-30 20:46:09 +00003876 }
drh3aac2dd2004-04-26 14:10:20 +00003877 }
drh72f82862001-05-24 21:06:34 +00003878 if( c==0 ){
drha2c20e42008-03-29 16:01:04 +00003879 pCur->info.nKey = nCellKey;
drh44845222008-07-17 18:39:57 +00003880 if( pPage->intKey && !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00003881 lwr = idx;
drhfc70e6f2004-05-12 21:11:27 +00003882 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00003883 break;
3884 }else{
drh8b18dd42004-05-12 19:18:15 +00003885 if( pRes ) *pRes = 0;
drh1e968a02008-03-25 00:22:21 +00003886 rc = SQLITE_OK;
3887 goto moveto_finish;
drh8b18dd42004-05-12 19:18:15 +00003888 }
drh72f82862001-05-24 21:06:34 +00003889 }
3890 if( c<0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003891 lwr = idx+1;
drh72f82862001-05-24 21:06:34 +00003892 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00003893 upr = idx-1;
drh72f82862001-05-24 21:06:34 +00003894 }
drhf1d68b32007-03-29 04:43:26 +00003895 if( lwr>upr ){
drha2c20e42008-03-29 16:01:04 +00003896 pCur->info.nKey = nCellKey;
drhf1d68b32007-03-29 04:43:26 +00003897 break;
3898 }
drhf49661a2008-12-10 16:45:50 +00003899 pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
drh72f82862001-05-24 21:06:34 +00003900 }
3901 assert( lwr==upr+1 );
danielk197771d5d2c2008-09-29 11:49:47 +00003902 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00003903 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00003904 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00003905 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00003906 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00003907 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00003908 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00003909 }
3910 if( chldPg==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003911 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh72f82862001-05-24 21:06:34 +00003912 if( pRes ) *pRes = c;
drh1e968a02008-03-25 00:22:21 +00003913 rc = SQLITE_OK;
3914 goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00003915 }
drhf49661a2008-12-10 16:45:50 +00003916 pCur->aiIdx[pCur->iPage] = (u16)lwr;
drh271efa52004-05-30 19:19:05 +00003917 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003918 pCur->validNKey = 0;
drh8178a752003-01-05 21:41:40 +00003919 rc = moveToChild(pCur, chldPg);
drh1e968a02008-03-25 00:22:21 +00003920 if( rc ) goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00003921 }
drh1e968a02008-03-25 00:22:21 +00003922moveto_finish:
drhe63d9992008-08-13 19:11:48 +00003923 return rc;
3924}
3925
3926/*
3927** In this version of BtreeMoveto, pKey is a packed index record
3928** such as is generated by the OP_MakeRecord opcode. Unpack the
3929** record and then call BtreeMovetoUnpacked() to do the work.
3930*/
3931int sqlite3BtreeMoveto(
3932 BtCursor *pCur, /* Cursor open on the btree to be searched */
3933 const void *pKey, /* Packed key if the btree is an index */
3934 i64 nKey, /* Integer key for tables. Size of pKey for indices */
3935 int bias, /* Bias search to the high end */
3936 int *pRes /* Write search results here */
3937){
3938 int rc; /* Status code */
3939 UnpackedRecord *pIdxKey; /* Unpacked index key */
drh23f79d02008-08-20 22:06:47 +00003940 UnpackedRecord aSpace[16]; /* Temp space for pIdxKey - to avoid a malloc */
drhe63d9992008-08-13 19:11:48 +00003941
drhe14006d2008-03-25 17:23:32 +00003942 if( pKey ){
drhf49661a2008-12-10 16:45:50 +00003943 assert( nKey==(i64)(int)nKey );
3944 pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
drh23f79d02008-08-20 22:06:47 +00003945 aSpace, sizeof(aSpace));
drhe63d9992008-08-13 19:11:48 +00003946 if( pIdxKey==0 ) return SQLITE_NOMEM;
3947 }else{
3948 pIdxKey = 0;
3949 }
3950 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
3951 if( pKey ){
3952 sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
drhe14006d2008-03-25 17:23:32 +00003953 }
drh1e968a02008-03-25 00:22:21 +00003954 return rc;
drh72f82862001-05-24 21:06:34 +00003955}
3956
drhd677b3d2007-08-20 22:48:41 +00003957
drh72f82862001-05-24 21:06:34 +00003958/*
drhc39e0002004-05-07 23:50:57 +00003959** Return TRUE if the cursor is not pointing at an entry of the table.
3960**
3961** TRUE will be returned after a call to sqlite3BtreeNext() moves
3962** past the last entry in the table or sqlite3BtreePrev() moves past
3963** the first entry. TRUE is also returned if the table is empty.
3964*/
3965int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00003966 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
3967 ** have been deleted? This API will need to change to return an error code
3968 ** as well as the boolean result value.
3969 */
3970 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00003971}
3972
3973/*
drhb21c8cd2007-08-21 19:33:56 +00003974** Return the database connection handle for a cursor.
3975*/
3976sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){
drhe5fe6902007-12-07 18:55:28 +00003977 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
3978 return pCur->pBtree->db;
drhb21c8cd2007-08-21 19:33:56 +00003979}
3980
3981/*
drhbd03cae2001-06-02 02:40:57 +00003982** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00003983** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00003984** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00003985** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00003986*/
drhd094db12008-04-03 21:46:57 +00003987int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00003988 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003989 int idx;
danielk197797a227c2006-01-20 16:32:04 +00003990 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00003991
drh1fee73e2007-08-29 04:00:57 +00003992 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003993 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003994 if( rc!=SQLITE_OK ){
3995 return rc;
3996 }
drh8c4d3a62007-04-06 01:03:32 +00003997 assert( pRes!=0 );
drh8c4d3a62007-04-06 01:03:32 +00003998 if( CURSOR_INVALID==pCur->eState ){
3999 *pRes = 1;
4000 return SQLITE_OK;
4001 }
danielk1977da184232006-01-05 11:34:32 +00004002 if( pCur->skip>0 ){
4003 pCur->skip = 0;
4004 *pRes = 0;
4005 return SQLITE_OK;
4006 }
4007 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00004008
danielk197771d5d2c2008-09-29 11:49:47 +00004009 pPage = pCur->apPage[pCur->iPage];
4010 idx = ++pCur->aiIdx[pCur->iPage];
4011 assert( pPage->isInit );
4012 assert( idx<=pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00004013
drh271efa52004-05-30 19:19:05 +00004014 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004015 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004016 if( idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00004017 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004018 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00004019 if( rc ) return rc;
4020 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00004021 *pRes = 0;
4022 return rc;
drh72f82862001-05-24 21:06:34 +00004023 }
drh5e2f8b92001-05-28 00:41:15 +00004024 do{
danielk197771d5d2c2008-09-29 11:49:47 +00004025 if( pCur->iPage==0 ){
drh8c1238a2003-01-02 14:43:55 +00004026 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00004027 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00004028 return SQLITE_OK;
4029 }
drh16a9b832007-05-05 18:39:25 +00004030 sqlite3BtreeMoveToParent(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00004031 pPage = pCur->apPage[pCur->iPage];
4032 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00004033 *pRes = 0;
drh44845222008-07-17 18:39:57 +00004034 if( pPage->intKey ){
drh8b18dd42004-05-12 19:18:15 +00004035 rc = sqlite3BtreeNext(pCur, pRes);
4036 }else{
4037 rc = SQLITE_OK;
4038 }
4039 return rc;
drh8178a752003-01-05 21:41:40 +00004040 }
4041 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00004042 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00004043 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00004044 }
drh5e2f8b92001-05-28 00:41:15 +00004045 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00004046 return rc;
drh72f82862001-05-24 21:06:34 +00004047}
drhd677b3d2007-08-20 22:48:41 +00004048
drh72f82862001-05-24 21:06:34 +00004049
drh3b7511c2001-05-26 13:15:44 +00004050/*
drh2dcc9aa2002-12-04 13:40:25 +00004051** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00004052** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00004053** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00004054** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00004055*/
drhd094db12008-04-03 21:46:57 +00004056int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00004057 int rc;
drh8178a752003-01-05 21:41:40 +00004058 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00004059
drh1fee73e2007-08-29 04:00:57 +00004060 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004061 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004062 if( rc!=SQLITE_OK ){
4063 return rc;
4064 }
drha2c20e42008-03-29 16:01:04 +00004065 pCur->atLast = 0;
drh8c4d3a62007-04-06 01:03:32 +00004066 if( CURSOR_INVALID==pCur->eState ){
4067 *pRes = 1;
4068 return SQLITE_OK;
4069 }
danielk1977da184232006-01-05 11:34:32 +00004070 if( pCur->skip<0 ){
4071 pCur->skip = 0;
4072 *pRes = 0;
4073 return SQLITE_OK;
4074 }
4075 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00004076
danielk197771d5d2c2008-09-29 11:49:47 +00004077 pPage = pCur->apPage[pCur->iPage];
4078 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00004079 if( !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00004080 int idx = pCur->aiIdx[pCur->iPage];
4081 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
drhd677b3d2007-08-20 22:48:41 +00004082 if( rc ){
4083 return rc;
4084 }
drh2dcc9aa2002-12-04 13:40:25 +00004085 rc = moveToRightmost(pCur);
4086 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004087 while( pCur->aiIdx[pCur->iPage]==0 ){
4088 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00004089 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00004090 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00004091 return SQLITE_OK;
4092 }
drh16a9b832007-05-05 18:39:25 +00004093 sqlite3BtreeMoveToParent(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00004094 }
drh271efa52004-05-30 19:19:05 +00004095 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004096 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004097
4098 pCur->aiIdx[pCur->iPage]--;
4099 pPage = pCur->apPage[pCur->iPage];
drh44845222008-07-17 18:39:57 +00004100 if( pPage->intKey && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00004101 rc = sqlite3BtreePrevious(pCur, pRes);
4102 }else{
4103 rc = SQLITE_OK;
4104 }
drh2dcc9aa2002-12-04 13:40:25 +00004105 }
drh8178a752003-01-05 21:41:40 +00004106 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00004107 return rc;
4108}
4109
4110/*
drh3b7511c2001-05-26 13:15:44 +00004111** Allocate a new page from the database file.
4112**
danielk19773b8a05f2007-03-19 17:44:26 +00004113** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00004114** has already been called on the new page.) The new page has also
4115** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00004116** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00004117**
4118** SQLITE_OK is returned on success. Any other return value indicates
4119** an error. *ppPage and *pPgno are undefined in the event of an error.
danielk19773b8a05f2007-03-19 17:44:26 +00004120** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00004121**
drh199e3cf2002-07-18 11:01:47 +00004122** If the "nearby" parameter is not 0, then a (feeble) effort is made to
4123** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00004124** attempt to keep related pages close to each other in the database file,
4125** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00004126**
4127** If the "exact" parameter is not 0, and the page-number nearby exists
4128** anywhere on the free-list, then it is guarenteed to be returned. This
4129** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00004130*/
drh4f0c5872007-03-26 22:05:01 +00004131static int allocateBtreePage(
danielk1977aef0bf62005-12-30 16:28:01 +00004132 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00004133 MemPage **ppPage,
4134 Pgno *pPgno,
4135 Pgno nearby,
4136 u8 exact
4137){
drh3aac2dd2004-04-26 14:10:20 +00004138 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00004139 int rc;
drh3aac2dd2004-04-26 14:10:20 +00004140 int n; /* Number of pages on the freelist */
4141 int k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00004142 MemPage *pTrunk = 0;
4143 MemPage *pPrevTrunk = 0;
drh30e58752002-03-02 20:41:57 +00004144
drh1fee73e2007-08-29 04:00:57 +00004145 assert( sqlite3_mutex_held(pBt->mutex) );
drh3aac2dd2004-04-26 14:10:20 +00004146 pPage1 = pBt->pPage1;
4147 n = get4byte(&pPage1->aData[36]);
4148 if( n>0 ){
drh91025292004-05-03 19:49:32 +00004149 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00004150 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004151 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
4152
4153 /* If the 'exact' parameter was true and a query of the pointer-map
4154 ** shows that the page 'nearby' is somewhere on the free-list, then
4155 ** the entire-list will be searched for that page.
4156 */
4157#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197789d40042008-11-17 14:20:56 +00004158 if( exact && nearby<=pagerPagecount(pBt) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004159 u8 eType;
4160 assert( nearby>0 );
4161 assert( pBt->autoVacuum );
4162 rc = ptrmapGet(pBt, nearby, &eType, 0);
4163 if( rc ) return rc;
4164 if( eType==PTRMAP_FREEPAGE ){
4165 searchList = 1;
4166 }
4167 *pPgno = nearby;
4168 }
4169#endif
4170
4171 /* Decrement the free-list count by 1. Set iTrunk to the index of the
4172 ** first free-list trunk page. iPrevTrunk is initially 1.
4173 */
danielk19773b8a05f2007-03-19 17:44:26 +00004174 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00004175 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004176 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004177
4178 /* The code within this loop is run only once if the 'searchList' variable
4179 ** is not true. Otherwise, it runs once for each trunk-page on the
4180 ** free-list until the page 'nearby' is located.
4181 */
4182 do {
4183 pPrevTrunk = pTrunk;
4184 if( pPrevTrunk ){
4185 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00004186 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004187 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00004188 }
drh16a9b832007-05-05 18:39:25 +00004189 rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004190 if( rc ){
drhd3627af2006-12-18 18:34:51 +00004191 pTrunk = 0;
4192 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004193 }
4194
4195 k = get4byte(&pTrunk->aData[4]);
4196 if( k==0 && !searchList ){
4197 /* The trunk has no leaves and the list is not being searched.
4198 ** So extract the trunk page itself and use it as the newly
4199 ** allocated page */
4200 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00004201 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004202 if( rc ){
4203 goto end_allocate_page;
4204 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004205 *pPgno = iTrunk;
4206 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4207 *ppPage = pTrunk;
4208 pTrunk = 0;
4209 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh45b1fac2008-07-04 17:52:42 +00004210 }else if( k>pBt->usableSize/4 - 2 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004211 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00004212 rc = SQLITE_CORRUPT_BKPT;
4213 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004214#ifndef SQLITE_OMIT_AUTOVACUUM
4215 }else if( searchList && nearby==iTrunk ){
4216 /* The list is being searched and this trunk page is the page
4217 ** to allocate, regardless of whether it has leaves.
4218 */
4219 assert( *pPgno==iTrunk );
4220 *ppPage = pTrunk;
4221 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00004222 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004223 if( rc ){
4224 goto end_allocate_page;
4225 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004226 if( k==0 ){
4227 if( !pPrevTrunk ){
4228 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4229 }else{
4230 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
4231 }
4232 }else{
4233 /* The trunk page is required by the caller but it contains
4234 ** pointers to free-list leaves. The first leaf becomes a trunk
4235 ** page in this case.
4236 */
4237 MemPage *pNewTrunk;
4238 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh16a9b832007-05-05 18:39:25 +00004239 rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004240 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00004241 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004242 }
danielk19773b8a05f2007-03-19 17:44:26 +00004243 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004244 if( rc!=SQLITE_OK ){
4245 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00004246 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004247 }
4248 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
4249 put4byte(&pNewTrunk->aData[4], k-1);
4250 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00004251 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004252 if( !pPrevTrunk ){
drhc5053fb2008-11-27 02:22:10 +00004253 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
danielk1977cb1a7eb2004-11-05 12:27:02 +00004254 put4byte(&pPage1->aData[32], iNewTrunk);
4255 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00004256 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004257 if( rc ){
4258 goto end_allocate_page;
4259 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004260 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
4261 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004262 }
4263 pTrunk = 0;
4264 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
4265#endif
4266 }else{
4267 /* Extract a leaf from the trunk */
4268 int closest;
4269 Pgno iPage;
4270 unsigned char *aData = pTrunk->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00004271 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004272 if( rc ){
4273 goto end_allocate_page;
4274 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004275 if( nearby>0 ){
4276 int i, dist;
4277 closest = 0;
4278 dist = get4byte(&aData[8]) - nearby;
4279 if( dist<0 ) dist = -dist;
4280 for(i=1; i<k; i++){
4281 int d2 = get4byte(&aData[8+i*4]) - nearby;
4282 if( d2<0 ) d2 = -d2;
4283 if( d2<dist ){
4284 closest = i;
4285 dist = d2;
4286 }
4287 }
4288 }else{
4289 closest = 0;
4290 }
4291
4292 iPage = get4byte(&aData[8+closest*4]);
4293 if( !searchList || iPage==nearby ){
danielk197789d40042008-11-17 14:20:56 +00004294 Pgno nPage;
shane1f9e6aa2008-06-09 19:27:11 +00004295 *pPgno = iPage;
danielk197789d40042008-11-17 14:20:56 +00004296 nPage = pagerPagecount(pBt);
danielk1977ad0132d2008-06-07 08:58:22 +00004297 if( *pPgno>nPage ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004298 /* Free page off the end of the file */
danielk197743e377a2008-05-05 12:09:32 +00004299 rc = SQLITE_CORRUPT_BKPT;
4300 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004301 }
4302 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
4303 ": %d more free pages\n",
4304 *pPgno, closest+1, k, pTrunk->pgno, n-1));
4305 if( closest<k-1 ){
4306 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
4307 }
4308 put4byte(&aData[4], k-1);
drhc5053fb2008-11-27 02:22:10 +00004309 assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
drh16a9b832007-05-05 18:39:25 +00004310 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004311 if( rc==SQLITE_OK ){
drh538f5702007-04-13 02:14:30 +00004312 sqlite3PagerDontRollback((*ppPage)->pDbPage);
danielk19773b8a05f2007-03-19 17:44:26 +00004313 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004314 if( rc!=SQLITE_OK ){
4315 releasePage(*ppPage);
4316 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004317 }
4318 searchList = 0;
4319 }
drhee696e22004-08-30 16:52:17 +00004320 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004321 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00004322 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004323 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00004324 }else{
drh3aac2dd2004-04-26 14:10:20 +00004325 /* There are no pages on the freelist, so create a new page at the
4326 ** end of the file */
danielk197789d40042008-11-17 14:20:56 +00004327 int nPage = pagerPagecount(pBt);
danielk1977ad0132d2008-06-07 08:58:22 +00004328 *pPgno = nPage + 1;
danielk1977afcdd022004-10-31 16:25:42 +00004329
4330#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00004331 if( pBt->nTrunc ){
4332 /* An incr-vacuum has already run within this transaction. So the
4333 ** page to allocate is not from the physical end of the file, but
4334 ** at pBt->nTrunc.
4335 */
4336 *pPgno = pBt->nTrunc+1;
4337 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
4338 (*pPgno)++;
4339 }
4340 }
danielk1977266664d2006-02-10 08:24:21 +00004341 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00004342 /* If *pPgno refers to a pointer-map page, allocate two new pages
4343 ** at the end of the file instead of one. The first allocated page
4344 ** becomes a new pointer-map page, the second is used by the caller.
4345 */
4346 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00004347 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977afcdd022004-10-31 16:25:42 +00004348 (*pPgno)++;
drh72190432008-01-31 14:54:43 +00004349 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
danielk1977afcdd022004-10-31 16:25:42 +00004350 }
danielk1977dddbcdc2007-04-26 14:42:34 +00004351 if( pBt->nTrunc ){
4352 pBt->nTrunc = *pPgno;
4353 }
danielk1977afcdd022004-10-31 16:25:42 +00004354#endif
4355
danielk1977599fcba2004-11-08 07:13:13 +00004356 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh16a9b832007-05-05 18:39:25 +00004357 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
drh3b7511c2001-05-26 13:15:44 +00004358 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00004359 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004360 if( rc!=SQLITE_OK ){
4361 releasePage(*ppPage);
4362 }
drh3a4c1412004-05-09 20:40:11 +00004363 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00004364 }
danielk1977599fcba2004-11-08 07:13:13 +00004365
4366 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00004367
4368end_allocate_page:
4369 releasePage(pTrunk);
4370 releasePage(pPrevTrunk);
danielk1977b247c212008-11-21 09:09:01 +00004371 if( rc==SQLITE_OK ){
4372 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
4373 releasePage(*ppPage);
4374 return SQLITE_CORRUPT_BKPT;
4375 }
4376 (*ppPage)->isInit = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00004377 }
drh3b7511c2001-05-26 13:15:44 +00004378 return rc;
4379}
4380
4381/*
drh3aac2dd2004-04-26 14:10:20 +00004382** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00004383**
danielk19773b8a05f2007-03-19 17:44:26 +00004384** sqlite3PagerUnref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00004385*/
drh3aac2dd2004-04-26 14:10:20 +00004386static int freePage(MemPage *pPage){
danielk1977aef0bf62005-12-30 16:28:01 +00004387 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00004388 MemPage *pPage1 = pBt->pPage1;
4389 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00004390
drh3aac2dd2004-04-26 14:10:20 +00004391 /* Prepare the page for freeing */
drh1fee73e2007-08-29 04:00:57 +00004392 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh3aac2dd2004-04-26 14:10:20 +00004393 assert( pPage->pgno>1 );
4394 pPage->isInit = 0;
drh3aac2dd2004-04-26 14:10:20 +00004395
drha34b6762004-05-07 13:30:42 +00004396 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00004397 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00004398 if( rc ) return rc;
4399 n = get4byte(&pPage1->aData[36]);
4400 put4byte(&pPage1->aData[36], n+1);
4401
drhfcce93f2006-02-22 03:08:32 +00004402#ifdef SQLITE_SECURE_DELETE
4403 /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
4404 ** always fully overwrite deleted information with zeros.
4405 */
danielk19773b8a05f2007-03-19 17:44:26 +00004406 rc = sqlite3PagerWrite(pPage->pDbPage);
drhfcce93f2006-02-22 03:08:32 +00004407 if( rc ) return rc;
4408 memset(pPage->aData, 0, pPage->pBt->pageSize);
4409#endif
4410
danielk1977687566d2004-11-02 12:56:41 +00004411 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00004412 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00004413 */
danielk197785d90ca2008-07-19 14:25:15 +00004414 if( ISAUTOVACUUM ){
danielk1977687566d2004-11-02 12:56:41 +00004415 rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
danielk1977a64a0352004-11-05 01:45:13 +00004416 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00004417 }
danielk1977687566d2004-11-02 12:56:41 +00004418
drh3aac2dd2004-04-26 14:10:20 +00004419 if( n==0 ){
4420 /* This is the first free page */
danielk19773b8a05f2007-03-19 17:44:26 +00004421 rc = sqlite3PagerWrite(pPage->pDbPage);
drhda200cc2004-05-09 11:51:38 +00004422 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004423 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00004424 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00004425 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00004426 }else{
4427 /* Other free pages already exist. Retrive the first trunk page
4428 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00004429 MemPage *pTrunk;
drh16a9b832007-05-05 18:39:25 +00004430 rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0);
drh3b7511c2001-05-26 13:15:44 +00004431 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004432 k = get4byte(&pTrunk->aData[4]);
drhee696e22004-08-30 16:52:17 +00004433 if( k>=pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00004434 /* The trunk is full. Turn the page being freed into a new
drh45b1fac2008-07-04 17:52:42 +00004435 ** trunk page with no leaves.
4436 **
4437 ** Note that the trunk page is not really full until it contains
4438 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
4439 ** coded. But due to a coding error in versions of SQLite prior to
4440 ** 3.6.0, databases with freelist trunk pages holding more than
4441 ** usableSize/4 - 8 entries will be reported as corrupt. In order
4442 ** to maintain backwards compatibility with older versions of SQLite,
4443 ** we will contain to restrict the number of entries to usableSize/4 - 8
4444 ** for now. At some point in the future (once everyone has upgraded
4445 ** to 3.6.0 or later) we should consider fixing the conditional above
4446 ** to read "usableSize/4-2" instead of "usableSize/4-8".
4447 */
danielk19773b8a05f2007-03-19 17:44:26 +00004448 rc = sqlite3PagerWrite(pPage->pDbPage);
drhb9ee4932007-09-07 14:32:06 +00004449 if( rc==SQLITE_OK ){
4450 put4byte(pPage->aData, pTrunk->pgno);
4451 put4byte(&pPage->aData[4], 0);
4452 put4byte(&pPage1->aData[32], pPage->pgno);
4453 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
4454 pPage->pgno, pTrunk->pgno));
4455 }
4456 }else if( k<0 ){
4457 rc = SQLITE_CORRUPT;
drh3aac2dd2004-04-26 14:10:20 +00004458 }else{
4459 /* Add the newly freed page as a leaf on the current trunk */
danielk19773b8a05f2007-03-19 17:44:26 +00004460 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00004461 if( rc==SQLITE_OK ){
4462 put4byte(&pTrunk->aData[4], k+1);
4463 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drhfcce93f2006-02-22 03:08:32 +00004464#ifndef SQLITE_SECURE_DELETE
danielk1977a1fa00d2008-08-27 15:16:33 +00004465 rc = sqlite3PagerDontWrite(pPage->pDbPage);
drhfcce93f2006-02-22 03:08:32 +00004466#endif
drhf5345442007-04-09 12:45:02 +00004467 }
drh3a4c1412004-05-09 20:40:11 +00004468 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00004469 }
4470 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00004471 }
drh3b7511c2001-05-26 13:15:44 +00004472 return rc;
4473}
4474
4475/*
drh3aac2dd2004-04-26 14:10:20 +00004476** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00004477*/
drh3aac2dd2004-04-26 14:10:20 +00004478static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00004479 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00004480 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00004481 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00004482 int rc;
drh94440812007-03-06 11:42:19 +00004483 int nOvfl;
4484 int ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00004485
drh1fee73e2007-08-29 04:00:57 +00004486 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh16a9b832007-05-05 18:39:25 +00004487 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004488 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00004489 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00004490 }
drh6f11bef2004-05-13 01:12:56 +00004491 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh94440812007-03-06 11:42:19 +00004492 ovflPageSize = pBt->usableSize - 4;
drh72365832007-03-06 15:53:44 +00004493 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
4494 assert( ovflPgno==0 || nOvfl>0 );
4495 while( nOvfl-- ){
drh3aac2dd2004-04-26 14:10:20 +00004496 MemPage *pOvfl;
danielk197789d40042008-11-17 14:20:56 +00004497 if( ovflPgno==0 || ovflPgno>pagerPagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00004498 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00004499 }
danielk19778c0a9592007-04-30 16:55:00 +00004500
4501 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno);
drh3b7511c2001-05-26 13:15:44 +00004502 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00004503 rc = freePage(pOvfl);
danielk19773b8a05f2007-03-19 17:44:26 +00004504 sqlite3PagerUnref(pOvfl->pDbPage);
danielk19776b456a22005-03-21 04:04:02 +00004505 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00004506 }
drh5e2f8b92001-05-28 00:41:15 +00004507 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00004508}
4509
4510/*
drh91025292004-05-03 19:49:32 +00004511** Create the byte sequence used to represent a cell on page pPage
4512** and write that byte sequence into pCell[]. Overflow pages are
4513** allocated and filled in as necessary. The calling procedure
4514** is responsible for making sure sufficient space has been allocated
4515** for pCell[].
4516**
4517** Note that pCell does not necessary need to point to the pPage->aData
4518** area. pCell might point to some temporary storage. The cell will
4519** be constructed in this temporary area then copied into pPage->aData
4520** later.
drh3b7511c2001-05-26 13:15:44 +00004521*/
4522static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00004523 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00004524 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00004525 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00004526 const void *pData,int nData, /* The data */
drhb026e052007-05-02 01:34:31 +00004527 int nZero, /* Extra zero bytes to append to pData */
drh4b70f112004-05-02 21:12:19 +00004528 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00004529){
drh3b7511c2001-05-26 13:15:44 +00004530 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00004531 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00004532 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00004533 int spaceLeft;
4534 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00004535 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00004536 unsigned char *pPrior;
4537 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00004538 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00004539 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00004540 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00004541 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00004542
drh1fee73e2007-08-29 04:00:57 +00004543 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00004544
drhc5053fb2008-11-27 02:22:10 +00004545 /* pPage is not necessarily writeable since pCell might be auxiliary
4546 ** buffer space that is separate from the pPage buffer area */
4547 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
4548 || sqlite3PagerIswriteable(pPage->pDbPage) );
4549
drh91025292004-05-03 19:49:32 +00004550 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00004551 nHeader = 0;
drh91025292004-05-03 19:49:32 +00004552 if( !pPage->leaf ){
4553 nHeader += 4;
4554 }
drh8b18dd42004-05-12 19:18:15 +00004555 if( pPage->hasData ){
drhb026e052007-05-02 01:34:31 +00004556 nHeader += putVarint(&pCell[nHeader], nData+nZero);
drh6f11bef2004-05-13 01:12:56 +00004557 }else{
drhb026e052007-05-02 01:34:31 +00004558 nData = nZero = 0;
drh91025292004-05-03 19:49:32 +00004559 }
drh6f11bef2004-05-13 01:12:56 +00004560 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh16a9b832007-05-05 18:39:25 +00004561 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004562 assert( info.nHeader==nHeader );
4563 assert( info.nKey==nKey );
danielk197789d40042008-11-17 14:20:56 +00004564 assert( info.nData==(u32)(nData+nZero) );
drh6f11bef2004-05-13 01:12:56 +00004565
4566 /* Fill in the payload */
drhb026e052007-05-02 01:34:31 +00004567 nPayload = nData + nZero;
drh3aac2dd2004-04-26 14:10:20 +00004568 if( pPage->intKey ){
4569 pSrc = pData;
4570 nSrc = nData;
drh91025292004-05-03 19:49:32 +00004571 nData = 0;
drhf49661a2008-12-10 16:45:50 +00004572 }else{
4573 /* TBD: Perhaps raise SQLITE_CORRUPT if nKey is larger than 31 bits? */
4574 nPayload += (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00004575 pSrc = pKey;
drhf49661a2008-12-10 16:45:50 +00004576 nSrc = (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00004577 }
drh6f11bef2004-05-13 01:12:56 +00004578 *pnSize = info.nSize;
4579 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00004580 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00004581 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00004582
drh3b7511c2001-05-26 13:15:44 +00004583 while( nPayload>0 ){
4584 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00004585#ifndef SQLITE_OMIT_AUTOVACUUM
4586 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00004587 if( pBt->autoVacuum ){
4588 do{
4589 pgnoOvfl++;
4590 } while(
4591 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
4592 );
danielk1977b39f70b2007-05-17 18:28:11 +00004593 }
danielk1977afcdd022004-10-31 16:25:42 +00004594#endif
drhf49661a2008-12-10 16:45:50 +00004595 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00004596#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00004597 /* If the database supports auto-vacuum, and the second or subsequent
4598 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00004599 ** for that page now.
4600 **
4601 ** If this is the first overflow page, then write a partial entry
4602 ** to the pointer-map. If we write nothing to this pointer-map slot,
4603 ** then the optimistic overflow chain processing in clearCell()
4604 ** may misinterpret the uninitialised values and delete the
4605 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00004606 */
danielk19774ef24492007-05-23 09:52:41 +00004607 if( pBt->autoVacuum && rc==SQLITE_OK ){
4608 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
4609 rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
danielk197789a4be82007-05-23 13:34:32 +00004610 if( rc ){
4611 releasePage(pOvfl);
4612 }
danielk1977afcdd022004-10-31 16:25:42 +00004613 }
4614#endif
drh3b7511c2001-05-26 13:15:44 +00004615 if( rc ){
drh9b171272004-05-08 02:03:22 +00004616 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00004617 return rc;
4618 }
drhc5053fb2008-11-27 02:22:10 +00004619
4620 /* If pToRelease is not zero than pPrior points into the data area
4621 ** of pToRelease. Make sure pToRelease is still writeable. */
4622 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
4623
4624 /* If pPrior is part of the data area of pPage, then make sure pPage
4625 ** is still writeable */
4626 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
4627 || sqlite3PagerIswriteable(pPage->pDbPage) );
4628
drh3aac2dd2004-04-26 14:10:20 +00004629 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00004630 releasePage(pToRelease);
4631 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00004632 pPrior = pOvfl->aData;
4633 put4byte(pPrior, 0);
4634 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00004635 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00004636 }
4637 n = nPayload;
4638 if( n>spaceLeft ) n = spaceLeft;
drhc5053fb2008-11-27 02:22:10 +00004639
4640 /* If pToRelease is not zero than pPayload points into the data area
4641 ** of pToRelease. Make sure pToRelease is still writeable. */
4642 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
4643
4644 /* If pPayload is part of the data area of pPage, then make sure pPage
4645 ** is still writeable */
4646 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
4647 || sqlite3PagerIswriteable(pPage->pDbPage) );
4648
drhb026e052007-05-02 01:34:31 +00004649 if( nSrc>0 ){
4650 if( n>nSrc ) n = nSrc;
4651 assert( pSrc );
4652 memcpy(pPayload, pSrc, n);
4653 }else{
4654 memset(pPayload, 0, n);
4655 }
drh3b7511c2001-05-26 13:15:44 +00004656 nPayload -= n;
drhde647132004-05-07 17:57:49 +00004657 pPayload += n;
drh9b171272004-05-08 02:03:22 +00004658 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00004659 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00004660 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00004661 if( nSrc==0 ){
4662 nSrc = nData;
4663 pSrc = pData;
4664 }
drhdd793422001-06-28 01:54:48 +00004665 }
drh9b171272004-05-08 02:03:22 +00004666 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00004667 return SQLITE_OK;
4668}
4669
drh14acc042001-06-10 19:56:58 +00004670/*
4671** Remove the i-th cell from pPage. This routine effects pPage only.
4672** The cell content is not freed or deallocated. It is assumed that
4673** the cell content has been copied someplace else. This routine just
4674** removes the reference to the cell from pPage.
4675**
4676** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00004677*/
shane0af3f892008-11-12 04:55:34 +00004678static int dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00004679 int i; /* Loop counter */
4680 int pc; /* Offset to cell content of cell being deleted */
4681 u8 *data; /* pPage->aData */
4682 u8 *ptr; /* Used to move bytes around within data[] */
shanedcc50b72008-11-13 18:29:50 +00004683 int rc; /* The return code */
drh43605152004-05-29 21:46:49 +00004684
drh8c42ca92001-06-22 19:15:00 +00004685 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00004686 assert( sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00004687 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00004688 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00004689 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00004690 ptr = &data[pPage->cellOffset + 2*idx];
shane0af3f892008-11-12 04:55:34 +00004691 pc = get2byte(ptr);
drhc5053fb2008-11-27 02:22:10 +00004692 if( (pc<pPage->hdrOffset+6+(pPage->leaf?0:4))
4693 || (pc+sz>pPage->pBt->usableSize) ){
shane0af3f892008-11-12 04:55:34 +00004694 return SQLITE_CORRUPT_BKPT;
4695 }
shanedcc50b72008-11-13 18:29:50 +00004696 rc = freeSpace(pPage, pc, sz);
4697 if( rc!=SQLITE_OK ){
4698 return rc;
4699 }
drh43605152004-05-29 21:46:49 +00004700 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
4701 ptr[0] = ptr[2];
4702 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00004703 }
4704 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00004705 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
4706 pPage->nFree += 2;
shane0af3f892008-11-12 04:55:34 +00004707 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004708}
4709
4710/*
4711** Insert a new cell on pPage at cell index "i". pCell points to the
4712** content of the cell.
4713**
4714** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00004715** will not fit, then make a copy of the cell content into pTemp if
4716** pTemp is not null. Regardless of pTemp, allocate a new entry
4717** in pPage->aOvfl[] and make it point to the cell content (either
4718** in pTemp or the original pCell) and also record its index.
4719** Allocating a new entry in pPage->aCell[] implies that
4720** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00004721**
4722** If nSkip is non-zero, then do not copy the first nSkip bytes of the
4723** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00004724** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00004725** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00004726*/
danielk1977e80463b2004-11-03 03:01:16 +00004727static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00004728 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00004729 int i, /* New cell becomes the i-th cell of the page */
4730 u8 *pCell, /* Content of the new cell */
4731 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00004732 u8 *pTemp, /* Temp storage space for pCell, if needed */
4733 u8 nSkip /* Do not write the first nSkip bytes of the cell */
drh24cd67e2004-05-10 16:18:47 +00004734){
drh43605152004-05-29 21:46:49 +00004735 int idx; /* Where to write new cell content in data[] */
4736 int j; /* Loop counter */
4737 int top; /* First byte of content for any cell in data[] */
4738 int end; /* First byte past the last cell pointer in data[] */
4739 int ins; /* Index in data[] where new cell pointer is inserted */
4740 int hdr; /* Offset into data[] of the page header */
4741 int cellOffset; /* Address of first cell pointer in data[] */
4742 u8 *data; /* The content of the whole page */
4743 u8 *ptr; /* Used for moving information around in data[] */
4744
4745 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
drhf49661a2008-12-10 16:45:50 +00004746 assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
4747 assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
drh43605152004-05-29 21:46:49 +00004748 assert( sz==cellSizePtr(pPage, pCell) );
drh1fee73e2007-08-29 04:00:57 +00004749 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +00004750 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00004751 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00004752 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004753 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00004754 }
drh43605152004-05-29 21:46:49 +00004755 j = pPage->nOverflow++;
danielk197789d40042008-11-17 14:20:56 +00004756 assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
drh43605152004-05-29 21:46:49 +00004757 pPage->aOvfl[j].pCell = pCell;
drhf49661a2008-12-10 16:45:50 +00004758 pPage->aOvfl[j].idx = (u16)i;
drh43605152004-05-29 21:46:49 +00004759 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00004760 }else{
danielk19776e465eb2007-08-21 13:11:00 +00004761 int rc = sqlite3PagerWrite(pPage->pDbPage);
4762 if( rc!=SQLITE_OK ){
4763 return rc;
4764 }
4765 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00004766 data = pPage->aData;
4767 hdr = pPage->hdrOffset;
4768 top = get2byte(&data[hdr+5]);
4769 cellOffset = pPage->cellOffset;
4770 end = cellOffset + 2*pPage->nCell + 2;
4771 ins = cellOffset + 2*i;
4772 if( end > top - sz ){
shane0af3f892008-11-12 04:55:34 +00004773 rc = defragmentPage(pPage);
4774 if( rc!=SQLITE_OK ){
4775 return rc;
4776 }
drh43605152004-05-29 21:46:49 +00004777 top = get2byte(&data[hdr+5]);
4778 assert( end + sz <= top );
4779 }
4780 idx = allocateSpace(pPage, sz);
4781 assert( idx>0 );
4782 assert( end <= get2byte(&data[hdr+5]) );
shane0af3f892008-11-12 04:55:34 +00004783 if (idx+sz > pPage->pBt->usableSize) {
shane34ac18d2008-11-11 22:18:20 +00004784 return SQLITE_CORRUPT_BKPT;
shane0af3f892008-11-12 04:55:34 +00004785 }
drh43605152004-05-29 21:46:49 +00004786 pPage->nCell++;
4787 pPage->nFree -= 2;
danielk1977a3ad5e72005-01-07 08:56:44 +00004788 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004789 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
4790 ptr[0] = ptr[-2];
4791 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00004792 }
drh43605152004-05-29 21:46:49 +00004793 put2byte(&data[ins], idx);
4794 put2byte(&data[hdr+3], pPage->nCell);
danielk1977a19df672004-11-03 11:37:07 +00004795#ifndef SQLITE_OMIT_AUTOVACUUM
4796 if( pPage->pBt->autoVacuum ){
4797 /* The cell may contain a pointer to an overflow page. If so, write
4798 ** the entry for the overflow page into the pointer map.
4799 */
4800 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00004801 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh72365832007-03-06 15:53:44 +00004802 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk1977a19df672004-11-03 11:37:07 +00004803 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
4804 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
danielk19776e465eb2007-08-21 13:11:00 +00004805 rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
danielk1977a19df672004-11-03 11:37:07 +00004806 if( rc!=SQLITE_OK ) return rc;
4807 }
4808 }
4809#endif
drh14acc042001-06-10 19:56:58 +00004810 }
danielk1977e80463b2004-11-03 03:01:16 +00004811
danielk1977e80463b2004-11-03 03:01:16 +00004812 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004813}
4814
4815/*
drhfa1a98a2004-05-14 19:08:17 +00004816** Add a list of cells to a page. The page should be initially empty.
4817** The cells are guaranteed to fit on the page.
4818*/
4819static void assemblePage(
4820 MemPage *pPage, /* The page to be assemblied */
4821 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00004822 u8 **apCell, /* Pointers to cell bodies */
drha9121e42008-02-19 14:59:35 +00004823 u16 *aSize /* Sizes of the cells */
drhfa1a98a2004-05-14 19:08:17 +00004824){
4825 int i; /* Loop counter */
4826 int totalSize; /* Total size of all cells */
4827 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00004828 int cellptr; /* Address of next cell pointer */
4829 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00004830 u8 *data; /* Data for the page */
4831
drh43605152004-05-29 21:46:49 +00004832 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00004833 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00004834 assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
drhfa1a98a2004-05-14 19:08:17 +00004835 totalSize = 0;
4836 for(i=0; i<nCell; i++){
4837 totalSize += aSize[i];
4838 }
drh43605152004-05-29 21:46:49 +00004839 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00004840 assert( pPage->nCell==0 );
drhc5053fb2008-11-27 02:22:10 +00004841 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00004842 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00004843 data = pPage->aData;
4844 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00004845 put2byte(&data[hdr+3], nCell);
drh09d0deb2005-08-02 17:13:09 +00004846 if( nCell ){
4847 cellbody = allocateSpace(pPage, totalSize);
4848 assert( cellbody>0 );
4849 assert( pPage->nFree >= 2*nCell );
4850 pPage->nFree -= 2*nCell;
4851 for(i=0; i<nCell; i++){
4852 put2byte(&data[cellptr], cellbody);
4853 memcpy(&data[cellbody], apCell[i], aSize[i]);
4854 cellptr += 2;
4855 cellbody += aSize[i];
4856 }
4857 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00004858 }
drhf49661a2008-12-10 16:45:50 +00004859 pPage->nCell = (u16)nCell;
drhfa1a98a2004-05-14 19:08:17 +00004860}
4861
drh14acc042001-06-10 19:56:58 +00004862/*
drhc3b70572003-01-04 19:44:07 +00004863** The following parameters determine how many adjacent pages get involved
4864** in a balancing operation. NN is the number of neighbors on either side
4865** of the page that participate in the balancing operation. NB is the
4866** total number of pages that participate, including the target page and
4867** NN neighbors on either side.
4868**
4869** The minimum value of NN is 1 (of course). Increasing NN above 1
4870** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
4871** in exchange for a larger degradation in INSERT and UPDATE performance.
4872** The value of NN appears to give the best results overall.
4873*/
4874#define NN 1 /* Number of neighbors on either side of pPage */
4875#define NB (NN*2+1) /* Total pages involved in the balance */
4876
drh43605152004-05-29 21:46:49 +00004877/* Forward reference */
danielk197771d5d2c2008-09-29 11:49:47 +00004878static int balance(BtCursor*, int);
danielk1977ac245ec2005-01-14 13:50:11 +00004879
drh615ae552005-01-16 23:21:00 +00004880#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004881/*
4882** This version of balance() handles the common special case where
4883** a new entry is being inserted on the extreme right-end of the
4884** tree, in other words, when the new entry will become the largest
4885** entry in the tree.
4886**
4887** Instead of trying balance the 3 right-most leaf pages, just add
4888** a new page to the right-hand side and put the one new entry in
4889** that page. This leaves the right side of the tree somewhat
4890** unbalanced. But odds are that we will be inserting new entries
4891** at the end soon afterwards so the nearly empty page will quickly
4892** fill up. On average.
4893**
4894** pPage is the leaf page which is the right-most page in the tree.
4895** pParent is its parent. pPage must have a single overflow entry
4896** which is also the right-most entry on the page.
4897*/
danielk197771d5d2c2008-09-29 11:49:47 +00004898static int balance_quick(BtCursor *pCur){
danielk1977ac245ec2005-01-14 13:50:11 +00004899 int rc;
danielk1977eaa06f62008-09-18 17:34:44 +00004900 MemPage *pNew = 0;
danielk1977ac245ec2005-01-14 13:50:11 +00004901 Pgno pgnoNew;
4902 u8 *pCell;
drha9121e42008-02-19 14:59:35 +00004903 u16 szCell;
danielk1977ac245ec2005-01-14 13:50:11 +00004904 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00004905 MemPage *pPage = pCur->apPage[pCur->iPage];
4906 MemPage *pParent = pCur->apPage[pCur->iPage-1];
danielk1977aef0bf62005-12-30 16:28:01 +00004907 BtShared *pBt = pPage->pBt;
danielk197779a40da2005-01-16 08:00:01 +00004908 int parentIdx = pParent->nCell; /* pParent new divider cell index */
4909 int parentSize; /* Size of new divider cell */
4910 u8 parentCell[64]; /* Space for the new divider cell */
danielk1977ac245ec2005-01-14 13:50:11 +00004911
drh1fee73e2007-08-29 04:00:57 +00004912 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00004913
danielk1977ac245ec2005-01-14 13:50:11 +00004914 /* Allocate a new page. Insert the overflow cell from pPage
4915 ** into it. Then remove the overflow cell from pPage.
4916 */
drh4f0c5872007-03-26 22:05:01 +00004917 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk1977eaa06f62008-09-18 17:34:44 +00004918 if( rc==SQLITE_OK ){
4919 pCell = pPage->aOvfl[0].pCell;
4920 szCell = cellSizePtr(pPage, pCell);
drhc5053fb2008-11-27 02:22:10 +00004921 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
danielk1977eaa06f62008-09-18 17:34:44 +00004922 zeroPage(pNew, pPage->aData[0]);
4923 assemblePage(pNew, 1, &pCell, &szCell);
4924 pPage->nOverflow = 0;
4925
danielk1977eaa06f62008-09-18 17:34:44 +00004926 /* pPage is currently the right-child of pParent. Change this
4927 ** so that the right-child is the new page allocated above and
4928 ** pPage is the next-to-right child.
4929 **
4930 ** Ignore the return value of the call to fillInCell(). fillInCell()
4931 ** may only return other than SQLITE_OK if it is required to allocate
4932 ** one or more overflow pages. Since an internal table B-Tree cell
4933 ** may never spill over onto an overflow page (it is a maximum of
4934 ** 13 bytes in size), it is not neccessary to check the return code.
4935 **
4936 ** Similarly, the insertCell() function cannot fail if the page
4937 ** being inserted into is already writable and the cell does not
4938 ** contain an overflow pointer. So ignore this return code too.
4939 */
4940 assert( pPage->nCell>0 );
4941 pCell = findCell(pPage, pPage->nCell-1);
4942 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
4943 fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
4944 assert( parentSize<64 );
4945 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
4946 insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
4947 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
4948 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
4949
4950 /* If this is an auto-vacuum database, update the pointer map
4951 ** with entries for the new page, and any pointer from the
4952 ** cell on the page to an overflow page.
4953 */
4954 if( ISAUTOVACUUM ){
4955 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
4956 if( rc==SQLITE_OK ){
4957 rc = ptrmapPutOvfl(pNew, 0);
4958 }
danielk1977ac11ee62005-01-15 12:45:51 +00004959 }
danielk1977e08a3c42008-09-18 18:17:03 +00004960
4961 /* Release the reference to the new page. */
4962 releasePage(pNew);
danielk1977ac11ee62005-01-15 12:45:51 +00004963 }
4964
danielk1977eaa06f62008-09-18 17:34:44 +00004965 /* At this point the pPage->nFree variable is not set correctly with
4966 ** respect to the content of the page (because it was set to 0 by
4967 ** insertCell). So call sqlite3BtreeInitPage() to make sure it is
4968 ** correct.
4969 **
4970 ** This has to be done even if an error will be returned. Normally, if
4971 ** an error occurs during tree balancing, the contents of MemPage are
4972 ** not important, as they will be recalculated when the page is rolled
4973 ** back. But here, in balance_quick(), it is possible that pPage has
4974 ** not yet been marked dirty or written into the journal file. Therefore
4975 ** it will not be rolled back and so it is important to make sure that
4976 ** the page data and contents of MemPage are consistent.
4977 */
4978 pPage->isInit = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004979 sqlite3BtreeInitPage(pPage);
danielk1977eaa06f62008-09-18 17:34:44 +00004980
danielk1977e08a3c42008-09-18 18:17:03 +00004981 /* If everything else succeeded, balance the parent page, in
4982 ** case the divider cell inserted caused it to become overfull.
danielk197779a40da2005-01-16 08:00:01 +00004983 */
danielk1977eaa06f62008-09-18 17:34:44 +00004984 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00004985 releasePage(pPage);
4986 pCur->iPage--;
4987 rc = balance(pCur, 0);
danielk1977eaa06f62008-09-18 17:34:44 +00004988 }
4989 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004990}
drh615ae552005-01-16 23:21:00 +00004991#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00004992
drhc3b70572003-01-04 19:44:07 +00004993/*
drhab01f612004-05-22 02:55:23 +00004994** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00004995** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00004996** Usually NN siblings on either side of pPage is used in the balancing,
4997** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00004998** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00004999** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00005000** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00005001**
drh0c6cc4e2004-06-15 02:13:26 +00005002** The number of siblings of pPage might be increased or decreased by one or
5003** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00005004** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00005005** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00005006** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00005007** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00005008**
drh8b2f49b2001-06-08 00:21:52 +00005009** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00005010** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00005011** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00005012** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00005013**
drh8c42ca92001-06-22 19:15:00 +00005014** In the course of balancing the siblings of pPage, the parent of pPage
5015** might become overfull or underfull. If that happens, then this routine
5016** is called recursively on the parent.
5017**
drh5e00f6c2001-09-13 13:46:56 +00005018** If this routine fails for any reason, it might leave the database
5019** in a corrupted state. So if this routine fails, the database should
5020** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00005021*/
danielk197771d5d2c2008-09-29 11:49:47 +00005022static int balance_nonroot(BtCursor *pCur){
5023 MemPage *pPage; /* The over or underfull page to balance */
drh8b2f49b2001-06-08 00:21:52 +00005024 MemPage *pParent; /* The parent of pPage */
drh16a9b832007-05-05 18:39:25 +00005025 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00005026 int nCell = 0; /* Number of cells in apCell[] */
5027 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
drh8b2f49b2001-06-08 00:21:52 +00005028 int nOld; /* Number of pages in apOld[] */
5029 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00005030 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00005031 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00005032 int idx; /* Index of pPage in pParent->aCell[] */
5033 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00005034 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00005035 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00005036 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00005037 int usableSpace; /* Bytes in pPage beyond the header */
5038 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00005039 int subtotal; /* Subtotal of bytes in cells on one page */
drhe5ae5732008-06-15 02:51:47 +00005040 int iSpace1 = 0; /* First unused byte of aSpace1[] */
5041 int iSpace2 = 0; /* First unused byte of aSpace2[] */
drhfacf0302008-06-17 15:12:00 +00005042 int szScratch; /* Size of scratch memory requested */
drhc3b70572003-01-04 19:44:07 +00005043 MemPage *apOld[NB]; /* pPage and up to two siblings */
5044 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00005045 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00005046 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
5047 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drh4b70f112004-05-02 21:12:19 +00005048 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00005049 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
5050 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00005051 u8 **apCell = 0; /* All cells begin balanced */
drha9121e42008-02-19 14:59:35 +00005052 u16 *szCell; /* Local size of all cells in apCell[] */
drhe5ae5732008-06-15 02:51:47 +00005053 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
5054 u8 *aSpace1; /* Space for copies of dividers cells before balance */
5055 u8 *aSpace2 = 0; /* Space for overflow dividers cells after balance */
danielk1977ac11ee62005-01-15 12:45:51 +00005056 u8 *aFrom = 0;
drh8b2f49b2001-06-08 00:21:52 +00005057
danielk197771d5d2c2008-09-29 11:49:47 +00005058 pPage = pCur->apPage[pCur->iPage];
drh1fee73e2007-08-29 04:00:57 +00005059 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf94a1732008-09-30 17:18:17 +00005060 VVA_ONLY( pCur->pagesShuffled = 1 );
drhd677b3d2007-08-20 22:48:41 +00005061
drh14acc042001-06-10 19:56:58 +00005062 /*
drh43605152004-05-29 21:46:49 +00005063 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00005064 */
danielk197771d5d2c2008-09-29 11:49:47 +00005065 assert( pCur->iPage>0 );
5066 assert( pPage->isInit );
danielk19776e465eb2007-08-21 13:11:00 +00005067 assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 );
drh4b70f112004-05-02 21:12:19 +00005068 pBt = pPage->pBt;
danielk197771d5d2c2008-09-29 11:49:47 +00005069 pParent = pCur->apPage[pCur->iPage-1];
drh43605152004-05-29 21:46:49 +00005070 assert( pParent );
danielk19773b8a05f2007-03-19 17:44:26 +00005071 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
danielk197707cb5602006-01-20 10:55:05 +00005072 return rc;
5073 }
danielk1977474b7cc2008-07-09 11:49:46 +00005074
drh43605152004-05-29 21:46:49 +00005075 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00005076
drh615ae552005-01-16 23:21:00 +00005077#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00005078 /*
5079 ** A special case: If a new entry has just been inserted into a
5080 ** table (that is, a btree with integer keys and all data at the leaves)
drh09d0deb2005-08-02 17:13:09 +00005081 ** and the new entry is the right-most entry in the tree (it has the
drhf222e712005-01-14 22:55:49 +00005082 ** largest key) then use the special balance_quick() routine for
5083 ** balancing. balance_quick() is much faster and results in a tighter
5084 ** packing of data in the common case.
5085 */
danielk1977ac245ec2005-01-14 13:50:11 +00005086 if( pPage->leaf &&
5087 pPage->intKey &&
danielk1977ac245ec2005-01-14 13:50:11 +00005088 pPage->nOverflow==1 &&
5089 pPage->aOvfl[0].idx==pPage->nCell &&
danielk197771d5d2c2008-09-29 11:49:47 +00005090 pParent->pgno!=1 &&
danielk1977ac245ec2005-01-14 13:50:11 +00005091 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
5092 ){
drh44845222008-07-17 18:39:57 +00005093 assert( pPage->intKey );
danielk1977ac11ee62005-01-15 12:45:51 +00005094 /*
5095 ** TODO: Check the siblings to the left of pPage. It may be that
5096 ** they are not full and no new page is required.
5097 */
danielk197771d5d2c2008-09-29 11:49:47 +00005098 return balance_quick(pCur);
danielk1977ac245ec2005-01-14 13:50:11 +00005099 }
5100#endif
5101
danielk19776e465eb2007-08-21 13:11:00 +00005102 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){
5103 return rc;
5104 }
5105
drh2e38c322004-09-03 18:38:44 +00005106 /*
drh4b70f112004-05-02 21:12:19 +00005107 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00005108 ** to pPage. The "idx" variable is the index of that cell. If pPage
5109 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00005110 */
danielk1977bf93c562008-09-29 15:53:25 +00005111 idx = pCur->aiIdx[pCur->iPage-1];
5112 assertParentIndex(pParent, idx, pPage->pgno);
drh8b2f49b2001-06-08 00:21:52 +00005113
5114 /*
drh14acc042001-06-10 19:56:58 +00005115 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00005116 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00005117 */
drh14acc042001-06-10 19:56:58 +00005118 nOld = nNew = 0;
drh14acc042001-06-10 19:56:58 +00005119
5120 /*
drh4b70f112004-05-02 21:12:19 +00005121 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00005122 ** the siblings. An attempt is made to find NN siblings on either
5123 ** side of pPage. More siblings are taken from one side, however, if
5124 ** pPage there are fewer than NN siblings on the other side. If pParent
5125 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00005126 */
drhc3b70572003-01-04 19:44:07 +00005127 nxDiv = idx - NN;
5128 if( nxDiv + NB > pParent->nCell ){
5129 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00005130 }
drhc3b70572003-01-04 19:44:07 +00005131 if( nxDiv<0 ){
5132 nxDiv = 0;
5133 }
drh8b2f49b2001-06-08 00:21:52 +00005134 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00005135 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00005136 if( k<pParent->nCell ){
danielk19771cc5ed82007-05-16 17:28:43 +00005137 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00005138 nDiv++;
drha34b6762004-05-07 13:30:42 +00005139 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00005140 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00005141 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00005142 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00005143 }else{
5144 break;
drh8b2f49b2001-06-08 00:21:52 +00005145 }
danielk197771d5d2c2008-09-29 11:49:47 +00005146 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i]);
drh6019e162001-07-02 17:51:45 +00005147 if( rc ) goto balance_cleanup;
danielk197771d5d2c2008-09-29 11:49:47 +00005148 /* apOld[i]->idxParent = k; */
drh91025292004-05-03 19:49:32 +00005149 apCopy[i] = 0;
5150 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00005151 nOld++;
danielk1977634f2982005-03-28 08:44:07 +00005152 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
drh8b2f49b2001-06-08 00:21:52 +00005153 }
5154
drha9121e42008-02-19 14:59:35 +00005155 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00005156 ** alignment */
drha9121e42008-02-19 14:59:35 +00005157 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00005158
drh8b2f49b2001-06-08 00:21:52 +00005159 /*
danielk1977634f2982005-03-28 08:44:07 +00005160 ** Allocate space for memory structures
5161 */
drhfacf0302008-06-17 15:12:00 +00005162 szScratch =
drha9121e42008-02-19 14:59:35 +00005163 nMaxCells*sizeof(u8*) /* apCell */
5164 + nMaxCells*sizeof(u16) /* szCell */
5165 + (ROUND8(sizeof(MemPage))+pBt->pageSize)*NB /* aCopy */
drhe5ae5732008-06-15 02:51:47 +00005166 + pBt->pageSize /* aSpace1 */
drhfacf0302008-06-17 15:12:00 +00005167 + (ISAUTOVACUUM ? nMaxCells : 0); /* aFrom */
5168 apCell = sqlite3ScratchMalloc( szScratch );
danielk1977634f2982005-03-28 08:44:07 +00005169 if( apCell==0 ){
5170 rc = SQLITE_NOMEM;
5171 goto balance_cleanup;
5172 }
drha9121e42008-02-19 14:59:35 +00005173 szCell = (u16*)&apCell[nMaxCells];
danielk1977634f2982005-03-28 08:44:07 +00005174 aCopy[0] = (u8*)&szCell[nMaxCells];
drh66e80082008-12-16 13:46:29 +00005175 assert( ((aCopy[0] - (u8*)0) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00005176 for(i=1; i<NB; i++){
drhc96d8532005-05-03 12:30:33 +00005177 aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
drh66e80082008-12-16 13:46:29 +00005178 assert( ((aCopy[i] - (u8*)0) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00005179 }
drhe5ae5732008-06-15 02:51:47 +00005180 aSpace1 = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
drh66e80082008-12-16 13:46:29 +00005181 assert( ((aSpace1 - (u8*)0) & 7)==0 ); /* 8-byte alignment required */
danielk197785d90ca2008-07-19 14:25:15 +00005182 if( ISAUTOVACUUM ){
drhe5ae5732008-06-15 02:51:47 +00005183 aFrom = &aSpace1[pBt->pageSize];
danielk1977634f2982005-03-28 08:44:07 +00005184 }
drhfacf0302008-06-17 15:12:00 +00005185 aSpace2 = sqlite3PageMalloc(pBt->pageSize);
drhe5ae5732008-06-15 02:51:47 +00005186 if( aSpace2==0 ){
5187 rc = SQLITE_NOMEM;
5188 goto balance_cleanup;
5189 }
danielk1977634f2982005-03-28 08:44:07 +00005190
5191 /*
drh14acc042001-06-10 19:56:58 +00005192 ** Make copies of the content of pPage and its siblings into aOld[].
5193 ** The rest of this function will use data from the copies rather
5194 ** that the original pages since the original pages will be in the
5195 ** process of being overwritten.
5196 */
5197 for(i=0; i<nOld; i++){
drhbf4bca52007-09-06 22:19:14 +00005198 MemPage *p = apCopy[i] = (MemPage*)aCopy[i];
5199 memcpy(p, apOld[i], sizeof(MemPage));
5200 p->aData = (void*)&p[1];
5201 memcpy(p->aData, apOld[i]->aData, pBt->pageSize);
drh14acc042001-06-10 19:56:58 +00005202 }
5203
5204 /*
5205 ** Load pointers to all cells on sibling pages and the divider cells
5206 ** into the local apCell[] array. Make copies of the divider cells
drhe5ae5732008-06-15 02:51:47 +00005207 ** into space obtained form aSpace1[] and remove the the divider Cells
drhb6f41482004-05-14 01:58:11 +00005208 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00005209 **
5210 ** If the siblings are on leaf pages, then the child pointers of the
5211 ** divider cells are stripped from the cells before they are copied
drhe5ae5732008-06-15 02:51:47 +00005212 ** into aSpace1[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00005213 ** child pointers. If siblings are not leaves, then all cell in
5214 ** apCell[] include child pointers. Either way, all cells in apCell[]
5215 ** are alike.
drh96f5b762004-05-16 16:24:36 +00005216 **
5217 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
5218 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00005219 */
5220 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00005221 leafCorrection = pPage->leaf*4;
drh44845222008-07-17 18:39:57 +00005222 leafData = pPage->hasData;
drh8b2f49b2001-06-08 00:21:52 +00005223 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00005224 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00005225 int limit = pOld->nCell+pOld->nOverflow;
5226 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00005227 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00005228 apCell[nCell] = findOverflowCell(pOld, j);
5229 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk197785d90ca2008-07-19 14:25:15 +00005230 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005231 int a;
drhf49661a2008-12-10 16:45:50 +00005232 aFrom[nCell] = (u8)i; assert( i>=0 && i<6 );
danielk1977ac11ee62005-01-15 12:45:51 +00005233 for(a=0; a<pOld->nOverflow; a++){
5234 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
5235 aFrom[nCell] = 0xFF;
5236 break;
5237 }
5238 }
5239 }
drh14acc042001-06-10 19:56:58 +00005240 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00005241 }
5242 if( i<nOld-1 ){
drha9121e42008-02-19 14:59:35 +00005243 u16 sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00005244 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00005245 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
5246 ** are duplicates of keys on the child pages. We need to remove
5247 ** the divider cells from pParent, but the dividers cells are not
5248 ** added to apCell[] because they are duplicates of child cells.
5249 */
drh8b18dd42004-05-12 19:18:15 +00005250 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00005251 }else{
drhb6f41482004-05-14 01:58:11 +00005252 u8 *pTemp;
danielk1977634f2982005-03-28 08:44:07 +00005253 assert( nCell<nMaxCells );
drhb6f41482004-05-14 01:58:11 +00005254 szCell[nCell] = sz;
drhe5ae5732008-06-15 02:51:47 +00005255 pTemp = &aSpace1[iSpace1];
5256 iSpace1 += sz;
5257 assert( sz<=pBt->pageSize/4 );
5258 assert( iSpace1<=pBt->pageSize );
drhb6f41482004-05-14 01:58:11 +00005259 memcpy(pTemp, apDiv[i], sz);
5260 apCell[nCell] = pTemp+leafCorrection;
danielk197785d90ca2008-07-19 14:25:15 +00005261 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005262 aFrom[nCell] = 0xFF;
5263 }
drhb6f41482004-05-14 01:58:11 +00005264 dropCell(pParent, nxDiv, sz);
drhf49661a2008-12-10 16:45:50 +00005265 assert( leafCorrection==0 || leafCorrection==4 );
5266 szCell[nCell] -= (u16)leafCorrection;
drh43605152004-05-29 21:46:49 +00005267 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00005268 if( !pOld->leaf ){
5269 assert( leafCorrection==0 );
5270 /* The right pointer of the child page pOld becomes the left
5271 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00005272 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00005273 }else{
5274 assert( leafCorrection==4 );
danielk197739c96042007-05-12 10:41:47 +00005275 if( szCell[nCell]<4 ){
5276 /* Do not allow any cells smaller than 4 bytes. */
5277 szCell[nCell] = 4;
5278 }
drh8b18dd42004-05-12 19:18:15 +00005279 }
5280 nCell++;
drh4b70f112004-05-02 21:12:19 +00005281 }
drh8b2f49b2001-06-08 00:21:52 +00005282 }
5283 }
5284
5285 /*
drh6019e162001-07-02 17:51:45 +00005286 ** Figure out the number of pages needed to hold all nCell cells.
5287 ** Store this number in "k". Also compute szNew[] which is the total
5288 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00005289 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00005290 ** cntNew[k] should equal nCell.
5291 **
drh96f5b762004-05-16 16:24:36 +00005292 ** Values computed by this block:
5293 **
5294 ** k: The total number of sibling pages
5295 ** szNew[i]: Spaced used on the i-th sibling page.
5296 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
5297 ** the right of the i-th sibling page.
5298 ** usableSpace: Number of bytes of space available on each sibling.
5299 **
drh8b2f49b2001-06-08 00:21:52 +00005300 */
drh43605152004-05-29 21:46:49 +00005301 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00005302 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00005303 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00005304 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00005305 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00005306 szNew[k] = subtotal - szCell[i];
5307 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00005308 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00005309 subtotal = 0;
5310 k++;
5311 }
5312 }
5313 szNew[k] = subtotal;
5314 cntNew[k] = nCell;
5315 k++;
drh96f5b762004-05-16 16:24:36 +00005316
5317 /*
5318 ** The packing computed by the previous block is biased toward the siblings
5319 ** on the left side. The left siblings are always nearly full, while the
5320 ** right-most sibling might be nearly empty. This block of code attempts
5321 ** to adjust the packing of siblings to get a better balance.
5322 **
5323 ** This adjustment is more than an optimization. The packing above might
5324 ** be so out of balance as to be illegal. For example, the right-most
5325 ** sibling might be completely empty. This adjustment is not optional.
5326 */
drh6019e162001-07-02 17:51:45 +00005327 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00005328 int szRight = szNew[i]; /* Size of sibling on the right */
5329 int szLeft = szNew[i-1]; /* Size of sibling on the left */
5330 int r; /* Index of right-most cell in left sibling */
5331 int d; /* Index of first cell to the left of right sibling */
5332
5333 r = cntNew[i-1] - 1;
5334 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00005335 assert( d<nMaxCells );
5336 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00005337 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
5338 szRight += szCell[d] + 2;
5339 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00005340 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00005341 r = cntNew[i-1] - 1;
5342 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00005343 }
drh96f5b762004-05-16 16:24:36 +00005344 szNew[i] = szRight;
5345 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00005346 }
drh09d0deb2005-08-02 17:13:09 +00005347
5348 /* Either we found one or more cells (cntnew[0])>0) or we are the
5349 ** a virtual root page. A virtual root page is when the real root
5350 ** page is page 1 and we are the only child of that page.
5351 */
5352 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00005353
5354 /*
drh6b308672002-07-08 02:16:37 +00005355 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00005356 */
drh4b70f112004-05-02 21:12:19 +00005357 assert( pPage->pgno>1 );
5358 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00005359 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00005360 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00005361 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00005362 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00005363 pgnoNew[i] = pgnoOld[i];
5364 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00005365 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00005366 nNew++;
danielk197728129562005-01-11 10:25:06 +00005367 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00005368 }else{
drh7aa8f852006-03-28 00:24:44 +00005369 assert( i>0 );
drh4f0c5872007-03-26 22:05:01 +00005370 rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
drh6b308672002-07-08 02:16:37 +00005371 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00005372 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00005373 nNew++;
drh6b308672002-07-08 02:16:37 +00005374 }
drh8b2f49b2001-06-08 00:21:52 +00005375 }
5376
danielk1977299b1872004-11-22 10:02:10 +00005377 /* Free any old pages that were not reused as new pages.
5378 */
5379 while( i<nOld ){
5380 rc = freePage(apOld[i]);
5381 if( rc ) goto balance_cleanup;
5382 releasePage(apOld[i]);
5383 apOld[i] = 0;
5384 i++;
5385 }
5386
drh8b2f49b2001-06-08 00:21:52 +00005387 /*
drhf9ffac92002-03-02 19:00:31 +00005388 ** Put the new pages in accending order. This helps to
5389 ** keep entries in the disk file in order so that a scan
5390 ** of the table is a linear scan through the file. That
5391 ** in turn helps the operating system to deliver pages
5392 ** from the disk more rapidly.
5393 **
5394 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00005395 ** n is never more than NB (a small constant), that should
5396 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00005397 **
drhc3b70572003-01-04 19:44:07 +00005398 ** When NB==3, this one optimization makes the database
5399 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00005400 */
5401 for(i=0; i<k-1; i++){
5402 int minV = pgnoNew[i];
5403 int minI = i;
5404 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00005405 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00005406 minI = j;
5407 minV = pgnoNew[j];
5408 }
5409 }
5410 if( minI>i ){
5411 int t;
5412 MemPage *pT;
5413 t = pgnoNew[i];
5414 pT = apNew[i];
5415 pgnoNew[i] = pgnoNew[minI];
5416 apNew[i] = apNew[minI];
5417 pgnoNew[minI] = t;
5418 apNew[minI] = pT;
5419 }
5420 }
drha2fce642004-06-05 00:01:44 +00005421 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00005422 pgnoOld[0],
5423 nOld>=2 ? pgnoOld[1] : 0,
5424 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00005425 pgnoNew[0], szNew[0],
5426 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
5427 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00005428 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
5429 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00005430
drhf9ffac92002-03-02 19:00:31 +00005431 /*
drh14acc042001-06-10 19:56:58 +00005432 ** Evenly distribute the data in apCell[] across the new pages.
5433 ** Insert divider cells into pParent as necessary.
5434 */
5435 j = 0;
5436 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00005437 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00005438 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00005439 assert( j<nMaxCells );
drh4b70f112004-05-02 21:12:19 +00005440 assert( pNew->pgno==pgnoNew[i] );
drh10131482008-07-11 03:34:09 +00005441 zeroPage(pNew, pageFlags);
drhfa1a98a2004-05-14 19:08:17 +00005442 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00005443 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00005444 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00005445
danielk1977ac11ee62005-01-15 12:45:51 +00005446 /* If this is an auto-vacuum database, update the pointer map entries
5447 ** that point to the siblings that were rearranged. These can be: left
5448 ** children of cells, the right-child of the page, or overflow pages
5449 ** pointed to by cells.
5450 */
danielk197785d90ca2008-07-19 14:25:15 +00005451 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005452 for(k=j; k<cntNew[i]; k++){
danielk1977634f2982005-03-28 08:44:07 +00005453 assert( k<nMaxCells );
danielk1977ac11ee62005-01-15 12:45:51 +00005454 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
danielk197779a40da2005-01-16 08:00:01 +00005455 rc = ptrmapPutOvfl(pNew, k-j);
danielk197787c52b52008-07-19 11:49:07 +00005456 if( rc==SQLITE_OK && leafCorrection==0 ){
5457 rc = ptrmapPut(pBt, get4byte(apCell[k]), PTRMAP_BTREE, pNew->pgno);
5458 }
danielk197779a40da2005-01-16 08:00:01 +00005459 if( rc!=SQLITE_OK ){
5460 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00005461 }
5462 }
5463 }
5464 }
danielk1977ac11ee62005-01-15 12:45:51 +00005465
5466 j = cntNew[i];
5467
5468 /* If the sibling page assembled above was not the right-most sibling,
5469 ** insert a divider cell into the parent page.
5470 */
drh14acc042001-06-10 19:56:58 +00005471 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00005472 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00005473 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00005474 int sz;
danielk1977634f2982005-03-28 08:44:07 +00005475
5476 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00005477 pCell = apCell[j];
5478 sz = szCell[j] + leafCorrection;
drhe5ae5732008-06-15 02:51:47 +00005479 pTemp = &aSpace2[iSpace2];
drh4b70f112004-05-02 21:12:19 +00005480 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00005481 memcpy(&pNew->aData[8], pCell, 4);
danielk197785d90ca2008-07-19 14:25:15 +00005482 if( ISAUTOVACUUM
danielk197787c52b52008-07-19 11:49:07 +00005483 && (aFrom[j]==0xFF || apCopy[aFrom[j]]->pgno!=pNew->pgno)
5484 ){
5485 rc = ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno);
5486 if( rc!=SQLITE_OK ){
5487 goto balance_cleanup;
5488 }
5489 }
drh8b18dd42004-05-12 19:18:15 +00005490 }else if( leafData ){
drhfd131da2007-08-07 17:13:03 +00005491 /* If the tree is a leaf-data tree, and the siblings are leaves,
danielk1977ac11ee62005-01-15 12:45:51 +00005492 ** then there is no divider cell in apCell[]. Instead, the divider
5493 ** cell consists of the integer key for the right-most cell of
5494 ** the sibling-page assembled above only.
5495 */
drh6f11bef2004-05-13 01:12:56 +00005496 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00005497 j--;
drh16a9b832007-05-05 18:39:25 +00005498 sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
drhe5ae5732008-06-15 02:51:47 +00005499 pCell = pTemp;
drhb026e052007-05-02 01:34:31 +00005500 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
drh8b18dd42004-05-12 19:18:15 +00005501 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00005502 }else{
5503 pCell -= 4;
danielk19774aeff622007-05-12 09:30:47 +00005504 /* Obscure case for non-leaf-data trees: If the cell at pCell was
drh85b623f2007-12-13 21:54:09 +00005505 ** previously stored on a leaf node, and its reported size was 4
danielk19774aeff622007-05-12 09:30:47 +00005506 ** bytes, then it may actually be smaller than this
5507 ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
drh85b623f2007-12-13 21:54:09 +00005508 ** any cell). But it is important to pass the correct size to
danielk19774aeff622007-05-12 09:30:47 +00005509 ** insertCell(), so reparse the cell now.
5510 **
5511 ** Note that this can never happen in an SQLite data file, as all
5512 ** cells are at least 4 bytes. It only happens in b-trees used
5513 ** to evaluate "IN (SELECT ...)" and similar clauses.
5514 */
5515 if( szCell[j]==4 ){
5516 assert(leafCorrection==4);
5517 sz = cellSizePtr(pParent, pCell);
5518 }
drh4b70f112004-05-02 21:12:19 +00005519 }
drhe5ae5732008-06-15 02:51:47 +00005520 iSpace2 += sz;
5521 assert( sz<=pBt->pageSize/4 );
5522 assert( iSpace2<=pBt->pageSize );
danielk1977a3ad5e72005-01-07 08:56:44 +00005523 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
danielk1977e80463b2004-11-03 03:01:16 +00005524 if( rc!=SQLITE_OK ) goto balance_cleanup;
drhc5053fb2008-11-27 02:22:10 +00005525 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
drh43605152004-05-29 21:46:49 +00005526 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
danielk197785d90ca2008-07-19 14:25:15 +00005527
danielk1977ac11ee62005-01-15 12:45:51 +00005528 /* If this is an auto-vacuum database, and not a leaf-data tree,
5529 ** then update the pointer map with an entry for the overflow page
5530 ** that the cell just inserted points to (if any).
5531 */
danielk197785d90ca2008-07-19 14:25:15 +00005532 if( ISAUTOVACUUM && !leafData ){
danielk197779a40da2005-01-16 08:00:01 +00005533 rc = ptrmapPutOvfl(pParent, nxDiv);
5534 if( rc!=SQLITE_OK ){
5535 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00005536 }
5537 }
drh14acc042001-06-10 19:56:58 +00005538 j++;
5539 nxDiv++;
5540 }
danielk197787c52b52008-07-19 11:49:07 +00005541
danielk197787c52b52008-07-19 11:49:07 +00005542 /* Set the pointer-map entry for the new sibling page. */
danielk197785d90ca2008-07-19 14:25:15 +00005543 if( ISAUTOVACUUM ){
danielk197787c52b52008-07-19 11:49:07 +00005544 rc = ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno);
5545 if( rc!=SQLITE_OK ){
5546 goto balance_cleanup;
5547 }
5548 }
drh14acc042001-06-10 19:56:58 +00005549 }
drh6019e162001-07-02 17:51:45 +00005550 assert( j==nCell );
drh7aa8f852006-03-28 00:24:44 +00005551 assert( nOld>0 );
5552 assert( nNew>0 );
drh4b70f112004-05-02 21:12:19 +00005553 if( (pageFlags & PTF_LEAF)==0 ){
danielk197787c52b52008-07-19 11:49:07 +00005554 u8 *zChild = &apCopy[nOld-1]->aData[8];
5555 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
danielk197785d90ca2008-07-19 14:25:15 +00005556 if( ISAUTOVACUUM ){
danielk197787c52b52008-07-19 11:49:07 +00005557 rc = ptrmapPut(pBt, get4byte(zChild), PTRMAP_BTREE, apNew[nNew-1]->pgno);
5558 if( rc!=SQLITE_OK ){
5559 goto balance_cleanup;
5560 }
5561 }
drh14acc042001-06-10 19:56:58 +00005562 }
drhc5053fb2008-11-27 02:22:10 +00005563 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
drh43605152004-05-29 21:46:49 +00005564 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00005565 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00005566 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00005567 }else{
5568 /* Right-most sibling is the left child of the first entry in pParent
5569 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00005570 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00005571 }
5572
5573 /*
drh3a4c1412004-05-09 20:40:11 +00005574 ** Balance the parent page. Note that the current page (pPage) might
danielk1977ac11ee62005-01-15 12:45:51 +00005575 ** have been added to the freelist so it might no longer be initialized.
drh3a4c1412004-05-09 20:40:11 +00005576 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00005577 */
danielk197771d5d2c2008-09-29 11:49:47 +00005578 assert( pParent->isInit );
drhfacf0302008-06-17 15:12:00 +00005579 sqlite3ScratchFree(apCell);
drhe5ae5732008-06-15 02:51:47 +00005580 apCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005581 releasePage(pPage);
5582 pCur->iPage--;
5583 rc = balance(pCur, 0);
drhda200cc2004-05-09 11:51:38 +00005584
drh8b2f49b2001-06-08 00:21:52 +00005585 /*
drh14acc042001-06-10 19:56:58 +00005586 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00005587 */
drh14acc042001-06-10 19:56:58 +00005588balance_cleanup:
drhfacf0302008-06-17 15:12:00 +00005589 sqlite3PageFree(aSpace2);
5590 sqlite3ScratchFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00005591 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00005592 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00005593 }
drh14acc042001-06-10 19:56:58 +00005594 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00005595 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00005596 }
drh9bf9e9c2008-12-05 20:01:43 +00005597 pPage->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00005598
danielk197771d5d2c2008-09-29 11:49:47 +00005599 /* releasePage(pParent); */
drh3a4c1412004-05-09 20:40:11 +00005600 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
5601 pPage->pgno, nOld, nNew, nCell));
danielk1977eaa06f62008-09-18 17:34:44 +00005602
drh8b2f49b2001-06-08 00:21:52 +00005603 return rc;
5604}
5605
5606/*
drh43605152004-05-29 21:46:49 +00005607** This routine is called for the root page of a btree when the root
5608** page contains no cells. This is an opportunity to make the tree
5609** shallower by one level.
5610*/
danielk197771d5d2c2008-09-29 11:49:47 +00005611static int balance_shallower(BtCursor *pCur){
5612 MemPage *pPage; /* Root page of B-Tree */
drh43605152004-05-29 21:46:49 +00005613 MemPage *pChild; /* The only child page of pPage */
5614 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00005615 int rc = SQLITE_OK; /* Return code from subprocedures */
danielk1977aef0bf62005-12-30 16:28:01 +00005616 BtShared *pBt; /* The main BTree structure */
drh2e38c322004-09-03 18:38:44 +00005617 int mxCellPerPage; /* Maximum number of cells per page */
5618 u8 **apCell; /* All cells from pages being balanced */
drha9121e42008-02-19 14:59:35 +00005619 u16 *szCell; /* Local size of all cells */
drh43605152004-05-29 21:46:49 +00005620
danielk197771d5d2c2008-09-29 11:49:47 +00005621 assert( pCur->iPage==0 );
5622 pPage = pCur->apPage[0];
5623
drh43605152004-05-29 21:46:49 +00005624 assert( pPage->nCell==0 );
drh1fee73e2007-08-29 04:00:57 +00005625 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh2e38c322004-09-03 18:38:44 +00005626 pBt = pPage->pBt;
5627 mxCellPerPage = MX_CELL(pBt);
drhe5ae5732008-06-15 02:51:47 +00005628 apCell = sqlite3Malloc( mxCellPerPage*(sizeof(u8*)+sizeof(u16)) );
drh2e38c322004-09-03 18:38:44 +00005629 if( apCell==0 ) return SQLITE_NOMEM;
drha9121e42008-02-19 14:59:35 +00005630 szCell = (u16*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00005631 if( pPage->leaf ){
5632 /* The table is completely empty */
5633 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
5634 }else{
5635 /* The root page is empty but has one child. Transfer the
5636 ** information from that one child into the root page if it
5637 ** will fit. This reduces the depth of the tree by one.
5638 **
5639 ** If the root page is page 1, it has less space available than
5640 ** its child (due to the 100 byte header that occurs at the beginning
5641 ** of the database fle), so it might not be able to hold all of the
5642 ** information currently contained in the child. If this is the
5643 ** case, then do not do the transfer. Leave page 1 empty except
5644 ** for the right-pointer to the child page. The child page becomes
5645 ** the virtual root of the tree.
5646 */
drhf94a1732008-09-30 17:18:17 +00005647 VVA_ONLY( pCur->pagesShuffled = 1 );
drh43605152004-05-29 21:46:49 +00005648 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5649 assert( pgnoChild>0 );
danielk197789d40042008-11-17 14:20:56 +00005650 assert( pgnoChild<=pagerPagecount(pPage->pBt) );
drh16a9b832007-05-05 18:39:25 +00005651 rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
drh2e38c322004-09-03 18:38:44 +00005652 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005653 if( pPage->pgno==1 ){
danielk197771d5d2c2008-09-29 11:49:47 +00005654 rc = sqlite3BtreeInitPage(pChild);
drh2e38c322004-09-03 18:38:44 +00005655 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005656 assert( pChild->nOverflow==0 );
5657 if( pChild->nFree>=100 ){
5658 /* The child information will fit on the root page, so do the
5659 ** copy */
5660 int i;
5661 zeroPage(pPage, pChild->aData[0]);
5662 for(i=0; i<pChild->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00005663 apCell[i] = findCell(pChild,i);
drh43605152004-05-29 21:46:49 +00005664 szCell[i] = cellSizePtr(pChild, apCell[i]);
5665 }
5666 assemblePage(pPage, pChild->nCell, apCell, szCell);
danielk1977ae825582004-11-23 09:06:55 +00005667 /* Copy the right-pointer of the child to the parent. */
drhc5053fb2008-11-27 02:22:10 +00005668 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977ae825582004-11-23 09:06:55 +00005669 put4byte(&pPage->aData[pPage->hdrOffset+8],
5670 get4byte(&pChild->aData[pChild->hdrOffset+8]));
drh9bf9e9c2008-12-05 20:01:43 +00005671 rc = freePage(pChild);
drh43605152004-05-29 21:46:49 +00005672 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
5673 }else{
5674 /* The child has more information that will fit on the root.
5675 ** The tree is already balanced. Do nothing. */
5676 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
5677 }
5678 }else{
5679 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
5680 pPage->isInit = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005681 rc = sqlite3BtreeInitPage(pPage);
drh43605152004-05-29 21:46:49 +00005682 assert( rc==SQLITE_OK );
5683 freePage(pChild);
5684 TRACE(("BALANCE: transfer child %d into root %d\n",
5685 pChild->pgno, pPage->pgno));
5686 }
danielk1977ac11ee62005-01-15 12:45:51 +00005687 assert( pPage->nOverflow==0 );
shane831c3292008-11-10 17:14:58 +00005688#ifndef SQLITE_OMIT_AUTOVACUUM
drh9bf9e9c2008-12-05 20:01:43 +00005689 if( ISAUTOVACUUM && rc==SQLITE_OK ){
danielk197700a696d2008-09-29 16:41:31 +00005690 rc = setChildPtrmaps(pPage);
danielk1977ac11ee62005-01-15 12:45:51 +00005691 }
shane831c3292008-11-10 17:14:58 +00005692#endif
drh43605152004-05-29 21:46:49 +00005693 releasePage(pChild);
5694 }
drh2e38c322004-09-03 18:38:44 +00005695end_shallow_balance:
drh17435752007-08-16 04:30:38 +00005696 sqlite3_free(apCell);
drh2e38c322004-09-03 18:38:44 +00005697 return rc;
drh43605152004-05-29 21:46:49 +00005698}
5699
5700
5701/*
5702** The root page is overfull
5703**
5704** When this happens, Create a new child page and copy the
5705** contents of the root into the child. Then make the root
5706** page an empty page with rightChild pointing to the new
5707** child. Finally, call balance_internal() on the new child
5708** to cause it to split.
5709*/
danielk197771d5d2c2008-09-29 11:49:47 +00005710static int balance_deeper(BtCursor *pCur){
drh43605152004-05-29 21:46:49 +00005711 int rc; /* Return value from subprocedures */
danielk197771d5d2c2008-09-29 11:49:47 +00005712 MemPage *pPage; /* Pointer to the root page */
drh43605152004-05-29 21:46:49 +00005713 MemPage *pChild; /* Pointer to a new child page */
5714 Pgno pgnoChild; /* Page number of the new child page */
danielk1977aef0bf62005-12-30 16:28:01 +00005715 BtShared *pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00005716 int usableSize; /* Total usable size of a page */
5717 u8 *data; /* Content of the parent page */
5718 u8 *cdata; /* Content of the child page */
5719 int hdr; /* Offset to page header in parent */
drh281b21d2008-08-22 12:57:08 +00005720 int cbrk; /* Offset to content of first cell in parent */
drh43605152004-05-29 21:46:49 +00005721
danielk197771d5d2c2008-09-29 11:49:47 +00005722 assert( pCur->iPage==0 );
5723 assert( pCur->apPage[0]->nOverflow>0 );
5724
drhf94a1732008-09-30 17:18:17 +00005725 VVA_ONLY( pCur->pagesShuffled = 1 );
danielk197771d5d2c2008-09-29 11:49:47 +00005726 pPage = pCur->apPage[0];
drh43605152004-05-29 21:46:49 +00005727 pBt = pPage->pBt;
drh1fee73e2007-08-29 04:00:57 +00005728 assert( sqlite3_mutex_held(pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00005729 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh4f0c5872007-03-26 22:05:01 +00005730 rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
drh43605152004-05-29 21:46:49 +00005731 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00005732 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
drh43605152004-05-29 21:46:49 +00005733 usableSize = pBt->usableSize;
5734 data = pPage->aData;
5735 hdr = pPage->hdrOffset;
drh281b21d2008-08-22 12:57:08 +00005736 cbrk = get2byte(&data[hdr+5]);
drh43605152004-05-29 21:46:49 +00005737 cdata = pChild->aData;
5738 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
drh281b21d2008-08-22 12:57:08 +00005739 memcpy(&cdata[cbrk], &data[cbrk], usableSize-cbrk);
danielk1977bc2ca9e2008-11-13 14:28:28 +00005740
5741 assert( pChild->isInit==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00005742 rc = sqlite3BtreeInitPage(pChild);
5743 if( rc==SQLITE_OK ){
5744 int nCopy = pPage->nOverflow*sizeof(pPage->aOvfl[0]);
5745 memcpy(pChild->aOvfl, pPage->aOvfl, nCopy);
5746 pChild->nOverflow = pPage->nOverflow;
5747 if( pChild->nOverflow ){
5748 pChild->nFree = 0;
5749 }
5750 assert( pChild->nCell==pPage->nCell );
drhc5053fb2008-11-27 02:22:10 +00005751 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00005752 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
5753 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
5754 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
5755 if( ISAUTOVACUUM ){
danielk197771d5d2c2008-09-29 11:49:47 +00005756 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
shane831c3292008-11-10 17:14:58 +00005757#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197771d5d2c2008-09-29 11:49:47 +00005758 if( rc==SQLITE_OK ){
danielk197700a696d2008-09-29 16:41:31 +00005759 rc = setChildPtrmaps(pChild);
danielk1977ac11ee62005-01-15 12:45:51 +00005760 }
shane831c3292008-11-10 17:14:58 +00005761#endif
danielk1977ac11ee62005-01-15 12:45:51 +00005762 }
danielk197787c52b52008-07-19 11:49:07 +00005763 }
danielk19776b456a22005-03-21 04:04:02 +00005764
danielk197771d5d2c2008-09-29 11:49:47 +00005765 if( rc==SQLITE_OK ){
5766 pCur->iPage++;
5767 pCur->apPage[1] = pChild;
danielk1977bf93c562008-09-29 15:53:25 +00005768 pCur->aiIdx[0] = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005769 rc = balance_nonroot(pCur);
5770 }else{
5771 releasePage(pChild);
5772 }
5773
drh43605152004-05-29 21:46:49 +00005774 return rc;
5775}
5776
5777/*
danielk197771d5d2c2008-09-29 11:49:47 +00005778** The page that pCur currently points to has just been modified in
5779** some way. This function figures out if this modification means the
5780** tree needs to be balanced, and if so calls the appropriate balancing
5781** routine.
5782**
5783** Parameter isInsert is true if a new cell was just inserted into the
5784** page, or false otherwise.
drh43605152004-05-29 21:46:49 +00005785*/
danielk197771d5d2c2008-09-29 11:49:47 +00005786static int balance(BtCursor *pCur, int isInsert){
drh43605152004-05-29 21:46:49 +00005787 int rc = SQLITE_OK;
danielk197771d5d2c2008-09-29 11:49:47 +00005788 MemPage *pPage = pCur->apPage[pCur->iPage];
5789
drh1fee73e2007-08-29 04:00:57 +00005790 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197771d5d2c2008-09-29 11:49:47 +00005791 if( pCur->iPage==0 ){
danielk19776e465eb2007-08-21 13:11:00 +00005792 rc = sqlite3PagerWrite(pPage->pDbPage);
5793 if( rc==SQLITE_OK && pPage->nOverflow>0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00005794 rc = balance_deeper(pCur);
drh9bf9e9c2008-12-05 20:01:43 +00005795 assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
drh43605152004-05-29 21:46:49 +00005796 }
danielk1977687566d2004-11-02 12:56:41 +00005797 if( rc==SQLITE_OK && pPage->nCell==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00005798 rc = balance_shallower(pCur);
drh9bf9e9c2008-12-05 20:01:43 +00005799 assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
drh43605152004-05-29 21:46:49 +00005800 }
5801 }else{
danielk1977ac245ec2005-01-14 13:50:11 +00005802 if( pPage->nOverflow>0 ||
danielk197771d5d2c2008-09-29 11:49:47 +00005803 (!isInsert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
5804 rc = balance_nonroot(pCur);
drh9bf9e9c2008-12-05 20:01:43 +00005805 assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
drh43605152004-05-29 21:46:49 +00005806 }
5807 }
5808 return rc;
5809}
5810
5811/*
drh8dcd7ca2004-08-08 19:43:29 +00005812** This routine checks all cursors that point to table pgnoRoot.
drh980b1a72006-08-16 16:42:48 +00005813** If any of those cursors were opened with wrFlag==0 in a different
5814** database connection (a database connection that shares the pager
5815** cache with the current connection) and that other connection
5816** is not in the ReadUncommmitted state, then this routine returns
5817** SQLITE_LOCKED.
danielk1977299b1872004-11-22 10:02:10 +00005818**
danielk19773588ceb2008-06-10 17:30:26 +00005819** As well as cursors with wrFlag==0, cursors with wrFlag==1 and
5820** isIncrblobHandle==1 are also considered 'read' cursors. Incremental
5821** blob cursors are used for both reading and writing.
5822**
5823** When pgnoRoot is the root page of an intkey table, this function is also
5824** responsible for invalidating incremental blob cursors when the table row
5825** on which they are opened is deleted or modified. Cursors are invalidated
5826** according to the following rules:
5827**
5828** 1) When BtreeClearTable() is called to completely delete the contents
5829** of a B-Tree table, pExclude is set to zero and parameter iRow is
5830** set to non-zero. In this case all incremental blob cursors open
5831** on the table rooted at pgnoRoot are invalidated.
5832**
5833** 2) When BtreeInsert(), BtreeDelete() or BtreePutData() is called to
5834** modify a table row via an SQL statement, pExclude is set to the
5835** write cursor used to do the modification and parameter iRow is set
5836** to the integer row id of the B-Tree entry being modified. Unless
5837** pExclude is itself an incremental blob cursor, then all incremental
5838** blob cursors open on row iRow of the B-Tree are invalidated.
5839**
5840** 3) If both pExclude and iRow are set to zero, no incremental blob
5841** cursors are invalidated.
drhf74b8d92002-09-01 23:20:45 +00005842*/
danielk19773588ceb2008-06-10 17:30:26 +00005843static int checkReadLocks(
5844 Btree *pBtree,
5845 Pgno pgnoRoot,
5846 BtCursor *pExclude,
5847 i64 iRow
5848){
danielk1977299b1872004-11-22 10:02:10 +00005849 BtCursor *p;
drh980b1a72006-08-16 16:42:48 +00005850 BtShared *pBt = pBtree->pBt;
drhe5fe6902007-12-07 18:55:28 +00005851 sqlite3 *db = pBtree->db;
drh1fee73e2007-08-29 04:00:57 +00005852 assert( sqlite3BtreeHoldsMutex(pBtree) );
danielk1977299b1872004-11-22 10:02:10 +00005853 for(p=pBt->pCursor; p; p=p->pNext){
drh980b1a72006-08-16 16:42:48 +00005854 if( p==pExclude ) continue;
drh980b1a72006-08-16 16:42:48 +00005855 if( p->pgnoRoot!=pgnoRoot ) continue;
danielk19773588ceb2008-06-10 17:30:26 +00005856#ifndef SQLITE_OMIT_INCRBLOB
5857 if( p->isIncrblobHandle && (
5858 (!pExclude && iRow)
5859 || (pExclude && !pExclude->isIncrblobHandle && p->info.nKey==iRow)
5860 )){
5861 p->eState = CURSOR_INVALID;
5862 }
5863#endif
5864 if( p->eState!=CURSOR_VALID ) continue;
5865 if( p->wrFlag==0
5866#ifndef SQLITE_OMIT_INCRBLOB
5867 || p->isIncrblobHandle
5868#endif
5869 ){
drhe5fe6902007-12-07 18:55:28 +00005870 sqlite3 *dbOther = p->pBtree->db;
drh980b1a72006-08-16 16:42:48 +00005871 if( dbOther==0 ||
5872 (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
5873 return SQLITE_LOCKED;
5874 }
danielk1977299b1872004-11-22 10:02:10 +00005875 }
5876 }
drhf74b8d92002-09-01 23:20:45 +00005877 return SQLITE_OK;
5878}
5879
5880/*
drh3b7511c2001-05-26 13:15:44 +00005881** Insert a new record into the BTree. The key is given by (pKey,nKey)
5882** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00005883** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00005884** is left pointing at a random location.
5885**
5886** For an INTKEY table, only the nKey value of the key is used. pKey is
5887** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00005888*/
drh3aac2dd2004-04-26 14:10:20 +00005889int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00005890 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00005891 const void *pKey, i64 nKey, /* The key of the new record */
drhe4d90812007-03-29 05:51:49 +00005892 const void *pData, int nData, /* The data of the new record */
drhb026e052007-05-02 01:34:31 +00005893 int nZero, /* Number of extra 0 bytes to append to data */
drhe4d90812007-03-29 05:51:49 +00005894 int appendBias /* True if this is likely an append */
drh3b7511c2001-05-26 13:15:44 +00005895){
drh3b7511c2001-05-26 13:15:44 +00005896 int rc;
5897 int loc;
drh14acc042001-06-10 19:56:58 +00005898 int szNew;
danielk197771d5d2c2008-09-29 11:49:47 +00005899 int idx;
drh3b7511c2001-05-26 13:15:44 +00005900 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00005901 Btree *p = pCur->pBtree;
5902 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00005903 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00005904 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00005905
drh1fee73e2007-08-29 04:00:57 +00005906 assert( cursorHoldsMutex(pCur) );
danielk1977aef0bf62005-12-30 16:28:01 +00005907 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005908 /* Must start a transaction before doing an insert */
drhd677b3d2007-08-20 22:48:41 +00005909 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drhd677b3d2007-08-20 22:48:41 +00005910 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005911 }
drhf74b8d92002-09-01 23:20:45 +00005912 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00005913 if( !pCur->wrFlag ){
5914 return SQLITE_PERM; /* Cursor not open for writing */
5915 }
danielk19773588ceb2008-06-10 17:30:26 +00005916 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, nKey) ){
drhf74b8d92002-09-01 23:20:45 +00005917 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5918 }
drhfb982642007-08-30 01:19:59 +00005919 if( pCur->eState==CURSOR_FAULT ){
5920 return pCur->skip;
5921 }
danielk1977da184232006-01-05 11:34:32 +00005922
5923 /* Save the positions of any other cursors open on this table */
danielk1977be51a652008-10-08 17:58:48 +00005924 sqlite3BtreeClearCursor(pCur);
danielk19772e94d4d2006-01-09 05:36:27 +00005925 if(
danielk19772e94d4d2006-01-09 05:36:27 +00005926 SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
drhe63d9992008-08-13 19:11:48 +00005927 SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
danielk19772e94d4d2006-01-09 05:36:27 +00005928 ){
danielk1977da184232006-01-05 11:34:32 +00005929 return rc;
5930 }
5931
danielk197771d5d2c2008-09-29 11:49:47 +00005932 pPage = pCur->apPage[pCur->iPage];
drh4a1c3802004-05-12 15:15:47 +00005933 assert( pPage->intKey || nKey>=0 );
drh44845222008-07-17 18:39:57 +00005934 assert( pPage->leaf || !pPage->intKey );
drh3a4c1412004-05-09 20:40:11 +00005935 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
5936 pCur->pgnoRoot, nKey, nData, pPage->pgno,
5937 loc==0 ? "overwrite" : "new entry"));
danielk197771d5d2c2008-09-29 11:49:47 +00005938 assert( pPage->isInit );
danielk197752ae7242008-03-25 14:24:56 +00005939 allocateTempSpace(pBt);
5940 newCell = pBt->pTmpSpace;
drh2e38c322004-09-03 18:38:44 +00005941 if( newCell==0 ) return SQLITE_NOMEM;
drhb026e052007-05-02 01:34:31 +00005942 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
drh2e38c322004-09-03 18:38:44 +00005943 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00005944 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00005945 assert( szNew<=MX_CELL_SIZE(pBt) );
danielk197771d5d2c2008-09-29 11:49:47 +00005946 idx = pCur->aiIdx[pCur->iPage];
danielk1977da184232006-01-05 11:34:32 +00005947 if( loc==0 && CURSOR_VALID==pCur->eState ){
drha9121e42008-02-19 14:59:35 +00005948 u16 szOld;
danielk197771d5d2c2008-09-29 11:49:47 +00005949 assert( idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00005950 rc = sqlite3PagerWrite(pPage->pDbPage);
5951 if( rc ){
5952 goto end_insert;
5953 }
danielk197771d5d2c2008-09-29 11:49:47 +00005954 oldCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00005955 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005956 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00005957 }
drh43605152004-05-29 21:46:49 +00005958 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00005959 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00005960 if( rc ) goto end_insert;
shane0af3f892008-11-12 04:55:34 +00005961 rc = dropCell(pPage, idx, szOld);
5962 if( rc!=SQLITE_OK ) {
5963 goto end_insert;
5964 }
drh7c717f72001-06-24 20:39:41 +00005965 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00005966 assert( pPage->leaf );
danielk197771d5d2c2008-09-29 11:49:47 +00005967 idx = ++pCur->aiIdx[pCur->iPage];
drh271efa52004-05-30 19:19:05 +00005968 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00005969 pCur->validNKey = 0;
drh14acc042001-06-10 19:56:58 +00005970 }else{
drh4b70f112004-05-02 21:12:19 +00005971 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00005972 }
danielk197771d5d2c2008-09-29 11:49:47 +00005973 rc = insertCell(pPage, idx, newCell, szNew, 0, 0);
drh9bf9e9c2008-12-05 20:01:43 +00005974 if( rc==SQLITE_OK ){
5975 rc = balance(pCur, 1);
5976 }
5977
5978 /* Must make sure nOverflow is reset to zero even if the balance()
5979 ** fails. Internal data structure corruption will result otherwise. */
5980 assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
5981 pPage->nOverflow = 0;
5982
danielk1977299b1872004-11-22 10:02:10 +00005983 if( rc==SQLITE_OK ){
5984 moveToRoot(pCur);
5985 }
drh2e38c322004-09-03 18:38:44 +00005986end_insert:
drh5e2f8b92001-05-28 00:41:15 +00005987 return rc;
5988}
5989
5990/*
drh4b70f112004-05-02 21:12:19 +00005991** Delete the entry that the cursor is pointing to. The cursor
drhf94a1732008-09-30 17:18:17 +00005992** is left pointing at a arbitrary location.
drh3b7511c2001-05-26 13:15:44 +00005993*/
drh3aac2dd2004-04-26 14:10:20 +00005994int sqlite3BtreeDelete(BtCursor *pCur){
danielk197771d5d2c2008-09-29 11:49:47 +00005995 MemPage *pPage = pCur->apPage[pCur->iPage];
5996 int idx;
drh4b70f112004-05-02 21:12:19 +00005997 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00005998 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00005999 Pgno pgnoChild = 0;
drhd677b3d2007-08-20 22:48:41 +00006000 Btree *p = pCur->pBtree;
6001 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006002
drh1fee73e2007-08-29 04:00:57 +00006003 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00006004 assert( pPage->isInit );
danielk1977aef0bf62005-12-30 16:28:01 +00006005 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00006006 /* Must start a transaction before doing a delete */
drhd677b3d2007-08-20 22:48:41 +00006007 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drhd677b3d2007-08-20 22:48:41 +00006008 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006009 }
drhf74b8d92002-09-01 23:20:45 +00006010 assert( !pBt->readOnly );
drhfb982642007-08-30 01:19:59 +00006011 if( pCur->eState==CURSOR_FAULT ){
6012 return pCur->skip;
6013 }
danielk197771d5d2c2008-09-29 11:49:47 +00006014 if( pCur->aiIdx[pCur->iPage]>=pPage->nCell ){
drhbd03cae2001-06-02 02:40:57 +00006015 return SQLITE_ERROR; /* The cursor is not pointing to anything */
6016 }
drhecdc7532001-09-23 02:35:53 +00006017 if( !pCur->wrFlag ){
6018 return SQLITE_PERM; /* Did not open this cursor for writing */
6019 }
danielk19773588ceb2008-06-10 17:30:26 +00006020 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur, pCur->info.nKey) ){
drhf74b8d92002-09-01 23:20:45 +00006021 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
6022 }
danielk1977da184232006-01-05 11:34:32 +00006023
6024 /* Restore the current cursor position (a no-op if the cursor is not in
6025 ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors
danielk19773b8a05f2007-03-19 17:44:26 +00006026 ** open on the same table. Then call sqlite3PagerWrite() on the page
danielk1977da184232006-01-05 11:34:32 +00006027 ** that the entry will be deleted from.
6028 */
6029 if(
drha3460582008-07-11 21:02:53 +00006030 (rc = restoreCursorPosition(pCur))!=0 ||
drhd1167392006-01-23 13:00:35 +00006031 (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
danielk19773b8a05f2007-03-19 17:44:26 +00006032 (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
danielk1977da184232006-01-05 11:34:32 +00006033 ){
6034 return rc;
6035 }
danielk1977e6efa742004-11-10 11:55:10 +00006036
drh85b623f2007-12-13 21:54:09 +00006037 /* Locate the cell within its page and leave pCell pointing to the
danielk1977e6efa742004-11-10 11:55:10 +00006038 ** data. The clearCell() call frees any overflow pages associated with the
6039 ** cell. The cell itself is still intact.
6040 */
danielk197771d5d2c2008-09-29 11:49:47 +00006041 idx = pCur->aiIdx[pCur->iPage];
6042 pCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00006043 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006044 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00006045 }
danielk197728129562005-01-11 10:25:06 +00006046 rc = clearCell(pPage, pCell);
drhd677b3d2007-08-20 22:48:41 +00006047 if( rc ){
drhd677b3d2007-08-20 22:48:41 +00006048 return rc;
6049 }
danielk1977e6efa742004-11-10 11:55:10 +00006050
drh4b70f112004-05-02 21:12:19 +00006051 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00006052 /*
drh5e00f6c2001-09-13 13:46:56 +00006053 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00006054 ** do something we will leave a hole on an internal page.
6055 ** We have to fill the hole by moving in a cell from a leaf. The
6056 ** next Cell after the one to be deleted is guaranteed to exist and
danielk1977299b1872004-11-22 10:02:10 +00006057 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00006058 */
drh14acc042001-06-10 19:56:58 +00006059 BtCursor leafCur;
drh1bd10f82008-12-10 21:19:56 +00006060 MemPage *pLeafPage = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00006061
drh4b70f112004-05-02 21:12:19 +00006062 unsigned char *pNext;
danielk1977299b1872004-11-22 10:02:10 +00006063 int notUsed;
danielk19776b456a22005-03-21 04:04:02 +00006064 unsigned char *tempCell = 0;
drh44845222008-07-17 18:39:57 +00006065 assert( !pPage->intKey );
drh16a9b832007-05-05 18:39:25 +00006066 sqlite3BtreeGetTempCursor(pCur, &leafCur);
danielk1977299b1872004-11-22 10:02:10 +00006067 rc = sqlite3BtreeNext(&leafCur, &notUsed);
danielk19776b456a22005-03-21 04:04:02 +00006068 if( rc==SQLITE_OK ){
danielk19772f78fc62008-09-30 09:31:45 +00006069 assert( leafCur.aiIdx[leafCur.iPage]==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00006070 pLeafPage = leafCur.apPage[leafCur.iPage];
danielk197771d5d2c2008-09-29 11:49:47 +00006071 rc = sqlite3PagerWrite(pLeafPage->pDbPage);
danielk19776b456a22005-03-21 04:04:02 +00006072 }
6073 if( rc==SQLITE_OK ){
danielk19772f78fc62008-09-30 09:31:45 +00006074 int leafCursorInvalid = 0;
drha9121e42008-02-19 14:59:35 +00006075 u16 szNext;
danielk19776b456a22005-03-21 04:04:02 +00006076 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
danielk197771d5d2c2008-09-29 11:49:47 +00006077 pCur->pgnoRoot, pPage->pgno, pLeafPage->pgno));
6078 dropCell(pPage, idx, cellSizePtr(pPage, pCell));
danielk19772f78fc62008-09-30 09:31:45 +00006079 pNext = findCell(pLeafPage, 0);
danielk197771d5d2c2008-09-29 11:49:47 +00006080 szNext = cellSizePtr(pLeafPage, pNext);
danielk19776b456a22005-03-21 04:04:02 +00006081 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
danielk197752ae7242008-03-25 14:24:56 +00006082 allocateTempSpace(pBt);
6083 tempCell = pBt->pTmpSpace;
danielk19776b456a22005-03-21 04:04:02 +00006084 if( tempCell==0 ){
6085 rc = SQLITE_NOMEM;
6086 }
danielk19778ea1cfa2008-01-01 06:19:02 +00006087 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00006088 rc = insertCell(pPage, idx, pNext-4, szNext+4, tempCell, 0);
danielk19778ea1cfa2008-01-01 06:19:02 +00006089 }
danielk19772f78fc62008-09-30 09:31:45 +00006090
drhf94a1732008-09-30 17:18:17 +00006091
6092 /* The "if" statement in the next code block is critical. The
6093 ** slightest error in that statement would allow SQLite to operate
6094 ** correctly most of the time but produce very rare failures. To
6095 ** guard against this, the following macros help to verify that
6096 ** the "if" statement is well tested.
6097 */
6098 testcase( pPage->nOverflow==0 && pPage->nFree<pBt->usableSize*2/3
6099 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6100 testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3
6101 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6102 testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3+1
6103 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6104 testcase( pPage->nOverflow>0 && pPage->nFree<=pBt->usableSize*2/3
6105 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6106 testcase( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3))
6107 && pLeafPage->nFree+2+szNext == pBt->usableSize*2/3 );
6108
6109
danielk19772f78fc62008-09-30 09:31:45 +00006110 if( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3)) &&
6111 (pLeafPage->nFree+2+szNext > pBt->usableSize*2/3)
6112 ){
drhf94a1732008-09-30 17:18:17 +00006113 /* This branch is taken if the internal node is now either overflowing
6114 ** or underfull and the leaf node will be underfull after the just cell
danielk19772f78fc62008-09-30 09:31:45 +00006115 ** copied to the internal node is deleted from it. This is a special
6116 ** case because the call to balance() to correct the internal node
6117 ** may change the tree structure and invalidate the contents of
6118 ** the leafCur.apPage[] and leafCur.aiIdx[] arrays, which will be
6119 ** used by the balance() required to correct the underfull leaf
6120 ** node.
6121 **
6122 ** The formula used in the expression above are based on facets of
6123 ** the SQLite file-format that do not change over time.
6124 */
drhf94a1732008-09-30 17:18:17 +00006125 testcase( pPage->nFree==pBt->usableSize*2/3+1 );
6126 testcase( pLeafPage->nFree+2+szNext==pBt->usableSize*2/3+1 );
danielk19772f78fc62008-09-30 09:31:45 +00006127 leafCursorInvalid = 1;
6128 }
6129
danielk19778ea1cfa2008-01-01 06:19:02 +00006130 if( rc==SQLITE_OK ){
drhc5053fb2008-11-27 02:22:10 +00006131 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00006132 put4byte(findOverflowCell(pPage, idx), pgnoChild);
drhf94a1732008-09-30 17:18:17 +00006133 VVA_ONLY( pCur->pagesShuffled = 0 );
danielk197771d5d2c2008-09-29 11:49:47 +00006134 rc = balance(pCur, 0);
danielk19778ea1cfa2008-01-01 06:19:02 +00006135 }
danielk19772f78fc62008-09-30 09:31:45 +00006136
6137 if( rc==SQLITE_OK && leafCursorInvalid ){
6138 /* The leaf-node is now underfull and so the tree needs to be
6139 ** rebalanced. However, the balance() operation on the internal
6140 ** node above may have modified the structure of the B-Tree and
6141 ** so the current contents of leafCur.apPage[] and leafCur.aiIdx[]
6142 ** may not be trusted.
6143 **
6144 ** It is not possible to copy the ancestry from pCur, as the same
6145 ** balance() call has invalidated the pCur->apPage[] and aiIdx[]
6146 ** arrays.
drh7b682802008-09-30 14:06:28 +00006147 **
6148 ** The call to saveCursorPosition() below internally saves the
6149 ** key that leafCur is currently pointing to. Currently, there
6150 ** are two copies of that key in the tree - one here on the leaf
6151 ** page and one on some internal node in the tree. The copy on
6152 ** the leaf node is always the next key in tree-order after the
6153 ** copy on the internal node. So, the call to sqlite3BtreeNext()
6154 ** calls restoreCursorPosition() to point the cursor to the copy
6155 ** stored on the internal node, then advances to the next entry,
6156 ** which happens to be the copy of the key on the internal node.
danielk1977a69fda22008-09-30 16:48:10 +00006157 ** Net effect: leafCur is pointing back to the duplicate cell
6158 ** that needs to be removed, and the leafCur.apPage[] and
6159 ** leafCur.aiIdx[] arrays are correct.
danielk19772f78fc62008-09-30 09:31:45 +00006160 */
drhf94a1732008-09-30 17:18:17 +00006161 VVA_ONLY( Pgno leafPgno = pLeafPage->pgno );
danielk19772f78fc62008-09-30 09:31:45 +00006162 rc = saveCursorPosition(&leafCur);
6163 if( rc==SQLITE_OK ){
6164 rc = sqlite3BtreeNext(&leafCur, &notUsed);
6165 }
6166 pLeafPage = leafCur.apPage[leafCur.iPage];
6167 assert( pLeafPage->pgno==leafPgno );
6168 assert( leafCur.aiIdx[leafCur.iPage]==0 );
6169 }
6170
danielk19770cd1bbd2008-11-26 07:25:52 +00006171 if( SQLITE_OK==rc
6172 && SQLITE_OK==(rc = sqlite3PagerWrite(pLeafPage->pDbPage))
6173 ){
danielk19772f78fc62008-09-30 09:31:45 +00006174 dropCell(pLeafPage, 0, szNext);
drhf94a1732008-09-30 17:18:17 +00006175 VVA_ONLY( leafCur.pagesShuffled = 0 );
danielk197771d5d2c2008-09-29 11:49:47 +00006176 rc = balance(&leafCur, 0);
drhf94a1732008-09-30 17:18:17 +00006177 assert( leafCursorInvalid || !leafCur.pagesShuffled
6178 || !pCur->pagesShuffled );
danielk19778ea1cfa2008-01-01 06:19:02 +00006179 }
danielk19776b456a22005-03-21 04:04:02 +00006180 }
drh16a9b832007-05-05 18:39:25 +00006181 sqlite3BtreeReleaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00006182 }else{
danielk1977299b1872004-11-22 10:02:10 +00006183 TRACE(("DELETE: table=%d delete from leaf %d\n",
6184 pCur->pgnoRoot, pPage->pgno));
shanedcc50b72008-11-13 18:29:50 +00006185 rc = dropCell(pPage, idx, cellSizePtr(pPage, pCell));
6186 if( rc==SQLITE_OK ){
6187 rc = balance(pCur, 0);
6188 }
drh5e2f8b92001-05-28 00:41:15 +00006189 }
danielk19776b456a22005-03-21 04:04:02 +00006190 if( rc==SQLITE_OK ){
6191 moveToRoot(pCur);
6192 }
drh5e2f8b92001-05-28 00:41:15 +00006193 return rc;
drh3b7511c2001-05-26 13:15:44 +00006194}
drh8b2f49b2001-06-08 00:21:52 +00006195
6196/*
drhc6b52df2002-01-04 03:09:29 +00006197** Create a new BTree table. Write into *piTable the page
6198** number for the root page of the new table.
6199**
drhab01f612004-05-22 02:55:23 +00006200** The type of type is determined by the flags parameter. Only the
6201** following values of flags are currently in use. Other values for
6202** flags might not work:
6203**
6204** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
6205** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00006206*/
drhd677b3d2007-08-20 22:48:41 +00006207static int btreeCreateTable(Btree *p, int *piTable, int flags){
danielk1977aef0bf62005-12-30 16:28:01 +00006208 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006209 MemPage *pRoot;
6210 Pgno pgnoRoot;
6211 int rc;
drhd677b3d2007-08-20 22:48:41 +00006212
drh1fee73e2007-08-29 04:00:57 +00006213 assert( sqlite3BtreeHoldsMutex(p) );
danielk1977aef0bf62005-12-30 16:28:01 +00006214 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00006215 /* Must start a transaction first */
drhd677b3d2007-08-20 22:48:41 +00006216 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
6217 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006218 }
danielk197728129562005-01-11 10:25:06 +00006219 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00006220
danielk1977003ba062004-11-04 02:57:33 +00006221#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00006222 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00006223 if( rc ){
6224 return rc;
6225 }
danielk1977003ba062004-11-04 02:57:33 +00006226#else
danielk1977687566d2004-11-02 12:56:41 +00006227 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00006228 Pgno pgnoMove; /* Move a page here to make room for the root-page */
6229 MemPage *pPageMove; /* The page to move to. */
6230
danielk197720713f32007-05-03 11:43:33 +00006231 /* Creating a new table may probably require moving an existing database
6232 ** to make room for the new tables root page. In case this page turns
6233 ** out to be an overflow page, delete all overflow page-map caches
6234 ** held by open cursors.
6235 */
danielk197792d4d7a2007-05-04 12:05:56 +00006236 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00006237
danielk1977003ba062004-11-04 02:57:33 +00006238 /* Read the value of meta[3] from the database to determine where the
6239 ** root page of the new table should go. meta[3] is the largest root-page
6240 ** created so far, so the new root-page is (meta[3]+1).
6241 */
danielk1977aef0bf62005-12-30 16:28:01 +00006242 rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
drhd677b3d2007-08-20 22:48:41 +00006243 if( rc!=SQLITE_OK ){
6244 return rc;
6245 }
danielk1977003ba062004-11-04 02:57:33 +00006246 pgnoRoot++;
6247
danielk1977599fcba2004-11-08 07:13:13 +00006248 /* The new root-page may not be allocated on a pointer-map page, or the
6249 ** PENDING_BYTE page.
6250 */
drh72190432008-01-31 14:54:43 +00006251 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00006252 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00006253 pgnoRoot++;
6254 }
6255 assert( pgnoRoot>=3 );
6256
6257 /* Allocate a page. The page that currently resides at pgnoRoot will
6258 ** be moved to the allocated page (unless the allocated page happens
6259 ** to reside at pgnoRoot).
6260 */
drh4f0c5872007-03-26 22:05:01 +00006261 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00006262 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00006263 return rc;
6264 }
danielk1977003ba062004-11-04 02:57:33 +00006265
6266 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00006267 /* pgnoRoot is the page that will be used for the root-page of
6268 ** the new table (assuming an error did not occur). But we were
6269 ** allocated pgnoMove. If required (i.e. if it was not allocated
6270 ** by extending the file), the current page at position pgnoMove
6271 ** is already journaled.
6272 */
danielk1977003ba062004-11-04 02:57:33 +00006273 u8 eType;
6274 Pgno iPtrPage;
6275
6276 releasePage(pPageMove);
danielk1977f35843b2007-04-07 15:03:17 +00006277
6278 /* Move the page currently at pgnoRoot to pgnoMove. */
drh16a9b832007-05-05 18:39:25 +00006279 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006280 if( rc!=SQLITE_OK ){
6281 return rc;
6282 }
6283 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drhccae6022005-02-26 17:31:26 +00006284 if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00006285 releasePage(pRoot);
6286 return rc;
6287 }
drhccae6022005-02-26 17:31:26 +00006288 assert( eType!=PTRMAP_ROOTPAGE );
6289 assert( eType!=PTRMAP_FREEPAGE );
danielk19773b8a05f2007-03-19 17:44:26 +00006290 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk19775fd057a2005-03-09 13:09:43 +00006291 if( rc!=SQLITE_OK ){
6292 releasePage(pRoot);
6293 return rc;
6294 }
danielk19774c999992008-07-16 18:17:55 +00006295 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
danielk1977003ba062004-11-04 02:57:33 +00006296 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00006297
6298 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00006299 if( rc!=SQLITE_OK ){
6300 return rc;
6301 }
drh16a9b832007-05-05 18:39:25 +00006302 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006303 if( rc!=SQLITE_OK ){
6304 return rc;
6305 }
danielk19773b8a05f2007-03-19 17:44:26 +00006306 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00006307 if( rc!=SQLITE_OK ){
6308 releasePage(pRoot);
6309 return rc;
6310 }
6311 }else{
6312 pRoot = pPageMove;
6313 }
6314
danielk197742741be2005-01-08 12:42:39 +00006315 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00006316 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
6317 if( rc ){
6318 releasePage(pRoot);
6319 return rc;
6320 }
danielk1977aef0bf62005-12-30 16:28:01 +00006321 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00006322 if( rc ){
6323 releasePage(pRoot);
6324 return rc;
6325 }
danielk197742741be2005-01-08 12:42:39 +00006326
danielk1977003ba062004-11-04 02:57:33 +00006327 }else{
drh4f0c5872007-03-26 22:05:01 +00006328 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00006329 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00006330 }
6331#endif
danielk19773b8a05f2007-03-19 17:44:26 +00006332 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhde647132004-05-07 17:57:49 +00006333 zeroPage(pRoot, flags | PTF_LEAF);
danielk19773b8a05f2007-03-19 17:44:26 +00006334 sqlite3PagerUnref(pRoot->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00006335 *piTable = (int)pgnoRoot;
6336 return SQLITE_OK;
6337}
drhd677b3d2007-08-20 22:48:41 +00006338int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
6339 int rc;
6340 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006341 p->pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006342 rc = btreeCreateTable(p, piTable, flags);
6343 sqlite3BtreeLeave(p);
6344 return rc;
6345}
drh8b2f49b2001-06-08 00:21:52 +00006346
6347/*
6348** Erase the given database page and all its children. Return
6349** the page to the freelist.
6350*/
drh4b70f112004-05-02 21:12:19 +00006351static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00006352 BtShared *pBt, /* The BTree that contains the table */
drh4b70f112004-05-02 21:12:19 +00006353 Pgno pgno, /* Page number to clear */
danielk1977c7af4842008-10-27 13:59:33 +00006354 int freePageFlag, /* Deallocate page if true */
6355 int *pnChange
drh4b70f112004-05-02 21:12:19 +00006356){
danielk19776b456a22005-03-21 04:04:02 +00006357 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00006358 int rc;
drh4b70f112004-05-02 21:12:19 +00006359 unsigned char *pCell;
6360 int i;
drh8b2f49b2001-06-08 00:21:52 +00006361
drh1fee73e2007-08-29 04:00:57 +00006362 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197789d40042008-11-17 14:20:56 +00006363 if( pgno>pagerPagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00006364 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00006365 }
6366
danielk197771d5d2c2008-09-29 11:49:47 +00006367 rc = getAndInitPage(pBt, pgno, &pPage);
danielk19776b456a22005-03-21 04:04:02 +00006368 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00006369 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00006370 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00006371 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00006372 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00006373 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006374 }
drh4b70f112004-05-02 21:12:19 +00006375 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00006376 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006377 }
drha34b6762004-05-07 13:30:42 +00006378 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00006379 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00006380 if( rc ) goto cleardatabasepage_out;
danielk1977c7af4842008-10-27 13:59:33 +00006381 }else if( pnChange ){
6382 assert( pPage->intKey );
6383 *pnChange += pPage->nCell;
drh2aa679f2001-06-25 02:11:07 +00006384 }
6385 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00006386 rc = freePage(pPage);
danielk19773b8a05f2007-03-19 17:44:26 +00006387 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
drh3a4c1412004-05-09 20:40:11 +00006388 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00006389 }
danielk19776b456a22005-03-21 04:04:02 +00006390
6391cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00006392 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00006393 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006394}
6395
6396/*
drhab01f612004-05-22 02:55:23 +00006397** Delete all information from a single table in the database. iTable is
6398** the page number of the root of the table. After this routine returns,
6399** the root page is empty, but still exists.
6400**
6401** This routine will fail with SQLITE_LOCKED if there are any open
6402** read cursors on the table. Open write cursors are moved to the
6403** root of the table.
danielk1977c7af4842008-10-27 13:59:33 +00006404**
6405** If pnChange is not NULL, then table iTable must be an intkey table. The
6406** integer value pointed to by pnChange is incremented by the number of
6407** entries in the table.
drh8b2f49b2001-06-08 00:21:52 +00006408*/
danielk1977c7af4842008-10-27 13:59:33 +00006409int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
drh8b2f49b2001-06-08 00:21:52 +00006410 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00006411 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00006412 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006413 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00006414 if( p->inTrans!=TRANS_WRITE ){
drhd677b3d2007-08-20 22:48:41 +00006415 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
danielk19773588ceb2008-06-10 17:30:26 +00006416 }else if( (rc = checkReadLocks(p, iTable, 0, 1))!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00006417 /* nothing to do */
6418 }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
6419 /* nothing to do */
6420 }else{
danielk197762c14b32008-11-19 09:05:26 +00006421 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
drh8b2f49b2001-06-08 00:21:52 +00006422 }
drhd677b3d2007-08-20 22:48:41 +00006423 sqlite3BtreeLeave(p);
6424 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006425}
6426
6427/*
6428** Erase all information in a table and add the root of the table to
6429** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00006430** page 1) is never added to the freelist.
6431**
6432** This routine will fail with SQLITE_LOCKED if there are any open
6433** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00006434**
6435** If AUTOVACUUM is enabled and the page at iTable is not the last
6436** root page in the database file, then the last root page
6437** in the database file is moved into the slot formerly occupied by
6438** iTable and that last slot formerly occupied by the last root page
6439** is added to the freelist instead of iTable. In this say, all
6440** root pages are kept at the beginning of the database file, which
6441** is necessary for AUTOVACUUM to work right. *piMoved is set to the
6442** page number that used to be the last root page in the file before
6443** the move. If no page gets moved, *piMoved is set to 0.
6444** The last root page is recorded in meta[3] and the value of
6445** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00006446*/
danielk197789d40042008-11-17 14:20:56 +00006447static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00006448 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00006449 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00006450 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00006451
drh1fee73e2007-08-29 04:00:57 +00006452 assert( sqlite3BtreeHoldsMutex(p) );
danielk1977aef0bf62005-12-30 16:28:01 +00006453 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00006454 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00006455 }
danielk1977a0bf2652004-11-04 14:30:04 +00006456
danielk1977e6efa742004-11-10 11:55:10 +00006457 /* It is illegal to drop a table if any cursors are open on the
6458 ** database. This is because in auto-vacuum mode the backend may
6459 ** need to move another root-page to fill a gap left by the deleted
6460 ** root page. If an open cursor was using this page a problem would
6461 ** occur.
6462 */
6463 if( pBt->pCursor ){
6464 return SQLITE_LOCKED;
drh5df72a52002-06-06 23:16:05 +00006465 }
danielk1977a0bf2652004-11-04 14:30:04 +00006466
drh16a9b832007-05-05 18:39:25 +00006467 rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00006468 if( rc ) return rc;
danielk1977c7af4842008-10-27 13:59:33 +00006469 rc = sqlite3BtreeClearTable(p, iTable, 0);
danielk19776b456a22005-03-21 04:04:02 +00006470 if( rc ){
6471 releasePage(pPage);
6472 return rc;
6473 }
danielk1977a0bf2652004-11-04 14:30:04 +00006474
drh205f48e2004-11-05 00:43:11 +00006475 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00006476
drh4b70f112004-05-02 21:12:19 +00006477 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00006478#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00006479 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00006480 releasePage(pPage);
6481#else
6482 if( pBt->autoVacuum ){
6483 Pgno maxRootPgno;
danielk1977aef0bf62005-12-30 16:28:01 +00006484 rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006485 if( rc!=SQLITE_OK ){
6486 releasePage(pPage);
6487 return rc;
6488 }
6489
6490 if( iTable==maxRootPgno ){
6491 /* If the table being dropped is the table with the largest root-page
6492 ** number in the database, put the root page on the free list.
6493 */
6494 rc = freePage(pPage);
6495 releasePage(pPage);
6496 if( rc!=SQLITE_OK ){
6497 return rc;
6498 }
6499 }else{
6500 /* The table being dropped does not have the largest root-page
6501 ** number in the database. So move the page that does into the
6502 ** gap left by the deleted root-page.
6503 */
6504 MemPage *pMove;
6505 releasePage(pPage);
drh16a9b832007-05-05 18:39:25 +00006506 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006507 if( rc!=SQLITE_OK ){
6508 return rc;
6509 }
danielk19774c999992008-07-16 18:17:55 +00006510 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006511 releasePage(pMove);
6512 if( rc!=SQLITE_OK ){
6513 return rc;
6514 }
drh16a9b832007-05-05 18:39:25 +00006515 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006516 if( rc!=SQLITE_OK ){
6517 return rc;
6518 }
6519 rc = freePage(pMove);
6520 releasePage(pMove);
6521 if( rc!=SQLITE_OK ){
6522 return rc;
6523 }
6524 *piMoved = maxRootPgno;
6525 }
6526
danielk1977599fcba2004-11-08 07:13:13 +00006527 /* Set the new 'max-root-page' value in the database header. This
6528 ** is the old value less one, less one more if that happens to
6529 ** be a root-page number, less one again if that is the
6530 ** PENDING_BYTE_PAGE.
6531 */
danielk197787a6e732004-11-05 12:58:25 +00006532 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00006533 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
6534 maxRootPgno--;
6535 }
danielk1977266664d2006-02-10 08:24:21 +00006536 if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00006537 maxRootPgno--;
6538 }
danielk1977599fcba2004-11-08 07:13:13 +00006539 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
6540
danielk1977aef0bf62005-12-30 16:28:01 +00006541 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006542 }else{
6543 rc = freePage(pPage);
6544 releasePage(pPage);
6545 }
6546#endif
drh2aa679f2001-06-25 02:11:07 +00006547 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00006548 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00006549 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00006550 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00006551 }
drh8b2f49b2001-06-08 00:21:52 +00006552 return rc;
6553}
drhd677b3d2007-08-20 22:48:41 +00006554int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
6555 int rc;
6556 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006557 p->pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006558 rc = btreeDropTable(p, iTable, piMoved);
6559 sqlite3BtreeLeave(p);
6560 return rc;
6561}
drh8b2f49b2001-06-08 00:21:52 +00006562
drh001bbcb2003-03-19 03:14:00 +00006563
drh8b2f49b2001-06-08 00:21:52 +00006564/*
drh23e11ca2004-05-04 17:27:28 +00006565** Read the meta-information out of a database file. Meta[0]
6566** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00006567** through meta[15] are available for use by higher layers. Meta[0]
6568** is read-only, the others are read/write.
6569**
6570** The schema layer numbers meta values differently. At the schema
6571** layer (and the SetCookie and ReadCookie opcodes) the number of
6572** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00006573*/
danielk1977aef0bf62005-12-30 16:28:01 +00006574int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
drh1bd10f82008-12-10 21:19:56 +00006575 DbPage *pDbPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00006576 int rc;
drh4b70f112004-05-02 21:12:19 +00006577 unsigned char *pP1;
danielk1977aef0bf62005-12-30 16:28:01 +00006578 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006579
drhd677b3d2007-08-20 22:48:41 +00006580 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006581 pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006582
danielk1977da184232006-01-05 11:34:32 +00006583 /* Reading a meta-data value requires a read-lock on page 1 (and hence
6584 ** the sqlite_master table. We grab this lock regardless of whether or
6585 ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
6586 ** 1 is treated as a special case by queryTableLock() and lockTable()).
6587 */
6588 rc = queryTableLock(p, 1, READ_LOCK);
6589 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00006590 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00006591 return rc;
6592 }
6593
drh23e11ca2004-05-04 17:27:28 +00006594 assert( idx>=0 && idx<=15 );
danielk1977d9f6c532008-09-19 16:39:38 +00006595 if( pBt->pPage1 ){
6596 /* The b-tree is already holding a reference to page 1 of the database
6597 ** file. In this case the required meta-data value can be read directly
6598 ** from the page data of this reference. This is slightly faster than
6599 ** requesting a new reference from the pager layer.
6600 */
6601 pP1 = (unsigned char *)pBt->pPage1->aData;
6602 }else{
6603 /* The b-tree does not have a reference to page 1 of the database file.
6604 ** Obtain one from the pager layer.
6605 */
danielk1977ea897302008-09-19 15:10:58 +00006606 rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
6607 if( rc ){
6608 sqlite3BtreeLeave(p);
6609 return rc;
6610 }
6611 pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
drhd677b3d2007-08-20 22:48:41 +00006612 }
drh23e11ca2004-05-04 17:27:28 +00006613 *pMeta = get4byte(&pP1[36 + idx*4]);
danielk1977ea897302008-09-19 15:10:58 +00006614
danielk1977d9f6c532008-09-19 16:39:38 +00006615 /* If the b-tree is not holding a reference to page 1, then one was
6616 ** requested from the pager layer in the above block. Release it now.
6617 */
danielk1977ea897302008-09-19 15:10:58 +00006618 if( !pBt->pPage1 ){
6619 sqlite3PagerUnref(pDbPage);
6620 }
drhae157872004-08-14 19:20:09 +00006621
danielk1977599fcba2004-11-08 07:13:13 +00006622 /* If autovacuumed is disabled in this build but we are trying to
6623 ** access an autovacuumed database, then make the database readonly.
6624 */
danielk1977003ba062004-11-04 02:57:33 +00006625#ifdef SQLITE_OMIT_AUTOVACUUM
drhae157872004-08-14 19:20:09 +00006626 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00006627#endif
drhae157872004-08-14 19:20:09 +00006628
danielk1977da184232006-01-05 11:34:32 +00006629 /* Grab the read-lock on page 1. */
6630 rc = lockTable(p, 1, READ_LOCK);
drhd677b3d2007-08-20 22:48:41 +00006631 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00006632 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006633}
6634
6635/*
drh23e11ca2004-05-04 17:27:28 +00006636** Write meta-information back into the database. Meta[0] is
6637** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00006638*/
danielk1977aef0bf62005-12-30 16:28:01 +00006639int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
6640 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00006641 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00006642 int rc;
drh23e11ca2004-05-04 17:27:28 +00006643 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00006644 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006645 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00006646 if( p->inTrans!=TRANS_WRITE ){
drhd677b3d2007-08-20 22:48:41 +00006647 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
6648 }else{
6649 assert( pBt->pPage1!=0 );
6650 pP1 = pBt->pPage1->aData;
6651 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6652 if( rc==SQLITE_OK ){
6653 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +00006654#ifndef SQLITE_OMIT_AUTOVACUUM
drhd677b3d2007-08-20 22:48:41 +00006655 if( idx==7 ){
6656 assert( pBt->autoVacuum || iMeta==0 );
6657 assert( iMeta==0 || iMeta==1 );
drhf49661a2008-12-10 16:45:50 +00006658 pBt->incrVacuum = (u8)iMeta;
drhd677b3d2007-08-20 22:48:41 +00006659 }
danielk19774152e672007-09-12 17:01:45 +00006660#endif
drhd677b3d2007-08-20 22:48:41 +00006661 }
drh5df72a52002-06-06 23:16:05 +00006662 }
drhd677b3d2007-08-20 22:48:41 +00006663 sqlite3BtreeLeave(p);
6664 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006665}
drh8c42ca92001-06-22 19:15:00 +00006666
drhf328bc82004-05-10 23:29:49 +00006667/*
6668** Return the flag byte at the beginning of the page that the cursor
6669** is currently pointing to.
6670*/
6671int sqlite3BtreeFlags(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00006672 /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
drha3460582008-07-11 21:02:53 +00006673 ** restoreCursorPosition() here.
danielk1977da184232006-01-05 11:34:32 +00006674 */
danielk1977e448dc42008-01-02 11:50:51 +00006675 MemPage *pPage;
drha3460582008-07-11 21:02:53 +00006676 restoreCursorPosition(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00006677 pPage = pCur->apPage[pCur->iPage];
drh1fee73e2007-08-29 04:00:57 +00006678 assert( cursorHoldsMutex(pCur) );
drhd0679ed2007-08-28 22:24:34 +00006679 assert( pPage->pBt==pCur->pBt );
drhf328bc82004-05-10 23:29:49 +00006680 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
6681}
6682
drhdd793422001-06-28 01:54:48 +00006683
drhdd793422001-06-28 01:54:48 +00006684/*
drh5eddca62001-06-30 21:53:53 +00006685** Return the pager associated with a BTree. This routine is used for
6686** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00006687*/
danielk1977aef0bf62005-12-30 16:28:01 +00006688Pager *sqlite3BtreePager(Btree *p){
6689 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00006690}
drh5eddca62001-06-30 21:53:53 +00006691
drhb7f91642004-10-31 02:22:47 +00006692#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006693/*
6694** Append a message to the error message string.
6695*/
drh2e38c322004-09-03 18:38:44 +00006696static void checkAppendMsg(
6697 IntegrityCk *pCheck,
6698 char *zMsg1,
6699 const char *zFormat,
6700 ...
6701){
6702 va_list ap;
drh1dcdbc02007-01-27 02:24:54 +00006703 if( !pCheck->mxErr ) return;
6704 pCheck->mxErr--;
6705 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00006706 va_start(ap, zFormat);
drhf089aa42008-07-08 19:34:06 +00006707 if( pCheck->errMsg.nChar ){
6708 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
drh5eddca62001-06-30 21:53:53 +00006709 }
drhf089aa42008-07-08 19:34:06 +00006710 if( zMsg1 ){
6711 sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
6712 }
6713 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
6714 va_end(ap);
drhc890fec2008-08-01 20:10:08 +00006715 if( pCheck->errMsg.mallocFailed ){
6716 pCheck->mallocFailed = 1;
6717 }
drh5eddca62001-06-30 21:53:53 +00006718}
drhb7f91642004-10-31 02:22:47 +00006719#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006720
drhb7f91642004-10-31 02:22:47 +00006721#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006722/*
6723** Add 1 to the reference count for page iPage. If this is the second
6724** reference to the page, add an error message to pCheck->zErrMsg.
6725** Return 1 if there are 2 ore more references to the page and 0 if
6726** if this is the first reference to the page.
6727**
6728** Also check that the page number is in bounds.
6729*/
danielk197789d40042008-11-17 14:20:56 +00006730static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00006731 if( iPage==0 ) return 1;
danielk197789d40042008-11-17 14:20:56 +00006732 if( iPage>pCheck->nPage ){
drh2e38c322004-09-03 18:38:44 +00006733 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006734 return 1;
6735 }
6736 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00006737 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006738 return 1;
6739 }
6740 return (pCheck->anRef[iPage]++)>1;
6741}
6742
danielk1977afcdd022004-10-31 16:25:42 +00006743#ifndef SQLITE_OMIT_AUTOVACUUM
6744/*
6745** Check that the entry in the pointer-map for page iChild maps to
6746** page iParent, pointer type ptrType. If not, append an error message
6747** to pCheck.
6748*/
6749static void checkPtrmap(
6750 IntegrityCk *pCheck, /* Integrity check context */
6751 Pgno iChild, /* Child page number */
6752 u8 eType, /* Expected pointer map type */
6753 Pgno iParent, /* Expected pointer map parent page number */
6754 char *zContext /* Context description (used for error msg) */
6755){
6756 int rc;
6757 u8 ePtrmapType;
6758 Pgno iPtrmapParent;
6759
6760 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
6761 if( rc!=SQLITE_OK ){
drhe43ba702008-12-05 22:40:08 +00006762 if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
danielk1977afcdd022004-10-31 16:25:42 +00006763 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
6764 return;
6765 }
6766
6767 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
6768 checkAppendMsg(pCheck, zContext,
6769 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
6770 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
6771 }
6772}
6773#endif
6774
drh5eddca62001-06-30 21:53:53 +00006775/*
6776** Check the integrity of the freelist or of an overflow page list.
6777** Verify that the number of pages on the list is N.
6778*/
drh30e58752002-03-02 20:41:57 +00006779static void checkList(
6780 IntegrityCk *pCheck, /* Integrity checking context */
6781 int isFreeList, /* True for a freelist. False for overflow page list */
6782 int iPage, /* Page number for first page in the list */
6783 int N, /* Expected number of pages in the list */
6784 char *zContext /* Context for error messages */
6785){
6786 int i;
drh3a4c1412004-05-09 20:40:11 +00006787 int expected = N;
6788 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00006789 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00006790 DbPage *pOvflPage;
6791 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00006792 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00006793 checkAppendMsg(pCheck, zContext,
6794 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00006795 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00006796 break;
6797 }
6798 if( checkRef(pCheck, iPage, zContext) ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00006799 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
drh2e38c322004-09-03 18:38:44 +00006800 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006801 break;
6802 }
danielk19773b8a05f2007-03-19 17:44:26 +00006803 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00006804 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00006805 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00006806#ifndef SQLITE_OMIT_AUTOVACUUM
6807 if( pCheck->pBt->autoVacuum ){
6808 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
6809 }
6810#endif
drh45b1fac2008-07-04 17:52:42 +00006811 if( n>pCheck->pBt->usableSize/4-2 ){
drh2e38c322004-09-03 18:38:44 +00006812 checkAppendMsg(pCheck, zContext,
6813 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00006814 N--;
6815 }else{
6816 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00006817 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00006818#ifndef SQLITE_OMIT_AUTOVACUUM
6819 if( pCheck->pBt->autoVacuum ){
6820 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
6821 }
6822#endif
6823 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00006824 }
6825 N -= n;
drh30e58752002-03-02 20:41:57 +00006826 }
drh30e58752002-03-02 20:41:57 +00006827 }
danielk1977afcdd022004-10-31 16:25:42 +00006828#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006829 else{
6830 /* If this database supports auto-vacuum and iPage is not the last
6831 ** page in this overflow list, check that the pointer-map entry for
6832 ** the following page matches iPage.
6833 */
6834 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00006835 i = get4byte(pOvflData);
danielk1977687566d2004-11-02 12:56:41 +00006836 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
6837 }
danielk1977afcdd022004-10-31 16:25:42 +00006838 }
6839#endif
danielk19773b8a05f2007-03-19 17:44:26 +00006840 iPage = get4byte(pOvflData);
6841 sqlite3PagerUnref(pOvflPage);
drh5eddca62001-06-30 21:53:53 +00006842 }
6843}
drhb7f91642004-10-31 02:22:47 +00006844#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006845
drhb7f91642004-10-31 02:22:47 +00006846#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006847/*
6848** Do various sanity checks on a single page of a tree. Return
6849** the tree depth. Root pages return 0. Parents of root pages
6850** return 1, and so forth.
6851**
6852** These checks are done:
6853**
6854** 1. Make sure that cells and freeblocks do not overlap
6855** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00006856** NO 2. Make sure cell keys are in order.
6857** NO 3. Make sure no key is less than or equal to zLowerBound.
6858** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00006859** 5. Check the integrity of overflow pages.
6860** 6. Recursively call checkTreePage on all children.
6861** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00006862** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00006863** the root of the tree.
6864*/
6865static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00006866 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00006867 int iPage, /* Page number of the page to check */
drh74161702006-02-24 02:53:49 +00006868 char *zParentContext /* Parent context */
drh5eddca62001-06-30 21:53:53 +00006869){
6870 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00006871 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00006872 int hdr, cellStart;
6873 int nCell;
drhda200cc2004-05-09 11:51:38 +00006874 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00006875 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00006876 int usableSize;
drh5eddca62001-06-30 21:53:53 +00006877 char zContext[100];
shane0af3f892008-11-12 04:55:34 +00006878 char *hit = 0;
drh5eddca62001-06-30 21:53:53 +00006879
drh5bb3eb92007-05-04 13:15:55 +00006880 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
danielk1977ef73ee92004-11-06 12:26:07 +00006881
drh5eddca62001-06-30 21:53:53 +00006882 /* Check that the page exists
6883 */
drhd9cb6ac2005-10-20 07:28:17 +00006884 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00006885 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00006886 if( iPage==0 ) return 0;
6887 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh16a9b832007-05-05 18:39:25 +00006888 if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drhe43ba702008-12-05 22:40:08 +00006889 if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
drh2e38c322004-09-03 18:38:44 +00006890 checkAppendMsg(pCheck, zContext,
6891 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00006892 return 0;
6893 }
danielk197771d5d2c2008-09-29 11:49:47 +00006894 if( (rc = sqlite3BtreeInitPage(pPage))!=0 ){
drhe43ba702008-12-05 22:40:08 +00006895 if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
drh16a9b832007-05-05 18:39:25 +00006896 checkAppendMsg(pCheck, zContext,
6897 "sqlite3BtreeInitPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00006898 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00006899 return 0;
6900 }
6901
6902 /* Check out all the cells.
6903 */
6904 depth = 0;
drh1dcdbc02007-01-27 02:24:54 +00006905 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
drh6f11bef2004-05-13 01:12:56 +00006906 u8 *pCell;
danielk197789d40042008-11-17 14:20:56 +00006907 u32 sz;
drh6f11bef2004-05-13 01:12:56 +00006908 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00006909
6910 /* Check payload overflow pages
6911 */
drh5bb3eb92007-05-04 13:15:55 +00006912 sqlite3_snprintf(sizeof(zContext), zContext,
6913 "On tree page %d cell %d: ", iPage, i);
danielk19771cc5ed82007-05-16 17:28:43 +00006914 pCell = findCell(pPage,i);
drh16a9b832007-05-05 18:39:25 +00006915 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00006916 sz = info.nData;
drhf49661a2008-12-10 16:45:50 +00006917 if( !pPage->intKey ) sz += (int)info.nKey;
drh72365832007-03-06 15:53:44 +00006918 assert( sz==info.nPayload );
drh6f11bef2004-05-13 01:12:56 +00006919 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00006920 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00006921 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
6922#ifndef SQLITE_OMIT_AUTOVACUUM
6923 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006924 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00006925 }
6926#endif
6927 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00006928 }
6929
6930 /* Check sanity of left child page.
6931 */
drhda200cc2004-05-09 11:51:38 +00006932 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006933 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00006934#ifndef SQLITE_OMIT_AUTOVACUUM
6935 if( pBt->autoVacuum ){
6936 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
6937 }
6938#endif
danielk197762c14b32008-11-19 09:05:26 +00006939 d2 = checkTreePage(pCheck, pgno, zContext);
drhda200cc2004-05-09 11:51:38 +00006940 if( i>0 && d2!=depth ){
6941 checkAppendMsg(pCheck, zContext, "Child page depth differs");
6942 }
6943 depth = d2;
drh5eddca62001-06-30 21:53:53 +00006944 }
drh5eddca62001-06-30 21:53:53 +00006945 }
drhda200cc2004-05-09 11:51:38 +00006946 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006947 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh5bb3eb92007-05-04 13:15:55 +00006948 sqlite3_snprintf(sizeof(zContext), zContext,
6949 "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00006950#ifndef SQLITE_OMIT_AUTOVACUUM
6951 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006952 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00006953 }
6954#endif
danielk197762c14b32008-11-19 09:05:26 +00006955 checkTreePage(pCheck, pgno, zContext);
drhda200cc2004-05-09 11:51:38 +00006956 }
drh5eddca62001-06-30 21:53:53 +00006957
6958 /* Check for complete coverage of the page
6959 */
drhda200cc2004-05-09 11:51:38 +00006960 data = pPage->aData;
6961 hdr = pPage->hdrOffset;
drhf7141992008-06-19 00:16:08 +00006962 hit = sqlite3PageMalloc( pBt->pageSize );
drhc890fec2008-08-01 20:10:08 +00006963 if( hit==0 ){
6964 pCheck->mallocFailed = 1;
6965 }else{
shane5780ebd2008-11-11 17:36:30 +00006966 u16 contentOffset = get2byte(&data[hdr+5]);
6967 if (contentOffset > usableSize) {
6968 checkAppendMsg(pCheck, 0,
6969 "Corruption detected in header on page %d",iPage,0);
shane0af3f892008-11-12 04:55:34 +00006970 goto check_page_abort;
shane5780ebd2008-11-11 17:36:30 +00006971 }
6972 memset(hit+contentOffset, 0, usableSize-contentOffset);
6973 memset(hit, 1, contentOffset);
drh2e38c322004-09-03 18:38:44 +00006974 nCell = get2byte(&data[hdr+3]);
6975 cellStart = hdr + 12 - 4*pPage->leaf;
6976 for(i=0; i<nCell; i++){
6977 int pc = get2byte(&data[cellStart+i*2]);
danielk1977daca5432008-08-25 11:57:16 +00006978 u16 size = 1024;
drh2e38c322004-09-03 18:38:44 +00006979 int j;
danielk1977daca5432008-08-25 11:57:16 +00006980 if( pc<=usableSize ){
6981 size = cellSizePtr(pPage, &data[pc]);
6982 }
danielk19777701e812005-01-10 12:59:51 +00006983 if( (pc+size-1)>=usableSize || pc<0 ){
6984 checkAppendMsg(pCheck, 0,
6985 "Corruption detected in cell %d on page %d",i,iPage,0);
6986 }else{
6987 for(j=pc+size-1; j>=pc; j--) hit[j]++;
6988 }
drh2e38c322004-09-03 18:38:44 +00006989 }
6990 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
6991 cnt++){
6992 int size = get2byte(&data[i+2]);
6993 int j;
danielk19777701e812005-01-10 12:59:51 +00006994 if( (i+size-1)>=usableSize || i<0 ){
6995 checkAppendMsg(pCheck, 0,
6996 "Corruption detected in cell %d on page %d",i,iPage,0);
6997 }else{
6998 for(j=i+size-1; j>=i; j--) hit[j]++;
6999 }
drh2e38c322004-09-03 18:38:44 +00007000 i = get2byte(&data[i]);
7001 }
7002 for(i=cnt=0; i<usableSize; i++){
7003 if( hit[i]==0 ){
7004 cnt++;
7005 }else if( hit[i]>1 ){
7006 checkAppendMsg(pCheck, 0,
7007 "Multiple uses for byte %d of page %d", i, iPage);
7008 break;
7009 }
7010 }
7011 if( cnt!=data[hdr+7] ){
7012 checkAppendMsg(pCheck, 0,
7013 "Fragmented space is %d byte reported as %d on page %d",
7014 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00007015 }
7016 }
shane0af3f892008-11-12 04:55:34 +00007017check_page_abort:
7018 if (hit) sqlite3PageFree(hit);
drh6019e162001-07-02 17:51:45 +00007019
drh4b70f112004-05-02 21:12:19 +00007020 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00007021 return depth+1;
drh5eddca62001-06-30 21:53:53 +00007022}
drhb7f91642004-10-31 02:22:47 +00007023#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00007024
drhb7f91642004-10-31 02:22:47 +00007025#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007026/*
7027** This routine does a complete check of the given BTree file. aRoot[] is
7028** an array of pages numbers were each page number is the root page of
7029** a table. nRoot is the number of entries in aRoot.
7030**
drhc890fec2008-08-01 20:10:08 +00007031** Write the number of error seen in *pnErr. Except for some memory
drhe43ba702008-12-05 22:40:08 +00007032** allocation errors, an error message held in memory obtained from
drhc890fec2008-08-01 20:10:08 +00007033** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
drhe43ba702008-12-05 22:40:08 +00007034** returned. If a memory allocation error occurs, NULL is returned.
drh5eddca62001-06-30 21:53:53 +00007035*/
drh1dcdbc02007-01-27 02:24:54 +00007036char *sqlite3BtreeIntegrityCheck(
7037 Btree *p, /* The btree to be checked */
7038 int *aRoot, /* An array of root pages numbers for individual trees */
7039 int nRoot, /* Number of entries in aRoot[] */
7040 int mxErr, /* Stop reporting errors after this many */
7041 int *pnErr /* Write number of errors seen to this variable */
7042){
danielk197789d40042008-11-17 14:20:56 +00007043 Pgno i;
drh5eddca62001-06-30 21:53:53 +00007044 int nRef;
drhaaab5722002-02-19 13:39:21 +00007045 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00007046 BtShared *pBt = p->pBt;
drhf089aa42008-07-08 19:34:06 +00007047 char zErr[100];
drh5eddca62001-06-30 21:53:53 +00007048
drhd677b3d2007-08-20 22:48:41 +00007049 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00007050 pBt->db = p->db;
danielk19773b8a05f2007-03-19 17:44:26 +00007051 nRef = sqlite3PagerRefcount(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00007052 if( lockBtreeWithRetry(p)!=SQLITE_OK ){
drhc890fec2008-08-01 20:10:08 +00007053 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00007054 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00007055 return sqlite3DbStrDup(0, "cannot acquire a read lock on the database");
drhefc251d2001-07-01 22:12:01 +00007056 }
drh5eddca62001-06-30 21:53:53 +00007057 sCheck.pBt = pBt;
7058 sCheck.pPager = pBt->pPager;
danielk197789d40042008-11-17 14:20:56 +00007059 sCheck.nPage = pagerPagecount(sCheck.pBt);
drh1dcdbc02007-01-27 02:24:54 +00007060 sCheck.mxErr = mxErr;
7061 sCheck.nErr = 0;
drhc890fec2008-08-01 20:10:08 +00007062 sCheck.mallocFailed = 0;
drh1dcdbc02007-01-27 02:24:54 +00007063 *pnErr = 0;
danielk1977e5321f02007-04-27 07:05:44 +00007064#ifndef SQLITE_OMIT_AUTOVACUUM
7065 if( pBt->nTrunc!=0 ){
7066 sCheck.nPage = pBt->nTrunc;
7067 }
7068#endif
drh0de8c112002-07-06 16:32:14 +00007069 if( sCheck.nPage==0 ){
7070 unlockBtreeIfUnused(pBt);
drhd677b3d2007-08-20 22:48:41 +00007071 sqlite3BtreeLeave(p);
drh0de8c112002-07-06 16:32:14 +00007072 return 0;
7073 }
drhe5ae5732008-06-15 02:51:47 +00007074 sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00007075 if( !sCheck.anRef ){
7076 unlockBtreeIfUnused(pBt);
drh1dcdbc02007-01-27 02:24:54 +00007077 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00007078 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00007079 return 0;
danielk1977ac245ec2005-01-14 13:50:11 +00007080 }
drhda200cc2004-05-09 11:51:38 +00007081 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00007082 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00007083 if( i<=sCheck.nPage ){
7084 sCheck.anRef[i] = 1;
7085 }
drhf089aa42008-07-08 19:34:06 +00007086 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
drh5eddca62001-06-30 21:53:53 +00007087
7088 /* Check the integrity of the freelist
7089 */
drha34b6762004-05-07 13:30:42 +00007090 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
7091 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00007092
7093 /* Check all the tables.
7094 */
danielk197789d40042008-11-17 14:20:56 +00007095 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
drh4ff6dfa2002-03-03 23:06:00 +00007096 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00007097#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00007098 if( pBt->autoVacuum && aRoot[i]>1 ){
7099 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
7100 }
7101#endif
danielk197762c14b32008-11-19 09:05:26 +00007102 checkTreePage(&sCheck, aRoot[i], "List of tree roots: ");
drh5eddca62001-06-30 21:53:53 +00007103 }
7104
7105 /* Make sure every page in the file is referenced
7106 */
drh1dcdbc02007-01-27 02:24:54 +00007107 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00007108#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00007109 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00007110 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00007111 }
danielk1977afcdd022004-10-31 16:25:42 +00007112#else
7113 /* If the database supports auto-vacuum, make sure no tables contain
7114 ** references to pointer-map pages.
7115 */
7116 if( sCheck.anRef[i]==0 &&
danielk1977266664d2006-02-10 08:24:21 +00007117 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00007118 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
7119 }
7120 if( sCheck.anRef[i]!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00007121 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00007122 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
7123 }
7124#endif
drh5eddca62001-06-30 21:53:53 +00007125 }
7126
7127 /* Make sure this analysis did not leave any unref() pages
7128 */
drh5e00f6c2001-09-13 13:46:56 +00007129 unlockBtreeIfUnused(pBt);
danielk19773b8a05f2007-03-19 17:44:26 +00007130 if( nRef != sqlite3PagerRefcount(pBt->pPager) ){
drh2e38c322004-09-03 18:38:44 +00007131 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00007132 "Outstanding page count goes from %d to %d during this analysis",
danielk19773b8a05f2007-03-19 17:44:26 +00007133 nRef, sqlite3PagerRefcount(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00007134 );
drh5eddca62001-06-30 21:53:53 +00007135 }
7136
7137 /* Clean up and report errors.
7138 */
drhd677b3d2007-08-20 22:48:41 +00007139 sqlite3BtreeLeave(p);
drh17435752007-08-16 04:30:38 +00007140 sqlite3_free(sCheck.anRef);
drhc890fec2008-08-01 20:10:08 +00007141 if( sCheck.mallocFailed ){
7142 sqlite3StrAccumReset(&sCheck.errMsg);
7143 *pnErr = sCheck.nErr+1;
7144 return 0;
7145 }
drh1dcdbc02007-01-27 02:24:54 +00007146 *pnErr = sCheck.nErr;
drhf089aa42008-07-08 19:34:06 +00007147 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
7148 return sqlite3StrAccumFinish(&sCheck.errMsg);
drh5eddca62001-06-30 21:53:53 +00007149}
drhb7f91642004-10-31 02:22:47 +00007150#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00007151
drh73509ee2003-04-06 20:44:45 +00007152/*
7153** Return the full pathname of the underlying database file.
drhd0679ed2007-08-28 22:24:34 +00007154**
7155** The pager filename is invariant as long as the pager is
7156** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +00007157*/
danielk1977aef0bf62005-12-30 16:28:01 +00007158const char *sqlite3BtreeGetFilename(Btree *p){
7159 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007160 return sqlite3PagerFilename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00007161}
7162
7163/*
danielk19775865e3d2004-06-14 06:03:57 +00007164** Return the pathname of the directory that contains the database file.
drhd0679ed2007-08-28 22:24:34 +00007165**
7166** The pager directory name is invariant as long as the pager is
7167** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00007168*/
danielk1977aef0bf62005-12-30 16:28:01 +00007169const char *sqlite3BtreeGetDirname(Btree *p){
7170 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007171 return sqlite3PagerDirname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00007172}
7173
7174/*
7175** Return the pathname of the journal file for this database. The return
7176** value of this routine is the same regardless of whether the journal file
7177** has been created or not.
drhd0679ed2007-08-28 22:24:34 +00007178**
7179** The pager journal filename is invariant as long as the pager is
7180** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00007181*/
danielk1977aef0bf62005-12-30 16:28:01 +00007182const char *sqlite3BtreeGetJournalname(Btree *p){
7183 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007184 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00007185}
7186
drhb7f91642004-10-31 02:22:47 +00007187#ifndef SQLITE_OMIT_VACUUM
danielk19775865e3d2004-06-14 06:03:57 +00007188/*
drhf7c57532003-04-25 13:22:51 +00007189** Copy the complete content of pBtFrom into pBtTo. A transaction
7190** must be active for both files.
7191**
danielk1977f653d782008-03-20 11:04:21 +00007192** The size of file pTo may be reduced by this operation.
7193** If anything goes wrong, the transaction on pTo is rolled back.
7194**
7195** If successful, CommitPhaseOne() may be called on pTo before returning.
7196** The caller should finish committing the transaction on pTo by calling
7197** sqlite3BtreeCommit().
drh73509ee2003-04-06 20:44:45 +00007198*/
drhd677b3d2007-08-20 22:48:41 +00007199static int btreeCopyFile(Btree *pTo, Btree *pFrom){
drhf7c57532003-04-25 13:22:51 +00007200 int rc = SQLITE_OK;
danielk1977f653d782008-03-20 11:04:21 +00007201 Pgno i;
7202
7203 Pgno nFromPage; /* Number of pages in pFrom */
7204 Pgno nToPage; /* Number of pages in pTo */
7205 Pgno nNewPage; /* Number of pages in pTo after the copy */
7206
7207 Pgno iSkip; /* Pending byte page in pTo */
7208 int nToPageSize; /* Page size of pTo in bytes */
7209 int nFromPageSize; /* Page size of pFrom in bytes */
drhf7c57532003-04-25 13:22:51 +00007210
danielk1977aef0bf62005-12-30 16:28:01 +00007211 BtShared *pBtTo = pTo->pBt;
7212 BtShared *pBtFrom = pFrom->pBt;
drhe5fe6902007-12-07 18:55:28 +00007213 pBtTo->db = pTo->db;
7214 pBtFrom->db = pFrom->db;
danielk1977f653d782008-03-20 11:04:21 +00007215
7216 nToPageSize = pBtTo->pageSize;
7217 nFromPageSize = pBtFrom->pageSize;
danielk1977aef0bf62005-12-30 16:28:01 +00007218
7219 if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
danielk1977ee5741e2004-05-31 10:01:34 +00007220 return SQLITE_ERROR;
7221 }
danielk1977f653d782008-03-20 11:04:21 +00007222 if( pBtTo->pCursor ){
7223 return SQLITE_BUSY;
drhf7c57532003-04-25 13:22:51 +00007224 }
drh538f5702007-04-13 02:14:30 +00007225
danielk197789d40042008-11-17 14:20:56 +00007226 nToPage = pagerPagecount(pBtTo);
7227 nFromPage = pagerPagecount(pBtFrom);
danielk1977f653d782008-03-20 11:04:21 +00007228 iSkip = PENDING_BYTE_PAGE(pBtTo);
7229
7230 /* Variable nNewPage is the number of pages required to store the
7231 ** contents of pFrom using the current page-size of pTo.
drh538f5702007-04-13 02:14:30 +00007232 */
drhf49661a2008-12-10 16:45:50 +00007233 nNewPage = (Pgno)
7234 (((i64)nFromPage*(i64)nFromPageSize+(i64)nToPageSize-1)/(i64)nToPageSize);
danielk1977f653d782008-03-20 11:04:21 +00007235
7236 for(i=1; rc==SQLITE_OK && (i<=nToPage || i<=nNewPage); i++){
7237
7238 /* Journal the original page.
7239 **
7240 ** iSkip is the page number of the locking page (PENDING_BYTE_PAGE)
7241 ** in database *pTo (before the copy). This page is never written
7242 ** into the journal file. Unless i==iSkip or the page was not
7243 ** present in pTo before the copy operation, journal page i from pTo.
7244 */
7245 if( i!=iSkip && i<=nToPage ){
danielk19774abd5442008-05-05 15:26:50 +00007246 DbPage *pDbPage = 0;
danielk1977f653d782008-03-20 11:04:21 +00007247 rc = sqlite3PagerGet(pBtTo->pPager, i, &pDbPage);
danielk19774abd5442008-05-05 15:26:50 +00007248 if( rc==SQLITE_OK ){
7249 rc = sqlite3PagerWrite(pDbPage);
danielk1977df2566a2008-05-07 19:11:03 +00007250 if( rc==SQLITE_OK && i>nFromPage ){
7251 /* Yeah. It seems wierd to call DontWrite() right after Write(). But
7252 ** that is because the names of those procedures do not exactly
7253 ** represent what they do. Write() really means "put this page in the
7254 ** rollback journal and mark it as dirty so that it will be written
7255 ** to the database file later." DontWrite() undoes the second part of
7256 ** that and prevents the page from being written to the database. The
7257 ** page is still on the rollback journal, though. And that is the
7258 ** whole point of this block: to put pages on the rollback journal.
7259 */
danielk1977a1fa00d2008-08-27 15:16:33 +00007260 rc = sqlite3PagerDontWrite(pDbPage);
danielk1977df2566a2008-05-07 19:11:03 +00007261 }
7262 sqlite3PagerUnref(pDbPage);
danielk1977f653d782008-03-20 11:04:21 +00007263 }
danielk1977f653d782008-03-20 11:04:21 +00007264 }
7265
7266 /* Overwrite the data in page i of the target database */
7267 if( rc==SQLITE_OK && i!=iSkip && i<=nNewPage ){
7268
7269 DbPage *pToPage = 0;
7270 sqlite3_int64 iOff;
7271
7272 rc = sqlite3PagerGet(pBtTo->pPager, i, &pToPage);
7273 if( rc==SQLITE_OK ){
7274 rc = sqlite3PagerWrite(pToPage);
7275 }
7276
7277 for(
7278 iOff=(i-1)*nToPageSize;
7279 rc==SQLITE_OK && iOff<i*nToPageSize;
7280 iOff += nFromPageSize
7281 ){
7282 DbPage *pFromPage = 0;
drhf49661a2008-12-10 16:45:50 +00007283 Pgno iFrom = (Pgno)(iOff/nFromPageSize)+1;
danielk1977f653d782008-03-20 11:04:21 +00007284
7285 if( iFrom==PENDING_BYTE_PAGE(pBtFrom) ){
7286 continue;
7287 }
7288
7289 rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
7290 if( rc==SQLITE_OK ){
7291 char *zTo = sqlite3PagerGetData(pToPage);
7292 char *zFrom = sqlite3PagerGetData(pFromPage);
7293 int nCopy;
7294
7295 if( nFromPageSize>=nToPageSize ){
7296 zFrom += ((i-1)*nToPageSize - ((iFrom-1)*nFromPageSize));
7297 nCopy = nToPageSize;
7298 }else{
7299 zTo += (((iFrom-1)*nFromPageSize) - (i-1)*nToPageSize);
7300 nCopy = nFromPageSize;
7301 }
7302
7303 memcpy(zTo, zFrom, nCopy);
danielk19772f78fc62008-09-30 09:31:45 +00007304 sqlite3PagerUnref(pFromPage);
danielk1977f653d782008-03-20 11:04:21 +00007305 }
7306 }
7307
danielk1977eaa06f62008-09-18 17:34:44 +00007308 if( pToPage ){
7309 MemPage *p = (MemPage *)sqlite3PagerGetExtra(pToPage);
7310 p->isInit = 0;
7311 sqlite3PagerUnref(pToPage);
7312 }
danielk1977f653d782008-03-20 11:04:21 +00007313 }
drh2e6d11b2003-04-25 15:37:57 +00007314 }
danielk1977f653d782008-03-20 11:04:21 +00007315
7316 /* If things have worked so far, the database file may need to be
7317 ** truncated. The complex part is that it may need to be truncated to
7318 ** a size that is not an integer multiple of nToPageSize - the current
7319 ** page size used by the pager associated with B-Tree pTo.
7320 **
7321 ** For example, say the page-size of pTo is 2048 bytes and the original
7322 ** number of pages is 5 (10 KB file). If pFrom has a page size of 1024
7323 ** bytes and 9 pages, then the file needs to be truncated to 9KB.
7324 */
7325 if( rc==SQLITE_OK ){
7326 if( nFromPageSize!=nToPageSize ){
7327 sqlite3_file *pFile = sqlite3PagerFile(pBtTo->pPager);
7328 i64 iSize = (i64)nFromPageSize * (i64)nFromPage;
7329 i64 iNow = (i64)((nToPage>nNewPage)?nToPage:nNewPage) * (i64)nToPageSize;
7330 i64 iPending = ((i64)PENDING_BYTE_PAGE(pBtTo)-1) *(i64)nToPageSize;
7331
7332 assert( iSize<=iNow );
7333
7334 /* Commit phase one syncs the journal file associated with pTo
7335 ** containing the original data. It does not sync the database file
7336 ** itself. After doing this it is safe to use OsTruncate() and other
7337 ** file APIs on the database file directly.
7338 */
7339 pBtTo->db = pTo->db;
7340 rc = sqlite3PagerCommitPhaseOne(pBtTo->pPager, 0, 0, 1);
7341 if( iSize<iNow && rc==SQLITE_OK ){
7342 rc = sqlite3OsTruncate(pFile, iSize);
7343 }
7344
7345 /* The loop that copied data from database pFrom to pTo did not
7346 ** populate the locking page of database pTo. If the page-size of
7347 ** pFrom is smaller than that of pTo, this means some data will
7348 ** not have been copied.
7349 **
7350 ** This block copies the missing data from database pFrom to pTo
7351 ** using file APIs. This is safe because at this point we know that
7352 ** all of the original data from pTo has been synced into the
7353 ** journal file. At this point it would be safe to do anything at
7354 ** all to the database file except truncate it to zero bytes.
7355 */
7356 if( rc==SQLITE_OK && nFromPageSize<nToPageSize && iSize>iPending){
7357 i64 iOff;
7358 for(
7359 iOff=iPending;
7360 rc==SQLITE_OK && iOff<(iPending+nToPageSize);
7361 iOff += nFromPageSize
7362 ){
7363 DbPage *pFromPage = 0;
drhf49661a2008-12-10 16:45:50 +00007364 Pgno iFrom = (Pgno)(iOff/nFromPageSize)+1;
danielk1977f653d782008-03-20 11:04:21 +00007365
7366 if( iFrom==PENDING_BYTE_PAGE(pBtFrom) || iFrom>nFromPage ){
7367 continue;
7368 }
7369
7370 rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
7371 if( rc==SQLITE_OK ){
7372 char *zFrom = sqlite3PagerGetData(pFromPage);
danielk197706249db2008-08-23 16:17:55 +00007373 rc = sqlite3OsWrite(pFile, zFrom, nFromPageSize, iOff);
danielk1977f653d782008-03-20 11:04:21 +00007374 sqlite3PagerUnref(pFromPage);
7375 }
7376 }
7377 }
7378
7379 /* Sync the database file */
7380 if( rc==SQLITE_OK ){
7381 rc = sqlite3PagerSync(pBtTo->pPager);
7382 }
7383 }else{
7384 rc = sqlite3PagerTruncate(pBtTo->pPager, nNewPage);
7385 }
7386 if( rc==SQLITE_OK ){
7387 pBtTo->pageSizeFixed = 0;
7388 }
drh2e6d11b2003-04-25 15:37:57 +00007389 }
drh538f5702007-04-13 02:14:30 +00007390
drhf7c57532003-04-25 13:22:51 +00007391 if( rc ){
danielk1977aef0bf62005-12-30 16:28:01 +00007392 sqlite3BtreeRollback(pTo);
drhf7c57532003-04-25 13:22:51 +00007393 }
danielk1977f653d782008-03-20 11:04:21 +00007394
drhf7c57532003-04-25 13:22:51 +00007395 return rc;
drh73509ee2003-04-06 20:44:45 +00007396}
drhd677b3d2007-08-20 22:48:41 +00007397int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
7398 int rc;
7399 sqlite3BtreeEnter(pTo);
7400 sqlite3BtreeEnter(pFrom);
7401 rc = btreeCopyFile(pTo, pFrom);
7402 sqlite3BtreeLeave(pFrom);
7403 sqlite3BtreeLeave(pTo);
7404 return rc;
7405}
7406
drhb7f91642004-10-31 02:22:47 +00007407#endif /* SQLITE_OMIT_VACUUM */
danielk19771d850a72004-05-31 08:26:49 +00007408
7409/*
7410** Return non-zero if a transaction is active.
7411*/
danielk1977aef0bf62005-12-30 16:28:01 +00007412int sqlite3BtreeIsInTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00007413 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00007414 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00007415}
7416
7417/*
7418** Return non-zero if a statement transaction is active.
7419*/
danielk1977aef0bf62005-12-30 16:28:01 +00007420int sqlite3BtreeIsInStmt(Btree *p){
drh1fee73e2007-08-29 04:00:57 +00007421 assert( sqlite3BtreeHoldsMutex(p) );
danielk1977aef0bf62005-12-30 16:28:01 +00007422 return (p->pBt && p->pBt->inStmt);
danielk19771d850a72004-05-31 08:26:49 +00007423}
danielk197713adf8a2004-06-03 16:08:41 +00007424
7425/*
danielk19772372c2b2006-06-27 16:34:56 +00007426** Return non-zero if a read (or write) transaction is active.
7427*/
7428int sqlite3BtreeIsInReadTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00007429 assert( sqlite3_mutex_held(p->db->mutex) );
danielk19772372c2b2006-06-27 16:34:56 +00007430 return (p && (p->inTrans!=TRANS_NONE));
7431}
7432
7433/*
danielk1977da184232006-01-05 11:34:32 +00007434** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +00007435** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +00007436** purposes (for example, to store a high-level schema associated with
7437** the shared-btree). The btree layer manages reference counting issues.
7438**
7439** The first time this is called on a shared-btree, nBytes bytes of memory
7440** are allocated, zeroed, and returned to the caller. For each subsequent
7441** call the nBytes parameter is ignored and a pointer to the same blob
7442** of memory returned.
7443**
danielk1977171bfed2008-06-23 09:50:50 +00007444** If the nBytes parameter is 0 and the blob of memory has not yet been
7445** allocated, a null pointer is returned. If the blob has already been
7446** allocated, it is returned as normal.
7447**
danielk1977da184232006-01-05 11:34:32 +00007448** Just before the shared-btree is closed, the function passed as the
7449** xFree argument when the memory allocation was made is invoked on the
drh17435752007-08-16 04:30:38 +00007450** blob of allocated memory. This function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +00007451** on the memory, the btree layer does that.
7452*/
7453void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
7454 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +00007455 sqlite3BtreeEnter(p);
danielk1977171bfed2008-06-23 09:50:50 +00007456 if( !pBt->pSchema && nBytes ){
drh17435752007-08-16 04:30:38 +00007457 pBt->pSchema = sqlite3MallocZero(nBytes);
danielk1977da184232006-01-05 11:34:32 +00007458 pBt->xFreeSchema = xFree;
7459 }
drh27641702007-08-22 02:56:42 +00007460 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00007461 return pBt->pSchema;
7462}
7463
danielk1977c87d34d2006-01-06 13:00:28 +00007464/*
7465** Return true if another user of the same shared btree as the argument
7466** handle holds an exclusive lock on the sqlite_master table.
7467*/
7468int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +00007469 int rc;
drhe5fe6902007-12-07 18:55:28 +00007470 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +00007471 sqlite3BtreeEnter(p);
7472 rc = (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
7473 sqlite3BtreeLeave(p);
7474 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +00007475}
7476
drha154dcd2006-03-22 22:10:07 +00007477
7478#ifndef SQLITE_OMIT_SHARED_CACHE
7479/*
7480** Obtain a lock on the table whose root page is iTab. The
7481** lock is a write lock if isWritelock is true or a read lock
7482** if it is false.
7483*/
danielk1977c00da102006-01-07 13:21:04 +00007484int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00007485 int rc = SQLITE_OK;
drh6a9ad3d2008-04-02 16:29:30 +00007486 if( p->sharable ){
7487 u8 lockType = READ_LOCK + isWriteLock;
7488 assert( READ_LOCK+1==WRITE_LOCK );
7489 assert( isWriteLock==0 || isWriteLock==1 );
7490 sqlite3BtreeEnter(p);
7491 rc = queryTableLock(p, iTab, lockType);
7492 if( rc==SQLITE_OK ){
7493 rc = lockTable(p, iTab, lockType);
7494 }
7495 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +00007496 }
7497 return rc;
7498}
drha154dcd2006-03-22 22:10:07 +00007499#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00007500
danielk1977b4e9af92007-05-01 17:49:49 +00007501#ifndef SQLITE_OMIT_INCRBLOB
7502/*
7503** Argument pCsr must be a cursor opened for writing on an
7504** INTKEY table currently pointing at a valid table entry.
7505** This function modifies the data stored as part of that entry.
7506** Only the data content may only be modified, it is not possible
7507** to change the length of the data stored.
7508*/
danielk1977dcbb5d32007-05-04 18:36:44 +00007509int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
drh1fee73e2007-08-29 04:00:57 +00007510 assert( cursorHoldsMutex(pCsr) );
drhe5fe6902007-12-07 18:55:28 +00007511 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00007512 assert(pCsr->isIncrblobHandle);
danielk19773588ceb2008-06-10 17:30:26 +00007513
drha3460582008-07-11 21:02:53 +00007514 restoreCursorPosition(pCsr);
danielk19773588ceb2008-06-10 17:30:26 +00007515 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
7516 if( pCsr->eState!=CURSOR_VALID ){
7517 return SQLITE_ABORT;
danielk1977dcbb5d32007-05-04 18:36:44 +00007518 }
7519
danielk1977d04417962007-05-02 13:16:30 +00007520 /* Check some preconditions:
danielk1977dcbb5d32007-05-04 18:36:44 +00007521 ** (a) the cursor is open for writing,
7522 ** (b) there is no read-lock on the table being modified and
7523 ** (c) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00007524 */
danielk1977d04417962007-05-02 13:16:30 +00007525 if( !pCsr->wrFlag ){
danielk1977dcbb5d32007-05-04 18:36:44 +00007526 return SQLITE_READONLY;
danielk1977d04417962007-05-02 13:16:30 +00007527 }
drhd0679ed2007-08-28 22:24:34 +00007528 assert( !pCsr->pBt->readOnly
7529 && pCsr->pBt->inTransaction==TRANS_WRITE );
danielk19773588ceb2008-06-10 17:30:26 +00007530 if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr, 0) ){
danielk1977d04417962007-05-02 13:16:30 +00007531 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
7532 }
danielk197771d5d2c2008-09-29 11:49:47 +00007533 if( pCsr->eState==CURSOR_INVALID || !pCsr->apPage[pCsr->iPage]->intKey ){
danielk1977d04417962007-05-02 13:16:30 +00007534 return SQLITE_ERROR;
danielk1977b4e9af92007-05-01 17:49:49 +00007535 }
7536
danielk19779f8d6402007-05-02 17:48:45 +00007537 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00007538}
danielk19772dec9702007-05-02 16:48:37 +00007539
7540/*
7541** Set a flag on this cursor to cache the locations of pages from the
danielk1977da107192007-05-04 08:32:13 +00007542** overflow list for the current row. This is used by cursors opened
7543** for incremental blob IO only.
7544**
7545** This function sets a flag only. The actual page location cache
7546** (stored in BtCursor.aOverflow[]) is allocated and used by function
7547** accessPayload() (the worker function for sqlite3BtreeData() and
7548** sqlite3BtreePutData()).
danielk19772dec9702007-05-02 16:48:37 +00007549*/
7550void sqlite3BtreeCacheOverflow(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00007551 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00007552 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00007553 assert(!pCur->isIncrblobHandle);
danielk19772dec9702007-05-02 16:48:37 +00007554 assert(!pCur->aOverflow);
danielk1977dcbb5d32007-05-04 18:36:44 +00007555 pCur->isIncrblobHandle = 1;
danielk19772dec9702007-05-02 16:48:37 +00007556}
danielk1977b4e9af92007-05-01 17:49:49 +00007557#endif