blob: 2f14070622b04c28c8f9882c891a7aeecbe21d0a [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*************************************************************************
drha2c20e42008-03-29 16:01:04 +000012** $Id: btree.c,v 1.448 2008/03/29 16:01:04 drh Exp $
drh8b2f49b2001-06-08 00:21:52 +000013**
14** This file implements a external (disk-based) database using BTrees.
drha3152892007-05-05 11:48:52 +000015** See the header comment on "btreeInt.h" for additional information.
16** Including a description of file format and an overview of operation.
drha059ad02001-04-17 20:09:11 +000017*/
drha3152892007-05-05 11:48:52 +000018#include "btreeInt.h"
paulb95a8862003-04-01 21:16:41 +000019
drh8c42ca92001-06-22 19:15:00 +000020/*
drha3152892007-05-05 11:48:52 +000021** The header string that appears at the beginning of every
22** SQLite database.
drh556b2a22005-06-14 16:04:05 +000023*/
drh556b2a22005-06-14 16:04:05 +000024static const char zMagicHeader[] = SQLITE_FILE_HEADER;
drh08ed44e2001-04-29 23:32:55 +000025
drh8c42ca92001-06-22 19:15:00 +000026/*
drha3152892007-05-05 11:48:52 +000027** Set this global variable to 1 to enable tracing using the TRACE
28** macro.
drh615ae552005-01-16 23:21:00 +000029*/
30#if SQLITE_TEST
mlcreech3a00f902008-03-04 17:45:01 +000031int sqlite3BtreeTrace=0; /* True to enable tracing */
drh615ae552005-01-16 23:21:00 +000032#endif
drh615ae552005-01-16 23:21:00 +000033
drh86f8c192007-08-22 00:39:19 +000034
35
drhe53831d2007-08-17 01:14:38 +000036#ifndef SQLITE_OMIT_SHARED_CACHE
37/*
38** A flag to indicate whether or not shared cache is enabled. Also,
39** a list of BtShared objects that are eligible for participation
drhd677b3d2007-08-20 22:48:41 +000040** in shared cache. The variables have file scope during normal builds,
drh86f8c192007-08-22 00:39:19 +000041** but the test harness needs to access these variables so we make them
drhd677b3d2007-08-20 22:48:41 +000042** global for test builds.
drhe53831d2007-08-17 01:14:38 +000043*/
44#ifdef SQLITE_TEST
45BtShared *sqlite3SharedCacheList = 0;
46int sqlite3SharedCacheEnabled = 0;
47#else
48static BtShared *sqlite3SharedCacheList = 0;
49static int sqlite3SharedCacheEnabled = 0;
50#endif
drhe53831d2007-08-17 01:14:38 +000051#endif /* SQLITE_OMIT_SHARED_CACHE */
52
53#ifndef SQLITE_OMIT_SHARED_CACHE
54/*
55** Enable or disable the shared pager and schema features.
56**
57** This routine has no effect on existing database connections.
58** The shared cache setting effects only future calls to
59** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
60*/
61int sqlite3_enable_shared_cache(int enable){
62 sqlite3SharedCacheEnabled = enable;
63 return SQLITE_OK;
64}
65#endif
66
drhd677b3d2007-08-20 22:48:41 +000067
drh615ae552005-01-16 23:21:00 +000068/*
drh66cbd152004-09-01 16:12:25 +000069** Forward declaration
70*/
drh980b1a72006-08-16 16:42:48 +000071static int checkReadLocks(Btree*,Pgno,BtCursor*);
drh66cbd152004-09-01 16:12:25 +000072
danielk1977aef0bf62005-12-30 16:28:01 +000073
74#ifdef SQLITE_OMIT_SHARED_CACHE
75 /*
76 ** The functions queryTableLock(), lockTable() and unlockAllTables()
77 ** manipulate entries in the BtShared.pLock linked list used to store
78 ** shared-cache table level locks. If the library is compiled with the
79 ** shared-cache feature disabled, then there is only ever one user
danielk1977da184232006-01-05 11:34:32 +000080 ** of each BtShared structure and so this locking is not necessary.
81 ** So define the lock related functions as no-ops.
danielk1977aef0bf62005-12-30 16:28:01 +000082 */
83 #define queryTableLock(a,b,c) SQLITE_OK
84 #define lockTable(a,b,c) SQLITE_OK
danielk1977da184232006-01-05 11:34:32 +000085 #define unlockAllTables(a)
drhe53831d2007-08-17 01:14:38 +000086#endif
danielk1977aef0bf62005-12-30 16:28:01 +000087
drhe53831d2007-08-17 01:14:38 +000088#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977da184232006-01-05 11:34:32 +000089/*
danielk1977aef0bf62005-12-30 16:28:01 +000090** Query to see if btree handle p may obtain a lock of type eLock
91** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
92** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
danielk1977c87d34d2006-01-06 13:00:28 +000093** SQLITE_LOCKED if not.
danielk1977aef0bf62005-12-30 16:28:01 +000094*/
95static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
96 BtShared *pBt = p->pBt;
97 BtLock *pIter;
98
drh1fee73e2007-08-29 04:00:57 +000099 assert( sqlite3BtreeHoldsMutex(p) );
drhd677b3d2007-08-20 22:48:41 +0000100
danielk1977da184232006-01-05 11:34:32 +0000101 /* This is a no-op if the shared-cache is not enabled */
drhe53831d2007-08-17 01:14:38 +0000102 if( !p->sharable ){
danielk1977da184232006-01-05 11:34:32 +0000103 return SQLITE_OK;
104 }
105
danielk1977641b0f42007-12-21 04:47:25 +0000106 /* If some other connection is holding an exclusive lock, the
107 ** requested lock may not be obtained.
108 */
109 if( pBt->pExclusive && pBt->pExclusive!=p ){
110 return SQLITE_LOCKED;
111 }
112
danielk1977da184232006-01-05 11:34:32 +0000113 /* This (along with lockTable()) is where the ReadUncommitted flag is
114 ** dealt with. If the caller is querying for a read-lock and the flag is
115 ** set, it is unconditionally granted - even if there are write-locks
116 ** on the table. If a write-lock is requested, the ReadUncommitted flag
117 ** is not considered.
118 **
119 ** In function lockTable(), if a read-lock is demanded and the
120 ** ReadUncommitted flag is set, no entry is added to the locks list
121 ** (BtShared.pLock).
122 **
123 ** To summarize: If the ReadUncommitted flag is set, then read cursors do
124 ** not create or respect table locks. The locking procedure for a
125 ** write-cursor does not change.
126 */
127 if(
drhe5fe6902007-12-07 18:55:28 +0000128 !p->db ||
129 0==(p->db->flags&SQLITE_ReadUncommitted) ||
danielk1977da184232006-01-05 11:34:32 +0000130 eLock==WRITE_LOCK ||
drh47ded162006-01-06 01:42:58 +0000131 iTab==MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000132 ){
133 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
134 if( pIter->pBtree!=p && pIter->iTable==iTab &&
135 (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
danielk1977c87d34d2006-01-06 13:00:28 +0000136 return SQLITE_LOCKED;
danielk1977da184232006-01-05 11:34:32 +0000137 }
danielk1977aef0bf62005-12-30 16:28:01 +0000138 }
139 }
140 return SQLITE_OK;
141}
drhe53831d2007-08-17 01:14:38 +0000142#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000143
drhe53831d2007-08-17 01:14:38 +0000144#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000145/*
146** Add a lock on the table with root-page iTable to the shared-btree used
147** by Btree handle p. Parameter eLock must be either READ_LOCK or
148** WRITE_LOCK.
149**
150** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
151** SQLITE_NOMEM may also be returned.
152*/
153static int lockTable(Btree *p, Pgno iTable, u8 eLock){
154 BtShared *pBt = p->pBt;
155 BtLock *pLock = 0;
156 BtLock *pIter;
157
drh1fee73e2007-08-29 04:00:57 +0000158 assert( sqlite3BtreeHoldsMutex(p) );
drhd677b3d2007-08-20 22:48:41 +0000159
danielk1977da184232006-01-05 11:34:32 +0000160 /* This is a no-op if the shared-cache is not enabled */
drhe53831d2007-08-17 01:14:38 +0000161 if( !p->sharable ){
danielk1977da184232006-01-05 11:34:32 +0000162 return SQLITE_OK;
163 }
164
danielk1977aef0bf62005-12-30 16:28:01 +0000165 assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
166
danielk1977da184232006-01-05 11:34:32 +0000167 /* If the read-uncommitted flag is set and a read-lock is requested,
168 ** return early without adding an entry to the BtShared.pLock list. See
169 ** comment in function queryTableLock() for more info on handling
170 ** the ReadUncommitted flag.
171 */
172 if(
drhe5fe6902007-12-07 18:55:28 +0000173 (p->db) &&
174 (p->db->flags&SQLITE_ReadUncommitted) &&
danielk1977da184232006-01-05 11:34:32 +0000175 (eLock==READ_LOCK) &&
drh47ded162006-01-06 01:42:58 +0000176 iTable!=MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000177 ){
178 return SQLITE_OK;
179 }
180
danielk1977aef0bf62005-12-30 16:28:01 +0000181 /* First search the list for an existing lock on this table. */
182 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
183 if( pIter->iTable==iTable && pIter->pBtree==p ){
184 pLock = pIter;
185 break;
186 }
187 }
188
189 /* If the above search did not find a BtLock struct associating Btree p
190 ** with table iTable, allocate one and link it into the list.
191 */
192 if( !pLock ){
drh17435752007-08-16 04:30:38 +0000193 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
danielk1977aef0bf62005-12-30 16:28:01 +0000194 if( !pLock ){
195 return SQLITE_NOMEM;
196 }
197 pLock->iTable = iTable;
198 pLock->pBtree = p;
199 pLock->pNext = pBt->pLock;
200 pBt->pLock = pLock;
201 }
202
203 /* Set the BtLock.eLock variable to the maximum of the current lock
204 ** and the requested lock. This means if a write-lock was already held
205 ** and a read-lock requested, we don't incorrectly downgrade the lock.
206 */
207 assert( WRITE_LOCK>READ_LOCK );
danielk19775118b912005-12-30 16:31:53 +0000208 if( eLock>pLock->eLock ){
209 pLock->eLock = eLock;
210 }
danielk1977aef0bf62005-12-30 16:28:01 +0000211
212 return SQLITE_OK;
213}
drhe53831d2007-08-17 01:14:38 +0000214#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000215
drhe53831d2007-08-17 01:14:38 +0000216#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000217/*
218** Release all the table locks (locks obtained via calls to the lockTable()
219** procedure) held by Btree handle p.
220*/
221static void unlockAllTables(Btree *p){
danielk1977641b0f42007-12-21 04:47:25 +0000222 BtShared *pBt = p->pBt;
223 BtLock **ppIter = &pBt->pLock;
danielk1977da184232006-01-05 11:34:32 +0000224
drh1fee73e2007-08-29 04:00:57 +0000225 assert( sqlite3BtreeHoldsMutex(p) );
drhe53831d2007-08-17 01:14:38 +0000226 assert( p->sharable || 0==*ppIter );
danielk1977da184232006-01-05 11:34:32 +0000227
danielk1977aef0bf62005-12-30 16:28:01 +0000228 while( *ppIter ){
229 BtLock *pLock = *ppIter;
danielk1977641b0f42007-12-21 04:47:25 +0000230 assert( pBt->pExclusive==0 || pBt->pExclusive==pLock->pBtree );
danielk1977aef0bf62005-12-30 16:28:01 +0000231 if( pLock->pBtree==p ){
232 *ppIter = pLock->pNext;
drh17435752007-08-16 04:30:38 +0000233 sqlite3_free(pLock);
danielk1977aef0bf62005-12-30 16:28:01 +0000234 }else{
235 ppIter = &pLock->pNext;
236 }
237 }
danielk1977641b0f42007-12-21 04:47:25 +0000238
239 if( pBt->pExclusive==p ){
240 pBt->pExclusive = 0;
241 }
danielk1977aef0bf62005-12-30 16:28:01 +0000242}
243#endif /* SQLITE_OMIT_SHARED_CACHE */
244
drh980b1a72006-08-16 16:42:48 +0000245static void releasePage(MemPage *pPage); /* Forward reference */
246
drh1fee73e2007-08-29 04:00:57 +0000247/*
248** Verify that the cursor holds a mutex on the BtShared
249*/
250#ifndef NDEBUG
251static int cursorHoldsMutex(BtCursor *p){
drhff0587c2007-08-29 17:43:19 +0000252 return sqlite3_mutex_held(p->pBt->mutex);
drh1fee73e2007-08-29 04:00:57 +0000253}
254#endif
255
256
danielk197792d4d7a2007-05-04 12:05:56 +0000257#ifndef SQLITE_OMIT_INCRBLOB
258/*
259** Invalidate the overflow page-list cache for cursor pCur, if any.
260*/
261static void invalidateOverflowCache(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000262 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000263 sqlite3_free(pCur->aOverflow);
danielk197792d4d7a2007-05-04 12:05:56 +0000264 pCur->aOverflow = 0;
265}
266
267/*
268** Invalidate the overflow page-list cache for all cursors opened
269** on the shared btree structure pBt.
270*/
271static void invalidateAllOverflowCache(BtShared *pBt){
272 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000273 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +0000274 for(p=pBt->pCursor; p; p=p->pNext){
275 invalidateOverflowCache(p);
276 }
277}
278#else
279 #define invalidateOverflowCache(x)
280 #define invalidateAllOverflowCache(x)
281#endif
282
drh980b1a72006-08-16 16:42:48 +0000283/*
284** Save the current cursor position in the variables BtCursor.nKey
285** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
286*/
287static int saveCursorPosition(BtCursor *pCur){
288 int rc;
289
290 assert( CURSOR_VALID==pCur->eState );
291 assert( 0==pCur->pKey );
drh1fee73e2007-08-29 04:00:57 +0000292 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000293
294 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
295
296 /* If this is an intKey table, then the above call to BtreeKeySize()
297 ** stores the integer key in pCur->nKey. In this case this value is
298 ** all that is required. Otherwise, if pCur is not open on an intKey
299 ** table, then malloc space for and store the pCur->nKey bytes of key
300 ** data.
301 */
302 if( rc==SQLITE_OK && 0==pCur->pPage->intKey){
drh17435752007-08-16 04:30:38 +0000303 void *pKey = sqlite3_malloc(pCur->nKey);
drh980b1a72006-08-16 16:42:48 +0000304 if( pKey ){
305 rc = sqlite3BtreeKey(pCur, 0, pCur->nKey, pKey);
306 if( rc==SQLITE_OK ){
307 pCur->pKey = pKey;
308 }else{
drh17435752007-08-16 04:30:38 +0000309 sqlite3_free(pKey);
drh980b1a72006-08-16 16:42:48 +0000310 }
311 }else{
312 rc = SQLITE_NOMEM;
313 }
314 }
315 assert( !pCur->pPage->intKey || !pCur->pKey );
316
317 if( rc==SQLITE_OK ){
318 releasePage(pCur->pPage);
319 pCur->pPage = 0;
320 pCur->eState = CURSOR_REQUIRESEEK;
321 }
322
danielk197792d4d7a2007-05-04 12:05:56 +0000323 invalidateOverflowCache(pCur);
drh980b1a72006-08-16 16:42:48 +0000324 return rc;
325}
326
327/*
328** Save the positions of all cursors except pExcept open on the table
329** with root-page iRoot. Usually, this is called just before cursor
330** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
331*/
332static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
333 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000334 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +0000335 assert( pExcept==0 || pExcept->pBt==pBt );
drh980b1a72006-08-16 16:42:48 +0000336 for(p=pBt->pCursor; p; p=p->pNext){
337 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
338 p->eState==CURSOR_VALID ){
339 int rc = saveCursorPosition(p);
340 if( SQLITE_OK!=rc ){
341 return rc;
342 }
343 }
344 }
345 return SQLITE_OK;
346}
347
348/*
drhbf700f32007-03-31 02:36:44 +0000349** Clear the current cursor position.
350*/
351static void clearCursorPosition(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000352 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000353 sqlite3_free(pCur->pKey);
drhbf700f32007-03-31 02:36:44 +0000354 pCur->pKey = 0;
355 pCur->eState = CURSOR_INVALID;
356}
357
358/*
drh980b1a72006-08-16 16:42:48 +0000359** Restore the cursor to the position it was in (or as close to as possible)
360** when saveCursorPosition() was called. Note that this call deletes the
361** saved position info stored by saveCursorPosition(), so there can be
362** at most one effective restoreOrClearCursorPosition() call after each
363** saveCursorPosition().
364**
365** If the second argument argument - doSeek - is false, then instead of
drh85b623f2007-12-13 21:54:09 +0000366** returning the cursor to its saved position, any saved position is deleted
drh980b1a72006-08-16 16:42:48 +0000367** and the cursor state set to CURSOR_INVALID.
368*/
drh16a9b832007-05-05 18:39:25 +0000369int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +0000370 int rc;
drh1fee73e2007-08-29 04:00:57 +0000371 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +0000372 assert( pCur->eState>=CURSOR_REQUIRESEEK );
373 if( pCur->eState==CURSOR_FAULT ){
374 return pCur->skip;
375 }
danielk197732a0d8b2007-05-04 19:03:02 +0000376#ifndef SQLITE_OMIT_INCRBLOB
danielk1977dcbb5d32007-05-04 18:36:44 +0000377 if( pCur->isIncrblobHandle ){
378 return SQLITE_ABORT;
379 }
danielk197732a0d8b2007-05-04 19:03:02 +0000380#endif
drh980b1a72006-08-16 16:42:48 +0000381 pCur->eState = CURSOR_INVALID;
drhe14006d2008-03-25 17:23:32 +0000382 rc = sqlite3BtreeMoveto(pCur, pCur->pKey, 0, pCur->nKey, 0, &pCur->skip);
drh980b1a72006-08-16 16:42:48 +0000383 if( rc==SQLITE_OK ){
drh17435752007-08-16 04:30:38 +0000384 sqlite3_free(pCur->pKey);
drh980b1a72006-08-16 16:42:48 +0000385 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +0000386 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drh980b1a72006-08-16 16:42:48 +0000387 }
388 return rc;
389}
390
drhbf700f32007-03-31 02:36:44 +0000391#define restoreOrClearCursorPosition(p) \
drhfb982642007-08-30 01:19:59 +0000392 (p->eState>=CURSOR_REQUIRESEEK ? \
drh16a9b832007-05-05 18:39:25 +0000393 sqlite3BtreeRestoreOrClearCursorPosition(p) : \
394 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +0000395
danielk1977599fcba2004-11-08 07:13:13 +0000396#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000397/*
drha3152892007-05-05 11:48:52 +0000398** Given a page number of a regular database page, return the page
399** number for the pointer-map page that contains the entry for the
400** input page number.
danielk1977afcdd022004-10-31 16:25:42 +0000401*/
danielk1977266664d2006-02-10 08:24:21 +0000402static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
drhd677b3d2007-08-20 22:48:41 +0000403 int nPagesPerMapPage, iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +0000404 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000405 nPagesPerMapPage = (pBt->usableSize/5)+1;
406 iPtrMap = (pgno-2)/nPagesPerMapPage;
407 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +0000408 if( ret==PENDING_BYTE_PAGE(pBt) ){
409 ret++;
410 }
411 return ret;
412}
danielk1977a19df672004-11-03 11:37:07 +0000413
danielk1977afcdd022004-10-31 16:25:42 +0000414/*
danielk1977afcdd022004-10-31 16:25:42 +0000415** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000416**
417** This routine updates the pointer map entry for page number 'key'
418** so that it maps to type 'eType' and parent page number 'pgno'.
419** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000420*/
danielk1977aef0bf62005-12-30 16:28:01 +0000421static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
danielk19773b8a05f2007-03-19 17:44:26 +0000422 DbPage *pDbPage; /* The pointer map page */
423 u8 *pPtrmap; /* The pointer map data */
424 Pgno iPtrmap; /* The pointer map page number */
425 int offset; /* Offset in pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000426 int rc;
427
drh1fee73e2007-08-29 04:00:57 +0000428 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977266664d2006-02-10 08:24:21 +0000429 /* The master-journal page number must never be used as a pointer map page */
430 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
431
danielk1977ac11ee62005-01-15 12:45:51 +0000432 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000433 if( key==0 ){
drh49285702005-09-17 15:20:26 +0000434 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000435 }
danielk1977266664d2006-02-10 08:24:21 +0000436 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000437 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977687566d2004-11-02 12:56:41 +0000438 if( rc!=SQLITE_OK ){
danielk1977afcdd022004-10-31 16:25:42 +0000439 return rc;
440 }
danielk1977266664d2006-02-10 08:24:21 +0000441 offset = PTRMAP_PTROFFSET(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000442 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000443
drh615ae552005-01-16 23:21:00 +0000444 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
445 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
danielk19773b8a05f2007-03-19 17:44:26 +0000446 rc = sqlite3PagerWrite(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000447 if( rc==SQLITE_OK ){
448 pPtrmap[offset] = eType;
449 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000450 }
danielk1977afcdd022004-10-31 16:25:42 +0000451 }
452
danielk19773b8a05f2007-03-19 17:44:26 +0000453 sqlite3PagerUnref(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000454 return rc;
danielk1977afcdd022004-10-31 16:25:42 +0000455}
456
457/*
458** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000459**
460** This routine retrieves the pointer map entry for page 'key', writing
461** the type and parent page number to *pEType and *pPgno respectively.
462** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000463*/
danielk1977aef0bf62005-12-30 16:28:01 +0000464static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +0000465 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000466 int iPtrmap; /* Pointer map page index */
467 u8 *pPtrmap; /* Pointer map page data */
468 int offset; /* Offset of entry in pointer map */
469 int rc;
470
drh1fee73e2007-08-29 04:00:57 +0000471 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000472
danielk1977266664d2006-02-10 08:24:21 +0000473 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000474 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000475 if( rc!=0 ){
476 return rc;
477 }
danielk19773b8a05f2007-03-19 17:44:26 +0000478 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000479
danielk1977266664d2006-02-10 08:24:21 +0000480 offset = PTRMAP_PTROFFSET(pBt, key);
drh43617e92006-03-06 20:55:46 +0000481 assert( pEType!=0 );
482 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +0000483 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000484
danielk19773b8a05f2007-03-19 17:44:26 +0000485 sqlite3PagerUnref(pDbPage);
drh49285702005-09-17 15:20:26 +0000486 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000487 return SQLITE_OK;
488}
489
490#endif /* SQLITE_OMIT_AUTOVACUUM */
491
drh0d316a42002-08-11 20:10:47 +0000492/*
drh271efa52004-05-30 19:19:05 +0000493** Given a btree page and a cell index (0 means the first cell on
494** the page, 1 means the second cell, and so forth) return a pointer
495** to the cell content.
496**
497** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000498*/
danielk19771cc5ed82007-05-16 17:28:43 +0000499#define findCell(pPage, iCell) \
500 ((pPage)->aData + get2byte(&(pPage)->aData[(pPage)->cellOffset+2*(iCell)]))
drhe6e4d6b2007-08-05 23:52:05 +0000501#ifdef SQLITE_TEST
drh16a9b832007-05-05 18:39:25 +0000502u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell){
drh43605152004-05-29 21:46:49 +0000503 assert( iCell>=0 );
drh029f3f82007-06-20 15:14:10 +0000504 assert( iCell<get2byte(&pPage->aData[pPage->hdrOffset+3]) );
danielk19771cc5ed82007-05-16 17:28:43 +0000505 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000506}
drhe6e4d6b2007-08-05 23:52:05 +0000507#endif
drh43605152004-05-29 21:46:49 +0000508
509/*
drh16a9b832007-05-05 18:39:25 +0000510** This a more complex version of sqlite3BtreeFindCell() that works for
drh43605152004-05-29 21:46:49 +0000511** pages that do contain overflow cells. See insert
512*/
513static u8 *findOverflowCell(MemPage *pPage, int iCell){
514 int i;
drh1fee73e2007-08-29 04:00:57 +0000515 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +0000516 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000517 int k;
518 struct _OvflCell *pOvfl;
519 pOvfl = &pPage->aOvfl[i];
520 k = pOvfl->idx;
521 if( k<=iCell ){
522 if( k==iCell ){
523 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000524 }
525 iCell--;
526 }
527 }
danielk19771cc5ed82007-05-16 17:28:43 +0000528 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000529}
530
531/*
532** Parse a cell content block and fill in the CellInfo structure. There
drh16a9b832007-05-05 18:39:25 +0000533** are two versions of this function. sqlite3BtreeParseCell() takes a
534** cell index as the second argument and sqlite3BtreeParseCellPtr()
535** takes a pointer to the body of the cell as its second argument.
danielk19771cc5ed82007-05-16 17:28:43 +0000536**
537** Within this file, the parseCell() macro can be called instead of
538** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
drh43605152004-05-29 21:46:49 +0000539*/
drh16a9b832007-05-05 18:39:25 +0000540void sqlite3BtreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000541 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000542 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000543 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000544){
drh271efa52004-05-30 19:19:05 +0000545 int n; /* Number bytes in cell content header */
546 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000547
drh1fee73e2007-08-29 04:00:57 +0000548 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000549
drh43605152004-05-29 21:46:49 +0000550 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000551 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000552 n = pPage->childPtrSize;
553 assert( n==4-4*pPage->leaf );
drh8b18dd42004-05-12 19:18:15 +0000554 if( pPage->hasData ){
drh271efa52004-05-30 19:19:05 +0000555 n += getVarint32(&pCell[n], &nPayload);
drh8b18dd42004-05-12 19:18:15 +0000556 }else{
drh271efa52004-05-30 19:19:05 +0000557 nPayload = 0;
drh3aac2dd2004-04-26 14:10:20 +0000558 }
drh271efa52004-05-30 19:19:05 +0000559 pInfo->nData = nPayload;
drh504b6982006-01-22 21:52:56 +0000560 if( pPage->intKey ){
561 n += getVarint(&pCell[n], (u64 *)&pInfo->nKey);
562 }else{
563 u32 x;
564 n += getVarint32(&pCell[n], &x);
565 pInfo->nKey = x;
566 nPayload += x;
drh6f11bef2004-05-13 01:12:56 +0000567 }
drh72365832007-03-06 15:53:44 +0000568 pInfo->nPayload = nPayload;
drh504b6982006-01-22 21:52:56 +0000569 pInfo->nHeader = n;
drh271efa52004-05-30 19:19:05 +0000570 if( nPayload<=pPage->maxLocal ){
571 /* This is the (easy) common case where the entire payload fits
572 ** on the local page. No overflow is required.
573 */
574 int nSize; /* Total size of cell content in bytes */
drh6f11bef2004-05-13 01:12:56 +0000575 pInfo->nLocal = nPayload;
576 pInfo->iOverflow = 0;
drh271efa52004-05-30 19:19:05 +0000577 nSize = nPayload + n;
578 if( nSize<4 ){
579 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000580 }
drh271efa52004-05-30 19:19:05 +0000581 pInfo->nSize = nSize;
drh6f11bef2004-05-13 01:12:56 +0000582 }else{
drh271efa52004-05-30 19:19:05 +0000583 /* If the payload will not fit completely on the local page, we have
584 ** to decide how much to store locally and how much to spill onto
585 ** overflow pages. The strategy is to minimize the amount of unused
586 ** space on overflow pages while keeping the amount of local storage
587 ** in between minLocal and maxLocal.
588 **
589 ** Warning: changing the way overflow payload is distributed in any
590 ** way will result in an incompatible file format.
591 */
592 int minLocal; /* Minimum amount of payload held locally */
593 int maxLocal; /* Maximum amount of payload held locally */
594 int surplus; /* Overflow payload available for local storage */
595
596 minLocal = pPage->minLocal;
597 maxLocal = pPage->maxLocal;
598 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000599 if( surplus <= maxLocal ){
600 pInfo->nLocal = surplus;
601 }else{
602 pInfo->nLocal = minLocal;
603 }
604 pInfo->iOverflow = pInfo->nLocal + n;
605 pInfo->nSize = pInfo->iOverflow + 4;
606 }
drh3aac2dd2004-04-26 14:10:20 +0000607}
danielk19771cc5ed82007-05-16 17:28:43 +0000608#define parseCell(pPage, iCell, pInfo) \
609 sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
drh16a9b832007-05-05 18:39:25 +0000610void sqlite3BtreeParseCell(
drh43605152004-05-29 21:46:49 +0000611 MemPage *pPage, /* Page containing the cell */
612 int iCell, /* The cell index. First cell is 0 */
613 CellInfo *pInfo /* Fill in this structure */
614){
danielk19771cc5ed82007-05-16 17:28:43 +0000615 parseCell(pPage, iCell, pInfo);
drh43605152004-05-29 21:46:49 +0000616}
drh3aac2dd2004-04-26 14:10:20 +0000617
618/*
drh43605152004-05-29 21:46:49 +0000619** Compute the total number of bytes that a Cell needs in the cell
620** data area of the btree-page. The return number includes the cell
621** data header and the local payload, but not any overflow page or
622** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000623*/
danielk1977bc6ada42004-06-30 08:20:16 +0000624#ifndef NDEBUG
drha9121e42008-02-19 14:59:35 +0000625static u16 cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000626 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000627 sqlite3BtreeParseCell(pPage, iCell, &info);
drh43605152004-05-29 21:46:49 +0000628 return info.nSize;
629}
danielk1977bc6ada42004-06-30 08:20:16 +0000630#endif
drha9121e42008-02-19 14:59:35 +0000631static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
drh43605152004-05-29 21:46:49 +0000632 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000633 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000634 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000635}
636
danielk197779a40da2005-01-16 08:00:01 +0000637#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +0000638/*
danielk197726836652005-01-17 01:33:13 +0000639** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +0000640** to an overflow page, insert an entry into the pointer-map
641** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +0000642*/
danielk197726836652005-01-17 01:33:13 +0000643static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
danielk197779a40da2005-01-16 08:00:01 +0000644 if( pCell ){
645 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000646 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh72365832007-03-06 15:53:44 +0000647 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk197779a40da2005-01-16 08:00:01 +0000648 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
649 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
650 return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
651 }
danielk1977ac11ee62005-01-15 12:45:51 +0000652 }
danielk197779a40da2005-01-16 08:00:01 +0000653 return SQLITE_OK;
danielk1977ac11ee62005-01-15 12:45:51 +0000654}
danielk197726836652005-01-17 01:33:13 +0000655/*
656** If the cell with index iCell on page pPage contains a pointer
657** to an overflow page, insert an entry into the pointer-map
658** for the overflow page.
659*/
660static int ptrmapPutOvfl(MemPage *pPage, int iCell){
661 u8 *pCell;
drh1fee73e2007-08-29 04:00:57 +0000662 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197726836652005-01-17 01:33:13 +0000663 pCell = findOverflowCell(pPage, iCell);
664 return ptrmapPutOvflPtr(pPage, pCell);
665}
danielk197779a40da2005-01-16 08:00:01 +0000666#endif
667
danielk1977ac11ee62005-01-15 12:45:51 +0000668
drhda200cc2004-05-09 11:51:38 +0000669/*
drh72f82862001-05-24 21:06:34 +0000670** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +0000671** end of the page and all free space is collected into one
672** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +0000673** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +0000674*/
drh2e38c322004-09-03 18:38:44 +0000675static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000676 int i; /* Loop counter */
677 int pc; /* Address of a i-th cell */
678 int addr; /* Offset of first byte after cell pointer array */
679 int hdr; /* Offset to the page header */
680 int size; /* Size of a cell */
681 int usableSize; /* Number of usable bytes on a page */
682 int cellOffset; /* Offset to the cell pointer array */
683 int brk; /* Offset to the cell content area */
684 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +0000685 unsigned char *data; /* The page data */
686 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +0000687
danielk19773b8a05f2007-03-19 17:44:26 +0000688 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000689 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +0000690 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000691 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +0000692 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh26b79942007-11-28 16:19:56 +0000693 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
drh43605152004-05-29 21:46:49 +0000694 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +0000695 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000696 cellOffset = pPage->cellOffset;
697 nCell = pPage->nCell;
698 assert( nCell==get2byte(&data[hdr+3]) );
699 usableSize = pPage->pBt->usableSize;
700 brk = get2byte(&data[hdr+5]);
701 memcpy(&temp[brk], &data[brk], usableSize - brk);
702 brk = usableSize;
703 for(i=0; i<nCell; i++){
704 u8 *pAddr; /* The i-th cell pointer */
705 pAddr = &data[cellOffset + i*2];
706 pc = get2byte(pAddr);
707 assert( pc<pPage->pBt->usableSize );
708 size = cellSizePtr(pPage, &temp[pc]);
709 brk -= size;
710 memcpy(&data[brk], &temp[pc], size);
711 put2byte(pAddr, brk);
drh2af926b2001-05-15 00:39:25 +0000712 }
drh43605152004-05-29 21:46:49 +0000713 assert( brk>=cellOffset+2*nCell );
714 put2byte(&data[hdr+5], brk);
715 data[hdr+1] = 0;
716 data[hdr+2] = 0;
717 data[hdr+7] = 0;
718 addr = cellOffset+2*nCell;
719 memset(&data[addr], 0, brk-addr);
drh2e38c322004-09-03 18:38:44 +0000720 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +0000721}
722
drha059ad02001-04-17 20:09:11 +0000723/*
drh43605152004-05-29 21:46:49 +0000724** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +0000725**
drh9e572e62004-04-23 23:43:10 +0000726** Return the index into pPage->aData[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000727** the new allocation. Or return 0 if there is not enough free
728** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000729**
drh72f82862001-05-24 21:06:34 +0000730** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000731** nBytes of contiguous free space, then this routine automatically
732** calls defragementPage() to consolidate all free space before
733** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000734*/
drh9e572e62004-04-23 23:43:10 +0000735static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +0000736 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +0000737 int size;
drh24cd67e2004-05-10 16:18:47 +0000738 int nFrag;
drh43605152004-05-29 21:46:49 +0000739 int top;
740 int nCell;
741 int cellOffset;
drh9e572e62004-04-23 23:43:10 +0000742 unsigned char *data;
drh43605152004-05-29 21:46:49 +0000743
drh9e572e62004-04-23 23:43:10 +0000744 data = pPage->aData;
danielk19773b8a05f2007-03-19 17:44:26 +0000745 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000746 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +0000747 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh9e572e62004-04-23 23:43:10 +0000748 if( nByte<4 ) nByte = 4;
drh43605152004-05-29 21:46:49 +0000749 if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
750 pPage->nFree -= nByte;
drh9e572e62004-04-23 23:43:10 +0000751 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000752
753 nFrag = data[hdr+7];
754 if( nFrag<60 ){
755 /* Search the freelist looking for a slot big enough to satisfy the
756 ** space request. */
757 addr = hdr+1;
758 while( (pc = get2byte(&data[addr]))>0 ){
759 size = get2byte(&data[pc+2]);
760 if( size>=nByte ){
761 if( size<nByte+4 ){
762 memcpy(&data[addr], &data[pc], 2);
763 data[hdr+7] = nFrag + size - nByte;
764 return pc;
765 }else{
766 put2byte(&data[pc+2], size-nByte);
767 return pc + size - nByte;
768 }
769 }
770 addr = pc;
drh9e572e62004-04-23 23:43:10 +0000771 }
772 }
drh43605152004-05-29 21:46:49 +0000773
774 /* Allocate memory from the gap in between the cell pointer array
775 ** and the cell content area.
776 */
777 top = get2byte(&data[hdr+5]);
778 nCell = get2byte(&data[hdr+3]);
779 cellOffset = pPage->cellOffset;
780 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
drh2e38c322004-09-03 18:38:44 +0000781 if( defragmentPage(pPage) ) return 0;
drh43605152004-05-29 21:46:49 +0000782 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +0000783 }
drh43605152004-05-29 21:46:49 +0000784 top -= nByte;
785 assert( cellOffset + 2*nCell <= top );
786 put2byte(&data[hdr+5], top);
787 return top;
drh7e3b0a02001-04-28 16:52:40 +0000788}
789
790/*
drh9e572e62004-04-23 23:43:10 +0000791** Return a section of the pPage->aData to the freelist.
792** The first byte of the new free block is pPage->aDisk[start]
793** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +0000794**
795** Most of the effort here is involved in coalesing adjacent
796** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000797*/
drh9e572e62004-04-23 23:43:10 +0000798static void freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +0000799 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +0000800 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +0000801
drh9e572e62004-04-23 23:43:10 +0000802 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +0000803 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000804 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +0000805 assert( (start + size)<=pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +0000806 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh9e572e62004-04-23 23:43:10 +0000807 if( size<4 ) size = 4;
808
drhfcce93f2006-02-22 03:08:32 +0000809#ifdef SQLITE_SECURE_DELETE
810 /* Overwrite deleted information with zeros when the SECURE_DELETE
811 ** option is enabled at compile-time */
812 memset(&data[start], 0, size);
813#endif
814
drh9e572e62004-04-23 23:43:10 +0000815 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +0000816 hdr = pPage->hdrOffset;
817 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +0000818 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +0000819 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000820 assert( pbegin>addr );
821 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +0000822 }
drhb6f41482004-05-14 01:58:11 +0000823 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000824 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +0000825 put2byte(&data[addr], start);
826 put2byte(&data[start], pbegin);
827 put2byte(&data[start+2], size);
drh2af926b2001-05-15 00:39:25 +0000828 pPage->nFree += size;
drh9e572e62004-04-23 23:43:10 +0000829
830 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +0000831 addr = pPage->hdrOffset + 1;
832 while( (pbegin = get2byte(&data[addr]))>0 ){
drh9e572e62004-04-23 23:43:10 +0000833 int pnext, psize;
drh3aac2dd2004-04-26 14:10:20 +0000834 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +0000835 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +0000836 pnext = get2byte(&data[pbegin]);
837 psize = get2byte(&data[pbegin+2]);
838 if( pbegin + psize + 3 >= pnext && pnext>0 ){
839 int frag = pnext - (pbegin+psize);
drh43605152004-05-29 21:46:49 +0000840 assert( frag<=data[pPage->hdrOffset+7] );
841 data[pPage->hdrOffset+7] -= frag;
drh9e572e62004-04-23 23:43:10 +0000842 put2byte(&data[pbegin], get2byte(&data[pnext]));
843 put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
844 }else{
drh3aac2dd2004-04-26 14:10:20 +0000845 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +0000846 }
847 }
drh7e3b0a02001-04-28 16:52:40 +0000848
drh43605152004-05-29 21:46:49 +0000849 /* If the cell content area begins with a freeblock, remove it. */
850 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
851 int top;
852 pbegin = get2byte(&data[hdr+1]);
853 memcpy(&data[hdr+1], &data[pbegin], 2);
854 top = get2byte(&data[hdr+5]);
855 put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
drh4b70f112004-05-02 21:12:19 +0000856 }
drh4b70f112004-05-02 21:12:19 +0000857}
858
859/*
drh271efa52004-05-30 19:19:05 +0000860** Decode the flags byte (the first byte of the header) for a page
861** and initialize fields of the MemPage structure accordingly.
862*/
863static void decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +0000864 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +0000865
866 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +0000867 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh271efa52004-05-30 19:19:05 +0000868 pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
869 pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
870 pPage->leaf = (flagByte & PTF_LEAF)!=0;
871 pPage->childPtrSize = 4*(pPage->leaf==0);
872 pBt = pPage->pBt;
873 if( flagByte & PTF_LEAFDATA ){
874 pPage->leafData = 1;
875 pPage->maxLocal = pBt->maxLeaf;
876 pPage->minLocal = pBt->minLeaf;
877 }else{
878 pPage->leafData = 0;
879 pPage->maxLocal = pBt->maxLocal;
880 pPage->minLocal = pBt->minLocal;
881 }
882 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
883}
884
885/*
drh7e3b0a02001-04-28 16:52:40 +0000886** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000887**
drhbd03cae2001-06-02 02:40:57 +0000888** The pParent parameter must be a pointer to the MemPage which
drh9e572e62004-04-23 23:43:10 +0000889** is the parent of the page being initialized. The root of a
890** BTree has no parent and so for that page, pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000891**
drh72f82862001-05-24 21:06:34 +0000892** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +0000893** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +0000894** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
895** guarantee that the page is well-formed. It only shows that
896** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000897*/
drh16a9b832007-05-05 18:39:25 +0000898int sqlite3BtreeInitPage(
drh3aac2dd2004-04-26 14:10:20 +0000899 MemPage *pPage, /* The page to be initialized */
drh9e572e62004-04-23 23:43:10 +0000900 MemPage *pParent /* The parent. Might be NULL */
901){
drh271efa52004-05-30 19:19:05 +0000902 int pc; /* Address of a freeblock within pPage->aData[] */
drh271efa52004-05-30 19:19:05 +0000903 int hdr; /* Offset to beginning of page header */
904 u8 *data; /* Equal to pPage->aData */
danielk1977aef0bf62005-12-30 16:28:01 +0000905 BtShared *pBt; /* The main btree structure */
drh271efa52004-05-30 19:19:05 +0000906 int usableSize; /* Amount of usable space on each page */
907 int cellOffset; /* Offset from start of page to first cell pointer */
908 int nFree; /* Number of unused bytes on the page */
909 int top; /* First byte of the cell content area */
drh2af926b2001-05-15 00:39:25 +0000910
drh2e38c322004-09-03 18:38:44 +0000911 pBt = pPage->pBt;
912 assert( pBt!=0 );
913 assert( pParent==0 || pParent->pBt==pBt );
drh1fee73e2007-08-29 04:00:57 +0000914 assert( sqlite3_mutex_held(pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +0000915 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +0000916 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
917 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
drhee696e22004-08-30 16:52:17 +0000918 if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){
919 /* The parent page should never change unless the file is corrupt */
drh49285702005-09-17 15:20:26 +0000920 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000921 }
drh10617cd2004-05-14 15:27:27 +0000922 if( pPage->isInit ) return SQLITE_OK;
drhda200cc2004-05-09 11:51:38 +0000923 if( pPage->pParent==0 && pParent!=0 ){
924 pPage->pParent = pParent;
danielk19773b8a05f2007-03-19 17:44:26 +0000925 sqlite3PagerRef(pParent->pDbPage);
drh5e2f8b92001-05-28 00:41:15 +0000926 }
drhde647132004-05-07 17:57:49 +0000927 hdr = pPage->hdrOffset;
drha34b6762004-05-07 13:30:42 +0000928 data = pPage->aData;
drh271efa52004-05-30 19:19:05 +0000929 decodeFlags(pPage, data[hdr]);
drh43605152004-05-29 21:46:49 +0000930 pPage->nOverflow = 0;
drhc8629a12004-05-08 20:07:40 +0000931 pPage->idxShift = 0;
drh2e38c322004-09-03 18:38:44 +0000932 usableSize = pBt->usableSize;
drh43605152004-05-29 21:46:49 +0000933 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
934 top = get2byte(&data[hdr+5]);
935 pPage->nCell = get2byte(&data[hdr+3]);
drh2e38c322004-09-03 18:38:44 +0000936 if( pPage->nCell>MX_CELL(pBt) ){
drhee696e22004-08-30 16:52:17 +0000937 /* To many cells for a single page. The page must be corrupt */
drh49285702005-09-17 15:20:26 +0000938 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000939 }
940 if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
941 /* All pages must have at least one cell, except for root pages */
drh49285702005-09-17 15:20:26 +0000942 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000943 }
drh9e572e62004-04-23 23:43:10 +0000944
945 /* Compute the total free space on the page */
drh9e572e62004-04-23 23:43:10 +0000946 pc = get2byte(&data[hdr+1]);
drh43605152004-05-29 21:46:49 +0000947 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
drh9e572e62004-04-23 23:43:10 +0000948 while( pc>0 ){
949 int next, size;
drhee696e22004-08-30 16:52:17 +0000950 if( pc>usableSize-4 ){
951 /* Free block is off the page */
drh49285702005-09-17 15:20:26 +0000952 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000953 }
drh9e572e62004-04-23 23:43:10 +0000954 next = get2byte(&data[pc]);
955 size = get2byte(&data[pc+2]);
drhee696e22004-08-30 16:52:17 +0000956 if( next>0 && next<=pc+size+3 ){
957 /* Free blocks must be in accending order */
drh49285702005-09-17 15:20:26 +0000958 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000959 }
drh3add3672004-05-15 00:29:24 +0000960 nFree += size;
drh9e572e62004-04-23 23:43:10 +0000961 pc = next;
962 }
drh3add3672004-05-15 00:29:24 +0000963 pPage->nFree = nFree;
drhee696e22004-08-30 16:52:17 +0000964 if( nFree>=usableSize ){
965 /* Free space cannot exceed total page size */
drh49285702005-09-17 15:20:26 +0000966 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000967 }
drh9e572e62004-04-23 23:43:10 +0000968
drhde647132004-05-07 17:57:49 +0000969 pPage->isInit = 1;
drh9e572e62004-04-23 23:43:10 +0000970 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +0000971}
972
973/*
drh8b2f49b2001-06-08 00:21:52 +0000974** Set up a raw page so that it looks like a database page holding
975** no entries.
drhbd03cae2001-06-02 02:40:57 +0000976*/
drh9e572e62004-04-23 23:43:10 +0000977static void zeroPage(MemPage *pPage, int flags){
978 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +0000979 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +0000980 int hdr = pPage->hdrOffset;
drh9e572e62004-04-23 23:43:10 +0000981 int first;
982
danielk19773b8a05f2007-03-19 17:44:26 +0000983 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drhbf4bca52007-09-06 22:19:14 +0000984 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
985 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +0000986 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +0000987 assert( sqlite3_mutex_held(pBt->mutex) );
drhb6f41482004-05-14 01:58:11 +0000988 memset(&data[hdr], 0, pBt->usableSize - hdr);
drh9e572e62004-04-23 23:43:10 +0000989 data[hdr] = flags;
drh43605152004-05-29 21:46:49 +0000990 first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
991 memset(&data[hdr+1], 0, 4);
992 data[hdr+7] = 0;
993 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +0000994 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +0000995 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +0000996 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +0000997 pPage->cellOffset = first;
998 pPage->nOverflow = 0;
drhda200cc2004-05-09 11:51:38 +0000999 pPage->idxShift = 0;
drh43605152004-05-29 21:46:49 +00001000 pPage->nCell = 0;
drhda200cc2004-05-09 11:51:38 +00001001 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00001002}
1003
1004/*
drh3aac2dd2004-04-26 14:10:20 +00001005** Get a page from the pager. Initialize the MemPage.pBt and
1006** MemPage.aData elements if needed.
drh538f5702007-04-13 02:14:30 +00001007**
1008** If the noContent flag is set, it means that we do not care about
1009** the content of the page at this time. So do not go to the disk
1010** to fetch the content. Just fill in the content with zeros for now.
1011** If in the future we call sqlite3PagerWrite() on this page, that
1012** means we have started to be concerned about content and the disk
1013** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00001014*/
drh16a9b832007-05-05 18:39:25 +00001015int sqlite3BtreeGetPage(
1016 BtShared *pBt, /* The btree */
1017 Pgno pgno, /* Number of the page to fetch */
1018 MemPage **ppPage, /* Return the page in this parameter */
1019 int noContent /* Do not load page content if true */
1020){
drh3aac2dd2004-04-26 14:10:20 +00001021 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001022 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00001023 DbPage *pDbPage;
1024
drh1fee73e2007-08-29 04:00:57 +00001025 assert( sqlite3_mutex_held(pBt->mutex) );
drh538f5702007-04-13 02:14:30 +00001026 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
drh3aac2dd2004-04-26 14:10:20 +00001027 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001028 pPage = (MemPage *)sqlite3PagerGetExtra(pDbPage);
1029 pPage->aData = sqlite3PagerGetData(pDbPage);
1030 pPage->pDbPage = pDbPage;
drh3aac2dd2004-04-26 14:10:20 +00001031 pPage->pBt = pBt;
1032 pPage->pgno = pgno;
drhde647132004-05-07 17:57:49 +00001033 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
drh3aac2dd2004-04-26 14:10:20 +00001034 *ppPage = pPage;
1035 return SQLITE_OK;
1036}
1037
1038/*
drhde647132004-05-07 17:57:49 +00001039** Get a page from the pager and initialize it. This routine
1040** is just a convenience wrapper around separate calls to
drh16a9b832007-05-05 18:39:25 +00001041** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
drhde647132004-05-07 17:57:49 +00001042*/
1043static int getAndInitPage(
danielk1977aef0bf62005-12-30 16:28:01 +00001044 BtShared *pBt, /* The database file */
drhde647132004-05-07 17:57:49 +00001045 Pgno pgno, /* Number of the page to get */
1046 MemPage **ppPage, /* Write the page pointer here */
1047 MemPage *pParent /* Parent of the page */
1048){
1049 int rc;
drh1fee73e2007-08-29 04:00:57 +00001050 assert( sqlite3_mutex_held(pBt->mutex) );
drhee696e22004-08-30 16:52:17 +00001051 if( pgno==0 ){
drh49285702005-09-17 15:20:26 +00001052 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001053 }
drh16a9b832007-05-05 18:39:25 +00001054 rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
drh10617cd2004-05-14 15:27:27 +00001055 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
drh16a9b832007-05-05 18:39:25 +00001056 rc = sqlite3BtreeInitPage(*ppPage, pParent);
drhde647132004-05-07 17:57:49 +00001057 }
1058 return rc;
1059}
1060
1061/*
drh3aac2dd2004-04-26 14:10:20 +00001062** Release a MemPage. This should be called once for each prior
drh16a9b832007-05-05 18:39:25 +00001063** call to sqlite3BtreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +00001064*/
drh4b70f112004-05-02 21:12:19 +00001065static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001066 if( pPage ){
1067 assert( pPage->aData );
1068 assert( pPage->pBt );
drhbf4bca52007-09-06 22:19:14 +00001069 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1070 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
drh1fee73e2007-08-29 04:00:57 +00001071 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001072 sqlite3PagerUnref(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00001073 }
1074}
1075
1076/*
drh72f82862001-05-24 21:06:34 +00001077** This routine is called when the reference count for a page
1078** reaches zero. We need to unref the pParent pointer when that
1079** happens.
1080*/
danielk19773b8a05f2007-03-19 17:44:26 +00001081static void pageDestructor(DbPage *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +00001082 MemPage *pPage;
1083 assert( (pageSize & 7)==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001084 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
drh1fee73e2007-08-29 04:00:57 +00001085 assert( pPage->isInit==0 || sqlite3_mutex_held(pPage->pBt->mutex) );
drh72f82862001-05-24 21:06:34 +00001086 if( pPage->pParent ){
1087 MemPage *pParent = pPage->pParent;
drhd0679ed2007-08-28 22:24:34 +00001088 assert( pParent->pBt==pPage->pBt );
drh72f82862001-05-24 21:06:34 +00001089 pPage->pParent = 0;
drha34b6762004-05-07 13:30:42 +00001090 releasePage(pParent);
drh72f82862001-05-24 21:06:34 +00001091 }
drh3aac2dd2004-04-26 14:10:20 +00001092 pPage->isInit = 0;
drh72f82862001-05-24 21:06:34 +00001093}
1094
1095/*
drha6abd042004-06-09 17:37:22 +00001096** During a rollback, when the pager reloads information into the cache
1097** so that the cache is restored to its original state at the start of
1098** the transaction, for each page restored this routine is called.
1099**
1100** This routine needs to reset the extra data section at the end of the
1101** page to agree with the restored data.
1102*/
danielk19773b8a05f2007-03-19 17:44:26 +00001103static void pageReinit(DbPage *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +00001104 MemPage *pPage;
1105 assert( (pageSize & 7)==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001106 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
drha6abd042004-06-09 17:37:22 +00001107 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00001108 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00001109 pPage->isInit = 0;
drh16a9b832007-05-05 18:39:25 +00001110 sqlite3BtreeInitPage(pPage, pPage->pParent);
drha6abd042004-06-09 17:37:22 +00001111 }
1112}
1113
1114/*
drhe5fe6902007-12-07 18:55:28 +00001115** Invoke the busy handler for a btree.
1116*/
1117static int sqlite3BtreeInvokeBusyHandler(void *pArg, int n){
1118 BtShared *pBt = (BtShared*)pArg;
1119 assert( pBt->db );
1120 assert( sqlite3_mutex_held(pBt->db->mutex) );
1121 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
1122}
1123
1124/*
drhad3e0102004-09-03 23:32:18 +00001125** Open a database file.
1126**
drh382c0242001-10-06 16:33:02 +00001127** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001128** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001129** database file will be deleted when sqlite3BtreeClose() is called.
drhe53831d2007-08-17 01:14:38 +00001130** If zFilename is ":memory:" then an in-memory database is created
1131** that is automatically destroyed when it is closed.
drha059ad02001-04-17 20:09:11 +00001132*/
drh23e11ca2004-05-04 17:27:28 +00001133int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001134 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00001135 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001136 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00001137 int flags, /* Options */
1138 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00001139){
drhd677b3d2007-08-20 22:48:41 +00001140 sqlite3_vfs *pVfs; /* The VFS to use for this btree */
drhe53831d2007-08-17 01:14:38 +00001141 BtShared *pBt = 0; /* Shared part of btree structure */
danielk1977aef0bf62005-12-30 16:28:01 +00001142 Btree *p; /* Handle to return */
danielk1977dddbcdc2007-04-26 14:42:34 +00001143 int rc = SQLITE_OK;
drh90f5ecb2004-07-22 01:19:35 +00001144 int nReserve;
1145 unsigned char zDbHeader[100];
danielk1977aef0bf62005-12-30 16:28:01 +00001146
1147 /* Set the variable isMemdb to true for an in-memory database, or
1148 ** false for a file-based database. This symbol is only required if
1149 ** either of the shared-data or autovacuum features are compiled
1150 ** into the library.
1151 */
1152#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
1153 #ifdef SQLITE_OMIT_MEMORYDB
drh980b1a72006-08-16 16:42:48 +00001154 const int isMemdb = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00001155 #else
drh980b1a72006-08-16 16:42:48 +00001156 const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
danielk1977aef0bf62005-12-30 16:28:01 +00001157 #endif
1158#endif
1159
drhe5fe6902007-12-07 18:55:28 +00001160 assert( db!=0 );
1161 assert( sqlite3_mutex_held(db->mutex) );
drh153c62c2007-08-24 03:51:33 +00001162
drhe5fe6902007-12-07 18:55:28 +00001163 pVfs = db->pVfs;
drh17435752007-08-16 04:30:38 +00001164 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00001165 if( !p ){
1166 return SQLITE_NOMEM;
1167 }
1168 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00001169 p->db = db;
danielk1977aef0bf62005-12-30 16:28:01 +00001170
drh198bf392006-01-06 21:52:49 +00001171#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001172 /*
1173 ** If this Btree is a candidate for shared cache, try to find an
1174 ** existing BtShared object that we can share with
1175 */
1176 if( (flags & BTREE_PRIVATE)==0
1177 && isMemdb==0
drhe5fe6902007-12-07 18:55:28 +00001178 && (db->flags & SQLITE_Vtab)==0
drhe53831d2007-08-17 01:14:38 +00001179 && zFilename && zFilename[0]
drhe53831d2007-08-17 01:14:38 +00001180 ){
drhff0587c2007-08-29 17:43:19 +00001181 if( sqlite3SharedCacheEnabled ){
danielk1977adfb9b02007-09-17 07:02:56 +00001182 int nFullPathname = pVfs->mxPathname+1;
1183 char *zFullPathname = (char *)sqlite3_malloc(nFullPathname);
drhff0587c2007-08-29 17:43:19 +00001184 sqlite3_mutex *mutexShared;
1185 p->sharable = 1;
drhe5fe6902007-12-07 18:55:28 +00001186 if( db ){
1187 db->flags |= SQLITE_SharedCache;
danielk1977aef0bf62005-12-30 16:28:01 +00001188 }
drhff0587c2007-08-29 17:43:19 +00001189 if( !zFullPathname ){
1190 sqlite3_free(p);
1191 return SQLITE_NOMEM;
1192 }
danielk1977adfb9b02007-09-17 07:02:56 +00001193 sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
drhff0587c2007-08-29 17:43:19 +00001194 mutexShared = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
1195 sqlite3_mutex_enter(mutexShared);
1196 for(pBt=sqlite3SharedCacheList; pBt; pBt=pBt->pNext){
1197 assert( pBt->nRef>0 );
1198 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
1199 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
1200 p->pBt = pBt;
1201 pBt->nRef++;
1202 break;
1203 }
1204 }
1205 sqlite3_mutex_leave(mutexShared);
1206 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00001207 }
drhff0587c2007-08-29 17:43:19 +00001208#ifdef SQLITE_DEBUG
1209 else{
1210 /* In debug mode, we mark all persistent databases as sharable
1211 ** even when they are not. This exercises the locking code and
1212 ** gives more opportunity for asserts(sqlite3_mutex_held())
1213 ** statements to find locking problems.
1214 */
1215 p->sharable = 1;
1216 }
1217#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001218 }
1219#endif
drha059ad02001-04-17 20:09:11 +00001220 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00001221 /*
1222 ** The following asserts make sure that structures used by the btree are
1223 ** the right size. This is to guard against size changes that result
1224 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00001225 */
drhe53831d2007-08-17 01:14:38 +00001226 assert( sizeof(i64)==8 || sizeof(i64)==4 );
1227 assert( sizeof(u64)==8 || sizeof(u64)==4 );
1228 assert( sizeof(u32)==4 );
1229 assert( sizeof(u16)==2 );
1230 assert( sizeof(Pgno)==4 );
1231
1232 pBt = sqlite3MallocZero( sizeof(*pBt) );
1233 if( pBt==0 ){
1234 rc = SQLITE_NOMEM;
1235 goto btree_open_out;
1236 }
drhe5fe6902007-12-07 18:55:28 +00001237 pBt->busyHdr.xFunc = sqlite3BtreeInvokeBusyHandler;
1238 pBt->busyHdr.pArg = pBt;
drh33f4e022007-09-03 15:19:34 +00001239 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
1240 EXTRA_SIZE, flags, vfsFlags);
drhe53831d2007-08-17 01:14:38 +00001241 if( rc==SQLITE_OK ){
1242 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
1243 }
1244 if( rc!=SQLITE_OK ){
1245 goto btree_open_out;
1246 }
drhe5fe6902007-12-07 18:55:28 +00001247 sqlite3PagerSetBusyhandler(pBt->pPager, &pBt->busyHdr);
drhe53831d2007-08-17 01:14:38 +00001248 p->pBt = pBt;
1249
1250 sqlite3PagerSetDestructor(pBt->pPager, pageDestructor);
1251 sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
1252 pBt->pCursor = 0;
1253 pBt->pPage1 = 0;
1254 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
1255 pBt->pageSize = get2byte(&zDbHeader[16]);
1256 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1257 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00001258 pBt->pageSize = 0;
1259 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drhe53831d2007-08-17 01:14:38 +00001260 pBt->maxEmbedFrac = 64; /* 25% */
1261 pBt->minEmbedFrac = 32; /* 12.5% */
1262 pBt->minLeafFrac = 32; /* 12.5% */
1263#ifndef SQLITE_OMIT_AUTOVACUUM
1264 /* If the magic name ":memory:" will create an in-memory database, then
1265 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
1266 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
1267 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
1268 ** regular file-name. In this case the auto-vacuum applies as per normal.
1269 */
1270 if( zFilename && !isMemdb ){
1271 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
1272 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
1273 }
1274#endif
1275 nReserve = 0;
1276 }else{
1277 nReserve = zDbHeader[20];
1278 pBt->maxEmbedFrac = zDbHeader[21];
1279 pBt->minEmbedFrac = zDbHeader[22];
1280 pBt->minLeafFrac = zDbHeader[23];
1281 pBt->pageSizeFixed = 1;
1282#ifndef SQLITE_OMIT_AUTOVACUUM
1283 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1284 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
1285#endif
1286 }
1287 pBt->usableSize = pBt->pageSize - nReserve;
1288 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
danielk1977a1644fd2007-08-29 12:31:25 +00001289 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drhe53831d2007-08-17 01:14:38 +00001290
1291#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1292 /* Add the new BtShared object to the linked list sharable BtShareds.
1293 */
1294 if( p->sharable ){
1295 sqlite3_mutex *mutexShared;
1296 pBt->nRef = 1;
1297 mutexShared = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
drh3285db22007-09-03 22:00:39 +00001298 if( SQLITE_THREADSAFE ){
1299 pBt->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
1300 if( pBt->mutex==0 ){
1301 rc = SQLITE_NOMEM;
drhe5fe6902007-12-07 18:55:28 +00001302 db->mallocFailed = 0;
drh3285db22007-09-03 22:00:39 +00001303 goto btree_open_out;
1304 }
drhff0587c2007-08-29 17:43:19 +00001305 }
drhe53831d2007-08-17 01:14:38 +00001306 sqlite3_mutex_enter(mutexShared);
1307 pBt->pNext = sqlite3SharedCacheList;
1308 sqlite3SharedCacheList = pBt;
1309 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00001310 }
drheee46cf2004-11-06 00:02:48 +00001311#endif
drh90f5ecb2004-07-22 01:19:35 +00001312 }
danielk1977aef0bf62005-12-30 16:28:01 +00001313
drhcfed7bc2006-03-13 14:28:05 +00001314#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001315 /* If the new Btree uses a sharable pBtShared, then link the new
1316 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00001317 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00001318 */
drhe53831d2007-08-17 01:14:38 +00001319 if( p->sharable ){
1320 int i;
1321 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00001322 for(i=0; i<db->nDb; i++){
1323 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00001324 while( pSib->pPrev ){ pSib = pSib->pPrev; }
1325 if( p->pBt<pSib->pBt ){
1326 p->pNext = pSib;
1327 p->pPrev = 0;
1328 pSib->pPrev = p;
1329 }else{
drhabddb0c2007-08-20 13:14:28 +00001330 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
drhe53831d2007-08-17 01:14:38 +00001331 pSib = pSib->pNext;
1332 }
1333 p->pNext = pSib->pNext;
1334 p->pPrev = pSib;
1335 if( p->pNext ){
1336 p->pNext->pPrev = p;
1337 }
1338 pSib->pNext = p;
1339 }
1340 break;
1341 }
1342 }
danielk1977aef0bf62005-12-30 16:28:01 +00001343 }
danielk1977aef0bf62005-12-30 16:28:01 +00001344#endif
1345 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00001346
1347btree_open_out:
1348 if( rc!=SQLITE_OK ){
1349 if( pBt && pBt->pPager ){
1350 sqlite3PagerClose(pBt->pPager);
1351 }
drh17435752007-08-16 04:30:38 +00001352 sqlite3_free(pBt);
1353 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00001354 *ppBtree = 0;
1355 }
1356 return rc;
drha059ad02001-04-17 20:09:11 +00001357}
1358
1359/*
drhe53831d2007-08-17 01:14:38 +00001360** Decrement the BtShared.nRef counter. When it reaches zero,
1361** remove the BtShared structure from the sharing list. Return
1362** true if the BtShared.nRef counter reaches zero and return
1363** false if it is still positive.
1364*/
1365static int removeFromSharingList(BtShared *pBt){
1366#ifndef SQLITE_OMIT_SHARED_CACHE
1367 sqlite3_mutex *pMaster;
1368 BtShared *pList;
1369 int removed = 0;
1370
drhd677b3d2007-08-20 22:48:41 +00001371 assert( sqlite3_mutex_notheld(pBt->mutex) );
drhe53831d2007-08-17 01:14:38 +00001372 pMaster = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
1373 sqlite3_mutex_enter(pMaster);
1374 pBt->nRef--;
1375 if( pBt->nRef<=0 ){
1376 if( sqlite3SharedCacheList==pBt ){
1377 sqlite3SharedCacheList = pBt->pNext;
1378 }else{
1379 pList = sqlite3SharedCacheList;
1380 while( pList && pList->pNext!=pBt ){
1381 pList=pList->pNext;
1382 }
1383 if( pList ){
1384 pList->pNext = pBt->pNext;
1385 }
1386 }
drh3285db22007-09-03 22:00:39 +00001387 if( SQLITE_THREADSAFE ){
1388 sqlite3_mutex_free(pBt->mutex);
1389 }
drhe53831d2007-08-17 01:14:38 +00001390 removed = 1;
1391 }
1392 sqlite3_mutex_leave(pMaster);
1393 return removed;
1394#else
1395 return 1;
1396#endif
1397}
1398
1399/*
drha059ad02001-04-17 20:09:11 +00001400** Close an open database and invalidate all cursors.
1401*/
danielk1977aef0bf62005-12-30 16:28:01 +00001402int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00001403 BtShared *pBt = p->pBt;
1404 BtCursor *pCur;
1405
danielk1977aef0bf62005-12-30 16:28:01 +00001406 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00001407 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00001408 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00001409 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00001410 pCur = pBt->pCursor;
1411 while( pCur ){
1412 BtCursor *pTmp = pCur;
1413 pCur = pCur->pNext;
1414 if( pTmp->pBtree==p ){
1415 sqlite3BtreeCloseCursor(pTmp);
1416 }
drha059ad02001-04-17 20:09:11 +00001417 }
danielk1977aef0bf62005-12-30 16:28:01 +00001418
danielk19778d34dfd2006-01-24 16:37:57 +00001419 /* Rollback any active transaction and free the handle structure.
1420 ** The call to sqlite3BtreeRollback() drops any table-locks held by
1421 ** this handle.
1422 */
danielk1977b597f742006-01-15 11:39:18 +00001423 sqlite3BtreeRollback(p);
drhe53831d2007-08-17 01:14:38 +00001424 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001425
danielk1977aef0bf62005-12-30 16:28:01 +00001426 /* If there are still other outstanding references to the shared-btree
1427 ** structure, return now. The remainder of this procedure cleans
1428 ** up the shared-btree.
1429 */
drhe53831d2007-08-17 01:14:38 +00001430 assert( p->wantToLock==0 && p->locked==0 );
1431 if( !p->sharable || removeFromSharingList(pBt) ){
1432 /* The pBt is no longer on the sharing list, so we can access
1433 ** it without having to hold the mutex.
1434 **
1435 ** Clean out and delete the BtShared object.
1436 */
1437 assert( !pBt->pCursor );
drhe53831d2007-08-17 01:14:38 +00001438 sqlite3PagerClose(pBt->pPager);
1439 if( pBt->xFreeSchema && pBt->pSchema ){
1440 pBt->xFreeSchema(pBt->pSchema);
1441 }
1442 sqlite3_free(pBt->pSchema);
danielk197752ae7242008-03-25 14:24:56 +00001443 sqlite3_free(pBt->pTmpSpace);
drhe53831d2007-08-17 01:14:38 +00001444 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00001445 }
1446
drhe53831d2007-08-17 01:14:38 +00001447#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00001448 assert( p->wantToLock==0 );
1449 assert( p->locked==0 );
1450 if( p->pPrev ) p->pPrev->pNext = p->pNext;
1451 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00001452#endif
1453
drhe53831d2007-08-17 01:14:38 +00001454 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00001455 return SQLITE_OK;
1456}
1457
1458/*
drhda47d772002-12-02 04:25:19 +00001459** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001460**
1461** The maximum number of cache pages is set to the absolute
1462** value of mxPage. If mxPage is negative, the pager will
1463** operate asynchronously - it will not stop to do fsync()s
1464** to insure data is written to the disk surface before
1465** continuing. Transactions still work if synchronous is off,
1466** and the database cannot be corrupted if this program
1467** crashes. But if the operating system crashes or there is
1468** an abrupt power failure when synchronous is off, the database
1469** could be left in an inconsistent and unrecoverable state.
1470** Synchronous is on by default so database corruption is not
1471** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001472*/
danielk1977aef0bf62005-12-30 16:28:01 +00001473int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
1474 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001475 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001476 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001477 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00001478 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00001479 return SQLITE_OK;
1480}
1481
1482/*
drh973b6e32003-02-12 14:09:42 +00001483** Change the way data is synced to disk in order to increase or decrease
1484** how well the database resists damage due to OS crashes and power
1485** failures. Level 1 is the same as asynchronous (no syncs() occur and
1486** there is a high probability of damage) Level 2 is the default. There
1487** is a very low but non-zero probability of damage. Level 3 reduces the
1488** probability of damage to near zero but with a write performance reduction.
1489*/
danielk197793758c82005-01-21 08:13:14 +00001490#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drhac530b12006-02-11 01:25:50 +00001491int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
danielk1977aef0bf62005-12-30 16:28:01 +00001492 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001493 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001494 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001495 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
drhd677b3d2007-08-20 22:48:41 +00001496 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00001497 return SQLITE_OK;
1498}
danielk197793758c82005-01-21 08:13:14 +00001499#endif
drh973b6e32003-02-12 14:09:42 +00001500
drh2c8997b2005-08-27 16:36:48 +00001501/*
1502** Return TRUE if the given btree is set to safety level 1. In other
1503** words, return TRUE if no sync() occurs on the disk files.
1504*/
danielk1977aef0bf62005-12-30 16:28:01 +00001505int sqlite3BtreeSyncDisabled(Btree *p){
1506 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001507 int rc;
drhe5fe6902007-12-07 18:55:28 +00001508 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001509 sqlite3BtreeEnter(p);
drhd0679ed2007-08-28 22:24:34 +00001510 assert( pBt && pBt->pPager );
drhd677b3d2007-08-20 22:48:41 +00001511 rc = sqlite3PagerNosync(pBt->pPager);
1512 sqlite3BtreeLeave(p);
1513 return rc;
drh2c8997b2005-08-27 16:36:48 +00001514}
1515
danielk1977576ec6b2005-01-21 11:55:25 +00001516#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00001517/*
drh90f5ecb2004-07-22 01:19:35 +00001518** Change the default pages size and the number of reserved bytes per page.
drh06f50212004-11-02 14:24:33 +00001519**
1520** The page size must be a power of 2 between 512 and 65536. If the page
1521** size supplied does not meet this constraint then the page size is not
1522** changed.
1523**
1524** Page sizes are constrained to be a power of two so that the region
1525** of the database file used for locking (beginning at PENDING_BYTE,
1526** the first byte past the 1GB boundary, 0x40000000) needs to occur
1527** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001528**
1529** If parameter nReserve is less than zero, then the number of reserved
1530** bytes per page is left unchanged.
drh90f5ecb2004-07-22 01:19:35 +00001531*/
danielk1977aef0bf62005-12-30 16:28:01 +00001532int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
danielk1977a1644fd2007-08-29 12:31:25 +00001533 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00001534 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001535 sqlite3BtreeEnter(p);
drh90f5ecb2004-07-22 01:19:35 +00001536 if( pBt->pageSizeFixed ){
drhd677b3d2007-08-20 22:48:41 +00001537 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00001538 return SQLITE_READONLY;
1539 }
1540 if( nReserve<0 ){
1541 nReserve = pBt->pageSize - pBt->usableSize;
1542 }
drh06f50212004-11-02 14:24:33 +00001543 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
1544 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00001545 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00001546 assert( !pBt->pPage1 && !pBt->pCursor );
danielk1977a1644fd2007-08-29 12:31:25 +00001547 pBt->pageSize = pageSize;
danielk197752ae7242008-03-25 14:24:56 +00001548 sqlite3_free(pBt->pTmpSpace);
1549 pBt->pTmpSpace = 0;
danielk1977a1644fd2007-08-29 12:31:25 +00001550 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001551 }
1552 pBt->usableSize = pBt->pageSize - nReserve;
drhd677b3d2007-08-20 22:48:41 +00001553 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00001554 return rc;
drh90f5ecb2004-07-22 01:19:35 +00001555}
1556
1557/*
1558** Return the currently defined page size
1559*/
danielk1977aef0bf62005-12-30 16:28:01 +00001560int sqlite3BtreeGetPageSize(Btree *p){
1561 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00001562}
danielk1977aef0bf62005-12-30 16:28:01 +00001563int sqlite3BtreeGetReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00001564 int n;
1565 sqlite3BtreeEnter(p);
1566 n = p->pBt->pageSize - p->pBt->usableSize;
1567 sqlite3BtreeLeave(p);
1568 return n;
drh2011d5f2004-07-22 02:40:37 +00001569}
drhf8e632b2007-05-08 14:51:36 +00001570
1571/*
1572** Set the maximum page count for a database if mxPage is positive.
1573** No changes are made if mxPage is 0 or negative.
1574** Regardless of the value of mxPage, return the maximum page count.
1575*/
1576int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00001577 int n;
1578 sqlite3BtreeEnter(p);
1579 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
1580 sqlite3BtreeLeave(p);
1581 return n;
drhf8e632b2007-05-08 14:51:36 +00001582}
danielk1977576ec6b2005-01-21 11:55:25 +00001583#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00001584
1585/*
danielk1977951af802004-11-05 15:45:09 +00001586** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
1587** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
1588** is disabled. The default value for the auto-vacuum property is
1589** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
1590*/
danielk1977aef0bf62005-12-30 16:28:01 +00001591int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00001592#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001593 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00001594#else
danielk1977dddbcdc2007-04-26 14:42:34 +00001595 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001596 int rc = SQLITE_OK;
danielk1977dddbcdc2007-04-26 14:42:34 +00001597 int av = (autoVacuum?1:0);
drhd677b3d2007-08-20 22:48:41 +00001598
1599 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00001600 if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00001601 rc = SQLITE_READONLY;
1602 }else{
1603 pBt->autoVacuum = av;
danielk1977951af802004-11-05 15:45:09 +00001604 }
drhd677b3d2007-08-20 22:48:41 +00001605 sqlite3BtreeLeave(p);
1606 return rc;
danielk1977951af802004-11-05 15:45:09 +00001607#endif
1608}
1609
1610/*
1611** Return the value of the 'auto-vacuum' property. If auto-vacuum is
1612** enabled 1 is returned. Otherwise 0.
1613*/
danielk1977aef0bf62005-12-30 16:28:01 +00001614int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00001615#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00001616 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00001617#else
drhd677b3d2007-08-20 22:48:41 +00001618 int rc;
1619 sqlite3BtreeEnter(p);
1620 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00001621 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
1622 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
1623 BTREE_AUTOVACUUM_INCR
1624 );
drhd677b3d2007-08-20 22:48:41 +00001625 sqlite3BtreeLeave(p);
1626 return rc;
danielk1977951af802004-11-05 15:45:09 +00001627#endif
1628}
1629
1630
1631/*
drha34b6762004-05-07 13:30:42 +00001632** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001633** also acquire a readlock on that file.
1634**
1635** SQLITE_OK is returned on success. If the file is not a
1636** well-formed database file, then SQLITE_CORRUPT is returned.
1637** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00001638** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00001639*/
danielk1977aef0bf62005-12-30 16:28:01 +00001640static int lockBtree(BtShared *pBt){
danielk1977f653d782008-03-20 11:04:21 +00001641 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001642 MemPage *pPage1;
drhd677b3d2007-08-20 22:48:41 +00001643
drh1fee73e2007-08-29 04:00:57 +00001644 assert( sqlite3_mutex_held(pBt->mutex) );
drha34b6762004-05-07 13:30:42 +00001645 if( pBt->pPage1 ) return SQLITE_OK;
drh16a9b832007-05-05 18:39:25 +00001646 rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00001647 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00001648
1649 /* Do some checking to help insure the file we opened really is
1650 ** a valid database file.
1651 */
drhb6f41482004-05-14 01:58:11 +00001652 rc = SQLITE_NOTADB;
danielk19773b8a05f2007-03-19 17:44:26 +00001653 if( sqlite3PagerPagecount(pBt->pPager)>0 ){
danielk1977f653d782008-03-20 11:04:21 +00001654 int pageSize;
1655 int usableSize;
drhb6f41482004-05-14 01:58:11 +00001656 u8 *page1 = pPage1->aData;
1657 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001658 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001659 }
drh309169a2007-04-24 17:27:51 +00001660 if( page1[18]>1 ){
1661 pBt->readOnly = 1;
1662 }
1663 if( page1[19]>1 ){
drhb6f41482004-05-14 01:58:11 +00001664 goto page1_init_failed;
1665 }
drh07d183d2005-05-01 22:52:42 +00001666 pageSize = get2byte(&page1[16]);
drh7dc385e2007-09-06 23:39:36 +00001667 if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
1668 (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
1669 ){
drh07d183d2005-05-01 22:52:42 +00001670 goto page1_init_failed;
1671 }
1672 assert( (pageSize & 7)==0 );
danielk1977f653d782008-03-20 11:04:21 +00001673 usableSize = pageSize - page1[20];
1674 if( pageSize!=pBt->pageSize ){
1675 /* After reading the first page of the database assuming a page size
1676 ** of BtShared.pageSize, we have discovered that the page-size is
1677 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
1678 ** zero and return SQLITE_OK. The caller will call this function
1679 ** again with the correct page-size.
1680 */
1681 releasePage(pPage1);
1682 pBt->usableSize = usableSize;
1683 pBt->pageSize = pageSize;
danielk197752ae7242008-03-25 14:24:56 +00001684 sqlite3_free(pBt->pTmpSpace);
1685 pBt->pTmpSpace = 0;
danielk1977f653d782008-03-20 11:04:21 +00001686 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
1687 return SQLITE_OK;
1688 }
1689 if( usableSize<500 ){
drhb6f41482004-05-14 01:58:11 +00001690 goto page1_init_failed;
1691 }
danielk1977f653d782008-03-20 11:04:21 +00001692 pBt->pageSize = pageSize;
1693 pBt->usableSize = usableSize;
drhb6f41482004-05-14 01:58:11 +00001694 pBt->maxEmbedFrac = page1[21];
1695 pBt->minEmbedFrac = page1[22];
1696 pBt->minLeafFrac = page1[23];
drh057cd3a2005-02-15 16:23:02 +00001697#ifndef SQLITE_OMIT_AUTOVACUUM
1698 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00001699 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00001700#endif
drh306dc212001-05-21 13:45:10 +00001701 }
drhb6f41482004-05-14 01:58:11 +00001702
1703 /* maxLocal is the maximum amount of payload to store locally for
1704 ** a cell. Make sure it is small enough so that at least minFanout
1705 ** cells can will fit on one page. We assume a 10-byte page header.
1706 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001707 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001708 ** 4-byte child pointer
1709 ** 9-byte nKey value
1710 ** 4-byte nData value
1711 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001712 ** So a cell consists of a 2-byte poiner, a header which is as much as
1713 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1714 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001715 */
drh43605152004-05-29 21:46:49 +00001716 pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
1717 pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
1718 pBt->maxLeaf = pBt->usableSize - 35;
1719 pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
drhb6f41482004-05-14 01:58:11 +00001720 if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
1721 goto page1_init_failed;
1722 }
drh2e38c322004-09-03 18:38:44 +00001723 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00001724 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001725 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001726
drh72f82862001-05-24 21:06:34 +00001727page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001728 releasePage(pPage1);
1729 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001730 return rc;
drh306dc212001-05-21 13:45:10 +00001731}
1732
1733/*
drhb8ef32c2005-03-14 02:01:49 +00001734** This routine works like lockBtree() except that it also invokes the
1735** busy callback if there is lock contention.
1736*/
danielk1977aef0bf62005-12-30 16:28:01 +00001737static int lockBtreeWithRetry(Btree *pRef){
drhb8ef32c2005-03-14 02:01:49 +00001738 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00001739
drh1fee73e2007-08-29 04:00:57 +00001740 assert( sqlite3BtreeHoldsMutex(pRef) );
danielk1977aef0bf62005-12-30 16:28:01 +00001741 if( pRef->inTrans==TRANS_NONE ){
1742 u8 inTransaction = pRef->pBt->inTransaction;
1743 btreeIntegrity(pRef);
1744 rc = sqlite3BtreeBeginTrans(pRef, 0);
1745 pRef->pBt->inTransaction = inTransaction;
1746 pRef->inTrans = TRANS_NONE;
1747 if( rc==SQLITE_OK ){
1748 pRef->pBt->nTransaction--;
1749 }
1750 btreeIntegrity(pRef);
drhb8ef32c2005-03-14 02:01:49 +00001751 }
1752 return rc;
1753}
1754
1755
1756/*
drhb8ca3072001-12-05 00:21:20 +00001757** If there are no outstanding cursors and we are not in the middle
1758** of a transaction but there is a read lock on the database, then
1759** this routine unrefs the first page of the database file which
1760** has the effect of releasing the read lock.
1761**
1762** If there are any outstanding cursors, this routine is a no-op.
1763**
1764** If there is a transaction in progress, this routine is a no-op.
1765*/
danielk1977aef0bf62005-12-30 16:28:01 +00001766static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00001767 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00001768 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00001769 if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
drhde4fcfd2008-01-19 23:50:26 +00001770 assert( pBt->pPage1->aData );
1771#if 0
drh24c9a2e2007-01-05 02:00:47 +00001772 if( pBt->pPage1->aData==0 ){
1773 MemPage *pPage = pBt->pPage1;
drhbf4bca52007-09-06 22:19:14 +00001774 pPage->aData = sqlite3PagerGetData(pPage->pDbPage);
drh24c9a2e2007-01-05 02:00:47 +00001775 pPage->pBt = pBt;
1776 pPage->pgno = 1;
1777 }
drhde4fcfd2008-01-19 23:50:26 +00001778#endif
drh24c9a2e2007-01-05 02:00:47 +00001779 releasePage(pBt->pPage1);
drh51c6d962004-06-06 00:42:25 +00001780 }
drh3aac2dd2004-04-26 14:10:20 +00001781 pBt->pPage1 = 0;
drh3aac2dd2004-04-26 14:10:20 +00001782 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001783 }
1784}
1785
1786/*
drh9e572e62004-04-23 23:43:10 +00001787** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00001788** file.
drh8b2f49b2001-06-08 00:21:52 +00001789*/
danielk1977aef0bf62005-12-30 16:28:01 +00001790static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00001791 MemPage *pP1;
1792 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00001793 int rc;
drhd677b3d2007-08-20 22:48:41 +00001794
drh1fee73e2007-08-29 04:00:57 +00001795 assert( sqlite3_mutex_held(pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001796 if( sqlite3PagerPagecount(pBt->pPager)>0 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001797 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00001798 assert( pP1!=0 );
1799 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00001800 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00001801 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00001802 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
1803 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00001804 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00001805 data[18] = 1;
1806 data[19] = 1;
drhb6f41482004-05-14 01:58:11 +00001807 data[20] = pBt->pageSize - pBt->usableSize;
1808 data[21] = pBt->maxEmbedFrac;
1809 data[22] = pBt->minEmbedFrac;
1810 data[23] = pBt->minLeafFrac;
1811 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00001812 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00001813 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00001814#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00001815 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00001816 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00001817 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00001818 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00001819#endif
drh8b2f49b2001-06-08 00:21:52 +00001820 return SQLITE_OK;
1821}
1822
1823/*
danielk1977ee5741e2004-05-31 10:01:34 +00001824** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00001825** is started if the second argument is nonzero, otherwise a read-
1826** transaction. If the second argument is 2 or more and exclusive
1827** transaction is started, meaning that no other process is allowed
1828** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00001829** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00001830** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00001831**
danielk1977ee5741e2004-05-31 10:01:34 +00001832** A write-transaction must be started before attempting any
1833** changes to the database. None of the following routines
1834** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00001835**
drh23e11ca2004-05-04 17:27:28 +00001836** sqlite3BtreeCreateTable()
1837** sqlite3BtreeCreateIndex()
1838** sqlite3BtreeClearTable()
1839** sqlite3BtreeDropTable()
1840** sqlite3BtreeInsert()
1841** sqlite3BtreeDelete()
1842** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00001843**
drhb8ef32c2005-03-14 02:01:49 +00001844** If an initial attempt to acquire the lock fails because of lock contention
1845** and the database was previously unlocked, then invoke the busy handler
1846** if there is one. But if there was previously a read-lock, do not
1847** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
1848** returned when there is already a read-lock in order to avoid a deadlock.
1849**
1850** Suppose there are two processes A and B. A has a read lock and B has
1851** a reserved lock. B tries to promote to exclusive but is blocked because
1852** of A's read lock. A tries to promote to reserved but is blocked by B.
1853** One or the other of the two processes must give way or there can be
1854** no progress. By returning SQLITE_BUSY and not invoking the busy callback
1855** when A already has a read lock, we encourage A to give up and let B
1856** proceed.
drha059ad02001-04-17 20:09:11 +00001857*/
danielk1977aef0bf62005-12-30 16:28:01 +00001858int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
1859 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00001860 int rc = SQLITE_OK;
1861
drhd677b3d2007-08-20 22:48:41 +00001862 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00001863 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00001864 btreeIntegrity(p);
1865
danielk1977ee5741e2004-05-31 10:01:34 +00001866 /* If the btree is already in a write-transaction, or it
1867 ** is already in a read-transaction and a read-transaction
1868 ** is requested, this is a no-op.
1869 */
danielk1977aef0bf62005-12-30 16:28:01 +00001870 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00001871 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00001872 }
drhb8ef32c2005-03-14 02:01:49 +00001873
1874 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00001875 if( pBt->readOnly && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00001876 rc = SQLITE_READONLY;
1877 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00001878 }
1879
danielk1977aef0bf62005-12-30 16:28:01 +00001880 /* If another database handle has already opened a write transaction
1881 ** on this shared-btree structure and a second write transaction is
1882 ** requested, return SQLITE_BUSY.
1883 */
1884 if( pBt->inTransaction==TRANS_WRITE && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00001885 rc = SQLITE_BUSY;
1886 goto trans_begun;
danielk1977aef0bf62005-12-30 16:28:01 +00001887 }
1888
danielk1977641b0f42007-12-21 04:47:25 +00001889#ifndef SQLITE_OMIT_SHARED_CACHE
1890 if( wrflag>1 ){
1891 BtLock *pIter;
1892 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
1893 if( pIter->pBtree!=p ){
1894 rc = SQLITE_BUSY;
1895 goto trans_begun;
1896 }
1897 }
1898 }
1899#endif
1900
drhb8ef32c2005-03-14 02:01:49 +00001901 do {
danielk1977f653d782008-03-20 11:04:21 +00001902 while( rc==SQLITE_OK && pBt->pPage1==0 ){
drhb8ef32c2005-03-14 02:01:49 +00001903 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +00001904 }
drh309169a2007-04-24 17:27:51 +00001905
drhb8ef32c2005-03-14 02:01:49 +00001906 if( rc==SQLITE_OK && wrflag ){
drh309169a2007-04-24 17:27:51 +00001907 if( pBt->readOnly ){
1908 rc = SQLITE_READONLY;
1909 }else{
1910 rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1);
1911 if( rc==SQLITE_OK ){
1912 rc = newDatabase(pBt);
1913 }
drhb8ef32c2005-03-14 02:01:49 +00001914 }
1915 }
1916
1917 if( rc==SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00001918 if( wrflag ) pBt->inStmt = 0;
1919 }else{
1920 unlockBtreeIfUnused(pBt);
1921 }
danielk1977aef0bf62005-12-30 16:28:01 +00001922 }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
drhe5fe6902007-12-07 18:55:28 +00001923 sqlite3BtreeInvokeBusyHandler(pBt, 0) );
danielk1977aef0bf62005-12-30 16:28:01 +00001924
1925 if( rc==SQLITE_OK ){
1926 if( p->inTrans==TRANS_NONE ){
1927 pBt->nTransaction++;
1928 }
1929 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
1930 if( p->inTrans>pBt->inTransaction ){
1931 pBt->inTransaction = p->inTrans;
1932 }
danielk1977641b0f42007-12-21 04:47:25 +00001933#ifndef SQLITE_OMIT_SHARED_CACHE
1934 if( wrflag>1 ){
1935 assert( !pBt->pExclusive );
1936 pBt->pExclusive = p;
1937 }
1938#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001939 }
1940
drhd677b3d2007-08-20 22:48:41 +00001941
1942trans_begun:
danielk1977aef0bf62005-12-30 16:28:01 +00001943 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00001944 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00001945 return rc;
drha059ad02001-04-17 20:09:11 +00001946}
1947
danielk1977687566d2004-11-02 12:56:41 +00001948#ifndef SQLITE_OMIT_AUTOVACUUM
1949
1950/*
1951** Set the pointer-map entries for all children of page pPage. Also, if
1952** pPage contains cells that point to overflow pages, set the pointer
1953** map entries for the overflow pages as well.
1954*/
1955static int setChildPtrmaps(MemPage *pPage){
1956 int i; /* Counter variable */
1957 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00001958 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00001959 BtShared *pBt = pPage->pBt;
danielk1977687566d2004-11-02 12:56:41 +00001960 int isInitOrig = pPage->isInit;
1961 Pgno pgno = pPage->pgno;
1962
drh1fee73e2007-08-29 04:00:57 +00001963 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19772df71c72007-05-24 07:22:42 +00001964 rc = sqlite3BtreeInitPage(pPage, pPage->pParent);
1965 if( rc!=SQLITE_OK ){
1966 goto set_child_ptrmaps_out;
1967 }
danielk1977687566d2004-11-02 12:56:41 +00001968 nCell = pPage->nCell;
1969
1970 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00001971 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00001972
danielk197726836652005-01-17 01:33:13 +00001973 rc = ptrmapPutOvflPtr(pPage, pCell);
1974 if( rc!=SQLITE_OK ){
1975 goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00001976 }
danielk197726836652005-01-17 01:33:13 +00001977
danielk1977687566d2004-11-02 12:56:41 +00001978 if( !pPage->leaf ){
1979 Pgno childPgno = get4byte(pCell);
1980 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
1981 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
1982 }
1983 }
1984
1985 if( !pPage->leaf ){
1986 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
1987 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
1988 }
1989
1990set_child_ptrmaps_out:
1991 pPage->isInit = isInitOrig;
1992 return rc;
1993}
1994
1995/*
1996** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
1997** page, is a pointer to page iFrom. Modify this pointer so that it points to
1998** iTo. Parameter eType describes the type of pointer to be modified, as
1999** follows:
2000**
2001** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
2002** page of pPage.
2003**
2004** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
2005** page pointed to by one of the cells on pPage.
2006**
2007** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
2008** overflow page in the list.
2009*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00002010static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00002011 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk1977687566d2004-11-02 12:56:41 +00002012 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00002013 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00002014 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00002015 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002016 }
danielk1977f78fc082004-11-02 14:40:32 +00002017 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00002018 }else{
2019 int isInitOrig = pPage->isInit;
2020 int i;
2021 int nCell;
2022
drh16a9b832007-05-05 18:39:25 +00002023 sqlite3BtreeInitPage(pPage, 0);
danielk1977687566d2004-11-02 12:56:41 +00002024 nCell = pPage->nCell;
2025
danielk1977687566d2004-11-02 12:56:41 +00002026 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002027 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002028 if( eType==PTRMAP_OVERFLOW1 ){
2029 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00002030 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
danielk1977687566d2004-11-02 12:56:41 +00002031 if( info.iOverflow ){
2032 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
2033 put4byte(&pCell[info.iOverflow], iTo);
2034 break;
2035 }
2036 }
2037 }else{
2038 if( get4byte(pCell)==iFrom ){
2039 put4byte(pCell, iTo);
2040 break;
2041 }
2042 }
2043 }
2044
2045 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00002046 if( eType!=PTRMAP_BTREE ||
2047 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00002048 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002049 }
danielk1977687566d2004-11-02 12:56:41 +00002050 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
2051 }
2052
2053 pPage->isInit = isInitOrig;
2054 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002055 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002056}
2057
danielk1977003ba062004-11-04 02:57:33 +00002058
danielk19777701e812005-01-10 12:59:51 +00002059/*
2060** Move the open database page pDbPage to location iFreePage in the
2061** database. The pDbPage reference remains valid.
2062*/
danielk1977003ba062004-11-04 02:57:33 +00002063static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00002064 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00002065 MemPage *pDbPage, /* Open page to move */
2066 u8 eType, /* Pointer map 'type' entry for pDbPage */
2067 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
2068 Pgno iFreePage /* The location to move pDbPage to */
danielk1977003ba062004-11-04 02:57:33 +00002069){
2070 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
2071 Pgno iDbPage = pDbPage->pgno;
2072 Pager *pPager = pBt->pPager;
2073 int rc;
2074
danielk1977a0bf2652004-11-04 14:30:04 +00002075 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
2076 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00002077 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00002078 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00002079
drh85b623f2007-12-13 21:54:09 +00002080 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00002081 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
2082 iDbPage, iFreePage, iPtrPage, eType));
danielk19773b8a05f2007-03-19 17:44:26 +00002083 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage);
danielk1977003ba062004-11-04 02:57:33 +00002084 if( rc!=SQLITE_OK ){
2085 return rc;
2086 }
2087 pDbPage->pgno = iFreePage;
2088
2089 /* If pDbPage was a btree-page, then it may have child pages and/or cells
2090 ** that point to overflow pages. The pointer map entries for all these
2091 ** pages need to be changed.
2092 **
2093 ** If pDbPage is an overflow page, then the first 4 bytes may store a
2094 ** pointer to a subsequent overflow page. If this is the case, then
2095 ** the pointer map needs to be updated for the subsequent overflow page.
2096 */
danielk1977a0bf2652004-11-04 14:30:04 +00002097 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00002098 rc = setChildPtrmaps(pDbPage);
2099 if( rc!=SQLITE_OK ){
2100 return rc;
2101 }
2102 }else{
2103 Pgno nextOvfl = get4byte(pDbPage->aData);
2104 if( nextOvfl!=0 ){
danielk1977003ba062004-11-04 02:57:33 +00002105 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
2106 if( rc!=SQLITE_OK ){
2107 return rc;
2108 }
2109 }
2110 }
2111
2112 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
2113 ** that it points at iFreePage. Also fix the pointer map entry for
2114 ** iPtrPage.
2115 */
danielk1977a0bf2652004-11-04 14:30:04 +00002116 if( eType!=PTRMAP_ROOTPAGE ){
drh16a9b832007-05-05 18:39:25 +00002117 rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00002118 if( rc!=SQLITE_OK ){
2119 return rc;
2120 }
danielk19773b8a05f2007-03-19 17:44:26 +00002121 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00002122 if( rc!=SQLITE_OK ){
2123 releasePage(pPtrPage);
2124 return rc;
2125 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002126 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00002127 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00002128 if( rc==SQLITE_OK ){
2129 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
2130 }
danielk1977003ba062004-11-04 02:57:33 +00002131 }
danielk1977003ba062004-11-04 02:57:33 +00002132 return rc;
2133}
2134
danielk1977dddbcdc2007-04-26 14:42:34 +00002135/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00002136static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00002137
2138/*
danielk1977dddbcdc2007-04-26 14:42:34 +00002139** Perform a single step of an incremental-vacuum. If successful,
2140** return SQLITE_OK. If there is no work to do (and therefore no
2141** point in calling this function again), return SQLITE_DONE.
2142**
2143** More specificly, this function attempts to re-organize the
2144** database so that the last page of the file currently in use
2145** is no longer in use.
2146**
2147** If the nFin parameter is non-zero, the implementation assumes
2148** that the caller will keep calling incrVacuumStep() until
2149** it returns SQLITE_DONE or an error, and that nFin is the
2150** number of pages the database file will contain after this
2151** process is complete.
2152*/
2153static int incrVacuumStep(BtShared *pBt, Pgno nFin){
2154 Pgno iLastPg; /* Last page in the database */
2155 Pgno nFreeList; /* Number of pages still on the free-list */
2156
drh1fee73e2007-08-29 04:00:57 +00002157 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977dddbcdc2007-04-26 14:42:34 +00002158 iLastPg = pBt->nTrunc;
2159 if( iLastPg==0 ){
2160 iLastPg = sqlite3PagerPagecount(pBt->pPager);
2161 }
2162
2163 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
2164 int rc;
2165 u8 eType;
2166 Pgno iPtrPage;
2167
2168 nFreeList = get4byte(&pBt->pPage1->aData[36]);
2169 if( nFreeList==0 || nFin==iLastPg ){
2170 return SQLITE_DONE;
2171 }
2172
2173 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
2174 if( rc!=SQLITE_OK ){
2175 return rc;
2176 }
2177 if( eType==PTRMAP_ROOTPAGE ){
2178 return SQLITE_CORRUPT_BKPT;
2179 }
2180
2181 if( eType==PTRMAP_FREEPAGE ){
2182 if( nFin==0 ){
2183 /* Remove the page from the files free-list. This is not required
danielk19774ef24492007-05-23 09:52:41 +00002184 ** if nFin is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00002185 ** truncated to zero after this function returns, so it doesn't
2186 ** matter if it still contains some garbage entries.
2187 */
2188 Pgno iFreePg;
2189 MemPage *pFreePg;
2190 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
2191 if( rc!=SQLITE_OK ){
2192 return rc;
2193 }
2194 assert( iFreePg==iLastPg );
2195 releasePage(pFreePg);
2196 }
2197 } else {
2198 Pgno iFreePg; /* Index of free page to move pLastPg to */
2199 MemPage *pLastPg;
2200
drh16a9b832007-05-05 18:39:25 +00002201 rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002202 if( rc!=SQLITE_OK ){
2203 return rc;
2204 }
2205
danielk1977b4626a32007-04-28 15:47:43 +00002206 /* If nFin is zero, this loop runs exactly once and page pLastPg
2207 ** is swapped with the first free page pulled off the free list.
2208 **
2209 ** On the other hand, if nFin is greater than zero, then keep
2210 ** looping until a free-page located within the first nFin pages
2211 ** of the file is found.
2212 */
danielk1977dddbcdc2007-04-26 14:42:34 +00002213 do {
2214 MemPage *pFreePg;
2215 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
2216 if( rc!=SQLITE_OK ){
2217 releasePage(pLastPg);
2218 return rc;
2219 }
2220 releasePage(pFreePg);
2221 }while( nFin!=0 && iFreePg>nFin );
2222 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00002223
2224 rc = sqlite3PagerWrite(pLastPg->pDbPage);
danielk1977662278e2007-11-05 15:30:12 +00002225 if( rc==SQLITE_OK ){
2226 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg);
2227 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002228 releasePage(pLastPg);
2229 if( rc!=SQLITE_OK ){
2230 return rc;
danielk1977662278e2007-11-05 15:30:12 +00002231 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002232 }
2233 }
2234
2235 pBt->nTrunc = iLastPg - 1;
2236 while( pBt->nTrunc==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, pBt->nTrunc) ){
2237 pBt->nTrunc--;
2238 }
2239 return SQLITE_OK;
2240}
2241
2242/*
2243** A write-transaction must be opened before calling this function.
2244** It performs a single unit of work towards an incremental vacuum.
2245**
2246** If the incremental vacuum is finished after this function has run,
2247** SQLITE_DONE is returned. If it is not finished, but no error occured,
2248** SQLITE_OK is returned. Otherwise an SQLite error code.
2249*/
2250int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002251 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002252 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002253
2254 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002255 pBt->db = p->db;
danielk1977dddbcdc2007-04-26 14:42:34 +00002256 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
2257 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002258 rc = SQLITE_DONE;
2259 }else{
2260 invalidateAllOverflowCache(pBt);
2261 rc = incrVacuumStep(pBt, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002262 }
drhd677b3d2007-08-20 22:48:41 +00002263 sqlite3BtreeLeave(p);
2264 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002265}
2266
2267/*
danielk19773b8a05f2007-03-19 17:44:26 +00002268** This routine is called prior to sqlite3PagerCommit when a transaction
danielk1977687566d2004-11-02 12:56:41 +00002269** is commited for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00002270**
2271** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
2272** the database file should be truncated to during the commit process.
2273** i.e. the database has been reorganized so that only the first *pnTrunc
2274** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00002275*/
danielk197724168722007-04-02 05:07:47 +00002276static int autoVacuumCommit(BtShared *pBt, Pgno *pnTrunc){
danielk1977dddbcdc2007-04-26 14:42:34 +00002277 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002278 Pager *pPager = pBt->pPager;
danielk1977687566d2004-11-02 12:56:41 +00002279#ifndef NDEBUG
danielk19773b8a05f2007-03-19 17:44:26 +00002280 int nRef = sqlite3PagerRefcount(pPager);
danielk1977687566d2004-11-02 12:56:41 +00002281#endif
2282
drh1fee73e2007-08-29 04:00:57 +00002283 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00002284 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00002285 assert(pBt->autoVacuum);
2286 if( !pBt->incrVacuum ){
2287 Pgno nFin = 0;
danielk1977687566d2004-11-02 12:56:41 +00002288
danielk1977dddbcdc2007-04-26 14:42:34 +00002289 if( pBt->nTrunc==0 ){
2290 Pgno nFree;
2291 Pgno nPtrmap;
2292 const int pgsz = pBt->pageSize;
2293 Pgno nOrig = sqlite3PagerPagecount(pBt->pPager);
danielk1977e5321f02007-04-27 07:05:44 +00002294
2295 if( PTRMAP_ISPAGE(pBt, nOrig) ){
2296 return SQLITE_CORRUPT_BKPT;
2297 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002298 if( nOrig==PENDING_BYTE_PAGE(pBt) ){
2299 nOrig--;
danielk1977687566d2004-11-02 12:56:41 +00002300 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002301 nFree = get4byte(&pBt->pPage1->aData[36]);
2302 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
2303 nFin = nOrig - nFree - nPtrmap;
2304 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
2305 nFin--;
danielk1977ac11ee62005-01-15 12:45:51 +00002306 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002307 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
2308 nFin--;
2309 }
2310 }
danielk1977687566d2004-11-02 12:56:41 +00002311
danielk1977dddbcdc2007-04-26 14:42:34 +00002312 while( rc==SQLITE_OK ){
2313 rc = incrVacuumStep(pBt, nFin);
2314 }
2315 if( rc==SQLITE_DONE ){
2316 assert(nFin==0 || pBt->nTrunc==0 || nFin<=pBt->nTrunc);
2317 rc = SQLITE_OK;
2318 if( pBt->nTrunc ){
drh67f80b62007-07-23 19:26:17 +00002319 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
danielk1977dddbcdc2007-04-26 14:42:34 +00002320 put4byte(&pBt->pPage1->aData[32], 0);
2321 put4byte(&pBt->pPage1->aData[36], 0);
2322 pBt->nTrunc = nFin;
2323 }
2324 }
2325 if( rc!=SQLITE_OK ){
2326 sqlite3PagerRollback(pPager);
2327 }
danielk1977687566d2004-11-02 12:56:41 +00002328 }
2329
danielk1977dddbcdc2007-04-26 14:42:34 +00002330 if( rc==SQLITE_OK ){
2331 *pnTrunc = pBt->nTrunc;
2332 pBt->nTrunc = 0;
2333 }
danielk19773b8a05f2007-03-19 17:44:26 +00002334 assert( nRef==sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002335 return rc;
2336}
danielk1977dddbcdc2007-04-26 14:42:34 +00002337
danielk1977687566d2004-11-02 12:56:41 +00002338#endif
2339
2340/*
drh80e35f42007-03-30 14:06:34 +00002341** This routine does the first phase of a two-phase commit. This routine
2342** causes a rollback journal to be created (if it does not already exist)
2343** and populated with enough information so that if a power loss occurs
2344** the database can be restored to its original state by playing back
2345** the journal. Then the contents of the journal are flushed out to
2346** the disk. After the journal is safely on oxide, the changes to the
2347** database are written into the database file and flushed to oxide.
2348** At the end of this call, the rollback journal still exists on the
2349** disk and we are still holding all locks, so the transaction has not
2350** committed. See sqlite3BtreeCommit() for the second phase of the
2351** commit process.
2352**
2353** This call is a no-op if no write-transaction is currently active on pBt.
2354**
2355** Otherwise, sync the database file for the btree pBt. zMaster points to
2356** the name of a master journal file that should be written into the
2357** individual journal file, or is NULL, indicating no master journal file
2358** (single database transaction).
2359**
2360** When this is called, the master journal should already have been
2361** created, populated with this journal pointer and synced to disk.
2362**
2363** Once this is routine has returned, the only thing required to commit
2364** the write-transaction for this database file is to delete the journal.
2365*/
2366int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
2367 int rc = SQLITE_OK;
2368 if( p->inTrans==TRANS_WRITE ){
2369 BtShared *pBt = p->pBt;
2370 Pgno nTrunc = 0;
drhd677b3d2007-08-20 22:48:41 +00002371 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002372 pBt->db = p->db;
drh80e35f42007-03-30 14:06:34 +00002373#ifndef SQLITE_OMIT_AUTOVACUUM
2374 if( pBt->autoVacuum ){
2375 rc = autoVacuumCommit(pBt, &nTrunc);
2376 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002377 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002378 return rc;
2379 }
2380 }
2381#endif
danielk1977f653d782008-03-20 11:04:21 +00002382 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, nTrunc, 0);
drhd677b3d2007-08-20 22:48:41 +00002383 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002384 }
2385 return rc;
2386}
2387
2388/*
drh2aa679f2001-06-25 02:11:07 +00002389** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00002390**
drh6e345992007-03-30 11:12:08 +00002391** This routine implements the second phase of a 2-phase commit. The
2392** sqlite3BtreeSync() routine does the first phase and should be invoked
2393** prior to calling this routine. The sqlite3BtreeSync() routine did
2394** all the work of writing information out to disk and flushing the
2395** contents so that they are written onto the disk platter. All this
2396** routine has to do is delete or truncate the rollback journal
2397** (which causes the transaction to commit) and drop locks.
2398**
drh5e00f6c2001-09-13 13:46:56 +00002399** This will release the write lock on the database file. If there
2400** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002401*/
drh80e35f42007-03-30 14:06:34 +00002402int sqlite3BtreeCommitPhaseTwo(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002403 BtShared *pBt = p->pBt;
2404
drhd677b3d2007-08-20 22:48:41 +00002405 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002406 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00002407 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002408
2409 /* If the handle has a write-transaction open, commit the shared-btrees
2410 ** transaction and set the shared state to TRANS_READ.
2411 */
2412 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00002413 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002414 assert( pBt->inTransaction==TRANS_WRITE );
2415 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00002416 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
danielk19777f7bc662006-01-23 13:47:47 +00002417 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002418 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002419 return rc;
2420 }
danielk1977aef0bf62005-12-30 16:28:01 +00002421 pBt->inTransaction = TRANS_READ;
2422 pBt->inStmt = 0;
danielk1977ee5741e2004-05-31 10:01:34 +00002423 }
danielk19777f7bc662006-01-23 13:47:47 +00002424 unlockAllTables(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002425
2426 /* If the handle has any kind of transaction open, decrement the transaction
2427 ** count of the shared btree. If the transaction count reaches 0, set
2428 ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
2429 ** will unlock the pager.
2430 */
2431 if( p->inTrans!=TRANS_NONE ){
2432 pBt->nTransaction--;
2433 if( 0==pBt->nTransaction ){
2434 pBt->inTransaction = TRANS_NONE;
2435 }
2436 }
2437
2438 /* Set the handles current transaction state to TRANS_NONE and unlock
2439 ** the pager if this call closed the only read or write transaction.
2440 */
2441 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00002442 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002443
2444 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002445 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002446 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002447}
2448
drh80e35f42007-03-30 14:06:34 +00002449/*
2450** Do both phases of a commit.
2451*/
2452int sqlite3BtreeCommit(Btree *p){
2453 int rc;
drhd677b3d2007-08-20 22:48:41 +00002454 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00002455 rc = sqlite3BtreeCommitPhaseOne(p, 0);
2456 if( rc==SQLITE_OK ){
2457 rc = sqlite3BtreeCommitPhaseTwo(p);
2458 }
drhd677b3d2007-08-20 22:48:41 +00002459 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002460 return rc;
2461}
2462
danielk1977fbcd5852004-06-15 02:44:18 +00002463#ifndef NDEBUG
2464/*
2465** Return the number of write-cursors open on this handle. This is for use
2466** in assert() expressions, so it is only compiled if NDEBUG is not
2467** defined.
drhfb982642007-08-30 01:19:59 +00002468**
2469** For the purposes of this routine, a write-cursor is any cursor that
2470** is capable of writing to the databse. That means the cursor was
2471** originally opened for writing and the cursor has not be disabled
2472** by having its state changed to CURSOR_FAULT.
danielk1977fbcd5852004-06-15 02:44:18 +00002473*/
danielk1977aef0bf62005-12-30 16:28:01 +00002474static int countWriteCursors(BtShared *pBt){
danielk1977fbcd5852004-06-15 02:44:18 +00002475 BtCursor *pCur;
2476 int r = 0;
2477 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drhfb982642007-08-30 01:19:59 +00002478 if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
danielk1977fbcd5852004-06-15 02:44:18 +00002479 }
2480 return r;
2481}
2482#endif
2483
drhc39e0002004-05-07 23:50:57 +00002484/*
drhfb982642007-08-30 01:19:59 +00002485** This routine sets the state to CURSOR_FAULT and the error
2486** code to errCode for every cursor on BtShared that pBtree
2487** references.
2488**
2489** Every cursor is tripped, including cursors that belong
2490** to other database connections that happen to be sharing
2491** the cache with pBtree.
2492**
2493** This routine gets called when a rollback occurs.
2494** All cursors using the same cache must be tripped
2495** to prevent them from trying to use the btree after
2496** the rollback. The rollback may have deleted tables
2497** or moved root pages, so it is not sufficient to
2498** save the state of the cursor. The cursor must be
2499** invalidated.
2500*/
2501void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
2502 BtCursor *p;
2503 sqlite3BtreeEnter(pBtree);
2504 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
2505 clearCursorPosition(p);
2506 p->eState = CURSOR_FAULT;
2507 p->skip = errCode;
2508 }
2509 sqlite3BtreeLeave(pBtree);
2510}
2511
2512/*
drhecdc7532001-09-23 02:35:53 +00002513** Rollback the transaction in progress. All cursors will be
2514** invalided by this operation. Any attempt to use a cursor
2515** that was open at the beginning of this operation will result
2516** in an error.
drh5e00f6c2001-09-13 13:46:56 +00002517**
2518** This will release the write lock on the database file. If there
2519** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002520*/
danielk1977aef0bf62005-12-30 16:28:01 +00002521int sqlite3BtreeRollback(Btree *p){
danielk19778d34dfd2006-01-24 16:37:57 +00002522 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002523 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00002524 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00002525
drhd677b3d2007-08-20 22:48:41 +00002526 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002527 pBt->db = p->db;
danielk19772b8c13e2006-01-24 14:21:24 +00002528 rc = saveAllCursors(pBt, 0, 0);
danielk19778d34dfd2006-01-24 16:37:57 +00002529#ifndef SQLITE_OMIT_SHARED_CACHE
danielk19772b8c13e2006-01-24 14:21:24 +00002530 if( rc!=SQLITE_OK ){
danielk19778d34dfd2006-01-24 16:37:57 +00002531 /* This is a horrible situation. An IO or malloc() error occured whilst
2532 ** trying to save cursor positions. If this is an automatic rollback (as
2533 ** the result of a constraint, malloc() failure or IO error) then
2534 ** the cache may be internally inconsistent (not contain valid trees) so
2535 ** we cannot simply return the error to the caller. Instead, abort
2536 ** all queries that may be using any of the cursors that failed to save.
2537 */
drhfb982642007-08-30 01:19:59 +00002538 sqlite3BtreeTripAllCursors(p, rc);
danielk19772b8c13e2006-01-24 14:21:24 +00002539 }
danielk19778d34dfd2006-01-24 16:37:57 +00002540#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002541 btreeIntegrity(p);
2542 unlockAllTables(p);
2543
2544 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00002545 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00002546
danielk1977dddbcdc2007-04-26 14:42:34 +00002547#ifndef SQLITE_OMIT_AUTOVACUUM
2548 pBt->nTrunc = 0;
2549#endif
2550
danielk19778d34dfd2006-01-24 16:37:57 +00002551 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00002552 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00002553 if( rc2!=SQLITE_OK ){
2554 rc = rc2;
2555 }
2556
drh24cd67e2004-05-10 16:18:47 +00002557 /* The rollback may have destroyed the pPage1->aData value. So
drh16a9b832007-05-05 18:39:25 +00002558 ** call sqlite3BtreeGetPage() on page 1 again to make
2559 ** sure pPage1->aData is set correctly. */
2560 if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh24cd67e2004-05-10 16:18:47 +00002561 releasePage(pPage1);
2562 }
danielk1977fbcd5852004-06-15 02:44:18 +00002563 assert( countWriteCursors(pBt)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002564 pBt->inTransaction = TRANS_READ;
drh24cd67e2004-05-10 16:18:47 +00002565 }
danielk1977aef0bf62005-12-30 16:28:01 +00002566
2567 if( p->inTrans!=TRANS_NONE ){
2568 assert( pBt->nTransaction>0 );
2569 pBt->nTransaction--;
2570 if( 0==pBt->nTransaction ){
2571 pBt->inTransaction = TRANS_NONE;
2572 }
2573 }
2574
2575 p->inTrans = TRANS_NONE;
danielk1977ee5741e2004-05-31 10:01:34 +00002576 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00002577 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002578
2579 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002580 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00002581 return rc;
2582}
2583
2584/*
drhab01f612004-05-22 02:55:23 +00002585** Start a statement subtransaction. The subtransaction can
2586** can be rolled back independently of the main transaction.
2587** You must start a transaction before starting a subtransaction.
2588** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00002589** commits or rolls back.
2590**
drhab01f612004-05-22 02:55:23 +00002591** Only one subtransaction may be active at a time. It is an error to try
2592** to start a new subtransaction if another subtransaction is already active.
2593**
2594** Statement subtransactions are used around individual SQL statements
2595** that are contained within a BEGIN...COMMIT block. If a constraint
2596** error occurs within the statement, the effect of that one statement
2597** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00002598*/
danielk1977aef0bf62005-12-30 16:28:01 +00002599int sqlite3BtreeBeginStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002600 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002601 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002602 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002603 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00002604 if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
drhd677b3d2007-08-20 22:48:41 +00002605 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
2606 }else{
2607 assert( pBt->inTransaction==TRANS_WRITE );
2608 rc = pBt->readOnly ? SQLITE_OK : sqlite3PagerStmtBegin(pBt->pPager);
2609 pBt->inStmt = 1;
drh0d65dc02002-02-03 00:56:09 +00002610 }
drhd677b3d2007-08-20 22:48:41 +00002611 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002612 return rc;
2613}
2614
2615
2616/*
drhab01f612004-05-22 02:55:23 +00002617** Commit the statment subtransaction currently in progress. If no
2618** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00002619*/
danielk1977aef0bf62005-12-30 16:28:01 +00002620int sqlite3BtreeCommitStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002621 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002622 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002623 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002624 pBt->db = p->db;
drh3aac2dd2004-04-26 14:10:20 +00002625 if( pBt->inStmt && !pBt->readOnly ){
danielk19773b8a05f2007-03-19 17:44:26 +00002626 rc = sqlite3PagerStmtCommit(pBt->pPager);
drh663fc632002-02-02 18:49:19 +00002627 }else{
2628 rc = SQLITE_OK;
2629 }
drh3aac2dd2004-04-26 14:10:20 +00002630 pBt->inStmt = 0;
drhd677b3d2007-08-20 22:48:41 +00002631 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002632 return rc;
2633}
2634
2635/*
drhab01f612004-05-22 02:55:23 +00002636** Rollback the active statement subtransaction. If no subtransaction
2637** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00002638**
drhab01f612004-05-22 02:55:23 +00002639** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00002640** to use a cursor that was open at the beginning of this operation
2641** will result in an error.
2642*/
danielk1977aef0bf62005-12-30 16:28:01 +00002643int sqlite3BtreeRollbackStmt(Btree *p){
danielk197797a227c2006-01-20 16:32:04 +00002644 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002645 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002646 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002647 pBt->db = p->db;
danielk197797a227c2006-01-20 16:32:04 +00002648 if( pBt->inStmt && !pBt->readOnly ){
danielk19773b8a05f2007-03-19 17:44:26 +00002649 rc = sqlite3PagerStmtRollback(pBt->pPager);
danielk197797a227c2006-01-20 16:32:04 +00002650 assert( countWriteCursors(pBt)==0 );
2651 pBt->inStmt = 0;
2652 }
drhd677b3d2007-08-20 22:48:41 +00002653 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002654 return rc;
2655}
2656
2657/*
drh8b2f49b2001-06-08 00:21:52 +00002658** Create a new cursor for the BTree whose root is on the page
2659** iTable. The act of acquiring a cursor gets a read lock on
2660** the database file.
drh1bee3d72001-10-15 00:44:35 +00002661**
2662** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00002663** If wrFlag==1, then the cursor can be used for reading or for
2664** writing if other conditions for writing are also met. These
2665** are the conditions that must be met in order for writing to
2666** be allowed:
drh6446c4d2001-12-15 14:22:18 +00002667**
drhf74b8d92002-09-01 23:20:45 +00002668** 1: The cursor must have been opened with wrFlag==1
2669**
drhfe5d71d2007-03-19 11:54:10 +00002670** 2: Other database connections that share the same pager cache
2671** but which are not in the READ_UNCOMMITTED state may not have
2672** cursors open with wrFlag==0 on the same table. Otherwise
2673** the changes made by this write cursor would be visible to
2674** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00002675**
2676** 3: The database must be writable (not on read-only media)
2677**
2678** 4: There must be an active transaction.
2679**
drh6446c4d2001-12-15 14:22:18 +00002680** No checking is done to make sure that page iTable really is the
2681** root page of a b-tree. If it is not, then the cursor acquired
2682** will not work correctly.
drha059ad02001-04-17 20:09:11 +00002683*/
drhd677b3d2007-08-20 22:48:41 +00002684static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00002685 Btree *p, /* The btree */
2686 int iTable, /* Root page of table to open */
2687 int wrFlag, /* 1 to write. 0 read-only */
2688 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
2689 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00002690){
drha059ad02001-04-17 20:09:11 +00002691 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002692 BtShared *pBt = p->pBt;
drhecdc7532001-09-23 02:35:53 +00002693
drh1fee73e2007-08-29 04:00:57 +00002694 assert( sqlite3BtreeHoldsMutex(p) );
drh8dcd7ca2004-08-08 19:43:29 +00002695 if( wrFlag ){
drh8dcd7ca2004-08-08 19:43:29 +00002696 if( pBt->readOnly ){
2697 return SQLITE_READONLY;
2698 }
drh980b1a72006-08-16 16:42:48 +00002699 if( checkReadLocks(p, iTable, 0) ){
drh8dcd7ca2004-08-08 19:43:29 +00002700 return SQLITE_LOCKED;
2701 }
drha0c9a112004-03-10 13:42:37 +00002702 }
danielk1977aef0bf62005-12-30 16:28:01 +00002703
drh4b70f112004-05-02 21:12:19 +00002704 if( pBt->pPage1==0 ){
danielk1977aef0bf62005-12-30 16:28:01 +00002705 rc = lockBtreeWithRetry(p);
drha059ad02001-04-17 20:09:11 +00002706 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00002707 return rc;
2708 }
drh1831f182007-04-24 17:35:59 +00002709 if( pBt->readOnly && wrFlag ){
2710 return SQLITE_READONLY;
2711 }
drha059ad02001-04-17 20:09:11 +00002712 }
drh8b2f49b2001-06-08 00:21:52 +00002713 pCur->pgnoRoot = (Pgno)iTable;
danielk19773b8a05f2007-03-19 17:44:26 +00002714 if( iTable==1 && sqlite3PagerPagecount(pBt->pPager)==0 ){
drh24cd67e2004-05-10 16:18:47 +00002715 rc = SQLITE_EMPTY;
2716 goto create_cursor_exception;
2717 }
drhde647132004-05-07 17:57:49 +00002718 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
drhbd03cae2001-06-02 02:40:57 +00002719 if( rc!=SQLITE_OK ){
2720 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00002721 }
danielk1977aef0bf62005-12-30 16:28:01 +00002722
danielk1977aef0bf62005-12-30 16:28:01 +00002723 /* Now that no other errors can occur, finish filling in the BtCursor
2724 ** variables, link the cursor into the BtShared list and set *ppCur (the
2725 ** output argument to this function).
2726 */
drh1e968a02008-03-25 00:22:21 +00002727 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00002728 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00002729 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +00002730 pCur->wrFlag = wrFlag;
drha059ad02001-04-17 20:09:11 +00002731 pCur->pNext = pBt->pCursor;
2732 if( pCur->pNext ){
2733 pCur->pNext->pPrev = pCur;
2734 }
2735 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00002736 pCur->eState = CURSOR_INVALID;
drhbd03cae2001-06-02 02:40:57 +00002737
danielk1977aef0bf62005-12-30 16:28:01 +00002738 return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00002739
drhbd03cae2001-06-02 02:40:57 +00002740create_cursor_exception:
drhbd03cae2001-06-02 02:40:57 +00002741 if( pCur ){
drh3aac2dd2004-04-26 14:10:20 +00002742 releasePage(pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +00002743 }
drh5e00f6c2001-09-13 13:46:56 +00002744 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00002745 return rc;
drha059ad02001-04-17 20:09:11 +00002746}
drhd677b3d2007-08-20 22:48:41 +00002747int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00002748 Btree *p, /* The btree */
2749 int iTable, /* Root page of table to open */
2750 int wrFlag, /* 1 to write. 0 read-only */
2751 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
2752 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00002753){
2754 int rc;
2755 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00002756 p->pBt->db = p->db;
danielk1977cd3e8f72008-03-25 09:47:35 +00002757 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
drhd677b3d2007-08-20 22:48:41 +00002758 sqlite3BtreeLeave(p);
2759 return rc;
2760}
danielk1977cd3e8f72008-03-25 09:47:35 +00002761int sqlite3BtreeCursorSize(){
2762 return sizeof(BtCursor);
2763}
2764
drhd677b3d2007-08-20 22:48:41 +00002765
drha059ad02001-04-17 20:09:11 +00002766
2767/*
drh5e00f6c2001-09-13 13:46:56 +00002768** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00002769** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00002770*/
drh3aac2dd2004-04-26 14:10:20 +00002771int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00002772 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00002773 if( pBtree ){
2774 BtShared *pBt = pCur->pBt;
2775 sqlite3BtreeEnter(pBtree);
2776 pBt->db = pBtree->db;
2777 clearCursorPosition(pCur);
2778 if( pCur->pPrev ){
2779 pCur->pPrev->pNext = pCur->pNext;
2780 }else{
2781 pBt->pCursor = pCur->pNext;
2782 }
2783 if( pCur->pNext ){
2784 pCur->pNext->pPrev = pCur->pPrev;
2785 }
2786 releasePage(pCur->pPage);
2787 unlockBtreeIfUnused(pBt);
2788 invalidateOverflowCache(pCur);
2789 /* sqlite3_free(pCur); */
2790 sqlite3BtreeLeave(pBtree);
drha059ad02001-04-17 20:09:11 +00002791 }
drh8c42ca92001-06-22 19:15:00 +00002792 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002793}
2794
drh7e3b0a02001-04-28 16:52:40 +00002795/*
drh5e2f8b92001-05-28 00:41:15 +00002796** Make a temporary cursor by filling in the fields of pTempCur.
2797** The temporary cursor is not on the cursor list for the Btree.
2798*/
drh16a9b832007-05-05 18:39:25 +00002799void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh1fee73e2007-08-29 04:00:57 +00002800 assert( cursorHoldsMutex(pCur) );
drh5e2f8b92001-05-28 00:41:15 +00002801 memcpy(pTempCur, pCur, sizeof(*pCur));
2802 pTempCur->pNext = 0;
2803 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00002804 if( pTempCur->pPage ){
danielk19773b8a05f2007-03-19 17:44:26 +00002805 sqlite3PagerRef(pTempCur->pPage->pDbPage);
drhecdc7532001-09-23 02:35:53 +00002806 }
drh5e2f8b92001-05-28 00:41:15 +00002807}
2808
2809/*
drhbd03cae2001-06-02 02:40:57 +00002810** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00002811** function above.
2812*/
drh16a9b832007-05-05 18:39:25 +00002813void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00002814 assert( cursorHoldsMutex(pCur) );
drhecdc7532001-09-23 02:35:53 +00002815 if( pCur->pPage ){
danielk19773b8a05f2007-03-19 17:44:26 +00002816 sqlite3PagerUnref(pCur->pPage->pDbPage);
drhecdc7532001-09-23 02:35:53 +00002817 }
drh5e2f8b92001-05-28 00:41:15 +00002818}
2819
2820/*
drh86057612007-06-26 01:04:48 +00002821** Make sure the BtCursor* given in the argument has a valid
2822** BtCursor.info structure. If it is not already valid, call
danielk19771cc5ed82007-05-16 17:28:43 +00002823** sqlite3BtreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00002824**
2825** BtCursor.info is a cache of the information in the current cell.
drh16a9b832007-05-05 18:39:25 +00002826** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
drh86057612007-06-26 01:04:48 +00002827**
2828** 2007-06-25: There is a bug in some versions of MSVC that cause the
2829** compiler to crash when getCellInfo() is implemented as a macro.
2830** But there is a measureable speed advantage to using the macro on gcc
2831** (when less compiler optimizations like -Os or -O0 are used and the
2832** compiler is not doing agressive inlining.) So we use a real function
2833** for MSVC and a macro for everything else. Ticket #2457.
drh9188b382004-05-14 21:12:22 +00002834*/
drh9188b382004-05-14 21:12:22 +00002835#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00002836 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00002837 CellInfo info;
drh51c6d962004-06-06 00:42:25 +00002838 memset(&info, 0, sizeof(info));
drh16a9b832007-05-05 18:39:25 +00002839 sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &info);
drh9188b382004-05-14 21:12:22 +00002840 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00002841 }
danielk19771cc5ed82007-05-16 17:28:43 +00002842#else
2843 #define assertCellInfo(x)
2844#endif
drh86057612007-06-26 01:04:48 +00002845#ifdef _MSC_VER
2846 /* Use a real function in MSVC to work around bugs in that compiler. */
2847 static void getCellInfo(BtCursor *pCur){
2848 if( pCur->info.nSize==0 ){
2849 sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info);
drha2c20e42008-03-29 16:01:04 +00002850 pCur->validNKey = 1;
drh86057612007-06-26 01:04:48 +00002851 }else{
2852 assertCellInfo(pCur);
2853 }
2854 }
2855#else /* if not _MSC_VER */
2856 /* Use a macro in all other compilers so that the function is inlined */
2857#define getCellInfo(pCur) \
2858 if( pCur->info.nSize==0 ){ \
danielk19771cc5ed82007-05-16 17:28:43 +00002859 sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info); \
drha2c20e42008-03-29 16:01:04 +00002860 pCur->validNKey = 1; \
drh86057612007-06-26 01:04:48 +00002861 }else{ \
2862 assertCellInfo(pCur); \
2863 }
2864#endif /* _MSC_VER */
drh9188b382004-05-14 21:12:22 +00002865
2866/*
drh3aac2dd2004-04-26 14:10:20 +00002867** Set *pSize to the size of the buffer needed to hold the value of
2868** the key for the current entry. If the cursor is not pointing
2869** to a valid entry, *pSize is set to 0.
2870**
drh4b70f112004-05-02 21:12:19 +00002871** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00002872** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00002873*/
drh4a1c3802004-05-12 15:15:47 +00002874int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drhd677b3d2007-08-20 22:48:41 +00002875 int rc;
2876
drh1fee73e2007-08-29 04:00:57 +00002877 assert( cursorHoldsMutex(pCur) );
drhd677b3d2007-08-20 22:48:41 +00002878 rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00002879 if( rc==SQLITE_OK ){
2880 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
2881 if( pCur->eState==CURSOR_INVALID ){
2882 *pSize = 0;
2883 }else{
drh86057612007-06-26 01:04:48 +00002884 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00002885 *pSize = pCur->info.nKey;
2886 }
drh72f82862001-05-24 21:06:34 +00002887 }
danielk1977da184232006-01-05 11:34:32 +00002888 return rc;
drha059ad02001-04-17 20:09:11 +00002889}
drh2af926b2001-05-15 00:39:25 +00002890
drh72f82862001-05-24 21:06:34 +00002891/*
drh0e1c19e2004-05-11 00:58:56 +00002892** Set *pSize to the number of bytes of data in the entry the
2893** cursor currently points to. Always return SQLITE_OK.
2894** Failure is not possible. If the cursor is not currently
2895** pointing to an entry (which can happen, for example, if
2896** the database is empty) then *pSize is set to 0.
2897*/
2898int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drhd677b3d2007-08-20 22:48:41 +00002899 int rc;
2900
drh1fee73e2007-08-29 04:00:57 +00002901 assert( cursorHoldsMutex(pCur) );
drhd677b3d2007-08-20 22:48:41 +00002902 rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00002903 if( rc==SQLITE_OK ){
2904 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
2905 if( pCur->eState==CURSOR_INVALID ){
2906 /* Not pointing at a valid entry - set *pSize to 0. */
2907 *pSize = 0;
2908 }else{
drh86057612007-06-26 01:04:48 +00002909 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00002910 *pSize = pCur->info.nData;
2911 }
drh0e1c19e2004-05-11 00:58:56 +00002912 }
danielk1977da184232006-01-05 11:34:32 +00002913 return rc;
drh0e1c19e2004-05-11 00:58:56 +00002914}
2915
2916/*
danielk1977d04417962007-05-02 13:16:30 +00002917** Given the page number of an overflow page in the database (parameter
2918** ovfl), this function finds the page number of the next page in the
2919** linked list of overflow pages. If possible, it uses the auto-vacuum
2920** pointer-map data instead of reading the content of page ovfl to do so.
2921**
2922** If an error occurs an SQLite error code is returned. Otherwise:
2923**
2924** Unless pPgnoNext is NULL, the page number of the next overflow
2925** page in the linked list is written to *pPgnoNext. If page ovfl
drh85b623f2007-12-13 21:54:09 +00002926** is the last page in its linked list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00002927**
2928** If ppPage is not NULL, *ppPage is set to the MemPage* handle
2929** for page ovfl. The underlying pager page may have been requested
2930** with the noContent flag set, so the page data accessable via
2931** this handle may not be trusted.
2932*/
2933static int getOverflowPage(
2934 BtShared *pBt,
2935 Pgno ovfl, /* Overflow page */
2936 MemPage **ppPage, /* OUT: MemPage handle */
2937 Pgno *pPgnoNext /* OUT: Next overflow page number */
2938){
2939 Pgno next = 0;
2940 int rc;
2941
drh1fee73e2007-08-29 04:00:57 +00002942 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977d04417962007-05-02 13:16:30 +00002943 /* One of these must not be NULL. Otherwise, why call this function? */
2944 assert(ppPage || pPgnoNext);
2945
2946 /* If pPgnoNext is NULL, then this function is being called to obtain
2947 ** a MemPage* reference only. No page-data is required in this case.
2948 */
2949 if( !pPgnoNext ){
drh16a9b832007-05-05 18:39:25 +00002950 return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1);
danielk1977d04417962007-05-02 13:16:30 +00002951 }
2952
2953#ifndef SQLITE_OMIT_AUTOVACUUM
2954 /* Try to find the next page in the overflow list using the
2955 ** autovacuum pointer-map pages. Guess that the next page in
2956 ** the overflow list is page number (ovfl+1). If that guess turns
2957 ** out to be wrong, fall back to loading the data of page
2958 ** number ovfl to determine the next page number.
2959 */
2960 if( pBt->autoVacuum ){
2961 Pgno pgno;
2962 Pgno iGuess = ovfl+1;
2963 u8 eType;
2964
2965 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
2966 iGuess++;
2967 }
2968
danielk197720713f32007-05-03 11:43:33 +00002969 if( iGuess<=sqlite3PagerPagecount(pBt->pPager) ){
danielk1977d04417962007-05-02 13:16:30 +00002970 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
2971 if( rc!=SQLITE_OK ){
2972 return rc;
2973 }
2974 if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
2975 next = iGuess;
2976 }
2977 }
2978 }
2979#endif
2980
2981 if( next==0 || ppPage ){
2982 MemPage *pPage = 0;
2983
drh16a9b832007-05-05 18:39:25 +00002984 rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0);
danielk1977d04417962007-05-02 13:16:30 +00002985 assert(rc==SQLITE_OK || pPage==0);
2986 if( next==0 && rc==SQLITE_OK ){
2987 next = get4byte(pPage->aData);
2988 }
2989
2990 if( ppPage ){
2991 *ppPage = pPage;
2992 }else{
2993 releasePage(pPage);
2994 }
2995 }
2996 *pPgnoNext = next;
2997
2998 return rc;
2999}
3000
danielk1977da107192007-05-04 08:32:13 +00003001/*
3002** Copy data from a buffer to a page, or from a page to a buffer.
3003**
3004** pPayload is a pointer to data stored on database page pDbPage.
3005** If argument eOp is false, then nByte bytes of data are copied
3006** from pPayload to the buffer pointed at by pBuf. If eOp is true,
3007** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
3008** of data are copied from the buffer pBuf to pPayload.
3009**
3010** SQLITE_OK is returned on success, otherwise an error code.
3011*/
3012static int copyPayload(
3013 void *pPayload, /* Pointer to page data */
3014 void *pBuf, /* Pointer to buffer */
3015 int nByte, /* Number of bytes to copy */
3016 int eOp, /* 0 -> copy from page, 1 -> copy to page */
3017 DbPage *pDbPage /* Page containing pPayload */
3018){
3019 if( eOp ){
3020 /* Copy data from buffer to page (a write operation) */
3021 int rc = sqlite3PagerWrite(pDbPage);
3022 if( rc!=SQLITE_OK ){
3023 return rc;
3024 }
3025 memcpy(pPayload, pBuf, nByte);
3026 }else{
3027 /* Copy data from page to buffer (a read operation) */
3028 memcpy(pBuf, pPayload, nByte);
3029 }
3030 return SQLITE_OK;
3031}
danielk1977d04417962007-05-02 13:16:30 +00003032
3033/*
danielk19779f8d6402007-05-02 17:48:45 +00003034** This function is used to read or overwrite payload information
3035** for the entry that the pCur cursor is pointing to. If the eOp
3036** parameter is 0, this is a read operation (data copied into
3037** buffer pBuf). If it is non-zero, a write (data copied from
3038** buffer pBuf).
3039**
3040** A total of "amt" bytes are read or written beginning at "offset".
3041** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00003042**
3043** This routine does not make a distinction between key and data.
danielk19779f8d6402007-05-02 17:48:45 +00003044** It just reads or writes bytes from the payload area. Data might
3045** appear on the main page or be scattered out on multiple overflow
3046** pages.
danielk1977da107192007-05-04 08:32:13 +00003047**
danielk1977dcbb5d32007-05-04 18:36:44 +00003048** If the BtCursor.isIncrblobHandle flag is set, and the current
danielk1977da107192007-05-04 08:32:13 +00003049** cursor entry uses one or more overflow pages, this function
3050** allocates space for and lazily popluates the overflow page-list
3051** cache array (BtCursor.aOverflow). Subsequent calls use this
3052** cache to make seeking to the supplied offset more efficient.
3053**
3054** Once an overflow page-list cache has been allocated, it may be
3055** invalidated if some other cursor writes to the same table, or if
3056** the cursor is moved to a different row. Additionally, in auto-vacuum
3057** mode, the following events may invalidate an overflow page-list cache.
3058**
3059** * An incremental vacuum,
3060** * A commit in auto_vacuum="full" mode,
3061** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00003062*/
danielk19779f8d6402007-05-02 17:48:45 +00003063static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00003064 BtCursor *pCur, /* Cursor pointing to entry to read from */
3065 int offset, /* Begin reading this far into payload */
3066 int amt, /* Read this many bytes */
3067 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00003068 int skipKey, /* offset begins at data if this is true */
3069 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00003070){
3071 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00003072 int rc = SQLITE_OK;
drhfa1a98a2004-05-14 19:08:17 +00003073 u32 nKey;
danielk19772dec9702007-05-02 16:48:37 +00003074 int iIdx = 0;
drhd0679ed2007-08-28 22:24:34 +00003075 MemPage *pPage = pCur->pPage; /* Btree page of current cursor entry */
drh51f015e2007-10-16 19:45:29 +00003076 BtShared *pBt; /* Btree this cursor belongs to */
drh3aac2dd2004-04-26 14:10:20 +00003077
danielk1977da107192007-05-04 08:32:13 +00003078 assert( pPage );
danielk1977da184232006-01-05 11:34:32 +00003079 assert( pCur->eState==CURSOR_VALID );
drh3aac2dd2004-04-26 14:10:20 +00003080 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
danielk1977da107192007-05-04 08:32:13 +00003081 assert( offset>=0 );
drh1fee73e2007-08-29 04:00:57 +00003082 assert( cursorHoldsMutex(pCur) );
danielk1977da107192007-05-04 08:32:13 +00003083
drh86057612007-06-26 01:04:48 +00003084 getCellInfo(pCur);
drh366fda62006-01-13 02:35:09 +00003085 aPayload = pCur->info.pCell + pCur->info.nHeader;
danielk1977da107192007-05-04 08:32:13 +00003086 nKey = (pPage->intKey ? 0 : pCur->info.nKey);
3087
drh3aac2dd2004-04-26 14:10:20 +00003088 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003089 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00003090 }
drhfa1a98a2004-05-14 19:08:17 +00003091 if( offset+amt > nKey+pCur->info.nData ){
danielk1977da107192007-05-04 08:32:13 +00003092 /* Trying to read or write past the end of the data is an error */
drha34b6762004-05-07 13:30:42 +00003093 return SQLITE_ERROR;
drh3aac2dd2004-04-26 14:10:20 +00003094 }
danielk1977da107192007-05-04 08:32:13 +00003095
3096 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00003097 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00003098 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00003099 if( a+offset>pCur->info.nLocal ){
3100 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00003101 }
danielk1977da107192007-05-04 08:32:13 +00003102 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00003103 offset = 0;
drha34b6762004-05-07 13:30:42 +00003104 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00003105 amt -= a;
drhdd793422001-06-28 01:54:48 +00003106 }else{
drhfa1a98a2004-05-14 19:08:17 +00003107 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00003108 }
danielk1977da107192007-05-04 08:32:13 +00003109
drh51f015e2007-10-16 19:45:29 +00003110 pBt = pCur->pBt;
danielk1977da107192007-05-04 08:32:13 +00003111 if( rc==SQLITE_OK && amt>0 ){
3112 const int ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
3113 Pgno nextPage;
3114
drhfa1a98a2004-05-14 19:08:17 +00003115 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00003116
danielk19772dec9702007-05-02 16:48:37 +00003117#ifndef SQLITE_OMIT_INCRBLOB
danielk1977dcbb5d32007-05-04 18:36:44 +00003118 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
danielk1977da107192007-05-04 08:32:13 +00003119 ** has not been allocated, allocate it now. The array is sized at
3120 ** one entry for each overflow page in the overflow chain. The
3121 ** page number of the first overflow page is stored in aOverflow[0],
3122 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
3123 ** (the cache is lazily populated).
3124 */
danielk1977dcbb5d32007-05-04 18:36:44 +00003125 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
danielk19772dec9702007-05-02 16:48:37 +00003126 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
drh17435752007-08-16 04:30:38 +00003127 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
danielk19772dec9702007-05-02 16:48:37 +00003128 if( nOvfl && !pCur->aOverflow ){
danielk1977da107192007-05-04 08:32:13 +00003129 rc = SQLITE_NOMEM;
danielk19772dec9702007-05-02 16:48:37 +00003130 }
3131 }
danielk1977da107192007-05-04 08:32:13 +00003132
3133 /* If the overflow page-list cache has been allocated and the
3134 ** entry for the first required overflow page is valid, skip
3135 ** directly to it.
3136 */
danielk19772dec9702007-05-02 16:48:37 +00003137 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
3138 iIdx = (offset/ovflSize);
3139 nextPage = pCur->aOverflow[iIdx];
3140 offset = (offset%ovflSize);
3141 }
3142#endif
danielk1977da107192007-05-04 08:32:13 +00003143
3144 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
3145
3146#ifndef SQLITE_OMIT_INCRBLOB
3147 /* If required, populate the overflow page-list cache. */
3148 if( pCur->aOverflow ){
3149 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
3150 pCur->aOverflow[iIdx] = nextPage;
3151 }
3152#endif
3153
danielk1977d04417962007-05-02 13:16:30 +00003154 if( offset>=ovflSize ){
3155 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00003156 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00003157 ** data is not required. So first try to lookup the overflow
3158 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00003159 ** function.
danielk1977d04417962007-05-02 13:16:30 +00003160 */
danielk19772dec9702007-05-02 16:48:37 +00003161#ifndef SQLITE_OMIT_INCRBLOB
danielk1977da107192007-05-04 08:32:13 +00003162 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
3163 nextPage = pCur->aOverflow[iIdx+1];
3164 } else
danielk19772dec9702007-05-02 16:48:37 +00003165#endif
danielk1977da107192007-05-04 08:32:13 +00003166 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
danielk1977da107192007-05-04 08:32:13 +00003167 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00003168 }else{
danielk19779f8d6402007-05-02 17:48:45 +00003169 /* Need to read this page properly. It contains some of the
3170 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00003171 */
3172 DbPage *pDbPage;
danielk1977cfe9a692004-06-16 12:00:29 +00003173 int a = amt;
danielk1977d04417962007-05-02 13:16:30 +00003174 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
danielk1977da107192007-05-04 08:32:13 +00003175 if( rc==SQLITE_OK ){
3176 aPayload = sqlite3PagerGetData(pDbPage);
3177 nextPage = get4byte(aPayload);
3178 if( a + offset > ovflSize ){
3179 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00003180 }
danielk1977da107192007-05-04 08:32:13 +00003181 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
3182 sqlite3PagerUnref(pDbPage);
3183 offset = 0;
3184 amt -= a;
3185 pBuf += a;
danielk19779f8d6402007-05-02 17:48:45 +00003186 }
danielk1977cfe9a692004-06-16 12:00:29 +00003187 }
drh2af926b2001-05-15 00:39:25 +00003188 }
drh2af926b2001-05-15 00:39:25 +00003189 }
danielk1977cfe9a692004-06-16 12:00:29 +00003190
danielk1977da107192007-05-04 08:32:13 +00003191 if( rc==SQLITE_OK && amt>0 ){
drh49285702005-09-17 15:20:26 +00003192 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00003193 }
danielk1977da107192007-05-04 08:32:13 +00003194 return rc;
drh2af926b2001-05-15 00:39:25 +00003195}
3196
drh72f82862001-05-24 21:06:34 +00003197/*
drh3aac2dd2004-04-26 14:10:20 +00003198** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003199** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003200** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00003201**
drh3aac2dd2004-04-26 14:10:20 +00003202** Return SQLITE_OK on success or an error code if anything goes
3203** wrong. An error is returned if "offset+amt" is larger than
3204** the available payload.
drh72f82862001-05-24 21:06:34 +00003205*/
drha34b6762004-05-07 13:30:42 +00003206int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003207 int rc;
3208
drh1fee73e2007-08-29 04:00:57 +00003209 assert( cursorHoldsMutex(pCur) );
drhd677b3d2007-08-20 22:48:41 +00003210 rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003211 if( rc==SQLITE_OK ){
3212 assert( pCur->eState==CURSOR_VALID );
3213 assert( pCur->pPage!=0 );
3214 if( pCur->pPage->intKey ){
3215 return SQLITE_CORRUPT_BKPT;
3216 }
3217 assert( pCur->pPage->intKey==0 );
3218 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh16a9b832007-05-05 18:39:25 +00003219 rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
drh6575a222005-03-10 17:06:34 +00003220 }
danielk1977da184232006-01-05 11:34:32 +00003221 return rc;
drh3aac2dd2004-04-26 14:10:20 +00003222}
3223
3224/*
drh3aac2dd2004-04-26 14:10:20 +00003225** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003226** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003227** begins at "offset".
3228**
3229** Return SQLITE_OK on success or an error code if anything goes
3230** wrong. An error is returned if "offset+amt" is larger than
3231** the available payload.
drh72f82862001-05-24 21:06:34 +00003232*/
drh3aac2dd2004-04-26 14:10:20 +00003233int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003234 int rc;
3235
drh1fee73e2007-08-29 04:00:57 +00003236 assert( cursorHoldsMutex(pCur) );
drhd677b3d2007-08-20 22:48:41 +00003237 rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003238 if( rc==SQLITE_OK ){
3239 assert( pCur->eState==CURSOR_VALID );
3240 assert( pCur->pPage!=0 );
3241 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh16a9b832007-05-05 18:39:25 +00003242 rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
danielk1977da184232006-01-05 11:34:32 +00003243 }
3244 return rc;
drh2af926b2001-05-15 00:39:25 +00003245}
3246
drh72f82862001-05-24 21:06:34 +00003247/*
drh0e1c19e2004-05-11 00:58:56 +00003248** Return a pointer to payload information from the entry that the
3249** pCur cursor is pointing to. The pointer is to the beginning of
3250** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00003251** skipKey==1. The number of bytes of available key/data is written
3252** into *pAmt. If *pAmt==0, then the value returned will not be
3253** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00003254**
3255** This routine is an optimization. It is common for the entire key
3256** and data to fit on the local page and for there to be no overflow
3257** pages. When that is so, this routine can be used to access the
3258** key and data without making a copy. If the key and/or data spills
drh16a9b832007-05-05 18:39:25 +00003259** onto overflow pages, then accessPayload() must be used to reassembly
drh0e1c19e2004-05-11 00:58:56 +00003260** the key/data and copy it into a preallocated buffer.
3261**
3262** The pointer returned by this routine looks directly into the cached
3263** page of the database. The data might change or move the next time
3264** any btree routine is called.
3265*/
3266static const unsigned char *fetchPayload(
3267 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00003268 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00003269 int skipKey /* read beginning at data if this is true */
3270){
3271 unsigned char *aPayload;
3272 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00003273 u32 nKey;
3274 int nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003275
3276 assert( pCur!=0 && pCur->pPage!=0 );
danielk1977da184232006-01-05 11:34:32 +00003277 assert( pCur->eState==CURSOR_VALID );
drh1fee73e2007-08-29 04:00:57 +00003278 assert( cursorHoldsMutex(pCur) );
drh0e1c19e2004-05-11 00:58:56 +00003279 pPage = pCur->pPage;
drh0e1c19e2004-05-11 00:58:56 +00003280 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh86057612007-06-26 01:04:48 +00003281 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00003282 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00003283 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00003284 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00003285 nKey = 0;
3286 }else{
3287 nKey = pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00003288 }
drh0e1c19e2004-05-11 00:58:56 +00003289 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003290 aPayload += nKey;
3291 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00003292 }else{
drhfa1a98a2004-05-14 19:08:17 +00003293 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00003294 if( nLocal>nKey ){
3295 nLocal = nKey;
3296 }
drh0e1c19e2004-05-11 00:58:56 +00003297 }
drhe51c44f2004-05-30 20:46:09 +00003298 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003299 return aPayload;
3300}
3301
3302
3303/*
drhe51c44f2004-05-30 20:46:09 +00003304** For the entry that cursor pCur is point to, return as
3305** many bytes of the key or data as are available on the local
3306** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00003307**
3308** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00003309** or be destroyed on the next call to any Btree routine,
3310** including calls from other threads against the same cache.
3311** Hence, a mutex on the BtShared should be held prior to calling
3312** this routine.
drh0e1c19e2004-05-11 00:58:56 +00003313**
3314** These routines is used to get quick access to key and data
3315** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00003316*/
drhe51c44f2004-05-30 20:46:09 +00003317const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
drh1fee73e2007-08-29 04:00:57 +00003318 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003319 if( pCur->eState==CURSOR_VALID ){
3320 return (const void*)fetchPayload(pCur, pAmt, 0);
3321 }
3322 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003323}
drhe51c44f2004-05-30 20:46:09 +00003324const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
drh1fee73e2007-08-29 04:00:57 +00003325 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003326 if( pCur->eState==CURSOR_VALID ){
3327 return (const void*)fetchPayload(pCur, pAmt, 1);
3328 }
3329 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003330}
3331
3332
3333/*
drh8178a752003-01-05 21:41:40 +00003334** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00003335** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00003336*/
drh3aac2dd2004-04-26 14:10:20 +00003337static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00003338 int rc;
3339 MemPage *pNewPage;
drh3aac2dd2004-04-26 14:10:20 +00003340 MemPage *pOldPage;
drhd0679ed2007-08-28 22:24:34 +00003341 BtShared *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00003342
drh1fee73e2007-08-29 04:00:57 +00003343 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003344 assert( pCur->eState==CURSOR_VALID );
drhde647132004-05-07 17:57:49 +00003345 rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00003346 if( rc ) return rc;
drh428ae8c2003-01-04 16:48:09 +00003347 pNewPage->idxParent = pCur->idx;
drh3aac2dd2004-04-26 14:10:20 +00003348 pOldPage = pCur->pPage;
3349 pOldPage->idxShift = 0;
3350 releasePage(pOldPage);
drh72f82862001-05-24 21:06:34 +00003351 pCur->pPage = pNewPage;
3352 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00003353 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003354 pCur->validNKey = 0;
drh4be295b2003-12-16 03:44:47 +00003355 if( pNewPage->nCell<1 ){
drh49285702005-09-17 15:20:26 +00003356 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00003357 }
drh72f82862001-05-24 21:06:34 +00003358 return SQLITE_OK;
3359}
3360
3361/*
drh8856d6a2004-04-29 14:42:46 +00003362** Return true if the page is the virtual root of its table.
3363**
3364** The virtual root page is the root page for most tables. But
3365** for the table rooted on page 1, sometime the real root page
3366** is empty except for the right-pointer. In such cases the
3367** virtual root page is the page that the right-pointer of page
3368** 1 is pointing to.
3369*/
drh16a9b832007-05-05 18:39:25 +00003370int sqlite3BtreeIsRootPage(MemPage *pPage){
drhd677b3d2007-08-20 22:48:41 +00003371 MemPage *pParent;
3372
drh1fee73e2007-08-29 04:00:57 +00003373 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00003374 pParent = pPage->pParent;
drhda200cc2004-05-09 11:51:38 +00003375 if( pParent==0 ) return 1;
3376 if( pParent->pgno>1 ) return 0;
3377 if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
drh8856d6a2004-04-29 14:42:46 +00003378 return 0;
3379}
3380
3381/*
drh5e2f8b92001-05-28 00:41:15 +00003382** Move the cursor up to the parent page.
3383**
3384** pCur->idx is set to the cell index that contains the pointer
3385** to the page we are coming from. If we are coming from the
3386** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00003387** the largest cell index.
drh72f82862001-05-24 21:06:34 +00003388*/
drh16a9b832007-05-05 18:39:25 +00003389void sqlite3BtreeMoveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00003390 MemPage *pParent;
drh8178a752003-01-05 21:41:40 +00003391 MemPage *pPage;
drh428ae8c2003-01-04 16:48:09 +00003392 int idxParent;
drh3aac2dd2004-04-26 14:10:20 +00003393
drh1fee73e2007-08-29 04:00:57 +00003394 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003395 assert( pCur->eState==CURSOR_VALID );
drh8178a752003-01-05 21:41:40 +00003396 pPage = pCur->pPage;
3397 assert( pPage!=0 );
drh16a9b832007-05-05 18:39:25 +00003398 assert( !sqlite3BtreeIsRootPage(pPage) );
drh8178a752003-01-05 21:41:40 +00003399 pParent = pPage->pParent;
3400 assert( pParent!=0 );
3401 idxParent = pPage->idxParent;
danielk19773b8a05f2007-03-19 17:44:26 +00003402 sqlite3PagerRef(pParent->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00003403 releasePage(pPage);
drh72f82862001-05-24 21:06:34 +00003404 pCur->pPage = pParent;
drh271efa52004-05-30 19:19:05 +00003405 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003406 pCur->validNKey = 0;
drh428ae8c2003-01-04 16:48:09 +00003407 assert( pParent->idxShift==0 );
drh43605152004-05-29 21:46:49 +00003408 pCur->idx = idxParent;
drh72f82862001-05-24 21:06:34 +00003409}
3410
3411/*
3412** Move the cursor to the root page
3413*/
drh5e2f8b92001-05-28 00:41:15 +00003414static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00003415 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00003416 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003417 Btree *p = pCur->pBtree;
3418 BtShared *pBt = p->pBt;
drhbd03cae2001-06-02 02:40:57 +00003419
drh1fee73e2007-08-29 04:00:57 +00003420 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +00003421 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
3422 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
3423 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
3424 if( pCur->eState>=CURSOR_REQUIRESEEK ){
3425 if( pCur->eState==CURSOR_FAULT ){
3426 return pCur->skip;
3427 }
drhbf700f32007-03-31 02:36:44 +00003428 clearCursorPosition(pCur);
3429 }
drh777e4c42006-01-13 04:31:58 +00003430 pRoot = pCur->pPage;
danielk197797a227c2006-01-20 16:32:04 +00003431 if( pRoot && pRoot->pgno==pCur->pgnoRoot ){
drh777e4c42006-01-13 04:31:58 +00003432 assert( pRoot->isInit );
3433 }else{
3434 if(
3435 SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0))
3436 ){
3437 pCur->eState = CURSOR_INVALID;
3438 return rc;
3439 }
3440 releasePage(pCur->pPage);
drh777e4c42006-01-13 04:31:58 +00003441 pCur->pPage = pRoot;
drhc39e0002004-05-07 23:50:57 +00003442 }
drh72f82862001-05-24 21:06:34 +00003443 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00003444 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003445 pCur->atLast = 0;
3446 pCur->validNKey = 0;
drh8856d6a2004-04-29 14:42:46 +00003447 if( pRoot->nCell==0 && !pRoot->leaf ){
3448 Pgno subpage;
3449 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00003450 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00003451 assert( subpage>0 );
danielk1977da184232006-01-05 11:34:32 +00003452 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00003453 rc = moveToChild(pCur, subpage);
drh8856d6a2004-04-29 14:42:46 +00003454 }
danielk1977da184232006-01-05 11:34:32 +00003455 pCur->eState = ((pCur->pPage->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
drh8856d6a2004-04-29 14:42:46 +00003456 return rc;
drh72f82862001-05-24 21:06:34 +00003457}
drh2af926b2001-05-15 00:39:25 +00003458
drh5e2f8b92001-05-28 00:41:15 +00003459/*
3460** Move the cursor down to the left-most leaf entry beneath the
3461** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00003462**
3463** The left-most leaf is the one with the smallest key - the first
3464** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00003465*/
3466static int moveToLeftmost(BtCursor *pCur){
3467 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00003468 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00003469 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00003470
drh1fee73e2007-08-29 04:00:57 +00003471 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003472 assert( pCur->eState==CURSOR_VALID );
drhd677b3d2007-08-20 22:48:41 +00003473 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
drha34b6762004-05-07 13:30:42 +00003474 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
danielk19771cc5ed82007-05-16 17:28:43 +00003475 pgno = get4byte(findCell(pPage, pCur->idx));
drh8178a752003-01-05 21:41:40 +00003476 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00003477 }
drhd677b3d2007-08-20 22:48:41 +00003478 return rc;
drh5e2f8b92001-05-28 00:41:15 +00003479}
3480
drh2dcc9aa2002-12-04 13:40:25 +00003481/*
3482** Move the cursor down to the right-most leaf entry beneath the
3483** page to which it is currently pointing. Notice the difference
3484** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
3485** finds the left-most entry beneath the *entry* whereas moveToRightmost()
3486** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00003487**
3488** The right-most entry is the one with the largest key - the last
3489** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00003490*/
3491static int moveToRightmost(BtCursor *pCur){
3492 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00003493 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00003494 MemPage *pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003495
drh1fee73e2007-08-29 04:00:57 +00003496 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003497 assert( pCur->eState==CURSOR_VALID );
drhd677b3d2007-08-20 22:48:41 +00003498 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
drh43605152004-05-29 21:46:49 +00003499 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh3aac2dd2004-04-26 14:10:20 +00003500 pCur->idx = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00003501 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003502 }
drhd677b3d2007-08-20 22:48:41 +00003503 if( rc==SQLITE_OK ){
3504 pCur->idx = pPage->nCell - 1;
3505 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003506 pCur->validNKey = 0;
drhd677b3d2007-08-20 22:48:41 +00003507 }
drh2dcc9aa2002-12-04 13:40:25 +00003508 return SQLITE_OK;
3509}
3510
drh5e00f6c2001-09-13 13:46:56 +00003511/* Move the cursor to the first entry in the table. Return SQLITE_OK
3512** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003513** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00003514*/
drh3aac2dd2004-04-26 14:10:20 +00003515int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00003516 int rc;
drhd677b3d2007-08-20 22:48:41 +00003517
drh1fee73e2007-08-29 04:00:57 +00003518 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003519 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00003520 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003521 if( rc==SQLITE_OK ){
3522 if( pCur->eState==CURSOR_INVALID ){
3523 assert( pCur->pPage->nCell==0 );
3524 *pRes = 1;
3525 rc = SQLITE_OK;
3526 }else{
3527 assert( pCur->pPage->nCell>0 );
3528 *pRes = 0;
3529 rc = moveToLeftmost(pCur);
3530 }
drh5e00f6c2001-09-13 13:46:56 +00003531 }
drh5e00f6c2001-09-13 13:46:56 +00003532 return rc;
3533}
drh5e2f8b92001-05-28 00:41:15 +00003534
drh9562b552002-02-19 15:00:07 +00003535/* Move the cursor to the last entry in the table. Return SQLITE_OK
3536** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003537** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00003538*/
drh3aac2dd2004-04-26 14:10:20 +00003539int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00003540 int rc;
drhd677b3d2007-08-20 22:48:41 +00003541
drh1fee73e2007-08-29 04:00:57 +00003542 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003543 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh9562b552002-02-19 15:00:07 +00003544 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003545 if( rc==SQLITE_OK ){
3546 if( CURSOR_INVALID==pCur->eState ){
3547 assert( pCur->pPage->nCell==0 );
3548 *pRes = 1;
3549 }else{
3550 assert( pCur->eState==CURSOR_VALID );
3551 *pRes = 0;
3552 rc = moveToRightmost(pCur);
drha2c20e42008-03-29 16:01:04 +00003553 getCellInfo(pCur);
3554 pCur->atLast = rc==SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003555 }
drh9562b552002-02-19 15:00:07 +00003556 }
drh9562b552002-02-19 15:00:07 +00003557 return rc;
3558}
3559
drhe14006d2008-03-25 17:23:32 +00003560/* Move the cursor so that it points to an entry near the key
3561** specified by pKey/nKey/pUnKey. Return a success code.
drh72f82862001-05-24 21:06:34 +00003562**
drhe14006d2008-03-25 17:23:32 +00003563** For INTKEY tables, only the nKey parameter is used. pKey
3564** and pUnKey must be NULL. For index tables, either pUnKey
3565** must point to a key that has already been unpacked, or else
3566** pKey/nKey describes a blob containing the key.
drh3aac2dd2004-04-26 14:10:20 +00003567**
drh5e2f8b92001-05-28 00:41:15 +00003568** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00003569** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00003570** were present. The cursor might point to an entry that comes
3571** before or after the key.
3572**
drhbd03cae2001-06-02 02:40:57 +00003573** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00003574** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00003575** this value is as follows:
3576**
3577** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00003578** is smaller than pKey or if the table is empty
3579** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00003580**
3581** *pRes==0 The cursor is left pointing at an entry that
3582** exactly matches pKey.
3583**
3584** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00003585** is larger than pKey.
drhd677b3d2007-08-20 22:48:41 +00003586**
drha059ad02001-04-17 20:09:11 +00003587*/
drhe4d90812007-03-29 05:51:49 +00003588int sqlite3BtreeMoveto(
3589 BtCursor *pCur, /* The cursor to be moved */
3590 const void *pKey, /* The key content for indices. Not used by tables */
drhe14006d2008-03-25 17:23:32 +00003591 UnpackedRecord *pUnKey,/* Unpacked version of pKey */
drhe4d90812007-03-29 05:51:49 +00003592 i64 nKey, /* Size of pKey. Or the key for tables */
3593 int biasRight, /* If true, bias the search to the high end */
3594 int *pRes /* Search result flag */
3595){
drh72f82862001-05-24 21:06:34 +00003596 int rc;
drh1e968a02008-03-25 00:22:21 +00003597 char aSpace[200];
drhd677b3d2007-08-20 22:48:41 +00003598
drh1fee73e2007-08-29 04:00:57 +00003599 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003600 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drha2c20e42008-03-29 16:01:04 +00003601
3602 /* If the cursor is already positioned at the point we are trying
3603 ** to move to, then just return without doing any work */
3604 if( pCur->eState==CURSOR_VALID && pCur->validNKey && pCur->pPage->intKey ){
3605 if( pCur->info.nKey==nKey ){
3606 *pRes = 0;
3607 return SQLITE_OK;
3608 }
3609 if( pCur->atLast && pCur->info.nKey<nKey ){
3610 *pRes = -1;
3611 return SQLITE_OK;
3612 }
3613 }
3614
3615
drh5e2f8b92001-05-28 00:41:15 +00003616 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003617 if( rc ){
3618 return rc;
3619 }
drhc39e0002004-05-07 23:50:57 +00003620 assert( pCur->pPage );
3621 assert( pCur->pPage->isInit );
danielk1977da184232006-01-05 11:34:32 +00003622 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00003623 *pRes = -1;
drhc39e0002004-05-07 23:50:57 +00003624 assert( pCur->pPage->nCell==0 );
3625 return SQLITE_OK;
3626 }
drh1e968a02008-03-25 00:22:21 +00003627 if( pCur->pPage->intKey ){
drhe14006d2008-03-25 17:23:32 +00003628 /* We are given an SQL table to search. The key is the integer
3629 ** rowid contained in nKey. pKey and pUnKey should both be NULL */
3630 assert( pUnKey==0 );
3631 assert( pKey==0 );
3632 }else if( pUnKey==0 ){
3633 /* We are to search an SQL index using a key encoded as a blob.
3634 ** The blob is found at pKey and is nKey bytes in length. Unpack
3635 ** this key so that we can use it. */
3636 assert( pKey!=0 );
3637 pUnKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, nKey, pKey,
drh1e968a02008-03-25 00:22:21 +00003638 aSpace, sizeof(aSpace));
drhe14006d2008-03-25 17:23:32 +00003639 if( pUnKey==0 ) return SQLITE_NOMEM;
3640 }else{
3641 /* We are to search an SQL index using a key that is already unpacked
3642 ** and handed to us in pUnKey. */
3643 assert( pKey==0 );
drh1e968a02008-03-25 00:22:21 +00003644 }
drh14684382006-11-30 13:05:29 +00003645 for(;;){
drh72f82862001-05-24 21:06:34 +00003646 int lwr, upr;
3647 Pgno chldPg;
3648 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00003649 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00003650 lwr = 0;
3651 upr = pPage->nCell-1;
drhe14006d2008-03-25 17:23:32 +00003652 if( !pPage->intKey && pUnKey==0 ){
drh1e968a02008-03-25 00:22:21 +00003653 rc = SQLITE_CORRUPT_BKPT;
3654 goto moveto_finish;
drh4eec4c12005-01-21 00:22:37 +00003655 }
drhe4d90812007-03-29 05:51:49 +00003656 if( biasRight ){
3657 pCur->idx = upr;
3658 }else{
3659 pCur->idx = (upr+lwr)/2;
3660 }
drhf1d68b32007-03-29 04:43:26 +00003661 if( lwr<=upr ) for(;;){
danielk197713adf8a2004-06-03 16:08:41 +00003662 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00003663 i64 nCellKey;
drh366fda62006-01-13 02:35:09 +00003664 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003665 pCur->validNKey = 1;
drh3aac2dd2004-04-26 14:10:20 +00003666 if( pPage->intKey ){
drh777e4c42006-01-13 04:31:58 +00003667 u8 *pCell;
danielk19771cc5ed82007-05-16 17:28:43 +00003668 pCell = findCell(pPage, pCur->idx) + pPage->childPtrSize;
drhd172f862006-01-12 15:01:15 +00003669 if( pPage->hasData ){
danielk1977bab45c62006-01-16 15:14:27 +00003670 u32 dummy;
drhd172f862006-01-12 15:01:15 +00003671 pCell += getVarint32(pCell, &dummy);
3672 }
drha2c20e42008-03-29 16:01:04 +00003673 getVarint(pCell, (u64*)&nCellKey);
drh3aac2dd2004-04-26 14:10:20 +00003674 if( nCellKey<nKey ){
3675 c = -1;
3676 }else if( nCellKey>nKey ){
3677 c = +1;
3678 }else{
3679 c = 0;
3680 }
drh3aac2dd2004-04-26 14:10:20 +00003681 }else{
drhe51c44f2004-05-30 20:46:09 +00003682 int available;
danielk197713adf8a2004-06-03 16:08:41 +00003683 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drh366fda62006-01-13 02:35:09 +00003684 nCellKey = pCur->info.nKey;
drhe51c44f2004-05-30 20:46:09 +00003685 if( available>=nCellKey ){
drhe14006d2008-03-25 17:23:32 +00003686 c = sqlite3VdbeRecordCompare(nCellKey, pCellKey, pUnKey);
drhe51c44f2004-05-30 20:46:09 +00003687 }else{
drh17435752007-08-16 04:30:38 +00003688 pCellKey = sqlite3_malloc( nCellKey );
danielk19776507ecb2008-03-25 09:56:44 +00003689 if( pCellKey==0 ){
3690 rc = SQLITE_NOMEM;
3691 goto moveto_finish;
3692 }
danielk197713adf8a2004-06-03 16:08:41 +00003693 rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
drhe14006d2008-03-25 17:23:32 +00003694 c = sqlite3VdbeRecordCompare(nCellKey, pCellKey, pUnKey);
drh17435752007-08-16 04:30:38 +00003695 sqlite3_free(pCellKey);
drh1e968a02008-03-25 00:22:21 +00003696 if( rc ) goto moveto_finish;
drhe51c44f2004-05-30 20:46:09 +00003697 }
drh3aac2dd2004-04-26 14:10:20 +00003698 }
drh72f82862001-05-24 21:06:34 +00003699 if( c==0 ){
drha2c20e42008-03-29 16:01:04 +00003700 pCur->info.nKey = nCellKey;
drh8b18dd42004-05-12 19:18:15 +00003701 if( pPage->leafData && !pPage->leaf ){
drhfc70e6f2004-05-12 21:11:27 +00003702 lwr = pCur->idx;
3703 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00003704 break;
3705 }else{
drh8b18dd42004-05-12 19:18:15 +00003706 if( pRes ) *pRes = 0;
drh1e968a02008-03-25 00:22:21 +00003707 rc = SQLITE_OK;
3708 goto moveto_finish;
drh8b18dd42004-05-12 19:18:15 +00003709 }
drh72f82862001-05-24 21:06:34 +00003710 }
3711 if( c<0 ){
3712 lwr = pCur->idx+1;
3713 }else{
3714 upr = pCur->idx-1;
3715 }
drhf1d68b32007-03-29 04:43:26 +00003716 if( lwr>upr ){
drha2c20e42008-03-29 16:01:04 +00003717 pCur->info.nKey = nCellKey;
drhf1d68b32007-03-29 04:43:26 +00003718 break;
3719 }
3720 pCur->idx = (lwr+upr)/2;
drh72f82862001-05-24 21:06:34 +00003721 }
3722 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00003723 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00003724 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00003725 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00003726 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00003727 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00003728 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00003729 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00003730 }
3731 if( chldPg==0 ){
drhc39e0002004-05-07 23:50:57 +00003732 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00003733 if( pRes ) *pRes = c;
drh1e968a02008-03-25 00:22:21 +00003734 rc = SQLITE_OK;
3735 goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00003736 }
drh428ae8c2003-01-04 16:48:09 +00003737 pCur->idx = lwr;
drh271efa52004-05-30 19:19:05 +00003738 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003739 pCur->validNKey = 0;
drh8178a752003-01-05 21:41:40 +00003740 rc = moveToChild(pCur, chldPg);
drh1e968a02008-03-25 00:22:21 +00003741 if( rc ) goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00003742 }
drh1e968a02008-03-25 00:22:21 +00003743moveto_finish:
drhe14006d2008-03-25 17:23:32 +00003744 if( pKey ){
3745 /* If we created our own unpacked key at the top of this
3746 ** procedure, then destroy that key before returning. */
3747 sqlite3VdbeDeleteUnpackedRecord(pUnKey);
3748 }
drh1e968a02008-03-25 00:22:21 +00003749 return rc;
drh72f82862001-05-24 21:06:34 +00003750}
3751
drhd677b3d2007-08-20 22:48:41 +00003752
drh72f82862001-05-24 21:06:34 +00003753/*
drhc39e0002004-05-07 23:50:57 +00003754** Return TRUE if the cursor is not pointing at an entry of the table.
3755**
3756** TRUE will be returned after a call to sqlite3BtreeNext() moves
3757** past the last entry in the table or sqlite3BtreePrev() moves past
3758** the first entry. TRUE is also returned if the table is empty.
3759*/
3760int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00003761 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
3762 ** have been deleted? This API will need to change to return an error code
3763 ** as well as the boolean result value.
3764 */
3765 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00003766}
3767
3768/*
drhb21c8cd2007-08-21 19:33:56 +00003769** Return the database connection handle for a cursor.
3770*/
3771sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){
drhe5fe6902007-12-07 18:55:28 +00003772 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
3773 return pCur->pBtree->db;
drhb21c8cd2007-08-21 19:33:56 +00003774}
3775
3776/*
drhbd03cae2001-06-02 02:40:57 +00003777** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00003778** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00003779** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00003780** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00003781*/
drhd677b3d2007-08-20 22:48:41 +00003782static int btreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00003783 int rc;
danielk197797a227c2006-01-20 16:32:04 +00003784 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00003785
drh1fee73e2007-08-29 04:00:57 +00003786 assert( cursorHoldsMutex(pCur) );
drhbf700f32007-03-31 02:36:44 +00003787 rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003788 if( rc!=SQLITE_OK ){
3789 return rc;
3790 }
drh8c4d3a62007-04-06 01:03:32 +00003791 assert( pRes!=0 );
3792 pPage = pCur->pPage;
3793 if( CURSOR_INVALID==pCur->eState ){
3794 *pRes = 1;
3795 return SQLITE_OK;
3796 }
danielk1977da184232006-01-05 11:34:32 +00003797 if( pCur->skip>0 ){
3798 pCur->skip = 0;
3799 *pRes = 0;
3800 return SQLITE_OK;
3801 }
3802 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00003803
drh8178a752003-01-05 21:41:40 +00003804 assert( pPage->isInit );
drh8178a752003-01-05 21:41:40 +00003805 assert( pCur->idx<pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00003806
drh72f82862001-05-24 21:06:34 +00003807 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00003808 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003809 pCur->validNKey = 0;
drh8178a752003-01-05 21:41:40 +00003810 if( pCur->idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00003811 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003812 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00003813 if( rc ) return rc;
3814 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003815 *pRes = 0;
3816 return rc;
drh72f82862001-05-24 21:06:34 +00003817 }
drh5e2f8b92001-05-28 00:41:15 +00003818 do{
drh16a9b832007-05-05 18:39:25 +00003819 if( sqlite3BtreeIsRootPage(pPage) ){
drh8c1238a2003-01-02 14:43:55 +00003820 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00003821 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00003822 return SQLITE_OK;
3823 }
drh16a9b832007-05-05 18:39:25 +00003824 sqlite3BtreeMoveToParent(pCur);
drh8178a752003-01-05 21:41:40 +00003825 pPage = pCur->pPage;
3826 }while( pCur->idx>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00003827 *pRes = 0;
drh8b18dd42004-05-12 19:18:15 +00003828 if( pPage->leafData ){
3829 rc = sqlite3BtreeNext(pCur, pRes);
3830 }else{
3831 rc = SQLITE_OK;
3832 }
3833 return rc;
drh8178a752003-01-05 21:41:40 +00003834 }
3835 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00003836 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00003837 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00003838 }
drh5e2f8b92001-05-28 00:41:15 +00003839 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003840 return rc;
drh72f82862001-05-24 21:06:34 +00003841}
drhd677b3d2007-08-20 22:48:41 +00003842int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
3843 int rc;
drh1fee73e2007-08-29 04:00:57 +00003844 assert( cursorHoldsMutex(pCur) );
drhd677b3d2007-08-20 22:48:41 +00003845 rc = btreeNext(pCur, pRes);
drhd677b3d2007-08-20 22:48:41 +00003846 return rc;
3847}
3848
drh72f82862001-05-24 21:06:34 +00003849
drh3b7511c2001-05-26 13:15:44 +00003850/*
drh2dcc9aa2002-12-04 13:40:25 +00003851** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00003852** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00003853** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00003854** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00003855*/
drhd677b3d2007-08-20 22:48:41 +00003856static int btreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00003857 int rc;
3858 Pgno pgno;
drh8178a752003-01-05 21:41:40 +00003859 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00003860
drh1fee73e2007-08-29 04:00:57 +00003861 assert( cursorHoldsMutex(pCur) );
drhbf700f32007-03-31 02:36:44 +00003862 rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003863 if( rc!=SQLITE_OK ){
3864 return rc;
3865 }
drha2c20e42008-03-29 16:01:04 +00003866 pCur->atLast = 0;
drh8c4d3a62007-04-06 01:03:32 +00003867 if( CURSOR_INVALID==pCur->eState ){
3868 *pRes = 1;
3869 return SQLITE_OK;
3870 }
danielk1977da184232006-01-05 11:34:32 +00003871 if( pCur->skip<0 ){
3872 pCur->skip = 0;
3873 *pRes = 0;
3874 return SQLITE_OK;
3875 }
3876 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00003877
drh8178a752003-01-05 21:41:40 +00003878 pPage = pCur->pPage;
drh8178a752003-01-05 21:41:40 +00003879 assert( pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00003880 assert( pCur->idx>=0 );
drha34b6762004-05-07 13:30:42 +00003881 if( !pPage->leaf ){
danielk19771cc5ed82007-05-16 17:28:43 +00003882 pgno = get4byte( findCell(pPage, pCur->idx) );
drh8178a752003-01-05 21:41:40 +00003883 rc = moveToChild(pCur, pgno);
drhd677b3d2007-08-20 22:48:41 +00003884 if( rc ){
3885 return rc;
3886 }
drh2dcc9aa2002-12-04 13:40:25 +00003887 rc = moveToRightmost(pCur);
3888 }else{
3889 while( pCur->idx==0 ){
drh16a9b832007-05-05 18:39:25 +00003890 if( sqlite3BtreeIsRootPage(pPage) ){
danielk1977da184232006-01-05 11:34:32 +00003891 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00003892 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00003893 return SQLITE_OK;
3894 }
drh16a9b832007-05-05 18:39:25 +00003895 sqlite3BtreeMoveToParent(pCur);
drh8178a752003-01-05 21:41:40 +00003896 pPage = pCur->pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003897 }
3898 pCur->idx--;
drh271efa52004-05-30 19:19:05 +00003899 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003900 pCur->validNKey = 0;
drh8237d452004-11-22 19:07:09 +00003901 if( pPage->leafData && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00003902 rc = sqlite3BtreePrevious(pCur, pRes);
3903 }else{
3904 rc = SQLITE_OK;
3905 }
drh2dcc9aa2002-12-04 13:40:25 +00003906 }
drh8178a752003-01-05 21:41:40 +00003907 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003908 return rc;
3909}
drhd677b3d2007-08-20 22:48:41 +00003910int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
3911 int rc;
drh1fee73e2007-08-29 04:00:57 +00003912 assert( cursorHoldsMutex(pCur) );
drhd677b3d2007-08-20 22:48:41 +00003913 rc = btreePrevious(pCur, pRes);
drhd677b3d2007-08-20 22:48:41 +00003914 return rc;
3915}
drh2dcc9aa2002-12-04 13:40:25 +00003916
3917/*
drh3b7511c2001-05-26 13:15:44 +00003918** Allocate a new page from the database file.
3919**
danielk19773b8a05f2007-03-19 17:44:26 +00003920** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00003921** has already been called on the new page.) The new page has also
3922** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00003923** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00003924**
3925** SQLITE_OK is returned on success. Any other return value indicates
3926** an error. *ppPage and *pPgno are undefined in the event of an error.
danielk19773b8a05f2007-03-19 17:44:26 +00003927** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00003928**
drh199e3cf2002-07-18 11:01:47 +00003929** If the "nearby" parameter is not 0, then a (feeble) effort is made to
3930** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00003931** attempt to keep related pages close to each other in the database file,
3932** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00003933**
3934** If the "exact" parameter is not 0, and the page-number nearby exists
3935** anywhere on the free-list, then it is guarenteed to be returned. This
3936** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00003937*/
drh4f0c5872007-03-26 22:05:01 +00003938static int allocateBtreePage(
danielk1977aef0bf62005-12-30 16:28:01 +00003939 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00003940 MemPage **ppPage,
3941 Pgno *pPgno,
3942 Pgno nearby,
3943 u8 exact
3944){
drh3aac2dd2004-04-26 14:10:20 +00003945 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00003946 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003947 int n; /* Number of pages on the freelist */
3948 int k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00003949 MemPage *pTrunk = 0;
3950 MemPage *pPrevTrunk = 0;
drh30e58752002-03-02 20:41:57 +00003951
drh1fee73e2007-08-29 04:00:57 +00003952 assert( sqlite3_mutex_held(pBt->mutex) );
drh3aac2dd2004-04-26 14:10:20 +00003953 pPage1 = pBt->pPage1;
3954 n = get4byte(&pPage1->aData[36]);
3955 if( n>0 ){
drh91025292004-05-03 19:49:32 +00003956 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00003957 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003958 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
3959
3960 /* If the 'exact' parameter was true and a query of the pointer-map
3961 ** shows that the page 'nearby' is somewhere on the free-list, then
3962 ** the entire-list will be searched for that page.
3963 */
3964#ifndef SQLITE_OMIT_AUTOVACUUM
danielk19774ef24492007-05-23 09:52:41 +00003965 if( exact && nearby<=sqlite3PagerPagecount(pBt->pPager) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00003966 u8 eType;
3967 assert( nearby>0 );
3968 assert( pBt->autoVacuum );
3969 rc = ptrmapGet(pBt, nearby, &eType, 0);
3970 if( rc ) return rc;
3971 if( eType==PTRMAP_FREEPAGE ){
3972 searchList = 1;
3973 }
3974 *pPgno = nearby;
3975 }
3976#endif
3977
3978 /* Decrement the free-list count by 1. Set iTrunk to the index of the
3979 ** first free-list trunk page. iPrevTrunk is initially 1.
3980 */
danielk19773b8a05f2007-03-19 17:44:26 +00003981 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00003982 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003983 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003984
3985 /* The code within this loop is run only once if the 'searchList' variable
3986 ** is not true. Otherwise, it runs once for each trunk-page on the
3987 ** free-list until the page 'nearby' is located.
3988 */
3989 do {
3990 pPrevTrunk = pTrunk;
3991 if( pPrevTrunk ){
3992 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00003993 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00003994 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00003995 }
drh16a9b832007-05-05 18:39:25 +00003996 rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003997 if( rc ){
drhd3627af2006-12-18 18:34:51 +00003998 pTrunk = 0;
3999 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004000 }
4001
4002 k = get4byte(&pTrunk->aData[4]);
4003 if( k==0 && !searchList ){
4004 /* The trunk has no leaves and the list is not being searched.
4005 ** So extract the trunk page itself and use it as the newly
4006 ** allocated page */
4007 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00004008 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004009 if( rc ){
4010 goto end_allocate_page;
4011 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004012 *pPgno = iTrunk;
4013 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4014 *ppPage = pTrunk;
4015 pTrunk = 0;
4016 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
4017 }else if( k>pBt->usableSize/4 - 8 ){
4018 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00004019 rc = SQLITE_CORRUPT_BKPT;
4020 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004021#ifndef SQLITE_OMIT_AUTOVACUUM
4022 }else if( searchList && nearby==iTrunk ){
4023 /* The list is being searched and this trunk page is the page
4024 ** to allocate, regardless of whether it has leaves.
4025 */
4026 assert( *pPgno==iTrunk );
4027 *ppPage = pTrunk;
4028 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00004029 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004030 if( rc ){
4031 goto end_allocate_page;
4032 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004033 if( k==0 ){
4034 if( !pPrevTrunk ){
4035 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4036 }else{
4037 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
4038 }
4039 }else{
4040 /* The trunk page is required by the caller but it contains
4041 ** pointers to free-list leaves. The first leaf becomes a trunk
4042 ** page in this case.
4043 */
4044 MemPage *pNewTrunk;
4045 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh16a9b832007-05-05 18:39:25 +00004046 rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004047 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00004048 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004049 }
danielk19773b8a05f2007-03-19 17:44:26 +00004050 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004051 if( rc!=SQLITE_OK ){
4052 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00004053 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004054 }
4055 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
4056 put4byte(&pNewTrunk->aData[4], k-1);
4057 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00004058 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004059 if( !pPrevTrunk ){
4060 put4byte(&pPage1->aData[32], iNewTrunk);
4061 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00004062 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004063 if( rc ){
4064 goto end_allocate_page;
4065 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004066 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
4067 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004068 }
4069 pTrunk = 0;
4070 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
4071#endif
4072 }else{
4073 /* Extract a leaf from the trunk */
4074 int closest;
4075 Pgno iPage;
4076 unsigned char *aData = pTrunk->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00004077 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004078 if( rc ){
4079 goto end_allocate_page;
4080 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004081 if( nearby>0 ){
4082 int i, dist;
4083 closest = 0;
4084 dist = get4byte(&aData[8]) - nearby;
4085 if( dist<0 ) dist = -dist;
4086 for(i=1; i<k; i++){
4087 int d2 = get4byte(&aData[8+i*4]) - nearby;
4088 if( d2<0 ) d2 = -d2;
4089 if( d2<dist ){
4090 closest = i;
4091 dist = d2;
4092 }
4093 }
4094 }else{
4095 closest = 0;
4096 }
4097
4098 iPage = get4byte(&aData[8+closest*4]);
4099 if( !searchList || iPage==nearby ){
4100 *pPgno = iPage;
danielk19773b8a05f2007-03-19 17:44:26 +00004101 if( *pPgno>sqlite3PagerPagecount(pBt->pPager) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004102 /* Free page off the end of the file */
drh49285702005-09-17 15:20:26 +00004103 return SQLITE_CORRUPT_BKPT;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004104 }
4105 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
4106 ": %d more free pages\n",
4107 *pPgno, closest+1, k, pTrunk->pgno, n-1));
4108 if( closest<k-1 ){
4109 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
4110 }
4111 put4byte(&aData[4], k-1);
drh16a9b832007-05-05 18:39:25 +00004112 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004113 if( rc==SQLITE_OK ){
drh538f5702007-04-13 02:14:30 +00004114 sqlite3PagerDontRollback((*ppPage)->pDbPage);
danielk19773b8a05f2007-03-19 17:44:26 +00004115 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004116 if( rc!=SQLITE_OK ){
4117 releasePage(*ppPage);
4118 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004119 }
4120 searchList = 0;
4121 }
drhee696e22004-08-30 16:52:17 +00004122 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004123 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00004124 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004125 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00004126 }else{
drh3aac2dd2004-04-26 14:10:20 +00004127 /* There are no pages on the freelist, so create a new page at the
4128 ** end of the file */
danielk19773b8a05f2007-03-19 17:44:26 +00004129 *pPgno = sqlite3PagerPagecount(pBt->pPager) + 1;
danielk1977afcdd022004-10-31 16:25:42 +00004130
4131#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00004132 if( pBt->nTrunc ){
4133 /* An incr-vacuum has already run within this transaction. So the
4134 ** page to allocate is not from the physical end of the file, but
4135 ** at pBt->nTrunc.
4136 */
4137 *pPgno = pBt->nTrunc+1;
4138 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
4139 (*pPgno)++;
4140 }
4141 }
danielk1977266664d2006-02-10 08:24:21 +00004142 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00004143 /* If *pPgno refers to a pointer-map page, allocate two new pages
4144 ** at the end of the file instead of one. The first allocated page
4145 ** becomes a new pointer-map page, the second is used by the caller.
4146 */
4147 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00004148 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977afcdd022004-10-31 16:25:42 +00004149 (*pPgno)++;
drh72190432008-01-31 14:54:43 +00004150 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
danielk1977afcdd022004-10-31 16:25:42 +00004151 }
danielk1977dddbcdc2007-04-26 14:42:34 +00004152 if( pBt->nTrunc ){
4153 pBt->nTrunc = *pPgno;
4154 }
danielk1977afcdd022004-10-31 16:25:42 +00004155#endif
4156
danielk1977599fcba2004-11-08 07:13:13 +00004157 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh16a9b832007-05-05 18:39:25 +00004158 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
drh3b7511c2001-05-26 13:15:44 +00004159 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00004160 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004161 if( rc!=SQLITE_OK ){
4162 releasePage(*ppPage);
4163 }
drh3a4c1412004-05-09 20:40:11 +00004164 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00004165 }
danielk1977599fcba2004-11-08 07:13:13 +00004166
4167 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00004168
4169end_allocate_page:
4170 releasePage(pTrunk);
4171 releasePage(pPrevTrunk);
drh3b7511c2001-05-26 13:15:44 +00004172 return rc;
4173}
4174
4175/*
drh3aac2dd2004-04-26 14:10:20 +00004176** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00004177**
danielk19773b8a05f2007-03-19 17:44:26 +00004178** sqlite3PagerUnref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00004179*/
drh3aac2dd2004-04-26 14:10:20 +00004180static int freePage(MemPage *pPage){
danielk1977aef0bf62005-12-30 16:28:01 +00004181 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00004182 MemPage *pPage1 = pBt->pPage1;
4183 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00004184
drh3aac2dd2004-04-26 14:10:20 +00004185 /* Prepare the page for freeing */
drh1fee73e2007-08-29 04:00:57 +00004186 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh3aac2dd2004-04-26 14:10:20 +00004187 assert( pPage->pgno>1 );
4188 pPage->isInit = 0;
4189 releasePage(pPage->pParent);
4190 pPage->pParent = 0;
4191
drha34b6762004-05-07 13:30:42 +00004192 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00004193 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00004194 if( rc ) return rc;
4195 n = get4byte(&pPage1->aData[36]);
4196 put4byte(&pPage1->aData[36], n+1);
4197
drhfcce93f2006-02-22 03:08:32 +00004198#ifdef SQLITE_SECURE_DELETE
4199 /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
4200 ** always fully overwrite deleted information with zeros.
4201 */
danielk19773b8a05f2007-03-19 17:44:26 +00004202 rc = sqlite3PagerWrite(pPage->pDbPage);
drhfcce93f2006-02-22 03:08:32 +00004203 if( rc ) return rc;
4204 memset(pPage->aData, 0, pPage->pBt->pageSize);
4205#endif
4206
danielk1977687566d2004-11-02 12:56:41 +00004207#ifndef SQLITE_OMIT_AUTOVACUUM
4208 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00004209 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00004210 */
4211 if( pBt->autoVacuum ){
4212 rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
danielk1977a64a0352004-11-05 01:45:13 +00004213 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00004214 }
4215#endif
4216
drh3aac2dd2004-04-26 14:10:20 +00004217 if( n==0 ){
4218 /* This is the first free page */
danielk19773b8a05f2007-03-19 17:44:26 +00004219 rc = sqlite3PagerWrite(pPage->pDbPage);
drhda200cc2004-05-09 11:51:38 +00004220 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004221 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00004222 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00004223 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00004224 }else{
4225 /* Other free pages already exist. Retrive the first trunk page
4226 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00004227 MemPage *pTrunk;
drh16a9b832007-05-05 18:39:25 +00004228 rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0);
drh3b7511c2001-05-26 13:15:44 +00004229 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004230 k = get4byte(&pTrunk->aData[4]);
drhee696e22004-08-30 16:52:17 +00004231 if( k>=pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00004232 /* The trunk is full. Turn the page being freed into a new
4233 ** trunk page with no leaves. */
danielk19773b8a05f2007-03-19 17:44:26 +00004234 rc = sqlite3PagerWrite(pPage->pDbPage);
drhb9ee4932007-09-07 14:32:06 +00004235 if( rc==SQLITE_OK ){
4236 put4byte(pPage->aData, pTrunk->pgno);
4237 put4byte(&pPage->aData[4], 0);
4238 put4byte(&pPage1->aData[32], pPage->pgno);
4239 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
4240 pPage->pgno, pTrunk->pgno));
4241 }
4242 }else if( k<0 ){
4243 rc = SQLITE_CORRUPT;
drh3aac2dd2004-04-26 14:10:20 +00004244 }else{
4245 /* Add the newly freed page as a leaf on the current trunk */
danielk19773b8a05f2007-03-19 17:44:26 +00004246 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00004247 if( rc==SQLITE_OK ){
4248 put4byte(&pTrunk->aData[4], k+1);
4249 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drhfcce93f2006-02-22 03:08:32 +00004250#ifndef SQLITE_SECURE_DELETE
drh538f5702007-04-13 02:14:30 +00004251 sqlite3PagerDontWrite(pPage->pDbPage);
drhfcce93f2006-02-22 03:08:32 +00004252#endif
drhf5345442007-04-09 12:45:02 +00004253 }
drh3a4c1412004-05-09 20:40:11 +00004254 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00004255 }
4256 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00004257 }
drh3b7511c2001-05-26 13:15:44 +00004258 return rc;
4259}
4260
4261/*
drh3aac2dd2004-04-26 14:10:20 +00004262** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00004263*/
drh3aac2dd2004-04-26 14:10:20 +00004264static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00004265 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00004266 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00004267 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00004268 int rc;
drh94440812007-03-06 11:42:19 +00004269 int nOvfl;
4270 int ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00004271
drh1fee73e2007-08-29 04:00:57 +00004272 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh16a9b832007-05-05 18:39:25 +00004273 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004274 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00004275 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00004276 }
drh6f11bef2004-05-13 01:12:56 +00004277 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh94440812007-03-06 11:42:19 +00004278 ovflPageSize = pBt->usableSize - 4;
drh72365832007-03-06 15:53:44 +00004279 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
4280 assert( ovflPgno==0 || nOvfl>0 );
4281 while( nOvfl-- ){
drh3aac2dd2004-04-26 14:10:20 +00004282 MemPage *pOvfl;
danielk19773b8a05f2007-03-19 17:44:26 +00004283 if( ovflPgno==0 || ovflPgno>sqlite3PagerPagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00004284 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00004285 }
danielk19778c0a9592007-04-30 16:55:00 +00004286
4287 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno);
drh3b7511c2001-05-26 13:15:44 +00004288 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00004289 rc = freePage(pOvfl);
danielk19773b8a05f2007-03-19 17:44:26 +00004290 sqlite3PagerUnref(pOvfl->pDbPage);
danielk19776b456a22005-03-21 04:04:02 +00004291 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00004292 }
drh5e2f8b92001-05-28 00:41:15 +00004293 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00004294}
4295
4296/*
drh91025292004-05-03 19:49:32 +00004297** Create the byte sequence used to represent a cell on page pPage
4298** and write that byte sequence into pCell[]. Overflow pages are
4299** allocated and filled in as necessary. The calling procedure
4300** is responsible for making sure sufficient space has been allocated
4301** for pCell[].
4302**
4303** Note that pCell does not necessary need to point to the pPage->aData
4304** area. pCell might point to some temporary storage. The cell will
4305** be constructed in this temporary area then copied into pPage->aData
4306** later.
drh3b7511c2001-05-26 13:15:44 +00004307*/
4308static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00004309 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00004310 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00004311 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00004312 const void *pData,int nData, /* The data */
drhb026e052007-05-02 01:34:31 +00004313 int nZero, /* Extra zero bytes to append to pData */
drh4b70f112004-05-02 21:12:19 +00004314 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00004315){
drh3b7511c2001-05-26 13:15:44 +00004316 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00004317 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00004318 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00004319 int spaceLeft;
4320 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00004321 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00004322 unsigned char *pPrior;
4323 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00004324 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00004325 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00004326 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00004327 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00004328
drh1fee73e2007-08-29 04:00:57 +00004329 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00004330
drh91025292004-05-03 19:49:32 +00004331 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00004332 nHeader = 0;
drh91025292004-05-03 19:49:32 +00004333 if( !pPage->leaf ){
4334 nHeader += 4;
4335 }
drh8b18dd42004-05-12 19:18:15 +00004336 if( pPage->hasData ){
drhb026e052007-05-02 01:34:31 +00004337 nHeader += putVarint(&pCell[nHeader], nData+nZero);
drh6f11bef2004-05-13 01:12:56 +00004338 }else{
drhb026e052007-05-02 01:34:31 +00004339 nData = nZero = 0;
drh91025292004-05-03 19:49:32 +00004340 }
drh6f11bef2004-05-13 01:12:56 +00004341 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh16a9b832007-05-05 18:39:25 +00004342 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004343 assert( info.nHeader==nHeader );
4344 assert( info.nKey==nKey );
drhb026e052007-05-02 01:34:31 +00004345 assert( info.nData==nData+nZero );
drh6f11bef2004-05-13 01:12:56 +00004346
4347 /* Fill in the payload */
drhb026e052007-05-02 01:34:31 +00004348 nPayload = nData + nZero;
drh3aac2dd2004-04-26 14:10:20 +00004349 if( pPage->intKey ){
4350 pSrc = pData;
4351 nSrc = nData;
drh91025292004-05-03 19:49:32 +00004352 nData = 0;
drh3aac2dd2004-04-26 14:10:20 +00004353 }else{
4354 nPayload += nKey;
4355 pSrc = pKey;
4356 nSrc = nKey;
4357 }
drh6f11bef2004-05-13 01:12:56 +00004358 *pnSize = info.nSize;
4359 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00004360 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00004361 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00004362
drh3b7511c2001-05-26 13:15:44 +00004363 while( nPayload>0 ){
4364 if( spaceLeft==0 ){
danielk1977b39f70b2007-05-17 18:28:11 +00004365 int isExact = 0;
danielk1977afcdd022004-10-31 16:25:42 +00004366#ifndef SQLITE_OMIT_AUTOVACUUM
4367 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00004368 if( pBt->autoVacuum ){
4369 do{
4370 pgnoOvfl++;
4371 } while(
4372 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
4373 );
danielk197789a4be82007-05-23 13:34:32 +00004374 if( pgnoOvfl>1 ){
danielk1977b39f70b2007-05-17 18:28:11 +00004375 /* isExact = 1; */
4376 }
4377 }
danielk1977afcdd022004-10-31 16:25:42 +00004378#endif
danielk1977b39f70b2007-05-17 18:28:11 +00004379 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, isExact);
danielk1977afcdd022004-10-31 16:25:42 +00004380#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00004381 /* If the database supports auto-vacuum, and the second or subsequent
4382 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00004383 ** for that page now.
4384 **
4385 ** If this is the first overflow page, then write a partial entry
4386 ** to the pointer-map. If we write nothing to this pointer-map slot,
4387 ** then the optimistic overflow chain processing in clearCell()
4388 ** may misinterpret the uninitialised values and delete the
4389 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00004390 */
danielk19774ef24492007-05-23 09:52:41 +00004391 if( pBt->autoVacuum && rc==SQLITE_OK ){
4392 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
4393 rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
danielk197789a4be82007-05-23 13:34:32 +00004394 if( rc ){
4395 releasePage(pOvfl);
4396 }
danielk1977afcdd022004-10-31 16:25:42 +00004397 }
4398#endif
drh3b7511c2001-05-26 13:15:44 +00004399 if( rc ){
drh9b171272004-05-08 02:03:22 +00004400 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00004401 return rc;
4402 }
drh3aac2dd2004-04-26 14:10:20 +00004403 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00004404 releasePage(pToRelease);
4405 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00004406 pPrior = pOvfl->aData;
4407 put4byte(pPrior, 0);
4408 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00004409 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00004410 }
4411 n = nPayload;
4412 if( n>spaceLeft ) n = spaceLeft;
drhb026e052007-05-02 01:34:31 +00004413 if( nSrc>0 ){
4414 if( n>nSrc ) n = nSrc;
4415 assert( pSrc );
4416 memcpy(pPayload, pSrc, n);
4417 }else{
4418 memset(pPayload, 0, n);
4419 }
drh3b7511c2001-05-26 13:15:44 +00004420 nPayload -= n;
drhde647132004-05-07 17:57:49 +00004421 pPayload += n;
drh9b171272004-05-08 02:03:22 +00004422 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00004423 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00004424 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00004425 if( nSrc==0 ){
4426 nSrc = nData;
4427 pSrc = pData;
4428 }
drhdd793422001-06-28 01:54:48 +00004429 }
drh9b171272004-05-08 02:03:22 +00004430 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00004431 return SQLITE_OK;
4432}
4433
4434/*
drhbd03cae2001-06-02 02:40:57 +00004435** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00004436** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00004437** pointer in the third argument.
4438*/
danielk1977aef0bf62005-12-30 16:28:01 +00004439static int reparentPage(BtShared *pBt, Pgno pgno, MemPage *pNewParent, int idx){
drhbd03cae2001-06-02 02:40:57 +00004440 MemPage *pThis;
danielk19773b8a05f2007-03-19 17:44:26 +00004441 DbPage *pDbPage;
drhbd03cae2001-06-02 02:40:57 +00004442
drh1fee73e2007-08-29 04:00:57 +00004443 assert( sqlite3_mutex_held(pBt->mutex) );
drh43617e92006-03-06 20:55:46 +00004444 assert( pNewParent!=0 );
danielk1977afcdd022004-10-31 16:25:42 +00004445 if( pgno==0 ) return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00004446 assert( pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00004447 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
4448 if( pDbPage ){
4449 pThis = (MemPage *)sqlite3PagerGetExtra(pDbPage);
drhda200cc2004-05-09 11:51:38 +00004450 if( pThis->isInit ){
drhbf4bca52007-09-06 22:19:14 +00004451 assert( pThis->aData==sqlite3PagerGetData(pDbPage) );
drhda200cc2004-05-09 11:51:38 +00004452 if( pThis->pParent!=pNewParent ){
danielk19773b8a05f2007-03-19 17:44:26 +00004453 if( pThis->pParent ) sqlite3PagerUnref(pThis->pParent->pDbPage);
drhda200cc2004-05-09 11:51:38 +00004454 pThis->pParent = pNewParent;
danielk19773b8a05f2007-03-19 17:44:26 +00004455 sqlite3PagerRef(pNewParent->pDbPage);
drhda200cc2004-05-09 11:51:38 +00004456 }
4457 pThis->idxParent = idx;
drhdd793422001-06-28 01:54:48 +00004458 }
danielk19773b8a05f2007-03-19 17:44:26 +00004459 sqlite3PagerUnref(pDbPage);
drhbd03cae2001-06-02 02:40:57 +00004460 }
danielk1977afcdd022004-10-31 16:25:42 +00004461
4462#ifndef SQLITE_OMIT_AUTOVACUUM
4463 if( pBt->autoVacuum ){
4464 return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
4465 }
4466#endif
4467 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00004468}
4469
danielk1977ac11ee62005-01-15 12:45:51 +00004470
4471
drhbd03cae2001-06-02 02:40:57 +00004472/*
drh4b70f112004-05-02 21:12:19 +00004473** Change the pParent pointer of all children of pPage to point back
4474** to pPage.
4475**
drhbd03cae2001-06-02 02:40:57 +00004476** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00004477** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00004478**
4479** This routine gets called after you memcpy() one page into
4480** another.
4481*/
danielk1977afcdd022004-10-31 16:25:42 +00004482static int reparentChildPages(MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00004483 int i;
danielk1977aef0bf62005-12-30 16:28:01 +00004484 BtShared *pBt = pPage->pBt;
danielk1977afcdd022004-10-31 16:25:42 +00004485 int rc = SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00004486
drh1fee73e2007-08-29 04:00:57 +00004487 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk1977afcdd022004-10-31 16:25:42 +00004488 if( pPage->leaf ) return SQLITE_OK;
danielk1977afcdd022004-10-31 16:25:42 +00004489
drhbd03cae2001-06-02 02:40:57 +00004490 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00004491 u8 *pCell = findCell(pPage, i);
drhcfc2e7f2008-03-23 00:20:36 +00004492 rc = reparentPage(pBt, get4byte(pCell), pPage, i);
4493 if( rc!=SQLITE_OK ) return rc;
drhbd03cae2001-06-02 02:40:57 +00004494 }
drhcfc2e7f2008-03-23 00:20:36 +00004495 rc = reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]),
4496 pPage, i);
4497 pPage->idxShift = 0;
danielk1977afcdd022004-10-31 16:25:42 +00004498 return rc;
drh14acc042001-06-10 19:56:58 +00004499}
4500
4501/*
4502** Remove the i-th cell from pPage. This routine effects pPage only.
4503** The cell content is not freed or deallocated. It is assumed that
4504** the cell content has been copied someplace else. This routine just
4505** removes the reference to the cell from pPage.
4506**
4507** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00004508*/
drh4b70f112004-05-02 21:12:19 +00004509static void dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00004510 int i; /* Loop counter */
4511 int pc; /* Offset to cell content of cell being deleted */
4512 u8 *data; /* pPage->aData */
4513 u8 *ptr; /* Used to move bytes around within data[] */
4514
drh8c42ca92001-06-22 19:15:00 +00004515 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00004516 assert( sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00004517 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00004518 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00004519 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00004520 ptr = &data[pPage->cellOffset + 2*idx];
4521 pc = get2byte(ptr);
4522 assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
drhde647132004-05-07 17:57:49 +00004523 freeSpace(pPage, pc, sz);
drh43605152004-05-29 21:46:49 +00004524 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
4525 ptr[0] = ptr[2];
4526 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00004527 }
4528 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00004529 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
4530 pPage->nFree += 2;
drh428ae8c2003-01-04 16:48:09 +00004531 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00004532}
4533
4534/*
4535** Insert a new cell on pPage at cell index "i". pCell points to the
4536** content of the cell.
4537**
4538** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00004539** will not fit, then make a copy of the cell content into pTemp if
4540** pTemp is not null. Regardless of pTemp, allocate a new entry
4541** in pPage->aOvfl[] and make it point to the cell content (either
4542** in pTemp or the original pCell) and also record its index.
4543** Allocating a new entry in pPage->aCell[] implies that
4544** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00004545**
4546** If nSkip is non-zero, then do not copy the first nSkip bytes of the
4547** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00004548** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00004549** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00004550*/
danielk1977e80463b2004-11-03 03:01:16 +00004551static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00004552 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00004553 int i, /* New cell becomes the i-th cell of the page */
4554 u8 *pCell, /* Content of the new cell */
4555 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00004556 u8 *pTemp, /* Temp storage space for pCell, if needed */
4557 u8 nSkip /* Do not write the first nSkip bytes of the cell */
drh24cd67e2004-05-10 16:18:47 +00004558){
drh43605152004-05-29 21:46:49 +00004559 int idx; /* Where to write new cell content in data[] */
4560 int j; /* Loop counter */
4561 int top; /* First byte of content for any cell in data[] */
4562 int end; /* First byte past the last cell pointer in data[] */
4563 int ins; /* Index in data[] where new cell pointer is inserted */
4564 int hdr; /* Offset into data[] of the page header */
4565 int cellOffset; /* Address of first cell pointer in data[] */
4566 u8 *data; /* The content of the whole page */
4567 u8 *ptr; /* Used for moving information around in data[] */
4568
4569 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
4570 assert( sz==cellSizePtr(pPage, pCell) );
drh1fee73e2007-08-29 04:00:57 +00004571 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +00004572 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00004573 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00004574 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004575 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00004576 }
drh43605152004-05-29 21:46:49 +00004577 j = pPage->nOverflow++;
4578 assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
4579 pPage->aOvfl[j].pCell = pCell;
4580 pPage->aOvfl[j].idx = i;
4581 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00004582 }else{
danielk19776e465eb2007-08-21 13:11:00 +00004583 int rc = sqlite3PagerWrite(pPage->pDbPage);
4584 if( rc!=SQLITE_OK ){
4585 return rc;
4586 }
4587 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00004588 data = pPage->aData;
4589 hdr = pPage->hdrOffset;
4590 top = get2byte(&data[hdr+5]);
4591 cellOffset = pPage->cellOffset;
4592 end = cellOffset + 2*pPage->nCell + 2;
4593 ins = cellOffset + 2*i;
4594 if( end > top - sz ){
danielk19776e465eb2007-08-21 13:11:00 +00004595 rc = defragmentPage(pPage);
danielk19776b456a22005-03-21 04:04:02 +00004596 if( rc!=SQLITE_OK ) return rc;
drh43605152004-05-29 21:46:49 +00004597 top = get2byte(&data[hdr+5]);
4598 assert( end + sz <= top );
4599 }
4600 idx = allocateSpace(pPage, sz);
4601 assert( idx>0 );
4602 assert( end <= get2byte(&data[hdr+5]) );
4603 pPage->nCell++;
4604 pPage->nFree -= 2;
danielk1977a3ad5e72005-01-07 08:56:44 +00004605 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004606 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
4607 ptr[0] = ptr[-2];
4608 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00004609 }
drh43605152004-05-29 21:46:49 +00004610 put2byte(&data[ins], idx);
4611 put2byte(&data[hdr+3], pPage->nCell);
4612 pPage->idxShift = 1;
danielk1977a19df672004-11-03 11:37:07 +00004613#ifndef SQLITE_OMIT_AUTOVACUUM
4614 if( pPage->pBt->autoVacuum ){
4615 /* The cell may contain a pointer to an overflow page. If so, write
4616 ** the entry for the overflow page into the pointer map.
4617 */
4618 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00004619 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh72365832007-03-06 15:53:44 +00004620 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk1977a19df672004-11-03 11:37:07 +00004621 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
4622 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
danielk19776e465eb2007-08-21 13:11:00 +00004623 rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
danielk1977a19df672004-11-03 11:37:07 +00004624 if( rc!=SQLITE_OK ) return rc;
4625 }
4626 }
4627#endif
drh14acc042001-06-10 19:56:58 +00004628 }
danielk1977e80463b2004-11-03 03:01:16 +00004629
danielk1977e80463b2004-11-03 03:01:16 +00004630 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004631}
4632
4633/*
drhfa1a98a2004-05-14 19:08:17 +00004634** Add a list of cells to a page. The page should be initially empty.
4635** The cells are guaranteed to fit on the page.
4636*/
4637static void assemblePage(
4638 MemPage *pPage, /* The page to be assemblied */
4639 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00004640 u8 **apCell, /* Pointers to cell bodies */
drha9121e42008-02-19 14:59:35 +00004641 u16 *aSize /* Sizes of the cells */
drhfa1a98a2004-05-14 19:08:17 +00004642){
4643 int i; /* Loop counter */
4644 int totalSize; /* Total size of all cells */
4645 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00004646 int cellptr; /* Address of next cell pointer */
4647 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00004648 u8 *data; /* Data for the page */
4649
drh43605152004-05-29 21:46:49 +00004650 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00004651 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa1a98a2004-05-14 19:08:17 +00004652 totalSize = 0;
4653 for(i=0; i<nCell; i++){
4654 totalSize += aSize[i];
4655 }
drh43605152004-05-29 21:46:49 +00004656 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00004657 assert( pPage->nCell==0 );
drh43605152004-05-29 21:46:49 +00004658 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00004659 data = pPage->aData;
4660 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00004661 put2byte(&data[hdr+3], nCell);
drh09d0deb2005-08-02 17:13:09 +00004662 if( nCell ){
4663 cellbody = allocateSpace(pPage, totalSize);
4664 assert( cellbody>0 );
4665 assert( pPage->nFree >= 2*nCell );
4666 pPage->nFree -= 2*nCell;
4667 for(i=0; i<nCell; i++){
4668 put2byte(&data[cellptr], cellbody);
4669 memcpy(&data[cellbody], apCell[i], aSize[i]);
4670 cellptr += 2;
4671 cellbody += aSize[i];
4672 }
4673 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00004674 }
4675 pPage->nCell = nCell;
drhfa1a98a2004-05-14 19:08:17 +00004676}
4677
drh14acc042001-06-10 19:56:58 +00004678/*
drhc3b70572003-01-04 19:44:07 +00004679** The following parameters determine how many adjacent pages get involved
4680** in a balancing operation. NN is the number of neighbors on either side
4681** of the page that participate in the balancing operation. NB is the
4682** total number of pages that participate, including the target page and
4683** NN neighbors on either side.
4684**
4685** The minimum value of NN is 1 (of course). Increasing NN above 1
4686** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
4687** in exchange for a larger degradation in INSERT and UPDATE performance.
4688** The value of NN appears to give the best results overall.
4689*/
4690#define NN 1 /* Number of neighbors on either side of pPage */
4691#define NB (NN*2+1) /* Total pages involved in the balance */
4692
drh43605152004-05-29 21:46:49 +00004693/* Forward reference */
danielk1977ac245ec2005-01-14 13:50:11 +00004694static int balance(MemPage*, int);
4695
drh615ae552005-01-16 23:21:00 +00004696#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004697/*
4698** This version of balance() handles the common special case where
4699** a new entry is being inserted on the extreme right-end of the
4700** tree, in other words, when the new entry will become the largest
4701** entry in the tree.
4702**
4703** Instead of trying balance the 3 right-most leaf pages, just add
4704** a new page to the right-hand side and put the one new entry in
4705** that page. This leaves the right side of the tree somewhat
4706** unbalanced. But odds are that we will be inserting new entries
4707** at the end soon afterwards so the nearly empty page will quickly
4708** fill up. On average.
4709**
4710** pPage is the leaf page which is the right-most page in the tree.
4711** pParent is its parent. pPage must have a single overflow entry
4712** which is also the right-most entry on the page.
4713*/
danielk1977ac245ec2005-01-14 13:50:11 +00004714static int balance_quick(MemPage *pPage, MemPage *pParent){
4715 int rc;
4716 MemPage *pNew;
4717 Pgno pgnoNew;
4718 u8 *pCell;
drha9121e42008-02-19 14:59:35 +00004719 u16 szCell;
danielk1977ac245ec2005-01-14 13:50:11 +00004720 CellInfo info;
danielk1977aef0bf62005-12-30 16:28:01 +00004721 BtShared *pBt = pPage->pBt;
danielk197779a40da2005-01-16 08:00:01 +00004722 int parentIdx = pParent->nCell; /* pParent new divider cell index */
4723 int parentSize; /* Size of new divider cell */
4724 u8 parentCell[64]; /* Space for the new divider cell */
danielk1977ac245ec2005-01-14 13:50:11 +00004725
drh1fee73e2007-08-29 04:00:57 +00004726 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00004727
danielk1977ac245ec2005-01-14 13:50:11 +00004728 /* Allocate a new page. Insert the overflow cell from pPage
4729 ** into it. Then remove the overflow cell from pPage.
4730 */
drh4f0c5872007-03-26 22:05:01 +00004731 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk1977ac245ec2005-01-14 13:50:11 +00004732 if( rc!=SQLITE_OK ){
4733 return rc;
4734 }
4735 pCell = pPage->aOvfl[0].pCell;
4736 szCell = cellSizePtr(pPage, pCell);
4737 zeroPage(pNew, pPage->aData[0]);
4738 assemblePage(pNew, 1, &pCell, &szCell);
4739 pPage->nOverflow = 0;
4740
danielk197779a40da2005-01-16 08:00:01 +00004741 /* Set the parent of the newly allocated page to pParent. */
4742 pNew->pParent = pParent;
danielk19773b8a05f2007-03-19 17:44:26 +00004743 sqlite3PagerRef(pParent->pDbPage);
danielk197779a40da2005-01-16 08:00:01 +00004744
danielk1977ac245ec2005-01-14 13:50:11 +00004745 /* pPage is currently the right-child of pParent. Change this
4746 ** so that the right-child is the new page allocated above and
danielk197779a40da2005-01-16 08:00:01 +00004747 ** pPage is the next-to-right child.
danielk1977ac245ec2005-01-14 13:50:11 +00004748 */
danielk1977ac11ee62005-01-15 12:45:51 +00004749 assert( pPage->nCell>0 );
danielk19771cc5ed82007-05-16 17:28:43 +00004750 pCell = findCell(pPage, pPage->nCell-1);
drh16a9b832007-05-05 18:39:25 +00004751 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drhb026e052007-05-02 01:34:31 +00004752 rc = fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
danielk1977ac245ec2005-01-14 13:50:11 +00004753 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00004754 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004755 }
4756 assert( parentSize<64 );
4757 rc = insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
4758 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00004759 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004760 }
4761 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
4762 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
4763
danielk197779a40da2005-01-16 08:00:01 +00004764#ifndef SQLITE_OMIT_AUTOVACUUM
4765 /* If this is an auto-vacuum database, update the pointer map
4766 ** with entries for the new page, and any pointer from the
4767 ** cell on the page to an overflow page.
4768 */
danielk1977ac11ee62005-01-15 12:45:51 +00004769 if( pBt->autoVacuum ){
4770 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
danielk1977deb403e2007-05-24 09:20:16 +00004771 if( rc==SQLITE_OK ){
4772 rc = ptrmapPutOvfl(pNew, 0);
danielk1977ac11ee62005-01-15 12:45:51 +00004773 }
danielk197779a40da2005-01-16 08:00:01 +00004774 if( rc!=SQLITE_OK ){
danielk1977deb403e2007-05-24 09:20:16 +00004775 releasePage(pNew);
danielk197779a40da2005-01-16 08:00:01 +00004776 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00004777 }
4778 }
danielk197779a40da2005-01-16 08:00:01 +00004779#endif
danielk1977ac11ee62005-01-15 12:45:51 +00004780
danielk197779a40da2005-01-16 08:00:01 +00004781 /* Release the reference to the new page and balance the parent page,
4782 ** in case the divider cell inserted caused it to become overfull.
4783 */
danielk1977ac245ec2005-01-14 13:50:11 +00004784 releasePage(pNew);
4785 return balance(pParent, 0);
4786}
drh615ae552005-01-16 23:21:00 +00004787#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00004788
drhc3b70572003-01-04 19:44:07 +00004789/*
drhab01f612004-05-22 02:55:23 +00004790** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00004791** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00004792** Usually NN siblings on either side of pPage is used in the balancing,
4793** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00004794** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00004795** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00004796** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00004797**
drh0c6cc4e2004-06-15 02:13:26 +00004798** The number of siblings of pPage might be increased or decreased by one or
4799** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00004800** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00004801** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00004802** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00004803** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00004804**
drh8b2f49b2001-06-08 00:21:52 +00004805** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00004806** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00004807** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00004808** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00004809**
drh8c42ca92001-06-22 19:15:00 +00004810** In the course of balancing the siblings of pPage, the parent of pPage
4811** might become overfull or underfull. If that happens, then this routine
4812** is called recursively on the parent.
4813**
drh5e00f6c2001-09-13 13:46:56 +00004814** If this routine fails for any reason, it might leave the database
4815** in a corrupted state. So if this routine fails, the database should
4816** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00004817*/
drh43605152004-05-29 21:46:49 +00004818static int balance_nonroot(MemPage *pPage){
drh8b2f49b2001-06-08 00:21:52 +00004819 MemPage *pParent; /* The parent of pPage */
drh16a9b832007-05-05 18:39:25 +00004820 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00004821 int nCell = 0; /* Number of cells in apCell[] */
4822 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
drh8b2f49b2001-06-08 00:21:52 +00004823 int nOld; /* Number of pages in apOld[] */
4824 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00004825 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00004826 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00004827 int idx; /* Index of pPage in pParent->aCell[] */
4828 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00004829 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00004830 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00004831 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00004832 int usableSpace; /* Bytes in pPage beyond the header */
4833 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00004834 int subtotal; /* Subtotal of bytes in cells on one page */
drhb6f41482004-05-14 01:58:11 +00004835 int iSpace = 0; /* First unused byte of aSpace[] */
drhc3b70572003-01-04 19:44:07 +00004836 MemPage *apOld[NB]; /* pPage and up to two siblings */
4837 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00004838 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00004839 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
4840 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drh4b70f112004-05-02 21:12:19 +00004841 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00004842 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
4843 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00004844 u8 **apCell = 0; /* All cells begin balanced */
drha9121e42008-02-19 14:59:35 +00004845 u16 *szCell; /* Local size of all cells in apCell[] */
drh2e38c322004-09-03 18:38:44 +00004846 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
4847 u8 *aSpace; /* Space to hold copies of dividers cells */
danielk19774e17d142005-01-16 09:06:33 +00004848#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00004849 u8 *aFrom = 0;
4850#endif
drh8b2f49b2001-06-08 00:21:52 +00004851
drh1fee73e2007-08-29 04:00:57 +00004852 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00004853
drh14acc042001-06-10 19:56:58 +00004854 /*
drh43605152004-05-29 21:46:49 +00004855 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00004856 */
drh3a4c1412004-05-09 20:40:11 +00004857 assert( pPage->isInit );
danielk19776e465eb2007-08-21 13:11:00 +00004858 assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 );
drh4b70f112004-05-02 21:12:19 +00004859 pBt = pPage->pBt;
drh14acc042001-06-10 19:56:58 +00004860 pParent = pPage->pParent;
drh43605152004-05-29 21:46:49 +00004861 assert( pParent );
danielk19773b8a05f2007-03-19 17:44:26 +00004862 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
danielk197707cb5602006-01-20 10:55:05 +00004863 return rc;
4864 }
drh43605152004-05-29 21:46:49 +00004865 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00004866
drh615ae552005-01-16 23:21:00 +00004867#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004868 /*
4869 ** A special case: If a new entry has just been inserted into a
4870 ** table (that is, a btree with integer keys and all data at the leaves)
drh09d0deb2005-08-02 17:13:09 +00004871 ** and the new entry is the right-most entry in the tree (it has the
drhf222e712005-01-14 22:55:49 +00004872 ** largest key) then use the special balance_quick() routine for
4873 ** balancing. balance_quick() is much faster and results in a tighter
4874 ** packing of data in the common case.
4875 */
danielk1977ac245ec2005-01-14 13:50:11 +00004876 if( pPage->leaf &&
4877 pPage->intKey &&
4878 pPage->leafData &&
4879 pPage->nOverflow==1 &&
4880 pPage->aOvfl[0].idx==pPage->nCell &&
danielk1977ac11ee62005-01-15 12:45:51 +00004881 pPage->pParent->pgno!=1 &&
danielk1977ac245ec2005-01-14 13:50:11 +00004882 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
4883 ){
danielk1977ac11ee62005-01-15 12:45:51 +00004884 /*
4885 ** TODO: Check the siblings to the left of pPage. It may be that
4886 ** they are not full and no new page is required.
4887 */
danielk1977ac245ec2005-01-14 13:50:11 +00004888 return balance_quick(pPage, pParent);
4889 }
4890#endif
4891
danielk19776e465eb2007-08-21 13:11:00 +00004892 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){
4893 return rc;
4894 }
4895
drh2e38c322004-09-03 18:38:44 +00004896 /*
drh4b70f112004-05-02 21:12:19 +00004897 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00004898 ** to pPage. The "idx" variable is the index of that cell. If pPage
4899 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00004900 */
drhbb49aba2003-01-04 18:53:27 +00004901 if( pParent->idxShift ){
drha34b6762004-05-07 13:30:42 +00004902 Pgno pgno;
drh4b70f112004-05-02 21:12:19 +00004903 pgno = pPage->pgno;
danielk19773b8a05f2007-03-19 17:44:26 +00004904 assert( pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbb49aba2003-01-04 18:53:27 +00004905 for(idx=0; idx<pParent->nCell; idx++){
danielk19771cc5ed82007-05-16 17:28:43 +00004906 if( get4byte(findCell(pParent, idx))==pgno ){
drhbb49aba2003-01-04 18:53:27 +00004907 break;
4908 }
drh8b2f49b2001-06-08 00:21:52 +00004909 }
drh4b70f112004-05-02 21:12:19 +00004910 assert( idx<pParent->nCell
drh43605152004-05-29 21:46:49 +00004911 || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
drhbb49aba2003-01-04 18:53:27 +00004912 }else{
4913 idx = pPage->idxParent;
drh8b2f49b2001-06-08 00:21:52 +00004914 }
drh8b2f49b2001-06-08 00:21:52 +00004915
4916 /*
drh14acc042001-06-10 19:56:58 +00004917 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00004918 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00004919 */
drh14acc042001-06-10 19:56:58 +00004920 nOld = nNew = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00004921 sqlite3PagerRef(pParent->pDbPage);
drh14acc042001-06-10 19:56:58 +00004922
4923 /*
drh4b70f112004-05-02 21:12:19 +00004924 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00004925 ** the siblings. An attempt is made to find NN siblings on either
4926 ** side of pPage. More siblings are taken from one side, however, if
4927 ** pPage there are fewer than NN siblings on the other side. If pParent
4928 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00004929 */
drhc3b70572003-01-04 19:44:07 +00004930 nxDiv = idx - NN;
4931 if( nxDiv + NB > pParent->nCell ){
4932 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00004933 }
drhc3b70572003-01-04 19:44:07 +00004934 if( nxDiv<0 ){
4935 nxDiv = 0;
4936 }
drh8b2f49b2001-06-08 00:21:52 +00004937 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00004938 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00004939 if( k<pParent->nCell ){
danielk19771cc5ed82007-05-16 17:28:43 +00004940 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00004941 nDiv++;
drha34b6762004-05-07 13:30:42 +00004942 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00004943 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00004944 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00004945 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00004946 }else{
4947 break;
drh8b2f49b2001-06-08 00:21:52 +00004948 }
drhde647132004-05-07 17:57:49 +00004949 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00004950 if( rc ) goto balance_cleanup;
drh428ae8c2003-01-04 16:48:09 +00004951 apOld[i]->idxParent = k;
drh91025292004-05-03 19:49:32 +00004952 apCopy[i] = 0;
4953 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00004954 nOld++;
danielk1977634f2982005-03-28 08:44:07 +00004955 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
drh8b2f49b2001-06-08 00:21:52 +00004956 }
4957
drha9121e42008-02-19 14:59:35 +00004958 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00004959 ** alignment */
drha9121e42008-02-19 14:59:35 +00004960 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00004961
drh8b2f49b2001-06-08 00:21:52 +00004962 /*
danielk1977634f2982005-03-28 08:44:07 +00004963 ** Allocate space for memory structures
4964 */
drh17435752007-08-16 04:30:38 +00004965 apCell = sqlite3_malloc(
drha9121e42008-02-19 14:59:35 +00004966 nMaxCells*sizeof(u8*) /* apCell */
4967 + nMaxCells*sizeof(u16) /* szCell */
4968 + (ROUND8(sizeof(MemPage))+pBt->pageSize)*NB /* aCopy */
4969 + pBt->pageSize*5 /* aSpace */
4970 + (ISAUTOVACUUM ? nMaxCells : 0) /* aFrom */
danielk1977634f2982005-03-28 08:44:07 +00004971 );
4972 if( apCell==0 ){
4973 rc = SQLITE_NOMEM;
4974 goto balance_cleanup;
4975 }
drha9121e42008-02-19 14:59:35 +00004976 szCell = (u16*)&apCell[nMaxCells];
danielk1977634f2982005-03-28 08:44:07 +00004977 aCopy[0] = (u8*)&szCell[nMaxCells];
drhc96d8532005-05-03 12:30:33 +00004978 assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004979 for(i=1; i<NB; i++){
drhc96d8532005-05-03 12:30:33 +00004980 aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
4981 assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004982 }
drhc96d8532005-05-03 12:30:33 +00004983 aSpace = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
4984 assert( ((aSpace - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004985#ifndef SQLITE_OMIT_AUTOVACUUM
4986 if( pBt->autoVacuum ){
drh07d183d2005-05-01 22:52:42 +00004987 aFrom = &aSpace[5*pBt->pageSize];
danielk1977634f2982005-03-28 08:44:07 +00004988 }
4989#endif
4990
4991 /*
drh14acc042001-06-10 19:56:58 +00004992 ** Make copies of the content of pPage and its siblings into aOld[].
4993 ** The rest of this function will use data from the copies rather
4994 ** that the original pages since the original pages will be in the
4995 ** process of being overwritten.
4996 */
4997 for(i=0; i<nOld; i++){
drhbf4bca52007-09-06 22:19:14 +00004998 MemPage *p = apCopy[i] = (MemPage*)aCopy[i];
4999 memcpy(p, apOld[i], sizeof(MemPage));
5000 p->aData = (void*)&p[1];
5001 memcpy(p->aData, apOld[i]->aData, pBt->pageSize);
drh14acc042001-06-10 19:56:58 +00005002 }
5003
5004 /*
5005 ** Load pointers to all cells on sibling pages and the divider cells
5006 ** into the local apCell[] array. Make copies of the divider cells
drhb6f41482004-05-14 01:58:11 +00005007 ** into space obtained form aSpace[] and remove the the divider Cells
5008 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00005009 **
5010 ** If the siblings are on leaf pages, then the child pointers of the
5011 ** divider cells are stripped from the cells before they are copied
drh96f5b762004-05-16 16:24:36 +00005012 ** into aSpace[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00005013 ** child pointers. If siblings are not leaves, then all cell in
5014 ** apCell[] include child pointers. Either way, all cells in apCell[]
5015 ** are alike.
drh96f5b762004-05-16 16:24:36 +00005016 **
5017 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
5018 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00005019 */
5020 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00005021 leafCorrection = pPage->leaf*4;
drh8b18dd42004-05-12 19:18:15 +00005022 leafData = pPage->leafData && pPage->leaf;
drh8b2f49b2001-06-08 00:21:52 +00005023 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00005024 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00005025 int limit = pOld->nCell+pOld->nOverflow;
5026 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00005027 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00005028 apCell[nCell] = findOverflowCell(pOld, j);
5029 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk1977ac11ee62005-01-15 12:45:51 +00005030#ifndef SQLITE_OMIT_AUTOVACUUM
5031 if( pBt->autoVacuum ){
5032 int a;
5033 aFrom[nCell] = i;
5034 for(a=0; a<pOld->nOverflow; a++){
5035 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
5036 aFrom[nCell] = 0xFF;
5037 break;
5038 }
5039 }
5040 }
5041#endif
drh14acc042001-06-10 19:56:58 +00005042 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00005043 }
5044 if( i<nOld-1 ){
drha9121e42008-02-19 14:59:35 +00005045 u16 sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00005046 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00005047 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
5048 ** are duplicates of keys on the child pages. We need to remove
5049 ** the divider cells from pParent, but the dividers cells are not
5050 ** added to apCell[] because they are duplicates of child cells.
5051 */
drh8b18dd42004-05-12 19:18:15 +00005052 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00005053 }else{
drhb6f41482004-05-14 01:58:11 +00005054 u8 *pTemp;
danielk1977634f2982005-03-28 08:44:07 +00005055 assert( nCell<nMaxCells );
drhb6f41482004-05-14 01:58:11 +00005056 szCell[nCell] = sz;
5057 pTemp = &aSpace[iSpace];
5058 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00005059 assert( iSpace<=pBt->pageSize*5 );
drhb6f41482004-05-14 01:58:11 +00005060 memcpy(pTemp, apDiv[i], sz);
5061 apCell[nCell] = pTemp+leafCorrection;
danielk1977ac11ee62005-01-15 12:45:51 +00005062#ifndef SQLITE_OMIT_AUTOVACUUM
5063 if( pBt->autoVacuum ){
5064 aFrom[nCell] = 0xFF;
5065 }
5066#endif
drhb6f41482004-05-14 01:58:11 +00005067 dropCell(pParent, nxDiv, sz);
drh8b18dd42004-05-12 19:18:15 +00005068 szCell[nCell] -= leafCorrection;
drh43605152004-05-29 21:46:49 +00005069 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00005070 if( !pOld->leaf ){
5071 assert( leafCorrection==0 );
5072 /* The right pointer of the child page pOld becomes the left
5073 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00005074 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00005075 }else{
5076 assert( leafCorrection==4 );
danielk197739c96042007-05-12 10:41:47 +00005077 if( szCell[nCell]<4 ){
5078 /* Do not allow any cells smaller than 4 bytes. */
5079 szCell[nCell] = 4;
5080 }
drh8b18dd42004-05-12 19:18:15 +00005081 }
5082 nCell++;
drh4b70f112004-05-02 21:12:19 +00005083 }
drh8b2f49b2001-06-08 00:21:52 +00005084 }
5085 }
5086
5087 /*
drh6019e162001-07-02 17:51:45 +00005088 ** Figure out the number of pages needed to hold all nCell cells.
5089 ** Store this number in "k". Also compute szNew[] which is the total
5090 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00005091 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00005092 ** cntNew[k] should equal nCell.
5093 **
drh96f5b762004-05-16 16:24:36 +00005094 ** Values computed by this block:
5095 **
5096 ** k: The total number of sibling pages
5097 ** szNew[i]: Spaced used on the i-th sibling page.
5098 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
5099 ** the right of the i-th sibling page.
5100 ** usableSpace: Number of bytes of space available on each sibling.
5101 **
drh8b2f49b2001-06-08 00:21:52 +00005102 */
drh43605152004-05-29 21:46:49 +00005103 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00005104 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00005105 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00005106 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00005107 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00005108 szNew[k] = subtotal - szCell[i];
5109 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00005110 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00005111 subtotal = 0;
5112 k++;
5113 }
5114 }
5115 szNew[k] = subtotal;
5116 cntNew[k] = nCell;
5117 k++;
drh96f5b762004-05-16 16:24:36 +00005118
5119 /*
5120 ** The packing computed by the previous block is biased toward the siblings
5121 ** on the left side. The left siblings are always nearly full, while the
5122 ** right-most sibling might be nearly empty. This block of code attempts
5123 ** to adjust the packing of siblings to get a better balance.
5124 **
5125 ** This adjustment is more than an optimization. The packing above might
5126 ** be so out of balance as to be illegal. For example, the right-most
5127 ** sibling might be completely empty. This adjustment is not optional.
5128 */
drh6019e162001-07-02 17:51:45 +00005129 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00005130 int szRight = szNew[i]; /* Size of sibling on the right */
5131 int szLeft = szNew[i-1]; /* Size of sibling on the left */
5132 int r; /* Index of right-most cell in left sibling */
5133 int d; /* Index of first cell to the left of right sibling */
5134
5135 r = cntNew[i-1] - 1;
5136 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00005137 assert( d<nMaxCells );
5138 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00005139 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
5140 szRight += szCell[d] + 2;
5141 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00005142 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00005143 r = cntNew[i-1] - 1;
5144 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00005145 }
drh96f5b762004-05-16 16:24:36 +00005146 szNew[i] = szRight;
5147 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00005148 }
drh09d0deb2005-08-02 17:13:09 +00005149
5150 /* Either we found one or more cells (cntnew[0])>0) or we are the
5151 ** a virtual root page. A virtual root page is when the real root
5152 ** page is page 1 and we are the only child of that page.
5153 */
5154 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00005155
5156 /*
drh6b308672002-07-08 02:16:37 +00005157 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00005158 */
drh4b70f112004-05-02 21:12:19 +00005159 assert( pPage->pgno>1 );
5160 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00005161 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00005162 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00005163 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00005164 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00005165 pgnoNew[i] = pgnoOld[i];
5166 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00005167 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00005168 nNew++;
danielk197728129562005-01-11 10:25:06 +00005169 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00005170 }else{
drh7aa8f852006-03-28 00:24:44 +00005171 assert( i>0 );
drh4f0c5872007-03-26 22:05:01 +00005172 rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
drh6b308672002-07-08 02:16:37 +00005173 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00005174 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00005175 nNew++;
drh6b308672002-07-08 02:16:37 +00005176 }
drhda200cc2004-05-09 11:51:38 +00005177 zeroPage(pNew, pageFlags);
drh8b2f49b2001-06-08 00:21:52 +00005178 }
5179
danielk1977299b1872004-11-22 10:02:10 +00005180 /* Free any old pages that were not reused as new pages.
5181 */
5182 while( i<nOld ){
5183 rc = freePage(apOld[i]);
5184 if( rc ) goto balance_cleanup;
5185 releasePage(apOld[i]);
5186 apOld[i] = 0;
5187 i++;
5188 }
5189
drh8b2f49b2001-06-08 00:21:52 +00005190 /*
drhf9ffac92002-03-02 19:00:31 +00005191 ** Put the new pages in accending order. This helps to
5192 ** keep entries in the disk file in order so that a scan
5193 ** of the table is a linear scan through the file. That
5194 ** in turn helps the operating system to deliver pages
5195 ** from the disk more rapidly.
5196 **
5197 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00005198 ** n is never more than NB (a small constant), that should
5199 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00005200 **
drhc3b70572003-01-04 19:44:07 +00005201 ** When NB==3, this one optimization makes the database
5202 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00005203 */
5204 for(i=0; i<k-1; i++){
5205 int minV = pgnoNew[i];
5206 int minI = i;
5207 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00005208 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00005209 minI = j;
5210 minV = pgnoNew[j];
5211 }
5212 }
5213 if( minI>i ){
5214 int t;
5215 MemPage *pT;
5216 t = pgnoNew[i];
5217 pT = apNew[i];
5218 pgnoNew[i] = pgnoNew[minI];
5219 apNew[i] = apNew[minI];
5220 pgnoNew[minI] = t;
5221 apNew[minI] = pT;
5222 }
5223 }
drha2fce642004-06-05 00:01:44 +00005224 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00005225 pgnoOld[0],
5226 nOld>=2 ? pgnoOld[1] : 0,
5227 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00005228 pgnoNew[0], szNew[0],
5229 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
5230 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00005231 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
5232 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00005233
drhf9ffac92002-03-02 19:00:31 +00005234 /*
drh14acc042001-06-10 19:56:58 +00005235 ** Evenly distribute the data in apCell[] across the new pages.
5236 ** Insert divider cells into pParent as necessary.
5237 */
5238 j = 0;
5239 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00005240 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00005241 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00005242 assert( j<nMaxCells );
drh4b70f112004-05-02 21:12:19 +00005243 assert( pNew->pgno==pgnoNew[i] );
drhfa1a98a2004-05-14 19:08:17 +00005244 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00005245 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00005246 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00005247
5248#ifndef SQLITE_OMIT_AUTOVACUUM
5249 /* If this is an auto-vacuum database, update the pointer map entries
5250 ** that point to the siblings that were rearranged. These can be: left
5251 ** children of cells, the right-child of the page, or overflow pages
5252 ** pointed to by cells.
5253 */
5254 if( pBt->autoVacuum ){
5255 for(k=j; k<cntNew[i]; k++){
danielk1977634f2982005-03-28 08:44:07 +00005256 assert( k<nMaxCells );
danielk1977ac11ee62005-01-15 12:45:51 +00005257 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
danielk197779a40da2005-01-16 08:00:01 +00005258 rc = ptrmapPutOvfl(pNew, k-j);
5259 if( rc!=SQLITE_OK ){
5260 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00005261 }
5262 }
5263 }
5264 }
5265#endif
5266
5267 j = cntNew[i];
5268
5269 /* If the sibling page assembled above was not the right-most sibling,
5270 ** insert a divider cell into the parent page.
5271 */
drh14acc042001-06-10 19:56:58 +00005272 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00005273 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00005274 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00005275 int sz;
danielk1977634f2982005-03-28 08:44:07 +00005276
5277 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00005278 pCell = apCell[j];
5279 sz = szCell[j] + leafCorrection;
drh4b70f112004-05-02 21:12:19 +00005280 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00005281 memcpy(&pNew->aData[8], pCell, 4);
drh24cd67e2004-05-10 16:18:47 +00005282 pTemp = 0;
drh8b18dd42004-05-12 19:18:15 +00005283 }else if( leafData ){
drhfd131da2007-08-07 17:13:03 +00005284 /* If the tree is a leaf-data tree, and the siblings are leaves,
danielk1977ac11ee62005-01-15 12:45:51 +00005285 ** then there is no divider cell in apCell[]. Instead, the divider
5286 ** cell consists of the integer key for the right-most cell of
5287 ** the sibling-page assembled above only.
5288 */
drh6f11bef2004-05-13 01:12:56 +00005289 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00005290 j--;
drh16a9b832007-05-05 18:39:25 +00005291 sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
drhb6f41482004-05-14 01:58:11 +00005292 pCell = &aSpace[iSpace];
drhb026e052007-05-02 01:34:31 +00005293 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
drhb6f41482004-05-14 01:58:11 +00005294 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00005295 assert( iSpace<=pBt->pageSize*5 );
drh8b18dd42004-05-12 19:18:15 +00005296 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00005297 }else{
5298 pCell -= 4;
drhb6f41482004-05-14 01:58:11 +00005299 pTemp = &aSpace[iSpace];
5300 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00005301 assert( iSpace<=pBt->pageSize*5 );
danielk19774aeff622007-05-12 09:30:47 +00005302 /* Obscure case for non-leaf-data trees: If the cell at pCell was
drh85b623f2007-12-13 21:54:09 +00005303 ** previously stored on a leaf node, and its reported size was 4
danielk19774aeff622007-05-12 09:30:47 +00005304 ** bytes, then it may actually be smaller than this
5305 ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
drh85b623f2007-12-13 21:54:09 +00005306 ** any cell). But it is important to pass the correct size to
danielk19774aeff622007-05-12 09:30:47 +00005307 ** insertCell(), so reparse the cell now.
5308 **
5309 ** Note that this can never happen in an SQLite data file, as all
5310 ** cells are at least 4 bytes. It only happens in b-trees used
5311 ** to evaluate "IN (SELECT ...)" and similar clauses.
5312 */
5313 if( szCell[j]==4 ){
5314 assert(leafCorrection==4);
5315 sz = cellSizePtr(pParent, pCell);
5316 }
drh4b70f112004-05-02 21:12:19 +00005317 }
danielk1977a3ad5e72005-01-07 08:56:44 +00005318 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
danielk1977e80463b2004-11-03 03:01:16 +00005319 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh43605152004-05-29 21:46:49 +00005320 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +00005321#ifndef SQLITE_OMIT_AUTOVACUUM
5322 /* If this is an auto-vacuum database, and not a leaf-data tree,
5323 ** then update the pointer map with an entry for the overflow page
5324 ** that the cell just inserted points to (if any).
5325 */
5326 if( pBt->autoVacuum && !leafData ){
danielk197779a40da2005-01-16 08:00:01 +00005327 rc = ptrmapPutOvfl(pParent, nxDiv);
5328 if( rc!=SQLITE_OK ){
5329 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00005330 }
5331 }
5332#endif
drh14acc042001-06-10 19:56:58 +00005333 j++;
5334 nxDiv++;
5335 }
5336 }
drh6019e162001-07-02 17:51:45 +00005337 assert( j==nCell );
drh7aa8f852006-03-28 00:24:44 +00005338 assert( nOld>0 );
5339 assert( nNew>0 );
drh4b70f112004-05-02 21:12:19 +00005340 if( (pageFlags & PTF_LEAF)==0 ){
drh43605152004-05-29 21:46:49 +00005341 memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
drh14acc042001-06-10 19:56:58 +00005342 }
drh43605152004-05-29 21:46:49 +00005343 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00005344 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00005345 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00005346 }else{
5347 /* Right-most sibling is the left child of the first entry in pParent
5348 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00005349 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00005350 }
5351
5352 /*
5353 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00005354 */
5355 for(i=0; i<nNew; i++){
danielk1977afcdd022004-10-31 16:25:42 +00005356 rc = reparentChildPages(apNew[i]);
5357 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00005358 }
danielk1977afcdd022004-10-31 16:25:42 +00005359 rc = reparentChildPages(pParent);
5360 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00005361
5362 /*
drh3a4c1412004-05-09 20:40:11 +00005363 ** Balance the parent page. Note that the current page (pPage) might
danielk1977ac11ee62005-01-15 12:45:51 +00005364 ** have been added to the freelist so it might no longer be initialized.
drh3a4c1412004-05-09 20:40:11 +00005365 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00005366 */
drhda200cc2004-05-09 11:51:38 +00005367 assert( pParent->isInit );
danielk1977ac245ec2005-01-14 13:50:11 +00005368 rc = balance(pParent, 0);
drhda200cc2004-05-09 11:51:38 +00005369
drh8b2f49b2001-06-08 00:21:52 +00005370 /*
drh14acc042001-06-10 19:56:58 +00005371 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00005372 */
drh14acc042001-06-10 19:56:58 +00005373balance_cleanup:
drh17435752007-08-16 04:30:38 +00005374 sqlite3_free(apCell);
drh8b2f49b2001-06-08 00:21:52 +00005375 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00005376 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00005377 }
drh14acc042001-06-10 19:56:58 +00005378 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00005379 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00005380 }
drh91025292004-05-03 19:49:32 +00005381 releasePage(pParent);
drh3a4c1412004-05-09 20:40:11 +00005382 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
5383 pPage->pgno, nOld, nNew, nCell));
drh8b2f49b2001-06-08 00:21:52 +00005384 return rc;
5385}
5386
5387/*
drh43605152004-05-29 21:46:49 +00005388** This routine is called for the root page of a btree when the root
5389** page contains no cells. This is an opportunity to make the tree
5390** shallower by one level.
5391*/
5392static int balance_shallower(MemPage *pPage){
5393 MemPage *pChild; /* The only child page of pPage */
5394 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00005395 int rc = SQLITE_OK; /* Return code from subprocedures */
danielk1977aef0bf62005-12-30 16:28:01 +00005396 BtShared *pBt; /* The main BTree structure */
drh2e38c322004-09-03 18:38:44 +00005397 int mxCellPerPage; /* Maximum number of cells per page */
5398 u8 **apCell; /* All cells from pages being balanced */
drha9121e42008-02-19 14:59:35 +00005399 u16 *szCell; /* Local size of all cells */
drh43605152004-05-29 21:46:49 +00005400
5401 assert( pPage->pParent==0 );
5402 assert( pPage->nCell==0 );
drh1fee73e2007-08-29 04:00:57 +00005403 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh2e38c322004-09-03 18:38:44 +00005404 pBt = pPage->pBt;
5405 mxCellPerPage = MX_CELL(pBt);
drha9121e42008-02-19 14:59:35 +00005406 apCell = sqlite3_malloc( mxCellPerPage*(sizeof(u8*)+sizeof(u16)) );
drh2e38c322004-09-03 18:38:44 +00005407 if( apCell==0 ) return SQLITE_NOMEM;
drha9121e42008-02-19 14:59:35 +00005408 szCell = (u16*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00005409 if( pPage->leaf ){
5410 /* The table is completely empty */
5411 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
5412 }else{
5413 /* The root page is empty but has one child. Transfer the
5414 ** information from that one child into the root page if it
5415 ** will fit. This reduces the depth of the tree by one.
5416 **
5417 ** If the root page is page 1, it has less space available than
5418 ** its child (due to the 100 byte header that occurs at the beginning
5419 ** of the database fle), so it might not be able to hold all of the
5420 ** information currently contained in the child. If this is the
5421 ** case, then do not do the transfer. Leave page 1 empty except
5422 ** for the right-pointer to the child page. The child page becomes
5423 ** the virtual root of the tree.
5424 */
5425 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5426 assert( pgnoChild>0 );
danielk19773b8a05f2007-03-19 17:44:26 +00005427 assert( pgnoChild<=sqlite3PagerPagecount(pPage->pBt->pPager) );
drh16a9b832007-05-05 18:39:25 +00005428 rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
drh2e38c322004-09-03 18:38:44 +00005429 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005430 if( pPage->pgno==1 ){
drh16a9b832007-05-05 18:39:25 +00005431 rc = sqlite3BtreeInitPage(pChild, pPage);
drh2e38c322004-09-03 18:38:44 +00005432 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005433 assert( pChild->nOverflow==0 );
5434 if( pChild->nFree>=100 ){
5435 /* The child information will fit on the root page, so do the
5436 ** copy */
5437 int i;
5438 zeroPage(pPage, pChild->aData[0]);
5439 for(i=0; i<pChild->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00005440 apCell[i] = findCell(pChild,i);
drh43605152004-05-29 21:46:49 +00005441 szCell[i] = cellSizePtr(pChild, apCell[i]);
5442 }
5443 assemblePage(pPage, pChild->nCell, apCell, szCell);
danielk1977ae825582004-11-23 09:06:55 +00005444 /* Copy the right-pointer of the child to the parent. */
5445 put4byte(&pPage->aData[pPage->hdrOffset+8],
5446 get4byte(&pChild->aData[pChild->hdrOffset+8]));
drh43605152004-05-29 21:46:49 +00005447 freePage(pChild);
5448 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
5449 }else{
5450 /* The child has more information that will fit on the root.
5451 ** The tree is already balanced. Do nothing. */
5452 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
5453 }
5454 }else{
5455 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
5456 pPage->isInit = 0;
5457 pPage->pParent = 0;
drh16a9b832007-05-05 18:39:25 +00005458 rc = sqlite3BtreeInitPage(pPage, 0);
drh43605152004-05-29 21:46:49 +00005459 assert( rc==SQLITE_OK );
5460 freePage(pChild);
5461 TRACE(("BALANCE: transfer child %d into root %d\n",
5462 pChild->pgno, pPage->pgno));
5463 }
danielk1977afcdd022004-10-31 16:25:42 +00005464 rc = reparentChildPages(pPage);
danielk1977ac11ee62005-01-15 12:45:51 +00005465 assert( pPage->nOverflow==0 );
5466#ifndef SQLITE_OMIT_AUTOVACUUM
5467 if( pBt->autoVacuum ){
danielk1977aac0a382005-01-16 11:07:06 +00005468 int i;
danielk1977ac11ee62005-01-15 12:45:51 +00005469 for(i=0; i<pPage->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00005470 rc = ptrmapPutOvfl(pPage, i);
5471 if( rc!=SQLITE_OK ){
5472 goto end_shallow_balance;
danielk1977ac11ee62005-01-15 12:45:51 +00005473 }
5474 }
5475 }
5476#endif
drh43605152004-05-29 21:46:49 +00005477 releasePage(pChild);
5478 }
drh2e38c322004-09-03 18:38:44 +00005479end_shallow_balance:
drh17435752007-08-16 04:30:38 +00005480 sqlite3_free(apCell);
drh2e38c322004-09-03 18:38:44 +00005481 return rc;
drh43605152004-05-29 21:46:49 +00005482}
5483
5484
5485/*
5486** The root page is overfull
5487**
5488** When this happens, Create a new child page and copy the
5489** contents of the root into the child. Then make the root
5490** page an empty page with rightChild pointing to the new
5491** child. Finally, call balance_internal() on the new child
5492** to cause it to split.
5493*/
5494static int balance_deeper(MemPage *pPage){
5495 int rc; /* Return value from subprocedures */
5496 MemPage *pChild; /* Pointer to a new child page */
5497 Pgno pgnoChild; /* Page number of the new child page */
danielk1977aef0bf62005-12-30 16:28:01 +00005498 BtShared *pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00005499 int usableSize; /* Total usable size of a page */
5500 u8 *data; /* Content of the parent page */
5501 u8 *cdata; /* Content of the child page */
5502 int hdr; /* Offset to page header in parent */
5503 int brk; /* Offset to content of first cell in parent */
5504
5505 assert( pPage->pParent==0 );
5506 assert( pPage->nOverflow>0 );
5507 pBt = pPage->pBt;
drh1fee73e2007-08-29 04:00:57 +00005508 assert( sqlite3_mutex_held(pBt->mutex) );
drh4f0c5872007-03-26 22:05:01 +00005509 rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
drh43605152004-05-29 21:46:49 +00005510 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00005511 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
drh43605152004-05-29 21:46:49 +00005512 usableSize = pBt->usableSize;
5513 data = pPage->aData;
5514 hdr = pPage->hdrOffset;
5515 brk = get2byte(&data[hdr+5]);
5516 cdata = pChild->aData;
5517 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
5518 memcpy(&cdata[brk], &data[brk], usableSize-brk);
danielk1977c7dc7532004-11-17 10:22:03 +00005519 assert( pChild->isInit==0 );
drh16a9b832007-05-05 18:39:25 +00005520 rc = sqlite3BtreeInitPage(pChild, pPage);
danielk19776b456a22005-03-21 04:04:02 +00005521 if( rc ) goto balancedeeper_out;
drh43605152004-05-29 21:46:49 +00005522 memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
5523 pChild->nOverflow = pPage->nOverflow;
5524 if( pChild->nOverflow ){
5525 pChild->nFree = 0;
5526 }
5527 assert( pChild->nCell==pPage->nCell );
5528 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
5529 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
5530 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
danielk19774e17d142005-01-16 09:06:33 +00005531#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00005532 if( pBt->autoVacuum ){
5533 int i;
5534 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
danielk19776b456a22005-03-21 04:04:02 +00005535 if( rc ) goto balancedeeper_out;
danielk1977ac11ee62005-01-15 12:45:51 +00005536 for(i=0; i<pChild->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00005537 rc = ptrmapPutOvfl(pChild, i);
5538 if( rc!=SQLITE_OK ){
5539 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00005540 }
5541 }
5542 }
danielk19774e17d142005-01-16 09:06:33 +00005543#endif
drh43605152004-05-29 21:46:49 +00005544 rc = balance_nonroot(pChild);
danielk19776b456a22005-03-21 04:04:02 +00005545
5546balancedeeper_out:
drh43605152004-05-29 21:46:49 +00005547 releasePage(pChild);
5548 return rc;
5549}
5550
5551/*
5552** Decide if the page pPage needs to be balanced. If balancing is
5553** required, call the appropriate balancing routine.
5554*/
danielk1977ac245ec2005-01-14 13:50:11 +00005555static int balance(MemPage *pPage, int insert){
drh43605152004-05-29 21:46:49 +00005556 int rc = SQLITE_OK;
drh1fee73e2007-08-29 04:00:57 +00005557 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +00005558 if( pPage->pParent==0 ){
danielk19776e465eb2007-08-21 13:11:00 +00005559 rc = sqlite3PagerWrite(pPage->pDbPage);
5560 if( rc==SQLITE_OK && pPage->nOverflow>0 ){
drh43605152004-05-29 21:46:49 +00005561 rc = balance_deeper(pPage);
5562 }
danielk1977687566d2004-11-02 12:56:41 +00005563 if( rc==SQLITE_OK && pPage->nCell==0 ){
drh43605152004-05-29 21:46:49 +00005564 rc = balance_shallower(pPage);
5565 }
5566 }else{
danielk1977ac245ec2005-01-14 13:50:11 +00005567 if( pPage->nOverflow>0 ||
5568 (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
drh43605152004-05-29 21:46:49 +00005569 rc = balance_nonroot(pPage);
5570 }
5571 }
5572 return rc;
5573}
5574
5575/*
drh8dcd7ca2004-08-08 19:43:29 +00005576** This routine checks all cursors that point to table pgnoRoot.
drh980b1a72006-08-16 16:42:48 +00005577** If any of those cursors were opened with wrFlag==0 in a different
5578** database connection (a database connection that shares the pager
5579** cache with the current connection) and that other connection
5580** is not in the ReadUncommmitted state, then this routine returns
5581** SQLITE_LOCKED.
danielk1977299b1872004-11-22 10:02:10 +00005582**
5583** In addition to checking for read-locks (where a read-lock
5584** means a cursor opened with wrFlag==0) this routine also moves
drh16a9b832007-05-05 18:39:25 +00005585** all write cursors so that they are pointing to the
drh980b1a72006-08-16 16:42:48 +00005586** first Cell on the root page. This is necessary because an insert
danielk1977299b1872004-11-22 10:02:10 +00005587** or delete might change the number of cells on a page or delete
5588** a page entirely and we do not want to leave any cursors
5589** pointing to non-existant pages or cells.
drhf74b8d92002-09-01 23:20:45 +00005590*/
drh980b1a72006-08-16 16:42:48 +00005591static int checkReadLocks(Btree *pBtree, Pgno pgnoRoot, BtCursor *pExclude){
danielk1977299b1872004-11-22 10:02:10 +00005592 BtCursor *p;
drh980b1a72006-08-16 16:42:48 +00005593 BtShared *pBt = pBtree->pBt;
drhe5fe6902007-12-07 18:55:28 +00005594 sqlite3 *db = pBtree->db;
drh1fee73e2007-08-29 04:00:57 +00005595 assert( sqlite3BtreeHoldsMutex(pBtree) );
danielk1977299b1872004-11-22 10:02:10 +00005596 for(p=pBt->pCursor; p; p=p->pNext){
drh980b1a72006-08-16 16:42:48 +00005597 if( p==pExclude ) continue;
5598 if( p->eState!=CURSOR_VALID ) continue;
5599 if( p->pgnoRoot!=pgnoRoot ) continue;
5600 if( p->wrFlag==0 ){
drhe5fe6902007-12-07 18:55:28 +00005601 sqlite3 *dbOther = p->pBtree->db;
drh980b1a72006-08-16 16:42:48 +00005602 if( dbOther==0 ||
5603 (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
5604 return SQLITE_LOCKED;
5605 }
5606 }else if( p->pPage->pgno!=p->pgnoRoot ){
danielk1977299b1872004-11-22 10:02:10 +00005607 moveToRoot(p);
5608 }
5609 }
drhf74b8d92002-09-01 23:20:45 +00005610 return SQLITE_OK;
5611}
5612
5613/*
danielk197752ae7242008-03-25 14:24:56 +00005614** Make sure pBt->pTmpSpace points to an allocation of
5615** MX_CELL_SIZE(pBt) bytes.
5616*/
5617static void allocateTempSpace(BtShared *pBt){
5618 if( !pBt->pTmpSpace ){
5619 pBt->pTmpSpace = sqlite3_malloc(MX_CELL_SIZE(pBt));
5620 }
5621}
5622
5623/*
drh3b7511c2001-05-26 13:15:44 +00005624** Insert a new record into the BTree. The key is given by (pKey,nKey)
5625** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00005626** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00005627** is left pointing at a random location.
5628**
5629** For an INTKEY table, only the nKey value of the key is used. pKey is
5630** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00005631*/
drh3aac2dd2004-04-26 14:10:20 +00005632int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00005633 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00005634 const void *pKey, i64 nKey, /* The key of the new record */
drhe4d90812007-03-29 05:51:49 +00005635 const void *pData, int nData, /* The data of the new record */
drhb026e052007-05-02 01:34:31 +00005636 int nZero, /* Number of extra 0 bytes to append to data */
drhe4d90812007-03-29 05:51:49 +00005637 int appendBias /* True if this is likely an append */
drh3b7511c2001-05-26 13:15:44 +00005638){
drh3b7511c2001-05-26 13:15:44 +00005639 int rc;
5640 int loc;
drh14acc042001-06-10 19:56:58 +00005641 int szNew;
drh3b7511c2001-05-26 13:15:44 +00005642 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00005643 Btree *p = pCur->pBtree;
5644 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00005645 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00005646 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00005647
drh1fee73e2007-08-29 04:00:57 +00005648 assert( cursorHoldsMutex(pCur) );
danielk1977aef0bf62005-12-30 16:28:01 +00005649 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005650 /* Must start a transaction before doing an insert */
drhd677b3d2007-08-20 22:48:41 +00005651 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drhd677b3d2007-08-20 22:48:41 +00005652 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005653 }
drhf74b8d92002-09-01 23:20:45 +00005654 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00005655 if( !pCur->wrFlag ){
5656 return SQLITE_PERM; /* Cursor not open for writing */
5657 }
drh980b1a72006-08-16 16:42:48 +00005658 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00005659 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5660 }
drhfb982642007-08-30 01:19:59 +00005661 if( pCur->eState==CURSOR_FAULT ){
5662 return pCur->skip;
5663 }
danielk1977da184232006-01-05 11:34:32 +00005664
5665 /* Save the positions of any other cursors open on this table */
drhbf700f32007-03-31 02:36:44 +00005666 clearCursorPosition(pCur);
danielk19772e94d4d2006-01-09 05:36:27 +00005667 if(
danielk19772e94d4d2006-01-09 05:36:27 +00005668 SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
drhe14006d2008-03-25 17:23:32 +00005669 SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, 0, nKey, appendBias, &loc))
danielk19772e94d4d2006-01-09 05:36:27 +00005670 ){
danielk1977da184232006-01-05 11:34:32 +00005671 return rc;
5672 }
5673
drh14acc042001-06-10 19:56:58 +00005674 pPage = pCur->pPage;
drh4a1c3802004-05-12 15:15:47 +00005675 assert( pPage->intKey || nKey>=0 );
drh8b18dd42004-05-12 19:18:15 +00005676 assert( pPage->leaf || !pPage->leafData );
drh3a4c1412004-05-09 20:40:11 +00005677 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
5678 pCur->pgnoRoot, nKey, nData, pPage->pgno,
5679 loc==0 ? "overwrite" : "new entry"));
drh7aa128d2002-06-21 13:09:16 +00005680 assert( pPage->isInit );
danielk197752ae7242008-03-25 14:24:56 +00005681 allocateTempSpace(pBt);
5682 newCell = pBt->pTmpSpace;
drh2e38c322004-09-03 18:38:44 +00005683 if( newCell==0 ) return SQLITE_NOMEM;
drhb026e052007-05-02 01:34:31 +00005684 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
drh2e38c322004-09-03 18:38:44 +00005685 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00005686 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00005687 assert( szNew<=MX_CELL_SIZE(pBt) );
danielk1977da184232006-01-05 11:34:32 +00005688 if( loc==0 && CURSOR_VALID==pCur->eState ){
drha9121e42008-02-19 14:59:35 +00005689 u16 szOld;
drha34b6762004-05-07 13:30:42 +00005690 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00005691 rc = sqlite3PagerWrite(pPage->pDbPage);
5692 if( rc ){
5693 goto end_insert;
5694 }
danielk19771cc5ed82007-05-16 17:28:43 +00005695 oldCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00005696 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005697 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00005698 }
drh43605152004-05-29 21:46:49 +00005699 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00005700 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00005701 if( rc ) goto end_insert;
drh4b70f112004-05-02 21:12:19 +00005702 dropCell(pPage, pCur->idx, szOld);
drh7c717f72001-06-24 20:39:41 +00005703 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00005704 assert( pPage->leaf );
drh14acc042001-06-10 19:56:58 +00005705 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00005706 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00005707 pCur->validNKey = 0;
drh14acc042001-06-10 19:56:58 +00005708 }else{
drh4b70f112004-05-02 21:12:19 +00005709 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00005710 }
danielk1977a3ad5e72005-01-07 08:56:44 +00005711 rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
danielk1977e80463b2004-11-03 03:01:16 +00005712 if( rc!=SQLITE_OK ) goto end_insert;
danielk1977ac245ec2005-01-14 13:50:11 +00005713 rc = balance(pPage, 1);
drh23e11ca2004-05-04 17:27:28 +00005714 /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
drh3fc190c2001-09-14 03:24:23 +00005715 /* fflush(stdout); */
danielk1977299b1872004-11-22 10:02:10 +00005716 if( rc==SQLITE_OK ){
5717 moveToRoot(pCur);
5718 }
drh2e38c322004-09-03 18:38:44 +00005719end_insert:
drh5e2f8b92001-05-28 00:41:15 +00005720 return rc;
5721}
5722
5723/*
drh4b70f112004-05-02 21:12:19 +00005724** Delete the entry that the cursor is pointing to. The cursor
5725** is left pointing at a random location.
drh3b7511c2001-05-26 13:15:44 +00005726*/
drh3aac2dd2004-04-26 14:10:20 +00005727int sqlite3BtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00005728 MemPage *pPage = pCur->pPage;
drh4b70f112004-05-02 21:12:19 +00005729 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00005730 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00005731 Pgno pgnoChild = 0;
drhd677b3d2007-08-20 22:48:41 +00005732 Btree *p = pCur->pBtree;
5733 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005734
drh1fee73e2007-08-29 04:00:57 +00005735 assert( cursorHoldsMutex(pCur) );
drh7aa128d2002-06-21 13:09:16 +00005736 assert( pPage->isInit );
danielk1977aef0bf62005-12-30 16:28:01 +00005737 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005738 /* Must start a transaction before doing a delete */
drhd677b3d2007-08-20 22:48:41 +00005739 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drhd677b3d2007-08-20 22:48:41 +00005740 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005741 }
drhf74b8d92002-09-01 23:20:45 +00005742 assert( !pBt->readOnly );
drhfb982642007-08-30 01:19:59 +00005743 if( pCur->eState==CURSOR_FAULT ){
5744 return pCur->skip;
5745 }
drhbd03cae2001-06-02 02:40:57 +00005746 if( pCur->idx >= pPage->nCell ){
5747 return SQLITE_ERROR; /* The cursor is not pointing to anything */
5748 }
drhecdc7532001-09-23 02:35:53 +00005749 if( !pCur->wrFlag ){
5750 return SQLITE_PERM; /* Did not open this cursor for writing */
5751 }
drh980b1a72006-08-16 16:42:48 +00005752 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00005753 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5754 }
danielk1977da184232006-01-05 11:34:32 +00005755
5756 /* Restore the current cursor position (a no-op if the cursor is not in
5757 ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors
danielk19773b8a05f2007-03-19 17:44:26 +00005758 ** open on the same table. Then call sqlite3PagerWrite() on the page
danielk1977da184232006-01-05 11:34:32 +00005759 ** that the entry will be deleted from.
5760 */
5761 if(
drhbf700f32007-03-31 02:36:44 +00005762 (rc = restoreOrClearCursorPosition(pCur))!=0 ||
drhd1167392006-01-23 13:00:35 +00005763 (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
danielk19773b8a05f2007-03-19 17:44:26 +00005764 (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
danielk1977da184232006-01-05 11:34:32 +00005765 ){
5766 return rc;
5767 }
danielk1977e6efa742004-11-10 11:55:10 +00005768
drh85b623f2007-12-13 21:54:09 +00005769 /* Locate the cell within its page and leave pCell pointing to the
danielk1977e6efa742004-11-10 11:55:10 +00005770 ** data. The clearCell() call frees any overflow pages associated with the
5771 ** cell. The cell itself is still intact.
5772 */
danielk19771cc5ed82007-05-16 17:28:43 +00005773 pCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00005774 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005775 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005776 }
danielk197728129562005-01-11 10:25:06 +00005777 rc = clearCell(pPage, pCell);
drhd677b3d2007-08-20 22:48:41 +00005778 if( rc ){
drhd677b3d2007-08-20 22:48:41 +00005779 return rc;
5780 }
danielk1977e6efa742004-11-10 11:55:10 +00005781
drh4b70f112004-05-02 21:12:19 +00005782 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00005783 /*
drh5e00f6c2001-09-13 13:46:56 +00005784 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00005785 ** do something we will leave a hole on an internal page.
5786 ** We have to fill the hole by moving in a cell from a leaf. The
5787 ** next Cell after the one to be deleted is guaranteed to exist and
danielk1977299b1872004-11-22 10:02:10 +00005788 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00005789 */
drh14acc042001-06-10 19:56:58 +00005790 BtCursor leafCur;
drh4b70f112004-05-02 21:12:19 +00005791 unsigned char *pNext;
danielk1977299b1872004-11-22 10:02:10 +00005792 int notUsed;
danielk19776b456a22005-03-21 04:04:02 +00005793 unsigned char *tempCell = 0;
drh8b18dd42004-05-12 19:18:15 +00005794 assert( !pPage->leafData );
drh16a9b832007-05-05 18:39:25 +00005795 sqlite3BtreeGetTempCursor(pCur, &leafCur);
danielk1977299b1872004-11-22 10:02:10 +00005796 rc = sqlite3BtreeNext(&leafCur, &notUsed);
danielk19776b456a22005-03-21 04:04:02 +00005797 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00005798 rc = sqlite3PagerWrite(leafCur.pPage->pDbPage);
danielk19776b456a22005-03-21 04:04:02 +00005799 }
5800 if( rc==SQLITE_OK ){
drha9121e42008-02-19 14:59:35 +00005801 u16 szNext;
danielk19776b456a22005-03-21 04:04:02 +00005802 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
5803 pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
5804 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
danielk19771cc5ed82007-05-16 17:28:43 +00005805 pNext = findCell(leafCur.pPage, leafCur.idx);
danielk19776b456a22005-03-21 04:04:02 +00005806 szNext = cellSizePtr(leafCur.pPage, pNext);
5807 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
danielk197752ae7242008-03-25 14:24:56 +00005808 allocateTempSpace(pBt);
5809 tempCell = pBt->pTmpSpace;
danielk19776b456a22005-03-21 04:04:02 +00005810 if( tempCell==0 ){
5811 rc = SQLITE_NOMEM;
5812 }
danielk19778ea1cfa2008-01-01 06:19:02 +00005813 if( rc==SQLITE_OK ){
5814 rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
5815 }
5816 if( rc==SQLITE_OK ){
5817 put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
5818 rc = balance(pPage, 0);
5819 }
5820 if( rc==SQLITE_OK ){
5821 dropCell(leafCur.pPage, leafCur.idx, szNext);
5822 rc = balance(leafCur.pPage, 0);
5823 }
danielk19776b456a22005-03-21 04:04:02 +00005824 }
drh16a9b832007-05-05 18:39:25 +00005825 sqlite3BtreeReleaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00005826 }else{
danielk1977299b1872004-11-22 10:02:10 +00005827 TRACE(("DELETE: table=%d delete from leaf %d\n",
5828 pCur->pgnoRoot, pPage->pgno));
5829 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
danielk1977ac245ec2005-01-14 13:50:11 +00005830 rc = balance(pPage, 0);
drh5e2f8b92001-05-28 00:41:15 +00005831 }
danielk19776b456a22005-03-21 04:04:02 +00005832 if( rc==SQLITE_OK ){
5833 moveToRoot(pCur);
5834 }
drh5e2f8b92001-05-28 00:41:15 +00005835 return rc;
drh3b7511c2001-05-26 13:15:44 +00005836}
drh8b2f49b2001-06-08 00:21:52 +00005837
5838/*
drhc6b52df2002-01-04 03:09:29 +00005839** Create a new BTree table. Write into *piTable the page
5840** number for the root page of the new table.
5841**
drhab01f612004-05-22 02:55:23 +00005842** The type of type is determined by the flags parameter. Only the
5843** following values of flags are currently in use. Other values for
5844** flags might not work:
5845**
5846** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
5847** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00005848*/
drhd677b3d2007-08-20 22:48:41 +00005849static int btreeCreateTable(Btree *p, int *piTable, int flags){
danielk1977aef0bf62005-12-30 16:28:01 +00005850 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005851 MemPage *pRoot;
5852 Pgno pgnoRoot;
5853 int rc;
drhd677b3d2007-08-20 22:48:41 +00005854
drh1fee73e2007-08-29 04:00:57 +00005855 assert( sqlite3BtreeHoldsMutex(p) );
danielk1977aef0bf62005-12-30 16:28:01 +00005856 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005857 /* Must start a transaction first */
drhd677b3d2007-08-20 22:48:41 +00005858 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
5859 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005860 }
danielk197728129562005-01-11 10:25:06 +00005861 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00005862
danielk1977003ba062004-11-04 02:57:33 +00005863#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00005864 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00005865 if( rc ){
5866 return rc;
5867 }
danielk1977003ba062004-11-04 02:57:33 +00005868#else
danielk1977687566d2004-11-02 12:56:41 +00005869 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00005870 Pgno pgnoMove; /* Move a page here to make room for the root-page */
5871 MemPage *pPageMove; /* The page to move to. */
5872
danielk197720713f32007-05-03 11:43:33 +00005873 /* Creating a new table may probably require moving an existing database
5874 ** to make room for the new tables root page. In case this page turns
5875 ** out to be an overflow page, delete all overflow page-map caches
5876 ** held by open cursors.
5877 */
danielk197792d4d7a2007-05-04 12:05:56 +00005878 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00005879
danielk1977003ba062004-11-04 02:57:33 +00005880 /* Read the value of meta[3] from the database to determine where the
5881 ** root page of the new table should go. meta[3] is the largest root-page
5882 ** created so far, so the new root-page is (meta[3]+1).
5883 */
danielk1977aef0bf62005-12-30 16:28:01 +00005884 rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
drhd677b3d2007-08-20 22:48:41 +00005885 if( rc!=SQLITE_OK ){
5886 return rc;
5887 }
danielk1977003ba062004-11-04 02:57:33 +00005888 pgnoRoot++;
5889
danielk1977599fcba2004-11-08 07:13:13 +00005890 /* The new root-page may not be allocated on a pointer-map page, or the
5891 ** PENDING_BYTE page.
5892 */
drh72190432008-01-31 14:54:43 +00005893 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00005894 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00005895 pgnoRoot++;
5896 }
5897 assert( pgnoRoot>=3 );
5898
5899 /* Allocate a page. The page that currently resides at pgnoRoot will
5900 ** be moved to the allocated page (unless the allocated page happens
5901 ** to reside at pgnoRoot).
5902 */
drh4f0c5872007-03-26 22:05:01 +00005903 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00005904 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00005905 return rc;
5906 }
danielk1977003ba062004-11-04 02:57:33 +00005907
5908 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00005909 /* pgnoRoot is the page that will be used for the root-page of
5910 ** the new table (assuming an error did not occur). But we were
5911 ** allocated pgnoMove. If required (i.e. if it was not allocated
5912 ** by extending the file), the current page at position pgnoMove
5913 ** is already journaled.
5914 */
danielk1977003ba062004-11-04 02:57:33 +00005915 u8 eType;
5916 Pgno iPtrPage;
5917
5918 releasePage(pPageMove);
danielk1977f35843b2007-04-07 15:03:17 +00005919
5920 /* Move the page currently at pgnoRoot to pgnoMove. */
drh16a9b832007-05-05 18:39:25 +00005921 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00005922 if( rc!=SQLITE_OK ){
5923 return rc;
5924 }
5925 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drhccae6022005-02-26 17:31:26 +00005926 if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00005927 releasePage(pRoot);
5928 return rc;
5929 }
drhccae6022005-02-26 17:31:26 +00005930 assert( eType!=PTRMAP_ROOTPAGE );
5931 assert( eType!=PTRMAP_FREEPAGE );
danielk19773b8a05f2007-03-19 17:44:26 +00005932 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk19775fd057a2005-03-09 13:09:43 +00005933 if( rc!=SQLITE_OK ){
5934 releasePage(pRoot);
5935 return rc;
5936 }
danielk1977003ba062004-11-04 02:57:33 +00005937 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove);
5938 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00005939
5940 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00005941 if( rc!=SQLITE_OK ){
5942 return rc;
5943 }
drh16a9b832007-05-05 18:39:25 +00005944 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00005945 if( rc!=SQLITE_OK ){
5946 return rc;
5947 }
danielk19773b8a05f2007-03-19 17:44:26 +00005948 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00005949 if( rc!=SQLITE_OK ){
5950 releasePage(pRoot);
5951 return rc;
5952 }
5953 }else{
5954 pRoot = pPageMove;
5955 }
5956
danielk197742741be2005-01-08 12:42:39 +00005957 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00005958 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
5959 if( rc ){
5960 releasePage(pRoot);
5961 return rc;
5962 }
danielk1977aef0bf62005-12-30 16:28:01 +00005963 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00005964 if( rc ){
5965 releasePage(pRoot);
5966 return rc;
5967 }
danielk197742741be2005-01-08 12:42:39 +00005968
danielk1977003ba062004-11-04 02:57:33 +00005969 }else{
drh4f0c5872007-03-26 22:05:01 +00005970 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00005971 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00005972 }
5973#endif
danielk19773b8a05f2007-03-19 17:44:26 +00005974 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhde647132004-05-07 17:57:49 +00005975 zeroPage(pRoot, flags | PTF_LEAF);
danielk19773b8a05f2007-03-19 17:44:26 +00005976 sqlite3PagerUnref(pRoot->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00005977 *piTable = (int)pgnoRoot;
5978 return SQLITE_OK;
5979}
drhd677b3d2007-08-20 22:48:41 +00005980int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
5981 int rc;
5982 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00005983 p->pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00005984 rc = btreeCreateTable(p, piTable, flags);
5985 sqlite3BtreeLeave(p);
5986 return rc;
5987}
drh8b2f49b2001-06-08 00:21:52 +00005988
5989/*
5990** Erase the given database page and all its children. Return
5991** the page to the freelist.
5992*/
drh4b70f112004-05-02 21:12:19 +00005993static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00005994 BtShared *pBt, /* The BTree that contains the table */
drh4b70f112004-05-02 21:12:19 +00005995 Pgno pgno, /* Page number to clear */
5996 MemPage *pParent, /* Parent page. NULL for the root */
5997 int freePageFlag /* Deallocate page if true */
5998){
danielk19776b456a22005-03-21 04:04:02 +00005999 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00006000 int rc;
drh4b70f112004-05-02 21:12:19 +00006001 unsigned char *pCell;
6002 int i;
drh8b2f49b2001-06-08 00:21:52 +00006003
drh1fee73e2007-08-29 04:00:57 +00006004 assert( sqlite3_mutex_held(pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00006005 if( pgno>sqlite3PagerPagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00006006 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00006007 }
6008
drhde647132004-05-07 17:57:49 +00006009 rc = getAndInitPage(pBt, pgno, &pPage, pParent);
danielk19776b456a22005-03-21 04:04:02 +00006010 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00006011 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00006012 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00006013 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006014 rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00006015 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006016 }
drh4b70f112004-05-02 21:12:19 +00006017 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00006018 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006019 }
drha34b6762004-05-07 13:30:42 +00006020 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006021 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00006022 if( rc ) goto cleardatabasepage_out;
drh2aa679f2001-06-25 02:11:07 +00006023 }
6024 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00006025 rc = freePage(pPage);
danielk19773b8a05f2007-03-19 17:44:26 +00006026 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
drh3a4c1412004-05-09 20:40:11 +00006027 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00006028 }
danielk19776b456a22005-03-21 04:04:02 +00006029
6030cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00006031 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00006032 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006033}
6034
6035/*
drhab01f612004-05-22 02:55:23 +00006036** Delete all information from a single table in the database. iTable is
6037** the page number of the root of the table. After this routine returns,
6038** the root page is empty, but still exists.
6039**
6040** This routine will fail with SQLITE_LOCKED if there are any open
6041** read cursors on the table. Open write cursors are moved to the
6042** root of the table.
drh8b2f49b2001-06-08 00:21:52 +00006043*/
danielk1977aef0bf62005-12-30 16:28:01 +00006044int sqlite3BtreeClearTable(Btree *p, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00006045 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00006046 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00006047 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006048 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00006049 if( p->inTrans!=TRANS_WRITE ){
drhd677b3d2007-08-20 22:48:41 +00006050 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
6051 }else if( (rc = checkReadLocks(p, iTable, 0))!=SQLITE_OK ){
6052 /* nothing to do */
6053 }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
6054 /* nothing to do */
6055 }else{
6056 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
drh8b2f49b2001-06-08 00:21:52 +00006057 }
drhd677b3d2007-08-20 22:48:41 +00006058 sqlite3BtreeLeave(p);
6059 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006060}
6061
6062/*
6063** Erase all information in a table and add the root of the table to
6064** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00006065** page 1) is never added to the freelist.
6066**
6067** This routine will fail with SQLITE_LOCKED if there are any open
6068** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00006069**
6070** If AUTOVACUUM is enabled and the page at iTable is not the last
6071** root page in the database file, then the last root page
6072** in the database file is moved into the slot formerly occupied by
6073** iTable and that last slot formerly occupied by the last root page
6074** is added to the freelist instead of iTable. In this say, all
6075** root pages are kept at the beginning of the database file, which
6076** is necessary for AUTOVACUUM to work right. *piMoved is set to the
6077** page number that used to be the last root page in the file before
6078** the move. If no page gets moved, *piMoved is set to 0.
6079** The last root page is recorded in meta[3] and the value of
6080** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00006081*/
drhd677b3d2007-08-20 22:48:41 +00006082static int btreeDropTable(Btree *p, int iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00006083 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00006084 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00006085 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00006086
drh1fee73e2007-08-29 04:00:57 +00006087 assert( sqlite3BtreeHoldsMutex(p) );
danielk1977aef0bf62005-12-30 16:28:01 +00006088 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00006089 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00006090 }
danielk1977a0bf2652004-11-04 14:30:04 +00006091
danielk1977e6efa742004-11-10 11:55:10 +00006092 /* It is illegal to drop a table if any cursors are open on the
6093 ** database. This is because in auto-vacuum mode the backend may
6094 ** need to move another root-page to fill a gap left by the deleted
6095 ** root page. If an open cursor was using this page a problem would
6096 ** occur.
6097 */
6098 if( pBt->pCursor ){
6099 return SQLITE_LOCKED;
drh5df72a52002-06-06 23:16:05 +00006100 }
danielk1977a0bf2652004-11-04 14:30:04 +00006101
drh16a9b832007-05-05 18:39:25 +00006102 rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00006103 if( rc ) return rc;
danielk1977aef0bf62005-12-30 16:28:01 +00006104 rc = sqlite3BtreeClearTable(p, iTable);
danielk19776b456a22005-03-21 04:04:02 +00006105 if( rc ){
6106 releasePage(pPage);
6107 return rc;
6108 }
danielk1977a0bf2652004-11-04 14:30:04 +00006109
drh205f48e2004-11-05 00:43:11 +00006110 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00006111
drh4b70f112004-05-02 21:12:19 +00006112 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00006113#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00006114 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00006115 releasePage(pPage);
6116#else
6117 if( pBt->autoVacuum ){
6118 Pgno maxRootPgno;
danielk1977aef0bf62005-12-30 16:28:01 +00006119 rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006120 if( rc!=SQLITE_OK ){
6121 releasePage(pPage);
6122 return rc;
6123 }
6124
6125 if( iTable==maxRootPgno ){
6126 /* If the table being dropped is the table with the largest root-page
6127 ** number in the database, put the root page on the free list.
6128 */
6129 rc = freePage(pPage);
6130 releasePage(pPage);
6131 if( rc!=SQLITE_OK ){
6132 return rc;
6133 }
6134 }else{
6135 /* The table being dropped does not have the largest root-page
6136 ** number in the database. So move the page that does into the
6137 ** gap left by the deleted root-page.
6138 */
6139 MemPage *pMove;
6140 releasePage(pPage);
drh16a9b832007-05-05 18:39:25 +00006141 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006142 if( rc!=SQLITE_OK ){
6143 return rc;
6144 }
6145 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable);
6146 releasePage(pMove);
6147 if( rc!=SQLITE_OK ){
6148 return rc;
6149 }
drh16a9b832007-05-05 18:39:25 +00006150 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006151 if( rc!=SQLITE_OK ){
6152 return rc;
6153 }
6154 rc = freePage(pMove);
6155 releasePage(pMove);
6156 if( rc!=SQLITE_OK ){
6157 return rc;
6158 }
6159 *piMoved = maxRootPgno;
6160 }
6161
danielk1977599fcba2004-11-08 07:13:13 +00006162 /* Set the new 'max-root-page' value in the database header. This
6163 ** is the old value less one, less one more if that happens to
6164 ** be a root-page number, less one again if that is the
6165 ** PENDING_BYTE_PAGE.
6166 */
danielk197787a6e732004-11-05 12:58:25 +00006167 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00006168 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
6169 maxRootPgno--;
6170 }
danielk1977266664d2006-02-10 08:24:21 +00006171 if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00006172 maxRootPgno--;
6173 }
danielk1977599fcba2004-11-08 07:13:13 +00006174 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
6175
danielk1977aef0bf62005-12-30 16:28:01 +00006176 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006177 }else{
6178 rc = freePage(pPage);
6179 releasePage(pPage);
6180 }
6181#endif
drh2aa679f2001-06-25 02:11:07 +00006182 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00006183 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00006184 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00006185 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00006186 }
drh8b2f49b2001-06-08 00:21:52 +00006187 return rc;
6188}
drhd677b3d2007-08-20 22:48:41 +00006189int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
6190 int rc;
6191 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006192 p->pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006193 rc = btreeDropTable(p, iTable, piMoved);
6194 sqlite3BtreeLeave(p);
6195 return rc;
6196}
drh8b2f49b2001-06-08 00:21:52 +00006197
drh001bbcb2003-03-19 03:14:00 +00006198
drh8b2f49b2001-06-08 00:21:52 +00006199/*
drh23e11ca2004-05-04 17:27:28 +00006200** Read the meta-information out of a database file. Meta[0]
6201** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00006202** through meta[15] are available for use by higher layers. Meta[0]
6203** is read-only, the others are read/write.
6204**
6205** The schema layer numbers meta values differently. At the schema
6206** layer (and the SetCookie and ReadCookie opcodes) the number of
6207** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00006208*/
danielk1977aef0bf62005-12-30 16:28:01 +00006209int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
danielk19773b8a05f2007-03-19 17:44:26 +00006210 DbPage *pDbPage;
drh8b2f49b2001-06-08 00:21:52 +00006211 int rc;
drh4b70f112004-05-02 21:12:19 +00006212 unsigned char *pP1;
danielk1977aef0bf62005-12-30 16:28:01 +00006213 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006214
drhd677b3d2007-08-20 22:48:41 +00006215 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006216 pBt->db = p->db;
drhd677b3d2007-08-20 22:48:41 +00006217
danielk1977da184232006-01-05 11:34:32 +00006218 /* Reading a meta-data value requires a read-lock on page 1 (and hence
6219 ** the sqlite_master table. We grab this lock regardless of whether or
6220 ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
6221 ** 1 is treated as a special case by queryTableLock() and lockTable()).
6222 */
6223 rc = queryTableLock(p, 1, READ_LOCK);
6224 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00006225 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00006226 return rc;
6227 }
6228
drh23e11ca2004-05-04 17:27:28 +00006229 assert( idx>=0 && idx<=15 );
danielk19773b8a05f2007-03-19 17:44:26 +00006230 rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
drhd677b3d2007-08-20 22:48:41 +00006231 if( rc ){
6232 sqlite3BtreeLeave(p);
6233 return rc;
6234 }
danielk19773b8a05f2007-03-19 17:44:26 +00006235 pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
drh23e11ca2004-05-04 17:27:28 +00006236 *pMeta = get4byte(&pP1[36 + idx*4]);
danielk19773b8a05f2007-03-19 17:44:26 +00006237 sqlite3PagerUnref(pDbPage);
drhae157872004-08-14 19:20:09 +00006238
danielk1977599fcba2004-11-08 07:13:13 +00006239 /* If autovacuumed is disabled in this build but we are trying to
6240 ** access an autovacuumed database, then make the database readonly.
6241 */
danielk1977003ba062004-11-04 02:57:33 +00006242#ifdef SQLITE_OMIT_AUTOVACUUM
drhae157872004-08-14 19:20:09 +00006243 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00006244#endif
drhae157872004-08-14 19:20:09 +00006245
danielk1977da184232006-01-05 11:34:32 +00006246 /* Grab the read-lock on page 1. */
6247 rc = lockTable(p, 1, READ_LOCK);
drhd677b3d2007-08-20 22:48:41 +00006248 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00006249 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006250}
6251
6252/*
drh23e11ca2004-05-04 17:27:28 +00006253** Write meta-information back into the database. Meta[0] is
6254** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00006255*/
danielk1977aef0bf62005-12-30 16:28:01 +00006256int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
6257 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00006258 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00006259 int rc;
drh23e11ca2004-05-04 17:27:28 +00006260 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00006261 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006262 pBt->db = p->db;
danielk1977aef0bf62005-12-30 16:28:01 +00006263 if( p->inTrans!=TRANS_WRITE ){
drhd677b3d2007-08-20 22:48:41 +00006264 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
6265 }else{
6266 assert( pBt->pPage1!=0 );
6267 pP1 = pBt->pPage1->aData;
6268 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6269 if( rc==SQLITE_OK ){
6270 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +00006271#ifndef SQLITE_OMIT_AUTOVACUUM
drhd677b3d2007-08-20 22:48:41 +00006272 if( idx==7 ){
6273 assert( pBt->autoVacuum || iMeta==0 );
6274 assert( iMeta==0 || iMeta==1 );
6275 pBt->incrVacuum = iMeta;
6276 }
danielk19774152e672007-09-12 17:01:45 +00006277#endif
drhd677b3d2007-08-20 22:48:41 +00006278 }
drh5df72a52002-06-06 23:16:05 +00006279 }
drhd677b3d2007-08-20 22:48:41 +00006280 sqlite3BtreeLeave(p);
6281 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006282}
drh8c42ca92001-06-22 19:15:00 +00006283
drhf328bc82004-05-10 23:29:49 +00006284/*
6285** Return the flag byte at the beginning of the page that the cursor
6286** is currently pointing to.
6287*/
6288int sqlite3BtreeFlags(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00006289 /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
drh777e4c42006-01-13 04:31:58 +00006290 ** restoreOrClearCursorPosition() here.
danielk1977da184232006-01-05 11:34:32 +00006291 */
danielk1977e448dc42008-01-02 11:50:51 +00006292 MemPage *pPage;
6293 restoreOrClearCursorPosition(pCur);
6294 pPage = pCur->pPage;
drh1fee73e2007-08-29 04:00:57 +00006295 assert( cursorHoldsMutex(pCur) );
drhd0679ed2007-08-28 22:24:34 +00006296 assert( pPage->pBt==pCur->pBt );
drhf328bc82004-05-10 23:29:49 +00006297 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
6298}
6299
drhdd793422001-06-28 01:54:48 +00006300
drhdd793422001-06-28 01:54:48 +00006301/*
drh5eddca62001-06-30 21:53:53 +00006302** Return the pager associated with a BTree. This routine is used for
6303** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00006304*/
danielk1977aef0bf62005-12-30 16:28:01 +00006305Pager *sqlite3BtreePager(Btree *p){
6306 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00006307}
drh5eddca62001-06-30 21:53:53 +00006308
drhb7f91642004-10-31 02:22:47 +00006309#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006310/*
6311** Append a message to the error message string.
6312*/
drh2e38c322004-09-03 18:38:44 +00006313static void checkAppendMsg(
6314 IntegrityCk *pCheck,
6315 char *zMsg1,
6316 const char *zFormat,
6317 ...
6318){
6319 va_list ap;
6320 char *zMsg2;
drh1dcdbc02007-01-27 02:24:54 +00006321 if( !pCheck->mxErr ) return;
6322 pCheck->mxErr--;
6323 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00006324 va_start(ap, zFormat);
danielk19771e536952007-08-16 10:09:01 +00006325 zMsg2 = sqlite3VMPrintf(0, zFormat, ap);
drh2e38c322004-09-03 18:38:44 +00006326 va_end(ap);
6327 if( zMsg1==0 ) zMsg1 = "";
drh5eddca62001-06-30 21:53:53 +00006328 if( pCheck->zErrMsg ){
6329 char *zOld = pCheck->zErrMsg;
6330 pCheck->zErrMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00006331 sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
drh17435752007-08-16 04:30:38 +00006332 sqlite3_free(zOld);
drh5eddca62001-06-30 21:53:53 +00006333 }else{
danielk19774adee202004-05-08 08:23:19 +00006334 sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00006335 }
drh17435752007-08-16 04:30:38 +00006336 sqlite3_free(zMsg2);
drh5eddca62001-06-30 21:53:53 +00006337}
drhb7f91642004-10-31 02:22:47 +00006338#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006339
drhb7f91642004-10-31 02:22:47 +00006340#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006341/*
6342** Add 1 to the reference count for page iPage. If this is the second
6343** reference to the page, add an error message to pCheck->zErrMsg.
6344** Return 1 if there are 2 ore more references to the page and 0 if
6345** if this is the first reference to the page.
6346**
6347** Also check that the page number is in bounds.
6348*/
drhaaab5722002-02-19 13:39:21 +00006349static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00006350 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00006351 if( iPage>pCheck->nPage || iPage<0 ){
drh2e38c322004-09-03 18:38:44 +00006352 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006353 return 1;
6354 }
6355 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00006356 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006357 return 1;
6358 }
6359 return (pCheck->anRef[iPage]++)>1;
6360}
6361
danielk1977afcdd022004-10-31 16:25:42 +00006362#ifndef SQLITE_OMIT_AUTOVACUUM
6363/*
6364** Check that the entry in the pointer-map for page iChild maps to
6365** page iParent, pointer type ptrType. If not, append an error message
6366** to pCheck.
6367*/
6368static void checkPtrmap(
6369 IntegrityCk *pCheck, /* Integrity check context */
6370 Pgno iChild, /* Child page number */
6371 u8 eType, /* Expected pointer map type */
6372 Pgno iParent, /* Expected pointer map parent page number */
6373 char *zContext /* Context description (used for error msg) */
6374){
6375 int rc;
6376 u8 ePtrmapType;
6377 Pgno iPtrmapParent;
6378
6379 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
6380 if( rc!=SQLITE_OK ){
6381 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
6382 return;
6383 }
6384
6385 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
6386 checkAppendMsg(pCheck, zContext,
6387 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
6388 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
6389 }
6390}
6391#endif
6392
drh5eddca62001-06-30 21:53:53 +00006393/*
6394** Check the integrity of the freelist or of an overflow page list.
6395** Verify that the number of pages on the list is N.
6396*/
drh30e58752002-03-02 20:41:57 +00006397static void checkList(
6398 IntegrityCk *pCheck, /* Integrity checking context */
6399 int isFreeList, /* True for a freelist. False for overflow page list */
6400 int iPage, /* Page number for first page in the list */
6401 int N, /* Expected number of pages in the list */
6402 char *zContext /* Context for error messages */
6403){
6404 int i;
drh3a4c1412004-05-09 20:40:11 +00006405 int expected = N;
6406 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00006407 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00006408 DbPage *pOvflPage;
6409 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00006410 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00006411 checkAppendMsg(pCheck, zContext,
6412 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00006413 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00006414 break;
6415 }
6416 if( checkRef(pCheck, iPage, zContext) ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00006417 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
drh2e38c322004-09-03 18:38:44 +00006418 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006419 break;
6420 }
danielk19773b8a05f2007-03-19 17:44:26 +00006421 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00006422 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00006423 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00006424#ifndef SQLITE_OMIT_AUTOVACUUM
6425 if( pCheck->pBt->autoVacuum ){
6426 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
6427 }
6428#endif
drh855eb1c2004-08-31 13:45:11 +00006429 if( n>pCheck->pBt->usableSize/4-8 ){
drh2e38c322004-09-03 18:38:44 +00006430 checkAppendMsg(pCheck, zContext,
6431 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00006432 N--;
6433 }else{
6434 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00006435 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00006436#ifndef SQLITE_OMIT_AUTOVACUUM
6437 if( pCheck->pBt->autoVacuum ){
6438 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
6439 }
6440#endif
6441 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00006442 }
6443 N -= n;
drh30e58752002-03-02 20:41:57 +00006444 }
drh30e58752002-03-02 20:41:57 +00006445 }
danielk1977afcdd022004-10-31 16:25:42 +00006446#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006447 else{
6448 /* If this database supports auto-vacuum and iPage is not the last
6449 ** page in this overflow list, check that the pointer-map entry for
6450 ** the following page matches iPage.
6451 */
6452 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00006453 i = get4byte(pOvflData);
danielk1977687566d2004-11-02 12:56:41 +00006454 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
6455 }
danielk1977afcdd022004-10-31 16:25:42 +00006456 }
6457#endif
danielk19773b8a05f2007-03-19 17:44:26 +00006458 iPage = get4byte(pOvflData);
6459 sqlite3PagerUnref(pOvflPage);
drh5eddca62001-06-30 21:53:53 +00006460 }
6461}
drhb7f91642004-10-31 02:22:47 +00006462#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006463
drhb7f91642004-10-31 02:22:47 +00006464#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006465/*
6466** Do various sanity checks on a single page of a tree. Return
6467** the tree depth. Root pages return 0. Parents of root pages
6468** return 1, and so forth.
6469**
6470** These checks are done:
6471**
6472** 1. Make sure that cells and freeblocks do not overlap
6473** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00006474** NO 2. Make sure cell keys are in order.
6475** NO 3. Make sure no key is less than or equal to zLowerBound.
6476** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00006477** 5. Check the integrity of overflow pages.
6478** 6. Recursively call checkTreePage on all children.
6479** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00006480** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00006481** the root of the tree.
6482*/
6483static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00006484 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00006485 int iPage, /* Page number of the page to check */
6486 MemPage *pParent, /* Parent page */
drh74161702006-02-24 02:53:49 +00006487 char *zParentContext /* Parent context */
drh5eddca62001-06-30 21:53:53 +00006488){
6489 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00006490 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00006491 int hdr, cellStart;
6492 int nCell;
drhda200cc2004-05-09 11:51:38 +00006493 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00006494 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00006495 int usableSize;
drh5eddca62001-06-30 21:53:53 +00006496 char zContext[100];
drh2e38c322004-09-03 18:38:44 +00006497 char *hit;
drh5eddca62001-06-30 21:53:53 +00006498
drh5bb3eb92007-05-04 13:15:55 +00006499 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
danielk1977ef73ee92004-11-06 12:26:07 +00006500
drh5eddca62001-06-30 21:53:53 +00006501 /* Check that the page exists
6502 */
drhd9cb6ac2005-10-20 07:28:17 +00006503 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00006504 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00006505 if( iPage==0 ) return 0;
6506 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh16a9b832007-05-05 18:39:25 +00006507 if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drh2e38c322004-09-03 18:38:44 +00006508 checkAppendMsg(pCheck, zContext,
6509 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00006510 return 0;
6511 }
drh16a9b832007-05-05 18:39:25 +00006512 if( (rc = sqlite3BtreeInitPage(pPage, pParent))!=0 ){
6513 checkAppendMsg(pCheck, zContext,
6514 "sqlite3BtreeInitPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00006515 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00006516 return 0;
6517 }
6518
6519 /* Check out all the cells.
6520 */
6521 depth = 0;
drh1dcdbc02007-01-27 02:24:54 +00006522 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
drh6f11bef2004-05-13 01:12:56 +00006523 u8 *pCell;
6524 int sz;
6525 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00006526
6527 /* Check payload overflow pages
6528 */
drh5bb3eb92007-05-04 13:15:55 +00006529 sqlite3_snprintf(sizeof(zContext), zContext,
6530 "On tree page %d cell %d: ", iPage, i);
danielk19771cc5ed82007-05-16 17:28:43 +00006531 pCell = findCell(pPage,i);
drh16a9b832007-05-05 18:39:25 +00006532 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00006533 sz = info.nData;
6534 if( !pPage->intKey ) sz += info.nKey;
drh72365832007-03-06 15:53:44 +00006535 assert( sz==info.nPayload );
drh6f11bef2004-05-13 01:12:56 +00006536 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00006537 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00006538 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
6539#ifndef SQLITE_OMIT_AUTOVACUUM
6540 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006541 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00006542 }
6543#endif
6544 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00006545 }
6546
6547 /* Check sanity of left child page.
6548 */
drhda200cc2004-05-09 11:51:38 +00006549 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006550 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00006551#ifndef SQLITE_OMIT_AUTOVACUUM
6552 if( pBt->autoVacuum ){
6553 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
6554 }
6555#endif
drh74161702006-02-24 02:53:49 +00006556 d2 = checkTreePage(pCheck,pgno,pPage,zContext);
drhda200cc2004-05-09 11:51:38 +00006557 if( i>0 && d2!=depth ){
6558 checkAppendMsg(pCheck, zContext, "Child page depth differs");
6559 }
6560 depth = d2;
drh5eddca62001-06-30 21:53:53 +00006561 }
drh5eddca62001-06-30 21:53:53 +00006562 }
drhda200cc2004-05-09 11:51:38 +00006563 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006564 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh5bb3eb92007-05-04 13:15:55 +00006565 sqlite3_snprintf(sizeof(zContext), zContext,
6566 "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00006567#ifndef SQLITE_OMIT_AUTOVACUUM
6568 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006569 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00006570 }
6571#endif
drh74161702006-02-24 02:53:49 +00006572 checkTreePage(pCheck, pgno, pPage, zContext);
drhda200cc2004-05-09 11:51:38 +00006573 }
drh5eddca62001-06-30 21:53:53 +00006574
6575 /* Check for complete coverage of the page
6576 */
drhda200cc2004-05-09 11:51:38 +00006577 data = pPage->aData;
6578 hdr = pPage->hdrOffset;
drh17435752007-08-16 04:30:38 +00006579 hit = sqlite3MallocZero( usableSize );
drh2e38c322004-09-03 18:38:44 +00006580 if( hit ){
6581 memset(hit, 1, get2byte(&data[hdr+5]));
6582 nCell = get2byte(&data[hdr+3]);
6583 cellStart = hdr + 12 - 4*pPage->leaf;
6584 for(i=0; i<nCell; i++){
6585 int pc = get2byte(&data[cellStart+i*2]);
drha9121e42008-02-19 14:59:35 +00006586 u16 size = cellSizePtr(pPage, &data[pc]);
drh2e38c322004-09-03 18:38:44 +00006587 int j;
danielk19777701e812005-01-10 12:59:51 +00006588 if( (pc+size-1)>=usableSize || pc<0 ){
6589 checkAppendMsg(pCheck, 0,
6590 "Corruption detected in cell %d on page %d",i,iPage,0);
6591 }else{
6592 for(j=pc+size-1; j>=pc; j--) hit[j]++;
6593 }
drh2e38c322004-09-03 18:38:44 +00006594 }
6595 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
6596 cnt++){
6597 int size = get2byte(&data[i+2]);
6598 int j;
danielk19777701e812005-01-10 12:59:51 +00006599 if( (i+size-1)>=usableSize || i<0 ){
6600 checkAppendMsg(pCheck, 0,
6601 "Corruption detected in cell %d on page %d",i,iPage,0);
6602 }else{
6603 for(j=i+size-1; j>=i; j--) hit[j]++;
6604 }
drh2e38c322004-09-03 18:38:44 +00006605 i = get2byte(&data[i]);
6606 }
6607 for(i=cnt=0; i<usableSize; i++){
6608 if( hit[i]==0 ){
6609 cnt++;
6610 }else if( hit[i]>1 ){
6611 checkAppendMsg(pCheck, 0,
6612 "Multiple uses for byte %d of page %d", i, iPage);
6613 break;
6614 }
6615 }
6616 if( cnt!=data[hdr+7] ){
6617 checkAppendMsg(pCheck, 0,
6618 "Fragmented space is %d byte reported as %d on page %d",
6619 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00006620 }
6621 }
drh17435752007-08-16 04:30:38 +00006622 sqlite3_free(hit);
drh6019e162001-07-02 17:51:45 +00006623
drh4b70f112004-05-02 21:12:19 +00006624 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00006625 return depth+1;
drh5eddca62001-06-30 21:53:53 +00006626}
drhb7f91642004-10-31 02:22:47 +00006627#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006628
drhb7f91642004-10-31 02:22:47 +00006629#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006630/*
6631** This routine does a complete check of the given BTree file. aRoot[] is
6632** an array of pages numbers were each page number is the root page of
6633** a table. nRoot is the number of entries in aRoot.
6634**
6635** If everything checks out, this routine returns NULL. If something is
6636** amiss, an error message is written into memory obtained from malloc()
6637** and a pointer to that error message is returned. The calling function
6638** is responsible for freeing the error message when it is done.
6639*/
drh1dcdbc02007-01-27 02:24:54 +00006640char *sqlite3BtreeIntegrityCheck(
6641 Btree *p, /* The btree to be checked */
6642 int *aRoot, /* An array of root pages numbers for individual trees */
6643 int nRoot, /* Number of entries in aRoot[] */
6644 int mxErr, /* Stop reporting errors after this many */
6645 int *pnErr /* Write number of errors seen to this variable */
6646){
drh5eddca62001-06-30 21:53:53 +00006647 int i;
6648 int nRef;
drhaaab5722002-02-19 13:39:21 +00006649 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00006650 BtShared *pBt = p->pBt;
drh5eddca62001-06-30 21:53:53 +00006651
drhd677b3d2007-08-20 22:48:41 +00006652 sqlite3BtreeEnter(p);
drhe5fe6902007-12-07 18:55:28 +00006653 pBt->db = p->db;
danielk19773b8a05f2007-03-19 17:44:26 +00006654 nRef = sqlite3PagerRefcount(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00006655 if( lockBtreeWithRetry(p)!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00006656 sqlite3BtreeLeave(p);
drh17435752007-08-16 04:30:38 +00006657 return sqlite3StrDup("Unable to acquire a read lock on the database");
drhefc251d2001-07-01 22:12:01 +00006658 }
drh5eddca62001-06-30 21:53:53 +00006659 sCheck.pBt = pBt;
6660 sCheck.pPager = pBt->pPager;
danielk19773b8a05f2007-03-19 17:44:26 +00006661 sCheck.nPage = sqlite3PagerPagecount(sCheck.pPager);
drh1dcdbc02007-01-27 02:24:54 +00006662 sCheck.mxErr = mxErr;
6663 sCheck.nErr = 0;
6664 *pnErr = 0;
danielk1977e5321f02007-04-27 07:05:44 +00006665#ifndef SQLITE_OMIT_AUTOVACUUM
6666 if( pBt->nTrunc!=0 ){
6667 sCheck.nPage = pBt->nTrunc;
6668 }
6669#endif
drh0de8c112002-07-06 16:32:14 +00006670 if( sCheck.nPage==0 ){
6671 unlockBtreeIfUnused(pBt);
drhd677b3d2007-08-20 22:48:41 +00006672 sqlite3BtreeLeave(p);
drh0de8c112002-07-06 16:32:14 +00006673 return 0;
6674 }
drh17435752007-08-16 04:30:38 +00006675 sCheck.anRef = sqlite3_malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00006676 if( !sCheck.anRef ){
6677 unlockBtreeIfUnused(pBt);
drh1dcdbc02007-01-27 02:24:54 +00006678 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00006679 sqlite3BtreeLeave(p);
drhe5fe6902007-12-07 18:55:28 +00006680 return sqlite3MPrintf(p->db, "Unable to malloc %d bytes",
danielk1977ac245ec2005-01-14 13:50:11 +00006681 (sCheck.nPage+1)*sizeof(sCheck.anRef[0]));
6682 }
drhda200cc2004-05-09 11:51:38 +00006683 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00006684 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00006685 if( i<=sCheck.nPage ){
6686 sCheck.anRef[i] = 1;
6687 }
drh5eddca62001-06-30 21:53:53 +00006688 sCheck.zErrMsg = 0;
6689
6690 /* Check the integrity of the freelist
6691 */
drha34b6762004-05-07 13:30:42 +00006692 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
6693 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00006694
6695 /* Check all the tables.
6696 */
drh1dcdbc02007-01-27 02:24:54 +00006697 for(i=0; i<nRoot && sCheck.mxErr; i++){
drh4ff6dfa2002-03-03 23:06:00 +00006698 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00006699#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006700 if( pBt->autoVacuum && aRoot[i]>1 ){
6701 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
6702 }
6703#endif
drh74161702006-02-24 02:53:49 +00006704 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ");
drh5eddca62001-06-30 21:53:53 +00006705 }
6706
6707 /* Make sure every page in the file is referenced
6708 */
drh1dcdbc02007-01-27 02:24:54 +00006709 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00006710#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00006711 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00006712 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00006713 }
danielk1977afcdd022004-10-31 16:25:42 +00006714#else
6715 /* If the database supports auto-vacuum, make sure no tables contain
6716 ** references to pointer-map pages.
6717 */
6718 if( sCheck.anRef[i]==0 &&
danielk1977266664d2006-02-10 08:24:21 +00006719 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006720 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
6721 }
6722 if( sCheck.anRef[i]!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00006723 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006724 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
6725 }
6726#endif
drh5eddca62001-06-30 21:53:53 +00006727 }
6728
6729 /* Make sure this analysis did not leave any unref() pages
6730 */
drh5e00f6c2001-09-13 13:46:56 +00006731 unlockBtreeIfUnused(pBt);
danielk19773b8a05f2007-03-19 17:44:26 +00006732 if( nRef != sqlite3PagerRefcount(pBt->pPager) ){
drh2e38c322004-09-03 18:38:44 +00006733 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00006734 "Outstanding page count goes from %d to %d during this analysis",
danielk19773b8a05f2007-03-19 17:44:26 +00006735 nRef, sqlite3PagerRefcount(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00006736 );
drh5eddca62001-06-30 21:53:53 +00006737 }
6738
6739 /* Clean up and report errors.
6740 */
drhd677b3d2007-08-20 22:48:41 +00006741 sqlite3BtreeLeave(p);
drh17435752007-08-16 04:30:38 +00006742 sqlite3_free(sCheck.anRef);
drh1dcdbc02007-01-27 02:24:54 +00006743 *pnErr = sCheck.nErr;
drh5eddca62001-06-30 21:53:53 +00006744 return sCheck.zErrMsg;
6745}
drhb7f91642004-10-31 02:22:47 +00006746#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00006747
drh73509ee2003-04-06 20:44:45 +00006748/*
6749** Return the full pathname of the underlying database file.
drhd0679ed2007-08-28 22:24:34 +00006750**
6751** The pager filename is invariant as long as the pager is
6752** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +00006753*/
danielk1977aef0bf62005-12-30 16:28:01 +00006754const char *sqlite3BtreeGetFilename(Btree *p){
6755 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00006756 return sqlite3PagerFilename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00006757}
6758
6759/*
danielk19775865e3d2004-06-14 06:03:57 +00006760** Return the pathname of the directory that contains the database file.
drhd0679ed2007-08-28 22:24:34 +00006761**
6762** The pager directory name is invariant as long as the pager is
6763** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00006764*/
danielk1977aef0bf62005-12-30 16:28:01 +00006765const char *sqlite3BtreeGetDirname(Btree *p){
6766 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00006767 return sqlite3PagerDirname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006768}
6769
6770/*
6771** Return the pathname of the journal file for this database. The return
6772** value of this routine is the same regardless of whether the journal file
6773** has been created or not.
drhd0679ed2007-08-28 22:24:34 +00006774**
6775** The pager journal filename is invariant as long as the pager is
6776** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00006777*/
danielk1977aef0bf62005-12-30 16:28:01 +00006778const char *sqlite3BtreeGetJournalname(Btree *p){
6779 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00006780 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006781}
6782
drhb7f91642004-10-31 02:22:47 +00006783#ifndef SQLITE_OMIT_VACUUM
danielk19775865e3d2004-06-14 06:03:57 +00006784/*
drhf7c57532003-04-25 13:22:51 +00006785** Copy the complete content of pBtFrom into pBtTo. A transaction
6786** must be active for both files.
6787**
danielk1977f653d782008-03-20 11:04:21 +00006788** The size of file pTo may be reduced by this operation.
6789** If anything goes wrong, the transaction on pTo is rolled back.
6790**
6791** If successful, CommitPhaseOne() may be called on pTo before returning.
6792** The caller should finish committing the transaction on pTo by calling
6793** sqlite3BtreeCommit().
drh73509ee2003-04-06 20:44:45 +00006794*/
drhd677b3d2007-08-20 22:48:41 +00006795static int btreeCopyFile(Btree *pTo, Btree *pFrom){
drhf7c57532003-04-25 13:22:51 +00006796 int rc = SQLITE_OK;
danielk1977f653d782008-03-20 11:04:21 +00006797 Pgno i;
6798
6799 Pgno nFromPage; /* Number of pages in pFrom */
6800 Pgno nToPage; /* Number of pages in pTo */
6801 Pgno nNewPage; /* Number of pages in pTo after the copy */
6802
6803 Pgno iSkip; /* Pending byte page in pTo */
6804 int nToPageSize; /* Page size of pTo in bytes */
6805 int nFromPageSize; /* Page size of pFrom in bytes */
drhf7c57532003-04-25 13:22:51 +00006806
danielk1977aef0bf62005-12-30 16:28:01 +00006807 BtShared *pBtTo = pTo->pBt;
6808 BtShared *pBtFrom = pFrom->pBt;
drhe5fe6902007-12-07 18:55:28 +00006809 pBtTo->db = pTo->db;
6810 pBtFrom->db = pFrom->db;
danielk1977f653d782008-03-20 11:04:21 +00006811
6812 nToPageSize = pBtTo->pageSize;
6813 nFromPageSize = pBtFrom->pageSize;
danielk1977aef0bf62005-12-30 16:28:01 +00006814
6815 if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
danielk1977ee5741e2004-05-31 10:01:34 +00006816 return SQLITE_ERROR;
6817 }
danielk1977f653d782008-03-20 11:04:21 +00006818 if( pBtTo->pCursor ){
6819 return SQLITE_BUSY;
drhf7c57532003-04-25 13:22:51 +00006820 }
drh538f5702007-04-13 02:14:30 +00006821
danielk1977f653d782008-03-20 11:04:21 +00006822 nToPage = sqlite3PagerPagecount(pBtTo->pPager);
6823 nFromPage = sqlite3PagerPagecount(pBtFrom->pPager);
6824 iSkip = PENDING_BYTE_PAGE(pBtTo);
6825
6826 /* Variable nNewPage is the number of pages required to store the
6827 ** contents of pFrom using the current page-size of pTo.
drh538f5702007-04-13 02:14:30 +00006828 */
danielk1977f653d782008-03-20 11:04:21 +00006829 nNewPage = ((i64)nFromPage * (i64)nFromPageSize + (i64)nToPageSize - 1) /
6830 (i64)nToPageSize;
6831
6832 for(i=1; rc==SQLITE_OK && (i<=nToPage || i<=nNewPage); i++){
6833
6834 /* Journal the original page.
6835 **
6836 ** iSkip is the page number of the locking page (PENDING_BYTE_PAGE)
6837 ** in database *pTo (before the copy). This page is never written
6838 ** into the journal file. Unless i==iSkip or the page was not
6839 ** present in pTo before the copy operation, journal page i from pTo.
6840 */
6841 if( i!=iSkip && i<=nToPage ){
6842 DbPage *pDbPage;
6843 rc = sqlite3PagerGet(pBtTo->pPager, i, &pDbPage);
6844 if( rc ){
6845 break;
6846 }
6847 rc = sqlite3PagerWrite(pDbPage);
6848 if( rc ){
6849 break;
6850 }
6851 if( i>nFromPage ){
6852 /* Yeah. It seems wierd to call DontWrite() right after Write(). But
6853 ** that is because the names of those procedures do not exactly
6854 ** represent what they do. Write() really means "put this page in the
6855 ** rollback journal and mark it as dirty so that it will be written
6856 ** to the database file later." DontWrite() undoes the second part of
6857 ** that and prevents the page from being written to the database. The
6858 ** page is still on the rollback journal, though. And that is the
6859 ** whole point of this block: to put pages on the rollback journal.
6860 */
6861 sqlite3PagerDontWrite(pDbPage);
6862 }
6863 sqlite3PagerUnref(pDbPage);
6864 }
6865
6866 /* Overwrite the data in page i of the target database */
6867 if( rc==SQLITE_OK && i!=iSkip && i<=nNewPage ){
6868
6869 DbPage *pToPage = 0;
6870 sqlite3_int64 iOff;
6871
6872 rc = sqlite3PagerGet(pBtTo->pPager, i, &pToPage);
6873 if( rc==SQLITE_OK ){
6874 rc = sqlite3PagerWrite(pToPage);
6875 }
6876
6877 for(
6878 iOff=(i-1)*nToPageSize;
6879 rc==SQLITE_OK && iOff<i*nToPageSize;
6880 iOff += nFromPageSize
6881 ){
6882 DbPage *pFromPage = 0;
6883 Pgno iFrom = (iOff/nFromPageSize)+1;
6884
6885 if( iFrom==PENDING_BYTE_PAGE(pBtFrom) ){
6886 continue;
6887 }
6888
6889 rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
6890 if( rc==SQLITE_OK ){
6891 char *zTo = sqlite3PagerGetData(pToPage);
6892 char *zFrom = sqlite3PagerGetData(pFromPage);
6893 int nCopy;
6894
6895 if( nFromPageSize>=nToPageSize ){
6896 zFrom += ((i-1)*nToPageSize - ((iFrom-1)*nFromPageSize));
6897 nCopy = nToPageSize;
6898 }else{
6899 zTo += (((iFrom-1)*nFromPageSize) - (i-1)*nToPageSize);
6900 nCopy = nFromPageSize;
6901 }
6902
6903 memcpy(zTo, zFrom, nCopy);
6904 sqlite3PagerUnref(pFromPage);
6905 }
6906 }
6907
6908 if( pToPage ) sqlite3PagerUnref(pToPage);
6909 }
drh2e6d11b2003-04-25 15:37:57 +00006910 }
danielk1977f653d782008-03-20 11:04:21 +00006911
6912 /* If things have worked so far, the database file may need to be
6913 ** truncated. The complex part is that it may need to be truncated to
6914 ** a size that is not an integer multiple of nToPageSize - the current
6915 ** page size used by the pager associated with B-Tree pTo.
6916 **
6917 ** For example, say the page-size of pTo is 2048 bytes and the original
6918 ** number of pages is 5 (10 KB file). If pFrom has a page size of 1024
6919 ** bytes and 9 pages, then the file needs to be truncated to 9KB.
6920 */
6921 if( rc==SQLITE_OK ){
6922 if( nFromPageSize!=nToPageSize ){
6923 sqlite3_file *pFile = sqlite3PagerFile(pBtTo->pPager);
6924 i64 iSize = (i64)nFromPageSize * (i64)nFromPage;
6925 i64 iNow = (i64)((nToPage>nNewPage)?nToPage:nNewPage) * (i64)nToPageSize;
6926 i64 iPending = ((i64)PENDING_BYTE_PAGE(pBtTo)-1) *(i64)nToPageSize;
6927
6928 assert( iSize<=iNow );
6929
6930 /* Commit phase one syncs the journal file associated with pTo
6931 ** containing the original data. It does not sync the database file
6932 ** itself. After doing this it is safe to use OsTruncate() and other
6933 ** file APIs on the database file directly.
6934 */
6935 pBtTo->db = pTo->db;
6936 rc = sqlite3PagerCommitPhaseOne(pBtTo->pPager, 0, 0, 1);
6937 if( iSize<iNow && rc==SQLITE_OK ){
6938 rc = sqlite3OsTruncate(pFile, iSize);
6939 }
6940
6941 /* The loop that copied data from database pFrom to pTo did not
6942 ** populate the locking page of database pTo. If the page-size of
6943 ** pFrom is smaller than that of pTo, this means some data will
6944 ** not have been copied.
6945 **
6946 ** This block copies the missing data from database pFrom to pTo
6947 ** using file APIs. This is safe because at this point we know that
6948 ** all of the original data from pTo has been synced into the
6949 ** journal file. At this point it would be safe to do anything at
6950 ** all to the database file except truncate it to zero bytes.
6951 */
6952 if( rc==SQLITE_OK && nFromPageSize<nToPageSize && iSize>iPending){
6953 i64 iOff;
6954 for(
6955 iOff=iPending;
6956 rc==SQLITE_OK && iOff<(iPending+nToPageSize);
6957 iOff += nFromPageSize
6958 ){
6959 DbPage *pFromPage = 0;
6960 Pgno iFrom = (iOff/nFromPageSize)+1;
6961
6962 if( iFrom==PENDING_BYTE_PAGE(pBtFrom) || iFrom>nFromPage ){
6963 continue;
6964 }
6965
6966 rc = sqlite3PagerGet(pBtFrom->pPager, iFrom, &pFromPage);
6967 if( rc==SQLITE_OK ){
6968 char *zFrom = sqlite3PagerGetData(pFromPage);
6969 rc = sqlite3OsWrite(pFile, zFrom, nFromPageSize, iOff);
6970 sqlite3PagerUnref(pFromPage);
6971 }
6972 }
6973 }
6974
6975 /* Sync the database file */
6976 if( rc==SQLITE_OK ){
6977 rc = sqlite3PagerSync(pBtTo->pPager);
6978 }
6979 }else{
6980 rc = sqlite3PagerTruncate(pBtTo->pPager, nNewPage);
6981 }
6982 if( rc==SQLITE_OK ){
6983 pBtTo->pageSizeFixed = 0;
6984 }
drh2e6d11b2003-04-25 15:37:57 +00006985 }
drh538f5702007-04-13 02:14:30 +00006986
drhf7c57532003-04-25 13:22:51 +00006987 if( rc ){
danielk1977aef0bf62005-12-30 16:28:01 +00006988 sqlite3BtreeRollback(pTo);
drhf7c57532003-04-25 13:22:51 +00006989 }
danielk1977f653d782008-03-20 11:04:21 +00006990
drhf7c57532003-04-25 13:22:51 +00006991 return rc;
drh73509ee2003-04-06 20:44:45 +00006992}
drhd677b3d2007-08-20 22:48:41 +00006993int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
6994 int rc;
6995 sqlite3BtreeEnter(pTo);
6996 sqlite3BtreeEnter(pFrom);
6997 rc = btreeCopyFile(pTo, pFrom);
6998 sqlite3BtreeLeave(pFrom);
6999 sqlite3BtreeLeave(pTo);
7000 return rc;
7001}
7002
drhb7f91642004-10-31 02:22:47 +00007003#endif /* SQLITE_OMIT_VACUUM */
danielk19771d850a72004-05-31 08:26:49 +00007004
7005/*
7006** Return non-zero if a transaction is active.
7007*/
danielk1977aef0bf62005-12-30 16:28:01 +00007008int sqlite3BtreeIsInTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00007009 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00007010 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00007011}
7012
7013/*
7014** Return non-zero if a statement transaction is active.
7015*/
danielk1977aef0bf62005-12-30 16:28:01 +00007016int sqlite3BtreeIsInStmt(Btree *p){
drh1fee73e2007-08-29 04:00:57 +00007017 assert( sqlite3BtreeHoldsMutex(p) );
danielk1977aef0bf62005-12-30 16:28:01 +00007018 return (p->pBt && p->pBt->inStmt);
danielk19771d850a72004-05-31 08:26:49 +00007019}
danielk197713adf8a2004-06-03 16:08:41 +00007020
7021/*
danielk19772372c2b2006-06-27 16:34:56 +00007022** Return non-zero if a read (or write) transaction is active.
7023*/
7024int sqlite3BtreeIsInReadTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00007025 assert( sqlite3_mutex_held(p->db->mutex) );
danielk19772372c2b2006-06-27 16:34:56 +00007026 return (p && (p->inTrans!=TRANS_NONE));
7027}
7028
7029/*
danielk1977da184232006-01-05 11:34:32 +00007030** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +00007031** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +00007032** purposes (for example, to store a high-level schema associated with
7033** the shared-btree). The btree layer manages reference counting issues.
7034**
7035** The first time this is called on a shared-btree, nBytes bytes of memory
7036** are allocated, zeroed, and returned to the caller. For each subsequent
7037** call the nBytes parameter is ignored and a pointer to the same blob
7038** of memory returned.
7039**
7040** Just before the shared-btree is closed, the function passed as the
7041** xFree argument when the memory allocation was made is invoked on the
drh17435752007-08-16 04:30:38 +00007042** blob of allocated memory. This function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +00007043** on the memory, the btree layer does that.
7044*/
7045void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
7046 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +00007047 sqlite3BtreeEnter(p);
danielk1977da184232006-01-05 11:34:32 +00007048 if( !pBt->pSchema ){
drh17435752007-08-16 04:30:38 +00007049 pBt->pSchema = sqlite3MallocZero(nBytes);
danielk1977da184232006-01-05 11:34:32 +00007050 pBt->xFreeSchema = xFree;
7051 }
drh27641702007-08-22 02:56:42 +00007052 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00007053 return pBt->pSchema;
7054}
7055
danielk1977c87d34d2006-01-06 13:00:28 +00007056/*
7057** Return true if another user of the same shared btree as the argument
7058** handle holds an exclusive lock on the sqlite_master table.
7059*/
7060int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +00007061 int rc;
drhe5fe6902007-12-07 18:55:28 +00007062 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +00007063 sqlite3BtreeEnter(p);
7064 rc = (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
7065 sqlite3BtreeLeave(p);
7066 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +00007067}
7068
drha154dcd2006-03-22 22:10:07 +00007069
7070#ifndef SQLITE_OMIT_SHARED_CACHE
7071/*
7072** Obtain a lock on the table whose root page is iTab. The
7073** lock is a write lock if isWritelock is true or a read lock
7074** if it is false.
7075*/
danielk1977c00da102006-01-07 13:21:04 +00007076int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00007077 int rc = SQLITE_OK;
danielk1977c00da102006-01-07 13:21:04 +00007078 u8 lockType = (isWriteLock?WRITE_LOCK:READ_LOCK);
drhd677b3d2007-08-20 22:48:41 +00007079 sqlite3BtreeEnter(p);
danielk19772e94d4d2006-01-09 05:36:27 +00007080 rc = queryTableLock(p, iTab, lockType);
danielk1977c00da102006-01-07 13:21:04 +00007081 if( rc==SQLITE_OK ){
7082 rc = lockTable(p, iTab, lockType);
7083 }
drhd677b3d2007-08-20 22:48:41 +00007084 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +00007085 return rc;
7086}
drha154dcd2006-03-22 22:10:07 +00007087#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00007088
danielk1977b4e9af92007-05-01 17:49:49 +00007089#ifndef SQLITE_OMIT_INCRBLOB
7090/*
7091** Argument pCsr must be a cursor opened for writing on an
7092** INTKEY table currently pointing at a valid table entry.
7093** This function modifies the data stored as part of that entry.
7094** Only the data content may only be modified, it is not possible
7095** to change the length of the data stored.
7096*/
danielk1977dcbb5d32007-05-04 18:36:44 +00007097int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
drh1fee73e2007-08-29 04:00:57 +00007098 assert( cursorHoldsMutex(pCsr) );
drhe5fe6902007-12-07 18:55:28 +00007099 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00007100 assert(pCsr->isIncrblobHandle);
drhfb982642007-08-30 01:19:59 +00007101 if( pCsr->eState>=CURSOR_REQUIRESEEK ){
7102 if( pCsr->eState==CURSOR_FAULT ){
7103 return pCsr->skip;
7104 }else{
7105 return SQLITE_ABORT;
7106 }
danielk1977dcbb5d32007-05-04 18:36:44 +00007107 }
7108
danielk1977d04417962007-05-02 13:16:30 +00007109 /* Check some preconditions:
danielk1977dcbb5d32007-05-04 18:36:44 +00007110 ** (a) the cursor is open for writing,
7111 ** (b) there is no read-lock on the table being modified and
7112 ** (c) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00007113 */
danielk1977d04417962007-05-02 13:16:30 +00007114 if( !pCsr->wrFlag ){
danielk1977dcbb5d32007-05-04 18:36:44 +00007115 return SQLITE_READONLY;
danielk1977d04417962007-05-02 13:16:30 +00007116 }
drhd0679ed2007-08-28 22:24:34 +00007117 assert( !pCsr->pBt->readOnly
7118 && pCsr->pBt->inTransaction==TRANS_WRITE );
danielk1977d04417962007-05-02 13:16:30 +00007119 if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr) ){
7120 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
7121 }
7122 if( pCsr->eState==CURSOR_INVALID || !pCsr->pPage->intKey ){
7123 return SQLITE_ERROR;
danielk1977b4e9af92007-05-01 17:49:49 +00007124 }
7125
danielk19779f8d6402007-05-02 17:48:45 +00007126 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00007127}
danielk19772dec9702007-05-02 16:48:37 +00007128
7129/*
7130** Set a flag on this cursor to cache the locations of pages from the
danielk1977da107192007-05-04 08:32:13 +00007131** overflow list for the current row. This is used by cursors opened
7132** for incremental blob IO only.
7133**
7134** This function sets a flag only. The actual page location cache
7135** (stored in BtCursor.aOverflow[]) is allocated and used by function
7136** accessPayload() (the worker function for sqlite3BtreeData() and
7137** sqlite3BtreePutData()).
danielk19772dec9702007-05-02 16:48:37 +00007138*/
7139void sqlite3BtreeCacheOverflow(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00007140 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00007141 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00007142 assert(!pCur->isIncrblobHandle);
danielk19772dec9702007-05-02 16:48:37 +00007143 assert(!pCur->aOverflow);
danielk1977dcbb5d32007-05-04 18:36:44 +00007144 pCur->isIncrblobHandle = 1;
danielk19772dec9702007-05-02 16:48:37 +00007145}
danielk1977b4e9af92007-05-01 17:49:49 +00007146#endif