blob: 46553e524029a3f37d6568275957b42f4d9ff829 [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*************************************************************************
danielk1977a1644fd2007-08-29 12:31:25 +000012** $Id: btree.c,v 1.417 2007/08/29 12:31:26 danielk1977 Exp $
drh8b2f49b2001-06-08 00:21:52 +000013**
14** This file implements a external (disk-based) database using BTrees.
drha3152892007-05-05 11:48:52 +000015** See the header comment on "btreeInt.h" for additional information.
16** Including a description of file format and an overview of operation.
drha059ad02001-04-17 20:09:11 +000017*/
drha3152892007-05-05 11:48:52 +000018#include "btreeInt.h"
paulb95a8862003-04-01 21:16:41 +000019
drh8c42ca92001-06-22 19:15:00 +000020/*
drha3152892007-05-05 11:48:52 +000021** The header string that appears at the beginning of every
22** SQLite database.
drh556b2a22005-06-14 16:04:05 +000023*/
drh556b2a22005-06-14 16:04:05 +000024static const char zMagicHeader[] = SQLITE_FILE_HEADER;
drh08ed44e2001-04-29 23:32:55 +000025
drh8c42ca92001-06-22 19:15:00 +000026/*
drha3152892007-05-05 11:48:52 +000027** Set this global variable to 1 to enable tracing using the TRACE
28** macro.
drh615ae552005-01-16 23:21:00 +000029*/
30#if SQLITE_TEST
drh0f7eb612006-08-08 13:51:43 +000031int sqlite3_btree_trace=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
106 /* This (along with lockTable()) is where the ReadUncommitted flag is
107 ** dealt with. If the caller is querying for a read-lock and the flag is
108 ** set, it is unconditionally granted - even if there are write-locks
109 ** on the table. If a write-lock is requested, the ReadUncommitted flag
110 ** is not considered.
111 **
112 ** In function lockTable(), if a read-lock is demanded and the
113 ** ReadUncommitted flag is set, no entry is added to the locks list
114 ** (BtShared.pLock).
115 **
116 ** To summarize: If the ReadUncommitted flag is set, then read cursors do
117 ** not create or respect table locks. The locking procedure for a
118 ** write-cursor does not change.
119 */
120 if(
121 !p->pSqlite ||
122 0==(p->pSqlite->flags&SQLITE_ReadUncommitted) ||
123 eLock==WRITE_LOCK ||
drh47ded162006-01-06 01:42:58 +0000124 iTab==MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000125 ){
126 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
127 if( pIter->pBtree!=p && pIter->iTable==iTab &&
128 (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
danielk1977c87d34d2006-01-06 13:00:28 +0000129 return SQLITE_LOCKED;
danielk1977da184232006-01-05 11:34:32 +0000130 }
danielk1977aef0bf62005-12-30 16:28:01 +0000131 }
132 }
133 return SQLITE_OK;
134}
drhe53831d2007-08-17 01:14:38 +0000135#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000136
drhe53831d2007-08-17 01:14:38 +0000137#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000138/*
139** Add a lock on the table with root-page iTable to the shared-btree used
140** by Btree handle p. Parameter eLock must be either READ_LOCK or
141** WRITE_LOCK.
142**
143** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
144** SQLITE_NOMEM may also be returned.
145*/
146static int lockTable(Btree *p, Pgno iTable, u8 eLock){
147 BtShared *pBt = p->pBt;
148 BtLock *pLock = 0;
149 BtLock *pIter;
150
drh1fee73e2007-08-29 04:00:57 +0000151 assert( sqlite3BtreeHoldsMutex(p) );
drhd677b3d2007-08-20 22:48:41 +0000152
danielk1977da184232006-01-05 11:34:32 +0000153 /* This is a no-op if the shared-cache is not enabled */
drhe53831d2007-08-17 01:14:38 +0000154 if( !p->sharable ){
danielk1977da184232006-01-05 11:34:32 +0000155 return SQLITE_OK;
156 }
157
danielk1977aef0bf62005-12-30 16:28:01 +0000158 assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
159
danielk1977da184232006-01-05 11:34:32 +0000160 /* If the read-uncommitted flag is set and a read-lock is requested,
161 ** return early without adding an entry to the BtShared.pLock list. See
162 ** comment in function queryTableLock() for more info on handling
163 ** the ReadUncommitted flag.
164 */
165 if(
166 (p->pSqlite) &&
167 (p->pSqlite->flags&SQLITE_ReadUncommitted) &&
168 (eLock==READ_LOCK) &&
drh47ded162006-01-06 01:42:58 +0000169 iTable!=MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000170 ){
171 return SQLITE_OK;
172 }
173
danielk1977aef0bf62005-12-30 16:28:01 +0000174 /* First search the list for an existing lock on this table. */
175 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
176 if( pIter->iTable==iTable && pIter->pBtree==p ){
177 pLock = pIter;
178 break;
179 }
180 }
181
182 /* If the above search did not find a BtLock struct associating Btree p
183 ** with table iTable, allocate one and link it into the list.
184 */
185 if( !pLock ){
drh17435752007-08-16 04:30:38 +0000186 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
danielk1977aef0bf62005-12-30 16:28:01 +0000187 if( !pLock ){
188 return SQLITE_NOMEM;
189 }
190 pLock->iTable = iTable;
191 pLock->pBtree = p;
192 pLock->pNext = pBt->pLock;
193 pBt->pLock = pLock;
194 }
195
196 /* Set the BtLock.eLock variable to the maximum of the current lock
197 ** and the requested lock. This means if a write-lock was already held
198 ** and a read-lock requested, we don't incorrectly downgrade the lock.
199 */
200 assert( WRITE_LOCK>READ_LOCK );
danielk19775118b912005-12-30 16:31:53 +0000201 if( eLock>pLock->eLock ){
202 pLock->eLock = eLock;
203 }
danielk1977aef0bf62005-12-30 16:28:01 +0000204
205 return SQLITE_OK;
206}
drhe53831d2007-08-17 01:14:38 +0000207#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000208
drhe53831d2007-08-17 01:14:38 +0000209#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000210/*
211** Release all the table locks (locks obtained via calls to the lockTable()
212** procedure) held by Btree handle p.
213*/
214static void unlockAllTables(Btree *p){
215 BtLock **ppIter = &p->pBt->pLock;
danielk1977da184232006-01-05 11:34:32 +0000216
drh1fee73e2007-08-29 04:00:57 +0000217 assert( sqlite3BtreeHoldsMutex(p) );
drhe53831d2007-08-17 01:14:38 +0000218 assert( p->sharable || 0==*ppIter );
danielk1977da184232006-01-05 11:34:32 +0000219
danielk1977aef0bf62005-12-30 16:28:01 +0000220 while( *ppIter ){
221 BtLock *pLock = *ppIter;
222 if( pLock->pBtree==p ){
223 *ppIter = pLock->pNext;
drh17435752007-08-16 04:30:38 +0000224 sqlite3_free(pLock);
danielk1977aef0bf62005-12-30 16:28:01 +0000225 }else{
226 ppIter = &pLock->pNext;
227 }
228 }
229}
230#endif /* SQLITE_OMIT_SHARED_CACHE */
231
drh980b1a72006-08-16 16:42:48 +0000232static void releasePage(MemPage *pPage); /* Forward reference */
233
drh1fee73e2007-08-29 04:00:57 +0000234/*
235** Verify that the cursor holds a mutex on the BtShared
236*/
237#ifndef NDEBUG
238static int cursorHoldsMutex(BtCursor *p){
239 return sqlite3BtreeHoldsMutex(p->pBtree);
240}
241#endif
242
243
danielk197792d4d7a2007-05-04 12:05:56 +0000244#ifndef SQLITE_OMIT_INCRBLOB
245/*
246** Invalidate the overflow page-list cache for cursor pCur, if any.
247*/
248static void invalidateOverflowCache(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000249 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000250 sqlite3_free(pCur->aOverflow);
danielk197792d4d7a2007-05-04 12:05:56 +0000251 pCur->aOverflow = 0;
252}
253
254/*
255** Invalidate the overflow page-list cache for all cursors opened
256** on the shared btree structure pBt.
257*/
258static void invalidateAllOverflowCache(BtShared *pBt){
259 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000260 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +0000261 for(p=pBt->pCursor; p; p=p->pNext){
262 invalidateOverflowCache(p);
263 }
264}
265#else
266 #define invalidateOverflowCache(x)
267 #define invalidateAllOverflowCache(x)
268#endif
269
drh980b1a72006-08-16 16:42:48 +0000270/*
271** Save the current cursor position in the variables BtCursor.nKey
272** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
273*/
274static int saveCursorPosition(BtCursor *pCur){
275 int rc;
276
277 assert( CURSOR_VALID==pCur->eState );
278 assert( 0==pCur->pKey );
drh1fee73e2007-08-29 04:00:57 +0000279 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000280
281 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
282
283 /* If this is an intKey table, then the above call to BtreeKeySize()
284 ** stores the integer key in pCur->nKey. In this case this value is
285 ** all that is required. Otherwise, if pCur is not open on an intKey
286 ** table, then malloc space for and store the pCur->nKey bytes of key
287 ** data.
288 */
289 if( rc==SQLITE_OK && 0==pCur->pPage->intKey){
drh17435752007-08-16 04:30:38 +0000290 void *pKey = sqlite3_malloc(pCur->nKey);
drh980b1a72006-08-16 16:42:48 +0000291 if( pKey ){
292 rc = sqlite3BtreeKey(pCur, 0, pCur->nKey, pKey);
293 if( rc==SQLITE_OK ){
294 pCur->pKey = pKey;
295 }else{
drh17435752007-08-16 04:30:38 +0000296 sqlite3_free(pKey);
drh980b1a72006-08-16 16:42:48 +0000297 }
298 }else{
299 rc = SQLITE_NOMEM;
300 }
301 }
302 assert( !pCur->pPage->intKey || !pCur->pKey );
303
304 if( rc==SQLITE_OK ){
305 releasePage(pCur->pPage);
306 pCur->pPage = 0;
307 pCur->eState = CURSOR_REQUIRESEEK;
308 }
309
danielk197792d4d7a2007-05-04 12:05:56 +0000310 invalidateOverflowCache(pCur);
drh980b1a72006-08-16 16:42:48 +0000311 return rc;
312}
313
314/*
315** Save the positions of all cursors except pExcept open on the table
316** with root-page iRoot. Usually, this is called just before cursor
317** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
318*/
319static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
320 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000321 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +0000322 assert( pExcept==0 || pExcept->pBt==pBt );
drh980b1a72006-08-16 16:42:48 +0000323 for(p=pBt->pCursor; p; p=p->pNext){
324 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
325 p->eState==CURSOR_VALID ){
326 int rc = saveCursorPosition(p);
327 if( SQLITE_OK!=rc ){
328 return rc;
329 }
330 }
331 }
332 return SQLITE_OK;
333}
334
335/*
drhbf700f32007-03-31 02:36:44 +0000336** Clear the current cursor position.
337*/
338static void clearCursorPosition(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000339 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000340 sqlite3_free(pCur->pKey);
drhbf700f32007-03-31 02:36:44 +0000341 pCur->pKey = 0;
342 pCur->eState = CURSOR_INVALID;
343}
344
345/*
drh980b1a72006-08-16 16:42:48 +0000346** Restore the cursor to the position it was in (or as close to as possible)
347** when saveCursorPosition() was called. Note that this call deletes the
348** saved position info stored by saveCursorPosition(), so there can be
349** at most one effective restoreOrClearCursorPosition() call after each
350** saveCursorPosition().
351**
352** If the second argument argument - doSeek - is false, then instead of
353** returning the cursor to it's saved position, any saved position is deleted
354** and the cursor state set to CURSOR_INVALID.
355*/
drh16a9b832007-05-05 18:39:25 +0000356int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +0000357 int rc;
drh1fee73e2007-08-29 04:00:57 +0000358 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000359 assert( pCur->eState==CURSOR_REQUIRESEEK );
danielk197732a0d8b2007-05-04 19:03:02 +0000360#ifndef SQLITE_OMIT_INCRBLOB
danielk1977dcbb5d32007-05-04 18:36:44 +0000361 if( pCur->isIncrblobHandle ){
362 return SQLITE_ABORT;
363 }
danielk197732a0d8b2007-05-04 19:03:02 +0000364#endif
drh980b1a72006-08-16 16:42:48 +0000365 pCur->eState = CURSOR_INVALID;
drhbf700f32007-03-31 02:36:44 +0000366 rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skip);
drh980b1a72006-08-16 16:42:48 +0000367 if( rc==SQLITE_OK ){
drh17435752007-08-16 04:30:38 +0000368 sqlite3_free(pCur->pKey);
drh980b1a72006-08-16 16:42:48 +0000369 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +0000370 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drh980b1a72006-08-16 16:42:48 +0000371 }
372 return rc;
373}
374
drhbf700f32007-03-31 02:36:44 +0000375#define restoreOrClearCursorPosition(p) \
drh16a9b832007-05-05 18:39:25 +0000376 (p->eState==CURSOR_REQUIRESEEK ? \
377 sqlite3BtreeRestoreOrClearCursorPosition(p) : \
378 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +0000379
danielk1977599fcba2004-11-08 07:13:13 +0000380#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000381/*
drha3152892007-05-05 11:48:52 +0000382** Given a page number of a regular database page, return the page
383** number for the pointer-map page that contains the entry for the
384** input page number.
danielk1977afcdd022004-10-31 16:25:42 +0000385*/
danielk1977266664d2006-02-10 08:24:21 +0000386static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
drhd677b3d2007-08-20 22:48:41 +0000387 int nPagesPerMapPage, iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +0000388 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000389 nPagesPerMapPage = (pBt->usableSize/5)+1;
390 iPtrMap = (pgno-2)/nPagesPerMapPage;
391 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +0000392 if( ret==PENDING_BYTE_PAGE(pBt) ){
393 ret++;
394 }
395 return ret;
396}
danielk1977a19df672004-11-03 11:37:07 +0000397
danielk1977afcdd022004-10-31 16:25:42 +0000398/*
danielk1977afcdd022004-10-31 16:25:42 +0000399** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000400**
401** This routine updates the pointer map entry for page number 'key'
402** so that it maps to type 'eType' and parent page number 'pgno'.
403** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000404*/
danielk1977aef0bf62005-12-30 16:28:01 +0000405static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
danielk19773b8a05f2007-03-19 17:44:26 +0000406 DbPage *pDbPage; /* The pointer map page */
407 u8 *pPtrmap; /* The pointer map data */
408 Pgno iPtrmap; /* The pointer map page number */
409 int offset; /* Offset in pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000410 int rc;
411
drh1fee73e2007-08-29 04:00:57 +0000412 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977266664d2006-02-10 08:24:21 +0000413 /* The master-journal page number must never be used as a pointer map page */
414 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
415
danielk1977ac11ee62005-01-15 12:45:51 +0000416 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000417 if( key==0 ){
drh49285702005-09-17 15:20:26 +0000418 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000419 }
danielk1977266664d2006-02-10 08:24:21 +0000420 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000421 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977687566d2004-11-02 12:56:41 +0000422 if( rc!=SQLITE_OK ){
danielk1977afcdd022004-10-31 16:25:42 +0000423 return rc;
424 }
danielk1977266664d2006-02-10 08:24:21 +0000425 offset = PTRMAP_PTROFFSET(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000426 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000427
drh615ae552005-01-16 23:21:00 +0000428 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
429 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
danielk19773b8a05f2007-03-19 17:44:26 +0000430 rc = sqlite3PagerWrite(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000431 if( rc==SQLITE_OK ){
432 pPtrmap[offset] = eType;
433 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000434 }
danielk1977afcdd022004-10-31 16:25:42 +0000435 }
436
danielk19773b8a05f2007-03-19 17:44:26 +0000437 sqlite3PagerUnref(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000438 return rc;
danielk1977afcdd022004-10-31 16:25:42 +0000439}
440
441/*
442** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000443**
444** This routine retrieves the pointer map entry for page 'key', writing
445** the type and parent page number to *pEType and *pPgno respectively.
446** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000447*/
danielk1977aef0bf62005-12-30 16:28:01 +0000448static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +0000449 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000450 int iPtrmap; /* Pointer map page index */
451 u8 *pPtrmap; /* Pointer map page data */
452 int offset; /* Offset of entry in pointer map */
453 int rc;
454
drh1fee73e2007-08-29 04:00:57 +0000455 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000456
danielk1977266664d2006-02-10 08:24:21 +0000457 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000458 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000459 if( rc!=0 ){
460 return rc;
461 }
danielk19773b8a05f2007-03-19 17:44:26 +0000462 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000463
danielk1977266664d2006-02-10 08:24:21 +0000464 offset = PTRMAP_PTROFFSET(pBt, key);
drh43617e92006-03-06 20:55:46 +0000465 assert( pEType!=0 );
466 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +0000467 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000468
danielk19773b8a05f2007-03-19 17:44:26 +0000469 sqlite3PagerUnref(pDbPage);
drh49285702005-09-17 15:20:26 +0000470 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000471 return SQLITE_OK;
472}
473
474#endif /* SQLITE_OMIT_AUTOVACUUM */
475
drh0d316a42002-08-11 20:10:47 +0000476/*
drh271efa52004-05-30 19:19:05 +0000477** Given a btree page and a cell index (0 means the first cell on
478** the page, 1 means the second cell, and so forth) return a pointer
479** to the cell content.
480**
481** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000482*/
danielk19771cc5ed82007-05-16 17:28:43 +0000483#define findCell(pPage, iCell) \
484 ((pPage)->aData + get2byte(&(pPage)->aData[(pPage)->cellOffset+2*(iCell)]))
drhe6e4d6b2007-08-05 23:52:05 +0000485#ifdef SQLITE_TEST
drh16a9b832007-05-05 18:39:25 +0000486u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell){
drh43605152004-05-29 21:46:49 +0000487 assert( iCell>=0 );
drh029f3f82007-06-20 15:14:10 +0000488 assert( iCell<get2byte(&pPage->aData[pPage->hdrOffset+3]) );
danielk19771cc5ed82007-05-16 17:28:43 +0000489 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000490}
drhe6e4d6b2007-08-05 23:52:05 +0000491#endif
drh43605152004-05-29 21:46:49 +0000492
493/*
drh16a9b832007-05-05 18:39:25 +0000494** This a more complex version of sqlite3BtreeFindCell() that works for
drh43605152004-05-29 21:46:49 +0000495** pages that do contain overflow cells. See insert
496*/
497static u8 *findOverflowCell(MemPage *pPage, int iCell){
498 int i;
drh1fee73e2007-08-29 04:00:57 +0000499 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +0000500 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000501 int k;
502 struct _OvflCell *pOvfl;
503 pOvfl = &pPage->aOvfl[i];
504 k = pOvfl->idx;
505 if( k<=iCell ){
506 if( k==iCell ){
507 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000508 }
509 iCell--;
510 }
511 }
danielk19771cc5ed82007-05-16 17:28:43 +0000512 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000513}
514
515/*
516** Parse a cell content block and fill in the CellInfo structure. There
drh16a9b832007-05-05 18:39:25 +0000517** are two versions of this function. sqlite3BtreeParseCell() takes a
518** cell index as the second argument and sqlite3BtreeParseCellPtr()
519** takes a pointer to the body of the cell as its second argument.
danielk19771cc5ed82007-05-16 17:28:43 +0000520**
521** Within this file, the parseCell() macro can be called instead of
522** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
drh43605152004-05-29 21:46:49 +0000523*/
drh16a9b832007-05-05 18:39:25 +0000524void sqlite3BtreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000525 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000526 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000527 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000528){
drh271efa52004-05-30 19:19:05 +0000529 int n; /* Number bytes in cell content header */
530 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000531
drh1fee73e2007-08-29 04:00:57 +0000532 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000533
drh43605152004-05-29 21:46:49 +0000534 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000535 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000536 n = pPage->childPtrSize;
537 assert( n==4-4*pPage->leaf );
drh8b18dd42004-05-12 19:18:15 +0000538 if( pPage->hasData ){
drh271efa52004-05-30 19:19:05 +0000539 n += getVarint32(&pCell[n], &nPayload);
drh8b18dd42004-05-12 19:18:15 +0000540 }else{
drh271efa52004-05-30 19:19:05 +0000541 nPayload = 0;
drh3aac2dd2004-04-26 14:10:20 +0000542 }
drh271efa52004-05-30 19:19:05 +0000543 pInfo->nData = nPayload;
drh504b6982006-01-22 21:52:56 +0000544 if( pPage->intKey ){
545 n += getVarint(&pCell[n], (u64 *)&pInfo->nKey);
546 }else{
547 u32 x;
548 n += getVarint32(&pCell[n], &x);
549 pInfo->nKey = x;
550 nPayload += x;
drh6f11bef2004-05-13 01:12:56 +0000551 }
drh72365832007-03-06 15:53:44 +0000552 pInfo->nPayload = nPayload;
drh504b6982006-01-22 21:52:56 +0000553 pInfo->nHeader = n;
drh271efa52004-05-30 19:19:05 +0000554 if( nPayload<=pPage->maxLocal ){
555 /* This is the (easy) common case where the entire payload fits
556 ** on the local page. No overflow is required.
557 */
558 int nSize; /* Total size of cell content in bytes */
drh6f11bef2004-05-13 01:12:56 +0000559 pInfo->nLocal = nPayload;
560 pInfo->iOverflow = 0;
drh271efa52004-05-30 19:19:05 +0000561 nSize = nPayload + n;
562 if( nSize<4 ){
563 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000564 }
drh271efa52004-05-30 19:19:05 +0000565 pInfo->nSize = nSize;
drh6f11bef2004-05-13 01:12:56 +0000566 }else{
drh271efa52004-05-30 19:19:05 +0000567 /* If the payload will not fit completely on the local page, we have
568 ** to decide how much to store locally and how much to spill onto
569 ** overflow pages. The strategy is to minimize the amount of unused
570 ** space on overflow pages while keeping the amount of local storage
571 ** in between minLocal and maxLocal.
572 **
573 ** Warning: changing the way overflow payload is distributed in any
574 ** way will result in an incompatible file format.
575 */
576 int minLocal; /* Minimum amount of payload held locally */
577 int maxLocal; /* Maximum amount of payload held locally */
578 int surplus; /* Overflow payload available for local storage */
579
580 minLocal = pPage->minLocal;
581 maxLocal = pPage->maxLocal;
582 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000583 if( surplus <= maxLocal ){
584 pInfo->nLocal = surplus;
585 }else{
586 pInfo->nLocal = minLocal;
587 }
588 pInfo->iOverflow = pInfo->nLocal + n;
589 pInfo->nSize = pInfo->iOverflow + 4;
590 }
drh3aac2dd2004-04-26 14:10:20 +0000591}
danielk19771cc5ed82007-05-16 17:28:43 +0000592#define parseCell(pPage, iCell, pInfo) \
593 sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
drh16a9b832007-05-05 18:39:25 +0000594void sqlite3BtreeParseCell(
drh43605152004-05-29 21:46:49 +0000595 MemPage *pPage, /* Page containing the cell */
596 int iCell, /* The cell index. First cell is 0 */
597 CellInfo *pInfo /* Fill in this structure */
598){
danielk19771cc5ed82007-05-16 17:28:43 +0000599 parseCell(pPage, iCell, pInfo);
drh43605152004-05-29 21:46:49 +0000600}
drh3aac2dd2004-04-26 14:10:20 +0000601
602/*
drh43605152004-05-29 21:46:49 +0000603** Compute the total number of bytes that a Cell needs in the cell
604** data area of the btree-page. The return number includes the cell
605** data header and the local payload, but not any overflow page or
606** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000607*/
danielk1977bc6ada42004-06-30 08:20:16 +0000608#ifndef NDEBUG
drh43605152004-05-29 21:46:49 +0000609static int cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000610 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000611 sqlite3BtreeParseCell(pPage, iCell, &info);
drh43605152004-05-29 21:46:49 +0000612 return info.nSize;
613}
danielk1977bc6ada42004-06-30 08:20:16 +0000614#endif
drh43605152004-05-29 21:46:49 +0000615static int cellSizePtr(MemPage *pPage, u8 *pCell){
616 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000617 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000618 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000619}
620
danielk197779a40da2005-01-16 08:00:01 +0000621#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +0000622/*
danielk197726836652005-01-17 01:33:13 +0000623** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +0000624** to an overflow page, insert an entry into the pointer-map
625** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +0000626*/
danielk197726836652005-01-17 01:33:13 +0000627static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
danielk197779a40da2005-01-16 08:00:01 +0000628 if( pCell ){
629 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000630 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh72365832007-03-06 15:53:44 +0000631 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk197779a40da2005-01-16 08:00:01 +0000632 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
633 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
634 return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
635 }
danielk1977ac11ee62005-01-15 12:45:51 +0000636 }
danielk197779a40da2005-01-16 08:00:01 +0000637 return SQLITE_OK;
danielk1977ac11ee62005-01-15 12:45:51 +0000638}
danielk197726836652005-01-17 01:33:13 +0000639/*
640** If the cell with index iCell on page pPage contains a pointer
641** to an overflow page, insert an entry into the pointer-map
642** for the overflow page.
643*/
644static int ptrmapPutOvfl(MemPage *pPage, int iCell){
645 u8 *pCell;
drh1fee73e2007-08-29 04:00:57 +0000646 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197726836652005-01-17 01:33:13 +0000647 pCell = findOverflowCell(pPage, iCell);
648 return ptrmapPutOvflPtr(pPage, pCell);
649}
danielk197779a40da2005-01-16 08:00:01 +0000650#endif
651
danielk1977ac11ee62005-01-15 12:45:51 +0000652
drhda200cc2004-05-09 11:51:38 +0000653/*
drh72f82862001-05-24 21:06:34 +0000654** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +0000655** end of the page and all free space is collected into one
656** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +0000657** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +0000658*/
drh2e38c322004-09-03 18:38:44 +0000659static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000660 int i; /* Loop counter */
661 int pc; /* Address of a i-th cell */
662 int addr; /* Offset of first byte after cell pointer array */
663 int hdr; /* Offset to the page header */
664 int size; /* Size of a cell */
665 int usableSize; /* Number of usable bytes on a page */
666 int cellOffset; /* Offset to the cell pointer array */
667 int brk; /* Offset to the cell content area */
668 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +0000669 unsigned char *data; /* The page data */
670 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +0000671
danielk19773b8a05f2007-03-19 17:44:26 +0000672 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000673 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +0000674 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000675 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +0000676 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh17435752007-08-16 04:30:38 +0000677 temp = sqlite3_malloc( pPage->pBt->pageSize );
drh2e38c322004-09-03 18:38:44 +0000678 if( temp==0 ) return SQLITE_NOMEM;
drh43605152004-05-29 21:46:49 +0000679 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +0000680 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000681 cellOffset = pPage->cellOffset;
682 nCell = pPage->nCell;
683 assert( nCell==get2byte(&data[hdr+3]) );
684 usableSize = pPage->pBt->usableSize;
685 brk = get2byte(&data[hdr+5]);
686 memcpy(&temp[brk], &data[brk], usableSize - brk);
687 brk = usableSize;
688 for(i=0; i<nCell; i++){
689 u8 *pAddr; /* The i-th cell pointer */
690 pAddr = &data[cellOffset + i*2];
691 pc = get2byte(pAddr);
692 assert( pc<pPage->pBt->usableSize );
693 size = cellSizePtr(pPage, &temp[pc]);
694 brk -= size;
695 memcpy(&data[brk], &temp[pc], size);
696 put2byte(pAddr, brk);
drh2af926b2001-05-15 00:39:25 +0000697 }
drh43605152004-05-29 21:46:49 +0000698 assert( brk>=cellOffset+2*nCell );
699 put2byte(&data[hdr+5], brk);
700 data[hdr+1] = 0;
701 data[hdr+2] = 0;
702 data[hdr+7] = 0;
703 addr = cellOffset+2*nCell;
704 memset(&data[addr], 0, brk-addr);
drh17435752007-08-16 04:30:38 +0000705 sqlite3_free(temp);
drh2e38c322004-09-03 18:38:44 +0000706 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +0000707}
708
drha059ad02001-04-17 20:09:11 +0000709/*
drh43605152004-05-29 21:46:49 +0000710** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +0000711**
drh9e572e62004-04-23 23:43:10 +0000712** Return the index into pPage->aData[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000713** the new allocation. Or return 0 if there is not enough free
714** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000715**
drh72f82862001-05-24 21:06:34 +0000716** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000717** nBytes of contiguous free space, then this routine automatically
718** calls defragementPage() to consolidate all free space before
719** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000720*/
drh9e572e62004-04-23 23:43:10 +0000721static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +0000722 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +0000723 int size;
drh24cd67e2004-05-10 16:18:47 +0000724 int nFrag;
drh43605152004-05-29 21:46:49 +0000725 int top;
726 int nCell;
727 int cellOffset;
drh9e572e62004-04-23 23:43:10 +0000728 unsigned char *data;
drh43605152004-05-29 21:46:49 +0000729
drh9e572e62004-04-23 23:43:10 +0000730 data = pPage->aData;
danielk19773b8a05f2007-03-19 17:44:26 +0000731 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000732 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +0000733 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh9e572e62004-04-23 23:43:10 +0000734 if( nByte<4 ) nByte = 4;
drh43605152004-05-29 21:46:49 +0000735 if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
736 pPage->nFree -= nByte;
drh9e572e62004-04-23 23:43:10 +0000737 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000738
739 nFrag = data[hdr+7];
740 if( nFrag<60 ){
741 /* Search the freelist looking for a slot big enough to satisfy the
742 ** space request. */
743 addr = hdr+1;
744 while( (pc = get2byte(&data[addr]))>0 ){
745 size = get2byte(&data[pc+2]);
746 if( size>=nByte ){
747 if( size<nByte+4 ){
748 memcpy(&data[addr], &data[pc], 2);
749 data[hdr+7] = nFrag + size - nByte;
750 return pc;
751 }else{
752 put2byte(&data[pc+2], size-nByte);
753 return pc + size - nByte;
754 }
755 }
756 addr = pc;
drh9e572e62004-04-23 23:43:10 +0000757 }
758 }
drh43605152004-05-29 21:46:49 +0000759
760 /* Allocate memory from the gap in between the cell pointer array
761 ** and the cell content area.
762 */
763 top = get2byte(&data[hdr+5]);
764 nCell = get2byte(&data[hdr+3]);
765 cellOffset = pPage->cellOffset;
766 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
drh2e38c322004-09-03 18:38:44 +0000767 if( defragmentPage(pPage) ) return 0;
drh43605152004-05-29 21:46:49 +0000768 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +0000769 }
drh43605152004-05-29 21:46:49 +0000770 top -= nByte;
771 assert( cellOffset + 2*nCell <= top );
772 put2byte(&data[hdr+5], top);
773 return top;
drh7e3b0a02001-04-28 16:52:40 +0000774}
775
776/*
drh9e572e62004-04-23 23:43:10 +0000777** Return a section of the pPage->aData to the freelist.
778** The first byte of the new free block is pPage->aDisk[start]
779** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +0000780**
781** Most of the effort here is involved in coalesing adjacent
782** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000783*/
drh9e572e62004-04-23 23:43:10 +0000784static void freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +0000785 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +0000786 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +0000787
drh9e572e62004-04-23 23:43:10 +0000788 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +0000789 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000790 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +0000791 assert( (start + size)<=pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +0000792 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh9e572e62004-04-23 23:43:10 +0000793 if( size<4 ) size = 4;
794
drhfcce93f2006-02-22 03:08:32 +0000795#ifdef SQLITE_SECURE_DELETE
796 /* Overwrite deleted information with zeros when the SECURE_DELETE
797 ** option is enabled at compile-time */
798 memset(&data[start], 0, size);
799#endif
800
drh9e572e62004-04-23 23:43:10 +0000801 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +0000802 hdr = pPage->hdrOffset;
803 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +0000804 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +0000805 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000806 assert( pbegin>addr );
807 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +0000808 }
drhb6f41482004-05-14 01:58:11 +0000809 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000810 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +0000811 put2byte(&data[addr], start);
812 put2byte(&data[start], pbegin);
813 put2byte(&data[start+2], size);
drh2af926b2001-05-15 00:39:25 +0000814 pPage->nFree += size;
drh9e572e62004-04-23 23:43:10 +0000815
816 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +0000817 addr = pPage->hdrOffset + 1;
818 while( (pbegin = get2byte(&data[addr]))>0 ){
drh9e572e62004-04-23 23:43:10 +0000819 int pnext, psize;
drh3aac2dd2004-04-26 14:10:20 +0000820 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +0000821 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +0000822 pnext = get2byte(&data[pbegin]);
823 psize = get2byte(&data[pbegin+2]);
824 if( pbegin + psize + 3 >= pnext && pnext>0 ){
825 int frag = pnext - (pbegin+psize);
drh43605152004-05-29 21:46:49 +0000826 assert( frag<=data[pPage->hdrOffset+7] );
827 data[pPage->hdrOffset+7] -= frag;
drh9e572e62004-04-23 23:43:10 +0000828 put2byte(&data[pbegin], get2byte(&data[pnext]));
829 put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
830 }else{
drh3aac2dd2004-04-26 14:10:20 +0000831 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +0000832 }
833 }
drh7e3b0a02001-04-28 16:52:40 +0000834
drh43605152004-05-29 21:46:49 +0000835 /* If the cell content area begins with a freeblock, remove it. */
836 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
837 int top;
838 pbegin = get2byte(&data[hdr+1]);
839 memcpy(&data[hdr+1], &data[pbegin], 2);
840 top = get2byte(&data[hdr+5]);
841 put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
drh4b70f112004-05-02 21:12:19 +0000842 }
drh4b70f112004-05-02 21:12:19 +0000843}
844
845/*
drh271efa52004-05-30 19:19:05 +0000846** Decode the flags byte (the first byte of the header) for a page
847** and initialize fields of the MemPage structure accordingly.
848*/
849static void decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +0000850 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +0000851
852 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +0000853 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh271efa52004-05-30 19:19:05 +0000854 pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
855 pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
856 pPage->leaf = (flagByte & PTF_LEAF)!=0;
857 pPage->childPtrSize = 4*(pPage->leaf==0);
858 pBt = pPage->pBt;
859 if( flagByte & PTF_LEAFDATA ){
860 pPage->leafData = 1;
861 pPage->maxLocal = pBt->maxLeaf;
862 pPage->minLocal = pBt->minLeaf;
863 }else{
864 pPage->leafData = 0;
865 pPage->maxLocal = pBt->maxLocal;
866 pPage->minLocal = pBt->minLocal;
867 }
868 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
869}
870
871/*
drh7e3b0a02001-04-28 16:52:40 +0000872** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000873**
drhbd03cae2001-06-02 02:40:57 +0000874** The pParent parameter must be a pointer to the MemPage which
drh9e572e62004-04-23 23:43:10 +0000875** is the parent of the page being initialized. The root of a
876** BTree has no parent and so for that page, pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000877**
drh72f82862001-05-24 21:06:34 +0000878** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +0000879** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +0000880** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
881** guarantee that the page is well-formed. It only shows that
882** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000883*/
drh16a9b832007-05-05 18:39:25 +0000884int sqlite3BtreeInitPage(
drh3aac2dd2004-04-26 14:10:20 +0000885 MemPage *pPage, /* The page to be initialized */
drh9e572e62004-04-23 23:43:10 +0000886 MemPage *pParent /* The parent. Might be NULL */
887){
drh271efa52004-05-30 19:19:05 +0000888 int pc; /* Address of a freeblock within pPage->aData[] */
drh271efa52004-05-30 19:19:05 +0000889 int hdr; /* Offset to beginning of page header */
890 u8 *data; /* Equal to pPage->aData */
danielk1977aef0bf62005-12-30 16:28:01 +0000891 BtShared *pBt; /* The main btree structure */
drh271efa52004-05-30 19:19:05 +0000892 int usableSize; /* Amount of usable space on each page */
893 int cellOffset; /* Offset from start of page to first cell pointer */
894 int nFree; /* Number of unused bytes on the page */
895 int top; /* First byte of the cell content area */
drh2af926b2001-05-15 00:39:25 +0000896
drh2e38c322004-09-03 18:38:44 +0000897 pBt = pPage->pBt;
898 assert( pBt!=0 );
899 assert( pParent==0 || pParent->pBt==pBt );
drh1fee73e2007-08-29 04:00:57 +0000900 assert( sqlite3_mutex_held(pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +0000901 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drh07d183d2005-05-01 22:52:42 +0000902 assert( pPage->aData == &((unsigned char*)pPage)[-pBt->pageSize] );
drhee696e22004-08-30 16:52:17 +0000903 if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){
904 /* The parent page should never change unless the file is corrupt */
drh49285702005-09-17 15:20:26 +0000905 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000906 }
drh10617cd2004-05-14 15:27:27 +0000907 if( pPage->isInit ) return SQLITE_OK;
drhda200cc2004-05-09 11:51:38 +0000908 if( pPage->pParent==0 && pParent!=0 ){
909 pPage->pParent = pParent;
danielk19773b8a05f2007-03-19 17:44:26 +0000910 sqlite3PagerRef(pParent->pDbPage);
drh5e2f8b92001-05-28 00:41:15 +0000911 }
drhde647132004-05-07 17:57:49 +0000912 hdr = pPage->hdrOffset;
drha34b6762004-05-07 13:30:42 +0000913 data = pPage->aData;
drh271efa52004-05-30 19:19:05 +0000914 decodeFlags(pPage, data[hdr]);
drh43605152004-05-29 21:46:49 +0000915 pPage->nOverflow = 0;
drhc8629a12004-05-08 20:07:40 +0000916 pPage->idxShift = 0;
drh2e38c322004-09-03 18:38:44 +0000917 usableSize = pBt->usableSize;
drh43605152004-05-29 21:46:49 +0000918 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
919 top = get2byte(&data[hdr+5]);
920 pPage->nCell = get2byte(&data[hdr+3]);
drh2e38c322004-09-03 18:38:44 +0000921 if( pPage->nCell>MX_CELL(pBt) ){
drhee696e22004-08-30 16:52:17 +0000922 /* To many cells for a single page. The page must be corrupt */
drh49285702005-09-17 15:20:26 +0000923 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000924 }
925 if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
926 /* All pages must have at least one cell, except for root pages */
drh49285702005-09-17 15:20:26 +0000927 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000928 }
drh9e572e62004-04-23 23:43:10 +0000929
930 /* Compute the total free space on the page */
drh9e572e62004-04-23 23:43:10 +0000931 pc = get2byte(&data[hdr+1]);
drh43605152004-05-29 21:46:49 +0000932 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
drh9e572e62004-04-23 23:43:10 +0000933 while( pc>0 ){
934 int next, size;
drhee696e22004-08-30 16:52:17 +0000935 if( pc>usableSize-4 ){
936 /* Free block is off the page */
drh49285702005-09-17 15:20:26 +0000937 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000938 }
drh9e572e62004-04-23 23:43:10 +0000939 next = get2byte(&data[pc]);
940 size = get2byte(&data[pc+2]);
drhee696e22004-08-30 16:52:17 +0000941 if( next>0 && next<=pc+size+3 ){
942 /* Free blocks must be in accending order */
drh49285702005-09-17 15:20:26 +0000943 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000944 }
drh3add3672004-05-15 00:29:24 +0000945 nFree += size;
drh9e572e62004-04-23 23:43:10 +0000946 pc = next;
947 }
drh3add3672004-05-15 00:29:24 +0000948 pPage->nFree = nFree;
drhee696e22004-08-30 16:52:17 +0000949 if( nFree>=usableSize ){
950 /* Free space cannot exceed total page size */
drh49285702005-09-17 15:20:26 +0000951 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000952 }
drh9e572e62004-04-23 23:43:10 +0000953
drhde647132004-05-07 17:57:49 +0000954 pPage->isInit = 1;
drh9e572e62004-04-23 23:43:10 +0000955 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +0000956}
957
958/*
drh8b2f49b2001-06-08 00:21:52 +0000959** Set up a raw page so that it looks like a database page holding
960** no entries.
drhbd03cae2001-06-02 02:40:57 +0000961*/
drh9e572e62004-04-23 23:43:10 +0000962static void zeroPage(MemPage *pPage, int flags){
963 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +0000964 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +0000965 int hdr = pPage->hdrOffset;
drh9e572e62004-04-23 23:43:10 +0000966 int first;
967
danielk19773b8a05f2007-03-19 17:44:26 +0000968 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drh07d183d2005-05-01 22:52:42 +0000969 assert( &data[pBt->pageSize] == (unsigned char*)pPage );
danielk19773b8a05f2007-03-19 17:44:26 +0000970 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +0000971 assert( sqlite3_mutex_held(pBt->mutex) );
drhb6f41482004-05-14 01:58:11 +0000972 memset(&data[hdr], 0, pBt->usableSize - hdr);
drh9e572e62004-04-23 23:43:10 +0000973 data[hdr] = flags;
drh43605152004-05-29 21:46:49 +0000974 first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
975 memset(&data[hdr+1], 0, 4);
976 data[hdr+7] = 0;
977 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +0000978 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +0000979 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +0000980 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +0000981 pPage->cellOffset = first;
982 pPage->nOverflow = 0;
drhda200cc2004-05-09 11:51:38 +0000983 pPage->idxShift = 0;
drh43605152004-05-29 21:46:49 +0000984 pPage->nCell = 0;
drhda200cc2004-05-09 11:51:38 +0000985 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +0000986}
987
988/*
drh3aac2dd2004-04-26 14:10:20 +0000989** Get a page from the pager. Initialize the MemPage.pBt and
990** MemPage.aData elements if needed.
drh538f5702007-04-13 02:14:30 +0000991**
992** If the noContent flag is set, it means that we do not care about
993** the content of the page at this time. So do not go to the disk
994** to fetch the content. Just fill in the content with zeros for now.
995** If in the future we call sqlite3PagerWrite() on this page, that
996** means we have started to be concerned about content and the disk
997** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +0000998*/
drh16a9b832007-05-05 18:39:25 +0000999int sqlite3BtreeGetPage(
1000 BtShared *pBt, /* The btree */
1001 Pgno pgno, /* Number of the page to fetch */
1002 MemPage **ppPage, /* Return the page in this parameter */
1003 int noContent /* Do not load page content if true */
1004){
drh3aac2dd2004-04-26 14:10:20 +00001005 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001006 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00001007 DbPage *pDbPage;
1008
drh1fee73e2007-08-29 04:00:57 +00001009 assert( sqlite3_mutex_held(pBt->mutex) );
drh538f5702007-04-13 02:14:30 +00001010 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
drh3aac2dd2004-04-26 14:10:20 +00001011 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001012 pPage = (MemPage *)sqlite3PagerGetExtra(pDbPage);
1013 pPage->aData = sqlite3PagerGetData(pDbPage);
1014 pPage->pDbPage = pDbPage;
drh3aac2dd2004-04-26 14:10:20 +00001015 pPage->pBt = pBt;
1016 pPage->pgno = pgno;
drhde647132004-05-07 17:57:49 +00001017 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
drh3aac2dd2004-04-26 14:10:20 +00001018 *ppPage = pPage;
1019 return SQLITE_OK;
1020}
1021
1022/*
drhde647132004-05-07 17:57:49 +00001023** Get a page from the pager and initialize it. This routine
1024** is just a convenience wrapper around separate calls to
drh16a9b832007-05-05 18:39:25 +00001025** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
drhde647132004-05-07 17:57:49 +00001026*/
1027static int getAndInitPage(
danielk1977aef0bf62005-12-30 16:28:01 +00001028 BtShared *pBt, /* The database file */
drhde647132004-05-07 17:57:49 +00001029 Pgno pgno, /* Number of the page to get */
1030 MemPage **ppPage, /* Write the page pointer here */
1031 MemPage *pParent /* Parent of the page */
1032){
1033 int rc;
drh1fee73e2007-08-29 04:00:57 +00001034 assert( sqlite3_mutex_held(pBt->mutex) );
drhee696e22004-08-30 16:52:17 +00001035 if( pgno==0 ){
drh49285702005-09-17 15:20:26 +00001036 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001037 }
drh16a9b832007-05-05 18:39:25 +00001038 rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
drh10617cd2004-05-14 15:27:27 +00001039 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
drh16a9b832007-05-05 18:39:25 +00001040 rc = sqlite3BtreeInitPage(*ppPage, pParent);
drhde647132004-05-07 17:57:49 +00001041 }
1042 return rc;
1043}
1044
1045/*
drh3aac2dd2004-04-26 14:10:20 +00001046** Release a MemPage. This should be called once for each prior
drh16a9b832007-05-05 18:39:25 +00001047** call to sqlite3BtreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +00001048*/
drh4b70f112004-05-02 21:12:19 +00001049static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001050 if( pPage ){
1051 assert( pPage->aData );
1052 assert( pPage->pBt );
drh07d183d2005-05-01 22:52:42 +00001053 assert( &pPage->aData[pPage->pBt->pageSize]==(unsigned char*)pPage );
drh1fee73e2007-08-29 04:00:57 +00001054 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001055 sqlite3PagerUnref(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00001056 }
1057}
1058
1059/*
drh72f82862001-05-24 21:06:34 +00001060** This routine is called when the reference count for a page
1061** reaches zero. We need to unref the pParent pointer when that
1062** happens.
1063*/
danielk19773b8a05f2007-03-19 17:44:26 +00001064static void pageDestructor(DbPage *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +00001065 MemPage *pPage;
1066 assert( (pageSize & 7)==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001067 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
drh1fee73e2007-08-29 04:00:57 +00001068 assert( pPage->isInit==0 || sqlite3_mutex_held(pPage->pBt->mutex) );
drh72f82862001-05-24 21:06:34 +00001069 if( pPage->pParent ){
1070 MemPage *pParent = pPage->pParent;
drhd0679ed2007-08-28 22:24:34 +00001071 assert( pPage->isInit==1 );
1072 assert( pParent->pBt==pPage->pBt );
drh72f82862001-05-24 21:06:34 +00001073 pPage->pParent = 0;
drha34b6762004-05-07 13:30:42 +00001074 releasePage(pParent);
drh72f82862001-05-24 21:06:34 +00001075 }
drh3aac2dd2004-04-26 14:10:20 +00001076 pPage->isInit = 0;
drh72f82862001-05-24 21:06:34 +00001077}
1078
1079/*
drha6abd042004-06-09 17:37:22 +00001080** During a rollback, when the pager reloads information into the cache
1081** so that the cache is restored to its original state at the start of
1082** the transaction, for each page restored this routine is called.
1083**
1084** This routine needs to reset the extra data section at the end of the
1085** page to agree with the restored data.
1086*/
danielk19773b8a05f2007-03-19 17:44:26 +00001087static void pageReinit(DbPage *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +00001088 MemPage *pPage;
1089 assert( (pageSize & 7)==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001090 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
drha6abd042004-06-09 17:37:22 +00001091 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00001092 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00001093 pPage->isInit = 0;
drh16a9b832007-05-05 18:39:25 +00001094 sqlite3BtreeInitPage(pPage, pPage->pParent);
drha6abd042004-06-09 17:37:22 +00001095 }
1096}
1097
1098/*
drhad3e0102004-09-03 23:32:18 +00001099** Open a database file.
1100**
drh382c0242001-10-06 16:33:02 +00001101** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001102** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001103** database file will be deleted when sqlite3BtreeClose() is called.
drhe53831d2007-08-17 01:14:38 +00001104** If zFilename is ":memory:" then an in-memory database is created
1105** that is automatically destroyed when it is closed.
drha059ad02001-04-17 20:09:11 +00001106*/
drh23e11ca2004-05-04 17:27:28 +00001107int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001108 const char *zFilename, /* Name of the file containing the BTree database */
danielk1977aef0bf62005-12-30 16:28:01 +00001109 sqlite3 *pSqlite, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001110 Btree **ppBtree, /* Pointer to new Btree object written here */
drh90f5ecb2004-07-22 01:19:35 +00001111 int flags /* Options */
drh6019e162001-07-02 17:51:45 +00001112){
drhd677b3d2007-08-20 22:48:41 +00001113 sqlite3_vfs *pVfs; /* The VFS to use for this btree */
drhe53831d2007-08-17 01:14:38 +00001114 BtShared *pBt = 0; /* Shared part of btree structure */
danielk1977aef0bf62005-12-30 16:28:01 +00001115 Btree *p; /* Handle to return */
danielk1977dddbcdc2007-04-26 14:42:34 +00001116 int rc = SQLITE_OK;
drh90f5ecb2004-07-22 01:19:35 +00001117 int nReserve;
1118 unsigned char zDbHeader[100];
danielk1977aef0bf62005-12-30 16:28:01 +00001119
1120 /* Set the variable isMemdb to true for an in-memory database, or
1121 ** false for a file-based database. This symbol is only required if
1122 ** either of the shared-data or autovacuum features are compiled
1123 ** into the library.
1124 */
1125#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
1126 #ifdef SQLITE_OMIT_MEMORYDB
drh980b1a72006-08-16 16:42:48 +00001127 const int isMemdb = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00001128 #else
drh980b1a72006-08-16 16:42:48 +00001129 const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
danielk1977aef0bf62005-12-30 16:28:01 +00001130 #endif
1131#endif
1132
drhd0679ed2007-08-28 22:24:34 +00001133 assert( pSqlite!=0 );
1134 assert( sqlite3_mutex_held(pSqlite->mutex) );
drh153c62c2007-08-24 03:51:33 +00001135
drhd0679ed2007-08-28 22:24:34 +00001136 pVfs = pSqlite->pVfs;
drh17435752007-08-16 04:30:38 +00001137 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00001138 if( !p ){
1139 return SQLITE_NOMEM;
1140 }
1141 p->inTrans = TRANS_NONE;
1142 p->pSqlite = pSqlite;
1143
drh198bf392006-01-06 21:52:49 +00001144#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001145 /*
1146 ** If this Btree is a candidate for shared cache, try to find an
1147 ** existing BtShared object that we can share with
1148 */
1149 if( (flags & BTREE_PRIVATE)==0
1150 && isMemdb==0
drhd0679ed2007-08-28 22:24:34 +00001151 && (pSqlite->flags & SQLITE_Vtab)==0
drhe53831d2007-08-17 01:14:38 +00001152 && zFilename && zFilename[0]
1153 && sqlite3SharedCacheEnabled
1154 ){
danielk197790949c22007-08-17 16:50:38 +00001155 char *zFullPathname = (char *)sqlite3_malloc(pVfs->mxPathname);
drhe53831d2007-08-17 01:14:38 +00001156 sqlite3_mutex *mutexShared;
1157 p->sharable = 1;
drh4a50aac2007-08-23 02:47:53 +00001158 if( pSqlite ){
1159 pSqlite->flags |= SQLITE_SharedCache;
1160 }
danielk1977aef0bf62005-12-30 16:28:01 +00001161 if( !zFullPathname ){
drh17435752007-08-16 04:30:38 +00001162 sqlite3_free(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001163 return SQLITE_NOMEM;
1164 }
danielk197790949c22007-08-17 16:50:38 +00001165 sqlite3OsFullPathname(pVfs, zFilename, zFullPathname);
drhe53831d2007-08-17 01:14:38 +00001166 mutexShared = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
1167 sqlite3_mutex_enter(mutexShared);
1168 for(pBt=sqlite3SharedCacheList; pBt; pBt=pBt->pNext){
danielk1977b82e7ed2006-01-11 14:09:31 +00001169 assert( pBt->nRef>0 );
drhd0679ed2007-08-28 22:24:34 +00001170 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
1171 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
danielk1977aef0bf62005-12-30 16:28:01 +00001172 p->pBt = pBt;
danielk1977aef0bf62005-12-30 16:28:01 +00001173 pBt->nRef++;
drhe53831d2007-08-17 01:14:38 +00001174 break;
danielk1977aef0bf62005-12-30 16:28:01 +00001175 }
1176 }
drhe53831d2007-08-17 01:14:38 +00001177 sqlite3_mutex_leave(mutexShared);
drh17435752007-08-16 04:30:38 +00001178 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00001179 }
1180#endif
drha059ad02001-04-17 20:09:11 +00001181 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00001182 /*
1183 ** The following asserts make sure that structures used by the btree are
1184 ** the right size. This is to guard against size changes that result
1185 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00001186 */
drhe53831d2007-08-17 01:14:38 +00001187 assert( sizeof(i64)==8 || sizeof(i64)==4 );
1188 assert( sizeof(u64)==8 || sizeof(u64)==4 );
1189 assert( sizeof(u32)==4 );
1190 assert( sizeof(u16)==2 );
1191 assert( sizeof(Pgno)==4 );
1192
1193 pBt = sqlite3MallocZero( sizeof(*pBt) );
1194 if( pBt==0 ){
1195 rc = SQLITE_NOMEM;
1196 goto btree_open_out;
1197 }
danielk1977b4b47412007-08-17 15:53:36 +00001198 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename, EXTRA_SIZE, flags);
drhe53831d2007-08-17 01:14:38 +00001199 if( rc==SQLITE_OK ){
1200 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
1201 }
1202 if( rc!=SQLITE_OK ){
1203 goto btree_open_out;
1204 }
1205 p->pBt = pBt;
1206
1207 sqlite3PagerSetDestructor(pBt->pPager, pageDestructor);
1208 sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
1209 pBt->pCursor = 0;
1210 pBt->pPage1 = 0;
1211 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
1212 pBt->pageSize = get2byte(&zDbHeader[16]);
1213 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1214 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00001215 pBt->pageSize = 0;
1216 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drhe53831d2007-08-17 01:14:38 +00001217 pBt->maxEmbedFrac = 64; /* 25% */
1218 pBt->minEmbedFrac = 32; /* 12.5% */
1219 pBt->minLeafFrac = 32; /* 12.5% */
1220#ifndef SQLITE_OMIT_AUTOVACUUM
1221 /* If the magic name ":memory:" will create an in-memory database, then
1222 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
1223 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
1224 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
1225 ** regular file-name. In this case the auto-vacuum applies as per normal.
1226 */
1227 if( zFilename && !isMemdb ){
1228 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
1229 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
1230 }
1231#endif
1232 nReserve = 0;
1233 }else{
1234 nReserve = zDbHeader[20];
1235 pBt->maxEmbedFrac = zDbHeader[21];
1236 pBt->minEmbedFrac = zDbHeader[22];
1237 pBt->minLeafFrac = zDbHeader[23];
1238 pBt->pageSizeFixed = 1;
1239#ifndef SQLITE_OMIT_AUTOVACUUM
1240 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1241 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
1242#endif
1243 }
1244 pBt->usableSize = pBt->pageSize - nReserve;
1245 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
danielk1977a1644fd2007-08-29 12:31:25 +00001246 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drhe53831d2007-08-17 01:14:38 +00001247
1248#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1249 /* Add the new BtShared object to the linked list sharable BtShareds.
1250 */
1251 if( p->sharable ){
1252 sqlite3_mutex *mutexShared;
1253 pBt->nRef = 1;
1254 mutexShared = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
1255 pBt->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
1256 sqlite3_mutex_enter(mutexShared);
1257 pBt->pNext = sqlite3SharedCacheList;
1258 sqlite3SharedCacheList = pBt;
1259 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00001260 }
drheee46cf2004-11-06 00:02:48 +00001261#endif
drh90f5ecb2004-07-22 01:19:35 +00001262 }
danielk1977aef0bf62005-12-30 16:28:01 +00001263
drhcfed7bc2006-03-13 14:28:05 +00001264#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001265 /* If the new Btree uses a sharable pBtShared, then link the new
1266 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00001267 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00001268 */
drhe53831d2007-08-17 01:14:38 +00001269 if( p->sharable ){
1270 int i;
1271 Btree *pSib;
1272 for(i=0; i<pSqlite->nDb; i++){
1273 if( (pSib = pSqlite->aDb[i].pBt)!=0 && pSib->sharable ){
1274 while( pSib->pPrev ){ pSib = pSib->pPrev; }
1275 if( p->pBt<pSib->pBt ){
1276 p->pNext = pSib;
1277 p->pPrev = 0;
1278 pSib->pPrev = p;
1279 }else{
drhabddb0c2007-08-20 13:14:28 +00001280 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
drhe53831d2007-08-17 01:14:38 +00001281 pSib = pSib->pNext;
1282 }
1283 p->pNext = pSib->pNext;
1284 p->pPrev = pSib;
1285 if( p->pNext ){
1286 p->pNext->pPrev = p;
1287 }
1288 pSib->pNext = p;
1289 }
1290 break;
1291 }
1292 }
danielk1977aef0bf62005-12-30 16:28:01 +00001293 }
danielk1977aef0bf62005-12-30 16:28:01 +00001294#endif
1295 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00001296
1297btree_open_out:
1298 if( rc!=SQLITE_OK ){
1299 if( pBt && pBt->pPager ){
1300 sqlite3PagerClose(pBt->pPager);
1301 }
drh17435752007-08-16 04:30:38 +00001302 sqlite3_free(pBt);
1303 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00001304 *ppBtree = 0;
1305 }
1306 return rc;
drha059ad02001-04-17 20:09:11 +00001307}
1308
1309/*
drhe53831d2007-08-17 01:14:38 +00001310** Decrement the BtShared.nRef counter. When it reaches zero,
1311** remove the BtShared structure from the sharing list. Return
1312** true if the BtShared.nRef counter reaches zero and return
1313** false if it is still positive.
1314*/
1315static int removeFromSharingList(BtShared *pBt){
1316#ifndef SQLITE_OMIT_SHARED_CACHE
1317 sqlite3_mutex *pMaster;
1318 BtShared *pList;
1319 int removed = 0;
1320
drhd677b3d2007-08-20 22:48:41 +00001321 assert( sqlite3_mutex_notheld(pBt->mutex) );
drhe53831d2007-08-17 01:14:38 +00001322 pMaster = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER);
1323 sqlite3_mutex_enter(pMaster);
1324 pBt->nRef--;
1325 if( pBt->nRef<=0 ){
1326 if( sqlite3SharedCacheList==pBt ){
1327 sqlite3SharedCacheList = pBt->pNext;
1328 }else{
1329 pList = sqlite3SharedCacheList;
1330 while( pList && pList->pNext!=pBt ){
1331 pList=pList->pNext;
1332 }
1333 if( pList ){
1334 pList->pNext = pBt->pNext;
1335 }
1336 }
1337 sqlite3_mutex_free(pBt->mutex);
1338 removed = 1;
1339 }
1340 sqlite3_mutex_leave(pMaster);
1341 return removed;
1342#else
1343 return 1;
1344#endif
1345}
1346
1347/*
drha059ad02001-04-17 20:09:11 +00001348** Close an open database and invalidate all cursors.
1349*/
danielk1977aef0bf62005-12-30 16:28:01 +00001350int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00001351 BtShared *pBt = p->pBt;
1352 BtCursor *pCur;
1353
danielk1977aef0bf62005-12-30 16:28:01 +00001354 /* Close all cursors opened via this handle. */
drhd0679ed2007-08-28 22:24:34 +00001355 assert( sqlite3_mutex_held(p->pSqlite->mutex) );
drhe53831d2007-08-17 01:14:38 +00001356 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001357 pCur = pBt->pCursor;
1358 while( pCur ){
1359 BtCursor *pTmp = pCur;
1360 pCur = pCur->pNext;
1361 if( pTmp->pBtree==p ){
1362 sqlite3BtreeCloseCursor(pTmp);
1363 }
drha059ad02001-04-17 20:09:11 +00001364 }
danielk1977aef0bf62005-12-30 16:28:01 +00001365
danielk19778d34dfd2006-01-24 16:37:57 +00001366 /* Rollback any active transaction and free the handle structure.
1367 ** The call to sqlite3BtreeRollback() drops any table-locks held by
1368 ** this handle.
1369 */
danielk1977b597f742006-01-15 11:39:18 +00001370 sqlite3BtreeRollback(p);
drhe53831d2007-08-17 01:14:38 +00001371 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001372
danielk1977aef0bf62005-12-30 16:28:01 +00001373 /* If there are still other outstanding references to the shared-btree
1374 ** structure, return now. The remainder of this procedure cleans
1375 ** up the shared-btree.
1376 */
drhe53831d2007-08-17 01:14:38 +00001377 assert( p->wantToLock==0 && p->locked==0 );
1378 if( !p->sharable || removeFromSharingList(pBt) ){
1379 /* The pBt is no longer on the sharing list, so we can access
1380 ** it without having to hold the mutex.
1381 **
1382 ** Clean out and delete the BtShared object.
1383 */
1384 assert( !pBt->pCursor );
drhe53831d2007-08-17 01:14:38 +00001385 sqlite3PagerClose(pBt->pPager);
1386 if( pBt->xFreeSchema && pBt->pSchema ){
1387 pBt->xFreeSchema(pBt->pSchema);
1388 }
1389 sqlite3_free(pBt->pSchema);
1390 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00001391 }
1392
drhe53831d2007-08-17 01:14:38 +00001393#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00001394 assert( p->wantToLock==0 );
1395 assert( p->locked==0 );
1396 if( p->pPrev ) p->pPrev->pNext = p->pNext;
1397 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00001398#endif
1399
drhe53831d2007-08-17 01:14:38 +00001400 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00001401 return SQLITE_OK;
1402}
1403
1404/*
drh90f5ecb2004-07-22 01:19:35 +00001405** Change the busy handler callback function.
1406*/
danielk1977aef0bf62005-12-30 16:28:01 +00001407int sqlite3BtreeSetBusyHandler(Btree *p, BusyHandler *pHandler){
1408 BtShared *pBt = p->pBt;
drhd0679ed2007-08-28 22:24:34 +00001409 assert( sqlite3_mutex_held(p->pSqlite->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001410 sqlite3BtreeEnter(p);
drhb8ef32c2005-03-14 02:01:49 +00001411 pBt->pBusyHandler = pHandler;
danielk19773b8a05f2007-03-19 17:44:26 +00001412 sqlite3PagerSetBusyhandler(pBt->pPager, pHandler);
drhd677b3d2007-08-20 22:48:41 +00001413 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00001414 return SQLITE_OK;
1415}
1416
1417/*
drhda47d772002-12-02 04:25:19 +00001418** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001419**
1420** The maximum number of cache pages is set to the absolute
1421** value of mxPage. If mxPage is negative, the pager will
1422** operate asynchronously - it will not stop to do fsync()s
1423** to insure data is written to the disk surface before
1424** continuing. Transactions still work if synchronous is off,
1425** and the database cannot be corrupted if this program
1426** crashes. But if the operating system crashes or there is
1427** an abrupt power failure when synchronous is off, the database
1428** could be left in an inconsistent and unrecoverable state.
1429** Synchronous is on by default so database corruption is not
1430** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001431*/
danielk1977aef0bf62005-12-30 16:28:01 +00001432int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
1433 BtShared *pBt = p->pBt;
drhd0679ed2007-08-28 22:24:34 +00001434 assert( sqlite3_mutex_held(p->pSqlite->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001435 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001436 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00001437 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00001438 return SQLITE_OK;
1439}
1440
1441/*
drh973b6e32003-02-12 14:09:42 +00001442** Change the way data is synced to disk in order to increase or decrease
1443** how well the database resists damage due to OS crashes and power
1444** failures. Level 1 is the same as asynchronous (no syncs() occur and
1445** there is a high probability of damage) Level 2 is the default. There
1446** is a very low but non-zero probability of damage. Level 3 reduces the
1447** probability of damage to near zero but with a write performance reduction.
1448*/
danielk197793758c82005-01-21 08:13:14 +00001449#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drhac530b12006-02-11 01:25:50 +00001450int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
danielk1977aef0bf62005-12-30 16:28:01 +00001451 BtShared *pBt = p->pBt;
drhd0679ed2007-08-28 22:24:34 +00001452 assert( sqlite3_mutex_held(p->pSqlite->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001453 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001454 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
drhd677b3d2007-08-20 22:48:41 +00001455 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00001456 return SQLITE_OK;
1457}
danielk197793758c82005-01-21 08:13:14 +00001458#endif
drh973b6e32003-02-12 14:09:42 +00001459
drh2c8997b2005-08-27 16:36:48 +00001460/*
1461** Return TRUE if the given btree is set to safety level 1. In other
1462** words, return TRUE if no sync() occurs on the disk files.
1463*/
danielk1977aef0bf62005-12-30 16:28:01 +00001464int sqlite3BtreeSyncDisabled(Btree *p){
1465 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001466 int rc;
drhd0679ed2007-08-28 22:24:34 +00001467 assert( sqlite3_mutex_held(p->pSqlite->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001468 sqlite3BtreeEnter(p);
drhd0679ed2007-08-28 22:24:34 +00001469 assert( pBt && pBt->pPager );
drhd677b3d2007-08-20 22:48:41 +00001470 rc = sqlite3PagerNosync(pBt->pPager);
1471 sqlite3BtreeLeave(p);
1472 return rc;
drh2c8997b2005-08-27 16:36:48 +00001473}
1474
danielk1977576ec6b2005-01-21 11:55:25 +00001475#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00001476/*
drh90f5ecb2004-07-22 01:19:35 +00001477** Change the default pages size and the number of reserved bytes per page.
drh06f50212004-11-02 14:24:33 +00001478**
1479** The page size must be a power of 2 between 512 and 65536. If the page
1480** size supplied does not meet this constraint then the page size is not
1481** changed.
1482**
1483** Page sizes are constrained to be a power of two so that the region
1484** of the database file used for locking (beginning at PENDING_BYTE,
1485** the first byte past the 1GB boundary, 0x40000000) needs to occur
1486** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001487**
1488** If parameter nReserve is less than zero, then the number of reserved
1489** bytes per page is left unchanged.
drh90f5ecb2004-07-22 01:19:35 +00001490*/
danielk1977aef0bf62005-12-30 16:28:01 +00001491int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
danielk1977a1644fd2007-08-29 12:31:25 +00001492 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00001493 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001494 sqlite3BtreeEnter(p);
drh90f5ecb2004-07-22 01:19:35 +00001495 if( pBt->pageSizeFixed ){
drhd677b3d2007-08-20 22:48:41 +00001496 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00001497 return SQLITE_READONLY;
1498 }
1499 if( nReserve<0 ){
1500 nReserve = pBt->pageSize - pBt->usableSize;
1501 }
drh06f50212004-11-02 14:24:33 +00001502 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
1503 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00001504 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00001505 assert( !pBt->pPage1 && !pBt->pCursor );
danielk1977a1644fd2007-08-29 12:31:25 +00001506 pBt->pageSize = pageSize;
1507 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001508 }
1509 pBt->usableSize = pBt->pageSize - nReserve;
drhd677b3d2007-08-20 22:48:41 +00001510 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00001511 return rc;
drh90f5ecb2004-07-22 01:19:35 +00001512}
1513
1514/*
1515** Return the currently defined page size
1516*/
danielk1977aef0bf62005-12-30 16:28:01 +00001517int sqlite3BtreeGetPageSize(Btree *p){
1518 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00001519}
danielk1977aef0bf62005-12-30 16:28:01 +00001520int sqlite3BtreeGetReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00001521 int n;
1522 sqlite3BtreeEnter(p);
1523 n = p->pBt->pageSize - p->pBt->usableSize;
1524 sqlite3BtreeLeave(p);
1525 return n;
drh2011d5f2004-07-22 02:40:37 +00001526}
drhf8e632b2007-05-08 14:51:36 +00001527
1528/*
1529** Set the maximum page count for a database if mxPage is positive.
1530** No changes are made if mxPage is 0 or negative.
1531** Regardless of the value of mxPage, return the maximum page count.
1532*/
1533int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00001534 int n;
1535 sqlite3BtreeEnter(p);
1536 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
1537 sqlite3BtreeLeave(p);
1538 return n;
drhf8e632b2007-05-08 14:51:36 +00001539}
danielk1977576ec6b2005-01-21 11:55:25 +00001540#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00001541
1542/*
danielk1977951af802004-11-05 15:45:09 +00001543** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
1544** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
1545** is disabled. The default value for the auto-vacuum property is
1546** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
1547*/
danielk1977aef0bf62005-12-30 16:28:01 +00001548int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00001549#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001550 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00001551#else
danielk1977dddbcdc2007-04-26 14:42:34 +00001552 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001553 int rc = SQLITE_OK;
danielk1977dddbcdc2007-04-26 14:42:34 +00001554 int av = (autoVacuum?1:0);
drhd677b3d2007-08-20 22:48:41 +00001555
1556 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00001557 if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00001558 rc = SQLITE_READONLY;
1559 }else{
1560 pBt->autoVacuum = av;
danielk1977951af802004-11-05 15:45:09 +00001561 }
drhd677b3d2007-08-20 22:48:41 +00001562 sqlite3BtreeLeave(p);
1563 return rc;
danielk1977951af802004-11-05 15:45:09 +00001564#endif
1565}
1566
1567/*
1568** Return the value of the 'auto-vacuum' property. If auto-vacuum is
1569** enabled 1 is returned. Otherwise 0.
1570*/
danielk1977aef0bf62005-12-30 16:28:01 +00001571int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00001572#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00001573 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00001574#else
drhd677b3d2007-08-20 22:48:41 +00001575 int rc;
1576 sqlite3BtreeEnter(p);
1577 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00001578 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
1579 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
1580 BTREE_AUTOVACUUM_INCR
1581 );
drhd677b3d2007-08-20 22:48:41 +00001582 sqlite3BtreeLeave(p);
1583 return rc;
danielk1977951af802004-11-05 15:45:09 +00001584#endif
1585}
1586
1587
1588/*
drha34b6762004-05-07 13:30:42 +00001589** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001590** also acquire a readlock on that file.
1591**
1592** SQLITE_OK is returned on success. If the file is not a
1593** well-formed database file, then SQLITE_CORRUPT is returned.
1594** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00001595** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00001596*/
danielk1977aef0bf62005-12-30 16:28:01 +00001597static int lockBtree(BtShared *pBt){
drh07d183d2005-05-01 22:52:42 +00001598 int rc, pageSize;
drh3aac2dd2004-04-26 14:10:20 +00001599 MemPage *pPage1;
drhd677b3d2007-08-20 22:48:41 +00001600
drh1fee73e2007-08-29 04:00:57 +00001601 assert( sqlite3_mutex_held(pBt->mutex) );
drha34b6762004-05-07 13:30:42 +00001602 if( pBt->pPage1 ) return SQLITE_OK;
drh16a9b832007-05-05 18:39:25 +00001603 rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00001604 if( rc!=SQLITE_OK ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00001605
drh306dc212001-05-21 13:45:10 +00001606
1607 /* Do some checking to help insure the file we opened really is
1608 ** a valid database file.
1609 */
drhb6f41482004-05-14 01:58:11 +00001610 rc = SQLITE_NOTADB;
danielk19773b8a05f2007-03-19 17:44:26 +00001611 if( sqlite3PagerPagecount(pBt->pPager)>0 ){
drhb6f41482004-05-14 01:58:11 +00001612 u8 *page1 = pPage1->aData;
1613 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001614 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001615 }
drh309169a2007-04-24 17:27:51 +00001616 if( page1[18]>1 ){
1617 pBt->readOnly = 1;
1618 }
1619 if( page1[19]>1 ){
drhb6f41482004-05-14 01:58:11 +00001620 goto page1_init_failed;
1621 }
drh07d183d2005-05-01 22:52:42 +00001622 pageSize = get2byte(&page1[16]);
drh15926592007-04-06 15:02:13 +00001623 if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ){
drh07d183d2005-05-01 22:52:42 +00001624 goto page1_init_failed;
1625 }
1626 assert( (pageSize & 7)==0 );
1627 pBt->pageSize = pageSize;
1628 pBt->usableSize = pageSize - page1[20];
drhb6f41482004-05-14 01:58:11 +00001629 if( pBt->usableSize<500 ){
1630 goto page1_init_failed;
1631 }
1632 pBt->maxEmbedFrac = page1[21];
1633 pBt->minEmbedFrac = page1[22];
1634 pBt->minLeafFrac = page1[23];
drh057cd3a2005-02-15 16:23:02 +00001635#ifndef SQLITE_OMIT_AUTOVACUUM
1636 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00001637 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00001638#endif
drh306dc212001-05-21 13:45:10 +00001639 }
drhb6f41482004-05-14 01:58:11 +00001640
1641 /* maxLocal is the maximum amount of payload to store locally for
1642 ** a cell. Make sure it is small enough so that at least minFanout
1643 ** cells can will fit on one page. We assume a 10-byte page header.
1644 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001645 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001646 ** 4-byte child pointer
1647 ** 9-byte nKey value
1648 ** 4-byte nData value
1649 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001650 ** So a cell consists of a 2-byte poiner, a header which is as much as
1651 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1652 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001653 */
drh43605152004-05-29 21:46:49 +00001654 pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
1655 pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
1656 pBt->maxLeaf = pBt->usableSize - 35;
1657 pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
drhb6f41482004-05-14 01:58:11 +00001658 if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
1659 goto page1_init_failed;
1660 }
drh2e38c322004-09-03 18:38:44 +00001661 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00001662 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001663 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001664
drh72f82862001-05-24 21:06:34 +00001665page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001666 releasePage(pPage1);
1667 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001668 return rc;
drh306dc212001-05-21 13:45:10 +00001669}
1670
1671/*
drhb8ef32c2005-03-14 02:01:49 +00001672** This routine works like lockBtree() except that it also invokes the
1673** busy callback if there is lock contention.
1674*/
danielk1977aef0bf62005-12-30 16:28:01 +00001675static int lockBtreeWithRetry(Btree *pRef){
drhb8ef32c2005-03-14 02:01:49 +00001676 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00001677
drh1fee73e2007-08-29 04:00:57 +00001678 assert( sqlite3BtreeHoldsMutex(pRef) );
danielk1977aef0bf62005-12-30 16:28:01 +00001679 if( pRef->inTrans==TRANS_NONE ){
1680 u8 inTransaction = pRef->pBt->inTransaction;
1681 btreeIntegrity(pRef);
1682 rc = sqlite3BtreeBeginTrans(pRef, 0);
1683 pRef->pBt->inTransaction = inTransaction;
1684 pRef->inTrans = TRANS_NONE;
1685 if( rc==SQLITE_OK ){
1686 pRef->pBt->nTransaction--;
1687 }
1688 btreeIntegrity(pRef);
drhb8ef32c2005-03-14 02:01:49 +00001689 }
1690 return rc;
1691}
1692
1693
1694/*
drhb8ca3072001-12-05 00:21:20 +00001695** If there are no outstanding cursors and we are not in the middle
1696** of a transaction but there is a read lock on the database, then
1697** this routine unrefs the first page of the database file which
1698** has the effect of releasing the read lock.
1699**
1700** If there are any outstanding cursors, this routine is a no-op.
1701**
1702** If there is a transaction in progress, this routine is a no-op.
1703*/
danielk1977aef0bf62005-12-30 16:28:01 +00001704static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00001705 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00001706 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00001707 if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
drh24c9a2e2007-01-05 02:00:47 +00001708 if( pBt->pPage1->aData==0 ){
1709 MemPage *pPage = pBt->pPage1;
1710 pPage->aData = &((u8*)pPage)[-pBt->pageSize];
1711 pPage->pBt = pBt;
1712 pPage->pgno = 1;
1713 }
1714 releasePage(pBt->pPage1);
drh51c6d962004-06-06 00:42:25 +00001715 }
drh3aac2dd2004-04-26 14:10:20 +00001716 pBt->pPage1 = 0;
drh3aac2dd2004-04-26 14:10:20 +00001717 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001718 }
1719}
1720
1721/*
drh9e572e62004-04-23 23:43:10 +00001722** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00001723** file.
drh8b2f49b2001-06-08 00:21:52 +00001724*/
danielk1977aef0bf62005-12-30 16:28:01 +00001725static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00001726 MemPage *pP1;
1727 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00001728 int rc;
drhd677b3d2007-08-20 22:48:41 +00001729
drh1fee73e2007-08-29 04:00:57 +00001730 assert( sqlite3_mutex_held(pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001731 if( sqlite3PagerPagecount(pBt->pPager)>0 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001732 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00001733 assert( pP1!=0 );
1734 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00001735 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00001736 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00001737 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
1738 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00001739 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00001740 data[18] = 1;
1741 data[19] = 1;
drhb6f41482004-05-14 01:58:11 +00001742 data[20] = pBt->pageSize - pBt->usableSize;
1743 data[21] = pBt->maxEmbedFrac;
1744 data[22] = pBt->minEmbedFrac;
1745 data[23] = pBt->minLeafFrac;
1746 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00001747 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00001748 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00001749#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00001750 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00001751 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00001752 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00001753 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00001754#endif
drh8b2f49b2001-06-08 00:21:52 +00001755 return SQLITE_OK;
1756}
1757
1758/*
danielk1977ee5741e2004-05-31 10:01:34 +00001759** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00001760** is started if the second argument is nonzero, otherwise a read-
1761** transaction. If the second argument is 2 or more and exclusive
1762** transaction is started, meaning that no other process is allowed
1763** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00001764** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00001765** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00001766**
danielk1977ee5741e2004-05-31 10:01:34 +00001767** A write-transaction must be started before attempting any
1768** changes to the database. None of the following routines
1769** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00001770**
drh23e11ca2004-05-04 17:27:28 +00001771** sqlite3BtreeCreateTable()
1772** sqlite3BtreeCreateIndex()
1773** sqlite3BtreeClearTable()
1774** sqlite3BtreeDropTable()
1775** sqlite3BtreeInsert()
1776** sqlite3BtreeDelete()
1777** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00001778**
drhb8ef32c2005-03-14 02:01:49 +00001779** If an initial attempt to acquire the lock fails because of lock contention
1780** and the database was previously unlocked, then invoke the busy handler
1781** if there is one. But if there was previously a read-lock, do not
1782** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
1783** returned when there is already a read-lock in order to avoid a deadlock.
1784**
1785** Suppose there are two processes A and B. A has a read lock and B has
1786** a reserved lock. B tries to promote to exclusive but is blocked because
1787** of A's read lock. A tries to promote to reserved but is blocked by B.
1788** One or the other of the two processes must give way or there can be
1789** no progress. By returning SQLITE_BUSY and not invoking the busy callback
1790** when A already has a read lock, we encourage A to give up and let B
1791** proceed.
drha059ad02001-04-17 20:09:11 +00001792*/
danielk1977aef0bf62005-12-30 16:28:01 +00001793int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
1794 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00001795 int rc = SQLITE_OK;
1796
drhd677b3d2007-08-20 22:48:41 +00001797 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001798 btreeIntegrity(p);
1799
danielk1977ee5741e2004-05-31 10:01:34 +00001800 /* If the btree is already in a write-transaction, or it
1801 ** is already in a read-transaction and a read-transaction
1802 ** is requested, this is a no-op.
1803 */
danielk1977aef0bf62005-12-30 16:28:01 +00001804 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00001805 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00001806 }
drhb8ef32c2005-03-14 02:01:49 +00001807
1808 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00001809 if( pBt->readOnly && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00001810 rc = SQLITE_READONLY;
1811 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00001812 }
1813
danielk1977aef0bf62005-12-30 16:28:01 +00001814 /* If another database handle has already opened a write transaction
1815 ** on this shared-btree structure and a second write transaction is
1816 ** requested, return SQLITE_BUSY.
1817 */
1818 if( pBt->inTransaction==TRANS_WRITE && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00001819 rc = SQLITE_BUSY;
1820 goto trans_begun;
danielk1977aef0bf62005-12-30 16:28:01 +00001821 }
1822
drhb8ef32c2005-03-14 02:01:49 +00001823 do {
1824 if( pBt->pPage1==0 ){
1825 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +00001826 }
drh309169a2007-04-24 17:27:51 +00001827
drhb8ef32c2005-03-14 02:01:49 +00001828 if( rc==SQLITE_OK && wrflag ){
drh309169a2007-04-24 17:27:51 +00001829 if( pBt->readOnly ){
1830 rc = SQLITE_READONLY;
1831 }else{
1832 rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1);
1833 if( rc==SQLITE_OK ){
1834 rc = newDatabase(pBt);
1835 }
drhb8ef32c2005-03-14 02:01:49 +00001836 }
1837 }
1838
1839 if( rc==SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00001840 if( wrflag ) pBt->inStmt = 0;
1841 }else{
1842 unlockBtreeIfUnused(pBt);
1843 }
danielk1977aef0bf62005-12-30 16:28:01 +00001844 }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
drha4afb652005-07-09 02:16:02 +00001845 sqlite3InvokeBusyHandler(pBt->pBusyHandler) );
danielk1977aef0bf62005-12-30 16:28:01 +00001846
1847 if( rc==SQLITE_OK ){
1848 if( p->inTrans==TRANS_NONE ){
1849 pBt->nTransaction++;
1850 }
1851 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
1852 if( p->inTrans>pBt->inTransaction ){
1853 pBt->inTransaction = p->inTrans;
1854 }
1855 }
1856
drhd677b3d2007-08-20 22:48:41 +00001857
1858trans_begun:
danielk1977aef0bf62005-12-30 16:28:01 +00001859 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00001860 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00001861 return rc;
drha059ad02001-04-17 20:09:11 +00001862}
1863
danielk1977687566d2004-11-02 12:56:41 +00001864#ifndef SQLITE_OMIT_AUTOVACUUM
1865
1866/*
1867** Set the pointer-map entries for all children of page pPage. Also, if
1868** pPage contains cells that point to overflow pages, set the pointer
1869** map entries for the overflow pages as well.
1870*/
1871static int setChildPtrmaps(MemPage *pPage){
1872 int i; /* Counter variable */
1873 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00001874 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00001875 BtShared *pBt = pPage->pBt;
danielk1977687566d2004-11-02 12:56:41 +00001876 int isInitOrig = pPage->isInit;
1877 Pgno pgno = pPage->pgno;
1878
drh1fee73e2007-08-29 04:00:57 +00001879 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19772df71c72007-05-24 07:22:42 +00001880 rc = sqlite3BtreeInitPage(pPage, pPage->pParent);
1881 if( rc!=SQLITE_OK ){
1882 goto set_child_ptrmaps_out;
1883 }
danielk1977687566d2004-11-02 12:56:41 +00001884 nCell = pPage->nCell;
1885
1886 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00001887 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00001888
danielk197726836652005-01-17 01:33:13 +00001889 rc = ptrmapPutOvflPtr(pPage, pCell);
1890 if( rc!=SQLITE_OK ){
1891 goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00001892 }
danielk197726836652005-01-17 01:33:13 +00001893
danielk1977687566d2004-11-02 12:56:41 +00001894 if( !pPage->leaf ){
1895 Pgno childPgno = get4byte(pCell);
1896 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
1897 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
1898 }
1899 }
1900
1901 if( !pPage->leaf ){
1902 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
1903 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
1904 }
1905
1906set_child_ptrmaps_out:
1907 pPage->isInit = isInitOrig;
1908 return rc;
1909}
1910
1911/*
1912** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
1913** page, is a pointer to page iFrom. Modify this pointer so that it points to
1914** iTo. Parameter eType describes the type of pointer to be modified, as
1915** follows:
1916**
1917** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
1918** page of pPage.
1919**
1920** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
1921** page pointed to by one of the cells on pPage.
1922**
1923** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
1924** overflow page in the list.
1925*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00001926static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00001927 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk1977687566d2004-11-02 12:56:41 +00001928 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00001929 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00001930 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00001931 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00001932 }
danielk1977f78fc082004-11-02 14:40:32 +00001933 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00001934 }else{
1935 int isInitOrig = pPage->isInit;
1936 int i;
1937 int nCell;
1938
drh16a9b832007-05-05 18:39:25 +00001939 sqlite3BtreeInitPage(pPage, 0);
danielk1977687566d2004-11-02 12:56:41 +00001940 nCell = pPage->nCell;
1941
danielk1977687566d2004-11-02 12:56:41 +00001942 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00001943 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00001944 if( eType==PTRMAP_OVERFLOW1 ){
1945 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00001946 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
danielk1977687566d2004-11-02 12:56:41 +00001947 if( info.iOverflow ){
1948 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
1949 put4byte(&pCell[info.iOverflow], iTo);
1950 break;
1951 }
1952 }
1953 }else{
1954 if( get4byte(pCell)==iFrom ){
1955 put4byte(pCell, iTo);
1956 break;
1957 }
1958 }
1959 }
1960
1961 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00001962 if( eType!=PTRMAP_BTREE ||
1963 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00001964 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00001965 }
danielk1977687566d2004-11-02 12:56:41 +00001966 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
1967 }
1968
1969 pPage->isInit = isInitOrig;
1970 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00001971 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00001972}
1973
danielk1977003ba062004-11-04 02:57:33 +00001974
danielk19777701e812005-01-10 12:59:51 +00001975/*
1976** Move the open database page pDbPage to location iFreePage in the
1977** database. The pDbPage reference remains valid.
1978*/
danielk1977003ba062004-11-04 02:57:33 +00001979static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00001980 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00001981 MemPage *pDbPage, /* Open page to move */
1982 u8 eType, /* Pointer map 'type' entry for pDbPage */
1983 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
1984 Pgno iFreePage /* The location to move pDbPage to */
danielk1977003ba062004-11-04 02:57:33 +00001985){
1986 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
1987 Pgno iDbPage = pDbPage->pgno;
1988 Pager *pPager = pBt->pPager;
1989 int rc;
1990
danielk1977a0bf2652004-11-04 14:30:04 +00001991 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
1992 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00001993 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00001994 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00001995
1996 /* Move page iDbPage from it's current location to page number iFreePage */
1997 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
1998 iDbPage, iFreePage, iPtrPage, eType));
danielk19773b8a05f2007-03-19 17:44:26 +00001999 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage);
danielk1977003ba062004-11-04 02:57:33 +00002000 if( rc!=SQLITE_OK ){
2001 return rc;
2002 }
2003 pDbPage->pgno = iFreePage;
2004
2005 /* If pDbPage was a btree-page, then it may have child pages and/or cells
2006 ** that point to overflow pages. The pointer map entries for all these
2007 ** pages need to be changed.
2008 **
2009 ** If pDbPage is an overflow page, then the first 4 bytes may store a
2010 ** pointer to a subsequent overflow page. If this is the case, then
2011 ** the pointer map needs to be updated for the subsequent overflow page.
2012 */
danielk1977a0bf2652004-11-04 14:30:04 +00002013 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00002014 rc = setChildPtrmaps(pDbPage);
2015 if( rc!=SQLITE_OK ){
2016 return rc;
2017 }
2018 }else{
2019 Pgno nextOvfl = get4byte(pDbPage->aData);
2020 if( nextOvfl!=0 ){
danielk1977003ba062004-11-04 02:57:33 +00002021 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
2022 if( rc!=SQLITE_OK ){
2023 return rc;
2024 }
2025 }
2026 }
2027
2028 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
2029 ** that it points at iFreePage. Also fix the pointer map entry for
2030 ** iPtrPage.
2031 */
danielk1977a0bf2652004-11-04 14:30:04 +00002032 if( eType!=PTRMAP_ROOTPAGE ){
drh16a9b832007-05-05 18:39:25 +00002033 rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00002034 if( rc!=SQLITE_OK ){
2035 return rc;
2036 }
danielk19773b8a05f2007-03-19 17:44:26 +00002037 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00002038 if( rc!=SQLITE_OK ){
2039 releasePage(pPtrPage);
2040 return rc;
2041 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002042 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00002043 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00002044 if( rc==SQLITE_OK ){
2045 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
2046 }
danielk1977003ba062004-11-04 02:57:33 +00002047 }
danielk1977003ba062004-11-04 02:57:33 +00002048 return rc;
2049}
2050
danielk1977dddbcdc2007-04-26 14:42:34 +00002051/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00002052static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00002053
2054/*
danielk1977dddbcdc2007-04-26 14:42:34 +00002055** Perform a single step of an incremental-vacuum. If successful,
2056** return SQLITE_OK. If there is no work to do (and therefore no
2057** point in calling this function again), return SQLITE_DONE.
2058**
2059** More specificly, this function attempts to re-organize the
2060** database so that the last page of the file currently in use
2061** is no longer in use.
2062**
2063** If the nFin parameter is non-zero, the implementation assumes
2064** that the caller will keep calling incrVacuumStep() until
2065** it returns SQLITE_DONE or an error, and that nFin is the
2066** number of pages the database file will contain after this
2067** process is complete.
2068*/
2069static int incrVacuumStep(BtShared *pBt, Pgno nFin){
2070 Pgno iLastPg; /* Last page in the database */
2071 Pgno nFreeList; /* Number of pages still on the free-list */
2072
drh1fee73e2007-08-29 04:00:57 +00002073 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977dddbcdc2007-04-26 14:42:34 +00002074 iLastPg = pBt->nTrunc;
2075 if( iLastPg==0 ){
2076 iLastPg = sqlite3PagerPagecount(pBt->pPager);
2077 }
2078
2079 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
2080 int rc;
2081 u8 eType;
2082 Pgno iPtrPage;
2083
2084 nFreeList = get4byte(&pBt->pPage1->aData[36]);
2085 if( nFreeList==0 || nFin==iLastPg ){
2086 return SQLITE_DONE;
2087 }
2088
2089 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
2090 if( rc!=SQLITE_OK ){
2091 return rc;
2092 }
2093 if( eType==PTRMAP_ROOTPAGE ){
2094 return SQLITE_CORRUPT_BKPT;
2095 }
2096
2097 if( eType==PTRMAP_FREEPAGE ){
2098 if( nFin==0 ){
2099 /* Remove the page from the files free-list. This is not required
danielk19774ef24492007-05-23 09:52:41 +00002100 ** if nFin is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00002101 ** truncated to zero after this function returns, so it doesn't
2102 ** matter if it still contains some garbage entries.
2103 */
2104 Pgno iFreePg;
2105 MemPage *pFreePg;
2106 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
2107 if( rc!=SQLITE_OK ){
2108 return rc;
2109 }
2110 assert( iFreePg==iLastPg );
2111 releasePage(pFreePg);
2112 }
2113 } else {
2114 Pgno iFreePg; /* Index of free page to move pLastPg to */
2115 MemPage *pLastPg;
2116
drh16a9b832007-05-05 18:39:25 +00002117 rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002118 if( rc!=SQLITE_OK ){
2119 return rc;
2120 }
2121
danielk1977b4626a32007-04-28 15:47:43 +00002122 /* If nFin is zero, this loop runs exactly once and page pLastPg
2123 ** is swapped with the first free page pulled off the free list.
2124 **
2125 ** On the other hand, if nFin is greater than zero, then keep
2126 ** looping until a free-page located within the first nFin pages
2127 ** of the file is found.
2128 */
danielk1977dddbcdc2007-04-26 14:42:34 +00002129 do {
2130 MemPage *pFreePg;
2131 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
2132 if( rc!=SQLITE_OK ){
2133 releasePage(pLastPg);
2134 return rc;
2135 }
2136 releasePage(pFreePg);
2137 }while( nFin!=0 && iFreePg>nFin );
2138 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00002139
2140 rc = sqlite3PagerWrite(pLastPg->pDbPage);
2141 if( rc!=SQLITE_OK ){
2142 return rc;
2143 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002144 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg);
2145 releasePage(pLastPg);
2146 if( rc!=SQLITE_OK ){
2147 return rc;
2148 }
2149 }
2150 }
2151
2152 pBt->nTrunc = iLastPg - 1;
2153 while( pBt->nTrunc==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, pBt->nTrunc) ){
2154 pBt->nTrunc--;
2155 }
2156 return SQLITE_OK;
2157}
2158
2159/*
2160** A write-transaction must be opened before calling this function.
2161** It performs a single unit of work towards an incremental vacuum.
2162**
2163** If the incremental vacuum is finished after this function has run,
2164** SQLITE_DONE is returned. If it is not finished, but no error occured,
2165** SQLITE_OK is returned. Otherwise an SQLite error code.
2166*/
2167int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002168 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002169 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002170
2171 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00002172 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
2173 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002174 rc = SQLITE_DONE;
2175 }else{
2176 invalidateAllOverflowCache(pBt);
2177 rc = incrVacuumStep(pBt, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002178 }
drhd677b3d2007-08-20 22:48:41 +00002179 sqlite3BtreeLeave(p);
2180 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002181}
2182
2183/*
danielk19773b8a05f2007-03-19 17:44:26 +00002184** This routine is called prior to sqlite3PagerCommit when a transaction
danielk1977687566d2004-11-02 12:56:41 +00002185** is commited for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00002186**
2187** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
2188** the database file should be truncated to during the commit process.
2189** i.e. the database has been reorganized so that only the first *pnTrunc
2190** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00002191*/
danielk197724168722007-04-02 05:07:47 +00002192static int autoVacuumCommit(BtShared *pBt, Pgno *pnTrunc){
danielk1977dddbcdc2007-04-26 14:42:34 +00002193 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002194 Pager *pPager = pBt->pPager;
danielk1977687566d2004-11-02 12:56:41 +00002195#ifndef NDEBUG
danielk19773b8a05f2007-03-19 17:44:26 +00002196 int nRef = sqlite3PagerRefcount(pPager);
danielk1977687566d2004-11-02 12:56:41 +00002197#endif
2198
drh1fee73e2007-08-29 04:00:57 +00002199 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00002200 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00002201 assert(pBt->autoVacuum);
2202 if( !pBt->incrVacuum ){
2203 Pgno nFin = 0;
danielk1977687566d2004-11-02 12:56:41 +00002204
danielk1977dddbcdc2007-04-26 14:42:34 +00002205 if( pBt->nTrunc==0 ){
2206 Pgno nFree;
2207 Pgno nPtrmap;
2208 const int pgsz = pBt->pageSize;
2209 Pgno nOrig = sqlite3PagerPagecount(pBt->pPager);
danielk1977e5321f02007-04-27 07:05:44 +00002210
2211 if( PTRMAP_ISPAGE(pBt, nOrig) ){
2212 return SQLITE_CORRUPT_BKPT;
2213 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002214 if( nOrig==PENDING_BYTE_PAGE(pBt) ){
2215 nOrig--;
danielk1977687566d2004-11-02 12:56:41 +00002216 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002217 nFree = get4byte(&pBt->pPage1->aData[36]);
2218 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
2219 nFin = nOrig - nFree - nPtrmap;
2220 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
2221 nFin--;
danielk1977ac11ee62005-01-15 12:45:51 +00002222 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002223 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
2224 nFin--;
2225 }
2226 }
danielk1977687566d2004-11-02 12:56:41 +00002227
danielk1977dddbcdc2007-04-26 14:42:34 +00002228 while( rc==SQLITE_OK ){
2229 rc = incrVacuumStep(pBt, nFin);
2230 }
2231 if( rc==SQLITE_DONE ){
2232 assert(nFin==0 || pBt->nTrunc==0 || nFin<=pBt->nTrunc);
2233 rc = SQLITE_OK;
2234 if( pBt->nTrunc ){
drh67f80b62007-07-23 19:26:17 +00002235 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
danielk1977dddbcdc2007-04-26 14:42:34 +00002236 put4byte(&pBt->pPage1->aData[32], 0);
2237 put4byte(&pBt->pPage1->aData[36], 0);
2238 pBt->nTrunc = nFin;
2239 }
2240 }
2241 if( rc!=SQLITE_OK ){
2242 sqlite3PagerRollback(pPager);
2243 }
danielk1977687566d2004-11-02 12:56:41 +00002244 }
2245
danielk1977dddbcdc2007-04-26 14:42:34 +00002246 if( rc==SQLITE_OK ){
2247 *pnTrunc = pBt->nTrunc;
2248 pBt->nTrunc = 0;
2249 }
danielk19773b8a05f2007-03-19 17:44:26 +00002250 assert( nRef==sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002251 return rc;
2252}
danielk1977dddbcdc2007-04-26 14:42:34 +00002253
danielk1977687566d2004-11-02 12:56:41 +00002254#endif
2255
2256/*
drh80e35f42007-03-30 14:06:34 +00002257** This routine does the first phase of a two-phase commit. This routine
2258** causes a rollback journal to be created (if it does not already exist)
2259** and populated with enough information so that if a power loss occurs
2260** the database can be restored to its original state by playing back
2261** the journal. Then the contents of the journal are flushed out to
2262** the disk. After the journal is safely on oxide, the changes to the
2263** database are written into the database file and flushed to oxide.
2264** At the end of this call, the rollback journal still exists on the
2265** disk and we are still holding all locks, so the transaction has not
2266** committed. See sqlite3BtreeCommit() for the second phase of the
2267** commit process.
2268**
2269** This call is a no-op if no write-transaction is currently active on pBt.
2270**
2271** Otherwise, sync the database file for the btree pBt. zMaster points to
2272** the name of a master journal file that should be written into the
2273** individual journal file, or is NULL, indicating no master journal file
2274** (single database transaction).
2275**
2276** When this is called, the master journal should already have been
2277** created, populated with this journal pointer and synced to disk.
2278**
2279** Once this is routine has returned, the only thing required to commit
2280** the write-transaction for this database file is to delete the journal.
2281*/
2282int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
2283 int rc = SQLITE_OK;
2284 if( p->inTrans==TRANS_WRITE ){
2285 BtShared *pBt = p->pBt;
2286 Pgno nTrunc = 0;
drhd677b3d2007-08-20 22:48:41 +00002287 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00002288#ifndef SQLITE_OMIT_AUTOVACUUM
2289 if( pBt->autoVacuum ){
2290 rc = autoVacuumCommit(pBt, &nTrunc);
2291 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002292 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002293 return rc;
2294 }
2295 }
2296#endif
2297 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, nTrunc);
drhd677b3d2007-08-20 22:48:41 +00002298 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002299 }
2300 return rc;
2301}
2302
2303/*
drh2aa679f2001-06-25 02:11:07 +00002304** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00002305**
drh6e345992007-03-30 11:12:08 +00002306** This routine implements the second phase of a 2-phase commit. The
2307** sqlite3BtreeSync() routine does the first phase and should be invoked
2308** prior to calling this routine. The sqlite3BtreeSync() routine did
2309** all the work of writing information out to disk and flushing the
2310** contents so that they are written onto the disk platter. All this
2311** routine has to do is delete or truncate the rollback journal
2312** (which causes the transaction to commit) and drop locks.
2313**
drh5e00f6c2001-09-13 13:46:56 +00002314** This will release the write lock on the database file. If there
2315** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002316*/
drh80e35f42007-03-30 14:06:34 +00002317int sqlite3BtreeCommitPhaseTwo(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002318 BtShared *pBt = p->pBt;
2319
drhd677b3d2007-08-20 22:48:41 +00002320 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002321 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002322
2323 /* If the handle has a write-transaction open, commit the shared-btrees
2324 ** transaction and set the shared state to TRANS_READ.
2325 */
2326 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00002327 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002328 assert( pBt->inTransaction==TRANS_WRITE );
2329 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00002330 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
danielk19777f7bc662006-01-23 13:47:47 +00002331 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002332 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002333 return rc;
2334 }
danielk1977aef0bf62005-12-30 16:28:01 +00002335 pBt->inTransaction = TRANS_READ;
2336 pBt->inStmt = 0;
danielk1977ee5741e2004-05-31 10:01:34 +00002337 }
danielk19777f7bc662006-01-23 13:47:47 +00002338 unlockAllTables(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002339
2340 /* If the handle has any kind of transaction open, decrement the transaction
2341 ** count of the shared btree. If the transaction count reaches 0, set
2342 ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
2343 ** will unlock the pager.
2344 */
2345 if( p->inTrans!=TRANS_NONE ){
2346 pBt->nTransaction--;
2347 if( 0==pBt->nTransaction ){
2348 pBt->inTransaction = TRANS_NONE;
2349 }
2350 }
2351
2352 /* Set the handles current transaction state to TRANS_NONE and unlock
2353 ** the pager if this call closed the only read or write transaction.
2354 */
2355 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00002356 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002357
2358 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002359 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002360 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002361}
2362
drh80e35f42007-03-30 14:06:34 +00002363/*
2364** Do both phases of a commit.
2365*/
2366int sqlite3BtreeCommit(Btree *p){
2367 int rc;
drhd677b3d2007-08-20 22:48:41 +00002368 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00002369 rc = sqlite3BtreeCommitPhaseOne(p, 0);
2370 if( rc==SQLITE_OK ){
2371 rc = sqlite3BtreeCommitPhaseTwo(p);
2372 }
drhd677b3d2007-08-20 22:48:41 +00002373 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002374 return rc;
2375}
2376
danielk1977fbcd5852004-06-15 02:44:18 +00002377#ifndef NDEBUG
2378/*
2379** Return the number of write-cursors open on this handle. This is for use
2380** in assert() expressions, so it is only compiled if NDEBUG is not
2381** defined.
2382*/
danielk1977aef0bf62005-12-30 16:28:01 +00002383static int countWriteCursors(BtShared *pBt){
danielk1977fbcd5852004-06-15 02:44:18 +00002384 BtCursor *pCur;
2385 int r = 0;
2386 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
danielk1977aef0bf62005-12-30 16:28:01 +00002387 if( pCur->wrFlag ) r++;
danielk1977fbcd5852004-06-15 02:44:18 +00002388 }
2389 return r;
2390}
2391#endif
2392
drhc39e0002004-05-07 23:50:57 +00002393/*
drhecdc7532001-09-23 02:35:53 +00002394** Rollback the transaction in progress. All cursors will be
2395** invalided by this operation. Any attempt to use a cursor
2396** that was open at the beginning of this operation will result
2397** in an error.
drh5e00f6c2001-09-13 13:46:56 +00002398**
2399** 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*/
danielk1977aef0bf62005-12-30 16:28:01 +00002402int sqlite3BtreeRollback(Btree *p){
danielk19778d34dfd2006-01-24 16:37:57 +00002403 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002404 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00002405 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00002406
drhd677b3d2007-08-20 22:48:41 +00002407 sqlite3BtreeEnter(p);
danielk19772b8c13e2006-01-24 14:21:24 +00002408 rc = saveAllCursors(pBt, 0, 0);
danielk19778d34dfd2006-01-24 16:37:57 +00002409#ifndef SQLITE_OMIT_SHARED_CACHE
danielk19772b8c13e2006-01-24 14:21:24 +00002410 if( rc!=SQLITE_OK ){
danielk19778d34dfd2006-01-24 16:37:57 +00002411 /* This is a horrible situation. An IO or malloc() error occured whilst
2412 ** trying to save cursor positions. If this is an automatic rollback (as
2413 ** the result of a constraint, malloc() failure or IO error) then
2414 ** the cache may be internally inconsistent (not contain valid trees) so
2415 ** we cannot simply return the error to the caller. Instead, abort
2416 ** all queries that may be using any of the cursors that failed to save.
2417 */
2418 while( pBt->pCursor ){
2419 sqlite3 *db = pBt->pCursor->pBtree->pSqlite;
2420 if( db ){
drh4cf7c7f2007-08-28 23:28:07 +00002421 /**** FIX ME: This can deadlock ****/
2422 sqlite3_mutex_enter(db->mutex);
danielk19778d34dfd2006-01-24 16:37:57 +00002423 sqlite3AbortOtherActiveVdbes(db, 0);
drh4cf7c7f2007-08-28 23:28:07 +00002424 sqlite3_mutex_leave(db->mutex);
danielk19778d34dfd2006-01-24 16:37:57 +00002425 }
2426 }
danielk19772b8c13e2006-01-24 14:21:24 +00002427 }
danielk19778d34dfd2006-01-24 16:37:57 +00002428#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002429 btreeIntegrity(p);
2430 unlockAllTables(p);
2431
2432 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00002433 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00002434
danielk1977dddbcdc2007-04-26 14:42:34 +00002435#ifndef SQLITE_OMIT_AUTOVACUUM
2436 pBt->nTrunc = 0;
2437#endif
2438
danielk19778d34dfd2006-01-24 16:37:57 +00002439 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00002440 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00002441 if( rc2!=SQLITE_OK ){
2442 rc = rc2;
2443 }
2444
drh24cd67e2004-05-10 16:18:47 +00002445 /* The rollback may have destroyed the pPage1->aData value. So
drh16a9b832007-05-05 18:39:25 +00002446 ** call sqlite3BtreeGetPage() on page 1 again to make
2447 ** sure pPage1->aData is set correctly. */
2448 if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh24cd67e2004-05-10 16:18:47 +00002449 releasePage(pPage1);
2450 }
danielk1977fbcd5852004-06-15 02:44:18 +00002451 assert( countWriteCursors(pBt)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002452 pBt->inTransaction = TRANS_READ;
drh24cd67e2004-05-10 16:18:47 +00002453 }
danielk1977aef0bf62005-12-30 16:28:01 +00002454
2455 if( p->inTrans!=TRANS_NONE ){
2456 assert( pBt->nTransaction>0 );
2457 pBt->nTransaction--;
2458 if( 0==pBt->nTransaction ){
2459 pBt->inTransaction = TRANS_NONE;
2460 }
2461 }
2462
2463 p->inTrans = TRANS_NONE;
danielk1977ee5741e2004-05-31 10:01:34 +00002464 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00002465 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002466
2467 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002468 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00002469 return rc;
2470}
2471
2472/*
drhab01f612004-05-22 02:55:23 +00002473** Start a statement subtransaction. The subtransaction can
2474** can be rolled back independently of the main transaction.
2475** You must start a transaction before starting a subtransaction.
2476** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00002477** commits or rolls back.
2478**
drhab01f612004-05-22 02:55:23 +00002479** Only one subtransaction may be active at a time. It is an error to try
2480** to start a new subtransaction if another subtransaction is already active.
2481**
2482** Statement subtransactions are used around individual SQL statements
2483** that are contained within a BEGIN...COMMIT block. If a constraint
2484** error occurs within the statement, the effect of that one statement
2485** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00002486*/
danielk1977aef0bf62005-12-30 16:28:01 +00002487int sqlite3BtreeBeginStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002488 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002489 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002490 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002491 if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
drhd677b3d2007-08-20 22:48:41 +00002492 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
2493 }else{
2494 assert( pBt->inTransaction==TRANS_WRITE );
2495 rc = pBt->readOnly ? SQLITE_OK : sqlite3PagerStmtBegin(pBt->pPager);
2496 pBt->inStmt = 1;
drh0d65dc02002-02-03 00:56:09 +00002497 }
drhd677b3d2007-08-20 22:48:41 +00002498 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002499 return rc;
2500}
2501
2502
2503/*
drhab01f612004-05-22 02:55:23 +00002504** Commit the statment subtransaction currently in progress. If no
2505** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00002506*/
danielk1977aef0bf62005-12-30 16:28:01 +00002507int sqlite3BtreeCommitStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002508 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002509 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002510 sqlite3BtreeEnter(p);
drh3aac2dd2004-04-26 14:10:20 +00002511 if( pBt->inStmt && !pBt->readOnly ){
danielk19773b8a05f2007-03-19 17:44:26 +00002512 rc = sqlite3PagerStmtCommit(pBt->pPager);
drh663fc632002-02-02 18:49:19 +00002513 }else{
2514 rc = SQLITE_OK;
2515 }
drh3aac2dd2004-04-26 14:10:20 +00002516 pBt->inStmt = 0;
drhd677b3d2007-08-20 22:48:41 +00002517 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002518 return rc;
2519}
2520
2521/*
drhab01f612004-05-22 02:55:23 +00002522** Rollback the active statement subtransaction. If no subtransaction
2523** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00002524**
drhab01f612004-05-22 02:55:23 +00002525** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00002526** to use a cursor that was open at the beginning of this operation
2527** will result in an error.
2528*/
danielk1977aef0bf62005-12-30 16:28:01 +00002529int sqlite3BtreeRollbackStmt(Btree *p){
danielk197797a227c2006-01-20 16:32:04 +00002530 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002531 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002532 sqlite3BtreeEnter(p);
danielk197797a227c2006-01-20 16:32:04 +00002533 sqlite3MallocDisallow();
2534 if( pBt->inStmt && !pBt->readOnly ){
danielk19773b8a05f2007-03-19 17:44:26 +00002535 rc = sqlite3PagerStmtRollback(pBt->pPager);
danielk197797a227c2006-01-20 16:32:04 +00002536 assert( countWriteCursors(pBt)==0 );
2537 pBt->inStmt = 0;
2538 }
2539 sqlite3MallocAllow();
drhd677b3d2007-08-20 22:48:41 +00002540 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002541 return rc;
2542}
2543
2544/*
drh3aac2dd2004-04-26 14:10:20 +00002545** Default key comparison function to be used if no comparison function
2546** is specified on the sqlite3BtreeCursor() call.
2547*/
2548static int dfltCompare(
2549 void *NotUsed, /* User data is not used */
2550 int n1, const void *p1, /* First key to compare */
2551 int n2, const void *p2 /* Second key to compare */
2552){
2553 int c;
2554 c = memcmp(p1, p2, n1<n2 ? n1 : n2);
2555 if( c==0 ){
2556 c = n1 - n2;
2557 }
2558 return c;
2559}
2560
2561/*
drh8b2f49b2001-06-08 00:21:52 +00002562** Create a new cursor for the BTree whose root is on the page
2563** iTable. The act of acquiring a cursor gets a read lock on
2564** the database file.
drh1bee3d72001-10-15 00:44:35 +00002565**
2566** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00002567** If wrFlag==1, then the cursor can be used for reading or for
2568** writing if other conditions for writing are also met. These
2569** are the conditions that must be met in order for writing to
2570** be allowed:
drh6446c4d2001-12-15 14:22:18 +00002571**
drhf74b8d92002-09-01 23:20:45 +00002572** 1: The cursor must have been opened with wrFlag==1
2573**
drhfe5d71d2007-03-19 11:54:10 +00002574** 2: Other database connections that share the same pager cache
2575** but which are not in the READ_UNCOMMITTED state may not have
2576** cursors open with wrFlag==0 on the same table. Otherwise
2577** the changes made by this write cursor would be visible to
2578** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00002579**
2580** 3: The database must be writable (not on read-only media)
2581**
2582** 4: There must be an active transaction.
2583**
drh6446c4d2001-12-15 14:22:18 +00002584** No checking is done to make sure that page iTable really is the
2585** root page of a b-tree. If it is not, then the cursor acquired
2586** will not work correctly.
drh3aac2dd2004-04-26 14:10:20 +00002587**
2588** The comparison function must be logically the same for every cursor
2589** on a particular table. Changing the comparison function will result
2590** in incorrect operations. If the comparison function is NULL, a
2591** default comparison function is used. The comparison function is
2592** always ignored for INTKEY tables.
drha059ad02001-04-17 20:09:11 +00002593*/
drhd677b3d2007-08-20 22:48:41 +00002594static int btreeCursor(
danielk1977aef0bf62005-12-30 16:28:01 +00002595 Btree *p, /* The btree */
drh3aac2dd2004-04-26 14:10:20 +00002596 int iTable, /* Root page of table to open */
2597 int wrFlag, /* 1 to write. 0 read-only */
2598 int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
2599 void *pArg, /* First arg to xCompare() */
2600 BtCursor **ppCur /* Write new cursor here */
2601){
drha059ad02001-04-17 20:09:11 +00002602 int rc;
drh8dcd7ca2004-08-08 19:43:29 +00002603 BtCursor *pCur;
danielk1977aef0bf62005-12-30 16:28:01 +00002604 BtShared *pBt = p->pBt;
drhecdc7532001-09-23 02:35:53 +00002605
drh1fee73e2007-08-29 04:00:57 +00002606 assert( sqlite3BtreeHoldsMutex(p) );
drh8dcd7ca2004-08-08 19:43:29 +00002607 *ppCur = 0;
2608 if( wrFlag ){
drh8dcd7ca2004-08-08 19:43:29 +00002609 if( pBt->readOnly ){
2610 return SQLITE_READONLY;
2611 }
drh980b1a72006-08-16 16:42:48 +00002612 if( checkReadLocks(p, iTable, 0) ){
drh8dcd7ca2004-08-08 19:43:29 +00002613 return SQLITE_LOCKED;
2614 }
drha0c9a112004-03-10 13:42:37 +00002615 }
danielk1977aef0bf62005-12-30 16:28:01 +00002616
drh4b70f112004-05-02 21:12:19 +00002617 if( pBt->pPage1==0 ){
danielk1977aef0bf62005-12-30 16:28:01 +00002618 rc = lockBtreeWithRetry(p);
drha059ad02001-04-17 20:09:11 +00002619 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00002620 return rc;
2621 }
drh1831f182007-04-24 17:35:59 +00002622 if( pBt->readOnly && wrFlag ){
2623 return SQLITE_READONLY;
2624 }
drha059ad02001-04-17 20:09:11 +00002625 }
drh17435752007-08-16 04:30:38 +00002626 pCur = sqlite3MallocZero( sizeof(*pCur) );
drha059ad02001-04-17 20:09:11 +00002627 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +00002628 rc = SQLITE_NOMEM;
2629 goto create_cursor_exception;
2630 }
drh8b2f49b2001-06-08 00:21:52 +00002631 pCur->pgnoRoot = (Pgno)iTable;
danielk19773b8a05f2007-03-19 17:44:26 +00002632 if( iTable==1 && sqlite3PagerPagecount(pBt->pPager)==0 ){
drh24cd67e2004-05-10 16:18:47 +00002633 rc = SQLITE_EMPTY;
2634 goto create_cursor_exception;
2635 }
drhde647132004-05-07 17:57:49 +00002636 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
drhbd03cae2001-06-02 02:40:57 +00002637 if( rc!=SQLITE_OK ){
2638 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00002639 }
danielk1977aef0bf62005-12-30 16:28:01 +00002640
danielk1977aef0bf62005-12-30 16:28:01 +00002641 /* Now that no other errors can occur, finish filling in the BtCursor
2642 ** variables, link the cursor into the BtShared list and set *ppCur (the
2643 ** output argument to this function).
2644 */
drh3aac2dd2004-04-26 14:10:20 +00002645 pCur->xCompare = xCmp ? xCmp : dfltCompare;
2646 pCur->pArg = pArg;
danielk1977aef0bf62005-12-30 16:28:01 +00002647 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00002648 pCur->pBt = pBt;
drhecdc7532001-09-23 02:35:53 +00002649 pCur->wrFlag = wrFlag;
drha059ad02001-04-17 20:09:11 +00002650 pCur->pNext = pBt->pCursor;
2651 if( pCur->pNext ){
2652 pCur->pNext->pPrev = pCur;
2653 }
2654 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00002655 pCur->eState = CURSOR_INVALID;
drh2af926b2001-05-15 00:39:25 +00002656 *ppCur = pCur;
drhbd03cae2001-06-02 02:40:57 +00002657
danielk1977aef0bf62005-12-30 16:28:01 +00002658 return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00002659
drhbd03cae2001-06-02 02:40:57 +00002660create_cursor_exception:
drhbd03cae2001-06-02 02:40:57 +00002661 if( pCur ){
drh3aac2dd2004-04-26 14:10:20 +00002662 releasePage(pCur->pPage);
drh17435752007-08-16 04:30:38 +00002663 sqlite3_free(pCur);
drhbd03cae2001-06-02 02:40:57 +00002664 }
drh5e00f6c2001-09-13 13:46:56 +00002665 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00002666 return rc;
drha059ad02001-04-17 20:09:11 +00002667}
drhd677b3d2007-08-20 22:48:41 +00002668int sqlite3BtreeCursor(
2669 Btree *p, /* The btree */
2670 int iTable, /* Root page of table to open */
2671 int wrFlag, /* 1 to write. 0 read-only */
2672 int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
2673 void *pArg, /* First arg to xCompare() */
2674 BtCursor **ppCur /* Write new cursor here */
2675){
2676 int rc;
2677 sqlite3BtreeEnter(p);
2678 rc = btreeCursor(p, iTable, wrFlag, xCmp, pArg, ppCur);
2679 sqlite3BtreeLeave(p);
2680 return rc;
2681}
2682
drha059ad02001-04-17 20:09:11 +00002683
2684/*
drh5e00f6c2001-09-13 13:46:56 +00002685** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00002686** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00002687*/
drh3aac2dd2004-04-26 14:10:20 +00002688int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhd0679ed2007-08-28 22:24:34 +00002689 BtShared *pBt = pCur->pBt;
drhd677b3d2007-08-20 22:48:41 +00002690
drh1fee73e2007-08-29 04:00:57 +00002691 assert( cursorHoldsMutex(pCur) );
drhd0679ed2007-08-28 22:24:34 +00002692 assert( sqlite3_mutex_held(pCur->pBtree->pSqlite->mutex) );
drhbf700f32007-03-31 02:36:44 +00002693 clearCursorPosition(pCur);
drha059ad02001-04-17 20:09:11 +00002694 if( pCur->pPrev ){
2695 pCur->pPrev->pNext = pCur->pNext;
2696 }else{
2697 pBt->pCursor = pCur->pNext;
2698 }
2699 if( pCur->pNext ){
2700 pCur->pNext->pPrev = pCur->pPrev;
2701 }
drh3aac2dd2004-04-26 14:10:20 +00002702 releasePage(pCur->pPage);
drh5e00f6c2001-09-13 13:46:56 +00002703 unlockBtreeIfUnused(pBt);
danielk197792d4d7a2007-05-04 12:05:56 +00002704 invalidateOverflowCache(pCur);
drh17435752007-08-16 04:30:38 +00002705 sqlite3_free(pCur);
drh8c42ca92001-06-22 19:15:00 +00002706 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002707}
2708
drh7e3b0a02001-04-28 16:52:40 +00002709/*
drh5e2f8b92001-05-28 00:41:15 +00002710** Make a temporary cursor by filling in the fields of pTempCur.
2711** The temporary cursor is not on the cursor list for the Btree.
2712*/
drh16a9b832007-05-05 18:39:25 +00002713void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh1fee73e2007-08-29 04:00:57 +00002714 assert( cursorHoldsMutex(pCur) );
drh5e2f8b92001-05-28 00:41:15 +00002715 memcpy(pTempCur, pCur, sizeof(*pCur));
2716 pTempCur->pNext = 0;
2717 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00002718 if( pTempCur->pPage ){
danielk19773b8a05f2007-03-19 17:44:26 +00002719 sqlite3PagerRef(pTempCur->pPage->pDbPage);
drhecdc7532001-09-23 02:35:53 +00002720 }
drh5e2f8b92001-05-28 00:41:15 +00002721}
2722
2723/*
drhbd03cae2001-06-02 02:40:57 +00002724** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00002725** function above.
2726*/
drh16a9b832007-05-05 18:39:25 +00002727void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00002728 assert( cursorHoldsMutex(pCur) );
drhecdc7532001-09-23 02:35:53 +00002729 if( pCur->pPage ){
danielk19773b8a05f2007-03-19 17:44:26 +00002730 sqlite3PagerUnref(pCur->pPage->pDbPage);
drhecdc7532001-09-23 02:35:53 +00002731 }
drh5e2f8b92001-05-28 00:41:15 +00002732}
2733
2734/*
drh86057612007-06-26 01:04:48 +00002735** Make sure the BtCursor* given in the argument has a valid
2736** BtCursor.info structure. If it is not already valid, call
danielk19771cc5ed82007-05-16 17:28:43 +00002737** sqlite3BtreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00002738**
2739** BtCursor.info is a cache of the information in the current cell.
drh16a9b832007-05-05 18:39:25 +00002740** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
drh86057612007-06-26 01:04:48 +00002741**
2742** 2007-06-25: There is a bug in some versions of MSVC that cause the
2743** compiler to crash when getCellInfo() is implemented as a macro.
2744** But there is a measureable speed advantage to using the macro on gcc
2745** (when less compiler optimizations like -Os or -O0 are used and the
2746** compiler is not doing agressive inlining.) So we use a real function
2747** for MSVC and a macro for everything else. Ticket #2457.
drh9188b382004-05-14 21:12:22 +00002748*/
drh9188b382004-05-14 21:12:22 +00002749#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00002750 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00002751 CellInfo info;
drh51c6d962004-06-06 00:42:25 +00002752 memset(&info, 0, sizeof(info));
drh16a9b832007-05-05 18:39:25 +00002753 sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &info);
drh9188b382004-05-14 21:12:22 +00002754 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00002755 }
danielk19771cc5ed82007-05-16 17:28:43 +00002756#else
2757 #define assertCellInfo(x)
2758#endif
drh86057612007-06-26 01:04:48 +00002759#ifdef _MSC_VER
2760 /* Use a real function in MSVC to work around bugs in that compiler. */
2761 static void getCellInfo(BtCursor *pCur){
2762 if( pCur->info.nSize==0 ){
2763 sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info);
2764 }else{
2765 assertCellInfo(pCur);
2766 }
2767 }
2768#else /* if not _MSC_VER */
2769 /* Use a macro in all other compilers so that the function is inlined */
2770#define getCellInfo(pCur) \
2771 if( pCur->info.nSize==0 ){ \
danielk19771cc5ed82007-05-16 17:28:43 +00002772 sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info); \
drh86057612007-06-26 01:04:48 +00002773 }else{ \
2774 assertCellInfo(pCur); \
2775 }
2776#endif /* _MSC_VER */
drh9188b382004-05-14 21:12:22 +00002777
2778/*
drh3aac2dd2004-04-26 14:10:20 +00002779** Set *pSize to the size of the buffer needed to hold the value of
2780** the key for the current entry. If the cursor is not pointing
2781** to a valid entry, *pSize is set to 0.
2782**
drh4b70f112004-05-02 21:12:19 +00002783** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00002784** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00002785*/
drh4a1c3802004-05-12 15:15:47 +00002786int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drhd677b3d2007-08-20 22:48:41 +00002787 int rc;
2788
drh1fee73e2007-08-29 04:00:57 +00002789 assert( cursorHoldsMutex(pCur) );
drhd677b3d2007-08-20 22:48:41 +00002790 rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00002791 if( rc==SQLITE_OK ){
2792 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
2793 if( pCur->eState==CURSOR_INVALID ){
2794 *pSize = 0;
2795 }else{
drh86057612007-06-26 01:04:48 +00002796 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00002797 *pSize = pCur->info.nKey;
2798 }
drh72f82862001-05-24 21:06:34 +00002799 }
danielk1977da184232006-01-05 11:34:32 +00002800 return rc;
drha059ad02001-04-17 20:09:11 +00002801}
drh2af926b2001-05-15 00:39:25 +00002802
drh72f82862001-05-24 21:06:34 +00002803/*
drh0e1c19e2004-05-11 00:58:56 +00002804** Set *pSize to the number of bytes of data in the entry the
2805** cursor currently points to. Always return SQLITE_OK.
2806** Failure is not possible. If the cursor is not currently
2807** pointing to an entry (which can happen, for example, if
2808** the database is empty) then *pSize is set to 0.
2809*/
2810int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drhd677b3d2007-08-20 22:48:41 +00002811 int rc;
2812
drh1fee73e2007-08-29 04:00:57 +00002813 assert( cursorHoldsMutex(pCur) );
drhd677b3d2007-08-20 22:48:41 +00002814 rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00002815 if( rc==SQLITE_OK ){
2816 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
2817 if( pCur->eState==CURSOR_INVALID ){
2818 /* Not pointing at a valid entry - set *pSize to 0. */
2819 *pSize = 0;
2820 }else{
drh86057612007-06-26 01:04:48 +00002821 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00002822 *pSize = pCur->info.nData;
2823 }
drh0e1c19e2004-05-11 00:58:56 +00002824 }
danielk1977da184232006-01-05 11:34:32 +00002825 return rc;
drh0e1c19e2004-05-11 00:58:56 +00002826}
2827
2828/*
danielk1977d04417962007-05-02 13:16:30 +00002829** Given the page number of an overflow page in the database (parameter
2830** ovfl), this function finds the page number of the next page in the
2831** linked list of overflow pages. If possible, it uses the auto-vacuum
2832** pointer-map data instead of reading the content of page ovfl to do so.
2833**
2834** If an error occurs an SQLite error code is returned. Otherwise:
2835**
2836** Unless pPgnoNext is NULL, the page number of the next overflow
2837** page in the linked list is written to *pPgnoNext. If page ovfl
2838** is the last page in it's linked list, *pPgnoNext is set to zero.
2839**
2840** If ppPage is not NULL, *ppPage is set to the MemPage* handle
2841** for page ovfl. The underlying pager page may have been requested
2842** with the noContent flag set, so the page data accessable via
2843** this handle may not be trusted.
2844*/
2845static int getOverflowPage(
2846 BtShared *pBt,
2847 Pgno ovfl, /* Overflow page */
2848 MemPage **ppPage, /* OUT: MemPage handle */
2849 Pgno *pPgnoNext /* OUT: Next overflow page number */
2850){
2851 Pgno next = 0;
2852 int rc;
2853
drh1fee73e2007-08-29 04:00:57 +00002854 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977d04417962007-05-02 13:16:30 +00002855 /* One of these must not be NULL. Otherwise, why call this function? */
2856 assert(ppPage || pPgnoNext);
2857
2858 /* If pPgnoNext is NULL, then this function is being called to obtain
2859 ** a MemPage* reference only. No page-data is required in this case.
2860 */
2861 if( !pPgnoNext ){
drh16a9b832007-05-05 18:39:25 +00002862 return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1);
danielk1977d04417962007-05-02 13:16:30 +00002863 }
2864
2865#ifndef SQLITE_OMIT_AUTOVACUUM
2866 /* Try to find the next page in the overflow list using the
2867 ** autovacuum pointer-map pages. Guess that the next page in
2868 ** the overflow list is page number (ovfl+1). If that guess turns
2869 ** out to be wrong, fall back to loading the data of page
2870 ** number ovfl to determine the next page number.
2871 */
2872 if( pBt->autoVacuum ){
2873 Pgno pgno;
2874 Pgno iGuess = ovfl+1;
2875 u8 eType;
2876
2877 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
2878 iGuess++;
2879 }
2880
danielk197720713f32007-05-03 11:43:33 +00002881 if( iGuess<=sqlite3PagerPagecount(pBt->pPager) ){
danielk1977d04417962007-05-02 13:16:30 +00002882 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
2883 if( rc!=SQLITE_OK ){
2884 return rc;
2885 }
2886 if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
2887 next = iGuess;
2888 }
2889 }
2890 }
2891#endif
2892
2893 if( next==0 || ppPage ){
2894 MemPage *pPage = 0;
2895
drh16a9b832007-05-05 18:39:25 +00002896 rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0);
danielk1977d04417962007-05-02 13:16:30 +00002897 assert(rc==SQLITE_OK || pPage==0);
2898 if( next==0 && rc==SQLITE_OK ){
2899 next = get4byte(pPage->aData);
2900 }
2901
2902 if( ppPage ){
2903 *ppPage = pPage;
2904 }else{
2905 releasePage(pPage);
2906 }
2907 }
2908 *pPgnoNext = next;
2909
2910 return rc;
2911}
2912
danielk1977da107192007-05-04 08:32:13 +00002913/*
2914** Copy data from a buffer to a page, or from a page to a buffer.
2915**
2916** pPayload is a pointer to data stored on database page pDbPage.
2917** If argument eOp is false, then nByte bytes of data are copied
2918** from pPayload to the buffer pointed at by pBuf. If eOp is true,
2919** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
2920** of data are copied from the buffer pBuf to pPayload.
2921**
2922** SQLITE_OK is returned on success, otherwise an error code.
2923*/
2924static int copyPayload(
2925 void *pPayload, /* Pointer to page data */
2926 void *pBuf, /* Pointer to buffer */
2927 int nByte, /* Number of bytes to copy */
2928 int eOp, /* 0 -> copy from page, 1 -> copy to page */
2929 DbPage *pDbPage /* Page containing pPayload */
2930){
2931 if( eOp ){
2932 /* Copy data from buffer to page (a write operation) */
2933 int rc = sqlite3PagerWrite(pDbPage);
2934 if( rc!=SQLITE_OK ){
2935 return rc;
2936 }
2937 memcpy(pPayload, pBuf, nByte);
2938 }else{
2939 /* Copy data from page to buffer (a read operation) */
2940 memcpy(pBuf, pPayload, nByte);
2941 }
2942 return SQLITE_OK;
2943}
danielk1977d04417962007-05-02 13:16:30 +00002944
2945/*
danielk19779f8d6402007-05-02 17:48:45 +00002946** This function is used to read or overwrite payload information
2947** for the entry that the pCur cursor is pointing to. If the eOp
2948** parameter is 0, this is a read operation (data copied into
2949** buffer pBuf). If it is non-zero, a write (data copied from
2950** buffer pBuf).
2951**
2952** A total of "amt" bytes are read or written beginning at "offset".
2953** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00002954**
2955** This routine does not make a distinction between key and data.
danielk19779f8d6402007-05-02 17:48:45 +00002956** It just reads or writes bytes from the payload area. Data might
2957** appear on the main page or be scattered out on multiple overflow
2958** pages.
danielk1977da107192007-05-04 08:32:13 +00002959**
danielk1977dcbb5d32007-05-04 18:36:44 +00002960** If the BtCursor.isIncrblobHandle flag is set, and the current
danielk1977da107192007-05-04 08:32:13 +00002961** cursor entry uses one or more overflow pages, this function
2962** allocates space for and lazily popluates the overflow page-list
2963** cache array (BtCursor.aOverflow). Subsequent calls use this
2964** cache to make seeking to the supplied offset more efficient.
2965**
2966** Once an overflow page-list cache has been allocated, it may be
2967** invalidated if some other cursor writes to the same table, or if
2968** the cursor is moved to a different row. Additionally, in auto-vacuum
2969** mode, the following events may invalidate an overflow page-list cache.
2970**
2971** * An incremental vacuum,
2972** * A commit in auto_vacuum="full" mode,
2973** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00002974*/
danielk19779f8d6402007-05-02 17:48:45 +00002975static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00002976 BtCursor *pCur, /* Cursor pointing to entry to read from */
2977 int offset, /* Begin reading this far into payload */
2978 int amt, /* Read this many bytes */
2979 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00002980 int skipKey, /* offset begins at data if this is true */
2981 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00002982){
2983 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00002984 int rc = SQLITE_OK;
drhfa1a98a2004-05-14 19:08:17 +00002985 u32 nKey;
danielk19772dec9702007-05-02 16:48:37 +00002986 int iIdx = 0;
drhd0679ed2007-08-28 22:24:34 +00002987 MemPage *pPage = pCur->pPage; /* Btree page of current cursor entry */
2988 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
drh3aac2dd2004-04-26 14:10:20 +00002989
danielk1977da107192007-05-04 08:32:13 +00002990 assert( pPage );
danielk1977da184232006-01-05 11:34:32 +00002991 assert( pCur->eState==CURSOR_VALID );
drh3aac2dd2004-04-26 14:10:20 +00002992 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
danielk1977da107192007-05-04 08:32:13 +00002993 assert( offset>=0 );
drh1fee73e2007-08-29 04:00:57 +00002994 assert( cursorHoldsMutex(pCur) );
danielk1977da107192007-05-04 08:32:13 +00002995
drh86057612007-06-26 01:04:48 +00002996 getCellInfo(pCur);
drh366fda62006-01-13 02:35:09 +00002997 aPayload = pCur->info.pCell + pCur->info.nHeader;
danielk1977da107192007-05-04 08:32:13 +00002998 nKey = (pPage->intKey ? 0 : pCur->info.nKey);
2999
drh3aac2dd2004-04-26 14:10:20 +00003000 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003001 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00003002 }
drhfa1a98a2004-05-14 19:08:17 +00003003 if( offset+amt > nKey+pCur->info.nData ){
danielk1977da107192007-05-04 08:32:13 +00003004 /* Trying to read or write past the end of the data is an error */
drha34b6762004-05-07 13:30:42 +00003005 return SQLITE_ERROR;
drh3aac2dd2004-04-26 14:10:20 +00003006 }
danielk1977da107192007-05-04 08:32:13 +00003007
3008 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00003009 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00003010 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00003011 if( a+offset>pCur->info.nLocal ){
3012 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00003013 }
danielk1977da107192007-05-04 08:32:13 +00003014 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00003015 offset = 0;
drha34b6762004-05-07 13:30:42 +00003016 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00003017 amt -= a;
drhdd793422001-06-28 01:54:48 +00003018 }else{
drhfa1a98a2004-05-14 19:08:17 +00003019 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00003020 }
danielk1977da107192007-05-04 08:32:13 +00003021
3022 if( rc==SQLITE_OK && amt>0 ){
3023 const int ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
3024 Pgno nextPage;
3025
drhfa1a98a2004-05-14 19:08:17 +00003026 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00003027
danielk19772dec9702007-05-02 16:48:37 +00003028#ifndef SQLITE_OMIT_INCRBLOB
danielk1977dcbb5d32007-05-04 18:36:44 +00003029 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
danielk1977da107192007-05-04 08:32:13 +00003030 ** has not been allocated, allocate it now. The array is sized at
3031 ** one entry for each overflow page in the overflow chain. The
3032 ** page number of the first overflow page is stored in aOverflow[0],
3033 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
3034 ** (the cache is lazily populated).
3035 */
danielk1977dcbb5d32007-05-04 18:36:44 +00003036 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
danielk19772dec9702007-05-02 16:48:37 +00003037 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
drh17435752007-08-16 04:30:38 +00003038 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
danielk19772dec9702007-05-02 16:48:37 +00003039 if( nOvfl && !pCur->aOverflow ){
danielk1977da107192007-05-04 08:32:13 +00003040 rc = SQLITE_NOMEM;
danielk19772dec9702007-05-02 16:48:37 +00003041 }
3042 }
danielk1977da107192007-05-04 08:32:13 +00003043
3044 /* If the overflow page-list cache has been allocated and the
3045 ** entry for the first required overflow page is valid, skip
3046 ** directly to it.
3047 */
danielk19772dec9702007-05-02 16:48:37 +00003048 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
3049 iIdx = (offset/ovflSize);
3050 nextPage = pCur->aOverflow[iIdx];
3051 offset = (offset%ovflSize);
3052 }
3053#endif
danielk1977da107192007-05-04 08:32:13 +00003054
3055 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
3056
3057#ifndef SQLITE_OMIT_INCRBLOB
3058 /* If required, populate the overflow page-list cache. */
3059 if( pCur->aOverflow ){
3060 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
3061 pCur->aOverflow[iIdx] = nextPage;
3062 }
3063#endif
3064
danielk1977d04417962007-05-02 13:16:30 +00003065 if( offset>=ovflSize ){
3066 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00003067 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00003068 ** data is not required. So first try to lookup the overflow
3069 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00003070 ** function.
danielk1977d04417962007-05-02 13:16:30 +00003071 */
danielk19772dec9702007-05-02 16:48:37 +00003072#ifndef SQLITE_OMIT_INCRBLOB
danielk1977da107192007-05-04 08:32:13 +00003073 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
3074 nextPage = pCur->aOverflow[iIdx+1];
3075 } else
danielk19772dec9702007-05-02 16:48:37 +00003076#endif
danielk1977da107192007-05-04 08:32:13 +00003077 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
danielk1977da107192007-05-04 08:32:13 +00003078 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00003079 }else{
danielk19779f8d6402007-05-02 17:48:45 +00003080 /* Need to read this page properly. It contains some of the
3081 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00003082 */
3083 DbPage *pDbPage;
danielk1977cfe9a692004-06-16 12:00:29 +00003084 int a = amt;
danielk1977d04417962007-05-02 13:16:30 +00003085 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
danielk1977da107192007-05-04 08:32:13 +00003086 if( rc==SQLITE_OK ){
3087 aPayload = sqlite3PagerGetData(pDbPage);
3088 nextPage = get4byte(aPayload);
3089 if( a + offset > ovflSize ){
3090 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00003091 }
danielk1977da107192007-05-04 08:32:13 +00003092 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
3093 sqlite3PagerUnref(pDbPage);
3094 offset = 0;
3095 amt -= a;
3096 pBuf += a;
danielk19779f8d6402007-05-02 17:48:45 +00003097 }
danielk1977cfe9a692004-06-16 12:00:29 +00003098 }
drh2af926b2001-05-15 00:39:25 +00003099 }
drh2af926b2001-05-15 00:39:25 +00003100 }
danielk1977cfe9a692004-06-16 12:00:29 +00003101
danielk1977da107192007-05-04 08:32:13 +00003102 if( rc==SQLITE_OK && amt>0 ){
drh49285702005-09-17 15:20:26 +00003103 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00003104 }
danielk1977da107192007-05-04 08:32:13 +00003105 return rc;
drh2af926b2001-05-15 00:39:25 +00003106}
3107
drh72f82862001-05-24 21:06:34 +00003108/*
drh3aac2dd2004-04-26 14:10:20 +00003109** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003110** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003111** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00003112**
drh3aac2dd2004-04-26 14:10:20 +00003113** Return SQLITE_OK on success or an error code if anything goes
3114** wrong. An error is returned if "offset+amt" is larger than
3115** the available payload.
drh72f82862001-05-24 21:06:34 +00003116*/
drha34b6762004-05-07 13:30:42 +00003117int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003118 int rc;
3119
drh1fee73e2007-08-29 04:00:57 +00003120 assert( cursorHoldsMutex(pCur) );
drhd677b3d2007-08-20 22:48:41 +00003121 rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003122 if( rc==SQLITE_OK ){
3123 assert( pCur->eState==CURSOR_VALID );
3124 assert( pCur->pPage!=0 );
3125 if( pCur->pPage->intKey ){
3126 return SQLITE_CORRUPT_BKPT;
3127 }
3128 assert( pCur->pPage->intKey==0 );
3129 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh16a9b832007-05-05 18:39:25 +00003130 rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
drh6575a222005-03-10 17:06:34 +00003131 }
danielk1977da184232006-01-05 11:34:32 +00003132 return rc;
drh3aac2dd2004-04-26 14:10:20 +00003133}
3134
3135/*
drh3aac2dd2004-04-26 14:10:20 +00003136** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003137** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003138** begins at "offset".
3139**
3140** Return SQLITE_OK on success or an error code if anything goes
3141** wrong. An error is returned if "offset+amt" is larger than
3142** the available payload.
drh72f82862001-05-24 21:06:34 +00003143*/
drh3aac2dd2004-04-26 14:10:20 +00003144int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003145 int rc;
3146
drh1fee73e2007-08-29 04:00:57 +00003147 assert( cursorHoldsMutex(pCur) );
drhd677b3d2007-08-20 22:48:41 +00003148 rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003149 if( rc==SQLITE_OK ){
3150 assert( pCur->eState==CURSOR_VALID );
3151 assert( pCur->pPage!=0 );
3152 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh16a9b832007-05-05 18:39:25 +00003153 rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
danielk1977da184232006-01-05 11:34:32 +00003154 }
3155 return rc;
drh2af926b2001-05-15 00:39:25 +00003156}
3157
drh72f82862001-05-24 21:06:34 +00003158/*
drh0e1c19e2004-05-11 00:58:56 +00003159** Return a pointer to payload information from the entry that the
3160** pCur cursor is pointing to. The pointer is to the beginning of
3161** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00003162** skipKey==1. The number of bytes of available key/data is written
3163** into *pAmt. If *pAmt==0, then the value returned will not be
3164** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00003165**
3166** This routine is an optimization. It is common for the entire key
3167** and data to fit on the local page and for there to be no overflow
3168** pages. When that is so, this routine can be used to access the
3169** key and data without making a copy. If the key and/or data spills
drh16a9b832007-05-05 18:39:25 +00003170** onto overflow pages, then accessPayload() must be used to reassembly
drh0e1c19e2004-05-11 00:58:56 +00003171** the key/data and copy it into a preallocated buffer.
3172**
3173** The pointer returned by this routine looks directly into the cached
3174** page of the database. The data might change or move the next time
3175** any btree routine is called.
3176*/
3177static const unsigned char *fetchPayload(
3178 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00003179 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00003180 int skipKey /* read beginning at data if this is true */
3181){
3182 unsigned char *aPayload;
3183 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00003184 u32 nKey;
3185 int nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003186
3187 assert( pCur!=0 && pCur->pPage!=0 );
danielk1977da184232006-01-05 11:34:32 +00003188 assert( pCur->eState==CURSOR_VALID );
drh1fee73e2007-08-29 04:00:57 +00003189 assert( cursorHoldsMutex(pCur) );
drh0e1c19e2004-05-11 00:58:56 +00003190 pPage = pCur->pPage;
drh0e1c19e2004-05-11 00:58:56 +00003191 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh86057612007-06-26 01:04:48 +00003192 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00003193 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00003194 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00003195 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00003196 nKey = 0;
3197 }else{
3198 nKey = pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00003199 }
drh0e1c19e2004-05-11 00:58:56 +00003200 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003201 aPayload += nKey;
3202 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00003203 }else{
drhfa1a98a2004-05-14 19:08:17 +00003204 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00003205 if( nLocal>nKey ){
3206 nLocal = nKey;
3207 }
drh0e1c19e2004-05-11 00:58:56 +00003208 }
drhe51c44f2004-05-30 20:46:09 +00003209 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003210 return aPayload;
3211}
3212
3213
3214/*
drhe51c44f2004-05-30 20:46:09 +00003215** For the entry that cursor pCur is point to, return as
3216** many bytes of the key or data as are available on the local
3217** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00003218**
3219** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00003220** or be destroyed on the next call to any Btree routine,
3221** including calls from other threads against the same cache.
3222** Hence, a mutex on the BtShared should be held prior to calling
3223** this routine.
drh0e1c19e2004-05-11 00:58:56 +00003224**
3225** These routines is used to get quick access to key and data
3226** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00003227*/
drhe51c44f2004-05-30 20:46:09 +00003228const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
drh1fee73e2007-08-29 04:00:57 +00003229 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003230 if( pCur->eState==CURSOR_VALID ){
3231 return (const void*)fetchPayload(pCur, pAmt, 0);
3232 }
3233 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003234}
drhe51c44f2004-05-30 20:46:09 +00003235const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
drh1fee73e2007-08-29 04:00:57 +00003236 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003237 if( pCur->eState==CURSOR_VALID ){
3238 return (const void*)fetchPayload(pCur, pAmt, 1);
3239 }
3240 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003241}
3242
3243
3244/*
drh8178a752003-01-05 21:41:40 +00003245** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00003246** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00003247*/
drh3aac2dd2004-04-26 14:10:20 +00003248static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00003249 int rc;
3250 MemPage *pNewPage;
drh3aac2dd2004-04-26 14:10:20 +00003251 MemPage *pOldPage;
drhd0679ed2007-08-28 22:24:34 +00003252 BtShared *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00003253
drh1fee73e2007-08-29 04:00:57 +00003254 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003255 assert( pCur->eState==CURSOR_VALID );
drhde647132004-05-07 17:57:49 +00003256 rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00003257 if( rc ) return rc;
drh428ae8c2003-01-04 16:48:09 +00003258 pNewPage->idxParent = pCur->idx;
drh3aac2dd2004-04-26 14:10:20 +00003259 pOldPage = pCur->pPage;
3260 pOldPage->idxShift = 0;
3261 releasePage(pOldPage);
drh72f82862001-05-24 21:06:34 +00003262 pCur->pPage = pNewPage;
3263 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00003264 pCur->info.nSize = 0;
drh4be295b2003-12-16 03:44:47 +00003265 if( pNewPage->nCell<1 ){
drh49285702005-09-17 15:20:26 +00003266 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00003267 }
drh72f82862001-05-24 21:06:34 +00003268 return SQLITE_OK;
3269}
3270
3271/*
drh8856d6a2004-04-29 14:42:46 +00003272** Return true if the page is the virtual root of its table.
3273**
3274** The virtual root page is the root page for most tables. But
3275** for the table rooted on page 1, sometime the real root page
3276** is empty except for the right-pointer. In such cases the
3277** virtual root page is the page that the right-pointer of page
3278** 1 is pointing to.
3279*/
drh16a9b832007-05-05 18:39:25 +00003280int sqlite3BtreeIsRootPage(MemPage *pPage){
drhd677b3d2007-08-20 22:48:41 +00003281 MemPage *pParent;
3282
drh1fee73e2007-08-29 04:00:57 +00003283 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00003284 pParent = pPage->pParent;
drhda200cc2004-05-09 11:51:38 +00003285 if( pParent==0 ) return 1;
3286 if( pParent->pgno>1 ) return 0;
3287 if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
drh8856d6a2004-04-29 14:42:46 +00003288 return 0;
3289}
3290
3291/*
drh5e2f8b92001-05-28 00:41:15 +00003292** Move the cursor up to the parent page.
3293**
3294** pCur->idx is set to the cell index that contains the pointer
3295** to the page we are coming from. If we are coming from the
3296** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00003297** the largest cell index.
drh72f82862001-05-24 21:06:34 +00003298*/
drh16a9b832007-05-05 18:39:25 +00003299void sqlite3BtreeMoveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00003300 MemPage *pParent;
drh8178a752003-01-05 21:41:40 +00003301 MemPage *pPage;
drh428ae8c2003-01-04 16:48:09 +00003302 int idxParent;
drh3aac2dd2004-04-26 14:10:20 +00003303
drh1fee73e2007-08-29 04:00:57 +00003304 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003305 assert( pCur->eState==CURSOR_VALID );
drh8178a752003-01-05 21:41:40 +00003306 pPage = pCur->pPage;
3307 assert( pPage!=0 );
drh16a9b832007-05-05 18:39:25 +00003308 assert( !sqlite3BtreeIsRootPage(pPage) );
drh8178a752003-01-05 21:41:40 +00003309 pParent = pPage->pParent;
3310 assert( pParent!=0 );
3311 idxParent = pPage->idxParent;
danielk19773b8a05f2007-03-19 17:44:26 +00003312 sqlite3PagerRef(pParent->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00003313 releasePage(pPage);
drh72f82862001-05-24 21:06:34 +00003314 pCur->pPage = pParent;
drh271efa52004-05-30 19:19:05 +00003315 pCur->info.nSize = 0;
drh428ae8c2003-01-04 16:48:09 +00003316 assert( pParent->idxShift==0 );
drh43605152004-05-29 21:46:49 +00003317 pCur->idx = idxParent;
drh72f82862001-05-24 21:06:34 +00003318}
3319
3320/*
3321** Move the cursor to the root page
3322*/
drh5e2f8b92001-05-28 00:41:15 +00003323static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00003324 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00003325 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003326 Btree *p = pCur->pBtree;
3327 BtShared *pBt = p->pBt;
drhbd03cae2001-06-02 02:40:57 +00003328
drh1fee73e2007-08-29 04:00:57 +00003329 assert( cursorHoldsMutex(pCur) );
drhbf700f32007-03-31 02:36:44 +00003330 if( pCur->eState==CURSOR_REQUIRESEEK ){
3331 clearCursorPosition(pCur);
3332 }
drh777e4c42006-01-13 04:31:58 +00003333 pRoot = pCur->pPage;
danielk197797a227c2006-01-20 16:32:04 +00003334 if( pRoot && pRoot->pgno==pCur->pgnoRoot ){
drh777e4c42006-01-13 04:31:58 +00003335 assert( pRoot->isInit );
3336 }else{
3337 if(
3338 SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0))
3339 ){
3340 pCur->eState = CURSOR_INVALID;
3341 return rc;
3342 }
3343 releasePage(pCur->pPage);
drh777e4c42006-01-13 04:31:58 +00003344 pCur->pPage = pRoot;
drhc39e0002004-05-07 23:50:57 +00003345 }
drh72f82862001-05-24 21:06:34 +00003346 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00003347 pCur->info.nSize = 0;
drh8856d6a2004-04-29 14:42:46 +00003348 if( pRoot->nCell==0 && !pRoot->leaf ){
3349 Pgno subpage;
3350 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00003351 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00003352 assert( subpage>0 );
danielk1977da184232006-01-05 11:34:32 +00003353 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00003354 rc = moveToChild(pCur, subpage);
drh8856d6a2004-04-29 14:42:46 +00003355 }
danielk1977da184232006-01-05 11:34:32 +00003356 pCur->eState = ((pCur->pPage->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
drh8856d6a2004-04-29 14:42:46 +00003357 return rc;
drh72f82862001-05-24 21:06:34 +00003358}
drh2af926b2001-05-15 00:39:25 +00003359
drh5e2f8b92001-05-28 00:41:15 +00003360/*
3361** Move the cursor down to the left-most leaf entry beneath the
3362** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00003363**
3364** The left-most leaf is the one with the smallest key - the first
3365** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00003366*/
3367static int moveToLeftmost(BtCursor *pCur){
3368 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00003369 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00003370 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00003371
drh1fee73e2007-08-29 04:00:57 +00003372 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003373 assert( pCur->eState==CURSOR_VALID );
drhd677b3d2007-08-20 22:48:41 +00003374 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
drha34b6762004-05-07 13:30:42 +00003375 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
danielk19771cc5ed82007-05-16 17:28:43 +00003376 pgno = get4byte(findCell(pPage, pCur->idx));
drh8178a752003-01-05 21:41:40 +00003377 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00003378 }
drhd677b3d2007-08-20 22:48:41 +00003379 return rc;
drh5e2f8b92001-05-28 00:41:15 +00003380}
3381
drh2dcc9aa2002-12-04 13:40:25 +00003382/*
3383** Move the cursor down to the right-most leaf entry beneath the
3384** page to which it is currently pointing. Notice the difference
3385** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
3386** finds the left-most entry beneath the *entry* whereas moveToRightmost()
3387** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00003388**
3389** The right-most entry is the one with the largest key - the last
3390** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00003391*/
3392static int moveToRightmost(BtCursor *pCur){
3393 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00003394 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00003395 MemPage *pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003396
drh1fee73e2007-08-29 04:00:57 +00003397 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003398 assert( pCur->eState==CURSOR_VALID );
drhd677b3d2007-08-20 22:48:41 +00003399 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
drh43605152004-05-29 21:46:49 +00003400 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh3aac2dd2004-04-26 14:10:20 +00003401 pCur->idx = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00003402 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003403 }
drhd677b3d2007-08-20 22:48:41 +00003404 if( rc==SQLITE_OK ){
3405 pCur->idx = pPage->nCell - 1;
3406 pCur->info.nSize = 0;
3407 }
drh2dcc9aa2002-12-04 13:40:25 +00003408 return SQLITE_OK;
3409}
3410
drh5e00f6c2001-09-13 13:46:56 +00003411/* Move the cursor to the first entry in the table. Return SQLITE_OK
3412** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003413** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00003414*/
drh3aac2dd2004-04-26 14:10:20 +00003415int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00003416 int rc;
drhd677b3d2007-08-20 22:48:41 +00003417
drh1fee73e2007-08-29 04:00:57 +00003418 assert( cursorHoldsMutex(pCur) );
3419 assert( sqlite3_mutex_held(pCur->pBtree->pSqlite->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00003420 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003421 if( rc==SQLITE_OK ){
3422 if( pCur->eState==CURSOR_INVALID ){
3423 assert( pCur->pPage->nCell==0 );
3424 *pRes = 1;
3425 rc = SQLITE_OK;
3426 }else{
3427 assert( pCur->pPage->nCell>0 );
3428 *pRes = 0;
3429 rc = moveToLeftmost(pCur);
3430 }
drh5e00f6c2001-09-13 13:46:56 +00003431 }
drh5e00f6c2001-09-13 13:46:56 +00003432 return rc;
3433}
drh5e2f8b92001-05-28 00:41:15 +00003434
drh9562b552002-02-19 15:00:07 +00003435/* Move the cursor to the last entry in the table. Return SQLITE_OK
3436** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003437** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00003438*/
drh3aac2dd2004-04-26 14:10:20 +00003439int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00003440 int rc;
drhd677b3d2007-08-20 22:48:41 +00003441
drh1fee73e2007-08-29 04:00:57 +00003442 assert( cursorHoldsMutex(pCur) );
3443 assert( sqlite3_mutex_held(pCur->pBtree->pSqlite->mutex) );
drh9562b552002-02-19 15:00:07 +00003444 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003445 if( rc==SQLITE_OK ){
3446 if( CURSOR_INVALID==pCur->eState ){
3447 assert( pCur->pPage->nCell==0 );
3448 *pRes = 1;
3449 }else{
3450 assert( pCur->eState==CURSOR_VALID );
3451 *pRes = 0;
3452 rc = moveToRightmost(pCur);
3453 }
drh9562b552002-02-19 15:00:07 +00003454 }
drh9562b552002-02-19 15:00:07 +00003455 return rc;
3456}
3457
drh3aac2dd2004-04-26 14:10:20 +00003458/* Move the cursor so that it points to an entry near pKey/nKey.
drh72f82862001-05-24 21:06:34 +00003459** Return a success code.
3460**
drh3aac2dd2004-04-26 14:10:20 +00003461** For INTKEY tables, only the nKey parameter is used. pKey is
3462** ignored. For other tables, nKey is the number of bytes of data
drh0b2f3162005-12-21 18:36:45 +00003463** in pKey. The comparison function specified when the cursor was
drh3aac2dd2004-04-26 14:10:20 +00003464** created is used to compare keys.
3465**
drh5e2f8b92001-05-28 00:41:15 +00003466** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00003467** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00003468** were present. The cursor might point to an entry that comes
3469** before or after the key.
3470**
drhbd03cae2001-06-02 02:40:57 +00003471** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00003472** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00003473** this value is as follows:
3474**
3475** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00003476** is smaller than pKey or if the table is empty
3477** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00003478**
3479** *pRes==0 The cursor is left pointing at an entry that
3480** exactly matches pKey.
3481**
3482** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00003483** is larger than pKey.
drhd677b3d2007-08-20 22:48:41 +00003484**
drha059ad02001-04-17 20:09:11 +00003485*/
drhe4d90812007-03-29 05:51:49 +00003486int sqlite3BtreeMoveto(
3487 BtCursor *pCur, /* The cursor to be moved */
3488 const void *pKey, /* The key content for indices. Not used by tables */
3489 i64 nKey, /* Size of pKey. Or the key for tables */
3490 int biasRight, /* If true, bias the search to the high end */
3491 int *pRes /* Search result flag */
3492){
drh72f82862001-05-24 21:06:34 +00003493 int rc;
drhd677b3d2007-08-20 22:48:41 +00003494
drh1fee73e2007-08-29 04:00:57 +00003495 assert( cursorHoldsMutex(pCur) );
3496 assert( sqlite3_mutex_held(pCur->pBtree->pSqlite->mutex) );
drh5e2f8b92001-05-28 00:41:15 +00003497 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003498 if( rc ){
3499 return rc;
3500 }
drhc39e0002004-05-07 23:50:57 +00003501 assert( pCur->pPage );
3502 assert( pCur->pPage->isInit );
danielk1977da184232006-01-05 11:34:32 +00003503 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00003504 *pRes = -1;
drhc39e0002004-05-07 23:50:57 +00003505 assert( pCur->pPage->nCell==0 );
3506 return SQLITE_OK;
3507 }
drh14684382006-11-30 13:05:29 +00003508 for(;;){
drh72f82862001-05-24 21:06:34 +00003509 int lwr, upr;
3510 Pgno chldPg;
3511 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00003512 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00003513 lwr = 0;
3514 upr = pPage->nCell-1;
drh4eec4c12005-01-21 00:22:37 +00003515 if( !pPage->intKey && pKey==0 ){
drh49285702005-09-17 15:20:26 +00003516 return SQLITE_CORRUPT_BKPT;
drh4eec4c12005-01-21 00:22:37 +00003517 }
drhe4d90812007-03-29 05:51:49 +00003518 if( biasRight ){
3519 pCur->idx = upr;
3520 }else{
3521 pCur->idx = (upr+lwr)/2;
3522 }
drhf1d68b32007-03-29 04:43:26 +00003523 if( lwr<=upr ) for(;;){
danielk197713adf8a2004-06-03 16:08:41 +00003524 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00003525 i64 nCellKey;
drh366fda62006-01-13 02:35:09 +00003526 pCur->info.nSize = 0;
drh3aac2dd2004-04-26 14:10:20 +00003527 if( pPage->intKey ){
drh777e4c42006-01-13 04:31:58 +00003528 u8 *pCell;
danielk19771cc5ed82007-05-16 17:28:43 +00003529 pCell = findCell(pPage, pCur->idx) + pPage->childPtrSize;
drhd172f862006-01-12 15:01:15 +00003530 if( pPage->hasData ){
danielk1977bab45c62006-01-16 15:14:27 +00003531 u32 dummy;
drhd172f862006-01-12 15:01:15 +00003532 pCell += getVarint32(pCell, &dummy);
3533 }
danielk1977bab45c62006-01-16 15:14:27 +00003534 getVarint(pCell, (u64 *)&nCellKey);
drh3aac2dd2004-04-26 14:10:20 +00003535 if( nCellKey<nKey ){
3536 c = -1;
3537 }else if( nCellKey>nKey ){
3538 c = +1;
3539 }else{
3540 c = 0;
3541 }
drh3aac2dd2004-04-26 14:10:20 +00003542 }else{
drhe51c44f2004-05-30 20:46:09 +00003543 int available;
danielk197713adf8a2004-06-03 16:08:41 +00003544 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drh366fda62006-01-13 02:35:09 +00003545 nCellKey = pCur->info.nKey;
drhe51c44f2004-05-30 20:46:09 +00003546 if( available>=nCellKey ){
3547 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
3548 }else{
drh17435752007-08-16 04:30:38 +00003549 pCellKey = sqlite3_malloc( nCellKey );
drhe51c44f2004-05-30 20:46:09 +00003550 if( pCellKey==0 ) return SQLITE_NOMEM;
danielk197713adf8a2004-06-03 16:08:41 +00003551 rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
drhe51c44f2004-05-30 20:46:09 +00003552 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
drh17435752007-08-16 04:30:38 +00003553 sqlite3_free(pCellKey);
drhd677b3d2007-08-20 22:48:41 +00003554 if( rc ){
3555 return rc;
3556 }
drhe51c44f2004-05-30 20:46:09 +00003557 }
drh3aac2dd2004-04-26 14:10:20 +00003558 }
drh72f82862001-05-24 21:06:34 +00003559 if( c==0 ){
drh8b18dd42004-05-12 19:18:15 +00003560 if( pPage->leafData && !pPage->leaf ){
drhfc70e6f2004-05-12 21:11:27 +00003561 lwr = pCur->idx;
3562 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00003563 break;
3564 }else{
drh8b18dd42004-05-12 19:18:15 +00003565 if( pRes ) *pRes = 0;
3566 return SQLITE_OK;
3567 }
drh72f82862001-05-24 21:06:34 +00003568 }
3569 if( c<0 ){
3570 lwr = pCur->idx+1;
3571 }else{
3572 upr = pCur->idx-1;
3573 }
drhf1d68b32007-03-29 04:43:26 +00003574 if( lwr>upr ){
3575 break;
3576 }
3577 pCur->idx = (lwr+upr)/2;
drh72f82862001-05-24 21:06:34 +00003578 }
3579 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00003580 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00003581 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00003582 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00003583 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00003584 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00003585 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00003586 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00003587 }
3588 if( chldPg==0 ){
drhc39e0002004-05-07 23:50:57 +00003589 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00003590 if( pRes ) *pRes = c;
3591 return SQLITE_OK;
3592 }
drh428ae8c2003-01-04 16:48:09 +00003593 pCur->idx = lwr;
drh271efa52004-05-30 19:19:05 +00003594 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00003595 rc = moveToChild(pCur, chldPg);
drhc39e0002004-05-07 23:50:57 +00003596 if( rc ){
3597 return rc;
3598 }
drh72f82862001-05-24 21:06:34 +00003599 }
drhbd03cae2001-06-02 02:40:57 +00003600 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00003601}
3602
drhd677b3d2007-08-20 22:48:41 +00003603
drh72f82862001-05-24 21:06:34 +00003604/*
drhc39e0002004-05-07 23:50:57 +00003605** Return TRUE if the cursor is not pointing at an entry of the table.
3606**
3607** TRUE will be returned after a call to sqlite3BtreeNext() moves
3608** past the last entry in the table or sqlite3BtreePrev() moves past
3609** the first entry. TRUE is also returned if the table is empty.
3610*/
3611int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00003612 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
3613 ** have been deleted? This API will need to change to return an error code
3614 ** as well as the boolean result value.
3615 */
3616 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00003617}
3618
3619/*
drhb21c8cd2007-08-21 19:33:56 +00003620** Return the database connection handle for a cursor.
3621*/
3622sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){
drhd0679ed2007-08-28 22:24:34 +00003623 assert( sqlite3_mutex_held(pCur->pBtree->pSqlite->mutex) );
drhb21c8cd2007-08-21 19:33:56 +00003624 return pCur->pBtree->pSqlite;
3625}
3626
3627/*
drhbd03cae2001-06-02 02:40:57 +00003628** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00003629** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00003630** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00003631** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00003632*/
drhd677b3d2007-08-20 22:48:41 +00003633static int btreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00003634 int rc;
danielk197797a227c2006-01-20 16:32:04 +00003635 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00003636
drh1fee73e2007-08-29 04:00:57 +00003637 assert( cursorHoldsMutex(pCur) );
drhbf700f32007-03-31 02:36:44 +00003638 rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003639 if( rc!=SQLITE_OK ){
3640 return rc;
3641 }
drh8c4d3a62007-04-06 01:03:32 +00003642 assert( pRes!=0 );
3643 pPage = pCur->pPage;
3644 if( CURSOR_INVALID==pCur->eState ){
3645 *pRes = 1;
3646 return SQLITE_OK;
3647 }
danielk1977da184232006-01-05 11:34:32 +00003648 if( pCur->skip>0 ){
3649 pCur->skip = 0;
3650 *pRes = 0;
3651 return SQLITE_OK;
3652 }
3653 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00003654
drh8178a752003-01-05 21:41:40 +00003655 assert( pPage->isInit );
drh8178a752003-01-05 21:41:40 +00003656 assert( pCur->idx<pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00003657
drh72f82862001-05-24 21:06:34 +00003658 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00003659 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00003660 if( pCur->idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00003661 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003662 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00003663 if( rc ) return rc;
3664 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003665 *pRes = 0;
3666 return rc;
drh72f82862001-05-24 21:06:34 +00003667 }
drh5e2f8b92001-05-28 00:41:15 +00003668 do{
drh16a9b832007-05-05 18:39:25 +00003669 if( sqlite3BtreeIsRootPage(pPage) ){
drh8c1238a2003-01-02 14:43:55 +00003670 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00003671 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00003672 return SQLITE_OK;
3673 }
drh16a9b832007-05-05 18:39:25 +00003674 sqlite3BtreeMoveToParent(pCur);
drh8178a752003-01-05 21:41:40 +00003675 pPage = pCur->pPage;
3676 }while( pCur->idx>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00003677 *pRes = 0;
drh8b18dd42004-05-12 19:18:15 +00003678 if( pPage->leafData ){
3679 rc = sqlite3BtreeNext(pCur, pRes);
3680 }else{
3681 rc = SQLITE_OK;
3682 }
3683 return rc;
drh8178a752003-01-05 21:41:40 +00003684 }
3685 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00003686 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00003687 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00003688 }
drh5e2f8b92001-05-28 00:41:15 +00003689 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003690 return rc;
drh72f82862001-05-24 21:06:34 +00003691}
drhd677b3d2007-08-20 22:48:41 +00003692int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
3693 int rc;
drh1fee73e2007-08-29 04:00:57 +00003694 assert( cursorHoldsMutex(pCur) );
drhd677b3d2007-08-20 22:48:41 +00003695 rc = btreeNext(pCur, pRes);
drhd677b3d2007-08-20 22:48:41 +00003696 return rc;
3697}
3698
drh72f82862001-05-24 21:06:34 +00003699
drh3b7511c2001-05-26 13:15:44 +00003700/*
drh2dcc9aa2002-12-04 13:40:25 +00003701** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00003702** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00003703** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00003704** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00003705*/
drhd677b3d2007-08-20 22:48:41 +00003706static int btreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00003707 int rc;
3708 Pgno pgno;
drh8178a752003-01-05 21:41:40 +00003709 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00003710
drh1fee73e2007-08-29 04:00:57 +00003711 assert( cursorHoldsMutex(pCur) );
drhbf700f32007-03-31 02:36:44 +00003712 rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003713 if( rc!=SQLITE_OK ){
3714 return rc;
3715 }
drh8c4d3a62007-04-06 01:03:32 +00003716 if( CURSOR_INVALID==pCur->eState ){
3717 *pRes = 1;
3718 return SQLITE_OK;
3719 }
danielk1977da184232006-01-05 11:34:32 +00003720 if( pCur->skip<0 ){
3721 pCur->skip = 0;
3722 *pRes = 0;
3723 return SQLITE_OK;
3724 }
3725 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00003726
drh8178a752003-01-05 21:41:40 +00003727 pPage = pCur->pPage;
drh8178a752003-01-05 21:41:40 +00003728 assert( pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00003729 assert( pCur->idx>=0 );
drha34b6762004-05-07 13:30:42 +00003730 if( !pPage->leaf ){
danielk19771cc5ed82007-05-16 17:28:43 +00003731 pgno = get4byte( findCell(pPage, pCur->idx) );
drh8178a752003-01-05 21:41:40 +00003732 rc = moveToChild(pCur, pgno);
drhd677b3d2007-08-20 22:48:41 +00003733 if( rc ){
3734 return rc;
3735 }
drh2dcc9aa2002-12-04 13:40:25 +00003736 rc = moveToRightmost(pCur);
3737 }else{
3738 while( pCur->idx==0 ){
drh16a9b832007-05-05 18:39:25 +00003739 if( sqlite3BtreeIsRootPage(pPage) ){
danielk1977da184232006-01-05 11:34:32 +00003740 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00003741 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00003742 return SQLITE_OK;
3743 }
drh16a9b832007-05-05 18:39:25 +00003744 sqlite3BtreeMoveToParent(pCur);
drh8178a752003-01-05 21:41:40 +00003745 pPage = pCur->pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003746 }
3747 pCur->idx--;
drh271efa52004-05-30 19:19:05 +00003748 pCur->info.nSize = 0;
drh8237d452004-11-22 19:07:09 +00003749 if( pPage->leafData && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00003750 rc = sqlite3BtreePrevious(pCur, pRes);
3751 }else{
3752 rc = SQLITE_OK;
3753 }
drh2dcc9aa2002-12-04 13:40:25 +00003754 }
drh8178a752003-01-05 21:41:40 +00003755 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003756 return rc;
3757}
drhd677b3d2007-08-20 22:48:41 +00003758int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
3759 int rc;
drh1fee73e2007-08-29 04:00:57 +00003760 assert( cursorHoldsMutex(pCur) );
drhd677b3d2007-08-20 22:48:41 +00003761 rc = btreePrevious(pCur, pRes);
drhd677b3d2007-08-20 22:48:41 +00003762 return rc;
3763}
drh2dcc9aa2002-12-04 13:40:25 +00003764
3765/*
drh3b7511c2001-05-26 13:15:44 +00003766** Allocate a new page from the database file.
3767**
danielk19773b8a05f2007-03-19 17:44:26 +00003768** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00003769** has already been called on the new page.) The new page has also
3770** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00003771** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00003772**
3773** SQLITE_OK is returned on success. Any other return value indicates
3774** an error. *ppPage and *pPgno are undefined in the event of an error.
danielk19773b8a05f2007-03-19 17:44:26 +00003775** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00003776**
drh199e3cf2002-07-18 11:01:47 +00003777** If the "nearby" parameter is not 0, then a (feeble) effort is made to
3778** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00003779** attempt to keep related pages close to each other in the database file,
3780** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00003781**
3782** If the "exact" parameter is not 0, and the page-number nearby exists
3783** anywhere on the free-list, then it is guarenteed to be returned. This
3784** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00003785*/
drh4f0c5872007-03-26 22:05:01 +00003786static int allocateBtreePage(
danielk1977aef0bf62005-12-30 16:28:01 +00003787 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00003788 MemPage **ppPage,
3789 Pgno *pPgno,
3790 Pgno nearby,
3791 u8 exact
3792){
drh3aac2dd2004-04-26 14:10:20 +00003793 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00003794 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003795 int n; /* Number of pages on the freelist */
3796 int k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00003797 MemPage *pTrunk = 0;
3798 MemPage *pPrevTrunk = 0;
drh30e58752002-03-02 20:41:57 +00003799
drh1fee73e2007-08-29 04:00:57 +00003800 assert( sqlite3_mutex_held(pBt->mutex) );
drh3aac2dd2004-04-26 14:10:20 +00003801 pPage1 = pBt->pPage1;
3802 n = get4byte(&pPage1->aData[36]);
3803 if( n>0 ){
drh91025292004-05-03 19:49:32 +00003804 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00003805 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003806 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
3807
3808 /* If the 'exact' parameter was true and a query of the pointer-map
3809 ** shows that the page 'nearby' is somewhere on the free-list, then
3810 ** the entire-list will be searched for that page.
3811 */
3812#ifndef SQLITE_OMIT_AUTOVACUUM
danielk19774ef24492007-05-23 09:52:41 +00003813 if( exact && nearby<=sqlite3PagerPagecount(pBt->pPager) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00003814 u8 eType;
3815 assert( nearby>0 );
3816 assert( pBt->autoVacuum );
3817 rc = ptrmapGet(pBt, nearby, &eType, 0);
3818 if( rc ) return rc;
3819 if( eType==PTRMAP_FREEPAGE ){
3820 searchList = 1;
3821 }
3822 *pPgno = nearby;
3823 }
3824#endif
3825
3826 /* Decrement the free-list count by 1. Set iTrunk to the index of the
3827 ** first free-list trunk page. iPrevTrunk is initially 1.
3828 */
danielk19773b8a05f2007-03-19 17:44:26 +00003829 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00003830 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003831 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003832
3833 /* The code within this loop is run only once if the 'searchList' variable
3834 ** is not true. Otherwise, it runs once for each trunk-page on the
3835 ** free-list until the page 'nearby' is located.
3836 */
3837 do {
3838 pPrevTrunk = pTrunk;
3839 if( pPrevTrunk ){
3840 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00003841 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00003842 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00003843 }
drh16a9b832007-05-05 18:39:25 +00003844 rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003845 if( rc ){
drhd3627af2006-12-18 18:34:51 +00003846 pTrunk = 0;
3847 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003848 }
3849
3850 k = get4byte(&pTrunk->aData[4]);
3851 if( k==0 && !searchList ){
3852 /* The trunk has no leaves and the list is not being searched.
3853 ** So extract the trunk page itself and use it as the newly
3854 ** allocated page */
3855 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00003856 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00003857 if( rc ){
3858 goto end_allocate_page;
3859 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003860 *pPgno = iTrunk;
3861 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3862 *ppPage = pTrunk;
3863 pTrunk = 0;
3864 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3865 }else if( k>pBt->usableSize/4 - 8 ){
3866 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00003867 rc = SQLITE_CORRUPT_BKPT;
3868 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003869#ifndef SQLITE_OMIT_AUTOVACUUM
3870 }else if( searchList && nearby==iTrunk ){
3871 /* The list is being searched and this trunk page is the page
3872 ** to allocate, regardless of whether it has leaves.
3873 */
3874 assert( *pPgno==iTrunk );
3875 *ppPage = pTrunk;
3876 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00003877 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00003878 if( rc ){
3879 goto end_allocate_page;
3880 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003881 if( k==0 ){
3882 if( !pPrevTrunk ){
3883 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3884 }else{
3885 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
3886 }
3887 }else{
3888 /* The trunk page is required by the caller but it contains
3889 ** pointers to free-list leaves. The first leaf becomes a trunk
3890 ** page in this case.
3891 */
3892 MemPage *pNewTrunk;
3893 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh16a9b832007-05-05 18:39:25 +00003894 rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003895 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00003896 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003897 }
danielk19773b8a05f2007-03-19 17:44:26 +00003898 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003899 if( rc!=SQLITE_OK ){
3900 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00003901 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003902 }
3903 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
3904 put4byte(&pNewTrunk->aData[4], k-1);
3905 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00003906 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003907 if( !pPrevTrunk ){
3908 put4byte(&pPage1->aData[32], iNewTrunk);
3909 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00003910 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00003911 if( rc ){
3912 goto end_allocate_page;
3913 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003914 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
3915 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003916 }
3917 pTrunk = 0;
3918 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3919#endif
3920 }else{
3921 /* Extract a leaf from the trunk */
3922 int closest;
3923 Pgno iPage;
3924 unsigned char *aData = pTrunk->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00003925 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00003926 if( rc ){
3927 goto end_allocate_page;
3928 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003929 if( nearby>0 ){
3930 int i, dist;
3931 closest = 0;
3932 dist = get4byte(&aData[8]) - nearby;
3933 if( dist<0 ) dist = -dist;
3934 for(i=1; i<k; i++){
3935 int d2 = get4byte(&aData[8+i*4]) - nearby;
3936 if( d2<0 ) d2 = -d2;
3937 if( d2<dist ){
3938 closest = i;
3939 dist = d2;
3940 }
3941 }
3942 }else{
3943 closest = 0;
3944 }
3945
3946 iPage = get4byte(&aData[8+closest*4]);
3947 if( !searchList || iPage==nearby ){
3948 *pPgno = iPage;
danielk19773b8a05f2007-03-19 17:44:26 +00003949 if( *pPgno>sqlite3PagerPagecount(pBt->pPager) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00003950 /* Free page off the end of the file */
drh49285702005-09-17 15:20:26 +00003951 return SQLITE_CORRUPT_BKPT;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003952 }
3953 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
3954 ": %d more free pages\n",
3955 *pPgno, closest+1, k, pTrunk->pgno, n-1));
3956 if( closest<k-1 ){
3957 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
3958 }
3959 put4byte(&aData[4], k-1);
drh16a9b832007-05-05 18:39:25 +00003960 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003961 if( rc==SQLITE_OK ){
drh538f5702007-04-13 02:14:30 +00003962 sqlite3PagerDontRollback((*ppPage)->pDbPage);
danielk19773b8a05f2007-03-19 17:44:26 +00003963 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00003964 if( rc!=SQLITE_OK ){
3965 releasePage(*ppPage);
3966 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003967 }
3968 searchList = 0;
3969 }
drhee696e22004-08-30 16:52:17 +00003970 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003971 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00003972 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003973 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00003974 }else{
drh3aac2dd2004-04-26 14:10:20 +00003975 /* There are no pages on the freelist, so create a new page at the
3976 ** end of the file */
danielk19773b8a05f2007-03-19 17:44:26 +00003977 *pPgno = sqlite3PagerPagecount(pBt->pPager) + 1;
danielk1977afcdd022004-10-31 16:25:42 +00003978
3979#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00003980 if( pBt->nTrunc ){
3981 /* An incr-vacuum has already run within this transaction. So the
3982 ** page to allocate is not from the physical end of the file, but
3983 ** at pBt->nTrunc.
3984 */
3985 *pPgno = pBt->nTrunc+1;
3986 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
3987 (*pPgno)++;
3988 }
3989 }
danielk1977266664d2006-02-10 08:24:21 +00003990 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00003991 /* If *pPgno refers to a pointer-map page, allocate two new pages
3992 ** at the end of the file instead of one. The first allocated page
3993 ** becomes a new pointer-map page, the second is used by the caller.
3994 */
3995 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00003996 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977afcdd022004-10-31 16:25:42 +00003997 (*pPgno)++;
3998 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003999 if( pBt->nTrunc ){
4000 pBt->nTrunc = *pPgno;
4001 }
danielk1977afcdd022004-10-31 16:25:42 +00004002#endif
4003
danielk1977599fcba2004-11-08 07:13:13 +00004004 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh16a9b832007-05-05 18:39:25 +00004005 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
drh3b7511c2001-05-26 13:15:44 +00004006 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00004007 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004008 if( rc!=SQLITE_OK ){
4009 releasePage(*ppPage);
4010 }
drh3a4c1412004-05-09 20:40:11 +00004011 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00004012 }
danielk1977599fcba2004-11-08 07:13:13 +00004013
4014 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00004015
4016end_allocate_page:
4017 releasePage(pTrunk);
4018 releasePage(pPrevTrunk);
drh3b7511c2001-05-26 13:15:44 +00004019 return rc;
4020}
4021
4022/*
drh3aac2dd2004-04-26 14:10:20 +00004023** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00004024**
danielk19773b8a05f2007-03-19 17:44:26 +00004025** sqlite3PagerUnref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00004026*/
drh3aac2dd2004-04-26 14:10:20 +00004027static int freePage(MemPage *pPage){
danielk1977aef0bf62005-12-30 16:28:01 +00004028 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00004029 MemPage *pPage1 = pBt->pPage1;
4030 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00004031
drh3aac2dd2004-04-26 14:10:20 +00004032 /* Prepare the page for freeing */
drh1fee73e2007-08-29 04:00:57 +00004033 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh3aac2dd2004-04-26 14:10:20 +00004034 assert( pPage->pgno>1 );
4035 pPage->isInit = 0;
4036 releasePage(pPage->pParent);
4037 pPage->pParent = 0;
4038
drha34b6762004-05-07 13:30:42 +00004039 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00004040 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00004041 if( rc ) return rc;
4042 n = get4byte(&pPage1->aData[36]);
4043 put4byte(&pPage1->aData[36], n+1);
4044
drhfcce93f2006-02-22 03:08:32 +00004045#ifdef SQLITE_SECURE_DELETE
4046 /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
4047 ** always fully overwrite deleted information with zeros.
4048 */
danielk19773b8a05f2007-03-19 17:44:26 +00004049 rc = sqlite3PagerWrite(pPage->pDbPage);
drhfcce93f2006-02-22 03:08:32 +00004050 if( rc ) return rc;
4051 memset(pPage->aData, 0, pPage->pBt->pageSize);
4052#endif
4053
danielk1977687566d2004-11-02 12:56:41 +00004054#ifndef SQLITE_OMIT_AUTOVACUUM
4055 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00004056 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00004057 */
4058 if( pBt->autoVacuum ){
4059 rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
danielk1977a64a0352004-11-05 01:45:13 +00004060 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00004061 }
4062#endif
4063
drh3aac2dd2004-04-26 14:10:20 +00004064 if( n==0 ){
4065 /* This is the first free page */
danielk19773b8a05f2007-03-19 17:44:26 +00004066 rc = sqlite3PagerWrite(pPage->pDbPage);
drhda200cc2004-05-09 11:51:38 +00004067 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004068 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00004069 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00004070 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00004071 }else{
4072 /* Other free pages already exist. Retrive the first trunk page
4073 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00004074 MemPage *pTrunk;
drh16a9b832007-05-05 18:39:25 +00004075 rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0);
drh3b7511c2001-05-26 13:15:44 +00004076 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004077 k = get4byte(&pTrunk->aData[4]);
drhee696e22004-08-30 16:52:17 +00004078 if( k>=pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00004079 /* The trunk is full. Turn the page being freed into a new
4080 ** trunk page with no leaves. */
danielk19773b8a05f2007-03-19 17:44:26 +00004081 rc = sqlite3PagerWrite(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00004082 if( rc ) return rc;
4083 put4byte(pPage->aData, pTrunk->pgno);
4084 put4byte(&pPage->aData[4], 0);
4085 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00004086 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
4087 pPage->pgno, pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00004088 }else{
4089 /* Add the newly freed page as a leaf on the current trunk */
danielk19773b8a05f2007-03-19 17:44:26 +00004090 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00004091 if( rc==SQLITE_OK ){
4092 put4byte(&pTrunk->aData[4], k+1);
4093 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drhfcce93f2006-02-22 03:08:32 +00004094#ifndef SQLITE_SECURE_DELETE
drh538f5702007-04-13 02:14:30 +00004095 sqlite3PagerDontWrite(pPage->pDbPage);
drhfcce93f2006-02-22 03:08:32 +00004096#endif
drhf5345442007-04-09 12:45:02 +00004097 }
drh3a4c1412004-05-09 20:40:11 +00004098 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00004099 }
4100 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00004101 }
drh3b7511c2001-05-26 13:15:44 +00004102 return rc;
4103}
4104
4105/*
drh3aac2dd2004-04-26 14:10:20 +00004106** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00004107*/
drh3aac2dd2004-04-26 14:10:20 +00004108static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00004109 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00004110 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00004111 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00004112 int rc;
drh94440812007-03-06 11:42:19 +00004113 int nOvfl;
4114 int ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00004115
drh1fee73e2007-08-29 04:00:57 +00004116 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh16a9b832007-05-05 18:39:25 +00004117 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004118 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00004119 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00004120 }
drh6f11bef2004-05-13 01:12:56 +00004121 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh94440812007-03-06 11:42:19 +00004122 ovflPageSize = pBt->usableSize - 4;
drh72365832007-03-06 15:53:44 +00004123 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
4124 assert( ovflPgno==0 || nOvfl>0 );
4125 while( nOvfl-- ){
drh3aac2dd2004-04-26 14:10:20 +00004126 MemPage *pOvfl;
danielk19773b8a05f2007-03-19 17:44:26 +00004127 if( ovflPgno==0 || ovflPgno>sqlite3PagerPagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00004128 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00004129 }
danielk19778c0a9592007-04-30 16:55:00 +00004130
4131 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno);
drh3b7511c2001-05-26 13:15:44 +00004132 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00004133 rc = freePage(pOvfl);
danielk19773b8a05f2007-03-19 17:44:26 +00004134 sqlite3PagerUnref(pOvfl->pDbPage);
danielk19776b456a22005-03-21 04:04:02 +00004135 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00004136 }
drh5e2f8b92001-05-28 00:41:15 +00004137 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00004138}
4139
4140/*
drh91025292004-05-03 19:49:32 +00004141** Create the byte sequence used to represent a cell on page pPage
4142** and write that byte sequence into pCell[]. Overflow pages are
4143** allocated and filled in as necessary. The calling procedure
4144** is responsible for making sure sufficient space has been allocated
4145** for pCell[].
4146**
4147** Note that pCell does not necessary need to point to the pPage->aData
4148** area. pCell might point to some temporary storage. The cell will
4149** be constructed in this temporary area then copied into pPage->aData
4150** later.
drh3b7511c2001-05-26 13:15:44 +00004151*/
4152static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00004153 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00004154 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00004155 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00004156 const void *pData,int nData, /* The data */
drhb026e052007-05-02 01:34:31 +00004157 int nZero, /* Extra zero bytes to append to pData */
drh4b70f112004-05-02 21:12:19 +00004158 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00004159){
drh3b7511c2001-05-26 13:15:44 +00004160 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00004161 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00004162 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00004163 int spaceLeft;
4164 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00004165 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00004166 unsigned char *pPrior;
4167 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00004168 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00004169 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00004170 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00004171 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00004172
drh1fee73e2007-08-29 04:00:57 +00004173 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00004174
drh91025292004-05-03 19:49:32 +00004175 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00004176 nHeader = 0;
drh91025292004-05-03 19:49:32 +00004177 if( !pPage->leaf ){
4178 nHeader += 4;
4179 }
drh8b18dd42004-05-12 19:18:15 +00004180 if( pPage->hasData ){
drhb026e052007-05-02 01:34:31 +00004181 nHeader += putVarint(&pCell[nHeader], nData+nZero);
drh6f11bef2004-05-13 01:12:56 +00004182 }else{
drhb026e052007-05-02 01:34:31 +00004183 nData = nZero = 0;
drh91025292004-05-03 19:49:32 +00004184 }
drh6f11bef2004-05-13 01:12:56 +00004185 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh16a9b832007-05-05 18:39:25 +00004186 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004187 assert( info.nHeader==nHeader );
4188 assert( info.nKey==nKey );
drhb026e052007-05-02 01:34:31 +00004189 assert( info.nData==nData+nZero );
drh6f11bef2004-05-13 01:12:56 +00004190
4191 /* Fill in the payload */
drhb026e052007-05-02 01:34:31 +00004192 nPayload = nData + nZero;
drh3aac2dd2004-04-26 14:10:20 +00004193 if( pPage->intKey ){
4194 pSrc = pData;
4195 nSrc = nData;
drh91025292004-05-03 19:49:32 +00004196 nData = 0;
drh3aac2dd2004-04-26 14:10:20 +00004197 }else{
4198 nPayload += nKey;
4199 pSrc = pKey;
4200 nSrc = nKey;
4201 }
drh6f11bef2004-05-13 01:12:56 +00004202 *pnSize = info.nSize;
4203 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00004204 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00004205 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00004206
drh3b7511c2001-05-26 13:15:44 +00004207 while( nPayload>0 ){
4208 if( spaceLeft==0 ){
danielk1977b39f70b2007-05-17 18:28:11 +00004209 int isExact = 0;
danielk1977afcdd022004-10-31 16:25:42 +00004210#ifndef SQLITE_OMIT_AUTOVACUUM
4211 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00004212 if( pBt->autoVacuum ){
4213 do{
4214 pgnoOvfl++;
4215 } while(
4216 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
4217 );
danielk197789a4be82007-05-23 13:34:32 +00004218 if( pgnoOvfl>1 ){
danielk1977b39f70b2007-05-17 18:28:11 +00004219 /* isExact = 1; */
4220 }
4221 }
danielk1977afcdd022004-10-31 16:25:42 +00004222#endif
danielk1977b39f70b2007-05-17 18:28:11 +00004223 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, isExact);
danielk1977afcdd022004-10-31 16:25:42 +00004224#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00004225 /* If the database supports auto-vacuum, and the second or subsequent
4226 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00004227 ** for that page now.
4228 **
4229 ** If this is the first overflow page, then write a partial entry
4230 ** to the pointer-map. If we write nothing to this pointer-map slot,
4231 ** then the optimistic overflow chain processing in clearCell()
4232 ** may misinterpret the uninitialised values and delete the
4233 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00004234 */
danielk19774ef24492007-05-23 09:52:41 +00004235 if( pBt->autoVacuum && rc==SQLITE_OK ){
4236 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
4237 rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
danielk197789a4be82007-05-23 13:34:32 +00004238 if( rc ){
4239 releasePage(pOvfl);
4240 }
danielk1977afcdd022004-10-31 16:25:42 +00004241 }
4242#endif
drh3b7511c2001-05-26 13:15:44 +00004243 if( rc ){
drh9b171272004-05-08 02:03:22 +00004244 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00004245 return rc;
4246 }
drh3aac2dd2004-04-26 14:10:20 +00004247 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00004248 releasePage(pToRelease);
4249 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00004250 pPrior = pOvfl->aData;
4251 put4byte(pPrior, 0);
4252 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00004253 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00004254 }
4255 n = nPayload;
4256 if( n>spaceLeft ) n = spaceLeft;
drhb026e052007-05-02 01:34:31 +00004257 if( nSrc>0 ){
4258 if( n>nSrc ) n = nSrc;
4259 assert( pSrc );
4260 memcpy(pPayload, pSrc, n);
4261 }else{
4262 memset(pPayload, 0, n);
4263 }
drh3b7511c2001-05-26 13:15:44 +00004264 nPayload -= n;
drhde647132004-05-07 17:57:49 +00004265 pPayload += n;
drh9b171272004-05-08 02:03:22 +00004266 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00004267 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00004268 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00004269 if( nSrc==0 ){
4270 nSrc = nData;
4271 pSrc = pData;
4272 }
drhdd793422001-06-28 01:54:48 +00004273 }
drh9b171272004-05-08 02:03:22 +00004274 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00004275 return SQLITE_OK;
4276}
4277
4278/*
drhbd03cae2001-06-02 02:40:57 +00004279** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00004280** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00004281** pointer in the third argument.
4282*/
danielk1977aef0bf62005-12-30 16:28:01 +00004283static int reparentPage(BtShared *pBt, Pgno pgno, MemPage *pNewParent, int idx){
drhbd03cae2001-06-02 02:40:57 +00004284 MemPage *pThis;
danielk19773b8a05f2007-03-19 17:44:26 +00004285 DbPage *pDbPage;
drhbd03cae2001-06-02 02:40:57 +00004286
drh1fee73e2007-08-29 04:00:57 +00004287 assert( sqlite3_mutex_held(pBt->mutex) );
drh43617e92006-03-06 20:55:46 +00004288 assert( pNewParent!=0 );
danielk1977afcdd022004-10-31 16:25:42 +00004289 if( pgno==0 ) return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00004290 assert( pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00004291 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
4292 if( pDbPage ){
4293 pThis = (MemPage *)sqlite3PagerGetExtra(pDbPage);
drhda200cc2004-05-09 11:51:38 +00004294 if( pThis->isInit ){
danielk19773b8a05f2007-03-19 17:44:26 +00004295 assert( pThis->aData==(sqlite3PagerGetData(pDbPage)) );
drhda200cc2004-05-09 11:51:38 +00004296 if( pThis->pParent!=pNewParent ){
danielk19773b8a05f2007-03-19 17:44:26 +00004297 if( pThis->pParent ) sqlite3PagerUnref(pThis->pParent->pDbPage);
drhda200cc2004-05-09 11:51:38 +00004298 pThis->pParent = pNewParent;
danielk19773b8a05f2007-03-19 17:44:26 +00004299 sqlite3PagerRef(pNewParent->pDbPage);
drhda200cc2004-05-09 11:51:38 +00004300 }
4301 pThis->idxParent = idx;
drhdd793422001-06-28 01:54:48 +00004302 }
danielk19773b8a05f2007-03-19 17:44:26 +00004303 sqlite3PagerUnref(pDbPage);
drhbd03cae2001-06-02 02:40:57 +00004304 }
danielk1977afcdd022004-10-31 16:25:42 +00004305
4306#ifndef SQLITE_OMIT_AUTOVACUUM
4307 if( pBt->autoVacuum ){
4308 return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
4309 }
4310#endif
4311 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00004312}
4313
danielk1977ac11ee62005-01-15 12:45:51 +00004314
4315
drhbd03cae2001-06-02 02:40:57 +00004316/*
drh4b70f112004-05-02 21:12:19 +00004317** Change the pParent pointer of all children of pPage to point back
4318** to pPage.
4319**
drhbd03cae2001-06-02 02:40:57 +00004320** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00004321** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00004322**
4323** This routine gets called after you memcpy() one page into
4324** another.
4325*/
danielk1977afcdd022004-10-31 16:25:42 +00004326static int reparentChildPages(MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00004327 int i;
danielk1977aef0bf62005-12-30 16:28:01 +00004328 BtShared *pBt = pPage->pBt;
danielk1977afcdd022004-10-31 16:25:42 +00004329 int rc = SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00004330
drh1fee73e2007-08-29 04:00:57 +00004331 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk1977afcdd022004-10-31 16:25:42 +00004332 if( pPage->leaf ) return SQLITE_OK;
danielk1977afcdd022004-10-31 16:25:42 +00004333
drhbd03cae2001-06-02 02:40:57 +00004334 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00004335 u8 *pCell = findCell(pPage, i);
danielk1977afcdd022004-10-31 16:25:42 +00004336 if( !pPage->leaf ){
4337 rc = reparentPage(pBt, get4byte(pCell), pPage, i);
4338 if( rc!=SQLITE_OK ) return rc;
4339 }
drhbd03cae2001-06-02 02:40:57 +00004340 }
danielk1977afcdd022004-10-31 16:25:42 +00004341 if( !pPage->leaf ){
4342 rc = reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]),
4343 pPage, i);
4344 pPage->idxShift = 0;
4345 }
4346 return rc;
drh14acc042001-06-10 19:56:58 +00004347}
4348
4349/*
4350** Remove the i-th cell from pPage. This routine effects pPage only.
4351** The cell content is not freed or deallocated. It is assumed that
4352** the cell content has been copied someplace else. This routine just
4353** removes the reference to the cell from pPage.
4354**
4355** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00004356*/
drh4b70f112004-05-02 21:12:19 +00004357static void dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00004358 int i; /* Loop counter */
4359 int pc; /* Offset to cell content of cell being deleted */
4360 u8 *data; /* pPage->aData */
4361 u8 *ptr; /* Used to move bytes around within data[] */
4362
drh8c42ca92001-06-22 19:15:00 +00004363 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00004364 assert( sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00004365 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00004366 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00004367 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00004368 ptr = &data[pPage->cellOffset + 2*idx];
4369 pc = get2byte(ptr);
4370 assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
drhde647132004-05-07 17:57:49 +00004371 freeSpace(pPage, pc, sz);
drh43605152004-05-29 21:46:49 +00004372 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
4373 ptr[0] = ptr[2];
4374 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00004375 }
4376 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00004377 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
4378 pPage->nFree += 2;
drh428ae8c2003-01-04 16:48:09 +00004379 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00004380}
4381
4382/*
4383** Insert a new cell on pPage at cell index "i". pCell points to the
4384** content of the cell.
4385**
4386** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00004387** will not fit, then make a copy of the cell content into pTemp if
4388** pTemp is not null. Regardless of pTemp, allocate a new entry
4389** in pPage->aOvfl[] and make it point to the cell content (either
4390** in pTemp or the original pCell) and also record its index.
4391** Allocating a new entry in pPage->aCell[] implies that
4392** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00004393**
4394** If nSkip is non-zero, then do not copy the first nSkip bytes of the
4395** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00004396** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00004397** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00004398*/
danielk1977e80463b2004-11-03 03:01:16 +00004399static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00004400 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00004401 int i, /* New cell becomes the i-th cell of the page */
4402 u8 *pCell, /* Content of the new cell */
4403 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00004404 u8 *pTemp, /* Temp storage space for pCell, if needed */
4405 u8 nSkip /* Do not write the first nSkip bytes of the cell */
drh24cd67e2004-05-10 16:18:47 +00004406){
drh43605152004-05-29 21:46:49 +00004407 int idx; /* Where to write new cell content in data[] */
4408 int j; /* Loop counter */
4409 int top; /* First byte of content for any cell in data[] */
4410 int end; /* First byte past the last cell pointer in data[] */
4411 int ins; /* Index in data[] where new cell pointer is inserted */
4412 int hdr; /* Offset into data[] of the page header */
4413 int cellOffset; /* Address of first cell pointer in data[] */
4414 u8 *data; /* The content of the whole page */
4415 u8 *ptr; /* Used for moving information around in data[] */
4416
4417 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
4418 assert( sz==cellSizePtr(pPage, pCell) );
drh1fee73e2007-08-29 04:00:57 +00004419 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +00004420 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00004421 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00004422 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004423 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00004424 }
drh43605152004-05-29 21:46:49 +00004425 j = pPage->nOverflow++;
4426 assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
4427 pPage->aOvfl[j].pCell = pCell;
4428 pPage->aOvfl[j].idx = i;
4429 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00004430 }else{
danielk19776e465eb2007-08-21 13:11:00 +00004431 int rc = sqlite3PagerWrite(pPage->pDbPage);
4432 if( rc!=SQLITE_OK ){
4433 return rc;
4434 }
4435 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00004436 data = pPage->aData;
4437 hdr = pPage->hdrOffset;
4438 top = get2byte(&data[hdr+5]);
4439 cellOffset = pPage->cellOffset;
4440 end = cellOffset + 2*pPage->nCell + 2;
4441 ins = cellOffset + 2*i;
4442 if( end > top - sz ){
danielk19776e465eb2007-08-21 13:11:00 +00004443 rc = defragmentPage(pPage);
danielk19776b456a22005-03-21 04:04:02 +00004444 if( rc!=SQLITE_OK ) return rc;
drh43605152004-05-29 21:46:49 +00004445 top = get2byte(&data[hdr+5]);
4446 assert( end + sz <= top );
4447 }
4448 idx = allocateSpace(pPage, sz);
4449 assert( idx>0 );
4450 assert( end <= get2byte(&data[hdr+5]) );
4451 pPage->nCell++;
4452 pPage->nFree -= 2;
danielk1977a3ad5e72005-01-07 08:56:44 +00004453 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004454 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
4455 ptr[0] = ptr[-2];
4456 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00004457 }
drh43605152004-05-29 21:46:49 +00004458 put2byte(&data[ins], idx);
4459 put2byte(&data[hdr+3], pPage->nCell);
4460 pPage->idxShift = 1;
danielk1977a19df672004-11-03 11:37:07 +00004461#ifndef SQLITE_OMIT_AUTOVACUUM
4462 if( pPage->pBt->autoVacuum ){
4463 /* The cell may contain a pointer to an overflow page. If so, write
4464 ** the entry for the overflow page into the pointer map.
4465 */
4466 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00004467 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh72365832007-03-06 15:53:44 +00004468 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk1977a19df672004-11-03 11:37:07 +00004469 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
4470 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
danielk19776e465eb2007-08-21 13:11:00 +00004471 rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
danielk1977a19df672004-11-03 11:37:07 +00004472 if( rc!=SQLITE_OK ) return rc;
4473 }
4474 }
4475#endif
drh14acc042001-06-10 19:56:58 +00004476 }
danielk1977e80463b2004-11-03 03:01:16 +00004477
danielk1977e80463b2004-11-03 03:01:16 +00004478 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004479}
4480
4481/*
drhfa1a98a2004-05-14 19:08:17 +00004482** Add a list of cells to a page. The page should be initially empty.
4483** The cells are guaranteed to fit on the page.
4484*/
4485static void assemblePage(
4486 MemPage *pPage, /* The page to be assemblied */
4487 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00004488 u8 **apCell, /* Pointers to cell bodies */
drhfa1a98a2004-05-14 19:08:17 +00004489 int *aSize /* Sizes of the cells */
4490){
4491 int i; /* Loop counter */
4492 int totalSize; /* Total size of all cells */
4493 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00004494 int cellptr; /* Address of next cell pointer */
4495 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00004496 u8 *data; /* Data for the page */
4497
drh43605152004-05-29 21:46:49 +00004498 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00004499 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa1a98a2004-05-14 19:08:17 +00004500 totalSize = 0;
4501 for(i=0; i<nCell; i++){
4502 totalSize += aSize[i];
4503 }
drh43605152004-05-29 21:46:49 +00004504 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00004505 assert( pPage->nCell==0 );
drh43605152004-05-29 21:46:49 +00004506 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00004507 data = pPage->aData;
4508 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00004509 put2byte(&data[hdr+3], nCell);
drh09d0deb2005-08-02 17:13:09 +00004510 if( nCell ){
4511 cellbody = allocateSpace(pPage, totalSize);
4512 assert( cellbody>0 );
4513 assert( pPage->nFree >= 2*nCell );
4514 pPage->nFree -= 2*nCell;
4515 for(i=0; i<nCell; i++){
4516 put2byte(&data[cellptr], cellbody);
4517 memcpy(&data[cellbody], apCell[i], aSize[i]);
4518 cellptr += 2;
4519 cellbody += aSize[i];
4520 }
4521 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00004522 }
4523 pPage->nCell = nCell;
drhfa1a98a2004-05-14 19:08:17 +00004524}
4525
drh14acc042001-06-10 19:56:58 +00004526/*
drhc3b70572003-01-04 19:44:07 +00004527** The following parameters determine how many adjacent pages get involved
4528** in a balancing operation. NN is the number of neighbors on either side
4529** of the page that participate in the balancing operation. NB is the
4530** total number of pages that participate, including the target page and
4531** NN neighbors on either side.
4532**
4533** The minimum value of NN is 1 (of course). Increasing NN above 1
4534** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
4535** in exchange for a larger degradation in INSERT and UPDATE performance.
4536** The value of NN appears to give the best results overall.
4537*/
4538#define NN 1 /* Number of neighbors on either side of pPage */
4539#define NB (NN*2+1) /* Total pages involved in the balance */
4540
drh43605152004-05-29 21:46:49 +00004541/* Forward reference */
danielk1977ac245ec2005-01-14 13:50:11 +00004542static int balance(MemPage*, int);
4543
drh615ae552005-01-16 23:21:00 +00004544#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004545/*
4546** This version of balance() handles the common special case where
4547** a new entry is being inserted on the extreme right-end of the
4548** tree, in other words, when the new entry will become the largest
4549** entry in the tree.
4550**
4551** Instead of trying balance the 3 right-most leaf pages, just add
4552** a new page to the right-hand side and put the one new entry in
4553** that page. This leaves the right side of the tree somewhat
4554** unbalanced. But odds are that we will be inserting new entries
4555** at the end soon afterwards so the nearly empty page will quickly
4556** fill up. On average.
4557**
4558** pPage is the leaf page which is the right-most page in the tree.
4559** pParent is its parent. pPage must have a single overflow entry
4560** which is also the right-most entry on the page.
4561*/
danielk1977ac245ec2005-01-14 13:50:11 +00004562static int balance_quick(MemPage *pPage, MemPage *pParent){
4563 int rc;
4564 MemPage *pNew;
4565 Pgno pgnoNew;
4566 u8 *pCell;
4567 int szCell;
4568 CellInfo info;
danielk1977aef0bf62005-12-30 16:28:01 +00004569 BtShared *pBt = pPage->pBt;
danielk197779a40da2005-01-16 08:00:01 +00004570 int parentIdx = pParent->nCell; /* pParent new divider cell index */
4571 int parentSize; /* Size of new divider cell */
4572 u8 parentCell[64]; /* Space for the new divider cell */
danielk1977ac245ec2005-01-14 13:50:11 +00004573
drh1fee73e2007-08-29 04:00:57 +00004574 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00004575
danielk1977ac245ec2005-01-14 13:50:11 +00004576 /* Allocate a new page. Insert the overflow cell from pPage
4577 ** into it. Then remove the overflow cell from pPage.
4578 */
drh4f0c5872007-03-26 22:05:01 +00004579 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk1977ac245ec2005-01-14 13:50:11 +00004580 if( rc!=SQLITE_OK ){
4581 return rc;
4582 }
4583 pCell = pPage->aOvfl[0].pCell;
4584 szCell = cellSizePtr(pPage, pCell);
4585 zeroPage(pNew, pPage->aData[0]);
4586 assemblePage(pNew, 1, &pCell, &szCell);
4587 pPage->nOverflow = 0;
4588
danielk197779a40da2005-01-16 08:00:01 +00004589 /* Set the parent of the newly allocated page to pParent. */
4590 pNew->pParent = pParent;
danielk19773b8a05f2007-03-19 17:44:26 +00004591 sqlite3PagerRef(pParent->pDbPage);
danielk197779a40da2005-01-16 08:00:01 +00004592
danielk1977ac245ec2005-01-14 13:50:11 +00004593 /* pPage is currently the right-child of pParent. Change this
4594 ** so that the right-child is the new page allocated above and
danielk197779a40da2005-01-16 08:00:01 +00004595 ** pPage is the next-to-right child.
danielk1977ac245ec2005-01-14 13:50:11 +00004596 */
danielk1977ac11ee62005-01-15 12:45:51 +00004597 assert( pPage->nCell>0 );
danielk19771cc5ed82007-05-16 17:28:43 +00004598 pCell = findCell(pPage, pPage->nCell-1);
drh16a9b832007-05-05 18:39:25 +00004599 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drhb026e052007-05-02 01:34:31 +00004600 rc = fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
danielk1977ac245ec2005-01-14 13:50:11 +00004601 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00004602 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004603 }
4604 assert( parentSize<64 );
4605 rc = insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
4606 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00004607 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004608 }
4609 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
4610 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
4611
danielk197779a40da2005-01-16 08:00:01 +00004612#ifndef SQLITE_OMIT_AUTOVACUUM
4613 /* If this is an auto-vacuum database, update the pointer map
4614 ** with entries for the new page, and any pointer from the
4615 ** cell on the page to an overflow page.
4616 */
danielk1977ac11ee62005-01-15 12:45:51 +00004617 if( pBt->autoVacuum ){
4618 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
danielk1977deb403e2007-05-24 09:20:16 +00004619 if( rc==SQLITE_OK ){
4620 rc = ptrmapPutOvfl(pNew, 0);
danielk1977ac11ee62005-01-15 12:45:51 +00004621 }
danielk197779a40da2005-01-16 08:00:01 +00004622 if( rc!=SQLITE_OK ){
danielk1977deb403e2007-05-24 09:20:16 +00004623 releasePage(pNew);
danielk197779a40da2005-01-16 08:00:01 +00004624 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00004625 }
4626 }
danielk197779a40da2005-01-16 08:00:01 +00004627#endif
danielk1977ac11ee62005-01-15 12:45:51 +00004628
danielk197779a40da2005-01-16 08:00:01 +00004629 /* Release the reference to the new page and balance the parent page,
4630 ** in case the divider cell inserted caused it to become overfull.
4631 */
danielk1977ac245ec2005-01-14 13:50:11 +00004632 releasePage(pNew);
4633 return balance(pParent, 0);
4634}
drh615ae552005-01-16 23:21:00 +00004635#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00004636
drhc3b70572003-01-04 19:44:07 +00004637/*
drhab01f612004-05-22 02:55:23 +00004638** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00004639** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00004640** Usually NN siblings on either side of pPage is used in the balancing,
4641** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00004642** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00004643** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00004644** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00004645**
drh0c6cc4e2004-06-15 02:13:26 +00004646** The number of siblings of pPage might be increased or decreased by one or
4647** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00004648** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00004649** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00004650** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00004651** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00004652**
drh8b2f49b2001-06-08 00:21:52 +00004653** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00004654** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00004655** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00004656** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00004657**
drh8c42ca92001-06-22 19:15:00 +00004658** In the course of balancing the siblings of pPage, the parent of pPage
4659** might become overfull or underfull. If that happens, then this routine
4660** is called recursively on the parent.
4661**
drh5e00f6c2001-09-13 13:46:56 +00004662** If this routine fails for any reason, it might leave the database
4663** in a corrupted state. So if this routine fails, the database should
4664** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00004665*/
drh43605152004-05-29 21:46:49 +00004666static int balance_nonroot(MemPage *pPage){
drh8b2f49b2001-06-08 00:21:52 +00004667 MemPage *pParent; /* The parent of pPage */
drh16a9b832007-05-05 18:39:25 +00004668 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00004669 int nCell = 0; /* Number of cells in apCell[] */
4670 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
drh8b2f49b2001-06-08 00:21:52 +00004671 int nOld; /* Number of pages in apOld[] */
4672 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00004673 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00004674 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00004675 int idx; /* Index of pPage in pParent->aCell[] */
4676 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00004677 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00004678 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00004679 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00004680 int usableSpace; /* Bytes in pPage beyond the header */
4681 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00004682 int subtotal; /* Subtotal of bytes in cells on one page */
drhb6f41482004-05-14 01:58:11 +00004683 int iSpace = 0; /* First unused byte of aSpace[] */
drhc3b70572003-01-04 19:44:07 +00004684 MemPage *apOld[NB]; /* pPage and up to two siblings */
4685 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00004686 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00004687 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
4688 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drh4b70f112004-05-02 21:12:19 +00004689 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00004690 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
4691 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00004692 u8 **apCell = 0; /* All cells begin balanced */
drh2e38c322004-09-03 18:38:44 +00004693 int *szCell; /* Local size of all cells in apCell[] */
4694 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
4695 u8 *aSpace; /* Space to hold copies of dividers cells */
danielk19774e17d142005-01-16 09:06:33 +00004696#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00004697 u8 *aFrom = 0;
4698#endif
drh8b2f49b2001-06-08 00:21:52 +00004699
drh1fee73e2007-08-29 04:00:57 +00004700 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00004701
drh14acc042001-06-10 19:56:58 +00004702 /*
drh43605152004-05-29 21:46:49 +00004703 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00004704 */
drh3a4c1412004-05-09 20:40:11 +00004705 assert( pPage->isInit );
danielk19776e465eb2007-08-21 13:11:00 +00004706 assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 );
drh4b70f112004-05-02 21:12:19 +00004707 pBt = pPage->pBt;
drh14acc042001-06-10 19:56:58 +00004708 pParent = pPage->pParent;
drh43605152004-05-29 21:46:49 +00004709 assert( pParent );
danielk19773b8a05f2007-03-19 17:44:26 +00004710 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
danielk197707cb5602006-01-20 10:55:05 +00004711 return rc;
4712 }
drh43605152004-05-29 21:46:49 +00004713 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00004714
drh615ae552005-01-16 23:21:00 +00004715#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004716 /*
4717 ** A special case: If a new entry has just been inserted into a
4718 ** table (that is, a btree with integer keys and all data at the leaves)
drh09d0deb2005-08-02 17:13:09 +00004719 ** and the new entry is the right-most entry in the tree (it has the
drhf222e712005-01-14 22:55:49 +00004720 ** largest key) then use the special balance_quick() routine for
4721 ** balancing. balance_quick() is much faster and results in a tighter
4722 ** packing of data in the common case.
4723 */
danielk1977ac245ec2005-01-14 13:50:11 +00004724 if( pPage->leaf &&
4725 pPage->intKey &&
4726 pPage->leafData &&
4727 pPage->nOverflow==1 &&
4728 pPage->aOvfl[0].idx==pPage->nCell &&
danielk1977ac11ee62005-01-15 12:45:51 +00004729 pPage->pParent->pgno!=1 &&
danielk1977ac245ec2005-01-14 13:50:11 +00004730 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
4731 ){
danielk1977ac11ee62005-01-15 12:45:51 +00004732 /*
4733 ** TODO: Check the siblings to the left of pPage. It may be that
4734 ** they are not full and no new page is required.
4735 */
danielk1977ac245ec2005-01-14 13:50:11 +00004736 return balance_quick(pPage, pParent);
4737 }
4738#endif
4739
danielk19776e465eb2007-08-21 13:11:00 +00004740 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){
4741 return rc;
4742 }
4743
drh2e38c322004-09-03 18:38:44 +00004744 /*
drh4b70f112004-05-02 21:12:19 +00004745 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00004746 ** to pPage. The "idx" variable is the index of that cell. If pPage
4747 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00004748 */
drhbb49aba2003-01-04 18:53:27 +00004749 if( pParent->idxShift ){
drha34b6762004-05-07 13:30:42 +00004750 Pgno pgno;
drh4b70f112004-05-02 21:12:19 +00004751 pgno = pPage->pgno;
danielk19773b8a05f2007-03-19 17:44:26 +00004752 assert( pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbb49aba2003-01-04 18:53:27 +00004753 for(idx=0; idx<pParent->nCell; idx++){
danielk19771cc5ed82007-05-16 17:28:43 +00004754 if( get4byte(findCell(pParent, idx))==pgno ){
drhbb49aba2003-01-04 18:53:27 +00004755 break;
4756 }
drh8b2f49b2001-06-08 00:21:52 +00004757 }
drh4b70f112004-05-02 21:12:19 +00004758 assert( idx<pParent->nCell
drh43605152004-05-29 21:46:49 +00004759 || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
drhbb49aba2003-01-04 18:53:27 +00004760 }else{
4761 idx = pPage->idxParent;
drh8b2f49b2001-06-08 00:21:52 +00004762 }
drh8b2f49b2001-06-08 00:21:52 +00004763
4764 /*
drh14acc042001-06-10 19:56:58 +00004765 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00004766 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00004767 */
drh14acc042001-06-10 19:56:58 +00004768 nOld = nNew = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00004769 sqlite3PagerRef(pParent->pDbPage);
drh14acc042001-06-10 19:56:58 +00004770
4771 /*
drh4b70f112004-05-02 21:12:19 +00004772 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00004773 ** the siblings. An attempt is made to find NN siblings on either
4774 ** side of pPage. More siblings are taken from one side, however, if
4775 ** pPage there are fewer than NN siblings on the other side. If pParent
4776 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00004777 */
drhc3b70572003-01-04 19:44:07 +00004778 nxDiv = idx - NN;
4779 if( nxDiv + NB > pParent->nCell ){
4780 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00004781 }
drhc3b70572003-01-04 19:44:07 +00004782 if( nxDiv<0 ){
4783 nxDiv = 0;
4784 }
drh8b2f49b2001-06-08 00:21:52 +00004785 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00004786 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00004787 if( k<pParent->nCell ){
danielk19771cc5ed82007-05-16 17:28:43 +00004788 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00004789 nDiv++;
drha34b6762004-05-07 13:30:42 +00004790 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00004791 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00004792 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00004793 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00004794 }else{
4795 break;
drh8b2f49b2001-06-08 00:21:52 +00004796 }
drhde647132004-05-07 17:57:49 +00004797 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00004798 if( rc ) goto balance_cleanup;
drh428ae8c2003-01-04 16:48:09 +00004799 apOld[i]->idxParent = k;
drh91025292004-05-03 19:49:32 +00004800 apCopy[i] = 0;
4801 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00004802 nOld++;
danielk1977634f2982005-03-28 08:44:07 +00004803 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
drh8b2f49b2001-06-08 00:21:52 +00004804 }
4805
drh8d97f1f2005-05-05 18:14:13 +00004806 /* Make nMaxCells a multiple of 2 in order to preserve 8-byte
4807 ** alignment */
4808 nMaxCells = (nMaxCells + 1)&~1;
4809
drh8b2f49b2001-06-08 00:21:52 +00004810 /*
danielk1977634f2982005-03-28 08:44:07 +00004811 ** Allocate space for memory structures
4812 */
drh17435752007-08-16 04:30:38 +00004813 apCell = sqlite3_malloc(
danielk1977634f2982005-03-28 08:44:07 +00004814 nMaxCells*sizeof(u8*) /* apCell */
4815 + nMaxCells*sizeof(int) /* szCell */
drhc96d8532005-05-03 12:30:33 +00004816 + ROUND8(sizeof(MemPage))*NB /* aCopy */
drh07d183d2005-05-01 22:52:42 +00004817 + pBt->pageSize*(5+NB) /* aSpace */
drhc96d8532005-05-03 12:30:33 +00004818 + (ISAUTOVACUUM ? nMaxCells : 0) /* aFrom */
danielk1977634f2982005-03-28 08:44:07 +00004819 );
4820 if( apCell==0 ){
4821 rc = SQLITE_NOMEM;
4822 goto balance_cleanup;
4823 }
4824 szCell = (int*)&apCell[nMaxCells];
4825 aCopy[0] = (u8*)&szCell[nMaxCells];
drhc96d8532005-05-03 12:30:33 +00004826 assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004827 for(i=1; i<NB; i++){
drhc96d8532005-05-03 12:30:33 +00004828 aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
4829 assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004830 }
drhc96d8532005-05-03 12:30:33 +00004831 aSpace = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
4832 assert( ((aSpace - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004833#ifndef SQLITE_OMIT_AUTOVACUUM
4834 if( pBt->autoVacuum ){
drh07d183d2005-05-01 22:52:42 +00004835 aFrom = &aSpace[5*pBt->pageSize];
danielk1977634f2982005-03-28 08:44:07 +00004836 }
4837#endif
4838
4839 /*
drh14acc042001-06-10 19:56:58 +00004840 ** Make copies of the content of pPage and its siblings into aOld[].
4841 ** The rest of this function will use data from the copies rather
4842 ** that the original pages since the original pages will be in the
4843 ** process of being overwritten.
4844 */
4845 for(i=0; i<nOld; i++){
drh07d183d2005-05-01 22:52:42 +00004846 MemPage *p = apCopy[i] = (MemPage*)&aCopy[i][pBt->pageSize];
drh07d183d2005-05-01 22:52:42 +00004847 p->aData = &((u8*)p)[-pBt->pageSize];
4848 memcpy(p->aData, apOld[i]->aData, pBt->pageSize + sizeof(MemPage));
4849 /* The memcpy() above changes the value of p->aData so we have to
4850 ** set it again. */
drh07d183d2005-05-01 22:52:42 +00004851 p->aData = &((u8*)p)[-pBt->pageSize];
drh14acc042001-06-10 19:56:58 +00004852 }
4853
4854 /*
4855 ** Load pointers to all cells on sibling pages and the divider cells
4856 ** into the local apCell[] array. Make copies of the divider cells
drhb6f41482004-05-14 01:58:11 +00004857 ** into space obtained form aSpace[] and remove the the divider Cells
4858 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00004859 **
4860 ** If the siblings are on leaf pages, then the child pointers of the
4861 ** divider cells are stripped from the cells before they are copied
drh96f5b762004-05-16 16:24:36 +00004862 ** into aSpace[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00004863 ** child pointers. If siblings are not leaves, then all cell in
4864 ** apCell[] include child pointers. Either way, all cells in apCell[]
4865 ** are alike.
drh96f5b762004-05-16 16:24:36 +00004866 **
4867 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
4868 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00004869 */
4870 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00004871 leafCorrection = pPage->leaf*4;
drh8b18dd42004-05-12 19:18:15 +00004872 leafData = pPage->leafData && pPage->leaf;
drh8b2f49b2001-06-08 00:21:52 +00004873 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00004874 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00004875 int limit = pOld->nCell+pOld->nOverflow;
4876 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00004877 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00004878 apCell[nCell] = findOverflowCell(pOld, j);
4879 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk1977ac11ee62005-01-15 12:45:51 +00004880#ifndef SQLITE_OMIT_AUTOVACUUM
4881 if( pBt->autoVacuum ){
4882 int a;
4883 aFrom[nCell] = i;
4884 for(a=0; a<pOld->nOverflow; a++){
4885 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
4886 aFrom[nCell] = 0xFF;
4887 break;
4888 }
4889 }
4890 }
4891#endif
drh14acc042001-06-10 19:56:58 +00004892 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00004893 }
4894 if( i<nOld-1 ){
drh43605152004-05-29 21:46:49 +00004895 int sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00004896 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00004897 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
4898 ** are duplicates of keys on the child pages. We need to remove
4899 ** the divider cells from pParent, but the dividers cells are not
4900 ** added to apCell[] because they are duplicates of child cells.
4901 */
drh8b18dd42004-05-12 19:18:15 +00004902 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00004903 }else{
drhb6f41482004-05-14 01:58:11 +00004904 u8 *pTemp;
danielk1977634f2982005-03-28 08:44:07 +00004905 assert( nCell<nMaxCells );
drhb6f41482004-05-14 01:58:11 +00004906 szCell[nCell] = sz;
4907 pTemp = &aSpace[iSpace];
4908 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004909 assert( iSpace<=pBt->pageSize*5 );
drhb6f41482004-05-14 01:58:11 +00004910 memcpy(pTemp, apDiv[i], sz);
4911 apCell[nCell] = pTemp+leafCorrection;
danielk1977ac11ee62005-01-15 12:45:51 +00004912#ifndef SQLITE_OMIT_AUTOVACUUM
4913 if( pBt->autoVacuum ){
4914 aFrom[nCell] = 0xFF;
4915 }
4916#endif
drhb6f41482004-05-14 01:58:11 +00004917 dropCell(pParent, nxDiv, sz);
drh8b18dd42004-05-12 19:18:15 +00004918 szCell[nCell] -= leafCorrection;
drh43605152004-05-29 21:46:49 +00004919 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00004920 if( !pOld->leaf ){
4921 assert( leafCorrection==0 );
4922 /* The right pointer of the child page pOld becomes the left
4923 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00004924 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00004925 }else{
4926 assert( leafCorrection==4 );
danielk197739c96042007-05-12 10:41:47 +00004927 if( szCell[nCell]<4 ){
4928 /* Do not allow any cells smaller than 4 bytes. */
4929 szCell[nCell] = 4;
4930 }
drh8b18dd42004-05-12 19:18:15 +00004931 }
4932 nCell++;
drh4b70f112004-05-02 21:12:19 +00004933 }
drh8b2f49b2001-06-08 00:21:52 +00004934 }
4935 }
4936
4937 /*
drh6019e162001-07-02 17:51:45 +00004938 ** Figure out the number of pages needed to hold all nCell cells.
4939 ** Store this number in "k". Also compute szNew[] which is the total
4940 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00004941 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00004942 ** cntNew[k] should equal nCell.
4943 **
drh96f5b762004-05-16 16:24:36 +00004944 ** Values computed by this block:
4945 **
4946 ** k: The total number of sibling pages
4947 ** szNew[i]: Spaced used on the i-th sibling page.
4948 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
4949 ** the right of the i-th sibling page.
4950 ** usableSpace: Number of bytes of space available on each sibling.
4951 **
drh8b2f49b2001-06-08 00:21:52 +00004952 */
drh43605152004-05-29 21:46:49 +00004953 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00004954 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00004955 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00004956 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00004957 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00004958 szNew[k] = subtotal - szCell[i];
4959 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00004960 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00004961 subtotal = 0;
4962 k++;
4963 }
4964 }
4965 szNew[k] = subtotal;
4966 cntNew[k] = nCell;
4967 k++;
drh96f5b762004-05-16 16:24:36 +00004968
4969 /*
4970 ** The packing computed by the previous block is biased toward the siblings
4971 ** on the left side. The left siblings are always nearly full, while the
4972 ** right-most sibling might be nearly empty. This block of code attempts
4973 ** to adjust the packing of siblings to get a better balance.
4974 **
4975 ** This adjustment is more than an optimization. The packing above might
4976 ** be so out of balance as to be illegal. For example, the right-most
4977 ** sibling might be completely empty. This adjustment is not optional.
4978 */
drh6019e162001-07-02 17:51:45 +00004979 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00004980 int szRight = szNew[i]; /* Size of sibling on the right */
4981 int szLeft = szNew[i-1]; /* Size of sibling on the left */
4982 int r; /* Index of right-most cell in left sibling */
4983 int d; /* Index of first cell to the left of right sibling */
4984
4985 r = cntNew[i-1] - 1;
4986 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00004987 assert( d<nMaxCells );
4988 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00004989 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
4990 szRight += szCell[d] + 2;
4991 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00004992 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00004993 r = cntNew[i-1] - 1;
4994 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00004995 }
drh96f5b762004-05-16 16:24:36 +00004996 szNew[i] = szRight;
4997 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00004998 }
drh09d0deb2005-08-02 17:13:09 +00004999
5000 /* Either we found one or more cells (cntnew[0])>0) or we are the
5001 ** a virtual root page. A virtual root page is when the real root
5002 ** page is page 1 and we are the only child of that page.
5003 */
5004 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00005005
5006 /*
drh6b308672002-07-08 02:16:37 +00005007 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00005008 */
drh4b70f112004-05-02 21:12:19 +00005009 assert( pPage->pgno>1 );
5010 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00005011 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00005012 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00005013 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00005014 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00005015 pgnoNew[i] = pgnoOld[i];
5016 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00005017 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00005018 nNew++;
danielk197728129562005-01-11 10:25:06 +00005019 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00005020 }else{
drh7aa8f852006-03-28 00:24:44 +00005021 assert( i>0 );
drh4f0c5872007-03-26 22:05:01 +00005022 rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
drh6b308672002-07-08 02:16:37 +00005023 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00005024 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00005025 nNew++;
drh6b308672002-07-08 02:16:37 +00005026 }
drhda200cc2004-05-09 11:51:38 +00005027 zeroPage(pNew, pageFlags);
drh8b2f49b2001-06-08 00:21:52 +00005028 }
5029
danielk1977299b1872004-11-22 10:02:10 +00005030 /* Free any old pages that were not reused as new pages.
5031 */
5032 while( i<nOld ){
5033 rc = freePage(apOld[i]);
5034 if( rc ) goto balance_cleanup;
5035 releasePage(apOld[i]);
5036 apOld[i] = 0;
5037 i++;
5038 }
5039
drh8b2f49b2001-06-08 00:21:52 +00005040 /*
drhf9ffac92002-03-02 19:00:31 +00005041 ** Put the new pages in accending order. This helps to
5042 ** keep entries in the disk file in order so that a scan
5043 ** of the table is a linear scan through the file. That
5044 ** in turn helps the operating system to deliver pages
5045 ** from the disk more rapidly.
5046 **
5047 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00005048 ** n is never more than NB (a small constant), that should
5049 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00005050 **
drhc3b70572003-01-04 19:44:07 +00005051 ** When NB==3, this one optimization makes the database
5052 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00005053 */
5054 for(i=0; i<k-1; i++){
5055 int minV = pgnoNew[i];
5056 int minI = i;
5057 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00005058 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00005059 minI = j;
5060 minV = pgnoNew[j];
5061 }
5062 }
5063 if( minI>i ){
5064 int t;
5065 MemPage *pT;
5066 t = pgnoNew[i];
5067 pT = apNew[i];
5068 pgnoNew[i] = pgnoNew[minI];
5069 apNew[i] = apNew[minI];
5070 pgnoNew[minI] = t;
5071 apNew[minI] = pT;
5072 }
5073 }
drha2fce642004-06-05 00:01:44 +00005074 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00005075 pgnoOld[0],
5076 nOld>=2 ? pgnoOld[1] : 0,
5077 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00005078 pgnoNew[0], szNew[0],
5079 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
5080 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00005081 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
5082 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00005083
drhf9ffac92002-03-02 19:00:31 +00005084 /*
drh14acc042001-06-10 19:56:58 +00005085 ** Evenly distribute the data in apCell[] across the new pages.
5086 ** Insert divider cells into pParent as necessary.
5087 */
5088 j = 0;
5089 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00005090 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00005091 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00005092 assert( j<nMaxCells );
drh4b70f112004-05-02 21:12:19 +00005093 assert( pNew->pgno==pgnoNew[i] );
drhfa1a98a2004-05-14 19:08:17 +00005094 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00005095 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00005096 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00005097
5098#ifndef SQLITE_OMIT_AUTOVACUUM
5099 /* If this is an auto-vacuum database, update the pointer map entries
5100 ** that point to the siblings that were rearranged. These can be: left
5101 ** children of cells, the right-child of the page, or overflow pages
5102 ** pointed to by cells.
5103 */
5104 if( pBt->autoVacuum ){
5105 for(k=j; k<cntNew[i]; k++){
danielk1977634f2982005-03-28 08:44:07 +00005106 assert( k<nMaxCells );
danielk1977ac11ee62005-01-15 12:45:51 +00005107 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
danielk197779a40da2005-01-16 08:00:01 +00005108 rc = ptrmapPutOvfl(pNew, k-j);
5109 if( rc!=SQLITE_OK ){
5110 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00005111 }
5112 }
5113 }
5114 }
5115#endif
5116
5117 j = cntNew[i];
5118
5119 /* If the sibling page assembled above was not the right-most sibling,
5120 ** insert a divider cell into the parent page.
5121 */
drh14acc042001-06-10 19:56:58 +00005122 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00005123 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00005124 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00005125 int sz;
danielk1977634f2982005-03-28 08:44:07 +00005126
5127 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00005128 pCell = apCell[j];
5129 sz = szCell[j] + leafCorrection;
drh4b70f112004-05-02 21:12:19 +00005130 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00005131 memcpy(&pNew->aData[8], pCell, 4);
drh24cd67e2004-05-10 16:18:47 +00005132 pTemp = 0;
drh8b18dd42004-05-12 19:18:15 +00005133 }else if( leafData ){
drhfd131da2007-08-07 17:13:03 +00005134 /* If the tree is a leaf-data tree, and the siblings are leaves,
danielk1977ac11ee62005-01-15 12:45:51 +00005135 ** then there is no divider cell in apCell[]. Instead, the divider
5136 ** cell consists of the integer key for the right-most cell of
5137 ** the sibling-page assembled above only.
5138 */
drh6f11bef2004-05-13 01:12:56 +00005139 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00005140 j--;
drh16a9b832007-05-05 18:39:25 +00005141 sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
drhb6f41482004-05-14 01:58:11 +00005142 pCell = &aSpace[iSpace];
drhb026e052007-05-02 01:34:31 +00005143 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
drhb6f41482004-05-14 01:58:11 +00005144 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00005145 assert( iSpace<=pBt->pageSize*5 );
drh8b18dd42004-05-12 19:18:15 +00005146 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00005147 }else{
5148 pCell -= 4;
drhb6f41482004-05-14 01:58:11 +00005149 pTemp = &aSpace[iSpace];
5150 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00005151 assert( iSpace<=pBt->pageSize*5 );
danielk19774aeff622007-05-12 09:30:47 +00005152 /* Obscure case for non-leaf-data trees: If the cell at pCell was
5153 ** previously stored on a leaf node, and it's reported size was 4
5154 ** bytes, then it may actually be smaller than this
5155 ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
5156 ** any cell). But it's important to pass the correct size to
5157 ** insertCell(), so reparse the cell now.
5158 **
5159 ** Note that this can never happen in an SQLite data file, as all
5160 ** cells are at least 4 bytes. It only happens in b-trees used
5161 ** to evaluate "IN (SELECT ...)" and similar clauses.
5162 */
5163 if( szCell[j]==4 ){
5164 assert(leafCorrection==4);
5165 sz = cellSizePtr(pParent, pCell);
5166 }
drh4b70f112004-05-02 21:12:19 +00005167 }
danielk1977a3ad5e72005-01-07 08:56:44 +00005168 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
danielk1977e80463b2004-11-03 03:01:16 +00005169 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh43605152004-05-29 21:46:49 +00005170 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +00005171#ifndef SQLITE_OMIT_AUTOVACUUM
5172 /* If this is an auto-vacuum database, and not a leaf-data tree,
5173 ** then update the pointer map with an entry for the overflow page
5174 ** that the cell just inserted points to (if any).
5175 */
5176 if( pBt->autoVacuum && !leafData ){
danielk197779a40da2005-01-16 08:00:01 +00005177 rc = ptrmapPutOvfl(pParent, nxDiv);
5178 if( rc!=SQLITE_OK ){
5179 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00005180 }
5181 }
5182#endif
drh14acc042001-06-10 19:56:58 +00005183 j++;
5184 nxDiv++;
5185 }
5186 }
drh6019e162001-07-02 17:51:45 +00005187 assert( j==nCell );
drh7aa8f852006-03-28 00:24:44 +00005188 assert( nOld>0 );
5189 assert( nNew>0 );
drh4b70f112004-05-02 21:12:19 +00005190 if( (pageFlags & PTF_LEAF)==0 ){
drh43605152004-05-29 21:46:49 +00005191 memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
drh14acc042001-06-10 19:56:58 +00005192 }
drh43605152004-05-29 21:46:49 +00005193 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00005194 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00005195 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00005196 }else{
5197 /* Right-most sibling is the left child of the first entry in pParent
5198 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00005199 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00005200 }
5201
5202 /*
5203 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00005204 */
5205 for(i=0; i<nNew; i++){
danielk1977afcdd022004-10-31 16:25:42 +00005206 rc = reparentChildPages(apNew[i]);
5207 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00005208 }
danielk1977afcdd022004-10-31 16:25:42 +00005209 rc = reparentChildPages(pParent);
5210 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00005211
5212 /*
drh3a4c1412004-05-09 20:40:11 +00005213 ** Balance the parent page. Note that the current page (pPage) might
danielk1977ac11ee62005-01-15 12:45:51 +00005214 ** have been added to the freelist so it might no longer be initialized.
drh3a4c1412004-05-09 20:40:11 +00005215 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00005216 */
drhda200cc2004-05-09 11:51:38 +00005217 assert( pParent->isInit );
danielk1977ac245ec2005-01-14 13:50:11 +00005218 rc = balance(pParent, 0);
drhda200cc2004-05-09 11:51:38 +00005219
drh8b2f49b2001-06-08 00:21:52 +00005220 /*
drh14acc042001-06-10 19:56:58 +00005221 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00005222 */
drh14acc042001-06-10 19:56:58 +00005223balance_cleanup:
drh17435752007-08-16 04:30:38 +00005224 sqlite3_free(apCell);
drh8b2f49b2001-06-08 00:21:52 +00005225 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00005226 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00005227 }
drh14acc042001-06-10 19:56:58 +00005228 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00005229 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00005230 }
drh91025292004-05-03 19:49:32 +00005231 releasePage(pParent);
drh3a4c1412004-05-09 20:40:11 +00005232 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
5233 pPage->pgno, nOld, nNew, nCell));
drh8b2f49b2001-06-08 00:21:52 +00005234 return rc;
5235}
5236
5237/*
drh43605152004-05-29 21:46:49 +00005238** This routine is called for the root page of a btree when the root
5239** page contains no cells. This is an opportunity to make the tree
5240** shallower by one level.
5241*/
5242static int balance_shallower(MemPage *pPage){
5243 MemPage *pChild; /* The only child page of pPage */
5244 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00005245 int rc = SQLITE_OK; /* Return code from subprocedures */
danielk1977aef0bf62005-12-30 16:28:01 +00005246 BtShared *pBt; /* The main BTree structure */
drh2e38c322004-09-03 18:38:44 +00005247 int mxCellPerPage; /* Maximum number of cells per page */
5248 u8 **apCell; /* All cells from pages being balanced */
5249 int *szCell; /* Local size of all cells */
drh43605152004-05-29 21:46:49 +00005250
5251 assert( pPage->pParent==0 );
5252 assert( pPage->nCell==0 );
drh1fee73e2007-08-29 04:00:57 +00005253 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh2e38c322004-09-03 18:38:44 +00005254 pBt = pPage->pBt;
5255 mxCellPerPage = MX_CELL(pBt);
drh17435752007-08-16 04:30:38 +00005256 apCell = sqlite3_malloc( mxCellPerPage*(sizeof(u8*)+sizeof(int)) );
drh2e38c322004-09-03 18:38:44 +00005257 if( apCell==0 ) return SQLITE_NOMEM;
5258 szCell = (int*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00005259 if( pPage->leaf ){
5260 /* The table is completely empty */
5261 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
5262 }else{
5263 /* The root page is empty but has one child. Transfer the
5264 ** information from that one child into the root page if it
5265 ** will fit. This reduces the depth of the tree by one.
5266 **
5267 ** If the root page is page 1, it has less space available than
5268 ** its child (due to the 100 byte header that occurs at the beginning
5269 ** of the database fle), so it might not be able to hold all of the
5270 ** information currently contained in the child. If this is the
5271 ** case, then do not do the transfer. Leave page 1 empty except
5272 ** for the right-pointer to the child page. The child page becomes
5273 ** the virtual root of the tree.
5274 */
5275 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5276 assert( pgnoChild>0 );
danielk19773b8a05f2007-03-19 17:44:26 +00005277 assert( pgnoChild<=sqlite3PagerPagecount(pPage->pBt->pPager) );
drh16a9b832007-05-05 18:39:25 +00005278 rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
drh2e38c322004-09-03 18:38:44 +00005279 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005280 if( pPage->pgno==1 ){
drh16a9b832007-05-05 18:39:25 +00005281 rc = sqlite3BtreeInitPage(pChild, pPage);
drh2e38c322004-09-03 18:38:44 +00005282 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005283 assert( pChild->nOverflow==0 );
5284 if( pChild->nFree>=100 ){
5285 /* The child information will fit on the root page, so do the
5286 ** copy */
5287 int i;
5288 zeroPage(pPage, pChild->aData[0]);
5289 for(i=0; i<pChild->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00005290 apCell[i] = findCell(pChild,i);
drh43605152004-05-29 21:46:49 +00005291 szCell[i] = cellSizePtr(pChild, apCell[i]);
5292 }
5293 assemblePage(pPage, pChild->nCell, apCell, szCell);
danielk1977ae825582004-11-23 09:06:55 +00005294 /* Copy the right-pointer of the child to the parent. */
5295 put4byte(&pPage->aData[pPage->hdrOffset+8],
5296 get4byte(&pChild->aData[pChild->hdrOffset+8]));
drh43605152004-05-29 21:46:49 +00005297 freePage(pChild);
5298 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
5299 }else{
5300 /* The child has more information that will fit on the root.
5301 ** The tree is already balanced. Do nothing. */
5302 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
5303 }
5304 }else{
5305 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
5306 pPage->isInit = 0;
5307 pPage->pParent = 0;
drh16a9b832007-05-05 18:39:25 +00005308 rc = sqlite3BtreeInitPage(pPage, 0);
drh43605152004-05-29 21:46:49 +00005309 assert( rc==SQLITE_OK );
5310 freePage(pChild);
5311 TRACE(("BALANCE: transfer child %d into root %d\n",
5312 pChild->pgno, pPage->pgno));
5313 }
danielk1977afcdd022004-10-31 16:25:42 +00005314 rc = reparentChildPages(pPage);
danielk1977ac11ee62005-01-15 12:45:51 +00005315 assert( pPage->nOverflow==0 );
5316#ifndef SQLITE_OMIT_AUTOVACUUM
5317 if( pBt->autoVacuum ){
danielk1977aac0a382005-01-16 11:07:06 +00005318 int i;
danielk1977ac11ee62005-01-15 12:45:51 +00005319 for(i=0; i<pPage->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00005320 rc = ptrmapPutOvfl(pPage, i);
5321 if( rc!=SQLITE_OK ){
5322 goto end_shallow_balance;
danielk1977ac11ee62005-01-15 12:45:51 +00005323 }
5324 }
5325 }
5326#endif
drh43605152004-05-29 21:46:49 +00005327 releasePage(pChild);
5328 }
drh2e38c322004-09-03 18:38:44 +00005329end_shallow_balance:
drh17435752007-08-16 04:30:38 +00005330 sqlite3_free(apCell);
drh2e38c322004-09-03 18:38:44 +00005331 return rc;
drh43605152004-05-29 21:46:49 +00005332}
5333
5334
5335/*
5336** The root page is overfull
5337**
5338** When this happens, Create a new child page and copy the
5339** contents of the root into the child. Then make the root
5340** page an empty page with rightChild pointing to the new
5341** child. Finally, call balance_internal() on the new child
5342** to cause it to split.
5343*/
5344static int balance_deeper(MemPage *pPage){
5345 int rc; /* Return value from subprocedures */
5346 MemPage *pChild; /* Pointer to a new child page */
5347 Pgno pgnoChild; /* Page number of the new child page */
danielk1977aef0bf62005-12-30 16:28:01 +00005348 BtShared *pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00005349 int usableSize; /* Total usable size of a page */
5350 u8 *data; /* Content of the parent page */
5351 u8 *cdata; /* Content of the child page */
5352 int hdr; /* Offset to page header in parent */
5353 int brk; /* Offset to content of first cell in parent */
5354
5355 assert( pPage->pParent==0 );
5356 assert( pPage->nOverflow>0 );
5357 pBt = pPage->pBt;
drh1fee73e2007-08-29 04:00:57 +00005358 assert( sqlite3_mutex_held(pBt->mutex) );
drh4f0c5872007-03-26 22:05:01 +00005359 rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
drh43605152004-05-29 21:46:49 +00005360 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00005361 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
drh43605152004-05-29 21:46:49 +00005362 usableSize = pBt->usableSize;
5363 data = pPage->aData;
5364 hdr = pPage->hdrOffset;
5365 brk = get2byte(&data[hdr+5]);
5366 cdata = pChild->aData;
5367 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
5368 memcpy(&cdata[brk], &data[brk], usableSize-brk);
danielk1977c7dc7532004-11-17 10:22:03 +00005369 assert( pChild->isInit==0 );
drh16a9b832007-05-05 18:39:25 +00005370 rc = sqlite3BtreeInitPage(pChild, pPage);
danielk19776b456a22005-03-21 04:04:02 +00005371 if( rc ) goto balancedeeper_out;
drh43605152004-05-29 21:46:49 +00005372 memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
5373 pChild->nOverflow = pPage->nOverflow;
5374 if( pChild->nOverflow ){
5375 pChild->nFree = 0;
5376 }
5377 assert( pChild->nCell==pPage->nCell );
5378 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
5379 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
5380 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
danielk19774e17d142005-01-16 09:06:33 +00005381#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00005382 if( pBt->autoVacuum ){
5383 int i;
5384 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
danielk19776b456a22005-03-21 04:04:02 +00005385 if( rc ) goto balancedeeper_out;
danielk1977ac11ee62005-01-15 12:45:51 +00005386 for(i=0; i<pChild->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00005387 rc = ptrmapPutOvfl(pChild, i);
5388 if( rc!=SQLITE_OK ){
5389 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00005390 }
5391 }
5392 }
danielk19774e17d142005-01-16 09:06:33 +00005393#endif
drh43605152004-05-29 21:46:49 +00005394 rc = balance_nonroot(pChild);
danielk19776b456a22005-03-21 04:04:02 +00005395
5396balancedeeper_out:
drh43605152004-05-29 21:46:49 +00005397 releasePage(pChild);
5398 return rc;
5399}
5400
5401/*
5402** Decide if the page pPage needs to be balanced. If balancing is
5403** required, call the appropriate balancing routine.
5404*/
danielk1977ac245ec2005-01-14 13:50:11 +00005405static int balance(MemPage *pPage, int insert){
drh43605152004-05-29 21:46:49 +00005406 int rc = SQLITE_OK;
drh1fee73e2007-08-29 04:00:57 +00005407 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +00005408 if( pPage->pParent==0 ){
danielk19776e465eb2007-08-21 13:11:00 +00005409 rc = sqlite3PagerWrite(pPage->pDbPage);
5410 if( rc==SQLITE_OK && pPage->nOverflow>0 ){
drh43605152004-05-29 21:46:49 +00005411 rc = balance_deeper(pPage);
5412 }
danielk1977687566d2004-11-02 12:56:41 +00005413 if( rc==SQLITE_OK && pPage->nCell==0 ){
drh43605152004-05-29 21:46:49 +00005414 rc = balance_shallower(pPage);
5415 }
5416 }else{
danielk1977ac245ec2005-01-14 13:50:11 +00005417 if( pPage->nOverflow>0 ||
5418 (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
drh43605152004-05-29 21:46:49 +00005419 rc = balance_nonroot(pPage);
5420 }
5421 }
5422 return rc;
5423}
5424
5425/*
drh8dcd7ca2004-08-08 19:43:29 +00005426** This routine checks all cursors that point to table pgnoRoot.
drh980b1a72006-08-16 16:42:48 +00005427** If any of those cursors were opened with wrFlag==0 in a different
5428** database connection (a database connection that shares the pager
5429** cache with the current connection) and that other connection
5430** is not in the ReadUncommmitted state, then this routine returns
5431** SQLITE_LOCKED.
danielk1977299b1872004-11-22 10:02:10 +00005432**
5433** In addition to checking for read-locks (where a read-lock
5434** means a cursor opened with wrFlag==0) this routine also moves
drh16a9b832007-05-05 18:39:25 +00005435** all write cursors so that they are pointing to the
drh980b1a72006-08-16 16:42:48 +00005436** first Cell on the root page. This is necessary because an insert
danielk1977299b1872004-11-22 10:02:10 +00005437** or delete might change the number of cells on a page or delete
5438** a page entirely and we do not want to leave any cursors
5439** pointing to non-existant pages or cells.
drhf74b8d92002-09-01 23:20:45 +00005440*/
drh980b1a72006-08-16 16:42:48 +00005441static int checkReadLocks(Btree *pBtree, Pgno pgnoRoot, BtCursor *pExclude){
danielk1977299b1872004-11-22 10:02:10 +00005442 BtCursor *p;
drh980b1a72006-08-16 16:42:48 +00005443 BtShared *pBt = pBtree->pBt;
5444 sqlite3 *db = pBtree->pSqlite;
drh1fee73e2007-08-29 04:00:57 +00005445 assert( sqlite3BtreeHoldsMutex(pBtree) );
danielk1977299b1872004-11-22 10:02:10 +00005446 for(p=pBt->pCursor; p; p=p->pNext){
drh980b1a72006-08-16 16:42:48 +00005447 if( p==pExclude ) continue;
5448 if( p->eState!=CURSOR_VALID ) continue;
5449 if( p->pgnoRoot!=pgnoRoot ) continue;
5450 if( p->wrFlag==0 ){
5451 sqlite3 *dbOther = p->pBtree->pSqlite;
5452 if( dbOther==0 ||
5453 (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
5454 return SQLITE_LOCKED;
5455 }
5456 }else if( p->pPage->pgno!=p->pgnoRoot ){
danielk1977299b1872004-11-22 10:02:10 +00005457 moveToRoot(p);
5458 }
5459 }
drhf74b8d92002-09-01 23:20:45 +00005460 return SQLITE_OK;
5461}
5462
5463/*
drh3b7511c2001-05-26 13:15:44 +00005464** Insert a new record into the BTree. The key is given by (pKey,nKey)
5465** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00005466** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00005467** is left pointing at a random location.
5468**
5469** For an INTKEY table, only the nKey value of the key is used. pKey is
5470** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00005471*/
drh3aac2dd2004-04-26 14:10:20 +00005472int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00005473 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00005474 const void *pKey, i64 nKey, /* The key of the new record */
drhe4d90812007-03-29 05:51:49 +00005475 const void *pData, int nData, /* The data of the new record */
drhb026e052007-05-02 01:34:31 +00005476 int nZero, /* Number of extra 0 bytes to append to data */
drhe4d90812007-03-29 05:51:49 +00005477 int appendBias /* True if this is likely an append */
drh3b7511c2001-05-26 13:15:44 +00005478){
drh3b7511c2001-05-26 13:15:44 +00005479 int rc;
5480 int loc;
drh14acc042001-06-10 19:56:58 +00005481 int szNew;
drh3b7511c2001-05-26 13:15:44 +00005482 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00005483 Btree *p = pCur->pBtree;
5484 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00005485 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00005486 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00005487
drh1fee73e2007-08-29 04:00:57 +00005488 assert( cursorHoldsMutex(pCur) );
danielk1977aef0bf62005-12-30 16:28:01 +00005489 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005490 /* Must start a transaction before doing an insert */
drhd677b3d2007-08-20 22:48:41 +00005491 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drhd677b3d2007-08-20 22:48:41 +00005492 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005493 }
drhf74b8d92002-09-01 23:20:45 +00005494 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00005495 if( !pCur->wrFlag ){
5496 return SQLITE_PERM; /* Cursor not open for writing */
5497 }
drh980b1a72006-08-16 16:42:48 +00005498 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00005499 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5500 }
danielk1977da184232006-01-05 11:34:32 +00005501
5502 /* Save the positions of any other cursors open on this table */
drhbf700f32007-03-31 02:36:44 +00005503 clearCursorPosition(pCur);
danielk19772e94d4d2006-01-09 05:36:27 +00005504 if(
danielk19772e94d4d2006-01-09 05:36:27 +00005505 SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
drhe4d90812007-03-29 05:51:49 +00005506 SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
danielk19772e94d4d2006-01-09 05:36:27 +00005507 ){
danielk1977da184232006-01-05 11:34:32 +00005508 return rc;
5509 }
5510
drh14acc042001-06-10 19:56:58 +00005511 pPage = pCur->pPage;
drh4a1c3802004-05-12 15:15:47 +00005512 assert( pPage->intKey || nKey>=0 );
drh8b18dd42004-05-12 19:18:15 +00005513 assert( pPage->leaf || !pPage->leafData );
drh3a4c1412004-05-09 20:40:11 +00005514 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
5515 pCur->pgnoRoot, nKey, nData, pPage->pgno,
5516 loc==0 ? "overwrite" : "new entry"));
drh7aa128d2002-06-21 13:09:16 +00005517 assert( pPage->isInit );
drh17435752007-08-16 04:30:38 +00005518 newCell = sqlite3_malloc( MX_CELL_SIZE(pBt) );
drh2e38c322004-09-03 18:38:44 +00005519 if( newCell==0 ) return SQLITE_NOMEM;
drhb026e052007-05-02 01:34:31 +00005520 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
drh2e38c322004-09-03 18:38:44 +00005521 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00005522 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00005523 assert( szNew<=MX_CELL_SIZE(pBt) );
danielk1977da184232006-01-05 11:34:32 +00005524 if( loc==0 && CURSOR_VALID==pCur->eState ){
drha34b6762004-05-07 13:30:42 +00005525 int szOld;
5526 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00005527 rc = sqlite3PagerWrite(pPage->pDbPage);
5528 if( rc ){
5529 goto end_insert;
5530 }
danielk19771cc5ed82007-05-16 17:28:43 +00005531 oldCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00005532 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005533 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00005534 }
drh43605152004-05-29 21:46:49 +00005535 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00005536 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00005537 if( rc ) goto end_insert;
drh4b70f112004-05-02 21:12:19 +00005538 dropCell(pPage, pCur->idx, szOld);
drh7c717f72001-06-24 20:39:41 +00005539 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00005540 assert( pPage->leaf );
drh14acc042001-06-10 19:56:58 +00005541 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00005542 pCur->info.nSize = 0;
drh14acc042001-06-10 19:56:58 +00005543 }else{
drh4b70f112004-05-02 21:12:19 +00005544 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00005545 }
danielk1977a3ad5e72005-01-07 08:56:44 +00005546 rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
danielk1977e80463b2004-11-03 03:01:16 +00005547 if( rc!=SQLITE_OK ) goto end_insert;
danielk1977ac245ec2005-01-14 13:50:11 +00005548 rc = balance(pPage, 1);
drh23e11ca2004-05-04 17:27:28 +00005549 /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
drh3fc190c2001-09-14 03:24:23 +00005550 /* fflush(stdout); */
danielk1977299b1872004-11-22 10:02:10 +00005551 if( rc==SQLITE_OK ){
5552 moveToRoot(pCur);
5553 }
drh2e38c322004-09-03 18:38:44 +00005554end_insert:
drh17435752007-08-16 04:30:38 +00005555 sqlite3_free(newCell);
drh5e2f8b92001-05-28 00:41:15 +00005556 return rc;
5557}
5558
5559/*
drh4b70f112004-05-02 21:12:19 +00005560** Delete the entry that the cursor is pointing to. The cursor
5561** is left pointing at a random location.
drh3b7511c2001-05-26 13:15:44 +00005562*/
drh3aac2dd2004-04-26 14:10:20 +00005563int sqlite3BtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00005564 MemPage *pPage = pCur->pPage;
drh4b70f112004-05-02 21:12:19 +00005565 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00005566 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00005567 Pgno pgnoChild = 0;
drhd677b3d2007-08-20 22:48:41 +00005568 Btree *p = pCur->pBtree;
5569 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005570
drh1fee73e2007-08-29 04:00:57 +00005571 assert( cursorHoldsMutex(pCur) );
drh7aa128d2002-06-21 13:09:16 +00005572 assert( pPage->isInit );
danielk1977aef0bf62005-12-30 16:28:01 +00005573 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005574 /* Must start a transaction before doing a delete */
drhd677b3d2007-08-20 22:48:41 +00005575 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drhd677b3d2007-08-20 22:48:41 +00005576 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005577 }
drhf74b8d92002-09-01 23:20:45 +00005578 assert( !pBt->readOnly );
drhbd03cae2001-06-02 02:40:57 +00005579 if( pCur->idx >= pPage->nCell ){
5580 return SQLITE_ERROR; /* The cursor is not pointing to anything */
5581 }
drhecdc7532001-09-23 02:35:53 +00005582 if( !pCur->wrFlag ){
5583 return SQLITE_PERM; /* Did not open this cursor for writing */
5584 }
drh980b1a72006-08-16 16:42:48 +00005585 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00005586 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5587 }
danielk1977da184232006-01-05 11:34:32 +00005588
5589 /* Restore the current cursor position (a no-op if the cursor is not in
5590 ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors
danielk19773b8a05f2007-03-19 17:44:26 +00005591 ** open on the same table. Then call sqlite3PagerWrite() on the page
danielk1977da184232006-01-05 11:34:32 +00005592 ** that the entry will be deleted from.
5593 */
5594 if(
drhbf700f32007-03-31 02:36:44 +00005595 (rc = restoreOrClearCursorPosition(pCur))!=0 ||
drhd1167392006-01-23 13:00:35 +00005596 (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
danielk19773b8a05f2007-03-19 17:44:26 +00005597 (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
danielk1977da184232006-01-05 11:34:32 +00005598 ){
5599 return rc;
5600 }
danielk1977e6efa742004-11-10 11:55:10 +00005601
5602 /* Locate the cell within it's page and leave pCell pointing to the
5603 ** data. The clearCell() call frees any overflow pages associated with the
5604 ** cell. The cell itself is still intact.
5605 */
danielk19771cc5ed82007-05-16 17:28:43 +00005606 pCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00005607 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005608 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005609 }
danielk197728129562005-01-11 10:25:06 +00005610 rc = clearCell(pPage, pCell);
drhd677b3d2007-08-20 22:48:41 +00005611 if( rc ){
drhd677b3d2007-08-20 22:48:41 +00005612 return rc;
5613 }
danielk1977e6efa742004-11-10 11:55:10 +00005614
drh4b70f112004-05-02 21:12:19 +00005615 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00005616 /*
drh5e00f6c2001-09-13 13:46:56 +00005617 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00005618 ** do something we will leave a hole on an internal page.
5619 ** We have to fill the hole by moving in a cell from a leaf. The
5620 ** next Cell after the one to be deleted is guaranteed to exist and
danielk1977299b1872004-11-22 10:02:10 +00005621 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00005622 */
drh14acc042001-06-10 19:56:58 +00005623 BtCursor leafCur;
drh4b70f112004-05-02 21:12:19 +00005624 unsigned char *pNext;
drh02afc862006-01-20 18:10:57 +00005625 int szNext; /* The compiler warning is wrong: szNext is always
5626 ** initialized before use. Adding an extra initialization
5627 ** to silence the compiler slows down the code. */
danielk1977299b1872004-11-22 10:02:10 +00005628 int notUsed;
danielk19776b456a22005-03-21 04:04:02 +00005629 unsigned char *tempCell = 0;
drh8b18dd42004-05-12 19:18:15 +00005630 assert( !pPage->leafData );
drh16a9b832007-05-05 18:39:25 +00005631 sqlite3BtreeGetTempCursor(pCur, &leafCur);
danielk1977299b1872004-11-22 10:02:10 +00005632 rc = sqlite3BtreeNext(&leafCur, &notUsed);
danielk19776b456a22005-03-21 04:04:02 +00005633 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00005634 rc = sqlite3PagerWrite(leafCur.pPage->pDbPage);
danielk19776b456a22005-03-21 04:04:02 +00005635 }
5636 if( rc==SQLITE_OK ){
5637 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
5638 pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
5639 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
danielk19771cc5ed82007-05-16 17:28:43 +00005640 pNext = findCell(leafCur.pPage, leafCur.idx);
danielk19776b456a22005-03-21 04:04:02 +00005641 szNext = cellSizePtr(leafCur.pPage, pNext);
5642 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
drh17435752007-08-16 04:30:38 +00005643 tempCell = sqlite3_malloc( MX_CELL_SIZE(pBt) );
danielk19776b456a22005-03-21 04:04:02 +00005644 if( tempCell==0 ){
5645 rc = SQLITE_NOMEM;
5646 }
5647 }
5648 if( rc==SQLITE_OK ){
5649 rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
5650 }
5651 if( rc==SQLITE_OK ){
5652 put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
5653 rc = balance(pPage, 0);
5654 }
5655 if( rc==SQLITE_OK ){
5656 dropCell(leafCur.pPage, leafCur.idx, szNext);
5657 rc = balance(leafCur.pPage, 0);
5658 }
drh17435752007-08-16 04:30:38 +00005659 sqlite3_free(tempCell);
drh16a9b832007-05-05 18:39:25 +00005660 sqlite3BtreeReleaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00005661 }else{
danielk1977299b1872004-11-22 10:02:10 +00005662 TRACE(("DELETE: table=%d delete from leaf %d\n",
5663 pCur->pgnoRoot, pPage->pgno));
5664 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
danielk1977ac245ec2005-01-14 13:50:11 +00005665 rc = balance(pPage, 0);
drh5e2f8b92001-05-28 00:41:15 +00005666 }
danielk19776b456a22005-03-21 04:04:02 +00005667 if( rc==SQLITE_OK ){
5668 moveToRoot(pCur);
5669 }
drh5e2f8b92001-05-28 00:41:15 +00005670 return rc;
drh3b7511c2001-05-26 13:15:44 +00005671}
drh8b2f49b2001-06-08 00:21:52 +00005672
5673/*
drhc6b52df2002-01-04 03:09:29 +00005674** Create a new BTree table. Write into *piTable the page
5675** number for the root page of the new table.
5676**
drhab01f612004-05-22 02:55:23 +00005677** The type of type is determined by the flags parameter. Only the
5678** following values of flags are currently in use. Other values for
5679** flags might not work:
5680**
5681** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
5682** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00005683*/
drhd677b3d2007-08-20 22:48:41 +00005684static int btreeCreateTable(Btree *p, int *piTable, int flags){
danielk1977aef0bf62005-12-30 16:28:01 +00005685 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005686 MemPage *pRoot;
5687 Pgno pgnoRoot;
5688 int rc;
drhd677b3d2007-08-20 22:48:41 +00005689
drh1fee73e2007-08-29 04:00:57 +00005690 assert( sqlite3BtreeHoldsMutex(p) );
danielk1977aef0bf62005-12-30 16:28:01 +00005691 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005692 /* Must start a transaction first */
drhd677b3d2007-08-20 22:48:41 +00005693 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
5694 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005695 }
danielk197728129562005-01-11 10:25:06 +00005696 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00005697
danielk1977003ba062004-11-04 02:57:33 +00005698#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00005699 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00005700 if( rc ){
5701 return rc;
5702 }
danielk1977003ba062004-11-04 02:57:33 +00005703#else
danielk1977687566d2004-11-02 12:56:41 +00005704 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00005705 Pgno pgnoMove; /* Move a page here to make room for the root-page */
5706 MemPage *pPageMove; /* The page to move to. */
5707
danielk197720713f32007-05-03 11:43:33 +00005708 /* Creating a new table may probably require moving an existing database
5709 ** to make room for the new tables root page. In case this page turns
5710 ** out to be an overflow page, delete all overflow page-map caches
5711 ** held by open cursors.
5712 */
danielk197792d4d7a2007-05-04 12:05:56 +00005713 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00005714
danielk1977003ba062004-11-04 02:57:33 +00005715 /* Read the value of meta[3] from the database to determine where the
5716 ** root page of the new table should go. meta[3] is the largest root-page
5717 ** created so far, so the new root-page is (meta[3]+1).
5718 */
danielk1977aef0bf62005-12-30 16:28:01 +00005719 rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
drhd677b3d2007-08-20 22:48:41 +00005720 if( rc!=SQLITE_OK ){
5721 return rc;
5722 }
danielk1977003ba062004-11-04 02:57:33 +00005723 pgnoRoot++;
5724
danielk1977599fcba2004-11-08 07:13:13 +00005725 /* The new root-page may not be allocated on a pointer-map page, or the
5726 ** PENDING_BYTE page.
5727 */
danielk1977266664d2006-02-10 08:24:21 +00005728 if( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00005729 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00005730 pgnoRoot++;
5731 }
5732 assert( pgnoRoot>=3 );
5733
5734 /* Allocate a page. The page that currently resides at pgnoRoot will
5735 ** be moved to the allocated page (unless the allocated page happens
5736 ** to reside at pgnoRoot).
5737 */
drh4f0c5872007-03-26 22:05:01 +00005738 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00005739 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00005740 return rc;
5741 }
danielk1977003ba062004-11-04 02:57:33 +00005742
5743 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00005744 /* pgnoRoot is the page that will be used for the root-page of
5745 ** the new table (assuming an error did not occur). But we were
5746 ** allocated pgnoMove. If required (i.e. if it was not allocated
5747 ** by extending the file), the current page at position pgnoMove
5748 ** is already journaled.
5749 */
danielk1977003ba062004-11-04 02:57:33 +00005750 u8 eType;
5751 Pgno iPtrPage;
5752
5753 releasePage(pPageMove);
danielk1977f35843b2007-04-07 15:03:17 +00005754
5755 /* Move the page currently at pgnoRoot to pgnoMove. */
drh16a9b832007-05-05 18:39:25 +00005756 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00005757 if( rc!=SQLITE_OK ){
5758 return rc;
5759 }
5760 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drhccae6022005-02-26 17:31:26 +00005761 if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00005762 releasePage(pRoot);
5763 return rc;
5764 }
drhccae6022005-02-26 17:31:26 +00005765 assert( eType!=PTRMAP_ROOTPAGE );
5766 assert( eType!=PTRMAP_FREEPAGE );
danielk19773b8a05f2007-03-19 17:44:26 +00005767 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk19775fd057a2005-03-09 13:09:43 +00005768 if( rc!=SQLITE_OK ){
5769 releasePage(pRoot);
5770 return rc;
5771 }
danielk1977003ba062004-11-04 02:57:33 +00005772 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove);
5773 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00005774
5775 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00005776 if( rc!=SQLITE_OK ){
5777 return rc;
5778 }
drh16a9b832007-05-05 18:39:25 +00005779 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00005780 if( rc!=SQLITE_OK ){
5781 return rc;
5782 }
danielk19773b8a05f2007-03-19 17:44:26 +00005783 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00005784 if( rc!=SQLITE_OK ){
5785 releasePage(pRoot);
5786 return rc;
5787 }
5788 }else{
5789 pRoot = pPageMove;
5790 }
5791
danielk197742741be2005-01-08 12:42:39 +00005792 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00005793 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
5794 if( rc ){
5795 releasePage(pRoot);
5796 return rc;
5797 }
danielk1977aef0bf62005-12-30 16:28:01 +00005798 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00005799 if( rc ){
5800 releasePage(pRoot);
5801 return rc;
5802 }
danielk197742741be2005-01-08 12:42:39 +00005803
danielk1977003ba062004-11-04 02:57:33 +00005804 }else{
drh4f0c5872007-03-26 22:05:01 +00005805 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00005806 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00005807 }
5808#endif
danielk19773b8a05f2007-03-19 17:44:26 +00005809 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhde647132004-05-07 17:57:49 +00005810 zeroPage(pRoot, flags | PTF_LEAF);
danielk19773b8a05f2007-03-19 17:44:26 +00005811 sqlite3PagerUnref(pRoot->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00005812 *piTable = (int)pgnoRoot;
5813 return SQLITE_OK;
5814}
drhd677b3d2007-08-20 22:48:41 +00005815int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
5816 int rc;
5817 sqlite3BtreeEnter(p);
5818 rc = btreeCreateTable(p, piTable, flags);
5819 sqlite3BtreeLeave(p);
5820 return rc;
5821}
drh8b2f49b2001-06-08 00:21:52 +00005822
5823/*
5824** Erase the given database page and all its children. Return
5825** the page to the freelist.
5826*/
drh4b70f112004-05-02 21:12:19 +00005827static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00005828 BtShared *pBt, /* The BTree that contains the table */
drh4b70f112004-05-02 21:12:19 +00005829 Pgno pgno, /* Page number to clear */
5830 MemPage *pParent, /* Parent page. NULL for the root */
5831 int freePageFlag /* Deallocate page if true */
5832){
danielk19776b456a22005-03-21 04:04:02 +00005833 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00005834 int rc;
drh4b70f112004-05-02 21:12:19 +00005835 unsigned char *pCell;
5836 int i;
drh8b2f49b2001-06-08 00:21:52 +00005837
drh1fee73e2007-08-29 04:00:57 +00005838 assert( sqlite3_mutex_held(pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00005839 if( pgno>sqlite3PagerPagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00005840 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00005841 }
5842
drhde647132004-05-07 17:57:49 +00005843 rc = getAndInitPage(pBt, pgno, &pPage, pParent);
danielk19776b456a22005-03-21 04:04:02 +00005844 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00005845 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00005846 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00005847 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005848 rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00005849 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00005850 }
drh4b70f112004-05-02 21:12:19 +00005851 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00005852 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00005853 }
drha34b6762004-05-07 13:30:42 +00005854 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005855 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00005856 if( rc ) goto cleardatabasepage_out;
drh2aa679f2001-06-25 02:11:07 +00005857 }
5858 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00005859 rc = freePage(pPage);
danielk19773b8a05f2007-03-19 17:44:26 +00005860 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
drh3a4c1412004-05-09 20:40:11 +00005861 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00005862 }
danielk19776b456a22005-03-21 04:04:02 +00005863
5864cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00005865 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00005866 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005867}
5868
5869/*
drhab01f612004-05-22 02:55:23 +00005870** Delete all information from a single table in the database. iTable is
5871** the page number of the root of the table. After this routine returns,
5872** the root page is empty, but still exists.
5873**
5874** This routine will fail with SQLITE_LOCKED if there are any open
5875** read cursors on the table. Open write cursors are moved to the
5876** root of the table.
drh8b2f49b2001-06-08 00:21:52 +00005877*/
danielk1977aef0bf62005-12-30 16:28:01 +00005878int sqlite3BtreeClearTable(Btree *p, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00005879 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00005880 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00005881 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00005882 if( p->inTrans!=TRANS_WRITE ){
drhd677b3d2007-08-20 22:48:41 +00005883 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
5884 }else if( (rc = checkReadLocks(p, iTable, 0))!=SQLITE_OK ){
5885 /* nothing to do */
5886 }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
5887 /* nothing to do */
5888 }else{
5889 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
drh8b2f49b2001-06-08 00:21:52 +00005890 }
drhd677b3d2007-08-20 22:48:41 +00005891 sqlite3BtreeLeave(p);
5892 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005893}
5894
5895/*
5896** Erase all information in a table and add the root of the table to
5897** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00005898** page 1) is never added to the freelist.
5899**
5900** This routine will fail with SQLITE_LOCKED if there are any open
5901** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00005902**
5903** If AUTOVACUUM is enabled and the page at iTable is not the last
5904** root page in the database file, then the last root page
5905** in the database file is moved into the slot formerly occupied by
5906** iTable and that last slot formerly occupied by the last root page
5907** is added to the freelist instead of iTable. In this say, all
5908** root pages are kept at the beginning of the database file, which
5909** is necessary for AUTOVACUUM to work right. *piMoved is set to the
5910** page number that used to be the last root page in the file before
5911** the move. If no page gets moved, *piMoved is set to 0.
5912** The last root page is recorded in meta[3] and the value of
5913** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00005914*/
drhd677b3d2007-08-20 22:48:41 +00005915static int btreeDropTable(Btree *p, int iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00005916 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00005917 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00005918 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00005919
drh1fee73e2007-08-29 04:00:57 +00005920 assert( sqlite3BtreeHoldsMutex(p) );
danielk1977aef0bf62005-12-30 16:28:01 +00005921 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005922 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005923 }
danielk1977a0bf2652004-11-04 14:30:04 +00005924
danielk1977e6efa742004-11-10 11:55:10 +00005925 /* It is illegal to drop a table if any cursors are open on the
5926 ** database. This is because in auto-vacuum mode the backend may
5927 ** need to move another root-page to fill a gap left by the deleted
5928 ** root page. If an open cursor was using this page a problem would
5929 ** occur.
5930 */
5931 if( pBt->pCursor ){
5932 return SQLITE_LOCKED;
drh5df72a52002-06-06 23:16:05 +00005933 }
danielk1977a0bf2652004-11-04 14:30:04 +00005934
drh16a9b832007-05-05 18:39:25 +00005935 rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00005936 if( rc ) return rc;
danielk1977aef0bf62005-12-30 16:28:01 +00005937 rc = sqlite3BtreeClearTable(p, iTable);
danielk19776b456a22005-03-21 04:04:02 +00005938 if( rc ){
5939 releasePage(pPage);
5940 return rc;
5941 }
danielk1977a0bf2652004-11-04 14:30:04 +00005942
drh205f48e2004-11-05 00:43:11 +00005943 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00005944
drh4b70f112004-05-02 21:12:19 +00005945 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00005946#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00005947 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00005948 releasePage(pPage);
5949#else
5950 if( pBt->autoVacuum ){
5951 Pgno maxRootPgno;
danielk1977aef0bf62005-12-30 16:28:01 +00005952 rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00005953 if( rc!=SQLITE_OK ){
5954 releasePage(pPage);
5955 return rc;
5956 }
5957
5958 if( iTable==maxRootPgno ){
5959 /* If the table being dropped is the table with the largest root-page
5960 ** number in the database, put the root page on the free list.
5961 */
5962 rc = freePage(pPage);
5963 releasePage(pPage);
5964 if( rc!=SQLITE_OK ){
5965 return rc;
5966 }
5967 }else{
5968 /* The table being dropped does not have the largest root-page
5969 ** number in the database. So move the page that does into the
5970 ** gap left by the deleted root-page.
5971 */
5972 MemPage *pMove;
5973 releasePage(pPage);
drh16a9b832007-05-05 18:39:25 +00005974 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00005975 if( rc!=SQLITE_OK ){
5976 return rc;
5977 }
5978 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable);
5979 releasePage(pMove);
5980 if( rc!=SQLITE_OK ){
5981 return rc;
5982 }
drh16a9b832007-05-05 18:39:25 +00005983 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00005984 if( rc!=SQLITE_OK ){
5985 return rc;
5986 }
5987 rc = freePage(pMove);
5988 releasePage(pMove);
5989 if( rc!=SQLITE_OK ){
5990 return rc;
5991 }
5992 *piMoved = maxRootPgno;
5993 }
5994
danielk1977599fcba2004-11-08 07:13:13 +00005995 /* Set the new 'max-root-page' value in the database header. This
5996 ** is the old value less one, less one more if that happens to
5997 ** be a root-page number, less one again if that is the
5998 ** PENDING_BYTE_PAGE.
5999 */
danielk197787a6e732004-11-05 12:58:25 +00006000 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00006001 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
6002 maxRootPgno--;
6003 }
danielk1977266664d2006-02-10 08:24:21 +00006004 if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00006005 maxRootPgno--;
6006 }
danielk1977599fcba2004-11-08 07:13:13 +00006007 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
6008
danielk1977aef0bf62005-12-30 16:28:01 +00006009 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006010 }else{
6011 rc = freePage(pPage);
6012 releasePage(pPage);
6013 }
6014#endif
drh2aa679f2001-06-25 02:11:07 +00006015 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00006016 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00006017 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00006018 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00006019 }
drh8b2f49b2001-06-08 00:21:52 +00006020 return rc;
6021}
drhd677b3d2007-08-20 22:48:41 +00006022int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
6023 int rc;
6024 sqlite3BtreeEnter(p);
6025 rc = btreeDropTable(p, iTable, piMoved);
6026 sqlite3BtreeLeave(p);
6027 return rc;
6028}
drh8b2f49b2001-06-08 00:21:52 +00006029
drh001bbcb2003-03-19 03:14:00 +00006030
drh8b2f49b2001-06-08 00:21:52 +00006031/*
drh23e11ca2004-05-04 17:27:28 +00006032** Read the meta-information out of a database file. Meta[0]
6033** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00006034** through meta[15] are available for use by higher layers. Meta[0]
6035** is read-only, the others are read/write.
6036**
6037** The schema layer numbers meta values differently. At the schema
6038** layer (and the SetCookie and ReadCookie opcodes) the number of
6039** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00006040*/
danielk1977aef0bf62005-12-30 16:28:01 +00006041int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
danielk19773b8a05f2007-03-19 17:44:26 +00006042 DbPage *pDbPage;
drh8b2f49b2001-06-08 00:21:52 +00006043 int rc;
drh4b70f112004-05-02 21:12:19 +00006044 unsigned char *pP1;
danielk1977aef0bf62005-12-30 16:28:01 +00006045 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006046
drhd677b3d2007-08-20 22:48:41 +00006047 sqlite3BtreeEnter(p);
6048
danielk1977da184232006-01-05 11:34:32 +00006049 /* Reading a meta-data value requires a read-lock on page 1 (and hence
6050 ** the sqlite_master table. We grab this lock regardless of whether or
6051 ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
6052 ** 1 is treated as a special case by queryTableLock() and lockTable()).
6053 */
6054 rc = queryTableLock(p, 1, READ_LOCK);
6055 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00006056 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00006057 return rc;
6058 }
6059
drh23e11ca2004-05-04 17:27:28 +00006060 assert( idx>=0 && idx<=15 );
danielk19773b8a05f2007-03-19 17:44:26 +00006061 rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
drhd677b3d2007-08-20 22:48:41 +00006062 if( rc ){
6063 sqlite3BtreeLeave(p);
6064 return rc;
6065 }
danielk19773b8a05f2007-03-19 17:44:26 +00006066 pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
drh23e11ca2004-05-04 17:27:28 +00006067 *pMeta = get4byte(&pP1[36 + idx*4]);
danielk19773b8a05f2007-03-19 17:44:26 +00006068 sqlite3PagerUnref(pDbPage);
drhae157872004-08-14 19:20:09 +00006069
danielk1977599fcba2004-11-08 07:13:13 +00006070 /* If autovacuumed is disabled in this build but we are trying to
6071 ** access an autovacuumed database, then make the database readonly.
6072 */
danielk1977003ba062004-11-04 02:57:33 +00006073#ifdef SQLITE_OMIT_AUTOVACUUM
drhae157872004-08-14 19:20:09 +00006074 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00006075#endif
drhae157872004-08-14 19:20:09 +00006076
danielk1977da184232006-01-05 11:34:32 +00006077 /* Grab the read-lock on page 1. */
6078 rc = lockTable(p, 1, READ_LOCK);
drhd677b3d2007-08-20 22:48:41 +00006079 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00006080 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006081}
6082
6083/*
drh23e11ca2004-05-04 17:27:28 +00006084** Write meta-information back into the database. Meta[0] is
6085** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00006086*/
danielk1977aef0bf62005-12-30 16:28:01 +00006087int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
6088 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00006089 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00006090 int rc;
drh23e11ca2004-05-04 17:27:28 +00006091 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00006092 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00006093 if( p->inTrans!=TRANS_WRITE ){
drhd677b3d2007-08-20 22:48:41 +00006094 rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
6095 }else{
6096 assert( pBt->pPage1!=0 );
6097 pP1 = pBt->pPage1->aData;
6098 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6099 if( rc==SQLITE_OK ){
6100 put4byte(&pP1[36 + idx*4], iMeta);
6101 if( idx==7 ){
6102 assert( pBt->autoVacuum || iMeta==0 );
6103 assert( iMeta==0 || iMeta==1 );
6104 pBt->incrVacuum = iMeta;
6105 }
6106 }
drh5df72a52002-06-06 23:16:05 +00006107 }
drhd677b3d2007-08-20 22:48:41 +00006108 sqlite3BtreeLeave(p);
6109 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006110}
drh8c42ca92001-06-22 19:15:00 +00006111
drhf328bc82004-05-10 23:29:49 +00006112/*
6113** Return the flag byte at the beginning of the page that the cursor
6114** is currently pointing to.
6115*/
6116int sqlite3BtreeFlags(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00006117 /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
drh777e4c42006-01-13 04:31:58 +00006118 ** restoreOrClearCursorPosition() here.
danielk1977da184232006-01-05 11:34:32 +00006119 */
drhf328bc82004-05-10 23:29:49 +00006120 MemPage *pPage = pCur->pPage;
drh1fee73e2007-08-29 04:00:57 +00006121 assert( cursorHoldsMutex(pCur) );
drhd0679ed2007-08-28 22:24:34 +00006122 assert( pPage->pBt==pCur->pBt );
drhf328bc82004-05-10 23:29:49 +00006123 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
6124}
6125
drhdd793422001-06-28 01:54:48 +00006126
drhdd793422001-06-28 01:54:48 +00006127/*
drh5eddca62001-06-30 21:53:53 +00006128** Return the pager associated with a BTree. This routine is used for
6129** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00006130*/
danielk1977aef0bf62005-12-30 16:28:01 +00006131Pager *sqlite3BtreePager(Btree *p){
6132 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00006133}
drh5eddca62001-06-30 21:53:53 +00006134
drhb7f91642004-10-31 02:22:47 +00006135#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006136/*
6137** Append a message to the error message string.
6138*/
drh2e38c322004-09-03 18:38:44 +00006139static void checkAppendMsg(
6140 IntegrityCk *pCheck,
6141 char *zMsg1,
6142 const char *zFormat,
6143 ...
6144){
6145 va_list ap;
6146 char *zMsg2;
drh1dcdbc02007-01-27 02:24:54 +00006147 if( !pCheck->mxErr ) return;
6148 pCheck->mxErr--;
6149 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00006150 va_start(ap, zFormat);
danielk19771e536952007-08-16 10:09:01 +00006151 zMsg2 = sqlite3VMPrintf(0, zFormat, ap);
drh2e38c322004-09-03 18:38:44 +00006152 va_end(ap);
6153 if( zMsg1==0 ) zMsg1 = "";
drh5eddca62001-06-30 21:53:53 +00006154 if( pCheck->zErrMsg ){
6155 char *zOld = pCheck->zErrMsg;
6156 pCheck->zErrMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00006157 sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
drh17435752007-08-16 04:30:38 +00006158 sqlite3_free(zOld);
drh5eddca62001-06-30 21:53:53 +00006159 }else{
danielk19774adee202004-05-08 08:23:19 +00006160 sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00006161 }
drh17435752007-08-16 04:30:38 +00006162 sqlite3_free(zMsg2);
drh5eddca62001-06-30 21:53:53 +00006163}
drhb7f91642004-10-31 02:22:47 +00006164#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006165
drhb7f91642004-10-31 02:22:47 +00006166#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006167/*
6168** Add 1 to the reference count for page iPage. If this is the second
6169** reference to the page, add an error message to pCheck->zErrMsg.
6170** Return 1 if there are 2 ore more references to the page and 0 if
6171** if this is the first reference to the page.
6172**
6173** Also check that the page number is in bounds.
6174*/
drhaaab5722002-02-19 13:39:21 +00006175static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00006176 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00006177 if( iPage>pCheck->nPage || iPage<0 ){
drh2e38c322004-09-03 18:38:44 +00006178 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006179 return 1;
6180 }
6181 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00006182 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006183 return 1;
6184 }
6185 return (pCheck->anRef[iPage]++)>1;
6186}
6187
danielk1977afcdd022004-10-31 16:25:42 +00006188#ifndef SQLITE_OMIT_AUTOVACUUM
6189/*
6190** Check that the entry in the pointer-map for page iChild maps to
6191** page iParent, pointer type ptrType. If not, append an error message
6192** to pCheck.
6193*/
6194static void checkPtrmap(
6195 IntegrityCk *pCheck, /* Integrity check context */
6196 Pgno iChild, /* Child page number */
6197 u8 eType, /* Expected pointer map type */
6198 Pgno iParent, /* Expected pointer map parent page number */
6199 char *zContext /* Context description (used for error msg) */
6200){
6201 int rc;
6202 u8 ePtrmapType;
6203 Pgno iPtrmapParent;
6204
6205 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
6206 if( rc!=SQLITE_OK ){
6207 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
6208 return;
6209 }
6210
6211 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
6212 checkAppendMsg(pCheck, zContext,
6213 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
6214 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
6215 }
6216}
6217#endif
6218
drh5eddca62001-06-30 21:53:53 +00006219/*
6220** Check the integrity of the freelist or of an overflow page list.
6221** Verify that the number of pages on the list is N.
6222*/
drh30e58752002-03-02 20:41:57 +00006223static void checkList(
6224 IntegrityCk *pCheck, /* Integrity checking context */
6225 int isFreeList, /* True for a freelist. False for overflow page list */
6226 int iPage, /* Page number for first page in the list */
6227 int N, /* Expected number of pages in the list */
6228 char *zContext /* Context for error messages */
6229){
6230 int i;
drh3a4c1412004-05-09 20:40:11 +00006231 int expected = N;
6232 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00006233 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00006234 DbPage *pOvflPage;
6235 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00006236 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00006237 checkAppendMsg(pCheck, zContext,
6238 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00006239 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00006240 break;
6241 }
6242 if( checkRef(pCheck, iPage, zContext) ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00006243 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
drh2e38c322004-09-03 18:38:44 +00006244 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006245 break;
6246 }
danielk19773b8a05f2007-03-19 17:44:26 +00006247 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00006248 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00006249 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00006250#ifndef SQLITE_OMIT_AUTOVACUUM
6251 if( pCheck->pBt->autoVacuum ){
6252 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
6253 }
6254#endif
drh855eb1c2004-08-31 13:45:11 +00006255 if( n>pCheck->pBt->usableSize/4-8 ){
drh2e38c322004-09-03 18:38:44 +00006256 checkAppendMsg(pCheck, zContext,
6257 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00006258 N--;
6259 }else{
6260 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00006261 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00006262#ifndef SQLITE_OMIT_AUTOVACUUM
6263 if( pCheck->pBt->autoVacuum ){
6264 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
6265 }
6266#endif
6267 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00006268 }
6269 N -= n;
drh30e58752002-03-02 20:41:57 +00006270 }
drh30e58752002-03-02 20:41:57 +00006271 }
danielk1977afcdd022004-10-31 16:25:42 +00006272#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006273 else{
6274 /* If this database supports auto-vacuum and iPage is not the last
6275 ** page in this overflow list, check that the pointer-map entry for
6276 ** the following page matches iPage.
6277 */
6278 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00006279 i = get4byte(pOvflData);
danielk1977687566d2004-11-02 12:56:41 +00006280 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
6281 }
danielk1977afcdd022004-10-31 16:25:42 +00006282 }
6283#endif
danielk19773b8a05f2007-03-19 17:44:26 +00006284 iPage = get4byte(pOvflData);
6285 sqlite3PagerUnref(pOvflPage);
drh5eddca62001-06-30 21:53:53 +00006286 }
6287}
drhb7f91642004-10-31 02:22:47 +00006288#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006289
drhb7f91642004-10-31 02:22:47 +00006290#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006291/*
6292** Do various sanity checks on a single page of a tree. Return
6293** the tree depth. Root pages return 0. Parents of root pages
6294** return 1, and so forth.
6295**
6296** These checks are done:
6297**
6298** 1. Make sure that cells and freeblocks do not overlap
6299** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00006300** NO 2. Make sure cell keys are in order.
6301** NO 3. Make sure no key is less than or equal to zLowerBound.
6302** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00006303** 5. Check the integrity of overflow pages.
6304** 6. Recursively call checkTreePage on all children.
6305** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00006306** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00006307** the root of the tree.
6308*/
6309static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00006310 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00006311 int iPage, /* Page number of the page to check */
6312 MemPage *pParent, /* Parent page */
drh74161702006-02-24 02:53:49 +00006313 char *zParentContext /* Parent context */
drh5eddca62001-06-30 21:53:53 +00006314){
6315 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00006316 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00006317 int hdr, cellStart;
6318 int nCell;
drhda200cc2004-05-09 11:51:38 +00006319 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00006320 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00006321 int usableSize;
drh5eddca62001-06-30 21:53:53 +00006322 char zContext[100];
drh2e38c322004-09-03 18:38:44 +00006323 char *hit;
drh5eddca62001-06-30 21:53:53 +00006324
drh5bb3eb92007-05-04 13:15:55 +00006325 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
danielk1977ef73ee92004-11-06 12:26:07 +00006326
drh5eddca62001-06-30 21:53:53 +00006327 /* Check that the page exists
6328 */
drhd9cb6ac2005-10-20 07:28:17 +00006329 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00006330 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00006331 if( iPage==0 ) return 0;
6332 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh16a9b832007-05-05 18:39:25 +00006333 if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drh2e38c322004-09-03 18:38:44 +00006334 checkAppendMsg(pCheck, zContext,
6335 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00006336 return 0;
6337 }
drh16a9b832007-05-05 18:39:25 +00006338 if( (rc = sqlite3BtreeInitPage(pPage, pParent))!=0 ){
6339 checkAppendMsg(pCheck, zContext,
6340 "sqlite3BtreeInitPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00006341 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00006342 return 0;
6343 }
6344
6345 /* Check out all the cells.
6346 */
6347 depth = 0;
drh1dcdbc02007-01-27 02:24:54 +00006348 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
drh6f11bef2004-05-13 01:12:56 +00006349 u8 *pCell;
6350 int sz;
6351 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00006352
6353 /* Check payload overflow pages
6354 */
drh5bb3eb92007-05-04 13:15:55 +00006355 sqlite3_snprintf(sizeof(zContext), zContext,
6356 "On tree page %d cell %d: ", iPage, i);
danielk19771cc5ed82007-05-16 17:28:43 +00006357 pCell = findCell(pPage,i);
drh16a9b832007-05-05 18:39:25 +00006358 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00006359 sz = info.nData;
6360 if( !pPage->intKey ) sz += info.nKey;
drh72365832007-03-06 15:53:44 +00006361 assert( sz==info.nPayload );
drh6f11bef2004-05-13 01:12:56 +00006362 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00006363 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00006364 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
6365#ifndef SQLITE_OMIT_AUTOVACUUM
6366 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006367 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00006368 }
6369#endif
6370 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00006371 }
6372
6373 /* Check sanity of left child page.
6374 */
drhda200cc2004-05-09 11:51:38 +00006375 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006376 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00006377#ifndef SQLITE_OMIT_AUTOVACUUM
6378 if( pBt->autoVacuum ){
6379 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
6380 }
6381#endif
drh74161702006-02-24 02:53:49 +00006382 d2 = checkTreePage(pCheck,pgno,pPage,zContext);
drhda200cc2004-05-09 11:51:38 +00006383 if( i>0 && d2!=depth ){
6384 checkAppendMsg(pCheck, zContext, "Child page depth differs");
6385 }
6386 depth = d2;
drh5eddca62001-06-30 21:53:53 +00006387 }
drh5eddca62001-06-30 21:53:53 +00006388 }
drhda200cc2004-05-09 11:51:38 +00006389 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006390 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh5bb3eb92007-05-04 13:15:55 +00006391 sqlite3_snprintf(sizeof(zContext), zContext,
6392 "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00006393#ifndef SQLITE_OMIT_AUTOVACUUM
6394 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00006395 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00006396 }
6397#endif
drh74161702006-02-24 02:53:49 +00006398 checkTreePage(pCheck, pgno, pPage, zContext);
drhda200cc2004-05-09 11:51:38 +00006399 }
drh5eddca62001-06-30 21:53:53 +00006400
6401 /* Check for complete coverage of the page
6402 */
drhda200cc2004-05-09 11:51:38 +00006403 data = pPage->aData;
6404 hdr = pPage->hdrOffset;
drh17435752007-08-16 04:30:38 +00006405 hit = sqlite3MallocZero( usableSize );
drh2e38c322004-09-03 18:38:44 +00006406 if( hit ){
6407 memset(hit, 1, get2byte(&data[hdr+5]));
6408 nCell = get2byte(&data[hdr+3]);
6409 cellStart = hdr + 12 - 4*pPage->leaf;
6410 for(i=0; i<nCell; i++){
6411 int pc = get2byte(&data[cellStart+i*2]);
6412 int size = cellSizePtr(pPage, &data[pc]);
6413 int j;
danielk19777701e812005-01-10 12:59:51 +00006414 if( (pc+size-1)>=usableSize || pc<0 ){
6415 checkAppendMsg(pCheck, 0,
6416 "Corruption detected in cell %d on page %d",i,iPage,0);
6417 }else{
6418 for(j=pc+size-1; j>=pc; j--) hit[j]++;
6419 }
drh2e38c322004-09-03 18:38:44 +00006420 }
6421 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
6422 cnt++){
6423 int size = get2byte(&data[i+2]);
6424 int j;
danielk19777701e812005-01-10 12:59:51 +00006425 if( (i+size-1)>=usableSize || i<0 ){
6426 checkAppendMsg(pCheck, 0,
6427 "Corruption detected in cell %d on page %d",i,iPage,0);
6428 }else{
6429 for(j=i+size-1; j>=i; j--) hit[j]++;
6430 }
drh2e38c322004-09-03 18:38:44 +00006431 i = get2byte(&data[i]);
6432 }
6433 for(i=cnt=0; i<usableSize; i++){
6434 if( hit[i]==0 ){
6435 cnt++;
6436 }else if( hit[i]>1 ){
6437 checkAppendMsg(pCheck, 0,
6438 "Multiple uses for byte %d of page %d", i, iPage);
6439 break;
6440 }
6441 }
6442 if( cnt!=data[hdr+7] ){
6443 checkAppendMsg(pCheck, 0,
6444 "Fragmented space is %d byte reported as %d on page %d",
6445 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00006446 }
6447 }
drh17435752007-08-16 04:30:38 +00006448 sqlite3_free(hit);
drh6019e162001-07-02 17:51:45 +00006449
drh4b70f112004-05-02 21:12:19 +00006450 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00006451 return depth+1;
drh5eddca62001-06-30 21:53:53 +00006452}
drhb7f91642004-10-31 02:22:47 +00006453#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006454
drhb7f91642004-10-31 02:22:47 +00006455#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006456/*
6457** This routine does a complete check of the given BTree file. aRoot[] is
6458** an array of pages numbers were each page number is the root page of
6459** a table. nRoot is the number of entries in aRoot.
6460**
6461** If everything checks out, this routine returns NULL. If something is
6462** amiss, an error message is written into memory obtained from malloc()
6463** and a pointer to that error message is returned. The calling function
6464** is responsible for freeing the error message when it is done.
6465*/
drh1dcdbc02007-01-27 02:24:54 +00006466char *sqlite3BtreeIntegrityCheck(
6467 Btree *p, /* The btree to be checked */
6468 int *aRoot, /* An array of root pages numbers for individual trees */
6469 int nRoot, /* Number of entries in aRoot[] */
6470 int mxErr, /* Stop reporting errors after this many */
6471 int *pnErr /* Write number of errors seen to this variable */
6472){
drh5eddca62001-06-30 21:53:53 +00006473 int i;
6474 int nRef;
drhaaab5722002-02-19 13:39:21 +00006475 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00006476 BtShared *pBt = p->pBt;
drh5eddca62001-06-30 21:53:53 +00006477
drhd677b3d2007-08-20 22:48:41 +00006478 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00006479 nRef = sqlite3PagerRefcount(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00006480 if( lockBtreeWithRetry(p)!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00006481 sqlite3BtreeLeave(p);
drh17435752007-08-16 04:30:38 +00006482 return sqlite3StrDup("Unable to acquire a read lock on the database");
drhefc251d2001-07-01 22:12:01 +00006483 }
drh5eddca62001-06-30 21:53:53 +00006484 sCheck.pBt = pBt;
6485 sCheck.pPager = pBt->pPager;
danielk19773b8a05f2007-03-19 17:44:26 +00006486 sCheck.nPage = sqlite3PagerPagecount(sCheck.pPager);
drh1dcdbc02007-01-27 02:24:54 +00006487 sCheck.mxErr = mxErr;
6488 sCheck.nErr = 0;
6489 *pnErr = 0;
danielk1977e5321f02007-04-27 07:05:44 +00006490#ifndef SQLITE_OMIT_AUTOVACUUM
6491 if( pBt->nTrunc!=0 ){
6492 sCheck.nPage = pBt->nTrunc;
6493 }
6494#endif
drh0de8c112002-07-06 16:32:14 +00006495 if( sCheck.nPage==0 ){
6496 unlockBtreeIfUnused(pBt);
drhd677b3d2007-08-20 22:48:41 +00006497 sqlite3BtreeLeave(p);
drh0de8c112002-07-06 16:32:14 +00006498 return 0;
6499 }
drh17435752007-08-16 04:30:38 +00006500 sCheck.anRef = sqlite3_malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00006501 if( !sCheck.anRef ){
6502 unlockBtreeIfUnused(pBt);
drh1dcdbc02007-01-27 02:24:54 +00006503 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00006504 sqlite3BtreeLeave(p);
danielk19771e536952007-08-16 10:09:01 +00006505 return sqlite3MPrintf(p->pSqlite, "Unable to malloc %d bytes",
danielk1977ac245ec2005-01-14 13:50:11 +00006506 (sCheck.nPage+1)*sizeof(sCheck.anRef[0]));
6507 }
drhda200cc2004-05-09 11:51:38 +00006508 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00006509 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00006510 if( i<=sCheck.nPage ){
6511 sCheck.anRef[i] = 1;
6512 }
drh5eddca62001-06-30 21:53:53 +00006513 sCheck.zErrMsg = 0;
6514
6515 /* Check the integrity of the freelist
6516 */
drha34b6762004-05-07 13:30:42 +00006517 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
6518 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00006519
6520 /* Check all the tables.
6521 */
drh1dcdbc02007-01-27 02:24:54 +00006522 for(i=0; i<nRoot && sCheck.mxErr; i++){
drh4ff6dfa2002-03-03 23:06:00 +00006523 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00006524#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006525 if( pBt->autoVacuum && aRoot[i]>1 ){
6526 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
6527 }
6528#endif
drh74161702006-02-24 02:53:49 +00006529 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ");
drh5eddca62001-06-30 21:53:53 +00006530 }
6531
6532 /* Make sure every page in the file is referenced
6533 */
drh1dcdbc02007-01-27 02:24:54 +00006534 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00006535#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00006536 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00006537 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00006538 }
danielk1977afcdd022004-10-31 16:25:42 +00006539#else
6540 /* If the database supports auto-vacuum, make sure no tables contain
6541 ** references to pointer-map pages.
6542 */
6543 if( sCheck.anRef[i]==0 &&
danielk1977266664d2006-02-10 08:24:21 +00006544 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006545 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
6546 }
6547 if( sCheck.anRef[i]!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00006548 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006549 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
6550 }
6551#endif
drh5eddca62001-06-30 21:53:53 +00006552 }
6553
6554 /* Make sure this analysis did not leave any unref() pages
6555 */
drh5e00f6c2001-09-13 13:46:56 +00006556 unlockBtreeIfUnused(pBt);
danielk19773b8a05f2007-03-19 17:44:26 +00006557 if( nRef != sqlite3PagerRefcount(pBt->pPager) ){
drh2e38c322004-09-03 18:38:44 +00006558 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00006559 "Outstanding page count goes from %d to %d during this analysis",
danielk19773b8a05f2007-03-19 17:44:26 +00006560 nRef, sqlite3PagerRefcount(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00006561 );
drh5eddca62001-06-30 21:53:53 +00006562 }
6563
6564 /* Clean up and report errors.
6565 */
drhd677b3d2007-08-20 22:48:41 +00006566 sqlite3BtreeLeave(p);
drh17435752007-08-16 04:30:38 +00006567 sqlite3_free(sCheck.anRef);
drh1dcdbc02007-01-27 02:24:54 +00006568 *pnErr = sCheck.nErr;
drh5eddca62001-06-30 21:53:53 +00006569 return sCheck.zErrMsg;
6570}
drhb7f91642004-10-31 02:22:47 +00006571#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00006572
drh73509ee2003-04-06 20:44:45 +00006573/*
6574** Return the full pathname of the underlying database file.
drhd0679ed2007-08-28 22:24:34 +00006575**
6576** The pager filename is invariant as long as the pager is
6577** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +00006578*/
danielk1977aef0bf62005-12-30 16:28:01 +00006579const char *sqlite3BtreeGetFilename(Btree *p){
6580 assert( p->pBt->pPager!=0 );
drh1fee73e2007-08-29 04:00:57 +00006581 /* assert( sqlite3BtreeHoldsMutex(p) ); */
danielk19773b8a05f2007-03-19 17:44:26 +00006582 return sqlite3PagerFilename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00006583}
6584
6585/*
danielk19775865e3d2004-06-14 06:03:57 +00006586** Return the pathname of the directory that contains the database file.
drhd0679ed2007-08-28 22:24:34 +00006587**
6588** The pager directory name is invariant as long as the pager is
6589** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00006590*/
danielk1977aef0bf62005-12-30 16:28:01 +00006591const char *sqlite3BtreeGetDirname(Btree *p){
6592 assert( p->pBt->pPager!=0 );
drh1fee73e2007-08-29 04:00:57 +00006593 assert( sqlite3BtreeHoldsMutex(p) );
danielk19773b8a05f2007-03-19 17:44:26 +00006594 return sqlite3PagerDirname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006595}
6596
6597/*
6598** Return the pathname of the journal file for this database. The return
6599** value of this routine is the same regardless of whether the journal file
6600** has been created or not.
drhd0679ed2007-08-28 22:24:34 +00006601**
6602** The pager journal filename is invariant as long as the pager is
6603** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00006604*/
danielk1977aef0bf62005-12-30 16:28:01 +00006605const char *sqlite3BtreeGetJournalname(Btree *p){
6606 assert( p->pBt->pPager!=0 );
drh1fee73e2007-08-29 04:00:57 +00006607 assert( sqlite3BtreeHoldsMutex(p) );
danielk19773b8a05f2007-03-19 17:44:26 +00006608 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006609}
6610
drhb7f91642004-10-31 02:22:47 +00006611#ifndef SQLITE_OMIT_VACUUM
danielk19775865e3d2004-06-14 06:03:57 +00006612/*
drhf7c57532003-04-25 13:22:51 +00006613** Copy the complete content of pBtFrom into pBtTo. A transaction
6614** must be active for both files.
6615**
6616** The size of file pBtFrom may be reduced by this operation.
drh43605152004-05-29 21:46:49 +00006617** If anything goes wrong, the transaction on pBtFrom is rolled back.
drh73509ee2003-04-06 20:44:45 +00006618*/
drhd677b3d2007-08-20 22:48:41 +00006619static int btreeCopyFile(Btree *pTo, Btree *pFrom){
drhf7c57532003-04-25 13:22:51 +00006620 int rc = SQLITE_OK;
drh50f2f432005-09-16 11:32:18 +00006621 Pgno i, nPage, nToPage, iSkip;
drhf7c57532003-04-25 13:22:51 +00006622
danielk1977aef0bf62005-12-30 16:28:01 +00006623 BtShared *pBtTo = pTo->pBt;
6624 BtShared *pBtFrom = pFrom->pBt;
6625
6626 if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
danielk1977ee5741e2004-05-31 10:01:34 +00006627 return SQLITE_ERROR;
6628 }
drhf7c57532003-04-25 13:22:51 +00006629 if( pBtTo->pCursor ) return SQLITE_BUSY;
danielk19773b8a05f2007-03-19 17:44:26 +00006630 nToPage = sqlite3PagerPagecount(pBtTo->pPager);
6631 nPage = sqlite3PagerPagecount(pBtFrom->pPager);
drh50f2f432005-09-16 11:32:18 +00006632 iSkip = PENDING_BYTE_PAGE(pBtTo);
danielk1977369f27e2004-06-15 11:40:04 +00006633 for(i=1; rc==SQLITE_OK && i<=nPage; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00006634 DbPage *pDbPage;
drh50f2f432005-09-16 11:32:18 +00006635 if( i==iSkip ) continue;
danielk19773b8a05f2007-03-19 17:44:26 +00006636 rc = sqlite3PagerGet(pBtFrom->pPager, i, &pDbPage);
drhf7c57532003-04-25 13:22:51 +00006637 if( rc ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00006638 rc = sqlite3PagerOverwrite(pBtTo->pPager, i, sqlite3PagerGetData(pDbPage));
6639 sqlite3PagerUnref(pDbPage);
drhf7c57532003-04-25 13:22:51 +00006640 }
drh538f5702007-04-13 02:14:30 +00006641
6642 /* If the file is shrinking, journal the pages that are being truncated
6643 ** so that they can be rolled back if the commit fails.
6644 */
drh2e6d11b2003-04-25 15:37:57 +00006645 for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00006646 DbPage *pDbPage;
drh49285702005-09-17 15:20:26 +00006647 if( i==iSkip ) continue;
danielk19773b8a05f2007-03-19 17:44:26 +00006648 rc = sqlite3PagerGet(pBtTo->pPager, i, &pDbPage);
drh2e6d11b2003-04-25 15:37:57 +00006649 if( rc ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00006650 rc = sqlite3PagerWrite(pDbPage);
drh538f5702007-04-13 02:14:30 +00006651 sqlite3PagerDontWrite(pDbPage);
6652 /* Yeah. It seems wierd to call DontWrite() right after Write(). But
6653 ** that is because the names of those procedures do not exactly
6654 ** represent what they do. Write() really means "put this page in the
6655 ** rollback journal and mark it as dirty so that it will be written
6656 ** to the database file later." DontWrite() undoes the second part of
6657 ** that and prevents the page from being written to the database. The
6658 ** page is still on the rollback journal, though. And that is the whole
6659 ** point of this loop: to put pages on the rollback journal. */
danielk19773b8a05f2007-03-19 17:44:26 +00006660 sqlite3PagerUnref(pDbPage);
drh2e6d11b2003-04-25 15:37:57 +00006661 }
6662 if( !rc && nPage<nToPage ){
danielk19773b8a05f2007-03-19 17:44:26 +00006663 rc = sqlite3PagerTruncate(pBtTo->pPager, nPage);
drh2e6d11b2003-04-25 15:37:57 +00006664 }
drh538f5702007-04-13 02:14:30 +00006665
drhf7c57532003-04-25 13:22:51 +00006666 if( rc ){
danielk1977aef0bf62005-12-30 16:28:01 +00006667 sqlite3BtreeRollback(pTo);
drhf7c57532003-04-25 13:22:51 +00006668 }
6669 return rc;
drh73509ee2003-04-06 20:44:45 +00006670}
drhd677b3d2007-08-20 22:48:41 +00006671int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
6672 int rc;
6673 sqlite3BtreeEnter(pTo);
6674 sqlite3BtreeEnter(pFrom);
6675 rc = btreeCopyFile(pTo, pFrom);
6676 sqlite3BtreeLeave(pFrom);
6677 sqlite3BtreeLeave(pTo);
6678 return rc;
6679}
6680
drhb7f91642004-10-31 02:22:47 +00006681#endif /* SQLITE_OMIT_VACUUM */
danielk19771d850a72004-05-31 08:26:49 +00006682
6683/*
6684** Return non-zero if a transaction is active.
6685*/
danielk1977aef0bf62005-12-30 16:28:01 +00006686int sqlite3BtreeIsInTrans(Btree *p){
drh1fee73e2007-08-29 04:00:57 +00006687 assert( p==0 || sqlite3_mutex_held(p->pSqlite->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00006688 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00006689}
6690
6691/*
6692** Return non-zero if a statement transaction is active.
6693*/
danielk1977aef0bf62005-12-30 16:28:01 +00006694int sqlite3BtreeIsInStmt(Btree *p){
drh1fee73e2007-08-29 04:00:57 +00006695 assert( sqlite3BtreeHoldsMutex(p) );
danielk1977aef0bf62005-12-30 16:28:01 +00006696 return (p->pBt && p->pBt->inStmt);
danielk19771d850a72004-05-31 08:26:49 +00006697}
danielk197713adf8a2004-06-03 16:08:41 +00006698
6699/*
danielk19772372c2b2006-06-27 16:34:56 +00006700** Return non-zero if a read (or write) transaction is active.
6701*/
6702int sqlite3BtreeIsInReadTrans(Btree *p){
drh1fee73e2007-08-29 04:00:57 +00006703 assert( sqlite3_mutex_held(p->pSqlite->mutex) );
danielk19772372c2b2006-06-27 16:34:56 +00006704 return (p && (p->inTrans!=TRANS_NONE));
6705}
6706
6707/*
danielk1977da184232006-01-05 11:34:32 +00006708** This function returns a pointer to a blob of memory associated with
6709** a single shared-btree. The memory is used by client code for it's own
6710** purposes (for example, to store a high-level schema associated with
6711** the shared-btree). The btree layer manages reference counting issues.
6712**
6713** The first time this is called on a shared-btree, nBytes bytes of memory
6714** are allocated, zeroed, and returned to the caller. For each subsequent
6715** call the nBytes parameter is ignored and a pointer to the same blob
6716** of memory returned.
6717**
6718** Just before the shared-btree is closed, the function passed as the
6719** xFree argument when the memory allocation was made is invoked on the
drh17435752007-08-16 04:30:38 +00006720** blob of allocated memory. This function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +00006721** on the memory, the btree layer does that.
6722*/
6723void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
6724 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +00006725 sqlite3BtreeEnter(p);
danielk1977da184232006-01-05 11:34:32 +00006726 if( !pBt->pSchema ){
drh17435752007-08-16 04:30:38 +00006727 pBt->pSchema = sqlite3MallocZero(nBytes);
danielk1977da184232006-01-05 11:34:32 +00006728 pBt->xFreeSchema = xFree;
6729 }
drh27641702007-08-22 02:56:42 +00006730 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00006731 return pBt->pSchema;
6732}
6733
danielk1977c87d34d2006-01-06 13:00:28 +00006734/*
6735** Return true if another user of the same shared btree as the argument
6736** handle holds an exclusive lock on the sqlite_master table.
6737*/
6738int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +00006739 int rc;
drh1fee73e2007-08-29 04:00:57 +00006740 assert( sqlite3_mutex_held(p->pSqlite->mutex) );
drh27641702007-08-22 02:56:42 +00006741 sqlite3BtreeEnter(p);
6742 rc = (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
6743 sqlite3BtreeLeave(p);
6744 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +00006745}
6746
drha154dcd2006-03-22 22:10:07 +00006747
6748#ifndef SQLITE_OMIT_SHARED_CACHE
6749/*
6750** Obtain a lock on the table whose root page is iTab. The
6751** lock is a write lock if isWritelock is true or a read lock
6752** if it is false.
6753*/
danielk1977c00da102006-01-07 13:21:04 +00006754int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00006755 int rc = SQLITE_OK;
danielk1977c00da102006-01-07 13:21:04 +00006756 u8 lockType = (isWriteLock?WRITE_LOCK:READ_LOCK);
drhd677b3d2007-08-20 22:48:41 +00006757 sqlite3BtreeEnter(p);
danielk19772e94d4d2006-01-09 05:36:27 +00006758 rc = queryTableLock(p, iTab, lockType);
danielk1977c00da102006-01-07 13:21:04 +00006759 if( rc==SQLITE_OK ){
6760 rc = lockTable(p, iTab, lockType);
6761 }
drhd677b3d2007-08-20 22:48:41 +00006762 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +00006763 return rc;
6764}
drha154dcd2006-03-22 22:10:07 +00006765#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00006766
danielk1977b4e9af92007-05-01 17:49:49 +00006767#ifndef SQLITE_OMIT_INCRBLOB
6768/*
6769** Argument pCsr must be a cursor opened for writing on an
6770** INTKEY table currently pointing at a valid table entry.
6771** This function modifies the data stored as part of that entry.
6772** Only the data content may only be modified, it is not possible
6773** to change the length of the data stored.
6774*/
danielk1977dcbb5d32007-05-04 18:36:44 +00006775int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
drh1fee73e2007-08-29 04:00:57 +00006776 assert( cursorHoldsMutex(pCsr) );
6777 assert( sqlite3_mutex_held(pCsr->pBtree->pSqlite->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00006778 assert(pCsr->isIncrblobHandle);
6779 if( pCsr->eState==CURSOR_REQUIRESEEK ){
6780 return SQLITE_ABORT;
6781 }
6782
danielk1977d04417962007-05-02 13:16:30 +00006783 /* Check some preconditions:
danielk1977dcbb5d32007-05-04 18:36:44 +00006784 ** (a) the cursor is open for writing,
6785 ** (b) there is no read-lock on the table being modified and
6786 ** (c) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00006787 */
danielk1977d04417962007-05-02 13:16:30 +00006788 if( !pCsr->wrFlag ){
danielk1977dcbb5d32007-05-04 18:36:44 +00006789 return SQLITE_READONLY;
danielk1977d04417962007-05-02 13:16:30 +00006790 }
drhd0679ed2007-08-28 22:24:34 +00006791 assert( !pCsr->pBt->readOnly
6792 && pCsr->pBt->inTransaction==TRANS_WRITE );
danielk1977d04417962007-05-02 13:16:30 +00006793 if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr) ){
6794 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
6795 }
6796 if( pCsr->eState==CURSOR_INVALID || !pCsr->pPage->intKey ){
6797 return SQLITE_ERROR;
danielk1977b4e9af92007-05-01 17:49:49 +00006798 }
6799
danielk19779f8d6402007-05-02 17:48:45 +00006800 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00006801}
danielk19772dec9702007-05-02 16:48:37 +00006802
6803/*
6804** Set a flag on this cursor to cache the locations of pages from the
danielk1977da107192007-05-04 08:32:13 +00006805** overflow list for the current row. This is used by cursors opened
6806** for incremental blob IO only.
6807**
6808** This function sets a flag only. The actual page location cache
6809** (stored in BtCursor.aOverflow[]) is allocated and used by function
6810** accessPayload() (the worker function for sqlite3BtreeData() and
6811** sqlite3BtreePutData()).
danielk19772dec9702007-05-02 16:48:37 +00006812*/
6813void sqlite3BtreeCacheOverflow(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00006814 assert( cursorHoldsMutex(pCur) );
6815 assert( sqlite3_mutex_held(pCur->pBtree->pSqlite->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00006816 assert(!pCur->isIncrblobHandle);
danielk19772dec9702007-05-02 16:48:37 +00006817 assert(!pCur->aOverflow);
danielk1977dcbb5d32007-05-04 18:36:44 +00006818 pCur->isIncrblobHandle = 1;
danielk19772dec9702007-05-02 16:48:37 +00006819}
danielk1977b4e9af92007-05-01 17:49:49 +00006820#endif