blob: e371f6184a964d75a14dfa8cd6b840be5e2764e1 [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*************************************************************************
danielk1977325ccfa2009-07-02 05:23:25 +000012** $Id: btree.c,v 1.647 2009/07/02 05:23:26 danielk1977 Exp $
drh8b2f49b2001-06-08 00:21:52 +000013**
14** This file implements a external (disk-based) database using BTrees.
drha3152892007-05-05 11:48:52 +000015** See the header comment on "btreeInt.h" for additional information.
16** Including a description of file format and an overview of operation.
drha059ad02001-04-17 20:09:11 +000017*/
drha3152892007-05-05 11:48:52 +000018#include "btreeInt.h"
paulb95a8862003-04-01 21:16:41 +000019
drh8c42ca92001-06-22 19:15:00 +000020/*
drha3152892007-05-05 11:48:52 +000021** The header string that appears at the beginning of every
22** SQLite database.
drh556b2a22005-06-14 16:04:05 +000023*/
drh556b2a22005-06-14 16:04:05 +000024static const char zMagicHeader[] = SQLITE_FILE_HEADER;
drh08ed44e2001-04-29 23:32:55 +000025
drh8c42ca92001-06-22 19:15:00 +000026/*
drha3152892007-05-05 11:48:52 +000027** Set this global variable to 1 to enable tracing using the TRACE
28** macro.
drh615ae552005-01-16 23:21:00 +000029*/
drhe8f52c52008-07-12 14:52:20 +000030#if 0
danielk1977a50d9aa2009-06-08 14:49:45 +000031int sqlite3BtreeTrace=1; /* 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
danielk1977aef0bf62005-12-30 16:28:01 +000070
71#ifdef SQLITE_OMIT_SHARED_CACHE
72 /*
drhc25eabe2009-02-24 18:57:31 +000073 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
74 ** and clearAllSharedCacheTableLocks()
danielk1977aef0bf62005-12-30 16:28:01 +000075 ** manipulate entries in the BtShared.pLock linked list used to store
76 ** shared-cache table level locks. If the library is compiled with the
77 ** shared-cache feature disabled, then there is only ever one user
danielk1977da184232006-01-05 11:34:32 +000078 ** of each BtShared structure and so this locking is not necessary.
79 ** So define the lock related functions as no-ops.
danielk1977aef0bf62005-12-30 16:28:01 +000080 */
drhc25eabe2009-02-24 18:57:31 +000081 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
82 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
83 #define clearAllSharedCacheTableLocks(a)
danielk197796d48e92009-06-29 06:00:37 +000084 #define hasSharedCacheTableLock(a,b,c,d) 1
85 #define hasReadConflicts(a, b) 0
drhe53831d2007-08-17 01:14:38 +000086#endif
danielk1977aef0bf62005-12-30 16:28:01 +000087
drhe53831d2007-08-17 01:14:38 +000088#ifndef SQLITE_OMIT_SHARED_CACHE
danielk197796d48e92009-06-29 06:00:37 +000089
90#ifdef SQLITE_DEBUG
91/*
92** This function is only used as part of an assert() statement. It checks
93** that connection p holds the required locks to read or write to the
94** b-tree with root page iRoot. If so, true is returned. Otherwise, false.
95** For example, when writing to a table b-tree with root-page iRoot via
96** Btree connection pBtree:
97**
98** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
99**
100** When writing to an index b-tree that resides in a sharable database, the
101** caller should have first obtained a lock specifying the root page of
102** the corresponding table b-tree. This makes things a bit more complicated,
103** as this module treats each b-tree as a separate structure. To determine
104** the table b-tree corresponding to the index b-tree being written, this
105** function has to search through the database schema.
106**
107** Instead of a lock on the b-tree rooted at page iRoot, the caller may
108** hold a write-lock on the schema table (root page 1). This is also
109** acceptable.
110*/
111static int hasSharedCacheTableLock(
112 Btree *pBtree, /* Handle that must hold lock */
113 Pgno iRoot, /* Root page of b-tree */
114 int isIndex, /* True if iRoot is the root of an index b-tree */
115 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
116){
117 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
118 Pgno iTab = 0;
119 BtLock *pLock;
120
121 /* If this b-tree database is not shareable, or if the client is reading
122 ** and has the read-uncommitted flag set, then no lock is required.
123 ** In these cases return true immediately. If the client is reading
124 ** or writing an index b-tree, but the schema is not loaded, then return
125 ** true also. In this case the lock is required, but it is too difficult
126 ** to check if the client actually holds it. This doesn't happen very
127 ** often. */
128 if( (pBtree->sharable==0)
129 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
130 || (isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0 ))
131 ){
132 return 1;
133 }
134
135 /* Figure out the root-page that the lock should be held on. For table
136 ** b-trees, this is just the root page of the b-tree being read or
137 ** written. For index b-trees, it is the root page of the associated
138 ** table. */
139 if( isIndex ){
140 HashElem *p;
141 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
142 Index *pIdx = (Index *)sqliteHashData(p);
143 if( pIdx->tnum==iRoot ){
144 iTab = pIdx->pTable->tnum;
145 }
146 }
147 }else{
148 iTab = iRoot;
149 }
150
151 /* Search for the required lock. Either a write-lock on root-page iTab, a
152 ** write-lock on the schema table, or (if the client is reading) a
153 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
154 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
155 if( pLock->pBtree==pBtree
156 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
157 && pLock->eLock>=eLockType
158 ){
159 return 1;
160 }
161 }
162
163 /* Failed to find the required lock. */
164 return 0;
165}
166
167/*
168** This function is also used as part of assert() statements only. It
169** returns true if there exist one or more cursors open on the table
170** with root page iRoot that do not belong to either connection pBtree
171** or some other connection that has the read-uncommitted flag set.
172**
173** For example, before writing to page iRoot:
174**
175** assert( !hasReadConflicts(pBtree, iRoot) );
176*/
177static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
178 BtCursor *p;
179 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
180 if( p->pgnoRoot==iRoot
181 && p->pBtree!=pBtree
182 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
183 ){
184 return 1;
185 }
186 }
187 return 0;
188}
189#endif /* #ifdef SQLITE_DEBUG */
190
danielk1977da184232006-01-05 11:34:32 +0000191/*
danielk1977aef0bf62005-12-30 16:28:01 +0000192** Query to see if btree handle p may obtain a lock of type eLock
193** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
drhc25eabe2009-02-24 18:57:31 +0000194** SQLITE_OK if the lock may be obtained (by calling
195** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
danielk1977aef0bf62005-12-30 16:28:01 +0000196*/
drhc25eabe2009-02-24 18:57:31 +0000197static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
danielk1977aef0bf62005-12-30 16:28:01 +0000198 BtShared *pBt = p->pBt;
199 BtLock *pIter;
200
drh1fee73e2007-08-29 04:00:57 +0000201 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000202 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
203 assert( p->db!=0 );
drhd677b3d2007-08-20 22:48:41 +0000204
danielk19775b413d72009-04-01 09:41:54 +0000205 /* If requesting a write-lock, then the Btree must have an open write
206 ** transaction on this file. And, obviously, for this to be so there
207 ** must be an open write transaction on the file itself.
208 */
209 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
210 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
211
danielk1977da184232006-01-05 11:34:32 +0000212 /* This is a no-op if the shared-cache is not enabled */
drhe53831d2007-08-17 01:14:38 +0000213 if( !p->sharable ){
danielk1977da184232006-01-05 11:34:32 +0000214 return SQLITE_OK;
215 }
216
danielk1977641b0f42007-12-21 04:47:25 +0000217 /* If some other connection is holding an exclusive lock, the
218 ** requested lock may not be obtained.
219 */
danielk1977404ca072009-03-16 13:19:36 +0000220 if( pBt->pWriter!=p && pBt->isExclusive ){
221 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
222 return SQLITE_LOCKED_SHAREDCACHE;
danielk1977641b0f42007-12-21 04:47:25 +0000223 }
224
drhc25eabe2009-02-24 18:57:31 +0000225 /* This (along with setSharedCacheTableLock()) is where
226 ** the ReadUncommitted flag is dealt with.
227 ** If the caller is querying for a read-lock on any table
drhc74d0b1d2009-02-24 16:18:05 +0000228 ** other than the sqlite_master table (table 1) and if the ReadUncommitted
229 ** flag is set, then the lock granted even if there are write-locks
danielk1977da184232006-01-05 11:34:32 +0000230 ** on the table. If a write-lock is requested, the ReadUncommitted flag
231 ** is not considered.
232 **
drhc25eabe2009-02-24 18:57:31 +0000233 ** In function setSharedCacheTableLock(), if a read-lock is demanded and the
danielk1977da184232006-01-05 11:34:32 +0000234 ** ReadUncommitted flag is set, no entry is added to the locks list
235 ** (BtShared.pLock).
236 **
drhc74d0b1d2009-02-24 16:18:05 +0000237 ** To summarize: If the ReadUncommitted flag is set, then read cursors
238 ** on non-schema tables do not create or respect table locks. The locking
239 ** procedure for a write-cursor does not change.
danielk1977da184232006-01-05 11:34:32 +0000240 */
241 if(
drhe5fe6902007-12-07 18:55:28 +0000242 0==(p->db->flags&SQLITE_ReadUncommitted) ||
danielk1977da184232006-01-05 11:34:32 +0000243 eLock==WRITE_LOCK ||
drh47ded162006-01-06 01:42:58 +0000244 iTab==MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000245 ){
246 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
danielk19775b413d72009-04-01 09:41:54 +0000247 /* The condition (pIter->eLock!=eLock) in the following if(...)
248 ** statement is a simplification of:
249 **
250 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
251 **
252 ** since we know that if eLock==WRITE_LOCK, then no other connection
253 ** may hold a WRITE_LOCK on any table in this file (since there can
254 ** only be a single writer).
255 */
256 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
257 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
258 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
danielk1977404ca072009-03-16 13:19:36 +0000259 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
260 if( eLock==WRITE_LOCK ){
261 assert( p==pBt->pWriter );
262 pBt->isPending = 1;
263 }
264 return SQLITE_LOCKED_SHAREDCACHE;
danielk1977da184232006-01-05 11:34:32 +0000265 }
danielk1977aef0bf62005-12-30 16:28:01 +0000266 }
267 }
268 return SQLITE_OK;
269}
drhe53831d2007-08-17 01:14:38 +0000270#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000271
drhe53831d2007-08-17 01:14:38 +0000272#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000273/*
274** Add a lock on the table with root-page iTable to the shared-btree used
275** by Btree handle p. Parameter eLock must be either READ_LOCK or
276** WRITE_LOCK.
277**
278** SQLITE_OK is returned if the lock is added successfully. SQLITE_BUSY and
279** SQLITE_NOMEM may also be returned.
280*/
drhc25eabe2009-02-24 18:57:31 +0000281static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
danielk1977aef0bf62005-12-30 16:28:01 +0000282 BtShared *pBt = p->pBt;
283 BtLock *pLock = 0;
284 BtLock *pIter;
285
drh1fee73e2007-08-29 04:00:57 +0000286 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000287 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
288 assert( p->db!=0 );
drhd677b3d2007-08-20 22:48:41 +0000289
danielk1977da184232006-01-05 11:34:32 +0000290 /* This is a no-op if the shared-cache is not enabled */
drhe53831d2007-08-17 01:14:38 +0000291 if( !p->sharable ){
danielk1977da184232006-01-05 11:34:32 +0000292 return SQLITE_OK;
293 }
294
drhc25eabe2009-02-24 18:57:31 +0000295 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
danielk1977aef0bf62005-12-30 16:28:01 +0000296
drhc74d0b1d2009-02-24 16:18:05 +0000297 /* If the read-uncommitted flag is set and a read-lock is requested on
298 ** a non-schema table, then the lock is always granted. Return early
299 ** without adding an entry to the BtShared.pLock list. See
drhc25eabe2009-02-24 18:57:31 +0000300 ** comment in function querySharedCacheTableLock() for more info
301 ** on handling the ReadUncommitted flag.
danielk1977da184232006-01-05 11:34:32 +0000302 */
303 if(
drhe5fe6902007-12-07 18:55:28 +0000304 (p->db->flags&SQLITE_ReadUncommitted) &&
danielk1977da184232006-01-05 11:34:32 +0000305 (eLock==READ_LOCK) &&
drh47ded162006-01-06 01:42:58 +0000306 iTable!=MASTER_ROOT
danielk1977da184232006-01-05 11:34:32 +0000307 ){
308 return SQLITE_OK;
309 }
310
danielk1977aef0bf62005-12-30 16:28:01 +0000311 /* First search the list for an existing lock on this table. */
312 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
313 if( pIter->iTable==iTable && pIter->pBtree==p ){
314 pLock = pIter;
315 break;
316 }
317 }
318
319 /* If the above search did not find a BtLock struct associating Btree p
320 ** with table iTable, allocate one and link it into the list.
321 */
322 if( !pLock ){
drh17435752007-08-16 04:30:38 +0000323 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
danielk1977aef0bf62005-12-30 16:28:01 +0000324 if( !pLock ){
325 return SQLITE_NOMEM;
326 }
327 pLock->iTable = iTable;
328 pLock->pBtree = p;
329 pLock->pNext = pBt->pLock;
330 pBt->pLock = pLock;
331 }
332
333 /* Set the BtLock.eLock variable to the maximum of the current lock
334 ** and the requested lock. This means if a write-lock was already held
335 ** and a read-lock requested, we don't incorrectly downgrade the lock.
336 */
337 assert( WRITE_LOCK>READ_LOCK );
danielk19775118b912005-12-30 16:31:53 +0000338 if( eLock>pLock->eLock ){
339 pLock->eLock = eLock;
340 }
danielk1977aef0bf62005-12-30 16:28:01 +0000341
342 return SQLITE_OK;
343}
drhe53831d2007-08-17 01:14:38 +0000344#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000345
drhe53831d2007-08-17 01:14:38 +0000346#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000347/*
drhc25eabe2009-02-24 18:57:31 +0000348** Release all the table locks (locks obtained via calls to
349** the setSharedCacheTableLock() procedure) held by Btree handle p.
danielk1977fa542f12009-04-02 18:28:08 +0000350**
351** This function assumes that handle p has an open read or write
352** transaction. If it does not, then the BtShared.isPending variable
353** may be incorrectly cleared.
danielk1977aef0bf62005-12-30 16:28:01 +0000354*/
drhc25eabe2009-02-24 18:57:31 +0000355static void clearAllSharedCacheTableLocks(Btree *p){
danielk1977641b0f42007-12-21 04:47:25 +0000356 BtShared *pBt = p->pBt;
357 BtLock **ppIter = &pBt->pLock;
danielk1977da184232006-01-05 11:34:32 +0000358
drh1fee73e2007-08-29 04:00:57 +0000359 assert( sqlite3BtreeHoldsMutex(p) );
drhe53831d2007-08-17 01:14:38 +0000360 assert( p->sharable || 0==*ppIter );
danielk1977fa542f12009-04-02 18:28:08 +0000361 assert( p->inTrans>0 );
danielk1977da184232006-01-05 11:34:32 +0000362
danielk1977aef0bf62005-12-30 16:28:01 +0000363 while( *ppIter ){
364 BtLock *pLock = *ppIter;
danielk1977404ca072009-03-16 13:19:36 +0000365 assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
danielk1977fa542f12009-04-02 18:28:08 +0000366 assert( pLock->pBtree->inTrans>=pLock->eLock );
danielk1977aef0bf62005-12-30 16:28:01 +0000367 if( pLock->pBtree==p ){
368 *ppIter = pLock->pNext;
drh17435752007-08-16 04:30:38 +0000369 sqlite3_free(pLock);
danielk1977aef0bf62005-12-30 16:28:01 +0000370 }else{
371 ppIter = &pLock->pNext;
372 }
373 }
danielk1977641b0f42007-12-21 04:47:25 +0000374
danielk1977404ca072009-03-16 13:19:36 +0000375 assert( pBt->isPending==0 || pBt->pWriter );
376 if( pBt->pWriter==p ){
377 pBt->pWriter = 0;
378 pBt->isExclusive = 0;
379 pBt->isPending = 0;
380 }else if( pBt->nTransaction==2 ){
381 /* This function is called when connection p is concluding its
382 ** transaction. If there currently exists a writer, and p is not
383 ** that writer, then the number of locks held by connections other
384 ** than the writer must be about to drop to zero. In this case
385 ** set the isPending flag to 0.
386 **
387 ** If there is not currently a writer, then BtShared.isPending must
388 ** be zero already. So this next line is harmless in that case.
389 */
390 pBt->isPending = 0;
danielk1977641b0f42007-12-21 04:47:25 +0000391 }
danielk1977aef0bf62005-12-30 16:28:01 +0000392}
393#endif /* SQLITE_OMIT_SHARED_CACHE */
394
drh980b1a72006-08-16 16:42:48 +0000395static void releasePage(MemPage *pPage); /* Forward reference */
396
drh1fee73e2007-08-29 04:00:57 +0000397/*
398** Verify that the cursor holds a mutex on the BtShared
399*/
400#ifndef NDEBUG
401static int cursorHoldsMutex(BtCursor *p){
drhff0587c2007-08-29 17:43:19 +0000402 return sqlite3_mutex_held(p->pBt->mutex);
drh1fee73e2007-08-29 04:00:57 +0000403}
404#endif
405
406
danielk197792d4d7a2007-05-04 12:05:56 +0000407#ifndef SQLITE_OMIT_INCRBLOB
408/*
409** Invalidate the overflow page-list cache for cursor pCur, if any.
410*/
411static void invalidateOverflowCache(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000412 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000413 sqlite3_free(pCur->aOverflow);
danielk197792d4d7a2007-05-04 12:05:56 +0000414 pCur->aOverflow = 0;
415}
416
417/*
418** Invalidate the overflow page-list cache for all cursors opened
419** on the shared btree structure pBt.
420*/
421static void invalidateAllOverflowCache(BtShared *pBt){
422 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000423 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +0000424 for(p=pBt->pCursor; p; p=p->pNext){
425 invalidateOverflowCache(p);
426 }
427}
danielk197796d48e92009-06-29 06:00:37 +0000428
429/*
430** This function is called before modifying the contents of a table
431** b-tree to invalidate any incrblob cursors that are open on the
432** row or one of the rows being modified. Argument pgnoRoot is the
433** root-page of the table b-tree.
434**
435** If argument isClearTable is true, then the entire contents of the
436** table is about to be deleted. In this case invalidate all incrblob
437** cursors open on any row within the table with root-page pgnoRoot.
438**
439** Otherwise, if argument isClearTable is false, then the row with
440** rowid iRow is being replaced or deleted. In this case invalidate
441** only those incrblob cursors open on this specific row.
442*/
443static void invalidateIncrblobCursors(
444 Btree *pBtree, /* The database file to check */
445 Pgno pgnoRoot, /* Look for read cursors on this btree */
446 i64 iRow, /* The rowid that might be changing */
447 int isClearTable /* True if all rows are being deleted */
448){
449 BtCursor *p;
450 BtShared *pBt = pBtree->pBt;
451 assert( sqlite3BtreeHoldsMutex(pBtree) );
452 for(p=pBt->pCursor; p; p=p->pNext){
453 if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
454 p->eState = CURSOR_INVALID;
455 }
456 }
457}
458
danielk197792d4d7a2007-05-04 12:05:56 +0000459#else
460 #define invalidateOverflowCache(x)
461 #define invalidateAllOverflowCache(x)
danielk197796d48e92009-06-29 06:00:37 +0000462 #define invalidateIncrblobCursors(w,x,y,z)
danielk197792d4d7a2007-05-04 12:05:56 +0000463#endif
464
drh980b1a72006-08-16 16:42:48 +0000465/*
danielk1977bea2a942009-01-20 17:06:27 +0000466** Set bit pgno of the BtShared.pHasContent bitvec. This is called
467** when a page that previously contained data becomes a free-list leaf
468** page.
469**
470** The BtShared.pHasContent bitvec exists to work around an obscure
471** bug caused by the interaction of two useful IO optimizations surrounding
472** free-list leaf pages:
473**
474** 1) When all data is deleted from a page and the page becomes
475** a free-list leaf page, the page is not written to the database
476** (as free-list leaf pages contain no meaningful data). Sometimes
477** such a page is not even journalled (as it will not be modified,
478** why bother journalling it?).
479**
480** 2) When a free-list leaf page is reused, its content is not read
481** from the database or written to the journal file (why should it
482** be, if it is not at all meaningful?).
483**
484** By themselves, these optimizations work fine and provide a handy
485** performance boost to bulk delete or insert operations. However, if
486** a page is moved to the free-list and then reused within the same
487** transaction, a problem comes up. If the page is not journalled when
488** it is moved to the free-list and it is also not journalled when it
489** is extracted from the free-list and reused, then the original data
490** may be lost. In the event of a rollback, it may not be possible
491** to restore the database to its original configuration.
492**
493** The solution is the BtShared.pHasContent bitvec. Whenever a page is
494** moved to become a free-list leaf page, the corresponding bit is
495** set in the bitvec. Whenever a leaf page is extracted from the free-list,
496** optimization 2 above is ommitted if the corresponding bit is already
497** set in BtShared.pHasContent. The contents of the bitvec are cleared
498** at the end of every transaction.
499*/
500static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
501 int rc = SQLITE_OK;
502 if( !pBt->pHasContent ){
503 int nPage;
504 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
505 if( rc==SQLITE_OK ){
506 pBt->pHasContent = sqlite3BitvecCreate((u32)nPage);
507 if( !pBt->pHasContent ){
508 rc = SQLITE_NOMEM;
509 }
510 }
511 }
512 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
513 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
514 }
515 return rc;
516}
517
518/*
519** Query the BtShared.pHasContent vector.
520**
521** This function is called when a free-list leaf page is removed from the
522** free-list for reuse. It returns false if it is safe to retrieve the
523** page from the pager layer with the 'no-content' flag set. True otherwise.
524*/
525static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
526 Bitvec *p = pBt->pHasContent;
527 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
528}
529
530/*
531** Clear (destroy) the BtShared.pHasContent bitvec. This should be
532** invoked at the conclusion of each write-transaction.
533*/
534static void btreeClearHasContent(BtShared *pBt){
535 sqlite3BitvecDestroy(pBt->pHasContent);
536 pBt->pHasContent = 0;
537}
538
539/*
drh980b1a72006-08-16 16:42:48 +0000540** Save the current cursor position in the variables BtCursor.nKey
541** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
542*/
543static int saveCursorPosition(BtCursor *pCur){
544 int rc;
545
546 assert( CURSOR_VALID==pCur->eState );
547 assert( 0==pCur->pKey );
drh1fee73e2007-08-29 04:00:57 +0000548 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000549
550 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
551
552 /* If this is an intKey table, then the above call to BtreeKeySize()
553 ** stores the integer key in pCur->nKey. In this case this value is
554 ** all that is required. Otherwise, if pCur is not open on an intKey
555 ** table, then malloc space for and store the pCur->nKey bytes of key
556 ** data.
557 */
danielk197771d5d2c2008-09-29 11:49:47 +0000558 if( rc==SQLITE_OK && 0==pCur->apPage[0]->intKey){
drhf49661a2008-12-10 16:45:50 +0000559 void *pKey = sqlite3Malloc( (int)pCur->nKey );
drh980b1a72006-08-16 16:42:48 +0000560 if( pKey ){
drhf49661a2008-12-10 16:45:50 +0000561 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
drh980b1a72006-08-16 16:42:48 +0000562 if( rc==SQLITE_OK ){
563 pCur->pKey = pKey;
564 }else{
drh17435752007-08-16 04:30:38 +0000565 sqlite3_free(pKey);
drh980b1a72006-08-16 16:42:48 +0000566 }
567 }else{
568 rc = SQLITE_NOMEM;
569 }
570 }
danielk197771d5d2c2008-09-29 11:49:47 +0000571 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
drh980b1a72006-08-16 16:42:48 +0000572
573 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +0000574 int i;
575 for(i=0; i<=pCur->iPage; i++){
576 releasePage(pCur->apPage[i]);
577 pCur->apPage[i] = 0;
578 }
579 pCur->iPage = -1;
drh980b1a72006-08-16 16:42:48 +0000580 pCur->eState = CURSOR_REQUIRESEEK;
581 }
582
danielk197792d4d7a2007-05-04 12:05:56 +0000583 invalidateOverflowCache(pCur);
drh980b1a72006-08-16 16:42:48 +0000584 return rc;
585}
586
587/*
588** Save the positions of all cursors except pExcept open on the table
589** with root-page iRoot. Usually, this is called just before cursor
590** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
591*/
592static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
593 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000594 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +0000595 assert( pExcept==0 || pExcept->pBt==pBt );
drh980b1a72006-08-16 16:42:48 +0000596 for(p=pBt->pCursor; p; p=p->pNext){
597 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
598 p->eState==CURSOR_VALID ){
599 int rc = saveCursorPosition(p);
600 if( SQLITE_OK!=rc ){
601 return rc;
602 }
603 }
604 }
605 return SQLITE_OK;
606}
607
608/*
drhbf700f32007-03-31 02:36:44 +0000609** Clear the current cursor position.
610*/
danielk1977be51a652008-10-08 17:58:48 +0000611void sqlite3BtreeClearCursor(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000612 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000613 sqlite3_free(pCur->pKey);
drhbf700f32007-03-31 02:36:44 +0000614 pCur->pKey = 0;
615 pCur->eState = CURSOR_INVALID;
616}
617
618/*
drh980b1a72006-08-16 16:42:48 +0000619** Restore the cursor to the position it was in (or as close to as possible)
620** when saveCursorPosition() was called. Note that this call deletes the
621** saved position info stored by saveCursorPosition(), so there can be
drha3460582008-07-11 21:02:53 +0000622** at most one effective restoreCursorPosition() call after each
drh980b1a72006-08-16 16:42:48 +0000623** saveCursorPosition().
drh980b1a72006-08-16 16:42:48 +0000624*/
drha3460582008-07-11 21:02:53 +0000625int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +0000626 int rc;
drh1fee73e2007-08-29 04:00:57 +0000627 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +0000628 assert( pCur->eState>=CURSOR_REQUIRESEEK );
629 if( pCur->eState==CURSOR_FAULT ){
630 return pCur->skip;
631 }
drh980b1a72006-08-16 16:42:48 +0000632 pCur->eState = CURSOR_INVALID;
drhe63d9992008-08-13 19:11:48 +0000633 rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skip);
drh980b1a72006-08-16 16:42:48 +0000634 if( rc==SQLITE_OK ){
drh17435752007-08-16 04:30:38 +0000635 sqlite3_free(pCur->pKey);
drh980b1a72006-08-16 16:42:48 +0000636 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +0000637 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drh980b1a72006-08-16 16:42:48 +0000638 }
639 return rc;
640}
641
drha3460582008-07-11 21:02:53 +0000642#define restoreCursorPosition(p) \
drhfb982642007-08-30 01:19:59 +0000643 (p->eState>=CURSOR_REQUIRESEEK ? \
drha3460582008-07-11 21:02:53 +0000644 sqlite3BtreeRestoreCursorPosition(p) : \
drh16a9b832007-05-05 18:39:25 +0000645 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +0000646
drha3460582008-07-11 21:02:53 +0000647/*
648** Determine whether or not a cursor has moved from the position it
drhdfe88ec2008-11-03 20:55:06 +0000649** was last placed at. Cursors can move when the row they are pointing
drha3460582008-07-11 21:02:53 +0000650** at is deleted out from under them.
651**
652** This routine returns an error code if something goes wrong. The
653** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
654*/
655int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
656 int rc;
657
658 rc = restoreCursorPosition(pCur);
659 if( rc ){
660 *pHasMoved = 1;
661 return rc;
662 }
663 if( pCur->eState!=CURSOR_VALID || pCur->skip!=0 ){
664 *pHasMoved = 1;
665 }else{
666 *pHasMoved = 0;
667 }
668 return SQLITE_OK;
669}
670
danielk1977599fcba2004-11-08 07:13:13 +0000671#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000672/*
drha3152892007-05-05 11:48:52 +0000673** Given a page number of a regular database page, return the page
674** number for the pointer-map page that contains the entry for the
675** input page number.
danielk1977afcdd022004-10-31 16:25:42 +0000676*/
danielk1977266664d2006-02-10 08:24:21 +0000677static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
danielk197789d40042008-11-17 14:20:56 +0000678 int nPagesPerMapPage;
679 Pgno iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +0000680 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000681 nPagesPerMapPage = (pBt->usableSize/5)+1;
682 iPtrMap = (pgno-2)/nPagesPerMapPage;
683 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +0000684 if( ret==PENDING_BYTE_PAGE(pBt) ){
685 ret++;
686 }
687 return ret;
688}
danielk1977a19df672004-11-03 11:37:07 +0000689
danielk1977afcdd022004-10-31 16:25:42 +0000690/*
danielk1977afcdd022004-10-31 16:25:42 +0000691** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000692**
693** This routine updates the pointer map entry for page number 'key'
694** so that it maps to type 'eType' and parent page number 'pgno'.
695** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000696*/
danielk1977aef0bf62005-12-30 16:28:01 +0000697static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
danielk19773b8a05f2007-03-19 17:44:26 +0000698 DbPage *pDbPage; /* The pointer map page */
699 u8 *pPtrmap; /* The pointer map data */
700 Pgno iPtrmap; /* The pointer map page number */
701 int offset; /* Offset in pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000702 int rc;
703
drh1fee73e2007-08-29 04:00:57 +0000704 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977266664d2006-02-10 08:24:21 +0000705 /* The master-journal page number must never be used as a pointer map page */
706 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
707
danielk1977ac11ee62005-01-15 12:45:51 +0000708 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000709 if( key==0 ){
drh49285702005-09-17 15:20:26 +0000710 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000711 }
danielk1977266664d2006-02-10 08:24:21 +0000712 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000713 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977687566d2004-11-02 12:56:41 +0000714 if( rc!=SQLITE_OK ){
danielk1977afcdd022004-10-31 16:25:42 +0000715 return rc;
716 }
danielk19778c666b12008-07-18 09:34:57 +0000717 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drhacfc72b2009-06-05 18:44:15 +0000718 if( offset<0 ){
719 return SQLITE_CORRUPT_BKPT;
720 }
danielk19773b8a05f2007-03-19 17:44:26 +0000721 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000722
drh615ae552005-01-16 23:21:00 +0000723 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
724 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
danielk19773b8a05f2007-03-19 17:44:26 +0000725 rc = sqlite3PagerWrite(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000726 if( rc==SQLITE_OK ){
727 pPtrmap[offset] = eType;
728 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000729 }
danielk1977afcdd022004-10-31 16:25:42 +0000730 }
731
danielk19773b8a05f2007-03-19 17:44:26 +0000732 sqlite3PagerUnref(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000733 return rc;
danielk1977afcdd022004-10-31 16:25:42 +0000734}
735
736/*
737** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000738**
739** This routine retrieves the pointer map entry for page 'key', writing
740** the type and parent page number to *pEType and *pPgno respectively.
741** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000742*/
danielk1977aef0bf62005-12-30 16:28:01 +0000743static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +0000744 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000745 int iPtrmap; /* Pointer map page index */
746 u8 *pPtrmap; /* Pointer map page data */
747 int offset; /* Offset of entry in pointer map */
748 int rc;
749
drh1fee73e2007-08-29 04:00:57 +0000750 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000751
danielk1977266664d2006-02-10 08:24:21 +0000752 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000753 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000754 if( rc!=0 ){
755 return rc;
756 }
danielk19773b8a05f2007-03-19 17:44:26 +0000757 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000758
danielk19778c666b12008-07-18 09:34:57 +0000759 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drh43617e92006-03-06 20:55:46 +0000760 assert( pEType!=0 );
761 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +0000762 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000763
danielk19773b8a05f2007-03-19 17:44:26 +0000764 sqlite3PagerUnref(pDbPage);
drh49285702005-09-17 15:20:26 +0000765 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000766 return SQLITE_OK;
767}
768
danielk197785d90ca2008-07-19 14:25:15 +0000769#else /* if defined SQLITE_OMIT_AUTOVACUUM */
770 #define ptrmapPut(w,x,y,z) SQLITE_OK
771 #define ptrmapGet(w,x,y,z) SQLITE_OK
danielk1977325ccfa2009-07-02 05:23:25 +0000772 #define ptrmapPutOvflPtr(x, y) SQLITE_OK
danielk197785d90ca2008-07-19 14:25:15 +0000773#endif
danielk1977afcdd022004-10-31 16:25:42 +0000774
drh0d316a42002-08-11 20:10:47 +0000775/*
drh271efa52004-05-30 19:19:05 +0000776** Given a btree page and a cell index (0 means the first cell on
777** the page, 1 means the second cell, and so forth) return a pointer
778** to the cell content.
779**
780** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000781*/
drh1688c862008-07-18 02:44:17 +0000782#define findCell(P,I) \
783 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
drh43605152004-05-29 21:46:49 +0000784
785/*
drh93a960a2008-07-10 00:32:42 +0000786** This a more complex version of findCell() that works for
drh43605152004-05-29 21:46:49 +0000787** pages that do contain overflow cells. See insert
788*/
789static u8 *findOverflowCell(MemPage *pPage, int iCell){
790 int i;
drh1fee73e2007-08-29 04:00:57 +0000791 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +0000792 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000793 int k;
794 struct _OvflCell *pOvfl;
795 pOvfl = &pPage->aOvfl[i];
796 k = pOvfl->idx;
797 if( k<=iCell ){
798 if( k==iCell ){
799 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000800 }
801 iCell--;
802 }
803 }
danielk19771cc5ed82007-05-16 17:28:43 +0000804 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000805}
806
807/*
808** Parse a cell content block and fill in the CellInfo structure. There
drh16a9b832007-05-05 18:39:25 +0000809** are two versions of this function. sqlite3BtreeParseCell() takes a
810** cell index as the second argument and sqlite3BtreeParseCellPtr()
811** takes a pointer to the body of the cell as its second argument.
danielk19771cc5ed82007-05-16 17:28:43 +0000812**
813** Within this file, the parseCell() macro can be called instead of
814** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
drh43605152004-05-29 21:46:49 +0000815*/
drh16a9b832007-05-05 18:39:25 +0000816void sqlite3BtreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000817 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000818 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000819 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000820){
drhf49661a2008-12-10 16:45:50 +0000821 u16 n; /* Number bytes in cell content header */
drh271efa52004-05-30 19:19:05 +0000822 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000823
drh1fee73e2007-08-29 04:00:57 +0000824 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000825
drh43605152004-05-29 21:46:49 +0000826 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000827 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000828 n = pPage->childPtrSize;
829 assert( n==4-4*pPage->leaf );
drh504b6982006-01-22 21:52:56 +0000830 if( pPage->intKey ){
drh79df1f42008-07-18 00:57:33 +0000831 if( pPage->hasData ){
832 n += getVarint32(&pCell[n], nPayload);
833 }else{
834 nPayload = 0;
835 }
drh1bd10f82008-12-10 21:19:56 +0000836 n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
drh79df1f42008-07-18 00:57:33 +0000837 pInfo->nData = nPayload;
drh504b6982006-01-22 21:52:56 +0000838 }else{
drh79df1f42008-07-18 00:57:33 +0000839 pInfo->nData = 0;
840 n += getVarint32(&pCell[n], nPayload);
841 pInfo->nKey = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000842 }
drh72365832007-03-06 15:53:44 +0000843 pInfo->nPayload = nPayload;
drh504b6982006-01-22 21:52:56 +0000844 pInfo->nHeader = n;
drh79df1f42008-07-18 00:57:33 +0000845 if( likely(nPayload<=pPage->maxLocal) ){
drh271efa52004-05-30 19:19:05 +0000846 /* This is the (easy) common case where the entire payload fits
847 ** on the local page. No overflow is required.
848 */
849 int nSize; /* Total size of cell content in bytes */
drh79df1f42008-07-18 00:57:33 +0000850 nSize = nPayload + n;
drhf49661a2008-12-10 16:45:50 +0000851 pInfo->nLocal = (u16)nPayload;
drh6f11bef2004-05-13 01:12:56 +0000852 pInfo->iOverflow = 0;
drh79df1f42008-07-18 00:57:33 +0000853 if( (nSize & ~3)==0 ){
drh271efa52004-05-30 19:19:05 +0000854 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000855 }
drh1bd10f82008-12-10 21:19:56 +0000856 pInfo->nSize = (u16)nSize;
drh6f11bef2004-05-13 01:12:56 +0000857 }else{
drh271efa52004-05-30 19:19:05 +0000858 /* If the payload will not fit completely on the local page, we have
859 ** to decide how much to store locally and how much to spill onto
860 ** overflow pages. The strategy is to minimize the amount of unused
861 ** space on overflow pages while keeping the amount of local storage
862 ** in between minLocal and maxLocal.
863 **
864 ** Warning: changing the way overflow payload is distributed in any
865 ** way will result in an incompatible file format.
866 */
867 int minLocal; /* Minimum amount of payload held locally */
868 int maxLocal; /* Maximum amount of payload held locally */
869 int surplus; /* Overflow payload available for local storage */
870
871 minLocal = pPage->minLocal;
872 maxLocal = pPage->maxLocal;
873 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000874 if( surplus <= maxLocal ){
drhf49661a2008-12-10 16:45:50 +0000875 pInfo->nLocal = (u16)surplus;
drh6f11bef2004-05-13 01:12:56 +0000876 }else{
drhf49661a2008-12-10 16:45:50 +0000877 pInfo->nLocal = (u16)minLocal;
drh6f11bef2004-05-13 01:12:56 +0000878 }
drhf49661a2008-12-10 16:45:50 +0000879 pInfo->iOverflow = (u16)(pInfo->nLocal + n);
drh6f11bef2004-05-13 01:12:56 +0000880 pInfo->nSize = pInfo->iOverflow + 4;
881 }
drh3aac2dd2004-04-26 14:10:20 +0000882}
danielk19771cc5ed82007-05-16 17:28:43 +0000883#define parseCell(pPage, iCell, pInfo) \
884 sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
drh16a9b832007-05-05 18:39:25 +0000885void sqlite3BtreeParseCell(
drh43605152004-05-29 21:46:49 +0000886 MemPage *pPage, /* Page containing the cell */
887 int iCell, /* The cell index. First cell is 0 */
888 CellInfo *pInfo /* Fill in this structure */
889){
danielk19771cc5ed82007-05-16 17:28:43 +0000890 parseCell(pPage, iCell, pInfo);
drh43605152004-05-29 21:46:49 +0000891}
drh3aac2dd2004-04-26 14:10:20 +0000892
893/*
drh43605152004-05-29 21:46:49 +0000894** Compute the total number of bytes that a Cell needs in the cell
895** data area of the btree-page. The return number includes the cell
896** data header and the local payload, but not any overflow page or
897** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000898*/
danielk1977ae5558b2009-04-29 11:31:47 +0000899static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
900 u8 *pIter = &pCell[pPage->childPtrSize];
901 u32 nSize;
902
903#ifdef SQLITE_DEBUG
904 /* The value returned by this function should always be the same as
905 ** the (CellInfo.nSize) value found by doing a full parse of the
906 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
907 ** this function verifies that this invariant is not violated. */
908 CellInfo debuginfo;
909 sqlite3BtreeParseCellPtr(pPage, pCell, &debuginfo);
910#endif
911
912 if( pPage->intKey ){
913 u8 *pEnd;
914 if( pPage->hasData ){
915 pIter += getVarint32(pIter, nSize);
916 }else{
917 nSize = 0;
918 }
919
920 /* pIter now points at the 64-bit integer key value, a variable length
921 ** integer. The following block moves pIter to point at the first byte
922 ** past the end of the key value. */
923 pEnd = &pIter[9];
924 while( (*pIter++)&0x80 && pIter<pEnd );
925 }else{
926 pIter += getVarint32(pIter, nSize);
927 }
928
929 if( nSize>pPage->maxLocal ){
930 int minLocal = pPage->minLocal;
931 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
932 if( nSize>pPage->maxLocal ){
933 nSize = minLocal;
934 }
935 nSize += 4;
936 }
shane75ac1de2009-06-09 18:58:52 +0000937 nSize += (u32)(pIter - pCell);
danielk1977ae5558b2009-04-29 11:31:47 +0000938
939 /* The minimum size of any cell is 4 bytes. */
940 if( nSize<4 ){
941 nSize = 4;
942 }
943
944 assert( nSize==debuginfo.nSize );
shane60a4b532009-05-06 18:57:09 +0000945 return (u16)nSize;
danielk1977ae5558b2009-04-29 11:31:47 +0000946}
danielk1977bc6ada42004-06-30 08:20:16 +0000947#ifndef NDEBUG
drha9121e42008-02-19 14:59:35 +0000948static u16 cellSize(MemPage *pPage, int iCell){
danielk1977ae5558b2009-04-29 11:31:47 +0000949 return cellSizePtr(pPage, findCell(pPage, iCell));
drh43605152004-05-29 21:46:49 +0000950}
danielk1977bc6ada42004-06-30 08:20:16 +0000951#endif
drh3b7511c2001-05-26 13:15:44 +0000952
danielk197779a40da2005-01-16 08:00:01 +0000953#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +0000954/*
danielk197726836652005-01-17 01:33:13 +0000955** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +0000956** to an overflow page, insert an entry into the pointer-map
957** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +0000958*/
danielk197726836652005-01-17 01:33:13 +0000959static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
drhfa67c3c2008-07-11 02:21:40 +0000960 CellInfo info;
961 assert( pCell!=0 );
962 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
963 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk19774dbaa892009-06-16 16:50:22 +0000964 if( info.iOverflow ){
drhfa67c3c2008-07-11 02:21:40 +0000965 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
966 return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +0000967 }
danielk197779a40da2005-01-16 08:00:01 +0000968 return SQLITE_OK;
danielk1977ac11ee62005-01-15 12:45:51 +0000969}
danielk197779a40da2005-01-16 08:00:01 +0000970#endif
971
danielk1977ac11ee62005-01-15 12:45:51 +0000972
drhda200cc2004-05-09 11:51:38 +0000973/*
drh72f82862001-05-24 21:06:34 +0000974** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +0000975** end of the page and all free space is collected into one
976** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +0000977** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +0000978*/
shane0af3f892008-11-12 04:55:34 +0000979static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000980 int i; /* Loop counter */
981 int pc; /* Address of a i-th cell */
982 int addr; /* Offset of first byte after cell pointer array */
983 int hdr; /* Offset to the page header */
984 int size; /* Size of a cell */
985 int usableSize; /* Number of usable bytes on a page */
986 int cellOffset; /* Offset to the cell pointer array */
drh281b21d2008-08-22 12:57:08 +0000987 int cbrk; /* Offset to the cell content area */
drh43605152004-05-29 21:46:49 +0000988 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +0000989 unsigned char *data; /* The page data */
990 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +0000991
danielk19773b8a05f2007-03-19 17:44:26 +0000992 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000993 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +0000994 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000995 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +0000996 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh26b79942007-11-28 16:19:56 +0000997 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
drh43605152004-05-29 21:46:49 +0000998 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +0000999 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00001000 cellOffset = pPage->cellOffset;
1001 nCell = pPage->nCell;
1002 assert( nCell==get2byte(&data[hdr+3]) );
1003 usableSize = pPage->pBt->usableSize;
drh281b21d2008-08-22 12:57:08 +00001004 cbrk = get2byte(&data[hdr+5]);
1005 memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
1006 cbrk = usableSize;
drh43605152004-05-29 21:46:49 +00001007 for(i=0; i<nCell; i++){
1008 u8 *pAddr; /* The i-th cell pointer */
1009 pAddr = &data[cellOffset + i*2];
1010 pc = get2byte(pAddr);
shanedcc50b72008-11-13 18:29:50 +00001011 if( pc>=usableSize ){
shane0af3f892008-11-12 04:55:34 +00001012 return SQLITE_CORRUPT_BKPT;
1013 }
drh43605152004-05-29 21:46:49 +00001014 size = cellSizePtr(pPage, &temp[pc]);
drh281b21d2008-08-22 12:57:08 +00001015 cbrk -= size;
danielk19770d065412008-11-12 18:21:36 +00001016 if( cbrk<cellOffset+2*nCell || pc+size>usableSize ){
shane0af3f892008-11-12 04:55:34 +00001017 return SQLITE_CORRUPT_BKPT;
1018 }
danielk19770d065412008-11-12 18:21:36 +00001019 assert( cbrk+size<=usableSize && cbrk>=0 );
drh281b21d2008-08-22 12:57:08 +00001020 memcpy(&data[cbrk], &temp[pc], size);
1021 put2byte(pAddr, cbrk);
drh2af926b2001-05-15 00:39:25 +00001022 }
drh281b21d2008-08-22 12:57:08 +00001023 assert( cbrk>=cellOffset+2*nCell );
1024 put2byte(&data[hdr+5], cbrk);
drh43605152004-05-29 21:46:49 +00001025 data[hdr+1] = 0;
1026 data[hdr+2] = 0;
1027 data[hdr+7] = 0;
1028 addr = cellOffset+2*nCell;
drh281b21d2008-08-22 12:57:08 +00001029 memset(&data[addr], 0, cbrk-addr);
drhc5053fb2008-11-27 02:22:10 +00001030 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977360e6342008-11-12 08:49:51 +00001031 if( cbrk-addr!=pPage->nFree ){
1032 return SQLITE_CORRUPT_BKPT;
1033 }
shane0af3f892008-11-12 04:55:34 +00001034 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +00001035}
1036
drha059ad02001-04-17 20:09:11 +00001037/*
danielk19776011a752009-04-01 16:25:32 +00001038** Allocate nByte bytes of space from within the B-Tree page passed
1039** as the first argument. Return the index into pPage->aData[] of the
1040** first byte of allocated space.
drhbd03cae2001-06-02 02:40:57 +00001041**
danielk19776011a752009-04-01 16:25:32 +00001042** The caller guarantees that the space between the end of the cell-offset
1043** array and the start of the cell-content area is at least nByte bytes
1044** in size. So this routine can never fail.
drh2af926b2001-05-15 00:39:25 +00001045**
danielk19776011a752009-04-01 16:25:32 +00001046** If there are already 60 or more bytes of fragments within the page,
1047** the page is defragmented before returning. If this were not done there
1048** is a chance that the number of fragmented bytes could eventually
1049** overflow the single-byte field of the page-header in which this value
1050** is stored.
drh7e3b0a02001-04-28 16:52:40 +00001051*/
drh9e572e62004-04-23 23:43:10 +00001052static int allocateSpace(MemPage *pPage, int nByte){
danielk19776011a752009-04-01 16:25:32 +00001053 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1054 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
1055 int nFrag; /* Number of fragmented bytes on pPage */
drh43605152004-05-29 21:46:49 +00001056 int top;
drh43605152004-05-29 21:46:49 +00001057
danielk19773b8a05f2007-03-19 17:44:26 +00001058 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001059 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +00001060 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa67c3c2008-07-11 02:21:40 +00001061 assert( nByte>=0 ); /* Minimum cell size is 4 */
1062 assert( pPage->nFree>=nByte );
1063 assert( pPage->nOverflow==0 );
drh43605152004-05-29 21:46:49 +00001064
danielk19776011a752009-04-01 16:25:32 +00001065 /* Assert that the space between the cell-offset array and the
1066 ** cell-content area is greater than nByte bytes.
1067 */
1068 assert( nByte <= (
1069 get2byte(&data[hdr+5])-(hdr+8+(pPage->leaf?0:4)+2*get2byte(&data[hdr+3]))
1070 ));
1071
drh43605152004-05-29 21:46:49 +00001072 nFrag = data[hdr+7];
danielk19776011a752009-04-01 16:25:32 +00001073 if( nFrag>=60 ){
1074 defragmentPage(pPage);
1075 }else{
1076 /* Search the freelist looking for a free slot big enough to satisfy
1077 ** the request. The allocation is made from the first free slot in
1078 ** the list that is large enough to accomadate it.
1079 */
1080 int pc, addr;
1081 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
1082 int size = get2byte(&data[pc+2]); /* Size of free slot */
drh43605152004-05-29 21:46:49 +00001083 if( size>=nByte ){
drhf49661a2008-12-10 16:45:50 +00001084 int x = size - nByte;
danielk19776011a752009-04-01 16:25:32 +00001085 if( x<4 ){
danielk1977fad91942009-04-29 17:49:59 +00001086 /* Remove the slot from the free-list. Update the number of
1087 ** fragmented bytes within the page. */
drh43605152004-05-29 21:46:49 +00001088 memcpy(&data[addr], &data[pc], 2);
drhf49661a2008-12-10 16:45:50 +00001089 data[hdr+7] = (u8)(nFrag + x);
drh43605152004-05-29 21:46:49 +00001090 }else{
danielk1977fad91942009-04-29 17:49:59 +00001091 /* The slot remains on the free-list. Reduce its size to account
1092 ** for the portion used by the new allocation. */
drhf49661a2008-12-10 16:45:50 +00001093 put2byte(&data[pc+2], x);
drh43605152004-05-29 21:46:49 +00001094 }
danielk19776011a752009-04-01 16:25:32 +00001095 return pc + x;
drh43605152004-05-29 21:46:49 +00001096 }
drh9e572e62004-04-23 23:43:10 +00001097 }
1098 }
drh43605152004-05-29 21:46:49 +00001099
1100 /* Allocate memory from the gap in between the cell pointer array
1101 ** and the cell content area.
1102 */
danielk19776011a752009-04-01 16:25:32 +00001103 top = get2byte(&data[hdr+5]) - nByte;
drh43605152004-05-29 21:46:49 +00001104 put2byte(&data[hdr+5], top);
1105 return top;
drh7e3b0a02001-04-28 16:52:40 +00001106}
1107
1108/*
drh9e572e62004-04-23 23:43:10 +00001109** Return a section of the pPage->aData to the freelist.
1110** The first byte of the new free block is pPage->aDisk[start]
1111** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +00001112**
1113** Most of the effort here is involved in coalesing adjacent
1114** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +00001115*/
shanedcc50b72008-11-13 18:29:50 +00001116static int freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +00001117 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +00001118 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +00001119
drh9e572e62004-04-23 23:43:10 +00001120 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001121 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001122 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +00001123 assert( (start + size)<=pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +00001124 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh34004ce2008-07-11 16:15:17 +00001125 assert( size>=0 ); /* Minimum cell size is 4 */
drh9e572e62004-04-23 23:43:10 +00001126
drhfcce93f2006-02-22 03:08:32 +00001127#ifdef SQLITE_SECURE_DELETE
1128 /* Overwrite deleted information with zeros when the SECURE_DELETE
1129 ** option is enabled at compile-time */
1130 memset(&data[start], 0, size);
1131#endif
1132
drh9e572e62004-04-23 23:43:10 +00001133 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +00001134 hdr = pPage->hdrOffset;
1135 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +00001136 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +00001137 assert( pbegin<=pPage->pBt->usableSize-4 );
shanedcc50b72008-11-13 18:29:50 +00001138 if( pbegin<=addr ) {
1139 return SQLITE_CORRUPT_BKPT;
1140 }
drh3aac2dd2004-04-26 14:10:20 +00001141 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +00001142 }
shanedcc50b72008-11-13 18:29:50 +00001143 if ( pbegin>pPage->pBt->usableSize-4 ) {
1144 return SQLITE_CORRUPT_BKPT;
1145 }
drh3aac2dd2004-04-26 14:10:20 +00001146 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +00001147 put2byte(&data[addr], start);
1148 put2byte(&data[start], pbegin);
1149 put2byte(&data[start+2], size);
shane36840fd2009-06-26 16:32:13 +00001150 pPage->nFree = pPage->nFree + (u16)size;
drh9e572e62004-04-23 23:43:10 +00001151
1152 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +00001153 addr = pPage->hdrOffset + 1;
1154 while( (pbegin = get2byte(&data[addr]))>0 ){
drhf49661a2008-12-10 16:45:50 +00001155 int pnext, psize, x;
drh3aac2dd2004-04-26 14:10:20 +00001156 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +00001157 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +00001158 pnext = get2byte(&data[pbegin]);
1159 psize = get2byte(&data[pbegin+2]);
1160 if( pbegin + psize + 3 >= pnext && pnext>0 ){
1161 int frag = pnext - (pbegin+psize);
drhf49661a2008-12-10 16:45:50 +00001162 if( (frag<0) || (frag>(int)data[pPage->hdrOffset+7]) ){
shanedcc50b72008-11-13 18:29:50 +00001163 return SQLITE_CORRUPT_BKPT;
1164 }
drhf49661a2008-12-10 16:45:50 +00001165 data[pPage->hdrOffset+7] -= (u8)frag;
1166 x = get2byte(&data[pnext]);
1167 put2byte(&data[pbegin], x);
1168 x = pnext + get2byte(&data[pnext+2]) - pbegin;
1169 put2byte(&data[pbegin+2], x);
drh9e572e62004-04-23 23:43:10 +00001170 }else{
drh3aac2dd2004-04-26 14:10:20 +00001171 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +00001172 }
1173 }
drh7e3b0a02001-04-28 16:52:40 +00001174
drh43605152004-05-29 21:46:49 +00001175 /* If the cell content area begins with a freeblock, remove it. */
1176 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
1177 int top;
1178 pbegin = get2byte(&data[hdr+1]);
1179 memcpy(&data[hdr+1], &data[pbegin], 2);
drhf49661a2008-12-10 16:45:50 +00001180 top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
1181 put2byte(&data[hdr+5], top);
drh4b70f112004-05-02 21:12:19 +00001182 }
drhc5053fb2008-11-27 02:22:10 +00001183 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
shanedcc50b72008-11-13 18:29:50 +00001184 return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00001185}
1186
1187/*
drh271efa52004-05-30 19:19:05 +00001188** Decode the flags byte (the first byte of the header) for a page
1189** and initialize fields of the MemPage structure accordingly.
drh44845222008-07-17 18:39:57 +00001190**
1191** Only the following combinations are supported. Anything different
1192** indicates a corrupt database files:
1193**
1194** PTF_ZERODATA
1195** PTF_ZERODATA | PTF_LEAF
1196** PTF_LEAFDATA | PTF_INTKEY
1197** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
drh271efa52004-05-30 19:19:05 +00001198*/
drh44845222008-07-17 18:39:57 +00001199static int decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +00001200 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +00001201
1202 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +00001203 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00001204 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
drh44845222008-07-17 18:39:57 +00001205 flagByte &= ~PTF_LEAF;
1206 pPage->childPtrSize = 4-4*pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001207 pBt = pPage->pBt;
drh44845222008-07-17 18:39:57 +00001208 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
1209 pPage->intKey = 1;
1210 pPage->hasData = pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001211 pPage->maxLocal = pBt->maxLeaf;
1212 pPage->minLocal = pBt->minLeaf;
drh44845222008-07-17 18:39:57 +00001213 }else if( flagByte==PTF_ZERODATA ){
1214 pPage->intKey = 0;
1215 pPage->hasData = 0;
drh271efa52004-05-30 19:19:05 +00001216 pPage->maxLocal = pBt->maxLocal;
1217 pPage->minLocal = pBt->minLocal;
drh44845222008-07-17 18:39:57 +00001218 }else{
1219 return SQLITE_CORRUPT_BKPT;
drh271efa52004-05-30 19:19:05 +00001220 }
drh44845222008-07-17 18:39:57 +00001221 return SQLITE_OK;
drh271efa52004-05-30 19:19:05 +00001222}
1223
1224/*
drh7e3b0a02001-04-28 16:52:40 +00001225** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +00001226**
1227** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +00001228** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +00001229** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1230** guarantee that the page is well-formed. It only shows that
1231** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001232*/
danielk197771d5d2c2008-09-29 11:49:47 +00001233int sqlite3BtreeInitPage(MemPage *pPage){
drh2af926b2001-05-15 00:39:25 +00001234
danielk197771d5d2c2008-09-29 11:49:47 +00001235 assert( pPage->pBt!=0 );
1236 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001237 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +00001238 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1239 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00001240
1241 if( !pPage->isInit ){
drhf49661a2008-12-10 16:45:50 +00001242 u16 pc; /* Address of a freeblock within pPage->aData[] */
1243 u8 hdr; /* Offset to beginning of page header */
danielk197771d5d2c2008-09-29 11:49:47 +00001244 u8 *data; /* Equal to pPage->aData */
1245 BtShared *pBt; /* The main btree structure */
drhf49661a2008-12-10 16:45:50 +00001246 u16 usableSize; /* Amount of usable space on each page */
1247 u16 cellOffset; /* Offset from start of page to first cell pointer */
1248 u16 nFree; /* Number of unused bytes on the page */
1249 u16 top; /* First byte of the cell content area */
danielk197771d5d2c2008-09-29 11:49:47 +00001250
1251 pBt = pPage->pBt;
1252
danielk1977eaa06f62008-09-18 17:34:44 +00001253 hdr = pPage->hdrOffset;
1254 data = pPage->aData;
1255 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
1256 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
1257 pPage->maskPage = pBt->pageSize - 1;
1258 pPage->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00001259 usableSize = pBt->usableSize;
1260 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
1261 top = get2byte(&data[hdr+5]);
1262 pPage->nCell = get2byte(&data[hdr+3]);
1263 if( pPage->nCell>MX_CELL(pBt) ){
1264 /* To many cells for a single page. The page must be corrupt */
1265 return SQLITE_CORRUPT_BKPT;
1266 }
drh69e931e2009-06-03 21:04:35 +00001267
1268 /* A malformed database page might cause use to read past the end
1269 ** of page when parsing a cell.
1270 **
1271 ** The following block of code checks early to see if a cell extends
1272 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
1273 ** returned if it does.
1274 */
drh3b2a3fa2009-06-09 13:42:24 +00001275#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
drh69e931e2009-06-03 21:04:35 +00001276 {
1277 int iCellFirst; /* First allowable cell index */
1278 int iCellLast; /* Last possible cell index */
1279 int i; /* Index into the cell pointer array */
1280 int sz; /* Size of a cell */
1281
1282 iCellFirst = cellOffset + 2*pPage->nCell;
1283 iCellLast = usableSize - 4;
1284 if( !pPage->leaf ) iCellLast--;
1285 for(i=0; i<pPage->nCell; i++){
1286 pc = get2byte(&data[cellOffset+i*2]);
1287 if( pc<iCellFirst || pc>iCellLast ){
1288 return SQLITE_CORRUPT_BKPT;
1289 }
1290 sz = cellSizePtr(pPage, &data[pc]);
1291 if( pc+sz>usableSize ){
1292 return SQLITE_CORRUPT_BKPT;
1293 }
1294 }
1295 }
1296#endif
1297
danielk1977eaa06f62008-09-18 17:34:44 +00001298 /* Compute the total free space on the page */
1299 pc = get2byte(&data[hdr+1]);
danielk197793c829c2009-06-03 17:26:17 +00001300 nFree = data[hdr+7] + top;
danielk1977eaa06f62008-09-18 17:34:44 +00001301 while( pc>0 ){
drh1bd10f82008-12-10 21:19:56 +00001302 u16 next, size;
danielk1977eaa06f62008-09-18 17:34:44 +00001303 if( pc>usableSize-4 ){
1304 /* Free block is off the page */
1305 return SQLITE_CORRUPT_BKPT;
1306 }
1307 next = get2byte(&data[pc]);
1308 size = get2byte(&data[pc+2]);
1309 if( next>0 && next<=pc+size+3 ){
1310 /* Free blocks must be in accending order */
1311 return SQLITE_CORRUPT_BKPT;
1312 }
shane85095702009-06-15 16:27:08 +00001313 nFree = nFree + size;
danielk1977eaa06f62008-09-18 17:34:44 +00001314 pc = next;
1315 }
danielk197793c829c2009-06-03 17:26:17 +00001316
1317 /* At this point, nFree contains the sum of the offset to the start
1318 ** of the cell-content area plus the number of free bytes within
1319 ** the cell-content area. If this is greater than the usable-size
1320 ** of the page, then the page must be corrupted. This check also
1321 ** serves to verify that the offset to the start of the cell-content
1322 ** area, according to the page header, lies within the page.
1323 */
1324 if( nFree>usableSize ){
drh49285702005-09-17 15:20:26 +00001325 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001326 }
danielk197793c829c2009-06-03 17:26:17 +00001327 pPage->nFree = nFree - (cellOffset + 2*pPage->nCell);
drh9e572e62004-04-23 23:43:10 +00001328
drh1688c862008-07-18 02:44:17 +00001329#if 0
1330 /* Check that all the offsets in the cell offset array are within range.
1331 **
1332 ** Omitting this consistency check and using the pPage->maskPage mask
1333 ** to prevent overrunning the page buffer in findCell() results in a
1334 ** 2.5% performance gain.
1335 */
1336 {
1337 u8 *pOff; /* Iterator used to check all cell offsets are in range */
1338 u8 *pEnd; /* Pointer to end of cell offset array */
1339 u8 mask; /* Mask of bits that must be zero in MSB of cell offsets */
1340 mask = ~(((u8)(pBt->pageSize>>8))-1);
1341 pEnd = &data[cellOffset + pPage->nCell*2];
1342 for(pOff=&data[cellOffset]; pOff!=pEnd && !((*pOff)&mask); pOff+=2);
1343 if( pOff!=pEnd ){
1344 return SQLITE_CORRUPT_BKPT;
1345 }
danielk1977e16535f2008-06-11 18:15:29 +00001346 }
drh1688c862008-07-18 02:44:17 +00001347#endif
danielk1977e16535f2008-06-11 18:15:29 +00001348
danielk197771d5d2c2008-09-29 11:49:47 +00001349 pPage->isInit = 1;
1350 }
drh9e572e62004-04-23 23:43:10 +00001351 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001352}
1353
1354/*
drh8b2f49b2001-06-08 00:21:52 +00001355** Set up a raw page so that it looks like a database page holding
1356** no entries.
drhbd03cae2001-06-02 02:40:57 +00001357*/
drh9e572e62004-04-23 23:43:10 +00001358static void zeroPage(MemPage *pPage, int flags){
1359 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001360 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00001361 u8 hdr = pPage->hdrOffset;
1362 u16 first;
drh9e572e62004-04-23 23:43:10 +00001363
danielk19773b8a05f2007-03-19 17:44:26 +00001364 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drhbf4bca52007-09-06 22:19:14 +00001365 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1366 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +00001367 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00001368 assert( sqlite3_mutex_held(pBt->mutex) );
drh1af4a6e2008-07-18 03:32:51 +00001369 /*memset(&data[hdr], 0, pBt->usableSize - hdr);*/
drh1bd10f82008-12-10 21:19:56 +00001370 data[hdr] = (char)flags;
1371 first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
drh43605152004-05-29 21:46:49 +00001372 memset(&data[hdr+1], 0, 4);
1373 data[hdr+7] = 0;
1374 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +00001375 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +00001376 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +00001377 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +00001378 pPage->cellOffset = first;
1379 pPage->nOverflow = 0;
drh1688c862008-07-18 02:44:17 +00001380 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
1381 pPage->maskPage = pBt->pageSize - 1;
drh43605152004-05-29 21:46:49 +00001382 pPage->nCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001383 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00001384}
1385
drh897a8202008-09-18 01:08:15 +00001386
1387/*
1388** Convert a DbPage obtained from the pager into a MemPage used by
1389** the btree layer.
1390*/
1391static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
1392 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
1393 pPage->aData = sqlite3PagerGetData(pDbPage);
1394 pPage->pDbPage = pDbPage;
1395 pPage->pBt = pBt;
1396 pPage->pgno = pgno;
1397 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
1398 return pPage;
1399}
1400
drhbd03cae2001-06-02 02:40:57 +00001401/*
drh3aac2dd2004-04-26 14:10:20 +00001402** Get a page from the pager. Initialize the MemPage.pBt and
1403** MemPage.aData elements if needed.
drh538f5702007-04-13 02:14:30 +00001404**
1405** If the noContent flag is set, it means that we do not care about
1406** the content of the page at this time. So do not go to the disk
1407** to fetch the content. Just fill in the content with zeros for now.
1408** If in the future we call sqlite3PagerWrite() on this page, that
1409** means we have started to be concerned about content and the disk
1410** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00001411*/
drh16a9b832007-05-05 18:39:25 +00001412int sqlite3BtreeGetPage(
1413 BtShared *pBt, /* The btree */
1414 Pgno pgno, /* Number of the page to fetch */
1415 MemPage **ppPage, /* Return the page in this parameter */
1416 int noContent /* Do not load page content if true */
1417){
drh3aac2dd2004-04-26 14:10:20 +00001418 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001419 DbPage *pDbPage;
1420
drh1fee73e2007-08-29 04:00:57 +00001421 assert( sqlite3_mutex_held(pBt->mutex) );
drh538f5702007-04-13 02:14:30 +00001422 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
drh3aac2dd2004-04-26 14:10:20 +00001423 if( rc ) return rc;
drh897a8202008-09-18 01:08:15 +00001424 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
drh3aac2dd2004-04-26 14:10:20 +00001425 return SQLITE_OK;
1426}
1427
1428/*
danielk1977bea2a942009-01-20 17:06:27 +00001429** Retrieve a page from the pager cache. If the requested page is not
1430** already in the pager cache return NULL. Initialize the MemPage.pBt and
1431** MemPage.aData elements if needed.
1432*/
1433static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
1434 DbPage *pDbPage;
1435 assert( sqlite3_mutex_held(pBt->mutex) );
1436 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
1437 if( pDbPage ){
1438 return btreePageFromDbPage(pDbPage, pgno, pBt);
1439 }
1440 return 0;
1441}
1442
1443/*
danielk197789d40042008-11-17 14:20:56 +00001444** Return the size of the database file in pages. If there is any kind of
1445** error, return ((unsigned int)-1).
danielk197767fd7a92008-09-10 17:53:35 +00001446*/
danielk197789d40042008-11-17 14:20:56 +00001447static Pgno pagerPagecount(BtShared *pBt){
1448 int nPage = -1;
danielk197767fd7a92008-09-10 17:53:35 +00001449 int rc;
danielk197789d40042008-11-17 14:20:56 +00001450 assert( pBt->pPage1 );
1451 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1452 assert( rc==SQLITE_OK || nPage==-1 );
1453 return (Pgno)nPage;
danielk197767fd7a92008-09-10 17:53:35 +00001454}
1455
1456/*
drhde647132004-05-07 17:57:49 +00001457** Get a page from the pager and initialize it. This routine
1458** is just a convenience wrapper around separate calls to
drh16a9b832007-05-05 18:39:25 +00001459** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
drhde647132004-05-07 17:57:49 +00001460*/
1461static int getAndInitPage(
danielk1977aef0bf62005-12-30 16:28:01 +00001462 BtShared *pBt, /* The database file */
drhde647132004-05-07 17:57:49 +00001463 Pgno pgno, /* Number of the page to get */
danielk197771d5d2c2008-09-29 11:49:47 +00001464 MemPage **ppPage /* Write the page pointer here */
drhde647132004-05-07 17:57:49 +00001465){
1466 int rc;
drh897a8202008-09-18 01:08:15 +00001467 MemPage *pPage;
1468
drh1fee73e2007-08-29 04:00:57 +00001469 assert( sqlite3_mutex_held(pBt->mutex) );
drh897a8202008-09-18 01:08:15 +00001470 if( pgno==0 ){
drh49285702005-09-17 15:20:26 +00001471 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001472 }
danielk19779f580ad2008-09-10 14:45:57 +00001473
drh897a8202008-09-18 01:08:15 +00001474 /* It is often the case that the page we want is already in cache.
1475 ** If so, get it directly. This saves us from having to call
1476 ** pagerPagecount() to make sure pgno is within limits, which results
1477 ** in a measureable performance improvements.
1478 */
danielk1977bea2a942009-01-20 17:06:27 +00001479 *ppPage = pPage = btreePageLookup(pBt, pgno);
1480 if( pPage ){
drh897a8202008-09-18 01:08:15 +00001481 /* Page is already in cache */
drh897a8202008-09-18 01:08:15 +00001482 rc = SQLITE_OK;
1483 }else{
1484 /* Page not in cache. Acquire it. */
danielk197789d40042008-11-17 14:20:56 +00001485 if( pgno>pagerPagecount(pBt) ){
drh897a8202008-09-18 01:08:15 +00001486 return SQLITE_CORRUPT_BKPT;
1487 }
1488 rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
1489 if( rc ) return rc;
1490 pPage = *ppPage;
1491 }
danielk197771d5d2c2008-09-29 11:49:47 +00001492 if( !pPage->isInit ){
1493 rc = sqlite3BtreeInitPage(pPage);
drh897a8202008-09-18 01:08:15 +00001494 }
1495 if( rc!=SQLITE_OK ){
1496 releasePage(pPage);
1497 *ppPage = 0;
1498 }
drhde647132004-05-07 17:57:49 +00001499 return rc;
1500}
1501
1502/*
drh3aac2dd2004-04-26 14:10:20 +00001503** Release a MemPage. This should be called once for each prior
drh16a9b832007-05-05 18:39:25 +00001504** call to sqlite3BtreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +00001505*/
drh4b70f112004-05-02 21:12:19 +00001506static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001507 if( pPage ){
drh30df0092008-12-23 15:58:06 +00001508 assert( pPage->nOverflow==0 || sqlite3PagerPageRefcount(pPage->pDbPage)>1 );
drh3aac2dd2004-04-26 14:10:20 +00001509 assert( pPage->aData );
1510 assert( pPage->pBt );
drhbf4bca52007-09-06 22:19:14 +00001511 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1512 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
drh1fee73e2007-08-29 04:00:57 +00001513 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001514 sqlite3PagerUnref(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00001515 }
1516}
1517
1518/*
drha6abd042004-06-09 17:37:22 +00001519** During a rollback, when the pager reloads information into the cache
1520** so that the cache is restored to its original state at the start of
1521** the transaction, for each page restored this routine is called.
1522**
1523** This routine needs to reset the extra data section at the end of the
1524** page to agree with the restored data.
1525*/
danielk1977eaa06f62008-09-18 17:34:44 +00001526static void pageReinit(DbPage *pData){
drh07d183d2005-05-01 22:52:42 +00001527 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00001528 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
danielk1977d217e6f2009-04-01 17:13:51 +00001529 assert( sqlite3PagerPageRefcount(pData)>0 );
danielk197771d5d2c2008-09-29 11:49:47 +00001530 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00001531 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00001532 pPage->isInit = 0;
danielk1977d217e6f2009-04-01 17:13:51 +00001533 if( sqlite3PagerPageRefcount(pData)>1 ){
drh5e8d8872009-03-30 17:19:48 +00001534 /* pPage might not be a btree page; it might be an overflow page
1535 ** or ptrmap page or a free page. In those cases, the following
1536 ** call to sqlite3BtreeInitPage() will likely return SQLITE_CORRUPT.
1537 ** But no harm is done by this. And it is very important that
1538 ** sqlite3BtreeInitPage() be called on every btree page so we make
1539 ** the call for every page that comes in for re-initing. */
danielk197771d5d2c2008-09-29 11:49:47 +00001540 sqlite3BtreeInitPage(pPage);
1541 }
drha6abd042004-06-09 17:37:22 +00001542 }
1543}
1544
1545/*
drhe5fe6902007-12-07 18:55:28 +00001546** Invoke the busy handler for a btree.
1547*/
danielk19771ceedd32008-11-19 10:22:33 +00001548static int btreeInvokeBusyHandler(void *pArg){
drhe5fe6902007-12-07 18:55:28 +00001549 BtShared *pBt = (BtShared*)pArg;
1550 assert( pBt->db );
1551 assert( sqlite3_mutex_held(pBt->db->mutex) );
1552 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
1553}
1554
1555/*
drhad3e0102004-09-03 23:32:18 +00001556** Open a database file.
1557**
drh382c0242001-10-06 16:33:02 +00001558** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001559** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001560** database file will be deleted when sqlite3BtreeClose() is called.
drhe53831d2007-08-17 01:14:38 +00001561** If zFilename is ":memory:" then an in-memory database is created
1562** that is automatically destroyed when it is closed.
drhc47fd8e2009-04-30 13:30:32 +00001563**
1564** If the database is already opened in the same database connection
1565** and we are in shared cache mode, then the open will fail with an
1566** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
1567** objects in the same database connection since doing so will lead
1568** to problems with locking.
drha059ad02001-04-17 20:09:11 +00001569*/
drh23e11ca2004-05-04 17:27:28 +00001570int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001571 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00001572 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001573 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00001574 int flags, /* Options */
1575 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00001576){
drh7555d8e2009-03-20 13:15:30 +00001577 sqlite3_vfs *pVfs; /* The VFS to use for this btree */
1578 BtShared *pBt = 0; /* Shared part of btree structure */
1579 Btree *p; /* Handle to return */
1580 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
1581 int rc = SQLITE_OK; /* Result code from this function */
1582 u8 nReserve; /* Byte of unused space on each page */
1583 unsigned char zDbHeader[100]; /* Database header content */
danielk1977aef0bf62005-12-30 16:28:01 +00001584
1585 /* Set the variable isMemdb to true for an in-memory database, or
1586 ** false for a file-based database. This symbol is only required if
1587 ** either of the shared-data or autovacuum features are compiled
1588 ** into the library.
1589 */
1590#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
1591 #ifdef SQLITE_OMIT_MEMORYDB
drh980b1a72006-08-16 16:42:48 +00001592 const int isMemdb = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00001593 #else
drh980b1a72006-08-16 16:42:48 +00001594 const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
danielk1977aef0bf62005-12-30 16:28:01 +00001595 #endif
1596#endif
1597
drhe5fe6902007-12-07 18:55:28 +00001598 assert( db!=0 );
1599 assert( sqlite3_mutex_held(db->mutex) );
drh153c62c2007-08-24 03:51:33 +00001600
drhe5fe6902007-12-07 18:55:28 +00001601 pVfs = db->pVfs;
drh17435752007-08-16 04:30:38 +00001602 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00001603 if( !p ){
1604 return SQLITE_NOMEM;
1605 }
1606 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00001607 p->db = db;
danielk1977aef0bf62005-12-30 16:28:01 +00001608
drh198bf392006-01-06 21:52:49 +00001609#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001610 /*
1611 ** If this Btree is a candidate for shared cache, try to find an
1612 ** existing BtShared object that we can share with
1613 */
danielk197720c6cc22009-04-01 18:03:00 +00001614 if( isMemdb==0 && zFilename && zFilename[0] ){
danielk1977502b4e02008-09-02 14:07:24 +00001615 if( sqlite3GlobalConfig.sharedCacheEnabled ){
danielk1977adfb9b02007-09-17 07:02:56 +00001616 int nFullPathname = pVfs->mxPathname+1;
drhe5ae5732008-06-15 02:51:47 +00001617 char *zFullPathname = sqlite3Malloc(nFullPathname);
drhff0587c2007-08-29 17:43:19 +00001618 sqlite3_mutex *mutexShared;
1619 p->sharable = 1;
drh34004ce2008-07-11 16:15:17 +00001620 db->flags |= SQLITE_SharedCache;
drhff0587c2007-08-29 17:43:19 +00001621 if( !zFullPathname ){
1622 sqlite3_free(p);
1623 return SQLITE_NOMEM;
1624 }
danielk1977adfb9b02007-09-17 07:02:56 +00001625 sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
drh7555d8e2009-03-20 13:15:30 +00001626 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
1627 sqlite3_mutex_enter(mutexOpen);
danielk197759f8c082008-06-18 17:09:10 +00001628 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhff0587c2007-08-29 17:43:19 +00001629 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001630 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
drhff0587c2007-08-29 17:43:19 +00001631 assert( pBt->nRef>0 );
1632 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
1633 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
drhc47fd8e2009-04-30 13:30:32 +00001634 int iDb;
1635 for(iDb=db->nDb-1; iDb>=0; iDb--){
1636 Btree *pExisting = db->aDb[iDb].pBt;
1637 if( pExisting && pExisting->pBt==pBt ){
1638 sqlite3_mutex_leave(mutexShared);
1639 sqlite3_mutex_leave(mutexOpen);
1640 sqlite3_free(zFullPathname);
1641 sqlite3_free(p);
1642 return SQLITE_CONSTRAINT;
1643 }
1644 }
drhff0587c2007-08-29 17:43:19 +00001645 p->pBt = pBt;
1646 pBt->nRef++;
1647 break;
1648 }
1649 }
1650 sqlite3_mutex_leave(mutexShared);
1651 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00001652 }
drhff0587c2007-08-29 17:43:19 +00001653#ifdef SQLITE_DEBUG
1654 else{
1655 /* In debug mode, we mark all persistent databases as sharable
1656 ** even when they are not. This exercises the locking code and
1657 ** gives more opportunity for asserts(sqlite3_mutex_held())
1658 ** statements to find locking problems.
1659 */
1660 p->sharable = 1;
1661 }
1662#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001663 }
1664#endif
drha059ad02001-04-17 20:09:11 +00001665 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00001666 /*
1667 ** The following asserts make sure that structures used by the btree are
1668 ** the right size. This is to guard against size changes that result
1669 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00001670 */
drhe53831d2007-08-17 01:14:38 +00001671 assert( sizeof(i64)==8 || sizeof(i64)==4 );
1672 assert( sizeof(u64)==8 || sizeof(u64)==4 );
1673 assert( sizeof(u32)==4 );
1674 assert( sizeof(u16)==2 );
1675 assert( sizeof(Pgno)==4 );
1676
1677 pBt = sqlite3MallocZero( sizeof(*pBt) );
1678 if( pBt==0 ){
1679 rc = SQLITE_NOMEM;
1680 goto btree_open_out;
1681 }
danielk197771d5d2c2008-09-29 11:49:47 +00001682 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
drh33f4e022007-09-03 15:19:34 +00001683 EXTRA_SIZE, flags, vfsFlags);
drhe53831d2007-08-17 01:14:38 +00001684 if( rc==SQLITE_OK ){
1685 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
1686 }
1687 if( rc!=SQLITE_OK ){
1688 goto btree_open_out;
1689 }
danielk19772a50ff02009-04-10 09:47:06 +00001690 pBt->db = db;
danielk19771ceedd32008-11-19 10:22:33 +00001691 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
drhe53831d2007-08-17 01:14:38 +00001692 p->pBt = pBt;
1693
drhe53831d2007-08-17 01:14:38 +00001694 sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
1695 pBt->pCursor = 0;
1696 pBt->pPage1 = 0;
1697 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
1698 pBt->pageSize = get2byte(&zDbHeader[16]);
1699 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1700 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00001701 pBt->pageSize = 0;
drhe53831d2007-08-17 01:14:38 +00001702#ifndef SQLITE_OMIT_AUTOVACUUM
1703 /* If the magic name ":memory:" will create an in-memory database, then
1704 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
1705 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
1706 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
1707 ** regular file-name. In this case the auto-vacuum applies as per normal.
1708 */
1709 if( zFilename && !isMemdb ){
1710 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
1711 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
1712 }
1713#endif
1714 nReserve = 0;
1715 }else{
1716 nReserve = zDbHeader[20];
drhe53831d2007-08-17 01:14:38 +00001717 pBt->pageSizeFixed = 1;
1718#ifndef SQLITE_OMIT_AUTOVACUUM
1719 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1720 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
1721#endif
1722 }
drhfa9601a2009-06-18 17:22:39 +00001723 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhc0b61812009-04-30 01:22:41 +00001724 if( rc ) goto btree_open_out;
drhe53831d2007-08-17 01:14:38 +00001725 pBt->usableSize = pBt->pageSize - nReserve;
1726 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
drhe53831d2007-08-17 01:14:38 +00001727
1728#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1729 /* Add the new BtShared object to the linked list sharable BtShareds.
1730 */
1731 if( p->sharable ){
1732 sqlite3_mutex *mutexShared;
1733 pBt->nRef = 1;
danielk197759f8c082008-06-18 17:09:10 +00001734 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
danielk1977075c23a2008-09-01 18:34:20 +00001735 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
danielk197759f8c082008-06-18 17:09:10 +00001736 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
drh3285db22007-09-03 22:00:39 +00001737 if( pBt->mutex==0 ){
1738 rc = SQLITE_NOMEM;
drhe5fe6902007-12-07 18:55:28 +00001739 db->mallocFailed = 0;
drh3285db22007-09-03 22:00:39 +00001740 goto btree_open_out;
1741 }
drhff0587c2007-08-29 17:43:19 +00001742 }
drhe53831d2007-08-17 01:14:38 +00001743 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001744 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
1745 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
drhe53831d2007-08-17 01:14:38 +00001746 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00001747 }
drheee46cf2004-11-06 00:02:48 +00001748#endif
drh90f5ecb2004-07-22 01:19:35 +00001749 }
danielk1977aef0bf62005-12-30 16:28:01 +00001750
drhcfed7bc2006-03-13 14:28:05 +00001751#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001752 /* If the new Btree uses a sharable pBtShared, then link the new
1753 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00001754 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00001755 */
drhe53831d2007-08-17 01:14:38 +00001756 if( p->sharable ){
1757 int i;
1758 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00001759 for(i=0; i<db->nDb; i++){
1760 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00001761 while( pSib->pPrev ){ pSib = pSib->pPrev; }
1762 if( p->pBt<pSib->pBt ){
1763 p->pNext = pSib;
1764 p->pPrev = 0;
1765 pSib->pPrev = p;
1766 }else{
drhabddb0c2007-08-20 13:14:28 +00001767 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
drhe53831d2007-08-17 01:14:38 +00001768 pSib = pSib->pNext;
1769 }
1770 p->pNext = pSib->pNext;
1771 p->pPrev = pSib;
1772 if( p->pNext ){
1773 p->pNext->pPrev = p;
1774 }
1775 pSib->pNext = p;
1776 }
1777 break;
1778 }
1779 }
danielk1977aef0bf62005-12-30 16:28:01 +00001780 }
danielk1977aef0bf62005-12-30 16:28:01 +00001781#endif
1782 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00001783
1784btree_open_out:
1785 if( rc!=SQLITE_OK ){
1786 if( pBt && pBt->pPager ){
1787 sqlite3PagerClose(pBt->pPager);
1788 }
drh17435752007-08-16 04:30:38 +00001789 sqlite3_free(pBt);
1790 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00001791 *ppBtree = 0;
1792 }
drh7555d8e2009-03-20 13:15:30 +00001793 if( mutexOpen ){
1794 assert( sqlite3_mutex_held(mutexOpen) );
1795 sqlite3_mutex_leave(mutexOpen);
1796 }
danielk1977dddbcdc2007-04-26 14:42:34 +00001797 return rc;
drha059ad02001-04-17 20:09:11 +00001798}
1799
1800/*
drhe53831d2007-08-17 01:14:38 +00001801** Decrement the BtShared.nRef counter. When it reaches zero,
1802** remove the BtShared structure from the sharing list. Return
1803** true if the BtShared.nRef counter reaches zero and return
1804** false if it is still positive.
1805*/
1806static int removeFromSharingList(BtShared *pBt){
1807#ifndef SQLITE_OMIT_SHARED_CACHE
1808 sqlite3_mutex *pMaster;
1809 BtShared *pList;
1810 int removed = 0;
1811
drhd677b3d2007-08-20 22:48:41 +00001812 assert( sqlite3_mutex_notheld(pBt->mutex) );
danielk197759f8c082008-06-18 17:09:10 +00001813 pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhe53831d2007-08-17 01:14:38 +00001814 sqlite3_mutex_enter(pMaster);
1815 pBt->nRef--;
1816 if( pBt->nRef<=0 ){
drh78f82d12008-09-02 00:52:52 +00001817 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
1818 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
drhe53831d2007-08-17 01:14:38 +00001819 }else{
drh78f82d12008-09-02 00:52:52 +00001820 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
drh34004ce2008-07-11 16:15:17 +00001821 while( ALWAYS(pList) && pList->pNext!=pBt ){
drhe53831d2007-08-17 01:14:38 +00001822 pList=pList->pNext;
1823 }
drh34004ce2008-07-11 16:15:17 +00001824 if( ALWAYS(pList) ){
drhe53831d2007-08-17 01:14:38 +00001825 pList->pNext = pBt->pNext;
1826 }
1827 }
drh3285db22007-09-03 22:00:39 +00001828 if( SQLITE_THREADSAFE ){
1829 sqlite3_mutex_free(pBt->mutex);
1830 }
drhe53831d2007-08-17 01:14:38 +00001831 removed = 1;
1832 }
1833 sqlite3_mutex_leave(pMaster);
1834 return removed;
1835#else
1836 return 1;
1837#endif
1838}
1839
1840/*
drhf7141992008-06-19 00:16:08 +00001841** Make sure pBt->pTmpSpace points to an allocation of
1842** MX_CELL_SIZE(pBt) bytes.
1843*/
1844static void allocateTempSpace(BtShared *pBt){
1845 if( !pBt->pTmpSpace ){
1846 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
1847 }
1848}
1849
1850/*
1851** Free the pBt->pTmpSpace allocation
1852*/
1853static void freeTempSpace(BtShared *pBt){
1854 sqlite3PageFree( pBt->pTmpSpace);
1855 pBt->pTmpSpace = 0;
1856}
1857
1858/*
drha059ad02001-04-17 20:09:11 +00001859** Close an open database and invalidate all cursors.
1860*/
danielk1977aef0bf62005-12-30 16:28:01 +00001861int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00001862 BtShared *pBt = p->pBt;
1863 BtCursor *pCur;
1864
danielk1977aef0bf62005-12-30 16:28:01 +00001865 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00001866 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00001867 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001868 pCur = pBt->pCursor;
1869 while( pCur ){
1870 BtCursor *pTmp = pCur;
1871 pCur = pCur->pNext;
1872 if( pTmp->pBtree==p ){
1873 sqlite3BtreeCloseCursor(pTmp);
1874 }
drha059ad02001-04-17 20:09:11 +00001875 }
danielk1977aef0bf62005-12-30 16:28:01 +00001876
danielk19778d34dfd2006-01-24 16:37:57 +00001877 /* Rollback any active transaction and free the handle structure.
1878 ** The call to sqlite3BtreeRollback() drops any table-locks held by
1879 ** this handle.
1880 */
danielk1977b597f742006-01-15 11:39:18 +00001881 sqlite3BtreeRollback(p);
drhe53831d2007-08-17 01:14:38 +00001882 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001883
danielk1977aef0bf62005-12-30 16:28:01 +00001884 /* If there are still other outstanding references to the shared-btree
1885 ** structure, return now. The remainder of this procedure cleans
1886 ** up the shared-btree.
1887 */
drhe53831d2007-08-17 01:14:38 +00001888 assert( p->wantToLock==0 && p->locked==0 );
1889 if( !p->sharable || removeFromSharingList(pBt) ){
1890 /* The pBt is no longer on the sharing list, so we can access
1891 ** it without having to hold the mutex.
1892 **
1893 ** Clean out and delete the BtShared object.
1894 */
1895 assert( !pBt->pCursor );
drhe53831d2007-08-17 01:14:38 +00001896 sqlite3PagerClose(pBt->pPager);
1897 if( pBt->xFreeSchema && pBt->pSchema ){
1898 pBt->xFreeSchema(pBt->pSchema);
1899 }
1900 sqlite3_free(pBt->pSchema);
drhf7141992008-06-19 00:16:08 +00001901 freeTempSpace(pBt);
drh65bbf292008-06-19 01:03:17 +00001902 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00001903 }
1904
drhe53831d2007-08-17 01:14:38 +00001905#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00001906 assert( p->wantToLock==0 );
1907 assert( p->locked==0 );
1908 if( p->pPrev ) p->pPrev->pNext = p->pNext;
1909 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00001910#endif
1911
drhe53831d2007-08-17 01:14:38 +00001912 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00001913 return SQLITE_OK;
1914}
1915
1916/*
drhda47d772002-12-02 04:25:19 +00001917** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001918**
1919** The maximum number of cache pages is set to the absolute
1920** value of mxPage. If mxPage is negative, the pager will
1921** operate asynchronously - it will not stop to do fsync()s
1922** to insure data is written to the disk surface before
1923** continuing. Transactions still work if synchronous is off,
1924** and the database cannot be corrupted if this program
1925** crashes. But if the operating system crashes or there is
1926** an abrupt power failure when synchronous is off, the database
1927** could be left in an inconsistent and unrecoverable state.
1928** Synchronous is on by default so database corruption is not
1929** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001930*/
danielk1977aef0bf62005-12-30 16:28:01 +00001931int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
1932 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001933 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001934 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001935 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00001936 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00001937 return SQLITE_OK;
1938}
1939
1940/*
drh973b6e32003-02-12 14:09:42 +00001941** Change the way data is synced to disk in order to increase or decrease
1942** how well the database resists damage due to OS crashes and power
1943** failures. Level 1 is the same as asynchronous (no syncs() occur and
1944** there is a high probability of damage) Level 2 is the default. There
1945** is a very low but non-zero probability of damage. Level 3 reduces the
1946** probability of damage to near zero but with a write performance reduction.
1947*/
danielk197793758c82005-01-21 08:13:14 +00001948#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drhac530b12006-02-11 01:25:50 +00001949int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
danielk1977aef0bf62005-12-30 16:28:01 +00001950 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001951 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001952 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001953 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
drhd677b3d2007-08-20 22:48:41 +00001954 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00001955 return SQLITE_OK;
1956}
danielk197793758c82005-01-21 08:13:14 +00001957#endif
drh973b6e32003-02-12 14:09:42 +00001958
drh2c8997b2005-08-27 16:36:48 +00001959/*
1960** Return TRUE if the given btree is set to safety level 1. In other
1961** words, return TRUE if no sync() occurs on the disk files.
1962*/
danielk1977aef0bf62005-12-30 16:28:01 +00001963int sqlite3BtreeSyncDisabled(Btree *p){
1964 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001965 int rc;
drhe5fe6902007-12-07 18:55:28 +00001966 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001967 sqlite3BtreeEnter(p);
drhd0679ed2007-08-28 22:24:34 +00001968 assert( pBt && pBt->pPager );
drhd677b3d2007-08-20 22:48:41 +00001969 rc = sqlite3PagerNosync(pBt->pPager);
1970 sqlite3BtreeLeave(p);
1971 return rc;
drh2c8997b2005-08-27 16:36:48 +00001972}
1973
danielk1977576ec6b2005-01-21 11:55:25 +00001974#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00001975/*
drh90f5ecb2004-07-22 01:19:35 +00001976** Change the default pages size and the number of reserved bytes per page.
drhce4869f2009-04-02 20:16:58 +00001977** Or, if the page size has already been fixed, return SQLITE_READONLY
1978** without changing anything.
drh06f50212004-11-02 14:24:33 +00001979**
1980** The page size must be a power of 2 between 512 and 65536. If the page
1981** size supplied does not meet this constraint then the page size is not
1982** changed.
1983**
1984** Page sizes are constrained to be a power of two so that the region
1985** of the database file used for locking (beginning at PENDING_BYTE,
1986** the first byte past the 1GB boundary, 0x40000000) needs to occur
1987** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001988**
1989** If parameter nReserve is less than zero, then the number of reserved
1990** bytes per page is left unchanged.
drhce4869f2009-04-02 20:16:58 +00001991**
1992** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
1993** and autovacuum mode can no longer be changed.
drh90f5ecb2004-07-22 01:19:35 +00001994*/
drhce4869f2009-04-02 20:16:58 +00001995int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
danielk1977a1644fd2007-08-29 12:31:25 +00001996 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00001997 BtShared *pBt = p->pBt;
drhf49661a2008-12-10 16:45:50 +00001998 assert( nReserve>=-1 && nReserve<=255 );
drhd677b3d2007-08-20 22:48:41 +00001999 sqlite3BtreeEnter(p);
drh90f5ecb2004-07-22 01:19:35 +00002000 if( pBt->pageSizeFixed ){
drhd677b3d2007-08-20 22:48:41 +00002001 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00002002 return SQLITE_READONLY;
2003 }
2004 if( nReserve<0 ){
2005 nReserve = pBt->pageSize - pBt->usableSize;
2006 }
drhf49661a2008-12-10 16:45:50 +00002007 assert( nReserve>=0 && nReserve<=255 );
drh06f50212004-11-02 14:24:33 +00002008 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2009 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00002010 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002011 assert( !pBt->pPage1 && !pBt->pCursor );
drh1bd10f82008-12-10 21:19:56 +00002012 pBt->pageSize = (u16)pageSize;
drhf7141992008-06-19 00:16:08 +00002013 freeTempSpace(pBt);
drh90f5ecb2004-07-22 01:19:35 +00002014 }
drhfa9601a2009-06-18 17:22:39 +00002015 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhf49661a2008-12-10 16:45:50 +00002016 pBt->usableSize = pBt->pageSize - (u16)nReserve;
drhce4869f2009-04-02 20:16:58 +00002017 if( iFix ) pBt->pageSizeFixed = 1;
drhd677b3d2007-08-20 22:48:41 +00002018 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00002019 return rc;
drh90f5ecb2004-07-22 01:19:35 +00002020}
2021
2022/*
2023** Return the currently defined page size
2024*/
danielk1977aef0bf62005-12-30 16:28:01 +00002025int sqlite3BtreeGetPageSize(Btree *p){
2026 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00002027}
drh7f751222009-03-17 22:33:00 +00002028
2029/*
2030** Return the number of bytes of space at the end of every page that
2031** are intentually left unused. This is the "reserved" space that is
2032** sometimes used by extensions.
2033*/
danielk1977aef0bf62005-12-30 16:28:01 +00002034int sqlite3BtreeGetReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002035 int n;
2036 sqlite3BtreeEnter(p);
2037 n = p->pBt->pageSize - p->pBt->usableSize;
2038 sqlite3BtreeLeave(p);
2039 return n;
drh2011d5f2004-07-22 02:40:37 +00002040}
drhf8e632b2007-05-08 14:51:36 +00002041
2042/*
2043** Set the maximum page count for a database if mxPage is positive.
2044** No changes are made if mxPage is 0 or negative.
2045** Regardless of the value of mxPage, return the maximum page count.
2046*/
2047int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00002048 int n;
2049 sqlite3BtreeEnter(p);
2050 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
2051 sqlite3BtreeLeave(p);
2052 return n;
drhf8e632b2007-05-08 14:51:36 +00002053}
danielk1977576ec6b2005-01-21 11:55:25 +00002054#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00002055
2056/*
danielk1977951af802004-11-05 15:45:09 +00002057** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
2058** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
2059** is disabled. The default value for the auto-vacuum property is
2060** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
2061*/
danielk1977aef0bf62005-12-30 16:28:01 +00002062int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00002063#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002064 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00002065#else
danielk1977dddbcdc2007-04-26 14:42:34 +00002066 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002067 int rc = SQLITE_OK;
drh076d4662009-02-18 20:31:18 +00002068 u8 av = (u8)autoVacuum;
drhd677b3d2007-08-20 22:48:41 +00002069
2070 sqlite3BtreeEnter(p);
drh076d4662009-02-18 20:31:18 +00002071 if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002072 rc = SQLITE_READONLY;
2073 }else{
drh076d4662009-02-18 20:31:18 +00002074 pBt->autoVacuum = av ?1:0;
2075 pBt->incrVacuum = av==2 ?1:0;
danielk1977951af802004-11-05 15:45:09 +00002076 }
drhd677b3d2007-08-20 22:48:41 +00002077 sqlite3BtreeLeave(p);
2078 return rc;
danielk1977951af802004-11-05 15:45:09 +00002079#endif
2080}
2081
2082/*
2083** Return the value of the 'auto-vacuum' property. If auto-vacuum is
2084** enabled 1 is returned. Otherwise 0.
2085*/
danielk1977aef0bf62005-12-30 16:28:01 +00002086int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00002087#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002088 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00002089#else
drhd677b3d2007-08-20 22:48:41 +00002090 int rc;
2091 sqlite3BtreeEnter(p);
2092 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00002093 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
2094 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
2095 BTREE_AUTOVACUUM_INCR
2096 );
drhd677b3d2007-08-20 22:48:41 +00002097 sqlite3BtreeLeave(p);
2098 return rc;
danielk1977951af802004-11-05 15:45:09 +00002099#endif
2100}
2101
2102
2103/*
drha34b6762004-05-07 13:30:42 +00002104** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00002105** also acquire a readlock on that file.
2106**
2107** SQLITE_OK is returned on success. If the file is not a
2108** well-formed database file, then SQLITE_CORRUPT is returned.
2109** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00002110** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00002111*/
danielk1977aef0bf62005-12-30 16:28:01 +00002112static int lockBtree(BtShared *pBt){
danielk1977f653d782008-03-20 11:04:21 +00002113 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002114 MemPage *pPage1;
danielk197793f7af92008-05-09 16:57:50 +00002115 int nPage;
drhd677b3d2007-08-20 22:48:41 +00002116
drh1fee73e2007-08-29 04:00:57 +00002117 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977295dc102009-04-01 19:07:03 +00002118 assert( pBt->pPage1==0 );
drh16a9b832007-05-05 18:39:25 +00002119 rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00002120 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00002121
2122 /* Do some checking to help insure the file we opened really is
2123 ** a valid database file.
2124 */
danielk1977ad0132d2008-06-07 08:58:22 +00002125 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
2126 if( rc!=SQLITE_OK ){
danielk197793f7af92008-05-09 16:57:50 +00002127 goto page1_init_failed;
2128 }else if( nPage>0 ){
danielk1977f653d782008-03-20 11:04:21 +00002129 int pageSize;
2130 int usableSize;
drhb6f41482004-05-14 01:58:11 +00002131 u8 *page1 = pPage1->aData;
danielk1977ad0132d2008-06-07 08:58:22 +00002132 rc = SQLITE_NOTADB;
drhb6f41482004-05-14 01:58:11 +00002133 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00002134 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00002135 }
drh309169a2007-04-24 17:27:51 +00002136 if( page1[18]>1 ){
2137 pBt->readOnly = 1;
2138 }
2139 if( page1[19]>1 ){
drhb6f41482004-05-14 01:58:11 +00002140 goto page1_init_failed;
2141 }
drhe5ae5732008-06-15 02:51:47 +00002142
2143 /* The maximum embedded fraction must be exactly 25%. And the minimum
2144 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
2145 ** The original design allowed these amounts to vary, but as of
2146 ** version 3.6.0, we require them to be fixed.
2147 */
2148 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
2149 goto page1_init_failed;
2150 }
drh07d183d2005-05-01 22:52:42 +00002151 pageSize = get2byte(&page1[16]);
drh7dc385e2007-09-06 23:39:36 +00002152 if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
2153 (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
2154 ){
drh07d183d2005-05-01 22:52:42 +00002155 goto page1_init_failed;
2156 }
2157 assert( (pageSize & 7)==0 );
danielk1977f653d782008-03-20 11:04:21 +00002158 usableSize = pageSize - page1[20];
2159 if( pageSize!=pBt->pageSize ){
2160 /* After reading the first page of the database assuming a page size
2161 ** of BtShared.pageSize, we have discovered that the page-size is
2162 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
2163 ** zero and return SQLITE_OK. The caller will call this function
2164 ** again with the correct page-size.
2165 */
2166 releasePage(pPage1);
drhf49661a2008-12-10 16:45:50 +00002167 pBt->usableSize = (u16)usableSize;
2168 pBt->pageSize = (u16)pageSize;
drhf7141992008-06-19 00:16:08 +00002169 freeTempSpace(pBt);
drhfa9601a2009-06-18 17:22:39 +00002170 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
2171 pageSize-usableSize);
drhc0b61812009-04-30 01:22:41 +00002172 if( rc ) goto page1_init_failed;
danielk1977f653d782008-03-20 11:04:21 +00002173 return SQLITE_OK;
2174 }
drhb33e1b92009-06-18 11:29:20 +00002175 if( usableSize<480 ){
drhb6f41482004-05-14 01:58:11 +00002176 goto page1_init_failed;
2177 }
drh1bd10f82008-12-10 21:19:56 +00002178 pBt->pageSize = (u16)pageSize;
2179 pBt->usableSize = (u16)usableSize;
drh057cd3a2005-02-15 16:23:02 +00002180#ifndef SQLITE_OMIT_AUTOVACUUM
2181 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00002182 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00002183#endif
drh306dc212001-05-21 13:45:10 +00002184 }
drhb6f41482004-05-14 01:58:11 +00002185
2186 /* maxLocal is the maximum amount of payload to store locally for
2187 ** a cell. Make sure it is small enough so that at least minFanout
2188 ** cells can will fit on one page. We assume a 10-byte page header.
2189 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00002190 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00002191 ** 4-byte child pointer
2192 ** 9-byte nKey value
2193 ** 4-byte nData value
2194 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00002195 ** So a cell consists of a 2-byte poiner, a header which is as much as
2196 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
2197 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00002198 */
drhe5ae5732008-06-15 02:51:47 +00002199 pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
2200 pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
drh43605152004-05-29 21:46:49 +00002201 pBt->maxLeaf = pBt->usableSize - 35;
drhe5ae5732008-06-15 02:51:47 +00002202 pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
drh2e38c322004-09-03 18:38:44 +00002203 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00002204 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00002205 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00002206
drh72f82862001-05-24 21:06:34 +00002207page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00002208 releasePage(pPage1);
2209 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00002210 return rc;
drh306dc212001-05-21 13:45:10 +00002211}
2212
2213/*
drhb8ef32c2005-03-14 02:01:49 +00002214** This routine works like lockBtree() except that it also invokes the
2215** busy callback if there is lock contention.
2216*/
danielk1977aef0bf62005-12-30 16:28:01 +00002217static int lockBtreeWithRetry(Btree *pRef){
drhb8ef32c2005-03-14 02:01:49 +00002218 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00002219
drh1fee73e2007-08-29 04:00:57 +00002220 assert( sqlite3BtreeHoldsMutex(pRef) );
danielk1977aef0bf62005-12-30 16:28:01 +00002221 if( pRef->inTrans==TRANS_NONE ){
2222 u8 inTransaction = pRef->pBt->inTransaction;
2223 btreeIntegrity(pRef);
2224 rc = sqlite3BtreeBeginTrans(pRef, 0);
2225 pRef->pBt->inTransaction = inTransaction;
2226 pRef->inTrans = TRANS_NONE;
2227 if( rc==SQLITE_OK ){
2228 pRef->pBt->nTransaction--;
2229 }
2230 btreeIntegrity(pRef);
drhb8ef32c2005-03-14 02:01:49 +00002231 }
2232 return rc;
2233}
2234
2235
2236/*
drhb8ca3072001-12-05 00:21:20 +00002237** If there are no outstanding cursors and we are not in the middle
2238** of a transaction but there is a read lock on the database, then
2239** this routine unrefs the first page of the database file which
2240** has the effect of releasing the read lock.
2241**
2242** If there are any outstanding cursors, this routine is a no-op.
2243**
2244** If there is a transaction in progress, this routine is a no-op.
2245*/
danielk1977aef0bf62005-12-30 16:28:01 +00002246static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00002247 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00002248 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
danielk1977c1761e82009-06-25 09:40:03 +00002249 assert( pBt->pPage1->aData );
2250 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
2251 assert( pBt->pPage1->aData );
2252 releasePage(pBt->pPage1);
drh3aac2dd2004-04-26 14:10:20 +00002253 pBt->pPage1 = 0;
drhb8ca3072001-12-05 00:21:20 +00002254 }
2255}
2256
2257/*
drh9e572e62004-04-23 23:43:10 +00002258** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00002259** file.
drh8b2f49b2001-06-08 00:21:52 +00002260*/
danielk1977aef0bf62005-12-30 16:28:01 +00002261static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00002262 MemPage *pP1;
2263 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00002264 int rc;
danielk1977ad0132d2008-06-07 08:58:22 +00002265 int nPage;
drhd677b3d2007-08-20 22:48:41 +00002266
drh1fee73e2007-08-29 04:00:57 +00002267 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977ad0132d2008-06-07 08:58:22 +00002268 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
2269 if( rc!=SQLITE_OK || nPage>0 ){
2270 return rc;
2271 }
drh3aac2dd2004-04-26 14:10:20 +00002272 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00002273 assert( pP1!=0 );
2274 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00002275 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00002276 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00002277 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
2278 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00002279 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00002280 data[18] = 1;
2281 data[19] = 1;
drhf49661a2008-12-10 16:45:50 +00002282 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
2283 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
drhe5ae5732008-06-15 02:51:47 +00002284 data[21] = 64;
2285 data[22] = 32;
2286 data[23] = 32;
drhb6f41482004-05-14 01:58:11 +00002287 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00002288 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00002289 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00002290#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002291 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00002292 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00002293 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00002294 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00002295#endif
drh8b2f49b2001-06-08 00:21:52 +00002296 return SQLITE_OK;
2297}
2298
2299/*
danielk1977ee5741e2004-05-31 10:01:34 +00002300** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00002301** is started if the second argument is nonzero, otherwise a read-
2302** transaction. If the second argument is 2 or more and exclusive
2303** transaction is started, meaning that no other process is allowed
2304** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00002305** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00002306** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00002307**
danielk1977ee5741e2004-05-31 10:01:34 +00002308** A write-transaction must be started before attempting any
2309** changes to the database. None of the following routines
2310** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00002311**
drh23e11ca2004-05-04 17:27:28 +00002312** sqlite3BtreeCreateTable()
2313** sqlite3BtreeCreateIndex()
2314** sqlite3BtreeClearTable()
2315** sqlite3BtreeDropTable()
2316** sqlite3BtreeInsert()
2317** sqlite3BtreeDelete()
2318** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00002319**
drhb8ef32c2005-03-14 02:01:49 +00002320** If an initial attempt to acquire the lock fails because of lock contention
2321** and the database was previously unlocked, then invoke the busy handler
2322** if there is one. But if there was previously a read-lock, do not
2323** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
2324** returned when there is already a read-lock in order to avoid a deadlock.
2325**
2326** Suppose there are two processes A and B. A has a read lock and B has
2327** a reserved lock. B tries to promote to exclusive but is blocked because
2328** of A's read lock. A tries to promote to reserved but is blocked by B.
2329** One or the other of the two processes must give way or there can be
2330** no progress. By returning SQLITE_BUSY and not invoking the busy callback
2331** when A already has a read lock, we encourage A to give up and let B
2332** proceed.
drha059ad02001-04-17 20:09:11 +00002333*/
danielk1977aef0bf62005-12-30 16:28:01 +00002334int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
danielk1977404ca072009-03-16 13:19:36 +00002335 sqlite3 *pBlock = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00002336 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00002337 int rc = SQLITE_OK;
2338
drhd677b3d2007-08-20 22:48:41 +00002339 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002340 btreeIntegrity(p);
2341
danielk1977ee5741e2004-05-31 10:01:34 +00002342 /* If the btree is already in a write-transaction, or it
2343 ** is already in a read-transaction and a read-transaction
2344 ** is requested, this is a no-op.
2345 */
danielk1977aef0bf62005-12-30 16:28:01 +00002346 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00002347 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002348 }
drhb8ef32c2005-03-14 02:01:49 +00002349
2350 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00002351 if( pBt->readOnly && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00002352 rc = SQLITE_READONLY;
2353 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002354 }
2355
danielk1977404ca072009-03-16 13:19:36 +00002356#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +00002357 /* If another database handle has already opened a write transaction
2358 ** on this shared-btree structure and a second write transaction is
danielk1977404ca072009-03-16 13:19:36 +00002359 ** requested, return SQLITE_LOCKED.
danielk1977aef0bf62005-12-30 16:28:01 +00002360 */
danielk1977404ca072009-03-16 13:19:36 +00002361 if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
2362 pBlock = pBt->pWriter->db;
2363 }else if( wrflag>1 ){
danielk1977641b0f42007-12-21 04:47:25 +00002364 BtLock *pIter;
2365 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
2366 if( pIter->pBtree!=p ){
danielk1977404ca072009-03-16 13:19:36 +00002367 pBlock = pIter->pBtree->db;
2368 break;
danielk1977641b0f42007-12-21 04:47:25 +00002369 }
2370 }
2371 }
danielk1977404ca072009-03-16 13:19:36 +00002372 if( pBlock ){
2373 sqlite3ConnectionBlocked(p->db, pBlock);
2374 rc = SQLITE_LOCKED_SHAREDCACHE;
2375 goto trans_begun;
2376 }
danielk1977641b0f42007-12-21 04:47:25 +00002377#endif
2378
drhb8ef32c2005-03-14 02:01:49 +00002379 do {
danielk1977295dc102009-04-01 19:07:03 +00002380 /* Call lockBtree() until either pBt->pPage1 is populated or
2381 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
2382 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
2383 ** reading page 1 it discovers that the page-size of the database
2384 ** file is not pBt->pageSize. In this case lockBtree() will update
2385 ** pBt->pageSize to the page-size of the file on disk.
2386 */
2387 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
drh309169a2007-04-24 17:27:51 +00002388
drhb8ef32c2005-03-14 02:01:49 +00002389 if( rc==SQLITE_OK && wrflag ){
drh309169a2007-04-24 17:27:51 +00002390 if( pBt->readOnly ){
2391 rc = SQLITE_READONLY;
2392 }else{
danielk1977d8293352009-04-30 09:10:37 +00002393 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
drh309169a2007-04-24 17:27:51 +00002394 if( rc==SQLITE_OK ){
2395 rc = newDatabase(pBt);
2396 }
drhb8ef32c2005-03-14 02:01:49 +00002397 }
2398 }
2399
danielk1977bd434552009-03-18 10:33:00 +00002400 if( rc!=SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00002401 unlockBtreeIfUnused(pBt);
2402 }
danielk1977aef0bf62005-12-30 16:28:01 +00002403 }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
danielk19771ceedd32008-11-19 10:22:33 +00002404 btreeInvokeBusyHandler(pBt) );
danielk1977aef0bf62005-12-30 16:28:01 +00002405
2406 if( rc==SQLITE_OK ){
2407 if( p->inTrans==TRANS_NONE ){
2408 pBt->nTransaction++;
2409 }
2410 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
2411 if( p->inTrans>pBt->inTransaction ){
2412 pBt->inTransaction = p->inTrans;
2413 }
danielk1977641b0f42007-12-21 04:47:25 +00002414#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977404ca072009-03-16 13:19:36 +00002415 if( wrflag ){
2416 assert( !pBt->pWriter );
2417 pBt->pWriter = p;
shaneca18d202009-03-23 02:34:32 +00002418 pBt->isExclusive = (u8)(wrflag>1);
danielk1977641b0f42007-12-21 04:47:25 +00002419 }
2420#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002421 }
2422
drhd677b3d2007-08-20 22:48:41 +00002423
2424trans_begun:
danielk1977fd7f0452008-12-17 17:30:26 +00002425 if( rc==SQLITE_OK && wrflag ){
danielk197712dd5492008-12-18 15:45:07 +00002426 /* This call makes sure that the pager has the correct number of
2427 ** open savepoints. If the second parameter is greater than 0 and
2428 ** the sub-journal is not already open, then it will be opened here.
2429 */
danielk1977fd7f0452008-12-17 17:30:26 +00002430 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
2431 }
danielk197712dd5492008-12-18 15:45:07 +00002432
danielk1977aef0bf62005-12-30 16:28:01 +00002433 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002434 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00002435 return rc;
drha059ad02001-04-17 20:09:11 +00002436}
2437
danielk1977687566d2004-11-02 12:56:41 +00002438#ifndef SQLITE_OMIT_AUTOVACUUM
2439
2440/*
2441** Set the pointer-map entries for all children of page pPage. Also, if
2442** pPage contains cells that point to overflow pages, set the pointer
2443** map entries for the overflow pages as well.
2444*/
2445static int setChildPtrmaps(MemPage *pPage){
2446 int i; /* Counter variable */
2447 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00002448 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00002449 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00002450 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002451 Pgno pgno = pPage->pgno;
2452
drh1fee73e2007-08-29 04:00:57 +00002453 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197771d5d2c2008-09-29 11:49:47 +00002454 rc = sqlite3BtreeInitPage(pPage);
danielk19772df71c72007-05-24 07:22:42 +00002455 if( rc!=SQLITE_OK ){
2456 goto set_child_ptrmaps_out;
2457 }
danielk1977687566d2004-11-02 12:56:41 +00002458 nCell = pPage->nCell;
2459
2460 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002461 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002462
danielk197726836652005-01-17 01:33:13 +00002463 rc = ptrmapPutOvflPtr(pPage, pCell);
2464 if( rc!=SQLITE_OK ){
2465 goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002466 }
danielk197726836652005-01-17 01:33:13 +00002467
danielk1977687566d2004-11-02 12:56:41 +00002468 if( !pPage->leaf ){
2469 Pgno childPgno = get4byte(pCell);
2470 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
danielk197700a696d2008-09-29 16:41:31 +00002471 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002472 }
2473 }
2474
2475 if( !pPage->leaf ){
2476 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
2477 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
2478 }
2479
2480set_child_ptrmaps_out:
2481 pPage->isInit = isInitOrig;
2482 return rc;
2483}
2484
2485/*
danielk1977fa542f12009-04-02 18:28:08 +00002486** Somewhere on pPage, which is guaranteed to be a btree page, not an overflow
danielk1977687566d2004-11-02 12:56:41 +00002487** page, is a pointer to page iFrom. Modify this pointer so that it points to
2488** iTo. Parameter eType describes the type of pointer to be modified, as
2489** follows:
2490**
2491** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
2492** page of pPage.
2493**
2494** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
2495** page pointed to by one of the cells on pPage.
2496**
2497** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
2498** overflow page in the list.
2499*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00002500static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00002501 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00002502 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977687566d2004-11-02 12:56:41 +00002503 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00002504 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00002505 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00002506 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002507 }
danielk1977f78fc082004-11-02 14:40:32 +00002508 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00002509 }else{
drhf49661a2008-12-10 16:45:50 +00002510 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002511 int i;
2512 int nCell;
2513
danielk197771d5d2c2008-09-29 11:49:47 +00002514 sqlite3BtreeInitPage(pPage);
danielk1977687566d2004-11-02 12:56:41 +00002515 nCell = pPage->nCell;
2516
danielk1977687566d2004-11-02 12:56:41 +00002517 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002518 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002519 if( eType==PTRMAP_OVERFLOW1 ){
2520 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00002521 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
danielk1977687566d2004-11-02 12:56:41 +00002522 if( info.iOverflow ){
2523 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
2524 put4byte(&pCell[info.iOverflow], iTo);
2525 break;
2526 }
2527 }
2528 }else{
2529 if( get4byte(pCell)==iFrom ){
2530 put4byte(pCell, iTo);
2531 break;
2532 }
2533 }
2534 }
2535
2536 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00002537 if( eType!=PTRMAP_BTREE ||
2538 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00002539 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002540 }
danielk1977687566d2004-11-02 12:56:41 +00002541 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
2542 }
2543
2544 pPage->isInit = isInitOrig;
2545 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002546 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002547}
2548
danielk1977003ba062004-11-04 02:57:33 +00002549
danielk19777701e812005-01-10 12:59:51 +00002550/*
2551** Move the open database page pDbPage to location iFreePage in the
2552** database. The pDbPage reference remains valid.
2553*/
danielk1977003ba062004-11-04 02:57:33 +00002554static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00002555 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00002556 MemPage *pDbPage, /* Open page to move */
2557 u8 eType, /* Pointer map 'type' entry for pDbPage */
2558 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
danielk19774c999992008-07-16 18:17:55 +00002559 Pgno iFreePage, /* The location to move pDbPage to */
2560 int isCommit
danielk1977003ba062004-11-04 02:57:33 +00002561){
2562 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
2563 Pgno iDbPage = pDbPage->pgno;
2564 Pager *pPager = pBt->pPager;
2565 int rc;
2566
danielk1977a0bf2652004-11-04 14:30:04 +00002567 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
2568 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00002569 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00002570 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00002571
drh85b623f2007-12-13 21:54:09 +00002572 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00002573 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
2574 iDbPage, iFreePage, iPtrPage, eType));
danielk19774c999992008-07-16 18:17:55 +00002575 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
danielk1977003ba062004-11-04 02:57:33 +00002576 if( rc!=SQLITE_OK ){
2577 return rc;
2578 }
2579 pDbPage->pgno = iFreePage;
2580
2581 /* If pDbPage was a btree-page, then it may have child pages and/or cells
2582 ** that point to overflow pages. The pointer map entries for all these
2583 ** pages need to be changed.
2584 **
2585 ** If pDbPage is an overflow page, then the first 4 bytes may store a
2586 ** pointer to a subsequent overflow page. If this is the case, then
2587 ** the pointer map needs to be updated for the subsequent overflow page.
2588 */
danielk1977a0bf2652004-11-04 14:30:04 +00002589 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00002590 rc = setChildPtrmaps(pDbPage);
2591 if( rc!=SQLITE_OK ){
2592 return rc;
2593 }
2594 }else{
2595 Pgno nextOvfl = get4byte(pDbPage->aData);
2596 if( nextOvfl!=0 ){
danielk1977003ba062004-11-04 02:57:33 +00002597 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
2598 if( rc!=SQLITE_OK ){
2599 return rc;
2600 }
2601 }
2602 }
2603
2604 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
2605 ** that it points at iFreePage. Also fix the pointer map entry for
2606 ** iPtrPage.
2607 */
danielk1977a0bf2652004-11-04 14:30:04 +00002608 if( eType!=PTRMAP_ROOTPAGE ){
drh16a9b832007-05-05 18:39:25 +00002609 rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00002610 if( rc!=SQLITE_OK ){
2611 return rc;
2612 }
danielk19773b8a05f2007-03-19 17:44:26 +00002613 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00002614 if( rc!=SQLITE_OK ){
2615 releasePage(pPtrPage);
2616 return rc;
2617 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002618 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00002619 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00002620 if( rc==SQLITE_OK ){
2621 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
2622 }
danielk1977003ba062004-11-04 02:57:33 +00002623 }
danielk1977003ba062004-11-04 02:57:33 +00002624 return rc;
2625}
2626
danielk1977dddbcdc2007-04-26 14:42:34 +00002627/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00002628static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00002629
2630/*
danielk1977dddbcdc2007-04-26 14:42:34 +00002631** Perform a single step of an incremental-vacuum. If successful,
2632** return SQLITE_OK. If there is no work to do (and therefore no
2633** point in calling this function again), return SQLITE_DONE.
2634**
2635** More specificly, this function attempts to re-organize the
2636** database so that the last page of the file currently in use
2637** is no longer in use.
2638**
2639** If the nFin parameter is non-zero, the implementation assumes
2640** that the caller will keep calling incrVacuumStep() until
2641** it returns SQLITE_DONE or an error, and that nFin is the
2642** number of pages the database file will contain after this
2643** process is complete.
2644*/
danielk19773460d192008-12-27 15:23:13 +00002645static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
danielk1977dddbcdc2007-04-26 14:42:34 +00002646 Pgno nFreeList; /* Number of pages still on the free-list */
2647
drh1fee73e2007-08-29 04:00:57 +00002648 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977fa542f12009-04-02 18:28:08 +00002649 assert( iLastPg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00002650
2651 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
2652 int rc;
2653 u8 eType;
2654 Pgno iPtrPage;
2655
2656 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977fa542f12009-04-02 18:28:08 +00002657 if( nFreeList==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00002658 return SQLITE_DONE;
2659 }
2660
2661 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
2662 if( rc!=SQLITE_OK ){
2663 return rc;
2664 }
2665 if( eType==PTRMAP_ROOTPAGE ){
2666 return SQLITE_CORRUPT_BKPT;
2667 }
2668
2669 if( eType==PTRMAP_FREEPAGE ){
2670 if( nFin==0 ){
2671 /* Remove the page from the files free-list. This is not required
danielk19774ef24492007-05-23 09:52:41 +00002672 ** if nFin is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00002673 ** truncated to zero after this function returns, so it doesn't
2674 ** matter if it still contains some garbage entries.
2675 */
2676 Pgno iFreePg;
2677 MemPage *pFreePg;
2678 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
2679 if( rc!=SQLITE_OK ){
2680 return rc;
2681 }
2682 assert( iFreePg==iLastPg );
2683 releasePage(pFreePg);
2684 }
2685 } else {
2686 Pgno iFreePg; /* Index of free page to move pLastPg to */
2687 MemPage *pLastPg;
2688
drh16a9b832007-05-05 18:39:25 +00002689 rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002690 if( rc!=SQLITE_OK ){
2691 return rc;
2692 }
2693
danielk1977b4626a32007-04-28 15:47:43 +00002694 /* If nFin is zero, this loop runs exactly once and page pLastPg
2695 ** is swapped with the first free page pulled off the free list.
2696 **
2697 ** On the other hand, if nFin is greater than zero, then keep
2698 ** looping until a free-page located within the first nFin pages
2699 ** of the file is found.
2700 */
danielk1977dddbcdc2007-04-26 14:42:34 +00002701 do {
2702 MemPage *pFreePg;
2703 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
2704 if( rc!=SQLITE_OK ){
2705 releasePage(pLastPg);
2706 return rc;
2707 }
2708 releasePage(pFreePg);
2709 }while( nFin!=0 && iFreePg>nFin );
2710 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00002711
2712 rc = sqlite3PagerWrite(pLastPg->pDbPage);
danielk1977662278e2007-11-05 15:30:12 +00002713 if( rc==SQLITE_OK ){
danielk19774c999992008-07-16 18:17:55 +00002714 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
danielk1977662278e2007-11-05 15:30:12 +00002715 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002716 releasePage(pLastPg);
2717 if( rc!=SQLITE_OK ){
2718 return rc;
danielk1977662278e2007-11-05 15:30:12 +00002719 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002720 }
2721 }
2722
danielk19773460d192008-12-27 15:23:13 +00002723 if( nFin==0 ){
2724 iLastPg--;
2725 while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
danielk1977f4027782009-03-30 18:50:04 +00002726 if( PTRMAP_ISPAGE(pBt, iLastPg) ){
2727 MemPage *pPg;
2728 int rc = sqlite3BtreeGetPage(pBt, iLastPg, &pPg, 0);
2729 if( rc!=SQLITE_OK ){
2730 return rc;
2731 }
2732 rc = sqlite3PagerWrite(pPg->pDbPage);
2733 releasePage(pPg);
2734 if( rc!=SQLITE_OK ){
2735 return rc;
2736 }
2737 }
danielk19773460d192008-12-27 15:23:13 +00002738 iLastPg--;
2739 }
2740 sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
danielk1977dddbcdc2007-04-26 14:42:34 +00002741 }
2742 return SQLITE_OK;
2743}
2744
2745/*
2746** A write-transaction must be opened before calling this function.
2747** It performs a single unit of work towards an incremental vacuum.
2748**
2749** If the incremental vacuum is finished after this function has run,
shanebe217792009-03-05 04:20:31 +00002750** SQLITE_DONE is returned. If it is not finished, but no error occurred,
danielk1977dddbcdc2007-04-26 14:42:34 +00002751** SQLITE_OK is returned. Otherwise an SQLite error code.
2752*/
2753int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002754 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002755 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002756
2757 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00002758 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
2759 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002760 rc = SQLITE_DONE;
2761 }else{
2762 invalidateAllOverflowCache(pBt);
danielk1977bea2a942009-01-20 17:06:27 +00002763 rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt));
danielk1977dddbcdc2007-04-26 14:42:34 +00002764 }
drhd677b3d2007-08-20 22:48:41 +00002765 sqlite3BtreeLeave(p);
2766 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002767}
2768
2769/*
danielk19773b8a05f2007-03-19 17:44:26 +00002770** This routine is called prior to sqlite3PagerCommit when a transaction
danielk1977687566d2004-11-02 12:56:41 +00002771** is commited for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00002772**
2773** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
2774** the database file should be truncated to during the commit process.
2775** i.e. the database has been reorganized so that only the first *pnTrunc
2776** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00002777*/
danielk19773460d192008-12-27 15:23:13 +00002778static int autoVacuumCommit(BtShared *pBt){
danielk1977dddbcdc2007-04-26 14:42:34 +00002779 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002780 Pager *pPager = pBt->pPager;
drhf94a1732008-09-30 17:18:17 +00002781 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002782
drh1fee73e2007-08-29 04:00:57 +00002783 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00002784 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00002785 assert(pBt->autoVacuum);
2786 if( !pBt->incrVacuum ){
danielk19773460d192008-12-27 15:23:13 +00002787 Pgno nFin;
2788 Pgno nFree;
2789 Pgno nPtrmap;
2790 Pgno iFree;
2791 const int pgsz = pBt->pageSize;
2792 Pgno nOrig = pagerPagecount(pBt);
danielk1977687566d2004-11-02 12:56:41 +00002793
danielk1977ef165ce2009-04-06 17:50:03 +00002794 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
2795 /* It is not possible to create a database for which the final page
2796 ** is either a pointer-map page or the pending-byte page. If one
2797 ** is encountered, this indicates corruption.
2798 */
danielk19773460d192008-12-27 15:23:13 +00002799 return SQLITE_CORRUPT_BKPT;
2800 }
danielk1977ef165ce2009-04-06 17:50:03 +00002801
danielk19773460d192008-12-27 15:23:13 +00002802 nFree = get4byte(&pBt->pPage1->aData[36]);
2803 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
2804 nFin = nOrig - nFree - nPtrmap;
danielk1977ef165ce2009-04-06 17:50:03 +00002805 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
danielk19773460d192008-12-27 15:23:13 +00002806 nFin--;
2807 }
2808 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
2809 nFin--;
danielk1977dddbcdc2007-04-26 14:42:34 +00002810 }
drhc5e47ac2009-06-04 00:11:56 +00002811 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
danielk1977687566d2004-11-02 12:56:41 +00002812
danielk19773460d192008-12-27 15:23:13 +00002813 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
2814 rc = incrVacuumStep(pBt, nFin, iFree);
danielk1977dddbcdc2007-04-26 14:42:34 +00002815 }
danielk19773460d192008-12-27 15:23:13 +00002816 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00002817 rc = SQLITE_OK;
danielk19773460d192008-12-27 15:23:13 +00002818 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
2819 put4byte(&pBt->pPage1->aData[32], 0);
2820 put4byte(&pBt->pPage1->aData[36], 0);
2821 sqlite3PagerTruncateImage(pBt->pPager, nFin);
danielk1977dddbcdc2007-04-26 14:42:34 +00002822 }
2823 if( rc!=SQLITE_OK ){
2824 sqlite3PagerRollback(pPager);
2825 }
danielk1977687566d2004-11-02 12:56:41 +00002826 }
2827
danielk19773b8a05f2007-03-19 17:44:26 +00002828 assert( nRef==sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002829 return rc;
2830}
danielk1977dddbcdc2007-04-26 14:42:34 +00002831
danielk1977a50d9aa2009-06-08 14:49:45 +00002832#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
2833# define setChildPtrmaps(x) SQLITE_OK
2834#endif
danielk1977687566d2004-11-02 12:56:41 +00002835
2836/*
drh80e35f42007-03-30 14:06:34 +00002837** This routine does the first phase of a two-phase commit. This routine
2838** causes a rollback journal to be created (if it does not already exist)
2839** and populated with enough information so that if a power loss occurs
2840** the database can be restored to its original state by playing back
2841** the journal. Then the contents of the journal are flushed out to
2842** the disk. After the journal is safely on oxide, the changes to the
2843** database are written into the database file and flushed to oxide.
2844** At the end of this call, the rollback journal still exists on the
2845** disk and we are still holding all locks, so the transaction has not
drh51898cf2009-04-19 20:51:06 +00002846** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
drh80e35f42007-03-30 14:06:34 +00002847** commit process.
2848**
2849** This call is a no-op if no write-transaction is currently active on pBt.
2850**
2851** Otherwise, sync the database file for the btree pBt. zMaster points to
2852** the name of a master journal file that should be written into the
2853** individual journal file, or is NULL, indicating no master journal file
2854** (single database transaction).
2855**
2856** When this is called, the master journal should already have been
2857** created, populated with this journal pointer and synced to disk.
2858**
2859** Once this is routine has returned, the only thing required to commit
2860** the write-transaction for this database file is to delete the journal.
2861*/
2862int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
2863 int rc = SQLITE_OK;
2864 if( p->inTrans==TRANS_WRITE ){
2865 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002866 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00002867#ifndef SQLITE_OMIT_AUTOVACUUM
2868 if( pBt->autoVacuum ){
danielk19773460d192008-12-27 15:23:13 +00002869 rc = autoVacuumCommit(pBt);
drh80e35f42007-03-30 14:06:34 +00002870 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002871 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002872 return rc;
2873 }
2874 }
2875#endif
drh49b9d332009-01-02 18:10:42 +00002876 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
drhd677b3d2007-08-20 22:48:41 +00002877 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002878 }
2879 return rc;
2880}
2881
2882/*
drh2aa679f2001-06-25 02:11:07 +00002883** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00002884**
drh6e345992007-03-30 11:12:08 +00002885** This routine implements the second phase of a 2-phase commit. The
drh51898cf2009-04-19 20:51:06 +00002886** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
2887** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
2888** routine did all the work of writing information out to disk and flushing the
drh6e345992007-03-30 11:12:08 +00002889** contents so that they are written onto the disk platter. All this
drh51898cf2009-04-19 20:51:06 +00002890** routine has to do is delete or truncate or zero the header in the
2891** the rollback journal (which causes the transaction to commit) and
2892** drop locks.
drh6e345992007-03-30 11:12:08 +00002893**
drh5e00f6c2001-09-13 13:46:56 +00002894** This will release the write lock on the database file. If there
2895** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002896*/
drh80e35f42007-03-30 14:06:34 +00002897int sqlite3BtreeCommitPhaseTwo(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002898 BtShared *pBt = p->pBt;
2899
drhd677b3d2007-08-20 22:48:41 +00002900 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002901 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002902
2903 /* If the handle has a write-transaction open, commit the shared-btrees
2904 ** transaction and set the shared state to TRANS_READ.
2905 */
2906 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00002907 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002908 assert( pBt->inTransaction==TRANS_WRITE );
2909 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00002910 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
danielk19777f7bc662006-01-23 13:47:47 +00002911 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002912 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002913 return rc;
2914 }
danielk1977aef0bf62005-12-30 16:28:01 +00002915 pBt->inTransaction = TRANS_READ;
danielk1977ee5741e2004-05-31 10:01:34 +00002916 }
danielk1977aef0bf62005-12-30 16:28:01 +00002917
2918 /* If the handle has any kind of transaction open, decrement the transaction
2919 ** count of the shared btree. If the transaction count reaches 0, set
2920 ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
2921 ** will unlock the pager.
2922 */
2923 if( p->inTrans!=TRANS_NONE ){
danielk1977fa542f12009-04-02 18:28:08 +00002924 clearAllSharedCacheTableLocks(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002925 pBt->nTransaction--;
2926 if( 0==pBt->nTransaction ){
2927 pBt->inTransaction = TRANS_NONE;
2928 }
2929 }
2930
drh51898cf2009-04-19 20:51:06 +00002931 /* Set the current transaction state to TRANS_NONE and unlock
danielk1977aef0bf62005-12-30 16:28:01 +00002932 ** the pager if this call closed the only read or write transaction.
2933 */
danielk1977bea2a942009-01-20 17:06:27 +00002934 btreeClearHasContent(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002935 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00002936 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002937
2938 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002939 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002940 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002941}
2942
drh80e35f42007-03-30 14:06:34 +00002943/*
2944** Do both phases of a commit.
2945*/
2946int sqlite3BtreeCommit(Btree *p){
2947 int rc;
drhd677b3d2007-08-20 22:48:41 +00002948 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00002949 rc = sqlite3BtreeCommitPhaseOne(p, 0);
2950 if( rc==SQLITE_OK ){
2951 rc = sqlite3BtreeCommitPhaseTwo(p);
2952 }
drhd677b3d2007-08-20 22:48:41 +00002953 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002954 return rc;
2955}
2956
danielk1977fbcd5852004-06-15 02:44:18 +00002957#ifndef NDEBUG
2958/*
2959** Return the number of write-cursors open on this handle. This is for use
2960** in assert() expressions, so it is only compiled if NDEBUG is not
2961** defined.
drhfb982642007-08-30 01:19:59 +00002962**
2963** For the purposes of this routine, a write-cursor is any cursor that
2964** is capable of writing to the databse. That means the cursor was
2965** originally opened for writing and the cursor has not be disabled
2966** by having its state changed to CURSOR_FAULT.
danielk1977fbcd5852004-06-15 02:44:18 +00002967*/
danielk1977aef0bf62005-12-30 16:28:01 +00002968static int countWriteCursors(BtShared *pBt){
danielk1977fbcd5852004-06-15 02:44:18 +00002969 BtCursor *pCur;
2970 int r = 0;
2971 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drhfb982642007-08-30 01:19:59 +00002972 if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
danielk1977fbcd5852004-06-15 02:44:18 +00002973 }
2974 return r;
2975}
2976#endif
2977
drhc39e0002004-05-07 23:50:57 +00002978/*
drhfb982642007-08-30 01:19:59 +00002979** This routine sets the state to CURSOR_FAULT and the error
2980** code to errCode for every cursor on BtShared that pBtree
2981** references.
2982**
2983** Every cursor is tripped, including cursors that belong
2984** to other database connections that happen to be sharing
2985** the cache with pBtree.
2986**
2987** This routine gets called when a rollback occurs.
2988** All cursors using the same cache must be tripped
2989** to prevent them from trying to use the btree after
2990** the rollback. The rollback may have deleted tables
2991** or moved root pages, so it is not sufficient to
2992** save the state of the cursor. The cursor must be
2993** invalidated.
2994*/
2995void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
2996 BtCursor *p;
2997 sqlite3BtreeEnter(pBtree);
2998 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
danielk1977bc2ca9e2008-11-13 14:28:28 +00002999 int i;
danielk1977be51a652008-10-08 17:58:48 +00003000 sqlite3BtreeClearCursor(p);
drhfb982642007-08-30 01:19:59 +00003001 p->eState = CURSOR_FAULT;
3002 p->skip = errCode;
danielk1977bc2ca9e2008-11-13 14:28:28 +00003003 for(i=0; i<=p->iPage; i++){
3004 releasePage(p->apPage[i]);
3005 p->apPage[i] = 0;
3006 }
drhfb982642007-08-30 01:19:59 +00003007 }
3008 sqlite3BtreeLeave(pBtree);
3009}
3010
3011/*
drhecdc7532001-09-23 02:35:53 +00003012** Rollback the transaction in progress. All cursors will be
3013** invalided by this operation. Any attempt to use a cursor
3014** that was open at the beginning of this operation will result
3015** in an error.
drh5e00f6c2001-09-13 13:46:56 +00003016**
3017** This will release the write lock on the database file. If there
3018** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00003019*/
danielk1977aef0bf62005-12-30 16:28:01 +00003020int sqlite3BtreeRollback(Btree *p){
danielk19778d34dfd2006-01-24 16:37:57 +00003021 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003022 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00003023 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00003024
drhd677b3d2007-08-20 22:48:41 +00003025 sqlite3BtreeEnter(p);
danielk19772b8c13e2006-01-24 14:21:24 +00003026 rc = saveAllCursors(pBt, 0, 0);
danielk19778d34dfd2006-01-24 16:37:57 +00003027#ifndef SQLITE_OMIT_SHARED_CACHE
danielk19772b8c13e2006-01-24 14:21:24 +00003028 if( rc!=SQLITE_OK ){
shanebe217792009-03-05 04:20:31 +00003029 /* This is a horrible situation. An IO or malloc() error occurred whilst
danielk19778d34dfd2006-01-24 16:37:57 +00003030 ** trying to save cursor positions. If this is an automatic rollback (as
3031 ** the result of a constraint, malloc() failure or IO error) then
3032 ** the cache may be internally inconsistent (not contain valid trees) so
3033 ** we cannot simply return the error to the caller. Instead, abort
3034 ** all queries that may be using any of the cursors that failed to save.
3035 */
drhfb982642007-08-30 01:19:59 +00003036 sqlite3BtreeTripAllCursors(p, rc);
danielk19772b8c13e2006-01-24 14:21:24 +00003037 }
danielk19778d34dfd2006-01-24 16:37:57 +00003038#endif
danielk1977aef0bf62005-12-30 16:28:01 +00003039 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003040
3041 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00003042 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00003043
danielk19778d34dfd2006-01-24 16:37:57 +00003044 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00003045 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00003046 if( rc2!=SQLITE_OK ){
3047 rc = rc2;
3048 }
3049
drh24cd67e2004-05-10 16:18:47 +00003050 /* The rollback may have destroyed the pPage1->aData value. So
drh16a9b832007-05-05 18:39:25 +00003051 ** call sqlite3BtreeGetPage() on page 1 again to make
3052 ** sure pPage1->aData is set correctly. */
3053 if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh24cd67e2004-05-10 16:18:47 +00003054 releasePage(pPage1);
3055 }
danielk1977fbcd5852004-06-15 02:44:18 +00003056 assert( countWriteCursors(pBt)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00003057 pBt->inTransaction = TRANS_READ;
drh24cd67e2004-05-10 16:18:47 +00003058 }
danielk1977aef0bf62005-12-30 16:28:01 +00003059
3060 if( p->inTrans!=TRANS_NONE ){
danielk1977fa542f12009-04-02 18:28:08 +00003061 clearAllSharedCacheTableLocks(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003062 assert( pBt->nTransaction>0 );
3063 pBt->nTransaction--;
3064 if( 0==pBt->nTransaction ){
3065 pBt->inTransaction = TRANS_NONE;
3066 }
3067 }
3068
danielk1977bea2a942009-01-20 17:06:27 +00003069 btreeClearHasContent(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00003070 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00003071 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00003072
3073 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00003074 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00003075 return rc;
3076}
3077
3078/*
danielk1977bd434552009-03-18 10:33:00 +00003079** Start a statement subtransaction. The subtransaction can can be rolled
3080** back independently of the main transaction. You must start a transaction
3081** before starting a subtransaction. The subtransaction is ended automatically
3082** if the main transaction commits or rolls back.
drhab01f612004-05-22 02:55:23 +00003083**
3084** Statement subtransactions are used around individual SQL statements
3085** that are contained within a BEGIN...COMMIT block. If a constraint
3086** error occurs within the statement, the effect of that one statement
3087** can be rolled back without having to rollback the entire transaction.
danielk1977bd434552009-03-18 10:33:00 +00003088**
3089** A statement sub-transaction is implemented as an anonymous savepoint. The
3090** value passed as the second parameter is the total number of savepoints,
3091** including the new anonymous savepoint, open on the B-Tree. i.e. if there
3092** are no active savepoints and no other statement-transactions open,
3093** iStatement is 1. This anonymous savepoint can be released or rolled back
3094** using the sqlite3BtreeSavepoint() function.
drh663fc632002-02-02 18:49:19 +00003095*/
danielk1977bd434552009-03-18 10:33:00 +00003096int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
drh663fc632002-02-02 18:49:19 +00003097 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003098 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003099 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00003100 assert( p->inTrans==TRANS_WRITE );
drh64022502009-01-09 14:11:04 +00003101 assert( pBt->readOnly==0 );
danielk1977bd434552009-03-18 10:33:00 +00003102 assert( iStatement>0 );
3103 assert( iStatement>p->db->nSavepoint );
3104 if( NEVER(p->inTrans!=TRANS_WRITE || pBt->readOnly) ){
drh64022502009-01-09 14:11:04 +00003105 rc = SQLITE_INTERNAL;
drhd677b3d2007-08-20 22:48:41 +00003106 }else{
3107 assert( pBt->inTransaction==TRANS_WRITE );
drh64022502009-01-09 14:11:04 +00003108 /* At the pager level, a statement transaction is a savepoint with
3109 ** an index greater than all savepoints created explicitly using
3110 ** SQL statements. It is illegal to open, release or rollback any
3111 ** such savepoints while the statement transaction savepoint is active.
3112 */
danielk1977bd434552009-03-18 10:33:00 +00003113 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
danielk197797a227c2006-01-20 16:32:04 +00003114 }
drhd677b3d2007-08-20 22:48:41 +00003115 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00003116 return rc;
3117}
3118
3119/*
danielk1977fd7f0452008-12-17 17:30:26 +00003120** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
3121** or SAVEPOINT_RELEASE. This function either releases or rolls back the
danielk197712dd5492008-12-18 15:45:07 +00003122** savepoint identified by parameter iSavepoint, depending on the value
3123** of op.
3124**
3125** Normally, iSavepoint is greater than or equal to zero. However, if op is
3126** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
3127** contents of the entire transaction are rolled back. This is different
3128** from a normal transaction rollback, as no locks are released and the
3129** transaction remains open.
danielk1977fd7f0452008-12-17 17:30:26 +00003130*/
3131int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
3132 int rc = SQLITE_OK;
3133 if( p && p->inTrans==TRANS_WRITE ){
3134 BtShared *pBt = p->pBt;
danielk1977fd7f0452008-12-17 17:30:26 +00003135 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
3136 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
3137 sqlite3BtreeEnter(p);
danielk1977fd7f0452008-12-17 17:30:26 +00003138 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
drh9f0bbf92009-01-02 21:08:09 +00003139 if( rc==SQLITE_OK ){
3140 rc = newDatabase(pBt);
3141 }
danielk1977fd7f0452008-12-17 17:30:26 +00003142 sqlite3BtreeLeave(p);
3143 }
3144 return rc;
3145}
3146
3147/*
drh8b2f49b2001-06-08 00:21:52 +00003148** Create a new cursor for the BTree whose root is on the page
3149** iTable. The act of acquiring a cursor gets a read lock on
3150** the database file.
drh1bee3d72001-10-15 00:44:35 +00003151**
3152** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00003153** If wrFlag==1, then the cursor can be used for reading or for
3154** writing if other conditions for writing are also met. These
3155** are the conditions that must be met in order for writing to
3156** be allowed:
drh6446c4d2001-12-15 14:22:18 +00003157**
drhf74b8d92002-09-01 23:20:45 +00003158** 1: The cursor must have been opened with wrFlag==1
3159**
drhfe5d71d2007-03-19 11:54:10 +00003160** 2: Other database connections that share the same pager cache
3161** but which are not in the READ_UNCOMMITTED state may not have
3162** cursors open with wrFlag==0 on the same table. Otherwise
3163** the changes made by this write cursor would be visible to
3164** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00003165**
3166** 3: The database must be writable (not on read-only media)
3167**
3168** 4: There must be an active transaction.
3169**
drh6446c4d2001-12-15 14:22:18 +00003170** No checking is done to make sure that page iTable really is the
3171** root page of a b-tree. If it is not, then the cursor acquired
3172** will not work correctly.
danielk197771d5d2c2008-09-29 11:49:47 +00003173**
3174** It is assumed that the sqlite3BtreeCursorSize() bytes of memory
3175** pointed to by pCur have been zeroed by the caller.
drha059ad02001-04-17 20:09:11 +00003176*/
drhd677b3d2007-08-20 22:48:41 +00003177static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00003178 Btree *p, /* The btree */
3179 int iTable, /* Root page of table to open */
3180 int wrFlag, /* 1 to write. 0 read-only */
3181 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
3182 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00003183){
drha059ad02001-04-17 20:09:11 +00003184 int rc;
danielk197789d40042008-11-17 14:20:56 +00003185 Pgno nPage;
danielk1977aef0bf62005-12-30 16:28:01 +00003186 BtShared *pBt = p->pBt;
drhecdc7532001-09-23 02:35:53 +00003187
drh1fee73e2007-08-29 04:00:57 +00003188 assert( sqlite3BtreeHoldsMutex(p) );
drhf49661a2008-12-10 16:45:50 +00003189 assert( wrFlag==0 || wrFlag==1 );
danielk197796d48e92009-06-29 06:00:37 +00003190
3191 /* The following assert statements verify that if this is a sharable b-tree
3192 ** database, the connection is holding the required table locks, and that
3193 ** no other connection has any open cursor that conflicts with this lock.
3194 **
3195 ** The exception to this is read-only cursors open on the schema table.
3196 ** Such a cursor is opened without a lock while reading the database
3197 ** schema. This is safe because BtShared.mutex is held for the entire
3198 ** lifetime of this cursor. */
3199 assert( (iTable==1 && wrFlag==0)
3200 || hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1)
3201 );
3202 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
3203
3204 if( NEVER(wrFlag && pBt->readOnly) ){
3205 return SQLITE_READONLY;
drha0c9a112004-03-10 13:42:37 +00003206 }
danielk1977aef0bf62005-12-30 16:28:01 +00003207
drh4b70f112004-05-02 21:12:19 +00003208 if( pBt->pPage1==0 ){
danielk1977aef0bf62005-12-30 16:28:01 +00003209 rc = lockBtreeWithRetry(p);
drha059ad02001-04-17 20:09:11 +00003210 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00003211 return rc;
3212 }
3213 }
drh8b2f49b2001-06-08 00:21:52 +00003214 pCur->pgnoRoot = (Pgno)iTable;
danielk197789d40042008-11-17 14:20:56 +00003215 rc = sqlite3PagerPagecount(pBt->pPager, (int *)&nPage);
3216 if( rc!=SQLITE_OK ){
3217 return rc;
3218 }
3219 if( iTable==1 && nPage==0 ){
drh24cd67e2004-05-10 16:18:47 +00003220 rc = SQLITE_EMPTY;
3221 goto create_cursor_exception;
3222 }
danielk197771d5d2c2008-09-29 11:49:47 +00003223 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
drhbd03cae2001-06-02 02:40:57 +00003224 if( rc!=SQLITE_OK ){
3225 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00003226 }
danielk1977aef0bf62005-12-30 16:28:01 +00003227
danielk1977aef0bf62005-12-30 16:28:01 +00003228 /* Now that no other errors can occur, finish filling in the BtCursor
3229 ** variables, link the cursor into the BtShared list and set *ppCur (the
3230 ** output argument to this function).
3231 */
drh1e968a02008-03-25 00:22:21 +00003232 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00003233 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00003234 pCur->pBt = pBt;
drhf49661a2008-12-10 16:45:50 +00003235 pCur->wrFlag = (u8)wrFlag;
drha059ad02001-04-17 20:09:11 +00003236 pCur->pNext = pBt->pCursor;
3237 if( pCur->pNext ){
3238 pCur->pNext->pPrev = pCur;
3239 }
3240 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00003241 pCur->eState = CURSOR_INVALID;
drh7f751222009-03-17 22:33:00 +00003242 pCur->cachedRowid = 0;
drhbd03cae2001-06-02 02:40:57 +00003243
danielk1977aef0bf62005-12-30 16:28:01 +00003244 return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003245
drhbd03cae2001-06-02 02:40:57 +00003246create_cursor_exception:
danielk197771d5d2c2008-09-29 11:49:47 +00003247 releasePage(pCur->apPage[0]);
drh5e00f6c2001-09-13 13:46:56 +00003248 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00003249 return rc;
drha059ad02001-04-17 20:09:11 +00003250}
drhd677b3d2007-08-20 22:48:41 +00003251int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00003252 Btree *p, /* The btree */
3253 int iTable, /* Root page of table to open */
3254 int wrFlag, /* 1 to write. 0 read-only */
3255 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
3256 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00003257){
3258 int rc;
3259 sqlite3BtreeEnter(p);
danielk1977cd3e8f72008-03-25 09:47:35 +00003260 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
drhd677b3d2007-08-20 22:48:41 +00003261 sqlite3BtreeLeave(p);
3262 return rc;
3263}
drh7f751222009-03-17 22:33:00 +00003264
3265/*
3266** Return the size of a BtCursor object in bytes.
3267**
3268** This interfaces is needed so that users of cursors can preallocate
3269** sufficient storage to hold a cursor. The BtCursor object is opaque
3270** to users so they cannot do the sizeof() themselves - they must call
3271** this routine.
3272*/
3273int sqlite3BtreeCursorSize(void){
danielk1977cd3e8f72008-03-25 09:47:35 +00003274 return sizeof(BtCursor);
3275}
3276
drh7f751222009-03-17 22:33:00 +00003277/*
3278** Set the cached rowid value of every cursor in the same database file
3279** as pCur and having the same root page number as pCur. The value is
3280** set to iRowid.
3281**
3282** Only positive rowid values are considered valid for this cache.
3283** The cache is initialized to zero, indicating an invalid cache.
3284** A btree will work fine with zero or negative rowids. We just cannot
3285** cache zero or negative rowids, which means tables that use zero or
3286** negative rowids might run a little slower. But in practice, zero
3287** or negative rowids are very uncommon so this should not be a problem.
3288*/
3289void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
3290 BtCursor *p;
3291 for(p=pCur->pBt->pCursor; p; p=p->pNext){
3292 if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
3293 }
3294 assert( pCur->cachedRowid==iRowid );
3295}
drhd677b3d2007-08-20 22:48:41 +00003296
drh7f751222009-03-17 22:33:00 +00003297/*
3298** Return the cached rowid for the given cursor. A negative or zero
3299** return value indicates that the rowid cache is invalid and should be
3300** ignored. If the rowid cache has never before been set, then a
3301** zero is returned.
3302*/
3303sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
3304 return pCur->cachedRowid;
3305}
drha059ad02001-04-17 20:09:11 +00003306
3307/*
drh5e00f6c2001-09-13 13:46:56 +00003308** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00003309** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00003310*/
drh3aac2dd2004-04-26 14:10:20 +00003311int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00003312 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00003313 if( pBtree ){
danielk197771d5d2c2008-09-29 11:49:47 +00003314 int i;
danielk1977cd3e8f72008-03-25 09:47:35 +00003315 BtShared *pBt = pCur->pBt;
3316 sqlite3BtreeEnter(pBtree);
danielk1977be51a652008-10-08 17:58:48 +00003317 sqlite3BtreeClearCursor(pCur);
danielk1977cd3e8f72008-03-25 09:47:35 +00003318 if( pCur->pPrev ){
3319 pCur->pPrev->pNext = pCur->pNext;
3320 }else{
3321 pBt->pCursor = pCur->pNext;
3322 }
3323 if( pCur->pNext ){
3324 pCur->pNext->pPrev = pCur->pPrev;
3325 }
danielk197771d5d2c2008-09-29 11:49:47 +00003326 for(i=0; i<=pCur->iPage; i++){
3327 releasePage(pCur->apPage[i]);
3328 }
danielk1977cd3e8f72008-03-25 09:47:35 +00003329 unlockBtreeIfUnused(pBt);
3330 invalidateOverflowCache(pCur);
3331 /* sqlite3_free(pCur); */
3332 sqlite3BtreeLeave(pBtree);
drha059ad02001-04-17 20:09:11 +00003333 }
drh8c42ca92001-06-22 19:15:00 +00003334 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003335}
3336
drh0d588bb2009-06-17 13:09:38 +00003337#ifdef SQLITE_TEST
drh7e3b0a02001-04-28 16:52:40 +00003338/*
drh5e2f8b92001-05-28 00:41:15 +00003339** Make a temporary cursor by filling in the fields of pTempCur.
3340** The temporary cursor is not on the cursor list for the Btree.
3341*/
drh16a9b832007-05-05 18:39:25 +00003342void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
danielk197771d5d2c2008-09-29 11:49:47 +00003343 int i;
drh1fee73e2007-08-29 04:00:57 +00003344 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00003345 memcpy(pTempCur, pCur, sizeof(BtCursor));
drh5e2f8b92001-05-28 00:41:15 +00003346 pTempCur->pNext = 0;
3347 pTempCur->pPrev = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003348 for(i=0; i<=pTempCur->iPage; i++){
3349 sqlite3PagerRef(pTempCur->apPage[i]->pDbPage);
drhecdc7532001-09-23 02:35:53 +00003350 }
danielk197736e20932008-11-26 07:40:30 +00003351 assert( pTempCur->pKey==0 );
drh5e2f8b92001-05-28 00:41:15 +00003352}
drh0d588bb2009-06-17 13:09:38 +00003353#endif /* SQLITE_TEST */
drh5e2f8b92001-05-28 00:41:15 +00003354
drh0d588bb2009-06-17 13:09:38 +00003355#ifdef SQLITE_TEST
drh5e2f8b92001-05-28 00:41:15 +00003356/*
drhbd03cae2001-06-02 02:40:57 +00003357** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00003358** function above.
3359*/
drh16a9b832007-05-05 18:39:25 +00003360void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
danielk197771d5d2c2008-09-29 11:49:47 +00003361 int i;
drh1fee73e2007-08-29 04:00:57 +00003362 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00003363 for(i=0; i<=pCur->iPage; i++){
3364 sqlite3PagerUnref(pCur->apPage[i]->pDbPage);
drhecdc7532001-09-23 02:35:53 +00003365 }
danielk197736e20932008-11-26 07:40:30 +00003366 sqlite3_free(pCur->pKey);
drh5e2f8b92001-05-28 00:41:15 +00003367}
drh0d588bb2009-06-17 13:09:38 +00003368#endif /* SQLITE_TEST */
drh7f751222009-03-17 22:33:00 +00003369
drh5e2f8b92001-05-28 00:41:15 +00003370/*
drh86057612007-06-26 01:04:48 +00003371** Make sure the BtCursor* given in the argument has a valid
3372** BtCursor.info structure. If it is not already valid, call
danielk19771cc5ed82007-05-16 17:28:43 +00003373** sqlite3BtreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00003374**
3375** BtCursor.info is a cache of the information in the current cell.
drh16a9b832007-05-05 18:39:25 +00003376** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
drh86057612007-06-26 01:04:48 +00003377**
3378** 2007-06-25: There is a bug in some versions of MSVC that cause the
3379** compiler to crash when getCellInfo() is implemented as a macro.
3380** But there is a measureable speed advantage to using the macro on gcc
3381** (when less compiler optimizations like -Os or -O0 are used and the
3382** compiler is not doing agressive inlining.) So we use a real function
3383** for MSVC and a macro for everything else. Ticket #2457.
drh9188b382004-05-14 21:12:22 +00003384*/
drh9188b382004-05-14 21:12:22 +00003385#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00003386 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00003387 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00003388 int iPage = pCur->iPage;
drh51c6d962004-06-06 00:42:25 +00003389 memset(&info, 0, sizeof(info));
danielk197771d5d2c2008-09-29 11:49:47 +00003390 sqlite3BtreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
drh9188b382004-05-14 21:12:22 +00003391 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00003392 }
danielk19771cc5ed82007-05-16 17:28:43 +00003393#else
3394 #define assertCellInfo(x)
3395#endif
drh86057612007-06-26 01:04:48 +00003396#ifdef _MSC_VER
3397 /* Use a real function in MSVC to work around bugs in that compiler. */
3398 static void getCellInfo(BtCursor *pCur){
3399 if( pCur->info.nSize==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003400 int iPage = pCur->iPage;
3401 sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
drha2c20e42008-03-29 16:01:04 +00003402 pCur->validNKey = 1;
drh86057612007-06-26 01:04:48 +00003403 }else{
3404 assertCellInfo(pCur);
3405 }
3406 }
3407#else /* if not _MSC_VER */
3408 /* Use a macro in all other compilers so that the function is inlined */
danielk197771d5d2c2008-09-29 11:49:47 +00003409#define getCellInfo(pCur) \
3410 if( pCur->info.nSize==0 ){ \
3411 int iPage = pCur->iPage; \
3412 sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
3413 pCur->validNKey = 1; \
3414 }else{ \
3415 assertCellInfo(pCur); \
drh86057612007-06-26 01:04:48 +00003416 }
3417#endif /* _MSC_VER */
drh9188b382004-05-14 21:12:22 +00003418
3419/*
drh3aac2dd2004-04-26 14:10:20 +00003420** Set *pSize to the size of the buffer needed to hold the value of
3421** the key for the current entry. If the cursor is not pointing
3422** to a valid entry, *pSize is set to 0.
3423**
drh4b70f112004-05-02 21:12:19 +00003424** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00003425** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00003426*/
drh4a1c3802004-05-12 15:15:47 +00003427int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drhd677b3d2007-08-20 22:48:41 +00003428 int rc;
3429
drh1fee73e2007-08-29 04:00:57 +00003430 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003431 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003432 if( rc==SQLITE_OK ){
3433 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3434 if( pCur->eState==CURSOR_INVALID ){
3435 *pSize = 0;
3436 }else{
drh86057612007-06-26 01:04:48 +00003437 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00003438 *pSize = pCur->info.nKey;
3439 }
drh72f82862001-05-24 21:06:34 +00003440 }
danielk1977da184232006-01-05 11:34:32 +00003441 return rc;
drha059ad02001-04-17 20:09:11 +00003442}
drh2af926b2001-05-15 00:39:25 +00003443
drh72f82862001-05-24 21:06:34 +00003444/*
drh0e1c19e2004-05-11 00:58:56 +00003445** Set *pSize to the number of bytes of data in the entry the
3446** cursor currently points to. Always return SQLITE_OK.
3447** Failure is not possible. If the cursor is not currently
3448** pointing to an entry (which can happen, for example, if
3449** the database is empty) then *pSize is set to 0.
3450*/
3451int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drhd677b3d2007-08-20 22:48:41 +00003452 int rc;
3453
drh1fee73e2007-08-29 04:00:57 +00003454 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003455 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003456 if( rc==SQLITE_OK ){
3457 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3458 if( pCur->eState==CURSOR_INVALID ){
3459 /* Not pointing at a valid entry - set *pSize to 0. */
3460 *pSize = 0;
3461 }else{
drh86057612007-06-26 01:04:48 +00003462 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00003463 *pSize = pCur->info.nData;
3464 }
drh0e1c19e2004-05-11 00:58:56 +00003465 }
danielk1977da184232006-01-05 11:34:32 +00003466 return rc;
drh0e1c19e2004-05-11 00:58:56 +00003467}
3468
3469/*
danielk1977d04417962007-05-02 13:16:30 +00003470** Given the page number of an overflow page in the database (parameter
3471** ovfl), this function finds the page number of the next page in the
3472** linked list of overflow pages. If possible, it uses the auto-vacuum
3473** pointer-map data instead of reading the content of page ovfl to do so.
3474**
3475** If an error occurs an SQLite error code is returned. Otherwise:
3476**
danielk1977bea2a942009-01-20 17:06:27 +00003477** The page number of the next overflow page in the linked list is
3478** written to *pPgnoNext. If page ovfl is the last page in its linked
3479** list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003480**
danielk1977bea2a942009-01-20 17:06:27 +00003481** If ppPage is not NULL, and a reference to the MemPage object corresponding
3482** to page number pOvfl was obtained, then *ppPage is set to point to that
3483** reference. It is the responsibility of the caller to call releasePage()
3484** on *ppPage to free the reference. In no reference was obtained (because
3485** the pointer-map was used to obtain the value for *pPgnoNext), then
3486** *ppPage is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003487*/
3488static int getOverflowPage(
3489 BtShared *pBt,
3490 Pgno ovfl, /* Overflow page */
danielk1977bea2a942009-01-20 17:06:27 +00003491 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
danielk1977d04417962007-05-02 13:16:30 +00003492 Pgno *pPgnoNext /* OUT: Next overflow page number */
3493){
3494 Pgno next = 0;
danielk1977bea2a942009-01-20 17:06:27 +00003495 MemPage *pPage = 0;
drh1bd10f82008-12-10 21:19:56 +00003496 int rc = SQLITE_OK;
danielk1977d04417962007-05-02 13:16:30 +00003497
drh1fee73e2007-08-29 04:00:57 +00003498 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bea2a942009-01-20 17:06:27 +00003499 assert(pPgnoNext);
danielk1977d04417962007-05-02 13:16:30 +00003500
3501#ifndef SQLITE_OMIT_AUTOVACUUM
3502 /* Try to find the next page in the overflow list using the
3503 ** autovacuum pointer-map pages. Guess that the next page in
3504 ** the overflow list is page number (ovfl+1). If that guess turns
3505 ** out to be wrong, fall back to loading the data of page
3506 ** number ovfl to determine the next page number.
3507 */
3508 if( pBt->autoVacuum ){
3509 Pgno pgno;
3510 Pgno iGuess = ovfl+1;
3511 u8 eType;
3512
3513 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
3514 iGuess++;
3515 }
3516
danielk197789d40042008-11-17 14:20:56 +00003517 if( iGuess<=pagerPagecount(pBt) ){
danielk1977d04417962007-05-02 13:16:30 +00003518 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
danielk1977bea2a942009-01-20 17:06:27 +00003519 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
danielk1977d04417962007-05-02 13:16:30 +00003520 next = iGuess;
danielk1977bea2a942009-01-20 17:06:27 +00003521 rc = SQLITE_DONE;
danielk1977d04417962007-05-02 13:16:30 +00003522 }
3523 }
3524 }
3525#endif
3526
danielk1977bea2a942009-01-20 17:06:27 +00003527 if( rc==SQLITE_OK ){
3528 rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, 0);
danielk1977d04417962007-05-02 13:16:30 +00003529 assert(rc==SQLITE_OK || pPage==0);
3530 if( next==0 && rc==SQLITE_OK ){
3531 next = get4byte(pPage->aData);
3532 }
danielk1977443c0592009-01-16 15:21:05 +00003533 }
danielk197745d68822009-01-16 16:23:38 +00003534
danielk1977bea2a942009-01-20 17:06:27 +00003535 *pPgnoNext = next;
3536 if( ppPage ){
3537 *ppPage = pPage;
3538 }else{
3539 releasePage(pPage);
3540 }
3541 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
danielk1977d04417962007-05-02 13:16:30 +00003542}
3543
danielk1977da107192007-05-04 08:32:13 +00003544/*
3545** Copy data from a buffer to a page, or from a page to a buffer.
3546**
3547** pPayload is a pointer to data stored on database page pDbPage.
3548** If argument eOp is false, then nByte bytes of data are copied
3549** from pPayload to the buffer pointed at by pBuf. If eOp is true,
3550** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
3551** of data are copied from the buffer pBuf to pPayload.
3552**
3553** SQLITE_OK is returned on success, otherwise an error code.
3554*/
3555static int copyPayload(
3556 void *pPayload, /* Pointer to page data */
3557 void *pBuf, /* Pointer to buffer */
3558 int nByte, /* Number of bytes to copy */
3559 int eOp, /* 0 -> copy from page, 1 -> copy to page */
3560 DbPage *pDbPage /* Page containing pPayload */
3561){
3562 if( eOp ){
3563 /* Copy data from buffer to page (a write operation) */
3564 int rc = sqlite3PagerWrite(pDbPage);
3565 if( rc!=SQLITE_OK ){
3566 return rc;
3567 }
3568 memcpy(pPayload, pBuf, nByte);
3569 }else{
3570 /* Copy data from page to buffer (a read operation) */
3571 memcpy(pBuf, pPayload, nByte);
3572 }
3573 return SQLITE_OK;
3574}
danielk1977d04417962007-05-02 13:16:30 +00003575
3576/*
danielk19779f8d6402007-05-02 17:48:45 +00003577** This function is used to read or overwrite payload information
3578** for the entry that the pCur cursor is pointing to. If the eOp
3579** parameter is 0, this is a read operation (data copied into
3580** buffer pBuf). If it is non-zero, a write (data copied from
3581** buffer pBuf).
3582**
3583** A total of "amt" bytes are read or written beginning at "offset".
3584** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00003585**
3586** This routine does not make a distinction between key and data.
danielk19779f8d6402007-05-02 17:48:45 +00003587** It just reads or writes bytes from the payload area. Data might
3588** appear on the main page or be scattered out on multiple overflow
3589** pages.
danielk1977da107192007-05-04 08:32:13 +00003590**
danielk1977dcbb5d32007-05-04 18:36:44 +00003591** If the BtCursor.isIncrblobHandle flag is set, and the current
danielk1977da107192007-05-04 08:32:13 +00003592** cursor entry uses one or more overflow pages, this function
3593** allocates space for and lazily popluates the overflow page-list
3594** cache array (BtCursor.aOverflow). Subsequent calls use this
3595** cache to make seeking to the supplied offset more efficient.
3596**
3597** Once an overflow page-list cache has been allocated, it may be
3598** invalidated if some other cursor writes to the same table, or if
3599** the cursor is moved to a different row. Additionally, in auto-vacuum
3600** mode, the following events may invalidate an overflow page-list cache.
3601**
3602** * An incremental vacuum,
3603** * A commit in auto_vacuum="full" mode,
3604** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00003605*/
danielk19779f8d6402007-05-02 17:48:45 +00003606static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00003607 BtCursor *pCur, /* Cursor pointing to entry to read from */
danielk197789d40042008-11-17 14:20:56 +00003608 u32 offset, /* Begin reading this far into payload */
3609 u32 amt, /* Read this many bytes */
drh3aac2dd2004-04-26 14:10:20 +00003610 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00003611 int skipKey, /* offset begins at data if this is true */
3612 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00003613){
3614 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00003615 int rc = SQLITE_OK;
drhfa1a98a2004-05-14 19:08:17 +00003616 u32 nKey;
danielk19772dec9702007-05-02 16:48:37 +00003617 int iIdx = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003618 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
danielk19770d065412008-11-12 18:21:36 +00003619 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
drh3aac2dd2004-04-26 14:10:20 +00003620
danielk1977da107192007-05-04 08:32:13 +00003621 assert( pPage );
danielk1977da184232006-01-05 11:34:32 +00003622 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003623 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh1fee73e2007-08-29 04:00:57 +00003624 assert( cursorHoldsMutex(pCur) );
danielk1977da107192007-05-04 08:32:13 +00003625
drh86057612007-06-26 01:04:48 +00003626 getCellInfo(pCur);
drh366fda62006-01-13 02:35:09 +00003627 aPayload = pCur->info.pCell + pCur->info.nHeader;
drhf49661a2008-12-10 16:45:50 +00003628 nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
danielk1977da107192007-05-04 08:32:13 +00003629
drh3aac2dd2004-04-26 14:10:20 +00003630 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003631 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00003632 }
danielk19770d065412008-11-12 18:21:36 +00003633 if( offset+amt > nKey+pCur->info.nData
3634 || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
3635 ){
danielk1977da107192007-05-04 08:32:13 +00003636 /* Trying to read or write past the end of the data is an error */
danielk197767fd7a92008-09-10 17:53:35 +00003637 return SQLITE_CORRUPT_BKPT;
drh3aac2dd2004-04-26 14:10:20 +00003638 }
danielk1977da107192007-05-04 08:32:13 +00003639
3640 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00003641 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00003642 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00003643 if( a+offset>pCur->info.nLocal ){
3644 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00003645 }
danielk1977da107192007-05-04 08:32:13 +00003646 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00003647 offset = 0;
drha34b6762004-05-07 13:30:42 +00003648 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00003649 amt -= a;
drhdd793422001-06-28 01:54:48 +00003650 }else{
drhfa1a98a2004-05-14 19:08:17 +00003651 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00003652 }
danielk1977da107192007-05-04 08:32:13 +00003653
3654 if( rc==SQLITE_OK && amt>0 ){
danielk197789d40042008-11-17 14:20:56 +00003655 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
danielk1977da107192007-05-04 08:32:13 +00003656 Pgno nextPage;
3657
drhfa1a98a2004-05-14 19:08:17 +00003658 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00003659
danielk19772dec9702007-05-02 16:48:37 +00003660#ifndef SQLITE_OMIT_INCRBLOB
danielk1977dcbb5d32007-05-04 18:36:44 +00003661 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
danielk1977da107192007-05-04 08:32:13 +00003662 ** has not been allocated, allocate it now. The array is sized at
3663 ** one entry for each overflow page in the overflow chain. The
3664 ** page number of the first overflow page is stored in aOverflow[0],
3665 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
3666 ** (the cache is lazily populated).
3667 */
danielk1977dcbb5d32007-05-04 18:36:44 +00003668 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
danielk19772dec9702007-05-02 16:48:37 +00003669 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
drh17435752007-08-16 04:30:38 +00003670 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
danielk19772dec9702007-05-02 16:48:37 +00003671 if( nOvfl && !pCur->aOverflow ){
danielk1977da107192007-05-04 08:32:13 +00003672 rc = SQLITE_NOMEM;
danielk19772dec9702007-05-02 16:48:37 +00003673 }
3674 }
danielk1977da107192007-05-04 08:32:13 +00003675
3676 /* If the overflow page-list cache has been allocated and the
3677 ** entry for the first required overflow page is valid, skip
3678 ** directly to it.
3679 */
danielk19772dec9702007-05-02 16:48:37 +00003680 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
3681 iIdx = (offset/ovflSize);
3682 nextPage = pCur->aOverflow[iIdx];
3683 offset = (offset%ovflSize);
3684 }
3685#endif
danielk1977da107192007-05-04 08:32:13 +00003686
3687 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
3688
3689#ifndef SQLITE_OMIT_INCRBLOB
3690 /* If required, populate the overflow page-list cache. */
3691 if( pCur->aOverflow ){
3692 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
3693 pCur->aOverflow[iIdx] = nextPage;
3694 }
3695#endif
3696
danielk1977d04417962007-05-02 13:16:30 +00003697 if( offset>=ovflSize ){
3698 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00003699 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00003700 ** data is not required. So first try to lookup the overflow
3701 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00003702 ** function.
danielk1977d04417962007-05-02 13:16:30 +00003703 */
danielk19772dec9702007-05-02 16:48:37 +00003704#ifndef SQLITE_OMIT_INCRBLOB
danielk1977da107192007-05-04 08:32:13 +00003705 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
3706 nextPage = pCur->aOverflow[iIdx+1];
3707 } else
danielk19772dec9702007-05-02 16:48:37 +00003708#endif
danielk1977da107192007-05-04 08:32:13 +00003709 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
danielk1977da107192007-05-04 08:32:13 +00003710 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00003711 }else{
danielk19779f8d6402007-05-02 17:48:45 +00003712 /* Need to read this page properly. It contains some of the
3713 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00003714 */
3715 DbPage *pDbPage;
danielk1977cfe9a692004-06-16 12:00:29 +00003716 int a = amt;
danielk1977d04417962007-05-02 13:16:30 +00003717 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
danielk1977da107192007-05-04 08:32:13 +00003718 if( rc==SQLITE_OK ){
3719 aPayload = sqlite3PagerGetData(pDbPage);
3720 nextPage = get4byte(aPayload);
3721 if( a + offset > ovflSize ){
3722 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00003723 }
danielk1977da107192007-05-04 08:32:13 +00003724 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
3725 sqlite3PagerUnref(pDbPage);
3726 offset = 0;
3727 amt -= a;
3728 pBuf += a;
danielk19779f8d6402007-05-02 17:48:45 +00003729 }
danielk1977cfe9a692004-06-16 12:00:29 +00003730 }
drh2af926b2001-05-15 00:39:25 +00003731 }
drh2af926b2001-05-15 00:39:25 +00003732 }
danielk1977cfe9a692004-06-16 12:00:29 +00003733
danielk1977da107192007-05-04 08:32:13 +00003734 if( rc==SQLITE_OK && amt>0 ){
drh49285702005-09-17 15:20:26 +00003735 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00003736 }
danielk1977da107192007-05-04 08:32:13 +00003737 return rc;
drh2af926b2001-05-15 00:39:25 +00003738}
3739
drh72f82862001-05-24 21:06:34 +00003740/*
drh3aac2dd2004-04-26 14:10:20 +00003741** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003742** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003743** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00003744**
drh3aac2dd2004-04-26 14:10:20 +00003745** Return SQLITE_OK on success or an error code if anything goes
3746** wrong. An error is returned if "offset+amt" is larger than
3747** the available payload.
drh72f82862001-05-24 21:06:34 +00003748*/
drha34b6762004-05-07 13:30:42 +00003749int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003750 int rc;
3751
drh1fee73e2007-08-29 04:00:57 +00003752 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003753 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003754 if( rc==SQLITE_OK ){
3755 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003756 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3757 if( pCur->apPage[0]->intKey ){
danielk1977da184232006-01-05 11:34:32 +00003758 return SQLITE_CORRUPT_BKPT;
3759 }
danielk197771d5d2c2008-09-29 11:49:47 +00003760 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh16a9b832007-05-05 18:39:25 +00003761 rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
drh6575a222005-03-10 17:06:34 +00003762 }
danielk1977da184232006-01-05 11:34:32 +00003763 return rc;
drh3aac2dd2004-04-26 14:10:20 +00003764}
3765
3766/*
drh3aac2dd2004-04-26 14:10:20 +00003767** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003768** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003769** begins at "offset".
3770**
3771** Return SQLITE_OK on success or an error code if anything goes
3772** wrong. An error is returned if "offset+amt" is larger than
3773** the available payload.
drh72f82862001-05-24 21:06:34 +00003774*/
drh3aac2dd2004-04-26 14:10:20 +00003775int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003776 int rc;
3777
danielk19773588ceb2008-06-10 17:30:26 +00003778#ifndef SQLITE_OMIT_INCRBLOB
3779 if ( pCur->eState==CURSOR_INVALID ){
3780 return SQLITE_ABORT;
3781 }
3782#endif
3783
drh1fee73e2007-08-29 04:00:57 +00003784 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003785 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003786 if( rc==SQLITE_OK ){
3787 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003788 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3789 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh16a9b832007-05-05 18:39:25 +00003790 rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
danielk1977da184232006-01-05 11:34:32 +00003791 }
3792 return rc;
drh2af926b2001-05-15 00:39:25 +00003793}
3794
drh72f82862001-05-24 21:06:34 +00003795/*
drh0e1c19e2004-05-11 00:58:56 +00003796** Return a pointer to payload information from the entry that the
3797** pCur cursor is pointing to. The pointer is to the beginning of
3798** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00003799** skipKey==1. The number of bytes of available key/data is written
3800** into *pAmt. If *pAmt==0, then the value returned will not be
3801** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00003802**
3803** This routine is an optimization. It is common for the entire key
3804** and data to fit on the local page and for there to be no overflow
3805** pages. When that is so, this routine can be used to access the
3806** key and data without making a copy. If the key and/or data spills
drh7f751222009-03-17 22:33:00 +00003807** onto overflow pages, then accessPayload() must be used to reassemble
drh0e1c19e2004-05-11 00:58:56 +00003808** the key/data and copy it into a preallocated buffer.
3809**
3810** The pointer returned by this routine looks directly into the cached
3811** page of the database. The data might change or move the next time
3812** any btree routine is called.
3813*/
3814static const unsigned char *fetchPayload(
3815 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00003816 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00003817 int skipKey /* read beginning at data if this is true */
3818){
3819 unsigned char *aPayload;
3820 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00003821 u32 nKey;
danielk197789d40042008-11-17 14:20:56 +00003822 u32 nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003823
danielk197771d5d2c2008-09-29 11:49:47 +00003824 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
danielk1977da184232006-01-05 11:34:32 +00003825 assert( pCur->eState==CURSOR_VALID );
drh1fee73e2007-08-29 04:00:57 +00003826 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00003827 pPage = pCur->apPage[pCur->iPage];
3828 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh86057612007-06-26 01:04:48 +00003829 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00003830 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00003831 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00003832 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00003833 nKey = 0;
3834 }else{
drhf49661a2008-12-10 16:45:50 +00003835 nKey = (int)pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00003836 }
drh0e1c19e2004-05-11 00:58:56 +00003837 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003838 aPayload += nKey;
3839 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00003840 }else{
drhfa1a98a2004-05-14 19:08:17 +00003841 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00003842 if( nLocal>nKey ){
3843 nLocal = nKey;
3844 }
drh0e1c19e2004-05-11 00:58:56 +00003845 }
drhe51c44f2004-05-30 20:46:09 +00003846 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003847 return aPayload;
3848}
3849
3850
3851/*
drhe51c44f2004-05-30 20:46:09 +00003852** For the entry that cursor pCur is point to, return as
3853** many bytes of the key or data as are available on the local
3854** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00003855**
3856** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00003857** or be destroyed on the next call to any Btree routine,
3858** including calls from other threads against the same cache.
3859** Hence, a mutex on the BtShared should be held prior to calling
3860** this routine.
drh0e1c19e2004-05-11 00:58:56 +00003861**
3862** These routines is used to get quick access to key and data
3863** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00003864*/
drhe51c44f2004-05-30 20:46:09 +00003865const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
danielk19774b0aa4c2009-05-28 11:05:57 +00003866 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh1fee73e2007-08-29 04:00:57 +00003867 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003868 if( pCur->eState==CURSOR_VALID ){
3869 return (const void*)fetchPayload(pCur, pAmt, 0);
3870 }
3871 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003872}
drhe51c44f2004-05-30 20:46:09 +00003873const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
danielk19774b0aa4c2009-05-28 11:05:57 +00003874 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh1fee73e2007-08-29 04:00:57 +00003875 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003876 if( pCur->eState==CURSOR_VALID ){
3877 return (const void*)fetchPayload(pCur, pAmt, 1);
3878 }
3879 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003880}
3881
3882
3883/*
drh8178a752003-01-05 21:41:40 +00003884** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00003885** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00003886*/
drh3aac2dd2004-04-26 14:10:20 +00003887static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00003888 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003889 int i = pCur->iPage;
drh72f82862001-05-24 21:06:34 +00003890 MemPage *pNewPage;
drhd0679ed2007-08-28 22:24:34 +00003891 BtShared *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00003892
drh1fee73e2007-08-29 04:00:57 +00003893 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003894 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003895 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
3896 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
3897 return SQLITE_CORRUPT_BKPT;
3898 }
3899 rc = getAndInitPage(pBt, newPgno, &pNewPage);
drh6019e162001-07-02 17:51:45 +00003900 if( rc ) return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003901 pCur->apPage[i+1] = pNewPage;
3902 pCur->aiIdx[i+1] = 0;
3903 pCur->iPage++;
3904
drh271efa52004-05-30 19:19:05 +00003905 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003906 pCur->validNKey = 0;
drh4be295b2003-12-16 03:44:47 +00003907 if( pNewPage->nCell<1 ){
drh49285702005-09-17 15:20:26 +00003908 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00003909 }
drh72f82862001-05-24 21:06:34 +00003910 return SQLITE_OK;
3911}
3912
danielk1977bf93c562008-09-29 15:53:25 +00003913#ifndef NDEBUG
3914/*
3915** Page pParent is an internal (non-leaf) tree page. This function
3916** asserts that page number iChild is the left-child if the iIdx'th
3917** cell in page pParent. Or, if iIdx is equal to the total number of
3918** cells in pParent, that page number iChild is the right-child of
3919** the page.
3920*/
3921static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
3922 assert( iIdx<=pParent->nCell );
3923 if( iIdx==pParent->nCell ){
3924 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
3925 }else{
3926 assert( get4byte(findCell(pParent, iIdx))==iChild );
3927 }
3928}
3929#else
3930# define assertParentIndex(x,y,z)
3931#endif
3932
drh72f82862001-05-24 21:06:34 +00003933/*
drh5e2f8b92001-05-28 00:41:15 +00003934** Move the cursor up to the parent page.
3935**
3936** pCur->idx is set to the cell index that contains the pointer
3937** to the page we are coming from. If we are coming from the
3938** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00003939** the largest cell index.
drh72f82862001-05-24 21:06:34 +00003940*/
drh16a9b832007-05-05 18:39:25 +00003941void sqlite3BtreeMoveToParent(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00003942 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003943 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003944 assert( pCur->iPage>0 );
3945 assert( pCur->apPage[pCur->iPage] );
danielk1977bf93c562008-09-29 15:53:25 +00003946 assertParentIndex(
3947 pCur->apPage[pCur->iPage-1],
3948 pCur->aiIdx[pCur->iPage-1],
3949 pCur->apPage[pCur->iPage]->pgno
3950 );
danielk197771d5d2c2008-09-29 11:49:47 +00003951 releasePage(pCur->apPage[pCur->iPage]);
3952 pCur->iPage--;
drh271efa52004-05-30 19:19:05 +00003953 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003954 pCur->validNKey = 0;
drh72f82862001-05-24 21:06:34 +00003955}
3956
3957/*
3958** Move the cursor to the root page
3959*/
drh5e2f8b92001-05-28 00:41:15 +00003960static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00003961 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00003962 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003963 Btree *p = pCur->pBtree;
3964 BtShared *pBt = p->pBt;
drhbd03cae2001-06-02 02:40:57 +00003965
drh1fee73e2007-08-29 04:00:57 +00003966 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +00003967 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
3968 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
3969 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
3970 if( pCur->eState>=CURSOR_REQUIRESEEK ){
3971 if( pCur->eState==CURSOR_FAULT ){
3972 return pCur->skip;
3973 }
danielk1977be51a652008-10-08 17:58:48 +00003974 sqlite3BtreeClearCursor(pCur);
drhbf700f32007-03-31 02:36:44 +00003975 }
danielk197771d5d2c2008-09-29 11:49:47 +00003976
3977 if( pCur->iPage>=0 ){
3978 int i;
3979 for(i=1; i<=pCur->iPage; i++){
3980 releasePage(pCur->apPage[i]);
danielk1977d9f6c532008-09-19 16:39:38 +00003981 }
drh777e4c42006-01-13 04:31:58 +00003982 }else{
3983 if(
danielk197771d5d2c2008-09-29 11:49:47 +00003984 SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]))
drh777e4c42006-01-13 04:31:58 +00003985 ){
3986 pCur->eState = CURSOR_INVALID;
3987 return rc;
3988 }
drhc39e0002004-05-07 23:50:57 +00003989 }
danielk197771d5d2c2008-09-29 11:49:47 +00003990
3991 pRoot = pCur->apPage[0];
3992 assert( pRoot->pgno==pCur->pgnoRoot );
3993 pCur->iPage = 0;
3994 pCur->aiIdx[0] = 0;
drh271efa52004-05-30 19:19:05 +00003995 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003996 pCur->atLast = 0;
3997 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003998
drh8856d6a2004-04-29 14:42:46 +00003999 if( pRoot->nCell==0 && !pRoot->leaf ){
4000 Pgno subpage;
drhc85240d2009-06-04 16:14:33 +00004001 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
drh8856d6a2004-04-29 14:42:46 +00004002 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00004003 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00004004 assert( subpage>0 );
danielk1977da184232006-01-05 11:34:32 +00004005 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00004006 rc = moveToChild(pCur, subpage);
danielk197771d5d2c2008-09-29 11:49:47 +00004007 }else{
4008 pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
drh8856d6a2004-04-29 14:42:46 +00004009 }
4010 return rc;
drh72f82862001-05-24 21:06:34 +00004011}
drh2af926b2001-05-15 00:39:25 +00004012
drh5e2f8b92001-05-28 00:41:15 +00004013/*
4014** Move the cursor down to the left-most leaf entry beneath the
4015** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00004016**
4017** The left-most leaf is the one with the smallest key - the first
4018** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00004019*/
4020static int moveToLeftmost(BtCursor *pCur){
4021 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00004022 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00004023 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00004024
drh1fee73e2007-08-29 04:00:57 +00004025 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004026 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004027 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
4028 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
4029 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
drh8178a752003-01-05 21:41:40 +00004030 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00004031 }
drhd677b3d2007-08-20 22:48:41 +00004032 return rc;
drh5e2f8b92001-05-28 00:41:15 +00004033}
4034
drh2dcc9aa2002-12-04 13:40:25 +00004035/*
4036** Move the cursor down to the right-most leaf entry beneath the
4037** page to which it is currently pointing. Notice the difference
4038** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
4039** finds the left-most entry beneath the *entry* whereas moveToRightmost()
4040** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00004041**
4042** The right-most entry is the one with the largest key - the last
4043** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00004044*/
4045static int moveToRightmost(BtCursor *pCur){
4046 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00004047 int rc = SQLITE_OK;
drh1bd10f82008-12-10 21:19:56 +00004048 MemPage *pPage = 0;
drh2dcc9aa2002-12-04 13:40:25 +00004049
drh1fee73e2007-08-29 04:00:57 +00004050 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004051 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004052 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
drh43605152004-05-29 21:46:49 +00004053 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
danielk197771d5d2c2008-09-29 11:49:47 +00004054 pCur->aiIdx[pCur->iPage] = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00004055 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00004056 }
drhd677b3d2007-08-20 22:48:41 +00004057 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00004058 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
drhd677b3d2007-08-20 22:48:41 +00004059 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004060 pCur->validNKey = 0;
drhd677b3d2007-08-20 22:48:41 +00004061 }
danielk1977518002e2008-09-05 05:02:46 +00004062 return rc;
drh2dcc9aa2002-12-04 13:40:25 +00004063}
4064
drh5e00f6c2001-09-13 13:46:56 +00004065/* Move the cursor to the first entry in the table. Return SQLITE_OK
4066** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00004067** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00004068*/
drh3aac2dd2004-04-26 14:10:20 +00004069int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00004070 int rc;
drhd677b3d2007-08-20 22:48:41 +00004071
drh1fee73e2007-08-29 04:00:57 +00004072 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004073 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00004074 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004075 if( rc==SQLITE_OK ){
4076 if( pCur->eState==CURSOR_INVALID ){
danielk197771d5d2c2008-09-29 11:49:47 +00004077 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00004078 *pRes = 1;
4079 rc = SQLITE_OK;
4080 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004081 assert( pCur->apPage[pCur->iPage]->nCell>0 );
drhd677b3d2007-08-20 22:48:41 +00004082 *pRes = 0;
4083 rc = moveToLeftmost(pCur);
4084 }
drh5e00f6c2001-09-13 13:46:56 +00004085 }
drh5e00f6c2001-09-13 13:46:56 +00004086 return rc;
4087}
drh5e2f8b92001-05-28 00:41:15 +00004088
drh9562b552002-02-19 15:00:07 +00004089/* Move the cursor to the last entry in the table. Return SQLITE_OK
4090** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00004091** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00004092*/
drh3aac2dd2004-04-26 14:10:20 +00004093int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00004094 int rc;
drhd677b3d2007-08-20 22:48:41 +00004095
drh1fee73e2007-08-29 04:00:57 +00004096 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004097 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19773f632d52009-05-02 10:03:09 +00004098
4099 /* If the cursor already points to the last entry, this is a no-op. */
4100 if( CURSOR_VALID==pCur->eState && pCur->atLast ){
4101#ifdef SQLITE_DEBUG
4102 /* This block serves to assert() that the cursor really does point
4103 ** to the last entry in the b-tree. */
4104 int ii;
4105 for(ii=0; ii<pCur->iPage; ii++){
4106 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
4107 }
4108 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
4109 assert( pCur->apPage[pCur->iPage]->leaf );
4110#endif
4111 return SQLITE_OK;
4112 }
4113
drh9562b552002-02-19 15:00:07 +00004114 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004115 if( rc==SQLITE_OK ){
4116 if( CURSOR_INVALID==pCur->eState ){
danielk197771d5d2c2008-09-29 11:49:47 +00004117 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00004118 *pRes = 1;
4119 }else{
4120 assert( pCur->eState==CURSOR_VALID );
4121 *pRes = 0;
4122 rc = moveToRightmost(pCur);
drhf49661a2008-12-10 16:45:50 +00004123 pCur->atLast = rc==SQLITE_OK ?1:0;
drhd677b3d2007-08-20 22:48:41 +00004124 }
drh9562b552002-02-19 15:00:07 +00004125 }
drh9562b552002-02-19 15:00:07 +00004126 return rc;
4127}
4128
drhe14006d2008-03-25 17:23:32 +00004129/* Move the cursor so that it points to an entry near the key
drhe63d9992008-08-13 19:11:48 +00004130** specified by pIdxKey or intKey. Return a success code.
drh72f82862001-05-24 21:06:34 +00004131**
drhe63d9992008-08-13 19:11:48 +00004132** For INTKEY tables, the intKey parameter is used. pIdxKey
4133** must be NULL. For index tables, pIdxKey is used and intKey
4134** is ignored.
drh3aac2dd2004-04-26 14:10:20 +00004135**
drh5e2f8b92001-05-28 00:41:15 +00004136** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00004137** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00004138** were present. The cursor might point to an entry that comes
4139** before or after the key.
4140**
drh64022502009-01-09 14:11:04 +00004141** An integer is written into *pRes which is the result of
4142** comparing the key with the entry to which the cursor is
4143** pointing. The meaning of the integer written into
4144** *pRes is as follows:
drhbd03cae2001-06-02 02:40:57 +00004145**
4146** *pRes<0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004147** is smaller than intKey/pIdxKey or if the table is empty
drh1a844c32002-12-04 22:29:28 +00004148** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00004149**
4150** *pRes==0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004151** exactly matches intKey/pIdxKey.
drhbd03cae2001-06-02 02:40:57 +00004152**
4153** *pRes>0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004154** is larger than intKey/pIdxKey.
drhd677b3d2007-08-20 22:48:41 +00004155**
drha059ad02001-04-17 20:09:11 +00004156*/
drhe63d9992008-08-13 19:11:48 +00004157int sqlite3BtreeMovetoUnpacked(
4158 BtCursor *pCur, /* The cursor to be moved */
4159 UnpackedRecord *pIdxKey, /* Unpacked index key */
4160 i64 intKey, /* The table key */
4161 int biasRight, /* If true, bias the search to the high end */
4162 int *pRes /* Write search results here */
drhe4d90812007-03-29 05:51:49 +00004163){
drh72f82862001-05-24 21:06:34 +00004164 int rc;
drhd677b3d2007-08-20 22:48:41 +00004165
drh1fee73e2007-08-29 04:00:57 +00004166 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004167 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drha2c20e42008-03-29 16:01:04 +00004168
4169 /* If the cursor is already positioned at the point we are trying
4170 ** to move to, then just return without doing any work */
danielk197771d5d2c2008-09-29 11:49:47 +00004171 if( pCur->eState==CURSOR_VALID && pCur->validNKey
4172 && pCur->apPage[0]->intKey
4173 ){
drhe63d9992008-08-13 19:11:48 +00004174 if( pCur->info.nKey==intKey ){
drha2c20e42008-03-29 16:01:04 +00004175 *pRes = 0;
4176 return SQLITE_OK;
4177 }
drhe63d9992008-08-13 19:11:48 +00004178 if( pCur->atLast && pCur->info.nKey<intKey ){
drha2c20e42008-03-29 16:01:04 +00004179 *pRes = -1;
4180 return SQLITE_OK;
4181 }
4182 }
4183
drh5e2f8b92001-05-28 00:41:15 +00004184 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004185 if( rc ){
4186 return rc;
4187 }
danielk197771d5d2c2008-09-29 11:49:47 +00004188 assert( pCur->apPage[pCur->iPage] );
4189 assert( pCur->apPage[pCur->iPage]->isInit );
danielk1977da184232006-01-05 11:34:32 +00004190 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00004191 *pRes = -1;
danielk197771d5d2c2008-09-29 11:49:47 +00004192 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhc39e0002004-05-07 23:50:57 +00004193 return SQLITE_OK;
4194 }
danielk197771d5d2c2008-09-29 11:49:47 +00004195 assert( pCur->apPage[0]->intKey || pIdxKey );
drh14684382006-11-30 13:05:29 +00004196 for(;;){
drh72f82862001-05-24 21:06:34 +00004197 int lwr, upr;
4198 Pgno chldPg;
danielk197771d5d2c2008-09-29 11:49:47 +00004199 MemPage *pPage = pCur->apPage[pCur->iPage];
drh1a844c32002-12-04 22:29:28 +00004200 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00004201 lwr = 0;
4202 upr = pPage->nCell-1;
drh64022502009-01-09 14:11:04 +00004203 if( (!pPage->intKey && pIdxKey==0) || upr<0 ){
drh1e968a02008-03-25 00:22:21 +00004204 rc = SQLITE_CORRUPT_BKPT;
4205 goto moveto_finish;
drh4eec4c12005-01-21 00:22:37 +00004206 }
drhe4d90812007-03-29 05:51:49 +00004207 if( biasRight ){
drhf49661a2008-12-10 16:45:50 +00004208 pCur->aiIdx[pCur->iPage] = (u16)upr;
drhe4d90812007-03-29 05:51:49 +00004209 }else{
drhf49661a2008-12-10 16:45:50 +00004210 pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
drhe4d90812007-03-29 05:51:49 +00004211 }
drh64022502009-01-09 14:11:04 +00004212 for(;;){
danielk197711c327a2009-05-04 19:01:26 +00004213 int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
4214 u8 *pCell; /* Pointer to current cell in pPage */
4215
drh366fda62006-01-13 02:35:09 +00004216 pCur->info.nSize = 0;
danielk197711c327a2009-05-04 19:01:26 +00004217 pCell = findCell(pPage, idx) + pPage->childPtrSize;
drh3aac2dd2004-04-26 14:10:20 +00004218 if( pPage->intKey ){
danielk197711c327a2009-05-04 19:01:26 +00004219 i64 nCellKey;
drhd172f862006-01-12 15:01:15 +00004220 if( pPage->hasData ){
danielk1977bab45c62006-01-16 15:14:27 +00004221 u32 dummy;
shane3f8d5cf2008-04-24 19:15:09 +00004222 pCell += getVarint32(pCell, dummy);
drhd172f862006-01-12 15:01:15 +00004223 }
drha2c20e42008-03-29 16:01:04 +00004224 getVarint(pCell, (u64*)&nCellKey);
drhe63d9992008-08-13 19:11:48 +00004225 if( nCellKey==intKey ){
drh3aac2dd2004-04-26 14:10:20 +00004226 c = 0;
drhe63d9992008-08-13 19:11:48 +00004227 }else if( nCellKey<intKey ){
drh41eb9e92008-04-02 18:33:07 +00004228 c = -1;
4229 }else{
drhe63d9992008-08-13 19:11:48 +00004230 assert( nCellKey>intKey );
drh41eb9e92008-04-02 18:33:07 +00004231 c = +1;
drh3aac2dd2004-04-26 14:10:20 +00004232 }
danielk197711c327a2009-05-04 19:01:26 +00004233 pCur->validNKey = 1;
4234 pCur->info.nKey = nCellKey;
drh3aac2dd2004-04-26 14:10:20 +00004235 }else{
danielk197711c327a2009-05-04 19:01:26 +00004236 /* The maximum supported page-size is 32768 bytes. This means that
4237 ** the maximum number of record bytes stored on an index B-Tree
4238 ** page is at most 8198 bytes, which may be stored as a 2-byte
4239 ** varint. This information is used to attempt to avoid parsing
4240 ** the entire cell by checking for the cases where the record is
4241 ** stored entirely within the b-tree page by inspecting the first
4242 ** 2 bytes of the cell.
4243 */
4244 int nCell = pCell[0];
4245 if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
4246 /* This branch runs if the record-size field of the cell is a
4247 ** single byte varint and the record fits entirely on the main
4248 ** b-tree page. */
4249 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
4250 }else if( !(pCell[1] & 0x80)
4251 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
4252 ){
4253 /* The record-size field is a 2 byte varint and the record
4254 ** fits entirely on the main b-tree page. */
4255 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
drhe51c44f2004-05-30 20:46:09 +00004256 }else{
danielk197711c327a2009-05-04 19:01:26 +00004257 /* The record flows over onto one or more overflow pages. In
4258 ** this case the whole cell needs to be parsed, a buffer allocated
4259 ** and accessPayload() used to retrieve the record into the
4260 ** buffer before VdbeRecordCompare() can be called. */
4261 void *pCellKey;
4262 u8 * const pCellBody = pCell - pPage->childPtrSize;
4263 sqlite3BtreeParseCellPtr(pPage, pCellBody, &pCur->info);
shane60a4b532009-05-06 18:57:09 +00004264 nCell = (int)pCur->info.nKey;
danielk197711c327a2009-05-04 19:01:26 +00004265 pCellKey = sqlite3Malloc( nCell );
danielk19776507ecb2008-03-25 09:56:44 +00004266 if( pCellKey==0 ){
4267 rc = SQLITE_NOMEM;
4268 goto moveto_finish;
4269 }
danielk197711c327a2009-05-04 19:01:26 +00004270 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0, 0);
4271 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
drhfacf0302008-06-17 15:12:00 +00004272 sqlite3_free(pCellKey);
drh1e968a02008-03-25 00:22:21 +00004273 if( rc ) goto moveto_finish;
drhe51c44f2004-05-30 20:46:09 +00004274 }
drh3aac2dd2004-04-26 14:10:20 +00004275 }
drh72f82862001-05-24 21:06:34 +00004276 if( c==0 ){
drh44845222008-07-17 18:39:57 +00004277 if( pPage->intKey && !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00004278 lwr = idx;
drhfc70e6f2004-05-12 21:11:27 +00004279 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00004280 break;
4281 }else{
drh64022502009-01-09 14:11:04 +00004282 *pRes = 0;
drh1e968a02008-03-25 00:22:21 +00004283 rc = SQLITE_OK;
4284 goto moveto_finish;
drh8b18dd42004-05-12 19:18:15 +00004285 }
drh72f82862001-05-24 21:06:34 +00004286 }
4287 if( c<0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00004288 lwr = idx+1;
drh72f82862001-05-24 21:06:34 +00004289 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004290 upr = idx-1;
drh72f82862001-05-24 21:06:34 +00004291 }
drhf1d68b32007-03-29 04:43:26 +00004292 if( lwr>upr ){
4293 break;
4294 }
drhf49661a2008-12-10 16:45:50 +00004295 pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
drh72f82862001-05-24 21:06:34 +00004296 }
4297 assert( lwr==upr+1 );
danielk197771d5d2c2008-09-29 11:49:47 +00004298 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00004299 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00004300 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00004301 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00004302 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00004303 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00004304 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00004305 }
4306 if( chldPg==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00004307 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh72f82862001-05-24 21:06:34 +00004308 if( pRes ) *pRes = c;
drh1e968a02008-03-25 00:22:21 +00004309 rc = SQLITE_OK;
4310 goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00004311 }
drhf49661a2008-12-10 16:45:50 +00004312 pCur->aiIdx[pCur->iPage] = (u16)lwr;
drh271efa52004-05-30 19:19:05 +00004313 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004314 pCur->validNKey = 0;
drh8178a752003-01-05 21:41:40 +00004315 rc = moveToChild(pCur, chldPg);
drh1e968a02008-03-25 00:22:21 +00004316 if( rc ) goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00004317 }
drh1e968a02008-03-25 00:22:21 +00004318moveto_finish:
drhe63d9992008-08-13 19:11:48 +00004319 return rc;
4320}
4321
4322/*
4323** In this version of BtreeMoveto, pKey is a packed index record
4324** such as is generated by the OP_MakeRecord opcode. Unpack the
4325** record and then call BtreeMovetoUnpacked() to do the work.
4326*/
4327int sqlite3BtreeMoveto(
4328 BtCursor *pCur, /* Cursor open on the btree to be searched */
4329 const void *pKey, /* Packed key if the btree is an index */
4330 i64 nKey, /* Integer key for tables. Size of pKey for indices */
4331 int bias, /* Bias search to the high end */
4332 int *pRes /* Write search results here */
4333){
4334 int rc; /* Status code */
4335 UnpackedRecord *pIdxKey; /* Unpacked index key */
drh8c5d1522009-04-10 00:56:28 +00004336 char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
4337
drhe63d9992008-08-13 19:11:48 +00004338
drhe14006d2008-03-25 17:23:32 +00004339 if( pKey ){
drhf49661a2008-12-10 16:45:50 +00004340 assert( nKey==(i64)(int)nKey );
4341 pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
drh23f79d02008-08-20 22:06:47 +00004342 aSpace, sizeof(aSpace));
drhe63d9992008-08-13 19:11:48 +00004343 if( pIdxKey==0 ) return SQLITE_NOMEM;
4344 }else{
4345 pIdxKey = 0;
4346 }
4347 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
4348 if( pKey ){
4349 sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
drhe14006d2008-03-25 17:23:32 +00004350 }
drh1e968a02008-03-25 00:22:21 +00004351 return rc;
drh72f82862001-05-24 21:06:34 +00004352}
4353
drhd677b3d2007-08-20 22:48:41 +00004354
drh72f82862001-05-24 21:06:34 +00004355/*
drhc39e0002004-05-07 23:50:57 +00004356** Return TRUE if the cursor is not pointing at an entry of the table.
4357**
4358** TRUE will be returned after a call to sqlite3BtreeNext() moves
4359** past the last entry in the table or sqlite3BtreePrev() moves past
4360** the first entry. TRUE is also returned if the table is empty.
4361*/
4362int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00004363 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
4364 ** have been deleted? This API will need to change to return an error code
4365 ** as well as the boolean result value.
4366 */
4367 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00004368}
4369
4370/*
drhbd03cae2001-06-02 02:40:57 +00004371** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00004372** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00004373** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00004374** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00004375*/
drhd094db12008-04-03 21:46:57 +00004376int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00004377 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00004378 int idx;
danielk197797a227c2006-01-20 16:32:04 +00004379 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00004380
drh1fee73e2007-08-29 04:00:57 +00004381 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004382 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004383 if( rc!=SQLITE_OK ){
4384 return rc;
4385 }
drh8c4d3a62007-04-06 01:03:32 +00004386 assert( pRes!=0 );
drh8c4d3a62007-04-06 01:03:32 +00004387 if( CURSOR_INVALID==pCur->eState ){
4388 *pRes = 1;
4389 return SQLITE_OK;
4390 }
danielk1977da184232006-01-05 11:34:32 +00004391 if( pCur->skip>0 ){
4392 pCur->skip = 0;
4393 *pRes = 0;
4394 return SQLITE_OK;
4395 }
4396 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00004397
danielk197771d5d2c2008-09-29 11:49:47 +00004398 pPage = pCur->apPage[pCur->iPage];
4399 idx = ++pCur->aiIdx[pCur->iPage];
4400 assert( pPage->isInit );
4401 assert( idx<=pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00004402
drh271efa52004-05-30 19:19:05 +00004403 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004404 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004405 if( idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00004406 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004407 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00004408 if( rc ) return rc;
4409 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00004410 *pRes = 0;
4411 return rc;
drh72f82862001-05-24 21:06:34 +00004412 }
drh5e2f8b92001-05-28 00:41:15 +00004413 do{
danielk197771d5d2c2008-09-29 11:49:47 +00004414 if( pCur->iPage==0 ){
drh8c1238a2003-01-02 14:43:55 +00004415 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00004416 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00004417 return SQLITE_OK;
4418 }
drh16a9b832007-05-05 18:39:25 +00004419 sqlite3BtreeMoveToParent(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00004420 pPage = pCur->apPage[pCur->iPage];
4421 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00004422 *pRes = 0;
drh44845222008-07-17 18:39:57 +00004423 if( pPage->intKey ){
drh8b18dd42004-05-12 19:18:15 +00004424 rc = sqlite3BtreeNext(pCur, pRes);
4425 }else{
4426 rc = SQLITE_OK;
4427 }
4428 return rc;
drh8178a752003-01-05 21:41:40 +00004429 }
4430 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00004431 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00004432 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00004433 }
drh5e2f8b92001-05-28 00:41:15 +00004434 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00004435 return rc;
drh72f82862001-05-24 21:06:34 +00004436}
drhd677b3d2007-08-20 22:48:41 +00004437
drh72f82862001-05-24 21:06:34 +00004438
drh3b7511c2001-05-26 13:15:44 +00004439/*
drh2dcc9aa2002-12-04 13:40:25 +00004440** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00004441** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00004442** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00004443** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00004444*/
drhd094db12008-04-03 21:46:57 +00004445int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00004446 int rc;
drh8178a752003-01-05 21:41:40 +00004447 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00004448
drh1fee73e2007-08-29 04:00:57 +00004449 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004450 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004451 if( rc!=SQLITE_OK ){
4452 return rc;
4453 }
drha2c20e42008-03-29 16:01:04 +00004454 pCur->atLast = 0;
drh8c4d3a62007-04-06 01:03:32 +00004455 if( CURSOR_INVALID==pCur->eState ){
4456 *pRes = 1;
4457 return SQLITE_OK;
4458 }
danielk1977da184232006-01-05 11:34:32 +00004459 if( pCur->skip<0 ){
4460 pCur->skip = 0;
4461 *pRes = 0;
4462 return SQLITE_OK;
4463 }
4464 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00004465
danielk197771d5d2c2008-09-29 11:49:47 +00004466 pPage = pCur->apPage[pCur->iPage];
4467 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00004468 if( !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00004469 int idx = pCur->aiIdx[pCur->iPage];
4470 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
drhd677b3d2007-08-20 22:48:41 +00004471 if( rc ){
4472 return rc;
4473 }
drh2dcc9aa2002-12-04 13:40:25 +00004474 rc = moveToRightmost(pCur);
4475 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004476 while( pCur->aiIdx[pCur->iPage]==0 ){
4477 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00004478 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00004479 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00004480 return SQLITE_OK;
4481 }
drh16a9b832007-05-05 18:39:25 +00004482 sqlite3BtreeMoveToParent(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00004483 }
drh271efa52004-05-30 19:19:05 +00004484 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004485 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004486
4487 pCur->aiIdx[pCur->iPage]--;
4488 pPage = pCur->apPage[pCur->iPage];
drh44845222008-07-17 18:39:57 +00004489 if( pPage->intKey && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00004490 rc = sqlite3BtreePrevious(pCur, pRes);
4491 }else{
4492 rc = SQLITE_OK;
4493 }
drh2dcc9aa2002-12-04 13:40:25 +00004494 }
drh8178a752003-01-05 21:41:40 +00004495 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00004496 return rc;
4497}
4498
4499/*
drh3b7511c2001-05-26 13:15:44 +00004500** Allocate a new page from the database file.
4501**
danielk19773b8a05f2007-03-19 17:44:26 +00004502** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00004503** has already been called on the new page.) The new page has also
4504** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00004505** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00004506**
4507** SQLITE_OK is returned on success. Any other return value indicates
4508** an error. *ppPage and *pPgno are undefined in the event of an error.
danielk19773b8a05f2007-03-19 17:44:26 +00004509** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00004510**
drh199e3cf2002-07-18 11:01:47 +00004511** If the "nearby" parameter is not 0, then a (feeble) effort is made to
4512** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00004513** attempt to keep related pages close to each other in the database file,
4514** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00004515**
4516** If the "exact" parameter is not 0, and the page-number nearby exists
4517** anywhere on the free-list, then it is guarenteed to be returned. This
4518** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00004519*/
drh4f0c5872007-03-26 22:05:01 +00004520static int allocateBtreePage(
danielk1977aef0bf62005-12-30 16:28:01 +00004521 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00004522 MemPage **ppPage,
4523 Pgno *pPgno,
4524 Pgno nearby,
4525 u8 exact
4526){
drh3aac2dd2004-04-26 14:10:20 +00004527 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00004528 int rc;
drh35cd6432009-06-05 14:17:21 +00004529 u32 n; /* Number of pages on the freelist */
drh042d6a12009-06-17 13:57:16 +00004530 u32 k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00004531 MemPage *pTrunk = 0;
4532 MemPage *pPrevTrunk = 0;
drh1662b5a2009-06-04 19:06:09 +00004533 Pgno mxPage; /* Total size of the database file */
drh30e58752002-03-02 20:41:57 +00004534
drh1fee73e2007-08-29 04:00:57 +00004535 assert( sqlite3_mutex_held(pBt->mutex) );
drh3aac2dd2004-04-26 14:10:20 +00004536 pPage1 = pBt->pPage1;
drh1662b5a2009-06-04 19:06:09 +00004537 mxPage = pagerPagecount(pBt);
drh3aac2dd2004-04-26 14:10:20 +00004538 n = get4byte(&pPage1->aData[36]);
drh1662b5a2009-06-04 19:06:09 +00004539 if( n>mxPage ){
4540 return SQLITE_CORRUPT_BKPT;
4541 }
drh3aac2dd2004-04-26 14:10:20 +00004542 if( n>0 ){
drh91025292004-05-03 19:49:32 +00004543 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00004544 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004545 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
4546
4547 /* If the 'exact' parameter was true and a query of the pointer-map
4548 ** shows that the page 'nearby' is somewhere on the free-list, then
4549 ** the entire-list will be searched for that page.
4550 */
4551#ifndef SQLITE_OMIT_AUTOVACUUM
drh1662b5a2009-06-04 19:06:09 +00004552 if( exact && nearby<=mxPage ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004553 u8 eType;
4554 assert( nearby>0 );
4555 assert( pBt->autoVacuum );
4556 rc = ptrmapGet(pBt, nearby, &eType, 0);
4557 if( rc ) return rc;
4558 if( eType==PTRMAP_FREEPAGE ){
4559 searchList = 1;
4560 }
4561 *pPgno = nearby;
4562 }
4563#endif
4564
4565 /* Decrement the free-list count by 1. Set iTrunk to the index of the
4566 ** first free-list trunk page. iPrevTrunk is initially 1.
4567 */
danielk19773b8a05f2007-03-19 17:44:26 +00004568 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00004569 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004570 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004571
4572 /* The code within this loop is run only once if the 'searchList' variable
4573 ** is not true. Otherwise, it runs once for each trunk-page on the
4574 ** free-list until the page 'nearby' is located.
4575 */
4576 do {
4577 pPrevTrunk = pTrunk;
4578 if( pPrevTrunk ){
4579 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00004580 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004581 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00004582 }
drh1662b5a2009-06-04 19:06:09 +00004583 if( iTrunk>mxPage ){
4584 rc = SQLITE_CORRUPT_BKPT;
4585 }else{
4586 rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
4587 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004588 if( rc ){
drhd3627af2006-12-18 18:34:51 +00004589 pTrunk = 0;
4590 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004591 }
4592
4593 k = get4byte(&pTrunk->aData[4]);
4594 if( k==0 && !searchList ){
4595 /* The trunk has no leaves and the list is not being searched.
4596 ** So extract the trunk page itself and use it as the newly
4597 ** allocated page */
4598 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00004599 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004600 if( rc ){
4601 goto end_allocate_page;
4602 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004603 *pPgno = iTrunk;
4604 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4605 *ppPage = pTrunk;
4606 pTrunk = 0;
4607 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh042d6a12009-06-17 13:57:16 +00004608 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004609 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00004610 rc = SQLITE_CORRUPT_BKPT;
4611 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004612#ifndef SQLITE_OMIT_AUTOVACUUM
4613 }else if( searchList && nearby==iTrunk ){
4614 /* The list is being searched and this trunk page is the page
4615 ** to allocate, regardless of whether it has leaves.
4616 */
4617 assert( *pPgno==iTrunk );
4618 *ppPage = pTrunk;
4619 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00004620 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004621 if( rc ){
4622 goto end_allocate_page;
4623 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004624 if( k==0 ){
4625 if( !pPrevTrunk ){
4626 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4627 }else{
4628 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
4629 }
4630 }else{
4631 /* The trunk page is required by the caller but it contains
4632 ** pointers to free-list leaves. The first leaf becomes a trunk
4633 ** page in this case.
4634 */
4635 MemPage *pNewTrunk;
4636 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh1662b5a2009-06-04 19:06:09 +00004637 if( iNewTrunk>mxPage ){
4638 rc = SQLITE_CORRUPT_BKPT;
4639 goto end_allocate_page;
4640 }
drh16a9b832007-05-05 18:39:25 +00004641 rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004642 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00004643 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004644 }
danielk19773b8a05f2007-03-19 17:44:26 +00004645 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004646 if( rc!=SQLITE_OK ){
4647 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00004648 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004649 }
4650 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
4651 put4byte(&pNewTrunk->aData[4], k-1);
4652 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00004653 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004654 if( !pPrevTrunk ){
drhc5053fb2008-11-27 02:22:10 +00004655 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
danielk1977cb1a7eb2004-11-05 12:27:02 +00004656 put4byte(&pPage1->aData[32], iNewTrunk);
4657 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00004658 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004659 if( rc ){
4660 goto end_allocate_page;
4661 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004662 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
4663 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004664 }
4665 pTrunk = 0;
4666 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
4667#endif
danielk1977e5765212009-06-17 11:13:28 +00004668 }else if( k>0 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004669 /* Extract a leaf from the trunk */
drh042d6a12009-06-17 13:57:16 +00004670 u32 closest;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004671 Pgno iPage;
4672 unsigned char *aData = pTrunk->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00004673 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004674 if( rc ){
4675 goto end_allocate_page;
4676 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004677 if( nearby>0 ){
drh042d6a12009-06-17 13:57:16 +00004678 u32 i;
4679 int dist;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004680 closest = 0;
4681 dist = get4byte(&aData[8]) - nearby;
4682 if( dist<0 ) dist = -dist;
4683 for(i=1; i<k; i++){
4684 int d2 = get4byte(&aData[8+i*4]) - nearby;
4685 if( d2<0 ) d2 = -d2;
4686 if( d2<dist ){
4687 closest = i;
4688 dist = d2;
4689 }
4690 }
4691 }else{
4692 closest = 0;
4693 }
4694
4695 iPage = get4byte(&aData[8+closest*4]);
drh1662b5a2009-06-04 19:06:09 +00004696 if( iPage>mxPage ){
4697 rc = SQLITE_CORRUPT_BKPT;
4698 goto end_allocate_page;
4699 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004700 if( !searchList || iPage==nearby ){
danielk1977bea2a942009-01-20 17:06:27 +00004701 int noContent;
danielk197789d40042008-11-17 14:20:56 +00004702 Pgno nPage;
shane1f9e6aa2008-06-09 19:27:11 +00004703 *pPgno = iPage;
danielk197789d40042008-11-17 14:20:56 +00004704 nPage = pagerPagecount(pBt);
danielk19774dbaa892009-06-16 16:50:22 +00004705 if( iPage>nPage ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004706 /* Free page off the end of the file */
danielk197743e377a2008-05-05 12:09:32 +00004707 rc = SQLITE_CORRUPT_BKPT;
4708 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004709 }
4710 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
4711 ": %d more free pages\n",
4712 *pPgno, closest+1, k, pTrunk->pgno, n-1));
4713 if( closest<k-1 ){
4714 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
4715 }
4716 put4byte(&aData[4], k-1);
drhc5053fb2008-11-27 02:22:10 +00004717 assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
danielk1977bea2a942009-01-20 17:06:27 +00004718 noContent = !btreeGetHasContent(pBt, *pPgno);
4719 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, noContent);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004720 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00004721 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004722 if( rc!=SQLITE_OK ){
4723 releasePage(*ppPage);
4724 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004725 }
4726 searchList = 0;
4727 }
drhee696e22004-08-30 16:52:17 +00004728 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004729 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00004730 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004731 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00004732 }else{
drh3aac2dd2004-04-26 14:10:20 +00004733 /* There are no pages on the freelist, so create a new page at the
4734 ** end of the file */
danielk197789d40042008-11-17 14:20:56 +00004735 int nPage = pagerPagecount(pBt);
danielk1977ad0132d2008-06-07 08:58:22 +00004736 *pPgno = nPage + 1;
danielk1977afcdd022004-10-31 16:25:42 +00004737
danielk1977bea2a942009-01-20 17:06:27 +00004738 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
4739 (*pPgno)++;
4740 }
4741
danielk1977afcdd022004-10-31 16:25:42 +00004742#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977266664d2006-02-10 08:24:21 +00004743 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00004744 /* If *pPgno refers to a pointer-map page, allocate two new pages
4745 ** at the end of the file instead of one. The first allocated page
4746 ** becomes a new pointer-map page, the second is used by the caller.
4747 */
danielk1977ac861692009-03-28 10:54:22 +00004748 MemPage *pPg = 0;
danielk1977afcdd022004-10-31 16:25:42 +00004749 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00004750 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977ac861692009-03-28 10:54:22 +00004751 rc = sqlite3BtreeGetPage(pBt, *pPgno, &pPg, 0);
4752 if( rc==SQLITE_OK ){
4753 rc = sqlite3PagerWrite(pPg->pDbPage);
4754 releasePage(pPg);
4755 }
4756 if( rc ) return rc;
danielk1977afcdd022004-10-31 16:25:42 +00004757 (*pPgno)++;
drh72190432008-01-31 14:54:43 +00004758 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
danielk1977afcdd022004-10-31 16:25:42 +00004759 }
4760#endif
4761
danielk1977599fcba2004-11-08 07:13:13 +00004762 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh16a9b832007-05-05 18:39:25 +00004763 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
drh3b7511c2001-05-26 13:15:44 +00004764 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00004765 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004766 if( rc!=SQLITE_OK ){
4767 releasePage(*ppPage);
4768 }
drh3a4c1412004-05-09 20:40:11 +00004769 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00004770 }
danielk1977599fcba2004-11-08 07:13:13 +00004771
4772 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00004773
4774end_allocate_page:
4775 releasePage(pTrunk);
4776 releasePage(pPrevTrunk);
danielk1977b247c212008-11-21 09:09:01 +00004777 if( rc==SQLITE_OK ){
4778 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
4779 releasePage(*ppPage);
4780 return SQLITE_CORRUPT_BKPT;
4781 }
4782 (*ppPage)->isInit = 0;
danielk1977a50d9aa2009-06-08 14:49:45 +00004783 }else{
4784 *ppPage = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00004785 }
drh3b7511c2001-05-26 13:15:44 +00004786 return rc;
4787}
4788
4789/*
danielk1977bea2a942009-01-20 17:06:27 +00004790** This function is used to add page iPage to the database file free-list.
4791** It is assumed that the page is not already a part of the free-list.
drh5e2f8b92001-05-28 00:41:15 +00004792**
danielk1977bea2a942009-01-20 17:06:27 +00004793** The value passed as the second argument to this function is optional.
4794** If the caller happens to have a pointer to the MemPage object
4795** corresponding to page iPage handy, it may pass it as the second value.
4796** Otherwise, it may pass NULL.
4797**
4798** If a pointer to a MemPage object is passed as the second argument,
4799** its reference count is not altered by this function.
drh3b7511c2001-05-26 13:15:44 +00004800*/
danielk1977bea2a942009-01-20 17:06:27 +00004801static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
4802 MemPage *pTrunk = 0; /* Free-list trunk page */
4803 Pgno iTrunk = 0; /* Page number of free-list trunk page */
4804 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
4805 MemPage *pPage; /* Page being freed. May be NULL. */
4806 int rc; /* Return Code */
4807 int nFree; /* Initial number of pages on free-list */
drh8b2f49b2001-06-08 00:21:52 +00004808
danielk1977bea2a942009-01-20 17:06:27 +00004809 assert( sqlite3_mutex_held(pBt->mutex) );
4810 assert( iPage>1 );
4811 assert( !pMemPage || pMemPage->pgno==iPage );
4812
4813 if( pMemPage ){
4814 pPage = pMemPage;
4815 sqlite3PagerRef(pPage->pDbPage);
4816 }else{
4817 pPage = btreePageLookup(pBt, iPage);
4818 }
drh3aac2dd2004-04-26 14:10:20 +00004819
drha34b6762004-05-07 13:30:42 +00004820 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00004821 rc = sqlite3PagerWrite(pPage1->pDbPage);
danielk1977bea2a942009-01-20 17:06:27 +00004822 if( rc ) goto freepage_out;
4823 nFree = get4byte(&pPage1->aData[36]);
4824 put4byte(&pPage1->aData[36], nFree+1);
drh3aac2dd2004-04-26 14:10:20 +00004825
drhfcce93f2006-02-22 03:08:32 +00004826#ifdef SQLITE_SECURE_DELETE
4827 /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
4828 ** always fully overwrite deleted information with zeros.
4829 */
danielk1977bea2a942009-01-20 17:06:27 +00004830 if( (!pPage && (rc = sqlite3BtreeGetPage(pBt, iPage, &pPage, 0)))
4831 || (rc = sqlite3PagerWrite(pPage->pDbPage))
4832 ){
4833 goto freepage_out;
4834 }
drhfcce93f2006-02-22 03:08:32 +00004835 memset(pPage->aData, 0, pPage->pBt->pageSize);
4836#endif
4837
danielk1977687566d2004-11-02 12:56:41 +00004838 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00004839 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00004840 */
danielk197785d90ca2008-07-19 14:25:15 +00004841 if( ISAUTOVACUUM ){
danielk1977bea2a942009-01-20 17:06:27 +00004842 rc = ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0);
4843 if( rc ) goto freepage_out;
danielk1977687566d2004-11-02 12:56:41 +00004844 }
danielk1977687566d2004-11-02 12:56:41 +00004845
danielk1977bea2a942009-01-20 17:06:27 +00004846 /* Now manipulate the actual database free-list structure. There are two
4847 ** possibilities. If the free-list is currently empty, or if the first
4848 ** trunk page in the free-list is full, then this page will become a
4849 ** new free-list trunk page. Otherwise, it will become a leaf of the
4850 ** first trunk page in the current free-list. This block tests if it
4851 ** is possible to add the page as a new free-list leaf.
4852 */
4853 if( nFree!=0 ){
4854 int nLeaf; /* Initial number of leaf cells on trunk page */
4855
4856 iTrunk = get4byte(&pPage1->aData[32]);
4857 rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
4858 if( rc!=SQLITE_OK ){
4859 goto freepage_out;
4860 }
4861
4862 nLeaf = get4byte(&pTrunk->aData[4]);
4863 if( nLeaf<0 ){
4864 rc = SQLITE_CORRUPT_BKPT;
4865 goto freepage_out;
4866 }
4867 if( nLeaf<pBt->usableSize/4 - 8 ){
4868 /* In this case there is room on the trunk page to insert the page
4869 ** being freed as a new leaf.
drh45b1fac2008-07-04 17:52:42 +00004870 **
4871 ** Note that the trunk page is not really full until it contains
4872 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
4873 ** coded. But due to a coding error in versions of SQLite prior to
4874 ** 3.6.0, databases with freelist trunk pages holding more than
4875 ** usableSize/4 - 8 entries will be reported as corrupt. In order
4876 ** to maintain backwards compatibility with older versions of SQLite,
4877 ** we will contain to restrict the number of entries to usableSize/4 - 8
4878 ** for now. At some point in the future (once everyone has upgraded
4879 ** to 3.6.0 or later) we should consider fixing the conditional above
4880 ** to read "usableSize/4-2" instead of "usableSize/4-8".
4881 */
danielk19773b8a05f2007-03-19 17:44:26 +00004882 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00004883 if( rc==SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00004884 put4byte(&pTrunk->aData[4], nLeaf+1);
4885 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
drhfcce93f2006-02-22 03:08:32 +00004886#ifndef SQLITE_SECURE_DELETE
danielk1977bea2a942009-01-20 17:06:27 +00004887 if( pPage ){
4888 sqlite3PagerDontWrite(pPage->pDbPage);
4889 }
drhfcce93f2006-02-22 03:08:32 +00004890#endif
danielk1977bea2a942009-01-20 17:06:27 +00004891 rc = btreeSetHasContent(pBt, iPage);
drhf5345442007-04-09 12:45:02 +00004892 }
drh3a4c1412004-05-09 20:40:11 +00004893 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
danielk1977bea2a942009-01-20 17:06:27 +00004894 goto freepage_out;
drh3aac2dd2004-04-26 14:10:20 +00004895 }
drh3b7511c2001-05-26 13:15:44 +00004896 }
danielk1977bea2a942009-01-20 17:06:27 +00004897
4898 /* If control flows to this point, then it was not possible to add the
4899 ** the page being freed as a leaf page of the first trunk in the free-list.
4900 ** Possibly because the free-list is empty, or possibly because the
4901 ** first trunk in the free-list is full. Either way, the page being freed
4902 ** will become the new first trunk page in the free-list.
4903 */
shane63207ab2009-02-04 01:49:30 +00004904 if( ((!pPage) && (0 != (rc = sqlite3BtreeGetPage(pBt, iPage, &pPage, 0))))
4905 || (0 != (rc = sqlite3PagerWrite(pPage->pDbPage)))
danielk1977bea2a942009-01-20 17:06:27 +00004906 ){
4907 goto freepage_out;
4908 }
4909 put4byte(pPage->aData, iTrunk);
4910 put4byte(&pPage->aData[4], 0);
4911 put4byte(&pPage1->aData[32], iPage);
4912 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
4913
4914freepage_out:
4915 if( pPage ){
4916 pPage->isInit = 0;
4917 }
4918 releasePage(pPage);
4919 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00004920 return rc;
4921}
danielk1977bea2a942009-01-20 17:06:27 +00004922static int freePage(MemPage *pPage){
4923 return freePage2(pPage->pBt, pPage, pPage->pgno);
4924}
drh3b7511c2001-05-26 13:15:44 +00004925
4926/*
drh3aac2dd2004-04-26 14:10:20 +00004927** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00004928*/
drh3aac2dd2004-04-26 14:10:20 +00004929static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00004930 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00004931 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00004932 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00004933 int rc;
drh94440812007-03-06 11:42:19 +00004934 int nOvfl;
shane63207ab2009-02-04 01:49:30 +00004935 u16 ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00004936
drh1fee73e2007-08-29 04:00:57 +00004937 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh16a9b832007-05-05 18:39:25 +00004938 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004939 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00004940 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00004941 }
drh6f11bef2004-05-13 01:12:56 +00004942 ovflPgno = get4byte(&pCell[info.iOverflow]);
shane63207ab2009-02-04 01:49:30 +00004943 assert( pBt->usableSize > 4 );
drh94440812007-03-06 11:42:19 +00004944 ovflPageSize = pBt->usableSize - 4;
drh72365832007-03-06 15:53:44 +00004945 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
4946 assert( ovflPgno==0 || nOvfl>0 );
4947 while( nOvfl-- ){
shane63207ab2009-02-04 01:49:30 +00004948 Pgno iNext = 0;
danielk1977bea2a942009-01-20 17:06:27 +00004949 MemPage *pOvfl = 0;
danielk1977e589a672009-04-11 16:06:15 +00004950 if( ovflPgno<2 || ovflPgno>pagerPagecount(pBt) ){
4951 /* 0 is not a legal page number and page 1 cannot be an
4952 ** overflow page. Therefore if ovflPgno<2 or past the end of the
4953 ** file the database must be corrupt. */
drh49285702005-09-17 15:20:26 +00004954 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00004955 }
danielk1977bea2a942009-01-20 17:06:27 +00004956 if( nOvfl ){
4957 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
4958 if( rc ) return rc;
4959 }
4960 rc = freePage2(pBt, pOvfl, ovflPgno);
4961 if( pOvfl ){
4962 sqlite3PagerUnref(pOvfl->pDbPage);
4963 }
drh3b7511c2001-05-26 13:15:44 +00004964 if( rc ) return rc;
danielk1977bea2a942009-01-20 17:06:27 +00004965 ovflPgno = iNext;
drh3b7511c2001-05-26 13:15:44 +00004966 }
drh5e2f8b92001-05-28 00:41:15 +00004967 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00004968}
4969
4970/*
drh91025292004-05-03 19:49:32 +00004971** Create the byte sequence used to represent a cell on page pPage
4972** and write that byte sequence into pCell[]. Overflow pages are
4973** allocated and filled in as necessary. The calling procedure
4974** is responsible for making sure sufficient space has been allocated
4975** for pCell[].
4976**
4977** Note that pCell does not necessary need to point to the pPage->aData
4978** area. pCell might point to some temporary storage. The cell will
4979** be constructed in this temporary area then copied into pPage->aData
4980** later.
drh3b7511c2001-05-26 13:15:44 +00004981*/
4982static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00004983 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00004984 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00004985 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00004986 const void *pData,int nData, /* The data */
drhb026e052007-05-02 01:34:31 +00004987 int nZero, /* Extra zero bytes to append to pData */
drh4b70f112004-05-02 21:12:19 +00004988 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00004989){
drh3b7511c2001-05-26 13:15:44 +00004990 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00004991 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00004992 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00004993 int spaceLeft;
4994 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00004995 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00004996 unsigned char *pPrior;
4997 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00004998 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00004999 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00005000 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00005001 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00005002
drh1fee73e2007-08-29 04:00:57 +00005003 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00005004
drhc5053fb2008-11-27 02:22:10 +00005005 /* pPage is not necessarily writeable since pCell might be auxiliary
5006 ** buffer space that is separate from the pPage buffer area */
5007 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
5008 || sqlite3PagerIswriteable(pPage->pDbPage) );
5009
drh91025292004-05-03 19:49:32 +00005010 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00005011 nHeader = 0;
drh91025292004-05-03 19:49:32 +00005012 if( !pPage->leaf ){
5013 nHeader += 4;
5014 }
drh8b18dd42004-05-12 19:18:15 +00005015 if( pPage->hasData ){
drhb026e052007-05-02 01:34:31 +00005016 nHeader += putVarint(&pCell[nHeader], nData+nZero);
drh6f11bef2004-05-13 01:12:56 +00005017 }else{
drhb026e052007-05-02 01:34:31 +00005018 nData = nZero = 0;
drh91025292004-05-03 19:49:32 +00005019 }
drh6f11bef2004-05-13 01:12:56 +00005020 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh16a9b832007-05-05 18:39:25 +00005021 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005022 assert( info.nHeader==nHeader );
5023 assert( info.nKey==nKey );
danielk197789d40042008-11-17 14:20:56 +00005024 assert( info.nData==(u32)(nData+nZero) );
drh6f11bef2004-05-13 01:12:56 +00005025
5026 /* Fill in the payload */
drhb026e052007-05-02 01:34:31 +00005027 nPayload = nData + nZero;
drh3aac2dd2004-04-26 14:10:20 +00005028 if( pPage->intKey ){
5029 pSrc = pData;
5030 nSrc = nData;
drh91025292004-05-03 19:49:32 +00005031 nData = 0;
drhf49661a2008-12-10 16:45:50 +00005032 }else{
drh20abac22009-01-28 20:21:17 +00005033 if( nKey>0x7fffffff || pKey==0 ){
5034 return SQLITE_CORRUPT;
5035 }
drhf49661a2008-12-10 16:45:50 +00005036 nPayload += (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00005037 pSrc = pKey;
drhf49661a2008-12-10 16:45:50 +00005038 nSrc = (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00005039 }
drh6f11bef2004-05-13 01:12:56 +00005040 *pnSize = info.nSize;
5041 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00005042 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00005043 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00005044
drh3b7511c2001-05-26 13:15:44 +00005045 while( nPayload>0 ){
5046 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00005047#ifndef SQLITE_OMIT_AUTOVACUUM
5048 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00005049 if( pBt->autoVacuum ){
5050 do{
5051 pgnoOvfl++;
5052 } while(
5053 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
5054 );
danielk1977b39f70b2007-05-17 18:28:11 +00005055 }
danielk1977afcdd022004-10-31 16:25:42 +00005056#endif
drhf49661a2008-12-10 16:45:50 +00005057 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00005058#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00005059 /* If the database supports auto-vacuum, and the second or subsequent
5060 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00005061 ** for that page now.
5062 **
5063 ** If this is the first overflow page, then write a partial entry
5064 ** to the pointer-map. If we write nothing to this pointer-map slot,
5065 ** then the optimistic overflow chain processing in clearCell()
5066 ** may misinterpret the uninitialised values and delete the
5067 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00005068 */
danielk19774ef24492007-05-23 09:52:41 +00005069 if( pBt->autoVacuum && rc==SQLITE_OK ){
5070 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
5071 rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
danielk197789a4be82007-05-23 13:34:32 +00005072 if( rc ){
5073 releasePage(pOvfl);
5074 }
danielk1977afcdd022004-10-31 16:25:42 +00005075 }
5076#endif
drh3b7511c2001-05-26 13:15:44 +00005077 if( rc ){
drh9b171272004-05-08 02:03:22 +00005078 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00005079 return rc;
5080 }
drhc5053fb2008-11-27 02:22:10 +00005081
5082 /* If pToRelease is not zero than pPrior points into the data area
5083 ** of pToRelease. Make sure pToRelease is still writeable. */
5084 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
5085
5086 /* If pPrior is part of the data area of pPage, then make sure pPage
5087 ** is still writeable */
5088 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
5089 || sqlite3PagerIswriteable(pPage->pDbPage) );
5090
drh3aac2dd2004-04-26 14:10:20 +00005091 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00005092 releasePage(pToRelease);
5093 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00005094 pPrior = pOvfl->aData;
5095 put4byte(pPrior, 0);
5096 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00005097 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00005098 }
5099 n = nPayload;
5100 if( n>spaceLeft ) n = spaceLeft;
drhc5053fb2008-11-27 02:22:10 +00005101
5102 /* If pToRelease is not zero than pPayload points into the data area
5103 ** of pToRelease. Make sure pToRelease is still writeable. */
5104 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
5105
5106 /* If pPayload is part of the data area of pPage, then make sure pPage
5107 ** is still writeable */
5108 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
5109 || sqlite3PagerIswriteable(pPage->pDbPage) );
5110
drhb026e052007-05-02 01:34:31 +00005111 if( nSrc>0 ){
5112 if( n>nSrc ) n = nSrc;
5113 assert( pSrc );
5114 memcpy(pPayload, pSrc, n);
5115 }else{
5116 memset(pPayload, 0, n);
5117 }
drh3b7511c2001-05-26 13:15:44 +00005118 nPayload -= n;
drhde647132004-05-07 17:57:49 +00005119 pPayload += n;
drh9b171272004-05-08 02:03:22 +00005120 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00005121 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00005122 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00005123 if( nSrc==0 ){
5124 nSrc = nData;
5125 pSrc = pData;
5126 }
drhdd793422001-06-28 01:54:48 +00005127 }
drh9b171272004-05-08 02:03:22 +00005128 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00005129 return SQLITE_OK;
5130}
5131
drh14acc042001-06-10 19:56:58 +00005132/*
5133** Remove the i-th cell from pPage. This routine effects pPage only.
5134** The cell content is not freed or deallocated. It is assumed that
5135** the cell content has been copied someplace else. This routine just
5136** removes the reference to the cell from pPage.
5137**
5138** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00005139*/
shane0af3f892008-11-12 04:55:34 +00005140static int dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00005141 int i; /* Loop counter */
5142 int pc; /* Offset to cell content of cell being deleted */
5143 u8 *data; /* pPage->aData */
5144 u8 *ptr; /* Used to move bytes around within data[] */
shanedcc50b72008-11-13 18:29:50 +00005145 int rc; /* The return code */
drh43605152004-05-29 21:46:49 +00005146
drh8c42ca92001-06-22 19:15:00 +00005147 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00005148 assert( sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00005149 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00005150 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00005151 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00005152 ptr = &data[pPage->cellOffset + 2*idx];
shane0af3f892008-11-12 04:55:34 +00005153 pc = get2byte(ptr);
drhc5053fb2008-11-27 02:22:10 +00005154 if( (pc<pPage->hdrOffset+6+(pPage->leaf?0:4))
5155 || (pc+sz>pPage->pBt->usableSize) ){
shane0af3f892008-11-12 04:55:34 +00005156 return SQLITE_CORRUPT_BKPT;
5157 }
shanedcc50b72008-11-13 18:29:50 +00005158 rc = freeSpace(pPage, pc, sz);
5159 if( rc!=SQLITE_OK ){
5160 return rc;
5161 }
drh43605152004-05-29 21:46:49 +00005162 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
5163 ptr[0] = ptr[2];
5164 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00005165 }
5166 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00005167 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
5168 pPage->nFree += 2;
shane0af3f892008-11-12 04:55:34 +00005169 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00005170}
5171
5172/*
5173** Insert a new cell on pPage at cell index "i". pCell points to the
5174** content of the cell.
5175**
5176** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00005177** will not fit, then make a copy of the cell content into pTemp if
5178** pTemp is not null. Regardless of pTemp, allocate a new entry
5179** in pPage->aOvfl[] and make it point to the cell content (either
5180** in pTemp or the original pCell) and also record its index.
5181** Allocating a new entry in pPage->aCell[] implies that
5182** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00005183**
5184** If nSkip is non-zero, then do not copy the first nSkip bytes of the
5185** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00005186** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00005187** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00005188*/
danielk1977e80463b2004-11-03 03:01:16 +00005189static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00005190 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00005191 int i, /* New cell becomes the i-th cell of the page */
5192 u8 *pCell, /* Content of the new cell */
5193 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00005194 u8 *pTemp, /* Temp storage space for pCell, if needed */
danielk19774dbaa892009-06-16 16:50:22 +00005195 Pgno iChild /* If non-zero, replace first 4 bytes with this value */
drh24cd67e2004-05-10 16:18:47 +00005196){
drh43605152004-05-29 21:46:49 +00005197 int idx; /* Where to write new cell content in data[] */
5198 int j; /* Loop counter */
5199 int top; /* First byte of content for any cell in data[] */
5200 int end; /* First byte past the last cell pointer in data[] */
5201 int ins; /* Index in data[] where new cell pointer is inserted */
5202 int hdr; /* Offset into data[] of the page header */
5203 int cellOffset; /* Address of first cell pointer in data[] */
5204 u8 *data; /* The content of the whole page */
5205 u8 *ptr; /* Used for moving information around in data[] */
5206
danielk19774dbaa892009-06-16 16:50:22 +00005207 int nSkip = (iChild ? 4 : 0);
5208
drh43605152004-05-29 21:46:49 +00005209 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
drhf49661a2008-12-10 16:45:50 +00005210 assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
5211 assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
drh43605152004-05-29 21:46:49 +00005212 assert( sz==cellSizePtr(pPage, pCell) );
drh1fee73e2007-08-29 04:00:57 +00005213 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +00005214 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00005215 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00005216 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00005217 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00005218 }
danielk19774dbaa892009-06-16 16:50:22 +00005219 if( iChild ){
5220 put4byte(pCell, iChild);
5221 }
drh43605152004-05-29 21:46:49 +00005222 j = pPage->nOverflow++;
danielk197789d40042008-11-17 14:20:56 +00005223 assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
drh43605152004-05-29 21:46:49 +00005224 pPage->aOvfl[j].pCell = pCell;
drhf49661a2008-12-10 16:45:50 +00005225 pPage->aOvfl[j].idx = (u16)i;
drh14acc042001-06-10 19:56:58 +00005226 }else{
danielk19776e465eb2007-08-21 13:11:00 +00005227 int rc = sqlite3PagerWrite(pPage->pDbPage);
5228 if( rc!=SQLITE_OK ){
5229 return rc;
5230 }
5231 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00005232 data = pPage->aData;
5233 hdr = pPage->hdrOffset;
5234 top = get2byte(&data[hdr+5]);
5235 cellOffset = pPage->cellOffset;
5236 end = cellOffset + 2*pPage->nCell + 2;
5237 ins = cellOffset + 2*i;
5238 if( end > top - sz ){
shane0af3f892008-11-12 04:55:34 +00005239 rc = defragmentPage(pPage);
5240 if( rc!=SQLITE_OK ){
5241 return rc;
5242 }
drh43605152004-05-29 21:46:49 +00005243 top = get2byte(&data[hdr+5]);
5244 assert( end + sz <= top );
5245 }
5246 idx = allocateSpace(pPage, sz);
5247 assert( idx>0 );
5248 assert( end <= get2byte(&data[hdr+5]) );
shane0af3f892008-11-12 04:55:34 +00005249 if (idx+sz > pPage->pBt->usableSize) {
shane34ac18d2008-11-11 22:18:20 +00005250 return SQLITE_CORRUPT_BKPT;
shane0af3f892008-11-12 04:55:34 +00005251 }
drh43605152004-05-29 21:46:49 +00005252 pPage->nCell++;
shane36840fd2009-06-26 16:32:13 +00005253 pPage->nFree = pPage->nFree - (u16)(2 + sz);
danielk1977a3ad5e72005-01-07 08:56:44 +00005254 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
danielk19774dbaa892009-06-16 16:50:22 +00005255 if( iChild ){
5256 put4byte(&data[idx], iChild);
5257 }
drh43605152004-05-29 21:46:49 +00005258 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
5259 ptr[0] = ptr[-2];
5260 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00005261 }
drh43605152004-05-29 21:46:49 +00005262 put2byte(&data[ins], idx);
5263 put2byte(&data[hdr+3], pPage->nCell);
danielk1977a19df672004-11-03 11:37:07 +00005264#ifndef SQLITE_OMIT_AUTOVACUUM
5265 if( pPage->pBt->autoVacuum ){
5266 /* The cell may contain a pointer to an overflow page. If so, write
5267 ** the entry for the overflow page into the pointer map.
5268 */
danielk197746aa38f2009-06-25 16:11:05 +00005269 return ptrmapPutOvflPtr(pPage, pCell);
danielk1977a19df672004-11-03 11:37:07 +00005270 }
5271#endif
drh14acc042001-06-10 19:56:58 +00005272 }
danielk1977e80463b2004-11-03 03:01:16 +00005273
danielk1977e80463b2004-11-03 03:01:16 +00005274 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00005275}
5276
5277/*
drhfa1a98a2004-05-14 19:08:17 +00005278** Add a list of cells to a page. The page should be initially empty.
5279** The cells are guaranteed to fit on the page.
5280*/
5281static void assemblePage(
5282 MemPage *pPage, /* The page to be assemblied */
5283 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00005284 u8 **apCell, /* Pointers to cell bodies */
drha9121e42008-02-19 14:59:35 +00005285 u16 *aSize /* Sizes of the cells */
drhfa1a98a2004-05-14 19:08:17 +00005286){
5287 int i; /* Loop counter */
danielk1977fad91942009-04-29 17:49:59 +00005288 u8 *pCellptr; /* Address of next cell pointer */
drh43605152004-05-29 21:46:49 +00005289 int cellbody; /* Address of next cell body */
danielk1977fad91942009-04-29 17:49:59 +00005290 u8 * const data = pPage->aData; /* Pointer to data for pPage */
5291 const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
5292 const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
drhfa1a98a2004-05-14 19:08:17 +00005293
drh43605152004-05-29 21:46:49 +00005294 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00005295 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00005296 assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
drhc5053fb2008-11-27 02:22:10 +00005297 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977fad91942009-04-29 17:49:59 +00005298
5299 /* Check that the page has just been zeroed by zeroPage() */
5300 assert( pPage->nCell==0 );
5301 assert( get2byte(&data[hdr+5])==nUsable );
5302
5303 pCellptr = &data[pPage->cellOffset + nCell*2];
5304 cellbody = nUsable;
5305 for(i=nCell-1; i>=0; i--){
5306 pCellptr -= 2;
5307 cellbody -= aSize[i];
5308 put2byte(pCellptr, cellbody);
5309 memcpy(&data[cellbody], apCell[i], aSize[i]);
drhfa1a98a2004-05-14 19:08:17 +00005310 }
danielk1977fad91942009-04-29 17:49:59 +00005311 put2byte(&data[hdr+3], nCell);
5312 put2byte(&data[hdr+5], cellbody);
5313 pPage->nFree -= (nCell*2 + nUsable - cellbody);
drhf49661a2008-12-10 16:45:50 +00005314 pPage->nCell = (u16)nCell;
drhfa1a98a2004-05-14 19:08:17 +00005315}
5316
drh14acc042001-06-10 19:56:58 +00005317/*
drhc3b70572003-01-04 19:44:07 +00005318** The following parameters determine how many adjacent pages get involved
5319** in a balancing operation. NN is the number of neighbors on either side
5320** of the page that participate in the balancing operation. NB is the
5321** total number of pages that participate, including the target page and
5322** NN neighbors on either side.
5323**
5324** The minimum value of NN is 1 (of course). Increasing NN above 1
5325** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
5326** in exchange for a larger degradation in INSERT and UPDATE performance.
5327** The value of NN appears to give the best results overall.
5328*/
5329#define NN 1 /* Number of neighbors on either side of pPage */
5330#define NB (NN*2+1) /* Total pages involved in the balance */
5331
danielk1977ac245ec2005-01-14 13:50:11 +00005332
drh615ae552005-01-16 23:21:00 +00005333#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00005334/*
5335** This version of balance() handles the common special case where
5336** a new entry is being inserted on the extreme right-end of the
5337** tree, in other words, when the new entry will become the largest
5338** entry in the tree.
5339**
5340** Instead of trying balance the 3 right-most leaf pages, just add
5341** a new page to the right-hand side and put the one new entry in
5342** that page. This leaves the right side of the tree somewhat
5343** unbalanced. But odds are that we will be inserting new entries
5344** at the end soon afterwards so the nearly empty page will quickly
5345** fill up. On average.
5346**
5347** pPage is the leaf page which is the right-most page in the tree.
5348** pParent is its parent. pPage must have a single overflow entry
5349** which is also the right-most entry on the page.
danielk1977a50d9aa2009-06-08 14:49:45 +00005350**
5351** The pSpace buffer is used to store a temporary copy of the divider
5352** cell that will be inserted into pParent. Such a cell consists of a 4
5353** byte page number followed by a variable length integer. In other
5354** words, at most 13 bytes. Hence the pSpace buffer must be at
5355** least 13 bytes in size.
drhf222e712005-01-14 22:55:49 +00005356*/
danielk1977a50d9aa2009-06-08 14:49:45 +00005357static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
5358 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
danielk19774dbaa892009-06-16 16:50:22 +00005359 MemPage *pNew; /* Newly allocated page */
danielk19776f235cc2009-06-04 14:46:08 +00005360 int rc; /* Return Code */
5361 Pgno pgnoNew; /* Page number of pNew */
danielk1977ac245ec2005-01-14 13:50:11 +00005362
drh1fee73e2007-08-29 04:00:57 +00005363 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk1977a50d9aa2009-06-08 14:49:45 +00005364 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00005365 assert( pPage->nOverflow==1 );
5366
drhd46b6c22009-06-04 17:02:51 +00005367 if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
drhd677b3d2007-08-20 22:48:41 +00005368
danielk1977a50d9aa2009-06-08 14:49:45 +00005369 /* Allocate a new page. This page will become the right-sibling of
5370 ** pPage. Make the parent page writable, so that the new divider cell
5371 ** may be inserted. If both these operations are successful, proceed.
5372 */
drh4f0c5872007-03-26 22:05:01 +00005373 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk19774dbaa892009-06-16 16:50:22 +00005374
danielk1977eaa06f62008-09-18 17:34:44 +00005375 if( rc==SQLITE_OK ){
danielk1977a50d9aa2009-06-08 14:49:45 +00005376
5377 u8 *pOut = &pSpace[4];
danielk19776f235cc2009-06-04 14:46:08 +00005378 u8 *pCell = pPage->aOvfl[0].pCell;
5379 u16 szCell = cellSizePtr(pPage, pCell);
5380 u8 *pStop;
5381
drhc5053fb2008-11-27 02:22:10 +00005382 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00005383 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
5384 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
danielk1977eaa06f62008-09-18 17:34:44 +00005385 assemblePage(pNew, 1, &pCell, &szCell);
danielk19774dbaa892009-06-16 16:50:22 +00005386
5387 /* If this is an auto-vacuum database, update the pointer map
5388 ** with entries for the new page, and any pointer from the
5389 ** cell on the page to an overflow page. If either of these
5390 ** operations fails, the return code is set, but the contents
5391 ** of the parent page are still manipulated by thh code below.
5392 ** That is Ok, at this point the parent page is guaranteed to
5393 ** be marked as dirty. Returning an error code will cause a
5394 ** rollback, undoing any changes made to the parent page.
5395 */
5396 if( ISAUTOVACUUM ){
5397 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
5398 if( szCell>pNew->minLocal && rc==SQLITE_OK ){
5399 rc = ptrmapPutOvflPtr(pNew, pCell);
5400 }
5401 }
danielk1977eaa06f62008-09-18 17:34:44 +00005402
danielk19776f235cc2009-06-04 14:46:08 +00005403 /* Create a divider cell to insert into pParent. The divider cell
5404 ** consists of a 4-byte page number (the page number of pPage) and
5405 ** a variable length key value (which must be the same value as the
5406 ** largest key on pPage).
danielk1977eaa06f62008-09-18 17:34:44 +00005407 **
danielk19776f235cc2009-06-04 14:46:08 +00005408 ** To find the largest key value on pPage, first find the right-most
5409 ** cell on pPage. The first two fields of this cell are the
5410 ** record-length (a variable length integer at most 32-bits in size)
5411 ** and the key value (a variable length integer, may have any value).
5412 ** The first of the while(...) loops below skips over the record-length
5413 ** field. The second while(...) loop copies the key value from the
danielk1977a50d9aa2009-06-08 14:49:45 +00005414 ** cell on pPage into the pSpace buffer.
danielk1977eaa06f62008-09-18 17:34:44 +00005415 */
danielk1977eaa06f62008-09-18 17:34:44 +00005416 pCell = findCell(pPage, pPage->nCell-1);
danielk19776f235cc2009-06-04 14:46:08 +00005417 pStop = &pCell[9];
5418 while( (*(pCell++)&0x80) && pCell<pStop );
5419 pStop = &pCell[9];
5420 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
5421
danielk19774dbaa892009-06-16 16:50:22 +00005422 /* Insert the new divider cell into pParent. */
5423 insertCell(pParent,pParent->nCell,pSpace,(int)(pOut-pSpace),0,pPage->pgno);
danielk19776f235cc2009-06-04 14:46:08 +00005424
5425 /* Set the right-child pointer of pParent to point to the new page. */
danielk1977eaa06f62008-09-18 17:34:44 +00005426 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
5427
danielk1977e08a3c42008-09-18 18:17:03 +00005428 /* Release the reference to the new page. */
5429 releasePage(pNew);
danielk1977ac11ee62005-01-15 12:45:51 +00005430 }
5431
danielk1977eaa06f62008-09-18 17:34:44 +00005432 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00005433}
drh615ae552005-01-16 23:21:00 +00005434#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00005435
danielk19774dbaa892009-06-16 16:50:22 +00005436#if 0
drhc3b70572003-01-04 19:44:07 +00005437/*
danielk19774dbaa892009-06-16 16:50:22 +00005438** This function does not contribute anything to the operation of SQLite.
5439** it is sometimes activated temporarily while debugging code responsible
5440** for setting pointer-map entries.
5441*/
5442static int ptrmapCheckPages(MemPage **apPage, int nPage){
5443 int i, j;
5444 for(i=0; i<nPage; i++){
5445 Pgno n;
5446 u8 e;
5447 MemPage *pPage = apPage[i];
5448 BtShared *pBt = pPage->pBt;
5449 assert( pPage->isInit );
5450
5451 for(j=0; j<pPage->nCell; j++){
5452 CellInfo info;
5453 u8 *z;
5454
5455 z = findCell(pPage, j);
5456 sqlite3BtreeParseCellPtr(pPage, z, &info);
5457 if( info.iOverflow ){
5458 Pgno ovfl = get4byte(&z[info.iOverflow]);
5459 ptrmapGet(pBt, ovfl, &e, &n);
5460 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
5461 }
5462 if( !pPage->leaf ){
5463 Pgno child = get4byte(z);
5464 ptrmapGet(pBt, child, &e, &n);
5465 assert( n==pPage->pgno && e==PTRMAP_BTREE );
5466 }
5467 }
5468 if( !pPage->leaf ){
5469 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5470 ptrmapGet(pBt, child, &e, &n);
5471 assert( n==pPage->pgno && e==PTRMAP_BTREE );
5472 }
5473 }
5474 return 1;
5475}
5476#endif
5477
danielk1977cd581a72009-06-23 15:43:39 +00005478/*
5479** This function is used to copy the contents of the b-tree node stored
5480** on page pFrom to page pTo. If page pFrom was not a leaf page, then
5481** the pointer-map entries for each child page are updated so that the
5482** parent page stored in the pointer map is page pTo. If pFrom contained
5483** any cells with overflow page pointers, then the corresponding pointer
5484** map entries are also updated so that the parent page is page pTo.
5485**
5486** If pFrom is currently carrying any overflow cells (entries in the
5487** MemPage.aOvfl[] array), they are not copied to pTo.
5488**
5489** Before returning, page pTo is reinitialized using sqlite3BtreeInitPage().
5490**
5491** The performance of this function is not critical. It is only used by
5492** the balance_shallower() and balance_deeper() procedures, neither of
5493** which are called often under normal circumstances.
5494*/
5495static int copyNodeContent(MemPage *pFrom, MemPage *pTo){
5496 BtShared * const pBt = pFrom->pBt;
5497 u8 * const aFrom = pFrom->aData;
5498 u8 * const aTo = pTo->aData;
5499 int const iFromHdr = pFrom->hdrOffset;
5500 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
5501 int rc = SQLITE_OK;
5502 int iData;
5503
5504 assert( pFrom->isInit );
5505 assert( pFrom->nFree>=iToHdr );
5506 assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
5507
5508 /* Copy the b-tree node content from page pFrom to page pTo. */
5509 iData = get2byte(&aFrom[iFromHdr+5]);
5510 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
5511 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
5512
5513 /* Reinitialize page pTo so that the contents of the MemPage structure
5514 ** match the new data. The initialization of pTo "cannot" fail, as the
5515 ** data copied from pFrom is known to be valid. */
5516 pTo->isInit = 0;
5517 TESTONLY(rc = ) sqlite3BtreeInitPage(pTo);
5518 assert( rc==SQLITE_OK );
5519
5520 /* If this is an auto-vacuum database, update the pointer-map entries
5521 ** for any b-tree or overflow pages that pTo now contains the pointers to. */
5522 if( ISAUTOVACUUM ){
5523 rc = setChildPtrmaps(pTo);
5524 }
5525 return rc;
5526}
5527
5528/*
danielk19774dbaa892009-06-16 16:50:22 +00005529** This routine redistributes cells on the iParentIdx'th child of pParent
5530** (hereafter "the page") and up to 2 siblings so that all pages have about the
5531** same amount of free space. Usually a single sibling on either side of the
5532** page are used in the balancing, though both siblings might come from one
5533** side if the page is the first or last child of its parent. If the page
5534** has fewer than 2 siblings (something which can only happen if the page
5535** is a root page or a child of a root page) then all available siblings
5536** participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00005537**
danielk19774dbaa892009-06-16 16:50:22 +00005538** The number of siblings of the page might be increased or decreased by
5539** one or two in an effort to keep pages nearly full but not over full.
drh14acc042001-06-10 19:56:58 +00005540**
danielk19774dbaa892009-06-16 16:50:22 +00005541** Note that when this routine is called, some of the cells on the page
5542** might not actually be stored in MemPage.aData[]. This can happen
5543** if the page is overfull. This routine ensures that all cells allocated
5544** to the page and its siblings fit into MemPage.aData[] before returning.
drh14acc042001-06-10 19:56:58 +00005545**
danielk19774dbaa892009-06-16 16:50:22 +00005546** In the course of balancing the page and its siblings, cells may be
5547** inserted into or removed from the parent page (pParent). Doing so
5548** may cause the parent page to become overfull or underfull. If this
5549** happens, it is the responsibility of the caller to invoke the correct
5550** balancing routine to fix this problem (see the balance() routine).
drh8c42ca92001-06-22 19:15:00 +00005551**
drh5e00f6c2001-09-13 13:46:56 +00005552** If this routine fails for any reason, it might leave the database
danielk19776067a9b2009-06-09 09:41:00 +00005553** in a corrupted state. So if this routine fails, the database should
drh5e00f6c2001-09-13 13:46:56 +00005554** be rolled back.
danielk19774dbaa892009-06-16 16:50:22 +00005555**
5556** The third argument to this function, aOvflSpace, is a pointer to a
5557** buffer page-size bytes in size. If, in inserting cells into the parent
5558** page (pParent), the parent page becomes overfull, this buffer is
5559** used to store the parents overflow cells. Because this function inserts
5560** a maximum of four divider cells into the parent page, and the maximum
5561** size of a cell stored within an internal node is always less than 1/4
5562** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
5563** enough for all overflow cells.
5564**
5565** If aOvflSpace is set to a null pointer, this function returns
5566** SQLITE_NOMEM.
drh8b2f49b2001-06-08 00:21:52 +00005567*/
danielk19774dbaa892009-06-16 16:50:22 +00005568static int balance_nonroot(
5569 MemPage *pParent, /* Parent page of siblings being balanced */
5570 int iParentIdx, /* Index of "the page" in pParent */
danielk1977cd581a72009-06-23 15:43:39 +00005571 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
5572 int isRoot /* True if pParent is a root-page */
danielk19774dbaa892009-06-16 16:50:22 +00005573){
drh16a9b832007-05-05 18:39:25 +00005574 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00005575 int nCell = 0; /* Number of cells in apCell[] */
5576 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
danielk1977a4124bd2008-12-23 10:37:47 +00005577 int nNew = 0; /* Number of pages in apNew[] */
danielk19774dbaa892009-06-16 16:50:22 +00005578 int nOld; /* Number of pages in apOld[] */
drh14acc042001-06-10 19:56:58 +00005579 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00005580 int nxDiv; /* Next divider slot in pParent->aCell[] */
shane85095702009-06-15 16:27:08 +00005581 int rc = SQLITE_OK; /* The return code */
shane36840fd2009-06-26 16:32:13 +00005582 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00005583 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00005584 int usableSpace; /* Bytes in pPage beyond the header */
5585 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00005586 int subtotal; /* Subtotal of bytes in cells on one page */
drhe5ae5732008-06-15 02:51:47 +00005587 int iSpace1 = 0; /* First unused byte of aSpace1[] */
danielk19776067a9b2009-06-09 09:41:00 +00005588 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
drhfacf0302008-06-17 15:12:00 +00005589 int szScratch; /* Size of scratch memory requested */
drhc3b70572003-01-04 19:44:07 +00005590 MemPage *apOld[NB]; /* pPage and up to two siblings */
drh4b70f112004-05-02 21:12:19 +00005591 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00005592 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
danielk19774dbaa892009-06-16 16:50:22 +00005593 u8 *pRight; /* Location in parent of right-sibling pointer */
5594 u8 *apDiv[NB-1]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00005595 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
5596 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00005597 u8 **apCell = 0; /* All cells begin balanced */
drha9121e42008-02-19 14:59:35 +00005598 u16 *szCell; /* Local size of all cells in apCell[] */
danielk19774dbaa892009-06-16 16:50:22 +00005599 u8 *aSpace1; /* Space for copies of dividers cells */
5600 Pgno pgno; /* Temp var to store a page number in */
drh8b2f49b2001-06-08 00:21:52 +00005601
danielk1977a50d9aa2009-06-08 14:49:45 +00005602 pBt = pParent->pBt;
5603 assert( sqlite3_mutex_held(pBt->mutex) );
5604 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977474b7cc2008-07-09 11:49:46 +00005605
danielk1977e5765212009-06-17 11:13:28 +00005606#if 0
drh43605152004-05-29 21:46:49 +00005607 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
danielk1977e5765212009-06-17 11:13:28 +00005608#endif
drh2e38c322004-09-03 18:38:44 +00005609
danielk19774dbaa892009-06-16 16:50:22 +00005610 /* At this point pParent may have at most one overflow cell. And if
5611 ** this overflow cell is present, it must be the cell with
5612 ** index iParentIdx. This scenario comes about when this function
5613 ** is called (indirectly) from sqlite3BtreeDelete(). */
5614 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
5615 assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
5616
danielk197711a8a862009-06-17 11:49:52 +00005617 if( !aOvflSpace ){
5618 return SQLITE_NOMEM;
5619 }
5620
danielk1977a50d9aa2009-06-08 14:49:45 +00005621 /* Find the sibling pages to balance. Also locate the cells in pParent
5622 ** that divide the siblings. An attempt is made to find NN siblings on
5623 ** either side of pPage. More siblings are taken from one side, however,
5624 ** if there are fewer than NN siblings on the other side. If pParent
danielk19774dbaa892009-06-16 16:50:22 +00005625 ** has NB or fewer children then all children of pParent are taken.
5626 **
5627 ** This loop also drops the divider cells from the parent page. This
5628 ** way, the remainder of the function does not have to deal with any
5629 ** overflow cells in the parent page, as if one existed it has already
5630 ** been removed. */
5631 i = pParent->nOverflow + pParent->nCell;
5632 if( i<2 ){
drhc3b70572003-01-04 19:44:07 +00005633 nxDiv = 0;
danielk19774dbaa892009-06-16 16:50:22 +00005634 nOld = i+1;
5635 }else{
5636 nOld = 3;
5637 if( iParentIdx==0 ){
5638 nxDiv = 0;
5639 }else if( iParentIdx==i ){
5640 nxDiv = i-2;
drh14acc042001-06-10 19:56:58 +00005641 }else{
danielk19774dbaa892009-06-16 16:50:22 +00005642 nxDiv = iParentIdx-1;
drh8b2f49b2001-06-08 00:21:52 +00005643 }
danielk19774dbaa892009-06-16 16:50:22 +00005644 i = 2;
5645 }
5646 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
5647 pRight = &pParent->aData[pParent->hdrOffset+8];
5648 }else{
5649 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
5650 }
5651 pgno = get4byte(pRight);
5652 while( 1 ){
5653 rc = getAndInitPage(pBt, pgno, &apOld[i]);
5654 if( rc ){
5655 memset(apOld, 0, i*sizeof(MemPage*));
5656 goto balance_cleanup;
5657 }
danielk1977634f2982005-03-28 08:44:07 +00005658 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
danielk19774dbaa892009-06-16 16:50:22 +00005659 if( (i--)==0 ) break;
5660
5661 if( pParent->nOverflow && i+nxDiv==pParent->aOvfl[0].idx ){
5662 apDiv[i] = pParent->aOvfl[0].pCell;
5663 pgno = get4byte(apDiv[i]);
5664 szNew[i] = cellSizePtr(pParent, apDiv[i]);
5665 pParent->nOverflow = 0;
5666 }else{
5667 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
5668 pgno = get4byte(apDiv[i]);
5669 szNew[i] = cellSizePtr(pParent, apDiv[i]);
5670
5671 /* Drop the cell from the parent page. apDiv[i] still points to
5672 ** the cell within the parent, even though it has been dropped.
5673 ** This is safe because dropping a cell only overwrites the first
5674 ** four bytes of it, and this function does not need the first
5675 ** four bytes of the divider cell. So the pointer is safe to use
danielk197711a8a862009-06-17 11:49:52 +00005676 ** later on.
5677 **
5678 ** Unless SQLite is compiled in secure-delete mode. In this case,
5679 ** the dropCell() routine will overwrite the entire cell with zeroes.
5680 ** In this case, temporarily copy the cell into the aOvflSpace[]
5681 ** buffer. It will be copied out again as soon as the aSpace[] buffer
5682 ** is allocated. */
5683#ifdef SQLITE_SECURE_DELETE
5684 memcpy(&aOvflSpace[apDiv[i]-pParent->aData], apDiv[i], szNew[i]);
5685 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
5686#endif
danielk19774dbaa892009-06-16 16:50:22 +00005687 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i]);
5688 }
drh8b2f49b2001-06-08 00:21:52 +00005689 }
5690
drha9121e42008-02-19 14:59:35 +00005691 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00005692 ** alignment */
drha9121e42008-02-19 14:59:35 +00005693 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00005694
drh8b2f49b2001-06-08 00:21:52 +00005695 /*
danielk1977634f2982005-03-28 08:44:07 +00005696 ** Allocate space for memory structures
5697 */
danielk19774dbaa892009-06-16 16:50:22 +00005698 k = pBt->pageSize + ROUND8(sizeof(MemPage));
drhfacf0302008-06-17 15:12:00 +00005699 szScratch =
drha9121e42008-02-19 14:59:35 +00005700 nMaxCells*sizeof(u8*) /* apCell */
5701 + nMaxCells*sizeof(u16) /* szCell */
drhe5ae5732008-06-15 02:51:47 +00005702 + pBt->pageSize /* aSpace1 */
danielk19774dbaa892009-06-16 16:50:22 +00005703 + k*nOld; /* Page copies (apCopy) */
drhfacf0302008-06-17 15:12:00 +00005704 apCell = sqlite3ScratchMalloc( szScratch );
danielk197711a8a862009-06-17 11:49:52 +00005705 if( apCell==0 ){
danielk1977634f2982005-03-28 08:44:07 +00005706 rc = SQLITE_NOMEM;
5707 goto balance_cleanup;
5708 }
drha9121e42008-02-19 14:59:35 +00005709 szCell = (u16*)&apCell[nMaxCells];
danielk19774dbaa892009-06-16 16:50:22 +00005710 aSpace1 = (u8*)&szCell[nMaxCells];
drhea598cb2009-04-05 12:22:08 +00005711 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
drh14acc042001-06-10 19:56:58 +00005712
5713 /*
5714 ** Load pointers to all cells on sibling pages and the divider cells
5715 ** into the local apCell[] array. Make copies of the divider cells
danielk19774dbaa892009-06-16 16:50:22 +00005716 ** into space obtained from aSpace1[] and remove the the divider Cells
drhb6f41482004-05-14 01:58:11 +00005717 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00005718 **
5719 ** If the siblings are on leaf pages, then the child pointers of the
5720 ** divider cells are stripped from the cells before they are copied
drhe5ae5732008-06-15 02:51:47 +00005721 ** into aSpace1[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00005722 ** child pointers. If siblings are not leaves, then all cell in
5723 ** apCell[] include child pointers. Either way, all cells in apCell[]
5724 ** are alike.
drh96f5b762004-05-16 16:24:36 +00005725 **
5726 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
5727 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00005728 */
danielk1977a50d9aa2009-06-08 14:49:45 +00005729 leafCorrection = apOld[0]->leaf*4;
5730 leafData = apOld[0]->hasData;
drh8b2f49b2001-06-08 00:21:52 +00005731 for(i=0; i<nOld; i++){
danielk19774dbaa892009-06-16 16:50:22 +00005732 int limit;
5733
5734 /* Before doing anything else, take a copy of the i'th original sibling
5735 ** The rest of this function will use data from the copies rather
5736 ** that the original pages since the original pages will be in the
5737 ** process of being overwritten. */
5738 MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
5739 memcpy(pOld, apOld[i], sizeof(MemPage));
5740 pOld->aData = (void*)&pOld[1];
5741 memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
5742
5743 limit = pOld->nCell+pOld->nOverflow;
drh43605152004-05-29 21:46:49 +00005744 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00005745 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00005746 apCell[nCell] = findOverflowCell(pOld, j);
5747 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk19774dbaa892009-06-16 16:50:22 +00005748 nCell++;
5749 }
5750 if( i<nOld-1 && !leafData){
shane36840fd2009-06-26 16:32:13 +00005751 u16 sz = (u16)szNew[i];
danielk19774dbaa892009-06-16 16:50:22 +00005752 u8 *pTemp;
5753 assert( nCell<nMaxCells );
5754 szCell[nCell] = sz;
5755 pTemp = &aSpace1[iSpace1];
5756 iSpace1 += sz;
5757 assert( sz<=pBt->pageSize/4 );
5758 assert( iSpace1<=pBt->pageSize );
5759 memcpy(pTemp, apDiv[i], sz);
5760 apCell[nCell] = pTemp+leafCorrection;
5761 assert( leafCorrection==0 || leafCorrection==4 );
shane36840fd2009-06-26 16:32:13 +00005762 szCell[nCell] = szCell[nCell] - leafCorrection;
danielk19774dbaa892009-06-16 16:50:22 +00005763 if( !pOld->leaf ){
5764 assert( leafCorrection==0 );
5765 assert( pOld->hdrOffset==0 );
5766 /* The right pointer of the child page pOld becomes the left
5767 ** pointer of the divider cell */
5768 memcpy(apCell[nCell], &pOld->aData[8], 4);
5769 }else{
5770 assert( leafCorrection==4 );
5771 if( szCell[nCell]<4 ){
5772 /* Do not allow any cells smaller than 4 bytes. */
5773 szCell[nCell] = 4;
danielk1977ac11ee62005-01-15 12:45:51 +00005774 }
5775 }
drh14acc042001-06-10 19:56:58 +00005776 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00005777 }
drh8b2f49b2001-06-08 00:21:52 +00005778 }
5779
5780 /*
drh6019e162001-07-02 17:51:45 +00005781 ** Figure out the number of pages needed to hold all nCell cells.
5782 ** Store this number in "k". Also compute szNew[] which is the total
5783 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00005784 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00005785 ** cntNew[k] should equal nCell.
5786 **
drh96f5b762004-05-16 16:24:36 +00005787 ** Values computed by this block:
5788 **
5789 ** k: The total number of sibling pages
5790 ** szNew[i]: Spaced used on the i-th sibling page.
5791 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
5792 ** the right of the i-th sibling page.
5793 ** usableSpace: Number of bytes of space available on each sibling.
5794 **
drh8b2f49b2001-06-08 00:21:52 +00005795 */
drh43605152004-05-29 21:46:49 +00005796 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00005797 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00005798 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00005799 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00005800 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00005801 szNew[k] = subtotal - szCell[i];
5802 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00005803 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00005804 subtotal = 0;
5805 k++;
drheac74422009-06-14 12:47:11 +00005806 if( k>NB+1 ){ rc = SQLITE_CORRUPT; goto balance_cleanup; }
drh6019e162001-07-02 17:51:45 +00005807 }
5808 }
5809 szNew[k] = subtotal;
5810 cntNew[k] = nCell;
5811 k++;
drh96f5b762004-05-16 16:24:36 +00005812
5813 /*
5814 ** The packing computed by the previous block is biased toward the siblings
5815 ** on the left side. The left siblings are always nearly full, while the
5816 ** right-most sibling might be nearly empty. This block of code attempts
5817 ** to adjust the packing of siblings to get a better balance.
5818 **
5819 ** This adjustment is more than an optimization. The packing above might
5820 ** be so out of balance as to be illegal. For example, the right-most
5821 ** sibling might be completely empty. This adjustment is not optional.
5822 */
drh6019e162001-07-02 17:51:45 +00005823 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00005824 int szRight = szNew[i]; /* Size of sibling on the right */
5825 int szLeft = szNew[i-1]; /* Size of sibling on the left */
5826 int r; /* Index of right-most cell in left sibling */
5827 int d; /* Index of first cell to the left of right sibling */
5828
5829 r = cntNew[i-1] - 1;
5830 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00005831 assert( d<nMaxCells );
5832 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00005833 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
5834 szRight += szCell[d] + 2;
5835 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00005836 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00005837 r = cntNew[i-1] - 1;
5838 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00005839 }
drh96f5b762004-05-16 16:24:36 +00005840 szNew[i] = szRight;
5841 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00005842 }
drh09d0deb2005-08-02 17:13:09 +00005843
danielk19776f235cc2009-06-04 14:46:08 +00005844 /* Either we found one or more cells (cntnew[0])>0) or pPage is
drh09d0deb2005-08-02 17:13:09 +00005845 ** a virtual root page. A virtual root page is when the real root
5846 ** page is page 1 and we are the only child of that page.
5847 */
5848 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00005849
danielk1977e5765212009-06-17 11:13:28 +00005850 TRACE(("BALANCE: old: %d %d %d ",
5851 apOld[0]->pgno,
5852 nOld>=2 ? apOld[1]->pgno : 0,
5853 nOld>=3 ? apOld[2]->pgno : 0
5854 ));
5855
drh8b2f49b2001-06-08 00:21:52 +00005856 /*
drh6b308672002-07-08 02:16:37 +00005857 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00005858 */
drheac74422009-06-14 12:47:11 +00005859 if( apOld[0]->pgno<=1 ){
5860 rc = SQLITE_CORRUPT;
5861 goto balance_cleanup;
5862 }
danielk1977a50d9aa2009-06-08 14:49:45 +00005863 pageFlags = apOld[0]->aData[0];
drh14acc042001-06-10 19:56:58 +00005864 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00005865 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00005866 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00005867 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00005868 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00005869 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00005870 nNew++;
danielk197728129562005-01-11 10:25:06 +00005871 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00005872 }else{
drh7aa8f852006-03-28 00:24:44 +00005873 assert( i>0 );
danielk19774dbaa892009-06-16 16:50:22 +00005874 rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
drh6b308672002-07-08 02:16:37 +00005875 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00005876 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00005877 nNew++;
danielk19774dbaa892009-06-16 16:50:22 +00005878
5879 /* Set the pointer-map entry for the new sibling page. */
5880 if( ISAUTOVACUUM ){
5881 rc = ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno);
5882 if( rc!=SQLITE_OK ){
5883 goto balance_cleanup;
5884 }
5885 }
drh6b308672002-07-08 02:16:37 +00005886 }
drh8b2f49b2001-06-08 00:21:52 +00005887 }
5888
danielk1977299b1872004-11-22 10:02:10 +00005889 /* Free any old pages that were not reused as new pages.
5890 */
5891 while( i<nOld ){
5892 rc = freePage(apOld[i]);
5893 if( rc ) goto balance_cleanup;
5894 releasePage(apOld[i]);
5895 apOld[i] = 0;
5896 i++;
5897 }
5898
drh8b2f49b2001-06-08 00:21:52 +00005899 /*
drhf9ffac92002-03-02 19:00:31 +00005900 ** Put the new pages in accending order. This helps to
5901 ** keep entries in the disk file in order so that a scan
5902 ** of the table is a linear scan through the file. That
5903 ** in turn helps the operating system to deliver pages
5904 ** from the disk more rapidly.
5905 **
5906 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00005907 ** n is never more than NB (a small constant), that should
5908 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00005909 **
drhc3b70572003-01-04 19:44:07 +00005910 ** When NB==3, this one optimization makes the database
5911 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00005912 */
5913 for(i=0; i<k-1; i++){
danielk19774dbaa892009-06-16 16:50:22 +00005914 int minV = apNew[i]->pgno;
drhf9ffac92002-03-02 19:00:31 +00005915 int minI = i;
5916 for(j=i+1; j<k; j++){
danielk19774dbaa892009-06-16 16:50:22 +00005917 if( apNew[j]->pgno<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00005918 minI = j;
danielk19774dbaa892009-06-16 16:50:22 +00005919 minV = apNew[j]->pgno;
drhf9ffac92002-03-02 19:00:31 +00005920 }
5921 }
5922 if( minI>i ){
5923 int t;
5924 MemPage *pT;
danielk19774dbaa892009-06-16 16:50:22 +00005925 t = apNew[i]->pgno;
drhf9ffac92002-03-02 19:00:31 +00005926 pT = apNew[i];
drhf9ffac92002-03-02 19:00:31 +00005927 apNew[i] = apNew[minI];
drhf9ffac92002-03-02 19:00:31 +00005928 apNew[minI] = pT;
5929 }
5930 }
danielk1977e5765212009-06-17 11:13:28 +00005931 TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
danielk19774dbaa892009-06-16 16:50:22 +00005932 apNew[0]->pgno, szNew[0],
5933 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
5934 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
5935 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
5936 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
5937
5938 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
5939 put4byte(pRight, apNew[nNew-1]->pgno);
drh24cd67e2004-05-10 16:18:47 +00005940
drhf9ffac92002-03-02 19:00:31 +00005941 /*
drh14acc042001-06-10 19:56:58 +00005942 ** Evenly distribute the data in apCell[] across the new pages.
5943 ** Insert divider cells into pParent as necessary.
5944 */
5945 j = 0;
5946 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00005947 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00005948 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00005949 assert( j<nMaxCells );
drh10131482008-07-11 03:34:09 +00005950 zeroPage(pNew, pageFlags);
drhfa1a98a2004-05-14 19:08:17 +00005951 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00005952 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00005953 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00005954
danielk1977ac11ee62005-01-15 12:45:51 +00005955 j = cntNew[i];
5956
5957 /* If the sibling page assembled above was not the right-most sibling,
5958 ** insert a divider cell into the parent page.
5959 */
danielk19771c3d2bf2009-06-23 16:40:17 +00005960 assert( i<nNew-1 || j==nCell );
5961 if( j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00005962 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00005963 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00005964 int sz;
danielk1977634f2982005-03-28 08:44:07 +00005965
5966 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00005967 pCell = apCell[j];
5968 sz = szCell[j] + leafCorrection;
danielk19776067a9b2009-06-09 09:41:00 +00005969 pTemp = &aOvflSpace[iOvflSpace];
drh4b70f112004-05-02 21:12:19 +00005970 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00005971 memcpy(&pNew->aData[8], pCell, 4);
drh8b18dd42004-05-12 19:18:15 +00005972 }else if( leafData ){
drhfd131da2007-08-07 17:13:03 +00005973 /* If the tree is a leaf-data tree, and the siblings are leaves,
danielk1977ac11ee62005-01-15 12:45:51 +00005974 ** then there is no divider cell in apCell[]. Instead, the divider
5975 ** cell consists of the integer key for the right-most cell of
5976 ** the sibling-page assembled above only.
5977 */
drh6f11bef2004-05-13 01:12:56 +00005978 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00005979 j--;
drh16a9b832007-05-05 18:39:25 +00005980 sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
drhe5ae5732008-06-15 02:51:47 +00005981 pCell = pTemp;
danielk19774dbaa892009-06-16 16:50:22 +00005982 sz = 4 + putVarint(&pCell[4], info.nKey);
drh8b18dd42004-05-12 19:18:15 +00005983 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00005984 }else{
5985 pCell -= 4;
danielk19774aeff622007-05-12 09:30:47 +00005986 /* Obscure case for non-leaf-data trees: If the cell at pCell was
drh85b623f2007-12-13 21:54:09 +00005987 ** previously stored on a leaf node, and its reported size was 4
danielk19774aeff622007-05-12 09:30:47 +00005988 ** bytes, then it may actually be smaller than this
5989 ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
drh85b623f2007-12-13 21:54:09 +00005990 ** any cell). But it is important to pass the correct size to
danielk19774aeff622007-05-12 09:30:47 +00005991 ** insertCell(), so reparse the cell now.
5992 **
5993 ** Note that this can never happen in an SQLite data file, as all
5994 ** cells are at least 4 bytes. It only happens in b-trees used
5995 ** to evaluate "IN (SELECT ...)" and similar clauses.
5996 */
5997 if( szCell[j]==4 ){
5998 assert(leafCorrection==4);
5999 sz = cellSizePtr(pParent, pCell);
6000 }
drh4b70f112004-05-02 21:12:19 +00006001 }
danielk19776067a9b2009-06-09 09:41:00 +00006002 iOvflSpace += sz;
drhe5ae5732008-06-15 02:51:47 +00006003 assert( sz<=pBt->pageSize/4 );
danielk19776067a9b2009-06-09 09:41:00 +00006004 assert( iOvflSpace<=pBt->pageSize );
danielk19774dbaa892009-06-16 16:50:22 +00006005 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno);
danielk1977e80463b2004-11-03 03:01:16 +00006006 if( rc!=SQLITE_OK ) goto balance_cleanup;
drhc5053fb2008-11-27 02:22:10 +00006007 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk197785d90ca2008-07-19 14:25:15 +00006008
drh14acc042001-06-10 19:56:58 +00006009 j++;
6010 nxDiv++;
6011 }
6012 }
drh6019e162001-07-02 17:51:45 +00006013 assert( j==nCell );
drh7aa8f852006-03-28 00:24:44 +00006014 assert( nOld>0 );
6015 assert( nNew>0 );
drh4b70f112004-05-02 21:12:19 +00006016 if( (pageFlags & PTF_LEAF)==0 ){
danielk197787c52b52008-07-19 11:49:07 +00006017 u8 *zChild = &apCopy[nOld-1]->aData[8];
6018 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
drh14acc042001-06-10 19:56:58 +00006019 }
6020
danielk197713bd99f2009-06-24 05:40:34 +00006021 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
6022 /* The root page of the b-tree now contains no cells. The only sibling
6023 ** page is the right-child of the parent. Copy the contents of the
6024 ** child page into the parent, decreasing the overall height of the
6025 ** b-tree structure by one. This is described as the "balance-shallower"
6026 ** sub-algorithm in some documentation.
6027 **
6028 ** If this is an auto-vacuum database, the call to copyNodeContent()
6029 ** sets all pointer-map entries corresponding to database image pages
6030 ** for which the pointer is stored within the content being copied.
6031 **
6032 ** The second assert below verifies that the child page is defragmented
6033 ** (it must be, as it was just reconstructed using assemblePage()). This
6034 ** is important if the parent page happens to be page 1 of the database
6035 ** image. */
6036 assert( nNew==1 );
6037 assert( apNew[0]->nFree ==
6038 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
6039 );
6040 if( SQLITE_OK==(rc = copyNodeContent(apNew[0], pParent)) ){
6041 rc = freePage(apNew[0]);
6042 }
6043 }else if( ISAUTOVACUUM ){
6044 /* Fix the pointer-map entries for all the cells that were shifted around.
6045 ** There are several different types of pointer-map entries that need to
6046 ** be dealt with by this routine. Some of these have been set already, but
6047 ** many have not. The following is a summary:
6048 **
6049 ** 1) The entries associated with new sibling pages that were not
6050 ** siblings when this function was called. These have already
6051 ** been set. We don't need to worry about old siblings that were
6052 ** moved to the free-list - the freePage() code has taken care
6053 ** of those.
6054 **
6055 ** 2) The pointer-map entries associated with the first overflow
6056 ** page in any overflow chains used by new divider cells. These
6057 ** have also already been taken care of by the insertCell() code.
6058 **
6059 ** 3) If the sibling pages are not leaves, then the child pages of
6060 ** cells stored on the sibling pages may need to be updated.
6061 **
6062 ** 4) If the sibling pages are not internal intkey nodes, then any
6063 ** overflow pages used by these cells may need to be updated
6064 ** (internal intkey nodes never contain pointers to overflow pages).
6065 **
6066 ** 5) If the sibling pages are not leaves, then the pointer-map
6067 ** entries for the right-child pages of each sibling may need
6068 ** to be updated.
6069 **
6070 ** Cases 1 and 2 are dealt with above by other code. The next
6071 ** block deals with cases 3 and 4 and the one after that, case 5. Since
6072 ** setting a pointer map entry is a relatively expensive operation, this
6073 ** code only sets pointer map entries for child or overflow pages that have
6074 ** actually moved between pages. */
danielk19774dbaa892009-06-16 16:50:22 +00006075 MemPage *pNew = apNew[0];
6076 MemPage *pOld = apCopy[0];
6077 int nOverflow = pOld->nOverflow;
6078 int iNextOld = pOld->nCell + nOverflow;
6079 int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
6080 j = 0; /* Current 'old' sibling page */
6081 k = 0; /* Current 'new' sibling page */
6082 for(i=0; i<nCell && rc==SQLITE_OK; i++){
6083 int isDivider = 0;
6084 while( i==iNextOld ){
6085 /* Cell i is the cell immediately following the last cell on old
6086 ** sibling page j. If the siblings are not leaf pages of an
6087 ** intkey b-tree, then cell i was a divider cell. */
6088 pOld = apCopy[++j];
6089 iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
6090 if( pOld->nOverflow ){
6091 nOverflow = pOld->nOverflow;
6092 iOverflow = i + !leafData + pOld->aOvfl[0].idx;
6093 }
6094 isDivider = !leafData;
6095 }
6096
6097 assert(nOverflow>0 || iOverflow<i );
6098 assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
6099 assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
6100 if( i==iOverflow ){
6101 isDivider = 1;
6102 if( (--nOverflow)>0 ){
6103 iOverflow++;
6104 }
6105 }
6106
6107 if( i==cntNew[k] ){
6108 /* Cell i is the cell immediately following the last cell on new
6109 ** sibling page k. If the siblings are not leaf pages of an
6110 ** intkey b-tree, then cell i is a divider cell. */
6111 pNew = apNew[++k];
6112 if( !leafData ) continue;
6113 }
6114 assert( rc==SQLITE_OK );
6115 assert( j<nOld );
6116 assert( k<nNew );
6117
6118 /* If the cell was originally divider cell (and is not now) or
6119 ** an overflow cell, or if the cell was located on a different sibling
6120 ** page before the balancing, then the pointer map entries associated
6121 ** with any child or overflow pages need to be updated. */
6122 if( isDivider || pOld->pgno!=pNew->pgno ){
6123 if( !leafCorrection ){
6124 rc = ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno);
6125 }
6126 if( szCell[i]>pNew->minLocal && rc==SQLITE_OK ){
6127 rc = ptrmapPutOvflPtr(pNew, apCell[i]);
6128 }
6129 }
6130 }
6131
6132 if( !leafCorrection ){
6133 for(i=0; rc==SQLITE_OK && i<nNew; i++){
6134 rc = ptrmapPut(
6135 pBt, get4byte(&apNew[i]->aData[8]), PTRMAP_BTREE, apNew[i]->pgno);
6136 }
6137 }
6138
6139#if 0
6140 /* The ptrmapCheckPages() contains assert() statements that verify that
6141 ** all pointer map pages are set correctly. This is helpful while
6142 ** debugging. This is usually disabled because a corrupt database may
6143 ** cause an assert() statement to fail. */
6144 ptrmapCheckPages(apNew, nNew);
6145 ptrmapCheckPages(&pParent, 1);
6146#endif
6147 }
6148
danielk197771d5d2c2008-09-29 11:49:47 +00006149 assert( pParent->isInit );
danielk1977e5765212009-06-17 11:13:28 +00006150 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
6151 nOld, nNew, nCell));
danielk1977cd581a72009-06-23 15:43:39 +00006152
drh8b2f49b2001-06-08 00:21:52 +00006153 /*
drh14acc042001-06-10 19:56:58 +00006154 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00006155 */
drh14acc042001-06-10 19:56:58 +00006156balance_cleanup:
drhfacf0302008-06-17 15:12:00 +00006157 sqlite3ScratchFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00006158 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00006159 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00006160 }
drh14acc042001-06-10 19:56:58 +00006161 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00006162 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00006163 }
danielk1977eaa06f62008-09-18 17:34:44 +00006164
drh8b2f49b2001-06-08 00:21:52 +00006165 return rc;
6166}
6167
drh43605152004-05-29 21:46:49 +00006168
6169/*
danielk1977a50d9aa2009-06-08 14:49:45 +00006170** This function is called when the root page of a b-tree structure is
6171** overfull (has one or more overflow pages).
drh43605152004-05-29 21:46:49 +00006172**
danielk1977a50d9aa2009-06-08 14:49:45 +00006173** A new child page is allocated and the contents of the current root
6174** page, including overflow cells, are copied into the child. The root
6175** page is then overwritten to make it an empty page with the right-child
6176** pointer pointing to the new page.
6177**
6178** Before returning, all pointer-map entries corresponding to pages
6179** that the new child-page now contains pointers to are updated. The
6180** entry corresponding to the new right-child pointer of the root
6181** page is also updated.
6182**
6183** If successful, *ppChild is set to contain a reference to the child
6184** page and SQLITE_OK is returned. In this case the caller is required
6185** to call releasePage() on *ppChild exactly once. If an error occurs,
6186** an error code is returned and *ppChild is set to 0.
drh43605152004-05-29 21:46:49 +00006187*/
danielk1977a50d9aa2009-06-08 14:49:45 +00006188static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
6189 int rc; /* Return value from subprocedures */
6190 MemPage *pChild = 0; /* Pointer to a new child page */
6191 Pgno pgnoChild; /* Page number of the new child page */
6192 BtShared *pBt = pRoot->pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00006193
danielk1977a50d9aa2009-06-08 14:49:45 +00006194 assert( pRoot->nOverflow>0 );
drh1fee73e2007-08-29 04:00:57 +00006195 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bc2ca9e2008-11-13 14:28:28 +00006196
danielk1977a50d9aa2009-06-08 14:49:45 +00006197 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
6198 ** page that will become the new right-child of pPage. Copy the contents
6199 ** of the node stored on pRoot into the new child page.
6200 */
6201 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pRoot->pDbPage))
6202 || SQLITE_OK!=(rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0))
6203 || SQLITE_OK!=(rc = copyNodeContent(pRoot, pChild))
6204 || (ISAUTOVACUUM &&
6205 SQLITE_OK!=(rc = ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno)))
6206 ){
6207 *ppChild = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00006208 releasePage(pChild);
danielk1977a50d9aa2009-06-08 14:49:45 +00006209 return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00006210 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006211 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
6212 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
6213 assert( pChild->nCell==pRoot->nCell );
danielk197771d5d2c2008-09-29 11:49:47 +00006214
danielk1977a50d9aa2009-06-08 14:49:45 +00006215 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
6216
6217 /* Copy the overflow cells from pRoot to pChild */
6218 memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
6219 pChild->nOverflow = pRoot->nOverflow;
danielk1977a50d9aa2009-06-08 14:49:45 +00006220
6221 /* Zero the contents of pRoot. Then install pChild as the right-child. */
6222 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
6223 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
6224
6225 *ppChild = pChild;
6226 return SQLITE_OK;
drh43605152004-05-29 21:46:49 +00006227}
6228
6229/*
danielk197771d5d2c2008-09-29 11:49:47 +00006230** The page that pCur currently points to has just been modified in
6231** some way. This function figures out if this modification means the
6232** tree needs to be balanced, and if so calls the appropriate balancing
danielk1977a50d9aa2009-06-08 14:49:45 +00006233** routine. Balancing routines are:
6234**
6235** balance_quick()
danielk1977a50d9aa2009-06-08 14:49:45 +00006236** balance_deeper()
6237** balance_nonroot()
drh43605152004-05-29 21:46:49 +00006238*/
danielk1977a50d9aa2009-06-08 14:49:45 +00006239static int balance(BtCursor *pCur){
drh43605152004-05-29 21:46:49 +00006240 int rc = SQLITE_OK;
danielk1977a50d9aa2009-06-08 14:49:45 +00006241 const int nMin = pCur->pBt->usableSize * 2 / 3;
6242 u8 aBalanceQuickSpace[13];
6243 u8 *pFree = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00006244
shane75ac1de2009-06-09 18:58:52 +00006245 TESTONLY( int balance_quick_called = 0 );
6246 TESTONLY( int balance_deeper_called = 0 );
danielk1977a50d9aa2009-06-08 14:49:45 +00006247
6248 do {
6249 int iPage = pCur->iPage;
6250 MemPage *pPage = pCur->apPage[iPage];
6251
6252 if( iPage==0 ){
6253 if( pPage->nOverflow ){
6254 /* The root page of the b-tree is overfull. In this case call the
6255 ** balance_deeper() function to create a new child for the root-page
6256 ** and copy the current contents of the root-page to it. The
6257 ** next iteration of the do-loop will balance the child page.
6258 */
6259 assert( (balance_deeper_called++)==0 );
6260 rc = balance_deeper(pPage, &pCur->apPage[1]);
6261 if( rc==SQLITE_OK ){
6262 pCur->iPage = 1;
6263 pCur->aiIdx[0] = 0;
6264 pCur->aiIdx[1] = 0;
6265 assert( pCur->apPage[1]->nOverflow );
6266 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006267 }else{
danielk1977a50d9aa2009-06-08 14:49:45 +00006268 break;
6269 }
6270 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
6271 break;
6272 }else{
6273 MemPage * const pParent = pCur->apPage[iPage-1];
6274 int const iIdx = pCur->aiIdx[iPage-1];
6275
6276 rc = sqlite3PagerWrite(pParent->pDbPage);
6277 if( rc==SQLITE_OK ){
6278#ifndef SQLITE_OMIT_QUICKBALANCE
6279 if( pPage->hasData
6280 && pPage->nOverflow==1
6281 && pPage->aOvfl[0].idx==pPage->nCell
6282 && pParent->pgno!=1
6283 && pParent->nCell==iIdx
6284 ){
6285 /* Call balance_quick() to create a new sibling of pPage on which
6286 ** to store the overflow cell. balance_quick() inserts a new cell
6287 ** into pParent, which may cause pParent overflow. If this
6288 ** happens, the next interation of the do-loop will balance pParent
6289 ** use either balance_nonroot() or balance_deeper(). Until this
6290 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
6291 ** buffer.
6292 **
6293 ** The purpose of the following assert() is to check that only a
6294 ** single call to balance_quick() is made for each call to this
6295 ** function. If this were not verified, a subtle bug involving reuse
6296 ** of the aBalanceQuickSpace[] might sneak in.
6297 */
6298 assert( (balance_quick_called++)==0 );
6299 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
6300 }else
6301#endif
6302 {
6303 /* In this case, call balance_nonroot() to redistribute cells
6304 ** between pPage and up to 2 of its sibling pages. This involves
6305 ** modifying the contents of pParent, which may cause pParent to
6306 ** become overfull or underfull. The next iteration of the do-loop
6307 ** will balance the parent page to correct this.
6308 **
6309 ** If the parent page becomes overfull, the overflow cell or cells
6310 ** are stored in the pSpace buffer allocated immediately below.
6311 ** A subsequent iteration of the do-loop will deal with this by
6312 ** calling balance_nonroot() (balance_deeper() may be called first,
6313 ** but it doesn't deal with overflow cells - just moves them to a
6314 ** different page). Once this subsequent call to balance_nonroot()
6315 ** has completed, it is safe to release the pSpace buffer used by
6316 ** the previous call, as the overflow cell data will have been
6317 ** copied either into the body of a database page or into the new
6318 ** pSpace buffer passed to the latter call to balance_nonroot().
6319 */
6320 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
danielk1977cd581a72009-06-23 15:43:39 +00006321 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
danielk1977a50d9aa2009-06-08 14:49:45 +00006322 if( pFree ){
6323 /* If pFree is not NULL, it points to the pSpace buffer used
6324 ** by a previous call to balance_nonroot(). Its contents are
6325 ** now stored either on real database pages or within the
6326 ** new pSpace buffer, so it may be safely freed here. */
6327 sqlite3PageFree(pFree);
6328 }
6329
danielk19774dbaa892009-06-16 16:50:22 +00006330 /* The pSpace buffer will be freed after the next call to
6331 ** balance_nonroot(), or just before this function returns, whichever
6332 ** comes first. */
danielk1977a50d9aa2009-06-08 14:49:45 +00006333 pFree = pSpace;
danielk1977a50d9aa2009-06-08 14:49:45 +00006334 }
6335 }
6336
6337 pPage->nOverflow = 0;
6338
6339 /* The next iteration of the do-loop balances the parent page. */
6340 releasePage(pPage);
6341 pCur->iPage--;
drh43605152004-05-29 21:46:49 +00006342 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006343 }while( rc==SQLITE_OK );
6344
6345 if( pFree ){
6346 sqlite3PageFree(pFree);
drh43605152004-05-29 21:46:49 +00006347 }
6348 return rc;
6349}
6350
drhf74b8d92002-09-01 23:20:45 +00006351
6352/*
drh3b7511c2001-05-26 13:15:44 +00006353** Insert a new record into the BTree. The key is given by (pKey,nKey)
6354** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00006355** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00006356** is left pointing at a random location.
6357**
6358** For an INTKEY table, only the nKey value of the key is used. pKey is
6359** ignored. For a ZERODATA table, the pData and nData are both ignored.
danielk1977de630352009-05-04 11:42:29 +00006360**
6361** If the seekResult parameter is non-zero, then a successful call to
6362** sqlite3BtreeMoveto() to seek cursor pCur to (pKey, nKey) has already
6363** been performed. seekResult is the search result returned (a negative
6364** number if pCur points at an entry that is smaller than (pKey, nKey), or
6365** a positive value if pCur points at an etry that is larger than
6366** (pKey, nKey)).
6367**
6368** If the seekResult parameter is 0, then cursor pCur may point to any
6369** entry or to no entry at all. In this case this function has to seek
6370** the cursor before the new key can be inserted.
drh3b7511c2001-05-26 13:15:44 +00006371*/
drh3aac2dd2004-04-26 14:10:20 +00006372int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00006373 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00006374 const void *pKey, i64 nKey, /* The key of the new record */
drhe4d90812007-03-29 05:51:49 +00006375 const void *pData, int nData, /* The data of the new record */
drhb026e052007-05-02 01:34:31 +00006376 int nZero, /* Number of extra 0 bytes to append to data */
danielk1977de630352009-05-04 11:42:29 +00006377 int appendBias, /* True if this is likely an append */
6378 int seekResult /* Result of prior sqlite3BtreeMoveto() call */
drh3b7511c2001-05-26 13:15:44 +00006379){
drh3b7511c2001-05-26 13:15:44 +00006380 int rc;
danielk1977de630352009-05-04 11:42:29 +00006381 int loc = seekResult;
drh14acc042001-06-10 19:56:58 +00006382 int szNew;
danielk197771d5d2c2008-09-29 11:49:47 +00006383 int idx;
drh3b7511c2001-05-26 13:15:44 +00006384 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00006385 Btree *p = pCur->pBtree;
6386 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00006387 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00006388 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00006389
drh1fee73e2007-08-29 04:00:57 +00006390 assert( cursorHoldsMutex(pCur) );
drh64022502009-01-09 14:11:04 +00006391 assert( pBt->inTransaction==TRANS_WRITE );
drhf74b8d92002-09-01 23:20:45 +00006392 assert( !pBt->readOnly );
drh64022502009-01-09 14:11:04 +00006393 assert( pCur->wrFlag );
danielk197796d48e92009-06-29 06:00:37 +00006394 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
6395
6396 /* If this is an insert into a table b-tree, invalidate any incrblob
6397 ** cursors open on the row being replaced (assuming this is a replace
6398 ** operation - if it is not, the following is a no-op). */
6399 if( pCur->pKeyInfo==0 ){
6400 invalidateIncrblobCursors(p, pCur->pgnoRoot, nKey, 0);
drhf74b8d92002-09-01 23:20:45 +00006401 }
danielk197796d48e92009-06-29 06:00:37 +00006402
drhfb982642007-08-30 01:19:59 +00006403 if( pCur->eState==CURSOR_FAULT ){
6404 return pCur->skip;
6405 }
danielk1977da184232006-01-05 11:34:32 +00006406
danielk19779c3acf32009-05-02 07:36:49 +00006407 /* Save the positions of any other cursors open on this table.
6408 **
6409 ** In some cases, the call to sqlite3BtreeMoveto() below is a no-op. For
6410 ** example, when inserting data into a table with auto-generated integer
6411 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
6412 ** integer key to use. It then calls this function to actually insert the
6413 ** data into the intkey B-Tree. In this case sqlite3BtreeMoveto() recognizes
6414 ** that the cursor is already where it needs to be and returns without
6415 ** doing any work. To avoid thwarting these optimizations, it is important
6416 ** not to clear the cursor here.
6417 */
danielk1977de630352009-05-04 11:42:29 +00006418 if(
6419 SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) || (!loc &&
drhe63d9992008-08-13 19:11:48 +00006420 SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
danielk1977de630352009-05-04 11:42:29 +00006421 )){
danielk1977da184232006-01-05 11:34:32 +00006422 return rc;
6423 }
danielk1977b980d2212009-06-22 18:03:51 +00006424 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
danielk1977da184232006-01-05 11:34:32 +00006425
danielk197771d5d2c2008-09-29 11:49:47 +00006426 pPage = pCur->apPage[pCur->iPage];
drh4a1c3802004-05-12 15:15:47 +00006427 assert( pPage->intKey || nKey>=0 );
drh44845222008-07-17 18:39:57 +00006428 assert( pPage->leaf || !pPage->intKey );
drh3a4c1412004-05-09 20:40:11 +00006429 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
6430 pCur->pgnoRoot, nKey, nData, pPage->pgno,
6431 loc==0 ? "overwrite" : "new entry"));
danielk197771d5d2c2008-09-29 11:49:47 +00006432 assert( pPage->isInit );
danielk197752ae7242008-03-25 14:24:56 +00006433 allocateTempSpace(pBt);
6434 newCell = pBt->pTmpSpace;
drh2e38c322004-09-03 18:38:44 +00006435 if( newCell==0 ) return SQLITE_NOMEM;
drhb026e052007-05-02 01:34:31 +00006436 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
drh2e38c322004-09-03 18:38:44 +00006437 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00006438 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00006439 assert( szNew<=MX_CELL_SIZE(pBt) );
danielk197771d5d2c2008-09-29 11:49:47 +00006440 idx = pCur->aiIdx[pCur->iPage];
danielk1977b980d2212009-06-22 18:03:51 +00006441 if( loc==0 ){
drha9121e42008-02-19 14:59:35 +00006442 u16 szOld;
danielk197771d5d2c2008-09-29 11:49:47 +00006443 assert( idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00006444 rc = sqlite3PagerWrite(pPage->pDbPage);
6445 if( rc ){
6446 goto end_insert;
6447 }
danielk197771d5d2c2008-09-29 11:49:47 +00006448 oldCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00006449 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006450 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00006451 }
drh43605152004-05-29 21:46:49 +00006452 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00006453 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00006454 if( rc ) goto end_insert;
shane0af3f892008-11-12 04:55:34 +00006455 rc = dropCell(pPage, idx, szOld);
6456 if( rc!=SQLITE_OK ) {
6457 goto end_insert;
6458 }
drh7c717f72001-06-24 20:39:41 +00006459 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00006460 assert( pPage->leaf );
danielk197771d5d2c2008-09-29 11:49:47 +00006461 idx = ++pCur->aiIdx[pCur->iPage];
drh14acc042001-06-10 19:56:58 +00006462 }else{
drh4b70f112004-05-02 21:12:19 +00006463 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00006464 }
danielk197771d5d2c2008-09-29 11:49:47 +00006465 rc = insertCell(pPage, idx, newCell, szNew, 0, 0);
danielk19773f632d52009-05-02 10:03:09 +00006466 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
drh9bf9e9c2008-12-05 20:01:43 +00006467
danielk1977a50d9aa2009-06-08 14:49:45 +00006468 /* If no error has occured and pPage has an overflow cell, call balance()
6469 ** to redistribute the cells within the tree. Since balance() may move
6470 ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
6471 ** variables.
danielk19773f632d52009-05-02 10:03:09 +00006472 **
danielk1977a50d9aa2009-06-08 14:49:45 +00006473 ** Previous versions of SQLite called moveToRoot() to move the cursor
6474 ** back to the root page as balance() used to invalidate the contents
danielk197754109bb2009-06-23 11:22:29 +00006475 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
6476 ** set the cursor state to "invalid". This makes common insert operations
6477 ** slightly faster.
danielk19773f632d52009-05-02 10:03:09 +00006478 **
danielk1977a50d9aa2009-06-08 14:49:45 +00006479 ** There is a subtle but important optimization here too. When inserting
6480 ** multiple records into an intkey b-tree using a single cursor (as can
6481 ** happen while processing an "INSERT INTO ... SELECT" statement), it
6482 ** is advantageous to leave the cursor pointing to the last entry in
6483 ** the b-tree if possible. If the cursor is left pointing to the last
6484 ** entry in the table, and the next row inserted has an integer key
6485 ** larger than the largest existing key, it is possible to insert the
6486 ** row without seeking the cursor. This can be a big performance boost.
danielk19773f632d52009-05-02 10:03:09 +00006487 */
danielk1977a50d9aa2009-06-08 14:49:45 +00006488 pCur->info.nSize = 0;
6489 pCur->validNKey = 0;
6490 if( rc==SQLITE_OK && pPage->nOverflow ){
danielk1977a50d9aa2009-06-08 14:49:45 +00006491 rc = balance(pCur);
6492
6493 /* Must make sure nOverflow is reset to zero even if the balance()
danielk197754109bb2009-06-23 11:22:29 +00006494 ** fails. Internal data structure corruption will result otherwise.
6495 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
6496 ** from trying to save the current position of the cursor. */
danielk1977a50d9aa2009-06-08 14:49:45 +00006497 pCur->apPage[pCur->iPage]->nOverflow = 0;
danielk197754109bb2009-06-23 11:22:29 +00006498 pCur->eState = CURSOR_INVALID;
danielk19773f632d52009-05-02 10:03:09 +00006499 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006500 assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
drh9bf9e9c2008-12-05 20:01:43 +00006501
drh2e38c322004-09-03 18:38:44 +00006502end_insert:
drh5e2f8b92001-05-28 00:41:15 +00006503 return rc;
6504}
6505
6506/*
drh4b70f112004-05-02 21:12:19 +00006507** Delete the entry that the cursor is pointing to. The cursor
drhf94a1732008-09-30 17:18:17 +00006508** is left pointing at a arbitrary location.
drh3b7511c2001-05-26 13:15:44 +00006509*/
drh3aac2dd2004-04-26 14:10:20 +00006510int sqlite3BtreeDelete(BtCursor *pCur){
drhd677b3d2007-08-20 22:48:41 +00006511 Btree *p = pCur->pBtree;
danielk19774dbaa892009-06-16 16:50:22 +00006512 BtShared *pBt = p->pBt;
6513 int rc; /* Return code */
6514 MemPage *pPage; /* Page to delete cell from */
6515 unsigned char *pCell; /* Pointer to cell to delete */
6516 int iCellIdx; /* Index of cell to delete */
6517 int iCellDepth; /* Depth of node containing pCell */
drh8b2f49b2001-06-08 00:21:52 +00006518
drh1fee73e2007-08-29 04:00:57 +00006519 assert( cursorHoldsMutex(pCur) );
drh64022502009-01-09 14:11:04 +00006520 assert( pBt->inTransaction==TRANS_WRITE );
drhf74b8d92002-09-01 23:20:45 +00006521 assert( !pBt->readOnly );
drh64022502009-01-09 14:11:04 +00006522 assert( pCur->wrFlag );
danielk197796d48e92009-06-29 06:00:37 +00006523 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
6524 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
6525
danielk19774dbaa892009-06-16 16:50:22 +00006526 if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
6527 || NEVER(pCur->eState!=CURSOR_VALID)
6528 ){
6529 return SQLITE_ERROR; /* Something has gone awry. */
drhf74b8d92002-09-01 23:20:45 +00006530 }
danielk1977da184232006-01-05 11:34:32 +00006531
danielk197796d48e92009-06-29 06:00:37 +00006532 /* If this is a delete operation to remove a row from a table b-tree,
6533 ** invalidate any incrblob cursors open on the row being deleted. */
6534 if( pCur->pKeyInfo==0 ){
6535 invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
danielk19774dbaa892009-06-16 16:50:22 +00006536 }
6537
6538 iCellDepth = pCur->iPage;
6539 iCellIdx = pCur->aiIdx[iCellDepth];
6540 pPage = pCur->apPage[iCellDepth];
6541 pCell = findCell(pPage, iCellIdx);
6542
6543 /* If the page containing the entry to delete is not a leaf page, move
6544 ** the cursor to the largest entry in the tree that is smaller than
6545 ** the entry being deleted. This cell will replace the cell being deleted
6546 ** from the internal node. The 'previous' entry is used for this instead
6547 ** of the 'next' entry, as the previous entry is always a part of the
6548 ** sub-tree headed by the child page of the cell being deleted. This makes
6549 ** balancing the tree following the delete operation easier. */
6550 if( !pPage->leaf ){
6551 int notUsed;
6552 if( SQLITE_OK!=(rc = sqlite3BtreePrevious(pCur, &notUsed)) ){
6553 return rc;
6554 }
6555 }
6556
6557 /* Save the positions of any other cursors open on this table before
6558 ** making any modifications. Make the page containing the entry to be
6559 ** deleted writable. Then free any overflow pages associated with the
6560 ** entry and finally remove the cell itself from within the page. */
6561 if( SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))
6562 || SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage))
6563 || SQLITE_OK!=(rc = clearCell(pPage, pCell))
6564 || SQLITE_OK!=(rc = dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell)))
danielk1977da184232006-01-05 11:34:32 +00006565 ){
6566 return rc;
6567 }
danielk1977e6efa742004-11-10 11:55:10 +00006568
danielk19774dbaa892009-06-16 16:50:22 +00006569 /* If the cell deleted was not located on a leaf page, then the cursor
6570 ** is currently pointing to the largest entry in the sub-tree headed
6571 ** by the child-page of the cell that was just deleted from an internal
6572 ** node. The cell from the leaf node needs to be moved to the internal
6573 ** node to replace the deleted cell. */
drh4b70f112004-05-02 21:12:19 +00006574 if( !pPage->leaf ){
danielk19774dbaa892009-06-16 16:50:22 +00006575 MemPage *pLeaf = pCur->apPage[pCur->iPage];
6576 int nCell;
6577 Pgno n = pCur->apPage[iCellDepth+1]->pgno;
6578 unsigned char *pTmp;
danielk1977e6efa742004-11-10 11:55:10 +00006579
danielk19774dbaa892009-06-16 16:50:22 +00006580 pCell = findCell(pLeaf, pLeaf->nCell-1);
6581 nCell = cellSizePtr(pLeaf, pCell);
6582 assert( MX_CELL_SIZE(pBt)>=nCell );
danielk197771d5d2c2008-09-29 11:49:47 +00006583
danielk19774dbaa892009-06-16 16:50:22 +00006584 allocateTempSpace(pBt);
6585 pTmp = pBt->pTmpSpace;
danielk19772f78fc62008-09-30 09:31:45 +00006586
danielk19774dbaa892009-06-16 16:50:22 +00006587 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pLeaf->pDbPage))
6588 || SQLITE_OK!=(rc = insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n))
6589 || SQLITE_OK!=(rc = dropCell(pLeaf, pLeaf->nCell-1, nCell))
6590 ){
6591 return rc;
shanedcc50b72008-11-13 18:29:50 +00006592 }
drh5e2f8b92001-05-28 00:41:15 +00006593 }
danielk19774dbaa892009-06-16 16:50:22 +00006594
6595 /* Balance the tree. If the entry deleted was located on a leaf page,
6596 ** then the cursor still points to that page. In this case the first
6597 ** call to balance() repairs the tree, and the if(...) condition is
6598 ** never true.
6599 **
6600 ** Otherwise, if the entry deleted was on an internal node page, then
6601 ** pCur is pointing to the leaf page from which a cell was removed to
6602 ** replace the cell deleted from the internal node. This is slightly
6603 ** tricky as the leaf node may be underfull, and the internal node may
6604 ** be either under or overfull. In this case run the balancing algorithm
6605 ** on the leaf node first. If the balance proceeds far enough up the
6606 ** tree that we can be sure that any problem in the internal node has
6607 ** been corrected, so be it. Otherwise, after balancing the leaf node,
6608 ** walk the cursor up the tree to the internal node and balance it as
6609 ** well. */
6610 rc = balance(pCur);
6611 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
6612 while( pCur->iPage>iCellDepth ){
6613 releasePage(pCur->apPage[pCur->iPage--]);
6614 }
6615 rc = balance(pCur);
6616 }
6617
danielk19776b456a22005-03-21 04:04:02 +00006618 if( rc==SQLITE_OK ){
6619 moveToRoot(pCur);
6620 }
drh5e2f8b92001-05-28 00:41:15 +00006621 return rc;
drh3b7511c2001-05-26 13:15:44 +00006622}
drh8b2f49b2001-06-08 00:21:52 +00006623
6624/*
drhc6b52df2002-01-04 03:09:29 +00006625** Create a new BTree table. Write into *piTable the page
6626** number for the root page of the new table.
6627**
drhab01f612004-05-22 02:55:23 +00006628** The type of type is determined by the flags parameter. Only the
6629** following values of flags are currently in use. Other values for
6630** flags might not work:
6631**
6632** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
6633** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00006634*/
drhd677b3d2007-08-20 22:48:41 +00006635static int btreeCreateTable(Btree *p, int *piTable, int flags){
danielk1977aef0bf62005-12-30 16:28:01 +00006636 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006637 MemPage *pRoot;
6638 Pgno pgnoRoot;
6639 int rc;
drhd677b3d2007-08-20 22:48:41 +00006640
drh1fee73e2007-08-29 04:00:57 +00006641 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00006642 assert( pBt->inTransaction==TRANS_WRITE );
danielk197728129562005-01-11 10:25:06 +00006643 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00006644
danielk1977003ba062004-11-04 02:57:33 +00006645#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00006646 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00006647 if( rc ){
6648 return rc;
6649 }
danielk1977003ba062004-11-04 02:57:33 +00006650#else
danielk1977687566d2004-11-02 12:56:41 +00006651 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00006652 Pgno pgnoMove; /* Move a page here to make room for the root-page */
6653 MemPage *pPageMove; /* The page to move to. */
6654
danielk197720713f32007-05-03 11:43:33 +00006655 /* Creating a new table may probably require moving an existing database
6656 ** to make room for the new tables root page. In case this page turns
6657 ** out to be an overflow page, delete all overflow page-map caches
6658 ** held by open cursors.
6659 */
danielk197792d4d7a2007-05-04 12:05:56 +00006660 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00006661
danielk1977003ba062004-11-04 02:57:33 +00006662 /* Read the value of meta[3] from the database to determine where the
6663 ** root page of the new table should go. meta[3] is the largest root-page
6664 ** created so far, so the new root-page is (meta[3]+1).
6665 */
danielk19770d19f7a2009-06-03 11:25:07 +00006666 rc = sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
drhd677b3d2007-08-20 22:48:41 +00006667 if( rc!=SQLITE_OK ){
6668 return rc;
6669 }
danielk1977003ba062004-11-04 02:57:33 +00006670 pgnoRoot++;
6671
danielk1977599fcba2004-11-08 07:13:13 +00006672 /* The new root-page may not be allocated on a pointer-map page, or the
6673 ** PENDING_BYTE page.
6674 */
drh72190432008-01-31 14:54:43 +00006675 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00006676 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00006677 pgnoRoot++;
6678 }
6679 assert( pgnoRoot>=3 );
6680
6681 /* Allocate a page. The page that currently resides at pgnoRoot will
6682 ** be moved to the allocated page (unless the allocated page happens
6683 ** to reside at pgnoRoot).
6684 */
drh4f0c5872007-03-26 22:05:01 +00006685 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00006686 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00006687 return rc;
6688 }
danielk1977003ba062004-11-04 02:57:33 +00006689
6690 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00006691 /* pgnoRoot is the page that will be used for the root-page of
6692 ** the new table (assuming an error did not occur). But we were
6693 ** allocated pgnoMove. If required (i.e. if it was not allocated
6694 ** by extending the file), the current page at position pgnoMove
6695 ** is already journaled.
6696 */
danielk1977003ba062004-11-04 02:57:33 +00006697 u8 eType;
6698 Pgno iPtrPage;
6699
6700 releasePage(pPageMove);
danielk1977f35843b2007-04-07 15:03:17 +00006701
6702 /* Move the page currently at pgnoRoot to pgnoMove. */
drh16a9b832007-05-05 18:39:25 +00006703 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006704 if( rc!=SQLITE_OK ){
6705 return rc;
6706 }
6707 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drh27731d72009-06-22 12:05:10 +00006708 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
6709 rc = SQLITE_CORRUPT_BKPT;
6710 }
6711 if( rc!=SQLITE_OK ){
danielk1977003ba062004-11-04 02:57:33 +00006712 releasePage(pRoot);
6713 return rc;
6714 }
drhccae6022005-02-26 17:31:26 +00006715 assert( eType!=PTRMAP_ROOTPAGE );
6716 assert( eType!=PTRMAP_FREEPAGE );
danielk19774c999992008-07-16 18:17:55 +00006717 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
danielk1977003ba062004-11-04 02:57:33 +00006718 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00006719
6720 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00006721 if( rc!=SQLITE_OK ){
6722 return rc;
6723 }
drh16a9b832007-05-05 18:39:25 +00006724 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006725 if( rc!=SQLITE_OK ){
6726 return rc;
6727 }
danielk19773b8a05f2007-03-19 17:44:26 +00006728 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00006729 if( rc!=SQLITE_OK ){
6730 releasePage(pRoot);
6731 return rc;
6732 }
6733 }else{
6734 pRoot = pPageMove;
6735 }
6736
danielk197742741be2005-01-08 12:42:39 +00006737 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00006738 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
6739 if( rc ){
6740 releasePage(pRoot);
6741 return rc;
6742 }
danielk1977aef0bf62005-12-30 16:28:01 +00006743 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00006744 if( rc ){
6745 releasePage(pRoot);
6746 return rc;
6747 }
danielk197742741be2005-01-08 12:42:39 +00006748
danielk1977003ba062004-11-04 02:57:33 +00006749 }else{
drh4f0c5872007-03-26 22:05:01 +00006750 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00006751 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00006752 }
6753#endif
danielk19773b8a05f2007-03-19 17:44:26 +00006754 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhde647132004-05-07 17:57:49 +00006755 zeroPage(pRoot, flags | PTF_LEAF);
danielk19773b8a05f2007-03-19 17:44:26 +00006756 sqlite3PagerUnref(pRoot->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00006757 *piTable = (int)pgnoRoot;
6758 return SQLITE_OK;
6759}
drhd677b3d2007-08-20 22:48:41 +00006760int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
6761 int rc;
6762 sqlite3BtreeEnter(p);
6763 rc = btreeCreateTable(p, piTable, flags);
6764 sqlite3BtreeLeave(p);
6765 return rc;
6766}
drh8b2f49b2001-06-08 00:21:52 +00006767
6768/*
6769** Erase the given database page and all its children. Return
6770** the page to the freelist.
6771*/
drh4b70f112004-05-02 21:12:19 +00006772static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00006773 BtShared *pBt, /* The BTree that contains the table */
drh4b70f112004-05-02 21:12:19 +00006774 Pgno pgno, /* Page number to clear */
danielk1977c7af4842008-10-27 13:59:33 +00006775 int freePageFlag, /* Deallocate page if true */
6776 int *pnChange
drh4b70f112004-05-02 21:12:19 +00006777){
danielk19776b456a22005-03-21 04:04:02 +00006778 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00006779 int rc;
drh4b70f112004-05-02 21:12:19 +00006780 unsigned char *pCell;
6781 int i;
drh8b2f49b2001-06-08 00:21:52 +00006782
drh1fee73e2007-08-29 04:00:57 +00006783 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197789d40042008-11-17 14:20:56 +00006784 if( pgno>pagerPagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00006785 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00006786 }
6787
danielk197771d5d2c2008-09-29 11:49:47 +00006788 rc = getAndInitPage(pBt, pgno, &pPage);
danielk19776b456a22005-03-21 04:04:02 +00006789 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00006790 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00006791 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00006792 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00006793 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00006794 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006795 }
drh4b70f112004-05-02 21:12:19 +00006796 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00006797 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006798 }
drha34b6762004-05-07 13:30:42 +00006799 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00006800 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00006801 if( rc ) goto cleardatabasepage_out;
danielk1977c7af4842008-10-27 13:59:33 +00006802 }else if( pnChange ){
6803 assert( pPage->intKey );
6804 *pnChange += pPage->nCell;
drh2aa679f2001-06-25 02:11:07 +00006805 }
6806 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00006807 rc = freePage(pPage);
danielk19773b8a05f2007-03-19 17:44:26 +00006808 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
drh3a4c1412004-05-09 20:40:11 +00006809 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00006810 }
danielk19776b456a22005-03-21 04:04:02 +00006811
6812cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00006813 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00006814 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006815}
6816
6817/*
drhab01f612004-05-22 02:55:23 +00006818** Delete all information from a single table in the database. iTable is
6819** the page number of the root of the table. After this routine returns,
6820** the root page is empty, but still exists.
6821**
6822** This routine will fail with SQLITE_LOCKED if there are any open
6823** read cursors on the table. Open write cursors are moved to the
6824** root of the table.
danielk1977c7af4842008-10-27 13:59:33 +00006825**
6826** If pnChange is not NULL, then table iTable must be an intkey table. The
6827** integer value pointed to by pnChange is incremented by the number of
6828** entries in the table.
drh8b2f49b2001-06-08 00:21:52 +00006829*/
danielk1977c7af4842008-10-27 13:59:33 +00006830int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
drh8b2f49b2001-06-08 00:21:52 +00006831 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00006832 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00006833 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00006834 assert( p->inTrans==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +00006835
6836 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
6837 ** is the root of a table b-tree - if it is not, the following call is
6838 ** a no-op). */
6839 invalidateIncrblobCursors(p, iTable, 0, 1);
6840
6841 if( SQLITE_OK==(rc = saveAllCursors(pBt, (Pgno)iTable, 0)) ){
danielk197762c14b32008-11-19 09:05:26 +00006842 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
drh8b2f49b2001-06-08 00:21:52 +00006843 }
drhd677b3d2007-08-20 22:48:41 +00006844 sqlite3BtreeLeave(p);
6845 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006846}
6847
6848/*
6849** Erase all information in a table and add the root of the table to
6850** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00006851** page 1) is never added to the freelist.
6852**
6853** This routine will fail with SQLITE_LOCKED if there are any open
6854** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00006855**
6856** If AUTOVACUUM is enabled and the page at iTable is not the last
6857** root page in the database file, then the last root page
6858** in the database file is moved into the slot formerly occupied by
6859** iTable and that last slot formerly occupied by the last root page
6860** is added to the freelist instead of iTable. In this say, all
6861** root pages are kept at the beginning of the database file, which
6862** is necessary for AUTOVACUUM to work right. *piMoved is set to the
6863** page number that used to be the last root page in the file before
6864** the move. If no page gets moved, *piMoved is set to 0.
6865** The last root page is recorded in meta[3] and the value of
6866** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00006867*/
danielk197789d40042008-11-17 14:20:56 +00006868static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00006869 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00006870 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00006871 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00006872
drh1fee73e2007-08-29 04:00:57 +00006873 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00006874 assert( p->inTrans==TRANS_WRITE );
danielk1977a0bf2652004-11-04 14:30:04 +00006875
danielk1977e6efa742004-11-10 11:55:10 +00006876 /* It is illegal to drop a table if any cursors are open on the
6877 ** database. This is because in auto-vacuum mode the backend may
6878 ** need to move another root-page to fill a gap left by the deleted
6879 ** root page. If an open cursor was using this page a problem would
6880 ** occur.
6881 */
6882 if( pBt->pCursor ){
danielk1977404ca072009-03-16 13:19:36 +00006883 sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
6884 return SQLITE_LOCKED_SHAREDCACHE;
drh5df72a52002-06-06 23:16:05 +00006885 }
danielk1977a0bf2652004-11-04 14:30:04 +00006886
drh16a9b832007-05-05 18:39:25 +00006887 rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00006888 if( rc ) return rc;
danielk1977c7af4842008-10-27 13:59:33 +00006889 rc = sqlite3BtreeClearTable(p, iTable, 0);
danielk19776b456a22005-03-21 04:04:02 +00006890 if( rc ){
6891 releasePage(pPage);
6892 return rc;
6893 }
danielk1977a0bf2652004-11-04 14:30:04 +00006894
drh205f48e2004-11-05 00:43:11 +00006895 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00006896
drh4b70f112004-05-02 21:12:19 +00006897 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00006898#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00006899 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00006900 releasePage(pPage);
6901#else
6902 if( pBt->autoVacuum ){
6903 Pgno maxRootPgno;
danielk19770d19f7a2009-06-03 11:25:07 +00006904 rc = sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006905 if( rc!=SQLITE_OK ){
6906 releasePage(pPage);
6907 return rc;
6908 }
6909
6910 if( iTable==maxRootPgno ){
6911 /* If the table being dropped is the table with the largest root-page
6912 ** number in the database, put the root page on the free list.
6913 */
6914 rc = freePage(pPage);
6915 releasePage(pPage);
6916 if( rc!=SQLITE_OK ){
6917 return rc;
6918 }
6919 }else{
6920 /* The table being dropped does not have the largest root-page
6921 ** number in the database. So move the page that does into the
6922 ** gap left by the deleted root-page.
6923 */
6924 MemPage *pMove;
6925 releasePage(pPage);
drh16a9b832007-05-05 18:39:25 +00006926 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006927 if( rc!=SQLITE_OK ){
6928 return rc;
6929 }
danielk19774c999992008-07-16 18:17:55 +00006930 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006931 releasePage(pMove);
6932 if( rc!=SQLITE_OK ){
6933 return rc;
6934 }
drh16a9b832007-05-05 18:39:25 +00006935 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006936 if( rc!=SQLITE_OK ){
6937 return rc;
6938 }
6939 rc = freePage(pMove);
6940 releasePage(pMove);
6941 if( rc!=SQLITE_OK ){
6942 return rc;
6943 }
6944 *piMoved = maxRootPgno;
6945 }
6946
danielk1977599fcba2004-11-08 07:13:13 +00006947 /* Set the new 'max-root-page' value in the database header. This
6948 ** is the old value less one, less one more if that happens to
6949 ** be a root-page number, less one again if that is the
6950 ** PENDING_BYTE_PAGE.
6951 */
danielk197787a6e732004-11-05 12:58:25 +00006952 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00006953 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
6954 maxRootPgno--;
6955 }
danielk1977266664d2006-02-10 08:24:21 +00006956 if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00006957 maxRootPgno--;
6958 }
danielk1977599fcba2004-11-08 07:13:13 +00006959 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
6960
danielk1977aef0bf62005-12-30 16:28:01 +00006961 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006962 }else{
6963 rc = freePage(pPage);
6964 releasePage(pPage);
6965 }
6966#endif
drh2aa679f2001-06-25 02:11:07 +00006967 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00006968 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00006969 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00006970 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00006971 }
drh8b2f49b2001-06-08 00:21:52 +00006972 return rc;
6973}
drhd677b3d2007-08-20 22:48:41 +00006974int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
6975 int rc;
6976 sqlite3BtreeEnter(p);
6977 rc = btreeDropTable(p, iTable, piMoved);
6978 sqlite3BtreeLeave(p);
6979 return rc;
6980}
drh8b2f49b2001-06-08 00:21:52 +00006981
drh001bbcb2003-03-19 03:14:00 +00006982
drh8b2f49b2001-06-08 00:21:52 +00006983/*
drh23e11ca2004-05-04 17:27:28 +00006984** Read the meta-information out of a database file. Meta[0]
6985** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00006986** through meta[15] are available for use by higher layers. Meta[0]
6987** is read-only, the others are read/write.
6988**
6989** The schema layer numbers meta values differently. At the schema
6990** layer (and the SetCookie and ReadCookie opcodes) the number of
6991** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00006992*/
danielk1977aef0bf62005-12-30 16:28:01 +00006993int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
drh1bd10f82008-12-10 21:19:56 +00006994 DbPage *pDbPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00006995 int rc;
drh4b70f112004-05-02 21:12:19 +00006996 unsigned char *pP1;
danielk1977aef0bf62005-12-30 16:28:01 +00006997 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006998
drhd677b3d2007-08-20 22:48:41 +00006999 sqlite3BtreeEnter(p);
7000
danielk1977da184232006-01-05 11:34:32 +00007001 /* Reading a meta-data value requires a read-lock on page 1 (and hence
7002 ** the sqlite_master table. We grab this lock regardless of whether or
7003 ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page
drhc25eabe2009-02-24 18:57:31 +00007004 ** 1 is treated as a special case by querySharedCacheTableLock()
7005 ** and setSharedCacheTableLock()).
danielk1977da184232006-01-05 11:34:32 +00007006 */
drhc25eabe2009-02-24 18:57:31 +00007007 rc = querySharedCacheTableLock(p, 1, READ_LOCK);
danielk1977da184232006-01-05 11:34:32 +00007008 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00007009 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00007010 return rc;
7011 }
7012
drh23e11ca2004-05-04 17:27:28 +00007013 assert( idx>=0 && idx<=15 );
danielk1977d9f6c532008-09-19 16:39:38 +00007014 if( pBt->pPage1 ){
7015 /* The b-tree is already holding a reference to page 1 of the database
7016 ** file. In this case the required meta-data value can be read directly
7017 ** from the page data of this reference. This is slightly faster than
7018 ** requesting a new reference from the pager layer.
7019 */
7020 pP1 = (unsigned char *)pBt->pPage1->aData;
7021 }else{
7022 /* The b-tree does not have a reference to page 1 of the database file.
7023 ** Obtain one from the pager layer.
7024 */
danielk1977ea897302008-09-19 15:10:58 +00007025 rc = sqlite3PagerGet(pBt->pPager, 1, &pDbPage);
7026 if( rc ){
7027 sqlite3BtreeLeave(p);
7028 return rc;
7029 }
7030 pP1 = (unsigned char *)sqlite3PagerGetData(pDbPage);
drhd677b3d2007-08-20 22:48:41 +00007031 }
drh23e11ca2004-05-04 17:27:28 +00007032 *pMeta = get4byte(&pP1[36 + idx*4]);
danielk1977ea897302008-09-19 15:10:58 +00007033
danielk1977d9f6c532008-09-19 16:39:38 +00007034 /* If the b-tree is not holding a reference to page 1, then one was
7035 ** requested from the pager layer in the above block. Release it now.
7036 */
danielk1977ea897302008-09-19 15:10:58 +00007037 if( !pBt->pPage1 ){
7038 sqlite3PagerUnref(pDbPage);
7039 }
drhae157872004-08-14 19:20:09 +00007040
danielk1977599fcba2004-11-08 07:13:13 +00007041 /* If autovacuumed is disabled in this build but we are trying to
7042 ** access an autovacuumed database, then make the database readonly.
7043 */
danielk1977003ba062004-11-04 02:57:33 +00007044#ifdef SQLITE_OMIT_AUTOVACUUM
danielk19770d19f7a2009-06-03 11:25:07 +00007045 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00007046#endif
drhae157872004-08-14 19:20:09 +00007047
danielk1977fa542f12009-04-02 18:28:08 +00007048 /* If there is currently an open transaction, grab a read-lock
7049 ** on page 1 of the database file. This is done to make sure that
7050 ** no other connection can modify the meta value just read from
7051 ** the database until the transaction is concluded.
7052 */
7053 if( p->inTrans>0 ){
7054 rc = setSharedCacheTableLock(p, 1, READ_LOCK);
7055 }
drhd677b3d2007-08-20 22:48:41 +00007056 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00007057 return rc;
drh8b2f49b2001-06-08 00:21:52 +00007058}
7059
7060/*
drh23e11ca2004-05-04 17:27:28 +00007061** Write meta-information back into the database. Meta[0] is
7062** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00007063*/
danielk1977aef0bf62005-12-30 16:28:01 +00007064int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
7065 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00007066 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00007067 int rc;
drh23e11ca2004-05-04 17:27:28 +00007068 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00007069 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00007070 assert( p->inTrans==TRANS_WRITE );
7071 assert( pBt->pPage1!=0 );
7072 pP1 = pBt->pPage1->aData;
7073 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
7074 if( rc==SQLITE_OK ){
7075 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +00007076#ifndef SQLITE_OMIT_AUTOVACUUM
danielk19770d19f7a2009-06-03 11:25:07 +00007077 if( idx==BTREE_INCR_VACUUM ){
drh64022502009-01-09 14:11:04 +00007078 assert( pBt->autoVacuum || iMeta==0 );
7079 assert( iMeta==0 || iMeta==1 );
7080 pBt->incrVacuum = (u8)iMeta;
drhd677b3d2007-08-20 22:48:41 +00007081 }
drh64022502009-01-09 14:11:04 +00007082#endif
drh5df72a52002-06-06 23:16:05 +00007083 }
drhd677b3d2007-08-20 22:48:41 +00007084 sqlite3BtreeLeave(p);
7085 return rc;
drh8b2f49b2001-06-08 00:21:52 +00007086}
drh8c42ca92001-06-22 19:15:00 +00007087
drhf328bc82004-05-10 23:29:49 +00007088/*
7089** Return the flag byte at the beginning of the page that the cursor
7090** is currently pointing to.
7091*/
7092int sqlite3BtreeFlags(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00007093 /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
drha3460582008-07-11 21:02:53 +00007094 ** restoreCursorPosition() here.
danielk1977da184232006-01-05 11:34:32 +00007095 */
danielk1977e448dc42008-01-02 11:50:51 +00007096 MemPage *pPage;
drha3460582008-07-11 21:02:53 +00007097 restoreCursorPosition(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00007098 pPage = pCur->apPage[pCur->iPage];
drh1fee73e2007-08-29 04:00:57 +00007099 assert( cursorHoldsMutex(pCur) );
drh64022502009-01-09 14:11:04 +00007100 assert( pPage!=0 );
drhd0679ed2007-08-28 22:24:34 +00007101 assert( pPage->pBt==pCur->pBt );
drh64022502009-01-09 14:11:04 +00007102 return pPage->aData[pPage->hdrOffset];
drhf328bc82004-05-10 23:29:49 +00007103}
7104
danielk1977a5533162009-02-24 10:01:51 +00007105#ifndef SQLITE_OMIT_BTREECOUNT
7106/*
7107** The first argument, pCur, is a cursor opened on some b-tree. Count the
7108** number of entries in the b-tree and write the result to *pnEntry.
7109**
7110** SQLITE_OK is returned if the operation is successfully executed.
7111** Otherwise, if an error is encountered (i.e. an IO error or database
7112** corruption) an SQLite error code is returned.
7113*/
7114int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
7115 i64 nEntry = 0; /* Value to return in *pnEntry */
7116 int rc; /* Return code */
7117 rc = moveToRoot(pCur);
7118
7119 /* Unless an error occurs, the following loop runs one iteration for each
7120 ** page in the B-Tree structure (not including overflow pages).
7121 */
7122 while( rc==SQLITE_OK ){
7123 int iIdx; /* Index of child node in parent */
7124 MemPage *pPage; /* Current page of the b-tree */
7125
7126 /* If this is a leaf page or the tree is not an int-key tree, then
7127 ** this page contains countable entries. Increment the entry counter
7128 ** accordingly.
7129 */
7130 pPage = pCur->apPage[pCur->iPage];
7131 if( pPage->leaf || !pPage->intKey ){
7132 nEntry += pPage->nCell;
7133 }
7134
7135 /* pPage is a leaf node. This loop navigates the cursor so that it
7136 ** points to the first interior cell that it points to the parent of
7137 ** the next page in the tree that has not yet been visited. The
7138 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
7139 ** of the page, or to the number of cells in the page if the next page
7140 ** to visit is the right-child of its parent.
7141 **
7142 ** If all pages in the tree have been visited, return SQLITE_OK to the
7143 ** caller.
7144 */
7145 if( pPage->leaf ){
7146 do {
7147 if( pCur->iPage==0 ){
7148 /* All pages of the b-tree have been visited. Return successfully. */
7149 *pnEntry = nEntry;
7150 return SQLITE_OK;
7151 }
7152 sqlite3BtreeMoveToParent(pCur);
7153 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
7154
7155 pCur->aiIdx[pCur->iPage]++;
7156 pPage = pCur->apPage[pCur->iPage];
7157 }
7158
7159 /* Descend to the child node of the cell that the cursor currently
7160 ** points at. This is the right-child if (iIdx==pPage->nCell).
7161 */
7162 iIdx = pCur->aiIdx[pCur->iPage];
7163 if( iIdx==pPage->nCell ){
7164 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
7165 }else{
7166 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
7167 }
7168 }
7169
shanebe217792009-03-05 04:20:31 +00007170 /* An error has occurred. Return an error code. */
danielk1977a5533162009-02-24 10:01:51 +00007171 return rc;
7172}
7173#endif
drhdd793422001-06-28 01:54:48 +00007174
drhdd793422001-06-28 01:54:48 +00007175/*
drh5eddca62001-06-30 21:53:53 +00007176** Return the pager associated with a BTree. This routine is used for
7177** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00007178*/
danielk1977aef0bf62005-12-30 16:28:01 +00007179Pager *sqlite3BtreePager(Btree *p){
7180 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00007181}
drh5eddca62001-06-30 21:53:53 +00007182
drhb7f91642004-10-31 02:22:47 +00007183#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007184/*
7185** Append a message to the error message string.
7186*/
drh2e38c322004-09-03 18:38:44 +00007187static void checkAppendMsg(
7188 IntegrityCk *pCheck,
7189 char *zMsg1,
7190 const char *zFormat,
7191 ...
7192){
7193 va_list ap;
drh1dcdbc02007-01-27 02:24:54 +00007194 if( !pCheck->mxErr ) return;
7195 pCheck->mxErr--;
7196 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00007197 va_start(ap, zFormat);
drhf089aa42008-07-08 19:34:06 +00007198 if( pCheck->errMsg.nChar ){
7199 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
drh5eddca62001-06-30 21:53:53 +00007200 }
drhf089aa42008-07-08 19:34:06 +00007201 if( zMsg1 ){
7202 sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
7203 }
7204 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
7205 va_end(ap);
drhc890fec2008-08-01 20:10:08 +00007206 if( pCheck->errMsg.mallocFailed ){
7207 pCheck->mallocFailed = 1;
7208 }
drh5eddca62001-06-30 21:53:53 +00007209}
drhb7f91642004-10-31 02:22:47 +00007210#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00007211
drhb7f91642004-10-31 02:22:47 +00007212#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007213/*
7214** Add 1 to the reference count for page iPage. If this is the second
7215** reference to the page, add an error message to pCheck->zErrMsg.
7216** Return 1 if there are 2 ore more references to the page and 0 if
7217** if this is the first reference to the page.
7218**
7219** Also check that the page number is in bounds.
7220*/
danielk197789d40042008-11-17 14:20:56 +00007221static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00007222 if( iPage==0 ) return 1;
danielk197789d40042008-11-17 14:20:56 +00007223 if( iPage>pCheck->nPage ){
drh2e38c322004-09-03 18:38:44 +00007224 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00007225 return 1;
7226 }
7227 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00007228 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00007229 return 1;
7230 }
7231 return (pCheck->anRef[iPage]++)>1;
7232}
7233
danielk1977afcdd022004-10-31 16:25:42 +00007234#ifndef SQLITE_OMIT_AUTOVACUUM
7235/*
7236** Check that the entry in the pointer-map for page iChild maps to
7237** page iParent, pointer type ptrType. If not, append an error message
7238** to pCheck.
7239*/
7240static void checkPtrmap(
7241 IntegrityCk *pCheck, /* Integrity check context */
7242 Pgno iChild, /* Child page number */
7243 u8 eType, /* Expected pointer map type */
7244 Pgno iParent, /* Expected pointer map parent page number */
7245 char *zContext /* Context description (used for error msg) */
7246){
7247 int rc;
7248 u8 ePtrmapType;
7249 Pgno iPtrmapParent;
7250
7251 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
7252 if( rc!=SQLITE_OK ){
drhb56cd552009-05-01 13:16:54 +00007253 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
danielk1977afcdd022004-10-31 16:25:42 +00007254 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
7255 return;
7256 }
7257
7258 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
7259 checkAppendMsg(pCheck, zContext,
7260 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
7261 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
7262 }
7263}
7264#endif
7265
drh5eddca62001-06-30 21:53:53 +00007266/*
7267** Check the integrity of the freelist or of an overflow page list.
7268** Verify that the number of pages on the list is N.
7269*/
drh30e58752002-03-02 20:41:57 +00007270static void checkList(
7271 IntegrityCk *pCheck, /* Integrity checking context */
7272 int isFreeList, /* True for a freelist. False for overflow page list */
7273 int iPage, /* Page number for first page in the list */
7274 int N, /* Expected number of pages in the list */
7275 char *zContext /* Context for error messages */
7276){
7277 int i;
drh3a4c1412004-05-09 20:40:11 +00007278 int expected = N;
7279 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00007280 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00007281 DbPage *pOvflPage;
7282 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00007283 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00007284 checkAppendMsg(pCheck, zContext,
7285 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00007286 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00007287 break;
7288 }
7289 if( checkRef(pCheck, iPage, zContext) ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00007290 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
drh2e38c322004-09-03 18:38:44 +00007291 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00007292 break;
7293 }
danielk19773b8a05f2007-03-19 17:44:26 +00007294 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00007295 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00007296 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00007297#ifndef SQLITE_OMIT_AUTOVACUUM
7298 if( pCheck->pBt->autoVacuum ){
7299 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
7300 }
7301#endif
drh45b1fac2008-07-04 17:52:42 +00007302 if( n>pCheck->pBt->usableSize/4-2 ){
drh2e38c322004-09-03 18:38:44 +00007303 checkAppendMsg(pCheck, zContext,
7304 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00007305 N--;
7306 }else{
7307 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00007308 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00007309#ifndef SQLITE_OMIT_AUTOVACUUM
7310 if( pCheck->pBt->autoVacuum ){
7311 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
7312 }
7313#endif
7314 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00007315 }
7316 N -= n;
drh30e58752002-03-02 20:41:57 +00007317 }
drh30e58752002-03-02 20:41:57 +00007318 }
danielk1977afcdd022004-10-31 16:25:42 +00007319#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00007320 else{
7321 /* If this database supports auto-vacuum and iPage is not the last
7322 ** page in this overflow list, check that the pointer-map entry for
7323 ** the following page matches iPage.
7324 */
7325 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00007326 i = get4byte(pOvflData);
danielk1977687566d2004-11-02 12:56:41 +00007327 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
7328 }
danielk1977afcdd022004-10-31 16:25:42 +00007329 }
7330#endif
danielk19773b8a05f2007-03-19 17:44:26 +00007331 iPage = get4byte(pOvflData);
7332 sqlite3PagerUnref(pOvflPage);
drh5eddca62001-06-30 21:53:53 +00007333 }
7334}
drhb7f91642004-10-31 02:22:47 +00007335#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00007336
drhb7f91642004-10-31 02:22:47 +00007337#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007338/*
7339** Do various sanity checks on a single page of a tree. Return
7340** the tree depth. Root pages return 0. Parents of root pages
7341** return 1, and so forth.
7342**
7343** These checks are done:
7344**
7345** 1. Make sure that cells and freeblocks do not overlap
7346** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00007347** NO 2. Make sure cell keys are in order.
7348** NO 3. Make sure no key is less than or equal to zLowerBound.
7349** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00007350** 5. Check the integrity of overflow pages.
7351** 6. Recursively call checkTreePage on all children.
7352** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00007353** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00007354** the root of the tree.
7355*/
7356static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00007357 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00007358 int iPage, /* Page number of the page to check */
drh74161702006-02-24 02:53:49 +00007359 char *zParentContext /* Parent context */
drh5eddca62001-06-30 21:53:53 +00007360){
7361 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00007362 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00007363 int hdr, cellStart;
7364 int nCell;
drhda200cc2004-05-09 11:51:38 +00007365 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00007366 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00007367 int usableSize;
drh5eddca62001-06-30 21:53:53 +00007368 char zContext[100];
shane0af3f892008-11-12 04:55:34 +00007369 char *hit = 0;
drh5eddca62001-06-30 21:53:53 +00007370
drh5bb3eb92007-05-04 13:15:55 +00007371 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
danielk1977ef73ee92004-11-06 12:26:07 +00007372
drh5eddca62001-06-30 21:53:53 +00007373 /* Check that the page exists
7374 */
drhd9cb6ac2005-10-20 07:28:17 +00007375 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00007376 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00007377 if( iPage==0 ) return 0;
7378 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh16a9b832007-05-05 18:39:25 +00007379 if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drhb56cd552009-05-01 13:16:54 +00007380 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
drh2e38c322004-09-03 18:38:44 +00007381 checkAppendMsg(pCheck, zContext,
7382 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00007383 return 0;
7384 }
danielk197771d5d2c2008-09-29 11:49:47 +00007385 if( (rc = sqlite3BtreeInitPage(pPage))!=0 ){
drh64022502009-01-09 14:11:04 +00007386 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
drh16a9b832007-05-05 18:39:25 +00007387 checkAppendMsg(pCheck, zContext,
7388 "sqlite3BtreeInitPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00007389 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00007390 return 0;
7391 }
7392
7393 /* Check out all the cells.
7394 */
7395 depth = 0;
drh1dcdbc02007-01-27 02:24:54 +00007396 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
drh6f11bef2004-05-13 01:12:56 +00007397 u8 *pCell;
danielk197789d40042008-11-17 14:20:56 +00007398 u32 sz;
drh6f11bef2004-05-13 01:12:56 +00007399 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00007400
7401 /* Check payload overflow pages
7402 */
drh5bb3eb92007-05-04 13:15:55 +00007403 sqlite3_snprintf(sizeof(zContext), zContext,
7404 "On tree page %d cell %d: ", iPage, i);
danielk19771cc5ed82007-05-16 17:28:43 +00007405 pCell = findCell(pPage,i);
drh16a9b832007-05-05 18:39:25 +00007406 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00007407 sz = info.nData;
drhf49661a2008-12-10 16:45:50 +00007408 if( !pPage->intKey ) sz += (int)info.nKey;
drh72365832007-03-06 15:53:44 +00007409 assert( sz==info.nPayload );
danielk19775be31f52009-03-30 13:53:43 +00007410 if( (sz>info.nLocal)
7411 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
7412 ){
drhb6f41482004-05-14 01:58:11 +00007413 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00007414 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
7415#ifndef SQLITE_OMIT_AUTOVACUUM
7416 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00007417 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00007418 }
7419#endif
7420 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00007421 }
7422
7423 /* Check sanity of left child page.
7424 */
drhda200cc2004-05-09 11:51:38 +00007425 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00007426 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00007427#ifndef SQLITE_OMIT_AUTOVACUUM
7428 if( pBt->autoVacuum ){
7429 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
7430 }
7431#endif
danielk197762c14b32008-11-19 09:05:26 +00007432 d2 = checkTreePage(pCheck, pgno, zContext);
drhda200cc2004-05-09 11:51:38 +00007433 if( i>0 && d2!=depth ){
7434 checkAppendMsg(pCheck, zContext, "Child page depth differs");
7435 }
7436 depth = d2;
drh5eddca62001-06-30 21:53:53 +00007437 }
drh5eddca62001-06-30 21:53:53 +00007438 }
drhda200cc2004-05-09 11:51:38 +00007439 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00007440 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh5bb3eb92007-05-04 13:15:55 +00007441 sqlite3_snprintf(sizeof(zContext), zContext,
7442 "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00007443#ifndef SQLITE_OMIT_AUTOVACUUM
7444 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00007445 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00007446 }
7447#endif
danielk197762c14b32008-11-19 09:05:26 +00007448 checkTreePage(pCheck, pgno, zContext);
drhda200cc2004-05-09 11:51:38 +00007449 }
drh5eddca62001-06-30 21:53:53 +00007450
7451 /* Check for complete coverage of the page
7452 */
drhda200cc2004-05-09 11:51:38 +00007453 data = pPage->aData;
7454 hdr = pPage->hdrOffset;
drhf7141992008-06-19 00:16:08 +00007455 hit = sqlite3PageMalloc( pBt->pageSize );
drhc890fec2008-08-01 20:10:08 +00007456 if( hit==0 ){
7457 pCheck->mallocFailed = 1;
7458 }else{
shane5780ebd2008-11-11 17:36:30 +00007459 u16 contentOffset = get2byte(&data[hdr+5]);
7460 if (contentOffset > usableSize) {
7461 checkAppendMsg(pCheck, 0,
7462 "Corruption detected in header on page %d",iPage,0);
shane0af3f892008-11-12 04:55:34 +00007463 goto check_page_abort;
shane5780ebd2008-11-11 17:36:30 +00007464 }
7465 memset(hit+contentOffset, 0, usableSize-contentOffset);
7466 memset(hit, 1, contentOffset);
drh2e38c322004-09-03 18:38:44 +00007467 nCell = get2byte(&data[hdr+3]);
7468 cellStart = hdr + 12 - 4*pPage->leaf;
7469 for(i=0; i<nCell; i++){
7470 int pc = get2byte(&data[cellStart+i*2]);
danielk1977daca5432008-08-25 11:57:16 +00007471 u16 size = 1024;
drh2e38c322004-09-03 18:38:44 +00007472 int j;
danielk1977daca5432008-08-25 11:57:16 +00007473 if( pc<=usableSize ){
7474 size = cellSizePtr(pPage, &data[pc]);
7475 }
danielk19777701e812005-01-10 12:59:51 +00007476 if( (pc+size-1)>=usableSize || pc<0 ){
7477 checkAppendMsg(pCheck, 0,
7478 "Corruption detected in cell %d on page %d",i,iPage,0);
7479 }else{
7480 for(j=pc+size-1; j>=pc; j--) hit[j]++;
7481 }
drh2e38c322004-09-03 18:38:44 +00007482 }
7483 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
7484 cnt++){
7485 int size = get2byte(&data[i+2]);
7486 int j;
danielk19777701e812005-01-10 12:59:51 +00007487 if( (i+size-1)>=usableSize || i<0 ){
7488 checkAppendMsg(pCheck, 0,
7489 "Corruption detected in cell %d on page %d",i,iPage,0);
7490 }else{
7491 for(j=i+size-1; j>=i; j--) hit[j]++;
7492 }
drh2e38c322004-09-03 18:38:44 +00007493 i = get2byte(&data[i]);
7494 }
7495 for(i=cnt=0; i<usableSize; i++){
7496 if( hit[i]==0 ){
7497 cnt++;
7498 }else if( hit[i]>1 ){
7499 checkAppendMsg(pCheck, 0,
7500 "Multiple uses for byte %d of page %d", i, iPage);
7501 break;
7502 }
7503 }
7504 if( cnt!=data[hdr+7] ){
7505 checkAppendMsg(pCheck, 0,
7506 "Fragmented space is %d byte reported as %d on page %d",
7507 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00007508 }
7509 }
shane0af3f892008-11-12 04:55:34 +00007510check_page_abort:
7511 if (hit) sqlite3PageFree(hit);
drh6019e162001-07-02 17:51:45 +00007512
drh4b70f112004-05-02 21:12:19 +00007513 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00007514 return depth+1;
drh5eddca62001-06-30 21:53:53 +00007515}
drhb7f91642004-10-31 02:22:47 +00007516#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00007517
drhb7f91642004-10-31 02:22:47 +00007518#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007519/*
7520** This routine does a complete check of the given BTree file. aRoot[] is
7521** an array of pages numbers were each page number is the root page of
7522** a table. nRoot is the number of entries in aRoot.
7523**
drhc890fec2008-08-01 20:10:08 +00007524** Write the number of error seen in *pnErr. Except for some memory
drhe43ba702008-12-05 22:40:08 +00007525** allocation errors, an error message held in memory obtained from
drhc890fec2008-08-01 20:10:08 +00007526** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
drhe43ba702008-12-05 22:40:08 +00007527** returned. If a memory allocation error occurs, NULL is returned.
drh5eddca62001-06-30 21:53:53 +00007528*/
drh1dcdbc02007-01-27 02:24:54 +00007529char *sqlite3BtreeIntegrityCheck(
7530 Btree *p, /* The btree to be checked */
7531 int *aRoot, /* An array of root pages numbers for individual trees */
7532 int nRoot, /* Number of entries in aRoot[] */
7533 int mxErr, /* Stop reporting errors after this many */
7534 int *pnErr /* Write number of errors seen to this variable */
7535){
danielk197789d40042008-11-17 14:20:56 +00007536 Pgno i;
drh5eddca62001-06-30 21:53:53 +00007537 int nRef;
drhaaab5722002-02-19 13:39:21 +00007538 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00007539 BtShared *pBt = p->pBt;
drhf089aa42008-07-08 19:34:06 +00007540 char zErr[100];
drh5eddca62001-06-30 21:53:53 +00007541
drhd677b3d2007-08-20 22:48:41 +00007542 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00007543 nRef = sqlite3PagerRefcount(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00007544 if( lockBtreeWithRetry(p)!=SQLITE_OK ){
drhc890fec2008-08-01 20:10:08 +00007545 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00007546 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00007547 return sqlite3DbStrDup(0, "cannot acquire a read lock on the database");
drhefc251d2001-07-01 22:12:01 +00007548 }
drh5eddca62001-06-30 21:53:53 +00007549 sCheck.pBt = pBt;
7550 sCheck.pPager = pBt->pPager;
danielk197789d40042008-11-17 14:20:56 +00007551 sCheck.nPage = pagerPagecount(sCheck.pBt);
drh1dcdbc02007-01-27 02:24:54 +00007552 sCheck.mxErr = mxErr;
7553 sCheck.nErr = 0;
drhc890fec2008-08-01 20:10:08 +00007554 sCheck.mallocFailed = 0;
drh1dcdbc02007-01-27 02:24:54 +00007555 *pnErr = 0;
drh0de8c112002-07-06 16:32:14 +00007556 if( sCheck.nPage==0 ){
7557 unlockBtreeIfUnused(pBt);
drhd677b3d2007-08-20 22:48:41 +00007558 sqlite3BtreeLeave(p);
drh0de8c112002-07-06 16:32:14 +00007559 return 0;
7560 }
drhe5ae5732008-06-15 02:51:47 +00007561 sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00007562 if( !sCheck.anRef ){
7563 unlockBtreeIfUnused(pBt);
drh1dcdbc02007-01-27 02:24:54 +00007564 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00007565 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00007566 return 0;
danielk1977ac245ec2005-01-14 13:50:11 +00007567 }
drhda200cc2004-05-09 11:51:38 +00007568 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00007569 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00007570 if( i<=sCheck.nPage ){
7571 sCheck.anRef[i] = 1;
7572 }
drhf089aa42008-07-08 19:34:06 +00007573 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
drh5eddca62001-06-30 21:53:53 +00007574
7575 /* Check the integrity of the freelist
7576 */
drha34b6762004-05-07 13:30:42 +00007577 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
7578 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00007579
7580 /* Check all the tables.
7581 */
danielk197789d40042008-11-17 14:20:56 +00007582 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
drh4ff6dfa2002-03-03 23:06:00 +00007583 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00007584#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00007585 if( pBt->autoVacuum && aRoot[i]>1 ){
7586 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
7587 }
7588#endif
danielk197762c14b32008-11-19 09:05:26 +00007589 checkTreePage(&sCheck, aRoot[i], "List of tree roots: ");
drh5eddca62001-06-30 21:53:53 +00007590 }
7591
7592 /* Make sure every page in the file is referenced
7593 */
drh1dcdbc02007-01-27 02:24:54 +00007594 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00007595#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00007596 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00007597 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00007598 }
danielk1977afcdd022004-10-31 16:25:42 +00007599#else
7600 /* If the database supports auto-vacuum, make sure no tables contain
7601 ** references to pointer-map pages.
7602 */
7603 if( sCheck.anRef[i]==0 &&
danielk1977266664d2006-02-10 08:24:21 +00007604 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00007605 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
7606 }
7607 if( sCheck.anRef[i]!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00007608 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00007609 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
7610 }
7611#endif
drh5eddca62001-06-30 21:53:53 +00007612 }
7613
drh64022502009-01-09 14:11:04 +00007614 /* Make sure this analysis did not leave any unref() pages.
7615 ** This is an internal consistency check; an integrity check
7616 ** of the integrity check.
drh5eddca62001-06-30 21:53:53 +00007617 */
drh5e00f6c2001-09-13 13:46:56 +00007618 unlockBtreeIfUnused(pBt);
drh64022502009-01-09 14:11:04 +00007619 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
drh2e38c322004-09-03 18:38:44 +00007620 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00007621 "Outstanding page count goes from %d to %d during this analysis",
danielk19773b8a05f2007-03-19 17:44:26 +00007622 nRef, sqlite3PagerRefcount(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00007623 );
drh5eddca62001-06-30 21:53:53 +00007624 }
7625
7626 /* Clean up and report errors.
7627 */
drhd677b3d2007-08-20 22:48:41 +00007628 sqlite3BtreeLeave(p);
drh17435752007-08-16 04:30:38 +00007629 sqlite3_free(sCheck.anRef);
drhc890fec2008-08-01 20:10:08 +00007630 if( sCheck.mallocFailed ){
7631 sqlite3StrAccumReset(&sCheck.errMsg);
7632 *pnErr = sCheck.nErr+1;
7633 return 0;
7634 }
drh1dcdbc02007-01-27 02:24:54 +00007635 *pnErr = sCheck.nErr;
drhf089aa42008-07-08 19:34:06 +00007636 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
7637 return sqlite3StrAccumFinish(&sCheck.errMsg);
drh5eddca62001-06-30 21:53:53 +00007638}
drhb7f91642004-10-31 02:22:47 +00007639#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00007640
drh73509ee2003-04-06 20:44:45 +00007641/*
7642** Return the full pathname of the underlying database file.
drhd0679ed2007-08-28 22:24:34 +00007643**
7644** The pager filename is invariant as long as the pager is
7645** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +00007646*/
danielk1977aef0bf62005-12-30 16:28:01 +00007647const char *sqlite3BtreeGetFilename(Btree *p){
7648 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007649 return sqlite3PagerFilename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00007650}
7651
7652/*
danielk19775865e3d2004-06-14 06:03:57 +00007653** Return the pathname of the journal file for this database. The return
7654** value of this routine is the same regardless of whether the journal file
7655** has been created or not.
drhd0679ed2007-08-28 22:24:34 +00007656**
7657** The pager journal filename is invariant as long as the pager is
7658** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00007659*/
danielk1977aef0bf62005-12-30 16:28:01 +00007660const char *sqlite3BtreeGetJournalname(Btree *p){
7661 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007662 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00007663}
7664
danielk19771d850a72004-05-31 08:26:49 +00007665/*
7666** Return non-zero if a transaction is active.
7667*/
danielk1977aef0bf62005-12-30 16:28:01 +00007668int sqlite3BtreeIsInTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00007669 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00007670 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00007671}
7672
7673/*
danielk19772372c2b2006-06-27 16:34:56 +00007674** Return non-zero if a read (or write) transaction is active.
7675*/
7676int sqlite3BtreeIsInReadTrans(Btree *p){
drh64022502009-01-09 14:11:04 +00007677 assert( p );
drhe5fe6902007-12-07 18:55:28 +00007678 assert( sqlite3_mutex_held(p->db->mutex) );
drh64022502009-01-09 14:11:04 +00007679 return p->inTrans!=TRANS_NONE;
danielk19772372c2b2006-06-27 16:34:56 +00007680}
7681
danielk197704103022009-02-03 16:51:24 +00007682int sqlite3BtreeIsInBackup(Btree *p){
7683 assert( p );
7684 assert( sqlite3_mutex_held(p->db->mutex) );
7685 return p->nBackup!=0;
7686}
7687
danielk19772372c2b2006-06-27 16:34:56 +00007688/*
danielk1977da184232006-01-05 11:34:32 +00007689** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +00007690** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +00007691** purposes (for example, to store a high-level schema associated with
7692** the shared-btree). The btree layer manages reference counting issues.
7693**
7694** The first time this is called on a shared-btree, nBytes bytes of memory
7695** are allocated, zeroed, and returned to the caller. For each subsequent
7696** call the nBytes parameter is ignored and a pointer to the same blob
7697** of memory returned.
7698**
danielk1977171bfed2008-06-23 09:50:50 +00007699** If the nBytes parameter is 0 and the blob of memory has not yet been
7700** allocated, a null pointer is returned. If the blob has already been
7701** allocated, it is returned as normal.
7702**
danielk1977da184232006-01-05 11:34:32 +00007703** Just before the shared-btree is closed, the function passed as the
7704** xFree argument when the memory allocation was made is invoked on the
drh17435752007-08-16 04:30:38 +00007705** blob of allocated memory. This function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +00007706** on the memory, the btree layer does that.
7707*/
7708void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
7709 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +00007710 sqlite3BtreeEnter(p);
danielk1977171bfed2008-06-23 09:50:50 +00007711 if( !pBt->pSchema && nBytes ){
drh17435752007-08-16 04:30:38 +00007712 pBt->pSchema = sqlite3MallocZero(nBytes);
danielk1977da184232006-01-05 11:34:32 +00007713 pBt->xFreeSchema = xFree;
7714 }
drh27641702007-08-22 02:56:42 +00007715 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00007716 return pBt->pSchema;
7717}
7718
danielk1977c87d34d2006-01-06 13:00:28 +00007719/*
danielk1977404ca072009-03-16 13:19:36 +00007720** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
7721** btree as the argument handle holds an exclusive lock on the
7722** sqlite_master table. Otherwise SQLITE_OK.
danielk1977c87d34d2006-01-06 13:00:28 +00007723*/
7724int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +00007725 int rc;
drhe5fe6902007-12-07 18:55:28 +00007726 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +00007727 sqlite3BtreeEnter(p);
danielk1977404ca072009-03-16 13:19:36 +00007728 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
7729 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
drh27641702007-08-22 02:56:42 +00007730 sqlite3BtreeLeave(p);
7731 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +00007732}
7733
drha154dcd2006-03-22 22:10:07 +00007734
7735#ifndef SQLITE_OMIT_SHARED_CACHE
7736/*
7737** Obtain a lock on the table whose root page is iTab. The
7738** lock is a write lock if isWritelock is true or a read lock
7739** if it is false.
7740*/
danielk1977c00da102006-01-07 13:21:04 +00007741int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00007742 int rc = SQLITE_OK;
drh6a9ad3d2008-04-02 16:29:30 +00007743 if( p->sharable ){
7744 u8 lockType = READ_LOCK + isWriteLock;
7745 assert( READ_LOCK+1==WRITE_LOCK );
7746 assert( isWriteLock==0 || isWriteLock==1 );
7747 sqlite3BtreeEnter(p);
drhc25eabe2009-02-24 18:57:31 +00007748 rc = querySharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00007749 if( rc==SQLITE_OK ){
drhc25eabe2009-02-24 18:57:31 +00007750 rc = setSharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00007751 }
7752 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +00007753 }
7754 return rc;
7755}
drha154dcd2006-03-22 22:10:07 +00007756#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00007757
danielk1977b4e9af92007-05-01 17:49:49 +00007758#ifndef SQLITE_OMIT_INCRBLOB
7759/*
7760** Argument pCsr must be a cursor opened for writing on an
7761** INTKEY table currently pointing at a valid table entry.
7762** This function modifies the data stored as part of that entry.
7763** Only the data content may only be modified, it is not possible
7764** to change the length of the data stored.
7765*/
danielk1977dcbb5d32007-05-04 18:36:44 +00007766int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
drh1fee73e2007-08-29 04:00:57 +00007767 assert( cursorHoldsMutex(pCsr) );
drhe5fe6902007-12-07 18:55:28 +00007768 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
danielk197796d48e92009-06-29 06:00:37 +00007769 assert( pCsr->isIncrblobHandle );
danielk19773588ceb2008-06-10 17:30:26 +00007770
drha3460582008-07-11 21:02:53 +00007771 restoreCursorPosition(pCsr);
danielk19773588ceb2008-06-10 17:30:26 +00007772 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
7773 if( pCsr->eState!=CURSOR_VALID ){
7774 return SQLITE_ABORT;
danielk1977dcbb5d32007-05-04 18:36:44 +00007775 }
7776
danielk1977d04417962007-05-02 13:16:30 +00007777 /* Check some preconditions:
danielk1977dcbb5d32007-05-04 18:36:44 +00007778 ** (a) the cursor is open for writing,
7779 ** (b) there is no read-lock on the table being modified and
7780 ** (c) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00007781 */
danielk1977d04417962007-05-02 13:16:30 +00007782 if( !pCsr->wrFlag ){
danielk1977dcbb5d32007-05-04 18:36:44 +00007783 return SQLITE_READONLY;
danielk1977d04417962007-05-02 13:16:30 +00007784 }
danielk197796d48e92009-06-29 06:00:37 +00007785 assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
7786 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
7787 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
7788
danielk197771d5d2c2008-09-29 11:49:47 +00007789 if( pCsr->eState==CURSOR_INVALID || !pCsr->apPage[pCsr->iPage]->intKey ){
danielk1977d04417962007-05-02 13:16:30 +00007790 return SQLITE_ERROR;
danielk1977b4e9af92007-05-01 17:49:49 +00007791 }
7792
danielk19779f8d6402007-05-02 17:48:45 +00007793 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00007794}
danielk19772dec9702007-05-02 16:48:37 +00007795
7796/*
7797** Set a flag on this cursor to cache the locations of pages from the
danielk1977da107192007-05-04 08:32:13 +00007798** overflow list for the current row. This is used by cursors opened
7799** for incremental blob IO only.
7800**
7801** This function sets a flag only. The actual page location cache
7802** (stored in BtCursor.aOverflow[]) is allocated and used by function
7803** accessPayload() (the worker function for sqlite3BtreeData() and
7804** sqlite3BtreePutData()).
danielk19772dec9702007-05-02 16:48:37 +00007805*/
7806void sqlite3BtreeCacheOverflow(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00007807 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00007808 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00007809 assert(!pCur->isIncrblobHandle);
danielk19772dec9702007-05-02 16:48:37 +00007810 assert(!pCur->aOverflow);
danielk1977dcbb5d32007-05-04 18:36:44 +00007811 pCur->isIncrblobHandle = 1;
danielk19772dec9702007-05-02 16:48:37 +00007812}
danielk1977b4e9af92007-05-01 17:49:49 +00007813#endif