blob: 09d02965485cd476adecfeefd5a4785bb790a5a0 [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*************************************************************************
drhfd131da2007-08-07 17:13:03 +000012** $Id: btree.c,v 1.395 2007/08/07 17:13:04 drh Exp $
drh8b2f49b2001-06-08 00:21:52 +000013**
14** This file implements a external (disk-based) database using BTrees.
drha3152892007-05-05 11:48:52 +000015** See the header comment on "btreeInt.h" for additional information.
16** Including a description of file format and an overview of operation.
drha059ad02001-04-17 20:09:11 +000017*/
drha3152892007-05-05 11:48:52 +000018#include "btreeInt.h"
paulb95a8862003-04-01 21:16:41 +000019
drh8c42ca92001-06-22 19:15:00 +000020/*
drha3152892007-05-05 11:48:52 +000021** The header string that appears at the beginning of every
22** SQLite database.
drh556b2a22005-06-14 16:04:05 +000023*/
drh556b2a22005-06-14 16:04:05 +000024static const char zMagicHeader[] = SQLITE_FILE_HEADER;
drh08ed44e2001-04-29 23:32:55 +000025
drh8c42ca92001-06-22 19:15:00 +000026
27/*
drha3152892007-05-05 11:48:52 +000028** Set this global variable to 1 to enable tracing using the TRACE
29** macro.
drh615ae552005-01-16 23:21:00 +000030*/
31#if SQLITE_TEST
drh0f7eb612006-08-08 13:51:43 +000032int sqlite3_btree_trace=0; /* True to enable tracing */
drh615ae552005-01-16 23:21:00 +000033#endif
drh615ae552005-01-16 23:21:00 +000034
35/*
drh66cbd152004-09-01 16:12:25 +000036** Forward declaration
37*/
drh980b1a72006-08-16 16:42:48 +000038static int checkReadLocks(Btree*,Pgno,BtCursor*);
drh66cbd152004-09-01 16:12:25 +000039
danielk1977aef0bf62005-12-30 16:28:01 +000040
41#ifdef SQLITE_OMIT_SHARED_CACHE
42 /*
43 ** The functions queryTableLock(), lockTable() and unlockAllTables()
44 ** manipulate entries in the BtShared.pLock linked list used to store
45 ** shared-cache table level locks. If the library is compiled with the
46 ** shared-cache feature disabled, then there is only ever one user
danielk1977da184232006-01-05 11:34:32 +000047 ** of each BtShared structure and so this locking is not necessary.
48 ** So define the lock related functions as no-ops.
danielk1977aef0bf62005-12-30 16:28:01 +000049 */
50 #define queryTableLock(a,b,c) SQLITE_OK
51 #define lockTable(a,b,c) SQLITE_OK
danielk1977da184232006-01-05 11:34:32 +000052 #define unlockAllTables(a)
danielk1977aef0bf62005-12-30 16:28:01 +000053#else
54
danielk1977da184232006-01-05 11:34:32 +000055/*
danielk1977aef0bf62005-12-30 16:28:01 +000056** Query to see if btree handle p may obtain a lock of type eLock
57** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
58** SQLITE_OK if the lock may be obtained (by calling lockTable()), or
danielk1977c87d34d2006-01-06 13:00:28 +000059** SQLITE_LOCKED if not.
danielk1977aef0bf62005-12-30 16:28:01 +000060*/
61static int queryTableLock(Btree *p, Pgno iTab, u8 eLock){
62 BtShared *pBt = p->pBt;
63 BtLock *pIter;
64
danielk1977da184232006-01-05 11:34:32 +000065 /* This is a no-op if the shared-cache is not enabled */
drh6f7adc82006-01-11 21:41:20 +000066 if( 0==sqlite3ThreadDataReadOnly()->useSharedData ){
danielk1977da184232006-01-05 11:34:32 +000067 return SQLITE_OK;
68 }
69
70 /* This (along with lockTable()) is where the ReadUncommitted flag is
71 ** dealt with. If the caller is querying for a read-lock and the flag is
72 ** set, it is unconditionally granted - even if there are write-locks
73 ** on the table. If a write-lock is requested, the ReadUncommitted flag
74 ** is not considered.
75 **
76 ** In function lockTable(), if a read-lock is demanded and the
77 ** ReadUncommitted flag is set, no entry is added to the locks list
78 ** (BtShared.pLock).
79 **
80 ** To summarize: If the ReadUncommitted flag is set, then read cursors do
81 ** not create or respect table locks. The locking procedure for a
82 ** write-cursor does not change.
83 */
84 if(
85 !p->pSqlite ||
86 0==(p->pSqlite->flags&SQLITE_ReadUncommitted) ||
87 eLock==WRITE_LOCK ||
drh47ded162006-01-06 01:42:58 +000088 iTab==MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +000089 ){
90 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
91 if( pIter->pBtree!=p && pIter->iTable==iTab &&
92 (pIter->eLock!=eLock || eLock!=READ_LOCK) ){
danielk1977c87d34d2006-01-06 13:00:28 +000093 return SQLITE_LOCKED;
danielk1977da184232006-01-05 11:34:32 +000094 }
danielk1977aef0bf62005-12-30 16:28:01 +000095 }
96 }
97 return SQLITE_OK;
98}
99
100/*
101** Add a lock on the table with root-page iTable to the shared-btree used
102** by Btree handle p. Parameter eLock must be either READ_LOCK or
103** WRITE_LOCK.
104**
105** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
106** SQLITE_NOMEM may also be returned.
107*/
108static int lockTable(Btree *p, Pgno iTable, u8 eLock){
109 BtShared *pBt = p->pBt;
110 BtLock *pLock = 0;
111 BtLock *pIter;
112
danielk1977da184232006-01-05 11:34:32 +0000113 /* This is a no-op if the shared-cache is not enabled */
drh6f7adc82006-01-11 21:41:20 +0000114 if( 0==sqlite3ThreadDataReadOnly()->useSharedData ){
danielk1977da184232006-01-05 11:34:32 +0000115 return SQLITE_OK;
116 }
117
danielk1977aef0bf62005-12-30 16:28:01 +0000118 assert( SQLITE_OK==queryTableLock(p, iTable, eLock) );
119
danielk1977da184232006-01-05 11:34:32 +0000120 /* If the read-uncommitted flag is set and a read-lock is requested,
121 ** return early without adding an entry to the BtShared.pLock list. See
122 ** comment in function queryTableLock() for more info on handling
123 ** the ReadUncommitted flag.
124 */
125 if(
126 (p->pSqlite) &&
127 (p->pSqlite->flags&SQLITE_ReadUncommitted) &&
128 (eLock==READ_LOCK) &&
drh47ded162006-01-06 01:42:58 +0000129 iTable!=MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000130 ){
131 return SQLITE_OK;
132 }
133
danielk1977aef0bf62005-12-30 16:28:01 +0000134 /* First search the list for an existing lock on this table. */
135 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
136 if( pIter->iTable==iTable && pIter->pBtree==p ){
137 pLock = pIter;
138 break;
139 }
140 }
141
142 /* If the above search did not find a BtLock struct associating Btree p
143 ** with table iTable, allocate one and link it into the list.
144 */
145 if( !pLock ){
146 pLock = (BtLock *)sqliteMalloc(sizeof(BtLock));
147 if( !pLock ){
148 return SQLITE_NOMEM;
149 }
150 pLock->iTable = iTable;
151 pLock->pBtree = p;
152 pLock->pNext = pBt->pLock;
153 pBt->pLock = pLock;
154 }
155
156 /* Set the BtLock.eLock variable to the maximum of the current lock
157 ** and the requested lock. This means if a write-lock was already held
158 ** and a read-lock requested, we don't incorrectly downgrade the lock.
159 */
160 assert( WRITE_LOCK>READ_LOCK );
danielk19775118b912005-12-30 16:31:53 +0000161 if( eLock>pLock->eLock ){
162 pLock->eLock = eLock;
163 }
danielk1977aef0bf62005-12-30 16:28:01 +0000164
165 return SQLITE_OK;
166}
167
168/*
169** Release all the table locks (locks obtained via calls to the lockTable()
170** procedure) held by Btree handle p.
171*/
172static void unlockAllTables(Btree *p){
173 BtLock **ppIter = &p->pBt->pLock;
danielk1977da184232006-01-05 11:34:32 +0000174
175 /* If the shared-cache extension is not enabled, there should be no
176 ** locks in the BtShared.pLock list, making this procedure a no-op. Assert
177 ** that this is the case.
178 */
drh6f7adc82006-01-11 21:41:20 +0000179 assert( sqlite3ThreadDataReadOnly()->useSharedData || 0==*ppIter );
danielk1977da184232006-01-05 11:34:32 +0000180
danielk1977aef0bf62005-12-30 16:28:01 +0000181 while( *ppIter ){
182 BtLock *pLock = *ppIter;
183 if( pLock->pBtree==p ){
184 *ppIter = pLock->pNext;
185 sqliteFree(pLock);
186 }else{
187 ppIter = &pLock->pNext;
188 }
189 }
190}
191#endif /* SQLITE_OMIT_SHARED_CACHE */
192
drh980b1a72006-08-16 16:42:48 +0000193static void releasePage(MemPage *pPage); /* Forward reference */
194
danielk197792d4d7a2007-05-04 12:05:56 +0000195#ifndef SQLITE_OMIT_INCRBLOB
196/*
197** Invalidate the overflow page-list cache for cursor pCur, if any.
198*/
199static void invalidateOverflowCache(BtCursor *pCur){
200 sqliteFree(pCur->aOverflow);
201 pCur->aOverflow = 0;
202}
203
204/*
205** Invalidate the overflow page-list cache for all cursors opened
206** on the shared btree structure pBt.
207*/
208static void invalidateAllOverflowCache(BtShared *pBt){
209 BtCursor *p;
210 for(p=pBt->pCursor; p; p=p->pNext){
211 invalidateOverflowCache(p);
212 }
213}
214#else
215 #define invalidateOverflowCache(x)
216 #define invalidateAllOverflowCache(x)
217#endif
218
drh980b1a72006-08-16 16:42:48 +0000219/*
220** Save the current cursor position in the variables BtCursor.nKey
221** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
222*/
223static int saveCursorPosition(BtCursor *pCur){
224 int rc;
225
226 assert( CURSOR_VALID==pCur->eState );
227 assert( 0==pCur->pKey );
228
229 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
230
231 /* If this is an intKey table, then the above call to BtreeKeySize()
232 ** stores the integer key in pCur->nKey. In this case this value is
233 ** all that is required. Otherwise, if pCur is not open on an intKey
234 ** table, then malloc space for and store the pCur->nKey bytes of key
235 ** data.
236 */
237 if( rc==SQLITE_OK && 0==pCur->pPage->intKey){
238 void *pKey = sqliteMalloc(pCur->nKey);
239 if( pKey ){
240 rc = sqlite3BtreeKey(pCur, 0, pCur->nKey, pKey);
241 if( rc==SQLITE_OK ){
242 pCur->pKey = pKey;
243 }else{
244 sqliteFree(pKey);
245 }
246 }else{
247 rc = SQLITE_NOMEM;
248 }
249 }
250 assert( !pCur->pPage->intKey || !pCur->pKey );
251
252 if( rc==SQLITE_OK ){
253 releasePage(pCur->pPage);
254 pCur->pPage = 0;
255 pCur->eState = CURSOR_REQUIRESEEK;
256 }
257
danielk197792d4d7a2007-05-04 12:05:56 +0000258 invalidateOverflowCache(pCur);
drh980b1a72006-08-16 16:42:48 +0000259 return rc;
260}
261
262/*
263** Save the positions of all cursors except pExcept open on the table
264** with root-page iRoot. Usually, this is called just before cursor
265** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
266*/
267static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
268 BtCursor *p;
269 for(p=pBt->pCursor; p; p=p->pNext){
270 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
271 p->eState==CURSOR_VALID ){
272 int rc = saveCursorPosition(p);
273 if( SQLITE_OK!=rc ){
274 return rc;
275 }
276 }
277 }
278 return SQLITE_OK;
279}
280
281/*
drhbf700f32007-03-31 02:36:44 +0000282** Clear the current cursor position.
283*/
284static void clearCursorPosition(BtCursor *pCur){
285 sqliteFree(pCur->pKey);
286 pCur->pKey = 0;
287 pCur->eState = CURSOR_INVALID;
288}
289
290/*
drh980b1a72006-08-16 16:42:48 +0000291** Restore the cursor to the position it was in (or as close to as possible)
292** when saveCursorPosition() was called. Note that this call deletes the
293** saved position info stored by saveCursorPosition(), so there can be
294** at most one effective restoreOrClearCursorPosition() call after each
295** saveCursorPosition().
296**
297** If the second argument argument - doSeek - is false, then instead of
298** returning the cursor to it's saved position, any saved position is deleted
299** and the cursor state set to CURSOR_INVALID.
300*/
drh16a9b832007-05-05 18:39:25 +0000301int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +0000302 int rc;
drh980b1a72006-08-16 16:42:48 +0000303 assert( pCur->eState==CURSOR_REQUIRESEEK );
danielk197732a0d8b2007-05-04 19:03:02 +0000304#ifndef SQLITE_OMIT_INCRBLOB
danielk1977dcbb5d32007-05-04 18:36:44 +0000305 if( pCur->isIncrblobHandle ){
306 return SQLITE_ABORT;
307 }
danielk197732a0d8b2007-05-04 19:03:02 +0000308#endif
drh980b1a72006-08-16 16:42:48 +0000309 pCur->eState = CURSOR_INVALID;
drhbf700f32007-03-31 02:36:44 +0000310 rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skip);
drh980b1a72006-08-16 16:42:48 +0000311 if( rc==SQLITE_OK ){
312 sqliteFree(pCur->pKey);
313 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +0000314 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drh980b1a72006-08-16 16:42:48 +0000315 }
316 return rc;
317}
318
drhbf700f32007-03-31 02:36:44 +0000319#define restoreOrClearCursorPosition(p) \
drh16a9b832007-05-05 18:39:25 +0000320 (p->eState==CURSOR_REQUIRESEEK ? \
321 sqlite3BtreeRestoreOrClearCursorPosition(p) : \
322 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +0000323
danielk1977599fcba2004-11-08 07:13:13 +0000324#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000325/*
drha3152892007-05-05 11:48:52 +0000326** Given a page number of a regular database page, return the page
327** number for the pointer-map page that contains the entry for the
328** input page number.
danielk1977afcdd022004-10-31 16:25:42 +0000329*/
danielk1977266664d2006-02-10 08:24:21 +0000330static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
331 int nPagesPerMapPage = (pBt->usableSize/5)+1;
332 int iPtrMap = (pgno-2)/nPagesPerMapPage;
333 int ret = (iPtrMap*nPagesPerMapPage) + 2;
334 if( ret==PENDING_BYTE_PAGE(pBt) ){
335 ret++;
336 }
337 return ret;
338}
danielk1977a19df672004-11-03 11:37:07 +0000339
danielk1977afcdd022004-10-31 16:25:42 +0000340/*
danielk1977afcdd022004-10-31 16:25:42 +0000341** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000342**
343** This routine updates the pointer map entry for page number 'key'
344** so that it maps to type 'eType' and parent page number 'pgno'.
345** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000346*/
danielk1977aef0bf62005-12-30 16:28:01 +0000347static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
danielk19773b8a05f2007-03-19 17:44:26 +0000348 DbPage *pDbPage; /* The pointer map page */
349 u8 *pPtrmap; /* The pointer map data */
350 Pgno iPtrmap; /* The pointer map page number */
351 int offset; /* Offset in pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000352 int rc;
353
danielk1977266664d2006-02-10 08:24:21 +0000354 /* The master-journal page number must never be used as a pointer map page */
355 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
356
danielk1977ac11ee62005-01-15 12:45:51 +0000357 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000358 if( key==0 ){
drh49285702005-09-17 15:20:26 +0000359 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000360 }
danielk1977266664d2006-02-10 08:24:21 +0000361 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000362 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977687566d2004-11-02 12:56:41 +0000363 if( rc!=SQLITE_OK ){
danielk1977afcdd022004-10-31 16:25:42 +0000364 return rc;
365 }
danielk1977266664d2006-02-10 08:24:21 +0000366 offset = PTRMAP_PTROFFSET(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000367 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000368
drh615ae552005-01-16 23:21:00 +0000369 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
370 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
danielk19773b8a05f2007-03-19 17:44:26 +0000371 rc = sqlite3PagerWrite(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000372 if( rc==SQLITE_OK ){
373 pPtrmap[offset] = eType;
374 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000375 }
danielk1977afcdd022004-10-31 16:25:42 +0000376 }
377
danielk19773b8a05f2007-03-19 17:44:26 +0000378 sqlite3PagerUnref(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000379 return rc;
danielk1977afcdd022004-10-31 16:25:42 +0000380}
381
382/*
383** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000384**
385** This routine retrieves the pointer map entry for page 'key', writing
386** the type and parent page number to *pEType and *pPgno respectively.
387** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000388*/
danielk1977aef0bf62005-12-30 16:28:01 +0000389static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +0000390 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000391 int iPtrmap; /* Pointer map page index */
392 u8 *pPtrmap; /* Pointer map page data */
393 int offset; /* Offset of entry in pointer map */
394 int rc;
395
danielk1977266664d2006-02-10 08:24:21 +0000396 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000397 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000398 if( rc!=0 ){
399 return rc;
400 }
danielk19773b8a05f2007-03-19 17:44:26 +0000401 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000402
danielk1977266664d2006-02-10 08:24:21 +0000403 offset = PTRMAP_PTROFFSET(pBt, key);
drh43617e92006-03-06 20:55:46 +0000404 assert( pEType!=0 );
405 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +0000406 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000407
danielk19773b8a05f2007-03-19 17:44:26 +0000408 sqlite3PagerUnref(pDbPage);
drh49285702005-09-17 15:20:26 +0000409 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000410 return SQLITE_OK;
411}
412
413#endif /* SQLITE_OMIT_AUTOVACUUM */
414
drh0d316a42002-08-11 20:10:47 +0000415/*
drh271efa52004-05-30 19:19:05 +0000416** Given a btree page and a cell index (0 means the first cell on
417** the page, 1 means the second cell, and so forth) return a pointer
418** to the cell content.
419**
420** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000421*/
danielk19771cc5ed82007-05-16 17:28:43 +0000422#define findCell(pPage, iCell) \
423 ((pPage)->aData + get2byte(&(pPage)->aData[(pPage)->cellOffset+2*(iCell)]))
drhe6e4d6b2007-08-05 23:52:05 +0000424#ifdef SQLITE_TEST
drh16a9b832007-05-05 18:39:25 +0000425u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell){
drh43605152004-05-29 21:46:49 +0000426 assert( iCell>=0 );
drh029f3f82007-06-20 15:14:10 +0000427 assert( iCell<get2byte(&pPage->aData[pPage->hdrOffset+3]) );
danielk19771cc5ed82007-05-16 17:28:43 +0000428 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000429}
drhe6e4d6b2007-08-05 23:52:05 +0000430#endif
drh43605152004-05-29 21:46:49 +0000431
432/*
drh16a9b832007-05-05 18:39:25 +0000433** This a more complex version of sqlite3BtreeFindCell() that works for
drh43605152004-05-29 21:46:49 +0000434** pages that do contain overflow cells. See insert
435*/
436static u8 *findOverflowCell(MemPage *pPage, int iCell){
437 int i;
438 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000439 int k;
440 struct _OvflCell *pOvfl;
441 pOvfl = &pPage->aOvfl[i];
442 k = pOvfl->idx;
443 if( k<=iCell ){
444 if( k==iCell ){
445 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000446 }
447 iCell--;
448 }
449 }
danielk19771cc5ed82007-05-16 17:28:43 +0000450 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000451}
452
453/*
454** Parse a cell content block and fill in the CellInfo structure. There
drh16a9b832007-05-05 18:39:25 +0000455** are two versions of this function. sqlite3BtreeParseCell() takes a
456** cell index as the second argument and sqlite3BtreeParseCellPtr()
457** takes a pointer to the body of the cell as its second argument.
danielk19771cc5ed82007-05-16 17:28:43 +0000458**
459** Within this file, the parseCell() macro can be called instead of
460** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
drh43605152004-05-29 21:46:49 +0000461*/
drh16a9b832007-05-05 18:39:25 +0000462void sqlite3BtreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000463 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000464 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000465 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000466){
drh271efa52004-05-30 19:19:05 +0000467 int n; /* Number bytes in cell content header */
468 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000469
470 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000471 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000472 n = pPage->childPtrSize;
473 assert( n==4-4*pPage->leaf );
drh8b18dd42004-05-12 19:18:15 +0000474 if( pPage->hasData ){
drh271efa52004-05-30 19:19:05 +0000475 n += getVarint32(&pCell[n], &nPayload);
drh8b18dd42004-05-12 19:18:15 +0000476 }else{
drh271efa52004-05-30 19:19:05 +0000477 nPayload = 0;
drh3aac2dd2004-04-26 14:10:20 +0000478 }
drh271efa52004-05-30 19:19:05 +0000479 pInfo->nData = nPayload;
drh504b6982006-01-22 21:52:56 +0000480 if( pPage->intKey ){
481 n += getVarint(&pCell[n], (u64 *)&pInfo->nKey);
482 }else{
483 u32 x;
484 n += getVarint32(&pCell[n], &x);
485 pInfo->nKey = x;
486 nPayload += x;
drh6f11bef2004-05-13 01:12:56 +0000487 }
drh72365832007-03-06 15:53:44 +0000488 pInfo->nPayload = nPayload;
drh504b6982006-01-22 21:52:56 +0000489 pInfo->nHeader = n;
drh271efa52004-05-30 19:19:05 +0000490 if( nPayload<=pPage->maxLocal ){
491 /* This is the (easy) common case where the entire payload fits
492 ** on the local page. No overflow is required.
493 */
494 int nSize; /* Total size of cell content in bytes */
drh6f11bef2004-05-13 01:12:56 +0000495 pInfo->nLocal = nPayload;
496 pInfo->iOverflow = 0;
drh271efa52004-05-30 19:19:05 +0000497 nSize = nPayload + n;
498 if( nSize<4 ){
499 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000500 }
drh271efa52004-05-30 19:19:05 +0000501 pInfo->nSize = nSize;
drh6f11bef2004-05-13 01:12:56 +0000502 }else{
drh271efa52004-05-30 19:19:05 +0000503 /* If the payload will not fit completely on the local page, we have
504 ** to decide how much to store locally and how much to spill onto
505 ** overflow pages. The strategy is to minimize the amount of unused
506 ** space on overflow pages while keeping the amount of local storage
507 ** in between minLocal and maxLocal.
508 **
509 ** Warning: changing the way overflow payload is distributed in any
510 ** way will result in an incompatible file format.
511 */
512 int minLocal; /* Minimum amount of payload held locally */
513 int maxLocal; /* Maximum amount of payload held locally */
514 int surplus; /* Overflow payload available for local storage */
515
516 minLocal = pPage->minLocal;
517 maxLocal = pPage->maxLocal;
518 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000519 if( surplus <= maxLocal ){
520 pInfo->nLocal = surplus;
521 }else{
522 pInfo->nLocal = minLocal;
523 }
524 pInfo->iOverflow = pInfo->nLocal + n;
525 pInfo->nSize = pInfo->iOverflow + 4;
526 }
drh3aac2dd2004-04-26 14:10:20 +0000527}
danielk19771cc5ed82007-05-16 17:28:43 +0000528#define parseCell(pPage, iCell, pInfo) \
529 sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
drh16a9b832007-05-05 18:39:25 +0000530void sqlite3BtreeParseCell(
drh43605152004-05-29 21:46:49 +0000531 MemPage *pPage, /* Page containing the cell */
532 int iCell, /* The cell index. First cell is 0 */
533 CellInfo *pInfo /* Fill in this structure */
534){
danielk19771cc5ed82007-05-16 17:28:43 +0000535 parseCell(pPage, iCell, pInfo);
drh43605152004-05-29 21:46:49 +0000536}
drh3aac2dd2004-04-26 14:10:20 +0000537
538/*
drh43605152004-05-29 21:46:49 +0000539** Compute the total number of bytes that a Cell needs in the cell
540** data area of the btree-page. The return number includes the cell
541** data header and the local payload, but not any overflow page or
542** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000543*/
danielk1977bc6ada42004-06-30 08:20:16 +0000544#ifndef NDEBUG
drh43605152004-05-29 21:46:49 +0000545static int cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000546 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000547 sqlite3BtreeParseCell(pPage, iCell, &info);
drh43605152004-05-29 21:46:49 +0000548 return info.nSize;
549}
danielk1977bc6ada42004-06-30 08:20:16 +0000550#endif
drh43605152004-05-29 21:46:49 +0000551static int cellSizePtr(MemPage *pPage, u8 *pCell){
552 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000553 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000554 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000555}
556
danielk197779a40da2005-01-16 08:00:01 +0000557#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +0000558/*
danielk197726836652005-01-17 01:33:13 +0000559** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +0000560** to an overflow page, insert an entry into the pointer-map
561** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +0000562*/
danielk197726836652005-01-17 01:33:13 +0000563static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
danielk197779a40da2005-01-16 08:00:01 +0000564 if( pCell ){
565 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000566 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh72365832007-03-06 15:53:44 +0000567 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk197779a40da2005-01-16 08:00:01 +0000568 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
569 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
570 return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
571 }
danielk1977ac11ee62005-01-15 12:45:51 +0000572 }
danielk197779a40da2005-01-16 08:00:01 +0000573 return SQLITE_OK;
danielk1977ac11ee62005-01-15 12:45:51 +0000574}
danielk197726836652005-01-17 01:33:13 +0000575/*
576** If the cell with index iCell on page pPage contains a pointer
577** to an overflow page, insert an entry into the pointer-map
578** for the overflow page.
579*/
580static int ptrmapPutOvfl(MemPage *pPage, int iCell){
581 u8 *pCell;
582 pCell = findOverflowCell(pPage, iCell);
583 return ptrmapPutOvflPtr(pPage, pCell);
584}
danielk197779a40da2005-01-16 08:00:01 +0000585#endif
586
danielk1977ac11ee62005-01-15 12:45:51 +0000587
drhda200cc2004-05-09 11:51:38 +0000588/*
drh72f82862001-05-24 21:06:34 +0000589** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +0000590** end of the page and all free space is collected into one
591** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +0000592** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +0000593*/
drh2e38c322004-09-03 18:38:44 +0000594static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000595 int i; /* Loop counter */
596 int pc; /* Address of a i-th cell */
597 int addr; /* Offset of first byte after cell pointer array */
598 int hdr; /* Offset to the page header */
599 int size; /* Size of a cell */
600 int usableSize; /* Number of usable bytes on a page */
601 int cellOffset; /* Offset to the cell pointer array */
602 int brk; /* Offset to the cell content area */
603 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +0000604 unsigned char *data; /* The page data */
605 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +0000606
danielk19773b8a05f2007-03-19 17:44:26 +0000607 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000608 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +0000609 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000610 assert( pPage->nOverflow==0 );
drh2e38c322004-09-03 18:38:44 +0000611 temp = sqliteMalloc( pPage->pBt->pageSize );
612 if( temp==0 ) return SQLITE_NOMEM;
drh43605152004-05-29 21:46:49 +0000613 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +0000614 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000615 cellOffset = pPage->cellOffset;
616 nCell = pPage->nCell;
617 assert( nCell==get2byte(&data[hdr+3]) );
618 usableSize = pPage->pBt->usableSize;
619 brk = get2byte(&data[hdr+5]);
620 memcpy(&temp[brk], &data[brk], usableSize - brk);
621 brk = usableSize;
622 for(i=0; i<nCell; i++){
623 u8 *pAddr; /* The i-th cell pointer */
624 pAddr = &data[cellOffset + i*2];
625 pc = get2byte(pAddr);
626 assert( pc<pPage->pBt->usableSize );
627 size = cellSizePtr(pPage, &temp[pc]);
628 brk -= size;
629 memcpy(&data[brk], &temp[pc], size);
630 put2byte(pAddr, brk);
drh2af926b2001-05-15 00:39:25 +0000631 }
drh43605152004-05-29 21:46:49 +0000632 assert( brk>=cellOffset+2*nCell );
633 put2byte(&data[hdr+5], brk);
634 data[hdr+1] = 0;
635 data[hdr+2] = 0;
636 data[hdr+7] = 0;
637 addr = cellOffset+2*nCell;
638 memset(&data[addr], 0, brk-addr);
drh2e38c322004-09-03 18:38:44 +0000639 sqliteFree(temp);
640 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +0000641}
642
drha059ad02001-04-17 20:09:11 +0000643/*
drh43605152004-05-29 21:46:49 +0000644** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +0000645**
drh9e572e62004-04-23 23:43:10 +0000646** Return the index into pPage->aData[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000647** the new allocation. Or return 0 if there is not enough free
648** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000649**
drh72f82862001-05-24 21:06:34 +0000650** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000651** nBytes of contiguous free space, then this routine automatically
652** calls defragementPage() to consolidate all free space before
653** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000654*/
drh9e572e62004-04-23 23:43:10 +0000655static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +0000656 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +0000657 int size;
drh24cd67e2004-05-10 16:18:47 +0000658 int nFrag;
drh43605152004-05-29 21:46:49 +0000659 int top;
660 int nCell;
661 int cellOffset;
drh9e572e62004-04-23 23:43:10 +0000662 unsigned char *data;
drh43605152004-05-29 21:46:49 +0000663
drh9e572e62004-04-23 23:43:10 +0000664 data = pPage->aData;
danielk19773b8a05f2007-03-19 17:44:26 +0000665 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000666 assert( pPage->pBt );
667 if( nByte<4 ) nByte = 4;
drh43605152004-05-29 21:46:49 +0000668 if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
669 pPage->nFree -= nByte;
drh9e572e62004-04-23 23:43:10 +0000670 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000671
672 nFrag = data[hdr+7];
673 if( nFrag<60 ){
674 /* Search the freelist looking for a slot big enough to satisfy the
675 ** space request. */
676 addr = hdr+1;
677 while( (pc = get2byte(&data[addr]))>0 ){
678 size = get2byte(&data[pc+2]);
679 if( size>=nByte ){
680 if( size<nByte+4 ){
681 memcpy(&data[addr], &data[pc], 2);
682 data[hdr+7] = nFrag + size - nByte;
683 return pc;
684 }else{
685 put2byte(&data[pc+2], size-nByte);
686 return pc + size - nByte;
687 }
688 }
689 addr = pc;
drh9e572e62004-04-23 23:43:10 +0000690 }
691 }
drh43605152004-05-29 21:46:49 +0000692
693 /* Allocate memory from the gap in between the cell pointer array
694 ** and the cell content area.
695 */
696 top = get2byte(&data[hdr+5]);
697 nCell = get2byte(&data[hdr+3]);
698 cellOffset = pPage->cellOffset;
699 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
drh2e38c322004-09-03 18:38:44 +0000700 if( defragmentPage(pPage) ) return 0;
drh43605152004-05-29 21:46:49 +0000701 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +0000702 }
drh43605152004-05-29 21:46:49 +0000703 top -= nByte;
704 assert( cellOffset + 2*nCell <= top );
705 put2byte(&data[hdr+5], top);
706 return top;
drh7e3b0a02001-04-28 16:52:40 +0000707}
708
709/*
drh9e572e62004-04-23 23:43:10 +0000710** Return a section of the pPage->aData to the freelist.
711** The first byte of the new free block is pPage->aDisk[start]
712** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +0000713**
714** Most of the effort here is involved in coalesing adjacent
715** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000716*/
drh9e572e62004-04-23 23:43:10 +0000717static void freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +0000718 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +0000719 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +0000720
drh9e572e62004-04-23 23:43:10 +0000721 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +0000722 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000723 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +0000724 assert( (start + size)<=pPage->pBt->usableSize );
drh9e572e62004-04-23 23:43:10 +0000725 if( size<4 ) size = 4;
726
drhfcce93f2006-02-22 03:08:32 +0000727#ifdef SQLITE_SECURE_DELETE
728 /* Overwrite deleted information with zeros when the SECURE_DELETE
729 ** option is enabled at compile-time */
730 memset(&data[start], 0, size);
731#endif
732
drh9e572e62004-04-23 23:43:10 +0000733 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +0000734 hdr = pPage->hdrOffset;
735 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +0000736 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +0000737 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000738 assert( pbegin>addr );
739 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +0000740 }
drhb6f41482004-05-14 01:58:11 +0000741 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000742 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +0000743 put2byte(&data[addr], start);
744 put2byte(&data[start], pbegin);
745 put2byte(&data[start+2], size);
drh2af926b2001-05-15 00:39:25 +0000746 pPage->nFree += size;
drh9e572e62004-04-23 23:43:10 +0000747
748 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +0000749 addr = pPage->hdrOffset + 1;
750 while( (pbegin = get2byte(&data[addr]))>0 ){
drh9e572e62004-04-23 23:43:10 +0000751 int pnext, psize;
drh3aac2dd2004-04-26 14:10:20 +0000752 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +0000753 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +0000754 pnext = get2byte(&data[pbegin]);
755 psize = get2byte(&data[pbegin+2]);
756 if( pbegin + psize + 3 >= pnext && pnext>0 ){
757 int frag = pnext - (pbegin+psize);
drh43605152004-05-29 21:46:49 +0000758 assert( frag<=data[pPage->hdrOffset+7] );
759 data[pPage->hdrOffset+7] -= frag;
drh9e572e62004-04-23 23:43:10 +0000760 put2byte(&data[pbegin], get2byte(&data[pnext]));
761 put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
762 }else{
drh3aac2dd2004-04-26 14:10:20 +0000763 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +0000764 }
765 }
drh7e3b0a02001-04-28 16:52:40 +0000766
drh43605152004-05-29 21:46:49 +0000767 /* If the cell content area begins with a freeblock, remove it. */
768 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
769 int top;
770 pbegin = get2byte(&data[hdr+1]);
771 memcpy(&data[hdr+1], &data[pbegin], 2);
772 top = get2byte(&data[hdr+5]);
773 put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
drh4b70f112004-05-02 21:12:19 +0000774 }
drh4b70f112004-05-02 21:12:19 +0000775}
776
777/*
drh271efa52004-05-30 19:19:05 +0000778** Decode the flags byte (the first byte of the header) for a page
779** and initialize fields of the MemPage structure accordingly.
780*/
781static void decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +0000782 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +0000783
784 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
785 pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
786 pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
787 pPage->leaf = (flagByte & PTF_LEAF)!=0;
788 pPage->childPtrSize = 4*(pPage->leaf==0);
789 pBt = pPage->pBt;
790 if( flagByte & PTF_LEAFDATA ){
791 pPage->leafData = 1;
792 pPage->maxLocal = pBt->maxLeaf;
793 pPage->minLocal = pBt->minLeaf;
794 }else{
795 pPage->leafData = 0;
796 pPage->maxLocal = pBt->maxLocal;
797 pPage->minLocal = pBt->minLocal;
798 }
799 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
800}
801
802/*
drh7e3b0a02001-04-28 16:52:40 +0000803** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000804**
drhbd03cae2001-06-02 02:40:57 +0000805** The pParent parameter must be a pointer to the MemPage which
drh9e572e62004-04-23 23:43:10 +0000806** is the parent of the page being initialized. The root of a
807** BTree has no parent and so for that page, pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000808**
drh72f82862001-05-24 21:06:34 +0000809** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +0000810** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +0000811** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
812** guarantee that the page is well-formed. It only shows that
813** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000814*/
drh16a9b832007-05-05 18:39:25 +0000815int sqlite3BtreeInitPage(
drh3aac2dd2004-04-26 14:10:20 +0000816 MemPage *pPage, /* The page to be initialized */
drh9e572e62004-04-23 23:43:10 +0000817 MemPage *pParent /* The parent. Might be NULL */
818){
drh271efa52004-05-30 19:19:05 +0000819 int pc; /* Address of a freeblock within pPage->aData[] */
drh271efa52004-05-30 19:19:05 +0000820 int hdr; /* Offset to beginning of page header */
821 u8 *data; /* Equal to pPage->aData */
danielk1977aef0bf62005-12-30 16:28:01 +0000822 BtShared *pBt; /* The main btree structure */
drh271efa52004-05-30 19:19:05 +0000823 int usableSize; /* Amount of usable space on each page */
824 int cellOffset; /* Offset from start of page to first cell pointer */
825 int nFree; /* Number of unused bytes on the page */
826 int top; /* First byte of the cell content area */
drh2af926b2001-05-15 00:39:25 +0000827
drh2e38c322004-09-03 18:38:44 +0000828 pBt = pPage->pBt;
829 assert( pBt!=0 );
830 assert( pParent==0 || pParent->pBt==pBt );
danielk19773b8a05f2007-03-19 17:44:26 +0000831 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drh07d183d2005-05-01 22:52:42 +0000832 assert( pPage->aData == &((unsigned char*)pPage)[-pBt->pageSize] );
drhee696e22004-08-30 16:52:17 +0000833 if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){
834 /* The parent page should never change unless the file is corrupt */
drh49285702005-09-17 15:20:26 +0000835 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000836 }
drh10617cd2004-05-14 15:27:27 +0000837 if( pPage->isInit ) return SQLITE_OK;
drhda200cc2004-05-09 11:51:38 +0000838 if( pPage->pParent==0 && pParent!=0 ){
839 pPage->pParent = pParent;
danielk19773b8a05f2007-03-19 17:44:26 +0000840 sqlite3PagerRef(pParent->pDbPage);
drh5e2f8b92001-05-28 00:41:15 +0000841 }
drhde647132004-05-07 17:57:49 +0000842 hdr = pPage->hdrOffset;
drha34b6762004-05-07 13:30:42 +0000843 data = pPage->aData;
drh271efa52004-05-30 19:19:05 +0000844 decodeFlags(pPage, data[hdr]);
drh43605152004-05-29 21:46:49 +0000845 pPage->nOverflow = 0;
drhc8629a12004-05-08 20:07:40 +0000846 pPage->idxShift = 0;
drh2e38c322004-09-03 18:38:44 +0000847 usableSize = pBt->usableSize;
drh43605152004-05-29 21:46:49 +0000848 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
849 top = get2byte(&data[hdr+5]);
850 pPage->nCell = get2byte(&data[hdr+3]);
drh2e38c322004-09-03 18:38:44 +0000851 if( pPage->nCell>MX_CELL(pBt) ){
drhee696e22004-08-30 16:52:17 +0000852 /* To many cells for a single page. The page must be corrupt */
drh49285702005-09-17 15:20:26 +0000853 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000854 }
855 if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
856 /* All pages must have at least one cell, except for root pages */
drh49285702005-09-17 15:20:26 +0000857 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000858 }
drh9e572e62004-04-23 23:43:10 +0000859
860 /* Compute the total free space on the page */
drh9e572e62004-04-23 23:43:10 +0000861 pc = get2byte(&data[hdr+1]);
drh43605152004-05-29 21:46:49 +0000862 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
drh9e572e62004-04-23 23:43:10 +0000863 while( pc>0 ){
864 int next, size;
drhee696e22004-08-30 16:52:17 +0000865 if( pc>usableSize-4 ){
866 /* Free block is off the page */
drh49285702005-09-17 15:20:26 +0000867 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000868 }
drh9e572e62004-04-23 23:43:10 +0000869 next = get2byte(&data[pc]);
870 size = get2byte(&data[pc+2]);
drhee696e22004-08-30 16:52:17 +0000871 if( next>0 && next<=pc+size+3 ){
872 /* Free blocks must be in accending order */
drh49285702005-09-17 15:20:26 +0000873 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000874 }
drh3add3672004-05-15 00:29:24 +0000875 nFree += size;
drh9e572e62004-04-23 23:43:10 +0000876 pc = next;
877 }
drh3add3672004-05-15 00:29:24 +0000878 pPage->nFree = nFree;
drhee696e22004-08-30 16:52:17 +0000879 if( nFree>=usableSize ){
880 /* Free space cannot exceed total page size */
drh49285702005-09-17 15:20:26 +0000881 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000882 }
drh9e572e62004-04-23 23:43:10 +0000883
drhde647132004-05-07 17:57:49 +0000884 pPage->isInit = 1;
drh9e572e62004-04-23 23:43:10 +0000885 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +0000886}
887
888/*
drh8b2f49b2001-06-08 00:21:52 +0000889** Set up a raw page so that it looks like a database page holding
890** no entries.
drhbd03cae2001-06-02 02:40:57 +0000891*/
drh9e572e62004-04-23 23:43:10 +0000892static void zeroPage(MemPage *pPage, int flags){
893 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +0000894 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +0000895 int hdr = pPage->hdrOffset;
drh9e572e62004-04-23 23:43:10 +0000896 int first;
897
danielk19773b8a05f2007-03-19 17:44:26 +0000898 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drh07d183d2005-05-01 22:52:42 +0000899 assert( &data[pBt->pageSize] == (unsigned char*)pPage );
danielk19773b8a05f2007-03-19 17:44:26 +0000900 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drhb6f41482004-05-14 01:58:11 +0000901 memset(&data[hdr], 0, pBt->usableSize - hdr);
drh9e572e62004-04-23 23:43:10 +0000902 data[hdr] = flags;
drh43605152004-05-29 21:46:49 +0000903 first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
904 memset(&data[hdr+1], 0, 4);
905 data[hdr+7] = 0;
906 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +0000907 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +0000908 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +0000909 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +0000910 pPage->cellOffset = first;
911 pPage->nOverflow = 0;
drhda200cc2004-05-09 11:51:38 +0000912 pPage->idxShift = 0;
drh43605152004-05-29 21:46:49 +0000913 pPage->nCell = 0;
drhda200cc2004-05-09 11:51:38 +0000914 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +0000915}
916
917/*
drh3aac2dd2004-04-26 14:10:20 +0000918** Get a page from the pager. Initialize the MemPage.pBt and
919** MemPage.aData elements if needed.
drh538f5702007-04-13 02:14:30 +0000920**
921** If the noContent flag is set, it means that we do not care about
922** the content of the page at this time. So do not go to the disk
923** to fetch the content. Just fill in the content with zeros for now.
924** If in the future we call sqlite3PagerWrite() on this page, that
925** means we have started to be concerned about content and the disk
926** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +0000927*/
drh16a9b832007-05-05 18:39:25 +0000928int sqlite3BtreeGetPage(
929 BtShared *pBt, /* The btree */
930 Pgno pgno, /* Number of the page to fetch */
931 MemPage **ppPage, /* Return the page in this parameter */
932 int noContent /* Do not load page content if true */
933){
drh3aac2dd2004-04-26 14:10:20 +0000934 int rc;
drh3aac2dd2004-04-26 14:10:20 +0000935 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +0000936 DbPage *pDbPage;
937
drh538f5702007-04-13 02:14:30 +0000938 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
drh3aac2dd2004-04-26 14:10:20 +0000939 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +0000940 pPage = (MemPage *)sqlite3PagerGetExtra(pDbPage);
941 pPage->aData = sqlite3PagerGetData(pDbPage);
942 pPage->pDbPage = pDbPage;
drh3aac2dd2004-04-26 14:10:20 +0000943 pPage->pBt = pBt;
944 pPage->pgno = pgno;
drhde647132004-05-07 17:57:49 +0000945 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
drh3aac2dd2004-04-26 14:10:20 +0000946 *ppPage = pPage;
947 return SQLITE_OK;
948}
949
950/*
drhde647132004-05-07 17:57:49 +0000951** Get a page from the pager and initialize it. This routine
952** is just a convenience wrapper around separate calls to
drh16a9b832007-05-05 18:39:25 +0000953** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
drhde647132004-05-07 17:57:49 +0000954*/
955static int getAndInitPage(
danielk1977aef0bf62005-12-30 16:28:01 +0000956 BtShared *pBt, /* The database file */
drhde647132004-05-07 17:57:49 +0000957 Pgno pgno, /* Number of the page to get */
958 MemPage **ppPage, /* Write the page pointer here */
959 MemPage *pParent /* Parent of the page */
960){
961 int rc;
drhee696e22004-08-30 16:52:17 +0000962 if( pgno==0 ){
drh49285702005-09-17 15:20:26 +0000963 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000964 }
drh16a9b832007-05-05 18:39:25 +0000965 rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
drh10617cd2004-05-14 15:27:27 +0000966 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
drh16a9b832007-05-05 18:39:25 +0000967 rc = sqlite3BtreeInitPage(*ppPage, pParent);
drhde647132004-05-07 17:57:49 +0000968 }
969 return rc;
970}
971
972/*
drh3aac2dd2004-04-26 14:10:20 +0000973** Release a MemPage. This should be called once for each prior
drh16a9b832007-05-05 18:39:25 +0000974** call to sqlite3BtreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +0000975*/
drh4b70f112004-05-02 21:12:19 +0000976static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +0000977 if( pPage ){
978 assert( pPage->aData );
979 assert( pPage->pBt );
drh07d183d2005-05-01 22:52:42 +0000980 assert( &pPage->aData[pPage->pBt->pageSize]==(unsigned char*)pPage );
danielk19773b8a05f2007-03-19 17:44:26 +0000981 sqlite3PagerUnref(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +0000982 }
983}
984
985/*
drh72f82862001-05-24 21:06:34 +0000986** This routine is called when the reference count for a page
987** reaches zero. We need to unref the pParent pointer when that
988** happens.
989*/
danielk19773b8a05f2007-03-19 17:44:26 +0000990static void pageDestructor(DbPage *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +0000991 MemPage *pPage;
992 assert( (pageSize & 7)==0 );
danielk19773b8a05f2007-03-19 17:44:26 +0000993 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
drh72f82862001-05-24 21:06:34 +0000994 if( pPage->pParent ){
995 MemPage *pParent = pPage->pParent;
996 pPage->pParent = 0;
drha34b6762004-05-07 13:30:42 +0000997 releasePage(pParent);
drh72f82862001-05-24 21:06:34 +0000998 }
drh3aac2dd2004-04-26 14:10:20 +0000999 pPage->isInit = 0;
drh72f82862001-05-24 21:06:34 +00001000}
1001
1002/*
drha6abd042004-06-09 17:37:22 +00001003** During a rollback, when the pager reloads information into the cache
1004** so that the cache is restored to its original state at the start of
1005** the transaction, for each page restored this routine is called.
1006**
1007** This routine needs to reset the extra data section at the end of the
1008** page to agree with the restored data.
1009*/
danielk19773b8a05f2007-03-19 17:44:26 +00001010static void pageReinit(DbPage *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +00001011 MemPage *pPage;
1012 assert( (pageSize & 7)==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001013 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
drha6abd042004-06-09 17:37:22 +00001014 if( pPage->isInit ){
1015 pPage->isInit = 0;
drh16a9b832007-05-05 18:39:25 +00001016 sqlite3BtreeInitPage(pPage, pPage->pParent);
drha6abd042004-06-09 17:37:22 +00001017 }
1018}
1019
1020/*
drhad3e0102004-09-03 23:32:18 +00001021** Open a database file.
1022**
drh382c0242001-10-06 16:33:02 +00001023** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001024** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001025** database file will be deleted when sqlite3BtreeClose() is called.
drha059ad02001-04-17 20:09:11 +00001026*/
drh23e11ca2004-05-04 17:27:28 +00001027int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001028 const char *zFilename, /* Name of the file containing the BTree database */
danielk1977aef0bf62005-12-30 16:28:01 +00001029 sqlite3 *pSqlite, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001030 Btree **ppBtree, /* Pointer to new Btree object written here */
drh90f5ecb2004-07-22 01:19:35 +00001031 int flags /* Options */
drh6019e162001-07-02 17:51:45 +00001032){
danielk1977aef0bf62005-12-30 16:28:01 +00001033 BtShared *pBt; /* Shared part of btree structure */
1034 Btree *p; /* Handle to return */
danielk1977dddbcdc2007-04-26 14:42:34 +00001035 int rc = SQLITE_OK;
drh90f5ecb2004-07-22 01:19:35 +00001036 int nReserve;
1037 unsigned char zDbHeader[100];
drh6f7adc82006-01-11 21:41:20 +00001038#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1039 const ThreadData *pTsdro;
danielk1977da184232006-01-05 11:34:32 +00001040#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001041
1042 /* Set the variable isMemdb to true for an in-memory database, or
1043 ** false for a file-based database. This symbol is only required if
1044 ** either of the shared-data or autovacuum features are compiled
1045 ** into the library.
1046 */
1047#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
1048 #ifdef SQLITE_OMIT_MEMORYDB
drh980b1a72006-08-16 16:42:48 +00001049 const int isMemdb = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00001050 #else
drh980b1a72006-08-16 16:42:48 +00001051 const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
danielk1977aef0bf62005-12-30 16:28:01 +00001052 #endif
1053#endif
1054
1055 p = sqliteMalloc(sizeof(Btree));
1056 if( !p ){
1057 return SQLITE_NOMEM;
1058 }
1059 p->inTrans = TRANS_NONE;
1060 p->pSqlite = pSqlite;
1061
1062 /* Try to find an existing Btree structure opened on zFilename. */
drh198bf392006-01-06 21:52:49 +00001063#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drh6f7adc82006-01-11 21:41:20 +00001064 pTsdro = sqlite3ThreadDataReadOnly();
1065 if( pTsdro->useSharedData && zFilename && !isMemdb ){
drh66560ad2006-01-06 14:32:19 +00001066 char *zFullPathname = sqlite3OsFullPathname(zFilename);
danielk1977aef0bf62005-12-30 16:28:01 +00001067 if( !zFullPathname ){
1068 sqliteFree(p);
1069 return SQLITE_NOMEM;
1070 }
drh6f7adc82006-01-11 21:41:20 +00001071 for(pBt=pTsdro->pBtree; pBt; pBt=pBt->pNext){
danielk1977b82e7ed2006-01-11 14:09:31 +00001072 assert( pBt->nRef>0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001073 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager)) ){
danielk1977aef0bf62005-12-30 16:28:01 +00001074 p->pBt = pBt;
1075 *ppBtree = p;
1076 pBt->nRef++;
1077 sqliteFree(zFullPathname);
1078 return SQLITE_OK;
1079 }
1080 }
1081 sqliteFree(zFullPathname);
1082 }
1083#endif
drha059ad02001-04-17 20:09:11 +00001084
drhd62d3d02003-01-24 12:14:20 +00001085 /*
1086 ** The following asserts make sure that structures used by the btree are
1087 ** the right size. This is to guard against size changes that result
1088 ** when compiling on a different architecture.
1089 */
drh9b8f4472006-04-04 01:54:55 +00001090 assert( sizeof(i64)==8 || sizeof(i64)==4 );
1091 assert( sizeof(u64)==8 || sizeof(u64)==4 );
drhd62d3d02003-01-24 12:14:20 +00001092 assert( sizeof(u32)==4 );
1093 assert( sizeof(u16)==2 );
1094 assert( sizeof(Pgno)==4 );
drhd62d3d02003-01-24 12:14:20 +00001095
drha059ad02001-04-17 20:09:11 +00001096 pBt = sqliteMalloc( sizeof(*pBt) );
1097 if( pBt==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00001098 rc = SQLITE_NOMEM;
1099 goto btree_open_out;
drha059ad02001-04-17 20:09:11 +00001100 }
danielk19773b8a05f2007-03-19 17:44:26 +00001101 rc = sqlite3PagerOpen(&pBt->pPager, zFilename, EXTRA_SIZE, flags);
drh551b7732006-11-06 21:20:25 +00001102 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00001103 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
drh551b7732006-11-06 21:20:25 +00001104 }
drha059ad02001-04-17 20:09:11 +00001105 if( rc!=SQLITE_OK ){
danielk1977dddbcdc2007-04-26 14:42:34 +00001106 goto btree_open_out;
drha059ad02001-04-17 20:09:11 +00001107 }
danielk1977aef0bf62005-12-30 16:28:01 +00001108 p->pBt = pBt;
1109
danielk19773b8a05f2007-03-19 17:44:26 +00001110 sqlite3PagerSetDestructor(pBt->pPager, pageDestructor);
1111 sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
drha059ad02001-04-17 20:09:11 +00001112 pBt->pCursor = 0;
drha34b6762004-05-07 13:30:42 +00001113 pBt->pPage1 = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00001114 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
drh90f5ecb2004-07-22 01:19:35 +00001115 pBt->pageSize = get2byte(&zDbHeader[16]);
drh07d183d2005-05-01 22:52:42 +00001116 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1117 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
drh90f5ecb2004-07-22 01:19:35 +00001118 pBt->pageSize = SQLITE_DEFAULT_PAGE_SIZE;
1119 pBt->maxEmbedFrac = 64; /* 25% */
1120 pBt->minEmbedFrac = 32; /* 12.5% */
1121 pBt->minLeafFrac = 32; /* 12.5% */
drheee46cf2004-11-06 00:02:48 +00001122#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197703aded42004-11-22 05:26:27 +00001123 /* If the magic name ":memory:" will create an in-memory database, then
danielk1977dddbcdc2007-04-26 14:42:34 +00001124 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
1125 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
1126 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
1127 ** regular file-name. In this case the auto-vacuum applies as per normal.
danielk197703aded42004-11-22 05:26:27 +00001128 */
danielk1977aef0bf62005-12-30 16:28:01 +00001129 if( zFilename && !isMemdb ){
danielk1977dddbcdc2007-04-26 14:42:34 +00001130 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
1131 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
danielk1977951af802004-11-05 15:45:09 +00001132 }
drheee46cf2004-11-06 00:02:48 +00001133#endif
drh90f5ecb2004-07-22 01:19:35 +00001134 nReserve = 0;
1135 }else{
1136 nReserve = zDbHeader[20];
1137 pBt->maxEmbedFrac = zDbHeader[21];
1138 pBt->minEmbedFrac = zDbHeader[22];
1139 pBt->minLeafFrac = zDbHeader[23];
1140 pBt->pageSizeFixed = 1;
danielk1977951af802004-11-05 15:45:09 +00001141#ifndef SQLITE_OMIT_AUTOVACUUM
1142 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
danielk1977418899a2007-06-24 10:14:00 +00001143 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
danielk1977951af802004-11-05 15:45:09 +00001144#endif
drh90f5ecb2004-07-22 01:19:35 +00001145 }
1146 pBt->usableSize = pBt->pageSize - nReserve;
drh07d183d2005-05-01 22:52:42 +00001147 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
danielk19773b8a05f2007-03-19 17:44:26 +00001148 sqlite3PagerSetPagesize(pBt->pPager, pBt->pageSize);
danielk1977aef0bf62005-12-30 16:28:01 +00001149
drhcfed7bc2006-03-13 14:28:05 +00001150#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
danielk197754f01982006-01-18 15:25:17 +00001151 /* Add the new btree to the linked list starting at ThreadData.pBtree.
1152 ** There is no chance that a malloc() may fail inside of the
1153 ** sqlite3ThreadData() call, as the ThreadData structure must have already
1154 ** been allocated for pTsdro->useSharedData to be non-zero.
1155 */
drh6f7adc82006-01-11 21:41:20 +00001156 if( pTsdro->useSharedData && zFilename && !isMemdb ){
1157 pBt->pNext = pTsdro->pBtree;
1158 sqlite3ThreadData()->pBtree = pBt;
danielk1977aef0bf62005-12-30 16:28:01 +00001159 }
danielk1977aef0bf62005-12-30 16:28:01 +00001160#endif
danielk1977da184232006-01-05 11:34:32 +00001161 pBt->nRef = 1;
danielk1977aef0bf62005-12-30 16:28:01 +00001162 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00001163
1164btree_open_out:
1165 if( rc!=SQLITE_OK ){
1166 if( pBt && pBt->pPager ){
1167 sqlite3PagerClose(pBt->pPager);
1168 }
1169 sqliteFree(pBt);
1170 sqliteFree(p);
1171 *ppBtree = 0;
1172 }
1173 return rc;
drha059ad02001-04-17 20:09:11 +00001174}
1175
1176/*
1177** Close an open database and invalidate all cursors.
1178*/
danielk1977aef0bf62005-12-30 16:28:01 +00001179int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00001180 BtShared *pBt = p->pBt;
1181 BtCursor *pCur;
1182
danielk1977da184232006-01-05 11:34:32 +00001183#ifndef SQLITE_OMIT_SHARED_CACHE
drh6f7adc82006-01-11 21:41:20 +00001184 ThreadData *pTsd;
danielk1977da184232006-01-05 11:34:32 +00001185#endif
1186
danielk1977aef0bf62005-12-30 16:28:01 +00001187 /* Close all cursors opened via this handle. */
1188 pCur = pBt->pCursor;
1189 while( pCur ){
1190 BtCursor *pTmp = pCur;
1191 pCur = pCur->pNext;
1192 if( pTmp->pBtree==p ){
1193 sqlite3BtreeCloseCursor(pTmp);
1194 }
drha059ad02001-04-17 20:09:11 +00001195 }
danielk1977aef0bf62005-12-30 16:28:01 +00001196
danielk19778d34dfd2006-01-24 16:37:57 +00001197 /* Rollback any active transaction and free the handle structure.
1198 ** The call to sqlite3BtreeRollback() drops any table-locks held by
1199 ** this handle.
1200 */
danielk1977b597f742006-01-15 11:39:18 +00001201 sqlite3BtreeRollback(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001202 sqliteFree(p);
1203
1204#ifndef SQLITE_OMIT_SHARED_CACHE
1205 /* If there are still other outstanding references to the shared-btree
1206 ** structure, return now. The remainder of this procedure cleans
1207 ** up the shared-btree.
1208 */
1209 assert( pBt->nRef>0 );
1210 pBt->nRef--;
1211 if( pBt->nRef ){
1212 return SQLITE_OK;
1213 }
1214
danielk197754f01982006-01-18 15:25:17 +00001215 /* Remove the shared-btree from the thread wide list. Call
1216 ** ThreadDataReadOnly() and then cast away the const property of the
1217 ** pointer to avoid allocating thread data if it is not really required.
1218 */
1219 pTsd = (ThreadData *)sqlite3ThreadDataReadOnly();
danielk1977aef0bf62005-12-30 16:28:01 +00001220 if( pTsd->pBtree==pBt ){
danielk197754f01982006-01-18 15:25:17 +00001221 assert( pTsd==sqlite3ThreadData() );
danielk1977aef0bf62005-12-30 16:28:01 +00001222 pTsd->pBtree = pBt->pNext;
1223 }else{
1224 BtShared *pPrev;
drh74161702006-02-24 02:53:49 +00001225 for(pPrev=pTsd->pBtree; pPrev && pPrev->pNext!=pBt; pPrev=pPrev->pNext){}
danielk1977aef0bf62005-12-30 16:28:01 +00001226 if( pPrev ){
danielk197754f01982006-01-18 15:25:17 +00001227 assert( pTsd==sqlite3ThreadData() );
danielk1977aef0bf62005-12-30 16:28:01 +00001228 pPrev->pNext = pBt->pNext;
1229 }
1230 }
1231#endif
1232
1233 /* Close the pager and free the shared-btree structure */
1234 assert( !pBt->pCursor );
danielk19773b8a05f2007-03-19 17:44:26 +00001235 sqlite3PagerClose(pBt->pPager);
danielk1977da184232006-01-05 11:34:32 +00001236 if( pBt->xFreeSchema && pBt->pSchema ){
1237 pBt->xFreeSchema(pBt->pSchema);
1238 }
danielk1977de0fe3e2006-01-06 06:33:12 +00001239 sqliteFree(pBt->pSchema);
drha059ad02001-04-17 20:09:11 +00001240 sqliteFree(pBt);
1241 return SQLITE_OK;
1242}
1243
1244/*
drh90f5ecb2004-07-22 01:19:35 +00001245** Change the busy handler callback function.
1246*/
danielk1977aef0bf62005-12-30 16:28:01 +00001247int sqlite3BtreeSetBusyHandler(Btree *p, BusyHandler *pHandler){
1248 BtShared *pBt = p->pBt;
drhb8ef32c2005-03-14 02:01:49 +00001249 pBt->pBusyHandler = pHandler;
danielk19773b8a05f2007-03-19 17:44:26 +00001250 sqlite3PagerSetBusyhandler(pBt->pPager, pHandler);
drh90f5ecb2004-07-22 01:19:35 +00001251 return SQLITE_OK;
1252}
1253
1254/*
drhda47d772002-12-02 04:25:19 +00001255** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001256**
1257** The maximum number of cache pages is set to the absolute
1258** value of mxPage. If mxPage is negative, the pager will
1259** operate asynchronously - it will not stop to do fsync()s
1260** to insure data is written to the disk surface before
1261** continuing. Transactions still work if synchronous is off,
1262** and the database cannot be corrupted if this program
1263** crashes. But if the operating system crashes or there is
1264** an abrupt power failure when synchronous is off, the database
1265** could be left in an inconsistent and unrecoverable state.
1266** Synchronous is on by default so database corruption is not
1267** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001268*/
danielk1977aef0bf62005-12-30 16:28:01 +00001269int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
1270 BtShared *pBt = p->pBt;
danielk19773b8a05f2007-03-19 17:44:26 +00001271 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhf57b14a2001-09-14 18:54:08 +00001272 return SQLITE_OK;
1273}
1274
1275/*
drh973b6e32003-02-12 14:09:42 +00001276** Change the way data is synced to disk in order to increase or decrease
1277** how well the database resists damage due to OS crashes and power
1278** failures. Level 1 is the same as asynchronous (no syncs() occur and
1279** there is a high probability of damage) Level 2 is the default. There
1280** is a very low but non-zero probability of damage. Level 3 reduces the
1281** probability of damage to near zero but with a write performance reduction.
1282*/
danielk197793758c82005-01-21 08:13:14 +00001283#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drhac530b12006-02-11 01:25:50 +00001284int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
danielk1977aef0bf62005-12-30 16:28:01 +00001285 BtShared *pBt = p->pBt;
danielk19773b8a05f2007-03-19 17:44:26 +00001286 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
drh973b6e32003-02-12 14:09:42 +00001287 return SQLITE_OK;
1288}
danielk197793758c82005-01-21 08:13:14 +00001289#endif
drh973b6e32003-02-12 14:09:42 +00001290
drh2c8997b2005-08-27 16:36:48 +00001291/*
1292** Return TRUE if the given btree is set to safety level 1. In other
1293** words, return TRUE if no sync() occurs on the disk files.
1294*/
danielk1977aef0bf62005-12-30 16:28:01 +00001295int sqlite3BtreeSyncDisabled(Btree *p){
1296 BtShared *pBt = p->pBt;
drh2c8997b2005-08-27 16:36:48 +00001297 assert( pBt && pBt->pPager );
danielk19773b8a05f2007-03-19 17:44:26 +00001298 return sqlite3PagerNosync(pBt->pPager);
drh2c8997b2005-08-27 16:36:48 +00001299}
1300
danielk1977576ec6b2005-01-21 11:55:25 +00001301#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00001302/*
drh90f5ecb2004-07-22 01:19:35 +00001303** Change the default pages size and the number of reserved bytes per page.
drh06f50212004-11-02 14:24:33 +00001304**
1305** The page size must be a power of 2 between 512 and 65536. If the page
1306** size supplied does not meet this constraint then the page size is not
1307** changed.
1308**
1309** Page sizes are constrained to be a power of two so that the region
1310** of the database file used for locking (beginning at PENDING_BYTE,
1311** the first byte past the 1GB boundary, 0x40000000) needs to occur
1312** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001313**
1314** If parameter nReserve is less than zero, then the number of reserved
1315** bytes per page is left unchanged.
drh90f5ecb2004-07-22 01:19:35 +00001316*/
danielk1977aef0bf62005-12-30 16:28:01 +00001317int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
1318 BtShared *pBt = p->pBt;
drh90f5ecb2004-07-22 01:19:35 +00001319 if( pBt->pageSizeFixed ){
1320 return SQLITE_READONLY;
1321 }
1322 if( nReserve<0 ){
1323 nReserve = pBt->pageSize - pBt->usableSize;
1324 }
drh06f50212004-11-02 14:24:33 +00001325 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
1326 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00001327 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00001328 assert( !pBt->pPage1 && !pBt->pCursor );
danielk19773b8a05f2007-03-19 17:44:26 +00001329 pBt->pageSize = sqlite3PagerSetPagesize(pBt->pPager, pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001330 }
1331 pBt->usableSize = pBt->pageSize - nReserve;
1332 return SQLITE_OK;
1333}
1334
1335/*
1336** Return the currently defined page size
1337*/
danielk1977aef0bf62005-12-30 16:28:01 +00001338int sqlite3BtreeGetPageSize(Btree *p){
1339 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00001340}
danielk1977aef0bf62005-12-30 16:28:01 +00001341int sqlite3BtreeGetReserve(Btree *p){
1342 return p->pBt->pageSize - p->pBt->usableSize;
drh2011d5f2004-07-22 02:40:37 +00001343}
drhf8e632b2007-05-08 14:51:36 +00001344
1345/*
1346** Set the maximum page count for a database if mxPage is positive.
1347** No changes are made if mxPage is 0 or negative.
1348** Regardless of the value of mxPage, return the maximum page count.
1349*/
1350int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
1351 return sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
1352}
danielk1977576ec6b2005-01-21 11:55:25 +00001353#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00001354
1355/*
danielk1977951af802004-11-05 15:45:09 +00001356** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
1357** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
1358** is disabled. The default value for the auto-vacuum property is
1359** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
1360*/
danielk1977aef0bf62005-12-30 16:28:01 +00001361int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00001362#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001363 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00001364#else
danielk1977dddbcdc2007-04-26 14:42:34 +00001365 BtShared *pBt = p->pBt;
1366 int av = (autoVacuum?1:0);
danielk1977dddbcdc2007-04-26 14:42:34 +00001367 if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
danielk1977951af802004-11-05 15:45:09 +00001368 return SQLITE_READONLY;
1369 }
danielk1977dddbcdc2007-04-26 14:42:34 +00001370 pBt->autoVacuum = av;
danielk1977951af802004-11-05 15:45:09 +00001371 return SQLITE_OK;
1372#endif
1373}
1374
1375/*
1376** Return the value of the 'auto-vacuum' property. If auto-vacuum is
1377** enabled 1 is returned. Otherwise 0.
1378*/
danielk1977aef0bf62005-12-30 16:28:01 +00001379int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00001380#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00001381 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00001382#else
danielk1977dddbcdc2007-04-26 14:42:34 +00001383 return (
1384 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
1385 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
1386 BTREE_AUTOVACUUM_INCR
1387 );
danielk1977951af802004-11-05 15:45:09 +00001388#endif
1389}
1390
1391
1392/*
drha34b6762004-05-07 13:30:42 +00001393** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001394** also acquire a readlock on that file.
1395**
1396** SQLITE_OK is returned on success. If the file is not a
1397** well-formed database file, then SQLITE_CORRUPT is returned.
1398** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00001399** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00001400*/
danielk1977aef0bf62005-12-30 16:28:01 +00001401static int lockBtree(BtShared *pBt){
drh07d183d2005-05-01 22:52:42 +00001402 int rc, pageSize;
drh3aac2dd2004-04-26 14:10:20 +00001403 MemPage *pPage1;
drha34b6762004-05-07 13:30:42 +00001404 if( pBt->pPage1 ) return SQLITE_OK;
drh16a9b832007-05-05 18:39:25 +00001405 rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00001406 if( rc!=SQLITE_OK ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00001407
drh306dc212001-05-21 13:45:10 +00001408
1409 /* Do some checking to help insure the file we opened really is
1410 ** a valid database file.
1411 */
drhb6f41482004-05-14 01:58:11 +00001412 rc = SQLITE_NOTADB;
danielk19773b8a05f2007-03-19 17:44:26 +00001413 if( sqlite3PagerPagecount(pBt->pPager)>0 ){
drhb6f41482004-05-14 01:58:11 +00001414 u8 *page1 = pPage1->aData;
1415 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001416 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001417 }
drh309169a2007-04-24 17:27:51 +00001418 if( page1[18]>1 ){
1419 pBt->readOnly = 1;
1420 }
1421 if( page1[19]>1 ){
drhb6f41482004-05-14 01:58:11 +00001422 goto page1_init_failed;
1423 }
drh07d183d2005-05-01 22:52:42 +00001424 pageSize = get2byte(&page1[16]);
drh15926592007-04-06 15:02:13 +00001425 if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ){
drh07d183d2005-05-01 22:52:42 +00001426 goto page1_init_failed;
1427 }
1428 assert( (pageSize & 7)==0 );
1429 pBt->pageSize = pageSize;
1430 pBt->usableSize = pageSize - page1[20];
drhb6f41482004-05-14 01:58:11 +00001431 if( pBt->usableSize<500 ){
1432 goto page1_init_failed;
1433 }
1434 pBt->maxEmbedFrac = page1[21];
1435 pBt->minEmbedFrac = page1[22];
1436 pBt->minLeafFrac = page1[23];
drh057cd3a2005-02-15 16:23:02 +00001437#ifndef SQLITE_OMIT_AUTOVACUUM
1438 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00001439 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00001440#endif
drh306dc212001-05-21 13:45:10 +00001441 }
drhb6f41482004-05-14 01:58:11 +00001442
1443 /* maxLocal is the maximum amount of payload to store locally for
1444 ** a cell. Make sure it is small enough so that at least minFanout
1445 ** cells can will fit on one page. We assume a 10-byte page header.
1446 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001447 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001448 ** 4-byte child pointer
1449 ** 9-byte nKey value
1450 ** 4-byte nData value
1451 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001452 ** So a cell consists of a 2-byte poiner, a header which is as much as
1453 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1454 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001455 */
drh43605152004-05-29 21:46:49 +00001456 pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
1457 pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
1458 pBt->maxLeaf = pBt->usableSize - 35;
1459 pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
drhb6f41482004-05-14 01:58:11 +00001460 if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
1461 goto page1_init_failed;
1462 }
drh2e38c322004-09-03 18:38:44 +00001463 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00001464 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001465 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001466
drh72f82862001-05-24 21:06:34 +00001467page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001468 releasePage(pPage1);
1469 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001470 return rc;
drh306dc212001-05-21 13:45:10 +00001471}
1472
1473/*
drhb8ef32c2005-03-14 02:01:49 +00001474** This routine works like lockBtree() except that it also invokes the
1475** busy callback if there is lock contention.
1476*/
danielk1977aef0bf62005-12-30 16:28:01 +00001477static int lockBtreeWithRetry(Btree *pRef){
drhb8ef32c2005-03-14 02:01:49 +00001478 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00001479 if( pRef->inTrans==TRANS_NONE ){
1480 u8 inTransaction = pRef->pBt->inTransaction;
1481 btreeIntegrity(pRef);
1482 rc = sqlite3BtreeBeginTrans(pRef, 0);
1483 pRef->pBt->inTransaction = inTransaction;
1484 pRef->inTrans = TRANS_NONE;
1485 if( rc==SQLITE_OK ){
1486 pRef->pBt->nTransaction--;
1487 }
1488 btreeIntegrity(pRef);
drhb8ef32c2005-03-14 02:01:49 +00001489 }
1490 return rc;
1491}
1492
1493
1494/*
drhb8ca3072001-12-05 00:21:20 +00001495** If there are no outstanding cursors and we are not in the middle
1496** of a transaction but there is a read lock on the database, then
1497** this routine unrefs the first page of the database file which
1498** has the effect of releasing the read lock.
1499**
1500** If there are any outstanding cursors, this routine is a no-op.
1501**
1502** If there is a transaction in progress, this routine is a no-op.
1503*/
danielk1977aef0bf62005-12-30 16:28:01 +00001504static void unlockBtreeIfUnused(BtShared *pBt){
1505 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00001506 if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
drh24c9a2e2007-01-05 02:00:47 +00001507 if( pBt->pPage1->aData==0 ){
1508 MemPage *pPage = pBt->pPage1;
1509 pPage->aData = &((u8*)pPage)[-pBt->pageSize];
1510 pPage->pBt = pBt;
1511 pPage->pgno = 1;
1512 }
1513 releasePage(pBt->pPage1);
drh51c6d962004-06-06 00:42:25 +00001514 }
drh3aac2dd2004-04-26 14:10:20 +00001515 pBt->pPage1 = 0;
drh3aac2dd2004-04-26 14:10:20 +00001516 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001517 }
1518}
1519
1520/*
drh9e572e62004-04-23 23:43:10 +00001521** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00001522** file.
drh8b2f49b2001-06-08 00:21:52 +00001523*/
danielk1977aef0bf62005-12-30 16:28:01 +00001524static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00001525 MemPage *pP1;
1526 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00001527 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001528 if( sqlite3PagerPagecount(pBt->pPager)>0 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001529 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00001530 assert( pP1!=0 );
1531 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00001532 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00001533 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00001534 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
1535 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00001536 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00001537 data[18] = 1;
1538 data[19] = 1;
drhb6f41482004-05-14 01:58:11 +00001539 data[20] = pBt->pageSize - pBt->usableSize;
1540 data[21] = pBt->maxEmbedFrac;
1541 data[22] = pBt->minEmbedFrac;
1542 data[23] = pBt->minLeafFrac;
1543 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00001544 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00001545 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00001546#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00001547 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00001548 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00001549 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00001550 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00001551#endif
drh8b2f49b2001-06-08 00:21:52 +00001552 return SQLITE_OK;
1553}
1554
1555/*
danielk1977ee5741e2004-05-31 10:01:34 +00001556** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00001557** is started if the second argument is nonzero, otherwise a read-
1558** transaction. If the second argument is 2 or more and exclusive
1559** transaction is started, meaning that no other process is allowed
1560** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00001561** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00001562** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00001563**
danielk1977ee5741e2004-05-31 10:01:34 +00001564** A write-transaction must be started before attempting any
1565** changes to the database. None of the following routines
1566** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00001567**
drh23e11ca2004-05-04 17:27:28 +00001568** sqlite3BtreeCreateTable()
1569** sqlite3BtreeCreateIndex()
1570** sqlite3BtreeClearTable()
1571** sqlite3BtreeDropTable()
1572** sqlite3BtreeInsert()
1573** sqlite3BtreeDelete()
1574** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00001575**
drhb8ef32c2005-03-14 02:01:49 +00001576** If an initial attempt to acquire the lock fails because of lock contention
1577** and the database was previously unlocked, then invoke the busy handler
1578** if there is one. But if there was previously a read-lock, do not
1579** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
1580** returned when there is already a read-lock in order to avoid a deadlock.
1581**
1582** Suppose there are two processes A and B. A has a read lock and B has
1583** a reserved lock. B tries to promote to exclusive but is blocked because
1584** of A's read lock. A tries to promote to reserved but is blocked by B.
1585** One or the other of the two processes must give way or there can be
1586** no progress. By returning SQLITE_BUSY and not invoking the busy callback
1587** when A already has a read lock, we encourage A to give up and let B
1588** proceed.
drha059ad02001-04-17 20:09:11 +00001589*/
danielk1977aef0bf62005-12-30 16:28:01 +00001590int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
1591 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00001592 int rc = SQLITE_OK;
1593
danielk1977aef0bf62005-12-30 16:28:01 +00001594 btreeIntegrity(p);
1595
danielk1977ee5741e2004-05-31 10:01:34 +00001596 /* If the btree is already in a write-transaction, or it
1597 ** is already in a read-transaction and a read-transaction
1598 ** is requested, this is a no-op.
1599 */
danielk1977aef0bf62005-12-30 16:28:01 +00001600 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
danielk1977ee5741e2004-05-31 10:01:34 +00001601 return SQLITE_OK;
1602 }
drhb8ef32c2005-03-14 02:01:49 +00001603
1604 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00001605 if( pBt->readOnly && wrflag ){
1606 return SQLITE_READONLY;
1607 }
1608
danielk1977aef0bf62005-12-30 16:28:01 +00001609 /* If another database handle has already opened a write transaction
1610 ** on this shared-btree structure and a second write transaction is
1611 ** requested, return SQLITE_BUSY.
1612 */
1613 if( pBt->inTransaction==TRANS_WRITE && wrflag ){
1614 return SQLITE_BUSY;
1615 }
1616
drhb8ef32c2005-03-14 02:01:49 +00001617 do {
1618 if( pBt->pPage1==0 ){
1619 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +00001620 }
drh309169a2007-04-24 17:27:51 +00001621
drhb8ef32c2005-03-14 02:01:49 +00001622 if( rc==SQLITE_OK && wrflag ){
drh309169a2007-04-24 17:27:51 +00001623 if( pBt->readOnly ){
1624 rc = SQLITE_READONLY;
1625 }else{
1626 rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1);
1627 if( rc==SQLITE_OK ){
1628 rc = newDatabase(pBt);
1629 }
drhb8ef32c2005-03-14 02:01:49 +00001630 }
1631 }
1632
1633 if( rc==SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00001634 if( wrflag ) pBt->inStmt = 0;
1635 }else{
1636 unlockBtreeIfUnused(pBt);
1637 }
danielk1977aef0bf62005-12-30 16:28:01 +00001638 }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
drha4afb652005-07-09 02:16:02 +00001639 sqlite3InvokeBusyHandler(pBt->pBusyHandler) );
danielk1977aef0bf62005-12-30 16:28:01 +00001640
1641 if( rc==SQLITE_OK ){
1642 if( p->inTrans==TRANS_NONE ){
1643 pBt->nTransaction++;
1644 }
1645 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
1646 if( p->inTrans>pBt->inTransaction ){
1647 pBt->inTransaction = p->inTrans;
1648 }
1649 }
1650
1651 btreeIntegrity(p);
drhb8ca3072001-12-05 00:21:20 +00001652 return rc;
drha059ad02001-04-17 20:09:11 +00001653}
1654
danielk1977687566d2004-11-02 12:56:41 +00001655#ifndef SQLITE_OMIT_AUTOVACUUM
1656
1657/*
1658** Set the pointer-map entries for all children of page pPage. Also, if
1659** pPage contains cells that point to overflow pages, set the pointer
1660** map entries for the overflow pages as well.
1661*/
1662static int setChildPtrmaps(MemPage *pPage){
1663 int i; /* Counter variable */
1664 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00001665 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00001666 BtShared *pBt = pPage->pBt;
danielk1977687566d2004-11-02 12:56:41 +00001667 int isInitOrig = pPage->isInit;
1668 Pgno pgno = pPage->pgno;
1669
danielk19772df71c72007-05-24 07:22:42 +00001670 rc = sqlite3BtreeInitPage(pPage, pPage->pParent);
1671 if( rc!=SQLITE_OK ){
1672 goto set_child_ptrmaps_out;
1673 }
danielk1977687566d2004-11-02 12:56:41 +00001674 nCell = pPage->nCell;
1675
1676 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00001677 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00001678
danielk197726836652005-01-17 01:33:13 +00001679 rc = ptrmapPutOvflPtr(pPage, pCell);
1680 if( rc!=SQLITE_OK ){
1681 goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00001682 }
danielk197726836652005-01-17 01:33:13 +00001683
danielk1977687566d2004-11-02 12:56:41 +00001684 if( !pPage->leaf ){
1685 Pgno childPgno = get4byte(pCell);
1686 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
1687 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
1688 }
1689 }
1690
1691 if( !pPage->leaf ){
1692 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
1693 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
1694 }
1695
1696set_child_ptrmaps_out:
1697 pPage->isInit = isInitOrig;
1698 return rc;
1699}
1700
1701/*
1702** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
1703** page, is a pointer to page iFrom. Modify this pointer so that it points to
1704** iTo. Parameter eType describes the type of pointer to be modified, as
1705** follows:
1706**
1707** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
1708** page of pPage.
1709**
1710** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
1711** page pointed to by one of the cells on pPage.
1712**
1713** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
1714** overflow page in the list.
1715*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00001716static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
danielk1977687566d2004-11-02 12:56:41 +00001717 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00001718 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00001719 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00001720 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00001721 }
danielk1977f78fc082004-11-02 14:40:32 +00001722 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00001723 }else{
1724 int isInitOrig = pPage->isInit;
1725 int i;
1726 int nCell;
1727
drh16a9b832007-05-05 18:39:25 +00001728 sqlite3BtreeInitPage(pPage, 0);
danielk1977687566d2004-11-02 12:56:41 +00001729 nCell = pPage->nCell;
1730
danielk1977687566d2004-11-02 12:56:41 +00001731 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00001732 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00001733 if( eType==PTRMAP_OVERFLOW1 ){
1734 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00001735 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
danielk1977687566d2004-11-02 12:56:41 +00001736 if( info.iOverflow ){
1737 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
1738 put4byte(&pCell[info.iOverflow], iTo);
1739 break;
1740 }
1741 }
1742 }else{
1743 if( get4byte(pCell)==iFrom ){
1744 put4byte(pCell, iTo);
1745 break;
1746 }
1747 }
1748 }
1749
1750 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00001751 if( eType!=PTRMAP_BTREE ||
1752 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00001753 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00001754 }
danielk1977687566d2004-11-02 12:56:41 +00001755 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
1756 }
1757
1758 pPage->isInit = isInitOrig;
1759 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00001760 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00001761}
1762
danielk1977003ba062004-11-04 02:57:33 +00001763
danielk19777701e812005-01-10 12:59:51 +00001764/*
1765** Move the open database page pDbPage to location iFreePage in the
1766** database. The pDbPage reference remains valid.
1767*/
danielk1977003ba062004-11-04 02:57:33 +00001768static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00001769 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00001770 MemPage *pDbPage, /* Open page to move */
1771 u8 eType, /* Pointer map 'type' entry for pDbPage */
1772 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
1773 Pgno iFreePage /* The location to move pDbPage to */
danielk1977003ba062004-11-04 02:57:33 +00001774){
1775 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
1776 Pgno iDbPage = pDbPage->pgno;
1777 Pager *pPager = pBt->pPager;
1778 int rc;
1779
danielk1977a0bf2652004-11-04 14:30:04 +00001780 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
1781 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
danielk1977003ba062004-11-04 02:57:33 +00001782
1783 /* Move page iDbPage from it's current location to page number iFreePage */
1784 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
1785 iDbPage, iFreePage, iPtrPage, eType));
danielk19773b8a05f2007-03-19 17:44:26 +00001786 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage);
danielk1977003ba062004-11-04 02:57:33 +00001787 if( rc!=SQLITE_OK ){
1788 return rc;
1789 }
1790 pDbPage->pgno = iFreePage;
1791
1792 /* If pDbPage was a btree-page, then it may have child pages and/or cells
1793 ** that point to overflow pages. The pointer map entries for all these
1794 ** pages need to be changed.
1795 **
1796 ** If pDbPage is an overflow page, then the first 4 bytes may store a
1797 ** pointer to a subsequent overflow page. If this is the case, then
1798 ** the pointer map needs to be updated for the subsequent overflow page.
1799 */
danielk1977a0bf2652004-11-04 14:30:04 +00001800 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00001801 rc = setChildPtrmaps(pDbPage);
1802 if( rc!=SQLITE_OK ){
1803 return rc;
1804 }
1805 }else{
1806 Pgno nextOvfl = get4byte(pDbPage->aData);
1807 if( nextOvfl!=0 ){
danielk1977003ba062004-11-04 02:57:33 +00001808 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
1809 if( rc!=SQLITE_OK ){
1810 return rc;
1811 }
1812 }
1813 }
1814
1815 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
1816 ** that it points at iFreePage. Also fix the pointer map entry for
1817 ** iPtrPage.
1818 */
danielk1977a0bf2652004-11-04 14:30:04 +00001819 if( eType!=PTRMAP_ROOTPAGE ){
drh16a9b832007-05-05 18:39:25 +00001820 rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00001821 if( rc!=SQLITE_OK ){
1822 return rc;
1823 }
danielk19773b8a05f2007-03-19 17:44:26 +00001824 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00001825 if( rc!=SQLITE_OK ){
1826 releasePage(pPtrPage);
1827 return rc;
1828 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00001829 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00001830 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00001831 if( rc==SQLITE_OK ){
1832 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
1833 }
danielk1977003ba062004-11-04 02:57:33 +00001834 }
danielk1977003ba062004-11-04 02:57:33 +00001835 return rc;
1836}
1837
danielk1977dddbcdc2007-04-26 14:42:34 +00001838/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00001839static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00001840
1841/*
danielk1977dddbcdc2007-04-26 14:42:34 +00001842** Perform a single step of an incremental-vacuum. If successful,
1843** return SQLITE_OK. If there is no work to do (and therefore no
1844** point in calling this function again), return SQLITE_DONE.
1845**
1846** More specificly, this function attempts to re-organize the
1847** database so that the last page of the file currently in use
1848** is no longer in use.
1849**
1850** If the nFin parameter is non-zero, the implementation assumes
1851** that the caller will keep calling incrVacuumStep() until
1852** it returns SQLITE_DONE or an error, and that nFin is the
1853** number of pages the database file will contain after this
1854** process is complete.
1855*/
1856static int incrVacuumStep(BtShared *pBt, Pgno nFin){
1857 Pgno iLastPg; /* Last page in the database */
1858 Pgno nFreeList; /* Number of pages still on the free-list */
1859
1860 iLastPg = pBt->nTrunc;
1861 if( iLastPg==0 ){
1862 iLastPg = sqlite3PagerPagecount(pBt->pPager);
1863 }
1864
1865 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
1866 int rc;
1867 u8 eType;
1868 Pgno iPtrPage;
1869
1870 nFreeList = get4byte(&pBt->pPage1->aData[36]);
1871 if( nFreeList==0 || nFin==iLastPg ){
1872 return SQLITE_DONE;
1873 }
1874
1875 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
1876 if( rc!=SQLITE_OK ){
1877 return rc;
1878 }
1879 if( eType==PTRMAP_ROOTPAGE ){
1880 return SQLITE_CORRUPT_BKPT;
1881 }
1882
1883 if( eType==PTRMAP_FREEPAGE ){
1884 if( nFin==0 ){
1885 /* Remove the page from the files free-list. This is not required
danielk19774ef24492007-05-23 09:52:41 +00001886 ** if nFin is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00001887 ** truncated to zero after this function returns, so it doesn't
1888 ** matter if it still contains some garbage entries.
1889 */
1890 Pgno iFreePg;
1891 MemPage *pFreePg;
1892 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
1893 if( rc!=SQLITE_OK ){
1894 return rc;
1895 }
1896 assert( iFreePg==iLastPg );
1897 releasePage(pFreePg);
1898 }
1899 } else {
1900 Pgno iFreePg; /* Index of free page to move pLastPg to */
1901 MemPage *pLastPg;
1902
drh16a9b832007-05-05 18:39:25 +00001903 rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00001904 if( rc!=SQLITE_OK ){
1905 return rc;
1906 }
1907
danielk1977b4626a32007-04-28 15:47:43 +00001908 /* If nFin is zero, this loop runs exactly once and page pLastPg
1909 ** is swapped with the first free page pulled off the free list.
1910 **
1911 ** On the other hand, if nFin is greater than zero, then keep
1912 ** looping until a free-page located within the first nFin pages
1913 ** of the file is found.
1914 */
danielk1977dddbcdc2007-04-26 14:42:34 +00001915 do {
1916 MemPage *pFreePg;
1917 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
1918 if( rc!=SQLITE_OK ){
1919 releasePage(pLastPg);
1920 return rc;
1921 }
1922 releasePage(pFreePg);
1923 }while( nFin!=0 && iFreePg>nFin );
1924 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00001925
1926 rc = sqlite3PagerWrite(pLastPg->pDbPage);
1927 if( rc!=SQLITE_OK ){
1928 return rc;
1929 }
danielk1977dddbcdc2007-04-26 14:42:34 +00001930 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg);
1931 releasePage(pLastPg);
1932 if( rc!=SQLITE_OK ){
1933 return rc;
1934 }
1935 }
1936 }
1937
1938 pBt->nTrunc = iLastPg - 1;
1939 while( pBt->nTrunc==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, pBt->nTrunc) ){
1940 pBt->nTrunc--;
1941 }
1942 return SQLITE_OK;
1943}
1944
1945/*
1946** A write-transaction must be opened before calling this function.
1947** It performs a single unit of work towards an incremental vacuum.
1948**
1949** If the incremental vacuum is finished after this function has run,
1950** SQLITE_DONE is returned. If it is not finished, but no error occured,
1951** SQLITE_OK is returned. Otherwise an SQLite error code.
1952*/
1953int sqlite3BtreeIncrVacuum(Btree *p){
1954 BtShared *pBt = p->pBt;
danielk1977dddbcdc2007-04-26 14:42:34 +00001955 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
1956 if( !pBt->autoVacuum ){
1957 return SQLITE_DONE;
1958 }
danielk197792d4d7a2007-05-04 12:05:56 +00001959 invalidateAllOverflowCache(pBt);
danielk19772dec9702007-05-02 16:48:37 +00001960 return incrVacuumStep(pBt, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00001961}
1962
1963/*
danielk19773b8a05f2007-03-19 17:44:26 +00001964** This routine is called prior to sqlite3PagerCommit when a transaction
danielk1977687566d2004-11-02 12:56:41 +00001965** is commited for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00001966**
1967** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
1968** the database file should be truncated to during the commit process.
1969** i.e. the database has been reorganized so that only the first *pnTrunc
1970** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00001971*/
danielk197724168722007-04-02 05:07:47 +00001972static int autoVacuumCommit(BtShared *pBt, Pgno *pnTrunc){
danielk1977dddbcdc2007-04-26 14:42:34 +00001973 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00001974 Pager *pPager = pBt->pPager;
danielk1977687566d2004-11-02 12:56:41 +00001975#ifndef NDEBUG
danielk19773b8a05f2007-03-19 17:44:26 +00001976 int nRef = sqlite3PagerRefcount(pPager);
danielk1977687566d2004-11-02 12:56:41 +00001977#endif
1978
danielk197792d4d7a2007-05-04 12:05:56 +00001979 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00001980 assert(pBt->autoVacuum);
1981 if( !pBt->incrVacuum ){
1982 Pgno nFin = 0;
danielk1977687566d2004-11-02 12:56:41 +00001983
danielk1977dddbcdc2007-04-26 14:42:34 +00001984 if( pBt->nTrunc==0 ){
1985 Pgno nFree;
1986 Pgno nPtrmap;
1987 const int pgsz = pBt->pageSize;
1988 Pgno nOrig = sqlite3PagerPagecount(pBt->pPager);
danielk1977e5321f02007-04-27 07:05:44 +00001989
1990 if( PTRMAP_ISPAGE(pBt, nOrig) ){
1991 return SQLITE_CORRUPT_BKPT;
1992 }
danielk1977dddbcdc2007-04-26 14:42:34 +00001993 if( nOrig==PENDING_BYTE_PAGE(pBt) ){
1994 nOrig--;
danielk1977687566d2004-11-02 12:56:41 +00001995 }
danielk1977dddbcdc2007-04-26 14:42:34 +00001996 nFree = get4byte(&pBt->pPage1->aData[36]);
1997 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
1998 nFin = nOrig - nFree - nPtrmap;
1999 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
2000 nFin--;
danielk1977ac11ee62005-01-15 12:45:51 +00002001 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002002 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
2003 nFin--;
2004 }
2005 }
danielk1977687566d2004-11-02 12:56:41 +00002006
danielk1977dddbcdc2007-04-26 14:42:34 +00002007 while( rc==SQLITE_OK ){
2008 rc = incrVacuumStep(pBt, nFin);
2009 }
2010 if( rc==SQLITE_DONE ){
2011 assert(nFin==0 || pBt->nTrunc==0 || nFin<=pBt->nTrunc);
2012 rc = SQLITE_OK;
2013 if( pBt->nTrunc ){
drh67f80b62007-07-23 19:26:17 +00002014 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
danielk1977dddbcdc2007-04-26 14:42:34 +00002015 put4byte(&pBt->pPage1->aData[32], 0);
2016 put4byte(&pBt->pPage1->aData[36], 0);
2017 pBt->nTrunc = nFin;
2018 }
2019 }
2020 if( rc!=SQLITE_OK ){
2021 sqlite3PagerRollback(pPager);
2022 }
danielk1977687566d2004-11-02 12:56:41 +00002023 }
2024
danielk1977dddbcdc2007-04-26 14:42:34 +00002025 if( rc==SQLITE_OK ){
2026 *pnTrunc = pBt->nTrunc;
2027 pBt->nTrunc = 0;
2028 }
danielk19773b8a05f2007-03-19 17:44:26 +00002029 assert( nRef==sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002030 return rc;
2031}
danielk1977dddbcdc2007-04-26 14:42:34 +00002032
danielk1977687566d2004-11-02 12:56:41 +00002033#endif
2034
2035/*
drh80e35f42007-03-30 14:06:34 +00002036** This routine does the first phase of a two-phase commit. This routine
2037** causes a rollback journal to be created (if it does not already exist)
2038** and populated with enough information so that if a power loss occurs
2039** the database can be restored to its original state by playing back
2040** the journal. Then the contents of the journal are flushed out to
2041** the disk. After the journal is safely on oxide, the changes to the
2042** database are written into the database file and flushed to oxide.
2043** At the end of this call, the rollback journal still exists on the
2044** disk and we are still holding all locks, so the transaction has not
2045** committed. See sqlite3BtreeCommit() for the second phase of the
2046** commit process.
2047**
2048** This call is a no-op if no write-transaction is currently active on pBt.
2049**
2050** Otherwise, sync the database file for the btree pBt. zMaster points to
2051** the name of a master journal file that should be written into the
2052** individual journal file, or is NULL, indicating no master journal file
2053** (single database transaction).
2054**
2055** When this is called, the master journal should already have been
2056** created, populated with this journal pointer and synced to disk.
2057**
2058** Once this is routine has returned, the only thing required to commit
2059** the write-transaction for this database file is to delete the journal.
2060*/
2061int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
2062 int rc = SQLITE_OK;
2063 if( p->inTrans==TRANS_WRITE ){
2064 BtShared *pBt = p->pBt;
2065 Pgno nTrunc = 0;
2066#ifndef SQLITE_OMIT_AUTOVACUUM
2067 if( pBt->autoVacuum ){
2068 rc = autoVacuumCommit(pBt, &nTrunc);
2069 if( rc!=SQLITE_OK ){
2070 return rc;
2071 }
2072 }
2073#endif
2074 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, nTrunc);
2075 }
2076 return rc;
2077}
2078
2079/*
drh2aa679f2001-06-25 02:11:07 +00002080** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00002081**
drh6e345992007-03-30 11:12:08 +00002082** This routine implements the second phase of a 2-phase commit. The
2083** sqlite3BtreeSync() routine does the first phase and should be invoked
2084** prior to calling this routine. The sqlite3BtreeSync() routine did
2085** all the work of writing information out to disk and flushing the
2086** contents so that they are written onto the disk platter. All this
2087** routine has to do is delete or truncate the rollback journal
2088** (which causes the transaction to commit) and drop locks.
2089**
drh5e00f6c2001-09-13 13:46:56 +00002090** This will release the write lock on the database file. If there
2091** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002092*/
drh80e35f42007-03-30 14:06:34 +00002093int sqlite3BtreeCommitPhaseTwo(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002094 BtShared *pBt = p->pBt;
2095
2096 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002097
2098 /* If the handle has a write-transaction open, commit the shared-btrees
2099 ** transaction and set the shared state to TRANS_READ.
2100 */
2101 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00002102 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002103 assert( pBt->inTransaction==TRANS_WRITE );
2104 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00002105 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
danielk19777f7bc662006-01-23 13:47:47 +00002106 if( rc!=SQLITE_OK ){
2107 return rc;
2108 }
danielk1977aef0bf62005-12-30 16:28:01 +00002109 pBt->inTransaction = TRANS_READ;
2110 pBt->inStmt = 0;
danielk1977ee5741e2004-05-31 10:01:34 +00002111 }
danielk19777f7bc662006-01-23 13:47:47 +00002112 unlockAllTables(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002113
2114 /* If the handle has any kind of transaction open, decrement the transaction
2115 ** count of the shared btree. If the transaction count reaches 0, set
2116 ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
2117 ** will unlock the pager.
2118 */
2119 if( p->inTrans!=TRANS_NONE ){
2120 pBt->nTransaction--;
2121 if( 0==pBt->nTransaction ){
2122 pBt->inTransaction = TRANS_NONE;
2123 }
2124 }
2125
2126 /* Set the handles current transaction state to TRANS_NONE and unlock
2127 ** the pager if this call closed the only read or write transaction.
2128 */
2129 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00002130 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002131
2132 btreeIntegrity(p);
danielk19777f7bc662006-01-23 13:47:47 +00002133 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002134}
2135
drh80e35f42007-03-30 14:06:34 +00002136/*
2137** Do both phases of a commit.
2138*/
2139int sqlite3BtreeCommit(Btree *p){
2140 int rc;
2141 rc = sqlite3BtreeCommitPhaseOne(p, 0);
2142 if( rc==SQLITE_OK ){
2143 rc = sqlite3BtreeCommitPhaseTwo(p);
2144 }
2145 return rc;
2146}
2147
danielk1977fbcd5852004-06-15 02:44:18 +00002148#ifndef NDEBUG
2149/*
2150** Return the number of write-cursors open on this handle. This is for use
2151** in assert() expressions, so it is only compiled if NDEBUG is not
2152** defined.
2153*/
danielk1977aef0bf62005-12-30 16:28:01 +00002154static int countWriteCursors(BtShared *pBt){
danielk1977fbcd5852004-06-15 02:44:18 +00002155 BtCursor *pCur;
2156 int r = 0;
2157 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
danielk1977aef0bf62005-12-30 16:28:01 +00002158 if( pCur->wrFlag ) r++;
danielk1977fbcd5852004-06-15 02:44:18 +00002159 }
2160 return r;
2161}
2162#endif
2163
drhc39e0002004-05-07 23:50:57 +00002164/*
drhecdc7532001-09-23 02:35:53 +00002165** Rollback the transaction in progress. All cursors will be
2166** invalided by this operation. Any attempt to use a cursor
2167** that was open at the beginning of this operation will result
2168** in an error.
drh5e00f6c2001-09-13 13:46:56 +00002169**
2170** This will release the write lock on the database file. If there
2171** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002172*/
danielk1977aef0bf62005-12-30 16:28:01 +00002173int sqlite3BtreeRollback(Btree *p){
danielk19778d34dfd2006-01-24 16:37:57 +00002174 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002175 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00002176 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00002177
danielk19772b8c13e2006-01-24 14:21:24 +00002178 rc = saveAllCursors(pBt, 0, 0);
danielk19778d34dfd2006-01-24 16:37:57 +00002179#ifndef SQLITE_OMIT_SHARED_CACHE
danielk19772b8c13e2006-01-24 14:21:24 +00002180 if( rc!=SQLITE_OK ){
danielk19778d34dfd2006-01-24 16:37:57 +00002181 /* This is a horrible situation. An IO or malloc() error occured whilst
2182 ** trying to save cursor positions. If this is an automatic rollback (as
2183 ** the result of a constraint, malloc() failure or IO error) then
2184 ** the cache may be internally inconsistent (not contain valid trees) so
2185 ** we cannot simply return the error to the caller. Instead, abort
2186 ** all queries that may be using any of the cursors that failed to save.
2187 */
2188 while( pBt->pCursor ){
2189 sqlite3 *db = pBt->pCursor->pBtree->pSqlite;
2190 if( db ){
2191 sqlite3AbortOtherActiveVdbes(db, 0);
2192 }
2193 }
danielk19772b8c13e2006-01-24 14:21:24 +00002194 }
danielk19778d34dfd2006-01-24 16:37:57 +00002195#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002196 btreeIntegrity(p);
2197 unlockAllTables(p);
2198
2199 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00002200 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00002201
danielk1977dddbcdc2007-04-26 14:42:34 +00002202#ifndef SQLITE_OMIT_AUTOVACUUM
2203 pBt->nTrunc = 0;
2204#endif
2205
danielk19778d34dfd2006-01-24 16:37:57 +00002206 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00002207 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00002208 if( rc2!=SQLITE_OK ){
2209 rc = rc2;
2210 }
2211
drh24cd67e2004-05-10 16:18:47 +00002212 /* The rollback may have destroyed the pPage1->aData value. So
drh16a9b832007-05-05 18:39:25 +00002213 ** call sqlite3BtreeGetPage() on page 1 again to make
2214 ** sure pPage1->aData is set correctly. */
2215 if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh24cd67e2004-05-10 16:18:47 +00002216 releasePage(pPage1);
2217 }
danielk1977fbcd5852004-06-15 02:44:18 +00002218 assert( countWriteCursors(pBt)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002219 pBt->inTransaction = TRANS_READ;
drh24cd67e2004-05-10 16:18:47 +00002220 }
danielk1977aef0bf62005-12-30 16:28:01 +00002221
2222 if( p->inTrans!=TRANS_NONE ){
2223 assert( pBt->nTransaction>0 );
2224 pBt->nTransaction--;
2225 if( 0==pBt->nTransaction ){
2226 pBt->inTransaction = TRANS_NONE;
2227 }
2228 }
2229
2230 p->inTrans = TRANS_NONE;
danielk1977ee5741e2004-05-31 10:01:34 +00002231 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00002232 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002233
2234 btreeIntegrity(p);
drha059ad02001-04-17 20:09:11 +00002235 return rc;
2236}
2237
2238/*
drhab01f612004-05-22 02:55:23 +00002239** Start a statement subtransaction. The subtransaction can
2240** can be rolled back independently of the main transaction.
2241** You must start a transaction before starting a subtransaction.
2242** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00002243** commits or rolls back.
2244**
drhab01f612004-05-22 02:55:23 +00002245** Only one subtransaction may be active at a time. It is an error to try
2246** to start a new subtransaction if another subtransaction is already active.
2247**
2248** Statement subtransactions are used around individual SQL statements
2249** that are contained within a BEGIN...COMMIT block. If a constraint
2250** error occurs within the statement, the effect of that one statement
2251** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00002252*/
danielk1977aef0bf62005-12-30 16:28:01 +00002253int sqlite3BtreeBeginStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002254 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002255 BtShared *pBt = p->pBt;
2256 if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
drhf74b8d92002-09-01 23:20:45 +00002257 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh0d65dc02002-02-03 00:56:09 +00002258 }
danielk1977aef0bf62005-12-30 16:28:01 +00002259 assert( pBt->inTransaction==TRANS_WRITE );
danielk19773b8a05f2007-03-19 17:44:26 +00002260 rc = pBt->readOnly ? SQLITE_OK : sqlite3PagerStmtBegin(pBt->pPager);
drh3aac2dd2004-04-26 14:10:20 +00002261 pBt->inStmt = 1;
drh663fc632002-02-02 18:49:19 +00002262 return rc;
2263}
2264
2265
2266/*
drhab01f612004-05-22 02:55:23 +00002267** Commit the statment subtransaction currently in progress. If no
2268** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00002269*/
danielk1977aef0bf62005-12-30 16:28:01 +00002270int sqlite3BtreeCommitStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002271 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002272 BtShared *pBt = p->pBt;
drh3aac2dd2004-04-26 14:10:20 +00002273 if( pBt->inStmt && !pBt->readOnly ){
danielk19773b8a05f2007-03-19 17:44:26 +00002274 rc = sqlite3PagerStmtCommit(pBt->pPager);
drh663fc632002-02-02 18:49:19 +00002275 }else{
2276 rc = SQLITE_OK;
2277 }
drh3aac2dd2004-04-26 14:10:20 +00002278 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00002279 return rc;
2280}
2281
2282/*
drhab01f612004-05-22 02:55:23 +00002283** Rollback the active statement subtransaction. If no subtransaction
2284** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00002285**
drhab01f612004-05-22 02:55:23 +00002286** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00002287** to use a cursor that was open at the beginning of this operation
2288** will result in an error.
2289*/
danielk1977aef0bf62005-12-30 16:28:01 +00002290int sqlite3BtreeRollbackStmt(Btree *p){
danielk197797a227c2006-01-20 16:32:04 +00002291 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002292 BtShared *pBt = p->pBt;
danielk197797a227c2006-01-20 16:32:04 +00002293 sqlite3MallocDisallow();
2294 if( pBt->inStmt && !pBt->readOnly ){
danielk19773b8a05f2007-03-19 17:44:26 +00002295 rc = sqlite3PagerStmtRollback(pBt->pPager);
danielk197797a227c2006-01-20 16:32:04 +00002296 assert( countWriteCursors(pBt)==0 );
2297 pBt->inStmt = 0;
2298 }
2299 sqlite3MallocAllow();
drh663fc632002-02-02 18:49:19 +00002300 return rc;
2301}
2302
2303/*
drh3aac2dd2004-04-26 14:10:20 +00002304** Default key comparison function to be used if no comparison function
2305** is specified on the sqlite3BtreeCursor() call.
2306*/
2307static int dfltCompare(
2308 void *NotUsed, /* User data is not used */
2309 int n1, const void *p1, /* First key to compare */
2310 int n2, const void *p2 /* Second key to compare */
2311){
2312 int c;
2313 c = memcmp(p1, p2, n1<n2 ? n1 : n2);
2314 if( c==0 ){
2315 c = n1 - n2;
2316 }
2317 return c;
2318}
2319
2320/*
drh8b2f49b2001-06-08 00:21:52 +00002321** Create a new cursor for the BTree whose root is on the page
2322** iTable. The act of acquiring a cursor gets a read lock on
2323** the database file.
drh1bee3d72001-10-15 00:44:35 +00002324**
2325** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00002326** If wrFlag==1, then the cursor can be used for reading or for
2327** writing if other conditions for writing are also met. These
2328** are the conditions that must be met in order for writing to
2329** be allowed:
drh6446c4d2001-12-15 14:22:18 +00002330**
drhf74b8d92002-09-01 23:20:45 +00002331** 1: The cursor must have been opened with wrFlag==1
2332**
drhfe5d71d2007-03-19 11:54:10 +00002333** 2: Other database connections that share the same pager cache
2334** but which are not in the READ_UNCOMMITTED state may not have
2335** cursors open with wrFlag==0 on the same table. Otherwise
2336** the changes made by this write cursor would be visible to
2337** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00002338**
2339** 3: The database must be writable (not on read-only media)
2340**
2341** 4: There must be an active transaction.
2342**
drh6446c4d2001-12-15 14:22:18 +00002343** No checking is done to make sure that page iTable really is the
2344** root page of a b-tree. If it is not, then the cursor acquired
2345** will not work correctly.
drh3aac2dd2004-04-26 14:10:20 +00002346**
2347** The comparison function must be logically the same for every cursor
2348** on a particular table. Changing the comparison function will result
2349** in incorrect operations. If the comparison function is NULL, a
2350** default comparison function is used. The comparison function is
2351** always ignored for INTKEY tables.
drha059ad02001-04-17 20:09:11 +00002352*/
drh3aac2dd2004-04-26 14:10:20 +00002353int sqlite3BtreeCursor(
danielk1977aef0bf62005-12-30 16:28:01 +00002354 Btree *p, /* The btree */
drh3aac2dd2004-04-26 14:10:20 +00002355 int iTable, /* Root page of table to open */
2356 int wrFlag, /* 1 to write. 0 read-only */
2357 int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
2358 void *pArg, /* First arg to xCompare() */
2359 BtCursor **ppCur /* Write new cursor here */
2360){
drha059ad02001-04-17 20:09:11 +00002361 int rc;
drh8dcd7ca2004-08-08 19:43:29 +00002362 BtCursor *pCur;
danielk1977aef0bf62005-12-30 16:28:01 +00002363 BtShared *pBt = p->pBt;
drhecdc7532001-09-23 02:35:53 +00002364
drh8dcd7ca2004-08-08 19:43:29 +00002365 *ppCur = 0;
2366 if( wrFlag ){
drh8dcd7ca2004-08-08 19:43:29 +00002367 if( pBt->readOnly ){
2368 return SQLITE_READONLY;
2369 }
drh980b1a72006-08-16 16:42:48 +00002370 if( checkReadLocks(p, iTable, 0) ){
drh8dcd7ca2004-08-08 19:43:29 +00002371 return SQLITE_LOCKED;
2372 }
drha0c9a112004-03-10 13:42:37 +00002373 }
danielk1977aef0bf62005-12-30 16:28:01 +00002374
drh4b70f112004-05-02 21:12:19 +00002375 if( pBt->pPage1==0 ){
danielk1977aef0bf62005-12-30 16:28:01 +00002376 rc = lockBtreeWithRetry(p);
drha059ad02001-04-17 20:09:11 +00002377 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00002378 return rc;
2379 }
drh1831f182007-04-24 17:35:59 +00002380 if( pBt->readOnly && wrFlag ){
2381 return SQLITE_READONLY;
2382 }
drha059ad02001-04-17 20:09:11 +00002383 }
danielk1977da184232006-01-05 11:34:32 +00002384 pCur = sqliteMalloc( sizeof(*pCur) );
drha059ad02001-04-17 20:09:11 +00002385 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +00002386 rc = SQLITE_NOMEM;
2387 goto create_cursor_exception;
2388 }
drh8b2f49b2001-06-08 00:21:52 +00002389 pCur->pgnoRoot = (Pgno)iTable;
danielk19773b8a05f2007-03-19 17:44:26 +00002390 if( iTable==1 && sqlite3PagerPagecount(pBt->pPager)==0 ){
drh24cd67e2004-05-10 16:18:47 +00002391 rc = SQLITE_EMPTY;
2392 goto create_cursor_exception;
2393 }
drhde647132004-05-07 17:57:49 +00002394 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
drhbd03cae2001-06-02 02:40:57 +00002395 if( rc!=SQLITE_OK ){
2396 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00002397 }
danielk1977aef0bf62005-12-30 16:28:01 +00002398
danielk1977aef0bf62005-12-30 16:28:01 +00002399 /* Now that no other errors can occur, finish filling in the BtCursor
2400 ** variables, link the cursor into the BtShared list and set *ppCur (the
2401 ** output argument to this function).
2402 */
drh3aac2dd2004-04-26 14:10:20 +00002403 pCur->xCompare = xCmp ? xCmp : dfltCompare;
2404 pCur->pArg = pArg;
danielk1977aef0bf62005-12-30 16:28:01 +00002405 pCur->pBtree = p;
drhecdc7532001-09-23 02:35:53 +00002406 pCur->wrFlag = wrFlag;
drha059ad02001-04-17 20:09:11 +00002407 pCur->pNext = pBt->pCursor;
2408 if( pCur->pNext ){
2409 pCur->pNext->pPrev = pCur;
2410 }
2411 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00002412 pCur->eState = CURSOR_INVALID;
drh2af926b2001-05-15 00:39:25 +00002413 *ppCur = pCur;
drhbd03cae2001-06-02 02:40:57 +00002414
danielk1977aef0bf62005-12-30 16:28:01 +00002415 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00002416create_cursor_exception:
drhbd03cae2001-06-02 02:40:57 +00002417 if( pCur ){
drh3aac2dd2004-04-26 14:10:20 +00002418 releasePage(pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +00002419 sqliteFree(pCur);
2420 }
drh5e00f6c2001-09-13 13:46:56 +00002421 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00002422 return rc;
drha059ad02001-04-17 20:09:11 +00002423}
2424
2425/*
drh5e00f6c2001-09-13 13:46:56 +00002426** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00002427** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00002428*/
drh3aac2dd2004-04-26 14:10:20 +00002429int sqlite3BtreeCloseCursor(BtCursor *pCur){
danielk1977aef0bf62005-12-30 16:28:01 +00002430 BtShared *pBt = pCur->pBtree->pBt;
drhbf700f32007-03-31 02:36:44 +00002431 clearCursorPosition(pCur);
drha059ad02001-04-17 20:09:11 +00002432 if( pCur->pPrev ){
2433 pCur->pPrev->pNext = pCur->pNext;
2434 }else{
2435 pBt->pCursor = pCur->pNext;
2436 }
2437 if( pCur->pNext ){
2438 pCur->pNext->pPrev = pCur->pPrev;
2439 }
drh3aac2dd2004-04-26 14:10:20 +00002440 releasePage(pCur->pPage);
drh5e00f6c2001-09-13 13:46:56 +00002441 unlockBtreeIfUnused(pBt);
danielk197792d4d7a2007-05-04 12:05:56 +00002442 invalidateOverflowCache(pCur);
drha059ad02001-04-17 20:09:11 +00002443 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +00002444 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002445}
2446
drh7e3b0a02001-04-28 16:52:40 +00002447/*
drh5e2f8b92001-05-28 00:41:15 +00002448** Make a temporary cursor by filling in the fields of pTempCur.
2449** The temporary cursor is not on the cursor list for the Btree.
2450*/
drh16a9b832007-05-05 18:39:25 +00002451void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +00002452 memcpy(pTempCur, pCur, sizeof(*pCur));
2453 pTempCur->pNext = 0;
2454 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00002455 if( pTempCur->pPage ){
danielk19773b8a05f2007-03-19 17:44:26 +00002456 sqlite3PagerRef(pTempCur->pPage->pDbPage);
drhecdc7532001-09-23 02:35:53 +00002457 }
drh5e2f8b92001-05-28 00:41:15 +00002458}
2459
2460/*
drhbd03cae2001-06-02 02:40:57 +00002461** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00002462** function above.
2463*/
drh16a9b832007-05-05 18:39:25 +00002464void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +00002465 if( pCur->pPage ){
danielk19773b8a05f2007-03-19 17:44:26 +00002466 sqlite3PagerUnref(pCur->pPage->pDbPage);
drhecdc7532001-09-23 02:35:53 +00002467 }
drh5e2f8b92001-05-28 00:41:15 +00002468}
2469
2470/*
drh86057612007-06-26 01:04:48 +00002471** Make sure the BtCursor* given in the argument has a valid
2472** BtCursor.info structure. If it is not already valid, call
danielk19771cc5ed82007-05-16 17:28:43 +00002473** sqlite3BtreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00002474**
2475** BtCursor.info is a cache of the information in the current cell.
drh16a9b832007-05-05 18:39:25 +00002476** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
drh86057612007-06-26 01:04:48 +00002477**
2478** 2007-06-25: There is a bug in some versions of MSVC that cause the
2479** compiler to crash when getCellInfo() is implemented as a macro.
2480** But there is a measureable speed advantage to using the macro on gcc
2481** (when less compiler optimizations like -Os or -O0 are used and the
2482** compiler is not doing agressive inlining.) So we use a real function
2483** for MSVC and a macro for everything else. Ticket #2457.
drh9188b382004-05-14 21:12:22 +00002484*/
drh9188b382004-05-14 21:12:22 +00002485#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00002486 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00002487 CellInfo info;
drh51c6d962004-06-06 00:42:25 +00002488 memset(&info, 0, sizeof(info));
drh16a9b832007-05-05 18:39:25 +00002489 sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &info);
drh9188b382004-05-14 21:12:22 +00002490 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00002491 }
danielk19771cc5ed82007-05-16 17:28:43 +00002492#else
2493 #define assertCellInfo(x)
2494#endif
drh86057612007-06-26 01:04:48 +00002495#ifdef _MSC_VER
2496 /* Use a real function in MSVC to work around bugs in that compiler. */
2497 static void getCellInfo(BtCursor *pCur){
2498 if( pCur->info.nSize==0 ){
2499 sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info);
2500 }else{
2501 assertCellInfo(pCur);
2502 }
2503 }
2504#else /* if not _MSC_VER */
2505 /* Use a macro in all other compilers so that the function is inlined */
2506#define getCellInfo(pCur) \
2507 if( pCur->info.nSize==0 ){ \
danielk19771cc5ed82007-05-16 17:28:43 +00002508 sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info); \
drh86057612007-06-26 01:04:48 +00002509 }else{ \
2510 assertCellInfo(pCur); \
2511 }
2512#endif /* _MSC_VER */
drh9188b382004-05-14 21:12:22 +00002513
2514/*
drh3aac2dd2004-04-26 14:10:20 +00002515** Set *pSize to the size of the buffer needed to hold the value of
2516** the key for the current entry. If the cursor is not pointing
2517** to a valid entry, *pSize is set to 0.
2518**
drh4b70f112004-05-02 21:12:19 +00002519** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00002520** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00002521*/
drh4a1c3802004-05-12 15:15:47 +00002522int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drhbf700f32007-03-31 02:36:44 +00002523 int rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00002524 if( rc==SQLITE_OK ){
2525 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
2526 if( pCur->eState==CURSOR_INVALID ){
2527 *pSize = 0;
2528 }else{
drh86057612007-06-26 01:04:48 +00002529 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00002530 *pSize = pCur->info.nKey;
2531 }
drh72f82862001-05-24 21:06:34 +00002532 }
danielk1977da184232006-01-05 11:34:32 +00002533 return rc;
drha059ad02001-04-17 20:09:11 +00002534}
drh2af926b2001-05-15 00:39:25 +00002535
drh72f82862001-05-24 21:06:34 +00002536/*
drh0e1c19e2004-05-11 00:58:56 +00002537** Set *pSize to the number of bytes of data in the entry the
2538** cursor currently points to. Always return SQLITE_OK.
2539** Failure is not possible. If the cursor is not currently
2540** pointing to an entry (which can happen, for example, if
2541** the database is empty) then *pSize is set to 0.
2542*/
2543int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drhbf700f32007-03-31 02:36:44 +00002544 int rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00002545 if( rc==SQLITE_OK ){
2546 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
2547 if( pCur->eState==CURSOR_INVALID ){
2548 /* Not pointing at a valid entry - set *pSize to 0. */
2549 *pSize = 0;
2550 }else{
drh86057612007-06-26 01:04:48 +00002551 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00002552 *pSize = pCur->info.nData;
2553 }
drh0e1c19e2004-05-11 00:58:56 +00002554 }
danielk1977da184232006-01-05 11:34:32 +00002555 return rc;
drh0e1c19e2004-05-11 00:58:56 +00002556}
2557
2558/*
danielk1977d04417962007-05-02 13:16:30 +00002559** Given the page number of an overflow page in the database (parameter
2560** ovfl), this function finds the page number of the next page in the
2561** linked list of overflow pages. If possible, it uses the auto-vacuum
2562** pointer-map data instead of reading the content of page ovfl to do so.
2563**
2564** If an error occurs an SQLite error code is returned. Otherwise:
2565**
2566** Unless pPgnoNext is NULL, the page number of the next overflow
2567** page in the linked list is written to *pPgnoNext. If page ovfl
2568** is the last page in it's linked list, *pPgnoNext is set to zero.
2569**
2570** If ppPage is not NULL, *ppPage is set to the MemPage* handle
2571** for page ovfl. The underlying pager page may have been requested
2572** with the noContent flag set, so the page data accessable via
2573** this handle may not be trusted.
2574*/
2575static int getOverflowPage(
2576 BtShared *pBt,
2577 Pgno ovfl, /* Overflow page */
2578 MemPage **ppPage, /* OUT: MemPage handle */
2579 Pgno *pPgnoNext /* OUT: Next overflow page number */
2580){
2581 Pgno next = 0;
2582 int rc;
2583
2584 /* One of these must not be NULL. Otherwise, why call this function? */
2585 assert(ppPage || pPgnoNext);
2586
2587 /* If pPgnoNext is NULL, then this function is being called to obtain
2588 ** a MemPage* reference only. No page-data is required in this case.
2589 */
2590 if( !pPgnoNext ){
drh16a9b832007-05-05 18:39:25 +00002591 return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1);
danielk1977d04417962007-05-02 13:16:30 +00002592 }
2593
2594#ifndef SQLITE_OMIT_AUTOVACUUM
2595 /* Try to find the next page in the overflow list using the
2596 ** autovacuum pointer-map pages. Guess that the next page in
2597 ** the overflow list is page number (ovfl+1). If that guess turns
2598 ** out to be wrong, fall back to loading the data of page
2599 ** number ovfl to determine the next page number.
2600 */
2601 if( pBt->autoVacuum ){
2602 Pgno pgno;
2603 Pgno iGuess = ovfl+1;
2604 u8 eType;
2605
2606 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
2607 iGuess++;
2608 }
2609
danielk197720713f32007-05-03 11:43:33 +00002610 if( iGuess<=sqlite3PagerPagecount(pBt->pPager) ){
danielk1977d04417962007-05-02 13:16:30 +00002611 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
2612 if( rc!=SQLITE_OK ){
2613 return rc;
2614 }
2615 if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
2616 next = iGuess;
2617 }
2618 }
2619 }
2620#endif
2621
2622 if( next==0 || ppPage ){
2623 MemPage *pPage = 0;
2624
drh16a9b832007-05-05 18:39:25 +00002625 rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0);
danielk1977d04417962007-05-02 13:16:30 +00002626 assert(rc==SQLITE_OK || pPage==0);
2627 if( next==0 && rc==SQLITE_OK ){
2628 next = get4byte(pPage->aData);
2629 }
2630
2631 if( ppPage ){
2632 *ppPage = pPage;
2633 }else{
2634 releasePage(pPage);
2635 }
2636 }
2637 *pPgnoNext = next;
2638
2639 return rc;
2640}
2641
danielk1977da107192007-05-04 08:32:13 +00002642/*
2643** Copy data from a buffer to a page, or from a page to a buffer.
2644**
2645** pPayload is a pointer to data stored on database page pDbPage.
2646** If argument eOp is false, then nByte bytes of data are copied
2647** from pPayload to the buffer pointed at by pBuf. If eOp is true,
2648** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
2649** of data are copied from the buffer pBuf to pPayload.
2650**
2651** SQLITE_OK is returned on success, otherwise an error code.
2652*/
2653static int copyPayload(
2654 void *pPayload, /* Pointer to page data */
2655 void *pBuf, /* Pointer to buffer */
2656 int nByte, /* Number of bytes to copy */
2657 int eOp, /* 0 -> copy from page, 1 -> copy to page */
2658 DbPage *pDbPage /* Page containing pPayload */
2659){
2660 if( eOp ){
2661 /* Copy data from buffer to page (a write operation) */
2662 int rc = sqlite3PagerWrite(pDbPage);
2663 if( rc!=SQLITE_OK ){
2664 return rc;
2665 }
2666 memcpy(pPayload, pBuf, nByte);
2667 }else{
2668 /* Copy data from page to buffer (a read operation) */
2669 memcpy(pBuf, pPayload, nByte);
2670 }
2671 return SQLITE_OK;
2672}
danielk1977d04417962007-05-02 13:16:30 +00002673
2674/*
danielk19779f8d6402007-05-02 17:48:45 +00002675** This function is used to read or overwrite payload information
2676** for the entry that the pCur cursor is pointing to. If the eOp
2677** parameter is 0, this is a read operation (data copied into
2678** buffer pBuf). If it is non-zero, a write (data copied from
2679** buffer pBuf).
2680**
2681** A total of "amt" bytes are read or written beginning at "offset".
2682** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00002683**
2684** This routine does not make a distinction between key and data.
danielk19779f8d6402007-05-02 17:48:45 +00002685** It just reads or writes bytes from the payload area. Data might
2686** appear on the main page or be scattered out on multiple overflow
2687** pages.
danielk1977da107192007-05-04 08:32:13 +00002688**
danielk1977dcbb5d32007-05-04 18:36:44 +00002689** If the BtCursor.isIncrblobHandle flag is set, and the current
danielk1977da107192007-05-04 08:32:13 +00002690** cursor entry uses one or more overflow pages, this function
2691** allocates space for and lazily popluates the overflow page-list
2692** cache array (BtCursor.aOverflow). Subsequent calls use this
2693** cache to make seeking to the supplied offset more efficient.
2694**
2695** Once an overflow page-list cache has been allocated, it may be
2696** invalidated if some other cursor writes to the same table, or if
2697** the cursor is moved to a different row. Additionally, in auto-vacuum
2698** mode, the following events may invalidate an overflow page-list cache.
2699**
2700** * An incremental vacuum,
2701** * A commit in auto_vacuum="full" mode,
2702** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00002703*/
danielk19779f8d6402007-05-02 17:48:45 +00002704static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00002705 BtCursor *pCur, /* Cursor pointing to entry to read from */
2706 int offset, /* Begin reading this far into payload */
2707 int amt, /* Read this many bytes */
2708 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00002709 int skipKey, /* offset begins at data if this is true */
2710 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00002711){
2712 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00002713 int rc = SQLITE_OK;
drhfa1a98a2004-05-14 19:08:17 +00002714 u32 nKey;
danielk19772dec9702007-05-02 16:48:37 +00002715 int iIdx = 0;
danielk1977da107192007-05-04 08:32:13 +00002716 MemPage *pPage = pCur->pPage; /* Btree page of current cursor entry */
2717 BtShared *pBt = pCur->pBtree->pBt; /* Btree this cursor belongs to */
drh3aac2dd2004-04-26 14:10:20 +00002718
danielk1977da107192007-05-04 08:32:13 +00002719 assert( pPage );
danielk1977da184232006-01-05 11:34:32 +00002720 assert( pCur->eState==CURSOR_VALID );
drh3aac2dd2004-04-26 14:10:20 +00002721 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
danielk1977da107192007-05-04 08:32:13 +00002722 assert( offset>=0 );
2723
drh86057612007-06-26 01:04:48 +00002724 getCellInfo(pCur);
drh366fda62006-01-13 02:35:09 +00002725 aPayload = pCur->info.pCell + pCur->info.nHeader;
danielk1977da107192007-05-04 08:32:13 +00002726 nKey = (pPage->intKey ? 0 : pCur->info.nKey);
2727
drh3aac2dd2004-04-26 14:10:20 +00002728 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00002729 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00002730 }
drhfa1a98a2004-05-14 19:08:17 +00002731 if( offset+amt > nKey+pCur->info.nData ){
danielk1977da107192007-05-04 08:32:13 +00002732 /* Trying to read or write past the end of the data is an error */
drha34b6762004-05-07 13:30:42 +00002733 return SQLITE_ERROR;
drh3aac2dd2004-04-26 14:10:20 +00002734 }
danielk1977da107192007-05-04 08:32:13 +00002735
2736 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00002737 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00002738 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00002739 if( a+offset>pCur->info.nLocal ){
2740 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00002741 }
danielk1977da107192007-05-04 08:32:13 +00002742 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00002743 offset = 0;
drha34b6762004-05-07 13:30:42 +00002744 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00002745 amt -= a;
drhdd793422001-06-28 01:54:48 +00002746 }else{
drhfa1a98a2004-05-14 19:08:17 +00002747 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00002748 }
danielk1977da107192007-05-04 08:32:13 +00002749
2750 if( rc==SQLITE_OK && amt>0 ){
2751 const int ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
2752 Pgno nextPage;
2753
drhfa1a98a2004-05-14 19:08:17 +00002754 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00002755
danielk19772dec9702007-05-02 16:48:37 +00002756#ifndef SQLITE_OMIT_INCRBLOB
danielk1977dcbb5d32007-05-04 18:36:44 +00002757 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
danielk1977da107192007-05-04 08:32:13 +00002758 ** has not been allocated, allocate it now. The array is sized at
2759 ** one entry for each overflow page in the overflow chain. The
2760 ** page number of the first overflow page is stored in aOverflow[0],
2761 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
2762 ** (the cache is lazily populated).
2763 */
danielk1977dcbb5d32007-05-04 18:36:44 +00002764 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
danielk19772dec9702007-05-02 16:48:37 +00002765 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
2766 pCur->aOverflow = (Pgno *)sqliteMalloc(sizeof(Pgno)*nOvfl);
2767 if( nOvfl && !pCur->aOverflow ){
danielk1977da107192007-05-04 08:32:13 +00002768 rc = SQLITE_NOMEM;
danielk19772dec9702007-05-02 16:48:37 +00002769 }
2770 }
danielk1977da107192007-05-04 08:32:13 +00002771
2772 /* If the overflow page-list cache has been allocated and the
2773 ** entry for the first required overflow page is valid, skip
2774 ** directly to it.
2775 */
danielk19772dec9702007-05-02 16:48:37 +00002776 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
2777 iIdx = (offset/ovflSize);
2778 nextPage = pCur->aOverflow[iIdx];
2779 offset = (offset%ovflSize);
2780 }
2781#endif
danielk1977da107192007-05-04 08:32:13 +00002782
2783 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
2784
2785#ifndef SQLITE_OMIT_INCRBLOB
2786 /* If required, populate the overflow page-list cache. */
2787 if( pCur->aOverflow ){
2788 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
2789 pCur->aOverflow[iIdx] = nextPage;
2790 }
2791#endif
2792
danielk1977d04417962007-05-02 13:16:30 +00002793 if( offset>=ovflSize ){
2794 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00002795 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00002796 ** data is not required. So first try to lookup the overflow
2797 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00002798 ** function.
danielk1977d04417962007-05-02 13:16:30 +00002799 */
danielk19772dec9702007-05-02 16:48:37 +00002800#ifndef SQLITE_OMIT_INCRBLOB
danielk1977da107192007-05-04 08:32:13 +00002801 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
2802 nextPage = pCur->aOverflow[iIdx+1];
2803 } else
danielk19772dec9702007-05-02 16:48:37 +00002804#endif
danielk1977da107192007-05-04 08:32:13 +00002805 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
danielk1977da107192007-05-04 08:32:13 +00002806 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00002807 }else{
danielk19779f8d6402007-05-02 17:48:45 +00002808 /* Need to read this page properly. It contains some of the
2809 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00002810 */
2811 DbPage *pDbPage;
danielk1977cfe9a692004-06-16 12:00:29 +00002812 int a = amt;
danielk1977d04417962007-05-02 13:16:30 +00002813 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
danielk1977da107192007-05-04 08:32:13 +00002814 if( rc==SQLITE_OK ){
2815 aPayload = sqlite3PagerGetData(pDbPage);
2816 nextPage = get4byte(aPayload);
2817 if( a + offset > ovflSize ){
2818 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00002819 }
danielk1977da107192007-05-04 08:32:13 +00002820 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
2821 sqlite3PagerUnref(pDbPage);
2822 offset = 0;
2823 amt -= a;
2824 pBuf += a;
danielk19779f8d6402007-05-02 17:48:45 +00002825 }
danielk1977cfe9a692004-06-16 12:00:29 +00002826 }
drh2af926b2001-05-15 00:39:25 +00002827 }
drh2af926b2001-05-15 00:39:25 +00002828 }
danielk1977cfe9a692004-06-16 12:00:29 +00002829
danielk1977da107192007-05-04 08:32:13 +00002830 if( rc==SQLITE_OK && amt>0 ){
drh49285702005-09-17 15:20:26 +00002831 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00002832 }
danielk1977da107192007-05-04 08:32:13 +00002833 return rc;
drh2af926b2001-05-15 00:39:25 +00002834}
2835
drh72f82862001-05-24 21:06:34 +00002836/*
drh3aac2dd2004-04-26 14:10:20 +00002837** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00002838** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00002839** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00002840**
drh3aac2dd2004-04-26 14:10:20 +00002841** Return SQLITE_OK on success or an error code if anything goes
2842** wrong. An error is returned if "offset+amt" is larger than
2843** the available payload.
drh72f82862001-05-24 21:06:34 +00002844*/
drha34b6762004-05-07 13:30:42 +00002845int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhbf700f32007-03-31 02:36:44 +00002846 int rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00002847 if( rc==SQLITE_OK ){
2848 assert( pCur->eState==CURSOR_VALID );
2849 assert( pCur->pPage!=0 );
2850 if( pCur->pPage->intKey ){
2851 return SQLITE_CORRUPT_BKPT;
2852 }
2853 assert( pCur->pPage->intKey==0 );
2854 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh16a9b832007-05-05 18:39:25 +00002855 rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
drh6575a222005-03-10 17:06:34 +00002856 }
danielk1977da184232006-01-05 11:34:32 +00002857 return rc;
drh3aac2dd2004-04-26 14:10:20 +00002858}
2859
2860/*
drh3aac2dd2004-04-26 14:10:20 +00002861** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00002862** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00002863** begins at "offset".
2864**
2865** Return SQLITE_OK on success or an error code if anything goes
2866** wrong. An error is returned if "offset+amt" is larger than
2867** the available payload.
drh72f82862001-05-24 21:06:34 +00002868*/
drh3aac2dd2004-04-26 14:10:20 +00002869int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhbf700f32007-03-31 02:36:44 +00002870 int rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00002871 if( rc==SQLITE_OK ){
2872 assert( pCur->eState==CURSOR_VALID );
2873 assert( pCur->pPage!=0 );
2874 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh16a9b832007-05-05 18:39:25 +00002875 rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
danielk1977da184232006-01-05 11:34:32 +00002876 }
2877 return rc;
drh2af926b2001-05-15 00:39:25 +00002878}
2879
drh72f82862001-05-24 21:06:34 +00002880/*
drh0e1c19e2004-05-11 00:58:56 +00002881** Return a pointer to payload information from the entry that the
2882** pCur cursor is pointing to. The pointer is to the beginning of
2883** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00002884** skipKey==1. The number of bytes of available key/data is written
2885** into *pAmt. If *pAmt==0, then the value returned will not be
2886** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00002887**
2888** This routine is an optimization. It is common for the entire key
2889** and data to fit on the local page and for there to be no overflow
2890** pages. When that is so, this routine can be used to access the
2891** key and data without making a copy. If the key and/or data spills
drh16a9b832007-05-05 18:39:25 +00002892** onto overflow pages, then accessPayload() must be used to reassembly
drh0e1c19e2004-05-11 00:58:56 +00002893** the key/data and copy it into a preallocated buffer.
2894**
2895** The pointer returned by this routine looks directly into the cached
2896** page of the database. The data might change or move the next time
2897** any btree routine is called.
2898*/
2899static const unsigned char *fetchPayload(
2900 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00002901 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00002902 int skipKey /* read beginning at data if this is true */
2903){
2904 unsigned char *aPayload;
2905 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00002906 u32 nKey;
2907 int nLocal;
drh0e1c19e2004-05-11 00:58:56 +00002908
2909 assert( pCur!=0 && pCur->pPage!=0 );
danielk1977da184232006-01-05 11:34:32 +00002910 assert( pCur->eState==CURSOR_VALID );
drh0e1c19e2004-05-11 00:58:56 +00002911 pPage = pCur->pPage;
drh0e1c19e2004-05-11 00:58:56 +00002912 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
drh86057612007-06-26 01:04:48 +00002913 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00002914 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00002915 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00002916 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00002917 nKey = 0;
2918 }else{
2919 nKey = pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00002920 }
drh0e1c19e2004-05-11 00:58:56 +00002921 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00002922 aPayload += nKey;
2923 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00002924 }else{
drhfa1a98a2004-05-14 19:08:17 +00002925 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00002926 if( nLocal>nKey ){
2927 nLocal = nKey;
2928 }
drh0e1c19e2004-05-11 00:58:56 +00002929 }
drhe51c44f2004-05-30 20:46:09 +00002930 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00002931 return aPayload;
2932}
2933
2934
2935/*
drhe51c44f2004-05-30 20:46:09 +00002936** For the entry that cursor pCur is point to, return as
2937** many bytes of the key or data as are available on the local
2938** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00002939**
2940** The pointer returned is ephemeral. The key/data may move
2941** or be destroyed on the next call to any Btree routine.
2942**
2943** These routines is used to get quick access to key and data
2944** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00002945*/
drhe51c44f2004-05-30 20:46:09 +00002946const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
danielk1977da184232006-01-05 11:34:32 +00002947 if( pCur->eState==CURSOR_VALID ){
2948 return (const void*)fetchPayload(pCur, pAmt, 0);
2949 }
2950 return 0;
drh0e1c19e2004-05-11 00:58:56 +00002951}
drhe51c44f2004-05-30 20:46:09 +00002952const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
danielk1977da184232006-01-05 11:34:32 +00002953 if( pCur->eState==CURSOR_VALID ){
2954 return (const void*)fetchPayload(pCur, pAmt, 1);
2955 }
2956 return 0;
drh0e1c19e2004-05-11 00:58:56 +00002957}
2958
2959
2960/*
drh8178a752003-01-05 21:41:40 +00002961** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00002962** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00002963*/
drh3aac2dd2004-04-26 14:10:20 +00002964static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00002965 int rc;
2966 MemPage *pNewPage;
drh3aac2dd2004-04-26 14:10:20 +00002967 MemPage *pOldPage;
danielk1977aef0bf62005-12-30 16:28:01 +00002968 BtShared *pBt = pCur->pBtree->pBt;
drh72f82862001-05-24 21:06:34 +00002969
danielk1977da184232006-01-05 11:34:32 +00002970 assert( pCur->eState==CURSOR_VALID );
drhde647132004-05-07 17:57:49 +00002971 rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00002972 if( rc ) return rc;
drh428ae8c2003-01-04 16:48:09 +00002973 pNewPage->idxParent = pCur->idx;
drh3aac2dd2004-04-26 14:10:20 +00002974 pOldPage = pCur->pPage;
2975 pOldPage->idxShift = 0;
2976 releasePage(pOldPage);
drh72f82862001-05-24 21:06:34 +00002977 pCur->pPage = pNewPage;
2978 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00002979 pCur->info.nSize = 0;
drh4be295b2003-12-16 03:44:47 +00002980 if( pNewPage->nCell<1 ){
drh49285702005-09-17 15:20:26 +00002981 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00002982 }
drh72f82862001-05-24 21:06:34 +00002983 return SQLITE_OK;
2984}
2985
2986/*
drh8856d6a2004-04-29 14:42:46 +00002987** Return true if the page is the virtual root of its table.
2988**
2989** The virtual root page is the root page for most tables. But
2990** for the table rooted on page 1, sometime the real root page
2991** is empty except for the right-pointer. In such cases the
2992** virtual root page is the page that the right-pointer of page
2993** 1 is pointing to.
2994*/
drh16a9b832007-05-05 18:39:25 +00002995int sqlite3BtreeIsRootPage(MemPage *pPage){
drh8856d6a2004-04-29 14:42:46 +00002996 MemPage *pParent = pPage->pParent;
drhda200cc2004-05-09 11:51:38 +00002997 if( pParent==0 ) return 1;
2998 if( pParent->pgno>1 ) return 0;
2999 if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
drh8856d6a2004-04-29 14:42:46 +00003000 return 0;
3001}
3002
3003/*
drh5e2f8b92001-05-28 00:41:15 +00003004** Move the cursor up to the parent page.
3005**
3006** pCur->idx is set to the cell index that contains the pointer
3007** to the page we are coming from. If we are coming from the
3008** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00003009** the largest cell index.
drh72f82862001-05-24 21:06:34 +00003010*/
drh16a9b832007-05-05 18:39:25 +00003011void sqlite3BtreeMoveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00003012 MemPage *pParent;
drh8178a752003-01-05 21:41:40 +00003013 MemPage *pPage;
drh428ae8c2003-01-04 16:48:09 +00003014 int idxParent;
drh3aac2dd2004-04-26 14:10:20 +00003015
danielk1977da184232006-01-05 11:34:32 +00003016 assert( pCur->eState==CURSOR_VALID );
drh8178a752003-01-05 21:41:40 +00003017 pPage = pCur->pPage;
3018 assert( pPage!=0 );
drh16a9b832007-05-05 18:39:25 +00003019 assert( !sqlite3BtreeIsRootPage(pPage) );
drh8178a752003-01-05 21:41:40 +00003020 pParent = pPage->pParent;
3021 assert( pParent!=0 );
3022 idxParent = pPage->idxParent;
danielk19773b8a05f2007-03-19 17:44:26 +00003023 sqlite3PagerRef(pParent->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00003024 releasePage(pPage);
drh72f82862001-05-24 21:06:34 +00003025 pCur->pPage = pParent;
drh271efa52004-05-30 19:19:05 +00003026 pCur->info.nSize = 0;
drh428ae8c2003-01-04 16:48:09 +00003027 assert( pParent->idxShift==0 );
drh43605152004-05-29 21:46:49 +00003028 pCur->idx = idxParent;
drh72f82862001-05-24 21:06:34 +00003029}
3030
3031/*
3032** Move the cursor to the root page
3033*/
drh5e2f8b92001-05-28 00:41:15 +00003034static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00003035 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00003036 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00003037 BtShared *pBt = pCur->pBtree->pBt;
drhbd03cae2001-06-02 02:40:57 +00003038
drhbf700f32007-03-31 02:36:44 +00003039 if( pCur->eState==CURSOR_REQUIRESEEK ){
3040 clearCursorPosition(pCur);
3041 }
drh777e4c42006-01-13 04:31:58 +00003042 pRoot = pCur->pPage;
danielk197797a227c2006-01-20 16:32:04 +00003043 if( pRoot && pRoot->pgno==pCur->pgnoRoot ){
drh777e4c42006-01-13 04:31:58 +00003044 assert( pRoot->isInit );
3045 }else{
3046 if(
3047 SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0))
3048 ){
3049 pCur->eState = CURSOR_INVALID;
3050 return rc;
3051 }
3052 releasePage(pCur->pPage);
drh777e4c42006-01-13 04:31:58 +00003053 pCur->pPage = pRoot;
drhc39e0002004-05-07 23:50:57 +00003054 }
drh72f82862001-05-24 21:06:34 +00003055 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00003056 pCur->info.nSize = 0;
drh8856d6a2004-04-29 14:42:46 +00003057 if( pRoot->nCell==0 && !pRoot->leaf ){
3058 Pgno subpage;
3059 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00003060 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00003061 assert( subpage>0 );
danielk1977da184232006-01-05 11:34:32 +00003062 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00003063 rc = moveToChild(pCur, subpage);
drh8856d6a2004-04-29 14:42:46 +00003064 }
danielk1977da184232006-01-05 11:34:32 +00003065 pCur->eState = ((pCur->pPage->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
drh8856d6a2004-04-29 14:42:46 +00003066 return rc;
drh72f82862001-05-24 21:06:34 +00003067}
drh2af926b2001-05-15 00:39:25 +00003068
drh5e2f8b92001-05-28 00:41:15 +00003069/*
3070** Move the cursor down to the left-most leaf entry beneath the
3071** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00003072**
3073** The left-most leaf is the one with the smallest key - the first
3074** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00003075*/
3076static int moveToLeftmost(BtCursor *pCur){
3077 Pgno pgno;
3078 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003079 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00003080
danielk1977da184232006-01-05 11:34:32 +00003081 assert( pCur->eState==CURSOR_VALID );
drh3aac2dd2004-04-26 14:10:20 +00003082 while( !(pPage = pCur->pPage)->leaf ){
drha34b6762004-05-07 13:30:42 +00003083 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
danielk19771cc5ed82007-05-16 17:28:43 +00003084 pgno = get4byte(findCell(pPage, pCur->idx));
drh8178a752003-01-05 21:41:40 +00003085 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00003086 if( rc ) return rc;
3087 }
3088 return SQLITE_OK;
3089}
3090
drh2dcc9aa2002-12-04 13:40:25 +00003091/*
3092** Move the cursor down to the right-most leaf entry beneath the
3093** page to which it is currently pointing. Notice the difference
3094** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
3095** finds the left-most entry beneath the *entry* whereas moveToRightmost()
3096** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00003097**
3098** The right-most entry is the one with the largest key - the last
3099** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00003100*/
3101static int moveToRightmost(BtCursor *pCur){
3102 Pgno pgno;
3103 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003104 MemPage *pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003105
danielk1977da184232006-01-05 11:34:32 +00003106 assert( pCur->eState==CURSOR_VALID );
drh3aac2dd2004-04-26 14:10:20 +00003107 while( !(pPage = pCur->pPage)->leaf ){
drh43605152004-05-29 21:46:49 +00003108 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh3aac2dd2004-04-26 14:10:20 +00003109 pCur->idx = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00003110 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003111 if( rc ) return rc;
3112 }
drh3aac2dd2004-04-26 14:10:20 +00003113 pCur->idx = pPage->nCell - 1;
drh271efa52004-05-30 19:19:05 +00003114 pCur->info.nSize = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003115 return SQLITE_OK;
3116}
3117
drh5e00f6c2001-09-13 13:46:56 +00003118/* Move the cursor to the first entry in the table. Return SQLITE_OK
3119** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003120** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00003121*/
drh3aac2dd2004-04-26 14:10:20 +00003122int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00003123 int rc;
3124 rc = moveToRoot(pCur);
3125 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00003126 if( pCur->eState==CURSOR_INVALID ){
drhc39e0002004-05-07 23:50:57 +00003127 assert( pCur->pPage->nCell==0 );
drh5e00f6c2001-09-13 13:46:56 +00003128 *pRes = 1;
3129 return SQLITE_OK;
3130 }
drhc39e0002004-05-07 23:50:57 +00003131 assert( pCur->pPage->nCell>0 );
drh5e00f6c2001-09-13 13:46:56 +00003132 *pRes = 0;
3133 rc = moveToLeftmost(pCur);
3134 return rc;
3135}
drh5e2f8b92001-05-28 00:41:15 +00003136
drh9562b552002-02-19 15:00:07 +00003137/* Move the cursor to the last entry in the table. Return SQLITE_OK
3138** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003139** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00003140*/
drh3aac2dd2004-04-26 14:10:20 +00003141int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00003142 int rc;
drh9562b552002-02-19 15:00:07 +00003143 rc = moveToRoot(pCur);
3144 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00003145 if( CURSOR_INVALID==pCur->eState ){
drhc39e0002004-05-07 23:50:57 +00003146 assert( pCur->pPage->nCell==0 );
drh9562b552002-02-19 15:00:07 +00003147 *pRes = 1;
3148 return SQLITE_OK;
3149 }
danielk1977da184232006-01-05 11:34:32 +00003150 assert( pCur->eState==CURSOR_VALID );
drh9562b552002-02-19 15:00:07 +00003151 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003152 rc = moveToRightmost(pCur);
drh9562b552002-02-19 15:00:07 +00003153 return rc;
3154}
3155
drh3aac2dd2004-04-26 14:10:20 +00003156/* Move the cursor so that it points to an entry near pKey/nKey.
drh72f82862001-05-24 21:06:34 +00003157** Return a success code.
3158**
drh3aac2dd2004-04-26 14:10:20 +00003159** For INTKEY tables, only the nKey parameter is used. pKey is
3160** ignored. For other tables, nKey is the number of bytes of data
drh0b2f3162005-12-21 18:36:45 +00003161** in pKey. The comparison function specified when the cursor was
drh3aac2dd2004-04-26 14:10:20 +00003162** created is used to compare keys.
3163**
drh5e2f8b92001-05-28 00:41:15 +00003164** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00003165** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00003166** were present. The cursor might point to an entry that comes
3167** before or after the key.
3168**
drhbd03cae2001-06-02 02:40:57 +00003169** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00003170** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00003171** this value is as follows:
3172**
3173** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00003174** is smaller than pKey or if the table is empty
3175** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00003176**
3177** *pRes==0 The cursor is left pointing at an entry that
3178** exactly matches pKey.
3179**
3180** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00003181** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00003182*/
drhe4d90812007-03-29 05:51:49 +00003183int sqlite3BtreeMoveto(
3184 BtCursor *pCur, /* The cursor to be moved */
3185 const void *pKey, /* The key content for indices. Not used by tables */
3186 i64 nKey, /* Size of pKey. Or the key for tables */
3187 int biasRight, /* If true, bias the search to the high end */
3188 int *pRes /* Search result flag */
3189){
drh72f82862001-05-24 21:06:34 +00003190 int rc;
drh5e2f8b92001-05-28 00:41:15 +00003191 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00003192 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00003193 assert( pCur->pPage );
3194 assert( pCur->pPage->isInit );
danielk1977da184232006-01-05 11:34:32 +00003195 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00003196 *pRes = -1;
drhc39e0002004-05-07 23:50:57 +00003197 assert( pCur->pPage->nCell==0 );
3198 return SQLITE_OK;
3199 }
drh14684382006-11-30 13:05:29 +00003200 for(;;){
drh72f82862001-05-24 21:06:34 +00003201 int lwr, upr;
3202 Pgno chldPg;
3203 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00003204 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00003205 lwr = 0;
3206 upr = pPage->nCell-1;
drh4eec4c12005-01-21 00:22:37 +00003207 if( !pPage->intKey && pKey==0 ){
drh49285702005-09-17 15:20:26 +00003208 return SQLITE_CORRUPT_BKPT;
drh4eec4c12005-01-21 00:22:37 +00003209 }
drhe4d90812007-03-29 05:51:49 +00003210 if( biasRight ){
3211 pCur->idx = upr;
3212 }else{
3213 pCur->idx = (upr+lwr)/2;
3214 }
drhf1d68b32007-03-29 04:43:26 +00003215 if( lwr<=upr ) for(;;){
danielk197713adf8a2004-06-03 16:08:41 +00003216 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00003217 i64 nCellKey;
drh366fda62006-01-13 02:35:09 +00003218 pCur->info.nSize = 0;
drh3aac2dd2004-04-26 14:10:20 +00003219 if( pPage->intKey ){
drh777e4c42006-01-13 04:31:58 +00003220 u8 *pCell;
danielk19771cc5ed82007-05-16 17:28:43 +00003221 pCell = findCell(pPage, pCur->idx) + pPage->childPtrSize;
drhd172f862006-01-12 15:01:15 +00003222 if( pPage->hasData ){
danielk1977bab45c62006-01-16 15:14:27 +00003223 u32 dummy;
drhd172f862006-01-12 15:01:15 +00003224 pCell += getVarint32(pCell, &dummy);
3225 }
danielk1977bab45c62006-01-16 15:14:27 +00003226 getVarint(pCell, (u64 *)&nCellKey);
drh3aac2dd2004-04-26 14:10:20 +00003227 if( nCellKey<nKey ){
3228 c = -1;
3229 }else if( nCellKey>nKey ){
3230 c = +1;
3231 }else{
3232 c = 0;
3233 }
drh3aac2dd2004-04-26 14:10:20 +00003234 }else{
drhe51c44f2004-05-30 20:46:09 +00003235 int available;
danielk197713adf8a2004-06-03 16:08:41 +00003236 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drh366fda62006-01-13 02:35:09 +00003237 nCellKey = pCur->info.nKey;
drhe51c44f2004-05-30 20:46:09 +00003238 if( available>=nCellKey ){
3239 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
3240 }else{
3241 pCellKey = sqliteMallocRaw( nCellKey );
3242 if( pCellKey==0 ) return SQLITE_NOMEM;
danielk197713adf8a2004-06-03 16:08:41 +00003243 rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
drhe51c44f2004-05-30 20:46:09 +00003244 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
3245 sqliteFree(pCellKey);
3246 if( rc ) return rc;
3247 }
drh3aac2dd2004-04-26 14:10:20 +00003248 }
drh72f82862001-05-24 21:06:34 +00003249 if( c==0 ){
drh8b18dd42004-05-12 19:18:15 +00003250 if( pPage->leafData && !pPage->leaf ){
drhfc70e6f2004-05-12 21:11:27 +00003251 lwr = pCur->idx;
3252 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00003253 break;
3254 }else{
drh8b18dd42004-05-12 19:18:15 +00003255 if( pRes ) *pRes = 0;
3256 return SQLITE_OK;
3257 }
drh72f82862001-05-24 21:06:34 +00003258 }
3259 if( c<0 ){
3260 lwr = pCur->idx+1;
3261 }else{
3262 upr = pCur->idx-1;
3263 }
drhf1d68b32007-03-29 04:43:26 +00003264 if( lwr>upr ){
3265 break;
3266 }
3267 pCur->idx = (lwr+upr)/2;
drh72f82862001-05-24 21:06:34 +00003268 }
3269 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00003270 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00003271 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00003272 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00003273 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00003274 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00003275 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00003276 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00003277 }
3278 if( chldPg==0 ){
drhc39e0002004-05-07 23:50:57 +00003279 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00003280 if( pRes ) *pRes = c;
3281 return SQLITE_OK;
3282 }
drh428ae8c2003-01-04 16:48:09 +00003283 pCur->idx = lwr;
drh271efa52004-05-30 19:19:05 +00003284 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00003285 rc = moveToChild(pCur, chldPg);
drhc39e0002004-05-07 23:50:57 +00003286 if( rc ){
3287 return rc;
3288 }
drh72f82862001-05-24 21:06:34 +00003289 }
drhbd03cae2001-06-02 02:40:57 +00003290 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00003291}
3292
3293/*
drhc39e0002004-05-07 23:50:57 +00003294** Return TRUE if the cursor is not pointing at an entry of the table.
3295**
3296** TRUE will be returned after a call to sqlite3BtreeNext() moves
3297** past the last entry in the table or sqlite3BtreePrev() moves past
3298** the first entry. TRUE is also returned if the table is empty.
3299*/
3300int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00003301 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
3302 ** have been deleted? This API will need to change to return an error code
3303 ** as well as the boolean result value.
3304 */
3305 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00003306}
3307
3308/*
drhbd03cae2001-06-02 02:40:57 +00003309** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00003310** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00003311** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00003312** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00003313*/
drh3aac2dd2004-04-26 14:10:20 +00003314int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00003315 int rc;
danielk197797a227c2006-01-20 16:32:04 +00003316 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00003317
drhbf700f32007-03-31 02:36:44 +00003318 rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003319 if( rc!=SQLITE_OK ){
3320 return rc;
3321 }
drh8c4d3a62007-04-06 01:03:32 +00003322 assert( pRes!=0 );
3323 pPage = pCur->pPage;
3324 if( CURSOR_INVALID==pCur->eState ){
3325 *pRes = 1;
3326 return SQLITE_OK;
3327 }
danielk1977da184232006-01-05 11:34:32 +00003328 if( pCur->skip>0 ){
3329 pCur->skip = 0;
3330 *pRes = 0;
3331 return SQLITE_OK;
3332 }
3333 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00003334
drh8178a752003-01-05 21:41:40 +00003335 assert( pPage->isInit );
drh8178a752003-01-05 21:41:40 +00003336 assert( pCur->idx<pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00003337
drh72f82862001-05-24 21:06:34 +00003338 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00003339 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00003340 if( pCur->idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00003341 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003342 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00003343 if( rc ) return rc;
3344 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003345 *pRes = 0;
3346 return rc;
drh72f82862001-05-24 21:06:34 +00003347 }
drh5e2f8b92001-05-28 00:41:15 +00003348 do{
drh16a9b832007-05-05 18:39:25 +00003349 if( sqlite3BtreeIsRootPage(pPage) ){
drh8c1238a2003-01-02 14:43:55 +00003350 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00003351 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00003352 return SQLITE_OK;
3353 }
drh16a9b832007-05-05 18:39:25 +00003354 sqlite3BtreeMoveToParent(pCur);
drh8178a752003-01-05 21:41:40 +00003355 pPage = pCur->pPage;
3356 }while( pCur->idx>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00003357 *pRes = 0;
drh8b18dd42004-05-12 19:18:15 +00003358 if( pPage->leafData ){
3359 rc = sqlite3BtreeNext(pCur, pRes);
3360 }else{
3361 rc = SQLITE_OK;
3362 }
3363 return rc;
drh8178a752003-01-05 21:41:40 +00003364 }
3365 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00003366 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00003367 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00003368 }
drh5e2f8b92001-05-28 00:41:15 +00003369 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003370 return rc;
drh72f82862001-05-24 21:06:34 +00003371}
3372
drh3b7511c2001-05-26 13:15:44 +00003373/*
drh2dcc9aa2002-12-04 13:40:25 +00003374** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00003375** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00003376** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00003377** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00003378*/
drh3aac2dd2004-04-26 14:10:20 +00003379int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00003380 int rc;
3381 Pgno pgno;
drh8178a752003-01-05 21:41:40 +00003382 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00003383
drhbf700f32007-03-31 02:36:44 +00003384 rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003385 if( rc!=SQLITE_OK ){
3386 return rc;
3387 }
drh8c4d3a62007-04-06 01:03:32 +00003388 if( CURSOR_INVALID==pCur->eState ){
3389 *pRes = 1;
3390 return SQLITE_OK;
3391 }
danielk1977da184232006-01-05 11:34:32 +00003392 if( pCur->skip<0 ){
3393 pCur->skip = 0;
3394 *pRes = 0;
3395 return SQLITE_OK;
3396 }
3397 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00003398
drh8178a752003-01-05 21:41:40 +00003399 pPage = pCur->pPage;
drh8178a752003-01-05 21:41:40 +00003400 assert( pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00003401 assert( pCur->idx>=0 );
drha34b6762004-05-07 13:30:42 +00003402 if( !pPage->leaf ){
danielk19771cc5ed82007-05-16 17:28:43 +00003403 pgno = get4byte( findCell(pPage, pCur->idx) );
drh8178a752003-01-05 21:41:40 +00003404 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003405 if( rc ) return rc;
3406 rc = moveToRightmost(pCur);
3407 }else{
3408 while( pCur->idx==0 ){
drh16a9b832007-05-05 18:39:25 +00003409 if( sqlite3BtreeIsRootPage(pPage) ){
danielk1977da184232006-01-05 11:34:32 +00003410 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00003411 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00003412 return SQLITE_OK;
3413 }
drh16a9b832007-05-05 18:39:25 +00003414 sqlite3BtreeMoveToParent(pCur);
drh8178a752003-01-05 21:41:40 +00003415 pPage = pCur->pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003416 }
3417 pCur->idx--;
drh271efa52004-05-30 19:19:05 +00003418 pCur->info.nSize = 0;
drh8237d452004-11-22 19:07:09 +00003419 if( pPage->leafData && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00003420 rc = sqlite3BtreePrevious(pCur, pRes);
3421 }else{
3422 rc = SQLITE_OK;
3423 }
drh2dcc9aa2002-12-04 13:40:25 +00003424 }
drh8178a752003-01-05 21:41:40 +00003425 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003426 return rc;
3427}
3428
3429/*
drh3b7511c2001-05-26 13:15:44 +00003430** Allocate a new page from the database file.
3431**
danielk19773b8a05f2007-03-19 17:44:26 +00003432** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00003433** has already been called on the new page.) The new page has also
3434** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00003435** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00003436**
3437** SQLITE_OK is returned on success. Any other return value indicates
3438** an error. *ppPage and *pPgno are undefined in the event of an error.
danielk19773b8a05f2007-03-19 17:44:26 +00003439** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00003440**
drh199e3cf2002-07-18 11:01:47 +00003441** If the "nearby" parameter is not 0, then a (feeble) effort is made to
3442** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00003443** attempt to keep related pages close to each other in the database file,
3444** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00003445**
3446** If the "exact" parameter is not 0, and the page-number nearby exists
3447** anywhere on the free-list, then it is guarenteed to be returned. This
3448** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00003449*/
drh4f0c5872007-03-26 22:05:01 +00003450static int allocateBtreePage(
danielk1977aef0bf62005-12-30 16:28:01 +00003451 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00003452 MemPage **ppPage,
3453 Pgno *pPgno,
3454 Pgno nearby,
3455 u8 exact
3456){
drh3aac2dd2004-04-26 14:10:20 +00003457 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00003458 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003459 int n; /* Number of pages on the freelist */
3460 int k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00003461 MemPage *pTrunk = 0;
3462 MemPage *pPrevTrunk = 0;
drh30e58752002-03-02 20:41:57 +00003463
drh3aac2dd2004-04-26 14:10:20 +00003464 pPage1 = pBt->pPage1;
3465 n = get4byte(&pPage1->aData[36]);
3466 if( n>0 ){
drh91025292004-05-03 19:49:32 +00003467 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00003468 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003469 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
3470
3471 /* If the 'exact' parameter was true and a query of the pointer-map
3472 ** shows that the page 'nearby' is somewhere on the free-list, then
3473 ** the entire-list will be searched for that page.
3474 */
3475#ifndef SQLITE_OMIT_AUTOVACUUM
danielk19774ef24492007-05-23 09:52:41 +00003476 if( exact && nearby<=sqlite3PagerPagecount(pBt->pPager) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00003477 u8 eType;
3478 assert( nearby>0 );
3479 assert( pBt->autoVacuum );
3480 rc = ptrmapGet(pBt, nearby, &eType, 0);
3481 if( rc ) return rc;
3482 if( eType==PTRMAP_FREEPAGE ){
3483 searchList = 1;
3484 }
3485 *pPgno = nearby;
3486 }
3487#endif
3488
3489 /* Decrement the free-list count by 1. Set iTrunk to the index of the
3490 ** first free-list trunk page. iPrevTrunk is initially 1.
3491 */
danielk19773b8a05f2007-03-19 17:44:26 +00003492 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00003493 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003494 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003495
3496 /* The code within this loop is run only once if the 'searchList' variable
3497 ** is not true. Otherwise, it runs once for each trunk-page on the
3498 ** free-list until the page 'nearby' is located.
3499 */
3500 do {
3501 pPrevTrunk = pTrunk;
3502 if( pPrevTrunk ){
3503 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00003504 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00003505 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00003506 }
drh16a9b832007-05-05 18:39:25 +00003507 rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003508 if( rc ){
drhd3627af2006-12-18 18:34:51 +00003509 pTrunk = 0;
3510 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003511 }
3512
3513 k = get4byte(&pTrunk->aData[4]);
3514 if( k==0 && !searchList ){
3515 /* The trunk has no leaves and the list is not being searched.
3516 ** So extract the trunk page itself and use it as the newly
3517 ** allocated page */
3518 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00003519 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00003520 if( rc ){
3521 goto end_allocate_page;
3522 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003523 *pPgno = iTrunk;
3524 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3525 *ppPage = pTrunk;
3526 pTrunk = 0;
3527 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3528 }else if( k>pBt->usableSize/4 - 8 ){
3529 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00003530 rc = SQLITE_CORRUPT_BKPT;
3531 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003532#ifndef SQLITE_OMIT_AUTOVACUUM
3533 }else if( searchList && nearby==iTrunk ){
3534 /* The list is being searched and this trunk page is the page
3535 ** to allocate, regardless of whether it has leaves.
3536 */
3537 assert( *pPgno==iTrunk );
3538 *ppPage = pTrunk;
3539 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00003540 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00003541 if( rc ){
3542 goto end_allocate_page;
3543 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003544 if( k==0 ){
3545 if( !pPrevTrunk ){
3546 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3547 }else{
3548 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
3549 }
3550 }else{
3551 /* The trunk page is required by the caller but it contains
3552 ** pointers to free-list leaves. The first leaf becomes a trunk
3553 ** page in this case.
3554 */
3555 MemPage *pNewTrunk;
3556 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh16a9b832007-05-05 18:39:25 +00003557 rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003558 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00003559 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003560 }
danielk19773b8a05f2007-03-19 17:44:26 +00003561 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003562 if( rc!=SQLITE_OK ){
3563 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00003564 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003565 }
3566 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
3567 put4byte(&pNewTrunk->aData[4], k-1);
3568 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00003569 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003570 if( !pPrevTrunk ){
3571 put4byte(&pPage1->aData[32], iNewTrunk);
3572 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00003573 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00003574 if( rc ){
3575 goto end_allocate_page;
3576 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003577 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
3578 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003579 }
3580 pTrunk = 0;
3581 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3582#endif
3583 }else{
3584 /* Extract a leaf from the trunk */
3585 int closest;
3586 Pgno iPage;
3587 unsigned char *aData = pTrunk->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00003588 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00003589 if( rc ){
3590 goto end_allocate_page;
3591 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003592 if( nearby>0 ){
3593 int i, dist;
3594 closest = 0;
3595 dist = get4byte(&aData[8]) - nearby;
3596 if( dist<0 ) dist = -dist;
3597 for(i=1; i<k; i++){
3598 int d2 = get4byte(&aData[8+i*4]) - nearby;
3599 if( d2<0 ) d2 = -d2;
3600 if( d2<dist ){
3601 closest = i;
3602 dist = d2;
3603 }
3604 }
3605 }else{
3606 closest = 0;
3607 }
3608
3609 iPage = get4byte(&aData[8+closest*4]);
3610 if( !searchList || iPage==nearby ){
3611 *pPgno = iPage;
danielk19773b8a05f2007-03-19 17:44:26 +00003612 if( *pPgno>sqlite3PagerPagecount(pBt->pPager) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00003613 /* Free page off the end of the file */
drh49285702005-09-17 15:20:26 +00003614 return SQLITE_CORRUPT_BKPT;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003615 }
3616 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
3617 ": %d more free pages\n",
3618 *pPgno, closest+1, k, pTrunk->pgno, n-1));
3619 if( closest<k-1 ){
3620 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
3621 }
3622 put4byte(&aData[4], k-1);
drh16a9b832007-05-05 18:39:25 +00003623 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003624 if( rc==SQLITE_OK ){
drh538f5702007-04-13 02:14:30 +00003625 sqlite3PagerDontRollback((*ppPage)->pDbPage);
danielk19773b8a05f2007-03-19 17:44:26 +00003626 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00003627 if( rc!=SQLITE_OK ){
3628 releasePage(*ppPage);
3629 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003630 }
3631 searchList = 0;
3632 }
drhee696e22004-08-30 16:52:17 +00003633 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003634 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00003635 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003636 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00003637 }else{
drh3aac2dd2004-04-26 14:10:20 +00003638 /* There are no pages on the freelist, so create a new page at the
3639 ** end of the file */
danielk19773b8a05f2007-03-19 17:44:26 +00003640 *pPgno = sqlite3PagerPagecount(pBt->pPager) + 1;
danielk1977afcdd022004-10-31 16:25:42 +00003641
3642#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00003643 if( pBt->nTrunc ){
3644 /* An incr-vacuum has already run within this transaction. So the
3645 ** page to allocate is not from the physical end of the file, but
3646 ** at pBt->nTrunc.
3647 */
3648 *pPgno = pBt->nTrunc+1;
3649 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
3650 (*pPgno)++;
3651 }
3652 }
danielk1977266664d2006-02-10 08:24:21 +00003653 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00003654 /* If *pPgno refers to a pointer-map page, allocate two new pages
3655 ** at the end of the file instead of one. The first allocated page
3656 ** becomes a new pointer-map page, the second is used by the caller.
3657 */
3658 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00003659 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977afcdd022004-10-31 16:25:42 +00003660 (*pPgno)++;
3661 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003662 if( pBt->nTrunc ){
3663 pBt->nTrunc = *pPgno;
3664 }
danielk1977afcdd022004-10-31 16:25:42 +00003665#endif
3666
danielk1977599fcba2004-11-08 07:13:13 +00003667 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh16a9b832007-05-05 18:39:25 +00003668 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
drh3b7511c2001-05-26 13:15:44 +00003669 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00003670 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00003671 if( rc!=SQLITE_OK ){
3672 releasePage(*ppPage);
3673 }
drh3a4c1412004-05-09 20:40:11 +00003674 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00003675 }
danielk1977599fcba2004-11-08 07:13:13 +00003676
3677 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00003678
3679end_allocate_page:
3680 releasePage(pTrunk);
3681 releasePage(pPrevTrunk);
drh3b7511c2001-05-26 13:15:44 +00003682 return rc;
3683}
3684
3685/*
drh3aac2dd2004-04-26 14:10:20 +00003686** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00003687**
danielk19773b8a05f2007-03-19 17:44:26 +00003688** sqlite3PagerUnref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00003689*/
drh3aac2dd2004-04-26 14:10:20 +00003690static int freePage(MemPage *pPage){
danielk1977aef0bf62005-12-30 16:28:01 +00003691 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00003692 MemPage *pPage1 = pBt->pPage1;
3693 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00003694
drh3aac2dd2004-04-26 14:10:20 +00003695 /* Prepare the page for freeing */
3696 assert( pPage->pgno>1 );
3697 pPage->isInit = 0;
3698 releasePage(pPage->pParent);
3699 pPage->pParent = 0;
3700
drha34b6762004-05-07 13:30:42 +00003701 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00003702 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00003703 if( rc ) return rc;
3704 n = get4byte(&pPage1->aData[36]);
3705 put4byte(&pPage1->aData[36], n+1);
3706
drhfcce93f2006-02-22 03:08:32 +00003707#ifdef SQLITE_SECURE_DELETE
3708 /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
3709 ** always fully overwrite deleted information with zeros.
3710 */
danielk19773b8a05f2007-03-19 17:44:26 +00003711 rc = sqlite3PagerWrite(pPage->pDbPage);
drhfcce93f2006-02-22 03:08:32 +00003712 if( rc ) return rc;
3713 memset(pPage->aData, 0, pPage->pBt->pageSize);
3714#endif
3715
danielk1977687566d2004-11-02 12:56:41 +00003716#ifndef SQLITE_OMIT_AUTOVACUUM
3717 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00003718 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00003719 */
3720 if( pBt->autoVacuum ){
3721 rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
danielk1977a64a0352004-11-05 01:45:13 +00003722 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00003723 }
3724#endif
3725
drh3aac2dd2004-04-26 14:10:20 +00003726 if( n==0 ){
3727 /* This is the first free page */
danielk19773b8a05f2007-03-19 17:44:26 +00003728 rc = sqlite3PagerWrite(pPage->pDbPage);
drhda200cc2004-05-09 11:51:38 +00003729 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003730 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00003731 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003732 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003733 }else{
3734 /* Other free pages already exist. Retrive the first trunk page
3735 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00003736 MemPage *pTrunk;
drh16a9b832007-05-05 18:39:25 +00003737 rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0);
drh3b7511c2001-05-26 13:15:44 +00003738 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003739 k = get4byte(&pTrunk->aData[4]);
drhee696e22004-08-30 16:52:17 +00003740 if( k>=pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00003741 /* The trunk is full. Turn the page being freed into a new
3742 ** trunk page with no leaves. */
danielk19773b8a05f2007-03-19 17:44:26 +00003743 rc = sqlite3PagerWrite(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00003744 if( rc ) return rc;
3745 put4byte(pPage->aData, pTrunk->pgno);
3746 put4byte(&pPage->aData[4], 0);
3747 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003748 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
3749 pPage->pgno, pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003750 }else{
3751 /* Add the newly freed page as a leaf on the current trunk */
danielk19773b8a05f2007-03-19 17:44:26 +00003752 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00003753 if( rc==SQLITE_OK ){
3754 put4byte(&pTrunk->aData[4], k+1);
3755 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drhfcce93f2006-02-22 03:08:32 +00003756#ifndef SQLITE_SECURE_DELETE
drh538f5702007-04-13 02:14:30 +00003757 sqlite3PagerDontWrite(pPage->pDbPage);
drhfcce93f2006-02-22 03:08:32 +00003758#endif
drhf5345442007-04-09 12:45:02 +00003759 }
drh3a4c1412004-05-09 20:40:11 +00003760 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003761 }
3762 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003763 }
drh3b7511c2001-05-26 13:15:44 +00003764 return rc;
3765}
3766
3767/*
drh3aac2dd2004-04-26 14:10:20 +00003768** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00003769*/
drh3aac2dd2004-04-26 14:10:20 +00003770static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00003771 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00003772 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00003773 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00003774 int rc;
drh94440812007-03-06 11:42:19 +00003775 int nOvfl;
3776 int ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00003777
drh16a9b832007-05-05 18:39:25 +00003778 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003779 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00003780 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00003781 }
drh6f11bef2004-05-13 01:12:56 +00003782 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh94440812007-03-06 11:42:19 +00003783 ovflPageSize = pBt->usableSize - 4;
drh72365832007-03-06 15:53:44 +00003784 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
3785 assert( ovflPgno==0 || nOvfl>0 );
3786 while( nOvfl-- ){
drh3aac2dd2004-04-26 14:10:20 +00003787 MemPage *pOvfl;
danielk19773b8a05f2007-03-19 17:44:26 +00003788 if( ovflPgno==0 || ovflPgno>sqlite3PagerPagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00003789 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00003790 }
danielk19778c0a9592007-04-30 16:55:00 +00003791
3792 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno);
drh3b7511c2001-05-26 13:15:44 +00003793 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003794 rc = freePage(pOvfl);
danielk19773b8a05f2007-03-19 17:44:26 +00003795 sqlite3PagerUnref(pOvfl->pDbPage);
danielk19776b456a22005-03-21 04:04:02 +00003796 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00003797 }
drh5e2f8b92001-05-28 00:41:15 +00003798 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00003799}
3800
3801/*
drh91025292004-05-03 19:49:32 +00003802** Create the byte sequence used to represent a cell on page pPage
3803** and write that byte sequence into pCell[]. Overflow pages are
3804** allocated and filled in as necessary. The calling procedure
3805** is responsible for making sure sufficient space has been allocated
3806** for pCell[].
3807**
3808** Note that pCell does not necessary need to point to the pPage->aData
3809** area. pCell might point to some temporary storage. The cell will
3810** be constructed in this temporary area then copied into pPage->aData
3811** later.
drh3b7511c2001-05-26 13:15:44 +00003812*/
3813static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00003814 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00003815 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00003816 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00003817 const void *pData,int nData, /* The data */
drhb026e052007-05-02 01:34:31 +00003818 int nZero, /* Extra zero bytes to append to pData */
drh4b70f112004-05-02 21:12:19 +00003819 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00003820){
drh3b7511c2001-05-26 13:15:44 +00003821 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00003822 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00003823 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00003824 int spaceLeft;
3825 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00003826 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00003827 unsigned char *pPrior;
3828 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00003829 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00003830 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00003831 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00003832 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00003833
drh91025292004-05-03 19:49:32 +00003834 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00003835 nHeader = 0;
drh91025292004-05-03 19:49:32 +00003836 if( !pPage->leaf ){
3837 nHeader += 4;
3838 }
drh8b18dd42004-05-12 19:18:15 +00003839 if( pPage->hasData ){
drhb026e052007-05-02 01:34:31 +00003840 nHeader += putVarint(&pCell[nHeader], nData+nZero);
drh6f11bef2004-05-13 01:12:56 +00003841 }else{
drhb026e052007-05-02 01:34:31 +00003842 nData = nZero = 0;
drh91025292004-05-03 19:49:32 +00003843 }
drh6f11bef2004-05-13 01:12:56 +00003844 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh16a9b832007-05-05 18:39:25 +00003845 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003846 assert( info.nHeader==nHeader );
3847 assert( info.nKey==nKey );
drhb026e052007-05-02 01:34:31 +00003848 assert( info.nData==nData+nZero );
drh6f11bef2004-05-13 01:12:56 +00003849
3850 /* Fill in the payload */
drhb026e052007-05-02 01:34:31 +00003851 nPayload = nData + nZero;
drh3aac2dd2004-04-26 14:10:20 +00003852 if( pPage->intKey ){
3853 pSrc = pData;
3854 nSrc = nData;
drh91025292004-05-03 19:49:32 +00003855 nData = 0;
drh3aac2dd2004-04-26 14:10:20 +00003856 }else{
3857 nPayload += nKey;
3858 pSrc = pKey;
3859 nSrc = nKey;
3860 }
drh6f11bef2004-05-13 01:12:56 +00003861 *pnSize = info.nSize;
3862 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00003863 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00003864 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00003865
drh3b7511c2001-05-26 13:15:44 +00003866 while( nPayload>0 ){
3867 if( spaceLeft==0 ){
danielk1977b39f70b2007-05-17 18:28:11 +00003868 int isExact = 0;
danielk1977afcdd022004-10-31 16:25:42 +00003869#ifndef SQLITE_OMIT_AUTOVACUUM
3870 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00003871 if( pBt->autoVacuum ){
3872 do{
3873 pgnoOvfl++;
3874 } while(
3875 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
3876 );
danielk197789a4be82007-05-23 13:34:32 +00003877 if( pgnoOvfl>1 ){
danielk1977b39f70b2007-05-17 18:28:11 +00003878 /* isExact = 1; */
3879 }
3880 }
danielk1977afcdd022004-10-31 16:25:42 +00003881#endif
danielk1977b39f70b2007-05-17 18:28:11 +00003882 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, isExact);
danielk1977afcdd022004-10-31 16:25:42 +00003883#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00003884 /* If the database supports auto-vacuum, and the second or subsequent
3885 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00003886 ** for that page now.
3887 **
3888 ** If this is the first overflow page, then write a partial entry
3889 ** to the pointer-map. If we write nothing to this pointer-map slot,
3890 ** then the optimistic overflow chain processing in clearCell()
3891 ** may misinterpret the uninitialised values and delete the
3892 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00003893 */
danielk19774ef24492007-05-23 09:52:41 +00003894 if( pBt->autoVacuum && rc==SQLITE_OK ){
3895 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
3896 rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
danielk197789a4be82007-05-23 13:34:32 +00003897 if( rc ){
3898 releasePage(pOvfl);
3899 }
danielk1977afcdd022004-10-31 16:25:42 +00003900 }
3901#endif
drh3b7511c2001-05-26 13:15:44 +00003902 if( rc ){
drh9b171272004-05-08 02:03:22 +00003903 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00003904 return rc;
3905 }
drh3aac2dd2004-04-26 14:10:20 +00003906 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00003907 releasePage(pToRelease);
3908 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00003909 pPrior = pOvfl->aData;
3910 put4byte(pPrior, 0);
3911 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00003912 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00003913 }
3914 n = nPayload;
3915 if( n>spaceLeft ) n = spaceLeft;
drhb026e052007-05-02 01:34:31 +00003916 if( nSrc>0 ){
3917 if( n>nSrc ) n = nSrc;
3918 assert( pSrc );
3919 memcpy(pPayload, pSrc, n);
3920 }else{
3921 memset(pPayload, 0, n);
3922 }
drh3b7511c2001-05-26 13:15:44 +00003923 nPayload -= n;
drhde647132004-05-07 17:57:49 +00003924 pPayload += n;
drh9b171272004-05-08 02:03:22 +00003925 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00003926 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00003927 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00003928 if( nSrc==0 ){
3929 nSrc = nData;
3930 pSrc = pData;
3931 }
drhdd793422001-06-28 01:54:48 +00003932 }
drh9b171272004-05-08 02:03:22 +00003933 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00003934 return SQLITE_OK;
3935}
3936
3937/*
drhbd03cae2001-06-02 02:40:57 +00003938** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00003939** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00003940** pointer in the third argument.
3941*/
danielk1977aef0bf62005-12-30 16:28:01 +00003942static int reparentPage(BtShared *pBt, Pgno pgno, MemPage *pNewParent, int idx){
drhbd03cae2001-06-02 02:40:57 +00003943 MemPage *pThis;
danielk19773b8a05f2007-03-19 17:44:26 +00003944 DbPage *pDbPage;
drhbd03cae2001-06-02 02:40:57 +00003945
drh43617e92006-03-06 20:55:46 +00003946 assert( pNewParent!=0 );
danielk1977afcdd022004-10-31 16:25:42 +00003947 if( pgno==0 ) return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00003948 assert( pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00003949 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
3950 if( pDbPage ){
3951 pThis = (MemPage *)sqlite3PagerGetExtra(pDbPage);
drhda200cc2004-05-09 11:51:38 +00003952 if( pThis->isInit ){
danielk19773b8a05f2007-03-19 17:44:26 +00003953 assert( pThis->aData==(sqlite3PagerGetData(pDbPage)) );
drhda200cc2004-05-09 11:51:38 +00003954 if( pThis->pParent!=pNewParent ){
danielk19773b8a05f2007-03-19 17:44:26 +00003955 if( pThis->pParent ) sqlite3PagerUnref(pThis->pParent->pDbPage);
drhda200cc2004-05-09 11:51:38 +00003956 pThis->pParent = pNewParent;
danielk19773b8a05f2007-03-19 17:44:26 +00003957 sqlite3PagerRef(pNewParent->pDbPage);
drhda200cc2004-05-09 11:51:38 +00003958 }
3959 pThis->idxParent = idx;
drhdd793422001-06-28 01:54:48 +00003960 }
danielk19773b8a05f2007-03-19 17:44:26 +00003961 sqlite3PagerUnref(pDbPage);
drhbd03cae2001-06-02 02:40:57 +00003962 }
danielk1977afcdd022004-10-31 16:25:42 +00003963
3964#ifndef SQLITE_OMIT_AUTOVACUUM
3965 if( pBt->autoVacuum ){
3966 return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
3967 }
3968#endif
3969 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00003970}
3971
danielk1977ac11ee62005-01-15 12:45:51 +00003972
3973
drhbd03cae2001-06-02 02:40:57 +00003974/*
drh4b70f112004-05-02 21:12:19 +00003975** Change the pParent pointer of all children of pPage to point back
3976** to pPage.
3977**
drhbd03cae2001-06-02 02:40:57 +00003978** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00003979** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00003980**
3981** This routine gets called after you memcpy() one page into
3982** another.
3983*/
danielk1977afcdd022004-10-31 16:25:42 +00003984static int reparentChildPages(MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00003985 int i;
danielk1977aef0bf62005-12-30 16:28:01 +00003986 BtShared *pBt = pPage->pBt;
danielk1977afcdd022004-10-31 16:25:42 +00003987 int rc = SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00003988
danielk1977afcdd022004-10-31 16:25:42 +00003989 if( pPage->leaf ) return SQLITE_OK;
danielk1977afcdd022004-10-31 16:25:42 +00003990
drhbd03cae2001-06-02 02:40:57 +00003991 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00003992 u8 *pCell = findCell(pPage, i);
danielk1977afcdd022004-10-31 16:25:42 +00003993 if( !pPage->leaf ){
3994 rc = reparentPage(pBt, get4byte(pCell), pPage, i);
3995 if( rc!=SQLITE_OK ) return rc;
3996 }
drhbd03cae2001-06-02 02:40:57 +00003997 }
danielk1977afcdd022004-10-31 16:25:42 +00003998 if( !pPage->leaf ){
3999 rc = reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]),
4000 pPage, i);
4001 pPage->idxShift = 0;
4002 }
4003 return rc;
drh14acc042001-06-10 19:56:58 +00004004}
4005
4006/*
4007** Remove the i-th cell from pPage. This routine effects pPage only.
4008** The cell content is not freed or deallocated. It is assumed that
4009** the cell content has been copied someplace else. This routine just
4010** removes the reference to the cell from pPage.
4011**
4012** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00004013*/
drh4b70f112004-05-02 21:12:19 +00004014static void dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00004015 int i; /* Loop counter */
4016 int pc; /* Offset to cell content of cell being deleted */
4017 u8 *data; /* pPage->aData */
4018 u8 *ptr; /* Used to move bytes around within data[] */
4019
drh8c42ca92001-06-22 19:15:00 +00004020 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00004021 assert( sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00004022 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drhda200cc2004-05-09 11:51:38 +00004023 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00004024 ptr = &data[pPage->cellOffset + 2*idx];
4025 pc = get2byte(ptr);
4026 assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
drhde647132004-05-07 17:57:49 +00004027 freeSpace(pPage, pc, sz);
drh43605152004-05-29 21:46:49 +00004028 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
4029 ptr[0] = ptr[2];
4030 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00004031 }
4032 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00004033 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
4034 pPage->nFree += 2;
drh428ae8c2003-01-04 16:48:09 +00004035 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00004036}
4037
4038/*
4039** Insert a new cell on pPage at cell index "i". pCell points to the
4040** content of the cell.
4041**
4042** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00004043** will not fit, then make a copy of the cell content into pTemp if
4044** pTemp is not null. Regardless of pTemp, allocate a new entry
4045** in pPage->aOvfl[] and make it point to the cell content (either
4046** in pTemp or the original pCell) and also record its index.
4047** Allocating a new entry in pPage->aCell[] implies that
4048** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00004049**
4050** If nSkip is non-zero, then do not copy the first nSkip bytes of the
4051** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00004052** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00004053** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00004054*/
danielk1977e80463b2004-11-03 03:01:16 +00004055static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00004056 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00004057 int i, /* New cell becomes the i-th cell of the page */
4058 u8 *pCell, /* Content of the new cell */
4059 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00004060 u8 *pTemp, /* Temp storage space for pCell, if needed */
4061 u8 nSkip /* Do not write the first nSkip bytes of the cell */
drh24cd67e2004-05-10 16:18:47 +00004062){
drh43605152004-05-29 21:46:49 +00004063 int idx; /* Where to write new cell content in data[] */
4064 int j; /* Loop counter */
4065 int top; /* First byte of content for any cell in data[] */
4066 int end; /* First byte past the last cell pointer in data[] */
4067 int ins; /* Index in data[] where new cell pointer is inserted */
4068 int hdr; /* Offset into data[] of the page header */
4069 int cellOffset; /* Address of first cell pointer in data[] */
4070 u8 *data; /* The content of the whole page */
4071 u8 *ptr; /* Used for moving information around in data[] */
4072
4073 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
4074 assert( sz==cellSizePtr(pPage, pCell) );
danielk19773b8a05f2007-03-19 17:44:26 +00004075 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00004076 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00004077 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00004078 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004079 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00004080 }
drh43605152004-05-29 21:46:49 +00004081 j = pPage->nOverflow++;
4082 assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
4083 pPage->aOvfl[j].pCell = pCell;
4084 pPage->aOvfl[j].idx = i;
4085 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00004086 }else{
drh43605152004-05-29 21:46:49 +00004087 data = pPage->aData;
4088 hdr = pPage->hdrOffset;
4089 top = get2byte(&data[hdr+5]);
4090 cellOffset = pPage->cellOffset;
4091 end = cellOffset + 2*pPage->nCell + 2;
4092 ins = cellOffset + 2*i;
4093 if( end > top - sz ){
danielk19776b456a22005-03-21 04:04:02 +00004094 int rc = defragmentPage(pPage);
4095 if( rc!=SQLITE_OK ) return rc;
drh43605152004-05-29 21:46:49 +00004096 top = get2byte(&data[hdr+5]);
4097 assert( end + sz <= top );
4098 }
4099 idx = allocateSpace(pPage, sz);
4100 assert( idx>0 );
4101 assert( end <= get2byte(&data[hdr+5]) );
4102 pPage->nCell++;
4103 pPage->nFree -= 2;
danielk1977a3ad5e72005-01-07 08:56:44 +00004104 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004105 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
4106 ptr[0] = ptr[-2];
4107 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00004108 }
drh43605152004-05-29 21:46:49 +00004109 put2byte(&data[ins], idx);
4110 put2byte(&data[hdr+3], pPage->nCell);
4111 pPage->idxShift = 1;
danielk1977a19df672004-11-03 11:37:07 +00004112#ifndef SQLITE_OMIT_AUTOVACUUM
4113 if( pPage->pBt->autoVacuum ){
4114 /* The cell may contain a pointer to an overflow page. If so, write
4115 ** the entry for the overflow page into the pointer map.
4116 */
4117 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00004118 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh72365832007-03-06 15:53:44 +00004119 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk1977a19df672004-11-03 11:37:07 +00004120 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
4121 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
4122 int rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
4123 if( rc!=SQLITE_OK ) return rc;
4124 }
4125 }
4126#endif
drh14acc042001-06-10 19:56:58 +00004127 }
danielk1977e80463b2004-11-03 03:01:16 +00004128
danielk1977e80463b2004-11-03 03:01:16 +00004129 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004130}
4131
4132/*
drhfa1a98a2004-05-14 19:08:17 +00004133** Add a list of cells to a page. The page should be initially empty.
4134** The cells are guaranteed to fit on the page.
4135*/
4136static void assemblePage(
4137 MemPage *pPage, /* The page to be assemblied */
4138 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00004139 u8 **apCell, /* Pointers to cell bodies */
drhfa1a98a2004-05-14 19:08:17 +00004140 int *aSize /* Sizes of the cells */
4141){
4142 int i; /* Loop counter */
4143 int totalSize; /* Total size of all cells */
4144 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00004145 int cellptr; /* Address of next cell pointer */
4146 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00004147 u8 *data; /* Data for the page */
4148
drh43605152004-05-29 21:46:49 +00004149 assert( pPage->nOverflow==0 );
drhfa1a98a2004-05-14 19:08:17 +00004150 totalSize = 0;
4151 for(i=0; i<nCell; i++){
4152 totalSize += aSize[i];
4153 }
drh43605152004-05-29 21:46:49 +00004154 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00004155 assert( pPage->nCell==0 );
drh43605152004-05-29 21:46:49 +00004156 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00004157 data = pPage->aData;
4158 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00004159 put2byte(&data[hdr+3], nCell);
drh09d0deb2005-08-02 17:13:09 +00004160 if( nCell ){
4161 cellbody = allocateSpace(pPage, totalSize);
4162 assert( cellbody>0 );
4163 assert( pPage->nFree >= 2*nCell );
4164 pPage->nFree -= 2*nCell;
4165 for(i=0; i<nCell; i++){
4166 put2byte(&data[cellptr], cellbody);
4167 memcpy(&data[cellbody], apCell[i], aSize[i]);
4168 cellptr += 2;
4169 cellbody += aSize[i];
4170 }
4171 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00004172 }
4173 pPage->nCell = nCell;
drhfa1a98a2004-05-14 19:08:17 +00004174}
4175
drh14acc042001-06-10 19:56:58 +00004176/*
drhc3b70572003-01-04 19:44:07 +00004177** The following parameters determine how many adjacent pages get involved
4178** in a balancing operation. NN is the number of neighbors on either side
4179** of the page that participate in the balancing operation. NB is the
4180** total number of pages that participate, including the target page and
4181** NN neighbors on either side.
4182**
4183** The minimum value of NN is 1 (of course). Increasing NN above 1
4184** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
4185** in exchange for a larger degradation in INSERT and UPDATE performance.
4186** The value of NN appears to give the best results overall.
4187*/
4188#define NN 1 /* Number of neighbors on either side of pPage */
4189#define NB (NN*2+1) /* Total pages involved in the balance */
4190
drh43605152004-05-29 21:46:49 +00004191/* Forward reference */
danielk1977ac245ec2005-01-14 13:50:11 +00004192static int balance(MemPage*, int);
4193
drh615ae552005-01-16 23:21:00 +00004194#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004195/*
4196** This version of balance() handles the common special case where
4197** a new entry is being inserted on the extreme right-end of the
4198** tree, in other words, when the new entry will become the largest
4199** entry in the tree.
4200**
4201** Instead of trying balance the 3 right-most leaf pages, just add
4202** a new page to the right-hand side and put the one new entry in
4203** that page. This leaves the right side of the tree somewhat
4204** unbalanced. But odds are that we will be inserting new entries
4205** at the end soon afterwards so the nearly empty page will quickly
4206** fill up. On average.
4207**
4208** pPage is the leaf page which is the right-most page in the tree.
4209** pParent is its parent. pPage must have a single overflow entry
4210** which is also the right-most entry on the page.
4211*/
danielk1977ac245ec2005-01-14 13:50:11 +00004212static int balance_quick(MemPage *pPage, MemPage *pParent){
4213 int rc;
4214 MemPage *pNew;
4215 Pgno pgnoNew;
4216 u8 *pCell;
4217 int szCell;
4218 CellInfo info;
danielk1977aef0bf62005-12-30 16:28:01 +00004219 BtShared *pBt = pPage->pBt;
danielk197779a40da2005-01-16 08:00:01 +00004220 int parentIdx = pParent->nCell; /* pParent new divider cell index */
4221 int parentSize; /* Size of new divider cell */
4222 u8 parentCell[64]; /* Space for the new divider cell */
danielk1977ac245ec2005-01-14 13:50:11 +00004223
4224 /* Allocate a new page. Insert the overflow cell from pPage
4225 ** into it. Then remove the overflow cell from pPage.
4226 */
drh4f0c5872007-03-26 22:05:01 +00004227 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk1977ac245ec2005-01-14 13:50:11 +00004228 if( rc!=SQLITE_OK ){
4229 return rc;
4230 }
4231 pCell = pPage->aOvfl[0].pCell;
4232 szCell = cellSizePtr(pPage, pCell);
4233 zeroPage(pNew, pPage->aData[0]);
4234 assemblePage(pNew, 1, &pCell, &szCell);
4235 pPage->nOverflow = 0;
4236
danielk197779a40da2005-01-16 08:00:01 +00004237 /* Set the parent of the newly allocated page to pParent. */
4238 pNew->pParent = pParent;
danielk19773b8a05f2007-03-19 17:44:26 +00004239 sqlite3PagerRef(pParent->pDbPage);
danielk197779a40da2005-01-16 08:00:01 +00004240
danielk1977ac245ec2005-01-14 13:50:11 +00004241 /* pPage is currently the right-child of pParent. Change this
4242 ** so that the right-child is the new page allocated above and
danielk197779a40da2005-01-16 08:00:01 +00004243 ** pPage is the next-to-right child.
danielk1977ac245ec2005-01-14 13:50:11 +00004244 */
danielk1977ac11ee62005-01-15 12:45:51 +00004245 assert( pPage->nCell>0 );
danielk19771cc5ed82007-05-16 17:28:43 +00004246 pCell = findCell(pPage, pPage->nCell-1);
drh16a9b832007-05-05 18:39:25 +00004247 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drhb026e052007-05-02 01:34:31 +00004248 rc = fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
danielk1977ac245ec2005-01-14 13:50:11 +00004249 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00004250 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004251 }
4252 assert( parentSize<64 );
4253 rc = insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
4254 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00004255 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004256 }
4257 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
4258 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
4259
danielk197779a40da2005-01-16 08:00:01 +00004260#ifndef SQLITE_OMIT_AUTOVACUUM
4261 /* If this is an auto-vacuum database, update the pointer map
4262 ** with entries for the new page, and any pointer from the
4263 ** cell on the page to an overflow page.
4264 */
danielk1977ac11ee62005-01-15 12:45:51 +00004265 if( pBt->autoVacuum ){
4266 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
danielk1977deb403e2007-05-24 09:20:16 +00004267 if( rc==SQLITE_OK ){
4268 rc = ptrmapPutOvfl(pNew, 0);
danielk1977ac11ee62005-01-15 12:45:51 +00004269 }
danielk197779a40da2005-01-16 08:00:01 +00004270 if( rc!=SQLITE_OK ){
danielk1977deb403e2007-05-24 09:20:16 +00004271 releasePage(pNew);
danielk197779a40da2005-01-16 08:00:01 +00004272 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00004273 }
4274 }
danielk197779a40da2005-01-16 08:00:01 +00004275#endif
danielk1977ac11ee62005-01-15 12:45:51 +00004276
danielk197779a40da2005-01-16 08:00:01 +00004277 /* Release the reference to the new page and balance the parent page,
4278 ** in case the divider cell inserted caused it to become overfull.
4279 */
danielk1977ac245ec2005-01-14 13:50:11 +00004280 releasePage(pNew);
4281 return balance(pParent, 0);
4282}
drh615ae552005-01-16 23:21:00 +00004283#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00004284
drhc3b70572003-01-04 19:44:07 +00004285/*
drhab01f612004-05-22 02:55:23 +00004286** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00004287** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00004288** Usually NN siblings on either side of pPage is used in the balancing,
4289** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00004290** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00004291** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00004292** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00004293**
drh0c6cc4e2004-06-15 02:13:26 +00004294** The number of siblings of pPage might be increased or decreased by one or
4295** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00004296** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00004297** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00004298** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00004299** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00004300**
drh8b2f49b2001-06-08 00:21:52 +00004301** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00004302** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00004303** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00004304** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00004305**
drh8c42ca92001-06-22 19:15:00 +00004306** In the course of balancing the siblings of pPage, the parent of pPage
4307** might become overfull or underfull. If that happens, then this routine
4308** is called recursively on the parent.
4309**
drh5e00f6c2001-09-13 13:46:56 +00004310** If this routine fails for any reason, it might leave the database
4311** in a corrupted state. So if this routine fails, the database should
4312** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00004313*/
drh43605152004-05-29 21:46:49 +00004314static int balance_nonroot(MemPage *pPage){
drh8b2f49b2001-06-08 00:21:52 +00004315 MemPage *pParent; /* The parent of pPage */
drh16a9b832007-05-05 18:39:25 +00004316 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00004317 int nCell = 0; /* Number of cells in apCell[] */
4318 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
drh8b2f49b2001-06-08 00:21:52 +00004319 int nOld; /* Number of pages in apOld[] */
4320 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00004321 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00004322 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00004323 int idx; /* Index of pPage in pParent->aCell[] */
4324 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00004325 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00004326 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00004327 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00004328 int usableSpace; /* Bytes in pPage beyond the header */
4329 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00004330 int subtotal; /* Subtotal of bytes in cells on one page */
drhb6f41482004-05-14 01:58:11 +00004331 int iSpace = 0; /* First unused byte of aSpace[] */
drhc3b70572003-01-04 19:44:07 +00004332 MemPage *apOld[NB]; /* pPage and up to two siblings */
4333 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00004334 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00004335 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
4336 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drh4b70f112004-05-02 21:12:19 +00004337 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00004338 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
4339 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00004340 u8 **apCell = 0; /* All cells begin balanced */
drh2e38c322004-09-03 18:38:44 +00004341 int *szCell; /* Local size of all cells in apCell[] */
4342 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
4343 u8 *aSpace; /* Space to hold copies of dividers cells */
danielk19774e17d142005-01-16 09:06:33 +00004344#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00004345 u8 *aFrom = 0;
4346#endif
drh8b2f49b2001-06-08 00:21:52 +00004347
drh14acc042001-06-10 19:56:58 +00004348 /*
drh43605152004-05-29 21:46:49 +00004349 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00004350 */
drh3a4c1412004-05-09 20:40:11 +00004351 assert( pPage->isInit );
danielk19773b8a05f2007-03-19 17:44:26 +00004352 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh4b70f112004-05-02 21:12:19 +00004353 pBt = pPage->pBt;
drh14acc042001-06-10 19:56:58 +00004354 pParent = pPage->pParent;
drh43605152004-05-29 21:46:49 +00004355 assert( pParent );
danielk19773b8a05f2007-03-19 17:44:26 +00004356 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
danielk197707cb5602006-01-20 10:55:05 +00004357 return rc;
4358 }
drh43605152004-05-29 21:46:49 +00004359 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00004360
drh615ae552005-01-16 23:21:00 +00004361#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004362 /*
4363 ** A special case: If a new entry has just been inserted into a
4364 ** table (that is, a btree with integer keys and all data at the leaves)
drh09d0deb2005-08-02 17:13:09 +00004365 ** and the new entry is the right-most entry in the tree (it has the
drhf222e712005-01-14 22:55:49 +00004366 ** largest key) then use the special balance_quick() routine for
4367 ** balancing. balance_quick() is much faster and results in a tighter
4368 ** packing of data in the common case.
4369 */
danielk1977ac245ec2005-01-14 13:50:11 +00004370 if( pPage->leaf &&
4371 pPage->intKey &&
4372 pPage->leafData &&
4373 pPage->nOverflow==1 &&
4374 pPage->aOvfl[0].idx==pPage->nCell &&
danielk1977ac11ee62005-01-15 12:45:51 +00004375 pPage->pParent->pgno!=1 &&
danielk1977ac245ec2005-01-14 13:50:11 +00004376 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
4377 ){
danielk1977ac11ee62005-01-15 12:45:51 +00004378 /*
4379 ** TODO: Check the siblings to the left of pPage. It may be that
4380 ** they are not full and no new page is required.
4381 */
danielk1977ac245ec2005-01-14 13:50:11 +00004382 return balance_quick(pPage, pParent);
4383 }
4384#endif
4385
drh2e38c322004-09-03 18:38:44 +00004386 /*
drh4b70f112004-05-02 21:12:19 +00004387 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00004388 ** to pPage. The "idx" variable is the index of that cell. If pPage
4389 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00004390 */
drhbb49aba2003-01-04 18:53:27 +00004391 if( pParent->idxShift ){
drha34b6762004-05-07 13:30:42 +00004392 Pgno pgno;
drh4b70f112004-05-02 21:12:19 +00004393 pgno = pPage->pgno;
danielk19773b8a05f2007-03-19 17:44:26 +00004394 assert( pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbb49aba2003-01-04 18:53:27 +00004395 for(idx=0; idx<pParent->nCell; idx++){
danielk19771cc5ed82007-05-16 17:28:43 +00004396 if( get4byte(findCell(pParent, idx))==pgno ){
drhbb49aba2003-01-04 18:53:27 +00004397 break;
4398 }
drh8b2f49b2001-06-08 00:21:52 +00004399 }
drh4b70f112004-05-02 21:12:19 +00004400 assert( idx<pParent->nCell
drh43605152004-05-29 21:46:49 +00004401 || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
drhbb49aba2003-01-04 18:53:27 +00004402 }else{
4403 idx = pPage->idxParent;
drh8b2f49b2001-06-08 00:21:52 +00004404 }
drh8b2f49b2001-06-08 00:21:52 +00004405
4406 /*
drh14acc042001-06-10 19:56:58 +00004407 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00004408 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00004409 */
drh14acc042001-06-10 19:56:58 +00004410 nOld = nNew = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00004411 sqlite3PagerRef(pParent->pDbPage);
drh14acc042001-06-10 19:56:58 +00004412
4413 /*
drh4b70f112004-05-02 21:12:19 +00004414 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00004415 ** the siblings. An attempt is made to find NN siblings on either
4416 ** side of pPage. More siblings are taken from one side, however, if
4417 ** pPage there are fewer than NN siblings on the other side. If pParent
4418 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00004419 */
drhc3b70572003-01-04 19:44:07 +00004420 nxDiv = idx - NN;
4421 if( nxDiv + NB > pParent->nCell ){
4422 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00004423 }
drhc3b70572003-01-04 19:44:07 +00004424 if( nxDiv<0 ){
4425 nxDiv = 0;
4426 }
drh8b2f49b2001-06-08 00:21:52 +00004427 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00004428 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00004429 if( k<pParent->nCell ){
danielk19771cc5ed82007-05-16 17:28:43 +00004430 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00004431 nDiv++;
drha34b6762004-05-07 13:30:42 +00004432 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00004433 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00004434 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00004435 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00004436 }else{
4437 break;
drh8b2f49b2001-06-08 00:21:52 +00004438 }
drhde647132004-05-07 17:57:49 +00004439 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00004440 if( rc ) goto balance_cleanup;
drh428ae8c2003-01-04 16:48:09 +00004441 apOld[i]->idxParent = k;
drh91025292004-05-03 19:49:32 +00004442 apCopy[i] = 0;
4443 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00004444 nOld++;
danielk1977634f2982005-03-28 08:44:07 +00004445 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
drh8b2f49b2001-06-08 00:21:52 +00004446 }
4447
drh8d97f1f2005-05-05 18:14:13 +00004448 /* Make nMaxCells a multiple of 2 in order to preserve 8-byte
4449 ** alignment */
4450 nMaxCells = (nMaxCells + 1)&~1;
4451
drh8b2f49b2001-06-08 00:21:52 +00004452 /*
danielk1977634f2982005-03-28 08:44:07 +00004453 ** Allocate space for memory structures
4454 */
4455 apCell = sqliteMallocRaw(
4456 nMaxCells*sizeof(u8*) /* apCell */
4457 + nMaxCells*sizeof(int) /* szCell */
drhc96d8532005-05-03 12:30:33 +00004458 + ROUND8(sizeof(MemPage))*NB /* aCopy */
drh07d183d2005-05-01 22:52:42 +00004459 + pBt->pageSize*(5+NB) /* aSpace */
drhc96d8532005-05-03 12:30:33 +00004460 + (ISAUTOVACUUM ? nMaxCells : 0) /* aFrom */
danielk1977634f2982005-03-28 08:44:07 +00004461 );
4462 if( apCell==0 ){
4463 rc = SQLITE_NOMEM;
4464 goto balance_cleanup;
4465 }
4466 szCell = (int*)&apCell[nMaxCells];
4467 aCopy[0] = (u8*)&szCell[nMaxCells];
drhc96d8532005-05-03 12:30:33 +00004468 assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004469 for(i=1; i<NB; i++){
drhc96d8532005-05-03 12:30:33 +00004470 aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
4471 assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004472 }
drhc96d8532005-05-03 12:30:33 +00004473 aSpace = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
4474 assert( ((aSpace - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004475#ifndef SQLITE_OMIT_AUTOVACUUM
4476 if( pBt->autoVacuum ){
drh07d183d2005-05-01 22:52:42 +00004477 aFrom = &aSpace[5*pBt->pageSize];
danielk1977634f2982005-03-28 08:44:07 +00004478 }
4479#endif
4480
4481 /*
drh14acc042001-06-10 19:56:58 +00004482 ** Make copies of the content of pPage and its siblings into aOld[].
4483 ** The rest of this function will use data from the copies rather
4484 ** that the original pages since the original pages will be in the
4485 ** process of being overwritten.
4486 */
4487 for(i=0; i<nOld; i++){
drh07d183d2005-05-01 22:52:42 +00004488 MemPage *p = apCopy[i] = (MemPage*)&aCopy[i][pBt->pageSize];
drh07d183d2005-05-01 22:52:42 +00004489 p->aData = &((u8*)p)[-pBt->pageSize];
4490 memcpy(p->aData, apOld[i]->aData, pBt->pageSize + sizeof(MemPage));
4491 /* The memcpy() above changes the value of p->aData so we have to
4492 ** set it again. */
drh07d183d2005-05-01 22:52:42 +00004493 p->aData = &((u8*)p)[-pBt->pageSize];
drh14acc042001-06-10 19:56:58 +00004494 }
4495
4496 /*
4497 ** Load pointers to all cells on sibling pages and the divider cells
4498 ** into the local apCell[] array. Make copies of the divider cells
drhb6f41482004-05-14 01:58:11 +00004499 ** into space obtained form aSpace[] and remove the the divider Cells
4500 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00004501 **
4502 ** If the siblings are on leaf pages, then the child pointers of the
4503 ** divider cells are stripped from the cells before they are copied
drh96f5b762004-05-16 16:24:36 +00004504 ** into aSpace[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00004505 ** child pointers. If siblings are not leaves, then all cell in
4506 ** apCell[] include child pointers. Either way, all cells in apCell[]
4507 ** are alike.
drh96f5b762004-05-16 16:24:36 +00004508 **
4509 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
4510 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00004511 */
4512 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00004513 leafCorrection = pPage->leaf*4;
drh8b18dd42004-05-12 19:18:15 +00004514 leafData = pPage->leafData && pPage->leaf;
drh8b2f49b2001-06-08 00:21:52 +00004515 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00004516 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00004517 int limit = pOld->nCell+pOld->nOverflow;
4518 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00004519 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00004520 apCell[nCell] = findOverflowCell(pOld, j);
4521 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk1977ac11ee62005-01-15 12:45:51 +00004522#ifndef SQLITE_OMIT_AUTOVACUUM
4523 if( pBt->autoVacuum ){
4524 int a;
4525 aFrom[nCell] = i;
4526 for(a=0; a<pOld->nOverflow; a++){
4527 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
4528 aFrom[nCell] = 0xFF;
4529 break;
4530 }
4531 }
4532 }
4533#endif
drh14acc042001-06-10 19:56:58 +00004534 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00004535 }
4536 if( i<nOld-1 ){
drh43605152004-05-29 21:46:49 +00004537 int sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00004538 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00004539 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
4540 ** are duplicates of keys on the child pages. We need to remove
4541 ** the divider cells from pParent, but the dividers cells are not
4542 ** added to apCell[] because they are duplicates of child cells.
4543 */
drh8b18dd42004-05-12 19:18:15 +00004544 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00004545 }else{
drhb6f41482004-05-14 01:58:11 +00004546 u8 *pTemp;
danielk1977634f2982005-03-28 08:44:07 +00004547 assert( nCell<nMaxCells );
drhb6f41482004-05-14 01:58:11 +00004548 szCell[nCell] = sz;
4549 pTemp = &aSpace[iSpace];
4550 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004551 assert( iSpace<=pBt->pageSize*5 );
drhb6f41482004-05-14 01:58:11 +00004552 memcpy(pTemp, apDiv[i], sz);
4553 apCell[nCell] = pTemp+leafCorrection;
danielk1977ac11ee62005-01-15 12:45:51 +00004554#ifndef SQLITE_OMIT_AUTOVACUUM
4555 if( pBt->autoVacuum ){
4556 aFrom[nCell] = 0xFF;
4557 }
4558#endif
drhb6f41482004-05-14 01:58:11 +00004559 dropCell(pParent, nxDiv, sz);
drh8b18dd42004-05-12 19:18:15 +00004560 szCell[nCell] -= leafCorrection;
drh43605152004-05-29 21:46:49 +00004561 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00004562 if( !pOld->leaf ){
4563 assert( leafCorrection==0 );
4564 /* The right pointer of the child page pOld becomes the left
4565 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00004566 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00004567 }else{
4568 assert( leafCorrection==4 );
danielk197739c96042007-05-12 10:41:47 +00004569 if( szCell[nCell]<4 ){
4570 /* Do not allow any cells smaller than 4 bytes. */
4571 szCell[nCell] = 4;
4572 }
drh8b18dd42004-05-12 19:18:15 +00004573 }
4574 nCell++;
drh4b70f112004-05-02 21:12:19 +00004575 }
drh8b2f49b2001-06-08 00:21:52 +00004576 }
4577 }
4578
4579 /*
drh6019e162001-07-02 17:51:45 +00004580 ** Figure out the number of pages needed to hold all nCell cells.
4581 ** Store this number in "k". Also compute szNew[] which is the total
4582 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00004583 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00004584 ** cntNew[k] should equal nCell.
4585 **
drh96f5b762004-05-16 16:24:36 +00004586 ** Values computed by this block:
4587 **
4588 ** k: The total number of sibling pages
4589 ** szNew[i]: Spaced used on the i-th sibling page.
4590 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
4591 ** the right of the i-th sibling page.
4592 ** usableSpace: Number of bytes of space available on each sibling.
4593 **
drh8b2f49b2001-06-08 00:21:52 +00004594 */
drh43605152004-05-29 21:46:49 +00004595 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00004596 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00004597 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00004598 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00004599 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00004600 szNew[k] = subtotal - szCell[i];
4601 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00004602 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00004603 subtotal = 0;
4604 k++;
4605 }
4606 }
4607 szNew[k] = subtotal;
4608 cntNew[k] = nCell;
4609 k++;
drh96f5b762004-05-16 16:24:36 +00004610
4611 /*
4612 ** The packing computed by the previous block is biased toward the siblings
4613 ** on the left side. The left siblings are always nearly full, while the
4614 ** right-most sibling might be nearly empty. This block of code attempts
4615 ** to adjust the packing of siblings to get a better balance.
4616 **
4617 ** This adjustment is more than an optimization. The packing above might
4618 ** be so out of balance as to be illegal. For example, the right-most
4619 ** sibling might be completely empty. This adjustment is not optional.
4620 */
drh6019e162001-07-02 17:51:45 +00004621 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00004622 int szRight = szNew[i]; /* Size of sibling on the right */
4623 int szLeft = szNew[i-1]; /* Size of sibling on the left */
4624 int r; /* Index of right-most cell in left sibling */
4625 int d; /* Index of first cell to the left of right sibling */
4626
4627 r = cntNew[i-1] - 1;
4628 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00004629 assert( d<nMaxCells );
4630 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00004631 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
4632 szRight += szCell[d] + 2;
4633 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00004634 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00004635 r = cntNew[i-1] - 1;
4636 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00004637 }
drh96f5b762004-05-16 16:24:36 +00004638 szNew[i] = szRight;
4639 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00004640 }
drh09d0deb2005-08-02 17:13:09 +00004641
4642 /* Either we found one or more cells (cntnew[0])>0) or we are the
4643 ** a virtual root page. A virtual root page is when the real root
4644 ** page is page 1 and we are the only child of that page.
4645 */
4646 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00004647
4648 /*
drh6b308672002-07-08 02:16:37 +00004649 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00004650 */
drh4b70f112004-05-02 21:12:19 +00004651 assert( pPage->pgno>1 );
4652 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00004653 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00004654 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00004655 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00004656 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00004657 pgnoNew[i] = pgnoOld[i];
4658 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00004659 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00004660 nNew++;
danielk197728129562005-01-11 10:25:06 +00004661 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00004662 }else{
drh7aa8f852006-03-28 00:24:44 +00004663 assert( i>0 );
drh4f0c5872007-03-26 22:05:01 +00004664 rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
drh6b308672002-07-08 02:16:37 +00004665 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00004666 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00004667 nNew++;
drh6b308672002-07-08 02:16:37 +00004668 }
drhda200cc2004-05-09 11:51:38 +00004669 zeroPage(pNew, pageFlags);
drh8b2f49b2001-06-08 00:21:52 +00004670 }
4671
danielk1977299b1872004-11-22 10:02:10 +00004672 /* Free any old pages that were not reused as new pages.
4673 */
4674 while( i<nOld ){
4675 rc = freePage(apOld[i]);
4676 if( rc ) goto balance_cleanup;
4677 releasePage(apOld[i]);
4678 apOld[i] = 0;
4679 i++;
4680 }
4681
drh8b2f49b2001-06-08 00:21:52 +00004682 /*
drhf9ffac92002-03-02 19:00:31 +00004683 ** Put the new pages in accending order. This helps to
4684 ** keep entries in the disk file in order so that a scan
4685 ** of the table is a linear scan through the file. That
4686 ** in turn helps the operating system to deliver pages
4687 ** from the disk more rapidly.
4688 **
4689 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00004690 ** n is never more than NB (a small constant), that should
4691 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00004692 **
drhc3b70572003-01-04 19:44:07 +00004693 ** When NB==3, this one optimization makes the database
4694 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00004695 */
4696 for(i=0; i<k-1; i++){
4697 int minV = pgnoNew[i];
4698 int minI = i;
4699 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00004700 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00004701 minI = j;
4702 minV = pgnoNew[j];
4703 }
4704 }
4705 if( minI>i ){
4706 int t;
4707 MemPage *pT;
4708 t = pgnoNew[i];
4709 pT = apNew[i];
4710 pgnoNew[i] = pgnoNew[minI];
4711 apNew[i] = apNew[minI];
4712 pgnoNew[minI] = t;
4713 apNew[minI] = pT;
4714 }
4715 }
drha2fce642004-06-05 00:01:44 +00004716 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00004717 pgnoOld[0],
4718 nOld>=2 ? pgnoOld[1] : 0,
4719 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00004720 pgnoNew[0], szNew[0],
4721 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
4722 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00004723 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
4724 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00004725
drhf9ffac92002-03-02 19:00:31 +00004726 /*
drh14acc042001-06-10 19:56:58 +00004727 ** Evenly distribute the data in apCell[] across the new pages.
4728 ** Insert divider cells into pParent as necessary.
4729 */
4730 j = 0;
4731 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00004732 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00004733 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00004734 assert( j<nMaxCells );
drh4b70f112004-05-02 21:12:19 +00004735 assert( pNew->pgno==pgnoNew[i] );
drhfa1a98a2004-05-14 19:08:17 +00004736 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00004737 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00004738 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00004739
4740#ifndef SQLITE_OMIT_AUTOVACUUM
4741 /* If this is an auto-vacuum database, update the pointer map entries
4742 ** that point to the siblings that were rearranged. These can be: left
4743 ** children of cells, the right-child of the page, or overflow pages
4744 ** pointed to by cells.
4745 */
4746 if( pBt->autoVacuum ){
4747 for(k=j; k<cntNew[i]; k++){
danielk1977634f2982005-03-28 08:44:07 +00004748 assert( k<nMaxCells );
danielk1977ac11ee62005-01-15 12:45:51 +00004749 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
danielk197779a40da2005-01-16 08:00:01 +00004750 rc = ptrmapPutOvfl(pNew, k-j);
4751 if( rc!=SQLITE_OK ){
4752 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00004753 }
4754 }
4755 }
4756 }
4757#endif
4758
4759 j = cntNew[i];
4760
4761 /* If the sibling page assembled above was not the right-most sibling,
4762 ** insert a divider cell into the parent page.
4763 */
drh14acc042001-06-10 19:56:58 +00004764 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00004765 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00004766 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00004767 int sz;
danielk1977634f2982005-03-28 08:44:07 +00004768
4769 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00004770 pCell = apCell[j];
4771 sz = szCell[j] + leafCorrection;
drh4b70f112004-05-02 21:12:19 +00004772 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00004773 memcpy(&pNew->aData[8], pCell, 4);
drh24cd67e2004-05-10 16:18:47 +00004774 pTemp = 0;
drh8b18dd42004-05-12 19:18:15 +00004775 }else if( leafData ){
drhfd131da2007-08-07 17:13:03 +00004776 /* If the tree is a leaf-data tree, and the siblings are leaves,
danielk1977ac11ee62005-01-15 12:45:51 +00004777 ** then there is no divider cell in apCell[]. Instead, the divider
4778 ** cell consists of the integer key for the right-most cell of
4779 ** the sibling-page assembled above only.
4780 */
drh6f11bef2004-05-13 01:12:56 +00004781 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00004782 j--;
drh16a9b832007-05-05 18:39:25 +00004783 sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
drhb6f41482004-05-14 01:58:11 +00004784 pCell = &aSpace[iSpace];
drhb026e052007-05-02 01:34:31 +00004785 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
drhb6f41482004-05-14 01:58:11 +00004786 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004787 assert( iSpace<=pBt->pageSize*5 );
drh8b18dd42004-05-12 19:18:15 +00004788 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00004789 }else{
4790 pCell -= 4;
drhb6f41482004-05-14 01:58:11 +00004791 pTemp = &aSpace[iSpace];
4792 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004793 assert( iSpace<=pBt->pageSize*5 );
danielk19774aeff622007-05-12 09:30:47 +00004794 /* Obscure case for non-leaf-data trees: If the cell at pCell was
4795 ** previously stored on a leaf node, and it's reported size was 4
4796 ** bytes, then it may actually be smaller than this
4797 ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
4798 ** any cell). But it's important to pass the correct size to
4799 ** insertCell(), so reparse the cell now.
4800 **
4801 ** Note that this can never happen in an SQLite data file, as all
4802 ** cells are at least 4 bytes. It only happens in b-trees used
4803 ** to evaluate "IN (SELECT ...)" and similar clauses.
4804 */
4805 if( szCell[j]==4 ){
4806 assert(leafCorrection==4);
4807 sz = cellSizePtr(pParent, pCell);
4808 }
drh4b70f112004-05-02 21:12:19 +00004809 }
danielk1977a3ad5e72005-01-07 08:56:44 +00004810 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
danielk1977e80463b2004-11-03 03:01:16 +00004811 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh43605152004-05-29 21:46:49 +00004812 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +00004813#ifndef SQLITE_OMIT_AUTOVACUUM
4814 /* If this is an auto-vacuum database, and not a leaf-data tree,
4815 ** then update the pointer map with an entry for the overflow page
4816 ** that the cell just inserted points to (if any).
4817 */
4818 if( pBt->autoVacuum && !leafData ){
danielk197779a40da2005-01-16 08:00:01 +00004819 rc = ptrmapPutOvfl(pParent, nxDiv);
4820 if( rc!=SQLITE_OK ){
4821 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00004822 }
4823 }
4824#endif
drh14acc042001-06-10 19:56:58 +00004825 j++;
4826 nxDiv++;
4827 }
4828 }
drh6019e162001-07-02 17:51:45 +00004829 assert( j==nCell );
drh7aa8f852006-03-28 00:24:44 +00004830 assert( nOld>0 );
4831 assert( nNew>0 );
drh4b70f112004-05-02 21:12:19 +00004832 if( (pageFlags & PTF_LEAF)==0 ){
drh43605152004-05-29 21:46:49 +00004833 memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
drh14acc042001-06-10 19:56:58 +00004834 }
drh43605152004-05-29 21:46:49 +00004835 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00004836 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00004837 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00004838 }else{
4839 /* Right-most sibling is the left child of the first entry in pParent
4840 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00004841 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00004842 }
4843
4844 /*
4845 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00004846 */
4847 for(i=0; i<nNew; i++){
danielk1977afcdd022004-10-31 16:25:42 +00004848 rc = reparentChildPages(apNew[i]);
4849 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004850 }
danielk1977afcdd022004-10-31 16:25:42 +00004851 rc = reparentChildPages(pParent);
4852 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004853
4854 /*
drh3a4c1412004-05-09 20:40:11 +00004855 ** Balance the parent page. Note that the current page (pPage) might
danielk1977ac11ee62005-01-15 12:45:51 +00004856 ** have been added to the freelist so it might no longer be initialized.
drh3a4c1412004-05-09 20:40:11 +00004857 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00004858 */
drhda200cc2004-05-09 11:51:38 +00004859 assert( pParent->isInit );
danielk1977ac245ec2005-01-14 13:50:11 +00004860 rc = balance(pParent, 0);
drhda200cc2004-05-09 11:51:38 +00004861
drh8b2f49b2001-06-08 00:21:52 +00004862 /*
drh14acc042001-06-10 19:56:58 +00004863 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00004864 */
drh14acc042001-06-10 19:56:58 +00004865balance_cleanup:
drh2e38c322004-09-03 18:38:44 +00004866 sqliteFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00004867 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00004868 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00004869 }
drh14acc042001-06-10 19:56:58 +00004870 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00004871 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00004872 }
drh91025292004-05-03 19:49:32 +00004873 releasePage(pParent);
drh3a4c1412004-05-09 20:40:11 +00004874 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
4875 pPage->pgno, nOld, nNew, nCell));
drh8b2f49b2001-06-08 00:21:52 +00004876 return rc;
4877}
4878
4879/*
drh43605152004-05-29 21:46:49 +00004880** This routine is called for the root page of a btree when the root
4881** page contains no cells. This is an opportunity to make the tree
4882** shallower by one level.
4883*/
4884static int balance_shallower(MemPage *pPage){
4885 MemPage *pChild; /* The only child page of pPage */
4886 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00004887 int rc = SQLITE_OK; /* Return code from subprocedures */
danielk1977aef0bf62005-12-30 16:28:01 +00004888 BtShared *pBt; /* The main BTree structure */
drh2e38c322004-09-03 18:38:44 +00004889 int mxCellPerPage; /* Maximum number of cells per page */
4890 u8 **apCell; /* All cells from pages being balanced */
4891 int *szCell; /* Local size of all cells */
drh43605152004-05-29 21:46:49 +00004892
4893 assert( pPage->pParent==0 );
4894 assert( pPage->nCell==0 );
drh2e38c322004-09-03 18:38:44 +00004895 pBt = pPage->pBt;
4896 mxCellPerPage = MX_CELL(pBt);
4897 apCell = sqliteMallocRaw( mxCellPerPage*(sizeof(u8*)+sizeof(int)) );
4898 if( apCell==0 ) return SQLITE_NOMEM;
4899 szCell = (int*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00004900 if( pPage->leaf ){
4901 /* The table is completely empty */
4902 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
4903 }else{
4904 /* The root page is empty but has one child. Transfer the
4905 ** information from that one child into the root page if it
4906 ** will fit. This reduces the depth of the tree by one.
4907 **
4908 ** If the root page is page 1, it has less space available than
4909 ** its child (due to the 100 byte header that occurs at the beginning
4910 ** of the database fle), so it might not be able to hold all of the
4911 ** information currently contained in the child. If this is the
4912 ** case, then do not do the transfer. Leave page 1 empty except
4913 ** for the right-pointer to the child page. The child page becomes
4914 ** the virtual root of the tree.
4915 */
4916 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
4917 assert( pgnoChild>0 );
danielk19773b8a05f2007-03-19 17:44:26 +00004918 assert( pgnoChild<=sqlite3PagerPagecount(pPage->pBt->pPager) );
drh16a9b832007-05-05 18:39:25 +00004919 rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
drh2e38c322004-09-03 18:38:44 +00004920 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004921 if( pPage->pgno==1 ){
drh16a9b832007-05-05 18:39:25 +00004922 rc = sqlite3BtreeInitPage(pChild, pPage);
drh2e38c322004-09-03 18:38:44 +00004923 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004924 assert( pChild->nOverflow==0 );
4925 if( pChild->nFree>=100 ){
4926 /* The child information will fit on the root page, so do the
4927 ** copy */
4928 int i;
4929 zeroPage(pPage, pChild->aData[0]);
4930 for(i=0; i<pChild->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00004931 apCell[i] = findCell(pChild,i);
drh43605152004-05-29 21:46:49 +00004932 szCell[i] = cellSizePtr(pChild, apCell[i]);
4933 }
4934 assemblePage(pPage, pChild->nCell, apCell, szCell);
danielk1977ae825582004-11-23 09:06:55 +00004935 /* Copy the right-pointer of the child to the parent. */
4936 put4byte(&pPage->aData[pPage->hdrOffset+8],
4937 get4byte(&pChild->aData[pChild->hdrOffset+8]));
drh43605152004-05-29 21:46:49 +00004938 freePage(pChild);
4939 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
4940 }else{
4941 /* The child has more information that will fit on the root.
4942 ** The tree is already balanced. Do nothing. */
4943 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
4944 }
4945 }else{
4946 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
4947 pPage->isInit = 0;
4948 pPage->pParent = 0;
drh16a9b832007-05-05 18:39:25 +00004949 rc = sqlite3BtreeInitPage(pPage, 0);
drh43605152004-05-29 21:46:49 +00004950 assert( rc==SQLITE_OK );
4951 freePage(pChild);
4952 TRACE(("BALANCE: transfer child %d into root %d\n",
4953 pChild->pgno, pPage->pgno));
4954 }
danielk1977afcdd022004-10-31 16:25:42 +00004955 rc = reparentChildPages(pPage);
danielk1977ac11ee62005-01-15 12:45:51 +00004956 assert( pPage->nOverflow==0 );
4957#ifndef SQLITE_OMIT_AUTOVACUUM
4958 if( pBt->autoVacuum ){
danielk1977aac0a382005-01-16 11:07:06 +00004959 int i;
danielk1977ac11ee62005-01-15 12:45:51 +00004960 for(i=0; i<pPage->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00004961 rc = ptrmapPutOvfl(pPage, i);
4962 if( rc!=SQLITE_OK ){
4963 goto end_shallow_balance;
danielk1977ac11ee62005-01-15 12:45:51 +00004964 }
4965 }
4966 }
4967#endif
danielk1977afcdd022004-10-31 16:25:42 +00004968 if( rc!=SQLITE_OK ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004969 releasePage(pChild);
4970 }
drh2e38c322004-09-03 18:38:44 +00004971end_shallow_balance:
4972 sqliteFree(apCell);
4973 return rc;
drh43605152004-05-29 21:46:49 +00004974}
4975
4976
4977/*
4978** The root page is overfull
4979**
4980** When this happens, Create a new child page and copy the
4981** contents of the root into the child. Then make the root
4982** page an empty page with rightChild pointing to the new
4983** child. Finally, call balance_internal() on the new child
4984** to cause it to split.
4985*/
4986static int balance_deeper(MemPage *pPage){
4987 int rc; /* Return value from subprocedures */
4988 MemPage *pChild; /* Pointer to a new child page */
4989 Pgno pgnoChild; /* Page number of the new child page */
danielk1977aef0bf62005-12-30 16:28:01 +00004990 BtShared *pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00004991 int usableSize; /* Total usable size of a page */
4992 u8 *data; /* Content of the parent page */
4993 u8 *cdata; /* Content of the child page */
4994 int hdr; /* Offset to page header in parent */
4995 int brk; /* Offset to content of first cell in parent */
4996
4997 assert( pPage->pParent==0 );
4998 assert( pPage->nOverflow>0 );
4999 pBt = pPage->pBt;
drh4f0c5872007-03-26 22:05:01 +00005000 rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
drh43605152004-05-29 21:46:49 +00005001 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00005002 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
drh43605152004-05-29 21:46:49 +00005003 usableSize = pBt->usableSize;
5004 data = pPage->aData;
5005 hdr = pPage->hdrOffset;
5006 brk = get2byte(&data[hdr+5]);
5007 cdata = pChild->aData;
5008 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
5009 memcpy(&cdata[brk], &data[brk], usableSize-brk);
danielk1977c7dc7532004-11-17 10:22:03 +00005010 assert( pChild->isInit==0 );
drh16a9b832007-05-05 18:39:25 +00005011 rc = sqlite3BtreeInitPage(pChild, pPage);
danielk19776b456a22005-03-21 04:04:02 +00005012 if( rc ) goto balancedeeper_out;
drh43605152004-05-29 21:46:49 +00005013 memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
5014 pChild->nOverflow = pPage->nOverflow;
5015 if( pChild->nOverflow ){
5016 pChild->nFree = 0;
5017 }
5018 assert( pChild->nCell==pPage->nCell );
5019 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
5020 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
5021 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
danielk19774e17d142005-01-16 09:06:33 +00005022#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00005023 if( pBt->autoVacuum ){
5024 int i;
5025 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
danielk19776b456a22005-03-21 04:04:02 +00005026 if( rc ) goto balancedeeper_out;
danielk1977ac11ee62005-01-15 12:45:51 +00005027 for(i=0; i<pChild->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00005028 rc = ptrmapPutOvfl(pChild, i);
5029 if( rc!=SQLITE_OK ){
5030 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00005031 }
5032 }
5033 }
danielk19774e17d142005-01-16 09:06:33 +00005034#endif
drh43605152004-05-29 21:46:49 +00005035 rc = balance_nonroot(pChild);
danielk19776b456a22005-03-21 04:04:02 +00005036
5037balancedeeper_out:
drh43605152004-05-29 21:46:49 +00005038 releasePage(pChild);
5039 return rc;
5040}
5041
5042/*
5043** Decide if the page pPage needs to be balanced. If balancing is
5044** required, call the appropriate balancing routine.
5045*/
danielk1977ac245ec2005-01-14 13:50:11 +00005046static int balance(MemPage *pPage, int insert){
drh43605152004-05-29 21:46:49 +00005047 int rc = SQLITE_OK;
5048 if( pPage->pParent==0 ){
5049 if( pPage->nOverflow>0 ){
5050 rc = balance_deeper(pPage);
5051 }
danielk1977687566d2004-11-02 12:56:41 +00005052 if( rc==SQLITE_OK && pPage->nCell==0 ){
drh43605152004-05-29 21:46:49 +00005053 rc = balance_shallower(pPage);
5054 }
5055 }else{
danielk1977ac245ec2005-01-14 13:50:11 +00005056 if( pPage->nOverflow>0 ||
5057 (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
drh43605152004-05-29 21:46:49 +00005058 rc = balance_nonroot(pPage);
5059 }
5060 }
5061 return rc;
5062}
5063
5064/*
drh8dcd7ca2004-08-08 19:43:29 +00005065** This routine checks all cursors that point to table pgnoRoot.
drh980b1a72006-08-16 16:42:48 +00005066** If any of those cursors were opened with wrFlag==0 in a different
5067** database connection (a database connection that shares the pager
5068** cache with the current connection) and that other connection
5069** is not in the ReadUncommmitted state, then this routine returns
5070** SQLITE_LOCKED.
danielk1977299b1872004-11-22 10:02:10 +00005071**
5072** In addition to checking for read-locks (where a read-lock
5073** means a cursor opened with wrFlag==0) this routine also moves
drh16a9b832007-05-05 18:39:25 +00005074** all write cursors so that they are pointing to the
drh980b1a72006-08-16 16:42:48 +00005075** first Cell on the root page. This is necessary because an insert
danielk1977299b1872004-11-22 10:02:10 +00005076** or delete might change the number of cells on a page or delete
5077** a page entirely and we do not want to leave any cursors
5078** pointing to non-existant pages or cells.
drhf74b8d92002-09-01 23:20:45 +00005079*/
drh980b1a72006-08-16 16:42:48 +00005080static int checkReadLocks(Btree *pBtree, Pgno pgnoRoot, BtCursor *pExclude){
danielk1977299b1872004-11-22 10:02:10 +00005081 BtCursor *p;
drh980b1a72006-08-16 16:42:48 +00005082 BtShared *pBt = pBtree->pBt;
5083 sqlite3 *db = pBtree->pSqlite;
danielk1977299b1872004-11-22 10:02:10 +00005084 for(p=pBt->pCursor; p; p=p->pNext){
drh980b1a72006-08-16 16:42:48 +00005085 if( p==pExclude ) continue;
5086 if( p->eState!=CURSOR_VALID ) continue;
5087 if( p->pgnoRoot!=pgnoRoot ) continue;
5088 if( p->wrFlag==0 ){
5089 sqlite3 *dbOther = p->pBtree->pSqlite;
5090 if( dbOther==0 ||
5091 (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
5092 return SQLITE_LOCKED;
5093 }
5094 }else if( p->pPage->pgno!=p->pgnoRoot ){
danielk1977299b1872004-11-22 10:02:10 +00005095 moveToRoot(p);
5096 }
5097 }
drhf74b8d92002-09-01 23:20:45 +00005098 return SQLITE_OK;
5099}
5100
5101/*
drh3b7511c2001-05-26 13:15:44 +00005102** Insert a new record into the BTree. The key is given by (pKey,nKey)
5103** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00005104** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00005105** is left pointing at a random location.
5106**
5107** For an INTKEY table, only the nKey value of the key is used. pKey is
5108** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00005109*/
drh3aac2dd2004-04-26 14:10:20 +00005110int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00005111 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00005112 const void *pKey, i64 nKey, /* The key of the new record */
drhe4d90812007-03-29 05:51:49 +00005113 const void *pData, int nData, /* The data of the new record */
drhb026e052007-05-02 01:34:31 +00005114 int nZero, /* Number of extra 0 bytes to append to data */
drhe4d90812007-03-29 05:51:49 +00005115 int appendBias /* True if this is likely an append */
drh3b7511c2001-05-26 13:15:44 +00005116){
drh3b7511c2001-05-26 13:15:44 +00005117 int rc;
5118 int loc;
drh14acc042001-06-10 19:56:58 +00005119 int szNew;
drh3b7511c2001-05-26 13:15:44 +00005120 MemPage *pPage;
danielk1977aef0bf62005-12-30 16:28:01 +00005121 BtShared *pBt = pCur->pBtree->pBt;
drha34b6762004-05-07 13:30:42 +00005122 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00005123 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00005124
danielk1977aef0bf62005-12-30 16:28:01 +00005125 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005126 /* Must start a transaction before doing an insert */
5127 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005128 }
drhf74b8d92002-09-01 23:20:45 +00005129 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00005130 if( !pCur->wrFlag ){
5131 return SQLITE_PERM; /* Cursor not open for writing */
5132 }
drh980b1a72006-08-16 16:42:48 +00005133 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00005134 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5135 }
danielk1977da184232006-01-05 11:34:32 +00005136
5137 /* Save the positions of any other cursors open on this table */
drhbf700f32007-03-31 02:36:44 +00005138 clearCursorPosition(pCur);
danielk19772e94d4d2006-01-09 05:36:27 +00005139 if(
danielk19772e94d4d2006-01-09 05:36:27 +00005140 SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
drhe4d90812007-03-29 05:51:49 +00005141 SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
danielk19772e94d4d2006-01-09 05:36:27 +00005142 ){
danielk1977da184232006-01-05 11:34:32 +00005143 return rc;
5144 }
5145
drh14acc042001-06-10 19:56:58 +00005146 pPage = pCur->pPage;
drh4a1c3802004-05-12 15:15:47 +00005147 assert( pPage->intKey || nKey>=0 );
drh8b18dd42004-05-12 19:18:15 +00005148 assert( pPage->leaf || !pPage->leafData );
drh3a4c1412004-05-09 20:40:11 +00005149 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
5150 pCur->pgnoRoot, nKey, nData, pPage->pgno,
5151 loc==0 ? "overwrite" : "new entry"));
drh7aa128d2002-06-21 13:09:16 +00005152 assert( pPage->isInit );
danielk19773b8a05f2007-03-19 17:44:26 +00005153 rc = sqlite3PagerWrite(pPage->pDbPage);
drhbd03cae2001-06-02 02:40:57 +00005154 if( rc ) return rc;
drh2e38c322004-09-03 18:38:44 +00005155 newCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
5156 if( newCell==0 ) return SQLITE_NOMEM;
drhb026e052007-05-02 01:34:31 +00005157 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
drh2e38c322004-09-03 18:38:44 +00005158 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00005159 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00005160 assert( szNew<=MX_CELL_SIZE(pBt) );
danielk1977da184232006-01-05 11:34:32 +00005161 if( loc==0 && CURSOR_VALID==pCur->eState ){
drha34b6762004-05-07 13:30:42 +00005162 int szOld;
5163 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
danielk19771cc5ed82007-05-16 17:28:43 +00005164 oldCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00005165 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005166 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00005167 }
drh43605152004-05-29 21:46:49 +00005168 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00005169 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00005170 if( rc ) goto end_insert;
drh4b70f112004-05-02 21:12:19 +00005171 dropCell(pPage, pCur->idx, szOld);
drh7c717f72001-06-24 20:39:41 +00005172 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00005173 assert( pPage->leaf );
drh14acc042001-06-10 19:56:58 +00005174 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00005175 pCur->info.nSize = 0;
drh14acc042001-06-10 19:56:58 +00005176 }else{
drh4b70f112004-05-02 21:12:19 +00005177 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00005178 }
danielk1977a3ad5e72005-01-07 08:56:44 +00005179 rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
danielk1977e80463b2004-11-03 03:01:16 +00005180 if( rc!=SQLITE_OK ) goto end_insert;
danielk1977ac245ec2005-01-14 13:50:11 +00005181 rc = balance(pPage, 1);
drh23e11ca2004-05-04 17:27:28 +00005182 /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
drh3fc190c2001-09-14 03:24:23 +00005183 /* fflush(stdout); */
danielk1977299b1872004-11-22 10:02:10 +00005184 if( rc==SQLITE_OK ){
5185 moveToRoot(pCur);
5186 }
drh2e38c322004-09-03 18:38:44 +00005187end_insert:
5188 sqliteFree(newCell);
drh5e2f8b92001-05-28 00:41:15 +00005189 return rc;
5190}
5191
5192/*
drh4b70f112004-05-02 21:12:19 +00005193** Delete the entry that the cursor is pointing to. The cursor
5194** is left pointing at a random location.
drh3b7511c2001-05-26 13:15:44 +00005195*/
drh3aac2dd2004-04-26 14:10:20 +00005196int sqlite3BtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00005197 MemPage *pPage = pCur->pPage;
drh4b70f112004-05-02 21:12:19 +00005198 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00005199 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00005200 Pgno pgnoChild = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00005201 BtShared *pBt = pCur->pBtree->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005202
drh7aa128d2002-06-21 13:09:16 +00005203 assert( pPage->isInit );
danielk1977aef0bf62005-12-30 16:28:01 +00005204 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005205 /* Must start a transaction before doing a delete */
5206 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005207 }
drhf74b8d92002-09-01 23:20:45 +00005208 assert( !pBt->readOnly );
drhbd03cae2001-06-02 02:40:57 +00005209 if( pCur->idx >= pPage->nCell ){
5210 return SQLITE_ERROR; /* The cursor is not pointing to anything */
5211 }
drhecdc7532001-09-23 02:35:53 +00005212 if( !pCur->wrFlag ){
5213 return SQLITE_PERM; /* Did not open this cursor for writing */
5214 }
drh980b1a72006-08-16 16:42:48 +00005215 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00005216 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5217 }
danielk1977da184232006-01-05 11:34:32 +00005218
5219 /* Restore the current cursor position (a no-op if the cursor is not in
5220 ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors
danielk19773b8a05f2007-03-19 17:44:26 +00005221 ** open on the same table. Then call sqlite3PagerWrite() on the page
danielk1977da184232006-01-05 11:34:32 +00005222 ** that the entry will be deleted from.
5223 */
5224 if(
drhbf700f32007-03-31 02:36:44 +00005225 (rc = restoreOrClearCursorPosition(pCur))!=0 ||
drhd1167392006-01-23 13:00:35 +00005226 (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
danielk19773b8a05f2007-03-19 17:44:26 +00005227 (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
danielk1977da184232006-01-05 11:34:32 +00005228 ){
5229 return rc;
5230 }
danielk1977e6efa742004-11-10 11:55:10 +00005231
5232 /* Locate the cell within it's page and leave pCell pointing to the
5233 ** data. The clearCell() call frees any overflow pages associated with the
5234 ** cell. The cell itself is still intact.
5235 */
danielk19771cc5ed82007-05-16 17:28:43 +00005236 pCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00005237 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005238 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005239 }
danielk197728129562005-01-11 10:25:06 +00005240 rc = clearCell(pPage, pCell);
5241 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00005242
drh4b70f112004-05-02 21:12:19 +00005243 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00005244 /*
drh5e00f6c2001-09-13 13:46:56 +00005245 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00005246 ** do something we will leave a hole on an internal page.
5247 ** We have to fill the hole by moving in a cell from a leaf. The
5248 ** next Cell after the one to be deleted is guaranteed to exist and
danielk1977299b1872004-11-22 10:02:10 +00005249 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00005250 */
drh14acc042001-06-10 19:56:58 +00005251 BtCursor leafCur;
drh4b70f112004-05-02 21:12:19 +00005252 unsigned char *pNext;
drh02afc862006-01-20 18:10:57 +00005253 int szNext; /* The compiler warning is wrong: szNext is always
5254 ** initialized before use. Adding an extra initialization
5255 ** to silence the compiler slows down the code. */
danielk1977299b1872004-11-22 10:02:10 +00005256 int notUsed;
danielk19776b456a22005-03-21 04:04:02 +00005257 unsigned char *tempCell = 0;
drh8b18dd42004-05-12 19:18:15 +00005258 assert( !pPage->leafData );
drh16a9b832007-05-05 18:39:25 +00005259 sqlite3BtreeGetTempCursor(pCur, &leafCur);
danielk1977299b1872004-11-22 10:02:10 +00005260 rc = sqlite3BtreeNext(&leafCur, &notUsed);
danielk19776b456a22005-03-21 04:04:02 +00005261 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00005262 rc = sqlite3PagerWrite(leafCur.pPage->pDbPage);
danielk19776b456a22005-03-21 04:04:02 +00005263 }
5264 if( rc==SQLITE_OK ){
5265 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
5266 pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
5267 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
danielk19771cc5ed82007-05-16 17:28:43 +00005268 pNext = findCell(leafCur.pPage, leafCur.idx);
danielk19776b456a22005-03-21 04:04:02 +00005269 szNext = cellSizePtr(leafCur.pPage, pNext);
5270 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
5271 tempCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
5272 if( tempCell==0 ){
5273 rc = SQLITE_NOMEM;
5274 }
5275 }
5276 if( rc==SQLITE_OK ){
5277 rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
5278 }
5279 if( rc==SQLITE_OK ){
5280 put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
5281 rc = balance(pPage, 0);
5282 }
5283 if( rc==SQLITE_OK ){
5284 dropCell(leafCur.pPage, leafCur.idx, szNext);
5285 rc = balance(leafCur.pPage, 0);
5286 }
drh2e38c322004-09-03 18:38:44 +00005287 sqliteFree(tempCell);
drh16a9b832007-05-05 18:39:25 +00005288 sqlite3BtreeReleaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00005289 }else{
danielk1977299b1872004-11-22 10:02:10 +00005290 TRACE(("DELETE: table=%d delete from leaf %d\n",
5291 pCur->pgnoRoot, pPage->pgno));
5292 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
danielk1977ac245ec2005-01-14 13:50:11 +00005293 rc = balance(pPage, 0);
drh5e2f8b92001-05-28 00:41:15 +00005294 }
danielk19776b456a22005-03-21 04:04:02 +00005295 if( rc==SQLITE_OK ){
5296 moveToRoot(pCur);
5297 }
drh5e2f8b92001-05-28 00:41:15 +00005298 return rc;
drh3b7511c2001-05-26 13:15:44 +00005299}
drh8b2f49b2001-06-08 00:21:52 +00005300
5301/*
drhc6b52df2002-01-04 03:09:29 +00005302** Create a new BTree table. Write into *piTable the page
5303** number for the root page of the new table.
5304**
drhab01f612004-05-22 02:55:23 +00005305** The type of type is determined by the flags parameter. Only the
5306** following values of flags are currently in use. Other values for
5307** flags might not work:
5308**
5309** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
5310** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00005311*/
danielk1977aef0bf62005-12-30 16:28:01 +00005312int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
5313 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005314 MemPage *pRoot;
5315 Pgno pgnoRoot;
5316 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00005317 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005318 /* Must start a transaction first */
5319 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005320 }
danielk197728129562005-01-11 10:25:06 +00005321 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00005322
danielk1977003ba062004-11-04 02:57:33 +00005323#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00005324 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drh8b2f49b2001-06-08 00:21:52 +00005325 if( rc ) return rc;
danielk1977003ba062004-11-04 02:57:33 +00005326#else
danielk1977687566d2004-11-02 12:56:41 +00005327 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00005328 Pgno pgnoMove; /* Move a page here to make room for the root-page */
5329 MemPage *pPageMove; /* The page to move to. */
5330
danielk197720713f32007-05-03 11:43:33 +00005331 /* Creating a new table may probably require moving an existing database
5332 ** to make room for the new tables root page. In case this page turns
5333 ** out to be an overflow page, delete all overflow page-map caches
5334 ** held by open cursors.
5335 */
danielk197792d4d7a2007-05-04 12:05:56 +00005336 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00005337
danielk1977003ba062004-11-04 02:57:33 +00005338 /* Read the value of meta[3] from the database to determine where the
5339 ** root page of the new table should go. meta[3] is the largest root-page
5340 ** created so far, so the new root-page is (meta[3]+1).
5341 */
danielk1977aef0bf62005-12-30 16:28:01 +00005342 rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00005343 if( rc!=SQLITE_OK ) return rc;
5344 pgnoRoot++;
5345
danielk1977599fcba2004-11-08 07:13:13 +00005346 /* The new root-page may not be allocated on a pointer-map page, or the
5347 ** PENDING_BYTE page.
5348 */
danielk1977266664d2006-02-10 08:24:21 +00005349 if( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00005350 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00005351 pgnoRoot++;
5352 }
5353 assert( pgnoRoot>=3 );
5354
5355 /* Allocate a page. The page that currently resides at pgnoRoot will
5356 ** be moved to the allocated page (unless the allocated page happens
5357 ** to reside at pgnoRoot).
5358 */
drh4f0c5872007-03-26 22:05:01 +00005359 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00005360 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00005361 return rc;
5362 }
danielk1977003ba062004-11-04 02:57:33 +00005363
5364 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00005365 /* pgnoRoot is the page that will be used for the root-page of
5366 ** the new table (assuming an error did not occur). But we were
5367 ** allocated pgnoMove. If required (i.e. if it was not allocated
5368 ** by extending the file), the current page at position pgnoMove
5369 ** is already journaled.
5370 */
danielk1977003ba062004-11-04 02:57:33 +00005371 u8 eType;
5372 Pgno iPtrPage;
5373
5374 releasePage(pPageMove);
danielk1977f35843b2007-04-07 15:03:17 +00005375
5376 /* Move the page currently at pgnoRoot to pgnoMove. */
drh16a9b832007-05-05 18:39:25 +00005377 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00005378 if( rc!=SQLITE_OK ){
5379 return rc;
5380 }
5381 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drhccae6022005-02-26 17:31:26 +00005382 if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00005383 releasePage(pRoot);
5384 return rc;
5385 }
drhccae6022005-02-26 17:31:26 +00005386 assert( eType!=PTRMAP_ROOTPAGE );
5387 assert( eType!=PTRMAP_FREEPAGE );
danielk19773b8a05f2007-03-19 17:44:26 +00005388 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk19775fd057a2005-03-09 13:09:43 +00005389 if( rc!=SQLITE_OK ){
5390 releasePage(pRoot);
5391 return rc;
5392 }
danielk1977003ba062004-11-04 02:57:33 +00005393 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove);
5394 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00005395
5396 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00005397 if( rc!=SQLITE_OK ){
5398 return rc;
5399 }
drh16a9b832007-05-05 18:39:25 +00005400 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00005401 if( rc!=SQLITE_OK ){
5402 return rc;
5403 }
danielk19773b8a05f2007-03-19 17:44:26 +00005404 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00005405 if( rc!=SQLITE_OK ){
5406 releasePage(pRoot);
5407 return rc;
5408 }
5409 }else{
5410 pRoot = pPageMove;
5411 }
5412
danielk197742741be2005-01-08 12:42:39 +00005413 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00005414 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
5415 if( rc ){
5416 releasePage(pRoot);
5417 return rc;
5418 }
danielk1977aef0bf62005-12-30 16:28:01 +00005419 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00005420 if( rc ){
5421 releasePage(pRoot);
5422 return rc;
5423 }
danielk197742741be2005-01-08 12:42:39 +00005424
danielk1977003ba062004-11-04 02:57:33 +00005425 }else{
drh4f0c5872007-03-26 22:05:01 +00005426 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00005427 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00005428 }
5429#endif
danielk19773b8a05f2007-03-19 17:44:26 +00005430 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhde647132004-05-07 17:57:49 +00005431 zeroPage(pRoot, flags | PTF_LEAF);
danielk19773b8a05f2007-03-19 17:44:26 +00005432 sqlite3PagerUnref(pRoot->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00005433 *piTable = (int)pgnoRoot;
5434 return SQLITE_OK;
5435}
5436
5437/*
5438** Erase the given database page and all its children. Return
5439** the page to the freelist.
5440*/
drh4b70f112004-05-02 21:12:19 +00005441static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00005442 BtShared *pBt, /* The BTree that contains the table */
drh4b70f112004-05-02 21:12:19 +00005443 Pgno pgno, /* Page number to clear */
5444 MemPage *pParent, /* Parent page. NULL for the root */
5445 int freePageFlag /* Deallocate page if true */
5446){
danielk19776b456a22005-03-21 04:04:02 +00005447 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00005448 int rc;
drh4b70f112004-05-02 21:12:19 +00005449 unsigned char *pCell;
5450 int i;
drh8b2f49b2001-06-08 00:21:52 +00005451
danielk19773b8a05f2007-03-19 17:44:26 +00005452 if( pgno>sqlite3PagerPagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00005453 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00005454 }
5455
drhde647132004-05-07 17:57:49 +00005456 rc = getAndInitPage(pBt, pgno, &pPage, pParent);
danielk19776b456a22005-03-21 04:04:02 +00005457 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00005458 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00005459 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00005460 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005461 rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00005462 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00005463 }
drh4b70f112004-05-02 21:12:19 +00005464 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00005465 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00005466 }
drha34b6762004-05-07 13:30:42 +00005467 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005468 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00005469 if( rc ) goto cleardatabasepage_out;
drh2aa679f2001-06-25 02:11:07 +00005470 }
5471 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00005472 rc = freePage(pPage);
danielk19773b8a05f2007-03-19 17:44:26 +00005473 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
drh3a4c1412004-05-09 20:40:11 +00005474 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00005475 }
danielk19776b456a22005-03-21 04:04:02 +00005476
5477cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00005478 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00005479 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005480}
5481
5482/*
drhab01f612004-05-22 02:55:23 +00005483** Delete all information from a single table in the database. iTable is
5484** the page number of the root of the table. After this routine returns,
5485** the root page is empty, but still exists.
5486**
5487** This routine will fail with SQLITE_LOCKED if there are any open
5488** read cursors on the table. Open write cursors are moved to the
5489** root of the table.
drh8b2f49b2001-06-08 00:21:52 +00005490*/
danielk1977aef0bf62005-12-30 16:28:01 +00005491int sqlite3BtreeClearTable(Btree *p, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00005492 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00005493 BtShared *pBt = p->pBt;
5494 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005495 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005496 }
drh980b1a72006-08-16 16:42:48 +00005497 rc = checkReadLocks(p, iTable, 0);
5498 if( rc ){
5499 return rc;
drhecdc7532001-09-23 02:35:53 +00005500 }
danielk1977ed429312006-01-19 08:43:31 +00005501
5502 /* Save the position of all cursors open on this table */
5503 if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
5504 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005505 }
danielk1977ed429312006-01-19 08:43:31 +00005506
5507 return clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
drh8b2f49b2001-06-08 00:21:52 +00005508}
5509
5510/*
5511** Erase all information in a table and add the root of the table to
5512** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00005513** page 1) is never added to the freelist.
5514**
5515** This routine will fail with SQLITE_LOCKED if there are any open
5516** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00005517**
5518** If AUTOVACUUM is enabled and the page at iTable is not the last
5519** root page in the database file, then the last root page
5520** in the database file is moved into the slot formerly occupied by
5521** iTable and that last slot formerly occupied by the last root page
5522** is added to the freelist instead of iTable. In this say, all
5523** root pages are kept at the beginning of the database file, which
5524** is necessary for AUTOVACUUM to work right. *piMoved is set to the
5525** page number that used to be the last root page in the file before
5526** the move. If no page gets moved, *piMoved is set to 0.
5527** The last root page is recorded in meta[3] and the value of
5528** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00005529*/
danielk1977aef0bf62005-12-30 16:28:01 +00005530int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00005531 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00005532 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00005533 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00005534
danielk1977aef0bf62005-12-30 16:28:01 +00005535 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005536 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005537 }
danielk1977a0bf2652004-11-04 14:30:04 +00005538
danielk1977e6efa742004-11-10 11:55:10 +00005539 /* It is illegal to drop a table if any cursors are open on the
5540 ** database. This is because in auto-vacuum mode the backend may
5541 ** need to move another root-page to fill a gap left by the deleted
5542 ** root page. If an open cursor was using this page a problem would
5543 ** occur.
5544 */
5545 if( pBt->pCursor ){
5546 return SQLITE_LOCKED;
drh5df72a52002-06-06 23:16:05 +00005547 }
danielk1977a0bf2652004-11-04 14:30:04 +00005548
drh16a9b832007-05-05 18:39:25 +00005549 rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00005550 if( rc ) return rc;
danielk1977aef0bf62005-12-30 16:28:01 +00005551 rc = sqlite3BtreeClearTable(p, iTable);
danielk19776b456a22005-03-21 04:04:02 +00005552 if( rc ){
5553 releasePage(pPage);
5554 return rc;
5555 }
danielk1977a0bf2652004-11-04 14:30:04 +00005556
drh205f48e2004-11-05 00:43:11 +00005557 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00005558
drh4b70f112004-05-02 21:12:19 +00005559 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00005560#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00005561 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00005562 releasePage(pPage);
5563#else
5564 if( pBt->autoVacuum ){
5565 Pgno maxRootPgno;
danielk1977aef0bf62005-12-30 16:28:01 +00005566 rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00005567 if( rc!=SQLITE_OK ){
5568 releasePage(pPage);
5569 return rc;
5570 }
5571
5572 if( iTable==maxRootPgno ){
5573 /* If the table being dropped is the table with the largest root-page
5574 ** number in the database, put the root page on the free list.
5575 */
5576 rc = freePage(pPage);
5577 releasePage(pPage);
5578 if( rc!=SQLITE_OK ){
5579 return rc;
5580 }
5581 }else{
5582 /* The table being dropped does not have the largest root-page
5583 ** number in the database. So move the page that does into the
5584 ** gap left by the deleted root-page.
5585 */
5586 MemPage *pMove;
5587 releasePage(pPage);
drh16a9b832007-05-05 18:39:25 +00005588 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00005589 if( rc!=SQLITE_OK ){
5590 return rc;
5591 }
5592 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable);
5593 releasePage(pMove);
5594 if( rc!=SQLITE_OK ){
5595 return rc;
5596 }
drh16a9b832007-05-05 18:39:25 +00005597 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00005598 if( rc!=SQLITE_OK ){
5599 return rc;
5600 }
5601 rc = freePage(pMove);
5602 releasePage(pMove);
5603 if( rc!=SQLITE_OK ){
5604 return rc;
5605 }
5606 *piMoved = maxRootPgno;
5607 }
5608
danielk1977599fcba2004-11-08 07:13:13 +00005609 /* Set the new 'max-root-page' value in the database header. This
5610 ** is the old value less one, less one more if that happens to
5611 ** be a root-page number, less one again if that is the
5612 ** PENDING_BYTE_PAGE.
5613 */
danielk197787a6e732004-11-05 12:58:25 +00005614 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00005615 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
5616 maxRootPgno--;
5617 }
danielk1977266664d2006-02-10 08:24:21 +00005618 if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00005619 maxRootPgno--;
5620 }
danielk1977599fcba2004-11-08 07:13:13 +00005621 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
5622
danielk1977aef0bf62005-12-30 16:28:01 +00005623 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00005624 }else{
5625 rc = freePage(pPage);
5626 releasePage(pPage);
5627 }
5628#endif
drh2aa679f2001-06-25 02:11:07 +00005629 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00005630 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00005631 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00005632 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00005633 }
drh8b2f49b2001-06-08 00:21:52 +00005634 return rc;
5635}
5636
drh001bbcb2003-03-19 03:14:00 +00005637
drh8b2f49b2001-06-08 00:21:52 +00005638/*
drh23e11ca2004-05-04 17:27:28 +00005639** Read the meta-information out of a database file. Meta[0]
5640** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00005641** through meta[15] are available for use by higher layers. Meta[0]
5642** is read-only, the others are read/write.
5643**
5644** The schema layer numbers meta values differently. At the schema
5645** layer (and the SetCookie and ReadCookie opcodes) the number of
5646** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00005647*/
danielk1977aef0bf62005-12-30 16:28:01 +00005648int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
danielk19773b8a05f2007-03-19 17:44:26 +00005649 DbPage *pDbPage;
drh8b2f49b2001-06-08 00:21:52 +00005650 int rc;
drh4b70f112004-05-02 21:12:19 +00005651 unsigned char *pP1;
danielk1977aef0bf62005-12-30 16:28:01 +00005652 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005653
danielk1977da184232006-01-05 11:34:32 +00005654 /* Reading a meta-data value requires a read-lock on page 1 (and hence
5655 ** the sqlite_master table. We grab this lock regardless of whether or
5656 ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
5657 ** 1 is treated as a special case by queryTableLock() and lockTable()).
5658 */
5659 rc = queryTableLock(p, 1, READ_LOCK);
5660 if( rc!=SQLITE_OK ){
5661 return rc;
5662 }
5663
drh23e11ca2004-05-04 17:27:28 +00005664 assert( idx>=0 && idx<=15 );
danielk19773b8a05f2007-03-19 17:44:26 +00005665 rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00005666 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00005667 pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
drh23e11ca2004-05-04 17:27:28 +00005668 *pMeta = get4byte(&pP1[36 + idx*4]);
danielk19773b8a05f2007-03-19 17:44:26 +00005669 sqlite3PagerUnref(pDbPage);
drhae157872004-08-14 19:20:09 +00005670
danielk1977599fcba2004-11-08 07:13:13 +00005671 /* If autovacuumed is disabled in this build but we are trying to
5672 ** access an autovacuumed database, then make the database readonly.
5673 */
danielk1977003ba062004-11-04 02:57:33 +00005674#ifdef SQLITE_OMIT_AUTOVACUUM
drhae157872004-08-14 19:20:09 +00005675 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00005676#endif
drhae157872004-08-14 19:20:09 +00005677
danielk1977da184232006-01-05 11:34:32 +00005678 /* Grab the read-lock on page 1. */
5679 rc = lockTable(p, 1, READ_LOCK);
5680 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005681}
5682
5683/*
drh23e11ca2004-05-04 17:27:28 +00005684** Write meta-information back into the database. Meta[0] is
5685** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00005686*/
danielk1977aef0bf62005-12-30 16:28:01 +00005687int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
5688 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00005689 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00005690 int rc;
drh23e11ca2004-05-04 17:27:28 +00005691 assert( idx>=1 && idx<=15 );
danielk1977aef0bf62005-12-30 16:28:01 +00005692 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005693 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +00005694 }
drhde647132004-05-07 17:57:49 +00005695 assert( pBt->pPage1!=0 );
5696 pP1 = pBt->pPage1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00005697 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
drh4b70f112004-05-02 21:12:19 +00005698 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00005699 put4byte(&pP1[36 + idx*4], iMeta);
danielk197727b1f952007-06-25 08:16:58 +00005700 if( idx==7 ){
5701 assert( pBt->autoVacuum || iMeta==0 );
5702 assert( iMeta==0 || iMeta==1 );
5703 pBt->incrVacuum = iMeta;
5704 }
drh8b2f49b2001-06-08 00:21:52 +00005705 return SQLITE_OK;
5706}
drh8c42ca92001-06-22 19:15:00 +00005707
drhf328bc82004-05-10 23:29:49 +00005708/*
5709** Return the flag byte at the beginning of the page that the cursor
5710** is currently pointing to.
5711*/
5712int sqlite3BtreeFlags(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00005713 /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
drh777e4c42006-01-13 04:31:58 +00005714 ** restoreOrClearCursorPosition() here.
danielk1977da184232006-01-05 11:34:32 +00005715 */
drhf328bc82004-05-10 23:29:49 +00005716 MemPage *pPage = pCur->pPage;
5717 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
5718}
5719
drhdd793422001-06-28 01:54:48 +00005720
drhdd793422001-06-28 01:54:48 +00005721/*
drh5eddca62001-06-30 21:53:53 +00005722** Return the pager associated with a BTree. This routine is used for
5723** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00005724*/
danielk1977aef0bf62005-12-30 16:28:01 +00005725Pager *sqlite3BtreePager(Btree *p){
5726 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00005727}
drh5eddca62001-06-30 21:53:53 +00005728
drhb7f91642004-10-31 02:22:47 +00005729#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005730/*
5731** Append a message to the error message string.
5732*/
drh2e38c322004-09-03 18:38:44 +00005733static void checkAppendMsg(
5734 IntegrityCk *pCheck,
5735 char *zMsg1,
5736 const char *zFormat,
5737 ...
5738){
5739 va_list ap;
5740 char *zMsg2;
drh1dcdbc02007-01-27 02:24:54 +00005741 if( !pCheck->mxErr ) return;
5742 pCheck->mxErr--;
5743 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00005744 va_start(ap, zFormat);
5745 zMsg2 = sqlite3VMPrintf(zFormat, ap);
5746 va_end(ap);
5747 if( zMsg1==0 ) zMsg1 = "";
drh5eddca62001-06-30 21:53:53 +00005748 if( pCheck->zErrMsg ){
5749 char *zOld = pCheck->zErrMsg;
5750 pCheck->zErrMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00005751 sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00005752 sqliteFree(zOld);
5753 }else{
danielk19774adee202004-05-08 08:23:19 +00005754 sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00005755 }
drh2e38c322004-09-03 18:38:44 +00005756 sqliteFree(zMsg2);
drh5eddca62001-06-30 21:53:53 +00005757}
drhb7f91642004-10-31 02:22:47 +00005758#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00005759
drhb7f91642004-10-31 02:22:47 +00005760#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005761/*
5762** Add 1 to the reference count for page iPage. If this is the second
5763** reference to the page, add an error message to pCheck->zErrMsg.
5764** Return 1 if there are 2 ore more references to the page and 0 if
5765** if this is the first reference to the page.
5766**
5767** Also check that the page number is in bounds.
5768*/
drhaaab5722002-02-19 13:39:21 +00005769static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00005770 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00005771 if( iPage>pCheck->nPage || iPage<0 ){
drh2e38c322004-09-03 18:38:44 +00005772 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005773 return 1;
5774 }
5775 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00005776 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005777 return 1;
5778 }
5779 return (pCheck->anRef[iPage]++)>1;
5780}
5781
danielk1977afcdd022004-10-31 16:25:42 +00005782#ifndef SQLITE_OMIT_AUTOVACUUM
5783/*
5784** Check that the entry in the pointer-map for page iChild maps to
5785** page iParent, pointer type ptrType. If not, append an error message
5786** to pCheck.
5787*/
5788static void checkPtrmap(
5789 IntegrityCk *pCheck, /* Integrity check context */
5790 Pgno iChild, /* Child page number */
5791 u8 eType, /* Expected pointer map type */
5792 Pgno iParent, /* Expected pointer map parent page number */
5793 char *zContext /* Context description (used for error msg) */
5794){
5795 int rc;
5796 u8 ePtrmapType;
5797 Pgno iPtrmapParent;
5798
5799 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
5800 if( rc!=SQLITE_OK ){
5801 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
5802 return;
5803 }
5804
5805 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
5806 checkAppendMsg(pCheck, zContext,
5807 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
5808 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
5809 }
5810}
5811#endif
5812
drh5eddca62001-06-30 21:53:53 +00005813/*
5814** Check the integrity of the freelist or of an overflow page list.
5815** Verify that the number of pages on the list is N.
5816*/
drh30e58752002-03-02 20:41:57 +00005817static void checkList(
5818 IntegrityCk *pCheck, /* Integrity checking context */
5819 int isFreeList, /* True for a freelist. False for overflow page list */
5820 int iPage, /* Page number for first page in the list */
5821 int N, /* Expected number of pages in the list */
5822 char *zContext /* Context for error messages */
5823){
5824 int i;
drh3a4c1412004-05-09 20:40:11 +00005825 int expected = N;
5826 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00005827 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00005828 DbPage *pOvflPage;
5829 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00005830 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00005831 checkAppendMsg(pCheck, zContext,
5832 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00005833 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00005834 break;
5835 }
5836 if( checkRef(pCheck, iPage, zContext) ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00005837 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
drh2e38c322004-09-03 18:38:44 +00005838 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005839 break;
5840 }
danielk19773b8a05f2007-03-19 17:44:26 +00005841 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00005842 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00005843 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00005844#ifndef SQLITE_OMIT_AUTOVACUUM
5845 if( pCheck->pBt->autoVacuum ){
5846 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
5847 }
5848#endif
drh855eb1c2004-08-31 13:45:11 +00005849 if( n>pCheck->pBt->usableSize/4-8 ){
drh2e38c322004-09-03 18:38:44 +00005850 checkAppendMsg(pCheck, zContext,
5851 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00005852 N--;
5853 }else{
5854 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00005855 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00005856#ifndef SQLITE_OMIT_AUTOVACUUM
5857 if( pCheck->pBt->autoVacuum ){
5858 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
5859 }
5860#endif
5861 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00005862 }
5863 N -= n;
drh30e58752002-03-02 20:41:57 +00005864 }
drh30e58752002-03-02 20:41:57 +00005865 }
danielk1977afcdd022004-10-31 16:25:42 +00005866#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00005867 else{
5868 /* If this database supports auto-vacuum and iPage is not the last
5869 ** page in this overflow list, check that the pointer-map entry for
5870 ** the following page matches iPage.
5871 */
5872 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00005873 i = get4byte(pOvflData);
danielk1977687566d2004-11-02 12:56:41 +00005874 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
5875 }
danielk1977afcdd022004-10-31 16:25:42 +00005876 }
5877#endif
danielk19773b8a05f2007-03-19 17:44:26 +00005878 iPage = get4byte(pOvflData);
5879 sqlite3PagerUnref(pOvflPage);
drh5eddca62001-06-30 21:53:53 +00005880 }
5881}
drhb7f91642004-10-31 02:22:47 +00005882#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00005883
drhb7f91642004-10-31 02:22:47 +00005884#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005885/*
5886** Do various sanity checks on a single page of a tree. Return
5887** the tree depth. Root pages return 0. Parents of root pages
5888** return 1, and so forth.
5889**
5890** These checks are done:
5891**
5892** 1. Make sure that cells and freeblocks do not overlap
5893** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00005894** NO 2. Make sure cell keys are in order.
5895** NO 3. Make sure no key is less than or equal to zLowerBound.
5896** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00005897** 5. Check the integrity of overflow pages.
5898** 6. Recursively call checkTreePage on all children.
5899** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00005900** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00005901** the root of the tree.
5902*/
5903static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00005904 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00005905 int iPage, /* Page number of the page to check */
5906 MemPage *pParent, /* Parent page */
drh74161702006-02-24 02:53:49 +00005907 char *zParentContext /* Parent context */
drh5eddca62001-06-30 21:53:53 +00005908){
5909 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00005910 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00005911 int hdr, cellStart;
5912 int nCell;
drhda200cc2004-05-09 11:51:38 +00005913 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00005914 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00005915 int usableSize;
drh5eddca62001-06-30 21:53:53 +00005916 char zContext[100];
drh2e38c322004-09-03 18:38:44 +00005917 char *hit;
drh5eddca62001-06-30 21:53:53 +00005918
drh5bb3eb92007-05-04 13:15:55 +00005919 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
danielk1977ef73ee92004-11-06 12:26:07 +00005920
drh5eddca62001-06-30 21:53:53 +00005921 /* Check that the page exists
5922 */
drhd9cb6ac2005-10-20 07:28:17 +00005923 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00005924 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00005925 if( iPage==0 ) return 0;
5926 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh16a9b832007-05-05 18:39:25 +00005927 if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drh2e38c322004-09-03 18:38:44 +00005928 checkAppendMsg(pCheck, zContext,
5929 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00005930 return 0;
5931 }
drh16a9b832007-05-05 18:39:25 +00005932 if( (rc = sqlite3BtreeInitPage(pPage, pParent))!=0 ){
5933 checkAppendMsg(pCheck, zContext,
5934 "sqlite3BtreeInitPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00005935 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00005936 return 0;
5937 }
5938
5939 /* Check out all the cells.
5940 */
5941 depth = 0;
drh1dcdbc02007-01-27 02:24:54 +00005942 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
drh6f11bef2004-05-13 01:12:56 +00005943 u8 *pCell;
5944 int sz;
5945 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00005946
5947 /* Check payload overflow pages
5948 */
drh5bb3eb92007-05-04 13:15:55 +00005949 sqlite3_snprintf(sizeof(zContext), zContext,
5950 "On tree page %d cell %d: ", iPage, i);
danielk19771cc5ed82007-05-16 17:28:43 +00005951 pCell = findCell(pPage,i);
drh16a9b832007-05-05 18:39:25 +00005952 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005953 sz = info.nData;
5954 if( !pPage->intKey ) sz += info.nKey;
drh72365832007-03-06 15:53:44 +00005955 assert( sz==info.nPayload );
drh6f11bef2004-05-13 01:12:56 +00005956 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00005957 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00005958 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
5959#ifndef SQLITE_OMIT_AUTOVACUUM
5960 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00005961 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00005962 }
5963#endif
5964 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00005965 }
5966
5967 /* Check sanity of left child page.
5968 */
drhda200cc2004-05-09 11:51:38 +00005969 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005970 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00005971#ifndef SQLITE_OMIT_AUTOVACUUM
5972 if( pBt->autoVacuum ){
5973 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
5974 }
5975#endif
drh74161702006-02-24 02:53:49 +00005976 d2 = checkTreePage(pCheck,pgno,pPage,zContext);
drhda200cc2004-05-09 11:51:38 +00005977 if( i>0 && d2!=depth ){
5978 checkAppendMsg(pCheck, zContext, "Child page depth differs");
5979 }
5980 depth = d2;
drh5eddca62001-06-30 21:53:53 +00005981 }
drh5eddca62001-06-30 21:53:53 +00005982 }
drhda200cc2004-05-09 11:51:38 +00005983 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005984 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh5bb3eb92007-05-04 13:15:55 +00005985 sqlite3_snprintf(sizeof(zContext), zContext,
5986 "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00005987#ifndef SQLITE_OMIT_AUTOVACUUM
5988 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00005989 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00005990 }
5991#endif
drh74161702006-02-24 02:53:49 +00005992 checkTreePage(pCheck, pgno, pPage, zContext);
drhda200cc2004-05-09 11:51:38 +00005993 }
drh5eddca62001-06-30 21:53:53 +00005994
5995 /* Check for complete coverage of the page
5996 */
drhda200cc2004-05-09 11:51:38 +00005997 data = pPage->aData;
5998 hdr = pPage->hdrOffset;
drh2e38c322004-09-03 18:38:44 +00005999 hit = sqliteMalloc( usableSize );
6000 if( hit ){
6001 memset(hit, 1, get2byte(&data[hdr+5]));
6002 nCell = get2byte(&data[hdr+3]);
6003 cellStart = hdr + 12 - 4*pPage->leaf;
6004 for(i=0; i<nCell; i++){
6005 int pc = get2byte(&data[cellStart+i*2]);
6006 int size = cellSizePtr(pPage, &data[pc]);
6007 int j;
danielk19777701e812005-01-10 12:59:51 +00006008 if( (pc+size-1)>=usableSize || pc<0 ){
6009 checkAppendMsg(pCheck, 0,
6010 "Corruption detected in cell %d on page %d",i,iPage,0);
6011 }else{
6012 for(j=pc+size-1; j>=pc; j--) hit[j]++;
6013 }
drh2e38c322004-09-03 18:38:44 +00006014 }
6015 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
6016 cnt++){
6017 int size = get2byte(&data[i+2]);
6018 int j;
danielk19777701e812005-01-10 12:59:51 +00006019 if( (i+size-1)>=usableSize || i<0 ){
6020 checkAppendMsg(pCheck, 0,
6021 "Corruption detected in cell %d on page %d",i,iPage,0);
6022 }else{
6023 for(j=i+size-1; j>=i; j--) hit[j]++;
6024 }
drh2e38c322004-09-03 18:38:44 +00006025 i = get2byte(&data[i]);
6026 }
6027 for(i=cnt=0; i<usableSize; i++){
6028 if( hit[i]==0 ){
6029 cnt++;
6030 }else if( hit[i]>1 ){
6031 checkAppendMsg(pCheck, 0,
6032 "Multiple uses for byte %d of page %d", i, iPage);
6033 break;
6034 }
6035 }
6036 if( cnt!=data[hdr+7] ){
6037 checkAppendMsg(pCheck, 0,
6038 "Fragmented space is %d byte reported as %d on page %d",
6039 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00006040 }
6041 }
drh2e38c322004-09-03 18:38:44 +00006042 sqliteFree(hit);
drh6019e162001-07-02 17:51:45 +00006043
drh4b70f112004-05-02 21:12:19 +00006044 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00006045 return depth+1;
drh5eddca62001-06-30 21:53:53 +00006046}
drhb7f91642004-10-31 02:22:47 +00006047#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006048
drhb7f91642004-10-31 02:22:47 +00006049#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006050/*
6051** This routine does a complete check of the given BTree file. aRoot[] is
6052** an array of pages numbers were each page number is the root page of
6053** a table. nRoot is the number of entries in aRoot.
6054**
6055** If everything checks out, this routine returns NULL. If something is
6056** amiss, an error message is written into memory obtained from malloc()
6057** and a pointer to that error message is returned. The calling function
6058** is responsible for freeing the error message when it is done.
6059*/
drh1dcdbc02007-01-27 02:24:54 +00006060char *sqlite3BtreeIntegrityCheck(
6061 Btree *p, /* The btree to be checked */
6062 int *aRoot, /* An array of root pages numbers for individual trees */
6063 int nRoot, /* Number of entries in aRoot[] */
6064 int mxErr, /* Stop reporting errors after this many */
6065 int *pnErr /* Write number of errors seen to this variable */
6066){
drh5eddca62001-06-30 21:53:53 +00006067 int i;
6068 int nRef;
drhaaab5722002-02-19 13:39:21 +00006069 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00006070 BtShared *pBt = p->pBt;
drh5eddca62001-06-30 21:53:53 +00006071
danielk19773b8a05f2007-03-19 17:44:26 +00006072 nRef = sqlite3PagerRefcount(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00006073 if( lockBtreeWithRetry(p)!=SQLITE_OK ){
drhefc251d2001-07-01 22:12:01 +00006074 return sqliteStrDup("Unable to acquire a read lock on the database");
6075 }
drh5eddca62001-06-30 21:53:53 +00006076 sCheck.pBt = pBt;
6077 sCheck.pPager = pBt->pPager;
danielk19773b8a05f2007-03-19 17:44:26 +00006078 sCheck.nPage = sqlite3PagerPagecount(sCheck.pPager);
drh1dcdbc02007-01-27 02:24:54 +00006079 sCheck.mxErr = mxErr;
6080 sCheck.nErr = 0;
6081 *pnErr = 0;
danielk1977e5321f02007-04-27 07:05:44 +00006082#ifndef SQLITE_OMIT_AUTOVACUUM
6083 if( pBt->nTrunc!=0 ){
6084 sCheck.nPage = pBt->nTrunc;
6085 }
6086#endif
drh0de8c112002-07-06 16:32:14 +00006087 if( sCheck.nPage==0 ){
6088 unlockBtreeIfUnused(pBt);
6089 return 0;
6090 }
drh8c1238a2003-01-02 14:43:55 +00006091 sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00006092 if( !sCheck.anRef ){
6093 unlockBtreeIfUnused(pBt);
drh1dcdbc02007-01-27 02:24:54 +00006094 *pnErr = 1;
danielk1977ac245ec2005-01-14 13:50:11 +00006095 return sqlite3MPrintf("Unable to malloc %d bytes",
6096 (sCheck.nPage+1)*sizeof(sCheck.anRef[0]));
6097 }
drhda200cc2004-05-09 11:51:38 +00006098 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00006099 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00006100 if( i<=sCheck.nPage ){
6101 sCheck.anRef[i] = 1;
6102 }
drh5eddca62001-06-30 21:53:53 +00006103 sCheck.zErrMsg = 0;
6104
6105 /* Check the integrity of the freelist
6106 */
drha34b6762004-05-07 13:30:42 +00006107 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
6108 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00006109
6110 /* Check all the tables.
6111 */
drh1dcdbc02007-01-27 02:24:54 +00006112 for(i=0; i<nRoot && sCheck.mxErr; i++){
drh4ff6dfa2002-03-03 23:06:00 +00006113 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00006114#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006115 if( pBt->autoVacuum && aRoot[i]>1 ){
6116 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
6117 }
6118#endif
drh74161702006-02-24 02:53:49 +00006119 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ");
drh5eddca62001-06-30 21:53:53 +00006120 }
6121
6122 /* Make sure every page in the file is referenced
6123 */
drh1dcdbc02007-01-27 02:24:54 +00006124 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00006125#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00006126 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00006127 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00006128 }
danielk1977afcdd022004-10-31 16:25:42 +00006129#else
6130 /* If the database supports auto-vacuum, make sure no tables contain
6131 ** references to pointer-map pages.
6132 */
6133 if( sCheck.anRef[i]==0 &&
danielk1977266664d2006-02-10 08:24:21 +00006134 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006135 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
6136 }
6137 if( sCheck.anRef[i]!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00006138 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006139 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
6140 }
6141#endif
drh5eddca62001-06-30 21:53:53 +00006142 }
6143
6144 /* Make sure this analysis did not leave any unref() pages
6145 */
drh5e00f6c2001-09-13 13:46:56 +00006146 unlockBtreeIfUnused(pBt);
danielk19773b8a05f2007-03-19 17:44:26 +00006147 if( nRef != sqlite3PagerRefcount(pBt->pPager) ){
drh2e38c322004-09-03 18:38:44 +00006148 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00006149 "Outstanding page count goes from %d to %d during this analysis",
danielk19773b8a05f2007-03-19 17:44:26 +00006150 nRef, sqlite3PagerRefcount(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00006151 );
drh5eddca62001-06-30 21:53:53 +00006152 }
6153
6154 /* Clean up and report errors.
6155 */
6156 sqliteFree(sCheck.anRef);
drh1dcdbc02007-01-27 02:24:54 +00006157 *pnErr = sCheck.nErr;
drh5eddca62001-06-30 21:53:53 +00006158 return sCheck.zErrMsg;
6159}
drhb7f91642004-10-31 02:22:47 +00006160#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00006161
drh73509ee2003-04-06 20:44:45 +00006162/*
6163** Return the full pathname of the underlying database file.
6164*/
danielk1977aef0bf62005-12-30 16:28:01 +00006165const char *sqlite3BtreeGetFilename(Btree *p){
6166 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00006167 return sqlite3PagerFilename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00006168}
6169
6170/*
danielk19775865e3d2004-06-14 06:03:57 +00006171** Return the pathname of the directory that contains the database file.
6172*/
danielk1977aef0bf62005-12-30 16:28:01 +00006173const char *sqlite3BtreeGetDirname(Btree *p){
6174 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00006175 return sqlite3PagerDirname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006176}
6177
6178/*
6179** Return the pathname of the journal file for this database. The return
6180** value of this routine is the same regardless of whether the journal file
6181** has been created or not.
6182*/
danielk1977aef0bf62005-12-30 16:28:01 +00006183const char *sqlite3BtreeGetJournalname(Btree *p){
6184 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00006185 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006186}
6187
drhb7f91642004-10-31 02:22:47 +00006188#ifndef SQLITE_OMIT_VACUUM
danielk19775865e3d2004-06-14 06:03:57 +00006189/*
drhf7c57532003-04-25 13:22:51 +00006190** Copy the complete content of pBtFrom into pBtTo. A transaction
6191** must be active for both files.
6192**
6193** The size of file pBtFrom may be reduced by this operation.
drh43605152004-05-29 21:46:49 +00006194** If anything goes wrong, the transaction on pBtFrom is rolled back.
drh73509ee2003-04-06 20:44:45 +00006195*/
danielk1977aef0bf62005-12-30 16:28:01 +00006196int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
drhf7c57532003-04-25 13:22:51 +00006197 int rc = SQLITE_OK;
drh50f2f432005-09-16 11:32:18 +00006198 Pgno i, nPage, nToPage, iSkip;
drhf7c57532003-04-25 13:22:51 +00006199
danielk1977aef0bf62005-12-30 16:28:01 +00006200 BtShared *pBtTo = pTo->pBt;
6201 BtShared *pBtFrom = pFrom->pBt;
6202
6203 if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
danielk1977ee5741e2004-05-31 10:01:34 +00006204 return SQLITE_ERROR;
6205 }
drhf7c57532003-04-25 13:22:51 +00006206 if( pBtTo->pCursor ) return SQLITE_BUSY;
danielk19773b8a05f2007-03-19 17:44:26 +00006207 nToPage = sqlite3PagerPagecount(pBtTo->pPager);
6208 nPage = sqlite3PagerPagecount(pBtFrom->pPager);
drh50f2f432005-09-16 11:32:18 +00006209 iSkip = PENDING_BYTE_PAGE(pBtTo);
danielk1977369f27e2004-06-15 11:40:04 +00006210 for(i=1; rc==SQLITE_OK && i<=nPage; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00006211 DbPage *pDbPage;
drh50f2f432005-09-16 11:32:18 +00006212 if( i==iSkip ) continue;
danielk19773b8a05f2007-03-19 17:44:26 +00006213 rc = sqlite3PagerGet(pBtFrom->pPager, i, &pDbPage);
drhf7c57532003-04-25 13:22:51 +00006214 if( rc ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00006215 rc = sqlite3PagerOverwrite(pBtTo->pPager, i, sqlite3PagerGetData(pDbPage));
6216 sqlite3PagerUnref(pDbPage);
drhf7c57532003-04-25 13:22:51 +00006217 }
drh538f5702007-04-13 02:14:30 +00006218
6219 /* If the file is shrinking, journal the pages that are being truncated
6220 ** so that they can be rolled back if the commit fails.
6221 */
drh2e6d11b2003-04-25 15:37:57 +00006222 for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00006223 DbPage *pDbPage;
drh49285702005-09-17 15:20:26 +00006224 if( i==iSkip ) continue;
danielk19773b8a05f2007-03-19 17:44:26 +00006225 rc = sqlite3PagerGet(pBtTo->pPager, i, &pDbPage);
drh2e6d11b2003-04-25 15:37:57 +00006226 if( rc ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00006227 rc = sqlite3PagerWrite(pDbPage);
drh538f5702007-04-13 02:14:30 +00006228 sqlite3PagerDontWrite(pDbPage);
6229 /* Yeah. It seems wierd to call DontWrite() right after Write(). But
6230 ** that is because the names of those procedures do not exactly
6231 ** represent what they do. Write() really means "put this page in the
6232 ** rollback journal and mark it as dirty so that it will be written
6233 ** to the database file later." DontWrite() undoes the second part of
6234 ** that and prevents the page from being written to the database. The
6235 ** page is still on the rollback journal, though. And that is the whole
6236 ** point of this loop: to put pages on the rollback journal. */
danielk19773b8a05f2007-03-19 17:44:26 +00006237 sqlite3PagerUnref(pDbPage);
drh2e6d11b2003-04-25 15:37:57 +00006238 }
6239 if( !rc && nPage<nToPage ){
danielk19773b8a05f2007-03-19 17:44:26 +00006240 rc = sqlite3PagerTruncate(pBtTo->pPager, nPage);
drh2e6d11b2003-04-25 15:37:57 +00006241 }
drh538f5702007-04-13 02:14:30 +00006242
drhf7c57532003-04-25 13:22:51 +00006243 if( rc ){
danielk1977aef0bf62005-12-30 16:28:01 +00006244 sqlite3BtreeRollback(pTo);
drhf7c57532003-04-25 13:22:51 +00006245 }
6246 return rc;
drh73509ee2003-04-06 20:44:45 +00006247}
drhb7f91642004-10-31 02:22:47 +00006248#endif /* SQLITE_OMIT_VACUUM */
danielk19771d850a72004-05-31 08:26:49 +00006249
6250/*
6251** Return non-zero if a transaction is active.
6252*/
danielk1977aef0bf62005-12-30 16:28:01 +00006253int sqlite3BtreeIsInTrans(Btree *p){
6254 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00006255}
6256
6257/*
6258** Return non-zero if a statement transaction is active.
6259*/
danielk1977aef0bf62005-12-30 16:28:01 +00006260int sqlite3BtreeIsInStmt(Btree *p){
6261 return (p->pBt && p->pBt->inStmt);
danielk19771d850a72004-05-31 08:26:49 +00006262}
danielk197713adf8a2004-06-03 16:08:41 +00006263
6264/*
danielk19772372c2b2006-06-27 16:34:56 +00006265** Return non-zero if a read (or write) transaction is active.
6266*/
6267int sqlite3BtreeIsInReadTrans(Btree *p){
6268 return (p && (p->inTrans!=TRANS_NONE));
6269}
6270
6271/*
danielk1977da184232006-01-05 11:34:32 +00006272** This function returns a pointer to a blob of memory associated with
6273** a single shared-btree. The memory is used by client code for it's own
6274** purposes (for example, to store a high-level schema associated with
6275** the shared-btree). The btree layer manages reference counting issues.
6276**
6277** The first time this is called on a shared-btree, nBytes bytes of memory
6278** are allocated, zeroed, and returned to the caller. For each subsequent
6279** call the nBytes parameter is ignored and a pointer to the same blob
6280** of memory returned.
6281**
6282** Just before the shared-btree is closed, the function passed as the
6283** xFree argument when the memory allocation was made is invoked on the
6284** blob of allocated memory. This function should not call sqliteFree()
6285** on the memory, the btree layer does that.
6286*/
6287void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
6288 BtShared *pBt = p->pBt;
6289 if( !pBt->pSchema ){
6290 pBt->pSchema = sqliteMalloc(nBytes);
6291 pBt->xFreeSchema = xFree;
6292 }
6293 return pBt->pSchema;
6294}
6295
danielk1977c87d34d2006-01-06 13:00:28 +00006296/*
6297** Return true if another user of the same shared btree as the argument
6298** handle holds an exclusive lock on the sqlite_master table.
6299*/
6300int sqlite3BtreeSchemaLocked(Btree *p){
6301 return (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
6302}
6303
drha154dcd2006-03-22 22:10:07 +00006304
6305#ifndef SQLITE_OMIT_SHARED_CACHE
6306/*
6307** Obtain a lock on the table whose root page is iTab. The
6308** lock is a write lock if isWritelock is true or a read lock
6309** if it is false.
6310*/
danielk1977c00da102006-01-07 13:21:04 +00006311int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00006312 int rc = SQLITE_OK;
danielk1977c00da102006-01-07 13:21:04 +00006313 u8 lockType = (isWriteLock?WRITE_LOCK:READ_LOCK);
danielk19772e94d4d2006-01-09 05:36:27 +00006314 rc = queryTableLock(p, iTab, lockType);
danielk1977c00da102006-01-07 13:21:04 +00006315 if( rc==SQLITE_OK ){
6316 rc = lockTable(p, iTab, lockType);
6317 }
6318 return rc;
6319}
drha154dcd2006-03-22 22:10:07 +00006320#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00006321
danielk1977b4e9af92007-05-01 17:49:49 +00006322#ifndef SQLITE_OMIT_INCRBLOB
6323/*
6324** Argument pCsr must be a cursor opened for writing on an
6325** INTKEY table currently pointing at a valid table entry.
6326** This function modifies the data stored as part of that entry.
6327** Only the data content may only be modified, it is not possible
6328** to change the length of the data stored.
6329*/
danielk1977dcbb5d32007-05-04 18:36:44 +00006330int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
danielk1977d04417962007-05-02 13:16:30 +00006331
danielk1977dcbb5d32007-05-04 18:36:44 +00006332 assert(pCsr->isIncrblobHandle);
6333 if( pCsr->eState==CURSOR_REQUIRESEEK ){
6334 return SQLITE_ABORT;
6335 }
6336
danielk1977d04417962007-05-02 13:16:30 +00006337 /* Check some preconditions:
danielk1977dcbb5d32007-05-04 18:36:44 +00006338 ** (a) the cursor is open for writing,
6339 ** (b) there is no read-lock on the table being modified and
6340 ** (c) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00006341 */
danielk1977d04417962007-05-02 13:16:30 +00006342 if( !pCsr->wrFlag ){
danielk1977dcbb5d32007-05-04 18:36:44 +00006343 return SQLITE_READONLY;
danielk1977d04417962007-05-02 13:16:30 +00006344 }
drh87cc3b32007-05-08 21:45:27 +00006345 assert( !pCsr->pBtree->pBt->readOnly
6346 && pCsr->pBtree->pBt->inTransaction==TRANS_WRITE );
danielk1977d04417962007-05-02 13:16:30 +00006347 if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr) ){
6348 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
6349 }
6350 if( pCsr->eState==CURSOR_INVALID || !pCsr->pPage->intKey ){
6351 return SQLITE_ERROR;
danielk1977b4e9af92007-05-01 17:49:49 +00006352 }
6353
danielk19779f8d6402007-05-02 17:48:45 +00006354 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00006355}
danielk19772dec9702007-05-02 16:48:37 +00006356
6357/*
6358** Set a flag on this cursor to cache the locations of pages from the
danielk1977da107192007-05-04 08:32:13 +00006359** overflow list for the current row. This is used by cursors opened
6360** for incremental blob IO only.
6361**
6362** This function sets a flag only. The actual page location cache
6363** (stored in BtCursor.aOverflow[]) is allocated and used by function
6364** accessPayload() (the worker function for sqlite3BtreeData() and
6365** sqlite3BtreePutData()).
danielk19772dec9702007-05-02 16:48:37 +00006366*/
6367void sqlite3BtreeCacheOverflow(BtCursor *pCur){
danielk1977dcbb5d32007-05-04 18:36:44 +00006368 assert(!pCur->isIncrblobHandle);
danielk19772dec9702007-05-02 16:48:37 +00006369 assert(!pCur->aOverflow);
danielk1977dcbb5d32007-05-04 18:36:44 +00006370 pCur->isIncrblobHandle = 1;
danielk19772dec9702007-05-02 16:48:37 +00006371}
danielk1977b4e9af92007-05-01 17:49:49 +00006372#endif