blob: 1a8ddf3589dd0261e6309ae532a4dbeb05859dbc [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*************************************************************************
drh51898cf2009-04-19 20:51:06 +000012** $Id: btree.c,v 1.596 2009/04/19 20:51:07 drh Exp $
drh8b2f49b2001-06-08 00:21:52 +000013**
14** This file implements a external (disk-based) database using BTrees.
drha3152892007-05-05 11:48:52 +000015** See the header comment on "btreeInt.h" for additional information.
16** Including a description of file format and an overview of operation.
drha059ad02001-04-17 20:09:11 +000017*/
drha3152892007-05-05 11:48:52 +000018#include "btreeInt.h"
paulb95a8862003-04-01 21:16:41 +000019
drh8c42ca92001-06-22 19:15:00 +000020/*
drha3152892007-05-05 11:48:52 +000021** The header string that appears at the beginning of every
22** SQLite database.
drh556b2a22005-06-14 16:04:05 +000023*/
drh556b2a22005-06-14 16:04:05 +000024static const char zMagicHeader[] = SQLITE_FILE_HEADER;
drh08ed44e2001-04-29 23:32:55 +000025
drh8c42ca92001-06-22 19:15:00 +000026/*
drha3152892007-05-05 11:48:52 +000027** Set this global variable to 1 to enable tracing using the TRACE
28** macro.
drh615ae552005-01-16 23:21:00 +000029*/
drhe8f52c52008-07-12 14:52:20 +000030#if 0
mlcreech3a00f902008-03-04 17:45:01 +000031int sqlite3BtreeTrace=0; /* True to enable tracing */
drhe8f52c52008-07-12 14:52:20 +000032# define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
33#else
34# define TRACE(X)
drh615ae552005-01-16 23:21:00 +000035#endif
drh615ae552005-01-16 23:21:00 +000036
drh86f8c192007-08-22 00:39:19 +000037
38
drhe53831d2007-08-17 01:14:38 +000039#ifndef SQLITE_OMIT_SHARED_CACHE
40/*
danielk1977502b4e02008-09-02 14:07:24 +000041** A list of BtShared objects that are eligible for participation
42** in shared cache. This variable has file scope during normal builds,
43** but the test harness needs to access it so we make it global for
44** test builds.
drh7555d8e2009-03-20 13:15:30 +000045**
46** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
drhe53831d2007-08-17 01:14:38 +000047*/
48#ifdef SQLITE_TEST
drh78f82d12008-09-02 00:52:52 +000049BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
drhe53831d2007-08-17 01:14:38 +000050#else
drh78f82d12008-09-02 00:52:52 +000051static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
drhe53831d2007-08-17 01:14:38 +000052#endif
drhe53831d2007-08-17 01:14:38 +000053#endif /* SQLITE_OMIT_SHARED_CACHE */
54
55#ifndef SQLITE_OMIT_SHARED_CACHE
56/*
57** Enable or disable the shared pager and schema features.
58**
59** This routine has no effect on existing database connections.
60** The shared cache setting effects only future calls to
61** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
62*/
63int sqlite3_enable_shared_cache(int enable){
danielk1977502b4e02008-09-02 14:07:24 +000064 sqlite3GlobalConfig.sharedCacheEnabled = enable;
drhe53831d2007-08-17 01:14:38 +000065 return SQLITE_OK;
66}
67#endif
68
drhd677b3d2007-08-20 22:48:41 +000069
drh615ae552005-01-16 23:21:00 +000070/*
drh66cbd152004-09-01 16:12:25 +000071** Forward declaration
72*/
drh11b57d62009-02-24 19:21:41 +000073static int checkForReadConflicts(Btree*, Pgno, BtCursor*, i64);
drh66cbd152004-09-01 16:12:25 +000074
danielk1977aef0bf62005-12-30 16:28:01 +000075
76#ifdef SQLITE_OMIT_SHARED_CACHE
77 /*
drhc25eabe2009-02-24 18:57:31 +000078 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
79 ** and clearAllSharedCacheTableLocks()
danielk1977aef0bf62005-12-30 16:28:01 +000080 ** manipulate entries in the BtShared.pLock linked list used to store
81 ** shared-cache table level locks. If the library is compiled with the
82 ** shared-cache feature disabled, then there is only ever one user
danielk1977da184232006-01-05 11:34:32 +000083 ** of each BtShared structure and so this locking is not necessary.
84 ** So define the lock related functions as no-ops.
danielk1977aef0bf62005-12-30 16:28:01 +000085 */
drhc25eabe2009-02-24 18:57:31 +000086 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
87 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
88 #define clearAllSharedCacheTableLocks(a)
drhe53831d2007-08-17 01:14:38 +000089#endif
danielk1977aef0bf62005-12-30 16:28:01 +000090
drhe53831d2007-08-17 01:14:38 +000091#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977da184232006-01-05 11:34:32 +000092/*
danielk1977aef0bf62005-12-30 16:28:01 +000093** Query to see if btree handle p may obtain a lock of type eLock
94** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
drhc25eabe2009-02-24 18:57:31 +000095** SQLITE_OK if the lock may be obtained (by calling
96** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
danielk1977aef0bf62005-12-30 16:28:01 +000097*/
drhc25eabe2009-02-24 18:57:31 +000098static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
danielk1977aef0bf62005-12-30 16:28:01 +000099 BtShared *pBt = p->pBt;
100 BtLock *pIter;
101
drh1fee73e2007-08-29 04:00:57 +0000102 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000103 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
104 assert( p->db!=0 );
drhd677b3d2007-08-20 22:48:41 +0000105
danielk19775b413d72009-04-01 09:41:54 +0000106 /* If requesting a write-lock, then the Btree must have an open write
107 ** transaction on this file. And, obviously, for this to be so there
108 ** must be an open write transaction on the file itself.
109 */
110 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
111 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
112
danielk1977da184232006-01-05 11:34:32 +0000113 /* This is a no-op if the shared-cache is not enabled */
drhe53831d2007-08-17 01:14:38 +0000114 if( !p->sharable ){
danielk1977da184232006-01-05 11:34:32 +0000115 return SQLITE_OK;
116 }
117
danielk1977641b0f42007-12-21 04:47:25 +0000118 /* If some other connection is holding an exclusive lock, the
119 ** requested lock may not be obtained.
120 */
danielk1977404ca072009-03-16 13:19:36 +0000121 if( pBt->pWriter!=p && pBt->isExclusive ){
122 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
123 return SQLITE_LOCKED_SHAREDCACHE;
danielk1977641b0f42007-12-21 04:47:25 +0000124 }
125
drhc25eabe2009-02-24 18:57:31 +0000126 /* This (along with setSharedCacheTableLock()) is where
127 ** the ReadUncommitted flag is dealt with.
128 ** If the caller is querying for a read-lock on any table
drhc74d0b1d2009-02-24 16:18:05 +0000129 ** other than the sqlite_master table (table 1) and if the ReadUncommitted
130 ** flag is set, then the lock granted even if there are write-locks
danielk1977da184232006-01-05 11:34:32 +0000131 ** on the table. If a write-lock is requested, the ReadUncommitted flag
132 ** is not considered.
133 **
drhc25eabe2009-02-24 18:57:31 +0000134 ** In function setSharedCacheTableLock(), if a read-lock is demanded and the
danielk1977da184232006-01-05 11:34:32 +0000135 ** ReadUncommitted flag is set, no entry is added to the locks list
136 ** (BtShared.pLock).
137 **
drhc74d0b1d2009-02-24 16:18:05 +0000138 ** To summarize: If the ReadUncommitted flag is set, then read cursors
139 ** on non-schema tables do not create or respect table locks. The locking
140 ** procedure for a write-cursor does not change.
danielk1977da184232006-01-05 11:34:32 +0000141 */
142 if(
drhe5fe6902007-12-07 18:55:28 +0000143 0==(p->db->flags&SQLITE_ReadUncommitted) ||
danielk1977da184232006-01-05 11:34:32 +0000144 eLock==WRITE_LOCK ||
drh47ded162006-01-06 01:42:58 +0000145 iTab==MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000146 ){
147 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
danielk19775b413d72009-04-01 09:41:54 +0000148 /* The condition (pIter->eLock!=eLock) in the following if(...)
149 ** statement is a simplification of:
150 **
151 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
152 **
153 ** since we know that if eLock==WRITE_LOCK, then no other connection
154 ** may hold a WRITE_LOCK on any table in this file (since there can
155 ** only be a single writer).
156 */
157 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
158 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
159 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
danielk1977404ca072009-03-16 13:19:36 +0000160 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
161 if( eLock==WRITE_LOCK ){
162 assert( p==pBt->pWriter );
163 pBt->isPending = 1;
164 }
165 return SQLITE_LOCKED_SHAREDCACHE;
danielk1977da184232006-01-05 11:34:32 +0000166 }
danielk1977aef0bf62005-12-30 16:28:01 +0000167 }
168 }
169 return SQLITE_OK;
170}
drhe53831d2007-08-17 01:14:38 +0000171#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000172
drhe53831d2007-08-17 01:14:38 +0000173#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000174/*
175** Add a lock on the table with root-page iTable to the shared-btree used
176** by Btree handle p. Parameter eLock must be either READ_LOCK or
177** WRITE_LOCK.
178**
179** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
180** SQLITE_NOMEM may also be returned.
181*/
drhc25eabe2009-02-24 18:57:31 +0000182static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
danielk1977aef0bf62005-12-30 16:28:01 +0000183 BtShared *pBt = p->pBt;
184 BtLock *pLock = 0;
185 BtLock *pIter;
186
drh1fee73e2007-08-29 04:00:57 +0000187 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000188 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
189 assert( p->db!=0 );
drhd677b3d2007-08-20 22:48:41 +0000190
danielk1977da184232006-01-05 11:34:32 +0000191 /* This is a no-op if the shared-cache is not enabled */
drhe53831d2007-08-17 01:14:38 +0000192 if( !p->sharable ){
danielk1977da184232006-01-05 11:34:32 +0000193 return SQLITE_OK;
194 }
195
drhc25eabe2009-02-24 18:57:31 +0000196 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
danielk1977aef0bf62005-12-30 16:28:01 +0000197
drhc74d0b1d2009-02-24 16:18:05 +0000198 /* If the read-uncommitted flag is set and a read-lock is requested on
199 ** a non-schema table, then the lock is always granted. Return early
200 ** without adding an entry to the BtShared.pLock list. See
drhc25eabe2009-02-24 18:57:31 +0000201 ** comment in function querySharedCacheTableLock() for more info
202 ** on handling the ReadUncommitted flag.
danielk1977da184232006-01-05 11:34:32 +0000203 */
204 if(
drhe5fe6902007-12-07 18:55:28 +0000205 (p->db->flags&SQLITE_ReadUncommitted) &&
danielk1977da184232006-01-05 11:34:32 +0000206 (eLock==READ_LOCK) &&
drh47ded162006-01-06 01:42:58 +0000207 iTable!=MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000208 ){
209 return SQLITE_OK;
210 }
211
danielk1977aef0bf62005-12-30 16:28:01 +0000212 /* First search the list for an existing lock on this table. */
213 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
214 if( pIter->iTable==iTable && pIter->pBtree==p ){
215 pLock = pIter;
216 break;
217 }
218 }
219
220 /* If the above search did not find a BtLock struct associating Btree p
221 ** with table iTable, allocate one and link it into the list.
222 */
223 if( !pLock ){
drh17435752007-08-16 04:30:38 +0000224 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
danielk1977aef0bf62005-12-30 16:28:01 +0000225 if( !pLock ){
226 return SQLITE_NOMEM;
227 }
228 pLock->iTable = iTable;
229 pLock->pBtree = p;
230 pLock->pNext = pBt->pLock;
231 pBt->pLock = pLock;
232 }
233
234 /* Set the BtLock.eLock variable to the maximum of the current lock
235 ** and the requested lock. This means if a write-lock was already held
236 ** and a read-lock requested, we don't incorrectly downgrade the lock.
237 */
238 assert( WRITE_LOCK>READ_LOCK );
danielk19775118b912005-12-30 16:31:53 +0000239 if( eLock>pLock->eLock ){
240 pLock->eLock = eLock;
241 }
danielk1977aef0bf62005-12-30 16:28:01 +0000242
243 return SQLITE_OK;
244}
drhe53831d2007-08-17 01:14:38 +0000245#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000246
drhe53831d2007-08-17 01:14:38 +0000247#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000248/*
drhc25eabe2009-02-24 18:57:31 +0000249** Release all the table locks (locks obtained via calls to
250** the setSharedCacheTableLock() procedure) held by Btree handle p.
danielk1977fa542f12009-04-02 18:28:08 +0000251**
252** This function assumes that handle p has an open read or write
253** transaction. If it does not, then the BtShared.isPending variable
254** may be incorrectly cleared.
danielk1977aef0bf62005-12-30 16:28:01 +0000255*/
drhc25eabe2009-02-24 18:57:31 +0000256static void clearAllSharedCacheTableLocks(Btree *p){
danielk1977641b0f42007-12-21 04:47:25 +0000257 BtShared *pBt = p->pBt;
258 BtLock **ppIter = &pBt->pLock;
danielk1977da184232006-01-05 11:34:32 +0000259
drh1fee73e2007-08-29 04:00:57 +0000260 assert( sqlite3BtreeHoldsMutex(p) );
drhe53831d2007-08-17 01:14:38 +0000261 assert( p->sharable || 0==*ppIter );
danielk1977fa542f12009-04-02 18:28:08 +0000262 assert( p->inTrans>0 );
danielk1977da184232006-01-05 11:34:32 +0000263
danielk1977aef0bf62005-12-30 16:28:01 +0000264 while( *ppIter ){
265 BtLock *pLock = *ppIter;
danielk1977404ca072009-03-16 13:19:36 +0000266 assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
danielk1977fa542f12009-04-02 18:28:08 +0000267 assert( pLock->pBtree->inTrans>=pLock->eLock );
danielk1977aef0bf62005-12-30 16:28:01 +0000268 if( pLock->pBtree==p ){
269 *ppIter = pLock->pNext;
drh17435752007-08-16 04:30:38 +0000270 sqlite3_free(pLock);
danielk1977aef0bf62005-12-30 16:28:01 +0000271 }else{
272 ppIter = &pLock->pNext;
273 }
274 }
danielk1977641b0f42007-12-21 04:47:25 +0000275
danielk1977404ca072009-03-16 13:19:36 +0000276 assert( pBt->isPending==0 || pBt->pWriter );
277 if( pBt->pWriter==p ){
278 pBt->pWriter = 0;
279 pBt->isExclusive = 0;
280 pBt->isPending = 0;
281 }else if( pBt->nTransaction==2 ){
282 /* This function is called when connection p is concluding its
283 ** transaction. If there currently exists a writer, and p is not
284 ** that writer, then the number of locks held by connections other
285 ** than the writer must be about to drop to zero. In this case
286 ** set the isPending flag to 0.
287 **
288 ** If there is not currently a writer, then BtShared.isPending must
289 ** be zero already. So this next line is harmless in that case.
290 */
291 pBt->isPending = 0;
danielk1977641b0f42007-12-21 04:47:25 +0000292 }
danielk1977aef0bf62005-12-30 16:28:01 +0000293}
294#endif /* SQLITE_OMIT_SHARED_CACHE */
295
drh980b1a72006-08-16 16:42:48 +0000296static void releasePage(MemPage *pPage); /* Forward reference */
297
drh1fee73e2007-08-29 04:00:57 +0000298/*
299** Verify that the cursor holds a mutex on the BtShared
300*/
301#ifndef NDEBUG
302static int cursorHoldsMutex(BtCursor *p){
drhff0587c2007-08-29 17:43:19 +0000303 return sqlite3_mutex_held(p->pBt->mutex);
drh1fee73e2007-08-29 04:00:57 +0000304}
305#endif
306
307
danielk197792d4d7a2007-05-04 12:05:56 +0000308#ifndef SQLITE_OMIT_INCRBLOB
309/*
310** Invalidate the overflow page-list cache for cursor pCur, if any.
311*/
312static void invalidateOverflowCache(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000313 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000314 sqlite3_free(pCur->aOverflow);
danielk197792d4d7a2007-05-04 12:05:56 +0000315 pCur->aOverflow = 0;
316}
317
318/*
319** Invalidate the overflow page-list cache for all cursors opened
320** on the shared btree structure pBt.
321*/
322static void invalidateAllOverflowCache(BtShared *pBt){
323 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000324 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +0000325 for(p=pBt->pCursor; p; p=p->pNext){
326 invalidateOverflowCache(p);
327 }
328}
329#else
330 #define invalidateOverflowCache(x)
331 #define invalidateAllOverflowCache(x)
332#endif
333
drh980b1a72006-08-16 16:42:48 +0000334/*
danielk1977bea2a942009-01-20 17:06:27 +0000335** Set bit pgno of the BtShared.pHasContent bitvec. This is called
336** when a page that previously contained data becomes a free-list leaf
337** page.
338**
339** The BtShared.pHasContent bitvec exists to work around an obscure
340** bug caused by the interaction of two useful IO optimizations surrounding
341** free-list leaf pages:
342**
343** 1) When all data is deleted from a page and the page becomes
344** a free-list leaf page, the page is not written to the database
345** (as free-list leaf pages contain no meaningful data). Sometimes
346** such a page is not even journalled (as it will not be modified,
347** why bother journalling it?).
348**
349** 2) When a free-list leaf page is reused, its content is not read
350** from the database or written to the journal file (why should it
351** be, if it is not at all meaningful?).
352**
353** By themselves, these optimizations work fine and provide a handy
354** performance boost to bulk delete or insert operations. However, if
355** a page is moved to the free-list and then reused within the same
356** transaction, a problem comes up. If the page is not journalled when
357** it is moved to the free-list and it is also not journalled when it
358** is extracted from the free-list and reused, then the original data
359** may be lost. In the event of a rollback, it may not be possible
360** to restore the database to its original configuration.
361**
362** The solution is the BtShared.pHasContent bitvec. Whenever a page is
363** moved to become a free-list leaf page, the corresponding bit is
364** set in the bitvec. Whenever a leaf page is extracted from the free-list,
365** optimization 2 above is ommitted if the corresponding bit is already
366** set in BtShared.pHasContent. The contents of the bitvec are cleared
367** at the end of every transaction.
368*/
369static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
370 int rc = SQLITE_OK;
371 if( !pBt->pHasContent ){
372 int nPage;
373 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
374 if( rc==SQLITE_OK ){
375 pBt->pHasContent = sqlite3BitvecCreate((u32)nPage);
376 if( !pBt->pHasContent ){
377 rc = SQLITE_NOMEM;
378 }
379 }
380 }
381 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
382 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
383 }
384 return rc;
385}
386
387/*
388** Query the BtShared.pHasContent vector.
389**
390** This function is called when a free-list leaf page is removed from the
391** free-list for reuse. It returns false if it is safe to retrieve the
392** page from the pager layer with the 'no-content' flag set. True otherwise.
393*/
394static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
395 Bitvec *p = pBt->pHasContent;
396 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
397}
398
399/*
400** Clear (destroy) the BtShared.pHasContent bitvec. This should be
401** invoked at the conclusion of each write-transaction.
402*/
403static void btreeClearHasContent(BtShared *pBt){
404 sqlite3BitvecDestroy(pBt->pHasContent);
405 pBt->pHasContent = 0;
406}
407
408/*
drh980b1a72006-08-16 16:42:48 +0000409** Save the current cursor position in the variables BtCursor.nKey
410** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
411*/
412static int saveCursorPosition(BtCursor *pCur){
413 int rc;
414
415 assert( CURSOR_VALID==pCur->eState );
416 assert( 0==pCur->pKey );
drh1fee73e2007-08-29 04:00:57 +0000417 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000418
419 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
420
421 /* If this is an intKey table, then the above call to BtreeKeySize()
422 ** stores the integer key in pCur->nKey. In this case this value is
423 ** all that is required. Otherwise, if pCur is not open on an intKey
424 ** table, then malloc space for and store the pCur->nKey bytes of key
425 ** data.
426 */
danielk197771d5d2c2008-09-29 11:49:47 +0000427 if( rc==SQLITE_OK && 0==pCur->apPage[0]->intKey){
drhf49661a2008-12-10 16:45:50 +0000428 void *pKey = sqlite3Malloc( (int)pCur->nKey );
drh980b1a72006-08-16 16:42:48 +0000429 if( pKey ){
drhf49661a2008-12-10 16:45:50 +0000430 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
drh980b1a72006-08-16 16:42:48 +0000431 if( rc==SQLITE_OK ){
432 pCur->pKey = pKey;
433 }else{
drh17435752007-08-16 04:30:38 +0000434 sqlite3_free(pKey);
drh980b1a72006-08-16 16:42:48 +0000435 }
436 }else{
437 rc = SQLITE_NOMEM;
438 }
439 }
danielk197771d5d2c2008-09-29 11:49:47 +0000440 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
drh980b1a72006-08-16 16:42:48 +0000441
442 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +0000443 int i;
444 for(i=0; i<=pCur->iPage; i++){
445 releasePage(pCur->apPage[i]);
446 pCur->apPage[i] = 0;
447 }
448 pCur->iPage = -1;
drh980b1a72006-08-16 16:42:48 +0000449 pCur->eState = CURSOR_REQUIRESEEK;
450 }
451
danielk197792d4d7a2007-05-04 12:05:56 +0000452 invalidateOverflowCache(pCur);
drh980b1a72006-08-16 16:42:48 +0000453 return rc;
454}
455
456/*
457** Save the positions of all cursors except pExcept open on the table
458** with root-page iRoot. Usually, this is called just before cursor
459** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
460*/
461static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
462 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000463 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +0000464 assert( pExcept==0 || pExcept->pBt==pBt );
drh980b1a72006-08-16 16:42:48 +0000465 for(p=pBt->pCursor; p; p=p->pNext){
466 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
467 p->eState==CURSOR_VALID ){
468 int rc = saveCursorPosition(p);
469 if( SQLITE_OK!=rc ){
470 return rc;
471 }
472 }
473 }
474 return SQLITE_OK;
475}
476
477/*
drhbf700f32007-03-31 02:36:44 +0000478** Clear the current cursor position.
479*/
danielk1977be51a652008-10-08 17:58:48 +0000480void sqlite3BtreeClearCursor(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000481 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000482 sqlite3_free(pCur->pKey);
drhbf700f32007-03-31 02:36:44 +0000483 pCur->pKey = 0;
484 pCur->eState = CURSOR_INVALID;
485}
486
487/*
drh980b1a72006-08-16 16:42:48 +0000488** Restore the cursor to the position it was in (or as close to as possible)
489** when saveCursorPosition() was called. Note that this call deletes the
490** saved position info stored by saveCursorPosition(), so there can be
drha3460582008-07-11 21:02:53 +0000491** at most one effective restoreCursorPosition() call after each
drh980b1a72006-08-16 16:42:48 +0000492** saveCursorPosition().
drh980b1a72006-08-16 16:42:48 +0000493*/
drha3460582008-07-11 21:02:53 +0000494int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +0000495 int rc;
drh1fee73e2007-08-29 04:00:57 +0000496 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +0000497 assert( pCur->eState>=CURSOR_REQUIRESEEK );
498 if( pCur->eState==CURSOR_FAULT ){
499 return pCur->skip;
500 }
drh980b1a72006-08-16 16:42:48 +0000501 pCur->eState = CURSOR_INVALID;
drhe63d9992008-08-13 19:11:48 +0000502 rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skip);
drh980b1a72006-08-16 16:42:48 +0000503 if( rc==SQLITE_OK ){
drh17435752007-08-16 04:30:38 +0000504 sqlite3_free(pCur->pKey);
drh980b1a72006-08-16 16:42:48 +0000505 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +0000506 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drh980b1a72006-08-16 16:42:48 +0000507 }
508 return rc;
509}
510
drha3460582008-07-11 21:02:53 +0000511#define restoreCursorPosition(p) \
drhfb982642007-08-30 01:19:59 +0000512 (p->eState>=CURSOR_REQUIRESEEK ? \
drha3460582008-07-11 21:02:53 +0000513 sqlite3BtreeRestoreCursorPosition(p) : \
drh16a9b832007-05-05 18:39:25 +0000514 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +0000515
drha3460582008-07-11 21:02:53 +0000516/*
517** Determine whether or not a cursor has moved from the position it
drhdfe88ec2008-11-03 20:55:06 +0000518** was last placed at. Cursors can move when the row they are pointing
drha3460582008-07-11 21:02:53 +0000519** at is deleted out from under them.
520**
521** This routine returns an error code if something goes wrong. The
522** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
523*/
524int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
525 int rc;
526
527 rc = restoreCursorPosition(pCur);
528 if( rc ){
529 *pHasMoved = 1;
530 return rc;
531 }
532 if( pCur->eState!=CURSOR_VALID || pCur->skip!=0 ){
533 *pHasMoved = 1;
534 }else{
535 *pHasMoved = 0;
536 }
537 return SQLITE_OK;
538}
539
danielk1977599fcba2004-11-08 07:13:13 +0000540#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000541/*
drha3152892007-05-05 11:48:52 +0000542** Given a page number of a regular database page, return the page
543** number for the pointer-map page that contains the entry for the
544** input page number.
danielk1977afcdd022004-10-31 16:25:42 +0000545*/
danielk1977266664d2006-02-10 08:24:21 +0000546static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
danielk197789d40042008-11-17 14:20:56 +0000547 int nPagesPerMapPage;
548 Pgno iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +0000549 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000550 nPagesPerMapPage = (pBt->usableSize/5)+1;
551 iPtrMap = (pgno-2)/nPagesPerMapPage;
552 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +0000553 if( ret==PENDING_BYTE_PAGE(pBt) ){
554 ret++;
555 }
556 return ret;
557}
danielk1977a19df672004-11-03 11:37:07 +0000558
danielk1977afcdd022004-10-31 16:25:42 +0000559/*
danielk1977afcdd022004-10-31 16:25:42 +0000560** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000561**
562** This routine updates the pointer map entry for page number 'key'
563** so that it maps to type 'eType' and parent page number 'pgno'.
564** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000565*/
danielk1977aef0bf62005-12-30 16:28:01 +0000566static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
danielk19773b8a05f2007-03-19 17:44:26 +0000567 DbPage *pDbPage; /* The pointer map page */
568 u8 *pPtrmap; /* The pointer map data */
569 Pgno iPtrmap; /* The pointer map page number */
570 int offset; /* Offset in pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000571 int rc;
572
drh1fee73e2007-08-29 04:00:57 +0000573 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977266664d2006-02-10 08:24:21 +0000574 /* The master-journal page number must never be used as a pointer map page */
575 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
576
danielk1977ac11ee62005-01-15 12:45:51 +0000577 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000578 if( key==0 ){
drh49285702005-09-17 15:20:26 +0000579 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000580 }
danielk1977266664d2006-02-10 08:24:21 +0000581 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000582 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977687566d2004-11-02 12:56:41 +0000583 if( rc!=SQLITE_OK ){
danielk1977afcdd022004-10-31 16:25:42 +0000584 return rc;
585 }
danielk19778c666b12008-07-18 09:34:57 +0000586 offset = PTRMAP_PTROFFSET(iPtrmap, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000587 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000588
drh615ae552005-01-16 23:21:00 +0000589 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
590 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
danielk19773b8a05f2007-03-19 17:44:26 +0000591 rc = sqlite3PagerWrite(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000592 if( rc==SQLITE_OK ){
593 pPtrmap[offset] = eType;
594 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000595 }
danielk1977afcdd022004-10-31 16:25:42 +0000596 }
597
danielk19773b8a05f2007-03-19 17:44:26 +0000598 sqlite3PagerUnref(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000599 return rc;
danielk1977afcdd022004-10-31 16:25:42 +0000600}
601
602/*
603** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000604**
605** This routine retrieves the pointer map entry for page 'key', writing
606** the type and parent page number to *pEType and *pPgno respectively.
607** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000608*/
danielk1977aef0bf62005-12-30 16:28:01 +0000609static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +0000610 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000611 int iPtrmap; /* Pointer map page index */
612 u8 *pPtrmap; /* Pointer map page data */
613 int offset; /* Offset of entry in pointer map */
614 int rc;
615
drh1fee73e2007-08-29 04:00:57 +0000616 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000617
danielk1977266664d2006-02-10 08:24:21 +0000618 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000619 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000620 if( rc!=0 ){
621 return rc;
622 }
danielk19773b8a05f2007-03-19 17:44:26 +0000623 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000624
danielk19778c666b12008-07-18 09:34:57 +0000625 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drh43617e92006-03-06 20:55:46 +0000626 assert( pEType!=0 );
627 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +0000628 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000629
danielk19773b8a05f2007-03-19 17:44:26 +0000630 sqlite3PagerUnref(pDbPage);
drh49285702005-09-17 15:20:26 +0000631 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000632 return SQLITE_OK;
633}
634
danielk197785d90ca2008-07-19 14:25:15 +0000635#else /* if defined SQLITE_OMIT_AUTOVACUUM */
636 #define ptrmapPut(w,x,y,z) SQLITE_OK
637 #define ptrmapGet(w,x,y,z) SQLITE_OK
638 #define ptrmapPutOvfl(y,z) SQLITE_OK
639#endif
danielk1977afcdd022004-10-31 16:25:42 +0000640
drh0d316a42002-08-11 20:10:47 +0000641/*
drh271efa52004-05-30 19:19:05 +0000642** Given a btree page and a cell index (0 means the first cell on
643** the page, 1 means the second cell, and so forth) return a pointer
644** to the cell content.
645**
646** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000647*/
drh1688c862008-07-18 02:44:17 +0000648#define findCell(P,I) \
649 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
drh43605152004-05-29 21:46:49 +0000650
651/*
drh93a960a2008-07-10 00:32:42 +0000652** This a more complex version of findCell() that works for
drh43605152004-05-29 21:46:49 +0000653** pages that do contain overflow cells. See insert
654*/
655static u8 *findOverflowCell(MemPage *pPage, int iCell){
656 int i;
drh1fee73e2007-08-29 04:00:57 +0000657 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +0000658 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000659 int k;
660 struct _OvflCell *pOvfl;
661 pOvfl = &pPage->aOvfl[i];
662 k = pOvfl->idx;
663 if( k<=iCell ){
664 if( k==iCell ){
665 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000666 }
667 iCell--;
668 }
669 }
danielk19771cc5ed82007-05-16 17:28:43 +0000670 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000671}
672
673/*
674** Parse a cell content block and fill in the CellInfo structure. There
drh16a9b832007-05-05 18:39:25 +0000675** are two versions of this function. sqlite3BtreeParseCell() takes a
676** cell index as the second argument and sqlite3BtreeParseCellPtr()
677** takes a pointer to the body of the cell as its second argument.
danielk19771cc5ed82007-05-16 17:28:43 +0000678**
679** Within this file, the parseCell() macro can be called instead of
680** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
drh43605152004-05-29 21:46:49 +0000681*/
drh16a9b832007-05-05 18:39:25 +0000682void sqlite3BtreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000683 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000684 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000685 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000686){
drhf49661a2008-12-10 16:45:50 +0000687 u16 n; /* Number bytes in cell content header */
drh271efa52004-05-30 19:19:05 +0000688 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000689
drh1fee73e2007-08-29 04:00:57 +0000690 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000691
drh43605152004-05-29 21:46:49 +0000692 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000693 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000694 n = pPage->childPtrSize;
695 assert( n==4-4*pPage->leaf );
drh504b6982006-01-22 21:52:56 +0000696 if( pPage->intKey ){
drh79df1f42008-07-18 00:57:33 +0000697 if( pPage->hasData ){
698 n += getVarint32(&pCell[n], nPayload);
699 }else{
700 nPayload = 0;
701 }
drh1bd10f82008-12-10 21:19:56 +0000702 n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
drh79df1f42008-07-18 00:57:33 +0000703 pInfo->nData = nPayload;
drh504b6982006-01-22 21:52:56 +0000704 }else{
drh79df1f42008-07-18 00:57:33 +0000705 pInfo->nData = 0;
706 n += getVarint32(&pCell[n], nPayload);
707 pInfo->nKey = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000708 }
drh72365832007-03-06 15:53:44 +0000709 pInfo->nPayload = nPayload;
drh504b6982006-01-22 21:52:56 +0000710 pInfo->nHeader = n;
drh79df1f42008-07-18 00:57:33 +0000711 if( likely(nPayload<=pPage->maxLocal) ){
drh271efa52004-05-30 19:19:05 +0000712 /* This is the (easy) common case where the entire payload fits
713 ** on the local page. No overflow is required.
714 */
715 int nSize; /* Total size of cell content in bytes */
drh79df1f42008-07-18 00:57:33 +0000716 nSize = nPayload + n;
drhf49661a2008-12-10 16:45:50 +0000717 pInfo->nLocal = (u16)nPayload;
drh6f11bef2004-05-13 01:12:56 +0000718 pInfo->iOverflow = 0;
drh79df1f42008-07-18 00:57:33 +0000719 if( (nSize & ~3)==0 ){
drh271efa52004-05-30 19:19:05 +0000720 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000721 }
drh1bd10f82008-12-10 21:19:56 +0000722 pInfo->nSize = (u16)nSize;
drh6f11bef2004-05-13 01:12:56 +0000723 }else{
drh271efa52004-05-30 19:19:05 +0000724 /* If the payload will not fit completely on the local page, we have
725 ** to decide how much to store locally and how much to spill onto
726 ** overflow pages. The strategy is to minimize the amount of unused
727 ** space on overflow pages while keeping the amount of local storage
728 ** in between minLocal and maxLocal.
729 **
730 ** Warning: changing the way overflow payload is distributed in any
731 ** way will result in an incompatible file format.
732 */
733 int minLocal; /* Minimum amount of payload held locally */
734 int maxLocal; /* Maximum amount of payload held locally */
735 int surplus; /* Overflow payload available for local storage */
736
737 minLocal = pPage->minLocal;
738 maxLocal = pPage->maxLocal;
739 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000740 if( surplus <= maxLocal ){
drhf49661a2008-12-10 16:45:50 +0000741 pInfo->nLocal = (u16)surplus;
drh6f11bef2004-05-13 01:12:56 +0000742 }else{
drhf49661a2008-12-10 16:45:50 +0000743 pInfo->nLocal = (u16)minLocal;
drh6f11bef2004-05-13 01:12:56 +0000744 }
drhf49661a2008-12-10 16:45:50 +0000745 pInfo->iOverflow = (u16)(pInfo->nLocal + n);
drh6f11bef2004-05-13 01:12:56 +0000746 pInfo->nSize = pInfo->iOverflow + 4;
747 }
drh3aac2dd2004-04-26 14:10:20 +0000748}
danielk19771cc5ed82007-05-16 17:28:43 +0000749#define parseCell(pPage, iCell, pInfo) \
750 sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
drh16a9b832007-05-05 18:39:25 +0000751void sqlite3BtreeParseCell(
drh43605152004-05-29 21:46:49 +0000752 MemPage *pPage, /* Page containing the cell */
753 int iCell, /* The cell index. First cell is 0 */
754 CellInfo *pInfo /* Fill in this structure */
755){
danielk19771cc5ed82007-05-16 17:28:43 +0000756 parseCell(pPage, iCell, pInfo);
drh43605152004-05-29 21:46:49 +0000757}
drh3aac2dd2004-04-26 14:10:20 +0000758
759/*
drh43605152004-05-29 21:46:49 +0000760** Compute the total number of bytes that a Cell needs in the cell
761** data area of the btree-page. The return number includes the cell
762** data header and the local payload, but not any overflow page or
763** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000764*/
danielk1977bc6ada42004-06-30 08:20:16 +0000765#ifndef NDEBUG
drha9121e42008-02-19 14:59:35 +0000766static u16 cellSize(MemPage *pPage, int iCell){
drh6f11bef2004-05-13 01:12:56 +0000767 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000768 sqlite3BtreeParseCell(pPage, iCell, &info);
drh43605152004-05-29 21:46:49 +0000769 return info.nSize;
770}
danielk1977bc6ada42004-06-30 08:20:16 +0000771#endif
drha9121e42008-02-19 14:59:35 +0000772static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
drh43605152004-05-29 21:46:49 +0000773 CellInfo info;
drh16a9b832007-05-05 18:39:25 +0000774 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +0000775 return info.nSize;
drh3b7511c2001-05-26 13:15:44 +0000776}
777
danielk197779a40da2005-01-16 08:00:01 +0000778#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +0000779/*
danielk197726836652005-01-17 01:33:13 +0000780** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +0000781** to an overflow page, insert an entry into the pointer-map
782** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +0000783*/
danielk197726836652005-01-17 01:33:13 +0000784static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
drhfa67c3c2008-07-11 02:21:40 +0000785 CellInfo info;
786 assert( pCell!=0 );
787 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
788 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
789 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
790 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
791 return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +0000792 }
danielk197779a40da2005-01-16 08:00:01 +0000793 return SQLITE_OK;
danielk1977ac11ee62005-01-15 12:45:51 +0000794}
danielk197726836652005-01-17 01:33:13 +0000795/*
796** If the cell with index iCell on page pPage contains a pointer
797** to an overflow page, insert an entry into the pointer-map
798** for the overflow page.
799*/
800static int ptrmapPutOvfl(MemPage *pPage, int iCell){
801 u8 *pCell;
drh1fee73e2007-08-29 04:00:57 +0000802 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197726836652005-01-17 01:33:13 +0000803 pCell = findOverflowCell(pPage, iCell);
804 return ptrmapPutOvflPtr(pPage, pCell);
805}
danielk197779a40da2005-01-16 08:00:01 +0000806#endif
807
danielk1977ac11ee62005-01-15 12:45:51 +0000808
drhda200cc2004-05-09 11:51:38 +0000809/*
drh72f82862001-05-24 21:06:34 +0000810** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +0000811** end of the page and all free space is collected into one
812** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +0000813** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +0000814*/
shane0af3f892008-11-12 04:55:34 +0000815static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000816 int i; /* Loop counter */
817 int pc; /* Address of a i-th cell */
818 int addr; /* Offset of first byte after cell pointer array */
819 int hdr; /* Offset to the page header */
820 int size; /* Size of a cell */
821 int usableSize; /* Number of usable bytes on a page */
822 int cellOffset; /* Offset to the cell pointer array */
drh281b21d2008-08-22 12:57:08 +0000823 int cbrk; /* Offset to the cell content area */
drh43605152004-05-29 21:46:49 +0000824 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +0000825 unsigned char *data; /* The page data */
826 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +0000827
danielk19773b8a05f2007-03-19 17:44:26 +0000828 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000829 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +0000830 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000831 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +0000832 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh26b79942007-11-28 16:19:56 +0000833 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
drh43605152004-05-29 21:46:49 +0000834 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +0000835 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +0000836 cellOffset = pPage->cellOffset;
837 nCell = pPage->nCell;
838 assert( nCell==get2byte(&data[hdr+3]) );
839 usableSize = pPage->pBt->usableSize;
drh281b21d2008-08-22 12:57:08 +0000840 cbrk = get2byte(&data[hdr+5]);
841 memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
842 cbrk = usableSize;
drh43605152004-05-29 21:46:49 +0000843 for(i=0; i<nCell; i++){
844 u8 *pAddr; /* The i-th cell pointer */
845 pAddr = &data[cellOffset + i*2];
846 pc = get2byte(pAddr);
shanedcc50b72008-11-13 18:29:50 +0000847 if( pc>=usableSize ){
shane0af3f892008-11-12 04:55:34 +0000848 return SQLITE_CORRUPT_BKPT;
849 }
drh43605152004-05-29 21:46:49 +0000850 size = cellSizePtr(pPage, &temp[pc]);
drh281b21d2008-08-22 12:57:08 +0000851 cbrk -= size;
danielk19770d065412008-11-12 18:21:36 +0000852 if( cbrk<cellOffset+2*nCell || pc+size>usableSize ){
shane0af3f892008-11-12 04:55:34 +0000853 return SQLITE_CORRUPT_BKPT;
854 }
danielk19770d065412008-11-12 18:21:36 +0000855 assert( cbrk+size<=usableSize && cbrk>=0 );
drh281b21d2008-08-22 12:57:08 +0000856 memcpy(&data[cbrk], &temp[pc], size);
857 put2byte(pAddr, cbrk);
drh2af926b2001-05-15 00:39:25 +0000858 }
drh281b21d2008-08-22 12:57:08 +0000859 assert( cbrk>=cellOffset+2*nCell );
860 put2byte(&data[hdr+5], cbrk);
drh43605152004-05-29 21:46:49 +0000861 data[hdr+1] = 0;
862 data[hdr+2] = 0;
863 data[hdr+7] = 0;
864 addr = cellOffset+2*nCell;
drh281b21d2008-08-22 12:57:08 +0000865 memset(&data[addr], 0, cbrk-addr);
drhc5053fb2008-11-27 02:22:10 +0000866 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977360e6342008-11-12 08:49:51 +0000867 if( cbrk-addr!=pPage->nFree ){
868 return SQLITE_CORRUPT_BKPT;
869 }
shane0af3f892008-11-12 04:55:34 +0000870 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +0000871}
872
drha059ad02001-04-17 20:09:11 +0000873/*
danielk19776011a752009-04-01 16:25:32 +0000874** Allocate nByte bytes of space from within the B-Tree page passed
875** as the first argument. Return the index into pPage->aData[] of the
876** first byte of allocated space.
drhbd03cae2001-06-02 02:40:57 +0000877**
danielk19776011a752009-04-01 16:25:32 +0000878** The caller guarantees that the space between the end of the cell-offset
879** array and the start of the cell-content area is at least nByte bytes
880** in size. So this routine can never fail.
drh2af926b2001-05-15 00:39:25 +0000881**
danielk19776011a752009-04-01 16:25:32 +0000882** If there are already 60 or more bytes of fragments within the page,
883** the page is defragmented before returning. If this were not done there
884** is a chance that the number of fragmented bytes could eventually
885** overflow the single-byte field of the page-header in which this value
886** is stored.
drh7e3b0a02001-04-28 16:52:40 +0000887*/
drh9e572e62004-04-23 23:43:10 +0000888static int allocateSpace(MemPage *pPage, int nByte){
danielk19776011a752009-04-01 16:25:32 +0000889 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
890 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
891 int nFrag; /* Number of fragmented bytes on pPage */
drh43605152004-05-29 21:46:49 +0000892 int top;
drh43605152004-05-29 21:46:49 +0000893
danielk19773b8a05f2007-03-19 17:44:26 +0000894 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000895 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +0000896 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa67c3c2008-07-11 02:21:40 +0000897 assert( nByte>=0 ); /* Minimum cell size is 4 */
898 assert( pPage->nFree>=nByte );
899 assert( pPage->nOverflow==0 );
drh43605152004-05-29 21:46:49 +0000900
danielk19776011a752009-04-01 16:25:32 +0000901 /* Assert that the space between the cell-offset array and the
902 ** cell-content area is greater than nByte bytes.
903 */
904 assert( nByte <= (
905 get2byte(&data[hdr+5])-(hdr+8+(pPage->leaf?0:4)+2*get2byte(&data[hdr+3]))
906 ));
907
908 pPage->nFree -= (u16)nByte;
drh43605152004-05-29 21:46:49 +0000909 nFrag = data[hdr+7];
danielk19776011a752009-04-01 16:25:32 +0000910 if( nFrag>=60 ){
911 defragmentPage(pPage);
912 }else{
913 /* Search the freelist looking for a free slot big enough to satisfy
914 ** the request. The allocation is made from the first free slot in
915 ** the list that is large enough to accomadate it.
916 */
917 int pc, addr;
918 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
919 int size = get2byte(&data[pc+2]); /* Size of free slot */
drh43605152004-05-29 21:46:49 +0000920 if( size>=nByte ){
drhf49661a2008-12-10 16:45:50 +0000921 int x = size - nByte;
danielk19776011a752009-04-01 16:25:32 +0000922 if( x<4 ){
923 /* Remove the slot from the free-list. Update the number of
924 ** fragmented bytes within the page. */
drh43605152004-05-29 21:46:49 +0000925 memcpy(&data[addr], &data[pc], 2);
drhf49661a2008-12-10 16:45:50 +0000926 data[hdr+7] = (u8)(nFrag + x);
drh43605152004-05-29 21:46:49 +0000927 }else{
danielk19776011a752009-04-01 16:25:32 +0000928 /* The slot remains on the free-list. Reduce its size to account
929 ** for the portion used by the new allocation. */
drhf49661a2008-12-10 16:45:50 +0000930 put2byte(&data[pc+2], x);
drh43605152004-05-29 21:46:49 +0000931 }
danielk19776011a752009-04-01 16:25:32 +0000932 return pc + x;
drh43605152004-05-29 21:46:49 +0000933 }
drh9e572e62004-04-23 23:43:10 +0000934 }
935 }
drh43605152004-05-29 21:46:49 +0000936
937 /* Allocate memory from the gap in between the cell pointer array
938 ** and the cell content area.
939 */
danielk19776011a752009-04-01 16:25:32 +0000940 top = get2byte(&data[hdr+5]) - nByte;
drh43605152004-05-29 21:46:49 +0000941 put2byte(&data[hdr+5], top);
942 return top;
drh7e3b0a02001-04-28 16:52:40 +0000943}
944
945/*
drh9e572e62004-04-23 23:43:10 +0000946** Return a section of the pPage->aData to the freelist.
947** The first byte of the new free block is pPage->aDisk[start]
948** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +0000949**
950** Most of the effort here is involved in coalesing adjacent
951** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +0000952*/
shanedcc50b72008-11-13 18:29:50 +0000953static int freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +0000954 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +0000955 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +0000956
drh9e572e62004-04-23 23:43:10 +0000957 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +0000958 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000959 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +0000960 assert( (start + size)<=pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +0000961 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh34004ce2008-07-11 16:15:17 +0000962 assert( size>=0 ); /* Minimum cell size is 4 */
drh9e572e62004-04-23 23:43:10 +0000963
drhfcce93f2006-02-22 03:08:32 +0000964#ifdef SQLITE_SECURE_DELETE
965 /* Overwrite deleted information with zeros when the SECURE_DELETE
966 ** option is enabled at compile-time */
967 memset(&data[start], 0, size);
968#endif
969
drh9e572e62004-04-23 23:43:10 +0000970 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +0000971 hdr = pPage->hdrOffset;
972 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +0000973 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +0000974 assert( pbegin<=pPage->pBt->usableSize-4 );
shanedcc50b72008-11-13 18:29:50 +0000975 if( pbegin<=addr ) {
976 return SQLITE_CORRUPT_BKPT;
977 }
drh3aac2dd2004-04-26 14:10:20 +0000978 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +0000979 }
shanedcc50b72008-11-13 18:29:50 +0000980 if ( pbegin>pPage->pBt->usableSize-4 ) {
981 return SQLITE_CORRUPT_BKPT;
982 }
drh3aac2dd2004-04-26 14:10:20 +0000983 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +0000984 put2byte(&data[addr], start);
985 put2byte(&data[start], pbegin);
986 put2byte(&data[start+2], size);
drhf49661a2008-12-10 16:45:50 +0000987 pPage->nFree += (u16)size;
drh9e572e62004-04-23 23:43:10 +0000988
989 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +0000990 addr = pPage->hdrOffset + 1;
991 while( (pbegin = get2byte(&data[addr]))>0 ){
drhf49661a2008-12-10 16:45:50 +0000992 int pnext, psize, x;
drh3aac2dd2004-04-26 14:10:20 +0000993 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +0000994 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +0000995 pnext = get2byte(&data[pbegin]);
996 psize = get2byte(&data[pbegin+2]);
997 if( pbegin + psize + 3 >= pnext && pnext>0 ){
998 int frag = pnext - (pbegin+psize);
drhf49661a2008-12-10 16:45:50 +0000999 if( (frag<0) || (frag>(int)data[pPage->hdrOffset+7]) ){
shanedcc50b72008-11-13 18:29:50 +00001000 return SQLITE_CORRUPT_BKPT;
1001 }
drhf49661a2008-12-10 16:45:50 +00001002 data[pPage->hdrOffset+7] -= (u8)frag;
1003 x = get2byte(&data[pnext]);
1004 put2byte(&data[pbegin], x);
1005 x = pnext + get2byte(&data[pnext+2]) - pbegin;
1006 put2byte(&data[pbegin+2], x);
drh9e572e62004-04-23 23:43:10 +00001007 }else{
drh3aac2dd2004-04-26 14:10:20 +00001008 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +00001009 }
1010 }
drh7e3b0a02001-04-28 16:52:40 +00001011
drh43605152004-05-29 21:46:49 +00001012 /* If the cell content area begins with a freeblock, remove it. */
1013 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
1014 int top;
1015 pbegin = get2byte(&data[hdr+1]);
1016 memcpy(&data[hdr+1], &data[pbegin], 2);
drhf49661a2008-12-10 16:45:50 +00001017 top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
1018 put2byte(&data[hdr+5], top);
drh4b70f112004-05-02 21:12:19 +00001019 }
drhc5053fb2008-11-27 02:22:10 +00001020 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
shanedcc50b72008-11-13 18:29:50 +00001021 return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00001022}
1023
1024/*
drh271efa52004-05-30 19:19:05 +00001025** Decode the flags byte (the first byte of the header) for a page
1026** and initialize fields of the MemPage structure accordingly.
drh44845222008-07-17 18:39:57 +00001027**
1028** Only the following combinations are supported. Anything different
1029** indicates a corrupt database files:
1030**
1031** PTF_ZERODATA
1032** PTF_ZERODATA | PTF_LEAF
1033** PTF_LEAFDATA | PTF_INTKEY
1034** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
drh271efa52004-05-30 19:19:05 +00001035*/
drh44845222008-07-17 18:39:57 +00001036static int decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +00001037 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +00001038
1039 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +00001040 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00001041 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
drh44845222008-07-17 18:39:57 +00001042 flagByte &= ~PTF_LEAF;
1043 pPage->childPtrSize = 4-4*pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001044 pBt = pPage->pBt;
drh44845222008-07-17 18:39:57 +00001045 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
1046 pPage->intKey = 1;
1047 pPage->hasData = pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001048 pPage->maxLocal = pBt->maxLeaf;
1049 pPage->minLocal = pBt->minLeaf;
drh44845222008-07-17 18:39:57 +00001050 }else if( flagByte==PTF_ZERODATA ){
1051 pPage->intKey = 0;
1052 pPage->hasData = 0;
drh271efa52004-05-30 19:19:05 +00001053 pPage->maxLocal = pBt->maxLocal;
1054 pPage->minLocal = pBt->minLocal;
drh44845222008-07-17 18:39:57 +00001055 }else{
1056 return SQLITE_CORRUPT_BKPT;
drh271efa52004-05-30 19:19:05 +00001057 }
drh44845222008-07-17 18:39:57 +00001058 return SQLITE_OK;
drh271efa52004-05-30 19:19:05 +00001059}
1060
1061/*
drh7e3b0a02001-04-28 16:52:40 +00001062** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +00001063**
1064** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +00001065** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +00001066** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1067** guarantee that the page is well-formed. It only shows that
1068** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001069*/
danielk197771d5d2c2008-09-29 11:49:47 +00001070int sqlite3BtreeInitPage(MemPage *pPage){
drh2af926b2001-05-15 00:39:25 +00001071
danielk197771d5d2c2008-09-29 11:49:47 +00001072 assert( pPage->pBt!=0 );
1073 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001074 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +00001075 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1076 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00001077
1078 if( !pPage->isInit ){
drhf49661a2008-12-10 16:45:50 +00001079 u16 pc; /* Address of a freeblock within pPage->aData[] */
1080 u8 hdr; /* Offset to beginning of page header */
danielk197771d5d2c2008-09-29 11:49:47 +00001081 u8 *data; /* Equal to pPage->aData */
1082 BtShared *pBt; /* The main btree structure */
drhf49661a2008-12-10 16:45:50 +00001083 u16 usableSize; /* Amount of usable space on each page */
1084 u16 cellOffset; /* Offset from start of page to first cell pointer */
1085 u16 nFree; /* Number of unused bytes on the page */
1086 u16 top; /* First byte of the cell content area */
danielk197771d5d2c2008-09-29 11:49:47 +00001087
1088 pBt = pPage->pBt;
1089
danielk1977eaa06f62008-09-18 17:34:44 +00001090 hdr = pPage->hdrOffset;
1091 data = pPage->aData;
1092 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
1093 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
1094 pPage->maskPage = pBt->pageSize - 1;
1095 pPage->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00001096 usableSize = pBt->usableSize;
1097 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
1098 top = get2byte(&data[hdr+5]);
1099 pPage->nCell = get2byte(&data[hdr+3]);
1100 if( pPage->nCell>MX_CELL(pBt) ){
1101 /* To many cells for a single page. The page must be corrupt */
1102 return SQLITE_CORRUPT_BKPT;
1103 }
danielk1977eaa06f62008-09-18 17:34:44 +00001104
1105 /* Compute the total free space on the page */
1106 pc = get2byte(&data[hdr+1]);
1107 nFree = data[hdr+7] + top - (cellOffset + 2*pPage->nCell);
1108 while( pc>0 ){
drh1bd10f82008-12-10 21:19:56 +00001109 u16 next, size;
danielk1977eaa06f62008-09-18 17:34:44 +00001110 if( pc>usableSize-4 ){
1111 /* Free block is off the page */
1112 return SQLITE_CORRUPT_BKPT;
1113 }
1114 next = get2byte(&data[pc]);
1115 size = get2byte(&data[pc+2]);
1116 if( next>0 && next<=pc+size+3 ){
1117 /* Free blocks must be in accending order */
1118 return SQLITE_CORRUPT_BKPT;
1119 }
1120 nFree += size;
1121 pc = next;
1122 }
drhf49661a2008-12-10 16:45:50 +00001123 pPage->nFree = (u16)nFree;
danielk1977eaa06f62008-09-18 17:34:44 +00001124 if( nFree>=usableSize ){
1125 /* Free space cannot exceed total page size */
drh49285702005-09-17 15:20:26 +00001126 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001127 }
drh9e572e62004-04-23 23:43:10 +00001128
drh1688c862008-07-18 02:44:17 +00001129#if 0
1130 /* Check that all the offsets in the cell offset array are within range.
1131 **
1132 ** Omitting this consistency check and using the pPage->maskPage mask
1133 ** to prevent overrunning the page buffer in findCell() results in a
1134 ** 2.5% performance gain.
1135 */
1136 {
1137 u8 *pOff; /* Iterator used to check all cell offsets are in range */
1138 u8 *pEnd; /* Pointer to end of cell offset array */
1139 u8 mask; /* Mask of bits that must be zero in MSB of cell offsets */
1140 mask = ~(((u8)(pBt->pageSize>>8))-1);
1141 pEnd = &data[cellOffset + pPage->nCell*2];
1142 for(pOff=&data[cellOffset]; pOff!=pEnd && !((*pOff)&mask); pOff+=2);
1143 if( pOff!=pEnd ){
1144 return SQLITE_CORRUPT_BKPT;
1145 }
danielk1977e16535f2008-06-11 18:15:29 +00001146 }
drh1688c862008-07-18 02:44:17 +00001147#endif
danielk1977e16535f2008-06-11 18:15:29 +00001148
danielk197771d5d2c2008-09-29 11:49:47 +00001149 pPage->isInit = 1;
1150 }
drh9e572e62004-04-23 23:43:10 +00001151 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001152}
1153
1154/*
drh8b2f49b2001-06-08 00:21:52 +00001155** Set up a raw page so that it looks like a database page holding
1156** no entries.
drhbd03cae2001-06-02 02:40:57 +00001157*/
drh9e572e62004-04-23 23:43:10 +00001158static void zeroPage(MemPage *pPage, int flags){
1159 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001160 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00001161 u8 hdr = pPage->hdrOffset;
1162 u16 first;
drh9e572e62004-04-23 23:43:10 +00001163
danielk19773b8a05f2007-03-19 17:44:26 +00001164 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drhbf4bca52007-09-06 22:19:14 +00001165 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1166 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +00001167 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00001168 assert( sqlite3_mutex_held(pBt->mutex) );
drh1af4a6e2008-07-18 03:32:51 +00001169 /*memset(&data[hdr], 0, pBt->usableSize - hdr);*/
drh1bd10f82008-12-10 21:19:56 +00001170 data[hdr] = (char)flags;
1171 first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
drh43605152004-05-29 21:46:49 +00001172 memset(&data[hdr+1], 0, 4);
1173 data[hdr+7] = 0;
1174 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +00001175 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +00001176 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +00001177 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +00001178 pPage->cellOffset = first;
1179 pPage->nOverflow = 0;
drh1688c862008-07-18 02:44:17 +00001180 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
1181 pPage->maskPage = pBt->pageSize - 1;
drh43605152004-05-29 21:46:49 +00001182 pPage->nCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001183 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00001184}
1185
drh897a8202008-09-18 01:08:15 +00001186
1187/*
1188** Convert a DbPage obtained from the pager into a MemPage used by
1189** the btree layer.
1190*/
1191static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
1192 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
1193 pPage->aData = sqlite3PagerGetData(pDbPage);
1194 pPage->pDbPage = pDbPage;
1195 pPage->pBt = pBt;
1196 pPage->pgno = pgno;
1197 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
1198 return pPage;
1199}
1200
drhbd03cae2001-06-02 02:40:57 +00001201/*
drh3aac2dd2004-04-26 14:10:20 +00001202** Get a page from the pager. Initialize the MemPage.pBt and
1203** MemPage.aData elements if needed.
drh538f5702007-04-13 02:14:30 +00001204**
1205** If the noContent flag is set, it means that we do not care about
1206** the content of the page at this time. So do not go to the disk
1207** to fetch the content. Just fill in the content with zeros for now.
1208** If in the future we call sqlite3PagerWrite() on this page, that
1209** means we have started to be concerned about content and the disk
1210** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00001211*/
drh16a9b832007-05-05 18:39:25 +00001212int sqlite3BtreeGetPage(
1213 BtShared *pBt, /* The btree */
1214 Pgno pgno, /* Number of the page to fetch */
1215 MemPage **ppPage, /* Return the page in this parameter */
1216 int noContent /* Do not load page content if true */
1217){
drh3aac2dd2004-04-26 14:10:20 +00001218 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001219 DbPage *pDbPage;
1220
drh1fee73e2007-08-29 04:00:57 +00001221 assert( sqlite3_mutex_held(pBt->mutex) );
drh538f5702007-04-13 02:14:30 +00001222 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
drh3aac2dd2004-04-26 14:10:20 +00001223 if( rc ) return rc;
drh897a8202008-09-18 01:08:15 +00001224 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
drh3aac2dd2004-04-26 14:10:20 +00001225 return SQLITE_OK;
1226}
1227
1228/*
danielk1977bea2a942009-01-20 17:06:27 +00001229** Retrieve a page from the pager cache. If the requested page is not
1230** already in the pager cache return NULL. Initialize the MemPage.pBt and
1231** MemPage.aData elements if needed.
1232*/
1233static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
1234 DbPage *pDbPage;
1235 assert( sqlite3_mutex_held(pBt->mutex) );
1236 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
1237 if( pDbPage ){
1238 return btreePageFromDbPage(pDbPage, pgno, pBt);
1239 }
1240 return 0;
1241}
1242
1243/*
danielk197789d40042008-11-17 14:20:56 +00001244** Return the size of the database file in pages. If there is any kind of
1245** error, return ((unsigned int)-1).
danielk197767fd7a92008-09-10 17:53:35 +00001246*/
danielk197789d40042008-11-17 14:20:56 +00001247static Pgno pagerPagecount(BtShared *pBt){
1248 int nPage = -1;
danielk197767fd7a92008-09-10 17:53:35 +00001249 int rc;
danielk197789d40042008-11-17 14:20:56 +00001250 assert( pBt->pPage1 );
1251 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1252 assert( rc==SQLITE_OK || nPage==-1 );
1253 return (Pgno)nPage;
danielk197767fd7a92008-09-10 17:53:35 +00001254}
1255
1256/*
drhde647132004-05-07 17:57:49 +00001257** Get a page from the pager and initialize it. This routine
1258** is just a convenience wrapper around separate calls to
drh16a9b832007-05-05 18:39:25 +00001259** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
drhde647132004-05-07 17:57:49 +00001260*/
1261static int getAndInitPage(
danielk1977aef0bf62005-12-30 16:28:01 +00001262 BtShared *pBt, /* The database file */
drhde647132004-05-07 17:57:49 +00001263 Pgno pgno, /* Number of the page to get */
danielk197771d5d2c2008-09-29 11:49:47 +00001264 MemPage **ppPage /* Write the page pointer here */
drhde647132004-05-07 17:57:49 +00001265){
1266 int rc;
drh897a8202008-09-18 01:08:15 +00001267 MemPage *pPage;
1268
drh1fee73e2007-08-29 04:00:57 +00001269 assert( sqlite3_mutex_held(pBt->mutex) );
drh897a8202008-09-18 01:08:15 +00001270 if( pgno==0 ){
drh49285702005-09-17 15:20:26 +00001271 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001272 }
danielk19779f580ad2008-09-10 14:45:57 +00001273
drh897a8202008-09-18 01:08:15 +00001274 /* It is often the case that the page we want is already in cache.
1275 ** If so, get it directly. This saves us from having to call
1276 ** pagerPagecount() to make sure pgno is within limits, which results
1277 ** in a measureable performance improvements.
1278 */
danielk1977bea2a942009-01-20 17:06:27 +00001279 *ppPage = pPage = btreePageLookup(pBt, pgno);
1280 if( pPage ){
drh897a8202008-09-18 01:08:15 +00001281 /* Page is already in cache */
drh897a8202008-09-18 01:08:15 +00001282 rc = SQLITE_OK;
1283 }else{
1284 /* Page not in cache. Acquire it. */
danielk197789d40042008-11-17 14:20:56 +00001285 if( pgno>pagerPagecount(pBt) ){
drh897a8202008-09-18 01:08:15 +00001286 return SQLITE_CORRUPT_BKPT;
1287 }
1288 rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
1289 if( rc ) return rc;
1290 pPage = *ppPage;
1291 }
danielk197771d5d2c2008-09-29 11:49:47 +00001292 if( !pPage->isInit ){
1293 rc = sqlite3BtreeInitPage(pPage);
drh897a8202008-09-18 01:08:15 +00001294 }
1295 if( rc!=SQLITE_OK ){
1296 releasePage(pPage);
1297 *ppPage = 0;
1298 }
drhde647132004-05-07 17:57:49 +00001299 return rc;
1300}
1301
1302/*
drh3aac2dd2004-04-26 14:10:20 +00001303** Release a MemPage. This should be called once for each prior
drh16a9b832007-05-05 18:39:25 +00001304** call to sqlite3BtreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +00001305*/
drh4b70f112004-05-02 21:12:19 +00001306static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001307 if( pPage ){
drh30df0092008-12-23 15:58:06 +00001308 assert( pPage->nOverflow==0 || sqlite3PagerPageRefcount(pPage->pDbPage)>1 );
drh3aac2dd2004-04-26 14:10:20 +00001309 assert( pPage->aData );
1310 assert( pPage->pBt );
drhbf4bca52007-09-06 22:19:14 +00001311 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1312 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
drh1fee73e2007-08-29 04:00:57 +00001313 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001314 sqlite3PagerUnref(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00001315 }
1316}
1317
1318/*
drha6abd042004-06-09 17:37:22 +00001319** During a rollback, when the pager reloads information into the cache
1320** so that the cache is restored to its original state at the start of
1321** the transaction, for each page restored this routine is called.
1322**
1323** This routine needs to reset the extra data section at the end of the
1324** page to agree with the restored data.
1325*/
danielk1977eaa06f62008-09-18 17:34:44 +00001326static void pageReinit(DbPage *pData){
drh07d183d2005-05-01 22:52:42 +00001327 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00001328 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
danielk1977d217e6f2009-04-01 17:13:51 +00001329 assert( sqlite3PagerPageRefcount(pData)>0 );
danielk197771d5d2c2008-09-29 11:49:47 +00001330 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00001331 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00001332 pPage->isInit = 0;
danielk1977d217e6f2009-04-01 17:13:51 +00001333 if( sqlite3PagerPageRefcount(pData)>1 ){
drh5e8d8872009-03-30 17:19:48 +00001334 /* pPage might not be a btree page; it might be an overflow page
1335 ** or ptrmap page or a free page. In those cases, the following
1336 ** call to sqlite3BtreeInitPage() will likely return SQLITE_CORRUPT.
1337 ** But no harm is done by this. And it is very important that
1338 ** sqlite3BtreeInitPage() be called on every btree page so we make
1339 ** the call for every page that comes in for re-initing. */
danielk197771d5d2c2008-09-29 11:49:47 +00001340 sqlite3BtreeInitPage(pPage);
1341 }
drha6abd042004-06-09 17:37:22 +00001342 }
1343}
1344
1345/*
drhe5fe6902007-12-07 18:55:28 +00001346** Invoke the busy handler for a btree.
1347*/
danielk19771ceedd32008-11-19 10:22:33 +00001348static int btreeInvokeBusyHandler(void *pArg){
drhe5fe6902007-12-07 18:55:28 +00001349 BtShared *pBt = (BtShared*)pArg;
1350 assert( pBt->db );
1351 assert( sqlite3_mutex_held(pBt->db->mutex) );
1352 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
1353}
1354
1355/*
drhad3e0102004-09-03 23:32:18 +00001356** Open a database file.
1357**
drh382c0242001-10-06 16:33:02 +00001358** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001359** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001360** database file will be deleted when sqlite3BtreeClose() is called.
drhe53831d2007-08-17 01:14:38 +00001361** If zFilename is ":memory:" then an in-memory database is created
1362** that is automatically destroyed when it is closed.
drha059ad02001-04-17 20:09:11 +00001363*/
drh23e11ca2004-05-04 17:27:28 +00001364int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001365 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00001366 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001367 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00001368 int flags, /* Options */
1369 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00001370){
drh7555d8e2009-03-20 13:15:30 +00001371 sqlite3_vfs *pVfs; /* The VFS to use for this btree */
1372 BtShared *pBt = 0; /* Shared part of btree structure */
1373 Btree *p; /* Handle to return */
1374 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
1375 int rc = SQLITE_OK; /* Result code from this function */
1376 u8 nReserve; /* Byte of unused space on each page */
1377 unsigned char zDbHeader[100]; /* Database header content */
danielk1977aef0bf62005-12-30 16:28:01 +00001378
1379 /* Set the variable isMemdb to true for an in-memory database, or
1380 ** false for a file-based database. This symbol is only required if
1381 ** either of the shared-data or autovacuum features are compiled
1382 ** into the library.
1383 */
1384#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
1385 #ifdef SQLITE_OMIT_MEMORYDB
drh980b1a72006-08-16 16:42:48 +00001386 const int isMemdb = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00001387 #else
drh980b1a72006-08-16 16:42:48 +00001388 const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
danielk1977aef0bf62005-12-30 16:28:01 +00001389 #endif
1390#endif
1391
drhe5fe6902007-12-07 18:55:28 +00001392 assert( db!=0 );
1393 assert( sqlite3_mutex_held(db->mutex) );
drh153c62c2007-08-24 03:51:33 +00001394
drhe5fe6902007-12-07 18:55:28 +00001395 pVfs = db->pVfs;
drh17435752007-08-16 04:30:38 +00001396 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00001397 if( !p ){
1398 return SQLITE_NOMEM;
1399 }
1400 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00001401 p->db = db;
danielk1977aef0bf62005-12-30 16:28:01 +00001402
drh198bf392006-01-06 21:52:49 +00001403#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001404 /*
1405 ** If this Btree is a candidate for shared cache, try to find an
1406 ** existing BtShared object that we can share with
1407 */
danielk197720c6cc22009-04-01 18:03:00 +00001408 if( isMemdb==0 && zFilename && zFilename[0] ){
danielk1977502b4e02008-09-02 14:07:24 +00001409 if( sqlite3GlobalConfig.sharedCacheEnabled ){
danielk1977adfb9b02007-09-17 07:02:56 +00001410 int nFullPathname = pVfs->mxPathname+1;
drhe5ae5732008-06-15 02:51:47 +00001411 char *zFullPathname = sqlite3Malloc(nFullPathname);
drhff0587c2007-08-29 17:43:19 +00001412 sqlite3_mutex *mutexShared;
1413 p->sharable = 1;
drh34004ce2008-07-11 16:15:17 +00001414 db->flags |= SQLITE_SharedCache;
drhff0587c2007-08-29 17:43:19 +00001415 if( !zFullPathname ){
1416 sqlite3_free(p);
1417 return SQLITE_NOMEM;
1418 }
danielk1977adfb9b02007-09-17 07:02:56 +00001419 sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
drh7555d8e2009-03-20 13:15:30 +00001420 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
1421 sqlite3_mutex_enter(mutexOpen);
danielk197759f8c082008-06-18 17:09:10 +00001422 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhff0587c2007-08-29 17:43:19 +00001423 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001424 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
drhff0587c2007-08-29 17:43:19 +00001425 assert( pBt->nRef>0 );
1426 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
1427 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
1428 p->pBt = pBt;
1429 pBt->nRef++;
1430 break;
1431 }
1432 }
1433 sqlite3_mutex_leave(mutexShared);
1434 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00001435 }
drhff0587c2007-08-29 17:43:19 +00001436#ifdef SQLITE_DEBUG
1437 else{
1438 /* In debug mode, we mark all persistent databases as sharable
1439 ** even when they are not. This exercises the locking code and
1440 ** gives more opportunity for asserts(sqlite3_mutex_held())
1441 ** statements to find locking problems.
1442 */
1443 p->sharable = 1;
1444 }
1445#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001446 }
1447#endif
drha059ad02001-04-17 20:09:11 +00001448 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00001449 /*
1450 ** The following asserts make sure that structures used by the btree are
1451 ** the right size. This is to guard against size changes that result
1452 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00001453 */
drhe53831d2007-08-17 01:14:38 +00001454 assert( sizeof(i64)==8 || sizeof(i64)==4 );
1455 assert( sizeof(u64)==8 || sizeof(u64)==4 );
1456 assert( sizeof(u32)==4 );
1457 assert( sizeof(u16)==2 );
1458 assert( sizeof(Pgno)==4 );
1459
1460 pBt = sqlite3MallocZero( sizeof(*pBt) );
1461 if( pBt==0 ){
1462 rc = SQLITE_NOMEM;
1463 goto btree_open_out;
1464 }
danielk197771d5d2c2008-09-29 11:49:47 +00001465 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
drh33f4e022007-09-03 15:19:34 +00001466 EXTRA_SIZE, flags, vfsFlags);
drhe53831d2007-08-17 01:14:38 +00001467 if( rc==SQLITE_OK ){
1468 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
1469 }
1470 if( rc!=SQLITE_OK ){
1471 goto btree_open_out;
1472 }
danielk19772a50ff02009-04-10 09:47:06 +00001473 pBt->db = db;
danielk19771ceedd32008-11-19 10:22:33 +00001474 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
drhe53831d2007-08-17 01:14:38 +00001475 p->pBt = pBt;
1476
drhe53831d2007-08-17 01:14:38 +00001477 sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
1478 pBt->pCursor = 0;
1479 pBt->pPage1 = 0;
1480 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
1481 pBt->pageSize = get2byte(&zDbHeader[16]);
1482 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1483 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00001484 pBt->pageSize = 0;
1485 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drhe53831d2007-08-17 01:14:38 +00001486#ifndef SQLITE_OMIT_AUTOVACUUM
1487 /* If the magic name ":memory:" will create an in-memory database, then
1488 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
1489 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
1490 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
1491 ** regular file-name. In this case the auto-vacuum applies as per normal.
1492 */
1493 if( zFilename && !isMemdb ){
1494 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
1495 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
1496 }
1497#endif
1498 nReserve = 0;
1499 }else{
1500 nReserve = zDbHeader[20];
drhe53831d2007-08-17 01:14:38 +00001501 pBt->pageSizeFixed = 1;
1502#ifndef SQLITE_OMIT_AUTOVACUUM
1503 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1504 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
1505#endif
1506 }
1507 pBt->usableSize = pBt->pageSize - nReserve;
1508 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
danielk1977a1644fd2007-08-29 12:31:25 +00001509 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drhe53831d2007-08-17 01:14:38 +00001510
1511#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1512 /* Add the new BtShared object to the linked list sharable BtShareds.
1513 */
1514 if( p->sharable ){
1515 sqlite3_mutex *mutexShared;
1516 pBt->nRef = 1;
danielk197759f8c082008-06-18 17:09:10 +00001517 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
danielk1977075c23a2008-09-01 18:34:20 +00001518 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
danielk197759f8c082008-06-18 17:09:10 +00001519 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
drh3285db22007-09-03 22:00:39 +00001520 if( pBt->mutex==0 ){
1521 rc = SQLITE_NOMEM;
drhe5fe6902007-12-07 18:55:28 +00001522 db->mallocFailed = 0;
drh3285db22007-09-03 22:00:39 +00001523 goto btree_open_out;
1524 }
drhff0587c2007-08-29 17:43:19 +00001525 }
drhe53831d2007-08-17 01:14:38 +00001526 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001527 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
1528 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
drhe53831d2007-08-17 01:14:38 +00001529 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00001530 }
drheee46cf2004-11-06 00:02:48 +00001531#endif
drh90f5ecb2004-07-22 01:19:35 +00001532 }
danielk1977aef0bf62005-12-30 16:28:01 +00001533
drhcfed7bc2006-03-13 14:28:05 +00001534#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001535 /* If the new Btree uses a sharable pBtShared, then link the new
1536 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00001537 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00001538 */
drhe53831d2007-08-17 01:14:38 +00001539 if( p->sharable ){
1540 int i;
1541 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00001542 for(i=0; i<db->nDb; i++){
1543 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00001544 while( pSib->pPrev ){ pSib = pSib->pPrev; }
1545 if( p->pBt<pSib->pBt ){
1546 p->pNext = pSib;
1547 p->pPrev = 0;
1548 pSib->pPrev = p;
1549 }else{
drhabddb0c2007-08-20 13:14:28 +00001550 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
drhe53831d2007-08-17 01:14:38 +00001551 pSib = pSib->pNext;
1552 }
1553 p->pNext = pSib->pNext;
1554 p->pPrev = pSib;
1555 if( p->pNext ){
1556 p->pNext->pPrev = p;
1557 }
1558 pSib->pNext = p;
1559 }
1560 break;
1561 }
1562 }
danielk1977aef0bf62005-12-30 16:28:01 +00001563 }
danielk1977aef0bf62005-12-30 16:28:01 +00001564#endif
1565 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00001566
1567btree_open_out:
1568 if( rc!=SQLITE_OK ){
1569 if( pBt && pBt->pPager ){
1570 sqlite3PagerClose(pBt->pPager);
1571 }
drh17435752007-08-16 04:30:38 +00001572 sqlite3_free(pBt);
1573 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00001574 *ppBtree = 0;
1575 }
drh7555d8e2009-03-20 13:15:30 +00001576 if( mutexOpen ){
1577 assert( sqlite3_mutex_held(mutexOpen) );
1578 sqlite3_mutex_leave(mutexOpen);
1579 }
danielk1977dddbcdc2007-04-26 14:42:34 +00001580 return rc;
drha059ad02001-04-17 20:09:11 +00001581}
1582
1583/*
drhe53831d2007-08-17 01:14:38 +00001584** Decrement the BtShared.nRef counter. When it reaches zero,
1585** remove the BtShared structure from the sharing list. Return
1586** true if the BtShared.nRef counter reaches zero and return
1587** false if it is still positive.
1588*/
1589static int removeFromSharingList(BtShared *pBt){
1590#ifndef SQLITE_OMIT_SHARED_CACHE
1591 sqlite3_mutex *pMaster;
1592 BtShared *pList;
1593 int removed = 0;
1594
drhd677b3d2007-08-20 22:48:41 +00001595 assert( sqlite3_mutex_notheld(pBt->mutex) );
danielk197759f8c082008-06-18 17:09:10 +00001596 pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhe53831d2007-08-17 01:14:38 +00001597 sqlite3_mutex_enter(pMaster);
1598 pBt->nRef--;
1599 if( pBt->nRef<=0 ){
drh78f82d12008-09-02 00:52:52 +00001600 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
1601 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
drhe53831d2007-08-17 01:14:38 +00001602 }else{
drh78f82d12008-09-02 00:52:52 +00001603 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
drh34004ce2008-07-11 16:15:17 +00001604 while( ALWAYS(pList) && pList->pNext!=pBt ){
drhe53831d2007-08-17 01:14:38 +00001605 pList=pList->pNext;
1606 }
drh34004ce2008-07-11 16:15:17 +00001607 if( ALWAYS(pList) ){
drhe53831d2007-08-17 01:14:38 +00001608 pList->pNext = pBt->pNext;
1609 }
1610 }
drh3285db22007-09-03 22:00:39 +00001611 if( SQLITE_THREADSAFE ){
1612 sqlite3_mutex_free(pBt->mutex);
1613 }
drhe53831d2007-08-17 01:14:38 +00001614 removed = 1;
1615 }
1616 sqlite3_mutex_leave(pMaster);
1617 return removed;
1618#else
1619 return 1;
1620#endif
1621}
1622
1623/*
drhf7141992008-06-19 00:16:08 +00001624** Make sure pBt->pTmpSpace points to an allocation of
1625** MX_CELL_SIZE(pBt) bytes.
1626*/
1627static void allocateTempSpace(BtShared *pBt){
1628 if( !pBt->pTmpSpace ){
1629 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
1630 }
1631}
1632
1633/*
1634** Free the pBt->pTmpSpace allocation
1635*/
1636static void freeTempSpace(BtShared *pBt){
1637 sqlite3PageFree( pBt->pTmpSpace);
1638 pBt->pTmpSpace = 0;
1639}
1640
1641/*
drha059ad02001-04-17 20:09:11 +00001642** Close an open database and invalidate all cursors.
1643*/
danielk1977aef0bf62005-12-30 16:28:01 +00001644int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00001645 BtShared *pBt = p->pBt;
1646 BtCursor *pCur;
1647
danielk1977aef0bf62005-12-30 16:28:01 +00001648 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00001649 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00001650 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001651 pCur = pBt->pCursor;
1652 while( pCur ){
1653 BtCursor *pTmp = pCur;
1654 pCur = pCur->pNext;
1655 if( pTmp->pBtree==p ){
1656 sqlite3BtreeCloseCursor(pTmp);
1657 }
drha059ad02001-04-17 20:09:11 +00001658 }
danielk1977aef0bf62005-12-30 16:28:01 +00001659
danielk19778d34dfd2006-01-24 16:37:57 +00001660 /* Rollback any active transaction and free the handle structure.
1661 ** The call to sqlite3BtreeRollback() drops any table-locks held by
1662 ** this handle.
1663 */
danielk1977b597f742006-01-15 11:39:18 +00001664 sqlite3BtreeRollback(p);
drhe53831d2007-08-17 01:14:38 +00001665 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001666
danielk1977aef0bf62005-12-30 16:28:01 +00001667 /* If there are still other outstanding references to the shared-btree
1668 ** structure, return now. The remainder of this procedure cleans
1669 ** up the shared-btree.
1670 */
drhe53831d2007-08-17 01:14:38 +00001671 assert( p->wantToLock==0 && p->locked==0 );
1672 if( !p->sharable || removeFromSharingList(pBt) ){
1673 /* The pBt is no longer on the sharing list, so we can access
1674 ** it without having to hold the mutex.
1675 **
1676 ** Clean out and delete the BtShared object.
1677 */
1678 assert( !pBt->pCursor );
drhe53831d2007-08-17 01:14:38 +00001679 sqlite3PagerClose(pBt->pPager);
1680 if( pBt->xFreeSchema && pBt->pSchema ){
1681 pBt->xFreeSchema(pBt->pSchema);
1682 }
1683 sqlite3_free(pBt->pSchema);
drhf7141992008-06-19 00:16:08 +00001684 freeTempSpace(pBt);
drh65bbf292008-06-19 01:03:17 +00001685 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00001686 }
1687
drhe53831d2007-08-17 01:14:38 +00001688#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00001689 assert( p->wantToLock==0 );
1690 assert( p->locked==0 );
1691 if( p->pPrev ) p->pPrev->pNext = p->pNext;
1692 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00001693#endif
1694
drhe53831d2007-08-17 01:14:38 +00001695 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00001696 return SQLITE_OK;
1697}
1698
1699/*
drhda47d772002-12-02 04:25:19 +00001700** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001701**
1702** The maximum number of cache pages is set to the absolute
1703** value of mxPage. If mxPage is negative, the pager will
1704** operate asynchronously - it will not stop to do fsync()s
1705** to insure data is written to the disk surface before
1706** continuing. Transactions still work if synchronous is off,
1707** and the database cannot be corrupted if this program
1708** crashes. But if the operating system crashes or there is
1709** an abrupt power failure when synchronous is off, the database
1710** could be left in an inconsistent and unrecoverable state.
1711** Synchronous is on by default so database corruption is not
1712** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001713*/
danielk1977aef0bf62005-12-30 16:28:01 +00001714int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
1715 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001716 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001717 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001718 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00001719 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00001720 return SQLITE_OK;
1721}
1722
1723/*
drh973b6e32003-02-12 14:09:42 +00001724** Change the way data is synced to disk in order to increase or decrease
1725** how well the database resists damage due to OS crashes and power
1726** failures. Level 1 is the same as asynchronous (no syncs() occur and
1727** there is a high probability of damage) Level 2 is the default. There
1728** is a very low but non-zero probability of damage. Level 3 reduces the
1729** probability of damage to near zero but with a write performance reduction.
1730*/
danielk197793758c82005-01-21 08:13:14 +00001731#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drhac530b12006-02-11 01:25:50 +00001732int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
danielk1977aef0bf62005-12-30 16:28:01 +00001733 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001734 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001735 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001736 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
drhd677b3d2007-08-20 22:48:41 +00001737 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00001738 return SQLITE_OK;
1739}
danielk197793758c82005-01-21 08:13:14 +00001740#endif
drh973b6e32003-02-12 14:09:42 +00001741
drh2c8997b2005-08-27 16:36:48 +00001742/*
1743** Return TRUE if the given btree is set to safety level 1. In other
1744** words, return TRUE if no sync() occurs on the disk files.
1745*/
danielk1977aef0bf62005-12-30 16:28:01 +00001746int sqlite3BtreeSyncDisabled(Btree *p){
1747 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001748 int rc;
drhe5fe6902007-12-07 18:55:28 +00001749 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001750 sqlite3BtreeEnter(p);
drhd0679ed2007-08-28 22:24:34 +00001751 assert( pBt && pBt->pPager );
drhd677b3d2007-08-20 22:48:41 +00001752 rc = sqlite3PagerNosync(pBt->pPager);
1753 sqlite3BtreeLeave(p);
1754 return rc;
drh2c8997b2005-08-27 16:36:48 +00001755}
1756
danielk1977576ec6b2005-01-21 11:55:25 +00001757#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00001758/*
drh90f5ecb2004-07-22 01:19:35 +00001759** Change the default pages size and the number of reserved bytes per page.
drhce4869f2009-04-02 20:16:58 +00001760** Or, if the page size has already been fixed, return SQLITE_READONLY
1761** without changing anything.
drh06f50212004-11-02 14:24:33 +00001762**
1763** The page size must be a power of 2 between 512 and 65536. If the page
1764** size supplied does not meet this constraint then the page size is not
1765** changed.
1766**
1767** Page sizes are constrained to be a power of two so that the region
1768** of the database file used for locking (beginning at PENDING_BYTE,
1769** the first byte past the 1GB boundary, 0x40000000) needs to occur
1770** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001771**
1772** If parameter nReserve is less than zero, then the number of reserved
1773** bytes per page is left unchanged.
drhce4869f2009-04-02 20:16:58 +00001774**
1775** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
1776** and autovacuum mode can no longer be changed.
drh90f5ecb2004-07-22 01:19:35 +00001777*/
drhce4869f2009-04-02 20:16:58 +00001778int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
danielk1977a1644fd2007-08-29 12:31:25 +00001779 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00001780 BtShared *pBt = p->pBt;
drhf49661a2008-12-10 16:45:50 +00001781 assert( nReserve>=-1 && nReserve<=255 );
drhd677b3d2007-08-20 22:48:41 +00001782 sqlite3BtreeEnter(p);
drh90f5ecb2004-07-22 01:19:35 +00001783 if( pBt->pageSizeFixed ){
drhd677b3d2007-08-20 22:48:41 +00001784 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00001785 return SQLITE_READONLY;
1786 }
1787 if( nReserve<0 ){
1788 nReserve = pBt->pageSize - pBt->usableSize;
1789 }
drhf49661a2008-12-10 16:45:50 +00001790 assert( nReserve>=0 && nReserve<=255 );
drh06f50212004-11-02 14:24:33 +00001791 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
1792 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00001793 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00001794 assert( !pBt->pPage1 && !pBt->pCursor );
drh1bd10f82008-12-10 21:19:56 +00001795 pBt->pageSize = (u16)pageSize;
drhf7141992008-06-19 00:16:08 +00001796 freeTempSpace(pBt);
danielk1977a1644fd2007-08-29 12:31:25 +00001797 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
drh90f5ecb2004-07-22 01:19:35 +00001798 }
drhf49661a2008-12-10 16:45:50 +00001799 pBt->usableSize = pBt->pageSize - (u16)nReserve;
drhce4869f2009-04-02 20:16:58 +00001800 if( iFix ) pBt->pageSizeFixed = 1;
drhd677b3d2007-08-20 22:48:41 +00001801 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00001802 return rc;
drh90f5ecb2004-07-22 01:19:35 +00001803}
1804
1805/*
1806** Return the currently defined page size
1807*/
danielk1977aef0bf62005-12-30 16:28:01 +00001808int sqlite3BtreeGetPageSize(Btree *p){
1809 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00001810}
drh7f751222009-03-17 22:33:00 +00001811
1812/*
1813** Return the number of bytes of space at the end of every page that
1814** are intentually left unused. This is the "reserved" space that is
1815** sometimes used by extensions.
1816*/
danielk1977aef0bf62005-12-30 16:28:01 +00001817int sqlite3BtreeGetReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00001818 int n;
1819 sqlite3BtreeEnter(p);
1820 n = p->pBt->pageSize - p->pBt->usableSize;
1821 sqlite3BtreeLeave(p);
1822 return n;
drh2011d5f2004-07-22 02:40:37 +00001823}
drhf8e632b2007-05-08 14:51:36 +00001824
1825/*
1826** Set the maximum page count for a database if mxPage is positive.
1827** No changes are made if mxPage is 0 or negative.
1828** Regardless of the value of mxPage, return the maximum page count.
1829*/
1830int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00001831 int n;
1832 sqlite3BtreeEnter(p);
1833 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
1834 sqlite3BtreeLeave(p);
1835 return n;
drhf8e632b2007-05-08 14:51:36 +00001836}
danielk1977576ec6b2005-01-21 11:55:25 +00001837#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00001838
1839/*
danielk1977951af802004-11-05 15:45:09 +00001840** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
1841** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
1842** is disabled. The default value for the auto-vacuum property is
1843** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
1844*/
danielk1977aef0bf62005-12-30 16:28:01 +00001845int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00001846#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001847 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00001848#else
danielk1977dddbcdc2007-04-26 14:42:34 +00001849 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001850 int rc = SQLITE_OK;
drh076d4662009-02-18 20:31:18 +00001851 u8 av = (u8)autoVacuum;
drhd677b3d2007-08-20 22:48:41 +00001852
1853 sqlite3BtreeEnter(p);
drh076d4662009-02-18 20:31:18 +00001854 if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00001855 rc = SQLITE_READONLY;
1856 }else{
drh076d4662009-02-18 20:31:18 +00001857 pBt->autoVacuum = av ?1:0;
1858 pBt->incrVacuum = av==2 ?1:0;
danielk1977951af802004-11-05 15:45:09 +00001859 }
drhd677b3d2007-08-20 22:48:41 +00001860 sqlite3BtreeLeave(p);
1861 return rc;
danielk1977951af802004-11-05 15:45:09 +00001862#endif
1863}
1864
1865/*
1866** Return the value of the 'auto-vacuum' property. If auto-vacuum is
1867** enabled 1 is returned. Otherwise 0.
1868*/
danielk1977aef0bf62005-12-30 16:28:01 +00001869int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00001870#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00001871 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00001872#else
drhd677b3d2007-08-20 22:48:41 +00001873 int rc;
1874 sqlite3BtreeEnter(p);
1875 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00001876 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
1877 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
1878 BTREE_AUTOVACUUM_INCR
1879 );
drhd677b3d2007-08-20 22:48:41 +00001880 sqlite3BtreeLeave(p);
1881 return rc;
danielk1977951af802004-11-05 15:45:09 +00001882#endif
1883}
1884
1885
1886/*
drha34b6762004-05-07 13:30:42 +00001887** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00001888** also acquire a readlock on that file.
1889**
1890** SQLITE_OK is returned on success. If the file is not a
1891** well-formed database file, then SQLITE_CORRUPT is returned.
1892** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00001893** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00001894*/
danielk1977aef0bf62005-12-30 16:28:01 +00001895static int lockBtree(BtShared *pBt){
danielk1977f653d782008-03-20 11:04:21 +00001896 int rc;
drh3aac2dd2004-04-26 14:10:20 +00001897 MemPage *pPage1;
danielk197793f7af92008-05-09 16:57:50 +00001898 int nPage;
drhd677b3d2007-08-20 22:48:41 +00001899
drh1fee73e2007-08-29 04:00:57 +00001900 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977295dc102009-04-01 19:07:03 +00001901 assert( pBt->pPage1==0 );
drh16a9b832007-05-05 18:39:25 +00001902 rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00001903 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00001904
1905 /* Do some checking to help insure the file we opened really is
1906 ** a valid database file.
1907 */
danielk1977ad0132d2008-06-07 08:58:22 +00001908 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1909 if( rc!=SQLITE_OK ){
danielk197793f7af92008-05-09 16:57:50 +00001910 goto page1_init_failed;
1911 }else if( nPage>0 ){
danielk1977f653d782008-03-20 11:04:21 +00001912 int pageSize;
1913 int usableSize;
drhb6f41482004-05-14 01:58:11 +00001914 u8 *page1 = pPage1->aData;
danielk1977ad0132d2008-06-07 08:58:22 +00001915 rc = SQLITE_NOTADB;
drhb6f41482004-05-14 01:58:11 +00001916 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00001917 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00001918 }
drh309169a2007-04-24 17:27:51 +00001919 if( page1[18]>1 ){
1920 pBt->readOnly = 1;
1921 }
1922 if( page1[19]>1 ){
drhb6f41482004-05-14 01:58:11 +00001923 goto page1_init_failed;
1924 }
drhe5ae5732008-06-15 02:51:47 +00001925
1926 /* The maximum embedded fraction must be exactly 25%. And the minimum
1927 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
1928 ** The original design allowed these amounts to vary, but as of
1929 ** version 3.6.0, we require them to be fixed.
1930 */
1931 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
1932 goto page1_init_failed;
1933 }
drh07d183d2005-05-01 22:52:42 +00001934 pageSize = get2byte(&page1[16]);
drh7dc385e2007-09-06 23:39:36 +00001935 if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
1936 (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
1937 ){
drh07d183d2005-05-01 22:52:42 +00001938 goto page1_init_failed;
1939 }
1940 assert( (pageSize & 7)==0 );
danielk1977f653d782008-03-20 11:04:21 +00001941 usableSize = pageSize - page1[20];
1942 if( pageSize!=pBt->pageSize ){
1943 /* After reading the first page of the database assuming a page size
1944 ** of BtShared.pageSize, we have discovered that the page-size is
1945 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
1946 ** zero and return SQLITE_OK. The caller will call this function
1947 ** again with the correct page-size.
1948 */
1949 releasePage(pPage1);
drhf49661a2008-12-10 16:45:50 +00001950 pBt->usableSize = (u16)usableSize;
1951 pBt->pageSize = (u16)pageSize;
drhf7141992008-06-19 00:16:08 +00001952 freeTempSpace(pBt);
danielk1977f653d782008-03-20 11:04:21 +00001953 sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize);
1954 return SQLITE_OK;
1955 }
1956 if( usableSize<500 ){
drhb6f41482004-05-14 01:58:11 +00001957 goto page1_init_failed;
1958 }
drh1bd10f82008-12-10 21:19:56 +00001959 pBt->pageSize = (u16)pageSize;
1960 pBt->usableSize = (u16)usableSize;
drh057cd3a2005-02-15 16:23:02 +00001961#ifndef SQLITE_OMIT_AUTOVACUUM
1962 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00001963 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00001964#endif
drh306dc212001-05-21 13:45:10 +00001965 }
drhb6f41482004-05-14 01:58:11 +00001966
1967 /* maxLocal is the maximum amount of payload to store locally for
1968 ** a cell. Make sure it is small enough so that at least minFanout
1969 ** cells can will fit on one page. We assume a 10-byte page header.
1970 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00001971 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00001972 ** 4-byte child pointer
1973 ** 9-byte nKey value
1974 ** 4-byte nData value
1975 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00001976 ** So a cell consists of a 2-byte poiner, a header which is as much as
1977 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
1978 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00001979 */
drhe5ae5732008-06-15 02:51:47 +00001980 pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
1981 pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
drh43605152004-05-29 21:46:49 +00001982 pBt->maxLeaf = pBt->usableSize - 35;
drhe5ae5732008-06-15 02:51:47 +00001983 pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
drh2e38c322004-09-03 18:38:44 +00001984 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00001985 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00001986 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00001987
drh72f82862001-05-24 21:06:34 +00001988page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00001989 releasePage(pPage1);
1990 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00001991 return rc;
drh306dc212001-05-21 13:45:10 +00001992}
1993
1994/*
drhb8ef32c2005-03-14 02:01:49 +00001995** This routine works like lockBtree() except that it also invokes the
1996** busy callback if there is lock contention.
1997*/
danielk1977aef0bf62005-12-30 16:28:01 +00001998static int lockBtreeWithRetry(Btree *pRef){
drhb8ef32c2005-03-14 02:01:49 +00001999 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00002000
drh1fee73e2007-08-29 04:00:57 +00002001 assert( sqlite3BtreeHoldsMutex(pRef) );
danielk1977aef0bf62005-12-30 16:28:01 +00002002 if( pRef->inTrans==TRANS_NONE ){
2003 u8 inTransaction = pRef->pBt->inTransaction;
2004 btreeIntegrity(pRef);
2005 rc = sqlite3BtreeBeginTrans(pRef, 0);
2006 pRef->pBt->inTransaction = inTransaction;
2007 pRef->inTrans = TRANS_NONE;
2008 if( rc==SQLITE_OK ){
2009 pRef->pBt->nTransaction--;
2010 }
2011 btreeIntegrity(pRef);
drhb8ef32c2005-03-14 02:01:49 +00002012 }
2013 return rc;
2014}
2015
2016
2017/*
drhb8ca3072001-12-05 00:21:20 +00002018** If there are no outstanding cursors and we are not in the middle
2019** of a transaction but there is a read lock on the database, then
2020** this routine unrefs the first page of the database file which
2021** has the effect of releasing the read lock.
2022**
2023** If there are any outstanding cursors, this routine is a no-op.
2024**
2025** If there is a transaction in progress, this routine is a no-op.
2026*/
danielk1977aef0bf62005-12-30 16:28:01 +00002027static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00002028 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00002029 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00002030 if( sqlite3PagerRefcount(pBt->pPager)>=1 ){
drhde4fcfd2008-01-19 23:50:26 +00002031 assert( pBt->pPage1->aData );
drh24c9a2e2007-01-05 02:00:47 +00002032 releasePage(pBt->pPage1);
drh51c6d962004-06-06 00:42:25 +00002033 }
drh3aac2dd2004-04-26 14:10:20 +00002034 pBt->pPage1 = 0;
drhb8ca3072001-12-05 00:21:20 +00002035 }
2036}
2037
2038/*
drh9e572e62004-04-23 23:43:10 +00002039** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00002040** file.
drh8b2f49b2001-06-08 00:21:52 +00002041*/
danielk1977aef0bf62005-12-30 16:28:01 +00002042static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00002043 MemPage *pP1;
2044 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00002045 int rc;
danielk1977ad0132d2008-06-07 08:58:22 +00002046 int nPage;
drhd677b3d2007-08-20 22:48:41 +00002047
drh1fee73e2007-08-29 04:00:57 +00002048 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977ad0132d2008-06-07 08:58:22 +00002049 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
2050 if( rc!=SQLITE_OK || nPage>0 ){
2051 return rc;
2052 }
drh3aac2dd2004-04-26 14:10:20 +00002053 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00002054 assert( pP1!=0 );
2055 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00002056 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00002057 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00002058 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
2059 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00002060 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00002061 data[18] = 1;
2062 data[19] = 1;
drhf49661a2008-12-10 16:45:50 +00002063 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
2064 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
drhe5ae5732008-06-15 02:51:47 +00002065 data[21] = 64;
2066 data[22] = 32;
2067 data[23] = 32;
drhb6f41482004-05-14 01:58:11 +00002068 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00002069 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00002070 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00002071#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002072 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00002073 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00002074 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00002075 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00002076#endif
drh8b2f49b2001-06-08 00:21:52 +00002077 return SQLITE_OK;
2078}
2079
2080/*
danielk1977ee5741e2004-05-31 10:01:34 +00002081** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00002082** is started if the second argument is nonzero, otherwise a read-
2083** transaction. If the second argument is 2 or more and exclusive
2084** transaction is started, meaning that no other process is allowed
2085** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00002086** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00002087** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00002088**
danielk1977ee5741e2004-05-31 10:01:34 +00002089** A write-transaction must be started before attempting any
2090** changes to the database. None of the following routines
2091** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00002092**
drh23e11ca2004-05-04 17:27:28 +00002093** sqlite3BtreeCreateTable()
2094** sqlite3BtreeCreateIndex()
2095** sqlite3BtreeClearTable()
2096** sqlite3BtreeDropTable()
2097** sqlite3BtreeInsert()
2098** sqlite3BtreeDelete()
2099** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00002100**
drhb8ef32c2005-03-14 02:01:49 +00002101** If an initial attempt to acquire the lock fails because of lock contention
2102** and the database was previously unlocked, then invoke the busy handler
2103** if there is one. But if there was previously a read-lock, do not
2104** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
2105** returned when there is already a read-lock in order to avoid a deadlock.
2106**
2107** Suppose there are two processes A and B. A has a read lock and B has
2108** a reserved lock. B tries to promote to exclusive but is blocked because
2109** of A's read lock. A tries to promote to reserved but is blocked by B.
2110** One or the other of the two processes must give way or there can be
2111** no progress. By returning SQLITE_BUSY and not invoking the busy callback
2112** when A already has a read lock, we encourage A to give up and let B
2113** proceed.
drha059ad02001-04-17 20:09:11 +00002114*/
danielk1977aef0bf62005-12-30 16:28:01 +00002115int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
danielk1977404ca072009-03-16 13:19:36 +00002116 sqlite3 *pBlock = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00002117 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00002118 int rc = SQLITE_OK;
2119
drhd677b3d2007-08-20 22:48:41 +00002120 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002121 btreeIntegrity(p);
2122
danielk1977ee5741e2004-05-31 10:01:34 +00002123 /* If the btree is already in a write-transaction, or it
2124 ** is already in a read-transaction and a read-transaction
2125 ** is requested, this is a no-op.
2126 */
danielk1977aef0bf62005-12-30 16:28:01 +00002127 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00002128 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002129 }
drhb8ef32c2005-03-14 02:01:49 +00002130
2131 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00002132 if( pBt->readOnly && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00002133 rc = SQLITE_READONLY;
2134 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002135 }
2136
danielk1977404ca072009-03-16 13:19:36 +00002137#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +00002138 /* If another database handle has already opened a write transaction
2139 ** on this shared-btree structure and a second write transaction is
danielk1977404ca072009-03-16 13:19:36 +00002140 ** requested, return SQLITE_LOCKED.
danielk1977aef0bf62005-12-30 16:28:01 +00002141 */
danielk1977404ca072009-03-16 13:19:36 +00002142 if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
2143 pBlock = pBt->pWriter->db;
2144 }else if( wrflag>1 ){
danielk1977641b0f42007-12-21 04:47:25 +00002145 BtLock *pIter;
2146 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
2147 if( pIter->pBtree!=p ){
danielk1977404ca072009-03-16 13:19:36 +00002148 pBlock = pIter->pBtree->db;
2149 break;
danielk1977641b0f42007-12-21 04:47:25 +00002150 }
2151 }
2152 }
danielk1977404ca072009-03-16 13:19:36 +00002153 if( pBlock ){
2154 sqlite3ConnectionBlocked(p->db, pBlock);
2155 rc = SQLITE_LOCKED_SHAREDCACHE;
2156 goto trans_begun;
2157 }
danielk1977641b0f42007-12-21 04:47:25 +00002158#endif
2159
drhb8ef32c2005-03-14 02:01:49 +00002160 do {
danielk1977295dc102009-04-01 19:07:03 +00002161 /* Call lockBtree() until either pBt->pPage1 is populated or
2162 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
2163 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
2164 ** reading page 1 it discovers that the page-size of the database
2165 ** file is not pBt->pageSize. In this case lockBtree() will update
2166 ** pBt->pageSize to the page-size of the file on disk.
2167 */
2168 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
drh309169a2007-04-24 17:27:51 +00002169
drhb8ef32c2005-03-14 02:01:49 +00002170 if( rc==SQLITE_OK && wrflag ){
drh309169a2007-04-24 17:27:51 +00002171 if( pBt->readOnly ){
2172 rc = SQLITE_READONLY;
2173 }else{
danielk1977bea2a942009-01-20 17:06:27 +00002174 rc = sqlite3PagerBegin(pBt->pPager, wrflag>1);
drh309169a2007-04-24 17:27:51 +00002175 if( rc==SQLITE_OK ){
2176 rc = newDatabase(pBt);
2177 }
drhb8ef32c2005-03-14 02:01:49 +00002178 }
2179 }
2180
danielk1977bd434552009-03-18 10:33:00 +00002181 if( rc!=SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00002182 unlockBtreeIfUnused(pBt);
2183 }
danielk1977aef0bf62005-12-30 16:28:01 +00002184 }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
danielk19771ceedd32008-11-19 10:22:33 +00002185 btreeInvokeBusyHandler(pBt) );
danielk1977aef0bf62005-12-30 16:28:01 +00002186
2187 if( rc==SQLITE_OK ){
2188 if( p->inTrans==TRANS_NONE ){
2189 pBt->nTransaction++;
2190 }
2191 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
2192 if( p->inTrans>pBt->inTransaction ){
2193 pBt->inTransaction = p->inTrans;
2194 }
danielk1977641b0f42007-12-21 04:47:25 +00002195#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977404ca072009-03-16 13:19:36 +00002196 if( wrflag ){
2197 assert( !pBt->pWriter );
2198 pBt->pWriter = p;
shaneca18d202009-03-23 02:34:32 +00002199 pBt->isExclusive = (u8)(wrflag>1);
danielk1977641b0f42007-12-21 04:47:25 +00002200 }
2201#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002202 }
2203
drhd677b3d2007-08-20 22:48:41 +00002204
2205trans_begun:
danielk1977fd7f0452008-12-17 17:30:26 +00002206 if( rc==SQLITE_OK && wrflag ){
danielk197712dd5492008-12-18 15:45:07 +00002207 /* This call makes sure that the pager has the correct number of
2208 ** open savepoints. If the second parameter is greater than 0 and
2209 ** the sub-journal is not already open, then it will be opened here.
2210 */
danielk1977fd7f0452008-12-17 17:30:26 +00002211 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
2212 }
danielk197712dd5492008-12-18 15:45:07 +00002213
danielk1977aef0bf62005-12-30 16:28:01 +00002214 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002215 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00002216 return rc;
drha059ad02001-04-17 20:09:11 +00002217}
2218
danielk1977687566d2004-11-02 12:56:41 +00002219#ifndef SQLITE_OMIT_AUTOVACUUM
2220
2221/*
2222** Set the pointer-map entries for all children of page pPage. Also, if
2223** pPage contains cells that point to overflow pages, set the pointer
2224** map entries for the overflow pages as well.
2225*/
2226static int setChildPtrmaps(MemPage *pPage){
2227 int i; /* Counter variable */
2228 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00002229 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00002230 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00002231 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002232 Pgno pgno = pPage->pgno;
2233
drh1fee73e2007-08-29 04:00:57 +00002234 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197771d5d2c2008-09-29 11:49:47 +00002235 rc = sqlite3BtreeInitPage(pPage);
danielk19772df71c72007-05-24 07:22:42 +00002236 if( rc!=SQLITE_OK ){
2237 goto set_child_ptrmaps_out;
2238 }
danielk1977687566d2004-11-02 12:56:41 +00002239 nCell = pPage->nCell;
2240
2241 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002242 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002243
danielk197726836652005-01-17 01:33:13 +00002244 rc = ptrmapPutOvflPtr(pPage, pCell);
2245 if( rc!=SQLITE_OK ){
2246 goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002247 }
danielk197726836652005-01-17 01:33:13 +00002248
danielk1977687566d2004-11-02 12:56:41 +00002249 if( !pPage->leaf ){
2250 Pgno childPgno = get4byte(pCell);
2251 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
danielk197700a696d2008-09-29 16:41:31 +00002252 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002253 }
2254 }
2255
2256 if( !pPage->leaf ){
2257 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
2258 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
2259 }
2260
2261set_child_ptrmaps_out:
2262 pPage->isInit = isInitOrig;
2263 return rc;
2264}
2265
2266/*
danielk1977fa542f12009-04-02 18:28:08 +00002267** Somewhere on pPage, which is guaranteed to be a btree page, not an overflow
danielk1977687566d2004-11-02 12:56:41 +00002268** page, is a pointer to page iFrom. Modify this pointer so that it points to
2269** iTo. Parameter eType describes the type of pointer to be modified, as
2270** follows:
2271**
2272** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
2273** page of pPage.
2274**
2275** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
2276** page pointed to by one of the cells on pPage.
2277**
2278** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
2279** overflow page in the list.
2280*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00002281static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00002282 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00002283 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977687566d2004-11-02 12:56:41 +00002284 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00002285 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00002286 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00002287 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002288 }
danielk1977f78fc082004-11-02 14:40:32 +00002289 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00002290 }else{
drhf49661a2008-12-10 16:45:50 +00002291 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002292 int i;
2293 int nCell;
2294
danielk197771d5d2c2008-09-29 11:49:47 +00002295 sqlite3BtreeInitPage(pPage);
danielk1977687566d2004-11-02 12:56:41 +00002296 nCell = pPage->nCell;
2297
danielk1977687566d2004-11-02 12:56:41 +00002298 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002299 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002300 if( eType==PTRMAP_OVERFLOW1 ){
2301 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00002302 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
danielk1977687566d2004-11-02 12:56:41 +00002303 if( info.iOverflow ){
2304 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
2305 put4byte(&pCell[info.iOverflow], iTo);
2306 break;
2307 }
2308 }
2309 }else{
2310 if( get4byte(pCell)==iFrom ){
2311 put4byte(pCell, iTo);
2312 break;
2313 }
2314 }
2315 }
2316
2317 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00002318 if( eType!=PTRMAP_BTREE ||
2319 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00002320 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002321 }
danielk1977687566d2004-11-02 12:56:41 +00002322 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
2323 }
2324
2325 pPage->isInit = isInitOrig;
2326 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002327 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002328}
2329
danielk1977003ba062004-11-04 02:57:33 +00002330
danielk19777701e812005-01-10 12:59:51 +00002331/*
2332** Move the open database page pDbPage to location iFreePage in the
2333** database. The pDbPage reference remains valid.
2334*/
danielk1977003ba062004-11-04 02:57:33 +00002335static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00002336 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00002337 MemPage *pDbPage, /* Open page to move */
2338 u8 eType, /* Pointer map 'type' entry for pDbPage */
2339 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
danielk19774c999992008-07-16 18:17:55 +00002340 Pgno iFreePage, /* The location to move pDbPage to */
2341 int isCommit
danielk1977003ba062004-11-04 02:57:33 +00002342){
2343 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
2344 Pgno iDbPage = pDbPage->pgno;
2345 Pager *pPager = pBt->pPager;
2346 int rc;
2347
danielk1977a0bf2652004-11-04 14:30:04 +00002348 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
2349 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00002350 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00002351 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00002352
drh85b623f2007-12-13 21:54:09 +00002353 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00002354 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
2355 iDbPage, iFreePage, iPtrPage, eType));
danielk19774c999992008-07-16 18:17:55 +00002356 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
danielk1977003ba062004-11-04 02:57:33 +00002357 if( rc!=SQLITE_OK ){
2358 return rc;
2359 }
2360 pDbPage->pgno = iFreePage;
2361
2362 /* If pDbPage was a btree-page, then it may have child pages and/or cells
2363 ** that point to overflow pages. The pointer map entries for all these
2364 ** pages need to be changed.
2365 **
2366 ** If pDbPage is an overflow page, then the first 4 bytes may store a
2367 ** pointer to a subsequent overflow page. If this is the case, then
2368 ** the pointer map needs to be updated for the subsequent overflow page.
2369 */
danielk1977a0bf2652004-11-04 14:30:04 +00002370 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00002371 rc = setChildPtrmaps(pDbPage);
2372 if( rc!=SQLITE_OK ){
2373 return rc;
2374 }
2375 }else{
2376 Pgno nextOvfl = get4byte(pDbPage->aData);
2377 if( nextOvfl!=0 ){
danielk1977003ba062004-11-04 02:57:33 +00002378 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
2379 if( rc!=SQLITE_OK ){
2380 return rc;
2381 }
2382 }
2383 }
2384
2385 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
2386 ** that it points at iFreePage. Also fix the pointer map entry for
2387 ** iPtrPage.
2388 */
danielk1977a0bf2652004-11-04 14:30:04 +00002389 if( eType!=PTRMAP_ROOTPAGE ){
drh16a9b832007-05-05 18:39:25 +00002390 rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00002391 if( rc!=SQLITE_OK ){
2392 return rc;
2393 }
danielk19773b8a05f2007-03-19 17:44:26 +00002394 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00002395 if( rc!=SQLITE_OK ){
2396 releasePage(pPtrPage);
2397 return rc;
2398 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002399 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00002400 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00002401 if( rc==SQLITE_OK ){
2402 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
2403 }
danielk1977003ba062004-11-04 02:57:33 +00002404 }
danielk1977003ba062004-11-04 02:57:33 +00002405 return rc;
2406}
2407
danielk1977dddbcdc2007-04-26 14:42:34 +00002408/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00002409static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00002410
2411/*
danielk1977dddbcdc2007-04-26 14:42:34 +00002412** Perform a single step of an incremental-vacuum. If successful,
2413** return SQLITE_OK. If there is no work to do (and therefore no
2414** point in calling this function again), return SQLITE_DONE.
2415**
2416** More specificly, this function attempts to re-organize the
2417** database so that the last page of the file currently in use
2418** is no longer in use.
2419**
2420** If the nFin parameter is non-zero, the implementation assumes
2421** that the caller will keep calling incrVacuumStep() until
2422** it returns SQLITE_DONE or an error, and that nFin is the
2423** number of pages the database file will contain after this
2424** process is complete.
2425*/
danielk19773460d192008-12-27 15:23:13 +00002426static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
danielk1977dddbcdc2007-04-26 14:42:34 +00002427 Pgno nFreeList; /* Number of pages still on the free-list */
2428
drh1fee73e2007-08-29 04:00:57 +00002429 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977fa542f12009-04-02 18:28:08 +00002430 assert( iLastPg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00002431
2432 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
2433 int rc;
2434 u8 eType;
2435 Pgno iPtrPage;
2436
2437 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977fa542f12009-04-02 18:28:08 +00002438 if( nFreeList==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00002439 return SQLITE_DONE;
2440 }
2441
2442 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
2443 if( rc!=SQLITE_OK ){
2444 return rc;
2445 }
2446 if( eType==PTRMAP_ROOTPAGE ){
2447 return SQLITE_CORRUPT_BKPT;
2448 }
2449
2450 if( eType==PTRMAP_FREEPAGE ){
2451 if( nFin==0 ){
2452 /* Remove the page from the files free-list. This is not required
danielk19774ef24492007-05-23 09:52:41 +00002453 ** if nFin is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00002454 ** truncated to zero after this function returns, so it doesn't
2455 ** matter if it still contains some garbage entries.
2456 */
2457 Pgno iFreePg;
2458 MemPage *pFreePg;
2459 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
2460 if( rc!=SQLITE_OK ){
2461 return rc;
2462 }
2463 assert( iFreePg==iLastPg );
2464 releasePage(pFreePg);
2465 }
2466 } else {
2467 Pgno iFreePg; /* Index of free page to move pLastPg to */
2468 MemPage *pLastPg;
2469
drh16a9b832007-05-05 18:39:25 +00002470 rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002471 if( rc!=SQLITE_OK ){
2472 return rc;
2473 }
2474
danielk1977b4626a32007-04-28 15:47:43 +00002475 /* If nFin is zero, this loop runs exactly once and page pLastPg
2476 ** is swapped with the first free page pulled off the free list.
2477 **
2478 ** On the other hand, if nFin is greater than zero, then keep
2479 ** looping until a free-page located within the first nFin pages
2480 ** of the file is found.
2481 */
danielk1977dddbcdc2007-04-26 14:42:34 +00002482 do {
2483 MemPage *pFreePg;
2484 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
2485 if( rc!=SQLITE_OK ){
2486 releasePage(pLastPg);
2487 return rc;
2488 }
2489 releasePage(pFreePg);
2490 }while( nFin!=0 && iFreePg>nFin );
2491 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00002492
2493 rc = sqlite3PagerWrite(pLastPg->pDbPage);
danielk1977662278e2007-11-05 15:30:12 +00002494 if( rc==SQLITE_OK ){
danielk19774c999992008-07-16 18:17:55 +00002495 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
danielk1977662278e2007-11-05 15:30:12 +00002496 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002497 releasePage(pLastPg);
2498 if( rc!=SQLITE_OK ){
2499 return rc;
danielk1977662278e2007-11-05 15:30:12 +00002500 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002501 }
2502 }
2503
danielk19773460d192008-12-27 15:23:13 +00002504 if( nFin==0 ){
2505 iLastPg--;
2506 while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
danielk1977f4027782009-03-30 18:50:04 +00002507 if( PTRMAP_ISPAGE(pBt, iLastPg) ){
2508 MemPage *pPg;
2509 int rc = sqlite3BtreeGetPage(pBt, iLastPg, &pPg, 0);
2510 if( rc!=SQLITE_OK ){
2511 return rc;
2512 }
2513 rc = sqlite3PagerWrite(pPg->pDbPage);
2514 releasePage(pPg);
2515 if( rc!=SQLITE_OK ){
2516 return rc;
2517 }
2518 }
danielk19773460d192008-12-27 15:23:13 +00002519 iLastPg--;
2520 }
2521 sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
danielk1977dddbcdc2007-04-26 14:42:34 +00002522 }
2523 return SQLITE_OK;
2524}
2525
2526/*
2527** A write-transaction must be opened before calling this function.
2528** It performs a single unit of work towards an incremental vacuum.
2529**
2530** If the incremental vacuum is finished after this function has run,
shanebe217792009-03-05 04:20:31 +00002531** SQLITE_DONE is returned. If it is not finished, but no error occurred,
danielk1977dddbcdc2007-04-26 14:42:34 +00002532** SQLITE_OK is returned. Otherwise an SQLite error code.
2533*/
2534int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002535 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002536 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002537
2538 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00002539 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
2540 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002541 rc = SQLITE_DONE;
2542 }else{
2543 invalidateAllOverflowCache(pBt);
danielk1977bea2a942009-01-20 17:06:27 +00002544 rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt));
danielk1977dddbcdc2007-04-26 14:42:34 +00002545 }
drhd677b3d2007-08-20 22:48:41 +00002546 sqlite3BtreeLeave(p);
2547 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002548}
2549
2550/*
danielk19773b8a05f2007-03-19 17:44:26 +00002551** This routine is called prior to sqlite3PagerCommit when a transaction
danielk1977687566d2004-11-02 12:56:41 +00002552** is commited for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00002553**
2554** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
2555** the database file should be truncated to during the commit process.
2556** i.e. the database has been reorganized so that only the first *pnTrunc
2557** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00002558*/
danielk19773460d192008-12-27 15:23:13 +00002559static int autoVacuumCommit(BtShared *pBt){
danielk1977dddbcdc2007-04-26 14:42:34 +00002560 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002561 Pager *pPager = pBt->pPager;
drhf94a1732008-09-30 17:18:17 +00002562 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002563
drh1fee73e2007-08-29 04:00:57 +00002564 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00002565 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00002566 assert(pBt->autoVacuum);
2567 if( !pBt->incrVacuum ){
danielk19773460d192008-12-27 15:23:13 +00002568 Pgno nFin;
2569 Pgno nFree;
2570 Pgno nPtrmap;
2571 Pgno iFree;
2572 const int pgsz = pBt->pageSize;
2573 Pgno nOrig = pagerPagecount(pBt);
danielk1977687566d2004-11-02 12:56:41 +00002574
danielk1977ef165ce2009-04-06 17:50:03 +00002575 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
2576 /* It is not possible to create a database for which the final page
2577 ** is either a pointer-map page or the pending-byte page. If one
2578 ** is encountered, this indicates corruption.
2579 */
danielk19773460d192008-12-27 15:23:13 +00002580 return SQLITE_CORRUPT_BKPT;
2581 }
danielk1977ef165ce2009-04-06 17:50:03 +00002582
danielk19773460d192008-12-27 15:23:13 +00002583 nFree = get4byte(&pBt->pPage1->aData[36]);
2584 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
2585 nFin = nOrig - nFree - nPtrmap;
danielk1977ef165ce2009-04-06 17:50:03 +00002586 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
danielk19773460d192008-12-27 15:23:13 +00002587 nFin--;
2588 }
2589 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
2590 nFin--;
danielk1977dddbcdc2007-04-26 14:42:34 +00002591 }
danielk1977687566d2004-11-02 12:56:41 +00002592
danielk19773460d192008-12-27 15:23:13 +00002593 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
2594 rc = incrVacuumStep(pBt, nFin, iFree);
danielk1977dddbcdc2007-04-26 14:42:34 +00002595 }
danielk19773460d192008-12-27 15:23:13 +00002596 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00002597 rc = SQLITE_OK;
danielk19773460d192008-12-27 15:23:13 +00002598 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
2599 put4byte(&pBt->pPage1->aData[32], 0);
2600 put4byte(&pBt->pPage1->aData[36], 0);
2601 sqlite3PagerTruncateImage(pBt->pPager, nFin);
danielk1977dddbcdc2007-04-26 14:42:34 +00002602 }
2603 if( rc!=SQLITE_OK ){
2604 sqlite3PagerRollback(pPager);
2605 }
danielk1977687566d2004-11-02 12:56:41 +00002606 }
2607
danielk19773b8a05f2007-03-19 17:44:26 +00002608 assert( nRef==sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002609 return rc;
2610}
danielk1977dddbcdc2007-04-26 14:42:34 +00002611
shane831c3292008-11-10 17:14:58 +00002612#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
danielk1977687566d2004-11-02 12:56:41 +00002613
2614/*
drh80e35f42007-03-30 14:06:34 +00002615** This routine does the first phase of a two-phase commit. This routine
2616** causes a rollback journal to be created (if it does not already exist)
2617** and populated with enough information so that if a power loss occurs
2618** the database can be restored to its original state by playing back
2619** the journal. Then the contents of the journal are flushed out to
2620** the disk. After the journal is safely on oxide, the changes to the
2621** database are written into the database file and flushed to oxide.
2622** At the end of this call, the rollback journal still exists on the
2623** disk and we are still holding all locks, so the transaction has not
drh51898cf2009-04-19 20:51:06 +00002624** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
drh80e35f42007-03-30 14:06:34 +00002625** commit process.
2626**
2627** This call is a no-op if no write-transaction is currently active on pBt.
2628**
2629** Otherwise, sync the database file for the btree pBt. zMaster points to
2630** the name of a master journal file that should be written into the
2631** individual journal file, or is NULL, indicating no master journal file
2632** (single database transaction).
2633**
2634** When this is called, the master journal should already have been
2635** created, populated with this journal pointer and synced to disk.
2636**
2637** Once this is routine has returned, the only thing required to commit
2638** the write-transaction for this database file is to delete the journal.
2639*/
2640int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
2641 int rc = SQLITE_OK;
2642 if( p->inTrans==TRANS_WRITE ){
2643 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002644 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00002645#ifndef SQLITE_OMIT_AUTOVACUUM
2646 if( pBt->autoVacuum ){
danielk19773460d192008-12-27 15:23:13 +00002647 rc = autoVacuumCommit(pBt);
drh80e35f42007-03-30 14:06:34 +00002648 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002649 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002650 return rc;
2651 }
2652 }
2653#endif
drh49b9d332009-01-02 18:10:42 +00002654 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
drhd677b3d2007-08-20 22:48:41 +00002655 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002656 }
2657 return rc;
2658}
2659
2660/*
drh2aa679f2001-06-25 02:11:07 +00002661** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00002662**
drh6e345992007-03-30 11:12:08 +00002663** This routine implements the second phase of a 2-phase commit. The
drh51898cf2009-04-19 20:51:06 +00002664** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
2665** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
2666** routine did all the work of writing information out to disk and flushing the
drh6e345992007-03-30 11:12:08 +00002667** contents so that they are written onto the disk platter. All this
drh51898cf2009-04-19 20:51:06 +00002668** routine has to do is delete or truncate or zero the header in the
2669** the rollback journal (which causes the transaction to commit) and
2670** drop locks.
drh6e345992007-03-30 11:12:08 +00002671**
drh5e00f6c2001-09-13 13:46:56 +00002672** This will release the write lock on the database file. If there
2673** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002674*/
drh80e35f42007-03-30 14:06:34 +00002675int sqlite3BtreeCommitPhaseTwo(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002676 BtShared *pBt = p->pBt;
2677
drhd677b3d2007-08-20 22:48:41 +00002678 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002679 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002680
2681 /* If the handle has a write-transaction open, commit the shared-btrees
2682 ** transaction and set the shared state to TRANS_READ.
2683 */
2684 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00002685 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002686 assert( pBt->inTransaction==TRANS_WRITE );
2687 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00002688 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
danielk19777f7bc662006-01-23 13:47:47 +00002689 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002690 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002691 return rc;
2692 }
danielk1977aef0bf62005-12-30 16:28:01 +00002693 pBt->inTransaction = TRANS_READ;
danielk1977ee5741e2004-05-31 10:01:34 +00002694 }
danielk1977aef0bf62005-12-30 16:28:01 +00002695
2696 /* If the handle has any kind of transaction open, decrement the transaction
2697 ** count of the shared btree. If the transaction count reaches 0, set
2698 ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
2699 ** will unlock the pager.
2700 */
2701 if( p->inTrans!=TRANS_NONE ){
danielk1977fa542f12009-04-02 18:28:08 +00002702 clearAllSharedCacheTableLocks(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002703 pBt->nTransaction--;
2704 if( 0==pBt->nTransaction ){
2705 pBt->inTransaction = TRANS_NONE;
2706 }
2707 }
2708
drh51898cf2009-04-19 20:51:06 +00002709 /* Set the current transaction state to TRANS_NONE and unlock
danielk1977aef0bf62005-12-30 16:28:01 +00002710 ** the pager if this call closed the only read or write transaction.
2711 */
danielk1977bea2a942009-01-20 17:06:27 +00002712 btreeClearHasContent(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002713 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00002714 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002715
2716 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002717 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002718 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002719}
2720
drh80e35f42007-03-30 14:06:34 +00002721/*
2722** Do both phases of a commit.
2723*/
2724int sqlite3BtreeCommit(Btree *p){
2725 int rc;
drhd677b3d2007-08-20 22:48:41 +00002726 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00002727 rc = sqlite3BtreeCommitPhaseOne(p, 0);
2728 if( rc==SQLITE_OK ){
2729 rc = sqlite3BtreeCommitPhaseTwo(p);
2730 }
drhd677b3d2007-08-20 22:48:41 +00002731 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002732 return rc;
2733}
2734
danielk1977fbcd5852004-06-15 02:44:18 +00002735#ifndef NDEBUG
2736/*
2737** Return the number of write-cursors open on this handle. This is for use
2738** in assert() expressions, so it is only compiled if NDEBUG is not
2739** defined.
drhfb982642007-08-30 01:19:59 +00002740**
2741** For the purposes of this routine, a write-cursor is any cursor that
2742** is capable of writing to the databse. That means the cursor was
2743** originally opened for writing and the cursor has not be disabled
2744** by having its state changed to CURSOR_FAULT.
danielk1977fbcd5852004-06-15 02:44:18 +00002745*/
danielk1977aef0bf62005-12-30 16:28:01 +00002746static int countWriteCursors(BtShared *pBt){
danielk1977fbcd5852004-06-15 02:44:18 +00002747 BtCursor *pCur;
2748 int r = 0;
2749 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drhfb982642007-08-30 01:19:59 +00002750 if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
danielk1977fbcd5852004-06-15 02:44:18 +00002751 }
2752 return r;
2753}
2754#endif
2755
drhc39e0002004-05-07 23:50:57 +00002756/*
drhfb982642007-08-30 01:19:59 +00002757** This routine sets the state to CURSOR_FAULT and the error
2758** code to errCode for every cursor on BtShared that pBtree
2759** references.
2760**
2761** Every cursor is tripped, including cursors that belong
2762** to other database connections that happen to be sharing
2763** the cache with pBtree.
2764**
2765** This routine gets called when a rollback occurs.
2766** All cursors using the same cache must be tripped
2767** to prevent them from trying to use the btree after
2768** the rollback. The rollback may have deleted tables
2769** or moved root pages, so it is not sufficient to
2770** save the state of the cursor. The cursor must be
2771** invalidated.
2772*/
2773void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
2774 BtCursor *p;
2775 sqlite3BtreeEnter(pBtree);
2776 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
danielk1977bc2ca9e2008-11-13 14:28:28 +00002777 int i;
danielk1977be51a652008-10-08 17:58:48 +00002778 sqlite3BtreeClearCursor(p);
drhfb982642007-08-30 01:19:59 +00002779 p->eState = CURSOR_FAULT;
2780 p->skip = errCode;
danielk1977bc2ca9e2008-11-13 14:28:28 +00002781 for(i=0; i<=p->iPage; i++){
2782 releasePage(p->apPage[i]);
2783 p->apPage[i] = 0;
2784 }
drhfb982642007-08-30 01:19:59 +00002785 }
2786 sqlite3BtreeLeave(pBtree);
2787}
2788
2789/*
drhecdc7532001-09-23 02:35:53 +00002790** Rollback the transaction in progress. All cursors will be
2791** invalided by this operation. Any attempt to use a cursor
2792** that was open at the beginning of this operation will result
2793** in an error.
drh5e00f6c2001-09-13 13:46:56 +00002794**
2795** This will release the write lock on the database file. If there
2796** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002797*/
danielk1977aef0bf62005-12-30 16:28:01 +00002798int sqlite3BtreeRollback(Btree *p){
danielk19778d34dfd2006-01-24 16:37:57 +00002799 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002800 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00002801 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00002802
drhd677b3d2007-08-20 22:48:41 +00002803 sqlite3BtreeEnter(p);
danielk19772b8c13e2006-01-24 14:21:24 +00002804 rc = saveAllCursors(pBt, 0, 0);
danielk19778d34dfd2006-01-24 16:37:57 +00002805#ifndef SQLITE_OMIT_SHARED_CACHE
danielk19772b8c13e2006-01-24 14:21:24 +00002806 if( rc!=SQLITE_OK ){
shanebe217792009-03-05 04:20:31 +00002807 /* This is a horrible situation. An IO or malloc() error occurred whilst
danielk19778d34dfd2006-01-24 16:37:57 +00002808 ** trying to save cursor positions. If this is an automatic rollback (as
2809 ** the result of a constraint, malloc() failure or IO error) then
2810 ** the cache may be internally inconsistent (not contain valid trees) so
2811 ** we cannot simply return the error to the caller. Instead, abort
2812 ** all queries that may be using any of the cursors that failed to save.
2813 */
drhfb982642007-08-30 01:19:59 +00002814 sqlite3BtreeTripAllCursors(p, rc);
danielk19772b8c13e2006-01-24 14:21:24 +00002815 }
danielk19778d34dfd2006-01-24 16:37:57 +00002816#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002817 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002818
2819 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00002820 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00002821
danielk19778d34dfd2006-01-24 16:37:57 +00002822 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00002823 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00002824 if( rc2!=SQLITE_OK ){
2825 rc = rc2;
2826 }
2827
drh24cd67e2004-05-10 16:18:47 +00002828 /* The rollback may have destroyed the pPage1->aData value. So
drh16a9b832007-05-05 18:39:25 +00002829 ** call sqlite3BtreeGetPage() on page 1 again to make
2830 ** sure pPage1->aData is set correctly. */
2831 if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh24cd67e2004-05-10 16:18:47 +00002832 releasePage(pPage1);
2833 }
danielk1977fbcd5852004-06-15 02:44:18 +00002834 assert( countWriteCursors(pBt)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002835 pBt->inTransaction = TRANS_READ;
drh24cd67e2004-05-10 16:18:47 +00002836 }
danielk1977aef0bf62005-12-30 16:28:01 +00002837
2838 if( p->inTrans!=TRANS_NONE ){
danielk1977fa542f12009-04-02 18:28:08 +00002839 clearAllSharedCacheTableLocks(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002840 assert( pBt->nTransaction>0 );
2841 pBt->nTransaction--;
2842 if( 0==pBt->nTransaction ){
2843 pBt->inTransaction = TRANS_NONE;
2844 }
2845 }
2846
danielk1977bea2a942009-01-20 17:06:27 +00002847 btreeClearHasContent(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002848 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00002849 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002850
2851 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002852 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00002853 return rc;
2854}
2855
2856/*
danielk1977bd434552009-03-18 10:33:00 +00002857** Start a statement subtransaction. The subtransaction can can be rolled
2858** back independently of the main transaction. You must start a transaction
2859** before starting a subtransaction. The subtransaction is ended automatically
2860** if the main transaction commits or rolls back.
drhab01f612004-05-22 02:55:23 +00002861**
2862** Statement subtransactions are used around individual SQL statements
2863** that are contained within a BEGIN...COMMIT block. If a constraint
2864** error occurs within the statement, the effect of that one statement
2865** can be rolled back without having to rollback the entire transaction.
danielk1977bd434552009-03-18 10:33:00 +00002866**
2867** A statement sub-transaction is implemented as an anonymous savepoint. The
2868** value passed as the second parameter is the total number of savepoints,
2869** including the new anonymous savepoint, open on the B-Tree. i.e. if there
2870** are no active savepoints and no other statement-transactions open,
2871** iStatement is 1. This anonymous savepoint can be released or rolled back
2872** using the sqlite3BtreeSavepoint() function.
drh663fc632002-02-02 18:49:19 +00002873*/
danielk1977bd434552009-03-18 10:33:00 +00002874int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
drh663fc632002-02-02 18:49:19 +00002875 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002876 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002877 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00002878 assert( p->inTrans==TRANS_WRITE );
drh64022502009-01-09 14:11:04 +00002879 assert( pBt->readOnly==0 );
danielk1977bd434552009-03-18 10:33:00 +00002880 assert( iStatement>0 );
2881 assert( iStatement>p->db->nSavepoint );
2882 if( NEVER(p->inTrans!=TRANS_WRITE || pBt->readOnly) ){
drh64022502009-01-09 14:11:04 +00002883 rc = SQLITE_INTERNAL;
drhd677b3d2007-08-20 22:48:41 +00002884 }else{
2885 assert( pBt->inTransaction==TRANS_WRITE );
drh64022502009-01-09 14:11:04 +00002886 /* At the pager level, a statement transaction is a savepoint with
2887 ** an index greater than all savepoints created explicitly using
2888 ** SQL statements. It is illegal to open, release or rollback any
2889 ** such savepoints while the statement transaction savepoint is active.
2890 */
danielk1977bd434552009-03-18 10:33:00 +00002891 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
danielk197797a227c2006-01-20 16:32:04 +00002892 }
drhd677b3d2007-08-20 22:48:41 +00002893 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00002894 return rc;
2895}
2896
2897/*
danielk1977fd7f0452008-12-17 17:30:26 +00002898** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
2899** or SAVEPOINT_RELEASE. This function either releases or rolls back the
danielk197712dd5492008-12-18 15:45:07 +00002900** savepoint identified by parameter iSavepoint, depending on the value
2901** of op.
2902**
2903** Normally, iSavepoint is greater than or equal to zero. However, if op is
2904** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
2905** contents of the entire transaction are rolled back. This is different
2906** from a normal transaction rollback, as no locks are released and the
2907** transaction remains open.
danielk1977fd7f0452008-12-17 17:30:26 +00002908*/
2909int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
2910 int rc = SQLITE_OK;
2911 if( p && p->inTrans==TRANS_WRITE ){
2912 BtShared *pBt = p->pBt;
danielk1977fd7f0452008-12-17 17:30:26 +00002913 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
2914 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
2915 sqlite3BtreeEnter(p);
danielk1977fd7f0452008-12-17 17:30:26 +00002916 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
drh9f0bbf92009-01-02 21:08:09 +00002917 if( rc==SQLITE_OK ){
2918 rc = newDatabase(pBt);
2919 }
danielk1977fd7f0452008-12-17 17:30:26 +00002920 sqlite3BtreeLeave(p);
2921 }
2922 return rc;
2923}
2924
2925/*
drh8b2f49b2001-06-08 00:21:52 +00002926** Create a new cursor for the BTree whose root is on the page
2927** iTable. The act of acquiring a cursor gets a read lock on
2928** the database file.
drh1bee3d72001-10-15 00:44:35 +00002929**
2930** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00002931** If wrFlag==1, then the cursor can be used for reading or for
2932** writing if other conditions for writing are also met. These
2933** are the conditions that must be met in order for writing to
2934** be allowed:
drh6446c4d2001-12-15 14:22:18 +00002935**
drhf74b8d92002-09-01 23:20:45 +00002936** 1: The cursor must have been opened with wrFlag==1
2937**
drhfe5d71d2007-03-19 11:54:10 +00002938** 2: Other database connections that share the same pager cache
2939** but which are not in the READ_UNCOMMITTED state may not have
2940** cursors open with wrFlag==0 on the same table. Otherwise
2941** the changes made by this write cursor would be visible to
2942** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00002943**
2944** 3: The database must be writable (not on read-only media)
2945**
2946** 4: There must be an active transaction.
2947**
drh6446c4d2001-12-15 14:22:18 +00002948** No checking is done to make sure that page iTable really is the
2949** root page of a b-tree. If it is not, then the cursor acquired
2950** will not work correctly.
danielk197771d5d2c2008-09-29 11:49:47 +00002951**
2952** It is assumed that the sqlite3BtreeCursorSize() bytes of memory
2953** pointed to by pCur have been zeroed by the caller.
drha059ad02001-04-17 20:09:11 +00002954*/
drhd677b3d2007-08-20 22:48:41 +00002955static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00002956 Btree *p, /* The btree */
2957 int iTable, /* Root page of table to open */
2958 int wrFlag, /* 1 to write. 0 read-only */
2959 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
2960 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00002961){
drha059ad02001-04-17 20:09:11 +00002962 int rc;
danielk197789d40042008-11-17 14:20:56 +00002963 Pgno nPage;
danielk1977aef0bf62005-12-30 16:28:01 +00002964 BtShared *pBt = p->pBt;
drhecdc7532001-09-23 02:35:53 +00002965
drh1fee73e2007-08-29 04:00:57 +00002966 assert( sqlite3BtreeHoldsMutex(p) );
drhf49661a2008-12-10 16:45:50 +00002967 assert( wrFlag==0 || wrFlag==1 );
drh8dcd7ca2004-08-08 19:43:29 +00002968 if( wrFlag ){
drh64022502009-01-09 14:11:04 +00002969 assert( !pBt->readOnly );
2970 if( NEVER(pBt->readOnly) ){
drh8dcd7ca2004-08-08 19:43:29 +00002971 return SQLITE_READONLY;
2972 }
danielk1977404ca072009-03-16 13:19:36 +00002973 rc = checkForReadConflicts(p, iTable, 0, 0);
2974 if( rc!=SQLITE_OK ){
2975 assert( rc==SQLITE_LOCKED_SHAREDCACHE );
2976 return rc;
drh8dcd7ca2004-08-08 19:43:29 +00002977 }
drha0c9a112004-03-10 13:42:37 +00002978 }
danielk1977aef0bf62005-12-30 16:28:01 +00002979
drh4b70f112004-05-02 21:12:19 +00002980 if( pBt->pPage1==0 ){
danielk1977aef0bf62005-12-30 16:28:01 +00002981 rc = lockBtreeWithRetry(p);
drha059ad02001-04-17 20:09:11 +00002982 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00002983 return rc;
2984 }
2985 }
drh8b2f49b2001-06-08 00:21:52 +00002986 pCur->pgnoRoot = (Pgno)iTable;
danielk197789d40042008-11-17 14:20:56 +00002987 rc = sqlite3PagerPagecount(pBt->pPager, (int *)&nPage);
2988 if( rc!=SQLITE_OK ){
2989 return rc;
2990 }
2991 if( iTable==1 && nPage==0 ){
drh24cd67e2004-05-10 16:18:47 +00002992 rc = SQLITE_EMPTY;
2993 goto create_cursor_exception;
2994 }
danielk197771d5d2c2008-09-29 11:49:47 +00002995 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
drhbd03cae2001-06-02 02:40:57 +00002996 if( rc!=SQLITE_OK ){
2997 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00002998 }
danielk1977aef0bf62005-12-30 16:28:01 +00002999
danielk1977aef0bf62005-12-30 16:28:01 +00003000 /* Now that no other errors can occur, finish filling in the BtCursor
3001 ** variables, link the cursor into the BtShared list and set *ppCur (the
3002 ** output argument to this function).
3003 */
drh1e968a02008-03-25 00:22:21 +00003004 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00003005 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00003006 pCur->pBt = pBt;
drhf49661a2008-12-10 16:45:50 +00003007 pCur->wrFlag = (u8)wrFlag;
drha059ad02001-04-17 20:09:11 +00003008 pCur->pNext = pBt->pCursor;
3009 if( pCur->pNext ){
3010 pCur->pNext->pPrev = pCur;
3011 }
3012 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00003013 pCur->eState = CURSOR_INVALID;
drh7f751222009-03-17 22:33:00 +00003014 pCur->cachedRowid = 0;
drhbd03cae2001-06-02 02:40:57 +00003015
danielk1977aef0bf62005-12-30 16:28:01 +00003016 return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003017
drhbd03cae2001-06-02 02:40:57 +00003018create_cursor_exception:
danielk197771d5d2c2008-09-29 11:49:47 +00003019 releasePage(pCur->apPage[0]);
drh5e00f6c2001-09-13 13:46:56 +00003020 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00003021 return rc;
drha059ad02001-04-17 20:09:11 +00003022}
drhd677b3d2007-08-20 22:48:41 +00003023int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00003024 Btree *p, /* The btree */
3025 int iTable, /* Root page of table to open */
3026 int wrFlag, /* 1 to write. 0 read-only */
3027 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
3028 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00003029){
3030 int rc;
3031 sqlite3BtreeEnter(p);
danielk1977cd3e8f72008-03-25 09:47:35 +00003032 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
drhd677b3d2007-08-20 22:48:41 +00003033 sqlite3BtreeLeave(p);
3034 return rc;
3035}
drh7f751222009-03-17 22:33:00 +00003036
3037/*
3038** Return the size of a BtCursor object in bytes.
3039**
3040** This interfaces is needed so that users of cursors can preallocate
3041** sufficient storage to hold a cursor. The BtCursor object is opaque
3042** to users so they cannot do the sizeof() themselves - they must call
3043** this routine.
3044*/
3045int sqlite3BtreeCursorSize(void){
danielk1977cd3e8f72008-03-25 09:47:35 +00003046 return sizeof(BtCursor);
3047}
3048
drh7f751222009-03-17 22:33:00 +00003049/*
3050** Set the cached rowid value of every cursor in the same database file
3051** as pCur and having the same root page number as pCur. The value is
3052** set to iRowid.
3053**
3054** Only positive rowid values are considered valid for this cache.
3055** The cache is initialized to zero, indicating an invalid cache.
3056** A btree will work fine with zero or negative rowids. We just cannot
3057** cache zero or negative rowids, which means tables that use zero or
3058** negative rowids might run a little slower. But in practice, zero
3059** or negative rowids are very uncommon so this should not be a problem.
3060*/
3061void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
3062 BtCursor *p;
3063 for(p=pCur->pBt->pCursor; p; p=p->pNext){
3064 if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
3065 }
3066 assert( pCur->cachedRowid==iRowid );
3067}
drhd677b3d2007-08-20 22:48:41 +00003068
drh7f751222009-03-17 22:33:00 +00003069/*
3070** Return the cached rowid for the given cursor. A negative or zero
3071** return value indicates that the rowid cache is invalid and should be
3072** ignored. If the rowid cache has never before been set, then a
3073** zero is returned.
3074*/
3075sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
3076 return pCur->cachedRowid;
3077}
drha059ad02001-04-17 20:09:11 +00003078
3079/*
drh5e00f6c2001-09-13 13:46:56 +00003080** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00003081** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00003082*/
drh3aac2dd2004-04-26 14:10:20 +00003083int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00003084 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00003085 if( pBtree ){
danielk197771d5d2c2008-09-29 11:49:47 +00003086 int i;
danielk1977cd3e8f72008-03-25 09:47:35 +00003087 BtShared *pBt = pCur->pBt;
3088 sqlite3BtreeEnter(pBtree);
danielk1977be51a652008-10-08 17:58:48 +00003089 sqlite3BtreeClearCursor(pCur);
danielk1977cd3e8f72008-03-25 09:47:35 +00003090 if( pCur->pPrev ){
3091 pCur->pPrev->pNext = pCur->pNext;
3092 }else{
3093 pBt->pCursor = pCur->pNext;
3094 }
3095 if( pCur->pNext ){
3096 pCur->pNext->pPrev = pCur->pPrev;
3097 }
danielk197771d5d2c2008-09-29 11:49:47 +00003098 for(i=0; i<=pCur->iPage; i++){
3099 releasePage(pCur->apPage[i]);
3100 }
danielk1977cd3e8f72008-03-25 09:47:35 +00003101 unlockBtreeIfUnused(pBt);
3102 invalidateOverflowCache(pCur);
3103 /* sqlite3_free(pCur); */
3104 sqlite3BtreeLeave(pBtree);
drha059ad02001-04-17 20:09:11 +00003105 }
drh8c42ca92001-06-22 19:15:00 +00003106 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003107}
3108
drh7e3b0a02001-04-28 16:52:40 +00003109/*
drh5e2f8b92001-05-28 00:41:15 +00003110** Make a temporary cursor by filling in the fields of pTempCur.
3111** The temporary cursor is not on the cursor list for the Btree.
3112*/
drh16a9b832007-05-05 18:39:25 +00003113void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
danielk197771d5d2c2008-09-29 11:49:47 +00003114 int i;
drh1fee73e2007-08-29 04:00:57 +00003115 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00003116 memcpy(pTempCur, pCur, sizeof(BtCursor));
drh5e2f8b92001-05-28 00:41:15 +00003117 pTempCur->pNext = 0;
3118 pTempCur->pPrev = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003119 for(i=0; i<=pTempCur->iPage; i++){
3120 sqlite3PagerRef(pTempCur->apPage[i]->pDbPage);
drhecdc7532001-09-23 02:35:53 +00003121 }
danielk197736e20932008-11-26 07:40:30 +00003122 assert( pTempCur->pKey==0 );
drh5e2f8b92001-05-28 00:41:15 +00003123}
3124
3125/*
drhbd03cae2001-06-02 02:40:57 +00003126** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00003127** function above.
3128*/
drh16a9b832007-05-05 18:39:25 +00003129void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
danielk197771d5d2c2008-09-29 11:49:47 +00003130 int i;
drh1fee73e2007-08-29 04:00:57 +00003131 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00003132 for(i=0; i<=pCur->iPage; i++){
3133 sqlite3PagerUnref(pCur->apPage[i]->pDbPage);
drhecdc7532001-09-23 02:35:53 +00003134 }
danielk197736e20932008-11-26 07:40:30 +00003135 sqlite3_free(pCur->pKey);
drh5e2f8b92001-05-28 00:41:15 +00003136}
3137
drh7f751222009-03-17 22:33:00 +00003138
3139
drh5e2f8b92001-05-28 00:41:15 +00003140/*
drh86057612007-06-26 01:04:48 +00003141** Make sure the BtCursor* given in the argument has a valid
3142** BtCursor.info structure. If it is not already valid, call
danielk19771cc5ed82007-05-16 17:28:43 +00003143** sqlite3BtreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00003144**
3145** BtCursor.info is a cache of the information in the current cell.
drh16a9b832007-05-05 18:39:25 +00003146** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
drh86057612007-06-26 01:04:48 +00003147**
3148** 2007-06-25: There is a bug in some versions of MSVC that cause the
3149** compiler to crash when getCellInfo() is implemented as a macro.
3150** But there is a measureable speed advantage to using the macro on gcc
3151** (when less compiler optimizations like -Os or -O0 are used and the
3152** compiler is not doing agressive inlining.) So we use a real function
3153** for MSVC and a macro for everything else. Ticket #2457.
drh9188b382004-05-14 21:12:22 +00003154*/
drh9188b382004-05-14 21:12:22 +00003155#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00003156 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00003157 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00003158 int iPage = pCur->iPage;
drh51c6d962004-06-06 00:42:25 +00003159 memset(&info, 0, sizeof(info));
danielk197771d5d2c2008-09-29 11:49:47 +00003160 sqlite3BtreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
drh9188b382004-05-14 21:12:22 +00003161 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00003162 }
danielk19771cc5ed82007-05-16 17:28:43 +00003163#else
3164 #define assertCellInfo(x)
3165#endif
drh86057612007-06-26 01:04:48 +00003166#ifdef _MSC_VER
3167 /* Use a real function in MSVC to work around bugs in that compiler. */
3168 static void getCellInfo(BtCursor *pCur){
3169 if( pCur->info.nSize==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003170 int iPage = pCur->iPage;
3171 sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
drha2c20e42008-03-29 16:01:04 +00003172 pCur->validNKey = 1;
drh86057612007-06-26 01:04:48 +00003173 }else{
3174 assertCellInfo(pCur);
3175 }
3176 }
3177#else /* if not _MSC_VER */
3178 /* Use a macro in all other compilers so that the function is inlined */
danielk197771d5d2c2008-09-29 11:49:47 +00003179#define getCellInfo(pCur) \
3180 if( pCur->info.nSize==0 ){ \
3181 int iPage = pCur->iPage; \
3182 sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
3183 pCur->validNKey = 1; \
3184 }else{ \
3185 assertCellInfo(pCur); \
drh86057612007-06-26 01:04:48 +00003186 }
3187#endif /* _MSC_VER */
drh9188b382004-05-14 21:12:22 +00003188
3189/*
drh3aac2dd2004-04-26 14:10:20 +00003190** Set *pSize to the size of the buffer needed to hold the value of
3191** the key for the current entry. If the cursor is not pointing
3192** to a valid entry, *pSize is set to 0.
3193**
drh4b70f112004-05-02 21:12:19 +00003194** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00003195** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00003196*/
drh4a1c3802004-05-12 15:15:47 +00003197int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drhd677b3d2007-08-20 22:48:41 +00003198 int rc;
3199
drh1fee73e2007-08-29 04:00:57 +00003200 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003201 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003202 if( rc==SQLITE_OK ){
3203 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3204 if( pCur->eState==CURSOR_INVALID ){
3205 *pSize = 0;
3206 }else{
drh86057612007-06-26 01:04:48 +00003207 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00003208 *pSize = pCur->info.nKey;
3209 }
drh72f82862001-05-24 21:06:34 +00003210 }
danielk1977da184232006-01-05 11:34:32 +00003211 return rc;
drha059ad02001-04-17 20:09:11 +00003212}
drh2af926b2001-05-15 00:39:25 +00003213
drh72f82862001-05-24 21:06:34 +00003214/*
drh0e1c19e2004-05-11 00:58:56 +00003215** Set *pSize to the number of bytes of data in the entry the
3216** cursor currently points to. Always return SQLITE_OK.
3217** Failure is not possible. If the cursor is not currently
3218** pointing to an entry (which can happen, for example, if
3219** the database is empty) then *pSize is set to 0.
3220*/
3221int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drhd677b3d2007-08-20 22:48:41 +00003222 int rc;
3223
drh1fee73e2007-08-29 04:00:57 +00003224 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003225 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003226 if( rc==SQLITE_OK ){
3227 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3228 if( pCur->eState==CURSOR_INVALID ){
3229 /* Not pointing at a valid entry - set *pSize to 0. */
3230 *pSize = 0;
3231 }else{
drh86057612007-06-26 01:04:48 +00003232 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00003233 *pSize = pCur->info.nData;
3234 }
drh0e1c19e2004-05-11 00:58:56 +00003235 }
danielk1977da184232006-01-05 11:34:32 +00003236 return rc;
drh0e1c19e2004-05-11 00:58:56 +00003237}
3238
3239/*
danielk1977d04417962007-05-02 13:16:30 +00003240** Given the page number of an overflow page in the database (parameter
3241** ovfl), this function finds the page number of the next page in the
3242** linked list of overflow pages. If possible, it uses the auto-vacuum
3243** pointer-map data instead of reading the content of page ovfl to do so.
3244**
3245** If an error occurs an SQLite error code is returned. Otherwise:
3246**
danielk1977bea2a942009-01-20 17:06:27 +00003247** The page number of the next overflow page in the linked list is
3248** written to *pPgnoNext. If page ovfl is the last page in its linked
3249** list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003250**
danielk1977bea2a942009-01-20 17:06:27 +00003251** If ppPage is not NULL, and a reference to the MemPage object corresponding
3252** to page number pOvfl was obtained, then *ppPage is set to point to that
3253** reference. It is the responsibility of the caller to call releasePage()
3254** on *ppPage to free the reference. In no reference was obtained (because
3255** the pointer-map was used to obtain the value for *pPgnoNext), then
3256** *ppPage is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003257*/
3258static int getOverflowPage(
3259 BtShared *pBt,
3260 Pgno ovfl, /* Overflow page */
danielk1977bea2a942009-01-20 17:06:27 +00003261 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
danielk1977d04417962007-05-02 13:16:30 +00003262 Pgno *pPgnoNext /* OUT: Next overflow page number */
3263){
3264 Pgno next = 0;
danielk1977bea2a942009-01-20 17:06:27 +00003265 MemPage *pPage = 0;
drh1bd10f82008-12-10 21:19:56 +00003266 int rc = SQLITE_OK;
danielk1977d04417962007-05-02 13:16:30 +00003267
drh1fee73e2007-08-29 04:00:57 +00003268 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bea2a942009-01-20 17:06:27 +00003269 assert(pPgnoNext);
danielk1977d04417962007-05-02 13:16:30 +00003270
3271#ifndef SQLITE_OMIT_AUTOVACUUM
3272 /* Try to find the next page in the overflow list using the
3273 ** autovacuum pointer-map pages. Guess that the next page in
3274 ** the overflow list is page number (ovfl+1). If that guess turns
3275 ** out to be wrong, fall back to loading the data of page
3276 ** number ovfl to determine the next page number.
3277 */
3278 if( pBt->autoVacuum ){
3279 Pgno pgno;
3280 Pgno iGuess = ovfl+1;
3281 u8 eType;
3282
3283 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
3284 iGuess++;
3285 }
3286
danielk197789d40042008-11-17 14:20:56 +00003287 if( iGuess<=pagerPagecount(pBt) ){
danielk1977d04417962007-05-02 13:16:30 +00003288 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
danielk1977bea2a942009-01-20 17:06:27 +00003289 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
danielk1977d04417962007-05-02 13:16:30 +00003290 next = iGuess;
danielk1977bea2a942009-01-20 17:06:27 +00003291 rc = SQLITE_DONE;
danielk1977d04417962007-05-02 13:16:30 +00003292 }
3293 }
3294 }
3295#endif
3296
danielk1977bea2a942009-01-20 17:06:27 +00003297 if( rc==SQLITE_OK ){
3298 rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, 0);
danielk1977d04417962007-05-02 13:16:30 +00003299 assert(rc==SQLITE_OK || pPage==0);
3300 if( next==0 && rc==SQLITE_OK ){
3301 next = get4byte(pPage->aData);
3302 }
danielk1977443c0592009-01-16 15:21:05 +00003303 }
danielk197745d68822009-01-16 16:23:38 +00003304
danielk1977bea2a942009-01-20 17:06:27 +00003305 *pPgnoNext = next;
3306 if( ppPage ){
3307 *ppPage = pPage;
3308 }else{
3309 releasePage(pPage);
3310 }
3311 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
danielk1977d04417962007-05-02 13:16:30 +00003312}
3313
danielk1977da107192007-05-04 08:32:13 +00003314/*
3315** Copy data from a buffer to a page, or from a page to a buffer.
3316**
3317** pPayload is a pointer to data stored on database page pDbPage.
3318** If argument eOp is false, then nByte bytes of data are copied
3319** from pPayload to the buffer pointed at by pBuf. If eOp is true,
3320** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
3321** of data are copied from the buffer pBuf to pPayload.
3322**
3323** SQLITE_OK is returned on success, otherwise an error code.
3324*/
3325static int copyPayload(
3326 void *pPayload, /* Pointer to page data */
3327 void *pBuf, /* Pointer to buffer */
3328 int nByte, /* Number of bytes to copy */
3329 int eOp, /* 0 -> copy from page, 1 -> copy to page */
3330 DbPage *pDbPage /* Page containing pPayload */
3331){
3332 if( eOp ){
3333 /* Copy data from buffer to page (a write operation) */
3334 int rc = sqlite3PagerWrite(pDbPage);
3335 if( rc!=SQLITE_OK ){
3336 return rc;
3337 }
3338 memcpy(pPayload, pBuf, nByte);
3339 }else{
3340 /* Copy data from page to buffer (a read operation) */
3341 memcpy(pBuf, pPayload, nByte);
3342 }
3343 return SQLITE_OK;
3344}
danielk1977d04417962007-05-02 13:16:30 +00003345
3346/*
danielk19779f8d6402007-05-02 17:48:45 +00003347** This function is used to read or overwrite payload information
3348** for the entry that the pCur cursor is pointing to. If the eOp
3349** parameter is 0, this is a read operation (data copied into
3350** buffer pBuf). If it is non-zero, a write (data copied from
3351** buffer pBuf).
3352**
3353** A total of "amt" bytes are read or written beginning at "offset".
3354** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00003355**
3356** This routine does not make a distinction between key and data.
danielk19779f8d6402007-05-02 17:48:45 +00003357** It just reads or writes bytes from the payload area. Data might
3358** appear on the main page or be scattered out on multiple overflow
3359** pages.
danielk1977da107192007-05-04 08:32:13 +00003360**
danielk1977dcbb5d32007-05-04 18:36:44 +00003361** If the BtCursor.isIncrblobHandle flag is set, and the current
danielk1977da107192007-05-04 08:32:13 +00003362** cursor entry uses one or more overflow pages, this function
3363** allocates space for and lazily popluates the overflow page-list
3364** cache array (BtCursor.aOverflow). Subsequent calls use this
3365** cache to make seeking to the supplied offset more efficient.
3366**
3367** Once an overflow page-list cache has been allocated, it may be
3368** invalidated if some other cursor writes to the same table, or if
3369** the cursor is moved to a different row. Additionally, in auto-vacuum
3370** mode, the following events may invalidate an overflow page-list cache.
3371**
3372** * An incremental vacuum,
3373** * A commit in auto_vacuum="full" mode,
3374** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00003375*/
danielk19779f8d6402007-05-02 17:48:45 +00003376static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00003377 BtCursor *pCur, /* Cursor pointing to entry to read from */
danielk197789d40042008-11-17 14:20:56 +00003378 u32 offset, /* Begin reading this far into payload */
3379 u32 amt, /* Read this many bytes */
drh3aac2dd2004-04-26 14:10:20 +00003380 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00003381 int skipKey, /* offset begins at data if this is true */
3382 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00003383){
3384 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00003385 int rc = SQLITE_OK;
drhfa1a98a2004-05-14 19:08:17 +00003386 u32 nKey;
danielk19772dec9702007-05-02 16:48:37 +00003387 int iIdx = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003388 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
danielk19770d065412008-11-12 18:21:36 +00003389 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
drh3aac2dd2004-04-26 14:10:20 +00003390
danielk1977da107192007-05-04 08:32:13 +00003391 assert( pPage );
danielk1977da184232006-01-05 11:34:32 +00003392 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003393 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh1fee73e2007-08-29 04:00:57 +00003394 assert( cursorHoldsMutex(pCur) );
danielk1977da107192007-05-04 08:32:13 +00003395
drh86057612007-06-26 01:04:48 +00003396 getCellInfo(pCur);
drh366fda62006-01-13 02:35:09 +00003397 aPayload = pCur->info.pCell + pCur->info.nHeader;
drhf49661a2008-12-10 16:45:50 +00003398 nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
danielk1977da107192007-05-04 08:32:13 +00003399
drh3aac2dd2004-04-26 14:10:20 +00003400 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003401 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00003402 }
danielk19770d065412008-11-12 18:21:36 +00003403 if( offset+amt > nKey+pCur->info.nData
3404 || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
3405 ){
danielk1977da107192007-05-04 08:32:13 +00003406 /* Trying to read or write past the end of the data is an error */
danielk197767fd7a92008-09-10 17:53:35 +00003407 return SQLITE_CORRUPT_BKPT;
drh3aac2dd2004-04-26 14:10:20 +00003408 }
danielk1977da107192007-05-04 08:32:13 +00003409
3410 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00003411 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00003412 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00003413 if( a+offset>pCur->info.nLocal ){
3414 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00003415 }
danielk1977da107192007-05-04 08:32:13 +00003416 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00003417 offset = 0;
drha34b6762004-05-07 13:30:42 +00003418 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00003419 amt -= a;
drhdd793422001-06-28 01:54:48 +00003420 }else{
drhfa1a98a2004-05-14 19:08:17 +00003421 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00003422 }
danielk1977da107192007-05-04 08:32:13 +00003423
3424 if( rc==SQLITE_OK && amt>0 ){
danielk197789d40042008-11-17 14:20:56 +00003425 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
danielk1977da107192007-05-04 08:32:13 +00003426 Pgno nextPage;
3427
drhfa1a98a2004-05-14 19:08:17 +00003428 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00003429
danielk19772dec9702007-05-02 16:48:37 +00003430#ifndef SQLITE_OMIT_INCRBLOB
danielk1977dcbb5d32007-05-04 18:36:44 +00003431 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
danielk1977da107192007-05-04 08:32:13 +00003432 ** has not been allocated, allocate it now. The array is sized at
3433 ** one entry for each overflow page in the overflow chain. The
3434 ** page number of the first overflow page is stored in aOverflow[0],
3435 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
3436 ** (the cache is lazily populated).
3437 */
danielk1977dcbb5d32007-05-04 18:36:44 +00003438 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
danielk19772dec9702007-05-02 16:48:37 +00003439 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
drh17435752007-08-16 04:30:38 +00003440 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
danielk19772dec9702007-05-02 16:48:37 +00003441 if( nOvfl && !pCur->aOverflow ){
danielk1977da107192007-05-04 08:32:13 +00003442 rc = SQLITE_NOMEM;
danielk19772dec9702007-05-02 16:48:37 +00003443 }
3444 }
danielk1977da107192007-05-04 08:32:13 +00003445
3446 /* If the overflow page-list cache has been allocated and the
3447 ** entry for the first required overflow page is valid, skip
3448 ** directly to it.
3449 */
danielk19772dec9702007-05-02 16:48:37 +00003450 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
3451 iIdx = (offset/ovflSize);
3452 nextPage = pCur->aOverflow[iIdx];
3453 offset = (offset%ovflSize);
3454 }
3455#endif
danielk1977da107192007-05-04 08:32:13 +00003456
3457 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
3458
3459#ifndef SQLITE_OMIT_INCRBLOB
3460 /* If required, populate the overflow page-list cache. */
3461 if( pCur->aOverflow ){
3462 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
3463 pCur->aOverflow[iIdx] = nextPage;
3464 }
3465#endif
3466
danielk1977d04417962007-05-02 13:16:30 +00003467 if( offset>=ovflSize ){
3468 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00003469 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00003470 ** data is not required. So first try to lookup the overflow
3471 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00003472 ** function.
danielk1977d04417962007-05-02 13:16:30 +00003473 */
danielk19772dec9702007-05-02 16:48:37 +00003474#ifndef SQLITE_OMIT_INCRBLOB
danielk1977da107192007-05-04 08:32:13 +00003475 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
3476 nextPage = pCur->aOverflow[iIdx+1];
3477 } else
danielk19772dec9702007-05-02 16:48:37 +00003478#endif
danielk1977da107192007-05-04 08:32:13 +00003479 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
danielk1977da107192007-05-04 08:32:13 +00003480 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00003481 }else{
danielk19779f8d6402007-05-02 17:48:45 +00003482 /* Need to read this page properly. It contains some of the
3483 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00003484 */
3485 DbPage *pDbPage;
danielk1977cfe9a692004-06-16 12:00:29 +00003486 int a = amt;
danielk1977d04417962007-05-02 13:16:30 +00003487 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
danielk1977da107192007-05-04 08:32:13 +00003488 if( rc==SQLITE_OK ){
3489 aPayload = sqlite3PagerGetData(pDbPage);
3490 nextPage = get4byte(aPayload);
3491 if( a + offset > ovflSize ){
3492 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00003493 }
danielk1977da107192007-05-04 08:32:13 +00003494 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
3495 sqlite3PagerUnref(pDbPage);
3496 offset = 0;
3497 amt -= a;
3498 pBuf += a;
danielk19779f8d6402007-05-02 17:48:45 +00003499 }
danielk1977cfe9a692004-06-16 12:00:29 +00003500 }
drh2af926b2001-05-15 00:39:25 +00003501 }
drh2af926b2001-05-15 00:39:25 +00003502 }
danielk1977cfe9a692004-06-16 12:00:29 +00003503
danielk1977da107192007-05-04 08:32:13 +00003504 if( rc==SQLITE_OK && amt>0 ){
drh49285702005-09-17 15:20:26 +00003505 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00003506 }
danielk1977da107192007-05-04 08:32:13 +00003507 return rc;
drh2af926b2001-05-15 00:39:25 +00003508}
3509
drh72f82862001-05-24 21:06:34 +00003510/*
drh3aac2dd2004-04-26 14:10:20 +00003511** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003512** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003513** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00003514**
drh3aac2dd2004-04-26 14:10:20 +00003515** Return SQLITE_OK on success or an error code if anything goes
3516** wrong. An error is returned if "offset+amt" is larger than
3517** the available payload.
drh72f82862001-05-24 21:06:34 +00003518*/
drha34b6762004-05-07 13:30:42 +00003519int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003520 int rc;
3521
drh1fee73e2007-08-29 04:00:57 +00003522 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003523 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003524 if( rc==SQLITE_OK ){
3525 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003526 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3527 if( pCur->apPage[0]->intKey ){
danielk1977da184232006-01-05 11:34:32 +00003528 return SQLITE_CORRUPT_BKPT;
3529 }
danielk197771d5d2c2008-09-29 11:49:47 +00003530 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh16a9b832007-05-05 18:39:25 +00003531 rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
drh6575a222005-03-10 17:06:34 +00003532 }
danielk1977da184232006-01-05 11:34:32 +00003533 return rc;
drh3aac2dd2004-04-26 14:10:20 +00003534}
3535
3536/*
drh3aac2dd2004-04-26 14:10:20 +00003537** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003538** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003539** begins at "offset".
3540**
3541** Return SQLITE_OK on success or an error code if anything goes
3542** wrong. An error is returned if "offset+amt" is larger than
3543** the available payload.
drh72f82862001-05-24 21:06:34 +00003544*/
drh3aac2dd2004-04-26 14:10:20 +00003545int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003546 int rc;
3547
danielk19773588ceb2008-06-10 17:30:26 +00003548#ifndef SQLITE_OMIT_INCRBLOB
3549 if ( pCur->eState==CURSOR_INVALID ){
3550 return SQLITE_ABORT;
3551 }
3552#endif
3553
drh1fee73e2007-08-29 04:00:57 +00003554 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003555 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003556 if( rc==SQLITE_OK ){
3557 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003558 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3559 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh16a9b832007-05-05 18:39:25 +00003560 rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
danielk1977da184232006-01-05 11:34:32 +00003561 }
3562 return rc;
drh2af926b2001-05-15 00:39:25 +00003563}
3564
drh72f82862001-05-24 21:06:34 +00003565/*
drh0e1c19e2004-05-11 00:58:56 +00003566** Return a pointer to payload information from the entry that the
3567** pCur cursor is pointing to. The pointer is to the beginning of
3568** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00003569** skipKey==1. The number of bytes of available key/data is written
3570** into *pAmt. If *pAmt==0, then the value returned will not be
3571** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00003572**
3573** This routine is an optimization. It is common for the entire key
3574** and data to fit on the local page and for there to be no overflow
3575** pages. When that is so, this routine can be used to access the
3576** key and data without making a copy. If the key and/or data spills
drh7f751222009-03-17 22:33:00 +00003577** onto overflow pages, then accessPayload() must be used to reassemble
drh0e1c19e2004-05-11 00:58:56 +00003578** the key/data and copy it into a preallocated buffer.
3579**
3580** The pointer returned by this routine looks directly into the cached
3581** page of the database. The data might change or move the next time
3582** any btree routine is called.
3583*/
3584static const unsigned char *fetchPayload(
3585 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00003586 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00003587 int skipKey /* read beginning at data if this is true */
3588){
3589 unsigned char *aPayload;
3590 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00003591 u32 nKey;
danielk197789d40042008-11-17 14:20:56 +00003592 u32 nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003593
danielk197771d5d2c2008-09-29 11:49:47 +00003594 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
danielk1977da184232006-01-05 11:34:32 +00003595 assert( pCur->eState==CURSOR_VALID );
drh1fee73e2007-08-29 04:00:57 +00003596 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00003597 pPage = pCur->apPage[pCur->iPage];
3598 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh86057612007-06-26 01:04:48 +00003599 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00003600 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00003601 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00003602 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00003603 nKey = 0;
3604 }else{
drhf49661a2008-12-10 16:45:50 +00003605 nKey = (int)pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00003606 }
drh0e1c19e2004-05-11 00:58:56 +00003607 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003608 aPayload += nKey;
3609 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00003610 }else{
drhfa1a98a2004-05-14 19:08:17 +00003611 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00003612 if( nLocal>nKey ){
3613 nLocal = nKey;
3614 }
drh0e1c19e2004-05-11 00:58:56 +00003615 }
drhe51c44f2004-05-30 20:46:09 +00003616 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003617 return aPayload;
3618}
3619
3620
3621/*
drhe51c44f2004-05-30 20:46:09 +00003622** For the entry that cursor pCur is point to, return as
3623** many bytes of the key or data as are available on the local
3624** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00003625**
3626** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00003627** or be destroyed on the next call to any Btree routine,
3628** including calls from other threads against the same cache.
3629** Hence, a mutex on the BtShared should be held prior to calling
3630** this routine.
drh0e1c19e2004-05-11 00:58:56 +00003631**
3632** These routines is used to get quick access to key and data
3633** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00003634*/
drhe51c44f2004-05-30 20:46:09 +00003635const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
drh1fee73e2007-08-29 04:00:57 +00003636 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003637 if( pCur->eState==CURSOR_VALID ){
3638 return (const void*)fetchPayload(pCur, pAmt, 0);
3639 }
3640 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003641}
drhe51c44f2004-05-30 20:46:09 +00003642const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
drh1fee73e2007-08-29 04:00:57 +00003643 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003644 if( pCur->eState==CURSOR_VALID ){
3645 return (const void*)fetchPayload(pCur, pAmt, 1);
3646 }
3647 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003648}
3649
3650
3651/*
drh8178a752003-01-05 21:41:40 +00003652** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00003653** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00003654*/
drh3aac2dd2004-04-26 14:10:20 +00003655static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00003656 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003657 int i = pCur->iPage;
drh72f82862001-05-24 21:06:34 +00003658 MemPage *pNewPage;
drhd0679ed2007-08-28 22:24:34 +00003659 BtShared *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00003660
drh1fee73e2007-08-29 04:00:57 +00003661 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003662 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003663 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
3664 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
3665 return SQLITE_CORRUPT_BKPT;
3666 }
3667 rc = getAndInitPage(pBt, newPgno, &pNewPage);
drh6019e162001-07-02 17:51:45 +00003668 if( rc ) return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003669 pCur->apPage[i+1] = pNewPage;
3670 pCur->aiIdx[i+1] = 0;
3671 pCur->iPage++;
3672
drh271efa52004-05-30 19:19:05 +00003673 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003674 pCur->validNKey = 0;
drh4be295b2003-12-16 03:44:47 +00003675 if( pNewPage->nCell<1 ){
drh49285702005-09-17 15:20:26 +00003676 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00003677 }
drh72f82862001-05-24 21:06:34 +00003678 return SQLITE_OK;
3679}
3680
danielk1977bf93c562008-09-29 15:53:25 +00003681#ifndef NDEBUG
3682/*
3683** Page pParent is an internal (non-leaf) tree page. This function
3684** asserts that page number iChild is the left-child if the iIdx'th
3685** cell in page pParent. Or, if iIdx is equal to the total number of
3686** cells in pParent, that page number iChild is the right-child of
3687** the page.
3688*/
3689static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
3690 assert( iIdx<=pParent->nCell );
3691 if( iIdx==pParent->nCell ){
3692 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
3693 }else{
3694 assert( get4byte(findCell(pParent, iIdx))==iChild );
3695 }
3696}
3697#else
3698# define assertParentIndex(x,y,z)
3699#endif
3700
drh72f82862001-05-24 21:06:34 +00003701/*
drh5e2f8b92001-05-28 00:41:15 +00003702** Move the cursor up to the parent page.
3703**
3704** pCur->idx is set to the cell index that contains the pointer
3705** to the page we are coming from. If we are coming from the
3706** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00003707** the largest cell index.
drh72f82862001-05-24 21:06:34 +00003708*/
drh16a9b832007-05-05 18:39:25 +00003709void sqlite3BtreeMoveToParent(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00003710 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003711 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003712 assert( pCur->iPage>0 );
3713 assert( pCur->apPage[pCur->iPage] );
danielk1977bf93c562008-09-29 15:53:25 +00003714 assertParentIndex(
3715 pCur->apPage[pCur->iPage-1],
3716 pCur->aiIdx[pCur->iPage-1],
3717 pCur->apPage[pCur->iPage]->pgno
3718 );
danielk197771d5d2c2008-09-29 11:49:47 +00003719 releasePage(pCur->apPage[pCur->iPage]);
3720 pCur->iPage--;
drh271efa52004-05-30 19:19:05 +00003721 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003722 pCur->validNKey = 0;
drh72f82862001-05-24 21:06:34 +00003723}
3724
3725/*
3726** Move the cursor to the root page
3727*/
drh5e2f8b92001-05-28 00:41:15 +00003728static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00003729 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00003730 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003731 Btree *p = pCur->pBtree;
3732 BtShared *pBt = p->pBt;
drhbd03cae2001-06-02 02:40:57 +00003733
drh1fee73e2007-08-29 04:00:57 +00003734 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +00003735 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
3736 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
3737 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
3738 if( pCur->eState>=CURSOR_REQUIRESEEK ){
3739 if( pCur->eState==CURSOR_FAULT ){
3740 return pCur->skip;
3741 }
danielk1977be51a652008-10-08 17:58:48 +00003742 sqlite3BtreeClearCursor(pCur);
drhbf700f32007-03-31 02:36:44 +00003743 }
danielk197771d5d2c2008-09-29 11:49:47 +00003744
3745 if( pCur->iPage>=0 ){
3746 int i;
3747 for(i=1; i<=pCur->iPage; i++){
3748 releasePage(pCur->apPage[i]);
danielk1977d9f6c532008-09-19 16:39:38 +00003749 }
drh777e4c42006-01-13 04:31:58 +00003750 }else{
3751 if(
danielk197771d5d2c2008-09-29 11:49:47 +00003752 SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]))
drh777e4c42006-01-13 04:31:58 +00003753 ){
3754 pCur->eState = CURSOR_INVALID;
3755 return rc;
3756 }
drhc39e0002004-05-07 23:50:57 +00003757 }
danielk197771d5d2c2008-09-29 11:49:47 +00003758
3759 pRoot = pCur->apPage[0];
3760 assert( pRoot->pgno==pCur->pgnoRoot );
3761 pCur->iPage = 0;
3762 pCur->aiIdx[0] = 0;
drh271efa52004-05-30 19:19:05 +00003763 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003764 pCur->atLast = 0;
3765 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003766
drh8856d6a2004-04-29 14:42:46 +00003767 if( pRoot->nCell==0 && !pRoot->leaf ){
3768 Pgno subpage;
3769 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00003770 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00003771 assert( subpage>0 );
danielk1977da184232006-01-05 11:34:32 +00003772 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00003773 rc = moveToChild(pCur, subpage);
danielk197771d5d2c2008-09-29 11:49:47 +00003774 }else{
3775 pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
drh8856d6a2004-04-29 14:42:46 +00003776 }
3777 return rc;
drh72f82862001-05-24 21:06:34 +00003778}
drh2af926b2001-05-15 00:39:25 +00003779
drh5e2f8b92001-05-28 00:41:15 +00003780/*
3781** Move the cursor down to the left-most leaf entry beneath the
3782** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00003783**
3784** The left-most leaf is the one with the smallest key - the first
3785** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00003786*/
3787static int moveToLeftmost(BtCursor *pCur){
3788 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00003789 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00003790 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00003791
drh1fee73e2007-08-29 04:00:57 +00003792 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003793 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003794 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
3795 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
3796 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
drh8178a752003-01-05 21:41:40 +00003797 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00003798 }
drhd677b3d2007-08-20 22:48:41 +00003799 return rc;
drh5e2f8b92001-05-28 00:41:15 +00003800}
3801
drh2dcc9aa2002-12-04 13:40:25 +00003802/*
3803** Move the cursor down to the right-most leaf entry beneath the
3804** page to which it is currently pointing. Notice the difference
3805** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
3806** finds the left-most entry beneath the *entry* whereas moveToRightmost()
3807** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00003808**
3809** The right-most entry is the one with the largest key - the last
3810** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00003811*/
3812static int moveToRightmost(BtCursor *pCur){
3813 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00003814 int rc = SQLITE_OK;
drh1bd10f82008-12-10 21:19:56 +00003815 MemPage *pPage = 0;
drh2dcc9aa2002-12-04 13:40:25 +00003816
drh1fee73e2007-08-29 04:00:57 +00003817 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003818 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003819 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
drh43605152004-05-29 21:46:49 +00003820 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
danielk197771d5d2c2008-09-29 11:49:47 +00003821 pCur->aiIdx[pCur->iPage] = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00003822 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00003823 }
drhd677b3d2007-08-20 22:48:41 +00003824 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00003825 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
drhd677b3d2007-08-20 22:48:41 +00003826 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003827 pCur->validNKey = 0;
drhd677b3d2007-08-20 22:48:41 +00003828 }
danielk1977518002e2008-09-05 05:02:46 +00003829 return rc;
drh2dcc9aa2002-12-04 13:40:25 +00003830}
3831
drh5e00f6c2001-09-13 13:46:56 +00003832/* Move the cursor to the first entry in the table. Return SQLITE_OK
3833** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003834** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00003835*/
drh3aac2dd2004-04-26 14:10:20 +00003836int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00003837 int rc;
drhd677b3d2007-08-20 22:48:41 +00003838
drh1fee73e2007-08-29 04:00:57 +00003839 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003840 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00003841 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003842 if( rc==SQLITE_OK ){
3843 if( pCur->eState==CURSOR_INVALID ){
danielk197771d5d2c2008-09-29 11:49:47 +00003844 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00003845 *pRes = 1;
3846 rc = SQLITE_OK;
3847 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00003848 assert( pCur->apPage[pCur->iPage]->nCell>0 );
drhd677b3d2007-08-20 22:48:41 +00003849 *pRes = 0;
3850 rc = moveToLeftmost(pCur);
3851 }
drh5e00f6c2001-09-13 13:46:56 +00003852 }
drh5e00f6c2001-09-13 13:46:56 +00003853 return rc;
3854}
drh5e2f8b92001-05-28 00:41:15 +00003855
drh9562b552002-02-19 15:00:07 +00003856/* Move the cursor to the last entry in the table. Return SQLITE_OK
3857** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00003858** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00003859*/
drh3aac2dd2004-04-26 14:10:20 +00003860int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00003861 int rc;
drhd677b3d2007-08-20 22:48:41 +00003862
drh1fee73e2007-08-29 04:00:57 +00003863 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003864 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh9562b552002-02-19 15:00:07 +00003865 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003866 if( rc==SQLITE_OK ){
3867 if( CURSOR_INVALID==pCur->eState ){
danielk197771d5d2c2008-09-29 11:49:47 +00003868 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00003869 *pRes = 1;
3870 }else{
3871 assert( pCur->eState==CURSOR_VALID );
3872 *pRes = 0;
3873 rc = moveToRightmost(pCur);
drha2c20e42008-03-29 16:01:04 +00003874 getCellInfo(pCur);
drhf49661a2008-12-10 16:45:50 +00003875 pCur->atLast = rc==SQLITE_OK ?1:0;
drhd677b3d2007-08-20 22:48:41 +00003876 }
drh9562b552002-02-19 15:00:07 +00003877 }
drh9562b552002-02-19 15:00:07 +00003878 return rc;
3879}
3880
drhe14006d2008-03-25 17:23:32 +00003881/* Move the cursor so that it points to an entry near the key
drhe63d9992008-08-13 19:11:48 +00003882** specified by pIdxKey or intKey. Return a success code.
drh72f82862001-05-24 21:06:34 +00003883**
drhe63d9992008-08-13 19:11:48 +00003884** For INTKEY tables, the intKey parameter is used. pIdxKey
3885** must be NULL. For index tables, pIdxKey is used and intKey
3886** is ignored.
drh3aac2dd2004-04-26 14:10:20 +00003887**
drh5e2f8b92001-05-28 00:41:15 +00003888** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00003889** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00003890** were present. The cursor might point to an entry that comes
3891** before or after the key.
3892**
drh64022502009-01-09 14:11:04 +00003893** An integer is written into *pRes which is the result of
3894** comparing the key with the entry to which the cursor is
3895** pointing. The meaning of the integer written into
3896** *pRes is as follows:
drhbd03cae2001-06-02 02:40:57 +00003897**
3898** *pRes<0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00003899** is smaller than intKey/pIdxKey or if the table is empty
drh1a844c32002-12-04 22:29:28 +00003900** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00003901**
3902** *pRes==0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00003903** exactly matches intKey/pIdxKey.
drhbd03cae2001-06-02 02:40:57 +00003904**
3905** *pRes>0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00003906** is larger than intKey/pIdxKey.
drhd677b3d2007-08-20 22:48:41 +00003907**
drha059ad02001-04-17 20:09:11 +00003908*/
drhe63d9992008-08-13 19:11:48 +00003909int sqlite3BtreeMovetoUnpacked(
3910 BtCursor *pCur, /* The cursor to be moved */
3911 UnpackedRecord *pIdxKey, /* Unpacked index key */
3912 i64 intKey, /* The table key */
3913 int biasRight, /* If true, bias the search to the high end */
3914 int *pRes /* Write search results here */
drhe4d90812007-03-29 05:51:49 +00003915){
drh72f82862001-05-24 21:06:34 +00003916 int rc;
drhd677b3d2007-08-20 22:48:41 +00003917
drh1fee73e2007-08-29 04:00:57 +00003918 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00003919 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drha2c20e42008-03-29 16:01:04 +00003920
3921 /* If the cursor is already positioned at the point we are trying
3922 ** to move to, then just return without doing any work */
danielk197771d5d2c2008-09-29 11:49:47 +00003923 if( pCur->eState==CURSOR_VALID && pCur->validNKey
3924 && pCur->apPage[0]->intKey
3925 ){
drhe63d9992008-08-13 19:11:48 +00003926 if( pCur->info.nKey==intKey ){
drha2c20e42008-03-29 16:01:04 +00003927 *pRes = 0;
3928 return SQLITE_OK;
3929 }
drhe63d9992008-08-13 19:11:48 +00003930 if( pCur->atLast && pCur->info.nKey<intKey ){
drha2c20e42008-03-29 16:01:04 +00003931 *pRes = -1;
3932 return SQLITE_OK;
3933 }
3934 }
3935
drh5e2f8b92001-05-28 00:41:15 +00003936 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00003937 if( rc ){
3938 return rc;
3939 }
danielk197771d5d2c2008-09-29 11:49:47 +00003940 assert( pCur->apPage[pCur->iPage] );
3941 assert( pCur->apPage[pCur->iPage]->isInit );
danielk1977da184232006-01-05 11:34:32 +00003942 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00003943 *pRes = -1;
danielk197771d5d2c2008-09-29 11:49:47 +00003944 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhc39e0002004-05-07 23:50:57 +00003945 return SQLITE_OK;
3946 }
danielk197771d5d2c2008-09-29 11:49:47 +00003947 assert( pCur->apPage[0]->intKey || pIdxKey );
drh14684382006-11-30 13:05:29 +00003948 for(;;){
drh72f82862001-05-24 21:06:34 +00003949 int lwr, upr;
3950 Pgno chldPg;
danielk197771d5d2c2008-09-29 11:49:47 +00003951 MemPage *pPage = pCur->apPage[pCur->iPage];
drh1a844c32002-12-04 22:29:28 +00003952 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00003953 lwr = 0;
3954 upr = pPage->nCell-1;
drh64022502009-01-09 14:11:04 +00003955 if( (!pPage->intKey && pIdxKey==0) || upr<0 ){
drh1e968a02008-03-25 00:22:21 +00003956 rc = SQLITE_CORRUPT_BKPT;
3957 goto moveto_finish;
drh4eec4c12005-01-21 00:22:37 +00003958 }
drhe4d90812007-03-29 05:51:49 +00003959 if( biasRight ){
drhf49661a2008-12-10 16:45:50 +00003960 pCur->aiIdx[pCur->iPage] = (u16)upr;
drhe4d90812007-03-29 05:51:49 +00003961 }else{
drhf49661a2008-12-10 16:45:50 +00003962 pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
drhe4d90812007-03-29 05:51:49 +00003963 }
drh64022502009-01-09 14:11:04 +00003964 for(;;){
danielk197713adf8a2004-06-03 16:08:41 +00003965 void *pCellKey;
drh4a1c3802004-05-12 15:15:47 +00003966 i64 nCellKey;
danielk197771d5d2c2008-09-29 11:49:47 +00003967 int idx = pCur->aiIdx[pCur->iPage];
drh366fda62006-01-13 02:35:09 +00003968 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003969 pCur->validNKey = 1;
drh3aac2dd2004-04-26 14:10:20 +00003970 if( pPage->intKey ){
drh777e4c42006-01-13 04:31:58 +00003971 u8 *pCell;
danielk197771d5d2c2008-09-29 11:49:47 +00003972 pCell = findCell(pPage, idx) + pPage->childPtrSize;
drhd172f862006-01-12 15:01:15 +00003973 if( pPage->hasData ){
danielk1977bab45c62006-01-16 15:14:27 +00003974 u32 dummy;
shane3f8d5cf2008-04-24 19:15:09 +00003975 pCell += getVarint32(pCell, dummy);
drhd172f862006-01-12 15:01:15 +00003976 }
drha2c20e42008-03-29 16:01:04 +00003977 getVarint(pCell, (u64*)&nCellKey);
drhe63d9992008-08-13 19:11:48 +00003978 if( nCellKey==intKey ){
drh3aac2dd2004-04-26 14:10:20 +00003979 c = 0;
drhe63d9992008-08-13 19:11:48 +00003980 }else if( nCellKey<intKey ){
drh41eb9e92008-04-02 18:33:07 +00003981 c = -1;
3982 }else{
drhe63d9992008-08-13 19:11:48 +00003983 assert( nCellKey>intKey );
drh41eb9e92008-04-02 18:33:07 +00003984 c = +1;
drh3aac2dd2004-04-26 14:10:20 +00003985 }
drh3aac2dd2004-04-26 14:10:20 +00003986 }else{
drhe51c44f2004-05-30 20:46:09 +00003987 int available;
danielk197713adf8a2004-06-03 16:08:41 +00003988 pCellKey = (void *)fetchPayload(pCur, &available, 0);
drh366fda62006-01-13 02:35:09 +00003989 nCellKey = pCur->info.nKey;
drhe51c44f2004-05-30 20:46:09 +00003990 if( available>=nCellKey ){
drhf49661a2008-12-10 16:45:50 +00003991 c = sqlite3VdbeRecordCompare((int)nCellKey, pCellKey, pIdxKey);
drhe51c44f2004-05-30 20:46:09 +00003992 }else{
drhf49661a2008-12-10 16:45:50 +00003993 pCellKey = sqlite3Malloc( (int)nCellKey );
danielk19776507ecb2008-03-25 09:56:44 +00003994 if( pCellKey==0 ){
3995 rc = SQLITE_NOMEM;
3996 goto moveto_finish;
3997 }
drhf49661a2008-12-10 16:45:50 +00003998 rc = sqlite3BtreeKey(pCur, 0, (int)nCellKey, (void*)pCellKey);
drh1bd10f82008-12-10 21:19:56 +00003999 c = sqlite3VdbeRecordCompare((int)nCellKey, pCellKey, pIdxKey);
drhfacf0302008-06-17 15:12:00 +00004000 sqlite3_free(pCellKey);
drh1e968a02008-03-25 00:22:21 +00004001 if( rc ) goto moveto_finish;
drhe51c44f2004-05-30 20:46:09 +00004002 }
drh3aac2dd2004-04-26 14:10:20 +00004003 }
drh72f82862001-05-24 21:06:34 +00004004 if( c==0 ){
drha2c20e42008-03-29 16:01:04 +00004005 pCur->info.nKey = nCellKey;
drh44845222008-07-17 18:39:57 +00004006 if( pPage->intKey && !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00004007 lwr = idx;
drhfc70e6f2004-05-12 21:11:27 +00004008 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00004009 break;
4010 }else{
drh64022502009-01-09 14:11:04 +00004011 *pRes = 0;
drh1e968a02008-03-25 00:22:21 +00004012 rc = SQLITE_OK;
4013 goto moveto_finish;
drh8b18dd42004-05-12 19:18:15 +00004014 }
drh72f82862001-05-24 21:06:34 +00004015 }
4016 if( c<0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00004017 lwr = idx+1;
drh72f82862001-05-24 21:06:34 +00004018 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004019 upr = idx-1;
drh72f82862001-05-24 21:06:34 +00004020 }
drhf1d68b32007-03-29 04:43:26 +00004021 if( lwr>upr ){
drha2c20e42008-03-29 16:01:04 +00004022 pCur->info.nKey = nCellKey;
drhf1d68b32007-03-29 04:43:26 +00004023 break;
4024 }
drhf49661a2008-12-10 16:45:50 +00004025 pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
drh72f82862001-05-24 21:06:34 +00004026 }
4027 assert( lwr==upr+1 );
danielk197771d5d2c2008-09-29 11:49:47 +00004028 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00004029 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00004030 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00004031 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00004032 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00004033 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00004034 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00004035 }
4036 if( chldPg==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00004037 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh72f82862001-05-24 21:06:34 +00004038 if( pRes ) *pRes = c;
drh1e968a02008-03-25 00:22:21 +00004039 rc = SQLITE_OK;
4040 goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00004041 }
drhf49661a2008-12-10 16:45:50 +00004042 pCur->aiIdx[pCur->iPage] = (u16)lwr;
drh271efa52004-05-30 19:19:05 +00004043 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004044 pCur->validNKey = 0;
drh8178a752003-01-05 21:41:40 +00004045 rc = moveToChild(pCur, chldPg);
drh1e968a02008-03-25 00:22:21 +00004046 if( rc ) goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00004047 }
drh1e968a02008-03-25 00:22:21 +00004048moveto_finish:
drhe63d9992008-08-13 19:11:48 +00004049 return rc;
4050}
4051
4052/*
4053** In this version of BtreeMoveto, pKey is a packed index record
4054** such as is generated by the OP_MakeRecord opcode. Unpack the
4055** record and then call BtreeMovetoUnpacked() to do the work.
4056*/
4057int sqlite3BtreeMoveto(
4058 BtCursor *pCur, /* Cursor open on the btree to be searched */
4059 const void *pKey, /* Packed key if the btree is an index */
4060 i64 nKey, /* Integer key for tables. Size of pKey for indices */
4061 int bias, /* Bias search to the high end */
4062 int *pRes /* Write search results here */
4063){
4064 int rc; /* Status code */
4065 UnpackedRecord *pIdxKey; /* Unpacked index key */
drh8c5d1522009-04-10 00:56:28 +00004066 char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
4067
drhe63d9992008-08-13 19:11:48 +00004068
drhe14006d2008-03-25 17:23:32 +00004069 if( pKey ){
drhf49661a2008-12-10 16:45:50 +00004070 assert( nKey==(i64)(int)nKey );
4071 pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
drh23f79d02008-08-20 22:06:47 +00004072 aSpace, sizeof(aSpace));
drhe63d9992008-08-13 19:11:48 +00004073 if( pIdxKey==0 ) return SQLITE_NOMEM;
4074 }else{
4075 pIdxKey = 0;
4076 }
4077 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
4078 if( pKey ){
4079 sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
drhe14006d2008-03-25 17:23:32 +00004080 }
drh1e968a02008-03-25 00:22:21 +00004081 return rc;
drh72f82862001-05-24 21:06:34 +00004082}
4083
drhd677b3d2007-08-20 22:48:41 +00004084
drh72f82862001-05-24 21:06:34 +00004085/*
drhc39e0002004-05-07 23:50:57 +00004086** Return TRUE if the cursor is not pointing at an entry of the table.
4087**
4088** TRUE will be returned after a call to sqlite3BtreeNext() moves
4089** past the last entry in the table or sqlite3BtreePrev() moves past
4090** the first entry. TRUE is also returned if the table is empty.
4091*/
4092int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00004093 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
4094 ** have been deleted? This API will need to change to return an error code
4095 ** as well as the boolean result value.
4096 */
4097 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00004098}
4099
4100/*
drhb21c8cd2007-08-21 19:33:56 +00004101** Return the database connection handle for a cursor.
4102*/
4103sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){
drhe5fe6902007-12-07 18:55:28 +00004104 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
4105 return pCur->pBtree->db;
drhb21c8cd2007-08-21 19:33:56 +00004106}
4107
4108/*
drhbd03cae2001-06-02 02:40:57 +00004109** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00004110** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00004111** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00004112** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00004113*/
drhd094db12008-04-03 21:46:57 +00004114int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00004115 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00004116 int idx;
danielk197797a227c2006-01-20 16:32:04 +00004117 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00004118
drh1fee73e2007-08-29 04:00:57 +00004119 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004120 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004121 if( rc!=SQLITE_OK ){
4122 return rc;
4123 }
drh8c4d3a62007-04-06 01:03:32 +00004124 assert( pRes!=0 );
drh8c4d3a62007-04-06 01:03:32 +00004125 if( CURSOR_INVALID==pCur->eState ){
4126 *pRes = 1;
4127 return SQLITE_OK;
4128 }
danielk1977da184232006-01-05 11:34:32 +00004129 if( pCur->skip>0 ){
4130 pCur->skip = 0;
4131 *pRes = 0;
4132 return SQLITE_OK;
4133 }
4134 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00004135
danielk197771d5d2c2008-09-29 11:49:47 +00004136 pPage = pCur->apPage[pCur->iPage];
4137 idx = ++pCur->aiIdx[pCur->iPage];
4138 assert( pPage->isInit );
4139 assert( idx<=pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00004140
drh271efa52004-05-30 19:19:05 +00004141 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004142 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004143 if( idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00004144 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004145 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00004146 if( rc ) return rc;
4147 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00004148 *pRes = 0;
4149 return rc;
drh72f82862001-05-24 21:06:34 +00004150 }
drh5e2f8b92001-05-28 00:41:15 +00004151 do{
danielk197771d5d2c2008-09-29 11:49:47 +00004152 if( pCur->iPage==0 ){
drh8c1238a2003-01-02 14:43:55 +00004153 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00004154 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00004155 return SQLITE_OK;
4156 }
drh16a9b832007-05-05 18:39:25 +00004157 sqlite3BtreeMoveToParent(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00004158 pPage = pCur->apPage[pCur->iPage];
4159 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00004160 *pRes = 0;
drh44845222008-07-17 18:39:57 +00004161 if( pPage->intKey ){
drh8b18dd42004-05-12 19:18:15 +00004162 rc = sqlite3BtreeNext(pCur, pRes);
4163 }else{
4164 rc = SQLITE_OK;
4165 }
4166 return rc;
drh8178a752003-01-05 21:41:40 +00004167 }
4168 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00004169 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00004170 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00004171 }
drh5e2f8b92001-05-28 00:41:15 +00004172 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00004173 return rc;
drh72f82862001-05-24 21:06:34 +00004174}
drhd677b3d2007-08-20 22:48:41 +00004175
drh72f82862001-05-24 21:06:34 +00004176
drh3b7511c2001-05-26 13:15:44 +00004177/*
drh2dcc9aa2002-12-04 13:40:25 +00004178** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00004179** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00004180** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00004181** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00004182*/
drhd094db12008-04-03 21:46:57 +00004183int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00004184 int rc;
drh8178a752003-01-05 21:41:40 +00004185 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00004186
drh1fee73e2007-08-29 04:00:57 +00004187 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004188 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004189 if( rc!=SQLITE_OK ){
4190 return rc;
4191 }
drha2c20e42008-03-29 16:01:04 +00004192 pCur->atLast = 0;
drh8c4d3a62007-04-06 01:03:32 +00004193 if( CURSOR_INVALID==pCur->eState ){
4194 *pRes = 1;
4195 return SQLITE_OK;
4196 }
danielk1977da184232006-01-05 11:34:32 +00004197 if( pCur->skip<0 ){
4198 pCur->skip = 0;
4199 *pRes = 0;
4200 return SQLITE_OK;
4201 }
4202 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00004203
danielk197771d5d2c2008-09-29 11:49:47 +00004204 pPage = pCur->apPage[pCur->iPage];
4205 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00004206 if( !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00004207 int idx = pCur->aiIdx[pCur->iPage];
4208 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
drhd677b3d2007-08-20 22:48:41 +00004209 if( rc ){
4210 return rc;
4211 }
drh2dcc9aa2002-12-04 13:40:25 +00004212 rc = moveToRightmost(pCur);
4213 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004214 while( pCur->aiIdx[pCur->iPage]==0 ){
4215 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00004216 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00004217 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00004218 return SQLITE_OK;
4219 }
drh16a9b832007-05-05 18:39:25 +00004220 sqlite3BtreeMoveToParent(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00004221 }
drh271efa52004-05-30 19:19:05 +00004222 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004223 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004224
4225 pCur->aiIdx[pCur->iPage]--;
4226 pPage = pCur->apPage[pCur->iPage];
drh44845222008-07-17 18:39:57 +00004227 if( pPage->intKey && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00004228 rc = sqlite3BtreePrevious(pCur, pRes);
4229 }else{
4230 rc = SQLITE_OK;
4231 }
drh2dcc9aa2002-12-04 13:40:25 +00004232 }
drh8178a752003-01-05 21:41:40 +00004233 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00004234 return rc;
4235}
4236
4237/*
drh3b7511c2001-05-26 13:15:44 +00004238** Allocate a new page from the database file.
4239**
danielk19773b8a05f2007-03-19 17:44:26 +00004240** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00004241** has already been called on the new page.) The new page has also
4242** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00004243** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00004244**
4245** SQLITE_OK is returned on success. Any other return value indicates
4246** an error. *ppPage and *pPgno are undefined in the event of an error.
danielk19773b8a05f2007-03-19 17:44:26 +00004247** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00004248**
drh199e3cf2002-07-18 11:01:47 +00004249** If the "nearby" parameter is not 0, then a (feeble) effort is made to
4250** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00004251** attempt to keep related pages close to each other in the database file,
4252** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00004253**
4254** If the "exact" parameter is not 0, and the page-number nearby exists
4255** anywhere on the free-list, then it is guarenteed to be returned. This
4256** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00004257*/
drh4f0c5872007-03-26 22:05:01 +00004258static int allocateBtreePage(
danielk1977aef0bf62005-12-30 16:28:01 +00004259 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00004260 MemPage **ppPage,
4261 Pgno *pPgno,
4262 Pgno nearby,
4263 u8 exact
4264){
drh3aac2dd2004-04-26 14:10:20 +00004265 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00004266 int rc;
drh3aac2dd2004-04-26 14:10:20 +00004267 int n; /* Number of pages on the freelist */
4268 int k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00004269 MemPage *pTrunk = 0;
4270 MemPage *pPrevTrunk = 0;
drh30e58752002-03-02 20:41:57 +00004271
drh1fee73e2007-08-29 04:00:57 +00004272 assert( sqlite3_mutex_held(pBt->mutex) );
drh3aac2dd2004-04-26 14:10:20 +00004273 pPage1 = pBt->pPage1;
4274 n = get4byte(&pPage1->aData[36]);
4275 if( n>0 ){
drh91025292004-05-03 19:49:32 +00004276 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00004277 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004278 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
4279
4280 /* If the 'exact' parameter was true and a query of the pointer-map
4281 ** shows that the page 'nearby' is somewhere on the free-list, then
4282 ** the entire-list will be searched for that page.
4283 */
4284#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197789d40042008-11-17 14:20:56 +00004285 if( exact && nearby<=pagerPagecount(pBt) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004286 u8 eType;
4287 assert( nearby>0 );
4288 assert( pBt->autoVacuum );
4289 rc = ptrmapGet(pBt, nearby, &eType, 0);
4290 if( rc ) return rc;
4291 if( eType==PTRMAP_FREEPAGE ){
4292 searchList = 1;
4293 }
4294 *pPgno = nearby;
4295 }
4296#endif
4297
4298 /* Decrement the free-list count by 1. Set iTrunk to the index of the
4299 ** first free-list trunk page. iPrevTrunk is initially 1.
4300 */
danielk19773b8a05f2007-03-19 17:44:26 +00004301 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00004302 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004303 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004304
4305 /* The code within this loop is run only once if the 'searchList' variable
4306 ** is not true. Otherwise, it runs once for each trunk-page on the
4307 ** free-list until the page 'nearby' is located.
4308 */
4309 do {
4310 pPrevTrunk = pTrunk;
4311 if( pPrevTrunk ){
4312 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00004313 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004314 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00004315 }
drh16a9b832007-05-05 18:39:25 +00004316 rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004317 if( rc ){
drhd3627af2006-12-18 18:34:51 +00004318 pTrunk = 0;
4319 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004320 }
4321
4322 k = get4byte(&pTrunk->aData[4]);
4323 if( k==0 && !searchList ){
4324 /* The trunk has no leaves and the list is not being searched.
4325 ** So extract the trunk page itself and use it as the newly
4326 ** allocated page */
4327 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00004328 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004329 if( rc ){
4330 goto end_allocate_page;
4331 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004332 *pPgno = iTrunk;
4333 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4334 *ppPage = pTrunk;
4335 pTrunk = 0;
4336 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh45b1fac2008-07-04 17:52:42 +00004337 }else if( k>pBt->usableSize/4 - 2 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004338 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00004339 rc = SQLITE_CORRUPT_BKPT;
4340 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004341#ifndef SQLITE_OMIT_AUTOVACUUM
4342 }else if( searchList && nearby==iTrunk ){
4343 /* The list is being searched and this trunk page is the page
4344 ** to allocate, regardless of whether it has leaves.
4345 */
4346 assert( *pPgno==iTrunk );
4347 *ppPage = pTrunk;
4348 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00004349 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004350 if( rc ){
4351 goto end_allocate_page;
4352 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004353 if( k==0 ){
4354 if( !pPrevTrunk ){
4355 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4356 }else{
4357 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
4358 }
4359 }else{
4360 /* The trunk page is required by the caller but it contains
4361 ** pointers to free-list leaves. The first leaf becomes a trunk
4362 ** page in this case.
4363 */
4364 MemPage *pNewTrunk;
4365 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh16a9b832007-05-05 18:39:25 +00004366 rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004367 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00004368 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004369 }
danielk19773b8a05f2007-03-19 17:44:26 +00004370 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004371 if( rc!=SQLITE_OK ){
4372 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00004373 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004374 }
4375 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
4376 put4byte(&pNewTrunk->aData[4], k-1);
4377 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00004378 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004379 if( !pPrevTrunk ){
drhc5053fb2008-11-27 02:22:10 +00004380 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
danielk1977cb1a7eb2004-11-05 12:27:02 +00004381 put4byte(&pPage1->aData[32], iNewTrunk);
4382 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00004383 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004384 if( rc ){
4385 goto end_allocate_page;
4386 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004387 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
4388 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004389 }
4390 pTrunk = 0;
4391 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
4392#endif
4393 }else{
4394 /* Extract a leaf from the trunk */
4395 int closest;
4396 Pgno iPage;
4397 unsigned char *aData = pTrunk->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00004398 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004399 if( rc ){
4400 goto end_allocate_page;
4401 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004402 if( nearby>0 ){
4403 int i, dist;
4404 closest = 0;
4405 dist = get4byte(&aData[8]) - nearby;
4406 if( dist<0 ) dist = -dist;
4407 for(i=1; i<k; i++){
4408 int d2 = get4byte(&aData[8+i*4]) - nearby;
4409 if( d2<0 ) d2 = -d2;
4410 if( d2<dist ){
4411 closest = i;
4412 dist = d2;
4413 }
4414 }
4415 }else{
4416 closest = 0;
4417 }
4418
4419 iPage = get4byte(&aData[8+closest*4]);
4420 if( !searchList || iPage==nearby ){
danielk1977bea2a942009-01-20 17:06:27 +00004421 int noContent;
danielk197789d40042008-11-17 14:20:56 +00004422 Pgno nPage;
shane1f9e6aa2008-06-09 19:27:11 +00004423 *pPgno = iPage;
danielk197789d40042008-11-17 14:20:56 +00004424 nPage = pagerPagecount(pBt);
danielk1977ad0132d2008-06-07 08:58:22 +00004425 if( *pPgno>nPage ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004426 /* Free page off the end of the file */
danielk197743e377a2008-05-05 12:09:32 +00004427 rc = SQLITE_CORRUPT_BKPT;
4428 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004429 }
4430 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
4431 ": %d more free pages\n",
4432 *pPgno, closest+1, k, pTrunk->pgno, n-1));
4433 if( closest<k-1 ){
4434 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
4435 }
4436 put4byte(&aData[4], k-1);
drhc5053fb2008-11-27 02:22:10 +00004437 assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
danielk1977bea2a942009-01-20 17:06:27 +00004438 noContent = !btreeGetHasContent(pBt, *pPgno);
4439 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, noContent);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004440 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00004441 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004442 if( rc!=SQLITE_OK ){
4443 releasePage(*ppPage);
4444 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004445 }
4446 searchList = 0;
4447 }
drhee696e22004-08-30 16:52:17 +00004448 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004449 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00004450 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004451 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00004452 }else{
drh3aac2dd2004-04-26 14:10:20 +00004453 /* There are no pages on the freelist, so create a new page at the
4454 ** end of the file */
danielk197789d40042008-11-17 14:20:56 +00004455 int nPage = pagerPagecount(pBt);
danielk1977ad0132d2008-06-07 08:58:22 +00004456 *pPgno = nPage + 1;
danielk1977afcdd022004-10-31 16:25:42 +00004457
danielk1977bea2a942009-01-20 17:06:27 +00004458 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
4459 (*pPgno)++;
4460 }
4461
danielk1977afcdd022004-10-31 16:25:42 +00004462#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977266664d2006-02-10 08:24:21 +00004463 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00004464 /* If *pPgno refers to a pointer-map page, allocate two new pages
4465 ** at the end of the file instead of one. The first allocated page
4466 ** becomes a new pointer-map page, the second is used by the caller.
4467 */
danielk1977ac861692009-03-28 10:54:22 +00004468 MemPage *pPg = 0;
danielk1977afcdd022004-10-31 16:25:42 +00004469 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00004470 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977ac861692009-03-28 10:54:22 +00004471 rc = sqlite3BtreeGetPage(pBt, *pPgno, &pPg, 0);
4472 if( rc==SQLITE_OK ){
4473 rc = sqlite3PagerWrite(pPg->pDbPage);
4474 releasePage(pPg);
4475 }
4476 if( rc ) return rc;
danielk1977afcdd022004-10-31 16:25:42 +00004477 (*pPgno)++;
drh72190432008-01-31 14:54:43 +00004478 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
danielk1977afcdd022004-10-31 16:25:42 +00004479 }
4480#endif
4481
danielk1977599fcba2004-11-08 07:13:13 +00004482 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh16a9b832007-05-05 18:39:25 +00004483 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
drh3b7511c2001-05-26 13:15:44 +00004484 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00004485 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004486 if( rc!=SQLITE_OK ){
4487 releasePage(*ppPage);
4488 }
drh3a4c1412004-05-09 20:40:11 +00004489 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00004490 }
danielk1977599fcba2004-11-08 07:13:13 +00004491
4492 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00004493
4494end_allocate_page:
4495 releasePage(pTrunk);
4496 releasePage(pPrevTrunk);
danielk1977b247c212008-11-21 09:09:01 +00004497 if( rc==SQLITE_OK ){
4498 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
4499 releasePage(*ppPage);
4500 return SQLITE_CORRUPT_BKPT;
4501 }
4502 (*ppPage)->isInit = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00004503 }
drh3b7511c2001-05-26 13:15:44 +00004504 return rc;
4505}
4506
4507/*
danielk1977bea2a942009-01-20 17:06:27 +00004508** This function is used to add page iPage to the database file free-list.
4509** It is assumed that the page is not already a part of the free-list.
drh5e2f8b92001-05-28 00:41:15 +00004510**
danielk1977bea2a942009-01-20 17:06:27 +00004511** The value passed as the second argument to this function is optional.
4512** If the caller happens to have a pointer to the MemPage object
4513** corresponding to page iPage handy, it may pass it as the second value.
4514** Otherwise, it may pass NULL.
4515**
4516** If a pointer to a MemPage object is passed as the second argument,
4517** its reference count is not altered by this function.
drh3b7511c2001-05-26 13:15:44 +00004518*/
danielk1977bea2a942009-01-20 17:06:27 +00004519static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
4520 MemPage *pTrunk = 0; /* Free-list trunk page */
4521 Pgno iTrunk = 0; /* Page number of free-list trunk page */
4522 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
4523 MemPage *pPage; /* Page being freed. May be NULL. */
4524 int rc; /* Return Code */
4525 int nFree; /* Initial number of pages on free-list */
drh8b2f49b2001-06-08 00:21:52 +00004526
danielk1977bea2a942009-01-20 17:06:27 +00004527 assert( sqlite3_mutex_held(pBt->mutex) );
4528 assert( iPage>1 );
4529 assert( !pMemPage || pMemPage->pgno==iPage );
4530
4531 if( pMemPage ){
4532 pPage = pMemPage;
4533 sqlite3PagerRef(pPage->pDbPage);
4534 }else{
4535 pPage = btreePageLookup(pBt, iPage);
4536 }
drh3aac2dd2004-04-26 14:10:20 +00004537
drha34b6762004-05-07 13:30:42 +00004538 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00004539 rc = sqlite3PagerWrite(pPage1->pDbPage);
danielk1977bea2a942009-01-20 17:06:27 +00004540 if( rc ) goto freepage_out;
4541 nFree = get4byte(&pPage1->aData[36]);
4542 put4byte(&pPage1->aData[36], nFree+1);
drh3aac2dd2004-04-26 14:10:20 +00004543
drhfcce93f2006-02-22 03:08:32 +00004544#ifdef SQLITE_SECURE_DELETE
4545 /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
4546 ** always fully overwrite deleted information with zeros.
4547 */
danielk1977bea2a942009-01-20 17:06:27 +00004548 if( (!pPage && (rc = sqlite3BtreeGetPage(pBt, iPage, &pPage, 0)))
4549 || (rc = sqlite3PagerWrite(pPage->pDbPage))
4550 ){
4551 goto freepage_out;
4552 }
drhfcce93f2006-02-22 03:08:32 +00004553 memset(pPage->aData, 0, pPage->pBt->pageSize);
4554#endif
4555
danielk1977687566d2004-11-02 12:56:41 +00004556 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00004557 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00004558 */
danielk197785d90ca2008-07-19 14:25:15 +00004559 if( ISAUTOVACUUM ){
danielk1977bea2a942009-01-20 17:06:27 +00004560 rc = ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0);
4561 if( rc ) goto freepage_out;
danielk1977687566d2004-11-02 12:56:41 +00004562 }
danielk1977687566d2004-11-02 12:56:41 +00004563
danielk1977bea2a942009-01-20 17:06:27 +00004564 /* Now manipulate the actual database free-list structure. There are two
4565 ** possibilities. If the free-list is currently empty, or if the first
4566 ** trunk page in the free-list is full, then this page will become a
4567 ** new free-list trunk page. Otherwise, it will become a leaf of the
4568 ** first trunk page in the current free-list. This block tests if it
4569 ** is possible to add the page as a new free-list leaf.
4570 */
4571 if( nFree!=0 ){
4572 int nLeaf; /* Initial number of leaf cells on trunk page */
4573
4574 iTrunk = get4byte(&pPage1->aData[32]);
4575 rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
4576 if( rc!=SQLITE_OK ){
4577 goto freepage_out;
4578 }
4579
4580 nLeaf = get4byte(&pTrunk->aData[4]);
4581 if( nLeaf<0 ){
4582 rc = SQLITE_CORRUPT_BKPT;
4583 goto freepage_out;
4584 }
4585 if( nLeaf<pBt->usableSize/4 - 8 ){
4586 /* In this case there is room on the trunk page to insert the page
4587 ** being freed as a new leaf.
drh45b1fac2008-07-04 17:52:42 +00004588 **
4589 ** Note that the trunk page is not really full until it contains
4590 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
4591 ** coded. But due to a coding error in versions of SQLite prior to
4592 ** 3.6.0, databases with freelist trunk pages holding more than
4593 ** usableSize/4 - 8 entries will be reported as corrupt. In order
4594 ** to maintain backwards compatibility with older versions of SQLite,
4595 ** we will contain to restrict the number of entries to usableSize/4 - 8
4596 ** for now. At some point in the future (once everyone has upgraded
4597 ** to 3.6.0 or later) we should consider fixing the conditional above
4598 ** to read "usableSize/4-2" instead of "usableSize/4-8".
4599 */
danielk19773b8a05f2007-03-19 17:44:26 +00004600 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00004601 if( rc==SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00004602 put4byte(&pTrunk->aData[4], nLeaf+1);
4603 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
drhfcce93f2006-02-22 03:08:32 +00004604#ifndef SQLITE_SECURE_DELETE
danielk1977bea2a942009-01-20 17:06:27 +00004605 if( pPage ){
4606 sqlite3PagerDontWrite(pPage->pDbPage);
4607 }
drhfcce93f2006-02-22 03:08:32 +00004608#endif
danielk1977bea2a942009-01-20 17:06:27 +00004609 rc = btreeSetHasContent(pBt, iPage);
drhf5345442007-04-09 12:45:02 +00004610 }
drh3a4c1412004-05-09 20:40:11 +00004611 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
danielk1977bea2a942009-01-20 17:06:27 +00004612 goto freepage_out;
drh3aac2dd2004-04-26 14:10:20 +00004613 }
drh3b7511c2001-05-26 13:15:44 +00004614 }
danielk1977bea2a942009-01-20 17:06:27 +00004615
4616 /* If control flows to this point, then it was not possible to add the
4617 ** the page being freed as a leaf page of the first trunk in the free-list.
4618 ** Possibly because the free-list is empty, or possibly because the
4619 ** first trunk in the free-list is full. Either way, the page being freed
4620 ** will become the new first trunk page in the free-list.
4621 */
shane63207ab2009-02-04 01:49:30 +00004622 if( ((!pPage) && (0 != (rc = sqlite3BtreeGetPage(pBt, iPage, &pPage, 0))))
4623 || (0 != (rc = sqlite3PagerWrite(pPage->pDbPage)))
danielk1977bea2a942009-01-20 17:06:27 +00004624 ){
4625 goto freepage_out;
4626 }
4627 put4byte(pPage->aData, iTrunk);
4628 put4byte(&pPage->aData[4], 0);
4629 put4byte(&pPage1->aData[32], iPage);
4630 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
4631
4632freepage_out:
4633 if( pPage ){
4634 pPage->isInit = 0;
4635 }
4636 releasePage(pPage);
4637 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00004638 return rc;
4639}
danielk1977bea2a942009-01-20 17:06:27 +00004640static int freePage(MemPage *pPage){
4641 return freePage2(pPage->pBt, pPage, pPage->pgno);
4642}
drh3b7511c2001-05-26 13:15:44 +00004643
4644/*
drh3aac2dd2004-04-26 14:10:20 +00004645** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00004646*/
drh3aac2dd2004-04-26 14:10:20 +00004647static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00004648 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00004649 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00004650 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00004651 int rc;
drh94440812007-03-06 11:42:19 +00004652 int nOvfl;
shane63207ab2009-02-04 01:49:30 +00004653 u16 ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00004654
drh1fee73e2007-08-29 04:00:57 +00004655 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh16a9b832007-05-05 18:39:25 +00004656 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004657 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00004658 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00004659 }
drh6f11bef2004-05-13 01:12:56 +00004660 ovflPgno = get4byte(&pCell[info.iOverflow]);
shane63207ab2009-02-04 01:49:30 +00004661 assert( pBt->usableSize > 4 );
drh94440812007-03-06 11:42:19 +00004662 ovflPageSize = pBt->usableSize - 4;
drh72365832007-03-06 15:53:44 +00004663 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
4664 assert( ovflPgno==0 || nOvfl>0 );
4665 while( nOvfl-- ){
shane63207ab2009-02-04 01:49:30 +00004666 Pgno iNext = 0;
danielk1977bea2a942009-01-20 17:06:27 +00004667 MemPage *pOvfl = 0;
danielk1977e589a672009-04-11 16:06:15 +00004668 if( ovflPgno<2 || ovflPgno>pagerPagecount(pBt) ){
4669 /* 0 is not a legal page number and page 1 cannot be an
4670 ** overflow page. Therefore if ovflPgno<2 or past the end of the
4671 ** file the database must be corrupt. */
drh49285702005-09-17 15:20:26 +00004672 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00004673 }
danielk1977bea2a942009-01-20 17:06:27 +00004674 if( nOvfl ){
4675 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
4676 if( rc ) return rc;
4677 }
4678 rc = freePage2(pBt, pOvfl, ovflPgno);
4679 if( pOvfl ){
4680 sqlite3PagerUnref(pOvfl->pDbPage);
4681 }
drh3b7511c2001-05-26 13:15:44 +00004682 if( rc ) return rc;
danielk1977bea2a942009-01-20 17:06:27 +00004683 ovflPgno = iNext;
drh3b7511c2001-05-26 13:15:44 +00004684 }
drh5e2f8b92001-05-28 00:41:15 +00004685 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00004686}
4687
4688/*
drh91025292004-05-03 19:49:32 +00004689** Create the byte sequence used to represent a cell on page pPage
4690** and write that byte sequence into pCell[]. Overflow pages are
4691** allocated and filled in as necessary. The calling procedure
4692** is responsible for making sure sufficient space has been allocated
4693** for pCell[].
4694**
4695** Note that pCell does not necessary need to point to the pPage->aData
4696** area. pCell might point to some temporary storage. The cell will
4697** be constructed in this temporary area then copied into pPage->aData
4698** later.
drh3b7511c2001-05-26 13:15:44 +00004699*/
4700static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00004701 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00004702 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00004703 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00004704 const void *pData,int nData, /* The data */
drhb026e052007-05-02 01:34:31 +00004705 int nZero, /* Extra zero bytes to append to pData */
drh4b70f112004-05-02 21:12:19 +00004706 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00004707){
drh3b7511c2001-05-26 13:15:44 +00004708 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00004709 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00004710 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00004711 int spaceLeft;
4712 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00004713 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00004714 unsigned char *pPrior;
4715 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00004716 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00004717 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00004718 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00004719 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00004720
drh1fee73e2007-08-29 04:00:57 +00004721 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00004722
drhc5053fb2008-11-27 02:22:10 +00004723 /* pPage is not necessarily writeable since pCell might be auxiliary
4724 ** buffer space that is separate from the pPage buffer area */
4725 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
4726 || sqlite3PagerIswriteable(pPage->pDbPage) );
4727
drh91025292004-05-03 19:49:32 +00004728 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00004729 nHeader = 0;
drh91025292004-05-03 19:49:32 +00004730 if( !pPage->leaf ){
4731 nHeader += 4;
4732 }
drh8b18dd42004-05-12 19:18:15 +00004733 if( pPage->hasData ){
drhb026e052007-05-02 01:34:31 +00004734 nHeader += putVarint(&pCell[nHeader], nData+nZero);
drh6f11bef2004-05-13 01:12:56 +00004735 }else{
drhb026e052007-05-02 01:34:31 +00004736 nData = nZero = 0;
drh91025292004-05-03 19:49:32 +00004737 }
drh6f11bef2004-05-13 01:12:56 +00004738 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh16a9b832007-05-05 18:39:25 +00004739 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004740 assert( info.nHeader==nHeader );
4741 assert( info.nKey==nKey );
danielk197789d40042008-11-17 14:20:56 +00004742 assert( info.nData==(u32)(nData+nZero) );
drh6f11bef2004-05-13 01:12:56 +00004743
4744 /* Fill in the payload */
drhb026e052007-05-02 01:34:31 +00004745 nPayload = nData + nZero;
drh3aac2dd2004-04-26 14:10:20 +00004746 if( pPage->intKey ){
4747 pSrc = pData;
4748 nSrc = nData;
drh91025292004-05-03 19:49:32 +00004749 nData = 0;
drhf49661a2008-12-10 16:45:50 +00004750 }else{
drh20abac22009-01-28 20:21:17 +00004751 if( nKey>0x7fffffff || pKey==0 ){
4752 return SQLITE_CORRUPT;
4753 }
drhf49661a2008-12-10 16:45:50 +00004754 nPayload += (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00004755 pSrc = pKey;
drhf49661a2008-12-10 16:45:50 +00004756 nSrc = (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00004757 }
drh6f11bef2004-05-13 01:12:56 +00004758 *pnSize = info.nSize;
4759 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00004760 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00004761 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00004762
drh3b7511c2001-05-26 13:15:44 +00004763 while( nPayload>0 ){
4764 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00004765#ifndef SQLITE_OMIT_AUTOVACUUM
4766 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00004767 if( pBt->autoVacuum ){
4768 do{
4769 pgnoOvfl++;
4770 } while(
4771 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
4772 );
danielk1977b39f70b2007-05-17 18:28:11 +00004773 }
danielk1977afcdd022004-10-31 16:25:42 +00004774#endif
drhf49661a2008-12-10 16:45:50 +00004775 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00004776#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00004777 /* If the database supports auto-vacuum, and the second or subsequent
4778 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00004779 ** for that page now.
4780 **
4781 ** If this is the first overflow page, then write a partial entry
4782 ** to the pointer-map. If we write nothing to this pointer-map slot,
4783 ** then the optimistic overflow chain processing in clearCell()
4784 ** may misinterpret the uninitialised values and delete the
4785 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00004786 */
danielk19774ef24492007-05-23 09:52:41 +00004787 if( pBt->autoVacuum && rc==SQLITE_OK ){
4788 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
4789 rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
danielk197789a4be82007-05-23 13:34:32 +00004790 if( rc ){
4791 releasePage(pOvfl);
4792 }
danielk1977afcdd022004-10-31 16:25:42 +00004793 }
4794#endif
drh3b7511c2001-05-26 13:15:44 +00004795 if( rc ){
drh9b171272004-05-08 02:03:22 +00004796 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00004797 return rc;
4798 }
drhc5053fb2008-11-27 02:22:10 +00004799
4800 /* If pToRelease is not zero than pPrior points into the data area
4801 ** of pToRelease. Make sure pToRelease is still writeable. */
4802 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
4803
4804 /* If pPrior is part of the data area of pPage, then make sure pPage
4805 ** is still writeable */
4806 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
4807 || sqlite3PagerIswriteable(pPage->pDbPage) );
4808
drh3aac2dd2004-04-26 14:10:20 +00004809 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00004810 releasePage(pToRelease);
4811 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00004812 pPrior = pOvfl->aData;
4813 put4byte(pPrior, 0);
4814 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00004815 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00004816 }
4817 n = nPayload;
4818 if( n>spaceLeft ) n = spaceLeft;
drhc5053fb2008-11-27 02:22:10 +00004819
4820 /* If pToRelease is not zero than pPayload points into the data area
4821 ** of pToRelease. Make sure pToRelease is still writeable. */
4822 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
4823
4824 /* If pPayload is part of the data area of pPage, then make sure pPage
4825 ** is still writeable */
4826 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
4827 || sqlite3PagerIswriteable(pPage->pDbPage) );
4828
drhb026e052007-05-02 01:34:31 +00004829 if( nSrc>0 ){
4830 if( n>nSrc ) n = nSrc;
4831 assert( pSrc );
4832 memcpy(pPayload, pSrc, n);
4833 }else{
4834 memset(pPayload, 0, n);
4835 }
drh3b7511c2001-05-26 13:15:44 +00004836 nPayload -= n;
drhde647132004-05-07 17:57:49 +00004837 pPayload += n;
drh9b171272004-05-08 02:03:22 +00004838 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00004839 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00004840 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00004841 if( nSrc==0 ){
4842 nSrc = nData;
4843 pSrc = pData;
4844 }
drhdd793422001-06-28 01:54:48 +00004845 }
drh9b171272004-05-08 02:03:22 +00004846 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00004847 return SQLITE_OK;
4848}
4849
drh14acc042001-06-10 19:56:58 +00004850/*
4851** Remove the i-th cell from pPage. This routine effects pPage only.
4852** The cell content is not freed or deallocated. It is assumed that
4853** the cell content has been copied someplace else. This routine just
4854** removes the reference to the cell from pPage.
4855**
4856** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00004857*/
shane0af3f892008-11-12 04:55:34 +00004858static int dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00004859 int i; /* Loop counter */
4860 int pc; /* Offset to cell content of cell being deleted */
4861 u8 *data; /* pPage->aData */
4862 u8 *ptr; /* Used to move bytes around within data[] */
shanedcc50b72008-11-13 18:29:50 +00004863 int rc; /* The return code */
drh43605152004-05-29 21:46:49 +00004864
drh8c42ca92001-06-22 19:15:00 +00004865 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00004866 assert( sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00004867 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00004868 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00004869 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00004870 ptr = &data[pPage->cellOffset + 2*idx];
shane0af3f892008-11-12 04:55:34 +00004871 pc = get2byte(ptr);
drhc5053fb2008-11-27 02:22:10 +00004872 if( (pc<pPage->hdrOffset+6+(pPage->leaf?0:4))
4873 || (pc+sz>pPage->pBt->usableSize) ){
shane0af3f892008-11-12 04:55:34 +00004874 return SQLITE_CORRUPT_BKPT;
4875 }
shanedcc50b72008-11-13 18:29:50 +00004876 rc = freeSpace(pPage, pc, sz);
4877 if( rc!=SQLITE_OK ){
4878 return rc;
4879 }
drh43605152004-05-29 21:46:49 +00004880 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
4881 ptr[0] = ptr[2];
4882 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00004883 }
4884 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00004885 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
4886 pPage->nFree += 2;
shane0af3f892008-11-12 04:55:34 +00004887 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004888}
4889
4890/*
4891** Insert a new cell on pPage at cell index "i". pCell points to the
4892** content of the cell.
4893**
4894** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00004895** will not fit, then make a copy of the cell content into pTemp if
4896** pTemp is not null. Regardless of pTemp, allocate a new entry
4897** in pPage->aOvfl[] and make it point to the cell content (either
4898** in pTemp or the original pCell) and also record its index.
4899** Allocating a new entry in pPage->aCell[] implies that
4900** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00004901**
4902** If nSkip is non-zero, then do not copy the first nSkip bytes of the
4903** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00004904** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00004905** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00004906*/
danielk1977e80463b2004-11-03 03:01:16 +00004907static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00004908 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00004909 int i, /* New cell becomes the i-th cell of the page */
4910 u8 *pCell, /* Content of the new cell */
4911 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00004912 u8 *pTemp, /* Temp storage space for pCell, if needed */
4913 u8 nSkip /* Do not write the first nSkip bytes of the cell */
drh24cd67e2004-05-10 16:18:47 +00004914){
drh43605152004-05-29 21:46:49 +00004915 int idx; /* Where to write new cell content in data[] */
4916 int j; /* Loop counter */
4917 int top; /* First byte of content for any cell in data[] */
4918 int end; /* First byte past the last cell pointer in data[] */
4919 int ins; /* Index in data[] where new cell pointer is inserted */
4920 int hdr; /* Offset into data[] of the page header */
4921 int cellOffset; /* Address of first cell pointer in data[] */
4922 u8 *data; /* The content of the whole page */
4923 u8 *ptr; /* Used for moving information around in data[] */
4924
4925 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
drhf49661a2008-12-10 16:45:50 +00004926 assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
4927 assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
drh43605152004-05-29 21:46:49 +00004928 assert( sz==cellSizePtr(pPage, pCell) );
drh1fee73e2007-08-29 04:00:57 +00004929 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +00004930 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00004931 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00004932 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004933 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00004934 }
drh43605152004-05-29 21:46:49 +00004935 j = pPage->nOverflow++;
danielk197789d40042008-11-17 14:20:56 +00004936 assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
drh43605152004-05-29 21:46:49 +00004937 pPage->aOvfl[j].pCell = pCell;
drhf49661a2008-12-10 16:45:50 +00004938 pPage->aOvfl[j].idx = (u16)i;
drh43605152004-05-29 21:46:49 +00004939 pPage->nFree = 0;
drh14acc042001-06-10 19:56:58 +00004940 }else{
danielk19776e465eb2007-08-21 13:11:00 +00004941 int rc = sqlite3PagerWrite(pPage->pDbPage);
4942 if( rc!=SQLITE_OK ){
4943 return rc;
4944 }
4945 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00004946 data = pPage->aData;
4947 hdr = pPage->hdrOffset;
4948 top = get2byte(&data[hdr+5]);
4949 cellOffset = pPage->cellOffset;
4950 end = cellOffset + 2*pPage->nCell + 2;
4951 ins = cellOffset + 2*i;
4952 if( end > top - sz ){
shane0af3f892008-11-12 04:55:34 +00004953 rc = defragmentPage(pPage);
4954 if( rc!=SQLITE_OK ){
4955 return rc;
4956 }
drh43605152004-05-29 21:46:49 +00004957 top = get2byte(&data[hdr+5]);
4958 assert( end + sz <= top );
4959 }
4960 idx = allocateSpace(pPage, sz);
4961 assert( idx>0 );
4962 assert( end <= get2byte(&data[hdr+5]) );
shane0af3f892008-11-12 04:55:34 +00004963 if (idx+sz > pPage->pBt->usableSize) {
shane34ac18d2008-11-11 22:18:20 +00004964 return SQLITE_CORRUPT_BKPT;
shane0af3f892008-11-12 04:55:34 +00004965 }
drh43605152004-05-29 21:46:49 +00004966 pPage->nCell++;
4967 pPage->nFree -= 2;
danielk1977a3ad5e72005-01-07 08:56:44 +00004968 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00004969 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
4970 ptr[0] = ptr[-2];
4971 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00004972 }
drh43605152004-05-29 21:46:49 +00004973 put2byte(&data[ins], idx);
4974 put2byte(&data[hdr+3], pPage->nCell);
danielk1977a19df672004-11-03 11:37:07 +00004975#ifndef SQLITE_OMIT_AUTOVACUUM
4976 if( pPage->pBt->autoVacuum ){
4977 /* The cell may contain a pointer to an overflow page. If so, write
4978 ** the entry for the overflow page into the pointer map.
4979 */
4980 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00004981 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh72365832007-03-06 15:53:44 +00004982 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk1977a19df672004-11-03 11:37:07 +00004983 if( (info.nData+(pPage->intKey?0:info.nKey))>info.nLocal ){
4984 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
danielk19776e465eb2007-08-21 13:11:00 +00004985 rc = ptrmapPut(pPage->pBt, pgnoOvfl, PTRMAP_OVERFLOW1, pPage->pgno);
danielk1977a19df672004-11-03 11:37:07 +00004986 if( rc!=SQLITE_OK ) return rc;
4987 }
4988 }
4989#endif
drh14acc042001-06-10 19:56:58 +00004990 }
danielk1977e80463b2004-11-03 03:01:16 +00004991
danielk1977e80463b2004-11-03 03:01:16 +00004992 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00004993}
4994
4995/*
drhfa1a98a2004-05-14 19:08:17 +00004996** Add a list of cells to a page. The page should be initially empty.
4997** The cells are guaranteed to fit on the page.
4998*/
4999static void assemblePage(
5000 MemPage *pPage, /* The page to be assemblied */
5001 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00005002 u8 **apCell, /* Pointers to cell bodies */
drha9121e42008-02-19 14:59:35 +00005003 u16 *aSize /* Sizes of the cells */
drhfa1a98a2004-05-14 19:08:17 +00005004){
5005 int i; /* Loop counter */
5006 int totalSize; /* Total size of all cells */
5007 int hdr; /* Index of page header */
drh43605152004-05-29 21:46:49 +00005008 int cellptr; /* Address of next cell pointer */
5009 int cellbody; /* Address of next cell body */
drhfa1a98a2004-05-14 19:08:17 +00005010 u8 *data; /* Data for the page */
5011
drh43605152004-05-29 21:46:49 +00005012 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00005013 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00005014 assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
drhfa1a98a2004-05-14 19:08:17 +00005015 totalSize = 0;
5016 for(i=0; i<nCell; i++){
5017 totalSize += aSize[i];
5018 }
drh43605152004-05-29 21:46:49 +00005019 assert( totalSize+2*nCell<=pPage->nFree );
drhfa1a98a2004-05-14 19:08:17 +00005020 assert( pPage->nCell==0 );
drhc5053fb2008-11-27 02:22:10 +00005021 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00005022 cellptr = pPage->cellOffset;
drhfa1a98a2004-05-14 19:08:17 +00005023 data = pPage->aData;
5024 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00005025 put2byte(&data[hdr+3], nCell);
drh09d0deb2005-08-02 17:13:09 +00005026 if( nCell ){
5027 cellbody = allocateSpace(pPage, totalSize);
5028 assert( cellbody>0 );
5029 assert( pPage->nFree >= 2*nCell );
5030 pPage->nFree -= 2*nCell;
5031 for(i=0; i<nCell; i++){
5032 put2byte(&data[cellptr], cellbody);
5033 memcpy(&data[cellbody], apCell[i], aSize[i]);
5034 cellptr += 2;
5035 cellbody += aSize[i];
5036 }
5037 assert( cellbody==pPage->pBt->usableSize );
drhfa1a98a2004-05-14 19:08:17 +00005038 }
drhf49661a2008-12-10 16:45:50 +00005039 pPage->nCell = (u16)nCell;
drhfa1a98a2004-05-14 19:08:17 +00005040}
5041
drh14acc042001-06-10 19:56:58 +00005042/*
drhc3b70572003-01-04 19:44:07 +00005043** The following parameters determine how many adjacent pages get involved
5044** in a balancing operation. NN is the number of neighbors on either side
5045** of the page that participate in the balancing operation. NB is the
5046** total number of pages that participate, including the target page and
5047** NN neighbors on either side.
5048**
5049** The minimum value of NN is 1 (of course). Increasing NN above 1
5050** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
5051** in exchange for a larger degradation in INSERT and UPDATE performance.
5052** The value of NN appears to give the best results overall.
5053*/
5054#define NN 1 /* Number of neighbors on either side of pPage */
5055#define NB (NN*2+1) /* Total pages involved in the balance */
5056
drh43605152004-05-29 21:46:49 +00005057/* Forward reference */
danielk197771d5d2c2008-09-29 11:49:47 +00005058static int balance(BtCursor*, int);
danielk1977ac245ec2005-01-14 13:50:11 +00005059
drh615ae552005-01-16 23:21:00 +00005060#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00005061/*
5062** This version of balance() handles the common special case where
5063** a new entry is being inserted on the extreme right-end of the
5064** tree, in other words, when the new entry will become the largest
5065** entry in the tree.
5066**
5067** Instead of trying balance the 3 right-most leaf pages, just add
5068** a new page to the right-hand side and put the one new entry in
5069** that page. This leaves the right side of the tree somewhat
5070** unbalanced. But odds are that we will be inserting new entries
5071** at the end soon afterwards so the nearly empty page will quickly
5072** fill up. On average.
5073**
5074** pPage is the leaf page which is the right-most page in the tree.
5075** pParent is its parent. pPage must have a single overflow entry
5076** which is also the right-most entry on the page.
5077*/
danielk197771d5d2c2008-09-29 11:49:47 +00005078static int balance_quick(BtCursor *pCur){
danielk1977ac245ec2005-01-14 13:50:11 +00005079 int rc;
danielk1977eaa06f62008-09-18 17:34:44 +00005080 MemPage *pNew = 0;
danielk1977ac245ec2005-01-14 13:50:11 +00005081 Pgno pgnoNew;
5082 u8 *pCell;
drha9121e42008-02-19 14:59:35 +00005083 u16 szCell;
danielk1977ac245ec2005-01-14 13:50:11 +00005084 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00005085 MemPage *pPage = pCur->apPage[pCur->iPage];
5086 MemPage *pParent = pCur->apPage[pCur->iPage-1];
danielk1977aef0bf62005-12-30 16:28:01 +00005087 BtShared *pBt = pPage->pBt;
danielk197779a40da2005-01-16 08:00:01 +00005088 int parentIdx = pParent->nCell; /* pParent new divider cell index */
5089 int parentSize; /* Size of new divider cell */
5090 u8 parentCell[64]; /* Space for the new divider cell */
danielk1977ac245ec2005-01-14 13:50:11 +00005091
drh1fee73e2007-08-29 04:00:57 +00005092 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00005093
danielk1977ac245ec2005-01-14 13:50:11 +00005094 /* Allocate a new page. Insert the overflow cell from pPage
5095 ** into it. Then remove the overflow cell from pPage.
5096 */
drh4f0c5872007-03-26 22:05:01 +00005097 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk1977eaa06f62008-09-18 17:34:44 +00005098 if( rc==SQLITE_OK ){
5099 pCell = pPage->aOvfl[0].pCell;
5100 szCell = cellSizePtr(pPage, pCell);
drhc5053fb2008-11-27 02:22:10 +00005101 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
danielk1977eaa06f62008-09-18 17:34:44 +00005102 zeroPage(pNew, pPage->aData[0]);
5103 assemblePage(pNew, 1, &pCell, &szCell);
5104 pPage->nOverflow = 0;
5105
danielk1977eaa06f62008-09-18 17:34:44 +00005106 /* pPage is currently the right-child of pParent. Change this
5107 ** so that the right-child is the new page allocated above and
5108 ** pPage is the next-to-right child.
5109 **
5110 ** Ignore the return value of the call to fillInCell(). fillInCell()
5111 ** may only return other than SQLITE_OK if it is required to allocate
5112 ** one or more overflow pages. Since an internal table B-Tree cell
5113 ** may never spill over onto an overflow page (it is a maximum of
5114 ** 13 bytes in size), it is not neccessary to check the return code.
5115 **
5116 ** Similarly, the insertCell() function cannot fail if the page
5117 ** being inserted into is already writable and the cell does not
5118 ** contain an overflow pointer. So ignore this return code too.
5119 */
5120 assert( pPage->nCell>0 );
5121 pCell = findCell(pPage, pPage->nCell-1);
5122 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
5123 fillInCell(pParent, parentCell, 0, info.nKey, 0, 0, 0, &parentSize);
5124 assert( parentSize<64 );
5125 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
5126 insertCell(pParent, parentIdx, parentCell, parentSize, 0, 4);
5127 put4byte(findOverflowCell(pParent,parentIdx), pPage->pgno);
5128 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
5129
5130 /* If this is an auto-vacuum database, update the pointer map
5131 ** with entries for the new page, and any pointer from the
5132 ** cell on the page to an overflow page.
5133 */
5134 if( ISAUTOVACUUM ){
5135 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
5136 if( rc==SQLITE_OK ){
5137 rc = ptrmapPutOvfl(pNew, 0);
5138 }
danielk1977ac11ee62005-01-15 12:45:51 +00005139 }
danielk1977e08a3c42008-09-18 18:17:03 +00005140
5141 /* Release the reference to the new page. */
5142 releasePage(pNew);
danielk1977ac11ee62005-01-15 12:45:51 +00005143 }
5144
danielk1977eaa06f62008-09-18 17:34:44 +00005145 /* At this point the pPage->nFree variable is not set correctly with
5146 ** respect to the content of the page (because it was set to 0 by
5147 ** insertCell). So call sqlite3BtreeInitPage() to make sure it is
5148 ** correct.
5149 **
5150 ** This has to be done even if an error will be returned. Normally, if
5151 ** an error occurs during tree balancing, the contents of MemPage are
5152 ** not important, as they will be recalculated when the page is rolled
5153 ** back. But here, in balance_quick(), it is possible that pPage has
5154 ** not yet been marked dirty or written into the journal file. Therefore
5155 ** it will not be rolled back and so it is important to make sure that
5156 ** the page data and contents of MemPage are consistent.
5157 */
5158 pPage->isInit = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005159 sqlite3BtreeInitPage(pPage);
danielk1977a4124bd2008-12-23 10:37:47 +00005160 assert( pPage->nOverflow==0 );
danielk1977eaa06f62008-09-18 17:34:44 +00005161
danielk1977e08a3c42008-09-18 18:17:03 +00005162 /* If everything else succeeded, balance the parent page, in
5163 ** case the divider cell inserted caused it to become overfull.
danielk197779a40da2005-01-16 08:00:01 +00005164 */
danielk1977eaa06f62008-09-18 17:34:44 +00005165 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00005166 releasePage(pPage);
5167 pCur->iPage--;
5168 rc = balance(pCur, 0);
danielk1977eaa06f62008-09-18 17:34:44 +00005169 }
5170 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00005171}
drh615ae552005-01-16 23:21:00 +00005172#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00005173
drhc3b70572003-01-04 19:44:07 +00005174/*
drhab01f612004-05-22 02:55:23 +00005175** This routine redistributes Cells on pPage and up to NN*2 siblings
drh8b2f49b2001-06-08 00:21:52 +00005176** of pPage so that all pages have about the same amount of free space.
drh0c6cc4e2004-06-15 02:13:26 +00005177** Usually NN siblings on either side of pPage is used in the balancing,
5178** though more siblings might come from one side if pPage is the first
drhab01f612004-05-22 02:55:23 +00005179** or last child of its parent. If pPage has fewer than 2*NN siblings
drh8b2f49b2001-06-08 00:21:52 +00005180** (something which can only happen if pPage is the root page or a
drh14acc042001-06-10 19:56:58 +00005181** child of root) then all available siblings participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00005182**
drh0c6cc4e2004-06-15 02:13:26 +00005183** The number of siblings of pPage might be increased or decreased by one or
5184** two in an effort to keep pages nearly full but not over full. The root page
drhab01f612004-05-22 02:55:23 +00005185** is special and is allowed to be nearly empty. If pPage is
drh8c42ca92001-06-22 19:15:00 +00005186** the root page, then the depth of the tree might be increased
drh8b2f49b2001-06-08 00:21:52 +00005187** or decreased by one, as necessary, to keep the root page from being
drhab01f612004-05-22 02:55:23 +00005188** overfull or completely empty.
drh14acc042001-06-10 19:56:58 +00005189**
drh8b2f49b2001-06-08 00:21:52 +00005190** Note that when this routine is called, some of the Cells on pPage
drh4b70f112004-05-02 21:12:19 +00005191** might not actually be stored in pPage->aData[]. This can happen
drh8b2f49b2001-06-08 00:21:52 +00005192** if the page is overfull. Part of the job of this routine is to
drh4b70f112004-05-02 21:12:19 +00005193** make sure all Cells for pPage once again fit in pPage->aData[].
drh14acc042001-06-10 19:56:58 +00005194**
drh8c42ca92001-06-22 19:15:00 +00005195** In the course of balancing the siblings of pPage, the parent of pPage
5196** might become overfull or underfull. If that happens, then this routine
5197** is called recursively on the parent.
5198**
drh5e00f6c2001-09-13 13:46:56 +00005199** If this routine fails for any reason, it might leave the database
5200** in a corrupted state. So if this routine fails, the database should
5201** be rolled back.
drh8b2f49b2001-06-08 00:21:52 +00005202*/
danielk197771d5d2c2008-09-29 11:49:47 +00005203static int balance_nonroot(BtCursor *pCur){
5204 MemPage *pPage; /* The over or underfull page to balance */
drh8b2f49b2001-06-08 00:21:52 +00005205 MemPage *pParent; /* The parent of pPage */
drh16a9b832007-05-05 18:39:25 +00005206 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00005207 int nCell = 0; /* Number of cells in apCell[] */
5208 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
danielk1977a4124bd2008-12-23 10:37:47 +00005209 int nOld = 0; /* Number of pages in apOld[] */
5210 int nNew = 0; /* Number of pages in apNew[] */
drh8b2f49b2001-06-08 00:21:52 +00005211 int nDiv; /* Number of cells in apDiv[] */
drh14acc042001-06-10 19:56:58 +00005212 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00005213 int idx; /* Index of pPage in pParent->aCell[] */
5214 int nxDiv; /* Next divider slot in pParent->aCell[] */
drh14acc042001-06-10 19:56:58 +00005215 int rc; /* The return code */
drh91025292004-05-03 19:49:32 +00005216 int leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00005217 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00005218 int usableSpace; /* Bytes in pPage beyond the header */
5219 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00005220 int subtotal; /* Subtotal of bytes in cells on one page */
drhe5ae5732008-06-15 02:51:47 +00005221 int iSpace1 = 0; /* First unused byte of aSpace1[] */
5222 int iSpace2 = 0; /* First unused byte of aSpace2[] */
drhfacf0302008-06-17 15:12:00 +00005223 int szScratch; /* Size of scratch memory requested */
drhc3b70572003-01-04 19:44:07 +00005224 MemPage *apOld[NB]; /* pPage and up to two siblings */
5225 Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
drh4b70f112004-05-02 21:12:19 +00005226 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00005227 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
5228 Pgno pgnoNew[NB+2]; /* Page numbers for each page in apNew[] */
drh4b70f112004-05-02 21:12:19 +00005229 u8 *apDiv[NB]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00005230 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
5231 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00005232 u8 **apCell = 0; /* All cells begin balanced */
drha9121e42008-02-19 14:59:35 +00005233 u16 *szCell; /* Local size of all cells in apCell[] */
drhe5ae5732008-06-15 02:51:47 +00005234 u8 *aCopy[NB]; /* Space for holding data of apCopy[] */
5235 u8 *aSpace1; /* Space for copies of dividers cells before balance */
5236 u8 *aSpace2 = 0; /* Space for overflow dividers cells after balance */
danielk1977ac11ee62005-01-15 12:45:51 +00005237 u8 *aFrom = 0;
drh8b2f49b2001-06-08 00:21:52 +00005238
danielk197771d5d2c2008-09-29 11:49:47 +00005239 pPage = pCur->apPage[pCur->iPage];
drh1fee73e2007-08-29 04:00:57 +00005240 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf94a1732008-09-30 17:18:17 +00005241 VVA_ONLY( pCur->pagesShuffled = 1 );
drhd677b3d2007-08-20 22:48:41 +00005242
drh14acc042001-06-10 19:56:58 +00005243 /*
drh43605152004-05-29 21:46:49 +00005244 ** Find the parent page.
drh8b2f49b2001-06-08 00:21:52 +00005245 */
danielk197771d5d2c2008-09-29 11:49:47 +00005246 assert( pCur->iPage>0 );
5247 assert( pPage->isInit );
danielk19776e465eb2007-08-21 13:11:00 +00005248 assert( sqlite3PagerIswriteable(pPage->pDbPage) || pPage->nOverflow==1 );
drh4b70f112004-05-02 21:12:19 +00005249 pBt = pPage->pBt;
danielk197771d5d2c2008-09-29 11:49:47 +00005250 pParent = pCur->apPage[pCur->iPage-1];
drh43605152004-05-29 21:46:49 +00005251 assert( pParent );
danielk19773b8a05f2007-03-19 17:44:26 +00005252 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pParent->pDbPage)) ){
danielk1977a4124bd2008-12-23 10:37:47 +00005253 goto balance_cleanup;
danielk197707cb5602006-01-20 10:55:05 +00005254 }
danielk1977474b7cc2008-07-09 11:49:46 +00005255
drh43605152004-05-29 21:46:49 +00005256 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
drh2e38c322004-09-03 18:38:44 +00005257
drh615ae552005-01-16 23:21:00 +00005258#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00005259 /*
5260 ** A special case: If a new entry has just been inserted into a
5261 ** table (that is, a btree with integer keys and all data at the leaves)
drh09d0deb2005-08-02 17:13:09 +00005262 ** and the new entry is the right-most entry in the tree (it has the
drhf222e712005-01-14 22:55:49 +00005263 ** largest key) then use the special balance_quick() routine for
5264 ** balancing. balance_quick() is much faster and results in a tighter
5265 ** packing of data in the common case.
5266 */
danielk1977ac245ec2005-01-14 13:50:11 +00005267 if( pPage->leaf &&
5268 pPage->intKey &&
danielk1977ac245ec2005-01-14 13:50:11 +00005269 pPage->nOverflow==1 &&
5270 pPage->aOvfl[0].idx==pPage->nCell &&
danielk197771d5d2c2008-09-29 11:49:47 +00005271 pParent->pgno!=1 &&
danielk1977ac245ec2005-01-14 13:50:11 +00005272 get4byte(&pParent->aData[pParent->hdrOffset+8])==pPage->pgno
5273 ){
drh44845222008-07-17 18:39:57 +00005274 assert( pPage->intKey );
danielk1977ac11ee62005-01-15 12:45:51 +00005275 /*
5276 ** TODO: Check the siblings to the left of pPage. It may be that
5277 ** they are not full and no new page is required.
5278 */
danielk197771d5d2c2008-09-29 11:49:47 +00005279 return balance_quick(pCur);
danielk1977ac245ec2005-01-14 13:50:11 +00005280 }
5281#endif
5282
danielk19776e465eb2007-08-21 13:11:00 +00005283 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage)) ){
danielk1977a4124bd2008-12-23 10:37:47 +00005284 goto balance_cleanup;
danielk19776e465eb2007-08-21 13:11:00 +00005285 }
5286
drh2e38c322004-09-03 18:38:44 +00005287 /*
drh4b70f112004-05-02 21:12:19 +00005288 ** Find the cell in the parent page whose left child points back
drh14acc042001-06-10 19:56:58 +00005289 ** to pPage. The "idx" variable is the index of that cell. If pPage
5290 ** is the rightmost child of pParent then set idx to pParent->nCell
drh8b2f49b2001-06-08 00:21:52 +00005291 */
danielk1977bf93c562008-09-29 15:53:25 +00005292 idx = pCur->aiIdx[pCur->iPage-1];
5293 assertParentIndex(pParent, idx, pPage->pgno);
drh8b2f49b2001-06-08 00:21:52 +00005294
5295 /*
drh4b70f112004-05-02 21:12:19 +00005296 ** Find sibling pages to pPage and the cells in pParent that divide
drhc3b70572003-01-04 19:44:07 +00005297 ** the siblings. An attempt is made to find NN siblings on either
5298 ** side of pPage. More siblings are taken from one side, however, if
5299 ** pPage there are fewer than NN siblings on the other side. If pParent
5300 ** has NB or fewer children then all children of pParent are taken.
drh14acc042001-06-10 19:56:58 +00005301 */
drhc3b70572003-01-04 19:44:07 +00005302 nxDiv = idx - NN;
5303 if( nxDiv + NB > pParent->nCell ){
5304 nxDiv = pParent->nCell - NB + 1;
drh8b2f49b2001-06-08 00:21:52 +00005305 }
drhc3b70572003-01-04 19:44:07 +00005306 if( nxDiv<0 ){
5307 nxDiv = 0;
5308 }
drh8b2f49b2001-06-08 00:21:52 +00005309 nDiv = 0;
drhc3b70572003-01-04 19:44:07 +00005310 for(i=0, k=nxDiv; i<NB; i++, k++){
drh14acc042001-06-10 19:56:58 +00005311 if( k<pParent->nCell ){
danielk19771cc5ed82007-05-16 17:28:43 +00005312 apDiv[i] = findCell(pParent, k);
drh8b2f49b2001-06-08 00:21:52 +00005313 nDiv++;
drha34b6762004-05-07 13:30:42 +00005314 assert( !pParent->leaf );
drh43605152004-05-29 21:46:49 +00005315 pgnoOld[i] = get4byte(apDiv[i]);
drh14acc042001-06-10 19:56:58 +00005316 }else if( k==pParent->nCell ){
drh43605152004-05-29 21:46:49 +00005317 pgnoOld[i] = get4byte(&pParent->aData[pParent->hdrOffset+8]);
drh14acc042001-06-10 19:56:58 +00005318 }else{
5319 break;
drh8b2f49b2001-06-08 00:21:52 +00005320 }
danielk197771d5d2c2008-09-29 11:49:47 +00005321 rc = getAndInitPage(pBt, pgnoOld[i], &apOld[i]);
drh6019e162001-07-02 17:51:45 +00005322 if( rc ) goto balance_cleanup;
danielk197771d5d2c2008-09-29 11:49:47 +00005323 /* apOld[i]->idxParent = k; */
drh91025292004-05-03 19:49:32 +00005324 apCopy[i] = 0;
5325 assert( i==nOld );
drh14acc042001-06-10 19:56:58 +00005326 nOld++;
danielk1977634f2982005-03-28 08:44:07 +00005327 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
drh8b2f49b2001-06-08 00:21:52 +00005328 }
5329
drha9121e42008-02-19 14:59:35 +00005330 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00005331 ** alignment */
drha9121e42008-02-19 14:59:35 +00005332 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00005333
drh8b2f49b2001-06-08 00:21:52 +00005334 /*
danielk1977634f2982005-03-28 08:44:07 +00005335 ** Allocate space for memory structures
5336 */
drhfacf0302008-06-17 15:12:00 +00005337 szScratch =
drha9121e42008-02-19 14:59:35 +00005338 nMaxCells*sizeof(u8*) /* apCell */
5339 + nMaxCells*sizeof(u16) /* szCell */
5340 + (ROUND8(sizeof(MemPage))+pBt->pageSize)*NB /* aCopy */
drhe5ae5732008-06-15 02:51:47 +00005341 + pBt->pageSize /* aSpace1 */
drhfacf0302008-06-17 15:12:00 +00005342 + (ISAUTOVACUUM ? nMaxCells : 0); /* aFrom */
5343 apCell = sqlite3ScratchMalloc( szScratch );
danielk1977634f2982005-03-28 08:44:07 +00005344 if( apCell==0 ){
5345 rc = SQLITE_NOMEM;
5346 goto balance_cleanup;
5347 }
drha9121e42008-02-19 14:59:35 +00005348 szCell = (u16*)&apCell[nMaxCells];
danielk1977634f2982005-03-28 08:44:07 +00005349 aCopy[0] = (u8*)&szCell[nMaxCells];
drhea598cb2009-04-05 12:22:08 +00005350 assert( EIGHT_BYTE_ALIGNMENT(aCopy[0]) );
danielk1977634f2982005-03-28 08:44:07 +00005351 for(i=1; i<NB; i++){
drhc96d8532005-05-03 12:30:33 +00005352 aCopy[i] = &aCopy[i-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
drh66e80082008-12-16 13:46:29 +00005353 assert( ((aCopy[i] - (u8*)0) & 7)==0 ); /* 8-byte alignment required */
danielk1977634f2982005-03-28 08:44:07 +00005354 }
drhe5ae5732008-06-15 02:51:47 +00005355 aSpace1 = &aCopy[NB-1][pBt->pageSize+ROUND8(sizeof(MemPage))];
drhea598cb2009-04-05 12:22:08 +00005356 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
danielk197785d90ca2008-07-19 14:25:15 +00005357 if( ISAUTOVACUUM ){
drhe5ae5732008-06-15 02:51:47 +00005358 aFrom = &aSpace1[pBt->pageSize];
danielk1977634f2982005-03-28 08:44:07 +00005359 }
drhfacf0302008-06-17 15:12:00 +00005360 aSpace2 = sqlite3PageMalloc(pBt->pageSize);
drhe5ae5732008-06-15 02:51:47 +00005361 if( aSpace2==0 ){
5362 rc = SQLITE_NOMEM;
5363 goto balance_cleanup;
5364 }
danielk1977634f2982005-03-28 08:44:07 +00005365
5366 /*
drh14acc042001-06-10 19:56:58 +00005367 ** Make copies of the content of pPage and its siblings into aOld[].
5368 ** The rest of this function will use data from the copies rather
5369 ** that the original pages since the original pages will be in the
5370 ** process of being overwritten.
5371 */
5372 for(i=0; i<nOld; i++){
drhbf4bca52007-09-06 22:19:14 +00005373 MemPage *p = apCopy[i] = (MemPage*)aCopy[i];
5374 memcpy(p, apOld[i], sizeof(MemPage));
5375 p->aData = (void*)&p[1];
5376 memcpy(p->aData, apOld[i]->aData, pBt->pageSize);
drh14acc042001-06-10 19:56:58 +00005377 }
5378
5379 /*
5380 ** Load pointers to all cells on sibling pages and the divider cells
5381 ** into the local apCell[] array. Make copies of the divider cells
drhe5ae5732008-06-15 02:51:47 +00005382 ** into space obtained form aSpace1[] and remove the the divider Cells
drhb6f41482004-05-14 01:58:11 +00005383 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00005384 **
5385 ** If the siblings are on leaf pages, then the child pointers of the
5386 ** divider cells are stripped from the cells before they are copied
drhe5ae5732008-06-15 02:51:47 +00005387 ** into aSpace1[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00005388 ** child pointers. If siblings are not leaves, then all cell in
5389 ** apCell[] include child pointers. Either way, all cells in apCell[]
5390 ** are alike.
drh96f5b762004-05-16 16:24:36 +00005391 **
5392 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
5393 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00005394 */
5395 nCell = 0;
drh4b70f112004-05-02 21:12:19 +00005396 leafCorrection = pPage->leaf*4;
drh44845222008-07-17 18:39:57 +00005397 leafData = pPage->hasData;
drh8b2f49b2001-06-08 00:21:52 +00005398 for(i=0; i<nOld; i++){
drh4b70f112004-05-02 21:12:19 +00005399 MemPage *pOld = apCopy[i];
drh43605152004-05-29 21:46:49 +00005400 int limit = pOld->nCell+pOld->nOverflow;
5401 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00005402 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00005403 apCell[nCell] = findOverflowCell(pOld, j);
5404 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk197785d90ca2008-07-19 14:25:15 +00005405 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005406 int a;
drhf49661a2008-12-10 16:45:50 +00005407 aFrom[nCell] = (u8)i; assert( i>=0 && i<6 );
danielk1977ac11ee62005-01-15 12:45:51 +00005408 for(a=0; a<pOld->nOverflow; a++){
5409 if( pOld->aOvfl[a].pCell==apCell[nCell] ){
5410 aFrom[nCell] = 0xFF;
5411 break;
5412 }
5413 }
5414 }
drh14acc042001-06-10 19:56:58 +00005415 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00005416 }
5417 if( i<nOld-1 ){
drha9121e42008-02-19 14:59:35 +00005418 u16 sz = cellSizePtr(pParent, apDiv[i]);
drh8b18dd42004-05-12 19:18:15 +00005419 if( leafData ){
drh96f5b762004-05-16 16:24:36 +00005420 /* With the LEAFDATA flag, pParent cells hold only INTKEYs that
5421 ** are duplicates of keys on the child pages. We need to remove
5422 ** the divider cells from pParent, but the dividers cells are not
5423 ** added to apCell[] because they are duplicates of child cells.
5424 */
drh8b18dd42004-05-12 19:18:15 +00005425 dropCell(pParent, nxDiv, sz);
drh4b70f112004-05-02 21:12:19 +00005426 }else{
drhb6f41482004-05-14 01:58:11 +00005427 u8 *pTemp;
danielk1977634f2982005-03-28 08:44:07 +00005428 assert( nCell<nMaxCells );
drhb6f41482004-05-14 01:58:11 +00005429 szCell[nCell] = sz;
drhe5ae5732008-06-15 02:51:47 +00005430 pTemp = &aSpace1[iSpace1];
5431 iSpace1 += sz;
5432 assert( sz<=pBt->pageSize/4 );
5433 assert( iSpace1<=pBt->pageSize );
drhb6f41482004-05-14 01:58:11 +00005434 memcpy(pTemp, apDiv[i], sz);
5435 apCell[nCell] = pTemp+leafCorrection;
danielk197785d90ca2008-07-19 14:25:15 +00005436 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005437 aFrom[nCell] = 0xFF;
5438 }
drhb6f41482004-05-14 01:58:11 +00005439 dropCell(pParent, nxDiv, sz);
drhf49661a2008-12-10 16:45:50 +00005440 assert( leafCorrection==0 || leafCorrection==4 );
5441 szCell[nCell] -= (u16)leafCorrection;
drh43605152004-05-29 21:46:49 +00005442 assert( get4byte(pTemp)==pgnoOld[i] );
drh8b18dd42004-05-12 19:18:15 +00005443 if( !pOld->leaf ){
5444 assert( leafCorrection==0 );
5445 /* The right pointer of the child page pOld becomes the left
5446 ** pointer of the divider cell */
drh43605152004-05-29 21:46:49 +00005447 memcpy(apCell[nCell], &pOld->aData[pOld->hdrOffset+8], 4);
drh8b18dd42004-05-12 19:18:15 +00005448 }else{
5449 assert( leafCorrection==4 );
danielk197739c96042007-05-12 10:41:47 +00005450 if( szCell[nCell]<4 ){
5451 /* Do not allow any cells smaller than 4 bytes. */
5452 szCell[nCell] = 4;
5453 }
drh8b18dd42004-05-12 19:18:15 +00005454 }
5455 nCell++;
drh4b70f112004-05-02 21:12:19 +00005456 }
drh8b2f49b2001-06-08 00:21:52 +00005457 }
5458 }
5459
5460 /*
drh6019e162001-07-02 17:51:45 +00005461 ** Figure out the number of pages needed to hold all nCell cells.
5462 ** Store this number in "k". Also compute szNew[] which is the total
5463 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00005464 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00005465 ** cntNew[k] should equal nCell.
5466 **
drh96f5b762004-05-16 16:24:36 +00005467 ** Values computed by this block:
5468 **
5469 ** k: The total number of sibling pages
5470 ** szNew[i]: Spaced used on the i-th sibling page.
5471 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
5472 ** the right of the i-th sibling page.
5473 ** usableSpace: Number of bytes of space available on each sibling.
5474 **
drh8b2f49b2001-06-08 00:21:52 +00005475 */
drh43605152004-05-29 21:46:49 +00005476 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00005477 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00005478 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00005479 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00005480 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00005481 szNew[k] = subtotal - szCell[i];
5482 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00005483 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00005484 subtotal = 0;
5485 k++;
5486 }
5487 }
5488 szNew[k] = subtotal;
5489 cntNew[k] = nCell;
5490 k++;
drh96f5b762004-05-16 16:24:36 +00005491
5492 /*
5493 ** The packing computed by the previous block is biased toward the siblings
5494 ** on the left side. The left siblings are always nearly full, while the
5495 ** right-most sibling might be nearly empty. This block of code attempts
5496 ** to adjust the packing of siblings to get a better balance.
5497 **
5498 ** This adjustment is more than an optimization. The packing above might
5499 ** be so out of balance as to be illegal. For example, the right-most
5500 ** sibling might be completely empty. This adjustment is not optional.
5501 */
drh6019e162001-07-02 17:51:45 +00005502 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00005503 int szRight = szNew[i]; /* Size of sibling on the right */
5504 int szLeft = szNew[i-1]; /* Size of sibling on the left */
5505 int r; /* Index of right-most cell in left sibling */
5506 int d; /* Index of first cell to the left of right sibling */
5507
5508 r = cntNew[i-1] - 1;
5509 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00005510 assert( d<nMaxCells );
5511 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00005512 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
5513 szRight += szCell[d] + 2;
5514 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00005515 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00005516 r = cntNew[i-1] - 1;
5517 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00005518 }
drh96f5b762004-05-16 16:24:36 +00005519 szNew[i] = szRight;
5520 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00005521 }
drh09d0deb2005-08-02 17:13:09 +00005522
5523 /* Either we found one or more cells (cntnew[0])>0) or we are the
5524 ** a virtual root page. A virtual root page is when the real root
5525 ** page is page 1 and we are the only child of that page.
5526 */
5527 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00005528
5529 /*
drh6b308672002-07-08 02:16:37 +00005530 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00005531 */
drh4b70f112004-05-02 21:12:19 +00005532 assert( pPage->pgno>1 );
5533 pageFlags = pPage->aData[0];
drh14acc042001-06-10 19:56:58 +00005534 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00005535 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00005536 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00005537 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00005538 pgnoNew[i] = pgnoOld[i];
5539 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00005540 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00005541 nNew++;
danielk197728129562005-01-11 10:25:06 +00005542 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00005543 }else{
drh7aa8f852006-03-28 00:24:44 +00005544 assert( i>0 );
drh4f0c5872007-03-26 22:05:01 +00005545 rc = allocateBtreePage(pBt, &pNew, &pgnoNew[i], pgnoNew[i-1], 0);
drh6b308672002-07-08 02:16:37 +00005546 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00005547 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00005548 nNew++;
drh6b308672002-07-08 02:16:37 +00005549 }
drh8b2f49b2001-06-08 00:21:52 +00005550 }
5551
danielk1977299b1872004-11-22 10:02:10 +00005552 /* Free any old pages that were not reused as new pages.
5553 */
5554 while( i<nOld ){
5555 rc = freePage(apOld[i]);
5556 if( rc ) goto balance_cleanup;
5557 releasePage(apOld[i]);
5558 apOld[i] = 0;
5559 i++;
5560 }
5561
drh8b2f49b2001-06-08 00:21:52 +00005562 /*
drhf9ffac92002-03-02 19:00:31 +00005563 ** Put the new pages in accending order. This helps to
5564 ** keep entries in the disk file in order so that a scan
5565 ** of the table is a linear scan through the file. That
5566 ** in turn helps the operating system to deliver pages
5567 ** from the disk more rapidly.
5568 **
5569 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00005570 ** n is never more than NB (a small constant), that should
5571 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00005572 **
drhc3b70572003-01-04 19:44:07 +00005573 ** When NB==3, this one optimization makes the database
5574 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00005575 */
5576 for(i=0; i<k-1; i++){
5577 int minV = pgnoNew[i];
5578 int minI = i;
5579 for(j=i+1; j<k; j++){
drh7d02cb72003-06-04 16:24:39 +00005580 if( pgnoNew[j]<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00005581 minI = j;
5582 minV = pgnoNew[j];
5583 }
5584 }
5585 if( minI>i ){
5586 int t;
5587 MemPage *pT;
5588 t = pgnoNew[i];
5589 pT = apNew[i];
5590 pgnoNew[i] = pgnoNew[minI];
5591 apNew[i] = apNew[minI];
5592 pgnoNew[minI] = t;
5593 apNew[minI] = pT;
5594 }
5595 }
drha2fce642004-06-05 00:01:44 +00005596 TRACE(("BALANCE: old: %d %d %d new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
drh24cd67e2004-05-10 16:18:47 +00005597 pgnoOld[0],
5598 nOld>=2 ? pgnoOld[1] : 0,
5599 nOld>=3 ? pgnoOld[2] : 0,
drh10c0fa62004-05-18 12:50:17 +00005600 pgnoNew[0], szNew[0],
5601 nNew>=2 ? pgnoNew[1] : 0, nNew>=2 ? szNew[1] : 0,
5602 nNew>=3 ? pgnoNew[2] : 0, nNew>=3 ? szNew[2] : 0,
drha2fce642004-06-05 00:01:44 +00005603 nNew>=4 ? pgnoNew[3] : 0, nNew>=4 ? szNew[3] : 0,
5604 nNew>=5 ? pgnoNew[4] : 0, nNew>=5 ? szNew[4] : 0));
drh24cd67e2004-05-10 16:18:47 +00005605
drhf9ffac92002-03-02 19:00:31 +00005606 /*
drh14acc042001-06-10 19:56:58 +00005607 ** Evenly distribute the data in apCell[] across the new pages.
5608 ** Insert divider cells into pParent as necessary.
5609 */
5610 j = 0;
5611 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00005612 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00005613 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00005614 assert( j<nMaxCells );
drh4b70f112004-05-02 21:12:19 +00005615 assert( pNew->pgno==pgnoNew[i] );
drh10131482008-07-11 03:34:09 +00005616 zeroPage(pNew, pageFlags);
drhfa1a98a2004-05-14 19:08:17 +00005617 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00005618 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00005619 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00005620
danielk1977ac11ee62005-01-15 12:45:51 +00005621 /* If this is an auto-vacuum database, update the pointer map entries
5622 ** that point to the siblings that were rearranged. These can be: left
5623 ** children of cells, the right-child of the page, or overflow pages
5624 ** pointed to by cells.
5625 */
danielk197785d90ca2008-07-19 14:25:15 +00005626 if( ISAUTOVACUUM ){
danielk1977ac11ee62005-01-15 12:45:51 +00005627 for(k=j; k<cntNew[i]; k++){
danielk1977634f2982005-03-28 08:44:07 +00005628 assert( k<nMaxCells );
danielk1977ac11ee62005-01-15 12:45:51 +00005629 if( aFrom[k]==0xFF || apCopy[aFrom[k]]->pgno!=pNew->pgno ){
danielk197779a40da2005-01-16 08:00:01 +00005630 rc = ptrmapPutOvfl(pNew, k-j);
danielk197787c52b52008-07-19 11:49:07 +00005631 if( rc==SQLITE_OK && leafCorrection==0 ){
5632 rc = ptrmapPut(pBt, get4byte(apCell[k]), PTRMAP_BTREE, pNew->pgno);
5633 }
danielk197779a40da2005-01-16 08:00:01 +00005634 if( rc!=SQLITE_OK ){
5635 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00005636 }
5637 }
5638 }
5639 }
danielk1977ac11ee62005-01-15 12:45:51 +00005640
5641 j = cntNew[i];
5642
5643 /* If the sibling page assembled above was not the right-most sibling,
5644 ** insert a divider cell into the parent page.
5645 */
drh14acc042001-06-10 19:56:58 +00005646 if( i<nNew-1 && j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00005647 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00005648 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00005649 int sz;
danielk1977634f2982005-03-28 08:44:07 +00005650
5651 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00005652 pCell = apCell[j];
5653 sz = szCell[j] + leafCorrection;
drhe5ae5732008-06-15 02:51:47 +00005654 pTemp = &aSpace2[iSpace2];
drh4b70f112004-05-02 21:12:19 +00005655 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00005656 memcpy(&pNew->aData[8], pCell, 4);
danielk197785d90ca2008-07-19 14:25:15 +00005657 if( ISAUTOVACUUM
danielk197787c52b52008-07-19 11:49:07 +00005658 && (aFrom[j]==0xFF || apCopy[aFrom[j]]->pgno!=pNew->pgno)
5659 ){
5660 rc = ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno);
5661 if( rc!=SQLITE_OK ){
5662 goto balance_cleanup;
5663 }
5664 }
drh8b18dd42004-05-12 19:18:15 +00005665 }else if( leafData ){
drhfd131da2007-08-07 17:13:03 +00005666 /* If the tree is a leaf-data tree, and the siblings are leaves,
danielk1977ac11ee62005-01-15 12:45:51 +00005667 ** then there is no divider cell in apCell[]. Instead, the divider
5668 ** cell consists of the integer key for the right-most cell of
5669 ** the sibling-page assembled above only.
5670 */
drh6f11bef2004-05-13 01:12:56 +00005671 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00005672 j--;
drh16a9b832007-05-05 18:39:25 +00005673 sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
drhe5ae5732008-06-15 02:51:47 +00005674 pCell = pTemp;
drh20abac22009-01-28 20:21:17 +00005675 rc = fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
5676 if( rc!=SQLITE_OK ){
5677 goto balance_cleanup;
5678 }
drh8b18dd42004-05-12 19:18:15 +00005679 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00005680 }else{
5681 pCell -= 4;
danielk19774aeff622007-05-12 09:30:47 +00005682 /* Obscure case for non-leaf-data trees: If the cell at pCell was
drh85b623f2007-12-13 21:54:09 +00005683 ** previously stored on a leaf node, and its reported size was 4
danielk19774aeff622007-05-12 09:30:47 +00005684 ** bytes, then it may actually be smaller than this
5685 ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
drh85b623f2007-12-13 21:54:09 +00005686 ** any cell). But it is important to pass the correct size to
danielk19774aeff622007-05-12 09:30:47 +00005687 ** insertCell(), so reparse the cell now.
5688 **
5689 ** Note that this can never happen in an SQLite data file, as all
5690 ** cells are at least 4 bytes. It only happens in b-trees used
5691 ** to evaluate "IN (SELECT ...)" and similar clauses.
5692 */
5693 if( szCell[j]==4 ){
5694 assert(leafCorrection==4);
5695 sz = cellSizePtr(pParent, pCell);
5696 }
drh4b70f112004-05-02 21:12:19 +00005697 }
drhe5ae5732008-06-15 02:51:47 +00005698 iSpace2 += sz;
5699 assert( sz<=pBt->pageSize/4 );
5700 assert( iSpace2<=pBt->pageSize );
danielk1977a3ad5e72005-01-07 08:56:44 +00005701 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, 4);
danielk1977e80463b2004-11-03 03:01:16 +00005702 if( rc!=SQLITE_OK ) goto balance_cleanup;
drhc5053fb2008-11-27 02:22:10 +00005703 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
drh43605152004-05-29 21:46:49 +00005704 put4byte(findOverflowCell(pParent,nxDiv), pNew->pgno);
danielk197785d90ca2008-07-19 14:25:15 +00005705
danielk1977ac11ee62005-01-15 12:45:51 +00005706 /* If this is an auto-vacuum database, and not a leaf-data tree,
5707 ** then update the pointer map with an entry for the overflow page
5708 ** that the cell just inserted points to (if any).
5709 */
danielk197785d90ca2008-07-19 14:25:15 +00005710 if( ISAUTOVACUUM && !leafData ){
danielk197779a40da2005-01-16 08:00:01 +00005711 rc = ptrmapPutOvfl(pParent, nxDiv);
5712 if( rc!=SQLITE_OK ){
5713 goto balance_cleanup;
danielk1977ac11ee62005-01-15 12:45:51 +00005714 }
5715 }
drh14acc042001-06-10 19:56:58 +00005716 j++;
5717 nxDiv++;
5718 }
danielk197787c52b52008-07-19 11:49:07 +00005719
danielk197787c52b52008-07-19 11:49:07 +00005720 /* Set the pointer-map entry for the new sibling page. */
danielk197785d90ca2008-07-19 14:25:15 +00005721 if( ISAUTOVACUUM ){
danielk197787c52b52008-07-19 11:49:07 +00005722 rc = ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno);
5723 if( rc!=SQLITE_OK ){
5724 goto balance_cleanup;
5725 }
5726 }
drh14acc042001-06-10 19:56:58 +00005727 }
drh6019e162001-07-02 17:51:45 +00005728 assert( j==nCell );
drh7aa8f852006-03-28 00:24:44 +00005729 assert( nOld>0 );
5730 assert( nNew>0 );
drh4b70f112004-05-02 21:12:19 +00005731 if( (pageFlags & PTF_LEAF)==0 ){
danielk197787c52b52008-07-19 11:49:07 +00005732 u8 *zChild = &apCopy[nOld-1]->aData[8];
5733 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
danielk197785d90ca2008-07-19 14:25:15 +00005734 if( ISAUTOVACUUM ){
danielk197787c52b52008-07-19 11:49:07 +00005735 rc = ptrmapPut(pBt, get4byte(zChild), PTRMAP_BTREE, apNew[nNew-1]->pgno);
5736 if( rc!=SQLITE_OK ){
5737 goto balance_cleanup;
5738 }
5739 }
drh14acc042001-06-10 19:56:58 +00005740 }
drhc5053fb2008-11-27 02:22:10 +00005741 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
drh43605152004-05-29 21:46:49 +00005742 if( nxDiv==pParent->nCell+pParent->nOverflow ){
drh4b70f112004-05-02 21:12:19 +00005743 /* Right-most sibling is the right-most child of pParent */
drh43605152004-05-29 21:46:49 +00005744 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew[nNew-1]);
drh4b70f112004-05-02 21:12:19 +00005745 }else{
5746 /* Right-most sibling is the left child of the first entry in pParent
5747 ** past the right-most divider entry */
drh43605152004-05-29 21:46:49 +00005748 put4byte(findOverflowCell(pParent, nxDiv), pgnoNew[nNew-1]);
drh14acc042001-06-10 19:56:58 +00005749 }
5750
5751 /*
drh3a4c1412004-05-09 20:40:11 +00005752 ** Balance the parent page. Note that the current page (pPage) might
danielk1977ac11ee62005-01-15 12:45:51 +00005753 ** have been added to the freelist so it might no longer be initialized.
drh3a4c1412004-05-09 20:40:11 +00005754 ** But the parent page will always be initialized.
drh8b2f49b2001-06-08 00:21:52 +00005755 */
danielk197771d5d2c2008-09-29 11:49:47 +00005756 assert( pParent->isInit );
drhfacf0302008-06-17 15:12:00 +00005757 sqlite3ScratchFree(apCell);
drhe5ae5732008-06-15 02:51:47 +00005758 apCell = 0;
danielk1977a4124bd2008-12-23 10:37:47 +00005759 TRACE(("BALANCE: finished with %d: old=%d new=%d cells=%d\n",
5760 pPage->pgno, nOld, nNew, nCell));
5761 pPage->nOverflow = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005762 releasePage(pPage);
5763 pCur->iPage--;
5764 rc = balance(pCur, 0);
drhda200cc2004-05-09 11:51:38 +00005765
drh8b2f49b2001-06-08 00:21:52 +00005766 /*
drh14acc042001-06-10 19:56:58 +00005767 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00005768 */
drh14acc042001-06-10 19:56:58 +00005769balance_cleanup:
drhfacf0302008-06-17 15:12:00 +00005770 sqlite3PageFree(aSpace2);
5771 sqlite3ScratchFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00005772 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00005773 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00005774 }
drh14acc042001-06-10 19:56:58 +00005775 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00005776 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00005777 }
danielk1977a4124bd2008-12-23 10:37:47 +00005778 pCur->apPage[pCur->iPage]->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00005779
drh8b2f49b2001-06-08 00:21:52 +00005780 return rc;
5781}
5782
5783/*
drh43605152004-05-29 21:46:49 +00005784** This routine is called for the root page of a btree when the root
5785** page contains no cells. This is an opportunity to make the tree
5786** shallower by one level.
5787*/
danielk197771d5d2c2008-09-29 11:49:47 +00005788static int balance_shallower(BtCursor *pCur){
5789 MemPage *pPage; /* Root page of B-Tree */
drh43605152004-05-29 21:46:49 +00005790 MemPage *pChild; /* The only child page of pPage */
5791 Pgno pgnoChild; /* Page number for pChild */
drh2e38c322004-09-03 18:38:44 +00005792 int rc = SQLITE_OK; /* Return code from subprocedures */
danielk1977aef0bf62005-12-30 16:28:01 +00005793 BtShared *pBt; /* The main BTree structure */
drh2e38c322004-09-03 18:38:44 +00005794 int mxCellPerPage; /* Maximum number of cells per page */
5795 u8 **apCell; /* All cells from pages being balanced */
drha9121e42008-02-19 14:59:35 +00005796 u16 *szCell; /* Local size of all cells */
drh43605152004-05-29 21:46:49 +00005797
danielk197771d5d2c2008-09-29 11:49:47 +00005798 assert( pCur->iPage==0 );
5799 pPage = pCur->apPage[0];
5800
drh43605152004-05-29 21:46:49 +00005801 assert( pPage->nCell==0 );
drh1fee73e2007-08-29 04:00:57 +00005802 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh2e38c322004-09-03 18:38:44 +00005803 pBt = pPage->pBt;
5804 mxCellPerPage = MX_CELL(pBt);
drhe5ae5732008-06-15 02:51:47 +00005805 apCell = sqlite3Malloc( mxCellPerPage*(sizeof(u8*)+sizeof(u16)) );
drh2e38c322004-09-03 18:38:44 +00005806 if( apCell==0 ) return SQLITE_NOMEM;
drha9121e42008-02-19 14:59:35 +00005807 szCell = (u16*)&apCell[mxCellPerPage];
drh43605152004-05-29 21:46:49 +00005808 if( pPage->leaf ){
5809 /* The table is completely empty */
5810 TRACE(("BALANCE: empty table %d\n", pPage->pgno));
5811 }else{
5812 /* The root page is empty but has one child. Transfer the
5813 ** information from that one child into the root page if it
5814 ** will fit. This reduces the depth of the tree by one.
5815 **
5816 ** If the root page is page 1, it has less space available than
5817 ** its child (due to the 100 byte header that occurs at the beginning
5818 ** of the database fle), so it might not be able to hold all of the
5819 ** information currently contained in the child. If this is the
5820 ** case, then do not do the transfer. Leave page 1 empty except
5821 ** for the right-pointer to the child page. The child page becomes
5822 ** the virtual root of the tree.
5823 */
drhf94a1732008-09-30 17:18:17 +00005824 VVA_ONLY( pCur->pagesShuffled = 1 );
drh43605152004-05-29 21:46:49 +00005825 pgnoChild = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5826 assert( pgnoChild>0 );
danielk197789d40042008-11-17 14:20:56 +00005827 assert( pgnoChild<=pagerPagecount(pPage->pBt) );
drh16a9b832007-05-05 18:39:25 +00005828 rc = sqlite3BtreeGetPage(pPage->pBt, pgnoChild, &pChild, 0);
drh2e38c322004-09-03 18:38:44 +00005829 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005830 if( pPage->pgno==1 ){
danielk197771d5d2c2008-09-29 11:49:47 +00005831 rc = sqlite3BtreeInitPage(pChild);
drh2e38c322004-09-03 18:38:44 +00005832 if( rc ) goto end_shallow_balance;
drh43605152004-05-29 21:46:49 +00005833 assert( pChild->nOverflow==0 );
5834 if( pChild->nFree>=100 ){
5835 /* The child information will fit on the root page, so do the
5836 ** copy */
5837 int i;
5838 zeroPage(pPage, pChild->aData[0]);
5839 for(i=0; i<pChild->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00005840 apCell[i] = findCell(pChild,i);
drh43605152004-05-29 21:46:49 +00005841 szCell[i] = cellSizePtr(pChild, apCell[i]);
5842 }
5843 assemblePage(pPage, pChild->nCell, apCell, szCell);
danielk1977ae825582004-11-23 09:06:55 +00005844 /* Copy the right-pointer of the child to the parent. */
drhc5053fb2008-11-27 02:22:10 +00005845 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977ae825582004-11-23 09:06:55 +00005846 put4byte(&pPage->aData[pPage->hdrOffset+8],
5847 get4byte(&pChild->aData[pChild->hdrOffset+8]));
drh9bf9e9c2008-12-05 20:01:43 +00005848 rc = freePage(pChild);
drh43605152004-05-29 21:46:49 +00005849 TRACE(("BALANCE: child %d transfer to page 1\n", pChild->pgno));
5850 }else{
5851 /* The child has more information that will fit on the root.
5852 ** The tree is already balanced. Do nothing. */
5853 TRACE(("BALANCE: child %d will not fit on page 1\n", pChild->pgno));
5854 }
5855 }else{
5856 memcpy(pPage->aData, pChild->aData, pPage->pBt->usableSize);
5857 pPage->isInit = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005858 rc = sqlite3BtreeInitPage(pPage);
drh43605152004-05-29 21:46:49 +00005859 assert( rc==SQLITE_OK );
5860 freePage(pChild);
5861 TRACE(("BALANCE: transfer child %d into root %d\n",
5862 pChild->pgno, pPage->pgno));
5863 }
danielk1977ac11ee62005-01-15 12:45:51 +00005864 assert( pPage->nOverflow==0 );
shane831c3292008-11-10 17:14:58 +00005865#ifndef SQLITE_OMIT_AUTOVACUUM
drh9bf9e9c2008-12-05 20:01:43 +00005866 if( ISAUTOVACUUM && rc==SQLITE_OK ){
danielk197700a696d2008-09-29 16:41:31 +00005867 rc = setChildPtrmaps(pPage);
danielk1977ac11ee62005-01-15 12:45:51 +00005868 }
shane831c3292008-11-10 17:14:58 +00005869#endif
drh43605152004-05-29 21:46:49 +00005870 releasePage(pChild);
5871 }
drh2e38c322004-09-03 18:38:44 +00005872end_shallow_balance:
drh17435752007-08-16 04:30:38 +00005873 sqlite3_free(apCell);
drh2e38c322004-09-03 18:38:44 +00005874 return rc;
drh43605152004-05-29 21:46:49 +00005875}
5876
5877
5878/*
5879** The root page is overfull
5880**
5881** When this happens, Create a new child page and copy the
5882** contents of the root into the child. Then make the root
5883** page an empty page with rightChild pointing to the new
5884** child. Finally, call balance_internal() on the new child
5885** to cause it to split.
5886*/
danielk197771d5d2c2008-09-29 11:49:47 +00005887static int balance_deeper(BtCursor *pCur){
drh43605152004-05-29 21:46:49 +00005888 int rc; /* Return value from subprocedures */
danielk197771d5d2c2008-09-29 11:49:47 +00005889 MemPage *pPage; /* Pointer to the root page */
drh43605152004-05-29 21:46:49 +00005890 MemPage *pChild; /* Pointer to a new child page */
5891 Pgno pgnoChild; /* Page number of the new child page */
danielk1977aef0bf62005-12-30 16:28:01 +00005892 BtShared *pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00005893 int usableSize; /* Total usable size of a page */
5894 u8 *data; /* Content of the parent page */
5895 u8 *cdata; /* Content of the child page */
5896 int hdr; /* Offset to page header in parent */
drh281b21d2008-08-22 12:57:08 +00005897 int cbrk; /* Offset to content of first cell in parent */
drh43605152004-05-29 21:46:49 +00005898
danielk197771d5d2c2008-09-29 11:49:47 +00005899 assert( pCur->iPage==0 );
5900 assert( pCur->apPage[0]->nOverflow>0 );
5901
drhf94a1732008-09-30 17:18:17 +00005902 VVA_ONLY( pCur->pagesShuffled = 1 );
danielk197771d5d2c2008-09-29 11:49:47 +00005903 pPage = pCur->apPage[0];
drh43605152004-05-29 21:46:49 +00005904 pBt = pPage->pBt;
drh1fee73e2007-08-29 04:00:57 +00005905 assert( sqlite3_mutex_held(pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00005906 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh4f0c5872007-03-26 22:05:01 +00005907 rc = allocateBtreePage(pBt, &pChild, &pgnoChild, pPage->pgno, 0);
drh43605152004-05-29 21:46:49 +00005908 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00005909 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
drh43605152004-05-29 21:46:49 +00005910 usableSize = pBt->usableSize;
5911 data = pPage->aData;
5912 hdr = pPage->hdrOffset;
drh281b21d2008-08-22 12:57:08 +00005913 cbrk = get2byte(&data[hdr+5]);
drh43605152004-05-29 21:46:49 +00005914 cdata = pChild->aData;
5915 memcpy(cdata, &data[hdr], pPage->cellOffset+2*pPage->nCell-hdr);
drh281b21d2008-08-22 12:57:08 +00005916 memcpy(&cdata[cbrk], &data[cbrk], usableSize-cbrk);
danielk1977bc2ca9e2008-11-13 14:28:28 +00005917
5918 assert( pChild->isInit==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00005919 rc = sqlite3BtreeInitPage(pChild);
5920 if( rc==SQLITE_OK ){
5921 int nCopy = pPage->nOverflow*sizeof(pPage->aOvfl[0]);
5922 memcpy(pChild->aOvfl, pPage->aOvfl, nCopy);
5923 pChild->nOverflow = pPage->nOverflow;
5924 if( pChild->nOverflow ){
5925 pChild->nFree = 0;
5926 }
5927 assert( pChild->nCell==pPage->nCell );
drhc5053fb2008-11-27 02:22:10 +00005928 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00005929 zeroPage(pPage, pChild->aData[0] & ~PTF_LEAF);
5930 put4byte(&pPage->aData[pPage->hdrOffset+8], pgnoChild);
5931 TRACE(("BALANCE: copy root %d into %d\n", pPage->pgno, pChild->pgno));
5932 if( ISAUTOVACUUM ){
danielk197771d5d2c2008-09-29 11:49:47 +00005933 rc = ptrmapPut(pBt, pChild->pgno, PTRMAP_BTREE, pPage->pgno);
shane831c3292008-11-10 17:14:58 +00005934#ifndef SQLITE_OMIT_AUTOVACUUM
danielk197771d5d2c2008-09-29 11:49:47 +00005935 if( rc==SQLITE_OK ){
danielk197700a696d2008-09-29 16:41:31 +00005936 rc = setChildPtrmaps(pChild);
danielk1977ac11ee62005-01-15 12:45:51 +00005937 }
drh30df0092008-12-23 15:58:06 +00005938 if( rc ){
5939 pChild->nOverflow = 0;
5940 }
shane831c3292008-11-10 17:14:58 +00005941#endif
danielk1977ac11ee62005-01-15 12:45:51 +00005942 }
danielk197787c52b52008-07-19 11:49:07 +00005943 }
danielk19776b456a22005-03-21 04:04:02 +00005944
danielk197771d5d2c2008-09-29 11:49:47 +00005945 if( rc==SQLITE_OK ){
5946 pCur->iPage++;
5947 pCur->apPage[1] = pChild;
danielk1977bf93c562008-09-29 15:53:25 +00005948 pCur->aiIdx[0] = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00005949 rc = balance_nonroot(pCur);
5950 }else{
5951 releasePage(pChild);
5952 }
5953
drh43605152004-05-29 21:46:49 +00005954 return rc;
5955}
5956
5957/*
danielk197771d5d2c2008-09-29 11:49:47 +00005958** The page that pCur currently points to has just been modified in
5959** some way. This function figures out if this modification means the
5960** tree needs to be balanced, and if so calls the appropriate balancing
5961** routine.
5962**
5963** Parameter isInsert is true if a new cell was just inserted into the
5964** page, or false otherwise.
drh43605152004-05-29 21:46:49 +00005965*/
danielk197771d5d2c2008-09-29 11:49:47 +00005966static int balance(BtCursor *pCur, int isInsert){
drh43605152004-05-29 21:46:49 +00005967 int rc = SQLITE_OK;
danielk197771d5d2c2008-09-29 11:49:47 +00005968 MemPage *pPage = pCur->apPage[pCur->iPage];
5969
drh1fee73e2007-08-29 04:00:57 +00005970 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197771d5d2c2008-09-29 11:49:47 +00005971 if( pCur->iPage==0 ){
danielk19776e465eb2007-08-21 13:11:00 +00005972 rc = sqlite3PagerWrite(pPage->pDbPage);
5973 if( rc==SQLITE_OK && pPage->nOverflow>0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00005974 rc = balance_deeper(pCur);
danielk1977a4124bd2008-12-23 10:37:47 +00005975 assert( pCur->apPage[0]==pPage );
drh9bf9e9c2008-12-05 20:01:43 +00005976 assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
drh43605152004-05-29 21:46:49 +00005977 }
danielk1977687566d2004-11-02 12:56:41 +00005978 if( rc==SQLITE_OK && pPage->nCell==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00005979 rc = balance_shallower(pCur);
danielk1977a4124bd2008-12-23 10:37:47 +00005980 assert( pCur->apPage[0]==pPage );
drh9bf9e9c2008-12-05 20:01:43 +00005981 assert( pPage->nOverflow==0 || rc!=SQLITE_OK );
drh43605152004-05-29 21:46:49 +00005982 }
5983 }else{
danielk1977ac245ec2005-01-14 13:50:11 +00005984 if( pPage->nOverflow>0 ||
danielk197771d5d2c2008-09-29 11:49:47 +00005985 (!isInsert && pPage->nFree>pPage->pBt->usableSize*2/3) ){
5986 rc = balance_nonroot(pCur);
drh43605152004-05-29 21:46:49 +00005987 }
5988 }
5989 return rc;
5990}
5991
5992/*
drh8dcd7ca2004-08-08 19:43:29 +00005993** This routine checks all cursors that point to table pgnoRoot.
drh980b1a72006-08-16 16:42:48 +00005994** If any of those cursors were opened with wrFlag==0 in a different
5995** database connection (a database connection that shares the pager
5996** cache with the current connection) and that other connection
5997** is not in the ReadUncommmitted state, then this routine returns
5998** SQLITE_LOCKED.
danielk1977299b1872004-11-22 10:02:10 +00005999**
drh11b57d62009-02-24 19:21:41 +00006000** As well as cursors with wrFlag==0, cursors with
6001** isIncrblobHandle==1 are also considered 'read' cursors because
6002** incremental blob cursors are used for both reading and writing.
danielk19773588ceb2008-06-10 17:30:26 +00006003**
6004** When pgnoRoot is the root page of an intkey table, this function is also
6005** responsible for invalidating incremental blob cursors when the table row
6006** on which they are opened is deleted or modified. Cursors are invalidated
6007** according to the following rules:
6008**
6009** 1) When BtreeClearTable() is called to completely delete the contents
6010** of a B-Tree table, pExclude is set to zero and parameter iRow is
6011** set to non-zero. In this case all incremental blob cursors open
6012** on the table rooted at pgnoRoot are invalidated.
6013**
6014** 2) When BtreeInsert(), BtreeDelete() or BtreePutData() is called to
6015** modify a table row via an SQL statement, pExclude is set to the
6016** write cursor used to do the modification and parameter iRow is set
6017** to the integer row id of the B-Tree entry being modified. Unless
6018** pExclude is itself an incremental blob cursor, then all incremental
6019** blob cursors open on row iRow of the B-Tree are invalidated.
6020**
6021** 3) If both pExclude and iRow are set to zero, no incremental blob
6022** cursors are invalidated.
drhf74b8d92002-09-01 23:20:45 +00006023*/
drh11b57d62009-02-24 19:21:41 +00006024static int checkForReadConflicts(
6025 Btree *pBtree, /* The database file to check */
6026 Pgno pgnoRoot, /* Look for read cursors on this btree */
6027 BtCursor *pExclude, /* Ignore this cursor */
6028 i64 iRow /* The rowid that might be changing */
danielk19773588ceb2008-06-10 17:30:26 +00006029){
danielk1977299b1872004-11-22 10:02:10 +00006030 BtCursor *p;
drh980b1a72006-08-16 16:42:48 +00006031 BtShared *pBt = pBtree->pBt;
drhe5fe6902007-12-07 18:55:28 +00006032 sqlite3 *db = pBtree->db;
drh1fee73e2007-08-29 04:00:57 +00006033 assert( sqlite3BtreeHoldsMutex(pBtree) );
danielk1977299b1872004-11-22 10:02:10 +00006034 for(p=pBt->pCursor; p; p=p->pNext){
drh980b1a72006-08-16 16:42:48 +00006035 if( p==pExclude ) continue;
drh980b1a72006-08-16 16:42:48 +00006036 if( p->pgnoRoot!=pgnoRoot ) continue;
danielk19773588ceb2008-06-10 17:30:26 +00006037#ifndef SQLITE_OMIT_INCRBLOB
6038 if( p->isIncrblobHandle && (
6039 (!pExclude && iRow)
6040 || (pExclude && !pExclude->isIncrblobHandle && p->info.nKey==iRow)
6041 )){
6042 p->eState = CURSOR_INVALID;
6043 }
6044#endif
6045 if( p->eState!=CURSOR_VALID ) continue;
6046 if( p->wrFlag==0
6047#ifndef SQLITE_OMIT_INCRBLOB
6048 || p->isIncrblobHandle
6049#endif
6050 ){
drhe5fe6902007-12-07 18:55:28 +00006051 sqlite3 *dbOther = p->pBtree->db;
danielk1977404ca072009-03-16 13:19:36 +00006052 assert(dbOther);
6053 if( dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0 ){
6054 sqlite3ConnectionBlocked(db, dbOther);
6055 return SQLITE_LOCKED_SHAREDCACHE;
drh980b1a72006-08-16 16:42:48 +00006056 }
danielk1977299b1872004-11-22 10:02:10 +00006057 }
6058 }
drhf74b8d92002-09-01 23:20:45 +00006059 return SQLITE_OK;
6060}
6061
6062/*
drh3b7511c2001-05-26 13:15:44 +00006063** Insert a new record into the BTree. The key is given by (pKey,nKey)
6064** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00006065** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00006066** is left pointing at a random location.
6067**
6068** For an INTKEY table, only the nKey value of the key is used. pKey is
6069** ignored. For a ZERODATA table, the pData and nData are both ignored.
drh3b7511c2001-05-26 13:15:44 +00006070*/
drh3aac2dd2004-04-26 14:10:20 +00006071int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00006072 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00006073 const void *pKey, i64 nKey, /* The key of the new record */
drhe4d90812007-03-29 05:51:49 +00006074 const void *pData, int nData, /* The data of the new record */
drhb026e052007-05-02 01:34:31 +00006075 int nZero, /* Number of extra 0 bytes to append to data */
drhe4d90812007-03-29 05:51:49 +00006076 int appendBias /* True if this is likely an append */
drh3b7511c2001-05-26 13:15:44 +00006077){
drh3b7511c2001-05-26 13:15:44 +00006078 int rc;
6079 int loc;
drh14acc042001-06-10 19:56:58 +00006080 int szNew;
danielk197771d5d2c2008-09-29 11:49:47 +00006081 int idx;
drh3b7511c2001-05-26 13:15:44 +00006082 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00006083 Btree *p = pCur->pBtree;
6084 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00006085 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00006086 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00006087
drh1fee73e2007-08-29 04:00:57 +00006088 assert( cursorHoldsMutex(pCur) );
drh64022502009-01-09 14:11:04 +00006089 assert( pBt->inTransaction==TRANS_WRITE );
drhf74b8d92002-09-01 23:20:45 +00006090 assert( !pBt->readOnly );
drh64022502009-01-09 14:11:04 +00006091 assert( pCur->wrFlag );
danielk1977404ca072009-03-16 13:19:36 +00006092 rc = checkForReadConflicts(pCur->pBtree, pCur->pgnoRoot, pCur, nKey);
6093 if( rc ){
6094 /* The table pCur points to has a read lock */
6095 assert( rc==SQLITE_LOCKED_SHAREDCACHE );
6096 return rc;
drhf74b8d92002-09-01 23:20:45 +00006097 }
drhfb982642007-08-30 01:19:59 +00006098 if( pCur->eState==CURSOR_FAULT ){
6099 return pCur->skip;
6100 }
danielk1977da184232006-01-05 11:34:32 +00006101
6102 /* Save the positions of any other cursors open on this table */
danielk1977be51a652008-10-08 17:58:48 +00006103 sqlite3BtreeClearCursor(pCur);
danielk19772e94d4d2006-01-09 05:36:27 +00006104 if(
danielk19772e94d4d2006-01-09 05:36:27 +00006105 SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) ||
drhe63d9992008-08-13 19:11:48 +00006106 SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
danielk19772e94d4d2006-01-09 05:36:27 +00006107 ){
danielk1977da184232006-01-05 11:34:32 +00006108 return rc;
6109 }
6110
danielk197771d5d2c2008-09-29 11:49:47 +00006111 pPage = pCur->apPage[pCur->iPage];
drh4a1c3802004-05-12 15:15:47 +00006112 assert( pPage->intKey || nKey>=0 );
drh44845222008-07-17 18:39:57 +00006113 assert( pPage->leaf || !pPage->intKey );
drh3a4c1412004-05-09 20:40:11 +00006114 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
6115 pCur->pgnoRoot, nKey, nData, pPage->pgno,
6116 loc==0 ? "overwrite" : "new entry"));
danielk197771d5d2c2008-09-29 11:49:47 +00006117 assert( pPage->isInit );
danielk197752ae7242008-03-25 14:24:56 +00006118 allocateTempSpace(pBt);
6119 newCell = pBt->pTmpSpace;
drh2e38c322004-09-03 18:38:44 +00006120 if( newCell==0 ) return SQLITE_NOMEM;
drhb026e052007-05-02 01:34:31 +00006121 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
drh2e38c322004-09-03 18:38:44 +00006122 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00006123 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00006124 assert( szNew<=MX_CELL_SIZE(pBt) );
danielk197771d5d2c2008-09-29 11:49:47 +00006125 idx = pCur->aiIdx[pCur->iPage];
danielk1977da184232006-01-05 11:34:32 +00006126 if( loc==0 && CURSOR_VALID==pCur->eState ){
drha9121e42008-02-19 14:59:35 +00006127 u16 szOld;
danielk197771d5d2c2008-09-29 11:49:47 +00006128 assert( idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00006129 rc = sqlite3PagerWrite(pPage->pDbPage);
6130 if( rc ){
6131 goto end_insert;
6132 }
danielk197771d5d2c2008-09-29 11:49:47 +00006133 oldCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00006134 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006135 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00006136 }
drh43605152004-05-29 21:46:49 +00006137 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00006138 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00006139 if( rc ) goto end_insert;
shane0af3f892008-11-12 04:55:34 +00006140 rc = dropCell(pPage, idx, szOld);
6141 if( rc!=SQLITE_OK ) {
6142 goto end_insert;
6143 }
drh7c717f72001-06-24 20:39:41 +00006144 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00006145 assert( pPage->leaf );
danielk197771d5d2c2008-09-29 11:49:47 +00006146 idx = ++pCur->aiIdx[pCur->iPage];
drh271efa52004-05-30 19:19:05 +00006147 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00006148 pCur->validNKey = 0;
drh14acc042001-06-10 19:56:58 +00006149 }else{
drh4b70f112004-05-02 21:12:19 +00006150 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00006151 }
danielk197771d5d2c2008-09-29 11:49:47 +00006152 rc = insertCell(pPage, idx, newCell, szNew, 0, 0);
drh9bf9e9c2008-12-05 20:01:43 +00006153 if( rc==SQLITE_OK ){
6154 rc = balance(pCur, 1);
6155 }
6156
6157 /* Must make sure nOverflow is reset to zero even if the balance()
6158 ** fails. Internal data structure corruption will result otherwise. */
danielk1977a4124bd2008-12-23 10:37:47 +00006159 pCur->apPage[pCur->iPage]->nOverflow = 0;
drh9bf9e9c2008-12-05 20:01:43 +00006160
danielk1977299b1872004-11-22 10:02:10 +00006161 if( rc==SQLITE_OK ){
6162 moveToRoot(pCur);
6163 }
drh2e38c322004-09-03 18:38:44 +00006164end_insert:
drh5e2f8b92001-05-28 00:41:15 +00006165 return rc;
6166}
6167
6168/*
drh4b70f112004-05-02 21:12:19 +00006169** Delete the entry that the cursor is pointing to. The cursor
drhf94a1732008-09-30 17:18:17 +00006170** is left pointing at a arbitrary location.
drh3b7511c2001-05-26 13:15:44 +00006171*/
drh3aac2dd2004-04-26 14:10:20 +00006172int sqlite3BtreeDelete(BtCursor *pCur){
danielk197771d5d2c2008-09-29 11:49:47 +00006173 MemPage *pPage = pCur->apPage[pCur->iPage];
6174 int idx;
drh4b70f112004-05-02 21:12:19 +00006175 unsigned char *pCell;
drh5e2f8b92001-05-28 00:41:15 +00006176 int rc;
danielk1977cfe9a692004-06-16 12:00:29 +00006177 Pgno pgnoChild = 0;
drhd677b3d2007-08-20 22:48:41 +00006178 Btree *p = pCur->pBtree;
6179 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006180
drh1fee73e2007-08-29 04:00:57 +00006181 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00006182 assert( pPage->isInit );
drh64022502009-01-09 14:11:04 +00006183 assert( pBt->inTransaction==TRANS_WRITE );
drhf74b8d92002-09-01 23:20:45 +00006184 assert( !pBt->readOnly );
drhfb982642007-08-30 01:19:59 +00006185 if( pCur->eState==CURSOR_FAULT ){
6186 return pCur->skip;
6187 }
drh64022502009-01-09 14:11:04 +00006188 if( NEVER(pCur->aiIdx[pCur->iPage]>=pPage->nCell) ){
drhbd03cae2001-06-02 02:40:57 +00006189 return SQLITE_ERROR; /* The cursor is not pointing to anything */
6190 }
drh64022502009-01-09 14:11:04 +00006191 assert( pCur->wrFlag );
danielk1977404ca072009-03-16 13:19:36 +00006192 rc = checkForReadConflicts(p, pCur->pgnoRoot, pCur, pCur->info.nKey);
6193 if( rc!=SQLITE_OK ){
6194 /* The table pCur points to has a read lock */
6195 assert( rc==SQLITE_LOCKED_SHAREDCACHE );
6196 return rc;
drhf74b8d92002-09-01 23:20:45 +00006197 }
danielk1977da184232006-01-05 11:34:32 +00006198
6199 /* Restore the current cursor position (a no-op if the cursor is not in
6200 ** CURSOR_REQUIRESEEK state) and save the positions of any other cursors
danielk19773b8a05f2007-03-19 17:44:26 +00006201 ** open on the same table. Then call sqlite3PagerWrite() on the page
danielk1977da184232006-01-05 11:34:32 +00006202 ** that the entry will be deleted from.
6203 */
6204 if(
drha3460582008-07-11 21:02:53 +00006205 (rc = restoreCursorPosition(pCur))!=0 ||
drhd1167392006-01-23 13:00:35 +00006206 (rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))!=0 ||
danielk19773b8a05f2007-03-19 17:44:26 +00006207 (rc = sqlite3PagerWrite(pPage->pDbPage))!=0
danielk1977da184232006-01-05 11:34:32 +00006208 ){
6209 return rc;
6210 }
danielk1977e6efa742004-11-10 11:55:10 +00006211
drh85b623f2007-12-13 21:54:09 +00006212 /* Locate the cell within its page and leave pCell pointing to the
danielk1977e6efa742004-11-10 11:55:10 +00006213 ** data. The clearCell() call frees any overflow pages associated with the
6214 ** cell. The cell itself is still intact.
6215 */
danielk197771d5d2c2008-09-29 11:49:47 +00006216 idx = pCur->aiIdx[pCur->iPage];
6217 pCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00006218 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006219 pgnoChild = get4byte(pCell);
drh4b70f112004-05-02 21:12:19 +00006220 }
danielk197728129562005-01-11 10:25:06 +00006221 rc = clearCell(pPage, pCell);
drhd677b3d2007-08-20 22:48:41 +00006222 if( rc ){
drhd677b3d2007-08-20 22:48:41 +00006223 return rc;
6224 }
danielk1977e6efa742004-11-10 11:55:10 +00006225
drh4b70f112004-05-02 21:12:19 +00006226 if( !pPage->leaf ){
drh14acc042001-06-10 19:56:58 +00006227 /*
drh5e00f6c2001-09-13 13:46:56 +00006228 ** The entry we are about to delete is not a leaf so if we do not
drh9ca7d3b2001-06-28 11:50:21 +00006229 ** do something we will leave a hole on an internal page.
6230 ** We have to fill the hole by moving in a cell from a leaf. The
6231 ** next Cell after the one to be deleted is guaranteed to exist and
danielk1977299b1872004-11-22 10:02:10 +00006232 ** to be a leaf so we can use it.
drh5e2f8b92001-05-28 00:41:15 +00006233 */
drh14acc042001-06-10 19:56:58 +00006234 BtCursor leafCur;
drh1bd10f82008-12-10 21:19:56 +00006235 MemPage *pLeafPage = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00006236
drh4b70f112004-05-02 21:12:19 +00006237 unsigned char *pNext;
danielk1977299b1872004-11-22 10:02:10 +00006238 int notUsed;
danielk19776b456a22005-03-21 04:04:02 +00006239 unsigned char *tempCell = 0;
drh44845222008-07-17 18:39:57 +00006240 assert( !pPage->intKey );
drh16a9b832007-05-05 18:39:25 +00006241 sqlite3BtreeGetTempCursor(pCur, &leafCur);
danielk1977299b1872004-11-22 10:02:10 +00006242 rc = sqlite3BtreeNext(&leafCur, &notUsed);
danielk19776b456a22005-03-21 04:04:02 +00006243 if( rc==SQLITE_OK ){
danielk19772f78fc62008-09-30 09:31:45 +00006244 assert( leafCur.aiIdx[leafCur.iPage]==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00006245 pLeafPage = leafCur.apPage[leafCur.iPage];
danielk197771d5d2c2008-09-29 11:49:47 +00006246 rc = sqlite3PagerWrite(pLeafPage->pDbPage);
danielk19776b456a22005-03-21 04:04:02 +00006247 }
6248 if( rc==SQLITE_OK ){
danielk19772f78fc62008-09-30 09:31:45 +00006249 int leafCursorInvalid = 0;
drha9121e42008-02-19 14:59:35 +00006250 u16 szNext;
danielk19776b456a22005-03-21 04:04:02 +00006251 TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n",
danielk197771d5d2c2008-09-29 11:49:47 +00006252 pCur->pgnoRoot, pPage->pgno, pLeafPage->pgno));
6253 dropCell(pPage, idx, cellSizePtr(pPage, pCell));
danielk19772f78fc62008-09-30 09:31:45 +00006254 pNext = findCell(pLeafPage, 0);
danielk197771d5d2c2008-09-29 11:49:47 +00006255 szNext = cellSizePtr(pLeafPage, pNext);
danielk19776b456a22005-03-21 04:04:02 +00006256 assert( MX_CELL_SIZE(pBt)>=szNext+4 );
danielk197752ae7242008-03-25 14:24:56 +00006257 allocateTempSpace(pBt);
6258 tempCell = pBt->pTmpSpace;
danielk19776b456a22005-03-21 04:04:02 +00006259 if( tempCell==0 ){
6260 rc = SQLITE_NOMEM;
6261 }
danielk19778ea1cfa2008-01-01 06:19:02 +00006262 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00006263 rc = insertCell(pPage, idx, pNext-4, szNext+4, tempCell, 0);
danielk19778ea1cfa2008-01-01 06:19:02 +00006264 }
danielk19772f78fc62008-09-30 09:31:45 +00006265
drhf94a1732008-09-30 17:18:17 +00006266
6267 /* The "if" statement in the next code block is critical. The
6268 ** slightest error in that statement would allow SQLite to operate
6269 ** correctly most of the time but produce very rare failures. To
6270 ** guard against this, the following macros help to verify that
6271 ** the "if" statement is well tested.
6272 */
6273 testcase( pPage->nOverflow==0 && pPage->nFree<pBt->usableSize*2/3
6274 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6275 testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3
6276 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6277 testcase( pPage->nOverflow==0 && pPage->nFree==pBt->usableSize*2/3+1
6278 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6279 testcase( pPage->nOverflow>0 && pPage->nFree<=pBt->usableSize*2/3
6280 && pLeafPage->nFree+2+szNext > pBt->usableSize*2/3 );
6281 testcase( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3))
6282 && pLeafPage->nFree+2+szNext == pBt->usableSize*2/3 );
6283
6284
danielk19772f78fc62008-09-30 09:31:45 +00006285 if( (pPage->nOverflow>0 || (pPage->nFree > pBt->usableSize*2/3)) &&
6286 (pLeafPage->nFree+2+szNext > pBt->usableSize*2/3)
6287 ){
drhf94a1732008-09-30 17:18:17 +00006288 /* This branch is taken if the internal node is now either overflowing
6289 ** or underfull and the leaf node will be underfull after the just cell
danielk19772f78fc62008-09-30 09:31:45 +00006290 ** copied to the internal node is deleted from it. This is a special
6291 ** case because the call to balance() to correct the internal node
6292 ** may change the tree structure and invalidate the contents of
6293 ** the leafCur.apPage[] and leafCur.aiIdx[] arrays, which will be
6294 ** used by the balance() required to correct the underfull leaf
6295 ** node.
6296 **
6297 ** The formula used in the expression above are based on facets of
6298 ** the SQLite file-format that do not change over time.
6299 */
drhf94a1732008-09-30 17:18:17 +00006300 testcase( pPage->nFree==pBt->usableSize*2/3+1 );
6301 testcase( pLeafPage->nFree+2+szNext==pBt->usableSize*2/3+1 );
danielk19772f78fc62008-09-30 09:31:45 +00006302 leafCursorInvalid = 1;
6303 }
6304
danielk19778ea1cfa2008-01-01 06:19:02 +00006305 if( rc==SQLITE_OK ){
drhc5053fb2008-11-27 02:22:10 +00006306 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00006307 put4byte(findOverflowCell(pPage, idx), pgnoChild);
drhf94a1732008-09-30 17:18:17 +00006308 VVA_ONLY( pCur->pagesShuffled = 0 );
danielk197771d5d2c2008-09-29 11:49:47 +00006309 rc = balance(pCur, 0);
danielk19778ea1cfa2008-01-01 06:19:02 +00006310 }
danielk19772f78fc62008-09-30 09:31:45 +00006311
6312 if( rc==SQLITE_OK && leafCursorInvalid ){
6313 /* The leaf-node is now underfull and so the tree needs to be
6314 ** rebalanced. However, the balance() operation on the internal
6315 ** node above may have modified the structure of the B-Tree and
6316 ** so the current contents of leafCur.apPage[] and leafCur.aiIdx[]
6317 ** may not be trusted.
6318 **
6319 ** It is not possible to copy the ancestry from pCur, as the same
6320 ** balance() call has invalidated the pCur->apPage[] and aiIdx[]
6321 ** arrays.
drh7b682802008-09-30 14:06:28 +00006322 **
6323 ** The call to saveCursorPosition() below internally saves the
6324 ** key that leafCur is currently pointing to. Currently, there
6325 ** are two copies of that key in the tree - one here on the leaf
6326 ** page and one on some internal node in the tree. The copy on
6327 ** the leaf node is always the next key in tree-order after the
6328 ** copy on the internal node. So, the call to sqlite3BtreeNext()
6329 ** calls restoreCursorPosition() to point the cursor to the copy
6330 ** stored on the internal node, then advances to the next entry,
6331 ** which happens to be the copy of the key on the internal node.
danielk1977a69fda22008-09-30 16:48:10 +00006332 ** Net effect: leafCur is pointing back to the duplicate cell
6333 ** that needs to be removed, and the leafCur.apPage[] and
6334 ** leafCur.aiIdx[] arrays are correct.
danielk19772f78fc62008-09-30 09:31:45 +00006335 */
drhf94a1732008-09-30 17:18:17 +00006336 VVA_ONLY( Pgno leafPgno = pLeafPage->pgno );
danielk19772f78fc62008-09-30 09:31:45 +00006337 rc = saveCursorPosition(&leafCur);
6338 if( rc==SQLITE_OK ){
6339 rc = sqlite3BtreeNext(&leafCur, &notUsed);
6340 }
6341 pLeafPage = leafCur.apPage[leafCur.iPage];
danielk19775d189852009-04-07 14:38:58 +00006342 assert( rc!=SQLITE_OK || pLeafPage->pgno==leafPgno );
6343 assert( rc!=SQLITE_OK || leafCur.aiIdx[leafCur.iPage]==0 );
danielk19772f78fc62008-09-30 09:31:45 +00006344 }
6345
danielk19770cd1bbd2008-11-26 07:25:52 +00006346 if( SQLITE_OK==rc
6347 && SQLITE_OK==(rc = sqlite3PagerWrite(pLeafPage->pDbPage))
6348 ){
danielk19772f78fc62008-09-30 09:31:45 +00006349 dropCell(pLeafPage, 0, szNext);
drhf94a1732008-09-30 17:18:17 +00006350 VVA_ONLY( leafCur.pagesShuffled = 0 );
danielk197771d5d2c2008-09-29 11:49:47 +00006351 rc = balance(&leafCur, 0);
drhf94a1732008-09-30 17:18:17 +00006352 assert( leafCursorInvalid || !leafCur.pagesShuffled
6353 || !pCur->pagesShuffled );
danielk19778ea1cfa2008-01-01 06:19:02 +00006354 }
danielk19776b456a22005-03-21 04:04:02 +00006355 }
drh16a9b832007-05-05 18:39:25 +00006356 sqlite3BtreeReleaseTempCursor(&leafCur);
drh5e2f8b92001-05-28 00:41:15 +00006357 }else{
danielk1977299b1872004-11-22 10:02:10 +00006358 TRACE(("DELETE: table=%d delete from leaf %d\n",
6359 pCur->pgnoRoot, pPage->pgno));
shanedcc50b72008-11-13 18:29:50 +00006360 rc = dropCell(pPage, idx, cellSizePtr(pPage, pCell));
6361 if( rc==SQLITE_OK ){
6362 rc = balance(pCur, 0);
6363 }
drh5e2f8b92001-05-28 00:41:15 +00006364 }
danielk19776b456a22005-03-21 04:04:02 +00006365 if( rc==SQLITE_OK ){
6366 moveToRoot(pCur);
6367 }
drh5e2f8b92001-05-28 00:41:15 +00006368 return rc;
drh3b7511c2001-05-26 13:15:44 +00006369}
drh8b2f49b2001-06-08 00:21:52 +00006370
6371/*
drhc6b52df2002-01-04 03:09:29 +00006372** Create a new BTree table. Write into *piTable the page
6373** number for the root page of the new table.
6374**
drhab01f612004-05-22 02:55:23 +00006375** The type of type is determined by the flags parameter. Only the
6376** following values of flags are currently in use. Other values for
6377** flags might not work:
6378**
6379** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
6380** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00006381*/
drhd677b3d2007-08-20 22:48:41 +00006382static int btreeCreateTable(Btree *p, int *piTable, int flags){
danielk1977aef0bf62005-12-30 16:28:01 +00006383 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006384 MemPage *pRoot;
6385 Pgno pgnoRoot;
6386 int rc;
drhd677b3d2007-08-20 22:48:41 +00006387
drh1fee73e2007-08-29 04:00:57 +00006388 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00006389 assert( pBt->inTransaction==TRANS_WRITE );
danielk197728129562005-01-11 10:25:06 +00006390 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00006391
danielk1977003ba062004-11-04 02:57:33 +00006392#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00006393 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00006394 if( rc ){
6395 return rc;
6396 }
danielk1977003ba062004-11-04 02:57:33 +00006397#else
danielk1977687566d2004-11-02 12:56:41 +00006398 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00006399 Pgno pgnoMove; /* Move a page here to make room for the root-page */
6400 MemPage *pPageMove; /* The page to move to. */
6401
danielk197720713f32007-05-03 11:43:33 +00006402 /* Creating a new table may probably require moving an existing database
6403 ** to make room for the new tables root page. In case this page turns
6404 ** out to be an overflow page, delete all overflow page-map caches
6405 ** held by open cursors.
6406 */
danielk197792d4d7a2007-05-04 12:05:56 +00006407 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00006408
danielk1977003ba062004-11-04 02:57:33 +00006409 /* Read the value of meta[3] from the database to determine where the
6410 ** root page of the new table should go. meta[3] is the largest root-page
6411 ** created so far, so the new root-page is (meta[3]+1).
6412 */
danielk1977aef0bf62005-12-30 16:28:01 +00006413 rc = sqlite3BtreeGetMeta(p, 4, &pgnoRoot);
drhd677b3d2007-08-20 22:48:41 +00006414 if( rc!=SQLITE_OK ){
6415 return rc;
6416 }
danielk1977003ba062004-11-04 02:57:33 +00006417 pgnoRoot++;
6418
danielk1977599fcba2004-11-08 07:13:13 +00006419 /* The new root-page may not be allocated on a pointer-map page, or the
6420 ** PENDING_BYTE page.
6421 */
drh72190432008-01-31 14:54:43 +00006422 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00006423 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00006424 pgnoRoot++;
6425 }
6426 assert( pgnoRoot>=3 );
6427
6428 /* Allocate a page. The page that currently resides at pgnoRoot will
6429 ** be moved to the allocated page (unless the allocated page happens
6430 ** to reside at pgnoRoot).
6431 */
drh4f0c5872007-03-26 22:05:01 +00006432 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00006433 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00006434 return rc;
6435 }
danielk1977003ba062004-11-04 02:57:33 +00006436
6437 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00006438 /* pgnoRoot is the page that will be used for the root-page of
6439 ** the new table (assuming an error did not occur). But we were
6440 ** allocated pgnoMove. If required (i.e. if it was not allocated
6441 ** by extending the file), the current page at position pgnoMove
6442 ** is already journaled.
6443 */
danielk1977003ba062004-11-04 02:57:33 +00006444 u8 eType;
6445 Pgno iPtrPage;
6446
6447 releasePage(pPageMove);
danielk1977f35843b2007-04-07 15:03:17 +00006448
6449 /* Move the page currently at pgnoRoot to pgnoMove. */
drh16a9b832007-05-05 18:39:25 +00006450 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006451 if( rc!=SQLITE_OK ){
6452 return rc;
6453 }
6454 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drhccae6022005-02-26 17:31:26 +00006455 if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00006456 releasePage(pRoot);
6457 return rc;
6458 }
drhccae6022005-02-26 17:31:26 +00006459 assert( eType!=PTRMAP_ROOTPAGE );
6460 assert( eType!=PTRMAP_FREEPAGE );
danielk19774c999992008-07-16 18:17:55 +00006461 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
danielk1977003ba062004-11-04 02:57:33 +00006462 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00006463
6464 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00006465 if( rc!=SQLITE_OK ){
6466 return rc;
6467 }
drh16a9b832007-05-05 18:39:25 +00006468 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006469 if( rc!=SQLITE_OK ){
6470 return rc;
6471 }
danielk19773b8a05f2007-03-19 17:44:26 +00006472 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00006473 if( rc!=SQLITE_OK ){
6474 releasePage(pRoot);
6475 return rc;
6476 }
6477 }else{
6478 pRoot = pPageMove;
6479 }
6480
danielk197742741be2005-01-08 12:42:39 +00006481 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00006482 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
6483 if( rc ){
6484 releasePage(pRoot);
6485 return rc;
6486 }
danielk1977aef0bf62005-12-30 16:28:01 +00006487 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00006488 if( rc ){
6489 releasePage(pRoot);
6490 return rc;
6491 }
danielk197742741be2005-01-08 12:42:39 +00006492
danielk1977003ba062004-11-04 02:57:33 +00006493 }else{
drh4f0c5872007-03-26 22:05:01 +00006494 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00006495 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00006496 }
6497#endif
danielk19773b8a05f2007-03-19 17:44:26 +00006498 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhde647132004-05-07 17:57:49 +00006499 zeroPage(pRoot, flags | PTF_LEAF);
danielk19773b8a05f2007-03-19 17:44:26 +00006500 sqlite3PagerUnref(pRoot->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00006501 *piTable = (int)pgnoRoot;
6502 return SQLITE_OK;
6503}
drhd677b3d2007-08-20 22:48:41 +00006504int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
6505 int rc;
6506 sqlite3BtreeEnter(p);
6507 rc = btreeCreateTable(p, piTable, flags);
6508 sqlite3BtreeLeave(p);
6509 return rc;
6510}
drh8b2f49b2001-06-08 00:21:52 +00006511
6512/*
6513** Erase the given database page and all its children. Return
6514** the page to the freelist.
6515*/
drh4b70f112004-05-02 21:12:19 +00006516static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00006517 BtShared *pBt, /* The BTree that contains the table */
drh4b70f112004-05-02 21:12:19 +00006518 Pgno pgno, /* Page number to clear */
danielk1977c7af4842008-10-27 13:59:33 +00006519 int freePageFlag, /* Deallocate page if true */
6520 int *pnChange
drh4b70f112004-05-02 21:12:19 +00006521){
danielk19776b456a22005-03-21 04:04:02 +00006522 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00006523 int rc;
drh4b70f112004-05-02 21:12:19 +00006524 unsigned char *pCell;
6525 int i;
drh8b2f49b2001-06-08 00:21:52 +00006526
drh1fee73e2007-08-29 04:00:57 +00006527 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197789d40042008-11-17 14:20:56 +00006528 if( pgno>pagerPagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00006529 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00006530 }
6531
danielk197771d5d2c2008-09-29 11:49:47 +00006532 rc = getAndInitPage(pBt, pgno, &pPage);
danielk19776b456a22005-03-21 04:04:02 +00006533 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00006534 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00006535 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00006536 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00006537 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00006538 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006539 }
drh4b70f112004-05-02 21:12:19 +00006540 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00006541 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006542 }
drha34b6762004-05-07 13:30:42 +00006543 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00006544 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00006545 if( rc ) goto cleardatabasepage_out;
danielk1977c7af4842008-10-27 13:59:33 +00006546 }else if( pnChange ){
6547 assert( pPage->intKey );
6548 *pnChange += pPage->nCell;
drh2aa679f2001-06-25 02:11:07 +00006549 }
6550 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00006551 rc = freePage(pPage);
danielk19773b8a05f2007-03-19 17:44:26 +00006552 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
drh3a4c1412004-05-09 20:40:11 +00006553 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00006554 }
danielk19776b456a22005-03-21 04:04:02 +00006555
6556cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00006557 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00006558 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006559}
6560
6561/*
drhab01f612004-05-22 02:55:23 +00006562** Delete all information from a single table in the database. iTable is
6563** the page number of the root of the table. After this routine returns,
6564** the root page is empty, but still exists.
6565**
6566** This routine will fail with SQLITE_LOCKED if there are any open
6567** read cursors on the table. Open write cursors are moved to the
6568** root of the table.
danielk1977c7af4842008-10-27 13:59:33 +00006569**
6570** If pnChange is not NULL, then table iTable must be an intkey table. The
6571** integer value pointed to by pnChange is incremented by the number of
6572** entries in the table.
drh8b2f49b2001-06-08 00:21:52 +00006573*/
danielk1977c7af4842008-10-27 13:59:33 +00006574int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
drh8b2f49b2001-06-08 00:21:52 +00006575 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00006576 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00006577 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00006578 assert( p->inTrans==TRANS_WRITE );
drh11b57d62009-02-24 19:21:41 +00006579 if( (rc = checkForReadConflicts(p, iTable, 0, 1))!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00006580 /* nothing to do */
6581 }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){
6582 /* nothing to do */
6583 }else{
danielk197762c14b32008-11-19 09:05:26 +00006584 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
drh8b2f49b2001-06-08 00:21:52 +00006585 }
drhd677b3d2007-08-20 22:48:41 +00006586 sqlite3BtreeLeave(p);
6587 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006588}
6589
6590/*
6591** Erase all information in a table and add the root of the table to
6592** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00006593** page 1) is never added to the freelist.
6594**
6595** This routine will fail with SQLITE_LOCKED if there are any open
6596** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00006597**
6598** If AUTOVACUUM is enabled and the page at iTable is not the last
6599** root page in the database file, then the last root page
6600** in the database file is moved into the slot formerly occupied by
6601** iTable and that last slot formerly occupied by the last root page
6602** is added to the freelist instead of iTable. In this say, all
6603** root pages are kept at the beginning of the database file, which
6604** is necessary for AUTOVACUUM to work right. *piMoved is set to the
6605** page number that used to be the last root page in the file before
6606** the move. If no page gets moved, *piMoved is set to 0.
6607** The last root page is recorded in meta[3] and the value of
6608** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00006609*/
danielk197789d40042008-11-17 14:20:56 +00006610static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00006611 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00006612 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00006613 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00006614
drh1fee73e2007-08-29 04:00:57 +00006615 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00006616 assert( p->inTrans==TRANS_WRITE );
danielk1977a0bf2652004-11-04 14:30:04 +00006617
danielk1977e6efa742004-11-10 11:55:10 +00006618 /* It is illegal to drop a table if any cursors are open on the
6619 ** database. This is because in auto-vacuum mode the backend may
6620 ** need to move another root-page to fill a gap left by the deleted
6621 ** root page. If an open cursor was using this page a problem would
6622 ** occur.
6623 */
6624 if( pBt->pCursor ){
danielk1977404ca072009-03-16 13:19:36 +00006625 sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
6626 return SQLITE_LOCKED_SHAREDCACHE;
drh5df72a52002-06-06 23:16:05 +00006627 }
danielk1977a0bf2652004-11-04 14:30:04 +00006628
drh16a9b832007-05-05 18:39:25 +00006629 rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00006630 if( rc ) return rc;
danielk1977c7af4842008-10-27 13:59:33 +00006631 rc = sqlite3BtreeClearTable(p, iTable, 0);
danielk19776b456a22005-03-21 04:04:02 +00006632 if( rc ){
6633 releasePage(pPage);
6634 return rc;
6635 }
danielk1977a0bf2652004-11-04 14:30:04 +00006636
drh205f48e2004-11-05 00:43:11 +00006637 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00006638
drh4b70f112004-05-02 21:12:19 +00006639 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00006640#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00006641 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00006642 releasePage(pPage);
6643#else
6644 if( pBt->autoVacuum ){
6645 Pgno maxRootPgno;
danielk1977aef0bf62005-12-30 16:28:01 +00006646 rc = sqlite3BtreeGetMeta(p, 4, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006647 if( rc!=SQLITE_OK ){
6648 releasePage(pPage);
6649 return rc;
6650 }
6651
6652 if( iTable==maxRootPgno ){
6653 /* If the table being dropped is the table with the largest root-page
6654 ** number in the database, put the root page on the free list.
6655 */
6656 rc = freePage(pPage);
6657 releasePage(pPage);
6658 if( rc!=SQLITE_OK ){
6659 return rc;
6660 }
6661 }else{
6662 /* The table being dropped does not have the largest root-page
6663 ** number in the database. So move the page that does into the
6664 ** gap left by the deleted root-page.
6665 */
6666 MemPage *pMove;
6667 releasePage(pPage);
drh16a9b832007-05-05 18:39:25 +00006668 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006669 if( rc!=SQLITE_OK ){
6670 return rc;
6671 }
danielk19774c999992008-07-16 18:17:55 +00006672 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006673 releasePage(pMove);
6674 if( rc!=SQLITE_OK ){
6675 return rc;
6676 }
drh16a9b832007-05-05 18:39:25 +00006677 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006678 if( rc!=SQLITE_OK ){
6679 return rc;
6680 }
6681 rc = freePage(pMove);
6682 releasePage(pMove);
6683 if( rc!=SQLITE_OK ){
6684 return rc;
6685 }
6686 *piMoved = maxRootPgno;
6687 }
6688
danielk1977599fcba2004-11-08 07:13:13 +00006689 /* Set the new 'max-root-page' value in the database header. This
6690 ** is the old value less one, less one more if that happens to
6691 ** be a root-page number, less one again if that is the
6692 ** PENDING_BYTE_PAGE.
6693 */
danielk197787a6e732004-11-05 12:58:25 +00006694 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00006695 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
6696 maxRootPgno--;
6697 }
danielk1977266664d2006-02-10 08:24:21 +00006698 if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00006699 maxRootPgno--;
6700 }
danielk1977599fcba2004-11-08 07:13:13 +00006701 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
6702
danielk1977aef0bf62005-12-30 16:28:01 +00006703 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006704 }else{
6705 rc = freePage(pPage);
6706 releasePage(pPage);
6707 }
6708#endif
drh2aa679f2001-06-25 02:11:07 +00006709 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00006710 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00006711 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00006712 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00006713 }
drh8b2f49b2001-06-08 00:21:52 +00006714 return rc;
6715}
drhd677b3d2007-08-20 22:48:41 +00006716int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
6717 int rc;
6718 sqlite3BtreeEnter(p);
6719 rc = btreeDropTable(p, iTable, piMoved);
6720 sqlite3BtreeLeave(p);
6721 return rc;
6722}
drh8b2f49b2001-06-08 00:21:52 +00006723
drh001bbcb2003-03-19 03:14:00 +00006724
drh8b2f49b2001-06-08 00:21:52 +00006725/*
drh23e11ca2004-05-04 17:27:28 +00006726** Read the meta-information out of a database file. Meta[0]
6727** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00006728** through meta[15] are available for use by higher layers. Meta[0]
6729** is read-only, the others are read/write.
6730**
6731** The schema layer numbers meta values differently. At the schema
6732** layer (and the SetCookie and ReadCookie opcodes) the number of
6733** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00006734*/
danielk1977aef0bf62005-12-30 16:28:01 +00006735int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
drh1bd10f82008-12-10 21:19:56 +00006736 DbPage *pDbPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00006737 int rc;
drh4b70f112004-05-02 21:12:19 +00006738 unsigned char *pP1;
danielk1977aef0bf62005-12-30 16:28:01 +00006739 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006740
drhd677b3d2007-08-20 22:48:41 +00006741 sqlite3BtreeEnter(p);
6742
danielk1977da184232006-01-05 11:34:32 +00006743 /* Reading a meta-data value requires a read-lock on page 1 (and hence
6744 ** the sqlite_master table. We grab this lock regardless of whether or
6745 ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
drhc25eabe2009-02-24 18:57:31 +00006746 ** 1 is treated as a special case by querySharedCacheTableLock()
6747 ** and setSharedCacheTableLock()).
danielk1977da184232006-01-05 11:34:32 +00006748 */
drhc25eabe2009-02-24 18:57:31 +00006749 rc = querySharedCacheTableLock(p, 1, READ_LOCK);
danielk1977da184232006-01-05 11:34:32 +00006750 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00006751 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00006752 return rc;
6753 }
6754
drh23e11ca2004-05-04 17:27:28 +00006755 assert( idx>=0 && idx<=15 );
danielk1977d9f6c532008-09-19 16:39:38 +00006756 if( pBt->pPage1 ){
6757 /* The b-tree is already holding a reference to page 1 of the database
6758 ** file. In this case the required meta-data value can be read directly
6759 ** from the page data of this reference. This is slightly faster than
6760 ** requesting a new reference from the pager layer.
6761 */
6762 pP1 = (unsigned char *)pBt->pPage1->aData;
6763 }else{
6764 /* The b-tree does not have a reference to page 1 of the database file.
6765 ** Obtain one from the pager layer.
6766 */
danielk1977ea897302008-09-19 15:10:58 +00006767 rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
6768 if( rc ){
6769 sqlite3BtreeLeave(p);
6770 return rc;
6771 }
6772 pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
drhd677b3d2007-08-20 22:48:41 +00006773 }
drh23e11ca2004-05-04 17:27:28 +00006774 *pMeta = get4byte(&pP1[36 + idx*4]);
danielk1977ea897302008-09-19 15:10:58 +00006775
danielk1977d9f6c532008-09-19 16:39:38 +00006776 /* If the b-tree is not holding a reference to page 1, then one was
6777 ** requested from the pager layer in the above block. Release it now.
6778 */
danielk1977ea897302008-09-19 15:10:58 +00006779 if( !pBt->pPage1 ){
6780 sqlite3PagerUnref(pDbPage);
6781 }
drhae157872004-08-14 19:20:09 +00006782
danielk1977599fcba2004-11-08 07:13:13 +00006783 /* If autovacuumed is disabled in this build but we are trying to
6784 ** access an autovacuumed database, then make the database readonly.
6785 */
danielk1977003ba062004-11-04 02:57:33 +00006786#ifdef SQLITE_OMIT_AUTOVACUUM
drhae157872004-08-14 19:20:09 +00006787 if( idx==4 && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00006788#endif
drhae157872004-08-14 19:20:09 +00006789
danielk1977fa542f12009-04-02 18:28:08 +00006790 /* If there is currently an open transaction, grab a read-lock
6791 ** on page 1 of the database file. This is done to make sure that
6792 ** no other connection can modify the meta value just read from
6793 ** the database until the transaction is concluded.
6794 */
6795 if( p->inTrans>0 ){
6796 rc = setSharedCacheTableLock(p, 1, READ_LOCK);
6797 }
drhd677b3d2007-08-20 22:48:41 +00006798 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00006799 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006800}
6801
6802/*
drh23e11ca2004-05-04 17:27:28 +00006803** Write meta-information back into the database. Meta[0] is
6804** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00006805*/
danielk1977aef0bf62005-12-30 16:28:01 +00006806int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
6807 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00006808 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00006809 int rc;
drh23e11ca2004-05-04 17:27:28 +00006810 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00006811 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00006812 assert( p->inTrans==TRANS_WRITE );
6813 assert( pBt->pPage1!=0 );
6814 pP1 = pBt->pPage1->aData;
6815 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6816 if( rc==SQLITE_OK ){
6817 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +00006818#ifndef SQLITE_OMIT_AUTOVACUUM
drh64022502009-01-09 14:11:04 +00006819 if( idx==7 ){
6820 assert( pBt->autoVacuum || iMeta==0 );
6821 assert( iMeta==0 || iMeta==1 );
6822 pBt->incrVacuum = (u8)iMeta;
drhd677b3d2007-08-20 22:48:41 +00006823 }
drh64022502009-01-09 14:11:04 +00006824#endif
drh5df72a52002-06-06 23:16:05 +00006825 }
drhd677b3d2007-08-20 22:48:41 +00006826 sqlite3BtreeLeave(p);
6827 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006828}
drh8c42ca92001-06-22 19:15:00 +00006829
drhf328bc82004-05-10 23:29:49 +00006830/*
6831** Return the flag byte at the beginning of the page that the cursor
6832** is currently pointing to.
6833*/
6834int sqlite3BtreeFlags(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00006835 /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
drha3460582008-07-11 21:02:53 +00006836 ** restoreCursorPosition() here.
danielk1977da184232006-01-05 11:34:32 +00006837 */
danielk1977e448dc42008-01-02 11:50:51 +00006838 MemPage *pPage;
drha3460582008-07-11 21:02:53 +00006839 restoreCursorPosition(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00006840 pPage = pCur->apPage[pCur->iPage];
drh1fee73e2007-08-29 04:00:57 +00006841 assert( cursorHoldsMutex(pCur) );
drh64022502009-01-09 14:11:04 +00006842 assert( pPage!=0 );
drhd0679ed2007-08-28 22:24:34 +00006843 assert( pPage->pBt==pCur->pBt );
drh64022502009-01-09 14:11:04 +00006844 return pPage->aData[pPage->hdrOffset];
drhf328bc82004-05-10 23:29:49 +00006845}
6846
danielk1977a5533162009-02-24 10:01:51 +00006847#ifndef SQLITE_OMIT_BTREECOUNT
6848/*
6849** The first argument, pCur, is a cursor opened on some b-tree. Count the
6850** number of entries in the b-tree and write the result to *pnEntry.
6851**
6852** SQLITE_OK is returned if the operation is successfully executed.
6853** Otherwise, if an error is encountered (i.e. an IO error or database
6854** corruption) an SQLite error code is returned.
6855*/
6856int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
6857 i64 nEntry = 0; /* Value to return in *pnEntry */
6858 int rc; /* Return code */
6859 rc = moveToRoot(pCur);
6860
6861 /* Unless an error occurs, the following loop runs one iteration for each
6862 ** page in the B-Tree structure (not including overflow pages).
6863 */
6864 while( rc==SQLITE_OK ){
6865 int iIdx; /* Index of child node in parent */
6866 MemPage *pPage; /* Current page of the b-tree */
6867
6868 /* If this is a leaf page or the tree is not an int-key tree, then
6869 ** this page contains countable entries. Increment the entry counter
6870 ** accordingly.
6871 */
6872 pPage = pCur->apPage[pCur->iPage];
6873 if( pPage->leaf || !pPage->intKey ){
6874 nEntry += pPage->nCell;
6875 }
6876
6877 /* pPage is a leaf node. This loop navigates the cursor so that it
6878 ** points to the first interior cell that it points to the parent of
6879 ** the next page in the tree that has not yet been visited. The
6880 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
6881 ** of the page, or to the number of cells in the page if the next page
6882 ** to visit is the right-child of its parent.
6883 **
6884 ** If all pages in the tree have been visited, return SQLITE_OK to the
6885 ** caller.
6886 */
6887 if( pPage->leaf ){
6888 do {
6889 if( pCur->iPage==0 ){
6890 /* All pages of the b-tree have been visited. Return successfully. */
6891 *pnEntry = nEntry;
6892 return SQLITE_OK;
6893 }
6894 sqlite3BtreeMoveToParent(pCur);
6895 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
6896
6897 pCur->aiIdx[pCur->iPage]++;
6898 pPage = pCur->apPage[pCur->iPage];
6899 }
6900
6901 /* Descend to the child node of the cell that the cursor currently
6902 ** points at. This is the right-child if (iIdx==pPage->nCell).
6903 */
6904 iIdx = pCur->aiIdx[pCur->iPage];
6905 if( iIdx==pPage->nCell ){
6906 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
6907 }else{
6908 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
6909 }
6910 }
6911
shanebe217792009-03-05 04:20:31 +00006912 /* An error has occurred. Return an error code. */
danielk1977a5533162009-02-24 10:01:51 +00006913 return rc;
6914}
6915#endif
drhdd793422001-06-28 01:54:48 +00006916
drhdd793422001-06-28 01:54:48 +00006917/*
drh5eddca62001-06-30 21:53:53 +00006918** Return the pager associated with a BTree. This routine is used for
6919** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00006920*/
danielk1977aef0bf62005-12-30 16:28:01 +00006921Pager *sqlite3BtreePager(Btree *p){
6922 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00006923}
drh5eddca62001-06-30 21:53:53 +00006924
drhb7f91642004-10-31 02:22:47 +00006925#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006926/*
6927** Append a message to the error message string.
6928*/
drh2e38c322004-09-03 18:38:44 +00006929static void checkAppendMsg(
6930 IntegrityCk *pCheck,
6931 char *zMsg1,
6932 const char *zFormat,
6933 ...
6934){
6935 va_list ap;
drh1dcdbc02007-01-27 02:24:54 +00006936 if( !pCheck->mxErr ) return;
6937 pCheck->mxErr--;
6938 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00006939 va_start(ap, zFormat);
drhf089aa42008-07-08 19:34:06 +00006940 if( pCheck->errMsg.nChar ){
6941 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
drh5eddca62001-06-30 21:53:53 +00006942 }
drhf089aa42008-07-08 19:34:06 +00006943 if( zMsg1 ){
6944 sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
6945 }
6946 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
6947 va_end(ap);
drhc890fec2008-08-01 20:10:08 +00006948 if( pCheck->errMsg.mallocFailed ){
6949 pCheck->mallocFailed = 1;
6950 }
drh5eddca62001-06-30 21:53:53 +00006951}
drhb7f91642004-10-31 02:22:47 +00006952#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00006953
drhb7f91642004-10-31 02:22:47 +00006954#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00006955/*
6956** Add 1 to the reference count for page iPage. If this is the second
6957** reference to the page, add an error message to pCheck->zErrMsg.
6958** Return 1 if there are 2 ore more references to the page and 0 if
6959** if this is the first reference to the page.
6960**
6961** Also check that the page number is in bounds.
6962*/
danielk197789d40042008-11-17 14:20:56 +00006963static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00006964 if( iPage==0 ) return 1;
danielk197789d40042008-11-17 14:20:56 +00006965 if( iPage>pCheck->nPage ){
drh2e38c322004-09-03 18:38:44 +00006966 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006967 return 1;
6968 }
6969 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00006970 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00006971 return 1;
6972 }
6973 return (pCheck->anRef[iPage]++)>1;
6974}
6975
danielk1977afcdd022004-10-31 16:25:42 +00006976#ifndef SQLITE_OMIT_AUTOVACUUM
6977/*
6978** Check that the entry in the pointer-map for page iChild maps to
6979** page iParent, pointer type ptrType. If not, append an error message
6980** to pCheck.
6981*/
6982static void checkPtrmap(
6983 IntegrityCk *pCheck, /* Integrity check context */
6984 Pgno iChild, /* Child page number */
6985 u8 eType, /* Expected pointer map type */
6986 Pgno iParent, /* Expected pointer map parent page number */
6987 char *zContext /* Context description (used for error msg) */
6988){
6989 int rc;
6990 u8 ePtrmapType;
6991 Pgno iPtrmapParent;
6992
6993 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
6994 if( rc!=SQLITE_OK ){
drhe43ba702008-12-05 22:40:08 +00006995 if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
danielk1977afcdd022004-10-31 16:25:42 +00006996 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
6997 return;
6998 }
6999
7000 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
7001 checkAppendMsg(pCheck, zContext,
7002 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
7003 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
7004 }
7005}
7006#endif
7007
drh5eddca62001-06-30 21:53:53 +00007008/*
7009** Check the integrity of the freelist or of an overflow page list.
7010** Verify that the number of pages on the list is N.
7011*/
drh30e58752002-03-02 20:41:57 +00007012static void checkList(
7013 IntegrityCk *pCheck, /* Integrity checking context */
7014 int isFreeList, /* True for a freelist. False for overflow page list */
7015 int iPage, /* Page number for first page in the list */
7016 int N, /* Expected number of pages in the list */
7017 char *zContext /* Context for error messages */
7018){
7019 int i;
drh3a4c1412004-05-09 20:40:11 +00007020 int expected = N;
7021 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00007022 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00007023 DbPage *pOvflPage;
7024 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00007025 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00007026 checkAppendMsg(pCheck, zContext,
7027 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00007028 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00007029 break;
7030 }
7031 if( checkRef(pCheck, iPage, zContext) ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00007032 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
drh2e38c322004-09-03 18:38:44 +00007033 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00007034 break;
7035 }
danielk19773b8a05f2007-03-19 17:44:26 +00007036 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00007037 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00007038 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00007039#ifndef SQLITE_OMIT_AUTOVACUUM
7040 if( pCheck->pBt->autoVacuum ){
7041 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
7042 }
7043#endif
drh45b1fac2008-07-04 17:52:42 +00007044 if( n>pCheck->pBt->usableSize/4-2 ){
drh2e38c322004-09-03 18:38:44 +00007045 checkAppendMsg(pCheck, zContext,
7046 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00007047 N--;
7048 }else{
7049 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00007050 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00007051#ifndef SQLITE_OMIT_AUTOVACUUM
7052 if( pCheck->pBt->autoVacuum ){
7053 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
7054 }
7055#endif
7056 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00007057 }
7058 N -= n;
drh30e58752002-03-02 20:41:57 +00007059 }
drh30e58752002-03-02 20:41:57 +00007060 }
danielk1977afcdd022004-10-31 16:25:42 +00007061#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00007062 else{
7063 /* If this database supports auto-vacuum and iPage is not the last
7064 ** page in this overflow list, check that the pointer-map entry for
7065 ** the following page matches iPage.
7066 */
7067 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00007068 i = get4byte(pOvflData);
danielk1977687566d2004-11-02 12:56:41 +00007069 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
7070 }
danielk1977afcdd022004-10-31 16:25:42 +00007071 }
7072#endif
danielk19773b8a05f2007-03-19 17:44:26 +00007073 iPage = get4byte(pOvflData);
7074 sqlite3PagerUnref(pOvflPage);
drh5eddca62001-06-30 21:53:53 +00007075 }
7076}
drhb7f91642004-10-31 02:22:47 +00007077#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00007078
drhb7f91642004-10-31 02:22:47 +00007079#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007080/*
7081** Do various sanity checks on a single page of a tree. Return
7082** the tree depth. Root pages return 0. Parents of root pages
7083** return 1, and so forth.
7084**
7085** These checks are done:
7086**
7087** 1. Make sure that cells and freeblocks do not overlap
7088** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00007089** NO 2. Make sure cell keys are in order.
7090** NO 3. Make sure no key is less than or equal to zLowerBound.
7091** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00007092** 5. Check the integrity of overflow pages.
7093** 6. Recursively call checkTreePage on all children.
7094** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00007095** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00007096** the root of the tree.
7097*/
7098static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00007099 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00007100 int iPage, /* Page number of the page to check */
drh74161702006-02-24 02:53:49 +00007101 char *zParentContext /* Parent context */
drh5eddca62001-06-30 21:53:53 +00007102){
7103 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00007104 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00007105 int hdr, cellStart;
7106 int nCell;
drhda200cc2004-05-09 11:51:38 +00007107 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00007108 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00007109 int usableSize;
drh5eddca62001-06-30 21:53:53 +00007110 char zContext[100];
shane0af3f892008-11-12 04:55:34 +00007111 char *hit = 0;
drh5eddca62001-06-30 21:53:53 +00007112
drh5bb3eb92007-05-04 13:15:55 +00007113 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
danielk1977ef73ee92004-11-06 12:26:07 +00007114
drh5eddca62001-06-30 21:53:53 +00007115 /* Check that the page exists
7116 */
drhd9cb6ac2005-10-20 07:28:17 +00007117 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00007118 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00007119 if( iPage==0 ) return 0;
7120 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh16a9b832007-05-05 18:39:25 +00007121 if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drhe43ba702008-12-05 22:40:08 +00007122 if( rc==SQLITE_NOMEM ) pCheck->mallocFailed = 1;
drh2e38c322004-09-03 18:38:44 +00007123 checkAppendMsg(pCheck, zContext,
7124 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00007125 return 0;
7126 }
danielk197771d5d2c2008-09-29 11:49:47 +00007127 if( (rc = sqlite3BtreeInitPage(pPage))!=0 ){
drh64022502009-01-09 14:11:04 +00007128 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
drh16a9b832007-05-05 18:39:25 +00007129 checkAppendMsg(pCheck, zContext,
7130 "sqlite3BtreeInitPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00007131 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00007132 return 0;
7133 }
7134
7135 /* Check out all the cells.
7136 */
7137 depth = 0;
drh1dcdbc02007-01-27 02:24:54 +00007138 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
drh6f11bef2004-05-13 01:12:56 +00007139 u8 *pCell;
danielk197789d40042008-11-17 14:20:56 +00007140 u32 sz;
drh6f11bef2004-05-13 01:12:56 +00007141 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00007142
7143 /* Check payload overflow pages
7144 */
drh5bb3eb92007-05-04 13:15:55 +00007145 sqlite3_snprintf(sizeof(zContext), zContext,
7146 "On tree page %d cell %d: ", iPage, i);
danielk19771cc5ed82007-05-16 17:28:43 +00007147 pCell = findCell(pPage,i);
drh16a9b832007-05-05 18:39:25 +00007148 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00007149 sz = info.nData;
drhf49661a2008-12-10 16:45:50 +00007150 if( !pPage->intKey ) sz += (int)info.nKey;
drh72365832007-03-06 15:53:44 +00007151 assert( sz==info.nPayload );
danielk19775be31f52009-03-30 13:53:43 +00007152 if( (sz>info.nLocal)
7153 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
7154 ){
drhb6f41482004-05-14 01:58:11 +00007155 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00007156 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
7157#ifndef SQLITE_OMIT_AUTOVACUUM
7158 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00007159 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00007160 }
7161#endif
7162 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00007163 }
7164
7165 /* Check sanity of left child page.
7166 */
drhda200cc2004-05-09 11:51:38 +00007167 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00007168 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00007169#ifndef SQLITE_OMIT_AUTOVACUUM
7170 if( pBt->autoVacuum ){
7171 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
7172 }
7173#endif
danielk197762c14b32008-11-19 09:05:26 +00007174 d2 = checkTreePage(pCheck, pgno, zContext);
drhda200cc2004-05-09 11:51:38 +00007175 if( i>0 && d2!=depth ){
7176 checkAppendMsg(pCheck, zContext, "Child page depth differs");
7177 }
7178 depth = d2;
drh5eddca62001-06-30 21:53:53 +00007179 }
drh5eddca62001-06-30 21:53:53 +00007180 }
drhda200cc2004-05-09 11:51:38 +00007181 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00007182 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh5bb3eb92007-05-04 13:15:55 +00007183 sqlite3_snprintf(sizeof(zContext), zContext,
7184 "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00007185#ifndef SQLITE_OMIT_AUTOVACUUM
7186 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00007187 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00007188 }
7189#endif
danielk197762c14b32008-11-19 09:05:26 +00007190 checkTreePage(pCheck, pgno, zContext);
drhda200cc2004-05-09 11:51:38 +00007191 }
drh5eddca62001-06-30 21:53:53 +00007192
7193 /* Check for complete coverage of the page
7194 */
drhda200cc2004-05-09 11:51:38 +00007195 data = pPage->aData;
7196 hdr = pPage->hdrOffset;
drhf7141992008-06-19 00:16:08 +00007197 hit = sqlite3PageMalloc( pBt->pageSize );
drhc890fec2008-08-01 20:10:08 +00007198 if( hit==0 ){
7199 pCheck->mallocFailed = 1;
7200 }else{
shane5780ebd2008-11-11 17:36:30 +00007201 u16 contentOffset = get2byte(&data[hdr+5]);
7202 if (contentOffset > usableSize) {
7203 checkAppendMsg(pCheck, 0,
7204 "Corruption detected in header on page %d",iPage,0);
shane0af3f892008-11-12 04:55:34 +00007205 goto check_page_abort;
shane5780ebd2008-11-11 17:36:30 +00007206 }
7207 memset(hit+contentOffset, 0, usableSize-contentOffset);
7208 memset(hit, 1, contentOffset);
drh2e38c322004-09-03 18:38:44 +00007209 nCell = get2byte(&data[hdr+3]);
7210 cellStart = hdr + 12 - 4*pPage->leaf;
7211 for(i=0; i<nCell; i++){
7212 int pc = get2byte(&data[cellStart+i*2]);
danielk1977daca5432008-08-25 11:57:16 +00007213 u16 size = 1024;
drh2e38c322004-09-03 18:38:44 +00007214 int j;
danielk1977daca5432008-08-25 11:57:16 +00007215 if( pc<=usableSize ){
7216 size = cellSizePtr(pPage, &data[pc]);
7217 }
danielk19777701e812005-01-10 12:59:51 +00007218 if( (pc+size-1)>=usableSize || pc<0 ){
7219 checkAppendMsg(pCheck, 0,
7220 "Corruption detected in cell %d on page %d",i,iPage,0);
7221 }else{
7222 for(j=pc+size-1; j>=pc; j--) hit[j]++;
7223 }
drh2e38c322004-09-03 18:38:44 +00007224 }
7225 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
7226 cnt++){
7227 int size = get2byte(&data[i+2]);
7228 int j;
danielk19777701e812005-01-10 12:59:51 +00007229 if( (i+size-1)>=usableSize || i<0 ){
7230 checkAppendMsg(pCheck, 0,
7231 "Corruption detected in cell %d on page %d",i,iPage,0);
7232 }else{
7233 for(j=i+size-1; j>=i; j--) hit[j]++;
7234 }
drh2e38c322004-09-03 18:38:44 +00007235 i = get2byte(&data[i]);
7236 }
7237 for(i=cnt=0; i<usableSize; i++){
7238 if( hit[i]==0 ){
7239 cnt++;
7240 }else if( hit[i]>1 ){
7241 checkAppendMsg(pCheck, 0,
7242 "Multiple uses for byte %d of page %d", i, iPage);
7243 break;
7244 }
7245 }
7246 if( cnt!=data[hdr+7] ){
7247 checkAppendMsg(pCheck, 0,
7248 "Fragmented space is %d byte reported as %d on page %d",
7249 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00007250 }
7251 }
shane0af3f892008-11-12 04:55:34 +00007252check_page_abort:
7253 if (hit) sqlite3PageFree(hit);
drh6019e162001-07-02 17:51:45 +00007254
drh4b70f112004-05-02 21:12:19 +00007255 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00007256 return depth+1;
drh5eddca62001-06-30 21:53:53 +00007257}
drhb7f91642004-10-31 02:22:47 +00007258#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00007259
drhb7f91642004-10-31 02:22:47 +00007260#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007261/*
7262** This routine does a complete check of the given BTree file. aRoot[] is
7263** an array of pages numbers were each page number is the root page of
7264** a table. nRoot is the number of entries in aRoot.
7265**
drhc890fec2008-08-01 20:10:08 +00007266** Write the number of error seen in *pnErr. Except for some memory
drhe43ba702008-12-05 22:40:08 +00007267** allocation errors, an error message held in memory obtained from
drhc890fec2008-08-01 20:10:08 +00007268** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
drhe43ba702008-12-05 22:40:08 +00007269** returned. If a memory allocation error occurs, NULL is returned.
drh5eddca62001-06-30 21:53:53 +00007270*/
drh1dcdbc02007-01-27 02:24:54 +00007271char *sqlite3BtreeIntegrityCheck(
7272 Btree *p, /* The btree to be checked */
7273 int *aRoot, /* An array of root pages numbers for individual trees */
7274 int nRoot, /* Number of entries in aRoot[] */
7275 int mxErr, /* Stop reporting errors after this many */
7276 int *pnErr /* Write number of errors seen to this variable */
7277){
danielk197789d40042008-11-17 14:20:56 +00007278 Pgno i;
drh5eddca62001-06-30 21:53:53 +00007279 int nRef;
drhaaab5722002-02-19 13:39:21 +00007280 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00007281 BtShared *pBt = p->pBt;
drhf089aa42008-07-08 19:34:06 +00007282 char zErr[100];
drh5eddca62001-06-30 21:53:53 +00007283
drhd677b3d2007-08-20 22:48:41 +00007284 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00007285 nRef = sqlite3PagerRefcount(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00007286 if( lockBtreeWithRetry(p)!=SQLITE_OK ){
drhc890fec2008-08-01 20:10:08 +00007287 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00007288 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00007289 return sqlite3DbStrDup(0, "cannot acquire a read lock on the database");
drhefc251d2001-07-01 22:12:01 +00007290 }
drh5eddca62001-06-30 21:53:53 +00007291 sCheck.pBt = pBt;
7292 sCheck.pPager = pBt->pPager;
danielk197789d40042008-11-17 14:20:56 +00007293 sCheck.nPage = pagerPagecount(sCheck.pBt);
drh1dcdbc02007-01-27 02:24:54 +00007294 sCheck.mxErr = mxErr;
7295 sCheck.nErr = 0;
drhc890fec2008-08-01 20:10:08 +00007296 sCheck.mallocFailed = 0;
drh1dcdbc02007-01-27 02:24:54 +00007297 *pnErr = 0;
drh0de8c112002-07-06 16:32:14 +00007298 if( sCheck.nPage==0 ){
7299 unlockBtreeIfUnused(pBt);
drhd677b3d2007-08-20 22:48:41 +00007300 sqlite3BtreeLeave(p);
drh0de8c112002-07-06 16:32:14 +00007301 return 0;
7302 }
drhe5ae5732008-06-15 02:51:47 +00007303 sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00007304 if( !sCheck.anRef ){
7305 unlockBtreeIfUnused(pBt);
drh1dcdbc02007-01-27 02:24:54 +00007306 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00007307 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00007308 return 0;
danielk1977ac245ec2005-01-14 13:50:11 +00007309 }
drhda200cc2004-05-09 11:51:38 +00007310 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00007311 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00007312 if( i<=sCheck.nPage ){
7313 sCheck.anRef[i] = 1;
7314 }
drhf089aa42008-07-08 19:34:06 +00007315 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
drh5eddca62001-06-30 21:53:53 +00007316
7317 /* Check the integrity of the freelist
7318 */
drha34b6762004-05-07 13:30:42 +00007319 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
7320 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00007321
7322 /* Check all the tables.
7323 */
danielk197789d40042008-11-17 14:20:56 +00007324 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
drh4ff6dfa2002-03-03 23:06:00 +00007325 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00007326#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00007327 if( pBt->autoVacuum && aRoot[i]>1 ){
7328 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
7329 }
7330#endif
danielk197762c14b32008-11-19 09:05:26 +00007331 checkTreePage(&sCheck, aRoot[i], "List of tree roots: ");
drh5eddca62001-06-30 21:53:53 +00007332 }
7333
7334 /* Make sure every page in the file is referenced
7335 */
drh1dcdbc02007-01-27 02:24:54 +00007336 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00007337#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00007338 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00007339 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00007340 }
danielk1977afcdd022004-10-31 16:25:42 +00007341#else
7342 /* If the database supports auto-vacuum, make sure no tables contain
7343 ** references to pointer-map pages.
7344 */
7345 if( sCheck.anRef[i]==0 &&
danielk1977266664d2006-02-10 08:24:21 +00007346 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00007347 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
7348 }
7349 if( sCheck.anRef[i]!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00007350 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00007351 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
7352 }
7353#endif
drh5eddca62001-06-30 21:53:53 +00007354 }
7355
drh64022502009-01-09 14:11:04 +00007356 /* Make sure this analysis did not leave any unref() pages.
7357 ** This is an internal consistency check; an integrity check
7358 ** of the integrity check.
drh5eddca62001-06-30 21:53:53 +00007359 */
drh5e00f6c2001-09-13 13:46:56 +00007360 unlockBtreeIfUnused(pBt);
drh64022502009-01-09 14:11:04 +00007361 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
drh2e38c322004-09-03 18:38:44 +00007362 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00007363 "Outstanding page count goes from %d to %d during this analysis",
danielk19773b8a05f2007-03-19 17:44:26 +00007364 nRef, sqlite3PagerRefcount(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00007365 );
drh5eddca62001-06-30 21:53:53 +00007366 }
7367
7368 /* Clean up and report errors.
7369 */
drhd677b3d2007-08-20 22:48:41 +00007370 sqlite3BtreeLeave(p);
drh17435752007-08-16 04:30:38 +00007371 sqlite3_free(sCheck.anRef);
drhc890fec2008-08-01 20:10:08 +00007372 if( sCheck.mallocFailed ){
7373 sqlite3StrAccumReset(&sCheck.errMsg);
7374 *pnErr = sCheck.nErr+1;
7375 return 0;
7376 }
drh1dcdbc02007-01-27 02:24:54 +00007377 *pnErr = sCheck.nErr;
drhf089aa42008-07-08 19:34:06 +00007378 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
7379 return sqlite3StrAccumFinish(&sCheck.errMsg);
drh5eddca62001-06-30 21:53:53 +00007380}
drhb7f91642004-10-31 02:22:47 +00007381#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00007382
drh73509ee2003-04-06 20:44:45 +00007383/*
7384** Return the full pathname of the underlying database file.
drhd0679ed2007-08-28 22:24:34 +00007385**
7386** The pager filename is invariant as long as the pager is
7387** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +00007388*/
danielk1977aef0bf62005-12-30 16:28:01 +00007389const char *sqlite3BtreeGetFilename(Btree *p){
7390 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007391 return sqlite3PagerFilename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00007392}
7393
7394/*
danielk19775865e3d2004-06-14 06:03:57 +00007395** Return the pathname of the journal file for this database. The return
7396** value of this routine is the same regardless of whether the journal file
7397** has been created or not.
drhd0679ed2007-08-28 22:24:34 +00007398**
7399** The pager journal filename is invariant as long as the pager is
7400** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00007401*/
danielk1977aef0bf62005-12-30 16:28:01 +00007402const char *sqlite3BtreeGetJournalname(Btree *p){
7403 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007404 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00007405}
7406
danielk19771d850a72004-05-31 08:26:49 +00007407/*
7408** Return non-zero if a transaction is active.
7409*/
danielk1977aef0bf62005-12-30 16:28:01 +00007410int sqlite3BtreeIsInTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00007411 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00007412 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00007413}
7414
7415/*
danielk19772372c2b2006-06-27 16:34:56 +00007416** Return non-zero if a read (or write) transaction is active.
7417*/
7418int sqlite3BtreeIsInReadTrans(Btree *p){
drh64022502009-01-09 14:11:04 +00007419 assert( p );
drhe5fe6902007-12-07 18:55:28 +00007420 assert( sqlite3_mutex_held(p->db->mutex) );
drh64022502009-01-09 14:11:04 +00007421 return p->inTrans!=TRANS_NONE;
danielk19772372c2b2006-06-27 16:34:56 +00007422}
7423
danielk197704103022009-02-03 16:51:24 +00007424int sqlite3BtreeIsInBackup(Btree *p){
7425 assert( p );
7426 assert( sqlite3_mutex_held(p->db->mutex) );
7427 return p->nBackup!=0;
7428}
7429
danielk19772372c2b2006-06-27 16:34:56 +00007430/*
danielk1977da184232006-01-05 11:34:32 +00007431** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +00007432** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +00007433** purposes (for example, to store a high-level schema associated with
7434** the shared-btree). The btree layer manages reference counting issues.
7435**
7436** The first time this is called on a shared-btree, nBytes bytes of memory
7437** are allocated, zeroed, and returned to the caller. For each subsequent
7438** call the nBytes parameter is ignored and a pointer to the same blob
7439** of memory returned.
7440**
danielk1977171bfed2008-06-23 09:50:50 +00007441** If the nBytes parameter is 0 and the blob of memory has not yet been
7442** allocated, a null pointer is returned. If the blob has already been
7443** allocated, it is returned as normal.
7444**
danielk1977da184232006-01-05 11:34:32 +00007445** Just before the shared-btree is closed, the function passed as the
7446** xFree argument when the memory allocation was made is invoked on the
drh17435752007-08-16 04:30:38 +00007447** blob of allocated memory. This function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +00007448** on the memory, the btree layer does that.
7449*/
7450void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
7451 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +00007452 sqlite3BtreeEnter(p);
danielk1977171bfed2008-06-23 09:50:50 +00007453 if( !pBt->pSchema && nBytes ){
drh17435752007-08-16 04:30:38 +00007454 pBt->pSchema = sqlite3MallocZero(nBytes);
danielk1977da184232006-01-05 11:34:32 +00007455 pBt->xFreeSchema = xFree;
7456 }
drh27641702007-08-22 02:56:42 +00007457 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00007458 return pBt->pSchema;
7459}
7460
danielk1977c87d34d2006-01-06 13:00:28 +00007461/*
danielk1977404ca072009-03-16 13:19:36 +00007462** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
7463** btree as the argument handle holds an exclusive lock on the
7464** sqlite_master table. Otherwise SQLITE_OK.
danielk1977c87d34d2006-01-06 13:00:28 +00007465*/
7466int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +00007467 int rc;
drhe5fe6902007-12-07 18:55:28 +00007468 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +00007469 sqlite3BtreeEnter(p);
danielk1977404ca072009-03-16 13:19:36 +00007470 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
7471 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
drh27641702007-08-22 02:56:42 +00007472 sqlite3BtreeLeave(p);
7473 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +00007474}
7475
drha154dcd2006-03-22 22:10:07 +00007476
7477#ifndef SQLITE_OMIT_SHARED_CACHE
7478/*
7479** Obtain a lock on the table whose root page is iTab. The
7480** lock is a write lock if isWritelock is true or a read lock
7481** if it is false.
7482*/
danielk1977c00da102006-01-07 13:21:04 +00007483int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00007484 int rc = SQLITE_OK;
drh6a9ad3d2008-04-02 16:29:30 +00007485 if( p->sharable ){
7486 u8 lockType = READ_LOCK + isWriteLock;
7487 assert( READ_LOCK+1==WRITE_LOCK );
7488 assert( isWriteLock==0 || isWriteLock==1 );
7489 sqlite3BtreeEnter(p);
drhc25eabe2009-02-24 18:57:31 +00007490 rc = querySharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00007491 if( rc==SQLITE_OK ){
drhc25eabe2009-02-24 18:57:31 +00007492 rc = setSharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00007493 }
7494 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +00007495 }
7496 return rc;
7497}
drha154dcd2006-03-22 22:10:07 +00007498#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00007499
danielk1977b4e9af92007-05-01 17:49:49 +00007500#ifndef SQLITE_OMIT_INCRBLOB
7501/*
7502** Argument pCsr must be a cursor opened for writing on an
7503** INTKEY table currently pointing at a valid table entry.
7504** This function modifies the data stored as part of that entry.
7505** Only the data content may only be modified, it is not possible
7506** to change the length of the data stored.
7507*/
danielk1977dcbb5d32007-05-04 18:36:44 +00007508int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
danielk1977404ca072009-03-16 13:19:36 +00007509 int rc;
7510
drh1fee73e2007-08-29 04:00:57 +00007511 assert( cursorHoldsMutex(pCsr) );
drhe5fe6902007-12-07 18:55:28 +00007512 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00007513 assert(pCsr->isIncrblobHandle);
danielk19773588ceb2008-06-10 17:30:26 +00007514
drha3460582008-07-11 21:02:53 +00007515 restoreCursorPosition(pCsr);
danielk19773588ceb2008-06-10 17:30:26 +00007516 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
7517 if( pCsr->eState!=CURSOR_VALID ){
7518 return SQLITE_ABORT;
danielk1977dcbb5d32007-05-04 18:36:44 +00007519 }
7520
danielk1977d04417962007-05-02 13:16:30 +00007521 /* Check some preconditions:
danielk1977dcbb5d32007-05-04 18:36:44 +00007522 ** (a) the cursor is open for writing,
7523 ** (b) there is no read-lock on the table being modified and
7524 ** (c) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00007525 */
danielk1977d04417962007-05-02 13:16:30 +00007526 if( !pCsr->wrFlag ){
danielk1977dcbb5d32007-05-04 18:36:44 +00007527 return SQLITE_READONLY;
danielk1977d04417962007-05-02 13:16:30 +00007528 }
drhd0679ed2007-08-28 22:24:34 +00007529 assert( !pCsr->pBt->readOnly
7530 && pCsr->pBt->inTransaction==TRANS_WRITE );
danielk1977404ca072009-03-16 13:19:36 +00007531 rc = checkForReadConflicts(pCsr->pBtree, pCsr->pgnoRoot, pCsr, 0);
7532 if( rc!=SQLITE_OK ){
7533 /* The table pCur points to has a read lock */
7534 assert( rc==SQLITE_LOCKED_SHAREDCACHE );
7535 return rc;
danielk1977d04417962007-05-02 13:16:30 +00007536 }
danielk197771d5d2c2008-09-29 11:49:47 +00007537 if( pCsr->eState==CURSOR_INVALID || !pCsr->apPage[pCsr->iPage]->intKey ){
danielk1977d04417962007-05-02 13:16:30 +00007538 return SQLITE_ERROR;
danielk1977b4e9af92007-05-01 17:49:49 +00007539 }
7540
danielk19779f8d6402007-05-02 17:48:45 +00007541 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00007542}
danielk19772dec9702007-05-02 16:48:37 +00007543
7544/*
7545** Set a flag on this cursor to cache the locations of pages from the
danielk1977da107192007-05-04 08:32:13 +00007546** overflow list for the current row. This is used by cursors opened
7547** for incremental blob IO only.
7548**
7549** This function sets a flag only. The actual page location cache
7550** (stored in BtCursor.aOverflow[]) is allocated and used by function
7551** accessPayload() (the worker function for sqlite3BtreeData() and
7552** sqlite3BtreePutData()).
danielk19772dec9702007-05-02 16:48:37 +00007553*/
7554void sqlite3BtreeCacheOverflow(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00007555 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00007556 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00007557 assert(!pCur->isIncrblobHandle);
danielk19772dec9702007-05-02 16:48:37 +00007558 assert(!pCur->aOverflow);
danielk1977dcbb5d32007-05-04 18:36:44 +00007559 pCur->isIncrblobHandle = 1;
danielk19772dec9702007-05-02 16:48:37 +00007560}
danielk1977b4e9af92007-05-01 17:49:49 +00007561#endif