blob: 9bc1854cc41caee80a7ccdde8346b3f5f0340aaf [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*************************************************************************
danielk1977b39f70b2007-05-17 18:28:11 +000012** $Id: btree.c,v 1.383 2007/05/17 18:28:11 danielk1977 Exp $
drh8b2f49b2001-06-08 00:21:52 +000013**
14** This file implements a external (disk-based) database using BTrees.
drha3152892007-05-05 11:48:52 +000015** See the header comment on "btreeInt.h" for additional information.
16** Including a description of file format and an overview of operation.
drha059ad02001-04-17 20:09:11 +000017*/
drha3152892007-05-05 11:48:52 +000018#include "btreeInt.h"
paulb95a8862003-04-01 21:16:41 +000019
drh8c42ca92001-06-22 19:15:00 +000020/*
drha3152892007-05-05 11:48:52 +000021** The header string that appears at the beginning of every
22** SQLite database.
drh556b2a22005-06-14 16:04:05 +000023*/
drh556b2a22005-06-14 16:04:05 +000024static const char zMagicHeader[] = SQLITE_FILE_HEADER;
drh08ed44e2001-04-29 23:32:55 +000025
drh8c42ca92001-06-22 19:15:00 +000026
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)]))
drh16a9b832007-05-05 18:39:25 +0000424u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell){
drh43605152004-05-29 21:46:49 +0000425 u8 *data = pPage->aData;
426 assert( iCell>=0 );
427 assert( iCell<get2byte(&data[pPage->hdrOffset+3]) );
danielk19771cc5ed82007-05-16 17:28:43 +0000428 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000429}
430
431/*
drh16a9b832007-05-05 18:39:25 +0000432** This a more complex version of sqlite3BtreeFindCell() that works for
drh43605152004-05-29 21:46:49 +0000433** pages that do contain overflow cells. See insert
434*/
435static u8 *findOverflowCell(MemPage *pPage, int iCell){
436 int i;
437 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000438 int k;
439 struct _OvflCell *pOvfl;
440 pOvfl = &pPage->aOvfl[i];
441 k = pOvfl->idx;
442 if( k<=iCell ){
443 if( k==iCell ){
444 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000445 }
446 iCell--;
447 }
448 }
danielk19771cc5ed82007-05-16 17:28:43 +0000449 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000450}
451
452/*
453** Parse a cell content block and fill in the CellInfo structure. There
drh16a9b832007-05-05 18:39:25 +0000454** are two versions of this function. sqlite3BtreeParseCell() takes a
455** cell index as the second argument and sqlite3BtreeParseCellPtr()
456** takes a pointer to the body of the cell as its second argument.
danielk19771cc5ed82007-05-16 17:28:43 +0000457**
458** Within this file, the parseCell() macro can be called instead of
459** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
drh43605152004-05-29 21:46:49 +0000460*/
drh16a9b832007-05-05 18:39:25 +0000461void sqlite3BtreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000462 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000463 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000464 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000465){
drh271efa52004-05-30 19:19:05 +0000466 int n; /* Number bytes in cell content header */
467 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000468
469 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000470 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000471 n = pPage->childPtrSize;
472 assert( n==4-4*pPage->leaf );
drh8b18dd42004-05-12 19:18:15 +0000473 if( pPage->hasData ){
drh271efa52004-05-30 19:19:05 +0000474 n += getVarint32(&pCell[n], &nPayload);
drh8b18dd42004-05-12 19:18:15 +0000475 }else{
drh271efa52004-05-30 19:19:05 +0000476 nPayload = 0;
drh3aac2dd2004-04-26 14:10:20 +0000477 }
drh271efa52004-05-30 19:19:05 +0000478 pInfo->nData = nPayload;
drh504b6982006-01-22 21:52:56 +0000479 if( pPage->intKey ){
480 n += getVarint(&pCell[n], (u64 *)&pInfo->nKey);
481 }else{
482 u32 x;
483 n += getVarint32(&pCell[n], &x);
484 pInfo->nKey = x;
485 nPayload += x;
drh6f11bef2004-05-13 01:12:56 +0000486 }
drh72365832007-03-06 15:53:44 +0000487 pInfo->nPayload = nPayload;
drh504b6982006-01-22 21:52:56 +0000488 pInfo->nHeader = n;
drh271efa52004-05-30 19:19:05 +0000489 if( nPayload<=pPage->maxLocal ){
490 /* This is the (easy) common case where the entire payload fits
491 ** on the local page. No overflow is required.
492 */
493 int nSize; /* Total size of cell content in bytes */
drh6f11bef2004-05-13 01:12:56 +0000494 pInfo->nLocal = nPayload;
495 pInfo->iOverflow = 0;
drh271efa52004-05-30 19:19:05 +0000496 nSize = nPayload + n;
497 if( nSize<4 ){
498 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000499 }
drh271efa52004-05-30 19:19:05 +0000500 pInfo->nSize = nSize;
drh6f11bef2004-05-13 01:12:56 +0000501 }else{
drh271efa52004-05-30 19:19:05 +0000502 /* If the payload will not fit completely on the local page, we have
503 ** to decide how much to store locally and how much to spill onto
504 ** overflow pages. The strategy is to minimize the amount of unused
505 ** space on overflow pages while keeping the amount of local storage
506 ** in between minLocal and maxLocal.
507 **
508 ** Warning: changing the way overflow payload is distributed in any
509 ** way will result in an incompatible file format.
510 */
511 int minLocal; /* Minimum amount of payload held locally */
512 int maxLocal; /* Maximum amount of payload held locally */
513 int surplus; /* Overflow payload available for local storage */
514
515 minLocal = pPage->minLocal;
516 maxLocal = pPage->maxLocal;
517 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000518 if( surplus <= maxLocal ){
519 pInfo->nLocal = surplus;
520 }else{
521 pInfo->nLocal = minLocal;
522 }
523 pInfo->iOverflow = pInfo->nLocal + n;
524 pInfo->nSize = pInfo->iOverflow + 4;
525 }
drh3aac2dd2004-04-26 14:10:20 +0000526}
danielk19771cc5ed82007-05-16 17:28:43 +0000527#define parseCell(pPage, iCell, pInfo) \
528 sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
drh16a9b832007-05-05 18:39:25 +0000529void sqlite3BtreeParseCell(
drh43605152004-05-29 21:46:49 +0000530 MemPage *pPage, /* Page containing the cell */
531 int iCell, /* The cell index. First cell is 0 */
532 CellInfo *pInfo /* Fill in this structure */
533){
danielk19771cc5ed82007-05-16 17:28:43 +0000534 parseCell(pPage, iCell, pInfo);
drh43605152004-05-29 21:46:49 +0000535}
drh3aac2dd2004-04-26 14:10:20 +0000536
537/*
drh43605152004-05-29 21:46:49 +0000538** Compute the total number of bytes that a Cell needs in the cell
539** data area of the btree-page. The return number includes the cell
540** data header and the local payload, but not any overflow page or
541** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000542*/
danielk1977bc6ada42004-06-30 08:20:16 +0000543#ifndef NDEBUG
drh43605152004-05-29 21:46:49 +0000544static int cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000545 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000546 sqlite3BtreeParseCell(pPage, iCell, &info);
drh43605152004-05-29 21:46:49 +0000547 return info.nSize;
548}
danielk1977bc6ada42004-06-30 08:20:16 +0000549#endif
drh43605152004-05-29 21:46:49 +0000550static int cellSizePtr(MemPage *pPage, u8 *pCell){
551 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000552 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000553 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000554}
555
danielk197779a40da2005-01-16 08:00:01 +0000556#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +0000557/*
danielk197726836652005-01-17 01:33:13 +0000558** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +0000559** to an overflow page, insert an entry into the pointer-map
560** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +0000561*/
danielk197726836652005-01-17 01:33:13 +0000562static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
danielk197779a40da2005-01-16 08:00:01 +0000563 if( pCell ){
564 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000565 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh72365832007-03-06 15:53:44 +0000566 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk197779a40da2005-01-16 08:00:01 +0000567 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
568 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
569 return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
570 }
danielk1977ac11ee62005-01-15 12:45:51 +0000571 }
danielk197779a40da2005-01-16 08:00:01 +0000572 return SQLITE_OK;
danielk1977ac11ee62005-01-15 12:45:51 +0000573}
danielk197726836652005-01-17 01:33:13 +0000574/*
575** If the cell with index iCell on page pPage contains a pointer
576** to an overflow page, insert an entry into the pointer-map
577** for the overflow page.
578*/
579static int ptrmapPutOvfl(MemPage *pPage, int iCell){
580 u8 *pCell;
581 pCell = findOverflowCell(pPage, iCell);
582 return ptrmapPutOvflPtr(pPage, pCell);
583}
danielk197779a40da2005-01-16 08:00:01 +0000584#endif
585
danielk1977ac11ee62005-01-15 12:45:51 +0000586
drhda200cc2004-05-09 11:51:38 +0000587/*
drh72f82862001-05-24 21:06:34 +0000588** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +0000589** end of the page and all free space is collected into one
590** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +0000591** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +0000592*/
drh2e38c322004-09-03 18:38:44 +0000593static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000594 int i; /* Loop counter */
595 int pc; /* Address of a i-th cell */
596 int addr; /* Offset of first byte after cell pointer array */
597 int hdr; /* Offset to the page header */
598 int size; /* Size of a cell */
599 int usableSize; /* Number of usable bytes on a page */
600 int cellOffset; /* Offset to the cell pointer array */
601 int brk; /* Offset to the cell content area */
602 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +0000603 unsigned char *data; /* The page data */
604 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +0000605
danielk19773b8a05f2007-03-19 17:44:26 +0000606 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000607 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +0000608 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000609 assert( pPage->nOverflow==0 );
drh2e38c322004-09-03 18:38:44 +0000610 temp = sqliteMalloc( pPage->pBt->pageSize );
611 if( temp==0 ) return SQLITE_NOMEM;
drh43605152004-05-29 21:46:49 +0000612 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +0000613 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000614 cellOffset = pPage->cellOffset;
615 nCell = pPage->nCell;
616 assert( nCell==get2byte(&data[hdr+3]) );
617 usableSize = pPage->pBt->usableSize;
618 brk = get2byte(&data[hdr+5]);
619 memcpy(&temp[brk], &data[brk], usableSize - brk);
620 brk = usableSize;
621 for(i=0; i<nCell; i++){
622 u8 *pAddr; /* The i-th cell pointer */
623 pAddr = &data[cellOffset + i*2];
624 pc = get2byte(pAddr);
625 assert( pc<pPage->pBt->usableSize );
626 size = cellSizePtr(pPage, &temp[pc]);
627 brk -= size;
628 memcpy(&data[brk], &temp[pc], size);
629 put2byte(pAddr, brk);
drh2af926b2001-05-15 00:39:25 +0000630 }
drh43605152004-05-29 21:46:49 +0000631 assert( brk>=cellOffset+2*nCell );
632 put2byte(&data[hdr+5], brk);
633 data[hdr+1] = 0;
634 data[hdr+2] = 0;
635 data[hdr+7] = 0;
636 addr = cellOffset+2*nCell;
637 memset(&data[addr], 0, brk-addr);
drh2e38c322004-09-03 18:38:44 +0000638 sqliteFree(temp);
639 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +0000640}
641
drha059ad02001-04-17 20:09:11 +0000642/*
drh43605152004-05-29 21:46:49 +0000643** Allocate nByte bytes of space on a page.
drhbd03cae2001-06-02 02:40:57 +0000644**
drh9e572e62004-04-23 23:43:10 +0000645** Return the index into pPage->aData[] of the first byte of
drhbd03cae2001-06-02 02:40:57 +0000646** the new allocation. Or return 0 if there is not enough free
647** space on the page to satisfy the allocation request.
drh2af926b2001-05-15 00:39:25 +0000648**
drh72f82862001-05-24 21:06:34 +0000649** If the page contains nBytes of free space but does not contain
drh8b2f49b2001-06-08 00:21:52 +0000650** nBytes of contiguous free space, then this routine automatically
651** calls defragementPage() to consolidate all free space before
652** allocating the new chunk.
drh7e3b0a02001-04-28 16:52:40 +0000653*/
drh9e572e62004-04-23 23:43:10 +0000654static int allocateSpace(MemPage *pPage, int nByte){
drh3aac2dd2004-04-26 14:10:20 +0000655 int addr, pc, hdr;
drh9e572e62004-04-23 23:43:10 +0000656 int size;
drh24cd67e2004-05-10 16:18:47 +0000657 int nFrag;
drh43605152004-05-29 21:46:49 +0000658 int top;
659 int nCell;
660 int cellOffset;
drh9e572e62004-04-23 23:43:10 +0000661 unsigned char *data;
drh43605152004-05-29 21:46:49 +0000662
drh9e572e62004-04-23 23:43:10 +0000663 data = pPage->aData;
danielk19773b8a05f2007-03-19 17:44:26 +0000664 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000665 assert( pPage->pBt );
666 if( nByte<4 ) nByte = 4;
drh43605152004-05-29 21:46:49 +0000667 if( pPage->nFree<nByte || pPage->nOverflow>0 ) return 0;
668 pPage->nFree -= nByte;
drh9e572e62004-04-23 23:43:10 +0000669 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000670
671 nFrag = data[hdr+7];
672 if( nFrag<60 ){
673 /* Search the freelist looking for a slot big enough to satisfy the
674 ** space request. */
675 addr = hdr+1;
676 while( (pc = get2byte(&data[addr]))>0 ){
677 size = get2byte(&data[pc+2]);
678 if( size>=nByte ){
679 if( size<nByte+4 ){
680 memcpy(&data[addr], &data[pc], 2);
681 data[hdr+7] = nFrag + size - nByte;
682 return pc;
683 }else{
684 put2byte(&data[pc+2], size-nByte);
685 return pc + size - nByte;
686 }
687 }
688 addr = pc;
drh9e572e62004-04-23 23:43:10 +0000689 }
690 }
drh43605152004-05-29 21:46:49 +0000691
692 /* Allocate memory from the gap in between the cell pointer array
693 ** and the cell content area.
694 */
695 top = get2byte(&data[hdr+5]);
696 nCell = get2byte(&data[hdr+3]);
697 cellOffset = pPage->cellOffset;
698 if( nFrag>=60 || cellOffset + 2*nCell > top - nByte ){
drh2e38c322004-09-03 18:38:44 +0000699 if( defragmentPage(pPage) ) return 0;
drh43605152004-05-29 21:46:49 +0000700 top = get2byte(&data[hdr+5]);
drh2af926b2001-05-15 00:39:25 +0000701 }
drh43605152004-05-29 21:46:49 +0000702 top -= nByte;
703 assert( cellOffset + 2*nCell <= top );
704 put2byte(&data[hdr+5], top);
705 return top;
drh7e3b0a02001-04-28 16:52:40 +0000706}
707
708/*
drh9e572e62004-04-23 23:43:10 +0000709** Return a section of the pPage->aData to the freelist.
710** The first byte of the new free block is pPage->aDisk[start]
711** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +0000712**
713** Most of the effort here is involved in coalesing adjacent
714** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000715*/
drh9e572e62004-04-23 23:43:10 +0000716static void freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +0000717 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +0000718 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +0000719
drh9e572e62004-04-23 23:43:10 +0000720 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +0000721 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000722 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +0000723 assert( (start + size)<=pPage->pBt->usableSize );
drh9e572e62004-04-23 23:43:10 +0000724 if( size<4 ) size = 4;
725
drhfcce93f2006-02-22 03:08:32 +0000726#ifdef SQLITE_SECURE_DELETE
727 /* Overwrite deleted information with zeros when the SECURE_DELETE
728 ** option is enabled at compile-time */
729 memset(&data[start], 0, size);
730#endif
731
drh9e572e62004-04-23 23:43:10 +0000732 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +0000733 hdr = pPage->hdrOffset;
734 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +0000735 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +0000736 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000737 assert( pbegin>addr );
738 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +0000739 }
drhb6f41482004-05-14 01:58:11 +0000740 assert( pbegin<=pPage->pBt->usableSize-4 );
drh3aac2dd2004-04-26 14:10:20 +0000741 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +0000742 put2byte(&data[addr], start);
743 put2byte(&data[start], pbegin);
744 put2byte(&data[start+2], size);
drh2af926b2001-05-15 00:39:25 +0000745 pPage->nFree += size;
drh9e572e62004-04-23 23:43:10 +0000746
747 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +0000748 addr = pPage->hdrOffset + 1;
749 while( (pbegin = get2byte(&data[addr]))>0 ){
drh9e572e62004-04-23 23:43:10 +0000750 int pnext, psize;
drh3aac2dd2004-04-26 14:10:20 +0000751 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +0000752 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +0000753 pnext = get2byte(&data[pbegin]);
754 psize = get2byte(&data[pbegin+2]);
755 if( pbegin + psize + 3 >= pnext && pnext>0 ){
756 int frag = pnext - (pbegin+psize);
drh43605152004-05-29 21:46:49 +0000757 assert( frag<=data[pPage->hdrOffset+7] );
758 data[pPage->hdrOffset+7] -= frag;
drh9e572e62004-04-23 23:43:10 +0000759 put2byte(&data[pbegin], get2byte(&data[pnext]));
760 put2byte(&data[pbegin+2], pnext+get2byte(&data[pnext+2])-pbegin);
761 }else{
drh3aac2dd2004-04-26 14:10:20 +0000762 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +0000763 }
764 }
drh7e3b0a02001-04-28 16:52:40 +0000765
drh43605152004-05-29 21:46:49 +0000766 /* If the cell content area begins with a freeblock, remove it. */
767 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
768 int top;
769 pbegin = get2byte(&data[hdr+1]);
770 memcpy(&data[hdr+1], &data[pbegin], 2);
771 top = get2byte(&data[hdr+5]);
772 put2byte(&data[hdr+5], top + get2byte(&data[pbegin+2]));
drh4b70f112004-05-02 21:12:19 +0000773 }
drh4b70f112004-05-02 21:12:19 +0000774}
775
776/*
drh271efa52004-05-30 19:19:05 +0000777** Decode the flags byte (the first byte of the header) for a page
778** and initialize fields of the MemPage structure accordingly.
779*/
780static void decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +0000781 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +0000782
783 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
784 pPage->intKey = (flagByte & (PTF_INTKEY|PTF_LEAFDATA))!=0;
785 pPage->zeroData = (flagByte & PTF_ZERODATA)!=0;
786 pPage->leaf = (flagByte & PTF_LEAF)!=0;
787 pPage->childPtrSize = 4*(pPage->leaf==0);
788 pBt = pPage->pBt;
789 if( flagByte & PTF_LEAFDATA ){
790 pPage->leafData = 1;
791 pPage->maxLocal = pBt->maxLeaf;
792 pPage->minLocal = pBt->minLeaf;
793 }else{
794 pPage->leafData = 0;
795 pPage->maxLocal = pBt->maxLocal;
796 pPage->minLocal = pBt->minLocal;
797 }
798 pPage->hasData = !(pPage->zeroData || (!pPage->leaf && pPage->leafData));
799}
800
801/*
drh7e3b0a02001-04-28 16:52:40 +0000802** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +0000803**
drhbd03cae2001-06-02 02:40:57 +0000804** The pParent parameter must be a pointer to the MemPage which
drh9e572e62004-04-23 23:43:10 +0000805** is the parent of the page being initialized. The root of a
806** BTree has no parent and so for that page, pParent==NULL.
drh5e2f8b92001-05-28 00:41:15 +0000807**
drh72f82862001-05-24 21:06:34 +0000808** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +0000809** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +0000810** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
811** guarantee that the page is well-formed. It only shows that
812** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +0000813*/
drh16a9b832007-05-05 18:39:25 +0000814int sqlite3BtreeInitPage(
drh3aac2dd2004-04-26 14:10:20 +0000815 MemPage *pPage, /* The page to be initialized */
drh9e572e62004-04-23 23:43:10 +0000816 MemPage *pParent /* The parent. Might be NULL */
817){
drh271efa52004-05-30 19:19:05 +0000818 int pc; /* Address of a freeblock within pPage->aData[] */
drh271efa52004-05-30 19:19:05 +0000819 int hdr; /* Offset to beginning of page header */
820 u8 *data; /* Equal to pPage->aData */
danielk1977aef0bf62005-12-30 16:28:01 +0000821 BtShared *pBt; /* The main btree structure */
drh271efa52004-05-30 19:19:05 +0000822 int usableSize; /* Amount of usable space on each page */
823 int cellOffset; /* Offset from start of page to first cell pointer */
824 int nFree; /* Number of unused bytes on the page */
825 int top; /* First byte of the cell content area */
drh2af926b2001-05-15 00:39:25 +0000826
drh2e38c322004-09-03 18:38:44 +0000827 pBt = pPage->pBt;
828 assert( pBt!=0 );
829 assert( pParent==0 || pParent->pBt==pBt );
danielk19773b8a05f2007-03-19 17:44:26 +0000830 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drh07d183d2005-05-01 22:52:42 +0000831 assert( pPage->aData == &((unsigned char*)pPage)[-pBt->pageSize] );
drhee696e22004-08-30 16:52:17 +0000832 if( pPage->pParent!=pParent && (pPage->pParent!=0 || pPage->isInit) ){
833 /* The parent page should never change unless the file is corrupt */
drh49285702005-09-17 15:20:26 +0000834 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000835 }
drh10617cd2004-05-14 15:27:27 +0000836 if( pPage->isInit ) return SQLITE_OK;
drhda200cc2004-05-09 11:51:38 +0000837 if( pPage->pParent==0 && pParent!=0 ){
838 pPage->pParent = pParent;
danielk19773b8a05f2007-03-19 17:44:26 +0000839 sqlite3PagerRef(pParent->pDbPage);
drh5e2f8b92001-05-28 00:41:15 +0000840 }
drhde647132004-05-07 17:57:49 +0000841 hdr = pPage->hdrOffset;
drha34b6762004-05-07 13:30:42 +0000842 data = pPage->aData;
drh271efa52004-05-30 19:19:05 +0000843 decodeFlags(pPage, data[hdr]);
drh43605152004-05-29 21:46:49 +0000844 pPage->nOverflow = 0;
drhc8629a12004-05-08 20:07:40 +0000845 pPage->idxShift = 0;
drh2e38c322004-09-03 18:38:44 +0000846 usableSize = pBt->usableSize;
drh43605152004-05-29 21:46:49 +0000847 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
848 top = get2byte(&data[hdr+5]);
849 pPage->nCell = get2byte(&data[hdr+3]);
drh2e38c322004-09-03 18:38:44 +0000850 if( pPage->nCell>MX_CELL(pBt) ){
drhee696e22004-08-30 16:52:17 +0000851 /* To many cells for a single page. The page must be corrupt */
drh49285702005-09-17 15:20:26 +0000852 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000853 }
854 if( pPage->nCell==0 && pParent!=0 && pParent->pgno!=1 ){
855 /* All pages must have at least one cell, except for root pages */
drh49285702005-09-17 15:20:26 +0000856 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000857 }
drh9e572e62004-04-23 23:43:10 +0000858
859 /* Compute the total free space on the page */
drh9e572e62004-04-23 23:43:10 +0000860 pc = get2byte(&data[hdr+1]);
drh43605152004-05-29 21:46:49 +0000861 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
drh9e572e62004-04-23 23:43:10 +0000862 while( pc>0 ){
863 int next, size;
drhee696e22004-08-30 16:52:17 +0000864 if( pc>usableSize-4 ){
865 /* Free block is off the page */
drh49285702005-09-17 15:20:26 +0000866 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000867 }
drh9e572e62004-04-23 23:43:10 +0000868 next = get2byte(&data[pc]);
869 size = get2byte(&data[pc+2]);
drhee696e22004-08-30 16:52:17 +0000870 if( next>0 && next<=pc+size+3 ){
871 /* Free blocks must be in accending order */
drh49285702005-09-17 15:20:26 +0000872 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000873 }
drh3add3672004-05-15 00:29:24 +0000874 nFree += size;
drh9e572e62004-04-23 23:43:10 +0000875 pc = next;
876 }
drh3add3672004-05-15 00:29:24 +0000877 pPage->nFree = nFree;
drhee696e22004-08-30 16:52:17 +0000878 if( nFree>=usableSize ){
879 /* Free space cannot exceed total page size */
drh49285702005-09-17 15:20:26 +0000880 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000881 }
drh9e572e62004-04-23 23:43:10 +0000882
drhde647132004-05-07 17:57:49 +0000883 pPage->isInit = 1;
drh9e572e62004-04-23 23:43:10 +0000884 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +0000885}
886
887/*
drh8b2f49b2001-06-08 00:21:52 +0000888** Set up a raw page so that it looks like a database page holding
889** no entries.
drhbd03cae2001-06-02 02:40:57 +0000890*/
drh9e572e62004-04-23 23:43:10 +0000891static void zeroPage(MemPage *pPage, int flags){
892 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +0000893 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +0000894 int hdr = pPage->hdrOffset;
drh9e572e62004-04-23 23:43:10 +0000895 int first;
896
danielk19773b8a05f2007-03-19 17:44:26 +0000897 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drh07d183d2005-05-01 22:52:42 +0000898 assert( &data[pBt->pageSize] == (unsigned char*)pPage );
danielk19773b8a05f2007-03-19 17:44:26 +0000899 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drhb6f41482004-05-14 01:58:11 +0000900 memset(&data[hdr], 0, pBt->usableSize - hdr);
drh9e572e62004-04-23 23:43:10 +0000901 data[hdr] = flags;
drh43605152004-05-29 21:46:49 +0000902 first = hdr + 8 + 4*((flags&PTF_LEAF)==0);
903 memset(&data[hdr+1], 0, 4);
904 data[hdr+7] = 0;
905 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +0000906 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +0000907 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +0000908 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +0000909 pPage->cellOffset = first;
910 pPage->nOverflow = 0;
drhda200cc2004-05-09 11:51:38 +0000911 pPage->idxShift = 0;
drh43605152004-05-29 21:46:49 +0000912 pPage->nCell = 0;
drhda200cc2004-05-09 11:51:38 +0000913 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +0000914}
915
916/*
drh3aac2dd2004-04-26 14:10:20 +0000917** Get a page from the pager. Initialize the MemPage.pBt and
918** MemPage.aData elements if needed.
drh538f5702007-04-13 02:14:30 +0000919**
920** If the noContent flag is set, it means that we do not care about
921** the content of the page at this time. So do not go to the disk
922** to fetch the content. Just fill in the content with zeros for now.
923** If in the future we call sqlite3PagerWrite() on this page, that
924** means we have started to be concerned about content and the disk
925** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +0000926*/
drh16a9b832007-05-05 18:39:25 +0000927int sqlite3BtreeGetPage(
928 BtShared *pBt, /* The btree */
929 Pgno pgno, /* Number of the page to fetch */
930 MemPage **ppPage, /* Return the page in this parameter */
931 int noContent /* Do not load page content if true */
932){
drh3aac2dd2004-04-26 14:10:20 +0000933 int rc;
drh3aac2dd2004-04-26 14:10:20 +0000934 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +0000935 DbPage *pDbPage;
936
drh538f5702007-04-13 02:14:30 +0000937 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
drh3aac2dd2004-04-26 14:10:20 +0000938 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +0000939 pPage = (MemPage *)sqlite3PagerGetExtra(pDbPage);
940 pPage->aData = sqlite3PagerGetData(pDbPage);
941 pPage->pDbPage = pDbPage;
drh3aac2dd2004-04-26 14:10:20 +0000942 pPage->pBt = pBt;
943 pPage->pgno = pgno;
drhde647132004-05-07 17:57:49 +0000944 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
drh3aac2dd2004-04-26 14:10:20 +0000945 *ppPage = pPage;
946 return SQLITE_OK;
947}
948
949/*
drhde647132004-05-07 17:57:49 +0000950** Get a page from the pager and initialize it. This routine
951** is just a convenience wrapper around separate calls to
drh16a9b832007-05-05 18:39:25 +0000952** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
drhde647132004-05-07 17:57:49 +0000953*/
954static int getAndInitPage(
danielk1977aef0bf62005-12-30 16:28:01 +0000955 BtShared *pBt, /* The database file */
drhde647132004-05-07 17:57:49 +0000956 Pgno pgno, /* Number of the page to get */
957 MemPage **ppPage, /* Write the page pointer here */
958 MemPage *pParent /* Parent of the page */
959){
960 int rc;
drhee696e22004-08-30 16:52:17 +0000961 if( pgno==0 ){
drh49285702005-09-17 15:20:26 +0000962 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +0000963 }
drh16a9b832007-05-05 18:39:25 +0000964 rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
drh10617cd2004-05-14 15:27:27 +0000965 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
drh16a9b832007-05-05 18:39:25 +0000966 rc = sqlite3BtreeInitPage(*ppPage, pParent);
drhde647132004-05-07 17:57:49 +0000967 }
968 return rc;
969}
970
971/*
drh3aac2dd2004-04-26 14:10:20 +0000972** Release a MemPage. This should be called once for each prior
drh16a9b832007-05-05 18:39:25 +0000973** call to sqlite3BtreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +0000974*/
drh4b70f112004-05-02 21:12:19 +0000975static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +0000976 if( pPage ){
977 assert( pPage->aData );
978 assert( pPage->pBt );
drh07d183d2005-05-01 22:52:42 +0000979 assert( &pPage->aData[pPage->pBt->pageSize]==(unsigned char*)pPage );
danielk19773b8a05f2007-03-19 17:44:26 +0000980 sqlite3PagerUnref(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +0000981 }
982}
983
984/*
drh72f82862001-05-24 21:06:34 +0000985** This routine is called when the reference count for a page
986** reaches zero. We need to unref the pParent pointer when that
987** happens.
988*/
danielk19773b8a05f2007-03-19 17:44:26 +0000989static void pageDestructor(DbPage *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +0000990 MemPage *pPage;
991 assert( (pageSize & 7)==0 );
danielk19773b8a05f2007-03-19 17:44:26 +0000992 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
drh72f82862001-05-24 21:06:34 +0000993 if( pPage->pParent ){
994 MemPage *pParent = pPage->pParent;
995 pPage->pParent = 0;
drha34b6762004-05-07 13:30:42 +0000996 releasePage(pParent);
drh72f82862001-05-24 21:06:34 +0000997 }
drh3aac2dd2004-04-26 14:10:20 +0000998 pPage->isInit = 0;
drh72f82862001-05-24 21:06:34 +0000999}
1000
1001/*
drha6abd042004-06-09 17:37:22 +00001002** During a rollback, when the pager reloads information into the cache
1003** so that the cache is restored to its original state at the start of
1004** the transaction, for each page restored this routine is called.
1005**
1006** This routine needs to reset the extra data section at the end of the
1007** page to agree with the restored data.
1008*/
danielk19773b8a05f2007-03-19 17:44:26 +00001009static void pageReinit(DbPage *pData, int pageSize){
drh07d183d2005-05-01 22:52:42 +00001010 MemPage *pPage;
1011 assert( (pageSize & 7)==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001012 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
drha6abd042004-06-09 17:37:22 +00001013 if( pPage->isInit ){
1014 pPage->isInit = 0;
drh16a9b832007-05-05 18:39:25 +00001015 sqlite3BtreeInitPage(pPage, pPage->pParent);
drha6abd042004-06-09 17:37:22 +00001016 }
1017}
1018
1019/*
drhad3e0102004-09-03 23:32:18 +00001020** Open a database file.
1021**
drh382c0242001-10-06 16:33:02 +00001022** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001023** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001024** database file will be deleted when sqlite3BtreeClose() is called.
drha059ad02001-04-17 20:09:11 +00001025*/
drh23e11ca2004-05-04 17:27:28 +00001026int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001027 const char *zFilename, /* Name of the file containing the BTree database */
danielk1977aef0bf62005-12-30 16:28:01 +00001028 sqlite3 *pSqlite, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001029 Btree **ppBtree, /* Pointer to new Btree object written here */
drh90f5ecb2004-07-22 01:19:35 +00001030 int flags /* Options */
drh6019e162001-07-02 17:51:45 +00001031){
danielk1977aef0bf62005-12-30 16:28:01 +00001032 BtShared *pBt; /* Shared part of btree structure */
1033 Btree *p; /* Handle to return */
danielk1977dddbcdc2007-04-26 14:42:34 +00001034 int rc = SQLITE_OK;
drh90f5ecb2004-07-22 01:19:35 +00001035 int nReserve;
1036 unsigned char zDbHeader[100];
drh6f7adc82006-01-11 21:41:20 +00001037#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1038 const ThreadData *pTsdro;
danielk1977da184232006-01-05 11:34:32 +00001039#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001040
1041 /* Set the variable isMemdb to true for an in-memory database, or
1042 ** false for a file-based database. This symbol is only required if
1043 ** either of the shared-data or autovacuum features are compiled
1044 ** into the library.
1045 */
1046#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
1047 #ifdef SQLITE_OMIT_MEMORYDB
drh980b1a72006-08-16 16:42:48 +00001048 const int isMemdb = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00001049 #else
drh980b1a72006-08-16 16:42:48 +00001050 const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
danielk1977aef0bf62005-12-30 16:28:01 +00001051 #endif
1052#endif
1053
1054 p = sqliteMalloc(sizeof(Btree));
1055 if( !p ){
1056 return SQLITE_NOMEM;
1057 }
1058 p->inTrans = TRANS_NONE;
1059 p->pSqlite = pSqlite;
1060
1061 /* Try to find an existing Btree structure opened on zFilename. */
drh198bf392006-01-06 21:52:49 +00001062#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drh6f7adc82006-01-11 21:41:20 +00001063 pTsdro = sqlite3ThreadDataReadOnly();
1064 if( pTsdro->useSharedData && zFilename && !isMemdb ){
drh66560ad2006-01-06 14:32:19 +00001065 char *zFullPathname = sqlite3OsFullPathname(zFilename);
danielk1977aef0bf62005-12-30 16:28:01 +00001066 if( !zFullPathname ){
1067 sqliteFree(p);
1068 return SQLITE_NOMEM;
1069 }
drh6f7adc82006-01-11 21:41:20 +00001070 for(pBt=pTsdro->pBtree; pBt; pBt=pBt->pNext){
danielk1977b82e7ed2006-01-11 14:09:31 +00001071 assert( pBt->nRef>0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001072 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager)) ){
danielk1977aef0bf62005-12-30 16:28:01 +00001073 p->pBt = pBt;
1074 *ppBtree = p;
1075 pBt->nRef++;
1076 sqliteFree(zFullPathname);
1077 return SQLITE_OK;
1078 }
1079 }
1080 sqliteFree(zFullPathname);
1081 }
1082#endif
drha059ad02001-04-17 20:09:11 +00001083
drhd62d3d02003-01-24 12:14:20 +00001084 /*
1085 ** The following asserts make sure that structures used by the btree are
1086 ** the right size. This is to guard against size changes that result
1087 ** when compiling on a different architecture.
1088 */
drh9b8f4472006-04-04 01:54:55 +00001089 assert( sizeof(i64)==8 || sizeof(i64)==4 );
1090 assert( sizeof(u64)==8 || sizeof(u64)==4 );
drhd62d3d02003-01-24 12:14:20 +00001091 assert( sizeof(u32)==4 );
1092 assert( sizeof(u16)==2 );
1093 assert( sizeof(Pgno)==4 );
drhd62d3d02003-01-24 12:14:20 +00001094
drha059ad02001-04-17 20:09:11 +00001095 pBt = sqliteMalloc( sizeof(*pBt) );
1096 if( pBt==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00001097 rc = SQLITE_NOMEM;
1098 goto btree_open_out;
drha059ad02001-04-17 20:09:11 +00001099 }
danielk19773b8a05f2007-03-19 17:44:26 +00001100 rc = sqlite3PagerOpen(&pBt->pPager, zFilename, EXTRA_SIZE, flags);
drh551b7732006-11-06 21:20:25 +00001101 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00001102 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
drh551b7732006-11-06 21:20:25 +00001103 }
drha059ad02001-04-17 20:09:11 +00001104 if( rc!=SQLITE_OK ){
danielk1977dddbcdc2007-04-26 14:42:34 +00001105 goto btree_open_out;
drha059ad02001-04-17 20:09:11 +00001106 }
danielk1977aef0bf62005-12-30 16:28:01 +00001107 p->pBt = pBt;
1108
danielk19773b8a05f2007-03-19 17:44:26 +00001109 sqlite3PagerSetDestructor(pBt->pPager, pageDestructor);
1110 sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
drha059ad02001-04-17 20:09:11 +00001111 pBt->pCursor = 0;
drha34b6762004-05-07 13:30:42 +00001112 pBt->pPage1 = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00001113 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
drh90f5ecb2004-07-22 01:19:35 +00001114 pBt->pageSize = get2byte(&zDbHeader[16]);
drh07d183d2005-05-01 22:52:42 +00001115 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1116 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
drh90f5ecb2004-07-22 01:19:35 +00001117 pBt->pageSize = SQLITE_DEFAULT_PAGE_SIZE;
1118 pBt->maxEmbedFrac = 64; /* 25% */
1119 pBt->minEmbedFrac = 32; /* 12.5% */
1120 pBt->minLeafFrac = 32; /* 12.5% */
drheee46cf2004-11-06 00:02:48 +00001121#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197703aded42004-11-22 05:26:27 +00001122 /* If the magic name ":memory:" will create an in-memory database, then
danielk1977dddbcdc2007-04-26 14:42:34 +00001123 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
1124 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
1125 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
1126 ** regular file-name. In this case the auto-vacuum applies as per normal.
danielk197703aded42004-11-22 05:26:27 +00001127 */
danielk1977aef0bf62005-12-30 16:28:01 +00001128 if( zFilename && !isMemdb ){
danielk1977dddbcdc2007-04-26 14:42:34 +00001129 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
1130 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
danielk1977951af802004-11-05 15:45:09 +00001131 }
drheee46cf2004-11-06 00:02:48 +00001132#endif
drh90f5ecb2004-07-22 01:19:35 +00001133 nReserve = 0;
1134 }else{
1135 nReserve = zDbHeader[20];
1136 pBt->maxEmbedFrac = zDbHeader[21];
1137 pBt->minEmbedFrac = zDbHeader[22];
1138 pBt->minLeafFrac = zDbHeader[23];
1139 pBt->pageSizeFixed = 1;
danielk1977951af802004-11-05 15:45:09 +00001140#ifndef SQLITE_OMIT_AUTOVACUUM
1141 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1142#endif
drh90f5ecb2004-07-22 01:19:35 +00001143 }
1144 pBt->usableSize = pBt->pageSize - nReserve;
drh07d183d2005-05-01 22:52:42 +00001145 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
danielk19773b8a05f2007-03-19 17:44:26 +00001146 sqlite3PagerSetPagesize(pBt->pPager, pBt->pageSize);
danielk1977aef0bf62005-12-30 16:28:01 +00001147
drhcfed7bc2006-03-13 14:28:05 +00001148#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
danielk197754f01982006-01-18 15:25:17 +00001149 /* Add the new btree to the linked list starting at ThreadData.pBtree.
1150 ** There is no chance that a malloc() may fail inside of the
1151 ** sqlite3ThreadData() call, as the ThreadData structure must have already
1152 ** been allocated for pTsdro->useSharedData to be non-zero.
1153 */
drh6f7adc82006-01-11 21:41:20 +00001154 if( pTsdro->useSharedData && zFilename && !isMemdb ){
1155 pBt->pNext = pTsdro->pBtree;
1156 sqlite3ThreadData()->pBtree = pBt;
danielk1977aef0bf62005-12-30 16:28:01 +00001157 }
danielk1977aef0bf62005-12-30 16:28:01 +00001158#endif
danielk1977da184232006-01-05 11:34:32 +00001159 pBt->nRef = 1;
danielk1977aef0bf62005-12-30 16:28:01 +00001160 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00001161
1162btree_open_out:
1163 if( rc!=SQLITE_OK ){
1164 if( pBt && pBt->pPager ){
1165 sqlite3PagerClose(pBt->pPager);
1166 }
1167 sqliteFree(pBt);
1168 sqliteFree(p);
1169 *ppBtree = 0;
1170 }
1171 return rc;
drha059ad02001-04-17 20:09:11 +00001172}
1173
1174/*
1175** Close an open database and invalidate all cursors.
1176*/
danielk1977aef0bf62005-12-30 16:28:01 +00001177int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00001178 BtShared *pBt = p->pBt;
1179 BtCursor *pCur;
1180
danielk1977da184232006-01-05 11:34:32 +00001181#ifndef SQLITE_OMIT_SHARED_CACHE
drh6f7adc82006-01-11 21:41:20 +00001182 ThreadData *pTsd;
danielk1977da184232006-01-05 11:34:32 +00001183#endif
1184
danielk1977aef0bf62005-12-30 16:28:01 +00001185 /* Close all cursors opened via this handle. */
1186 pCur = pBt->pCursor;
1187 while( pCur ){
1188 BtCursor *pTmp = pCur;
1189 pCur = pCur->pNext;
1190 if( pTmp->pBtree==p ){
1191 sqlite3BtreeCloseCursor(pTmp);
1192 }
drha059ad02001-04-17 20:09:11 +00001193 }
danielk1977aef0bf62005-12-30 16:28:01 +00001194
danielk19778d34dfd2006-01-24 16:37:57 +00001195 /* Rollback any active transaction and free the handle structure.
1196 ** The call to sqlite3BtreeRollback() drops any table-locks held by
1197 ** this handle.
1198 */
danielk1977b597f742006-01-15 11:39:18 +00001199 sqlite3BtreeRollback(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001200 sqliteFree(p);
1201
1202#ifndef SQLITE_OMIT_SHARED_CACHE
1203 /* If there are still other outstanding references to the shared-btree
1204 ** structure, return now. The remainder of this procedure cleans
1205 ** up the shared-btree.
1206 */
1207 assert( pBt->nRef>0 );
1208 pBt->nRef--;
1209 if( pBt->nRef ){
1210 return SQLITE_OK;
1211 }
1212
danielk197754f01982006-01-18 15:25:17 +00001213 /* Remove the shared-btree from the thread wide list. Call
1214 ** ThreadDataReadOnly() and then cast away the const property of the
1215 ** pointer to avoid allocating thread data if it is not really required.
1216 */
1217 pTsd = (ThreadData *)sqlite3ThreadDataReadOnly();
danielk1977aef0bf62005-12-30 16:28:01 +00001218 if( pTsd->pBtree==pBt ){
danielk197754f01982006-01-18 15:25:17 +00001219 assert( pTsd==sqlite3ThreadData() );
danielk1977aef0bf62005-12-30 16:28:01 +00001220 pTsd->pBtree = pBt->pNext;
1221 }else{
1222 BtShared *pPrev;
drh74161702006-02-24 02:53:49 +00001223 for(pPrev=pTsd->pBtree; pPrev && pPrev->pNext!=pBt; pPrev=pPrev->pNext){}
danielk1977aef0bf62005-12-30 16:28:01 +00001224 if( pPrev ){
danielk197754f01982006-01-18 15:25:17 +00001225 assert( pTsd==sqlite3ThreadData() );
danielk1977aef0bf62005-12-30 16:28:01 +00001226 pPrev->pNext = pBt->pNext;
1227 }
1228 }
1229#endif
1230
1231 /* Close the pager and free the shared-btree structure */
1232 assert( !pBt->pCursor );
danielk19773b8a05f2007-03-19 17:44:26 +00001233 sqlite3PagerClose(pBt->pPager);
danielk1977da184232006-01-05 11:34:32 +00001234 if( pBt->xFreeSchema && pBt->pSchema ){
1235 pBt->xFreeSchema(pBt->pSchema);
1236 }
danielk1977de0fe3e2006-01-06 06:33:12 +00001237 sqliteFree(pBt->pSchema);
drha059ad02001-04-17 20:09:11 +00001238 sqliteFree(pBt);
1239 return SQLITE_OK;
1240}
1241
1242/*
drh90f5ecb2004-07-22 01:19:35 +00001243** Change the busy handler callback function.
1244*/
danielk1977aef0bf62005-12-30 16:28:01 +00001245int sqlite3BtreeSetBusyHandler(Btree *p, BusyHandler *pHandler){
1246 BtShared *pBt = p->pBt;
drhb8ef32c2005-03-14 02:01:49 +00001247 pBt->pBusyHandler = pHandler;
danielk19773b8a05f2007-03-19 17:44:26 +00001248 sqlite3PagerSetBusyhandler(pBt->pPager, pHandler);
drh90f5ecb2004-07-22 01:19:35 +00001249 return SQLITE_OK;
1250}
1251
1252/*
drhda47d772002-12-02 04:25:19 +00001253** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001254**
1255** The maximum number of cache pages is set to the absolute
1256** value of mxPage. If mxPage is negative, the pager will
1257** operate asynchronously - it will not stop to do fsync()s
1258** to insure data is written to the disk surface before
1259** continuing. Transactions still work if synchronous is off,
1260** and the database cannot be corrupted if this program
1261** crashes. But if the operating system crashes or there is
1262** an abrupt power failure when synchronous is off, the database
1263** could be left in an inconsistent and unrecoverable state.
1264** Synchronous is on by default so database corruption is not
1265** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001266*/
danielk1977aef0bf62005-12-30 16:28:01 +00001267int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
1268 BtShared *pBt = p->pBt;
danielk19773b8a05f2007-03-19 17:44:26 +00001269 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhf57b14a2001-09-14 18:54:08 +00001270 return SQLITE_OK;
1271}
1272
1273/*
drh973b6e32003-02-12 14:09:42 +00001274** Change the way data is synced to disk in order to increase or decrease
1275** how well the database resists damage due to OS crashes and power
1276** failures. Level 1 is the same as asynchronous (no syncs() occur and
1277** there is a high probability of damage) Level 2 is the default. There
1278** is a very low but non-zero probability of damage. Level 3 reduces the
1279** probability of damage to near zero but with a write performance reduction.
1280*/
danielk197793758c82005-01-21 08:13:14 +00001281#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drhac530b12006-02-11 01:25:50 +00001282int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
danielk1977aef0bf62005-12-30 16:28:01 +00001283 BtShared *pBt = p->pBt;
danielk19773b8a05f2007-03-19 17:44:26 +00001284 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
drh973b6e32003-02-12 14:09:42 +00001285 return SQLITE_OK;
1286}
danielk197793758c82005-01-21 08:13:14 +00001287#endif
drh973b6e32003-02-12 14:09:42 +00001288
drh2c8997b2005-08-27 16:36:48 +00001289/*
1290** Return TRUE if the given btree is set to safety level 1. In other
1291** words, return TRUE if no sync() occurs on the disk files.
1292*/
danielk1977aef0bf62005-12-30 16:28:01 +00001293int sqlite3BtreeSyncDisabled(Btree *p){
1294 BtShared *pBt = p->pBt;
drh2c8997b2005-08-27 16:36:48 +00001295 assert( pBt && pBt->pPager );
danielk19773b8a05f2007-03-19 17:44:26 +00001296 return sqlite3PagerNosync(pBt->pPager);
drh2c8997b2005-08-27 16:36:48 +00001297}
1298
danielk1977576ec6b2005-01-21 11:55:25 +00001299#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00001300/*
drh90f5ecb2004-07-22 01:19:35 +00001301** Change the default pages size and the number of reserved bytes per page.
drh06f50212004-11-02 14:24:33 +00001302**
1303** The page size must be a power of 2 between 512 and 65536. If the page
1304** size supplied does not meet this constraint then the page size is not
1305** changed.
1306**
1307** Page sizes are constrained to be a power of two so that the region
1308** of the database file used for locking (beginning at PENDING_BYTE,
1309** the first byte past the 1GB boundary, 0x40000000) needs to occur
1310** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001311**
1312** If parameter nReserve is less than zero, then the number of reserved
1313** bytes per page is left unchanged.
drh90f5ecb2004-07-22 01:19:35 +00001314*/
danielk1977aef0bf62005-12-30 16:28:01 +00001315int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
1316 BtShared *pBt = p->pBt;
drh90f5ecb2004-07-22 01:19:35 +00001317 if( pBt->pageSizeFixed ){
1318 return SQLITE_READONLY;
1319 }
1320 if( nReserve<0 ){
1321 nReserve = pBt->pageSize - pBt->usableSize;
1322 }
drh06f50212004-11-02 14:24:33 +00001323 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
1324 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00001325 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00001326 assert( !pBt->pPage1 && !pBt->pCursor );
danielk19773b8a05f2007-03-19 17:44:26 +00001327 pBt->pageSize = sqlite3PagerSetPagesize(pBt->pPager, pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001328 }
1329 pBt->usableSize = pBt->pageSize - nReserve;
1330 return SQLITE_OK;
1331}
1332
1333/*
1334** Return the currently defined page size
1335*/
danielk1977aef0bf62005-12-30 16:28:01 +00001336int sqlite3BtreeGetPageSize(Btree *p){
1337 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00001338}
danielk1977aef0bf62005-12-30 16:28:01 +00001339int sqlite3BtreeGetReserve(Btree *p){
1340 return p->pBt->pageSize - p->pBt->usableSize;
drh2011d5f2004-07-22 02:40:37 +00001341}
drhf8e632b2007-05-08 14:51:36 +00001342
1343/*
1344** Set the maximum page count for a database if mxPage is positive.
1345** No changes are made if mxPage is 0 or negative.
1346** Regardless of the value of mxPage, return the maximum page count.
1347*/
1348int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
1349 return sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
1350}
danielk1977576ec6b2005-01-21 11:55:25 +00001351#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00001352
1353/*
danielk1977951af802004-11-05 15:45:09 +00001354** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
1355** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
1356** is disabled. The default value for the auto-vacuum property is
1357** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
1358*/
danielk1977aef0bf62005-12-30 16:28:01 +00001359int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00001360#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001361 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00001362#else
danielk1977dddbcdc2007-04-26 14:42:34 +00001363 BtShared *pBt = p->pBt;
1364 int av = (autoVacuum?1:0);
1365 int iv = (autoVacuum==BTREE_AUTOVACUUM_INCR?1:0);
1366 if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
danielk1977951af802004-11-05 15:45:09 +00001367 return SQLITE_READONLY;
1368 }
danielk1977dddbcdc2007-04-26 14:42:34 +00001369 pBt->autoVacuum = av;
1370 pBt->incrVacuum = iv;
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);
1439#endif
drh306dc212001-05-21 13:45:10 +00001440 }
drhb6f41482004-05-14 01:58:11 +00001441
1442 /* maxLocal is the maximum amount of payload to store locally for
1443 ** a cell. Make sure it is small enough so that at least minFanout
1444 ** cells can will fit on one page. We assume a 10-byte page header.
1445 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001446 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001447 ** 4-byte child pointer
1448 ** 9-byte nKey value
1449 ** 4-byte nData value
1450 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001451 ** So a cell consists of a 2-byte poiner, a header which is as much as
1452 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1453 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001454 */
drh43605152004-05-29 21:46:49 +00001455 pBt->maxLocal = (pBt->usableSize-12)*pBt->maxEmbedFrac/255 - 23;
1456 pBt->minLocal = (pBt->usableSize-12)*pBt->minEmbedFrac/255 - 23;
1457 pBt->maxLeaf = pBt->usableSize - 35;
1458 pBt->minLeaf = (pBt->usableSize-12)*pBt->minLeafFrac/255 - 23;
drhb6f41482004-05-14 01:58:11 +00001459 if( pBt->minLocal>pBt->maxLocal || pBt->maxLocal<0 ){
1460 goto page1_init_failed;
1461 }
drh2e38c322004-09-03 18:38:44 +00001462 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00001463 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001464 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001465
drh72f82862001-05-24 21:06:34 +00001466page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001467 releasePage(pPage1);
1468 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001469 return rc;
drh306dc212001-05-21 13:45:10 +00001470}
1471
1472/*
drhb8ef32c2005-03-14 02:01:49 +00001473** This routine works like lockBtree() except that it also invokes the
1474** busy callback if there is lock contention.
1475*/
danielk1977aef0bf62005-12-30 16:28:01 +00001476static int lockBtreeWithRetry(Btree *pRef){
drhb8ef32c2005-03-14 02:01:49 +00001477 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00001478 if( pRef->inTrans==TRANS_NONE ){
1479 u8 inTransaction = pRef->pBt->inTransaction;
1480 btreeIntegrity(pRef);
1481 rc = sqlite3BtreeBeginTrans(pRef, 0);
1482 pRef->pBt->inTransaction = inTransaction;
1483 pRef->inTrans = TRANS_NONE;
1484 if( rc==SQLITE_OK ){
1485 pRef->pBt->nTransaction--;
1486 }
1487 btreeIntegrity(pRef);
drhb8ef32c2005-03-14 02:01:49 +00001488 }
1489 return rc;
1490}
1491
1492
1493/*
drhb8ca3072001-12-05 00:21:20 +00001494** If there are no outstanding cursors and we are not in the middle
1495** of a transaction but there is a read lock on the database, then
1496** this routine unrefs the first page of the database file which
1497** has the effect of releasing the read lock.
1498**
1499** If there are any outstanding cursors, this routine is a no-op.
1500**
1501** If there is a transaction in progress, this routine is a no-op.
1502*/
danielk1977aef0bf62005-12-30 16:28:01 +00001503static void unlockBtreeIfUnused(BtShared *pBt){
1504 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00001505 if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
drh24c9a2e2007-01-05 02:00:47 +00001506 if( pBt->pPage1->aData==0 ){
1507 MemPage *pPage = pBt->pPage1;
1508 pPage->aData = &((u8*)pPage)[-pBt->pageSize];
1509 pPage->pBt = pBt;
1510 pPage->pgno = 1;
1511 }
1512 releasePage(pBt->pPage1);
drh51c6d962004-06-06 00:42:25 +00001513 }
drh3aac2dd2004-04-26 14:10:20 +00001514 pBt->pPage1 = 0;
drh3aac2dd2004-04-26 14:10:20 +00001515 pBt->inStmt = 0;
drhb8ca3072001-12-05 00:21:20 +00001516 }
1517}
1518
1519/*
drh9e572e62004-04-23 23:43:10 +00001520** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00001521** file.
drh8b2f49b2001-06-08 00:21:52 +00001522*/
danielk1977aef0bf62005-12-30 16:28:01 +00001523static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00001524 MemPage *pP1;
1525 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00001526 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001527 if( sqlite3PagerPagecount(pBt->pPager)>0 ) return SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00001528 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00001529 assert( pP1!=0 );
1530 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00001531 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00001532 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00001533 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
1534 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00001535 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00001536 data[18] = 1;
1537 data[19] = 1;
drhb6f41482004-05-14 01:58:11 +00001538 data[20] = pBt->pageSize - pBt->usableSize;
1539 data[21] = pBt->maxEmbedFrac;
1540 data[22] = pBt->minEmbedFrac;
1541 data[23] = pBt->minLeafFrac;
1542 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00001543 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00001544 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00001545#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00001546 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
1547 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977003ba062004-11-04 02:57:33 +00001548#endif
drh8b2f49b2001-06-08 00:21:52 +00001549 return SQLITE_OK;
1550}
1551
1552/*
danielk1977ee5741e2004-05-31 10:01:34 +00001553** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00001554** is started if the second argument is nonzero, otherwise a read-
1555** transaction. If the second argument is 2 or more and exclusive
1556** transaction is started, meaning that no other process is allowed
1557** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00001558** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00001559** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00001560**
danielk1977ee5741e2004-05-31 10:01:34 +00001561** A write-transaction must be started before attempting any
1562** changes to the database. None of the following routines
1563** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00001564**
drh23e11ca2004-05-04 17:27:28 +00001565** sqlite3BtreeCreateTable()
1566** sqlite3BtreeCreateIndex()
1567** sqlite3BtreeClearTable()
1568** sqlite3BtreeDropTable()
1569** sqlite3BtreeInsert()
1570** sqlite3BtreeDelete()
1571** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00001572**
drhb8ef32c2005-03-14 02:01:49 +00001573** If an initial attempt to acquire the lock fails because of lock contention
1574** and the database was previously unlocked, then invoke the busy handler
1575** if there is one. But if there was previously a read-lock, do not
1576** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
1577** returned when there is already a read-lock in order to avoid a deadlock.
1578**
1579** Suppose there are two processes A and B. A has a read lock and B has
1580** a reserved lock. B tries to promote to exclusive but is blocked because
1581** of A's read lock. A tries to promote to reserved but is blocked by B.
1582** One or the other of the two processes must give way or there can be
1583** no progress. By returning SQLITE_BUSY and not invoking the busy callback
1584** when A already has a read lock, we encourage A to give up and let B
1585** proceed.
drha059ad02001-04-17 20:09:11 +00001586*/
danielk1977aef0bf62005-12-30 16:28:01 +00001587int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
1588 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00001589 int rc = SQLITE_OK;
1590
danielk1977aef0bf62005-12-30 16:28:01 +00001591 btreeIntegrity(p);
1592
danielk1977ee5741e2004-05-31 10:01:34 +00001593 /* If the btree is already in a write-transaction, or it
1594 ** is already in a read-transaction and a read-transaction
1595 ** is requested, this is a no-op.
1596 */
danielk1977aef0bf62005-12-30 16:28:01 +00001597 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
danielk1977ee5741e2004-05-31 10:01:34 +00001598 return SQLITE_OK;
1599 }
drhb8ef32c2005-03-14 02:01:49 +00001600
1601 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00001602 if( pBt->readOnly && wrflag ){
1603 return SQLITE_READONLY;
1604 }
1605
danielk1977aef0bf62005-12-30 16:28:01 +00001606 /* If another database handle has already opened a write transaction
1607 ** on this shared-btree structure and a second write transaction is
1608 ** requested, return SQLITE_BUSY.
1609 */
1610 if( pBt->inTransaction==TRANS_WRITE && wrflag ){
1611 return SQLITE_BUSY;
1612 }
1613
drhb8ef32c2005-03-14 02:01:49 +00001614 do {
1615 if( pBt->pPage1==0 ){
1616 rc = lockBtree(pBt);
drh8c42ca92001-06-22 19:15:00 +00001617 }
drh309169a2007-04-24 17:27:51 +00001618
drhb8ef32c2005-03-14 02:01:49 +00001619 if( rc==SQLITE_OK && wrflag ){
drh309169a2007-04-24 17:27:51 +00001620 if( pBt->readOnly ){
1621 rc = SQLITE_READONLY;
1622 }else{
1623 rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1);
1624 if( rc==SQLITE_OK ){
1625 rc = newDatabase(pBt);
1626 }
drhb8ef32c2005-03-14 02:01:49 +00001627 }
1628 }
1629
1630 if( rc==SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00001631 if( wrflag ) pBt->inStmt = 0;
1632 }else{
1633 unlockBtreeIfUnused(pBt);
1634 }
danielk1977aef0bf62005-12-30 16:28:01 +00001635 }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
drha4afb652005-07-09 02:16:02 +00001636 sqlite3InvokeBusyHandler(pBt->pBusyHandler) );
danielk1977aef0bf62005-12-30 16:28:01 +00001637
1638 if( rc==SQLITE_OK ){
1639 if( p->inTrans==TRANS_NONE ){
1640 pBt->nTransaction++;
1641 }
1642 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
1643 if( p->inTrans>pBt->inTransaction ){
1644 pBt->inTransaction = p->inTrans;
1645 }
1646 }
1647
1648 btreeIntegrity(p);
drhb8ca3072001-12-05 00:21:20 +00001649 return rc;
drha059ad02001-04-17 20:09:11 +00001650}
1651
danielk1977687566d2004-11-02 12:56:41 +00001652#ifndef SQLITE_OMIT_AUTOVACUUM
1653
1654/*
1655** Set the pointer-map entries for all children of page pPage. Also, if
1656** pPage contains cells that point to overflow pages, set the pointer
1657** map entries for the overflow pages as well.
1658*/
1659static int setChildPtrmaps(MemPage *pPage){
1660 int i; /* Counter variable */
1661 int nCell; /* Number of cells in page pPage */
1662 int rc = SQLITE_OK; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00001663 BtShared *pBt = pPage->pBt;
danielk1977687566d2004-11-02 12:56:41 +00001664 int isInitOrig = pPage->isInit;
1665 Pgno pgno = pPage->pgno;
1666
drh16a9b832007-05-05 18:39:25 +00001667 sqlite3BtreeInitPage(pPage, 0);
danielk1977687566d2004-11-02 12:56:41 +00001668 nCell = pPage->nCell;
1669
1670 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00001671 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00001672
danielk197726836652005-01-17 01:33:13 +00001673 rc = ptrmapPutOvflPtr(pPage, pCell);
1674 if( rc!=SQLITE_OK ){
1675 goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00001676 }
danielk197726836652005-01-17 01:33:13 +00001677
danielk1977687566d2004-11-02 12:56:41 +00001678 if( !pPage->leaf ){
1679 Pgno childPgno = get4byte(pCell);
1680 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
1681 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
1682 }
1683 }
1684
1685 if( !pPage->leaf ){
1686 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
1687 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
1688 }
1689
1690set_child_ptrmaps_out:
1691 pPage->isInit = isInitOrig;
1692 return rc;
1693}
1694
1695/*
1696** Somewhere on pPage, which is guarenteed to be a btree page, not an overflow
1697** page, is a pointer to page iFrom. Modify this pointer so that it points to
1698** iTo. Parameter eType describes the type of pointer to be modified, as
1699** follows:
1700**
1701** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
1702** page of pPage.
1703**
1704** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
1705** page pointed to by one of the cells on pPage.
1706**
1707** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
1708** overflow page in the list.
1709*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00001710static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
danielk1977687566d2004-11-02 12:56:41 +00001711 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00001712 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00001713 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00001714 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00001715 }
danielk1977f78fc082004-11-02 14:40:32 +00001716 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00001717 }else{
1718 int isInitOrig = pPage->isInit;
1719 int i;
1720 int nCell;
1721
drh16a9b832007-05-05 18:39:25 +00001722 sqlite3BtreeInitPage(pPage, 0);
danielk1977687566d2004-11-02 12:56:41 +00001723 nCell = pPage->nCell;
1724
danielk1977687566d2004-11-02 12:56:41 +00001725 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00001726 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00001727 if( eType==PTRMAP_OVERFLOW1 ){
1728 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00001729 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
danielk1977687566d2004-11-02 12:56:41 +00001730 if( info.iOverflow ){
1731 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
1732 put4byte(&pCell[info.iOverflow], iTo);
1733 break;
1734 }
1735 }
1736 }else{
1737 if( get4byte(pCell)==iFrom ){
1738 put4byte(pCell, iTo);
1739 break;
1740 }
1741 }
1742 }
1743
1744 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00001745 if( eType!=PTRMAP_BTREE ||
1746 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00001747 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00001748 }
danielk1977687566d2004-11-02 12:56:41 +00001749 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
1750 }
1751
1752 pPage->isInit = isInitOrig;
1753 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00001754 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00001755}
1756
danielk1977003ba062004-11-04 02:57:33 +00001757
danielk19777701e812005-01-10 12:59:51 +00001758/*
1759** Move the open database page pDbPage to location iFreePage in the
1760** database. The pDbPage reference remains valid.
1761*/
danielk1977003ba062004-11-04 02:57:33 +00001762static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00001763 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00001764 MemPage *pDbPage, /* Open page to move */
1765 u8 eType, /* Pointer map 'type' entry for pDbPage */
1766 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
1767 Pgno iFreePage /* The location to move pDbPage to */
danielk1977003ba062004-11-04 02:57:33 +00001768){
1769 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
1770 Pgno iDbPage = pDbPage->pgno;
1771 Pager *pPager = pBt->pPager;
1772 int rc;
1773
danielk1977a0bf2652004-11-04 14:30:04 +00001774 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
1775 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
danielk1977003ba062004-11-04 02:57:33 +00001776
1777 /* Move page iDbPage from it's current location to page number iFreePage */
1778 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
1779 iDbPage, iFreePage, iPtrPage, eType));
danielk19773b8a05f2007-03-19 17:44:26 +00001780 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage);
danielk1977003ba062004-11-04 02:57:33 +00001781 if( rc!=SQLITE_OK ){
1782 return rc;
1783 }
1784 pDbPage->pgno = iFreePage;
1785
1786 /* If pDbPage was a btree-page, then it may have child pages and/or cells
1787 ** that point to overflow pages. The pointer map entries for all these
1788 ** pages need to be changed.
1789 **
1790 ** If pDbPage is an overflow page, then the first 4 bytes may store a
1791 ** pointer to a subsequent overflow page. If this is the case, then
1792 ** the pointer map needs to be updated for the subsequent overflow page.
1793 */
danielk1977a0bf2652004-11-04 14:30:04 +00001794 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00001795 rc = setChildPtrmaps(pDbPage);
1796 if( rc!=SQLITE_OK ){
1797 return rc;
1798 }
1799 }else{
1800 Pgno nextOvfl = get4byte(pDbPage->aData);
1801 if( nextOvfl!=0 ){
danielk1977003ba062004-11-04 02:57:33 +00001802 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
1803 if( rc!=SQLITE_OK ){
1804 return rc;
1805 }
1806 }
1807 }
1808
1809 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
1810 ** that it points at iFreePage. Also fix the pointer map entry for
1811 ** iPtrPage.
1812 */
danielk1977a0bf2652004-11-04 14:30:04 +00001813 if( eType!=PTRMAP_ROOTPAGE ){
drh16a9b832007-05-05 18:39:25 +00001814 rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00001815 if( rc!=SQLITE_OK ){
1816 return rc;
1817 }
danielk19773b8a05f2007-03-19 17:44:26 +00001818 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00001819 if( rc!=SQLITE_OK ){
1820 releasePage(pPtrPage);
1821 return rc;
1822 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00001823 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00001824 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00001825 if( rc==SQLITE_OK ){
1826 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
1827 }
danielk1977003ba062004-11-04 02:57:33 +00001828 }
danielk1977003ba062004-11-04 02:57:33 +00001829 return rc;
1830}
1831
danielk1977dddbcdc2007-04-26 14:42:34 +00001832/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00001833static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00001834
1835/*
danielk1977dddbcdc2007-04-26 14:42:34 +00001836** Perform a single step of an incremental-vacuum. If successful,
1837** return SQLITE_OK. If there is no work to do (and therefore no
1838** point in calling this function again), return SQLITE_DONE.
1839**
1840** More specificly, this function attempts to re-organize the
1841** database so that the last page of the file currently in use
1842** is no longer in use.
1843**
1844** If the nFin parameter is non-zero, the implementation assumes
1845** that the caller will keep calling incrVacuumStep() until
1846** it returns SQLITE_DONE or an error, and that nFin is the
1847** number of pages the database file will contain after this
1848** process is complete.
1849*/
1850static int incrVacuumStep(BtShared *pBt, Pgno nFin){
1851 Pgno iLastPg; /* Last page in the database */
1852 Pgno nFreeList; /* Number of pages still on the free-list */
1853
1854 iLastPg = pBt->nTrunc;
1855 if( iLastPg==0 ){
1856 iLastPg = sqlite3PagerPagecount(pBt->pPager);
1857 }
1858
1859 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
1860 int rc;
1861 u8 eType;
1862 Pgno iPtrPage;
1863
1864 nFreeList = get4byte(&pBt->pPage1->aData[36]);
1865 if( nFreeList==0 || nFin==iLastPg ){
1866 return SQLITE_DONE;
1867 }
1868
1869 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
1870 if( rc!=SQLITE_OK ){
1871 return rc;
1872 }
1873 if( eType==PTRMAP_ROOTPAGE ){
1874 return SQLITE_CORRUPT_BKPT;
1875 }
1876
1877 if( eType==PTRMAP_FREEPAGE ){
1878 if( nFin==0 ){
1879 /* Remove the page from the files free-list. This is not required
1880 ** if nFin is non-zero. In this case, the free-list will be
1881 ** truncated to zero after this function returns, so it doesn't
1882 ** matter if it still contains some garbage entries.
1883 */
1884 Pgno iFreePg;
1885 MemPage *pFreePg;
1886 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
1887 if( rc!=SQLITE_OK ){
1888 return rc;
1889 }
1890 assert( iFreePg==iLastPg );
1891 releasePage(pFreePg);
1892 }
1893 } else {
1894 Pgno iFreePg; /* Index of free page to move pLastPg to */
1895 MemPage *pLastPg;
1896
drh16a9b832007-05-05 18:39:25 +00001897 rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00001898 if( rc!=SQLITE_OK ){
1899 return rc;
1900 }
1901
danielk1977b4626a32007-04-28 15:47:43 +00001902 /* If nFin is zero, this loop runs exactly once and page pLastPg
1903 ** is swapped with the first free page pulled off the free list.
1904 **
1905 ** On the other hand, if nFin is greater than zero, then keep
1906 ** looping until a free-page located within the first nFin pages
1907 ** of the file is found.
1908 */
danielk1977dddbcdc2007-04-26 14:42:34 +00001909 do {
1910 MemPage *pFreePg;
1911 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
1912 if( rc!=SQLITE_OK ){
1913 releasePage(pLastPg);
1914 return rc;
1915 }
1916 releasePage(pFreePg);
1917 }while( nFin!=0 && iFreePg>nFin );
1918 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00001919
1920 rc = sqlite3PagerWrite(pLastPg->pDbPage);
1921 if( rc!=SQLITE_OK ){
1922 return rc;
1923 }
danielk1977dddbcdc2007-04-26 14:42:34 +00001924 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg);
1925 releasePage(pLastPg);
1926 if( rc!=SQLITE_OK ){
1927 return rc;
1928 }
1929 }
1930 }
1931
1932 pBt->nTrunc = iLastPg - 1;
1933 while( pBt->nTrunc==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, pBt->nTrunc) ){
1934 pBt->nTrunc--;
1935 }
1936 return SQLITE_OK;
1937}
1938
1939/*
1940** A write-transaction must be opened before calling this function.
1941** It performs a single unit of work towards an incremental vacuum.
1942**
1943** If the incremental vacuum is finished after this function has run,
1944** SQLITE_DONE is returned. If it is not finished, but no error occured,
1945** SQLITE_OK is returned. Otherwise an SQLite error code.
1946*/
1947int sqlite3BtreeIncrVacuum(Btree *p){
1948 BtShared *pBt = p->pBt;
danielk1977dddbcdc2007-04-26 14:42:34 +00001949 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
1950 if( !pBt->autoVacuum ){
1951 return SQLITE_DONE;
1952 }
danielk197792d4d7a2007-05-04 12:05:56 +00001953 invalidateAllOverflowCache(pBt);
danielk19772dec9702007-05-02 16:48:37 +00001954 return incrVacuumStep(pBt, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00001955}
1956
1957/*
danielk19773b8a05f2007-03-19 17:44:26 +00001958** This routine is called prior to sqlite3PagerCommit when a transaction
danielk1977687566d2004-11-02 12:56:41 +00001959** is commited for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00001960**
1961** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
1962** the database file should be truncated to during the commit process.
1963** i.e. the database has been reorganized so that only the first *pnTrunc
1964** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00001965*/
danielk197724168722007-04-02 05:07:47 +00001966static int autoVacuumCommit(BtShared *pBt, Pgno *pnTrunc){
danielk1977dddbcdc2007-04-26 14:42:34 +00001967 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00001968 Pager *pPager = pBt->pPager;
danielk1977687566d2004-11-02 12:56:41 +00001969#ifndef NDEBUG
danielk19773b8a05f2007-03-19 17:44:26 +00001970 int nRef = sqlite3PagerRefcount(pPager);
danielk1977687566d2004-11-02 12:56:41 +00001971#endif
1972
danielk197792d4d7a2007-05-04 12:05:56 +00001973 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00001974 assert(pBt->autoVacuum);
1975 if( !pBt->incrVacuum ){
1976 Pgno nFin = 0;
danielk1977687566d2004-11-02 12:56:41 +00001977
danielk1977dddbcdc2007-04-26 14:42:34 +00001978 if( pBt->nTrunc==0 ){
1979 Pgno nFree;
1980 Pgno nPtrmap;
1981 const int pgsz = pBt->pageSize;
1982 Pgno nOrig = sqlite3PagerPagecount(pBt->pPager);
danielk1977e5321f02007-04-27 07:05:44 +00001983
1984 if( PTRMAP_ISPAGE(pBt, nOrig) ){
1985 return SQLITE_CORRUPT_BKPT;
1986 }
danielk1977dddbcdc2007-04-26 14:42:34 +00001987 if( nOrig==PENDING_BYTE_PAGE(pBt) ){
1988 nOrig--;
danielk1977687566d2004-11-02 12:56:41 +00001989 }
danielk1977dddbcdc2007-04-26 14:42:34 +00001990 nFree = get4byte(&pBt->pPage1->aData[36]);
1991 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
1992 nFin = nOrig - nFree - nPtrmap;
1993 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<=PENDING_BYTE_PAGE(pBt) ){
1994 nFin--;
danielk1977ac11ee62005-01-15 12:45:51 +00001995 }
danielk1977dddbcdc2007-04-26 14:42:34 +00001996 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
1997 nFin--;
1998 }
1999 }
danielk1977687566d2004-11-02 12:56:41 +00002000
danielk1977dddbcdc2007-04-26 14:42:34 +00002001 while( rc==SQLITE_OK ){
2002 rc = incrVacuumStep(pBt, nFin);
2003 }
2004 if( rc==SQLITE_DONE ){
2005 assert(nFin==0 || pBt->nTrunc==0 || nFin<=pBt->nTrunc);
2006 rc = SQLITE_OK;
2007 if( pBt->nTrunc ){
2008 sqlite3PagerWrite(pBt->pPage1->pDbPage);
2009 put4byte(&pBt->pPage1->aData[32], 0);
2010 put4byte(&pBt->pPage1->aData[36], 0);
2011 pBt->nTrunc = nFin;
2012 }
2013 }
2014 if( rc!=SQLITE_OK ){
2015 sqlite3PagerRollback(pPager);
2016 }
danielk1977687566d2004-11-02 12:56:41 +00002017 }
2018
danielk1977dddbcdc2007-04-26 14:42:34 +00002019 if( rc==SQLITE_OK ){
2020 *pnTrunc = pBt->nTrunc;
2021 pBt->nTrunc = 0;
2022 }
danielk19773b8a05f2007-03-19 17:44:26 +00002023 assert( nRef==sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002024 return rc;
2025}
danielk1977dddbcdc2007-04-26 14:42:34 +00002026
danielk1977687566d2004-11-02 12:56:41 +00002027#endif
2028
2029/*
drh80e35f42007-03-30 14:06:34 +00002030** This routine does the first phase of a two-phase commit. This routine
2031** causes a rollback journal to be created (if it does not already exist)
2032** and populated with enough information so that if a power loss occurs
2033** the database can be restored to its original state by playing back
2034** the journal. Then the contents of the journal are flushed out to
2035** the disk. After the journal is safely on oxide, the changes to the
2036** database are written into the database file and flushed to oxide.
2037** At the end of this call, the rollback journal still exists on the
2038** disk and we are still holding all locks, so the transaction has not
2039** committed. See sqlite3BtreeCommit() for the second phase of the
2040** commit process.
2041**
2042** This call is a no-op if no write-transaction is currently active on pBt.
2043**
2044** Otherwise, sync the database file for the btree pBt. zMaster points to
2045** the name of a master journal file that should be written into the
2046** individual journal file, or is NULL, indicating no master journal file
2047** (single database transaction).
2048**
2049** When this is called, the master journal should already have been
2050** created, populated with this journal pointer and synced to disk.
2051**
2052** Once this is routine has returned, the only thing required to commit
2053** the write-transaction for this database file is to delete the journal.
2054*/
2055int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
2056 int rc = SQLITE_OK;
2057 if( p->inTrans==TRANS_WRITE ){
2058 BtShared *pBt = p->pBt;
2059 Pgno nTrunc = 0;
2060#ifndef SQLITE_OMIT_AUTOVACUUM
2061 if( pBt->autoVacuum ){
2062 rc = autoVacuumCommit(pBt, &nTrunc);
2063 if( rc!=SQLITE_OK ){
2064 return rc;
2065 }
2066 }
2067#endif
2068 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, nTrunc);
2069 }
2070 return rc;
2071}
2072
2073/*
drh2aa679f2001-06-25 02:11:07 +00002074** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00002075**
drh6e345992007-03-30 11:12:08 +00002076** This routine implements the second phase of a 2-phase commit. The
2077** sqlite3BtreeSync() routine does the first phase and should be invoked
2078** prior to calling this routine. The sqlite3BtreeSync() routine did
2079** all the work of writing information out to disk and flushing the
2080** contents so that they are written onto the disk platter. All this
2081** routine has to do is delete or truncate the rollback journal
2082** (which causes the transaction to commit) and drop locks.
2083**
drh5e00f6c2001-09-13 13:46:56 +00002084** This will release the write lock on the database file. If there
2085** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002086*/
drh80e35f42007-03-30 14:06:34 +00002087int sqlite3BtreeCommitPhaseTwo(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002088 BtShared *pBt = p->pBt;
2089
2090 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002091
2092 /* If the handle has a write-transaction open, commit the shared-btrees
2093 ** transaction and set the shared state to TRANS_READ.
2094 */
2095 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00002096 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002097 assert( pBt->inTransaction==TRANS_WRITE );
2098 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00002099 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
danielk19777f7bc662006-01-23 13:47:47 +00002100 if( rc!=SQLITE_OK ){
2101 return rc;
2102 }
danielk1977aef0bf62005-12-30 16:28:01 +00002103 pBt->inTransaction = TRANS_READ;
2104 pBt->inStmt = 0;
danielk1977ee5741e2004-05-31 10:01:34 +00002105 }
danielk19777f7bc662006-01-23 13:47:47 +00002106 unlockAllTables(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002107
2108 /* If the handle has any kind of transaction open, decrement the transaction
2109 ** count of the shared btree. If the transaction count reaches 0, set
2110 ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
2111 ** will unlock the pager.
2112 */
2113 if( p->inTrans!=TRANS_NONE ){
2114 pBt->nTransaction--;
2115 if( 0==pBt->nTransaction ){
2116 pBt->inTransaction = TRANS_NONE;
2117 }
2118 }
2119
2120 /* Set the handles current transaction state to TRANS_NONE and unlock
2121 ** the pager if this call closed the only read or write transaction.
2122 */
2123 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00002124 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002125
2126 btreeIntegrity(p);
danielk19777f7bc662006-01-23 13:47:47 +00002127 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002128}
2129
drh80e35f42007-03-30 14:06:34 +00002130/*
2131** Do both phases of a commit.
2132*/
2133int sqlite3BtreeCommit(Btree *p){
2134 int rc;
2135 rc = sqlite3BtreeCommitPhaseOne(p, 0);
2136 if( rc==SQLITE_OK ){
2137 rc = sqlite3BtreeCommitPhaseTwo(p);
2138 }
2139 return rc;
2140}
2141
danielk1977fbcd5852004-06-15 02:44:18 +00002142#ifndef NDEBUG
2143/*
2144** Return the number of write-cursors open on this handle. This is for use
2145** in assert() expressions, so it is only compiled if NDEBUG is not
2146** defined.
2147*/
danielk1977aef0bf62005-12-30 16:28:01 +00002148static int countWriteCursors(BtShared *pBt){
danielk1977fbcd5852004-06-15 02:44:18 +00002149 BtCursor *pCur;
2150 int r = 0;
2151 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
danielk1977aef0bf62005-12-30 16:28:01 +00002152 if( pCur->wrFlag ) r++;
danielk1977fbcd5852004-06-15 02:44:18 +00002153 }
2154 return r;
2155}
2156#endif
2157
drhc39e0002004-05-07 23:50:57 +00002158/*
drhecdc7532001-09-23 02:35:53 +00002159** Rollback the transaction in progress. All cursors will be
2160** invalided by this operation. Any attempt to use a cursor
2161** that was open at the beginning of this operation will result
2162** in an error.
drh5e00f6c2001-09-13 13:46:56 +00002163**
2164** This will release the write lock on the database file. If there
2165** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002166*/
danielk1977aef0bf62005-12-30 16:28:01 +00002167int sqlite3BtreeRollback(Btree *p){
danielk19778d34dfd2006-01-24 16:37:57 +00002168 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002169 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00002170 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00002171
danielk19772b8c13e2006-01-24 14:21:24 +00002172 rc = saveAllCursors(pBt, 0, 0);
danielk19778d34dfd2006-01-24 16:37:57 +00002173#ifndef SQLITE_OMIT_SHARED_CACHE
danielk19772b8c13e2006-01-24 14:21:24 +00002174 if( rc!=SQLITE_OK ){
danielk19778d34dfd2006-01-24 16:37:57 +00002175 /* This is a horrible situation. An IO or malloc() error occured whilst
2176 ** trying to save cursor positions. If this is an automatic rollback (as
2177 ** the result of a constraint, malloc() failure or IO error) then
2178 ** the cache may be internally inconsistent (not contain valid trees) so
2179 ** we cannot simply return the error to the caller. Instead, abort
2180 ** all queries that may be using any of the cursors that failed to save.
2181 */
2182 while( pBt->pCursor ){
2183 sqlite3 *db = pBt->pCursor->pBtree->pSqlite;
2184 if( db ){
2185 sqlite3AbortOtherActiveVdbes(db, 0);
2186 }
2187 }
danielk19772b8c13e2006-01-24 14:21:24 +00002188 }
danielk19778d34dfd2006-01-24 16:37:57 +00002189#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002190 btreeIntegrity(p);
2191 unlockAllTables(p);
2192
2193 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00002194 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00002195
danielk1977dddbcdc2007-04-26 14:42:34 +00002196#ifndef SQLITE_OMIT_AUTOVACUUM
2197 pBt->nTrunc = 0;
2198#endif
2199
danielk19778d34dfd2006-01-24 16:37:57 +00002200 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00002201 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00002202 if( rc2!=SQLITE_OK ){
2203 rc = rc2;
2204 }
2205
drh24cd67e2004-05-10 16:18:47 +00002206 /* The rollback may have destroyed the pPage1->aData value. So
drh16a9b832007-05-05 18:39:25 +00002207 ** call sqlite3BtreeGetPage() on page 1 again to make
2208 ** sure pPage1->aData is set correctly. */
2209 if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh24cd67e2004-05-10 16:18:47 +00002210 releasePage(pPage1);
2211 }
danielk1977fbcd5852004-06-15 02:44:18 +00002212 assert( countWriteCursors(pBt)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002213 pBt->inTransaction = TRANS_READ;
drh24cd67e2004-05-10 16:18:47 +00002214 }
danielk1977aef0bf62005-12-30 16:28:01 +00002215
2216 if( p->inTrans!=TRANS_NONE ){
2217 assert( pBt->nTransaction>0 );
2218 pBt->nTransaction--;
2219 if( 0==pBt->nTransaction ){
2220 pBt->inTransaction = TRANS_NONE;
2221 }
2222 }
2223
2224 p->inTrans = TRANS_NONE;
danielk1977ee5741e2004-05-31 10:01:34 +00002225 pBt->inStmt = 0;
drh5e00f6c2001-09-13 13:46:56 +00002226 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002227
2228 btreeIntegrity(p);
drha059ad02001-04-17 20:09:11 +00002229 return rc;
2230}
2231
2232/*
drhab01f612004-05-22 02:55:23 +00002233** Start a statement subtransaction. The subtransaction can
2234** can be rolled back independently of the main transaction.
2235** You must start a transaction before starting a subtransaction.
2236** The subtransaction is ended automatically if the main transaction
drh663fc632002-02-02 18:49:19 +00002237** commits or rolls back.
2238**
drhab01f612004-05-22 02:55:23 +00002239** Only one subtransaction may be active at a time. It is an error to try
2240** to start a new subtransaction if another subtransaction is already active.
2241**
2242** Statement subtransactions are used around individual SQL statements
2243** that are contained within a BEGIN...COMMIT block. If a constraint
2244** error occurs within the statement, the effect of that one statement
2245** can be rolled back without having to rollback the entire transaction.
drh663fc632002-02-02 18:49:19 +00002246*/
danielk1977aef0bf62005-12-30 16:28:01 +00002247int sqlite3BtreeBeginStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002248 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002249 BtShared *pBt = p->pBt;
2250 if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
drhf74b8d92002-09-01 23:20:45 +00002251 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh0d65dc02002-02-03 00:56:09 +00002252 }
danielk1977aef0bf62005-12-30 16:28:01 +00002253 assert( pBt->inTransaction==TRANS_WRITE );
danielk19773b8a05f2007-03-19 17:44:26 +00002254 rc = pBt->readOnly ? SQLITE_OK : sqlite3PagerStmtBegin(pBt->pPager);
drh3aac2dd2004-04-26 14:10:20 +00002255 pBt->inStmt = 1;
drh663fc632002-02-02 18:49:19 +00002256 return rc;
2257}
2258
2259
2260/*
drhab01f612004-05-22 02:55:23 +00002261** Commit the statment subtransaction currently in progress. If no
2262** subtransaction is active, this is a no-op.
drh663fc632002-02-02 18:49:19 +00002263*/
danielk1977aef0bf62005-12-30 16:28:01 +00002264int sqlite3BtreeCommitStmt(Btree *p){
drh663fc632002-02-02 18:49:19 +00002265 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002266 BtShared *pBt = p->pBt;
drh3aac2dd2004-04-26 14:10:20 +00002267 if( pBt->inStmt && !pBt->readOnly ){
danielk19773b8a05f2007-03-19 17:44:26 +00002268 rc = sqlite3PagerStmtCommit(pBt->pPager);
drh663fc632002-02-02 18:49:19 +00002269 }else{
2270 rc = SQLITE_OK;
2271 }
drh3aac2dd2004-04-26 14:10:20 +00002272 pBt->inStmt = 0;
drh663fc632002-02-02 18:49:19 +00002273 return rc;
2274}
2275
2276/*
drhab01f612004-05-22 02:55:23 +00002277** Rollback the active statement subtransaction. If no subtransaction
2278** is active this routine is a no-op.
drh663fc632002-02-02 18:49:19 +00002279**
drhab01f612004-05-22 02:55:23 +00002280** All cursors will be invalidated by this operation. Any attempt
drh663fc632002-02-02 18:49:19 +00002281** to use a cursor that was open at the beginning of this operation
2282** will result in an error.
2283*/
danielk1977aef0bf62005-12-30 16:28:01 +00002284int sqlite3BtreeRollbackStmt(Btree *p){
danielk197797a227c2006-01-20 16:32:04 +00002285 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002286 BtShared *pBt = p->pBt;
danielk197797a227c2006-01-20 16:32:04 +00002287 sqlite3MallocDisallow();
2288 if( pBt->inStmt && !pBt->readOnly ){
danielk19773b8a05f2007-03-19 17:44:26 +00002289 rc = sqlite3PagerStmtRollback(pBt->pPager);
danielk197797a227c2006-01-20 16:32:04 +00002290 assert( countWriteCursors(pBt)==0 );
2291 pBt->inStmt = 0;
2292 }
2293 sqlite3MallocAllow();
drh663fc632002-02-02 18:49:19 +00002294 return rc;
2295}
2296
2297/*
drh3aac2dd2004-04-26 14:10:20 +00002298** Default key comparison function to be used if no comparison function
2299** is specified on the sqlite3BtreeCursor() call.
2300*/
2301static int dfltCompare(
2302 void *NotUsed, /* User data is not used */
2303 int n1, const void *p1, /* First key to compare */
2304 int n2, const void *p2 /* Second key to compare */
2305){
2306 int c;
2307 c = memcmp(p1, p2, n1<n2 ? n1 : n2);
2308 if( c==0 ){
2309 c = n1 - n2;
2310 }
2311 return c;
2312}
2313
2314/*
drh8b2f49b2001-06-08 00:21:52 +00002315** Create a new cursor for the BTree whose root is on the page
2316** iTable. The act of acquiring a cursor gets a read lock on
2317** the database file.
drh1bee3d72001-10-15 00:44:35 +00002318**
2319** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00002320** If wrFlag==1, then the cursor can be used for reading or for
2321** writing if other conditions for writing are also met. These
2322** are the conditions that must be met in order for writing to
2323** be allowed:
drh6446c4d2001-12-15 14:22:18 +00002324**
drhf74b8d92002-09-01 23:20:45 +00002325** 1: The cursor must have been opened with wrFlag==1
2326**
drhfe5d71d2007-03-19 11:54:10 +00002327** 2: Other database connections that share the same pager cache
2328** but which are not in the READ_UNCOMMITTED state may not have
2329** cursors open with wrFlag==0 on the same table. Otherwise
2330** the changes made by this write cursor would be visible to
2331** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00002332**
2333** 3: The database must be writable (not on read-only media)
2334**
2335** 4: There must be an active transaction.
2336**
drh6446c4d2001-12-15 14:22:18 +00002337** No checking is done to make sure that page iTable really is the
2338** root page of a b-tree. If it is not, then the cursor acquired
2339** will not work correctly.
drh3aac2dd2004-04-26 14:10:20 +00002340**
2341** The comparison function must be logically the same for every cursor
2342** on a particular table. Changing the comparison function will result
2343** in incorrect operations. If the comparison function is NULL, a
2344** default comparison function is used. The comparison function is
2345** always ignored for INTKEY tables.
drha059ad02001-04-17 20:09:11 +00002346*/
drh3aac2dd2004-04-26 14:10:20 +00002347int sqlite3BtreeCursor(
danielk1977aef0bf62005-12-30 16:28:01 +00002348 Btree *p, /* The btree */
drh3aac2dd2004-04-26 14:10:20 +00002349 int iTable, /* Root page of table to open */
2350 int wrFlag, /* 1 to write. 0 read-only */
2351 int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
2352 void *pArg, /* First arg to xCompare() */
2353 BtCursor **ppCur /* Write new cursor here */
2354){
drha059ad02001-04-17 20:09:11 +00002355 int rc;
drh8dcd7ca2004-08-08 19:43:29 +00002356 BtCursor *pCur;
danielk1977aef0bf62005-12-30 16:28:01 +00002357 BtShared *pBt = p->pBt;
drhecdc7532001-09-23 02:35:53 +00002358
drh8dcd7ca2004-08-08 19:43:29 +00002359 *ppCur = 0;
2360 if( wrFlag ){
drh8dcd7ca2004-08-08 19:43:29 +00002361 if( pBt->readOnly ){
2362 return SQLITE_READONLY;
2363 }
drh980b1a72006-08-16 16:42:48 +00002364 if( checkReadLocks(p, iTable, 0) ){
drh8dcd7ca2004-08-08 19:43:29 +00002365 return SQLITE_LOCKED;
2366 }
drha0c9a112004-03-10 13:42:37 +00002367 }
danielk1977aef0bf62005-12-30 16:28:01 +00002368
drh4b70f112004-05-02 21:12:19 +00002369 if( pBt->pPage1==0 ){
danielk1977aef0bf62005-12-30 16:28:01 +00002370 rc = lockBtreeWithRetry(p);
drha059ad02001-04-17 20:09:11 +00002371 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00002372 return rc;
2373 }
drh1831f182007-04-24 17:35:59 +00002374 if( pBt->readOnly && wrFlag ){
2375 return SQLITE_READONLY;
2376 }
drha059ad02001-04-17 20:09:11 +00002377 }
danielk1977da184232006-01-05 11:34:32 +00002378 pCur = sqliteMalloc( sizeof(*pCur) );
drha059ad02001-04-17 20:09:11 +00002379 if( pCur==0 ){
drhbd03cae2001-06-02 02:40:57 +00002380 rc = SQLITE_NOMEM;
2381 goto create_cursor_exception;
2382 }
drh8b2f49b2001-06-08 00:21:52 +00002383 pCur->pgnoRoot = (Pgno)iTable;
danielk19773b8a05f2007-03-19 17:44:26 +00002384 if( iTable==1 && sqlite3PagerPagecount(pBt->pPager)==0 ){
drh24cd67e2004-05-10 16:18:47 +00002385 rc = SQLITE_EMPTY;
2386 goto create_cursor_exception;
2387 }
drhde647132004-05-07 17:57:49 +00002388 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->pPage, 0);
drhbd03cae2001-06-02 02:40:57 +00002389 if( rc!=SQLITE_OK ){
2390 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00002391 }
danielk1977aef0bf62005-12-30 16:28:01 +00002392
danielk1977aef0bf62005-12-30 16:28:01 +00002393 /* Now that no other errors can occur, finish filling in the BtCursor
2394 ** variables, link the cursor into the BtShared list and set *ppCur (the
2395 ** output argument to this function).
2396 */
drh3aac2dd2004-04-26 14:10:20 +00002397 pCur->xCompare = xCmp ? xCmp : dfltCompare;
2398 pCur->pArg = pArg;
danielk1977aef0bf62005-12-30 16:28:01 +00002399 pCur->pBtree = p;
drhecdc7532001-09-23 02:35:53 +00002400 pCur->wrFlag = wrFlag;
drha059ad02001-04-17 20:09:11 +00002401 pCur->pNext = pBt->pCursor;
2402 if( pCur->pNext ){
2403 pCur->pNext->pPrev = pCur;
2404 }
2405 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00002406 pCur->eState = CURSOR_INVALID;
drh2af926b2001-05-15 00:39:25 +00002407 *ppCur = pCur;
drhbd03cae2001-06-02 02:40:57 +00002408
danielk1977aef0bf62005-12-30 16:28:01 +00002409 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00002410create_cursor_exception:
drhbd03cae2001-06-02 02:40:57 +00002411 if( pCur ){
drh3aac2dd2004-04-26 14:10:20 +00002412 releasePage(pCur->pPage);
drhbd03cae2001-06-02 02:40:57 +00002413 sqliteFree(pCur);
2414 }
drh5e00f6c2001-09-13 13:46:56 +00002415 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00002416 return rc;
drha059ad02001-04-17 20:09:11 +00002417}
2418
2419/*
drh5e00f6c2001-09-13 13:46:56 +00002420** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00002421** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00002422*/
drh3aac2dd2004-04-26 14:10:20 +00002423int sqlite3BtreeCloseCursor(BtCursor *pCur){
danielk1977aef0bf62005-12-30 16:28:01 +00002424 BtShared *pBt = pCur->pBtree->pBt;
drhbf700f32007-03-31 02:36:44 +00002425 clearCursorPosition(pCur);
drha059ad02001-04-17 20:09:11 +00002426 if( pCur->pPrev ){
2427 pCur->pPrev->pNext = pCur->pNext;
2428 }else{
2429 pBt->pCursor = pCur->pNext;
2430 }
2431 if( pCur->pNext ){
2432 pCur->pNext->pPrev = pCur->pPrev;
2433 }
drh3aac2dd2004-04-26 14:10:20 +00002434 releasePage(pCur->pPage);
drh5e00f6c2001-09-13 13:46:56 +00002435 unlockBtreeIfUnused(pBt);
danielk197792d4d7a2007-05-04 12:05:56 +00002436 invalidateOverflowCache(pCur);
drha059ad02001-04-17 20:09:11 +00002437 sqliteFree(pCur);
drh8c42ca92001-06-22 19:15:00 +00002438 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002439}
2440
drh7e3b0a02001-04-28 16:52:40 +00002441/*
drh5e2f8b92001-05-28 00:41:15 +00002442** Make a temporary cursor by filling in the fields of pTempCur.
2443** The temporary cursor is not on the cursor list for the Btree.
2444*/
drh16a9b832007-05-05 18:39:25 +00002445void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
drh5e2f8b92001-05-28 00:41:15 +00002446 memcpy(pTempCur, pCur, sizeof(*pCur));
2447 pTempCur->pNext = 0;
2448 pTempCur->pPrev = 0;
drhecdc7532001-09-23 02:35:53 +00002449 if( pTempCur->pPage ){
danielk19773b8a05f2007-03-19 17:44:26 +00002450 sqlite3PagerRef(pTempCur->pPage->pDbPage);
drhecdc7532001-09-23 02:35:53 +00002451 }
drh5e2f8b92001-05-28 00:41:15 +00002452}
2453
2454/*
drhbd03cae2001-06-02 02:40:57 +00002455** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00002456** function above.
2457*/
drh16a9b832007-05-05 18:39:25 +00002458void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
drhecdc7532001-09-23 02:35:53 +00002459 if( pCur->pPage ){
danielk19773b8a05f2007-03-19 17:44:26 +00002460 sqlite3PagerUnref(pCur->pPage->pDbPage);
drhecdc7532001-09-23 02:35:53 +00002461 }
drh5e2f8b92001-05-28 00:41:15 +00002462}
2463
2464/*
danielk19771cc5ed82007-05-16 17:28:43 +00002465** The GET_CELL_INFO() macro. Takes one argument, a pointer to a valid
2466** btree cursor (type BtCursor*). This macro makes sure the BtCursor.info
2467** field of the given cursor is valid. If it is not already valid, call
2468** sqlite3BtreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00002469**
2470** BtCursor.info is a cache of the information in the current cell.
drh16a9b832007-05-05 18:39:25 +00002471** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
drh9188b382004-05-14 21:12:22 +00002472*/
drh9188b382004-05-14 21:12:22 +00002473#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00002474 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00002475 CellInfo info;
drh51c6d962004-06-06 00:42:25 +00002476 memset(&info, 0, sizeof(info));
drh16a9b832007-05-05 18:39:25 +00002477 sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &info);
drh9188b382004-05-14 21:12:22 +00002478 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00002479 }
danielk19771cc5ed82007-05-16 17:28:43 +00002480#else
2481 #define assertCellInfo(x)
2482#endif
2483
2484#define GET_CELL_INFO(pCur) \
2485 if( pCur->info.nSize==0 ) \
2486 sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info); \
2487 else \
2488 assertCellInfo(pCur);
2489
drh9188b382004-05-14 21:12:22 +00002490
2491/*
drh3aac2dd2004-04-26 14:10:20 +00002492** Set *pSize to the size of the buffer needed to hold the value of
2493** the key for the current entry. If the cursor is not pointing
2494** to a valid entry, *pSize is set to 0.
2495**
drh4b70f112004-05-02 21:12:19 +00002496** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00002497** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00002498*/
drh4a1c3802004-05-12 15:15:47 +00002499int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drhbf700f32007-03-31 02:36:44 +00002500 int rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00002501 if( rc==SQLITE_OK ){
2502 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
2503 if( pCur->eState==CURSOR_INVALID ){
2504 *pSize = 0;
2505 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00002506 GET_CELL_INFO(pCur);
danielk1977da184232006-01-05 11:34:32 +00002507 *pSize = pCur->info.nKey;
2508 }
drh72f82862001-05-24 21:06:34 +00002509 }
danielk1977da184232006-01-05 11:34:32 +00002510 return rc;
drha059ad02001-04-17 20:09:11 +00002511}
drh2af926b2001-05-15 00:39:25 +00002512
drh72f82862001-05-24 21:06:34 +00002513/*
drh0e1c19e2004-05-11 00:58:56 +00002514** Set *pSize to the number of bytes of data in the entry the
2515** cursor currently points to. Always return SQLITE_OK.
2516** Failure is not possible. If the cursor is not currently
2517** pointing to an entry (which can happen, for example, if
2518** the database is empty) then *pSize is set to 0.
2519*/
2520int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drhbf700f32007-03-31 02:36:44 +00002521 int rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00002522 if( rc==SQLITE_OK ){
2523 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
2524 if( pCur->eState==CURSOR_INVALID ){
2525 /* Not pointing at a valid entry - set *pSize to 0. */
2526 *pSize = 0;
2527 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00002528 GET_CELL_INFO(pCur);
danielk1977da184232006-01-05 11:34:32 +00002529 *pSize = pCur->info.nData;
2530 }
drh0e1c19e2004-05-11 00:58:56 +00002531 }
danielk1977da184232006-01-05 11:34:32 +00002532 return rc;
drh0e1c19e2004-05-11 00:58:56 +00002533}
2534
2535/*
danielk1977d04417962007-05-02 13:16:30 +00002536** Given the page number of an overflow page in the database (parameter
2537** ovfl), this function finds the page number of the next page in the
2538** linked list of overflow pages. If possible, it uses the auto-vacuum
2539** pointer-map data instead of reading the content of page ovfl to do so.
2540**
2541** If an error occurs an SQLite error code is returned. Otherwise:
2542**
2543** Unless pPgnoNext is NULL, the page number of the next overflow
2544** page in the linked list is written to *pPgnoNext. If page ovfl
2545** is the last page in it's linked list, *pPgnoNext is set to zero.
2546**
2547** If ppPage is not NULL, *ppPage is set to the MemPage* handle
2548** for page ovfl. The underlying pager page may have been requested
2549** with the noContent flag set, so the page data accessable via
2550** this handle may not be trusted.
2551*/
2552static int getOverflowPage(
2553 BtShared *pBt,
2554 Pgno ovfl, /* Overflow page */
2555 MemPage **ppPage, /* OUT: MemPage handle */
2556 Pgno *pPgnoNext /* OUT: Next overflow page number */
2557){
2558 Pgno next = 0;
2559 int rc;
2560
2561 /* One of these must not be NULL. Otherwise, why call this function? */
2562 assert(ppPage || pPgnoNext);
2563
2564 /* If pPgnoNext is NULL, then this function is being called to obtain
2565 ** a MemPage* reference only. No page-data is required in this case.
2566 */
2567 if( !pPgnoNext ){
drh16a9b832007-05-05 18:39:25 +00002568 return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1);
danielk1977d04417962007-05-02 13:16:30 +00002569 }
2570
2571#ifndef SQLITE_OMIT_AUTOVACUUM
2572 /* Try to find the next page in the overflow list using the
2573 ** autovacuum pointer-map pages. Guess that the next page in
2574 ** the overflow list is page number (ovfl+1). If that guess turns
2575 ** out to be wrong, fall back to loading the data of page
2576 ** number ovfl to determine the next page number.
2577 */
2578 if( pBt->autoVacuum ){
2579 Pgno pgno;
2580 Pgno iGuess = ovfl+1;
2581 u8 eType;
2582
2583 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
2584 iGuess++;
2585 }
2586
danielk197720713f32007-05-03 11:43:33 +00002587 if( iGuess<=sqlite3PagerPagecount(pBt->pPager) ){
danielk1977d04417962007-05-02 13:16:30 +00002588 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
2589 if( rc!=SQLITE_OK ){
2590 return rc;
2591 }
2592 if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
2593 next = iGuess;
2594 }
2595 }
2596 }
2597#endif
2598
2599 if( next==0 || ppPage ){
2600 MemPage *pPage = 0;
2601
drh16a9b832007-05-05 18:39:25 +00002602 rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0);
danielk1977d04417962007-05-02 13:16:30 +00002603 assert(rc==SQLITE_OK || pPage==0);
2604 if( next==0 && rc==SQLITE_OK ){
2605 next = get4byte(pPage->aData);
2606 }
2607
2608 if( ppPage ){
2609 *ppPage = pPage;
2610 }else{
2611 releasePage(pPage);
2612 }
2613 }
2614 *pPgnoNext = next;
2615
2616 return rc;
2617}
2618
danielk1977da107192007-05-04 08:32:13 +00002619/*
2620** Copy data from a buffer to a page, or from a page to a buffer.
2621**
2622** pPayload is a pointer to data stored on database page pDbPage.
2623** If argument eOp is false, then nByte bytes of data are copied
2624** from pPayload to the buffer pointed at by pBuf. If eOp is true,
2625** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
2626** of data are copied from the buffer pBuf to pPayload.
2627**
2628** SQLITE_OK is returned on success, otherwise an error code.
2629*/
2630static int copyPayload(
2631 void *pPayload, /* Pointer to page data */
2632 void *pBuf, /* Pointer to buffer */
2633 int nByte, /* Number of bytes to copy */
2634 int eOp, /* 0 -> copy from page, 1 -> copy to page */
2635 DbPage *pDbPage /* Page containing pPayload */
2636){
2637 if( eOp ){
2638 /* Copy data from buffer to page (a write operation) */
2639 int rc = sqlite3PagerWrite(pDbPage);
2640 if( rc!=SQLITE_OK ){
2641 return rc;
2642 }
2643 memcpy(pPayload, pBuf, nByte);
2644 }else{
2645 /* Copy data from page to buffer (a read operation) */
2646 memcpy(pBuf, pPayload, nByte);
2647 }
2648 return SQLITE_OK;
2649}
danielk1977d04417962007-05-02 13:16:30 +00002650
2651/*
danielk19779f8d6402007-05-02 17:48:45 +00002652** This function is used to read or overwrite payload information
2653** for the entry that the pCur cursor is pointing to. If the eOp
2654** parameter is 0, this is a read operation (data copied into
2655** buffer pBuf). If it is non-zero, a write (data copied from
2656** buffer pBuf).
2657**
2658** A total of "amt" bytes are read or written beginning at "offset".
2659** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00002660**
2661** This routine does not make a distinction between key and data.
danielk19779f8d6402007-05-02 17:48:45 +00002662** It just reads or writes bytes from the payload area. Data might
2663** appear on the main page or be scattered out on multiple overflow
2664** pages.
danielk1977da107192007-05-04 08:32:13 +00002665**
danielk1977dcbb5d32007-05-04 18:36:44 +00002666** If the BtCursor.isIncrblobHandle flag is set, and the current
danielk1977da107192007-05-04 08:32:13 +00002667** cursor entry uses one or more overflow pages, this function
2668** allocates space for and lazily popluates the overflow page-list
2669** cache array (BtCursor.aOverflow). Subsequent calls use this
2670** cache to make seeking to the supplied offset more efficient.
2671**
2672** Once an overflow page-list cache has been allocated, it may be
2673** invalidated if some other cursor writes to the same table, or if
2674** the cursor is moved to a different row. Additionally, in auto-vacuum
2675** mode, the following events may invalidate an overflow page-list cache.
2676**
2677** * An incremental vacuum,
2678** * A commit in auto_vacuum="full" mode,
2679** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00002680*/
danielk19779f8d6402007-05-02 17:48:45 +00002681static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00002682 BtCursor *pCur, /* Cursor pointing to entry to read from */
2683 int offset, /* Begin reading this far into payload */
2684 int amt, /* Read this many bytes */
2685 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00002686 int skipKey, /* offset begins at data if this is true */
2687 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00002688){
2689 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00002690 int rc = SQLITE_OK;
drhfa1a98a2004-05-14 19:08:17 +00002691 u32 nKey;
danielk19772dec9702007-05-02 16:48:37 +00002692 int iIdx = 0;
danielk1977da107192007-05-04 08:32:13 +00002693 MemPage *pPage = pCur->pPage; /* Btree page of current cursor entry */
2694 BtShared *pBt = pCur->pBtree->pBt; /* Btree this cursor belongs to */
drh3aac2dd2004-04-26 14:10:20 +00002695
danielk1977da107192007-05-04 08:32:13 +00002696 assert( pPage );
danielk1977da184232006-01-05 11:34:32 +00002697 assert( pCur->eState==CURSOR_VALID );
drh3aac2dd2004-04-26 14:10:20 +00002698 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
danielk1977da107192007-05-04 08:32:13 +00002699 assert( offset>=0 );
2700
danielk19771cc5ed82007-05-16 17:28:43 +00002701 GET_CELL_INFO(pCur);
drh366fda62006-01-13 02:35:09 +00002702 aPayload = pCur->info.pCell + pCur->info.nHeader;
danielk1977da107192007-05-04 08:32:13 +00002703 nKey = (pPage->intKey ? 0 : pCur->info.nKey);
2704
drh3aac2dd2004-04-26 14:10:20 +00002705 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00002706 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00002707 }
drhfa1a98a2004-05-14 19:08:17 +00002708 if( offset+amt > nKey+pCur->info.nData ){
danielk1977da107192007-05-04 08:32:13 +00002709 /* Trying to read or write past the end of the data is an error */
drha34b6762004-05-07 13:30:42 +00002710 return SQLITE_ERROR;
drh3aac2dd2004-04-26 14:10:20 +00002711 }
danielk1977da107192007-05-04 08:32:13 +00002712
2713 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00002714 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00002715 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00002716 if( a+offset>pCur->info.nLocal ){
2717 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00002718 }
danielk1977da107192007-05-04 08:32:13 +00002719 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00002720 offset = 0;
drha34b6762004-05-07 13:30:42 +00002721 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00002722 amt -= a;
drhdd793422001-06-28 01:54:48 +00002723 }else{
drhfa1a98a2004-05-14 19:08:17 +00002724 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00002725 }
danielk1977da107192007-05-04 08:32:13 +00002726
2727 if( rc==SQLITE_OK && amt>0 ){
2728 const int ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
2729 Pgno nextPage;
2730
drhfa1a98a2004-05-14 19:08:17 +00002731 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00002732
danielk19772dec9702007-05-02 16:48:37 +00002733#ifndef SQLITE_OMIT_INCRBLOB
danielk1977dcbb5d32007-05-04 18:36:44 +00002734 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
danielk1977da107192007-05-04 08:32:13 +00002735 ** has not been allocated, allocate it now. The array is sized at
2736 ** one entry for each overflow page in the overflow chain. The
2737 ** page number of the first overflow page is stored in aOverflow[0],
2738 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
2739 ** (the cache is lazily populated).
2740 */
danielk1977dcbb5d32007-05-04 18:36:44 +00002741 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
danielk19772dec9702007-05-02 16:48:37 +00002742 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
2743 pCur->aOverflow = (Pgno *)sqliteMalloc(sizeof(Pgno)*nOvfl);
2744 if( nOvfl && !pCur->aOverflow ){
danielk1977da107192007-05-04 08:32:13 +00002745 rc = SQLITE_NOMEM;
danielk19772dec9702007-05-02 16:48:37 +00002746 }
2747 }
danielk1977da107192007-05-04 08:32:13 +00002748
2749 /* If the overflow page-list cache has been allocated and the
2750 ** entry for the first required overflow page is valid, skip
2751 ** directly to it.
2752 */
danielk19772dec9702007-05-02 16:48:37 +00002753 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
2754 iIdx = (offset/ovflSize);
2755 nextPage = pCur->aOverflow[iIdx];
2756 offset = (offset%ovflSize);
2757 }
2758#endif
danielk1977da107192007-05-04 08:32:13 +00002759
2760 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
2761
2762#ifndef SQLITE_OMIT_INCRBLOB
2763 /* If required, populate the overflow page-list cache. */
2764 if( pCur->aOverflow ){
2765 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
2766 pCur->aOverflow[iIdx] = nextPage;
2767 }
2768#endif
2769
danielk1977d04417962007-05-02 13:16:30 +00002770 if( offset>=ovflSize ){
2771 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00002772 ** number for the next page in the overflow chain. The page
2773 ** data is not required. So first try to lookup the overflow
2774 ** page-list cache, if any, then fall back to the getOverflowPage()
2775 ** function.
danielk1977d04417962007-05-02 13:16:30 +00002776 */
danielk19772dec9702007-05-02 16:48:37 +00002777#ifndef SQLITE_OMIT_INCRBLOB
danielk1977da107192007-05-04 08:32:13 +00002778 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
2779 nextPage = pCur->aOverflow[iIdx+1];
2780 } else
danielk19772dec9702007-05-02 16:48:37 +00002781#endif
danielk1977da107192007-05-04 08:32:13 +00002782 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
2783 assert(rc==SQLITE_OK || nextPage==0);
2784 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00002785 }else{
danielk19779f8d6402007-05-02 17:48:45 +00002786 /* Need to read this page properly. It contains some of the
2787 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00002788 */
2789 DbPage *pDbPage;
danielk1977cfe9a692004-06-16 12:00:29 +00002790 int a = amt;
danielk1977d04417962007-05-02 13:16:30 +00002791 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
danielk1977da107192007-05-04 08:32:13 +00002792 if( rc==SQLITE_OK ){
2793 aPayload = sqlite3PagerGetData(pDbPage);
2794 nextPage = get4byte(aPayload);
2795 if( a + offset > ovflSize ){
2796 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00002797 }
danielk1977da107192007-05-04 08:32:13 +00002798 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
2799 sqlite3PagerUnref(pDbPage);
2800 offset = 0;
2801 amt -= a;
2802 pBuf += a;
danielk19779f8d6402007-05-02 17:48:45 +00002803 }
danielk1977cfe9a692004-06-16 12:00:29 +00002804 }
drh2af926b2001-05-15 00:39:25 +00002805 }
drh2af926b2001-05-15 00:39:25 +00002806 }
danielk1977cfe9a692004-06-16 12:00:29 +00002807
danielk1977da107192007-05-04 08:32:13 +00002808 if( rc==SQLITE_OK && amt>0 ){
drh49285702005-09-17 15:20:26 +00002809 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00002810 }
danielk1977da107192007-05-04 08:32:13 +00002811 return rc;
drh2af926b2001-05-15 00:39:25 +00002812}
2813
drh72f82862001-05-24 21:06:34 +00002814/*
drh3aac2dd2004-04-26 14:10:20 +00002815** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00002816** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00002817** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00002818**
drh3aac2dd2004-04-26 14:10:20 +00002819** Return SQLITE_OK on success or an error code if anything goes
2820** wrong. An error is returned if "offset+amt" is larger than
2821** the available payload.
drh72f82862001-05-24 21:06:34 +00002822*/
drha34b6762004-05-07 13:30:42 +00002823int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhbf700f32007-03-31 02:36:44 +00002824 int rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00002825 if( rc==SQLITE_OK ){
2826 assert( pCur->eState==CURSOR_VALID );
2827 assert( pCur->pPage!=0 );
2828 if( pCur->pPage->intKey ){
2829 return SQLITE_CORRUPT_BKPT;
2830 }
2831 assert( pCur->pPage->intKey==0 );
2832 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh16a9b832007-05-05 18:39:25 +00002833 rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
drh6575a222005-03-10 17:06:34 +00002834 }
danielk1977da184232006-01-05 11:34:32 +00002835 return rc;
drh3aac2dd2004-04-26 14:10:20 +00002836}
2837
2838/*
drh3aac2dd2004-04-26 14:10:20 +00002839** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00002840** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00002841** begins at "offset".
2842**
2843** Return SQLITE_OK on success or an error code if anything goes
2844** wrong. An error is returned if "offset+amt" is larger than
2845** the available payload.
drh72f82862001-05-24 21:06:34 +00002846*/
drh3aac2dd2004-04-26 14:10:20 +00002847int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhbf700f32007-03-31 02:36:44 +00002848 int rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00002849 if( rc==SQLITE_OK ){
2850 assert( pCur->eState==CURSOR_VALID );
2851 assert( pCur->pPage!=0 );
2852 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh16a9b832007-05-05 18:39:25 +00002853 rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
danielk1977da184232006-01-05 11:34:32 +00002854 }
2855 return rc;
drh2af926b2001-05-15 00:39:25 +00002856}
2857
drh72f82862001-05-24 21:06:34 +00002858/*
drh0e1c19e2004-05-11 00:58:56 +00002859** Return a pointer to payload information from the entry that the
2860** pCur cursor is pointing to. The pointer is to the beginning of
2861** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00002862** skipKey==1. The number of bytes of available key/data is written
2863** into *pAmt. If *pAmt==0, then the value returned will not be
2864** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00002865**
2866** This routine is an optimization. It is common for the entire key
2867** and data to fit on the local page and for there to be no overflow
2868** pages. When that is so, this routine can be used to access the
2869** key and data without making a copy. If the key and/or data spills
drh16a9b832007-05-05 18:39:25 +00002870** onto overflow pages, then accessPayload() must be used to reassembly
drh0e1c19e2004-05-11 00:58:56 +00002871** the key/data and copy it into a preallocated buffer.
2872**
2873** The pointer returned by this routine looks directly into the cached
2874** page of the database. The data might change or move the next time
2875** any btree routine is called.
2876*/
2877static const unsigned char *fetchPayload(
2878 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00002879 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00002880 int skipKey /* read beginning at data if this is true */
2881){
2882 unsigned char *aPayload;
2883 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00002884 u32 nKey;
2885 int nLocal;
drh0e1c19e2004-05-11 00:58:56 +00002886
2887 assert( pCur!=0 && pCur->pPage!=0 );
danielk1977da184232006-01-05 11:34:32 +00002888 assert( pCur->eState==CURSOR_VALID );
drh0e1c19e2004-05-11 00:58:56 +00002889 pPage = pCur->pPage;
drh0e1c19e2004-05-11 00:58:56 +00002890 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
danielk19771cc5ed82007-05-16 17:28:43 +00002891 GET_CELL_INFO(pCur);
drh43605152004-05-29 21:46:49 +00002892 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00002893 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00002894 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00002895 nKey = 0;
2896 }else{
2897 nKey = pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00002898 }
drh0e1c19e2004-05-11 00:58:56 +00002899 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00002900 aPayload += nKey;
2901 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00002902 }else{
drhfa1a98a2004-05-14 19:08:17 +00002903 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00002904 if( nLocal>nKey ){
2905 nLocal = nKey;
2906 }
drh0e1c19e2004-05-11 00:58:56 +00002907 }
drhe51c44f2004-05-30 20:46:09 +00002908 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00002909 return aPayload;
2910}
2911
2912
2913/*
drhe51c44f2004-05-30 20:46:09 +00002914** For the entry that cursor pCur is point to, return as
2915** many bytes of the key or data as are available on the local
2916** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00002917**
2918** The pointer returned is ephemeral. The key/data may move
2919** or be destroyed on the next call to any Btree routine.
2920**
2921** These routines is used to get quick access to key and data
2922** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00002923*/
drhe51c44f2004-05-30 20:46:09 +00002924const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
danielk1977da184232006-01-05 11:34:32 +00002925 if( pCur->eState==CURSOR_VALID ){
2926 return (const void*)fetchPayload(pCur, pAmt, 0);
2927 }
2928 return 0;
drh0e1c19e2004-05-11 00:58:56 +00002929}
drhe51c44f2004-05-30 20:46:09 +00002930const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
danielk1977da184232006-01-05 11:34:32 +00002931 if( pCur->eState==CURSOR_VALID ){
2932 return (const void*)fetchPayload(pCur, pAmt, 1);
2933 }
2934 return 0;
drh0e1c19e2004-05-11 00:58:56 +00002935}
2936
2937
2938/*
drh8178a752003-01-05 21:41:40 +00002939** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00002940** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00002941*/
drh3aac2dd2004-04-26 14:10:20 +00002942static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00002943 int rc;
2944 MemPage *pNewPage;
drh3aac2dd2004-04-26 14:10:20 +00002945 MemPage *pOldPage;
danielk1977aef0bf62005-12-30 16:28:01 +00002946 BtShared *pBt = pCur->pBtree->pBt;
drh72f82862001-05-24 21:06:34 +00002947
danielk1977da184232006-01-05 11:34:32 +00002948 assert( pCur->eState==CURSOR_VALID );
drhde647132004-05-07 17:57:49 +00002949 rc = getAndInitPage(pBt, newPgno, &pNewPage, pCur->pPage);
drh6019e162001-07-02 17:51:45 +00002950 if( rc ) return rc;
drh428ae8c2003-01-04 16:48:09 +00002951 pNewPage->idxParent = pCur->idx;
drh3aac2dd2004-04-26 14:10:20 +00002952 pOldPage = pCur->pPage;
2953 pOldPage->idxShift = 0;
2954 releasePage(pOldPage);
drh72f82862001-05-24 21:06:34 +00002955 pCur->pPage = pNewPage;
2956 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00002957 pCur->info.nSize = 0;
drh4be295b2003-12-16 03:44:47 +00002958 if( pNewPage->nCell<1 ){
drh49285702005-09-17 15:20:26 +00002959 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00002960 }
drh72f82862001-05-24 21:06:34 +00002961 return SQLITE_OK;
2962}
2963
2964/*
drh8856d6a2004-04-29 14:42:46 +00002965** Return true if the page is the virtual root of its table.
2966**
2967** The virtual root page is the root page for most tables. But
2968** for the table rooted on page 1, sometime the real root page
2969** is empty except for the right-pointer. In such cases the
2970** virtual root page is the page that the right-pointer of page
2971** 1 is pointing to.
2972*/
drh16a9b832007-05-05 18:39:25 +00002973int sqlite3BtreeIsRootPage(MemPage *pPage){
drh8856d6a2004-04-29 14:42:46 +00002974 MemPage *pParent = pPage->pParent;
drhda200cc2004-05-09 11:51:38 +00002975 if( pParent==0 ) return 1;
2976 if( pParent->pgno>1 ) return 0;
2977 if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
drh8856d6a2004-04-29 14:42:46 +00002978 return 0;
2979}
2980
2981/*
drh5e2f8b92001-05-28 00:41:15 +00002982** Move the cursor up to the parent page.
2983**
2984** pCur->idx is set to the cell index that contains the pointer
2985** to the page we are coming from. If we are coming from the
2986** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00002987** the largest cell index.
drh72f82862001-05-24 21:06:34 +00002988*/
drh16a9b832007-05-05 18:39:25 +00002989void sqlite3BtreeMoveToParent(BtCursor *pCur){
drh72f82862001-05-24 21:06:34 +00002990 MemPage *pParent;
drh8178a752003-01-05 21:41:40 +00002991 MemPage *pPage;
drh428ae8c2003-01-04 16:48:09 +00002992 int idxParent;
drh3aac2dd2004-04-26 14:10:20 +00002993
danielk1977da184232006-01-05 11:34:32 +00002994 assert( pCur->eState==CURSOR_VALID );
drh8178a752003-01-05 21:41:40 +00002995 pPage = pCur->pPage;
2996 assert( pPage!=0 );
drh16a9b832007-05-05 18:39:25 +00002997 assert( !sqlite3BtreeIsRootPage(pPage) );
drh8178a752003-01-05 21:41:40 +00002998 pParent = pPage->pParent;
2999 assert( pParent!=0 );
3000 idxParent = pPage->idxParent;
danielk19773b8a05f2007-03-19 17:44:26 +00003001 sqlite3PagerRef(pParent->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00003002 releasePage(pPage);
drh72f82862001-05-24 21:06:34 +00003003 pCur->pPage = pParent;
drh271efa52004-05-30 19:19:05 +00003004 pCur->info.nSize = 0;
drh428ae8c2003-01-04 16:48:09 +00003005 assert( pParent->idxShift==0 );
drh43605152004-05-29 21:46:49 +00003006 pCur->idx = idxParent;
drh72f82862001-05-24 21:06:34 +00003007}
3008
3009/*
3010** Move the cursor to the root page
3011*/
drh5e2f8b92001-05-28 00:41:15 +00003012static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00003013 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00003014 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00003015 BtShared *pBt = pCur->pBtree->pBt;
drhbd03cae2001-06-02 02:40:57 +00003016
drhbf700f32007-03-31 02:36:44 +00003017 if( pCur->eState==CURSOR_REQUIRESEEK ){
3018 clearCursorPosition(pCur);
3019 }
drh777e4c42006-01-13 04:31:58 +00003020 pRoot = pCur->pPage;
danielk197797a227c2006-01-20 16:32:04 +00003021 if( pRoot && pRoot->pgno==pCur->pgnoRoot ){
drh777e4c42006-01-13 04:31:58 +00003022 assert( pRoot->isInit );
3023 }else{
3024 if(
3025 SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pRoot, 0))
3026 ){
3027 pCur->eState = CURSOR_INVALID;
3028 return rc;
3029 }
3030 releasePage(pCur->pPage);
drh777e4c42006-01-13 04:31:58 +00003031 pCur->pPage = pRoot;
drhc39e0002004-05-07 23:50:57 +00003032 }
drh72f82862001-05-24 21:06:34 +00003033 pCur->idx = 0;
drh271efa52004-05-30 19:19:05 +00003034 pCur->info.nSize = 0;
drh8856d6a2004-04-29 14:42:46 +00003035 if( pRoot->nCell==0 && !pRoot->leaf ){
3036 Pgno subpage;
3037 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00003038 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00003039 assert( subpage>0 );
danielk1977da184232006-01-05 11:34:32 +00003040 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00003041 rc = moveToChild(pCur, subpage);
drh8856d6a2004-04-29 14:42:46 +00003042 }
danielk1977da184232006-01-05 11:34:32 +00003043 pCur->eState = ((pCur->pPage->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
drh8856d6a2004-04-29 14:42:46 +00003044 return rc;
drh72f82862001-05-24 21:06:34 +00003045}
drh2af926b2001-05-15 00:39:25 +00003046
drh5e2f8b92001-05-28 00:41:15 +00003047/*
3048** Move the cursor down to the left-most leaf entry beneath the
3049** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00003050**
3051** The left-most leaf is the one with the smallest key - the first
3052** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00003053*/
3054static int moveToLeftmost(BtCursor *pCur){
3055 Pgno pgno;
3056 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003057 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00003058
danielk1977da184232006-01-05 11:34:32 +00003059 assert( pCur->eState==CURSOR_VALID );
drh3aac2dd2004-04-26 14:10:20 +00003060 while( !(pPage = pCur->pPage)->leaf ){
drha34b6762004-05-07 13:30:42 +00003061 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
danielk19771cc5ed82007-05-16 17:28:43 +00003062 pgno = get4byte(findCell(pPage, pCur->idx));
drh8178a752003-01-05 21:41:40 +00003063 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00003064 if( rc ) return rc;
3065 }
3066 return SQLITE_OK;
3067}
3068
drh2dcc9aa2002-12-04 13:40:25 +00003069/*
3070** Move the cursor down to the right-most leaf entry beneath the
3071** page to which it is currently pointing. Notice the difference
3072** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
3073** finds the left-most entry beneath the *entry* whereas moveToRightmost()
3074** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00003075**
3076** The right-most entry is the one with the largest key - the last
3077** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00003078*/
3079static int moveToRightmost(BtCursor *pCur){
3080 Pgno pgno;
3081 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003082 MemPage *pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003083
danielk1977da184232006-01-05 11:34:32 +00003084 assert( pCur->eState==CURSOR_VALID );
drh3aac2dd2004-04-26 14:10:20 +00003085 while( !(pPage = pCur->pPage)->leaf ){
drh43605152004-05-29 21:46:49 +00003086 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh3aac2dd2004-04-26 14:10:20 +00003087 pCur->idx = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00003088 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003089 if( rc ) return rc;
3090 }
drh3aac2dd2004-04-26 14:10:20 +00003091 pCur->idx = pPage->nCell - 1;
drh271efa52004-05-30 19:19:05 +00003092 pCur->info.nSize = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003093 return SQLITE_OK;
3094}
3095
drh5e00f6c2001-09-13 13:46:56 +00003096/* Move the cursor to the first entry in the table. Return SQLITE_OK
3097** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003098** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00003099*/
drh3aac2dd2004-04-26 14:10:20 +00003100int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00003101 int rc;
3102 rc = moveToRoot(pCur);
3103 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00003104 if( pCur->eState==CURSOR_INVALID ){
drhc39e0002004-05-07 23:50:57 +00003105 assert( pCur->pPage->nCell==0 );
drh5e00f6c2001-09-13 13:46:56 +00003106 *pRes = 1;
3107 return SQLITE_OK;
3108 }
drhc39e0002004-05-07 23:50:57 +00003109 assert( pCur->pPage->nCell>0 );
drh5e00f6c2001-09-13 13:46:56 +00003110 *pRes = 0;
3111 rc = moveToLeftmost(pCur);
3112 return rc;
3113}
drh5e2f8b92001-05-28 00:41:15 +00003114
drh9562b552002-02-19 15:00:07 +00003115/* Move the cursor to the last entry in the table. Return SQLITE_OK
3116** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003117** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00003118*/
drh3aac2dd2004-04-26 14:10:20 +00003119int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00003120 int rc;
drh9562b552002-02-19 15:00:07 +00003121 rc = moveToRoot(pCur);
3122 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00003123 if( CURSOR_INVALID==pCur->eState ){
drhc39e0002004-05-07 23:50:57 +00003124 assert( pCur->pPage->nCell==0 );
drh9562b552002-02-19 15:00:07 +00003125 *pRes = 1;
3126 return SQLITE_OK;
3127 }
danielk1977da184232006-01-05 11:34:32 +00003128 assert( pCur->eState==CURSOR_VALID );
drh9562b552002-02-19 15:00:07 +00003129 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003130 rc = moveToRightmost(pCur);
drh9562b552002-02-19 15:00:07 +00003131 return rc;
3132}
3133
drh3aac2dd2004-04-26 14:10:20 +00003134/* Move the cursor so that it points to an entry near pKey/nKey.
drh72f82862001-05-24 21:06:34 +00003135** Return a success code.
3136**
drh3aac2dd2004-04-26 14:10:20 +00003137** For INTKEY tables, only the nKey parameter is used. pKey is
3138** ignored. For other tables, nKey is the number of bytes of data
drh0b2f3162005-12-21 18:36:45 +00003139** in pKey. The comparison function specified when the cursor was
drh3aac2dd2004-04-26 14:10:20 +00003140** created is used to compare keys.
3141**
drh5e2f8b92001-05-28 00:41:15 +00003142** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00003143** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00003144** were present. The cursor might point to an entry that comes
3145** before or after the key.
3146**
drhbd03cae2001-06-02 02:40:57 +00003147** The result of comparing the key with the entry to which the
drhab01f612004-05-22 02:55:23 +00003148** cursor is written to *pRes if pRes!=NULL. The meaning of
drhbd03cae2001-06-02 02:40:57 +00003149** this value is as follows:
3150**
3151** *pRes<0 The cursor is left pointing at an entry that
drh1a844c32002-12-04 22:29:28 +00003152** is smaller than pKey or if the table is empty
3153** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00003154**
3155** *pRes==0 The cursor is left pointing at an entry that
3156** exactly matches pKey.
3157**
3158** *pRes>0 The cursor is left pointing at an entry that
drh7c717f72001-06-24 20:39:41 +00003159** is larger than pKey.
drha059ad02001-04-17 20:09:11 +00003160*/
drhe4d90812007-03-29 05:51:49 +00003161int sqlite3BtreeMoveto(
3162 BtCursor *pCur, /* The cursor to be moved */
3163 const void *pKey, /* The key content for indices. Not used by tables */
3164 i64 nKey, /* Size of pKey. Or the key for tables */
3165 int biasRight, /* If true, bias the search to the high end */
3166 int *pRes /* Search result flag */
3167){
drh72f82862001-05-24 21:06:34 +00003168 int rc;
drh5e2f8b92001-05-28 00:41:15 +00003169 rc = moveToRoot(pCur);
drh72f82862001-05-24 21:06:34 +00003170 if( rc ) return rc;
drhc39e0002004-05-07 23:50:57 +00003171 assert( pCur->pPage );
3172 assert( pCur->pPage->isInit );
danielk1977da184232006-01-05 11:34:32 +00003173 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00003174 *pRes = -1;
drhc39e0002004-05-07 23:50:57 +00003175 assert( pCur->pPage->nCell==0 );
3176 return SQLITE_OK;
3177 }
drh14684382006-11-30 13:05:29 +00003178 for(;;){
drh72f82862001-05-24 21:06:34 +00003179 int lwr, upr;
3180 Pgno chldPg;
3181 MemPage *pPage = pCur->pPage;
drh1a844c32002-12-04 22:29:28 +00003182 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00003183 lwr = 0;
3184 upr = pPage->nCell-1;
drh4eec4c12005-01-21 00:22:37 +00003185 if( !pPage->intKey && pKey==0 ){
drh49285702005-09-17 15:20:26 +00003186 return SQLITE_CORRUPT_BKPT;
drh4eec4c12005-01-21 00:22:37 +00003187 }
drhe4d90812007-03-29 05:51:49 +00003188 if( biasRight ){
3189 pCur->idx = upr;
3190 }else{
3191 pCur->idx = (upr+lwr)/2;
3192 }
drhf1d68b32007-03-29 04:43:26 +00003193 if( lwr<=upr ) for(;;){
danielk197713adf8a2004-06-03 16:08:41 +00003194 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00003195 i64 nCellKey;
drh366fda62006-01-13 02:35:09 +00003196 pCur->info.nSize = 0;
drh3aac2dd2004-04-26 14:10:20 +00003197 if( pPage->intKey ){
drh777e4c42006-01-13 04:31:58 +00003198 u8 *pCell;
danielk19771cc5ed82007-05-16 17:28:43 +00003199 pCell = findCell(pPage, pCur->idx) + pPage->childPtrSize;
drhd172f862006-01-12 15:01:15 +00003200 if( pPage->hasData ){
danielk1977bab45c62006-01-16 15:14:27 +00003201 u32 dummy;
drhd172f862006-01-12 15:01:15 +00003202 pCell += getVarint32(pCell, &dummy);
3203 }
danielk1977bab45c62006-01-16 15:14:27 +00003204 getVarint(pCell, (u64 *)&nCellKey);
drh3aac2dd2004-04-26 14:10:20 +00003205 if( nCellKey<nKey ){
3206 c = -1;
3207 }else if( nCellKey>nKey ){
3208 c = +1;
3209 }else{
3210 c = 0;
3211 }
drh3aac2dd2004-04-26 14:10:20 +00003212 }else{
drhe51c44f2004-05-30 20:46:09 +00003213 int available;
danielk197713adf8a2004-06-03 16:08:41 +00003214 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drh366fda62006-01-13 02:35:09 +00003215 nCellKey = pCur->info.nKey;
drhe51c44f2004-05-30 20:46:09 +00003216 if( available>=nCellKey ){
3217 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
3218 }else{
3219 pCellKey = sqliteMallocRaw( nCellKey );
3220 if( pCellKey==0 ) return SQLITE_NOMEM;
danielk197713adf8a2004-06-03 16:08:41 +00003221 rc = sqlite3BtreeKey(pCur, 0, nCellKey, (void *)pCellKey);
drhe51c44f2004-05-30 20:46:09 +00003222 c = pCur->xCompare(pCur->pArg, nCellKey, pCellKey, nKey, pKey);
3223 sqliteFree(pCellKey);
3224 if( rc ) return rc;
3225 }
drh3aac2dd2004-04-26 14:10:20 +00003226 }
drh72f82862001-05-24 21:06:34 +00003227 if( c==0 ){
drh8b18dd42004-05-12 19:18:15 +00003228 if( pPage->leafData && !pPage->leaf ){
drhfc70e6f2004-05-12 21:11:27 +00003229 lwr = pCur->idx;
3230 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00003231 break;
3232 }else{
drh8b18dd42004-05-12 19:18:15 +00003233 if( pRes ) *pRes = 0;
3234 return SQLITE_OK;
3235 }
drh72f82862001-05-24 21:06:34 +00003236 }
3237 if( c<0 ){
3238 lwr = pCur->idx+1;
3239 }else{
3240 upr = pCur->idx-1;
3241 }
drhf1d68b32007-03-29 04:43:26 +00003242 if( lwr>upr ){
3243 break;
3244 }
3245 pCur->idx = (lwr+upr)/2;
drh72f82862001-05-24 21:06:34 +00003246 }
3247 assert( lwr==upr+1 );
drh7aa128d2002-06-21 13:09:16 +00003248 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00003249 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00003250 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00003251 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00003252 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00003253 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00003254 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00003255 }
3256 if( chldPg==0 ){
drhc39e0002004-05-07 23:50:57 +00003257 assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
drh72f82862001-05-24 21:06:34 +00003258 if( pRes ) *pRes = c;
3259 return SQLITE_OK;
3260 }
drh428ae8c2003-01-04 16:48:09 +00003261 pCur->idx = lwr;
drh271efa52004-05-30 19:19:05 +00003262 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00003263 rc = moveToChild(pCur, chldPg);
drhc39e0002004-05-07 23:50:57 +00003264 if( rc ){
3265 return rc;
3266 }
drh72f82862001-05-24 21:06:34 +00003267 }
drhbd03cae2001-06-02 02:40:57 +00003268 /* NOT REACHED */
drh72f82862001-05-24 21:06:34 +00003269}
3270
3271/*
drhc39e0002004-05-07 23:50:57 +00003272** Return TRUE if the cursor is not pointing at an entry of the table.
3273**
3274** TRUE will be returned after a call to sqlite3BtreeNext() moves
3275** past the last entry in the table or sqlite3BtreePrev() moves past
3276** the first entry. TRUE is also returned if the table is empty.
3277*/
3278int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00003279 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
3280 ** have been deleted? This API will need to change to return an error code
3281 ** as well as the boolean result value.
3282 */
3283 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00003284}
3285
3286/*
drhbd03cae2001-06-02 02:40:57 +00003287** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00003288** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00003289** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00003290** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00003291*/
drh3aac2dd2004-04-26 14:10:20 +00003292int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00003293 int rc;
danielk197797a227c2006-01-20 16:32:04 +00003294 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00003295
drhbf700f32007-03-31 02:36:44 +00003296 rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003297 if( rc!=SQLITE_OK ){
3298 return rc;
3299 }
drh8c4d3a62007-04-06 01:03:32 +00003300 assert( pRes!=0 );
3301 pPage = pCur->pPage;
3302 if( CURSOR_INVALID==pCur->eState ){
3303 *pRes = 1;
3304 return SQLITE_OK;
3305 }
danielk1977da184232006-01-05 11:34:32 +00003306 if( pCur->skip>0 ){
3307 pCur->skip = 0;
3308 *pRes = 0;
3309 return SQLITE_OK;
3310 }
3311 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00003312
drh8178a752003-01-05 21:41:40 +00003313 assert( pPage->isInit );
drh8178a752003-01-05 21:41:40 +00003314 assert( pCur->idx<pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00003315
drh72f82862001-05-24 21:06:34 +00003316 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00003317 pCur->info.nSize = 0;
drh8178a752003-01-05 21:41:40 +00003318 if( pCur->idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00003319 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00003320 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00003321 if( rc ) return rc;
3322 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003323 *pRes = 0;
3324 return rc;
drh72f82862001-05-24 21:06:34 +00003325 }
drh5e2f8b92001-05-28 00:41:15 +00003326 do{
drh16a9b832007-05-05 18:39:25 +00003327 if( sqlite3BtreeIsRootPage(pPage) ){
drh8c1238a2003-01-02 14:43:55 +00003328 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00003329 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00003330 return SQLITE_OK;
3331 }
drh16a9b832007-05-05 18:39:25 +00003332 sqlite3BtreeMoveToParent(pCur);
drh8178a752003-01-05 21:41:40 +00003333 pPage = pCur->pPage;
3334 }while( pCur->idx>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00003335 *pRes = 0;
drh8b18dd42004-05-12 19:18:15 +00003336 if( pPage->leafData ){
3337 rc = sqlite3BtreeNext(pCur, pRes);
3338 }else{
3339 rc = SQLITE_OK;
3340 }
3341 return rc;
drh8178a752003-01-05 21:41:40 +00003342 }
3343 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00003344 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00003345 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00003346 }
drh5e2f8b92001-05-28 00:41:15 +00003347 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00003348 return rc;
drh72f82862001-05-24 21:06:34 +00003349}
3350
drh3b7511c2001-05-26 13:15:44 +00003351/*
drh2dcc9aa2002-12-04 13:40:25 +00003352** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00003353** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00003354** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00003355** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00003356*/
drh3aac2dd2004-04-26 14:10:20 +00003357int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00003358 int rc;
3359 Pgno pgno;
drh8178a752003-01-05 21:41:40 +00003360 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00003361
drhbf700f32007-03-31 02:36:44 +00003362 rc = restoreOrClearCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003363 if( rc!=SQLITE_OK ){
3364 return rc;
3365 }
drh8c4d3a62007-04-06 01:03:32 +00003366 if( CURSOR_INVALID==pCur->eState ){
3367 *pRes = 1;
3368 return SQLITE_OK;
3369 }
danielk1977da184232006-01-05 11:34:32 +00003370 if( pCur->skip<0 ){
3371 pCur->skip = 0;
3372 *pRes = 0;
3373 return SQLITE_OK;
3374 }
3375 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00003376
drh8178a752003-01-05 21:41:40 +00003377 pPage = pCur->pPage;
drh8178a752003-01-05 21:41:40 +00003378 assert( pPage->isInit );
drh2dcc9aa2002-12-04 13:40:25 +00003379 assert( pCur->idx>=0 );
drha34b6762004-05-07 13:30:42 +00003380 if( !pPage->leaf ){
danielk19771cc5ed82007-05-16 17:28:43 +00003381 pgno = get4byte( findCell(pPage, pCur->idx) );
drh8178a752003-01-05 21:41:40 +00003382 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003383 if( rc ) return rc;
3384 rc = moveToRightmost(pCur);
3385 }else{
3386 while( pCur->idx==0 ){
drh16a9b832007-05-05 18:39:25 +00003387 if( sqlite3BtreeIsRootPage(pPage) ){
danielk1977da184232006-01-05 11:34:32 +00003388 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00003389 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00003390 return SQLITE_OK;
3391 }
drh16a9b832007-05-05 18:39:25 +00003392 sqlite3BtreeMoveToParent(pCur);
drh8178a752003-01-05 21:41:40 +00003393 pPage = pCur->pPage;
drh2dcc9aa2002-12-04 13:40:25 +00003394 }
3395 pCur->idx--;
drh271efa52004-05-30 19:19:05 +00003396 pCur->info.nSize = 0;
drh8237d452004-11-22 19:07:09 +00003397 if( pPage->leafData && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00003398 rc = sqlite3BtreePrevious(pCur, pRes);
3399 }else{
3400 rc = SQLITE_OK;
3401 }
drh2dcc9aa2002-12-04 13:40:25 +00003402 }
drh8178a752003-01-05 21:41:40 +00003403 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003404 return rc;
3405}
3406
3407/*
drh3b7511c2001-05-26 13:15:44 +00003408** Allocate a new page from the database file.
3409**
danielk19773b8a05f2007-03-19 17:44:26 +00003410** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00003411** has already been called on the new page.) The new page has also
3412** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00003413** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00003414**
3415** SQLITE_OK is returned on success. Any other return value indicates
3416** an error. *ppPage and *pPgno are undefined in the event of an error.
danielk19773b8a05f2007-03-19 17:44:26 +00003417** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00003418**
drh199e3cf2002-07-18 11:01:47 +00003419** If the "nearby" parameter is not 0, then a (feeble) effort is made to
3420** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00003421** attempt to keep related pages close to each other in the database file,
3422** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00003423**
3424** If the "exact" parameter is not 0, and the page-number nearby exists
3425** anywhere on the free-list, then it is guarenteed to be returned. This
3426** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00003427*/
drh4f0c5872007-03-26 22:05:01 +00003428static int allocateBtreePage(
danielk1977aef0bf62005-12-30 16:28:01 +00003429 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00003430 MemPage **ppPage,
3431 Pgno *pPgno,
3432 Pgno nearby,
3433 u8 exact
3434){
drh3aac2dd2004-04-26 14:10:20 +00003435 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00003436 int rc;
drh3aac2dd2004-04-26 14:10:20 +00003437 int n; /* Number of pages on the freelist */
3438 int k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00003439 MemPage *pTrunk = 0;
3440 MemPage *pPrevTrunk = 0;
drh30e58752002-03-02 20:41:57 +00003441
drh3aac2dd2004-04-26 14:10:20 +00003442 pPage1 = pBt->pPage1;
3443 n = get4byte(&pPage1->aData[36]);
3444 if( n>0 ){
drh91025292004-05-03 19:49:32 +00003445 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00003446 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003447 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
3448
3449 /* If the 'exact' parameter was true and a query of the pointer-map
3450 ** shows that the page 'nearby' is somewhere on the free-list, then
3451 ** the entire-list will be searched for that page.
3452 */
3453#ifndef SQLITE_OMIT_AUTOVACUUM
3454 if( exact ){
3455 u8 eType;
3456 assert( nearby>0 );
3457 assert( pBt->autoVacuum );
3458 rc = ptrmapGet(pBt, nearby, &eType, 0);
3459 if( rc ) return rc;
3460 if( eType==PTRMAP_FREEPAGE ){
3461 searchList = 1;
3462 }
3463 *pPgno = nearby;
3464 }
3465#endif
3466
3467 /* Decrement the free-list count by 1. Set iTrunk to the index of the
3468 ** first free-list trunk page. iPrevTrunk is initially 1.
3469 */
danielk19773b8a05f2007-03-19 17:44:26 +00003470 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00003471 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003472 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003473
3474 /* The code within this loop is run only once if the 'searchList' variable
3475 ** is not true. Otherwise, it runs once for each trunk-page on the
3476 ** free-list until the page 'nearby' is located.
3477 */
3478 do {
3479 pPrevTrunk = pTrunk;
3480 if( pPrevTrunk ){
3481 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00003482 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00003483 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00003484 }
drh16a9b832007-05-05 18:39:25 +00003485 rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003486 if( rc ){
drhd3627af2006-12-18 18:34:51 +00003487 pTrunk = 0;
3488 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003489 }
3490
3491 k = get4byte(&pTrunk->aData[4]);
3492 if( k==0 && !searchList ){
3493 /* The trunk has no leaves and the list is not being searched.
3494 ** So extract the trunk page itself and use it as the newly
3495 ** allocated page */
3496 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00003497 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00003498 if( rc ){
3499 goto end_allocate_page;
3500 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003501 *pPgno = iTrunk;
3502 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3503 *ppPage = pTrunk;
3504 pTrunk = 0;
3505 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3506 }else if( k>pBt->usableSize/4 - 8 ){
3507 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00003508 rc = SQLITE_CORRUPT_BKPT;
3509 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003510#ifndef SQLITE_OMIT_AUTOVACUUM
3511 }else if( searchList && nearby==iTrunk ){
3512 /* The list is being searched and this trunk page is the page
3513 ** to allocate, regardless of whether it has leaves.
3514 */
3515 assert( *pPgno==iTrunk );
3516 *ppPage = pTrunk;
3517 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00003518 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00003519 if( rc ){
3520 goto end_allocate_page;
3521 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003522 if( k==0 ){
3523 if( !pPrevTrunk ){
3524 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
3525 }else{
3526 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
3527 }
3528 }else{
3529 /* The trunk page is required by the caller but it contains
3530 ** pointers to free-list leaves. The first leaf becomes a trunk
3531 ** page in this case.
3532 */
3533 MemPage *pNewTrunk;
3534 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh16a9b832007-05-05 18:39:25 +00003535 rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003536 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00003537 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003538 }
danielk19773b8a05f2007-03-19 17:44:26 +00003539 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003540 if( rc!=SQLITE_OK ){
3541 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00003542 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003543 }
3544 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
3545 put4byte(&pNewTrunk->aData[4], k-1);
3546 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00003547 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003548 if( !pPrevTrunk ){
3549 put4byte(&pPage1->aData[32], iNewTrunk);
3550 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00003551 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00003552 if( rc ){
3553 goto end_allocate_page;
3554 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003555 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
3556 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003557 }
3558 pTrunk = 0;
3559 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
3560#endif
3561 }else{
3562 /* Extract a leaf from the trunk */
3563 int closest;
3564 Pgno iPage;
3565 unsigned char *aData = pTrunk->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00003566 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00003567 if( rc ){
3568 goto end_allocate_page;
3569 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003570 if( nearby>0 ){
3571 int i, dist;
3572 closest = 0;
3573 dist = get4byte(&aData[8]) - nearby;
3574 if( dist<0 ) dist = -dist;
3575 for(i=1; i<k; i++){
3576 int d2 = get4byte(&aData[8+i*4]) - nearby;
3577 if( d2<0 ) d2 = -d2;
3578 if( d2<dist ){
3579 closest = i;
3580 dist = d2;
3581 }
3582 }
3583 }else{
3584 closest = 0;
3585 }
3586
3587 iPage = get4byte(&aData[8+closest*4]);
3588 if( !searchList || iPage==nearby ){
3589 *pPgno = iPage;
danielk19773b8a05f2007-03-19 17:44:26 +00003590 if( *pPgno>sqlite3PagerPagecount(pBt->pPager) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00003591 /* Free page off the end of the file */
drh49285702005-09-17 15:20:26 +00003592 return SQLITE_CORRUPT_BKPT;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003593 }
3594 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
3595 ": %d more free pages\n",
3596 *pPgno, closest+1, k, pTrunk->pgno, n-1));
3597 if( closest<k-1 ){
3598 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
3599 }
3600 put4byte(&aData[4], k-1);
drh16a9b832007-05-05 18:39:25 +00003601 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00003602 if( rc==SQLITE_OK ){
drh538f5702007-04-13 02:14:30 +00003603 sqlite3PagerDontRollback((*ppPage)->pDbPage);
danielk19773b8a05f2007-03-19 17:44:26 +00003604 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00003605 if( rc!=SQLITE_OK ){
3606 releasePage(*ppPage);
3607 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003608 }
3609 searchList = 0;
3610 }
drhee696e22004-08-30 16:52:17 +00003611 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00003612 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00003613 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00003614 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00003615 }else{
drh3aac2dd2004-04-26 14:10:20 +00003616 /* There are no pages on the freelist, so create a new page at the
3617 ** end of the file */
danielk19773b8a05f2007-03-19 17:44:26 +00003618 *pPgno = sqlite3PagerPagecount(pBt->pPager) + 1;
danielk1977afcdd022004-10-31 16:25:42 +00003619
3620#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00003621 if( pBt->nTrunc ){
3622 /* An incr-vacuum has already run within this transaction. So the
3623 ** page to allocate is not from the physical end of the file, but
3624 ** at pBt->nTrunc.
3625 */
3626 *pPgno = pBt->nTrunc+1;
3627 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
3628 (*pPgno)++;
3629 }
3630 }
danielk1977266664d2006-02-10 08:24:21 +00003631 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00003632 /* If *pPgno refers to a pointer-map page, allocate two new pages
3633 ** at the end of the file instead of one. The first allocated page
3634 ** becomes a new pointer-map page, the second is used by the caller.
3635 */
3636 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00003637 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977afcdd022004-10-31 16:25:42 +00003638 (*pPgno)++;
3639 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003640 if( pBt->nTrunc ){
3641 pBt->nTrunc = *pPgno;
3642 }
danielk1977afcdd022004-10-31 16:25:42 +00003643#endif
3644
danielk1977599fcba2004-11-08 07:13:13 +00003645 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh16a9b832007-05-05 18:39:25 +00003646 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
drh3b7511c2001-05-26 13:15:44 +00003647 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00003648 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00003649 if( rc!=SQLITE_OK ){
3650 releasePage(*ppPage);
3651 }
drh3a4c1412004-05-09 20:40:11 +00003652 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00003653 }
danielk1977599fcba2004-11-08 07:13:13 +00003654
3655 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00003656
3657end_allocate_page:
3658 releasePage(pTrunk);
3659 releasePage(pPrevTrunk);
drh3b7511c2001-05-26 13:15:44 +00003660 return rc;
3661}
3662
3663/*
drh3aac2dd2004-04-26 14:10:20 +00003664** Add a page of the database file to the freelist.
drh5e2f8b92001-05-28 00:41:15 +00003665**
danielk19773b8a05f2007-03-19 17:44:26 +00003666** sqlite3PagerUnref() is NOT called for pPage.
drh3b7511c2001-05-26 13:15:44 +00003667*/
drh3aac2dd2004-04-26 14:10:20 +00003668static int freePage(MemPage *pPage){
danielk1977aef0bf62005-12-30 16:28:01 +00003669 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00003670 MemPage *pPage1 = pBt->pPage1;
3671 int rc, n, k;
drh8b2f49b2001-06-08 00:21:52 +00003672
drh3aac2dd2004-04-26 14:10:20 +00003673 /* Prepare the page for freeing */
3674 assert( pPage->pgno>1 );
3675 pPage->isInit = 0;
3676 releasePage(pPage->pParent);
3677 pPage->pParent = 0;
3678
drha34b6762004-05-07 13:30:42 +00003679 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00003680 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00003681 if( rc ) return rc;
3682 n = get4byte(&pPage1->aData[36]);
3683 put4byte(&pPage1->aData[36], n+1);
3684
drhfcce93f2006-02-22 03:08:32 +00003685#ifdef SQLITE_SECURE_DELETE
3686 /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
3687 ** always fully overwrite deleted information with zeros.
3688 */
danielk19773b8a05f2007-03-19 17:44:26 +00003689 rc = sqlite3PagerWrite(pPage->pDbPage);
drhfcce93f2006-02-22 03:08:32 +00003690 if( rc ) return rc;
3691 memset(pPage->aData, 0, pPage->pBt->pageSize);
3692#endif
3693
danielk1977687566d2004-11-02 12:56:41 +00003694#ifndef SQLITE_OMIT_AUTOVACUUM
3695 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00003696 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00003697 */
3698 if( pBt->autoVacuum ){
3699 rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
danielk1977a64a0352004-11-05 01:45:13 +00003700 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00003701 }
3702#endif
3703
drh3aac2dd2004-04-26 14:10:20 +00003704 if( n==0 ){
3705 /* This is the first free page */
danielk19773b8a05f2007-03-19 17:44:26 +00003706 rc = sqlite3PagerWrite(pPage->pDbPage);
drhda200cc2004-05-09 11:51:38 +00003707 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003708 memset(pPage->aData, 0, 8);
drha34b6762004-05-07 13:30:42 +00003709 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003710 TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003711 }else{
3712 /* Other free pages already exist. Retrive the first trunk page
3713 ** of the freelist and find out how many leaves it has. */
drha34b6762004-05-07 13:30:42 +00003714 MemPage *pTrunk;
drh16a9b832007-05-05 18:39:25 +00003715 rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0);
drh3b7511c2001-05-26 13:15:44 +00003716 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00003717 k = get4byte(&pTrunk->aData[4]);
drhee696e22004-08-30 16:52:17 +00003718 if( k>=pBt->usableSize/4 - 8 ){
drh3aac2dd2004-04-26 14:10:20 +00003719 /* The trunk is full. Turn the page being freed into a new
3720 ** trunk page with no leaves. */
danielk19773b8a05f2007-03-19 17:44:26 +00003721 rc = sqlite3PagerWrite(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00003722 if( rc ) return rc;
3723 put4byte(pPage->aData, pTrunk->pgno);
3724 put4byte(&pPage->aData[4], 0);
3725 put4byte(&pPage1->aData[32], pPage->pgno);
drh3a4c1412004-05-09 20:40:11 +00003726 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
3727 pPage->pgno, pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003728 }else{
3729 /* Add the newly freed page as a leaf on the current trunk */
danielk19773b8a05f2007-03-19 17:44:26 +00003730 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00003731 if( rc==SQLITE_OK ){
3732 put4byte(&pTrunk->aData[4], k+1);
3733 put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
drhfcce93f2006-02-22 03:08:32 +00003734#ifndef SQLITE_SECURE_DELETE
drh538f5702007-04-13 02:14:30 +00003735 sqlite3PagerDontWrite(pPage->pDbPage);
drhfcce93f2006-02-22 03:08:32 +00003736#endif
drhf5345442007-04-09 12:45:02 +00003737 }
drh3a4c1412004-05-09 20:40:11 +00003738 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
drh3aac2dd2004-04-26 14:10:20 +00003739 }
3740 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00003741 }
drh3b7511c2001-05-26 13:15:44 +00003742 return rc;
3743}
3744
3745/*
drh3aac2dd2004-04-26 14:10:20 +00003746** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00003747*/
drh3aac2dd2004-04-26 14:10:20 +00003748static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00003749 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00003750 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00003751 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00003752 int rc;
drh94440812007-03-06 11:42:19 +00003753 int nOvfl;
3754 int ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00003755
drh16a9b832007-05-05 18:39:25 +00003756 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003757 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00003758 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00003759 }
drh6f11bef2004-05-13 01:12:56 +00003760 ovflPgno = get4byte(&pCell[info.iOverflow]);
drh94440812007-03-06 11:42:19 +00003761 ovflPageSize = pBt->usableSize - 4;
drh72365832007-03-06 15:53:44 +00003762 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
3763 assert( ovflPgno==0 || nOvfl>0 );
3764 while( nOvfl-- ){
drh3aac2dd2004-04-26 14:10:20 +00003765 MemPage *pOvfl;
danielk19773b8a05f2007-03-19 17:44:26 +00003766 if( ovflPgno==0 || ovflPgno>sqlite3PagerPagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00003767 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00003768 }
danielk19778c0a9592007-04-30 16:55:00 +00003769
3770 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno);
drh3b7511c2001-05-26 13:15:44 +00003771 if( rc ) return rc;
drha34b6762004-05-07 13:30:42 +00003772 rc = freePage(pOvfl);
danielk19773b8a05f2007-03-19 17:44:26 +00003773 sqlite3PagerUnref(pOvfl->pDbPage);
danielk19776b456a22005-03-21 04:04:02 +00003774 if( rc ) return rc;
drh3b7511c2001-05-26 13:15:44 +00003775 }
drh5e2f8b92001-05-28 00:41:15 +00003776 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00003777}
3778
3779/*
drh91025292004-05-03 19:49:32 +00003780** Create the byte sequence used to represent a cell on page pPage
3781** and write that byte sequence into pCell[]. Overflow pages are
3782** allocated and filled in as necessary. The calling procedure
3783** is responsible for making sure sufficient space has been allocated
3784** for pCell[].
3785**
3786** Note that pCell does not necessary need to point to the pPage->aData
3787** area. pCell might point to some temporary storage. The cell will
3788** be constructed in this temporary area then copied into pPage->aData
3789** later.
drh3b7511c2001-05-26 13:15:44 +00003790*/
3791static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00003792 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00003793 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00003794 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00003795 const void *pData,int nData, /* The data */
drhb026e052007-05-02 01:34:31 +00003796 int nZero, /* Extra zero bytes to append to pData */
drh4b70f112004-05-02 21:12:19 +00003797 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00003798){
drh3b7511c2001-05-26 13:15:44 +00003799 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00003800 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00003801 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00003802 int spaceLeft;
3803 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00003804 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00003805 unsigned char *pPrior;
3806 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00003807 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00003808 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00003809 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00003810 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00003811
drh91025292004-05-03 19:49:32 +00003812 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00003813 nHeader = 0;
drh91025292004-05-03 19:49:32 +00003814 if( !pPage->leaf ){
3815 nHeader += 4;
3816 }
drh8b18dd42004-05-12 19:18:15 +00003817 if( pPage->hasData ){
drhb026e052007-05-02 01:34:31 +00003818 nHeader += putVarint(&pCell[nHeader], nData+nZero);
drh6f11bef2004-05-13 01:12:56 +00003819 }else{
drhb026e052007-05-02 01:34:31 +00003820 nData = nZero = 0;
drh91025292004-05-03 19:49:32 +00003821 }
drh6f11bef2004-05-13 01:12:56 +00003822 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh16a9b832007-05-05 18:39:25 +00003823 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00003824 assert( info.nHeader==nHeader );
3825 assert( info.nKey==nKey );
drhb026e052007-05-02 01:34:31 +00003826 assert( info.nData==nData+nZero );
drh6f11bef2004-05-13 01:12:56 +00003827
3828 /* Fill in the payload */
drhb026e052007-05-02 01:34:31 +00003829 nPayload = nData + nZero;
drh3aac2dd2004-04-26 14:10:20 +00003830 if( pPage->intKey ){
3831 pSrc = pData;
3832 nSrc = nData;
drh91025292004-05-03 19:49:32 +00003833 nData = 0;
drh3aac2dd2004-04-26 14:10:20 +00003834 }else{
3835 nPayload += nKey;
3836 pSrc = pKey;
3837 nSrc = nKey;
3838 }
drh6f11bef2004-05-13 01:12:56 +00003839 *pnSize = info.nSize;
3840 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00003841 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00003842 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00003843
drh3b7511c2001-05-26 13:15:44 +00003844 while( nPayload>0 ){
3845 if( spaceLeft==0 ){
danielk1977b39f70b2007-05-17 18:28:11 +00003846 int isExact = 0;
danielk1977afcdd022004-10-31 16:25:42 +00003847#ifndef SQLITE_OMIT_AUTOVACUUM
3848 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00003849 if( pBt->autoVacuum ){
3850 do{
3851 pgnoOvfl++;
3852 } while(
3853 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
3854 );
3855 if( pgnoOvfl>1 ){
3856 /* isExact = 1; */
3857 }
3858 }
danielk1977afcdd022004-10-31 16:25:42 +00003859#endif
danielk1977b39f70b2007-05-17 18:28:11 +00003860 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, isExact);
danielk1977afcdd022004-10-31 16:25:42 +00003861#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00003862 /* If the database supports auto-vacuum, and the second or subsequent
3863 ** overflow page is being allocated, add an entry to the pointer-map
3864 ** for that page now. The entry for the first overflow page will be
3865 ** added later, by the insertCell() routine.
danielk1977afcdd022004-10-31 16:25:42 +00003866 */
danielk1977a19df672004-11-03 11:37:07 +00003867 if( pBt->autoVacuum && pgnoPtrmap!=0 && rc==SQLITE_OK ){
3868 rc = ptrmapPut(pBt, pgnoOvfl, PTRMAP_OVERFLOW2, pgnoPtrmap);
danielk1977afcdd022004-10-31 16:25:42 +00003869 }
3870#endif
drh3b7511c2001-05-26 13:15:44 +00003871 if( rc ){
drh9b171272004-05-08 02:03:22 +00003872 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00003873 return rc;
3874 }
drh3aac2dd2004-04-26 14:10:20 +00003875 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00003876 releasePage(pToRelease);
3877 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00003878 pPrior = pOvfl->aData;
3879 put4byte(pPrior, 0);
3880 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00003881 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00003882 }
3883 n = nPayload;
3884 if( n>spaceLeft ) n = spaceLeft;
drhb026e052007-05-02 01:34:31 +00003885 if( nSrc>0 ){
3886 if( n>nSrc ) n = nSrc;
3887 assert( pSrc );
3888 memcpy(pPayload, pSrc, n);
3889 }else{
3890 memset(pPayload, 0, n);
3891 }
drh3b7511c2001-05-26 13:15:44 +00003892 nPayload -= n;
drhde647132004-05-07 17:57:49 +00003893 pPayload += n;
drh9b171272004-05-08 02:03:22 +00003894 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00003895 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00003896 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00003897 if( nSrc==0 ){
3898 nSrc = nData;
3899 pSrc = pData;
3900 }
drhdd793422001-06-28 01:54:48 +00003901 }
drh9b171272004-05-08 02:03:22 +00003902 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00003903 return SQLITE_OK;
3904}
3905
3906/*
drhbd03cae2001-06-02 02:40:57 +00003907** Change the MemPage.pParent pointer on the page whose number is
drh8b2f49b2001-06-08 00:21:52 +00003908** given in the second argument so that MemPage.pParent holds the
drhbd03cae2001-06-02 02:40:57 +00003909** pointer in the third argument.
3910*/
danielk1977aef0bf62005-12-30 16:28:01 +00003911static int reparentPage(BtShared *pBt, Pgno pgno, MemPage *pNewParent, int idx){
drhbd03cae2001-06-02 02:40:57 +00003912 MemPage *pThis;
danielk19773b8a05f2007-03-19 17:44:26 +00003913 DbPage *pDbPage;
drhbd03cae2001-06-02 02:40:57 +00003914
drh43617e92006-03-06 20:55:46 +00003915 assert( pNewParent!=0 );
danielk1977afcdd022004-10-31 16:25:42 +00003916 if( pgno==0 ) return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00003917 assert( pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00003918 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
3919 if( pDbPage ){
3920 pThis = (MemPage *)sqlite3PagerGetExtra(pDbPage);
drhda200cc2004-05-09 11:51:38 +00003921 if( pThis->isInit ){
danielk19773b8a05f2007-03-19 17:44:26 +00003922 assert( pThis->aData==(sqlite3PagerGetData(pDbPage)) );
drhda200cc2004-05-09 11:51:38 +00003923 if( pThis->pParent!=pNewParent ){
danielk19773b8a05f2007-03-19 17:44:26 +00003924 if( pThis->pParent ) sqlite3PagerUnref(pThis->pParent->pDbPage);
drhda200cc2004-05-09 11:51:38 +00003925 pThis->pParent = pNewParent;
danielk19773b8a05f2007-03-19 17:44:26 +00003926 sqlite3PagerRef(pNewParent->pDbPage);
drhda200cc2004-05-09 11:51:38 +00003927 }
3928 pThis->idxParent = idx;
drhdd793422001-06-28 01:54:48 +00003929 }
danielk19773b8a05f2007-03-19 17:44:26 +00003930 sqlite3PagerUnref(pDbPage);
drhbd03cae2001-06-02 02:40:57 +00003931 }
danielk1977afcdd022004-10-31 16:25:42 +00003932
3933#ifndef SQLITE_OMIT_AUTOVACUUM
3934 if( pBt->autoVacuum ){
3935 return ptrmapPut(pBt, pgno, PTRMAP_BTREE, pNewParent->pgno);
3936 }
3937#endif
3938 return SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00003939}
3940
danielk1977ac11ee62005-01-15 12:45:51 +00003941
3942
drhbd03cae2001-06-02 02:40:57 +00003943/*
drh4b70f112004-05-02 21:12:19 +00003944** Change the pParent pointer of all children of pPage to point back
3945** to pPage.
3946**
drhbd03cae2001-06-02 02:40:57 +00003947** In other words, for every child of pPage, invoke reparentPage()
drh5e00f6c2001-09-13 13:46:56 +00003948** to make sure that each child knows that pPage is its parent.
drhbd03cae2001-06-02 02:40:57 +00003949**
3950** This routine gets called after you memcpy() one page into
3951** another.
3952*/
danielk1977afcdd022004-10-31 16:25:42 +00003953static int reparentChildPages(MemPage *pPage){
drhbd03cae2001-06-02 02:40:57 +00003954 int i;
danielk1977aef0bf62005-12-30 16:28:01 +00003955 BtShared *pBt = pPage->pBt;
danielk1977afcdd022004-10-31 16:25:42 +00003956 int rc = SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00003957
danielk1977afcdd022004-10-31 16:25:42 +00003958 if( pPage->leaf ) return SQLITE_OK;
danielk1977afcdd022004-10-31 16:25:42 +00003959
drhbd03cae2001-06-02 02:40:57 +00003960 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00003961 u8 *pCell = findCell(pPage, i);
danielk1977afcdd022004-10-31 16:25:42 +00003962 if( !pPage->leaf ){
3963 rc = reparentPage(pBt, get4byte(pCell), pPage, i);
3964 if( rc!=SQLITE_OK ) return rc;
3965 }
drhbd03cae2001-06-02 02:40:57 +00003966 }
danielk1977afcdd022004-10-31 16:25:42 +00003967 if( !pPage->leaf ){
3968 rc = reparentPage(pBt, get4byte(&pPage->aData[pPage->hdrOffset+8]),
3969 pPage, i);
3970 pPage->idxShift = 0;
3971 }
3972 return rc;
drh14acc042001-06-10 19:56:58 +00003973}
3974
3975/*
3976** Remove the i-th cell from pPage. This routine effects pPage only.
3977** The cell content is not freed or deallocated. It is assumed that
3978** the cell content has been copied someplace else. This routine just
3979** removes the reference to the cell from pPage.
3980**
3981** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00003982*/
drh4b70f112004-05-02 21:12:19 +00003983static void dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00003984 int i; /* Loop counter */
3985 int pc; /* Offset to cell content of cell being deleted */
3986 u8 *data; /* pPage->aData */
3987 u8 *ptr; /* Used to move bytes around within data[] */
3988
drh8c42ca92001-06-22 19:15:00 +00003989 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00003990 assert( sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00003991 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drhda200cc2004-05-09 11:51:38 +00003992 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00003993 ptr = &data[pPage->cellOffset + 2*idx];
3994 pc = get2byte(ptr);
3995 assert( pc>10 && pc+sz<=pPage->pBt->usableSize );
drhde647132004-05-07 17:57:49 +00003996 freeSpace(pPage, pc, sz);
drh43605152004-05-29 21:46:49 +00003997 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
3998 ptr[0] = ptr[2];
3999 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00004000 }
4001 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00004002 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
4003 pPage->nFree += 2;
drh428ae8c2003-01-04 16:48:09 +00004004 pPage->idxShift = 1;
drh14acc042001-06-10 19:56:58 +00004005}
4006
4007/*
4008** Insert a new cell on pPage at cell index "i". pCell points to the
4009** content of the cell.
4010**
4011** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00004012** will not fit, then make a copy of the cell content into pTemp if
4013** pTemp is not null. Regardless of pTemp, allocate a new entry
4014** in pPage->aOvfl[] and make it point to the cell content (either
4015** in pTemp or the original pCell) and also record its index.
4016** Allocating a new entry in pPage->aCell[] implies that
4017** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00004018**
4019** If nSkip is non-zero, then do not copy the first nSkip bytes of the
4020** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00004021** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00004022** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00004023*/
danielk1977e80463b2004-11-03 03:01:16 +00004024static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00004025 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00004026 int i, /* New cell becomes the i-th cell of the page */
4027 u8 *pCell, /* Content of the new cell */
4028 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00004029 u8 *pTemp, /* Temp storage space for pCell, if needed */
4030 u8 nSkip /* Do not write the first nSkip bytes of the cell */
drh24cd67e2004-05-10 16:18:47 +00004031){
drh43605152004-05-29 21:46:49 +00004032 int idx; /* Where to write new cell content in data[] */
4033 int j; /* Loop counter */
4034 int top; /* First byte of content for any cell in data[] */
4035 int end; /* First byte past the last cell pointer in data[] */
4036 int ins; /* Index in data[] where new cell pointer is inserted */
4037 int hdr; /* Offset into data[] of the page header */
4038 int cellOffset; /* Address of first cell pointer in data[] */
4039 u8 *data; /* The content of the whole page */
4040 u8 *ptr; /* Used for moving information around in data[] */
4041
4042 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
4043 assert( sz==cellSizePtr(pPage, pCell) );
danielk19773b8a05f2007-03-19 17:44:26 +00004044 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00004045 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00004046 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00004047 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004048 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00004049 }
drh43605152004-05-29 21:46:49 +00004050 j = pPage->nOverflow++;
4051 assert( j<sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0]) );
4052 pPage->aOvfl[j].pCell = pCell;
4053 pPage->aOvfl[j].idx = i;
4054 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00004055 }else{
drh43605152004-05-29 21:46:49 +00004056 data = pPage->aData;
4057 hdr = pPage->hdrOffset;
4058 top = get2byte(&data[hdr+5]);
4059 cellOffset = pPage->cellOffset;
4060 end = cellOffset + 2*pPage->nCell + 2;
4061 ins = cellOffset + 2*i;
4062 if( end > top - sz ){
danielk19776b456a22005-03-21 04:04:02 +00004063 int rc = defragmentPage(pPage);
4064 if( rc!=SQLITE_OK ) return rc;
drh43605152004-05-29 21:46:49 +00004065 top = get2byte(&data[hdr+5]);
4066 assert( end + sz <= top );
4067 }
4068 idx = allocateSpace(pPage, sz);
4069 assert( idx>0 );
4070 assert( end <= get2byte(&data[hdr+5]) );
4071 pPage->nCell++;
4072 pPage->nFree -= 2;
danielk1977a3ad5e72005-01-07 08:56:44 +00004073 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004074 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
4075 ptr[0] = ptr[-2];
4076 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00004077 }
drh43605152004-05-29 21:46:49 +00004078 put2byte(&data[ins], idx);
4079 put2byte(&data[hdr+3], pPage->nCell);
4080 pPage->idxShift = 1;
danielk1977a19df672004-11-03 11:37:07 +00004081#ifndef SQLITE_OMIT_AUTOVACUUM
4082 if( pPage->pBt->autoVacuum ){
4083 /* The cell may contain a pointer to an overflow page. If so, write
4084 ** the entry for the overflow page into the pointer map.
4085 */
4086 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00004087 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh72365832007-03-06 15:53:44 +00004088 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk1977a19df672004-11-03 11:37:07 +00004089 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
4090 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
4091 int rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
4092 if( rc!=SQLITE_OK ) return rc;
4093 }
4094 }
4095#endif
drh14acc042001-06-10 19:56:58 +00004096 }
danielk1977e80463b2004-11-03 03:01:16 +00004097
danielk1977e80463b2004-11-03 03:01:16 +00004098 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004099}
4100
4101/*
drhfa1a98a2004-05-14 19:08:17 +00004102** Add a list of cells to a page. The page should be initially empty.
4103** The cells are guaranteed to fit on the page.
4104*/
4105static void assemblePage(
4106 MemPage *pPage, /* The page to be assemblied */
4107 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00004108 u8 **apCell, /* Pointers to cell bodies */
drhfa1a98a2004-05-14 19:08:17 +00004109 int *aSize /* Sizes of the cells */
4110){
4111 int i; /* Loop counter */
4112 int totalSize; /* Total size of all cells */
4113 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00004114 int cellptr; /* Address of next cell pointer */
4115 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00004116 u8 *data; /* Data for the page */
4117
drh43605152004-05-29 21:46:49 +00004118 assert( pPage->nOverflow==0 );
drhfa1a98a2004-05-14 19:08:17 +00004119 totalSize = 0;
4120 for(i=0; i<nCell; i++){
4121 totalSize += aSize[i];
4122 }
drh43605152004-05-29 21:46:49 +00004123 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00004124 assert( pPage->nCell==0 );
drh43605152004-05-29 21:46:49 +00004125 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00004126 data = pPage->aData;
4127 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00004128 put2byte(&data[hdr+3], nCell);
drh09d0deb2005-08-02 17:13:09 +00004129 if( nCell ){
4130 cellbody = allocateSpace(pPage, totalSize);
4131 assert( cellbody>0 );
4132 assert( pPage->nFree >= 2*nCell );
4133 pPage->nFree -= 2*nCell;
4134 for(i=0; i<nCell; i++){
4135 put2byte(&data[cellptr], cellbody);
4136 memcpy(&data[cellbody], apCell[i], aSize[i]);
4137 cellptr += 2;
4138 cellbody += aSize[i];
4139 }
4140 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00004141 }
4142 pPage->nCell = nCell;
drhfa1a98a2004-05-14 19:08:17 +00004143}
4144
drh14acc042001-06-10 19:56:58 +00004145/*
drhc3b70572003-01-04 19:44:07 +00004146** The following parameters determine how many adjacent pages get involved
4147** in a balancing operation. NN is the number of neighbors on either side
4148** of the page that participate in the balancing operation. NB is the
4149** total number of pages that participate, including the target page and
4150** NN neighbors on either side.
4151**
4152** The minimum value of NN is 1 (of course). Increasing NN above 1
4153** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
4154** in exchange for a larger degradation in INSERT and UPDATE performance.
4155** The value of NN appears to give the best results overall.
4156*/
4157#define NN 1 /* Number of neighbors on either side of pPage */
4158#define NB (NN*2+1) /* Total pages involved in the balance */
4159
drh43605152004-05-29 21:46:49 +00004160/* Forward reference */
danielk1977ac245ec2005-01-14 13:50:11 +00004161static int balance(MemPage*, int);
4162
drh615ae552005-01-16 23:21:00 +00004163#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004164/*
4165** This version of balance() handles the common special case where
4166** a new entry is being inserted on the extreme right-end of the
4167** tree, in other words, when the new entry will become the largest
4168** entry in the tree.
4169**
4170** Instead of trying balance the 3 right-most leaf pages, just add
4171** a new page to the right-hand side and put the one new entry in
4172** that page. This leaves the right side of the tree somewhat
4173** unbalanced. But odds are that we will be inserting new entries
4174** at the end soon afterwards so the nearly empty page will quickly
4175** fill up. On average.
4176**
4177** pPage is the leaf page which is the right-most page in the tree.
4178** pParent is its parent. pPage must have a single overflow entry
4179** which is also the right-most entry on the page.
4180*/
danielk1977ac245ec2005-01-14 13:50:11 +00004181static int balance_quick(MemPage *pPage, MemPage *pParent){
4182 int rc;
4183 MemPage *pNew;
4184 Pgno pgnoNew;
4185 u8 *pCell;
4186 int szCell;
4187 CellInfo info;
danielk1977aef0bf62005-12-30 16:28:01 +00004188 BtShared *pBt = pPage->pBt;
danielk197779a40da2005-01-16 08:00:01 +00004189 int parentIdx = pParent->nCell; /* pParent new divider cell index */
4190 int parentSize; /* Size of new divider cell */
4191 u8 parentCell[64]; /* Space for the new divider cell */
danielk1977ac245ec2005-01-14 13:50:11 +00004192
4193 /* Allocate a new page. Insert the overflow cell from pPage
4194 ** into it. Then remove the overflow cell from pPage.
4195 */
drh4f0c5872007-03-26 22:05:01 +00004196 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk1977ac245ec2005-01-14 13:50:11 +00004197 if( rc!=SQLITE_OK ){
4198 return rc;
4199 }
4200 pCell = pPage->aOvfl[0].pCell;
4201 szCell = cellSizePtr(pPage, pCell);
4202 zeroPage(pNew, pPage->aData[0]);
4203 assemblePage(pNew, 1, &pCell, &szCell);
4204 pPage->nOverflow = 0;
4205
danielk197779a40da2005-01-16 08:00:01 +00004206 /* Set the parent of the newly allocated page to pParent. */
4207 pNew->pParent = pParent;
danielk19773b8a05f2007-03-19 17:44:26 +00004208 sqlite3PagerRef(pParent->pDbPage);
danielk197779a40da2005-01-16 08:00:01 +00004209
danielk1977ac245ec2005-01-14 13:50:11 +00004210 /* pPage is currently the right-child of pParent. Change this
4211 ** so that the right-child is the new page allocated above and
danielk197779a40da2005-01-16 08:00:01 +00004212 ** pPage is the next-to-right child.
danielk1977ac245ec2005-01-14 13:50:11 +00004213 */
danielk1977ac11ee62005-01-15 12:45:51 +00004214 assert( pPage->nCell>0 );
danielk19771cc5ed82007-05-16 17:28:43 +00004215 pCell = findCell(pPage, pPage->nCell-1);
drh16a9b832007-05-05 18:39:25 +00004216 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drhb026e052007-05-02 01:34:31 +00004217 rc = fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
danielk1977ac245ec2005-01-14 13:50:11 +00004218 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00004219 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004220 }
4221 assert( parentSize<64 );
4222 rc = insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
4223 if( rc!=SQLITE_OK ){
danielk197779a40da2005-01-16 08:00:01 +00004224 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00004225 }
4226 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
4227 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
4228
danielk197779a40da2005-01-16 08:00:01 +00004229#ifndef SQLITE_OMIT_AUTOVACUUM
4230 /* If this is an auto-vacuum database, update the pointer map
4231 ** with entries for the new page, and any pointer from the
4232 ** cell on the page to an overflow page.
4233 */
danielk1977ac11ee62005-01-15 12:45:51 +00004234 if( pBt->autoVacuum ){
4235 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
4236 if( rc!=SQLITE_OK ){
4237 return rc;
4238 }
danielk197779a40da2005-01-16 08:00:01 +00004239 rc = ptrmapPutOvfl(pNew, 0);
4240 if( rc!=SQLITE_OK ){
4241 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00004242 }
4243 }
danielk197779a40da2005-01-16 08:00:01 +00004244#endif
danielk1977ac11ee62005-01-15 12:45:51 +00004245
danielk197779a40da2005-01-16 08:00:01 +00004246 /* Release the reference to the new page and balance the parent page,
4247 ** in case the divider cell inserted caused it to become overfull.
4248 */
danielk1977ac245ec2005-01-14 13:50:11 +00004249 releasePage(pNew);
4250 return balance(pParent, 0);
4251}
drh615ae552005-01-16 23:21:00 +00004252#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00004253
drhc3b70572003-01-04 19:44:07 +00004254/*
drhab01f612004-05-22 02:55:23 +00004255** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00004256** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00004257** Usually NN siblings on either side of pPage is used in the balancing,
4258** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00004259** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00004260** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00004261** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00004262**
drh0c6cc4e2004-06-15 02:13:26 +00004263** The number of siblings of pPage might be increased or decreased by one or
4264** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00004265** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00004266** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00004267** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00004268** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00004269**
drh8b2f49b2001-06-08 00:21:52 +00004270** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00004271** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00004272** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00004273** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00004274**
drh8c42ca92001-06-22 19:15:00 +00004275** In the course of balancing the siblings of pPage, the parent of pPage
4276** might become overfull or underfull. If that happens, then this routine
4277** is called recursively on the parent.
4278**
drh5e00f6c2001-09-13 13:46:56 +00004279** If this routine fails for any reason, it might leave the database
4280** in a corrupted state. So if this routine fails, the database should
4281** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00004282*/
drh43605152004-05-29 21:46:49 +00004283static int balance_nonroot(MemPage *pPage){
drh8b2f49b2001-06-08 00:21:52 +00004284 MemPage *pParent; /* The parent of pPage */
drh16a9b832007-05-05 18:39:25 +00004285 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00004286 int nCell = 0; /* Number of cells in apCell[] */
4287 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
drh8b2f49b2001-06-08 00:21:52 +00004288 int nOld; /* Number of pages in apOld[] */
4289 int nNew; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00004290 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00004291 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00004292 int idx; /* Index of pPage in pParent->aCell[] */
4293 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00004294 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00004295 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00004296 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00004297 int usableSpace; /* Bytes in pPage beyond the header */
4298 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00004299 int subtotal; /* Subtotal of bytes in cells on one page */
drhb6f41482004-05-14 01:58:11 +00004300 int iSpace = 0; /* First unused byte of aSpace[] */
drhc3b70572003-01-04 19:44:07 +00004301 MemPage *apOld[NB]; /* pPage and up to two siblings */
4302 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00004303 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00004304 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
4305 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drh4b70f112004-05-02 21:12:19 +00004306 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00004307 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
4308 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00004309 u8 **apCell = 0; /* All cells begin balanced */
drh2e38c322004-09-03 18:38:44 +00004310 int *szCell; /* Local size of all cells in apCell[] */
4311 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
4312 u8 *aSpace; /* Space to hold copies of dividers cells */
danielk19774e17d142005-01-16 09:06:33 +00004313#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00004314 u8 *aFrom = 0;
4315#endif
drh8b2f49b2001-06-08 00:21:52 +00004316
drh14acc042001-06-10 19:56:58 +00004317 /*
drh43605152004-05-29 21:46:49 +00004318 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00004319 */
drh3a4c1412004-05-09 20:40:11 +00004320 assert( pPage->isInit );
danielk19773b8a05f2007-03-19 17:44:26 +00004321 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh4b70f112004-05-02 21:12:19 +00004322 pBt = pPage->pBt;
drh14acc042001-06-10 19:56:58 +00004323 pParent = pPage->pParent;
drh43605152004-05-29 21:46:49 +00004324 assert( pParent );
danielk19773b8a05f2007-03-19 17:44:26 +00004325 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
danielk197707cb5602006-01-20 10:55:05 +00004326 return rc;
4327 }
drh43605152004-05-29 21:46:49 +00004328 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00004329
drh615ae552005-01-16 23:21:00 +00004330#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00004331 /*
4332 ** A special case: If a new entry has just been inserted into a
4333 ** table (that is, a btree with integer keys and all data at the leaves)
drh09d0deb2005-08-02 17:13:09 +00004334 ** and the new entry is the right-most entry in the tree (it has the
drhf222e712005-01-14 22:55:49 +00004335 ** largest key) then use the special balance_quick() routine for
4336 ** balancing. balance_quick() is much faster and results in a tighter
4337 ** packing of data in the common case.
4338 */
danielk1977ac245ec2005-01-14 13:50:11 +00004339 if( pPage->leaf &&
4340 pPage->intKey &&
4341 pPage->leafData &&
4342 pPage->nOverflow==1 &&
4343 pPage->aOvfl[0].idx==pPage->nCell &&
danielk1977ac11ee62005-01-15 12:45:51 +00004344 pPage->pParent->pgno!=1 &&
danielk1977ac245ec2005-01-14 13:50:11 +00004345 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
4346 ){
danielk1977ac11ee62005-01-15 12:45:51 +00004347 /*
4348 ** TODO: Check the siblings to the left of pPage. It may be that
4349 ** they are not full and no new page is required.
4350 */
danielk1977ac245ec2005-01-14 13:50:11 +00004351 return balance_quick(pPage, pParent);
4352 }
4353#endif
4354
drh2e38c322004-09-03 18:38:44 +00004355 /*
drh4b70f112004-05-02 21:12:19 +00004356 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00004357 ** to pPage. The "idx" variable is the index of that cell. If pPage
4358 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00004359 */
drhbb49aba2003-01-04 18:53:27 +00004360 if( pParent->idxShift ){
drha34b6762004-05-07 13:30:42 +00004361 Pgno pgno;
drh4b70f112004-05-02 21:12:19 +00004362 pgno = pPage->pgno;
danielk19773b8a05f2007-03-19 17:44:26 +00004363 assert( pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbb49aba2003-01-04 18:53:27 +00004364 for(idx=0; idx<pParent->nCell; idx++){
danielk19771cc5ed82007-05-16 17:28:43 +00004365 if( get4byte(findCell(pParent, idx))==pgno ){
drhbb49aba2003-01-04 18:53:27 +00004366 break;
4367 }
drh8b2f49b2001-06-08 00:21:52 +00004368 }
drh4b70f112004-05-02 21:12:19 +00004369 assert( idx<pParent->nCell
drh43605152004-05-29 21:46:49 +00004370 || get4byte(&pParent->aData[pParent->hdrOffset+8])==pgno );
drhbb49aba2003-01-04 18:53:27 +00004371 }else{
4372 idx = pPage->idxParent;
drh8b2f49b2001-06-08 00:21:52 +00004373 }
drh8b2f49b2001-06-08 00:21:52 +00004374
4375 /*
drh14acc042001-06-10 19:56:58 +00004376 ** Initialize variables so that it will be safe to jump
drh5edc3122001-09-13 21:53:09 +00004377 ** directly to balance_cleanup at any moment.
drh8b2f49b2001-06-08 00:21:52 +00004378 */
drh14acc042001-06-10 19:56:58 +00004379 nOld = nNew = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00004380 sqlite3PagerRef(pParent->pDbPage);
drh14acc042001-06-10 19:56:58 +00004381
4382 /*
drh4b70f112004-05-02 21:12:19 +00004383 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00004384 ** the siblings. An attempt is made to find NN siblings on either
4385 ** side of pPage. More siblings are taken from one side, however, if
4386 ** pPage there are fewer than NN siblings on the other side. If pParent
4387 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00004388 */
drhc3b70572003-01-04 19:44:07 +00004389 nxDiv = idx - NN;
4390 if( nxDiv + NB > pParent->nCell ){
4391 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00004392 }
drhc3b70572003-01-04 19:44:07 +00004393 if( nxDiv<0 ){
4394 nxDiv = 0;
4395 }
drh8b2f49b2001-06-08 00:21:52 +00004396 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00004397 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00004398 if( k<pParent->nCell ){
danielk19771cc5ed82007-05-16 17:28:43 +00004399 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00004400 nDiv++;
drha34b6762004-05-07 13:30:42 +00004401 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00004402 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00004403 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00004404 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00004405 }else{
4406 break;
drh8b2f49b2001-06-08 00:21:52 +00004407 }
drhde647132004-05-07 17:57:49 +00004408 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i], pParent);
drh6019e162001-07-02 17:51:45 +00004409 if( rc ) goto balance_cleanup;
drh428ae8c2003-01-04 16:48:09 +00004410 apOld[i]->idxParent = k;
drh91025292004-05-03 19:49:32 +00004411 apCopy[i] = 0;
4412 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00004413 nOld++;
danielk1977634f2982005-03-28 08:44:07 +00004414 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
drh8b2f49b2001-06-08 00:21:52 +00004415 }
4416
drh8d97f1f2005-05-05 18:14:13 +00004417 /* Make nMaxCells a multiple of 2 in order to preserve 8-byte
4418 ** alignment */
4419 nMaxCells = (nMaxCells + 1)&~1;
4420
drh8b2f49b2001-06-08 00:21:52 +00004421 /*
danielk1977634f2982005-03-28 08:44:07 +00004422 ** Allocate space for memory structures
4423 */
4424 apCell = sqliteMallocRaw(
4425 nMaxCells*sizeof(u8*) /* apCell */
4426 + nMaxCells*sizeof(int) /* szCell */
drhc96d8532005-05-03 12:30:33 +00004427 + ROUND8(sizeof(MemPage))*NB /* aCopy */
drh07d183d2005-05-01 22:52:42 +00004428 + pBt->pageSize*(5+NB) /* aSpace */
drhc96d8532005-05-03 12:30:33 +00004429 + (ISAUTOVACUUM ? nMaxCells : 0) /* aFrom */
danielk1977634f2982005-03-28 08:44:07 +00004430 );
4431 if( apCell==0 ){
4432 rc = SQLITE_NOMEM;
4433 goto balance_cleanup;
4434 }
4435 szCell = (int*)&apCell[nMaxCells];
4436 aCopy[0] = (u8*)&szCell[nMaxCells];
drhc96d8532005-05-03 12:30:33 +00004437 assert( ((aCopy[0] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004438 for(i=1; i<NB; i++){
drhc96d8532005-05-03 12:30:33 +00004439 aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
4440 assert( ((aCopy[i] - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004441 }
drhc96d8532005-05-03 12:30:33 +00004442 aSpace = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
4443 assert( ((aSpace - (u8*)apCell) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00004444#ifndef SQLITE_OMIT_AUTOVACUUM
4445 if( pBt->autoVacuum ){
drh07d183d2005-05-01 22:52:42 +00004446 aFrom = &aSpace[5*pBt->pageSize];
danielk1977634f2982005-03-28 08:44:07 +00004447 }
4448#endif
4449
4450 /*
drh14acc042001-06-10 19:56:58 +00004451 ** Make copies of the content of pPage and its siblings into aOld[].
4452 ** The rest of this function will use data from the copies rather
4453 ** that the original pages since the original pages will be in the
4454 ** process of being overwritten.
4455 */
4456 for(i=0; i<nOld; i++){
drh07d183d2005-05-01 22:52:42 +00004457 MemPage *p = apCopy[i] = (MemPage*)&aCopy[i][pBt->pageSize];
drh07d183d2005-05-01 22:52:42 +00004458 p->aData = &((u8*)p)[-pBt->pageSize];
4459 memcpy(p->aData, apOld[i]->aData, pBt->pageSize + sizeof(MemPage));
4460 /* The memcpy() above changes the value of p->aData so we have to
4461 ** set it again. */
drh07d183d2005-05-01 22:52:42 +00004462 p->aData = &((u8*)p)[-pBt->pageSize];
drh14acc042001-06-10 19:56:58 +00004463 }
4464
4465 /*
4466 ** Load pointers to all cells on sibling pages and the divider cells
4467 ** into the local apCell[] array. Make copies of the divider cells
drhb6f41482004-05-14 01:58:11 +00004468 ** into space obtained form aSpace[] and remove the the divider Cells
4469 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00004470 **
4471 ** If the siblings are on leaf pages, then the child pointers of the
4472 ** divider cells are stripped from the cells before they are copied
drh96f5b762004-05-16 16:24:36 +00004473 ** into aSpace[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00004474 ** child pointers. If siblings are not leaves, then all cell in
4475 ** apCell[] include child pointers. Either way, all cells in apCell[]
4476 ** are alike.
drh96f5b762004-05-16 16:24:36 +00004477 **
4478 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
4479 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00004480 */
4481 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00004482 leafCorrection = pPage->leaf*4;
drh8b18dd42004-05-12 19:18:15 +00004483 leafData = pPage->leafData && pPage->leaf;
drh8b2f49b2001-06-08 00:21:52 +00004484 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00004485 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00004486 int limit = pOld->nCell+pOld->nOverflow;
4487 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00004488 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00004489 apCell[nCell] = findOverflowCell(pOld, j);
4490 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk1977ac11ee62005-01-15 12:45:51 +00004491#ifndef SQLITE_OMIT_AUTOVACUUM
4492 if( pBt->autoVacuum ){
4493 int a;
4494 aFrom[nCell] = i;
4495 for(a=0; a<pOld->nOverflow; a++){
4496 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
4497 aFrom[nCell] = 0xFF;
4498 break;
4499 }
4500 }
4501 }
4502#endif
drh14acc042001-06-10 19:56:58 +00004503 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00004504 }
4505 if( i<nOld-1 ){
drh43605152004-05-29 21:46:49 +00004506 int sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00004507 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00004508 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
4509 ** are duplicates of keys on the child pages. We need to remove
4510 ** the divider cells from pParent, but the dividers cells are not
4511 ** added to apCell[] because they are duplicates of child cells.
4512 */
drh8b18dd42004-05-12 19:18:15 +00004513 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00004514 }else{
drhb6f41482004-05-14 01:58:11 +00004515 u8 *pTemp;
danielk1977634f2982005-03-28 08:44:07 +00004516 assert( nCell<nMaxCells );
drhb6f41482004-05-14 01:58:11 +00004517 szCell[nCell] = sz;
4518 pTemp = &aSpace[iSpace];
4519 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004520 assert( iSpace<=pBt->pageSize*5 );
drhb6f41482004-05-14 01:58:11 +00004521 memcpy(pTemp, apDiv[i], sz);
4522 apCell[nCell] = pTemp+leafCorrection;
danielk1977ac11ee62005-01-15 12:45:51 +00004523#ifndef SQLITE_OMIT_AUTOVACUUM
4524 if( pBt->autoVacuum ){
4525 aFrom[nCell] = 0xFF;
4526 }
4527#endif
drhb6f41482004-05-14 01:58:11 +00004528 dropCell(pParent, nxDiv, sz);
drh8b18dd42004-05-12 19:18:15 +00004529 szCell[nCell] -= leafCorrection;
drh43605152004-05-29 21:46:49 +00004530 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00004531 if( !pOld->leaf ){
4532 assert( leafCorrection==0 );
4533 /* The right pointer of the child page pOld becomes the left
4534 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00004535 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00004536 }else{
4537 assert( leafCorrection==4 );
danielk197739c96042007-05-12 10:41:47 +00004538 if( szCell[nCell]<4 ){
4539 /* Do not allow any cells smaller than 4 bytes. */
4540 szCell[nCell] = 4;
4541 }
drh8b18dd42004-05-12 19:18:15 +00004542 }
4543 nCell++;
drh4b70f112004-05-02 21:12:19 +00004544 }
drh8b2f49b2001-06-08 00:21:52 +00004545 }
4546 }
4547
4548 /*
drh6019e162001-07-02 17:51:45 +00004549 ** Figure out the number of pages needed to hold all nCell cells.
4550 ** Store this number in "k". Also compute szNew[] which is the total
4551 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00004552 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00004553 ** cntNew[k] should equal nCell.
4554 **
drh96f5b762004-05-16 16:24:36 +00004555 ** Values computed by this block:
4556 **
4557 ** k: The total number of sibling pages
4558 ** szNew[i]: Spaced used on the i-th sibling page.
4559 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
4560 ** the right of the i-th sibling page.
4561 ** usableSpace: Number of bytes of space available on each sibling.
4562 **
drh8b2f49b2001-06-08 00:21:52 +00004563 */
drh43605152004-05-29 21:46:49 +00004564 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00004565 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00004566 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00004567 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00004568 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00004569 szNew[k] = subtotal - szCell[i];
4570 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00004571 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00004572 subtotal = 0;
4573 k++;
4574 }
4575 }
4576 szNew[k] = subtotal;
4577 cntNew[k] = nCell;
4578 k++;
drh96f5b762004-05-16 16:24:36 +00004579
4580 /*
4581 ** The packing computed by the previous block is biased toward the siblings
4582 ** on the left side. The left siblings are always nearly full, while the
4583 ** right-most sibling might be nearly empty. This block of code attempts
4584 ** to adjust the packing of siblings to get a better balance.
4585 **
4586 ** This adjustment is more than an optimization. The packing above might
4587 ** be so out of balance as to be illegal. For example, the right-most
4588 ** sibling might be completely empty. This adjustment is not optional.
4589 */
drh6019e162001-07-02 17:51:45 +00004590 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00004591 int szRight = szNew[i]; /* Size of sibling on the right */
4592 int szLeft = szNew[i-1]; /* Size of sibling on the left */
4593 int r; /* Index of right-most cell in left sibling */
4594 int d; /* Index of first cell to the left of right sibling */
4595
4596 r = cntNew[i-1] - 1;
4597 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00004598 assert( d<nMaxCells );
4599 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00004600 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
4601 szRight += szCell[d] + 2;
4602 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00004603 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00004604 r = cntNew[i-1] - 1;
4605 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00004606 }
drh96f5b762004-05-16 16:24:36 +00004607 szNew[i] = szRight;
4608 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00004609 }
drh09d0deb2005-08-02 17:13:09 +00004610
4611 /* Either we found one or more cells (cntnew[0])>0) or we are the
4612 ** a virtual root page. A virtual root page is when the real root
4613 ** page is page 1 and we are the only child of that page.
4614 */
4615 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00004616
4617 /*
drh6b308672002-07-08 02:16:37 +00004618 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00004619 */
drh4b70f112004-05-02 21:12:19 +00004620 assert( pPage->pgno>1 );
4621 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00004622 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00004623 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00004624 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00004625 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00004626 pgnoNew[i] = pgnoOld[i];
4627 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00004628 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00004629 nNew++;
danielk197728129562005-01-11 10:25:06 +00004630 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00004631 }else{
drh7aa8f852006-03-28 00:24:44 +00004632 assert( i>0 );
drh4f0c5872007-03-26 22:05:01 +00004633 rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
drh6b308672002-07-08 02:16:37 +00004634 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00004635 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00004636 nNew++;
drh6b308672002-07-08 02:16:37 +00004637 }
drhda200cc2004-05-09 11:51:38 +00004638 zeroPage(pNew, pageFlags);
drh8b2f49b2001-06-08 00:21:52 +00004639 }
4640
danielk1977299b1872004-11-22 10:02:10 +00004641 /* Free any old pages that were not reused as new pages.
4642 */
4643 while( i<nOld ){
4644 rc = freePage(apOld[i]);
4645 if( rc ) goto balance_cleanup;
4646 releasePage(apOld[i]);
4647 apOld[i] = 0;
4648 i++;
4649 }
4650
drh8b2f49b2001-06-08 00:21:52 +00004651 /*
drhf9ffac92002-03-02 19:00:31 +00004652 ** Put the new pages in accending order. This helps to
4653 ** keep entries in the disk file in order so that a scan
4654 ** of the table is a linear scan through the file. That
4655 ** in turn helps the operating system to deliver pages
4656 ** from the disk more rapidly.
4657 **
4658 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00004659 ** n is never more than NB (a small constant), that should
4660 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00004661 **
drhc3b70572003-01-04 19:44:07 +00004662 ** When NB==3, this one optimization makes the database
4663 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00004664 */
4665 for(i=0; i<k-1; i++){
4666 int minV = pgnoNew[i];
4667 int minI = i;
4668 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00004669 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00004670 minI = j;
4671 minV = pgnoNew[j];
4672 }
4673 }
4674 if( minI>i ){
4675 int t;
4676 MemPage *pT;
4677 t = pgnoNew[i];
4678 pT = apNew[i];
4679 pgnoNew[i] = pgnoNew[minI];
4680 apNew[i] = apNew[minI];
4681 pgnoNew[minI] = t;
4682 apNew[minI] = pT;
4683 }
4684 }
drha2fce642004-06-05 00:01:44 +00004685 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00004686 pgnoOld[0],
4687 nOld>=2 ? pgnoOld[1] : 0,
4688 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00004689 pgnoNew[0], szNew[0],
4690 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
4691 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00004692 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
4693 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00004694
drhf9ffac92002-03-02 19:00:31 +00004695 /*
drh14acc042001-06-10 19:56:58 +00004696 ** Evenly distribute the data in apCell[] across the new pages.
4697 ** Insert divider cells into pParent as necessary.
4698 */
4699 j = 0;
4700 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00004701 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00004702 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00004703 assert( j<nMaxCells );
drh4b70f112004-05-02 21:12:19 +00004704 assert( pNew->pgno==pgnoNew[i] );
drhfa1a98a2004-05-14 19:08:17 +00004705 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00004706 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00004707 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00004708
4709#ifndef SQLITE_OMIT_AUTOVACUUM
4710 /* If this is an auto-vacuum database, update the pointer map entries
4711 ** that point to the siblings that were rearranged. These can be: left
4712 ** children of cells, the right-child of the page, or overflow pages
4713 ** pointed to by cells.
4714 */
4715 if( pBt->autoVacuum ){
4716 for(k=j; k<cntNew[i]; k++){
danielk1977634f2982005-03-28 08:44:07 +00004717 assert( k<nMaxCells );
danielk1977ac11ee62005-01-15 12:45:51 +00004718 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
danielk197779a40da2005-01-16 08:00:01 +00004719 rc = ptrmapPutOvfl(pNew, k-j);
4720 if( rc!=SQLITE_OK ){
4721 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00004722 }
4723 }
4724 }
4725 }
4726#endif
4727
4728 j = cntNew[i];
4729
4730 /* If the sibling page assembled above was not the right-most sibling,
4731 ** insert a divider cell into the parent page.
4732 */
drh14acc042001-06-10 19:56:58 +00004733 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00004734 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00004735 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00004736 int sz;
danielk1977634f2982005-03-28 08:44:07 +00004737
4738 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00004739 pCell = apCell[j];
4740 sz = szCell[j] + leafCorrection;
drh4b70f112004-05-02 21:12:19 +00004741 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00004742 memcpy(&pNew->aData[8], pCell, 4);
drh24cd67e2004-05-10 16:18:47 +00004743 pTemp = 0;
drh8b18dd42004-05-12 19:18:15 +00004744 }else if( leafData ){
danielk1977ac11ee62005-01-15 12:45:51 +00004745 /* If the tree is a leaf-data tree, and the siblings are leaves,
4746 ** then there is no divider cell in apCell[]. Instead, the divider
4747 ** cell consists of the integer key for the right-most cell of
4748 ** the sibling-page assembled above only.
4749 */
drh6f11bef2004-05-13 01:12:56 +00004750 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00004751 j--;
drh16a9b832007-05-05 18:39:25 +00004752 sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
drhb6f41482004-05-14 01:58:11 +00004753 pCell = &aSpace[iSpace];
drhb026e052007-05-02 01:34:31 +00004754 fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
drhb6f41482004-05-14 01:58:11 +00004755 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004756 assert( iSpace<=pBt->pageSize*5 );
drh8b18dd42004-05-12 19:18:15 +00004757 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00004758 }else{
4759 pCell -= 4;
drhb6f41482004-05-14 01:58:11 +00004760 pTemp = &aSpace[iSpace];
4761 iSpace += sz;
drh07d183d2005-05-01 22:52:42 +00004762 assert( iSpace<=pBt->pageSize*5 );
danielk19774aeff622007-05-12 09:30:47 +00004763 /* Obscure case for non-leaf-data trees: If the cell at pCell was
4764 ** previously stored on a leaf node, and it's reported size was 4
4765 ** bytes, then it may actually be smaller than this
4766 ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
4767 ** any cell). But it's important to pass the correct size to
4768 ** insertCell(), so reparse the cell now.
4769 **
4770 ** Note that this can never happen in an SQLite data file, as all
4771 ** cells are at least 4 bytes. It only happens in b-trees used
4772 ** to evaluate "IN (SELECT ...)" and similar clauses.
4773 */
4774 if( szCell[j]==4 ){
4775 assert(leafCorrection==4);
4776 sz = cellSizePtr(pParent, pCell);
4777 }
drh4b70f112004-05-02 21:12:19 +00004778 }
danielk1977a3ad5e72005-01-07 08:56:44 +00004779 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
danielk1977e80463b2004-11-03 03:01:16 +00004780 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh43605152004-05-29 21:46:49 +00004781 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +00004782#ifndef SQLITE_OMIT_AUTOVACUUM
4783 /* If this is an auto-vacuum database, and not a leaf-data tree,
4784 ** then update the pointer map with an entry for the overflow page
4785 ** that the cell just inserted points to (if any).
4786 */
4787 if( pBt->autoVacuum && !leafData ){
danielk197779a40da2005-01-16 08:00:01 +00004788 rc = ptrmapPutOvfl(pParent, nxDiv);
4789 if( rc!=SQLITE_OK ){
4790 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00004791 }
4792 }
4793#endif
drh14acc042001-06-10 19:56:58 +00004794 j++;
4795 nxDiv++;
4796 }
4797 }
drh6019e162001-07-02 17:51:45 +00004798 assert( j==nCell );
drh7aa8f852006-03-28 00:24:44 +00004799 assert( nOld>0 );
4800 assert( nNew>0 );
drh4b70f112004-05-02 21:12:19 +00004801 if( (pageFlags & PTF_LEAF)==0 ){
drh43605152004-05-29 21:46:49 +00004802 memcpy(&apNew[nNew-1]->aData[8], &apCopy[nOld-1]->aData[8], 4);
drh14acc042001-06-10 19:56:58 +00004803 }
drh43605152004-05-29 21:46:49 +00004804 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00004805 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00004806 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00004807 }else{
4808 /* Right-most sibling is the left child of the first entry in pParent
4809 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00004810 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00004811 }
4812
4813 /*
4814 ** Reparent children of all cells.
drh8b2f49b2001-06-08 00:21:52 +00004815 */
4816 for(i=0; i<nNew; i++){
danielk1977afcdd022004-10-31 16:25:42 +00004817 rc = reparentChildPages(apNew[i]);
4818 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004819 }
danielk1977afcdd022004-10-31 16:25:42 +00004820 rc = reparentChildPages(pParent);
4821 if( rc!=SQLITE_OK ) goto balance_cleanup;
drh8b2f49b2001-06-08 00:21:52 +00004822
4823 /*
drh3a4c1412004-05-09 20:40:11 +00004824 ** Balance the parent page. Note that the current page (pPage) might
danielk1977ac11ee62005-01-15 12:45:51 +00004825 ** have been added to the freelist so it might no longer be initialized.
drh3a4c1412004-05-09 20:40:11 +00004826 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00004827 */
drhda200cc2004-05-09 11:51:38 +00004828 assert( pParent->isInit );
danielk1977ac245ec2005-01-14 13:50:11 +00004829 rc = balance(pParent, 0);
drhda200cc2004-05-09 11:51:38 +00004830
drh8b2f49b2001-06-08 00:21:52 +00004831 /*
drh14acc042001-06-10 19:56:58 +00004832 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00004833 */
drh14acc042001-06-10 19:56:58 +00004834balance_cleanup:
drh2e38c322004-09-03 18:38:44 +00004835 sqliteFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00004836 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00004837 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00004838 }
drh14acc042001-06-10 19:56:58 +00004839 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00004840 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00004841 }
drh91025292004-05-03 19:49:32 +00004842 releasePage(pParent);
drh3a4c1412004-05-09 20:40:11 +00004843 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
4844 pPage->pgno, nOld, nNew, nCell));
drh8b2f49b2001-06-08 00:21:52 +00004845 return rc;
4846}
4847
4848/*
drh43605152004-05-29 21:46:49 +00004849** This routine is called for the root page of a btree when the root
4850** page contains no cells. This is an opportunity to make the tree
4851** shallower by one level.
4852*/
4853static int balance_shallower(MemPage *pPage){
4854 MemPage *pChild; /* The only child page of pPage */
4855 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00004856 int rc = SQLITE_OK; /* Return code from subprocedures */
danielk1977aef0bf62005-12-30 16:28:01 +00004857 BtShared *pBt; /* The main BTree structure */
drh2e38c322004-09-03 18:38:44 +00004858 int mxCellPerPage; /* Maximum number of cells per page */
4859 u8 **apCell; /* All cells from pages being balanced */
4860 int *szCell; /* Local size of all cells */
drh43605152004-05-29 21:46:49 +00004861
4862 assert( pPage->pParent==0 );
4863 assert( pPage->nCell==0 );
drh2e38c322004-09-03 18:38:44 +00004864 pBt = pPage->pBt;
4865 mxCellPerPage = MX_CELL(pBt);
4866 apCell = sqliteMallocRaw( mxCellPerPage*(sizeof(u8*)+sizeof(int)) );
4867 if( apCell==0 ) return SQLITE_NOMEM;
4868 szCell = (int*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00004869 if( pPage->leaf ){
4870 /* The table is completely empty */
4871 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
4872 }else{
4873 /* The root page is empty but has one child. Transfer the
4874 ** information from that one child into the root page if it
4875 ** will fit. This reduces the depth of the tree by one.
4876 **
4877 ** If the root page is page 1, it has less space available than
4878 ** its child (due to the 100 byte header that occurs at the beginning
4879 ** of the database fle), so it might not be able to hold all of the
4880 ** information currently contained in the child. If this is the
4881 ** case, then do not do the transfer. Leave page 1 empty except
4882 ** for the right-pointer to the child page. The child page becomes
4883 ** the virtual root of the tree.
4884 */
4885 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
4886 assert( pgnoChild>0 );
danielk19773b8a05f2007-03-19 17:44:26 +00004887 assert( pgnoChild<=sqlite3PagerPagecount(pPage->pBt->pPager) );
drh16a9b832007-05-05 18:39:25 +00004888 rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
drh2e38c322004-09-03 18:38:44 +00004889 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004890 if( pPage->pgno==1 ){
drh16a9b832007-05-05 18:39:25 +00004891 rc = sqlite3BtreeInitPage(pChild, pPage);
drh2e38c322004-09-03 18:38:44 +00004892 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004893 assert( pChild->nOverflow==0 );
4894 if( pChild->nFree>=100 ){
4895 /* The child information will fit on the root page, so do the
4896 ** copy */
4897 int i;
4898 zeroPage(pPage, pChild->aData[0]);
4899 for(i=0; i<pChild->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00004900 apCell[i] = findCell(pChild,i);
drh43605152004-05-29 21:46:49 +00004901 szCell[i] = cellSizePtr(pChild, apCell[i]);
4902 }
4903 assemblePage(pPage, pChild->nCell, apCell, szCell);
danielk1977ae825582004-11-23 09:06:55 +00004904 /* Copy the right-pointer of the child to the parent. */
4905 put4byte(&pPage->aData[pPage->hdrOffset+8],
4906 get4byte(&pChild->aData[pChild->hdrOffset+8]));
drh43605152004-05-29 21:46:49 +00004907 freePage(pChild);
4908 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
4909 }else{
4910 /* The child has more information that will fit on the root.
4911 ** The tree is already balanced. Do nothing. */
4912 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
4913 }
4914 }else{
4915 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
4916 pPage->isInit = 0;
4917 pPage->pParent = 0;
drh16a9b832007-05-05 18:39:25 +00004918 rc = sqlite3BtreeInitPage(pPage, 0);
drh43605152004-05-29 21:46:49 +00004919 assert( rc==SQLITE_OK );
4920 freePage(pChild);
4921 TRACE(("BALANCE: transfer child %d into root %d\n",
4922 pChild->pgno, pPage->pgno));
4923 }
danielk1977afcdd022004-10-31 16:25:42 +00004924 rc = reparentChildPages(pPage);
danielk1977ac11ee62005-01-15 12:45:51 +00004925 assert( pPage->nOverflow==0 );
4926#ifndef SQLITE_OMIT_AUTOVACUUM
4927 if( pBt->autoVacuum ){
danielk1977aac0a382005-01-16 11:07:06 +00004928 int i;
danielk1977ac11ee62005-01-15 12:45:51 +00004929 for(i=0; i<pPage->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00004930 rc = ptrmapPutOvfl(pPage, i);
4931 if( rc!=SQLITE_OK ){
4932 goto end_shallow_balance;
danielk1977ac11ee62005-01-15 12:45:51 +00004933 }
4934 }
4935 }
4936#endif
danielk1977afcdd022004-10-31 16:25:42 +00004937 if( rc!=SQLITE_OK ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00004938 releasePage(pChild);
4939 }
drh2e38c322004-09-03 18:38:44 +00004940end_shallow_balance:
4941 sqliteFree(apCell);
4942 return rc;
drh43605152004-05-29 21:46:49 +00004943}
4944
4945
4946/*
4947** The root page is overfull
4948**
4949** When this happens, Create a new child page and copy the
4950** contents of the root into the child. Then make the root
4951** page an empty page with rightChild pointing to the new
4952** child. Finally, call balance_internal() on the new child
4953** to cause it to split.
4954*/
4955static int balance_deeper(MemPage *pPage){
4956 int rc; /* Return value from subprocedures */
4957 MemPage *pChild; /* Pointer to a new child page */
4958 Pgno pgnoChild; /* Page number of the new child page */
danielk1977aef0bf62005-12-30 16:28:01 +00004959 BtShared *pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00004960 int usableSize; /* Total usable size of a page */
4961 u8 *data; /* Content of the parent page */
4962 u8 *cdata; /* Content of the child page */
4963 int hdr; /* Offset to page header in parent */
4964 int brk; /* Offset to content of first cell in parent */
4965
4966 assert( pPage->pParent==0 );
4967 assert( pPage->nOverflow>0 );
4968 pBt = pPage->pBt;
drh4f0c5872007-03-26 22:05:01 +00004969 rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
drh43605152004-05-29 21:46:49 +00004970 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00004971 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
drh43605152004-05-29 21:46:49 +00004972 usableSize = pBt->usableSize;
4973 data = pPage->aData;
4974 hdr = pPage->hdrOffset;
4975 brk = get2byte(&data[hdr+5]);
4976 cdata = pChild->aData;
4977 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
4978 memcpy(&cdata[brk], &data[brk], usableSize-brk);
danielk1977c7dc7532004-11-17 10:22:03 +00004979 assert( pChild->isInit==0 );
drh16a9b832007-05-05 18:39:25 +00004980 rc = sqlite3BtreeInitPage(pChild, pPage);
danielk19776b456a22005-03-21 04:04:02 +00004981 if( rc ) goto balancedeeper_out;
drh43605152004-05-29 21:46:49 +00004982 memcpy(pChild->aOvfl, pPage->aOvfl, pPage->nOverflow*sizeof(pPage->aOvfl[0]));
4983 pChild->nOverflow = pPage->nOverflow;
4984 if( pChild->nOverflow ){
4985 pChild->nFree = 0;
4986 }
4987 assert( pChild->nCell==pPage->nCell );
4988 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
4989 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
4990 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
danielk19774e17d142005-01-16 09:06:33 +00004991#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977ac11ee62005-01-15 12:45:51 +00004992 if( pBt->autoVacuum ){
4993 int i;
4994 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
danielk19776b456a22005-03-21 04:04:02 +00004995 if( rc ) goto balancedeeper_out;
danielk1977ac11ee62005-01-15 12:45:51 +00004996 for(i=0; i<pChild->nCell; i++){
danielk197779a40da2005-01-16 08:00:01 +00004997 rc = ptrmapPutOvfl(pChild, i);
4998 if( rc!=SQLITE_OK ){
4999 return rc;
danielk1977ac11ee62005-01-15 12:45:51 +00005000 }
5001 }
5002 }
danielk19774e17d142005-01-16 09:06:33 +00005003#endif
drh43605152004-05-29 21:46:49 +00005004 rc = balance_nonroot(pChild);
danielk19776b456a22005-03-21 04:04:02 +00005005
5006balancedeeper_out:
drh43605152004-05-29 21:46:49 +00005007 releasePage(pChild);
5008 return rc;
5009}
5010
5011/*
5012** Decide if the page pPage needs to be balanced. If balancing is
5013** required, call the appropriate balancing routine.
5014*/
danielk1977ac245ec2005-01-14 13:50:11 +00005015static int balance(MemPage *pPage, int insert){
drh43605152004-05-29 21:46:49 +00005016 int rc = SQLITE_OK;
5017 if( pPage->pParent==0 ){
5018 if( pPage->nOverflow>0 ){
5019 rc = balance_deeper(pPage);
5020 }
danielk1977687566d2004-11-02 12:56:41 +00005021 if( rc==SQLITE_OK && pPage->nCell==0 ){
drh43605152004-05-29 21:46:49 +00005022 rc = balance_shallower(pPage);
5023 }
5024 }else{
danielk1977ac245ec2005-01-14 13:50:11 +00005025 if( pPage->nOverflow>0 ||
5026 (!insert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
drh43605152004-05-29 21:46:49 +00005027 rc = balance_nonroot(pPage);
5028 }
5029 }
5030 return rc;
5031}
5032
5033/*
drh8dcd7ca2004-08-08 19:43:29 +00005034** This routine checks all cursors that point to table pgnoRoot.
drh980b1a72006-08-16 16:42:48 +00005035** If any of those cursors were opened with wrFlag==0 in a different
5036** database connection (a database connection that shares the pager
5037** cache with the current connection) and that other connection
5038** is not in the ReadUncommmitted state, then this routine returns
5039** SQLITE_LOCKED.
danielk1977299b1872004-11-22 10:02:10 +00005040**
5041** In addition to checking for read-locks (where a read-lock
5042** means a cursor opened with wrFlag==0) this routine also moves
drh16a9b832007-05-05 18:39:25 +00005043** all write cursors so that they are pointing to the
drh980b1a72006-08-16 16:42:48 +00005044** first Cell on the root page. This is necessary because an insert
danielk1977299b1872004-11-22 10:02:10 +00005045** or delete might change the number of cells on a page or delete
5046** a page entirely and we do not want to leave any cursors
5047** pointing to non-existant pages or cells.
drhf74b8d92002-09-01 23:20:45 +00005048*/
drh980b1a72006-08-16 16:42:48 +00005049static int checkReadLocks(Btree *pBtree, Pgno pgnoRoot, BtCursor *pExclude){
danielk1977299b1872004-11-22 10:02:10 +00005050 BtCursor *p;
drh980b1a72006-08-16 16:42:48 +00005051 BtShared *pBt = pBtree->pBt;
5052 sqlite3 *db = pBtree->pSqlite;
danielk1977299b1872004-11-22 10:02:10 +00005053 for(p=pBt->pCursor; p; p=p->pNext){
drh980b1a72006-08-16 16:42:48 +00005054 if( p==pExclude ) continue;
5055 if( p->eState!=CURSOR_VALID ) continue;
5056 if( p->pgnoRoot!=pgnoRoot ) continue;
5057 if( p->wrFlag==0 ){
5058 sqlite3 *dbOther = p->pBtree->pSqlite;
5059 if( dbOther==0 ||
5060 (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){
5061 return SQLITE_LOCKED;
5062 }
5063 }else if( p->pPage->pgno!=p->pgnoRoot ){
danielk1977299b1872004-11-22 10:02:10 +00005064 moveToRoot(p);
5065 }
5066 }
drhf74b8d92002-09-01 23:20:45 +00005067 return SQLITE_OK;
5068}
5069
5070/*
drh3b7511c2001-05-26 13:15:44 +00005071** Insert a new record into the BTree. The key is given by (pKey,nKey)
5072** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00005073** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00005074** is left pointing at a random location.
5075**
5076** For an INTKEY table, only the nKey value of the key is used. pKey is
5077** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00005078*/
drh3aac2dd2004-04-26 14:10:20 +00005079int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00005080 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00005081 const void *pKey, i64 nKey, /* The key of the new record */
drhe4d90812007-03-29 05:51:49 +00005082 const void *pData, int nData, /* The data of the new record */
drhb026e052007-05-02 01:34:31 +00005083 int nZero, /* Number of extra 0 bytes to append to data */
drhe4d90812007-03-29 05:51:49 +00005084 int appendBias /* True if this is likely an append */
drh3b7511c2001-05-26 13:15:44 +00005085){
drh3b7511c2001-05-26 13:15:44 +00005086 int rc;
5087 int loc;
drh14acc042001-06-10 19:56:58 +00005088 int szNew;
drh3b7511c2001-05-26 13:15:44 +00005089 MemPage *pPage;
danielk1977aef0bf62005-12-30 16:28:01 +00005090 BtShared *pBt = pCur->pBtree->pBt;
drha34b6762004-05-07 13:30:42 +00005091 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00005092 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00005093
danielk1977aef0bf62005-12-30 16:28:01 +00005094 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005095 /* Must start a transaction before doing an insert */
5096 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005097 }
drhf74b8d92002-09-01 23:20:45 +00005098 assert( !pBt->readOnly );
drhecdc7532001-09-23 02:35:53 +00005099 if( !pCur->wrFlag ){
5100 return SQLITE_PERM; /* Cursor not open for writing */
5101 }
drh980b1a72006-08-16 16:42:48 +00005102 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00005103 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5104 }
danielk1977da184232006-01-05 11:34:32 +00005105
5106 /* Save the positions of any other cursors open on this table */
drhbf700f32007-03-31 02:36:44 +00005107 clearCursorPosition(pCur);
danielk19772e94d4d2006-01-09 05:36:27 +00005108 if(
danielk19772e94d4d2006-01-09 05:36:27 +00005109 SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
drhe4d90812007-03-29 05:51:49 +00005110 SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
danielk19772e94d4d2006-01-09 05:36:27 +00005111 ){
danielk1977da184232006-01-05 11:34:32 +00005112 return rc;
5113 }
5114
drh14acc042001-06-10 19:56:58 +00005115 pPage = pCur->pPage;
drh4a1c3802004-05-12 15:15:47 +00005116 assert( pPage->intKey || nKey>=0 );
drh8b18dd42004-05-12 19:18:15 +00005117 assert( pPage->leaf || !pPage->leafData );
drh3a4c1412004-05-09 20:40:11 +00005118 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
5119 pCur->pgnoRoot, nKey, nData, pPage->pgno,
5120 loc==0 ? "overwrite" : "new entry"));
drh7aa128d2002-06-21 13:09:16 +00005121 assert( pPage->isInit );
danielk19773b8a05f2007-03-19 17:44:26 +00005122 rc = sqlite3PagerWrite(pPage->pDbPage);
drhbd03cae2001-06-02 02:40:57 +00005123 if( rc ) return rc;
drh2e38c322004-09-03 18:38:44 +00005124 newCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
5125 if( newCell==0 ) return SQLITE_NOMEM;
drhb026e052007-05-02 01:34:31 +00005126 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
drh2e38c322004-09-03 18:38:44 +00005127 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00005128 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00005129 assert( szNew<=MX_CELL_SIZE(pBt) );
danielk1977da184232006-01-05 11:34:32 +00005130 if( loc==0 && CURSOR_VALID==pCur->eState ){
drha34b6762004-05-07 13:30:42 +00005131 int szOld;
5132 assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
danielk19771cc5ed82007-05-16 17:28:43 +00005133 oldCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00005134 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005135 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00005136 }
drh43605152004-05-29 21:46:49 +00005137 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00005138 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00005139 if( rc ) goto end_insert;
drh4b70f112004-05-02 21:12:19 +00005140 dropCell(pPage, pCur->idx, szOld);
drh7c717f72001-06-24 20:39:41 +00005141 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00005142 assert( pPage->leaf );
drh14acc042001-06-10 19:56:58 +00005143 pCur->idx++;
drh271efa52004-05-30 19:19:05 +00005144 pCur->info.nSize = 0;
drh14acc042001-06-10 19:56:58 +00005145 }else{
drh4b70f112004-05-02 21:12:19 +00005146 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00005147 }
danielk1977a3ad5e72005-01-07 08:56:44 +00005148 rc = insertCell(pPage, pCur->idx, newCell, szNew, 0, 0);
danielk1977e80463b2004-11-03 03:01:16 +00005149 if( rc!=SQLITE_OK ) goto end_insert;
danielk1977ac245ec2005-01-14 13:50:11 +00005150 rc = balance(pPage, 1);
drh23e11ca2004-05-04 17:27:28 +00005151 /* sqlite3BtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
drh3fc190c2001-09-14 03:24:23 +00005152 /* fflush(stdout); */
danielk1977299b1872004-11-22 10:02:10 +00005153 if( rc==SQLITE_OK ){
5154 moveToRoot(pCur);
5155 }
drh2e38c322004-09-03 18:38:44 +00005156end_insert:
5157 sqliteFree(newCell);
drh5e2f8b92001-05-28 00:41:15 +00005158 return rc;
5159}
5160
5161/*
drh4b70f112004-05-02 21:12:19 +00005162** Delete the entry that the cursor is pointing to. The cursor
5163** is left pointing at a random location.
drh3b7511c2001-05-26 13:15:44 +00005164*/
drh3aac2dd2004-04-26 14:10:20 +00005165int sqlite3BtreeDelete(BtCursor *pCur){
drh5e2f8b92001-05-28 00:41:15 +00005166 MemPage *pPage = pCur->pPage;
drh4b70f112004-05-02 21:12:19 +00005167 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00005168 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00005169 Pgno pgnoChild = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00005170 BtShared *pBt = pCur->pBtree->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005171
drh7aa128d2002-06-21 13:09:16 +00005172 assert( pPage->isInit );
danielk1977aef0bf62005-12-30 16:28:01 +00005173 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005174 /* Must start a transaction before doing a delete */
5175 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005176 }
drhf74b8d92002-09-01 23:20:45 +00005177 assert( !pBt->readOnly );
drhbd03cae2001-06-02 02:40:57 +00005178 if( pCur->idx >= pPage->nCell ){
5179 return SQLITE_ERROR; /* The cursor is not pointing to anything */
5180 }
drhecdc7532001-09-23 02:35:53 +00005181 if( !pCur->wrFlag ){
5182 return SQLITE_PERM; /* Did not open this cursor for writing */
5183 }
drh980b1a72006-08-16 16:42:48 +00005184 if( checkReadLocks(pCur->pBtree, pCur->pgnoRoot, pCur) ){
drhf74b8d92002-09-01 23:20:45 +00005185 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
5186 }
danielk1977da184232006-01-05 11:34:32 +00005187
5188 /* Restore the current cursor position (a no-op if the cursor is not in
5189 ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors
danielk19773b8a05f2007-03-19 17:44:26 +00005190 ** open on the same table. Then call sqlite3PagerWrite() on the page
danielk1977da184232006-01-05 11:34:32 +00005191 ** that the entry will be deleted from.
5192 */
5193 if(
drhbf700f32007-03-31 02:36:44 +00005194 (rc = restoreOrClearCursorPosition(pCur))!=0 ||
drhd1167392006-01-23 13:00:35 +00005195 (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
danielk19773b8a05f2007-03-19 17:44:26 +00005196 (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
danielk1977da184232006-01-05 11:34:32 +00005197 ){
5198 return rc;
5199 }
danielk1977e6efa742004-11-10 11:55:10 +00005200
5201 /* Locate the cell within it's page and leave pCell pointing to the
5202 ** data. The clearCell() call frees any overflow pages associated with the
5203 ** cell. The cell itself is still intact.
5204 */
danielk19771cc5ed82007-05-16 17:28:43 +00005205 pCell = findCell(pPage, pCur->idx);
drh4b70f112004-05-02 21:12:19 +00005206 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005207 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00005208 }
danielk197728129562005-01-11 10:25:06 +00005209 rc = clearCell(pPage, pCell);
5210 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00005211
drh4b70f112004-05-02 21:12:19 +00005212 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00005213 /*
drh5e00f6c2001-09-13 13:46:56 +00005214 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00005215 ** do something we will leave a hole on an internal page.
5216 ** We have to fill the hole by moving in a cell from a leaf. The
5217 ** next Cell after the one to be deleted is guaranteed to exist and
danielk1977299b1872004-11-22 10:02:10 +00005218 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00005219 */
drh14acc042001-06-10 19:56:58 +00005220 BtCursor leafCur;
drh4b70f112004-05-02 21:12:19 +00005221 unsigned char *pNext;
drh02afc862006-01-20 18:10:57 +00005222 int szNext; /* The compiler warning is wrong: szNext is always
5223 ** initialized before use. Adding an extra initialization
5224 ** to silence the compiler slows down the code. */
danielk1977299b1872004-11-22 10:02:10 +00005225 int notUsed;
danielk19776b456a22005-03-21 04:04:02 +00005226 unsigned char *tempCell = 0;
drh8b18dd42004-05-12 19:18:15 +00005227 assert( !pPage->leafData );
drh16a9b832007-05-05 18:39:25 +00005228 sqlite3BtreeGetTempCursor(pCur, &leafCur);
danielk1977299b1872004-11-22 10:02:10 +00005229 rc = sqlite3BtreeNext(&leafCur, &notUsed);
danielk19776b456a22005-03-21 04:04:02 +00005230 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00005231 rc = sqlite3PagerWrite(leafCur.pPage->pDbPage);
danielk19776b456a22005-03-21 04:04:02 +00005232 }
5233 if( rc==SQLITE_OK ){
5234 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
5235 pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno));
5236 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
danielk19771cc5ed82007-05-16 17:28:43 +00005237 pNext = findCell(leafCur.pPage, leafCur.idx);
danielk19776b456a22005-03-21 04:04:02 +00005238 szNext = cellSizePtr(leafCur.pPage, pNext);
5239 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
5240 tempCell = sqliteMallocRaw( MX_CELL_SIZE(pBt) );
5241 if( tempCell==0 ){
5242 rc = SQLITE_NOMEM;
5243 }
5244 }
5245 if( rc==SQLITE_OK ){
5246 rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0);
5247 }
5248 if( rc==SQLITE_OK ){
5249 put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild);
5250 rc = balance(pPage, 0);
5251 }
5252 if( rc==SQLITE_OK ){
5253 dropCell(leafCur.pPage, leafCur.idx, szNext);
5254 rc = balance(leafCur.pPage, 0);
5255 }
drh2e38c322004-09-03 18:38:44 +00005256 sqliteFree(tempCell);
drh16a9b832007-05-05 18:39:25 +00005257 sqlite3BtreeReleaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00005258 }else{
danielk1977299b1872004-11-22 10:02:10 +00005259 TRACE(("DELETE: table=%d delete from leaf %d\n",
5260 pCur->pgnoRoot, pPage->pgno));
5261 dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell));
danielk1977ac245ec2005-01-14 13:50:11 +00005262 rc = balance(pPage, 0);
drh5e2f8b92001-05-28 00:41:15 +00005263 }
danielk19776b456a22005-03-21 04:04:02 +00005264 if( rc==SQLITE_OK ){
5265 moveToRoot(pCur);
5266 }
drh5e2f8b92001-05-28 00:41:15 +00005267 return rc;
drh3b7511c2001-05-26 13:15:44 +00005268}
drh8b2f49b2001-06-08 00:21:52 +00005269
5270/*
drhc6b52df2002-01-04 03:09:29 +00005271** Create a new BTree table. Write into *piTable the page
5272** number for the root page of the new table.
5273**
drhab01f612004-05-22 02:55:23 +00005274** The type of type is determined by the flags parameter. Only the
5275** following values of flags are currently in use. Other values for
5276** flags might not work:
5277**
5278** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
5279** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00005280*/
danielk1977aef0bf62005-12-30 16:28:01 +00005281int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
5282 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005283 MemPage *pRoot;
5284 Pgno pgnoRoot;
5285 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00005286 if( pBt->inTransaction!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005287 /* Must start a transaction first */
5288 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005289 }
danielk197728129562005-01-11 10:25:06 +00005290 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00005291
danielk1977003ba062004-11-04 02:57:33 +00005292#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00005293 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drh8b2f49b2001-06-08 00:21:52 +00005294 if( rc ) return rc;
danielk1977003ba062004-11-04 02:57:33 +00005295#else
danielk1977687566d2004-11-02 12:56:41 +00005296 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00005297 Pgno pgnoMove; /* Move a page here to make room for the root-page */
5298 MemPage *pPageMove; /* The page to move to. */
5299
danielk197720713f32007-05-03 11:43:33 +00005300 /* Creating a new table may probably require moving an existing database
5301 ** to make room for the new tables root page. In case this page turns
5302 ** out to be an overflow page, delete all overflow page-map caches
5303 ** held by open cursors.
5304 */
danielk197792d4d7a2007-05-04 12:05:56 +00005305 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00005306
danielk1977003ba062004-11-04 02:57:33 +00005307 /* Read the value of meta[3] from the database to determine where the
5308 ** root page of the new table should go. meta[3] is the largest root-page
5309 ** created so far, so the new root-page is (meta[3]+1).
5310 */
danielk1977aef0bf62005-12-30 16:28:01 +00005311 rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00005312 if( rc!=SQLITE_OK ) return rc;
5313 pgnoRoot++;
5314
danielk1977599fcba2004-11-08 07:13:13 +00005315 /* The new root-page may not be allocated on a pointer-map page, or the
5316 ** PENDING_BYTE page.
5317 */
danielk1977266664d2006-02-10 08:24:21 +00005318 if( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00005319 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00005320 pgnoRoot++;
5321 }
5322 assert( pgnoRoot>=3 );
5323
5324 /* Allocate a page. The page that currently resides at pgnoRoot will
5325 ** be moved to the allocated page (unless the allocated page happens
5326 ** to reside at pgnoRoot).
5327 */
drh4f0c5872007-03-26 22:05:01 +00005328 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00005329 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00005330 return rc;
5331 }
danielk1977003ba062004-11-04 02:57:33 +00005332
5333 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00005334 /* pgnoRoot is the page that will be used for the root-page of
5335 ** the new table (assuming an error did not occur). But we were
5336 ** allocated pgnoMove. If required (i.e. if it was not allocated
5337 ** by extending the file), the current page at position pgnoMove
5338 ** is already journaled.
5339 */
danielk1977003ba062004-11-04 02:57:33 +00005340 u8 eType;
5341 Pgno iPtrPage;
5342
5343 releasePage(pPageMove);
danielk1977f35843b2007-04-07 15:03:17 +00005344
5345 /* Move the page currently at pgnoRoot to pgnoMove. */
drh16a9b832007-05-05 18:39:25 +00005346 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00005347 if( rc!=SQLITE_OK ){
5348 return rc;
5349 }
5350 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drhccae6022005-02-26 17:31:26 +00005351 if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00005352 releasePage(pRoot);
5353 return rc;
5354 }
drhccae6022005-02-26 17:31:26 +00005355 assert( eType!=PTRMAP_ROOTPAGE );
5356 assert( eType!=PTRMAP_FREEPAGE );
danielk19773b8a05f2007-03-19 17:44:26 +00005357 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk19775fd057a2005-03-09 13:09:43 +00005358 if( rc!=SQLITE_OK ){
5359 releasePage(pRoot);
5360 return rc;
5361 }
danielk1977003ba062004-11-04 02:57:33 +00005362 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove);
5363 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00005364
5365 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00005366 if( rc!=SQLITE_OK ){
5367 return rc;
5368 }
drh16a9b832007-05-05 18:39:25 +00005369 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00005370 if( rc!=SQLITE_OK ){
5371 return rc;
5372 }
danielk19773b8a05f2007-03-19 17:44:26 +00005373 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00005374 if( rc!=SQLITE_OK ){
5375 releasePage(pRoot);
5376 return rc;
5377 }
5378 }else{
5379 pRoot = pPageMove;
5380 }
5381
danielk197742741be2005-01-08 12:42:39 +00005382 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00005383 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
5384 if( rc ){
5385 releasePage(pRoot);
5386 return rc;
5387 }
danielk1977aef0bf62005-12-30 16:28:01 +00005388 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00005389 if( rc ){
5390 releasePage(pRoot);
5391 return rc;
5392 }
danielk197742741be2005-01-08 12:42:39 +00005393
danielk1977003ba062004-11-04 02:57:33 +00005394 }else{
drh4f0c5872007-03-26 22:05:01 +00005395 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00005396 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00005397 }
5398#endif
danielk19773b8a05f2007-03-19 17:44:26 +00005399 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhde647132004-05-07 17:57:49 +00005400 zeroPage(pRoot, flags | PTF_LEAF);
danielk19773b8a05f2007-03-19 17:44:26 +00005401 sqlite3PagerUnref(pRoot->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00005402 *piTable = (int)pgnoRoot;
5403 return SQLITE_OK;
5404}
5405
5406/*
5407** Erase the given database page and all its children. Return
5408** the page to the freelist.
5409*/
drh4b70f112004-05-02 21:12:19 +00005410static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00005411 BtShared *pBt, /* The BTree that contains the table */
drh4b70f112004-05-02 21:12:19 +00005412 Pgno pgno, /* Page number to clear */
5413 MemPage *pParent, /* Parent page. NULL for the root */
5414 int freePageFlag /* Deallocate page if true */
5415){
danielk19776b456a22005-03-21 04:04:02 +00005416 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00005417 int rc;
drh4b70f112004-05-02 21:12:19 +00005418 unsigned char *pCell;
5419 int i;
drh8b2f49b2001-06-08 00:21:52 +00005420
danielk19773b8a05f2007-03-19 17:44:26 +00005421 if( pgno>sqlite3PagerPagecount(pBt->pPager) ){
drh49285702005-09-17 15:20:26 +00005422 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00005423 }
5424
drhde647132004-05-07 17:57:49 +00005425 rc = getAndInitPage(pBt, pgno, &pPage, pParent);
danielk19776b456a22005-03-21 04:04:02 +00005426 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00005427 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00005428 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00005429 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005430 rc = clearDatabasePage(pBt, get4byte(pCell), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00005431 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00005432 }
drh4b70f112004-05-02 21:12:19 +00005433 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00005434 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00005435 }
drha34b6762004-05-07 13:30:42 +00005436 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005437 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), pPage->pParent, 1);
danielk19776b456a22005-03-21 04:04:02 +00005438 if( rc ) goto cleardatabasepage_out;
drh2aa679f2001-06-25 02:11:07 +00005439 }
5440 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00005441 rc = freePage(pPage);
danielk19773b8a05f2007-03-19 17:44:26 +00005442 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
drh3a4c1412004-05-09 20:40:11 +00005443 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00005444 }
danielk19776b456a22005-03-21 04:04:02 +00005445
5446cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00005447 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00005448 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005449}
5450
5451/*
drhab01f612004-05-22 02:55:23 +00005452** Delete all information from a single table in the database. iTable is
5453** the page number of the root of the table. After this routine returns,
5454** the root page is empty, but still exists.
5455**
5456** This routine will fail with SQLITE_LOCKED if there are any open
5457** read cursors on the table. Open write cursors are moved to the
5458** root of the table.
drh8b2f49b2001-06-08 00:21:52 +00005459*/
danielk1977aef0bf62005-12-30 16:28:01 +00005460int sqlite3BtreeClearTable(Btree *p, int iTable){
drh8b2f49b2001-06-08 00:21:52 +00005461 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00005462 BtShared *pBt = p->pBt;
5463 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005464 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005465 }
drh980b1a72006-08-16 16:42:48 +00005466 rc = checkReadLocks(p, iTable, 0);
5467 if( rc ){
5468 return rc;
drhecdc7532001-09-23 02:35:53 +00005469 }
danielk1977ed429312006-01-19 08:43:31 +00005470
5471 /* Save the position of all cursors open on this table */
5472 if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
5473 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005474 }
danielk1977ed429312006-01-19 08:43:31 +00005475
5476 return clearDatabasePage(pBt, (Pgno)iTable, 0, 0);
drh8b2f49b2001-06-08 00:21:52 +00005477}
5478
5479/*
5480** Erase all information in a table and add the root of the table to
5481** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00005482** page 1) is never added to the freelist.
5483**
5484** This routine will fail with SQLITE_LOCKED if there are any open
5485** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00005486**
5487** If AUTOVACUUM is enabled and the page at iTable is not the last
5488** root page in the database file, then the last root page
5489** in the database file is moved into the slot formerly occupied by
5490** iTable and that last slot formerly occupied by the last root page
5491** is added to the freelist instead of iTable. In this say, all
5492** root pages are kept at the beginning of the database file, which
5493** is necessary for AUTOVACUUM to work right. *piMoved is set to the
5494** page number that used to be the last root page in the file before
5495** the move. If no page gets moved, *piMoved is set to 0.
5496** The last root page is recorded in meta[3] and the value of
5497** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00005498*/
danielk1977aef0bf62005-12-30 16:28:01 +00005499int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00005500 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00005501 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00005502 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00005503
danielk1977aef0bf62005-12-30 16:28:01 +00005504 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005505 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh8b2f49b2001-06-08 00:21:52 +00005506 }
danielk1977a0bf2652004-11-04 14:30:04 +00005507
danielk1977e6efa742004-11-10 11:55:10 +00005508 /* It is illegal to drop a table if any cursors are open on the
5509 ** database. This is because in auto-vacuum mode the backend may
5510 ** need to move another root-page to fill a gap left by the deleted
5511 ** root page. If an open cursor was using this page a problem would
5512 ** occur.
5513 */
5514 if( pBt->pCursor ){
5515 return SQLITE_LOCKED;
drh5df72a52002-06-06 23:16:05 +00005516 }
danielk1977a0bf2652004-11-04 14:30:04 +00005517
drh16a9b832007-05-05 18:39:25 +00005518 rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00005519 if( rc ) return rc;
danielk1977aef0bf62005-12-30 16:28:01 +00005520 rc = sqlite3BtreeClearTable(p, iTable);
danielk19776b456a22005-03-21 04:04:02 +00005521 if( rc ){
5522 releasePage(pPage);
5523 return rc;
5524 }
danielk1977a0bf2652004-11-04 14:30:04 +00005525
drh205f48e2004-11-05 00:43:11 +00005526 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00005527
drh4b70f112004-05-02 21:12:19 +00005528 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00005529#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00005530 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00005531 releasePage(pPage);
5532#else
5533 if( pBt->autoVacuum ){
5534 Pgno maxRootPgno;
danielk1977aef0bf62005-12-30 16:28:01 +00005535 rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00005536 if( rc!=SQLITE_OK ){
5537 releasePage(pPage);
5538 return rc;
5539 }
5540
5541 if( iTable==maxRootPgno ){
5542 /* If the table being dropped is the table with the largest root-page
5543 ** number in the database, put the root page on the free list.
5544 */
5545 rc = freePage(pPage);
5546 releasePage(pPage);
5547 if( rc!=SQLITE_OK ){
5548 return rc;
5549 }
5550 }else{
5551 /* The table being dropped does not have the largest root-page
5552 ** number in the database. So move the page that does into the
5553 ** gap left by the deleted root-page.
5554 */
5555 MemPage *pMove;
5556 releasePage(pPage);
drh16a9b832007-05-05 18:39:25 +00005557 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00005558 if( rc!=SQLITE_OK ){
5559 return rc;
5560 }
5561 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable);
5562 releasePage(pMove);
5563 if( rc!=SQLITE_OK ){
5564 return rc;
5565 }
drh16a9b832007-05-05 18:39:25 +00005566 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00005567 if( rc!=SQLITE_OK ){
5568 return rc;
5569 }
5570 rc = freePage(pMove);
5571 releasePage(pMove);
5572 if( rc!=SQLITE_OK ){
5573 return rc;
5574 }
5575 *piMoved = maxRootPgno;
5576 }
5577
danielk1977599fcba2004-11-08 07:13:13 +00005578 /* Set the new 'max-root-page' value in the database header. This
5579 ** is the old value less one, less one more if that happens to
5580 ** be a root-page number, less one again if that is the
5581 ** PENDING_BYTE_PAGE.
5582 */
danielk197787a6e732004-11-05 12:58:25 +00005583 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00005584 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
5585 maxRootPgno--;
5586 }
danielk1977266664d2006-02-10 08:24:21 +00005587 if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00005588 maxRootPgno--;
5589 }
danielk1977599fcba2004-11-08 07:13:13 +00005590 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
5591
danielk1977aef0bf62005-12-30 16:28:01 +00005592 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00005593 }else{
5594 rc = freePage(pPage);
5595 releasePage(pPage);
5596 }
5597#endif
drh2aa679f2001-06-25 02:11:07 +00005598 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00005599 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00005600 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00005601 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00005602 }
drh8b2f49b2001-06-08 00:21:52 +00005603 return rc;
5604}
5605
drh001bbcb2003-03-19 03:14:00 +00005606
drh8b2f49b2001-06-08 00:21:52 +00005607/*
drh23e11ca2004-05-04 17:27:28 +00005608** Read the meta-information out of a database file. Meta[0]
5609** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00005610** through meta[15] are available for use by higher layers. Meta[0]
5611** is read-only, the others are read/write.
5612**
5613** The schema layer numbers meta values differently. At the schema
5614** layer (and the SetCookie and ReadCookie opcodes) the number of
5615** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00005616*/
danielk1977aef0bf62005-12-30 16:28:01 +00005617int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
danielk19773b8a05f2007-03-19 17:44:26 +00005618 DbPage *pDbPage;
drh8b2f49b2001-06-08 00:21:52 +00005619 int rc;
drh4b70f112004-05-02 21:12:19 +00005620 unsigned char *pP1;
danielk1977aef0bf62005-12-30 16:28:01 +00005621 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00005622
danielk1977da184232006-01-05 11:34:32 +00005623 /* Reading a meta-data value requires a read-lock on page 1 (and hence
5624 ** the sqlite_master table. We grab this lock regardless of whether or
5625 ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
5626 ** 1 is treated as a special case by queryTableLock() and lockTable()).
5627 */
5628 rc = queryTableLock(p, 1, READ_LOCK);
5629 if( rc!=SQLITE_OK ){
5630 return rc;
5631 }
5632
drh23e11ca2004-05-04 17:27:28 +00005633 assert( idx>=0 && idx<=15 );
danielk19773b8a05f2007-03-19 17:44:26 +00005634 rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00005635 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00005636 pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
drh23e11ca2004-05-04 17:27:28 +00005637 *pMeta = get4byte(&pP1[36 + idx*4]);
danielk19773b8a05f2007-03-19 17:44:26 +00005638 sqlite3PagerUnref(pDbPage);
drhae157872004-08-14 19:20:09 +00005639
danielk1977599fcba2004-11-08 07:13:13 +00005640 /* If autovacuumed is disabled in this build but we are trying to
5641 ** access an autovacuumed database, then make the database readonly.
5642 */
danielk1977003ba062004-11-04 02:57:33 +00005643#ifdef SQLITE_OMIT_AUTOVACUUM
drhae157872004-08-14 19:20:09 +00005644 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00005645#endif
drhae157872004-08-14 19:20:09 +00005646
danielk1977da184232006-01-05 11:34:32 +00005647 /* Grab the read-lock on page 1. */
5648 rc = lockTable(p, 1, READ_LOCK);
5649 return rc;
drh8b2f49b2001-06-08 00:21:52 +00005650}
5651
5652/*
drh23e11ca2004-05-04 17:27:28 +00005653** Write meta-information back into the database. Meta[0] is
5654** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00005655*/
danielk1977aef0bf62005-12-30 16:28:01 +00005656int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
5657 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00005658 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00005659 int rc;
drh23e11ca2004-05-04 17:27:28 +00005660 assert( idx>=1 && idx<=15 );
danielk1977aef0bf62005-12-30 16:28:01 +00005661 if( p->inTrans!=TRANS_WRITE ){
drhf74b8d92002-09-01 23:20:45 +00005662 return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
drh5df72a52002-06-06 23:16:05 +00005663 }
drhde647132004-05-07 17:57:49 +00005664 assert( pBt->pPage1!=0 );
5665 pP1 = pBt->pPage1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00005666 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
drh4b70f112004-05-02 21:12:19 +00005667 if( rc ) return rc;
drh23e11ca2004-05-04 17:27:28 +00005668 put4byte(&pP1[36 + idx*4], iMeta);
drh8b2f49b2001-06-08 00:21:52 +00005669 return SQLITE_OK;
5670}
drh8c42ca92001-06-22 19:15:00 +00005671
drhf328bc82004-05-10 23:29:49 +00005672/*
5673** Return the flag byte at the beginning of the page that the cursor
5674** is currently pointing to.
5675*/
5676int sqlite3BtreeFlags(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00005677 /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
drh777e4c42006-01-13 04:31:58 +00005678 ** restoreOrClearCursorPosition() here.
danielk1977da184232006-01-05 11:34:32 +00005679 */
drhf328bc82004-05-10 23:29:49 +00005680 MemPage *pPage = pCur->pPage;
5681 return pPage ? pPage->aData[pPage->hdrOffset] : 0;
5682}
5683
drhdd793422001-06-28 01:54:48 +00005684
drhdd793422001-06-28 01:54:48 +00005685/*
drh5eddca62001-06-30 21:53:53 +00005686** Return the pager associated with a BTree. This routine is used for
5687** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00005688*/
danielk1977aef0bf62005-12-30 16:28:01 +00005689Pager *sqlite3BtreePager(Btree *p){
5690 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00005691}
drh5eddca62001-06-30 21:53:53 +00005692
drhb7f91642004-10-31 02:22:47 +00005693#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005694/*
5695** Append a message to the error message string.
5696*/
drh2e38c322004-09-03 18:38:44 +00005697static void checkAppendMsg(
5698 IntegrityCk *pCheck,
5699 char *zMsg1,
5700 const char *zFormat,
5701 ...
5702){
5703 va_list ap;
5704 char *zMsg2;
drh1dcdbc02007-01-27 02:24:54 +00005705 if( !pCheck->mxErr ) return;
5706 pCheck->mxErr--;
5707 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00005708 va_start(ap, zFormat);
5709 zMsg2 = sqlite3VMPrintf(zFormat, ap);
5710 va_end(ap);
5711 if( zMsg1==0 ) zMsg1 = "";
drh5eddca62001-06-30 21:53:53 +00005712 if( pCheck->zErrMsg ){
5713 char *zOld = pCheck->zErrMsg;
5714 pCheck->zErrMsg = 0;
danielk19774adee202004-05-08 08:23:19 +00005715 sqlite3SetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00005716 sqliteFree(zOld);
5717 }else{
danielk19774adee202004-05-08 08:23:19 +00005718 sqlite3SetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
drh5eddca62001-06-30 21:53:53 +00005719 }
drh2e38c322004-09-03 18:38:44 +00005720 sqliteFree(zMsg2);
drh5eddca62001-06-30 21:53:53 +00005721}
drhb7f91642004-10-31 02:22:47 +00005722#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00005723
drhb7f91642004-10-31 02:22:47 +00005724#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005725/*
5726** Add 1 to the reference count for page iPage. If this is the second
5727** reference to the page, add an error message to pCheck->zErrMsg.
5728** Return 1 if there are 2 ore more references to the page and 0 if
5729** if this is the first reference to the page.
5730**
5731** Also check that the page number is in bounds.
5732*/
drhaaab5722002-02-19 13:39:21 +00005733static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00005734 if( iPage==0 ) return 1;
drh0de8c112002-07-06 16:32:14 +00005735 if( iPage>pCheck->nPage || iPage<0 ){
drh2e38c322004-09-03 18:38:44 +00005736 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005737 return 1;
5738 }
5739 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00005740 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005741 return 1;
5742 }
5743 return (pCheck->anRef[iPage]++)>1;
5744}
5745
danielk1977afcdd022004-10-31 16:25:42 +00005746#ifndef SQLITE_OMIT_AUTOVACUUM
5747/*
5748** Check that the entry in the pointer-map for page iChild maps to
5749** page iParent, pointer type ptrType. If not, append an error message
5750** to pCheck.
5751*/
5752static void checkPtrmap(
5753 IntegrityCk *pCheck, /* Integrity check context */
5754 Pgno iChild, /* Child page number */
5755 u8 eType, /* Expected pointer map type */
5756 Pgno iParent, /* Expected pointer map parent page number */
5757 char *zContext /* Context description (used for error msg) */
5758){
5759 int rc;
5760 u8 ePtrmapType;
5761 Pgno iPtrmapParent;
5762
5763 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
5764 if( rc!=SQLITE_OK ){
5765 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
5766 return;
5767 }
5768
5769 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
5770 checkAppendMsg(pCheck, zContext,
5771 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
5772 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
5773 }
5774}
5775#endif
5776
drh5eddca62001-06-30 21:53:53 +00005777/*
5778** Check the integrity of the freelist or of an overflow page list.
5779** Verify that the number of pages on the list is N.
5780*/
drh30e58752002-03-02 20:41:57 +00005781static void checkList(
5782 IntegrityCk *pCheck, /* Integrity checking context */
5783 int isFreeList, /* True for a freelist. False for overflow page list */
5784 int iPage, /* Page number for first page in the list */
5785 int N, /* Expected number of pages in the list */
5786 char *zContext /* Context for error messages */
5787){
5788 int i;
drh3a4c1412004-05-09 20:40:11 +00005789 int expected = N;
5790 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00005791 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00005792 DbPage *pOvflPage;
5793 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00005794 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00005795 checkAppendMsg(pCheck, zContext,
5796 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00005797 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00005798 break;
5799 }
5800 if( checkRef(pCheck, iPage, zContext) ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00005801 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
drh2e38c322004-09-03 18:38:44 +00005802 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00005803 break;
5804 }
danielk19773b8a05f2007-03-19 17:44:26 +00005805 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00005806 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00005807 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00005808#ifndef SQLITE_OMIT_AUTOVACUUM
5809 if( pCheck->pBt->autoVacuum ){
5810 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
5811 }
5812#endif
drh855eb1c2004-08-31 13:45:11 +00005813 if( n>pCheck->pBt->usableSize/4-8 ){
drh2e38c322004-09-03 18:38:44 +00005814 checkAppendMsg(pCheck, zContext,
5815 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00005816 N--;
5817 }else{
5818 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00005819 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00005820#ifndef SQLITE_OMIT_AUTOVACUUM
5821 if( pCheck->pBt->autoVacuum ){
5822 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
5823 }
5824#endif
5825 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00005826 }
5827 N -= n;
drh30e58752002-03-02 20:41:57 +00005828 }
drh30e58752002-03-02 20:41:57 +00005829 }
danielk1977afcdd022004-10-31 16:25:42 +00005830#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00005831 else{
5832 /* If this database supports auto-vacuum and iPage is not the last
5833 ** page in this overflow list, check that the pointer-map entry for
5834 ** the following page matches iPage.
5835 */
5836 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00005837 i = get4byte(pOvflData);
danielk1977687566d2004-11-02 12:56:41 +00005838 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
5839 }
danielk1977afcdd022004-10-31 16:25:42 +00005840 }
5841#endif
danielk19773b8a05f2007-03-19 17:44:26 +00005842 iPage = get4byte(pOvflData);
5843 sqlite3PagerUnref(pOvflPage);
drh5eddca62001-06-30 21:53:53 +00005844 }
5845}
drhb7f91642004-10-31 02:22:47 +00005846#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00005847
drhb7f91642004-10-31 02:22:47 +00005848#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00005849/*
5850** Do various sanity checks on a single page of a tree. Return
5851** the tree depth. Root pages return 0. Parents of root pages
5852** return 1, and so forth.
5853**
5854** These checks are done:
5855**
5856** 1. Make sure that cells and freeblocks do not overlap
5857** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00005858** NO 2. Make sure cell keys are in order.
5859** NO 3. Make sure no key is less than or equal to zLowerBound.
5860** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00005861** 5. Check the integrity of overflow pages.
5862** 6. Recursively call checkTreePage on all children.
5863** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00005864** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00005865** the root of the tree.
5866*/
5867static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00005868 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00005869 int iPage, /* Page number of the page to check */
5870 MemPage *pParent, /* Parent page */
drh74161702006-02-24 02:53:49 +00005871 char *zParentContext /* Parent context */
drh5eddca62001-06-30 21:53:53 +00005872){
5873 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00005874 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00005875 int hdr, cellStart;
5876 int nCell;
drhda200cc2004-05-09 11:51:38 +00005877 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00005878 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00005879 int usableSize;
drh5eddca62001-06-30 21:53:53 +00005880 char zContext[100];
drh2e38c322004-09-03 18:38:44 +00005881 char *hit;
drh5eddca62001-06-30 21:53:53 +00005882
drh5bb3eb92007-05-04 13:15:55 +00005883 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
danielk1977ef73ee92004-11-06 12:26:07 +00005884
drh5eddca62001-06-30 21:53:53 +00005885 /* Check that the page exists
5886 */
drhd9cb6ac2005-10-20 07:28:17 +00005887 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00005888 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00005889 if( iPage==0 ) return 0;
5890 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh16a9b832007-05-05 18:39:25 +00005891 if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drh2e38c322004-09-03 18:38:44 +00005892 checkAppendMsg(pCheck, zContext,
5893 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00005894 return 0;
5895 }
drh16a9b832007-05-05 18:39:25 +00005896 if( (rc = sqlite3BtreeInitPage(pPage, pParent))!=0 ){
5897 checkAppendMsg(pCheck, zContext,
5898 "sqlite3BtreeInitPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00005899 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00005900 return 0;
5901 }
5902
5903 /* Check out all the cells.
5904 */
5905 depth = 0;
drh1dcdbc02007-01-27 02:24:54 +00005906 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
drh6f11bef2004-05-13 01:12:56 +00005907 u8 *pCell;
5908 int sz;
5909 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00005910
5911 /* Check payload overflow pages
5912 */
drh5bb3eb92007-05-04 13:15:55 +00005913 sqlite3_snprintf(sizeof(zContext), zContext,
5914 "On tree page %d cell %d: ", iPage, i);
danielk19771cc5ed82007-05-16 17:28:43 +00005915 pCell = findCell(pPage,i);
drh16a9b832007-05-05 18:39:25 +00005916 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005917 sz = info.nData;
5918 if( !pPage->intKey ) sz += info.nKey;
drh72365832007-03-06 15:53:44 +00005919 assert( sz==info.nPayload );
drh6f11bef2004-05-13 01:12:56 +00005920 if( sz>info.nLocal ){
drhb6f41482004-05-14 01:58:11 +00005921 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00005922 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
5923#ifndef SQLITE_OMIT_AUTOVACUUM
5924 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00005925 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00005926 }
5927#endif
5928 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00005929 }
5930
5931 /* Check sanity of left child page.
5932 */
drhda200cc2004-05-09 11:51:38 +00005933 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005934 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00005935#ifndef SQLITE_OMIT_AUTOVACUUM
5936 if( pBt->autoVacuum ){
5937 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
5938 }
5939#endif
drh74161702006-02-24 02:53:49 +00005940 d2 = checkTreePage(pCheck,pgno,pPage,zContext);
drhda200cc2004-05-09 11:51:38 +00005941 if( i>0 && d2!=depth ){
5942 checkAppendMsg(pCheck, zContext, "Child page depth differs");
5943 }
5944 depth = d2;
drh5eddca62001-06-30 21:53:53 +00005945 }
drh5eddca62001-06-30 21:53:53 +00005946 }
drhda200cc2004-05-09 11:51:38 +00005947 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005948 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh5bb3eb92007-05-04 13:15:55 +00005949 sqlite3_snprintf(sizeof(zContext), zContext,
5950 "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00005951#ifndef SQLITE_OMIT_AUTOVACUUM
5952 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00005953 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00005954 }
5955#endif
drh74161702006-02-24 02:53:49 +00005956 checkTreePage(pCheck, pgno, pPage, zContext);
drhda200cc2004-05-09 11:51:38 +00005957 }
drh5eddca62001-06-30 21:53:53 +00005958
5959 /* Check for complete coverage of the page
5960 */
drhda200cc2004-05-09 11:51:38 +00005961 data = pPage->aData;
5962 hdr = pPage->hdrOffset;
drh2e38c322004-09-03 18:38:44 +00005963 hit = sqliteMalloc( usableSize );
5964 if( hit ){
5965 memset(hit, 1, get2byte(&data[hdr+5]));
5966 nCell = get2byte(&data[hdr+3]);
5967 cellStart = hdr + 12 - 4*pPage->leaf;
5968 for(i=0; i<nCell; i++){
5969 int pc = get2byte(&data[cellStart+i*2]);
5970 int size = cellSizePtr(pPage, &data[pc]);
5971 int j;
danielk19777701e812005-01-10 12:59:51 +00005972 if( (pc+size-1)>=usableSize || pc<0 ){
5973 checkAppendMsg(pCheck, 0,
5974 "Corruption detected in cell %d on page %d",i,iPage,0);
5975 }else{
5976 for(j=pc+size-1; j>=pc; j--) hit[j]++;
5977 }
drh2e38c322004-09-03 18:38:44 +00005978 }
5979 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
5980 cnt++){
5981 int size = get2byte(&data[i+2]);
5982 int j;
danielk19777701e812005-01-10 12:59:51 +00005983 if( (i+size-1)>=usableSize || i<0 ){
5984 checkAppendMsg(pCheck, 0,
5985 "Corruption detected in cell %d on page %d",i,iPage,0);
5986 }else{
5987 for(j=i+size-1; j>=i; j--) hit[j]++;
5988 }
drh2e38c322004-09-03 18:38:44 +00005989 i = get2byte(&data[i]);
5990 }
5991 for(i=cnt=0; i<usableSize; i++){
5992 if( hit[i]==0 ){
5993 cnt++;
5994 }else if( hit[i]>1 ){
5995 checkAppendMsg(pCheck, 0,
5996 "Multiple uses for byte %d of page %d", i, iPage);
5997 break;
5998 }
5999 }
6000 if( cnt!=data[hdr+7] ){
6001 checkAppendMsg(pCheck, 0,
6002 "Fragmented space is %d byte reported as %d on page %d",
6003 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00006004 }
6005 }
drh2e38c322004-09-03 18:38:44 +00006006 sqliteFree(hit);
drh6019e162001-07-02 17:51:45 +00006007
drh4b70f112004-05-02 21:12:19 +00006008 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00006009 return depth+1;
drh5eddca62001-06-30 21:53:53 +00006010}
drhb7f91642004-10-31 02:22:47 +00006011#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006012
drhb7f91642004-10-31 02:22:47 +00006013#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006014/*
6015** This routine does a complete check of the given BTree file. aRoot[] is
6016** an array of pages numbers were each page number is the root page of
6017** a table. nRoot is the number of entries in aRoot.
6018**
6019** If everything checks out, this routine returns NULL. If something is
6020** amiss, an error message is written into memory obtained from malloc()
6021** and a pointer to that error message is returned. The calling function
6022** is responsible for freeing the error message when it is done.
6023*/
drh1dcdbc02007-01-27 02:24:54 +00006024char *sqlite3BtreeIntegrityCheck(
6025 Btree *p, /* The btree to be checked */
6026 int *aRoot, /* An array of root pages numbers for individual trees */
6027 int nRoot, /* Number of entries in aRoot[] */
6028 int mxErr, /* Stop reporting errors after this many */
6029 int *pnErr /* Write number of errors seen to this variable */
6030){
drh5eddca62001-06-30 21:53:53 +00006031 int i;
6032 int nRef;
drhaaab5722002-02-19 13:39:21 +00006033 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00006034 BtShared *pBt = p->pBt;
drh5eddca62001-06-30 21:53:53 +00006035
danielk19773b8a05f2007-03-19 17:44:26 +00006036 nRef = sqlite3PagerRefcount(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00006037 if( lockBtreeWithRetry(p)!=SQLITE_OK ){
drhefc251d2001-07-01 22:12:01 +00006038 return sqliteStrDup("Unable to acquire a read lock on the database");
6039 }
drh5eddca62001-06-30 21:53:53 +00006040 sCheck.pBt = pBt;
6041 sCheck.pPager = pBt->pPager;
danielk19773b8a05f2007-03-19 17:44:26 +00006042 sCheck.nPage = sqlite3PagerPagecount(sCheck.pPager);
drh1dcdbc02007-01-27 02:24:54 +00006043 sCheck.mxErr = mxErr;
6044 sCheck.nErr = 0;
6045 *pnErr = 0;
danielk1977e5321f02007-04-27 07:05:44 +00006046#ifndef SQLITE_OMIT_AUTOVACUUM
6047 if( pBt->nTrunc!=0 ){
6048 sCheck.nPage = pBt->nTrunc;
6049 }
6050#endif
drh0de8c112002-07-06 16:32:14 +00006051 if( sCheck.nPage==0 ){
6052 unlockBtreeIfUnused(pBt);
6053 return 0;
6054 }
drh8c1238a2003-01-02 14:43:55 +00006055 sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00006056 if( !sCheck.anRef ){
6057 unlockBtreeIfUnused(pBt);
drh1dcdbc02007-01-27 02:24:54 +00006058 *pnErr = 1;
danielk1977ac245ec2005-01-14 13:50:11 +00006059 return sqlite3MPrintf("Unable to malloc %d bytes",
6060 (sCheck.nPage+1)*sizeof(sCheck.anRef[0]));
6061 }
drhda200cc2004-05-09 11:51:38 +00006062 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00006063 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00006064 if( i<=sCheck.nPage ){
6065 sCheck.anRef[i] = 1;
6066 }
drh5eddca62001-06-30 21:53:53 +00006067 sCheck.zErrMsg = 0;
6068
6069 /* Check the integrity of the freelist
6070 */
drha34b6762004-05-07 13:30:42 +00006071 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
6072 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00006073
6074 /* Check all the tables.
6075 */
drh1dcdbc02007-01-27 02:24:54 +00006076 for(i=0; i<nRoot && sCheck.mxErr; i++){
drh4ff6dfa2002-03-03 23:06:00 +00006077 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00006078#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00006079 if( pBt->autoVacuum && aRoot[i]>1 ){
6080 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
6081 }
6082#endif
drh74161702006-02-24 02:53:49 +00006083 checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ");
drh5eddca62001-06-30 21:53:53 +00006084 }
6085
6086 /* Make sure every page in the file is referenced
6087 */
drh1dcdbc02007-01-27 02:24:54 +00006088 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00006089#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00006090 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00006091 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00006092 }
danielk1977afcdd022004-10-31 16:25:42 +00006093#else
6094 /* If the database supports auto-vacuum, make sure no tables contain
6095 ** references to pointer-map pages.
6096 */
6097 if( sCheck.anRef[i]==0 &&
danielk1977266664d2006-02-10 08:24:21 +00006098 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006099 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
6100 }
6101 if( sCheck.anRef[i]!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00006102 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00006103 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
6104 }
6105#endif
drh5eddca62001-06-30 21:53:53 +00006106 }
6107
6108 /* Make sure this analysis did not leave any unref() pages
6109 */
drh5e00f6c2001-09-13 13:46:56 +00006110 unlockBtreeIfUnused(pBt);
danielk19773b8a05f2007-03-19 17:44:26 +00006111 if( nRef != sqlite3PagerRefcount(pBt->pPager) ){
drh2e38c322004-09-03 18:38:44 +00006112 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00006113 "Outstanding page count goes from %d to %d during this analysis",
danielk19773b8a05f2007-03-19 17:44:26 +00006114 nRef, sqlite3PagerRefcount(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00006115 );
drh5eddca62001-06-30 21:53:53 +00006116 }
6117
6118 /* Clean up and report errors.
6119 */
6120 sqliteFree(sCheck.anRef);
drh1dcdbc02007-01-27 02:24:54 +00006121 *pnErr = sCheck.nErr;
drh5eddca62001-06-30 21:53:53 +00006122 return sCheck.zErrMsg;
6123}
drhb7f91642004-10-31 02:22:47 +00006124#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00006125
drh73509ee2003-04-06 20:44:45 +00006126/*
6127** Return the full pathname of the underlying database file.
6128*/
danielk1977aef0bf62005-12-30 16:28:01 +00006129const char *sqlite3BtreeGetFilename(Btree *p){
6130 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00006131 return sqlite3PagerFilename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00006132}
6133
6134/*
danielk19775865e3d2004-06-14 06:03:57 +00006135** Return the pathname of the directory that contains the database file.
6136*/
danielk1977aef0bf62005-12-30 16:28:01 +00006137const char *sqlite3BtreeGetDirname(Btree *p){
6138 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00006139 return sqlite3PagerDirname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006140}
6141
6142/*
6143** Return the pathname of the journal file for this database. The return
6144** value of this routine is the same regardless of whether the journal file
6145** has been created or not.
6146*/
danielk1977aef0bf62005-12-30 16:28:01 +00006147const char *sqlite3BtreeGetJournalname(Btree *p){
6148 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00006149 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00006150}
6151
drhb7f91642004-10-31 02:22:47 +00006152#ifndef SQLITE_OMIT_VACUUM
danielk19775865e3d2004-06-14 06:03:57 +00006153/*
drhf7c57532003-04-25 13:22:51 +00006154** Copy the complete content of pBtFrom into pBtTo. A transaction
6155** must be active for both files.
6156**
6157** The size of file pBtFrom may be reduced by this operation.
drh43605152004-05-29 21:46:49 +00006158** If anything goes wrong, the transaction on pBtFrom is rolled back.
drh73509ee2003-04-06 20:44:45 +00006159*/
danielk1977aef0bf62005-12-30 16:28:01 +00006160int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
drhf7c57532003-04-25 13:22:51 +00006161 int rc = SQLITE_OK;
drh50f2f432005-09-16 11:32:18 +00006162 Pgno i, nPage, nToPage, iSkip;
drhf7c57532003-04-25 13:22:51 +00006163
danielk1977aef0bf62005-12-30 16:28:01 +00006164 BtShared *pBtTo = pTo->pBt;
6165 BtShared *pBtFrom = pFrom->pBt;
6166
6167 if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
danielk1977ee5741e2004-05-31 10:01:34 +00006168 return SQLITE_ERROR;
6169 }
drhf7c57532003-04-25 13:22:51 +00006170 if( pBtTo->pCursor ) return SQLITE_BUSY;
danielk19773b8a05f2007-03-19 17:44:26 +00006171 nToPage = sqlite3PagerPagecount(pBtTo->pPager);
6172 nPage = sqlite3PagerPagecount(pBtFrom->pPager);
drh50f2f432005-09-16 11:32:18 +00006173 iSkip = PENDING_BYTE_PAGE(pBtTo);
danielk1977369f27e2004-06-15 11:40:04 +00006174 for(i=1; rc==SQLITE_OK && i<=nPage; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00006175 DbPage *pDbPage;
drh50f2f432005-09-16 11:32:18 +00006176 if( i==iSkip ) continue;
danielk19773b8a05f2007-03-19 17:44:26 +00006177 rc = sqlite3PagerGet(pBtFrom->pPager, i, &pDbPage);
drhf7c57532003-04-25 13:22:51 +00006178 if( rc ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00006179 rc = sqlite3PagerOverwrite(pBtTo->pPager, i, sqlite3PagerGetData(pDbPage));
6180 sqlite3PagerUnref(pDbPage);
drhf7c57532003-04-25 13:22:51 +00006181 }
drh538f5702007-04-13 02:14:30 +00006182
6183 /* If the file is shrinking, journal the pages that are being truncated
6184 ** so that they can be rolled back if the commit fails.
6185 */
drh2e6d11b2003-04-25 15:37:57 +00006186 for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00006187 DbPage *pDbPage;
drh49285702005-09-17 15:20:26 +00006188 if( i==iSkip ) continue;
danielk19773b8a05f2007-03-19 17:44:26 +00006189 rc = sqlite3PagerGet(pBtTo->pPager, i, &pDbPage);
drh2e6d11b2003-04-25 15:37:57 +00006190 if( rc ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00006191 rc = sqlite3PagerWrite(pDbPage);
drh538f5702007-04-13 02:14:30 +00006192 sqlite3PagerDontWrite(pDbPage);
6193 /* Yeah. It seems wierd to call DontWrite() right after Write(). But
6194 ** that is because the names of those procedures do not exactly
6195 ** represent what they do. Write() really means "put this page in the
6196 ** rollback journal and mark it as dirty so that it will be written
6197 ** to the database file later." DontWrite() undoes the second part of
6198 ** that and prevents the page from being written to the database. The
6199 ** page is still on the rollback journal, though. And that is the whole
6200 ** point of this loop: to put pages on the rollback journal. */
danielk19773b8a05f2007-03-19 17:44:26 +00006201 sqlite3PagerUnref(pDbPage);
drh2e6d11b2003-04-25 15:37:57 +00006202 }
6203 if( !rc && nPage<nToPage ){
danielk19773b8a05f2007-03-19 17:44:26 +00006204 rc = sqlite3PagerTruncate(pBtTo->pPager, nPage);
drh2e6d11b2003-04-25 15:37:57 +00006205 }
drh538f5702007-04-13 02:14:30 +00006206
drhf7c57532003-04-25 13:22:51 +00006207 if( rc ){
danielk1977aef0bf62005-12-30 16:28:01 +00006208 sqlite3BtreeRollback(pTo);
drhf7c57532003-04-25 13:22:51 +00006209 }
6210 return rc;
drh73509ee2003-04-06 20:44:45 +00006211}
drhb7f91642004-10-31 02:22:47 +00006212#endif /* SQLITE_OMIT_VACUUM */
danielk19771d850a72004-05-31 08:26:49 +00006213
6214/*
6215** Return non-zero if a transaction is active.
6216*/
danielk1977aef0bf62005-12-30 16:28:01 +00006217int sqlite3BtreeIsInTrans(Btree *p){
6218 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00006219}
6220
6221/*
6222** Return non-zero if a statement transaction is active.
6223*/
danielk1977aef0bf62005-12-30 16:28:01 +00006224int sqlite3BtreeIsInStmt(Btree *p){
6225 return (p->pBt && p->pBt->inStmt);
danielk19771d850a72004-05-31 08:26:49 +00006226}
danielk197713adf8a2004-06-03 16:08:41 +00006227
6228/*
danielk19772372c2b2006-06-27 16:34:56 +00006229** Return non-zero if a read (or write) transaction is active.
6230*/
6231int sqlite3BtreeIsInReadTrans(Btree *p){
6232 return (p && (p->inTrans!=TRANS_NONE));
6233}
6234
6235/*
danielk1977da184232006-01-05 11:34:32 +00006236** This function returns a pointer to a blob of memory associated with
6237** a single shared-btree. The memory is used by client code for it's own
6238** purposes (for example, to store a high-level schema associated with
6239** the shared-btree). The btree layer manages reference counting issues.
6240**
6241** The first time this is called on a shared-btree, nBytes bytes of memory
6242** are allocated, zeroed, and returned to the caller. For each subsequent
6243** call the nBytes parameter is ignored and a pointer to the same blob
6244** of memory returned.
6245**
6246** Just before the shared-btree is closed, the function passed as the
6247** xFree argument when the memory allocation was made is invoked on the
6248** blob of allocated memory. This function should not call sqliteFree()
6249** on the memory, the btree layer does that.
6250*/
6251void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
6252 BtShared *pBt = p->pBt;
6253 if( !pBt->pSchema ){
6254 pBt->pSchema = sqliteMalloc(nBytes);
6255 pBt->xFreeSchema = xFree;
6256 }
6257 return pBt->pSchema;
6258}
6259
danielk1977c87d34d2006-01-06 13:00:28 +00006260/*
6261** Return true if another user of the same shared btree as the argument
6262** handle holds an exclusive lock on the sqlite_master table.
6263*/
6264int sqlite3BtreeSchemaLocked(Btree *p){
6265 return (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
6266}
6267
drha154dcd2006-03-22 22:10:07 +00006268
6269#ifndef SQLITE_OMIT_SHARED_CACHE
6270/*
6271** Obtain a lock on the table whose root page is iTab. The
6272** lock is a write lock if isWritelock is true or a read lock
6273** if it is false.
6274*/
danielk1977c00da102006-01-07 13:21:04 +00006275int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00006276 int rc = SQLITE_OK;
danielk1977c00da102006-01-07 13:21:04 +00006277 u8 lockType = (isWriteLock?WRITE_LOCK:READ_LOCK);
danielk19772e94d4d2006-01-09 05:36:27 +00006278 rc = queryTableLock(p, iTab, lockType);
danielk1977c00da102006-01-07 13:21:04 +00006279 if( rc==SQLITE_OK ){
6280 rc = lockTable(p, iTab, lockType);
6281 }
6282 return rc;
6283}
drha154dcd2006-03-22 22:10:07 +00006284#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00006285
danielk1977b4e9af92007-05-01 17:49:49 +00006286#ifndef SQLITE_OMIT_INCRBLOB
6287/*
6288** Argument pCsr must be a cursor opened for writing on an
6289** INTKEY table currently pointing at a valid table entry.
6290** This function modifies the data stored as part of that entry.
6291** Only the data content may only be modified, it is not possible
6292** to change the length of the data stored.
6293*/
danielk1977dcbb5d32007-05-04 18:36:44 +00006294int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
danielk1977d04417962007-05-02 13:16:30 +00006295
danielk1977dcbb5d32007-05-04 18:36:44 +00006296 assert(pCsr->isIncrblobHandle);
6297 if( pCsr->eState==CURSOR_REQUIRESEEK ){
6298 return SQLITE_ABORT;
6299 }
6300
danielk1977d04417962007-05-02 13:16:30 +00006301 /* Check some preconditions:
danielk1977dcbb5d32007-05-04 18:36:44 +00006302 ** (a) the cursor is open for writing,
6303 ** (b) there is no read-lock on the table being modified and
6304 ** (c) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00006305 */
danielk1977d04417962007-05-02 13:16:30 +00006306 if( !pCsr->wrFlag ){
danielk1977dcbb5d32007-05-04 18:36:44 +00006307 return SQLITE_READONLY;
danielk1977d04417962007-05-02 13:16:30 +00006308 }
drh87cc3b32007-05-08 21:45:27 +00006309 assert( !pCsr->pBtree->pBt->readOnly
6310 && pCsr->pBtree->pBt->inTransaction==TRANS_WRITE );
danielk1977d04417962007-05-02 13:16:30 +00006311 if( checkReadLocks(pCsr->pBtree, pCsr->pgnoRoot, pCsr) ){
6312 return SQLITE_LOCKED; /* The table pCur points to has a read lock */
6313 }
6314 if( pCsr->eState==CURSOR_INVALID || !pCsr->pPage->intKey ){
6315 return SQLITE_ERROR;
danielk1977b4e9af92007-05-01 17:49:49 +00006316 }
6317
danielk19779f8d6402007-05-02 17:48:45 +00006318 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00006319}
danielk19772dec9702007-05-02 16:48:37 +00006320
6321/*
6322** Set a flag on this cursor to cache the locations of pages from the
danielk1977da107192007-05-04 08:32:13 +00006323** overflow list for the current row. This is used by cursors opened
6324** for incremental blob IO only.
6325**
6326** This function sets a flag only. The actual page location cache
6327** (stored in BtCursor.aOverflow[]) is allocated and used by function
6328** accessPayload() (the worker function for sqlite3BtreeData() and
6329** sqlite3BtreePutData()).
danielk19772dec9702007-05-02 16:48:37 +00006330*/
6331void sqlite3BtreeCacheOverflow(BtCursor *pCur){
danielk1977dcbb5d32007-05-04 18:36:44 +00006332 assert(!pCur->isIncrblobHandle);
danielk19772dec9702007-05-02 16:48:37 +00006333 assert(!pCur->aOverflow);
danielk1977dcbb5d32007-05-04 18:36:44 +00006334 pCur->isIncrblobHandle = 1;
danielk19772dec9702007-05-02 16:48:37 +00006335}
danielk1977b4e9af92007-05-01 17:49:49 +00006336#endif