blob: 8b57837b28ccc38c36928fb05791e5ac50fd86be [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*************************************************************************
danielk1977602b4662009-07-02 07:47:33 +000012** $Id: btree.c,v 1.648 2009/07/02 07:47:33 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;
danielk1977602b4662009-07-02 07:47:33 +0000369 assert( pLock->iTable!=1 || pLock==&p->lock );
370 if( pLock->iTable!=1 ){
371 sqlite3_free(pLock);
372 }
danielk1977aef0bf62005-12-30 16:28:01 +0000373 }else{
374 ppIter = &pLock->pNext;
375 }
376 }
danielk1977641b0f42007-12-21 04:47:25 +0000377
danielk1977404ca072009-03-16 13:19:36 +0000378 assert( pBt->isPending==0 || pBt->pWriter );
379 if( pBt->pWriter==p ){
380 pBt->pWriter = 0;
381 pBt->isExclusive = 0;
382 pBt->isPending = 0;
383 }else if( pBt->nTransaction==2 ){
384 /* This function is called when connection p is concluding its
385 ** transaction. If there currently exists a writer, and p is not
386 ** that writer, then the number of locks held by connections other
387 ** than the writer must be about to drop to zero. In this case
388 ** set the isPending flag to 0.
389 **
390 ** If there is not currently a writer, then BtShared.isPending must
391 ** be zero already. So this next line is harmless in that case.
392 */
393 pBt->isPending = 0;
danielk1977641b0f42007-12-21 04:47:25 +0000394 }
danielk1977aef0bf62005-12-30 16:28:01 +0000395}
396#endif /* SQLITE_OMIT_SHARED_CACHE */
397
drh980b1a72006-08-16 16:42:48 +0000398static void releasePage(MemPage *pPage); /* Forward reference */
399
drh1fee73e2007-08-29 04:00:57 +0000400/*
401** Verify that the cursor holds a mutex on the BtShared
402*/
403#ifndef NDEBUG
404static int cursorHoldsMutex(BtCursor *p){
drhff0587c2007-08-29 17:43:19 +0000405 return sqlite3_mutex_held(p->pBt->mutex);
drh1fee73e2007-08-29 04:00:57 +0000406}
407#endif
408
409
danielk197792d4d7a2007-05-04 12:05:56 +0000410#ifndef SQLITE_OMIT_INCRBLOB
411/*
412** Invalidate the overflow page-list cache for cursor pCur, if any.
413*/
414static void invalidateOverflowCache(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000415 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000416 sqlite3_free(pCur->aOverflow);
danielk197792d4d7a2007-05-04 12:05:56 +0000417 pCur->aOverflow = 0;
418}
419
420/*
421** Invalidate the overflow page-list cache for all cursors opened
422** on the shared btree structure pBt.
423*/
424static void invalidateAllOverflowCache(BtShared *pBt){
425 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000426 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +0000427 for(p=pBt->pCursor; p; p=p->pNext){
428 invalidateOverflowCache(p);
429 }
430}
danielk197796d48e92009-06-29 06:00:37 +0000431
432/*
433** This function is called before modifying the contents of a table
434** b-tree to invalidate any incrblob cursors that are open on the
435** row or one of the rows being modified. Argument pgnoRoot is the
436** root-page of the table b-tree.
437**
438** If argument isClearTable is true, then the entire contents of the
439** table is about to be deleted. In this case invalidate all incrblob
440** cursors open on any row within the table with root-page pgnoRoot.
441**
442** Otherwise, if argument isClearTable is false, then the row with
443** rowid iRow is being replaced or deleted. In this case invalidate
444** only those incrblob cursors open on this specific row.
445*/
446static void invalidateIncrblobCursors(
447 Btree *pBtree, /* The database file to check */
448 Pgno pgnoRoot, /* Look for read cursors on this btree */
449 i64 iRow, /* The rowid that might be changing */
450 int isClearTable /* True if all rows are being deleted */
451){
452 BtCursor *p;
453 BtShared *pBt = pBtree->pBt;
454 assert( sqlite3BtreeHoldsMutex(pBtree) );
455 for(p=pBt->pCursor; p; p=p->pNext){
456 if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
457 p->eState = CURSOR_INVALID;
458 }
459 }
460}
461
danielk197792d4d7a2007-05-04 12:05:56 +0000462#else
463 #define invalidateOverflowCache(x)
464 #define invalidateAllOverflowCache(x)
danielk197796d48e92009-06-29 06:00:37 +0000465 #define invalidateIncrblobCursors(w,x,y,z)
danielk197792d4d7a2007-05-04 12:05:56 +0000466#endif
467
drh980b1a72006-08-16 16:42:48 +0000468/*
danielk1977bea2a942009-01-20 17:06:27 +0000469** Set bit pgno of the BtShared.pHasContent bitvec. This is called
470** when a page that previously contained data becomes a free-list leaf
471** page.
472**
473** The BtShared.pHasContent bitvec exists to work around an obscure
474** bug caused by the interaction of two useful IO optimizations surrounding
475** free-list leaf pages:
476**
477** 1) When all data is deleted from a page and the page becomes
478** a free-list leaf page, the page is not written to the database
479** (as free-list leaf pages contain no meaningful data). Sometimes
480** such a page is not even journalled (as it will not be modified,
481** why bother journalling it?).
482**
483** 2) When a free-list leaf page is reused, its content is not read
484** from the database or written to the journal file (why should it
485** be, if it is not at all meaningful?).
486**
487** By themselves, these optimizations work fine and provide a handy
488** performance boost to bulk delete or insert operations. However, if
489** a page is moved to the free-list and then reused within the same
490** transaction, a problem comes up. If the page is not journalled when
491** it is moved to the free-list and it is also not journalled when it
492** is extracted from the free-list and reused, then the original data
493** may be lost. In the event of a rollback, it may not be possible
494** to restore the database to its original configuration.
495**
496** The solution is the BtShared.pHasContent bitvec. Whenever a page is
497** moved to become a free-list leaf page, the corresponding bit is
498** set in the bitvec. Whenever a leaf page is extracted from the free-list,
499** optimization 2 above is ommitted if the corresponding bit is already
500** set in BtShared.pHasContent. The contents of the bitvec are cleared
501** at the end of every transaction.
502*/
503static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
504 int rc = SQLITE_OK;
505 if( !pBt->pHasContent ){
506 int nPage;
507 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
508 if( rc==SQLITE_OK ){
509 pBt->pHasContent = sqlite3BitvecCreate((u32)nPage);
510 if( !pBt->pHasContent ){
511 rc = SQLITE_NOMEM;
512 }
513 }
514 }
515 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
516 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
517 }
518 return rc;
519}
520
521/*
522** Query the BtShared.pHasContent vector.
523**
524** This function is called when a free-list leaf page is removed from the
525** free-list for reuse. It returns false if it is safe to retrieve the
526** page from the pager layer with the 'no-content' flag set. True otherwise.
527*/
528static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
529 Bitvec *p = pBt->pHasContent;
530 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
531}
532
533/*
534** Clear (destroy) the BtShared.pHasContent bitvec. This should be
535** invoked at the conclusion of each write-transaction.
536*/
537static void btreeClearHasContent(BtShared *pBt){
538 sqlite3BitvecDestroy(pBt->pHasContent);
539 pBt->pHasContent = 0;
540}
541
542/*
drh980b1a72006-08-16 16:42:48 +0000543** Save the current cursor position in the variables BtCursor.nKey
544** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
545*/
546static int saveCursorPosition(BtCursor *pCur){
547 int rc;
548
549 assert( CURSOR_VALID==pCur->eState );
550 assert( 0==pCur->pKey );
drh1fee73e2007-08-29 04:00:57 +0000551 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000552
553 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
554
555 /* If this is an intKey table, then the above call to BtreeKeySize()
556 ** stores the integer key in pCur->nKey. In this case this value is
557 ** all that is required. Otherwise, if pCur is not open on an intKey
558 ** table, then malloc space for and store the pCur->nKey bytes of key
559 ** data.
560 */
danielk197771d5d2c2008-09-29 11:49:47 +0000561 if( rc==SQLITE_OK && 0==pCur->apPage[0]->intKey){
drhf49661a2008-12-10 16:45:50 +0000562 void *pKey = sqlite3Malloc( (int)pCur->nKey );
drh980b1a72006-08-16 16:42:48 +0000563 if( pKey ){
drhf49661a2008-12-10 16:45:50 +0000564 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
drh980b1a72006-08-16 16:42:48 +0000565 if( rc==SQLITE_OK ){
566 pCur->pKey = pKey;
567 }else{
drh17435752007-08-16 04:30:38 +0000568 sqlite3_free(pKey);
drh980b1a72006-08-16 16:42:48 +0000569 }
570 }else{
571 rc = SQLITE_NOMEM;
572 }
573 }
danielk197771d5d2c2008-09-29 11:49:47 +0000574 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
drh980b1a72006-08-16 16:42:48 +0000575
576 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +0000577 int i;
578 for(i=0; i<=pCur->iPage; i++){
579 releasePage(pCur->apPage[i]);
580 pCur->apPage[i] = 0;
581 }
582 pCur->iPage = -1;
drh980b1a72006-08-16 16:42:48 +0000583 pCur->eState = CURSOR_REQUIRESEEK;
584 }
585
danielk197792d4d7a2007-05-04 12:05:56 +0000586 invalidateOverflowCache(pCur);
drh980b1a72006-08-16 16:42:48 +0000587 return rc;
588}
589
590/*
591** Save the positions of all cursors except pExcept open on the table
592** with root-page iRoot. Usually, this is called just before cursor
593** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
594*/
595static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
596 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000597 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +0000598 assert( pExcept==0 || pExcept->pBt==pBt );
drh980b1a72006-08-16 16:42:48 +0000599 for(p=pBt->pCursor; p; p=p->pNext){
600 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
601 p->eState==CURSOR_VALID ){
602 int rc = saveCursorPosition(p);
603 if( SQLITE_OK!=rc ){
604 return rc;
605 }
606 }
607 }
608 return SQLITE_OK;
609}
610
611/*
drhbf700f32007-03-31 02:36:44 +0000612** Clear the current cursor position.
613*/
danielk1977be51a652008-10-08 17:58:48 +0000614void sqlite3BtreeClearCursor(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000615 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000616 sqlite3_free(pCur->pKey);
drhbf700f32007-03-31 02:36:44 +0000617 pCur->pKey = 0;
618 pCur->eState = CURSOR_INVALID;
619}
620
621/*
drh980b1a72006-08-16 16:42:48 +0000622** Restore the cursor to the position it was in (or as close to as possible)
623** when saveCursorPosition() was called. Note that this call deletes the
624** saved position info stored by saveCursorPosition(), so there can be
drha3460582008-07-11 21:02:53 +0000625** at most one effective restoreCursorPosition() call after each
drh980b1a72006-08-16 16:42:48 +0000626** saveCursorPosition().
drh980b1a72006-08-16 16:42:48 +0000627*/
drha3460582008-07-11 21:02:53 +0000628int sqlite3BtreeRestoreCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +0000629 int rc;
drh1fee73e2007-08-29 04:00:57 +0000630 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +0000631 assert( pCur->eState>=CURSOR_REQUIRESEEK );
632 if( pCur->eState==CURSOR_FAULT ){
633 return pCur->skip;
634 }
drh980b1a72006-08-16 16:42:48 +0000635 pCur->eState = CURSOR_INVALID;
drhe63d9992008-08-13 19:11:48 +0000636 rc = sqlite3BtreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skip);
drh980b1a72006-08-16 16:42:48 +0000637 if( rc==SQLITE_OK ){
drh17435752007-08-16 04:30:38 +0000638 sqlite3_free(pCur->pKey);
drh980b1a72006-08-16 16:42:48 +0000639 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +0000640 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drh980b1a72006-08-16 16:42:48 +0000641 }
642 return rc;
643}
644
drha3460582008-07-11 21:02:53 +0000645#define restoreCursorPosition(p) \
drhfb982642007-08-30 01:19:59 +0000646 (p->eState>=CURSOR_REQUIRESEEK ? \
drha3460582008-07-11 21:02:53 +0000647 sqlite3BtreeRestoreCursorPosition(p) : \
drh16a9b832007-05-05 18:39:25 +0000648 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +0000649
drha3460582008-07-11 21:02:53 +0000650/*
651** Determine whether or not a cursor has moved from the position it
drhdfe88ec2008-11-03 20:55:06 +0000652** was last placed at. Cursors can move when the row they are pointing
drha3460582008-07-11 21:02:53 +0000653** at is deleted out from under them.
654**
655** This routine returns an error code if something goes wrong. The
656** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
657*/
658int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
659 int rc;
660
661 rc = restoreCursorPosition(pCur);
662 if( rc ){
663 *pHasMoved = 1;
664 return rc;
665 }
666 if( pCur->eState!=CURSOR_VALID || pCur->skip!=0 ){
667 *pHasMoved = 1;
668 }else{
669 *pHasMoved = 0;
670 }
671 return SQLITE_OK;
672}
673
danielk1977599fcba2004-11-08 07:13:13 +0000674#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000675/*
drha3152892007-05-05 11:48:52 +0000676** Given a page number of a regular database page, return the page
677** number for the pointer-map page that contains the entry for the
678** input page number.
danielk1977afcdd022004-10-31 16:25:42 +0000679*/
danielk1977266664d2006-02-10 08:24:21 +0000680static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
danielk197789d40042008-11-17 14:20:56 +0000681 int nPagesPerMapPage;
682 Pgno iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +0000683 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000684 nPagesPerMapPage = (pBt->usableSize/5)+1;
685 iPtrMap = (pgno-2)/nPagesPerMapPage;
686 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +0000687 if( ret==PENDING_BYTE_PAGE(pBt) ){
688 ret++;
689 }
690 return ret;
691}
danielk1977a19df672004-11-03 11:37:07 +0000692
danielk1977afcdd022004-10-31 16:25:42 +0000693/*
danielk1977afcdd022004-10-31 16:25:42 +0000694** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000695**
696** This routine updates the pointer map entry for page number 'key'
697** so that it maps to type 'eType' and parent page number 'pgno'.
698** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000699*/
danielk1977aef0bf62005-12-30 16:28:01 +0000700static int ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent){
danielk19773b8a05f2007-03-19 17:44:26 +0000701 DbPage *pDbPage; /* The pointer map page */
702 u8 *pPtrmap; /* The pointer map data */
703 Pgno iPtrmap; /* The pointer map page number */
704 int offset; /* Offset in pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000705 int rc;
706
drh1fee73e2007-08-29 04:00:57 +0000707 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977266664d2006-02-10 08:24:21 +0000708 /* The master-journal page number must never be used as a pointer map page */
709 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
710
danielk1977ac11ee62005-01-15 12:45:51 +0000711 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000712 if( key==0 ){
drh49285702005-09-17 15:20:26 +0000713 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000714 }
danielk1977266664d2006-02-10 08:24:21 +0000715 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000716 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977687566d2004-11-02 12:56:41 +0000717 if( rc!=SQLITE_OK ){
danielk1977afcdd022004-10-31 16:25:42 +0000718 return rc;
719 }
danielk19778c666b12008-07-18 09:34:57 +0000720 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drhacfc72b2009-06-05 18:44:15 +0000721 if( offset<0 ){
722 return SQLITE_CORRUPT_BKPT;
723 }
danielk19773b8a05f2007-03-19 17:44:26 +0000724 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000725
drh615ae552005-01-16 23:21:00 +0000726 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
727 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
danielk19773b8a05f2007-03-19 17:44:26 +0000728 rc = sqlite3PagerWrite(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000729 if( rc==SQLITE_OK ){
730 pPtrmap[offset] = eType;
731 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000732 }
danielk1977afcdd022004-10-31 16:25:42 +0000733 }
734
danielk19773b8a05f2007-03-19 17:44:26 +0000735 sqlite3PagerUnref(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000736 return rc;
danielk1977afcdd022004-10-31 16:25:42 +0000737}
738
739/*
740** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000741**
742** This routine retrieves the pointer map entry for page 'key', writing
743** the type and parent page number to *pEType and *pPgno respectively.
744** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000745*/
danielk1977aef0bf62005-12-30 16:28:01 +0000746static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +0000747 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000748 int iPtrmap; /* Pointer map page index */
749 u8 *pPtrmap; /* Pointer map page data */
750 int offset; /* Offset of entry in pointer map */
751 int rc;
752
drh1fee73e2007-08-29 04:00:57 +0000753 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000754
danielk1977266664d2006-02-10 08:24:21 +0000755 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000756 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000757 if( rc!=0 ){
758 return rc;
759 }
danielk19773b8a05f2007-03-19 17:44:26 +0000760 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000761
danielk19778c666b12008-07-18 09:34:57 +0000762 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drh43617e92006-03-06 20:55:46 +0000763 assert( pEType!=0 );
764 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +0000765 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000766
danielk19773b8a05f2007-03-19 17:44:26 +0000767 sqlite3PagerUnref(pDbPage);
drh49285702005-09-17 15:20:26 +0000768 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000769 return SQLITE_OK;
770}
771
danielk197785d90ca2008-07-19 14:25:15 +0000772#else /* if defined SQLITE_OMIT_AUTOVACUUM */
773 #define ptrmapPut(w,x,y,z) SQLITE_OK
774 #define ptrmapGet(w,x,y,z) SQLITE_OK
danielk1977325ccfa2009-07-02 05:23:25 +0000775 #define ptrmapPutOvflPtr(x, y) SQLITE_OK
danielk197785d90ca2008-07-19 14:25:15 +0000776#endif
danielk1977afcdd022004-10-31 16:25:42 +0000777
drh0d316a42002-08-11 20:10:47 +0000778/*
drh271efa52004-05-30 19:19:05 +0000779** Given a btree page and a cell index (0 means the first cell on
780** the page, 1 means the second cell, and so forth) return a pointer
781** to the cell content.
782**
783** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000784*/
drh1688c862008-07-18 02:44:17 +0000785#define findCell(P,I) \
786 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
drh43605152004-05-29 21:46:49 +0000787
788/*
drh93a960a2008-07-10 00:32:42 +0000789** This a more complex version of findCell() that works for
drh43605152004-05-29 21:46:49 +0000790** pages that do contain overflow cells. See insert
791*/
792static u8 *findOverflowCell(MemPage *pPage, int iCell){
793 int i;
drh1fee73e2007-08-29 04:00:57 +0000794 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +0000795 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000796 int k;
797 struct _OvflCell *pOvfl;
798 pOvfl = &pPage->aOvfl[i];
799 k = pOvfl->idx;
800 if( k<=iCell ){
801 if( k==iCell ){
802 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000803 }
804 iCell--;
805 }
806 }
danielk19771cc5ed82007-05-16 17:28:43 +0000807 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000808}
809
810/*
811** Parse a cell content block and fill in the CellInfo structure. There
drh16a9b832007-05-05 18:39:25 +0000812** are two versions of this function. sqlite3BtreeParseCell() takes a
813** cell index as the second argument and sqlite3BtreeParseCellPtr()
814** takes a pointer to the body of the cell as its second argument.
danielk19771cc5ed82007-05-16 17:28:43 +0000815**
816** Within this file, the parseCell() macro can be called instead of
817** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
drh43605152004-05-29 21:46:49 +0000818*/
drh16a9b832007-05-05 18:39:25 +0000819void sqlite3BtreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000820 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000821 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000822 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000823){
drhf49661a2008-12-10 16:45:50 +0000824 u16 n; /* Number bytes in cell content header */
drh271efa52004-05-30 19:19:05 +0000825 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000826
drh1fee73e2007-08-29 04:00:57 +0000827 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000828
drh43605152004-05-29 21:46:49 +0000829 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000830 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000831 n = pPage->childPtrSize;
832 assert( n==4-4*pPage->leaf );
drh504b6982006-01-22 21:52:56 +0000833 if( pPage->intKey ){
drh79df1f42008-07-18 00:57:33 +0000834 if( pPage->hasData ){
835 n += getVarint32(&pCell[n], nPayload);
836 }else{
837 nPayload = 0;
838 }
drh1bd10f82008-12-10 21:19:56 +0000839 n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
drh79df1f42008-07-18 00:57:33 +0000840 pInfo->nData = nPayload;
drh504b6982006-01-22 21:52:56 +0000841 }else{
drh79df1f42008-07-18 00:57:33 +0000842 pInfo->nData = 0;
843 n += getVarint32(&pCell[n], nPayload);
844 pInfo->nKey = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000845 }
drh72365832007-03-06 15:53:44 +0000846 pInfo->nPayload = nPayload;
drh504b6982006-01-22 21:52:56 +0000847 pInfo->nHeader = n;
drh79df1f42008-07-18 00:57:33 +0000848 if( likely(nPayload<=pPage->maxLocal) ){
drh271efa52004-05-30 19:19:05 +0000849 /* This is the (easy) common case where the entire payload fits
850 ** on the local page. No overflow is required.
851 */
852 int nSize; /* Total size of cell content in bytes */
drh79df1f42008-07-18 00:57:33 +0000853 nSize = nPayload + n;
drhf49661a2008-12-10 16:45:50 +0000854 pInfo->nLocal = (u16)nPayload;
drh6f11bef2004-05-13 01:12:56 +0000855 pInfo->iOverflow = 0;
drh79df1f42008-07-18 00:57:33 +0000856 if( (nSize & ~3)==0 ){
drh271efa52004-05-30 19:19:05 +0000857 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000858 }
drh1bd10f82008-12-10 21:19:56 +0000859 pInfo->nSize = (u16)nSize;
drh6f11bef2004-05-13 01:12:56 +0000860 }else{
drh271efa52004-05-30 19:19:05 +0000861 /* If the payload will not fit completely on the local page, we have
862 ** to decide how much to store locally and how much to spill onto
863 ** overflow pages. The strategy is to minimize the amount of unused
864 ** space on overflow pages while keeping the amount of local storage
865 ** in between minLocal and maxLocal.
866 **
867 ** Warning: changing the way overflow payload is distributed in any
868 ** way will result in an incompatible file format.
869 */
870 int minLocal; /* Minimum amount of payload held locally */
871 int maxLocal; /* Maximum amount of payload held locally */
872 int surplus; /* Overflow payload available for local storage */
873
874 minLocal = pPage->minLocal;
875 maxLocal = pPage->maxLocal;
876 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh6f11bef2004-05-13 01:12:56 +0000877 if( surplus <= maxLocal ){
drhf49661a2008-12-10 16:45:50 +0000878 pInfo->nLocal = (u16)surplus;
drh6f11bef2004-05-13 01:12:56 +0000879 }else{
drhf49661a2008-12-10 16:45:50 +0000880 pInfo->nLocal = (u16)minLocal;
drh6f11bef2004-05-13 01:12:56 +0000881 }
drhf49661a2008-12-10 16:45:50 +0000882 pInfo->iOverflow = (u16)(pInfo->nLocal + n);
drh6f11bef2004-05-13 01:12:56 +0000883 pInfo->nSize = pInfo->iOverflow + 4;
884 }
drh3aac2dd2004-04-26 14:10:20 +0000885}
danielk19771cc5ed82007-05-16 17:28:43 +0000886#define parseCell(pPage, iCell, pInfo) \
887 sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
drh16a9b832007-05-05 18:39:25 +0000888void sqlite3BtreeParseCell(
drh43605152004-05-29 21:46:49 +0000889 MemPage *pPage, /* Page containing the cell */
890 int iCell, /* The cell index. First cell is 0 */
891 CellInfo *pInfo /* Fill in this structure */
892){
danielk19771cc5ed82007-05-16 17:28:43 +0000893 parseCell(pPage, iCell, pInfo);
drh43605152004-05-29 21:46:49 +0000894}
drh3aac2dd2004-04-26 14:10:20 +0000895
896/*
drh43605152004-05-29 21:46:49 +0000897** Compute the total number of bytes that a Cell needs in the cell
898** data area of the btree-page. The return number includes the cell
899** data header and the local payload, but not any overflow page or
900** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000901*/
danielk1977ae5558b2009-04-29 11:31:47 +0000902static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
903 u8 *pIter = &pCell[pPage->childPtrSize];
904 u32 nSize;
905
906#ifdef SQLITE_DEBUG
907 /* The value returned by this function should always be the same as
908 ** the (CellInfo.nSize) value found by doing a full parse of the
909 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
910 ** this function verifies that this invariant is not violated. */
911 CellInfo debuginfo;
912 sqlite3BtreeParseCellPtr(pPage, pCell, &debuginfo);
913#endif
914
915 if( pPage->intKey ){
916 u8 *pEnd;
917 if( pPage->hasData ){
918 pIter += getVarint32(pIter, nSize);
919 }else{
920 nSize = 0;
921 }
922
923 /* pIter now points at the 64-bit integer key value, a variable length
924 ** integer. The following block moves pIter to point at the first byte
925 ** past the end of the key value. */
926 pEnd = &pIter[9];
927 while( (*pIter++)&0x80 && pIter<pEnd );
928 }else{
929 pIter += getVarint32(pIter, nSize);
930 }
931
932 if( nSize>pPage->maxLocal ){
933 int minLocal = pPage->minLocal;
934 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
935 if( nSize>pPage->maxLocal ){
936 nSize = minLocal;
937 }
938 nSize += 4;
939 }
shane75ac1de2009-06-09 18:58:52 +0000940 nSize += (u32)(pIter - pCell);
danielk1977ae5558b2009-04-29 11:31:47 +0000941
942 /* The minimum size of any cell is 4 bytes. */
943 if( nSize<4 ){
944 nSize = 4;
945 }
946
947 assert( nSize==debuginfo.nSize );
shane60a4b532009-05-06 18:57:09 +0000948 return (u16)nSize;
danielk1977ae5558b2009-04-29 11:31:47 +0000949}
danielk1977bc6ada42004-06-30 08:20:16 +0000950#ifndef NDEBUG
drha9121e42008-02-19 14:59:35 +0000951static u16 cellSize(MemPage *pPage, int iCell){
danielk1977ae5558b2009-04-29 11:31:47 +0000952 return cellSizePtr(pPage, findCell(pPage, iCell));
drh43605152004-05-29 21:46:49 +0000953}
danielk1977bc6ada42004-06-30 08:20:16 +0000954#endif
drh3b7511c2001-05-26 13:15:44 +0000955
danielk197779a40da2005-01-16 08:00:01 +0000956#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +0000957/*
danielk197726836652005-01-17 01:33:13 +0000958** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +0000959** to an overflow page, insert an entry into the pointer-map
960** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +0000961*/
danielk197726836652005-01-17 01:33:13 +0000962static int ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell){
drhfa67c3c2008-07-11 02:21:40 +0000963 CellInfo info;
964 assert( pCell!=0 );
965 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
966 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk19774dbaa892009-06-16 16:50:22 +0000967 if( info.iOverflow ){
drhfa67c3c2008-07-11 02:21:40 +0000968 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
969 return ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno);
danielk1977ac11ee62005-01-15 12:45:51 +0000970 }
danielk197779a40da2005-01-16 08:00:01 +0000971 return SQLITE_OK;
danielk1977ac11ee62005-01-15 12:45:51 +0000972}
danielk197779a40da2005-01-16 08:00:01 +0000973#endif
974
danielk1977ac11ee62005-01-15 12:45:51 +0000975
drhda200cc2004-05-09 11:51:38 +0000976/*
drh72f82862001-05-24 21:06:34 +0000977** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +0000978** end of the page and all free space is collected into one
979** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +0000980** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +0000981*/
shane0af3f892008-11-12 04:55:34 +0000982static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +0000983 int i; /* Loop counter */
984 int pc; /* Address of a i-th cell */
985 int addr; /* Offset of first byte after cell pointer array */
986 int hdr; /* Offset to the page header */
987 int size; /* Size of a cell */
988 int usableSize; /* Number of usable bytes on a page */
989 int cellOffset; /* Offset to the cell pointer array */
drh281b21d2008-08-22 12:57:08 +0000990 int cbrk; /* Offset to the cell content area */
drh43605152004-05-29 21:46:49 +0000991 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +0000992 unsigned char *data; /* The page data */
993 unsigned char *temp; /* Temp area for cell content */
drh2af926b2001-05-15 00:39:25 +0000994
danielk19773b8a05f2007-03-19 17:44:26 +0000995 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +0000996 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +0000997 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +0000998 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +0000999 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh26b79942007-11-28 16:19:56 +00001000 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
drh43605152004-05-29 21:46:49 +00001001 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +00001002 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00001003 cellOffset = pPage->cellOffset;
1004 nCell = pPage->nCell;
1005 assert( nCell==get2byte(&data[hdr+3]) );
1006 usableSize = pPage->pBt->usableSize;
drh281b21d2008-08-22 12:57:08 +00001007 cbrk = get2byte(&data[hdr+5]);
1008 memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
1009 cbrk = usableSize;
drh43605152004-05-29 21:46:49 +00001010 for(i=0; i<nCell; i++){
1011 u8 *pAddr; /* The i-th cell pointer */
1012 pAddr = &data[cellOffset + i*2];
1013 pc = get2byte(pAddr);
shanedcc50b72008-11-13 18:29:50 +00001014 if( pc>=usableSize ){
shane0af3f892008-11-12 04:55:34 +00001015 return SQLITE_CORRUPT_BKPT;
1016 }
drh43605152004-05-29 21:46:49 +00001017 size = cellSizePtr(pPage, &temp[pc]);
drh281b21d2008-08-22 12:57:08 +00001018 cbrk -= size;
danielk19770d065412008-11-12 18:21:36 +00001019 if( cbrk<cellOffset+2*nCell || pc+size>usableSize ){
shane0af3f892008-11-12 04:55:34 +00001020 return SQLITE_CORRUPT_BKPT;
1021 }
danielk19770d065412008-11-12 18:21:36 +00001022 assert( cbrk+size<=usableSize && cbrk>=0 );
drh281b21d2008-08-22 12:57:08 +00001023 memcpy(&data[cbrk], &temp[pc], size);
1024 put2byte(pAddr, cbrk);
drh2af926b2001-05-15 00:39:25 +00001025 }
drh281b21d2008-08-22 12:57:08 +00001026 assert( cbrk>=cellOffset+2*nCell );
1027 put2byte(&data[hdr+5], cbrk);
drh43605152004-05-29 21:46:49 +00001028 data[hdr+1] = 0;
1029 data[hdr+2] = 0;
1030 data[hdr+7] = 0;
1031 addr = cellOffset+2*nCell;
drh281b21d2008-08-22 12:57:08 +00001032 memset(&data[addr], 0, cbrk-addr);
drhc5053fb2008-11-27 02:22:10 +00001033 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977360e6342008-11-12 08:49:51 +00001034 if( cbrk-addr!=pPage->nFree ){
1035 return SQLITE_CORRUPT_BKPT;
1036 }
shane0af3f892008-11-12 04:55:34 +00001037 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +00001038}
1039
drha059ad02001-04-17 20:09:11 +00001040/*
danielk19776011a752009-04-01 16:25:32 +00001041** Allocate nByte bytes of space from within the B-Tree page passed
1042** as the first argument. Return the index into pPage->aData[] of the
1043** first byte of allocated space.
drhbd03cae2001-06-02 02:40:57 +00001044**
danielk19776011a752009-04-01 16:25:32 +00001045** The caller guarantees that the space between the end of the cell-offset
1046** array and the start of the cell-content area is at least nByte bytes
1047** in size. So this routine can never fail.
drh2af926b2001-05-15 00:39:25 +00001048**
danielk19776011a752009-04-01 16:25:32 +00001049** If there are already 60 or more bytes of fragments within the page,
1050** the page is defragmented before returning. If this were not done there
1051** is a chance that the number of fragmented bytes could eventually
1052** overflow the single-byte field of the page-header in which this value
1053** is stored.
drh7e3b0a02001-04-28 16:52:40 +00001054*/
drh9e572e62004-04-23 23:43:10 +00001055static int allocateSpace(MemPage *pPage, int nByte){
danielk19776011a752009-04-01 16:25:32 +00001056 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1057 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
1058 int nFrag; /* Number of fragmented bytes on pPage */
drh43605152004-05-29 21:46:49 +00001059 int top;
drh43605152004-05-29 21:46:49 +00001060
danielk19773b8a05f2007-03-19 17:44:26 +00001061 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001062 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +00001063 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa67c3c2008-07-11 02:21:40 +00001064 assert( nByte>=0 ); /* Minimum cell size is 4 */
1065 assert( pPage->nFree>=nByte );
1066 assert( pPage->nOverflow==0 );
drh43605152004-05-29 21:46:49 +00001067
danielk19776011a752009-04-01 16:25:32 +00001068 /* Assert that the space between the cell-offset array and the
1069 ** cell-content area is greater than nByte bytes.
1070 */
1071 assert( nByte <= (
1072 get2byte(&data[hdr+5])-(hdr+8+(pPage->leaf?0:4)+2*get2byte(&data[hdr+3]))
1073 ));
1074
drh43605152004-05-29 21:46:49 +00001075 nFrag = data[hdr+7];
danielk19776011a752009-04-01 16:25:32 +00001076 if( nFrag>=60 ){
1077 defragmentPage(pPage);
1078 }else{
1079 /* Search the freelist looking for a free slot big enough to satisfy
1080 ** the request. The allocation is made from the first free slot in
1081 ** the list that is large enough to accomadate it.
1082 */
1083 int pc, addr;
1084 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
1085 int size = get2byte(&data[pc+2]); /* Size of free slot */
drh43605152004-05-29 21:46:49 +00001086 if( size>=nByte ){
drhf49661a2008-12-10 16:45:50 +00001087 int x = size - nByte;
danielk19776011a752009-04-01 16:25:32 +00001088 if( x<4 ){
danielk1977fad91942009-04-29 17:49:59 +00001089 /* Remove the slot from the free-list. Update the number of
1090 ** fragmented bytes within the page. */
drh43605152004-05-29 21:46:49 +00001091 memcpy(&data[addr], &data[pc], 2);
drhf49661a2008-12-10 16:45:50 +00001092 data[hdr+7] = (u8)(nFrag + x);
drh43605152004-05-29 21:46:49 +00001093 }else{
danielk1977fad91942009-04-29 17:49:59 +00001094 /* The slot remains on the free-list. Reduce its size to account
1095 ** for the portion used by the new allocation. */
drhf49661a2008-12-10 16:45:50 +00001096 put2byte(&data[pc+2], x);
drh43605152004-05-29 21:46:49 +00001097 }
danielk19776011a752009-04-01 16:25:32 +00001098 return pc + x;
drh43605152004-05-29 21:46:49 +00001099 }
drh9e572e62004-04-23 23:43:10 +00001100 }
1101 }
drh43605152004-05-29 21:46:49 +00001102
1103 /* Allocate memory from the gap in between the cell pointer array
1104 ** and the cell content area.
1105 */
danielk19776011a752009-04-01 16:25:32 +00001106 top = get2byte(&data[hdr+5]) - nByte;
drh43605152004-05-29 21:46:49 +00001107 put2byte(&data[hdr+5], top);
1108 return top;
drh7e3b0a02001-04-28 16:52:40 +00001109}
1110
1111/*
drh9e572e62004-04-23 23:43:10 +00001112** Return a section of the pPage->aData to the freelist.
1113** The first byte of the new free block is pPage->aDisk[start]
1114** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +00001115**
1116** Most of the effort here is involved in coalesing adjacent
1117** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +00001118*/
shanedcc50b72008-11-13 18:29:50 +00001119static int freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +00001120 int addr, pbegin, hdr;
drh9e572e62004-04-23 23:43:10 +00001121 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +00001122
drh9e572e62004-04-23 23:43:10 +00001123 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001124 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001125 assert( start>=pPage->hdrOffset+6+(pPage->leaf?0:4) );
danielk1977bc6ada42004-06-30 08:20:16 +00001126 assert( (start + size)<=pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +00001127 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh34004ce2008-07-11 16:15:17 +00001128 assert( size>=0 ); /* Minimum cell size is 4 */
drh9e572e62004-04-23 23:43:10 +00001129
drhfcce93f2006-02-22 03:08:32 +00001130#ifdef SQLITE_SECURE_DELETE
1131 /* Overwrite deleted information with zeros when the SECURE_DELETE
1132 ** option is enabled at compile-time */
1133 memset(&data[start], 0, size);
1134#endif
1135
drh9e572e62004-04-23 23:43:10 +00001136 /* Add the space back into the linked list of freeblocks */
drh43605152004-05-29 21:46:49 +00001137 hdr = pPage->hdrOffset;
1138 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +00001139 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drhb6f41482004-05-14 01:58:11 +00001140 assert( pbegin<=pPage->pBt->usableSize-4 );
shanedcc50b72008-11-13 18:29:50 +00001141 if( pbegin<=addr ) {
1142 return SQLITE_CORRUPT_BKPT;
1143 }
drh3aac2dd2004-04-26 14:10:20 +00001144 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +00001145 }
shanedcc50b72008-11-13 18:29:50 +00001146 if ( pbegin>pPage->pBt->usableSize-4 ) {
1147 return SQLITE_CORRUPT_BKPT;
1148 }
drh3aac2dd2004-04-26 14:10:20 +00001149 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +00001150 put2byte(&data[addr], start);
1151 put2byte(&data[start], pbegin);
1152 put2byte(&data[start+2], size);
shane36840fd2009-06-26 16:32:13 +00001153 pPage->nFree = pPage->nFree + (u16)size;
drh9e572e62004-04-23 23:43:10 +00001154
1155 /* Coalesce adjacent free blocks */
drh3aac2dd2004-04-26 14:10:20 +00001156 addr = pPage->hdrOffset + 1;
1157 while( (pbegin = get2byte(&data[addr]))>0 ){
drhf49661a2008-12-10 16:45:50 +00001158 int pnext, psize, x;
drh3aac2dd2004-04-26 14:10:20 +00001159 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +00001160 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +00001161 pnext = get2byte(&data[pbegin]);
1162 psize = get2byte(&data[pbegin+2]);
1163 if( pbegin + psize + 3 >= pnext && pnext>0 ){
1164 int frag = pnext - (pbegin+psize);
drhf49661a2008-12-10 16:45:50 +00001165 if( (frag<0) || (frag>(int)data[pPage->hdrOffset+7]) ){
shanedcc50b72008-11-13 18:29:50 +00001166 return SQLITE_CORRUPT_BKPT;
1167 }
drhf49661a2008-12-10 16:45:50 +00001168 data[pPage->hdrOffset+7] -= (u8)frag;
1169 x = get2byte(&data[pnext]);
1170 put2byte(&data[pbegin], x);
1171 x = pnext + get2byte(&data[pnext+2]) - pbegin;
1172 put2byte(&data[pbegin+2], x);
drh9e572e62004-04-23 23:43:10 +00001173 }else{
drh3aac2dd2004-04-26 14:10:20 +00001174 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +00001175 }
1176 }
drh7e3b0a02001-04-28 16:52:40 +00001177
drh43605152004-05-29 21:46:49 +00001178 /* If the cell content area begins with a freeblock, remove it. */
1179 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
1180 int top;
1181 pbegin = get2byte(&data[hdr+1]);
1182 memcpy(&data[hdr+1], &data[pbegin], 2);
drhf49661a2008-12-10 16:45:50 +00001183 top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
1184 put2byte(&data[hdr+5], top);
drh4b70f112004-05-02 21:12:19 +00001185 }
drhc5053fb2008-11-27 02:22:10 +00001186 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
shanedcc50b72008-11-13 18:29:50 +00001187 return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00001188}
1189
1190/*
drh271efa52004-05-30 19:19:05 +00001191** Decode the flags byte (the first byte of the header) for a page
1192** and initialize fields of the MemPage structure accordingly.
drh44845222008-07-17 18:39:57 +00001193**
1194** Only the following combinations are supported. Anything different
1195** indicates a corrupt database files:
1196**
1197** PTF_ZERODATA
1198** PTF_ZERODATA | PTF_LEAF
1199** PTF_LEAFDATA | PTF_INTKEY
1200** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
drh271efa52004-05-30 19:19:05 +00001201*/
drh44845222008-07-17 18:39:57 +00001202static int decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +00001203 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +00001204
1205 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +00001206 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00001207 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
drh44845222008-07-17 18:39:57 +00001208 flagByte &= ~PTF_LEAF;
1209 pPage->childPtrSize = 4-4*pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001210 pBt = pPage->pBt;
drh44845222008-07-17 18:39:57 +00001211 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
1212 pPage->intKey = 1;
1213 pPage->hasData = pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001214 pPage->maxLocal = pBt->maxLeaf;
1215 pPage->minLocal = pBt->minLeaf;
drh44845222008-07-17 18:39:57 +00001216 }else if( flagByte==PTF_ZERODATA ){
1217 pPage->intKey = 0;
1218 pPage->hasData = 0;
drh271efa52004-05-30 19:19:05 +00001219 pPage->maxLocal = pBt->maxLocal;
1220 pPage->minLocal = pBt->minLocal;
drh44845222008-07-17 18:39:57 +00001221 }else{
1222 return SQLITE_CORRUPT_BKPT;
drh271efa52004-05-30 19:19:05 +00001223 }
drh44845222008-07-17 18:39:57 +00001224 return SQLITE_OK;
drh271efa52004-05-30 19:19:05 +00001225}
1226
1227/*
drh7e3b0a02001-04-28 16:52:40 +00001228** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +00001229**
1230** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +00001231** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +00001232** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1233** guarantee that the page is well-formed. It only shows that
1234** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001235*/
danielk197771d5d2c2008-09-29 11:49:47 +00001236int sqlite3BtreeInitPage(MemPage *pPage){
drh2af926b2001-05-15 00:39:25 +00001237
danielk197771d5d2c2008-09-29 11:49:47 +00001238 assert( pPage->pBt!=0 );
1239 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001240 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +00001241 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1242 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00001243
1244 if( !pPage->isInit ){
drhf49661a2008-12-10 16:45:50 +00001245 u16 pc; /* Address of a freeblock within pPage->aData[] */
1246 u8 hdr; /* Offset to beginning of page header */
danielk197771d5d2c2008-09-29 11:49:47 +00001247 u8 *data; /* Equal to pPage->aData */
1248 BtShared *pBt; /* The main btree structure */
drhf49661a2008-12-10 16:45:50 +00001249 u16 usableSize; /* Amount of usable space on each page */
1250 u16 cellOffset; /* Offset from start of page to first cell pointer */
1251 u16 nFree; /* Number of unused bytes on the page */
1252 u16 top; /* First byte of the cell content area */
danielk197771d5d2c2008-09-29 11:49:47 +00001253
1254 pBt = pPage->pBt;
1255
danielk1977eaa06f62008-09-18 17:34:44 +00001256 hdr = pPage->hdrOffset;
1257 data = pPage->aData;
1258 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
1259 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
1260 pPage->maskPage = pBt->pageSize - 1;
1261 pPage->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00001262 usableSize = pBt->usableSize;
1263 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
1264 top = get2byte(&data[hdr+5]);
1265 pPage->nCell = get2byte(&data[hdr+3]);
1266 if( pPage->nCell>MX_CELL(pBt) ){
1267 /* To many cells for a single page. The page must be corrupt */
1268 return SQLITE_CORRUPT_BKPT;
1269 }
drh69e931e2009-06-03 21:04:35 +00001270
1271 /* A malformed database page might cause use to read past the end
1272 ** of page when parsing a cell.
1273 **
1274 ** The following block of code checks early to see if a cell extends
1275 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
1276 ** returned if it does.
1277 */
drh3b2a3fa2009-06-09 13:42:24 +00001278#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
drh69e931e2009-06-03 21:04:35 +00001279 {
1280 int iCellFirst; /* First allowable cell index */
1281 int iCellLast; /* Last possible cell index */
1282 int i; /* Index into the cell pointer array */
1283 int sz; /* Size of a cell */
1284
1285 iCellFirst = cellOffset + 2*pPage->nCell;
1286 iCellLast = usableSize - 4;
1287 if( !pPage->leaf ) iCellLast--;
1288 for(i=0; i<pPage->nCell; i++){
1289 pc = get2byte(&data[cellOffset+i*2]);
1290 if( pc<iCellFirst || pc>iCellLast ){
1291 return SQLITE_CORRUPT_BKPT;
1292 }
1293 sz = cellSizePtr(pPage, &data[pc]);
1294 if( pc+sz>usableSize ){
1295 return SQLITE_CORRUPT_BKPT;
1296 }
1297 }
1298 }
1299#endif
1300
danielk1977eaa06f62008-09-18 17:34:44 +00001301 /* Compute the total free space on the page */
1302 pc = get2byte(&data[hdr+1]);
danielk197793c829c2009-06-03 17:26:17 +00001303 nFree = data[hdr+7] + top;
danielk1977eaa06f62008-09-18 17:34:44 +00001304 while( pc>0 ){
drh1bd10f82008-12-10 21:19:56 +00001305 u16 next, size;
danielk1977eaa06f62008-09-18 17:34:44 +00001306 if( pc>usableSize-4 ){
1307 /* Free block is off the page */
1308 return SQLITE_CORRUPT_BKPT;
1309 }
1310 next = get2byte(&data[pc]);
1311 size = get2byte(&data[pc+2]);
1312 if( next>0 && next<=pc+size+3 ){
1313 /* Free blocks must be in accending order */
1314 return SQLITE_CORRUPT_BKPT;
1315 }
shane85095702009-06-15 16:27:08 +00001316 nFree = nFree + size;
danielk1977eaa06f62008-09-18 17:34:44 +00001317 pc = next;
1318 }
danielk197793c829c2009-06-03 17:26:17 +00001319
1320 /* At this point, nFree contains the sum of the offset to the start
1321 ** of the cell-content area plus the number of free bytes within
1322 ** the cell-content area. If this is greater than the usable-size
1323 ** of the page, then the page must be corrupted. This check also
1324 ** serves to verify that the offset to the start of the cell-content
1325 ** area, according to the page header, lies within the page.
1326 */
1327 if( nFree>usableSize ){
drh49285702005-09-17 15:20:26 +00001328 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001329 }
danielk197793c829c2009-06-03 17:26:17 +00001330 pPage->nFree = nFree - (cellOffset + 2*pPage->nCell);
drh9e572e62004-04-23 23:43:10 +00001331
drh1688c862008-07-18 02:44:17 +00001332#if 0
1333 /* Check that all the offsets in the cell offset array are within range.
1334 **
1335 ** Omitting this consistency check and using the pPage->maskPage mask
1336 ** to prevent overrunning the page buffer in findCell() results in a
1337 ** 2.5% performance gain.
1338 */
1339 {
1340 u8 *pOff; /* Iterator used to check all cell offsets are in range */
1341 u8 *pEnd; /* Pointer to end of cell offset array */
1342 u8 mask; /* Mask of bits that must be zero in MSB of cell offsets */
1343 mask = ~(((u8)(pBt->pageSize>>8))-1);
1344 pEnd = &data[cellOffset + pPage->nCell*2];
1345 for(pOff=&data[cellOffset]; pOff!=pEnd && !((*pOff)&mask); pOff+=2);
1346 if( pOff!=pEnd ){
1347 return SQLITE_CORRUPT_BKPT;
1348 }
danielk1977e16535f2008-06-11 18:15:29 +00001349 }
drh1688c862008-07-18 02:44:17 +00001350#endif
danielk1977e16535f2008-06-11 18:15:29 +00001351
danielk197771d5d2c2008-09-29 11:49:47 +00001352 pPage->isInit = 1;
1353 }
drh9e572e62004-04-23 23:43:10 +00001354 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001355}
1356
1357/*
drh8b2f49b2001-06-08 00:21:52 +00001358** Set up a raw page so that it looks like a database page holding
1359** no entries.
drhbd03cae2001-06-02 02:40:57 +00001360*/
drh9e572e62004-04-23 23:43:10 +00001361static void zeroPage(MemPage *pPage, int flags){
1362 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001363 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00001364 u8 hdr = pPage->hdrOffset;
1365 u16 first;
drh9e572e62004-04-23 23:43:10 +00001366
danielk19773b8a05f2007-03-19 17:44:26 +00001367 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drhbf4bca52007-09-06 22:19:14 +00001368 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1369 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +00001370 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00001371 assert( sqlite3_mutex_held(pBt->mutex) );
drh1af4a6e2008-07-18 03:32:51 +00001372 /*memset(&data[hdr], 0, pBt->usableSize - hdr);*/
drh1bd10f82008-12-10 21:19:56 +00001373 data[hdr] = (char)flags;
1374 first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
drh43605152004-05-29 21:46:49 +00001375 memset(&data[hdr+1], 0, 4);
1376 data[hdr+7] = 0;
1377 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +00001378 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +00001379 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +00001380 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +00001381 pPage->cellOffset = first;
1382 pPage->nOverflow = 0;
drh1688c862008-07-18 02:44:17 +00001383 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
1384 pPage->maskPage = pBt->pageSize - 1;
drh43605152004-05-29 21:46:49 +00001385 pPage->nCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001386 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00001387}
1388
drh897a8202008-09-18 01:08:15 +00001389
1390/*
1391** Convert a DbPage obtained from the pager into a MemPage used by
1392** the btree layer.
1393*/
1394static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
1395 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
1396 pPage->aData = sqlite3PagerGetData(pDbPage);
1397 pPage->pDbPage = pDbPage;
1398 pPage->pBt = pBt;
1399 pPage->pgno = pgno;
1400 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
1401 return pPage;
1402}
1403
drhbd03cae2001-06-02 02:40:57 +00001404/*
drh3aac2dd2004-04-26 14:10:20 +00001405** Get a page from the pager. Initialize the MemPage.pBt and
1406** MemPage.aData elements if needed.
drh538f5702007-04-13 02:14:30 +00001407**
1408** If the noContent flag is set, it means that we do not care about
1409** the content of the page at this time. So do not go to the disk
1410** to fetch the content. Just fill in the content with zeros for now.
1411** If in the future we call sqlite3PagerWrite() on this page, that
1412** means we have started to be concerned about content and the disk
1413** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00001414*/
drh16a9b832007-05-05 18:39:25 +00001415int sqlite3BtreeGetPage(
1416 BtShared *pBt, /* The btree */
1417 Pgno pgno, /* Number of the page to fetch */
1418 MemPage **ppPage, /* Return the page in this parameter */
1419 int noContent /* Do not load page content if true */
1420){
drh3aac2dd2004-04-26 14:10:20 +00001421 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001422 DbPage *pDbPage;
1423
drh1fee73e2007-08-29 04:00:57 +00001424 assert( sqlite3_mutex_held(pBt->mutex) );
drh538f5702007-04-13 02:14:30 +00001425 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
drh3aac2dd2004-04-26 14:10:20 +00001426 if( rc ) return rc;
drh897a8202008-09-18 01:08:15 +00001427 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
drh3aac2dd2004-04-26 14:10:20 +00001428 return SQLITE_OK;
1429}
1430
1431/*
danielk1977bea2a942009-01-20 17:06:27 +00001432** Retrieve a page from the pager cache. If the requested page is not
1433** already in the pager cache return NULL. Initialize the MemPage.pBt and
1434** MemPage.aData elements if needed.
1435*/
1436static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
1437 DbPage *pDbPage;
1438 assert( sqlite3_mutex_held(pBt->mutex) );
1439 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
1440 if( pDbPage ){
1441 return btreePageFromDbPage(pDbPage, pgno, pBt);
1442 }
1443 return 0;
1444}
1445
1446/*
danielk197789d40042008-11-17 14:20:56 +00001447** Return the size of the database file in pages. If there is any kind of
1448** error, return ((unsigned int)-1).
danielk197767fd7a92008-09-10 17:53:35 +00001449*/
danielk197789d40042008-11-17 14:20:56 +00001450static Pgno pagerPagecount(BtShared *pBt){
1451 int nPage = -1;
danielk197767fd7a92008-09-10 17:53:35 +00001452 int rc;
danielk197789d40042008-11-17 14:20:56 +00001453 assert( pBt->pPage1 );
1454 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1455 assert( rc==SQLITE_OK || nPage==-1 );
1456 return (Pgno)nPage;
danielk197767fd7a92008-09-10 17:53:35 +00001457}
1458
1459/*
drhde647132004-05-07 17:57:49 +00001460** Get a page from the pager and initialize it. This routine
1461** is just a convenience wrapper around separate calls to
drh16a9b832007-05-05 18:39:25 +00001462** sqlite3BtreeGetPage() and sqlite3BtreeInitPage().
drhde647132004-05-07 17:57:49 +00001463*/
1464static int getAndInitPage(
danielk1977aef0bf62005-12-30 16:28:01 +00001465 BtShared *pBt, /* The database file */
drhde647132004-05-07 17:57:49 +00001466 Pgno pgno, /* Number of the page to get */
danielk197771d5d2c2008-09-29 11:49:47 +00001467 MemPage **ppPage /* Write the page pointer here */
drhde647132004-05-07 17:57:49 +00001468){
1469 int rc;
drh897a8202008-09-18 01:08:15 +00001470 MemPage *pPage;
1471
drh1fee73e2007-08-29 04:00:57 +00001472 assert( sqlite3_mutex_held(pBt->mutex) );
drh897a8202008-09-18 01:08:15 +00001473 if( pgno==0 ){
drh49285702005-09-17 15:20:26 +00001474 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001475 }
danielk19779f580ad2008-09-10 14:45:57 +00001476
drh897a8202008-09-18 01:08:15 +00001477 /* It is often the case that the page we want is already in cache.
1478 ** If so, get it directly. This saves us from having to call
1479 ** pagerPagecount() to make sure pgno is within limits, which results
1480 ** in a measureable performance improvements.
1481 */
danielk1977bea2a942009-01-20 17:06:27 +00001482 *ppPage = pPage = btreePageLookup(pBt, pgno);
1483 if( pPage ){
drh897a8202008-09-18 01:08:15 +00001484 /* Page is already in cache */
drh897a8202008-09-18 01:08:15 +00001485 rc = SQLITE_OK;
1486 }else{
1487 /* Page not in cache. Acquire it. */
danielk197789d40042008-11-17 14:20:56 +00001488 if( pgno>pagerPagecount(pBt) ){
drh897a8202008-09-18 01:08:15 +00001489 return SQLITE_CORRUPT_BKPT;
1490 }
1491 rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
1492 if( rc ) return rc;
1493 pPage = *ppPage;
1494 }
danielk197771d5d2c2008-09-29 11:49:47 +00001495 if( !pPage->isInit ){
1496 rc = sqlite3BtreeInitPage(pPage);
drh897a8202008-09-18 01:08:15 +00001497 }
1498 if( rc!=SQLITE_OK ){
1499 releasePage(pPage);
1500 *ppPage = 0;
1501 }
drhde647132004-05-07 17:57:49 +00001502 return rc;
1503}
1504
1505/*
drh3aac2dd2004-04-26 14:10:20 +00001506** Release a MemPage. This should be called once for each prior
drh16a9b832007-05-05 18:39:25 +00001507** call to sqlite3BtreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +00001508*/
drh4b70f112004-05-02 21:12:19 +00001509static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001510 if( pPage ){
drh30df0092008-12-23 15:58:06 +00001511 assert( pPage->nOverflow==0 || sqlite3PagerPageRefcount(pPage->pDbPage)>1 );
drh3aac2dd2004-04-26 14:10:20 +00001512 assert( pPage->aData );
1513 assert( pPage->pBt );
drhbf4bca52007-09-06 22:19:14 +00001514 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1515 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
drh1fee73e2007-08-29 04:00:57 +00001516 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001517 sqlite3PagerUnref(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00001518 }
1519}
1520
1521/*
drha6abd042004-06-09 17:37:22 +00001522** During a rollback, when the pager reloads information into the cache
1523** so that the cache is restored to its original state at the start of
1524** the transaction, for each page restored this routine is called.
1525**
1526** This routine needs to reset the extra data section at the end of the
1527** page to agree with the restored data.
1528*/
danielk1977eaa06f62008-09-18 17:34:44 +00001529static void pageReinit(DbPage *pData){
drh07d183d2005-05-01 22:52:42 +00001530 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00001531 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
danielk1977d217e6f2009-04-01 17:13:51 +00001532 assert( sqlite3PagerPageRefcount(pData)>0 );
danielk197771d5d2c2008-09-29 11:49:47 +00001533 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00001534 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00001535 pPage->isInit = 0;
danielk1977d217e6f2009-04-01 17:13:51 +00001536 if( sqlite3PagerPageRefcount(pData)>1 ){
drh5e8d8872009-03-30 17:19:48 +00001537 /* pPage might not be a btree page; it might be an overflow page
1538 ** or ptrmap page or a free page. In those cases, the following
1539 ** call to sqlite3BtreeInitPage() will likely return SQLITE_CORRUPT.
1540 ** But no harm is done by this. And it is very important that
1541 ** sqlite3BtreeInitPage() be called on every btree page so we make
1542 ** the call for every page that comes in for re-initing. */
danielk197771d5d2c2008-09-29 11:49:47 +00001543 sqlite3BtreeInitPage(pPage);
1544 }
drha6abd042004-06-09 17:37:22 +00001545 }
1546}
1547
1548/*
drhe5fe6902007-12-07 18:55:28 +00001549** Invoke the busy handler for a btree.
1550*/
danielk19771ceedd32008-11-19 10:22:33 +00001551static int btreeInvokeBusyHandler(void *pArg){
drhe5fe6902007-12-07 18:55:28 +00001552 BtShared *pBt = (BtShared*)pArg;
1553 assert( pBt->db );
1554 assert( sqlite3_mutex_held(pBt->db->mutex) );
1555 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
1556}
1557
1558/*
drhad3e0102004-09-03 23:32:18 +00001559** Open a database file.
1560**
drh382c0242001-10-06 16:33:02 +00001561** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001562** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001563** database file will be deleted when sqlite3BtreeClose() is called.
drhe53831d2007-08-17 01:14:38 +00001564** If zFilename is ":memory:" then an in-memory database is created
1565** that is automatically destroyed when it is closed.
drhc47fd8e2009-04-30 13:30:32 +00001566**
1567** If the database is already opened in the same database connection
1568** and we are in shared cache mode, then the open will fail with an
1569** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
1570** objects in the same database connection since doing so will lead
1571** to problems with locking.
drha059ad02001-04-17 20:09:11 +00001572*/
drh23e11ca2004-05-04 17:27:28 +00001573int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001574 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00001575 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001576 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00001577 int flags, /* Options */
1578 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00001579){
drh7555d8e2009-03-20 13:15:30 +00001580 sqlite3_vfs *pVfs; /* The VFS to use for this btree */
1581 BtShared *pBt = 0; /* Shared part of btree structure */
1582 Btree *p; /* Handle to return */
1583 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
1584 int rc = SQLITE_OK; /* Result code from this function */
1585 u8 nReserve; /* Byte of unused space on each page */
1586 unsigned char zDbHeader[100]; /* Database header content */
danielk1977aef0bf62005-12-30 16:28:01 +00001587
1588 /* Set the variable isMemdb to true for an in-memory database, or
1589 ** false for a file-based database. This symbol is only required if
1590 ** either of the shared-data or autovacuum features are compiled
1591 ** into the library.
1592 */
1593#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
1594 #ifdef SQLITE_OMIT_MEMORYDB
drh980b1a72006-08-16 16:42:48 +00001595 const int isMemdb = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00001596 #else
drh980b1a72006-08-16 16:42:48 +00001597 const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
danielk1977aef0bf62005-12-30 16:28:01 +00001598 #endif
1599#endif
1600
drhe5fe6902007-12-07 18:55:28 +00001601 assert( db!=0 );
1602 assert( sqlite3_mutex_held(db->mutex) );
drh153c62c2007-08-24 03:51:33 +00001603
drhe5fe6902007-12-07 18:55:28 +00001604 pVfs = db->pVfs;
drh17435752007-08-16 04:30:38 +00001605 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00001606 if( !p ){
1607 return SQLITE_NOMEM;
1608 }
1609 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00001610 p->db = db;
danielk1977602b4662009-07-02 07:47:33 +00001611#ifndef SQLITE_OMIT_SHARED_CACHE
1612 p->lock.pBtree = p;
1613 p->lock.iTable = 1;
1614#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001615
drh198bf392006-01-06 21:52:49 +00001616#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001617 /*
1618 ** If this Btree is a candidate for shared cache, try to find an
1619 ** existing BtShared object that we can share with
1620 */
danielk197720c6cc22009-04-01 18:03:00 +00001621 if( isMemdb==0 && zFilename && zFilename[0] ){
danielk1977502b4e02008-09-02 14:07:24 +00001622 if( sqlite3GlobalConfig.sharedCacheEnabled ){
danielk1977adfb9b02007-09-17 07:02:56 +00001623 int nFullPathname = pVfs->mxPathname+1;
drhe5ae5732008-06-15 02:51:47 +00001624 char *zFullPathname = sqlite3Malloc(nFullPathname);
drhff0587c2007-08-29 17:43:19 +00001625 sqlite3_mutex *mutexShared;
1626 p->sharable = 1;
drh34004ce2008-07-11 16:15:17 +00001627 db->flags |= SQLITE_SharedCache;
drhff0587c2007-08-29 17:43:19 +00001628 if( !zFullPathname ){
1629 sqlite3_free(p);
1630 return SQLITE_NOMEM;
1631 }
danielk1977adfb9b02007-09-17 07:02:56 +00001632 sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
drh7555d8e2009-03-20 13:15:30 +00001633 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
1634 sqlite3_mutex_enter(mutexOpen);
danielk197759f8c082008-06-18 17:09:10 +00001635 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhff0587c2007-08-29 17:43:19 +00001636 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001637 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
drhff0587c2007-08-29 17:43:19 +00001638 assert( pBt->nRef>0 );
1639 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
1640 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
drhc47fd8e2009-04-30 13:30:32 +00001641 int iDb;
1642 for(iDb=db->nDb-1; iDb>=0; iDb--){
1643 Btree *pExisting = db->aDb[iDb].pBt;
1644 if( pExisting && pExisting->pBt==pBt ){
1645 sqlite3_mutex_leave(mutexShared);
1646 sqlite3_mutex_leave(mutexOpen);
1647 sqlite3_free(zFullPathname);
1648 sqlite3_free(p);
1649 return SQLITE_CONSTRAINT;
1650 }
1651 }
drhff0587c2007-08-29 17:43:19 +00001652 p->pBt = pBt;
1653 pBt->nRef++;
1654 break;
1655 }
1656 }
1657 sqlite3_mutex_leave(mutexShared);
1658 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00001659 }
drhff0587c2007-08-29 17:43:19 +00001660#ifdef SQLITE_DEBUG
1661 else{
1662 /* In debug mode, we mark all persistent databases as sharable
1663 ** even when they are not. This exercises the locking code and
1664 ** gives more opportunity for asserts(sqlite3_mutex_held())
1665 ** statements to find locking problems.
1666 */
1667 p->sharable = 1;
1668 }
1669#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001670 }
1671#endif
drha059ad02001-04-17 20:09:11 +00001672 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00001673 /*
1674 ** The following asserts make sure that structures used by the btree are
1675 ** the right size. This is to guard against size changes that result
1676 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00001677 */
drhe53831d2007-08-17 01:14:38 +00001678 assert( sizeof(i64)==8 || sizeof(i64)==4 );
1679 assert( sizeof(u64)==8 || sizeof(u64)==4 );
1680 assert( sizeof(u32)==4 );
1681 assert( sizeof(u16)==2 );
1682 assert( sizeof(Pgno)==4 );
1683
1684 pBt = sqlite3MallocZero( sizeof(*pBt) );
1685 if( pBt==0 ){
1686 rc = SQLITE_NOMEM;
1687 goto btree_open_out;
1688 }
danielk197771d5d2c2008-09-29 11:49:47 +00001689 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
drh33f4e022007-09-03 15:19:34 +00001690 EXTRA_SIZE, flags, vfsFlags);
drhe53831d2007-08-17 01:14:38 +00001691 if( rc==SQLITE_OK ){
1692 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
1693 }
1694 if( rc!=SQLITE_OK ){
1695 goto btree_open_out;
1696 }
danielk19772a50ff02009-04-10 09:47:06 +00001697 pBt->db = db;
danielk19771ceedd32008-11-19 10:22:33 +00001698 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
drhe53831d2007-08-17 01:14:38 +00001699 p->pBt = pBt;
1700
drhe53831d2007-08-17 01:14:38 +00001701 sqlite3PagerSetReiniter(pBt->pPager, pageReinit);
1702 pBt->pCursor = 0;
1703 pBt->pPage1 = 0;
1704 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
1705 pBt->pageSize = get2byte(&zDbHeader[16]);
1706 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1707 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00001708 pBt->pageSize = 0;
drhe53831d2007-08-17 01:14:38 +00001709#ifndef SQLITE_OMIT_AUTOVACUUM
1710 /* If the magic name ":memory:" will create an in-memory database, then
1711 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
1712 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
1713 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
1714 ** regular file-name. In this case the auto-vacuum applies as per normal.
1715 */
1716 if( zFilename && !isMemdb ){
1717 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
1718 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
1719 }
1720#endif
1721 nReserve = 0;
1722 }else{
1723 nReserve = zDbHeader[20];
drhe53831d2007-08-17 01:14:38 +00001724 pBt->pageSizeFixed = 1;
1725#ifndef SQLITE_OMIT_AUTOVACUUM
1726 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1727 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
1728#endif
1729 }
drhfa9601a2009-06-18 17:22:39 +00001730 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhc0b61812009-04-30 01:22:41 +00001731 if( rc ) goto btree_open_out;
drhe53831d2007-08-17 01:14:38 +00001732 pBt->usableSize = pBt->pageSize - nReserve;
1733 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
drhe53831d2007-08-17 01:14:38 +00001734
1735#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1736 /* Add the new BtShared object to the linked list sharable BtShareds.
1737 */
1738 if( p->sharable ){
1739 sqlite3_mutex *mutexShared;
1740 pBt->nRef = 1;
danielk197759f8c082008-06-18 17:09:10 +00001741 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
danielk1977075c23a2008-09-01 18:34:20 +00001742 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
danielk197759f8c082008-06-18 17:09:10 +00001743 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
drh3285db22007-09-03 22:00:39 +00001744 if( pBt->mutex==0 ){
1745 rc = SQLITE_NOMEM;
drhe5fe6902007-12-07 18:55:28 +00001746 db->mallocFailed = 0;
drh3285db22007-09-03 22:00:39 +00001747 goto btree_open_out;
1748 }
drhff0587c2007-08-29 17:43:19 +00001749 }
drhe53831d2007-08-17 01:14:38 +00001750 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001751 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
1752 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
drhe53831d2007-08-17 01:14:38 +00001753 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00001754 }
drheee46cf2004-11-06 00:02:48 +00001755#endif
drh90f5ecb2004-07-22 01:19:35 +00001756 }
danielk1977aef0bf62005-12-30 16:28:01 +00001757
drhcfed7bc2006-03-13 14:28:05 +00001758#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001759 /* If the new Btree uses a sharable pBtShared, then link the new
1760 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00001761 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00001762 */
drhe53831d2007-08-17 01:14:38 +00001763 if( p->sharable ){
1764 int i;
1765 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00001766 for(i=0; i<db->nDb; i++){
1767 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00001768 while( pSib->pPrev ){ pSib = pSib->pPrev; }
1769 if( p->pBt<pSib->pBt ){
1770 p->pNext = pSib;
1771 p->pPrev = 0;
1772 pSib->pPrev = p;
1773 }else{
drhabddb0c2007-08-20 13:14:28 +00001774 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
drhe53831d2007-08-17 01:14:38 +00001775 pSib = pSib->pNext;
1776 }
1777 p->pNext = pSib->pNext;
1778 p->pPrev = pSib;
1779 if( p->pNext ){
1780 p->pNext->pPrev = p;
1781 }
1782 pSib->pNext = p;
1783 }
1784 break;
1785 }
1786 }
danielk1977aef0bf62005-12-30 16:28:01 +00001787 }
danielk1977aef0bf62005-12-30 16:28:01 +00001788#endif
1789 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00001790
1791btree_open_out:
1792 if( rc!=SQLITE_OK ){
1793 if( pBt && pBt->pPager ){
1794 sqlite3PagerClose(pBt->pPager);
1795 }
drh17435752007-08-16 04:30:38 +00001796 sqlite3_free(pBt);
1797 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00001798 *ppBtree = 0;
1799 }
drh7555d8e2009-03-20 13:15:30 +00001800 if( mutexOpen ){
1801 assert( sqlite3_mutex_held(mutexOpen) );
1802 sqlite3_mutex_leave(mutexOpen);
1803 }
danielk1977dddbcdc2007-04-26 14:42:34 +00001804 return rc;
drha059ad02001-04-17 20:09:11 +00001805}
1806
1807/*
drhe53831d2007-08-17 01:14:38 +00001808** Decrement the BtShared.nRef counter. When it reaches zero,
1809** remove the BtShared structure from the sharing list. Return
1810** true if the BtShared.nRef counter reaches zero and return
1811** false if it is still positive.
1812*/
1813static int removeFromSharingList(BtShared *pBt){
1814#ifndef SQLITE_OMIT_SHARED_CACHE
1815 sqlite3_mutex *pMaster;
1816 BtShared *pList;
1817 int removed = 0;
1818
drhd677b3d2007-08-20 22:48:41 +00001819 assert( sqlite3_mutex_notheld(pBt->mutex) );
danielk197759f8c082008-06-18 17:09:10 +00001820 pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhe53831d2007-08-17 01:14:38 +00001821 sqlite3_mutex_enter(pMaster);
1822 pBt->nRef--;
1823 if( pBt->nRef<=0 ){
drh78f82d12008-09-02 00:52:52 +00001824 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
1825 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
drhe53831d2007-08-17 01:14:38 +00001826 }else{
drh78f82d12008-09-02 00:52:52 +00001827 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
drh34004ce2008-07-11 16:15:17 +00001828 while( ALWAYS(pList) && pList->pNext!=pBt ){
drhe53831d2007-08-17 01:14:38 +00001829 pList=pList->pNext;
1830 }
drh34004ce2008-07-11 16:15:17 +00001831 if( ALWAYS(pList) ){
drhe53831d2007-08-17 01:14:38 +00001832 pList->pNext = pBt->pNext;
1833 }
1834 }
drh3285db22007-09-03 22:00:39 +00001835 if( SQLITE_THREADSAFE ){
1836 sqlite3_mutex_free(pBt->mutex);
1837 }
drhe53831d2007-08-17 01:14:38 +00001838 removed = 1;
1839 }
1840 sqlite3_mutex_leave(pMaster);
1841 return removed;
1842#else
1843 return 1;
1844#endif
1845}
1846
1847/*
drhf7141992008-06-19 00:16:08 +00001848** Make sure pBt->pTmpSpace points to an allocation of
1849** MX_CELL_SIZE(pBt) bytes.
1850*/
1851static void allocateTempSpace(BtShared *pBt){
1852 if( !pBt->pTmpSpace ){
1853 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
1854 }
1855}
1856
1857/*
1858** Free the pBt->pTmpSpace allocation
1859*/
1860static void freeTempSpace(BtShared *pBt){
1861 sqlite3PageFree( pBt->pTmpSpace);
1862 pBt->pTmpSpace = 0;
1863}
1864
1865/*
drha059ad02001-04-17 20:09:11 +00001866** Close an open database and invalidate all cursors.
1867*/
danielk1977aef0bf62005-12-30 16:28:01 +00001868int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00001869 BtShared *pBt = p->pBt;
1870 BtCursor *pCur;
1871
danielk1977aef0bf62005-12-30 16:28:01 +00001872 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00001873 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00001874 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001875 pCur = pBt->pCursor;
1876 while( pCur ){
1877 BtCursor *pTmp = pCur;
1878 pCur = pCur->pNext;
1879 if( pTmp->pBtree==p ){
1880 sqlite3BtreeCloseCursor(pTmp);
1881 }
drha059ad02001-04-17 20:09:11 +00001882 }
danielk1977aef0bf62005-12-30 16:28:01 +00001883
danielk19778d34dfd2006-01-24 16:37:57 +00001884 /* Rollback any active transaction and free the handle structure.
1885 ** The call to sqlite3BtreeRollback() drops any table-locks held by
1886 ** this handle.
1887 */
danielk1977b597f742006-01-15 11:39:18 +00001888 sqlite3BtreeRollback(p);
drhe53831d2007-08-17 01:14:38 +00001889 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001890
danielk1977aef0bf62005-12-30 16:28:01 +00001891 /* If there are still other outstanding references to the shared-btree
1892 ** structure, return now. The remainder of this procedure cleans
1893 ** up the shared-btree.
1894 */
drhe53831d2007-08-17 01:14:38 +00001895 assert( p->wantToLock==0 && p->locked==0 );
1896 if( !p->sharable || removeFromSharingList(pBt) ){
1897 /* The pBt is no longer on the sharing list, so we can access
1898 ** it without having to hold the mutex.
1899 **
1900 ** Clean out and delete the BtShared object.
1901 */
1902 assert( !pBt->pCursor );
drhe53831d2007-08-17 01:14:38 +00001903 sqlite3PagerClose(pBt->pPager);
1904 if( pBt->xFreeSchema && pBt->pSchema ){
1905 pBt->xFreeSchema(pBt->pSchema);
1906 }
1907 sqlite3_free(pBt->pSchema);
drhf7141992008-06-19 00:16:08 +00001908 freeTempSpace(pBt);
drh65bbf292008-06-19 01:03:17 +00001909 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00001910 }
1911
drhe53831d2007-08-17 01:14:38 +00001912#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00001913 assert( p->wantToLock==0 );
1914 assert( p->locked==0 );
1915 if( p->pPrev ) p->pPrev->pNext = p->pNext;
1916 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00001917#endif
1918
drhe53831d2007-08-17 01:14:38 +00001919 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00001920 return SQLITE_OK;
1921}
1922
1923/*
drhda47d772002-12-02 04:25:19 +00001924** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001925**
1926** The maximum number of cache pages is set to the absolute
1927** value of mxPage. If mxPage is negative, the pager will
1928** operate asynchronously - it will not stop to do fsync()s
1929** to insure data is written to the disk surface before
1930** continuing. Transactions still work if synchronous is off,
1931** and the database cannot be corrupted if this program
1932** crashes. But if the operating system crashes or there is
1933** an abrupt power failure when synchronous is off, the database
1934** could be left in an inconsistent and unrecoverable state.
1935** Synchronous is on by default so database corruption is not
1936** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00001937*/
danielk1977aef0bf62005-12-30 16:28:01 +00001938int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
1939 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001940 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001941 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001942 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00001943 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00001944 return SQLITE_OK;
1945}
1946
1947/*
drh973b6e32003-02-12 14:09:42 +00001948** Change the way data is synced to disk in order to increase or decrease
1949** how well the database resists damage due to OS crashes and power
1950** failures. Level 1 is the same as asynchronous (no syncs() occur and
1951** there is a high probability of damage) Level 2 is the default. There
1952** is a very low but non-zero probability of damage. Level 3 reduces the
1953** probability of damage to near zero but with a write performance reduction.
1954*/
danielk197793758c82005-01-21 08:13:14 +00001955#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drhac530b12006-02-11 01:25:50 +00001956int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
danielk1977aef0bf62005-12-30 16:28:01 +00001957 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00001958 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001959 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00001960 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
drhd677b3d2007-08-20 22:48:41 +00001961 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00001962 return SQLITE_OK;
1963}
danielk197793758c82005-01-21 08:13:14 +00001964#endif
drh973b6e32003-02-12 14:09:42 +00001965
drh2c8997b2005-08-27 16:36:48 +00001966/*
1967** Return TRUE if the given btree is set to safety level 1. In other
1968** words, return TRUE if no sync() occurs on the disk files.
1969*/
danielk1977aef0bf62005-12-30 16:28:01 +00001970int sqlite3BtreeSyncDisabled(Btree *p){
1971 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00001972 int rc;
drhe5fe6902007-12-07 18:55:28 +00001973 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00001974 sqlite3BtreeEnter(p);
drhd0679ed2007-08-28 22:24:34 +00001975 assert( pBt && pBt->pPager );
drhd677b3d2007-08-20 22:48:41 +00001976 rc = sqlite3PagerNosync(pBt->pPager);
1977 sqlite3BtreeLeave(p);
1978 return rc;
drh2c8997b2005-08-27 16:36:48 +00001979}
1980
danielk1977576ec6b2005-01-21 11:55:25 +00001981#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00001982/*
drh90f5ecb2004-07-22 01:19:35 +00001983** Change the default pages size and the number of reserved bytes per page.
drhce4869f2009-04-02 20:16:58 +00001984** Or, if the page size has already been fixed, return SQLITE_READONLY
1985** without changing anything.
drh06f50212004-11-02 14:24:33 +00001986**
1987** The page size must be a power of 2 between 512 and 65536. If the page
1988** size supplied does not meet this constraint then the page size is not
1989** changed.
1990**
1991** Page sizes are constrained to be a power of two so that the region
1992** of the database file used for locking (beginning at PENDING_BYTE,
1993** the first byte past the 1GB boundary, 0x40000000) needs to occur
1994** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00001995**
1996** If parameter nReserve is less than zero, then the number of reserved
1997** bytes per page is left unchanged.
drhce4869f2009-04-02 20:16:58 +00001998**
1999** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
2000** and autovacuum mode can no longer be changed.
drh90f5ecb2004-07-22 01:19:35 +00002001*/
drhce4869f2009-04-02 20:16:58 +00002002int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
danielk1977a1644fd2007-08-29 12:31:25 +00002003 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002004 BtShared *pBt = p->pBt;
drhf49661a2008-12-10 16:45:50 +00002005 assert( nReserve>=-1 && nReserve<=255 );
drhd677b3d2007-08-20 22:48:41 +00002006 sqlite3BtreeEnter(p);
drh90f5ecb2004-07-22 01:19:35 +00002007 if( pBt->pageSizeFixed ){
drhd677b3d2007-08-20 22:48:41 +00002008 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00002009 return SQLITE_READONLY;
2010 }
2011 if( nReserve<0 ){
2012 nReserve = pBt->pageSize - pBt->usableSize;
2013 }
drhf49661a2008-12-10 16:45:50 +00002014 assert( nReserve>=0 && nReserve<=255 );
drh06f50212004-11-02 14:24:33 +00002015 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2016 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00002017 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002018 assert( !pBt->pPage1 && !pBt->pCursor );
drh1bd10f82008-12-10 21:19:56 +00002019 pBt->pageSize = (u16)pageSize;
drhf7141992008-06-19 00:16:08 +00002020 freeTempSpace(pBt);
drh90f5ecb2004-07-22 01:19:35 +00002021 }
drhfa9601a2009-06-18 17:22:39 +00002022 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhf49661a2008-12-10 16:45:50 +00002023 pBt->usableSize = pBt->pageSize - (u16)nReserve;
drhce4869f2009-04-02 20:16:58 +00002024 if( iFix ) pBt->pageSizeFixed = 1;
drhd677b3d2007-08-20 22:48:41 +00002025 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00002026 return rc;
drh90f5ecb2004-07-22 01:19:35 +00002027}
2028
2029/*
2030** Return the currently defined page size
2031*/
danielk1977aef0bf62005-12-30 16:28:01 +00002032int sqlite3BtreeGetPageSize(Btree *p){
2033 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00002034}
drh7f751222009-03-17 22:33:00 +00002035
2036/*
2037** Return the number of bytes of space at the end of every page that
2038** are intentually left unused. This is the "reserved" space that is
2039** sometimes used by extensions.
2040*/
danielk1977aef0bf62005-12-30 16:28:01 +00002041int sqlite3BtreeGetReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002042 int n;
2043 sqlite3BtreeEnter(p);
2044 n = p->pBt->pageSize - p->pBt->usableSize;
2045 sqlite3BtreeLeave(p);
2046 return n;
drh2011d5f2004-07-22 02:40:37 +00002047}
drhf8e632b2007-05-08 14:51:36 +00002048
2049/*
2050** Set the maximum page count for a database if mxPage is positive.
2051** No changes are made if mxPage is 0 or negative.
2052** Regardless of the value of mxPage, return the maximum page count.
2053*/
2054int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00002055 int n;
2056 sqlite3BtreeEnter(p);
2057 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
2058 sqlite3BtreeLeave(p);
2059 return n;
drhf8e632b2007-05-08 14:51:36 +00002060}
danielk1977576ec6b2005-01-21 11:55:25 +00002061#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00002062
2063/*
danielk1977951af802004-11-05 15:45:09 +00002064** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
2065** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
2066** is disabled. The default value for the auto-vacuum property is
2067** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
2068*/
danielk1977aef0bf62005-12-30 16:28:01 +00002069int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00002070#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002071 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00002072#else
danielk1977dddbcdc2007-04-26 14:42:34 +00002073 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002074 int rc = SQLITE_OK;
drh076d4662009-02-18 20:31:18 +00002075 u8 av = (u8)autoVacuum;
drhd677b3d2007-08-20 22:48:41 +00002076
2077 sqlite3BtreeEnter(p);
drh076d4662009-02-18 20:31:18 +00002078 if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002079 rc = SQLITE_READONLY;
2080 }else{
drh076d4662009-02-18 20:31:18 +00002081 pBt->autoVacuum = av ?1:0;
2082 pBt->incrVacuum = av==2 ?1:0;
danielk1977951af802004-11-05 15:45:09 +00002083 }
drhd677b3d2007-08-20 22:48:41 +00002084 sqlite3BtreeLeave(p);
2085 return rc;
danielk1977951af802004-11-05 15:45:09 +00002086#endif
2087}
2088
2089/*
2090** Return the value of the 'auto-vacuum' property. If auto-vacuum is
2091** enabled 1 is returned. Otherwise 0.
2092*/
danielk1977aef0bf62005-12-30 16:28:01 +00002093int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00002094#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002095 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00002096#else
drhd677b3d2007-08-20 22:48:41 +00002097 int rc;
2098 sqlite3BtreeEnter(p);
2099 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00002100 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
2101 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
2102 BTREE_AUTOVACUUM_INCR
2103 );
drhd677b3d2007-08-20 22:48:41 +00002104 sqlite3BtreeLeave(p);
2105 return rc;
danielk1977951af802004-11-05 15:45:09 +00002106#endif
2107}
2108
2109
2110/*
drha34b6762004-05-07 13:30:42 +00002111** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00002112** also acquire a readlock on that file.
2113**
2114** SQLITE_OK is returned on success. If the file is not a
2115** well-formed database file, then SQLITE_CORRUPT is returned.
2116** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00002117** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00002118*/
danielk1977aef0bf62005-12-30 16:28:01 +00002119static int lockBtree(BtShared *pBt){
danielk1977f653d782008-03-20 11:04:21 +00002120 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002121 MemPage *pPage1;
danielk197793f7af92008-05-09 16:57:50 +00002122 int nPage;
drhd677b3d2007-08-20 22:48:41 +00002123
drh1fee73e2007-08-29 04:00:57 +00002124 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977295dc102009-04-01 19:07:03 +00002125 assert( pBt->pPage1==0 );
drh16a9b832007-05-05 18:39:25 +00002126 rc = sqlite3BtreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00002127 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00002128
2129 /* Do some checking to help insure the file we opened really is
2130 ** a valid database file.
2131 */
danielk1977ad0132d2008-06-07 08:58:22 +00002132 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
2133 if( rc!=SQLITE_OK ){
danielk197793f7af92008-05-09 16:57:50 +00002134 goto page1_init_failed;
2135 }else if( nPage>0 ){
danielk1977f653d782008-03-20 11:04:21 +00002136 int pageSize;
2137 int usableSize;
drhb6f41482004-05-14 01:58:11 +00002138 u8 *page1 = pPage1->aData;
danielk1977ad0132d2008-06-07 08:58:22 +00002139 rc = SQLITE_NOTADB;
drhb6f41482004-05-14 01:58:11 +00002140 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00002141 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00002142 }
drh309169a2007-04-24 17:27:51 +00002143 if( page1[18]>1 ){
2144 pBt->readOnly = 1;
2145 }
2146 if( page1[19]>1 ){
drhb6f41482004-05-14 01:58:11 +00002147 goto page1_init_failed;
2148 }
drhe5ae5732008-06-15 02:51:47 +00002149
2150 /* The maximum embedded fraction must be exactly 25%. And the minimum
2151 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
2152 ** The original design allowed these amounts to vary, but as of
2153 ** version 3.6.0, we require them to be fixed.
2154 */
2155 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
2156 goto page1_init_failed;
2157 }
drh07d183d2005-05-01 22:52:42 +00002158 pageSize = get2byte(&page1[16]);
drh7dc385e2007-09-06 23:39:36 +00002159 if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
2160 (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
2161 ){
drh07d183d2005-05-01 22:52:42 +00002162 goto page1_init_failed;
2163 }
2164 assert( (pageSize & 7)==0 );
danielk1977f653d782008-03-20 11:04:21 +00002165 usableSize = pageSize - page1[20];
2166 if( pageSize!=pBt->pageSize ){
2167 /* After reading the first page of the database assuming a page size
2168 ** of BtShared.pageSize, we have discovered that the page-size is
2169 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
2170 ** zero and return SQLITE_OK. The caller will call this function
2171 ** again with the correct page-size.
2172 */
2173 releasePage(pPage1);
drhf49661a2008-12-10 16:45:50 +00002174 pBt->usableSize = (u16)usableSize;
2175 pBt->pageSize = (u16)pageSize;
drhf7141992008-06-19 00:16:08 +00002176 freeTempSpace(pBt);
drhfa9601a2009-06-18 17:22:39 +00002177 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
2178 pageSize-usableSize);
drhc0b61812009-04-30 01:22:41 +00002179 if( rc ) goto page1_init_failed;
danielk1977f653d782008-03-20 11:04:21 +00002180 return SQLITE_OK;
2181 }
drhb33e1b92009-06-18 11:29:20 +00002182 if( usableSize<480 ){
drhb6f41482004-05-14 01:58:11 +00002183 goto page1_init_failed;
2184 }
drh1bd10f82008-12-10 21:19:56 +00002185 pBt->pageSize = (u16)pageSize;
2186 pBt->usableSize = (u16)usableSize;
drh057cd3a2005-02-15 16:23:02 +00002187#ifndef SQLITE_OMIT_AUTOVACUUM
2188 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00002189 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00002190#endif
drh306dc212001-05-21 13:45:10 +00002191 }
drhb6f41482004-05-14 01:58:11 +00002192
2193 /* maxLocal is the maximum amount of payload to store locally for
2194 ** a cell. Make sure it is small enough so that at least minFanout
2195 ** cells can will fit on one page. We assume a 10-byte page header.
2196 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00002197 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00002198 ** 4-byte child pointer
2199 ** 9-byte nKey value
2200 ** 4-byte nData value
2201 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00002202 ** So a cell consists of a 2-byte poiner, a header which is as much as
2203 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
2204 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00002205 */
drhe5ae5732008-06-15 02:51:47 +00002206 pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
2207 pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
drh43605152004-05-29 21:46:49 +00002208 pBt->maxLeaf = pBt->usableSize - 35;
drhe5ae5732008-06-15 02:51:47 +00002209 pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
drh2e38c322004-09-03 18:38:44 +00002210 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00002211 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00002212 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00002213
drh72f82862001-05-24 21:06:34 +00002214page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00002215 releasePage(pPage1);
2216 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00002217 return rc;
drh306dc212001-05-21 13:45:10 +00002218}
2219
2220/*
drhb8ef32c2005-03-14 02:01:49 +00002221** This routine works like lockBtree() except that it also invokes the
2222** busy callback if there is lock contention.
2223*/
danielk1977aef0bf62005-12-30 16:28:01 +00002224static int lockBtreeWithRetry(Btree *pRef){
drhb8ef32c2005-03-14 02:01:49 +00002225 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00002226
drh1fee73e2007-08-29 04:00:57 +00002227 assert( sqlite3BtreeHoldsMutex(pRef) );
danielk1977aef0bf62005-12-30 16:28:01 +00002228 if( pRef->inTrans==TRANS_NONE ){
2229 u8 inTransaction = pRef->pBt->inTransaction;
2230 btreeIntegrity(pRef);
2231 rc = sqlite3BtreeBeginTrans(pRef, 0);
2232 pRef->pBt->inTransaction = inTransaction;
2233 pRef->inTrans = TRANS_NONE;
2234 if( rc==SQLITE_OK ){
2235 pRef->pBt->nTransaction--;
2236 }
2237 btreeIntegrity(pRef);
drhb8ef32c2005-03-14 02:01:49 +00002238 }
2239 return rc;
2240}
2241
2242
2243/*
drhb8ca3072001-12-05 00:21:20 +00002244** If there are no outstanding cursors and we are not in the middle
2245** of a transaction but there is a read lock on the database, then
2246** this routine unrefs the first page of the database file which
2247** has the effect of releasing the read lock.
2248**
2249** If there are any outstanding cursors, this routine is a no-op.
2250**
2251** If there is a transaction in progress, this routine is a no-op.
2252*/
danielk1977aef0bf62005-12-30 16:28:01 +00002253static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00002254 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00002255 if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){
danielk1977c1761e82009-06-25 09:40:03 +00002256 assert( pBt->pPage1->aData );
2257 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
2258 assert( pBt->pPage1->aData );
2259 releasePage(pBt->pPage1);
drh3aac2dd2004-04-26 14:10:20 +00002260 pBt->pPage1 = 0;
drhb8ca3072001-12-05 00:21:20 +00002261 }
2262}
2263
2264/*
drh9e572e62004-04-23 23:43:10 +00002265** Create a new database by initializing the first page of the
drh8c42ca92001-06-22 19:15:00 +00002266** file.
drh8b2f49b2001-06-08 00:21:52 +00002267*/
danielk1977aef0bf62005-12-30 16:28:01 +00002268static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00002269 MemPage *pP1;
2270 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00002271 int rc;
danielk1977ad0132d2008-06-07 08:58:22 +00002272 int nPage;
drhd677b3d2007-08-20 22:48:41 +00002273
drh1fee73e2007-08-29 04:00:57 +00002274 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977ad0132d2008-06-07 08:58:22 +00002275 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
2276 if( rc!=SQLITE_OK || nPage>0 ){
2277 return rc;
2278 }
drh3aac2dd2004-04-26 14:10:20 +00002279 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00002280 assert( pP1!=0 );
2281 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00002282 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00002283 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00002284 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
2285 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00002286 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00002287 data[18] = 1;
2288 data[19] = 1;
drhf49661a2008-12-10 16:45:50 +00002289 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
2290 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
drhe5ae5732008-06-15 02:51:47 +00002291 data[21] = 64;
2292 data[22] = 32;
2293 data[23] = 32;
drhb6f41482004-05-14 01:58:11 +00002294 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00002295 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00002296 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00002297#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002298 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00002299 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00002300 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00002301 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00002302#endif
drh8b2f49b2001-06-08 00:21:52 +00002303 return SQLITE_OK;
2304}
2305
2306/*
danielk1977ee5741e2004-05-31 10:01:34 +00002307** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00002308** is started if the second argument is nonzero, otherwise a read-
2309** transaction. If the second argument is 2 or more and exclusive
2310** transaction is started, meaning that no other process is allowed
2311** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00002312** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00002313** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00002314**
danielk1977ee5741e2004-05-31 10:01:34 +00002315** A write-transaction must be started before attempting any
2316** changes to the database. None of the following routines
2317** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00002318**
drh23e11ca2004-05-04 17:27:28 +00002319** sqlite3BtreeCreateTable()
2320** sqlite3BtreeCreateIndex()
2321** sqlite3BtreeClearTable()
2322** sqlite3BtreeDropTable()
2323** sqlite3BtreeInsert()
2324** sqlite3BtreeDelete()
2325** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00002326**
drhb8ef32c2005-03-14 02:01:49 +00002327** If an initial attempt to acquire the lock fails because of lock contention
2328** and the database was previously unlocked, then invoke the busy handler
2329** if there is one. But if there was previously a read-lock, do not
2330** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
2331** returned when there is already a read-lock in order to avoid a deadlock.
2332**
2333** Suppose there are two processes A and B. A has a read lock and B has
2334** a reserved lock. B tries to promote to exclusive but is blocked because
2335** of A's read lock. A tries to promote to reserved but is blocked by B.
2336** One or the other of the two processes must give way or there can be
2337** no progress. By returning SQLITE_BUSY and not invoking the busy callback
2338** when A already has a read lock, we encourage A to give up and let B
2339** proceed.
drha059ad02001-04-17 20:09:11 +00002340*/
danielk1977aef0bf62005-12-30 16:28:01 +00002341int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
danielk1977404ca072009-03-16 13:19:36 +00002342 sqlite3 *pBlock = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00002343 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00002344 int rc = SQLITE_OK;
2345
drhd677b3d2007-08-20 22:48:41 +00002346 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002347 btreeIntegrity(p);
2348
danielk1977ee5741e2004-05-31 10:01:34 +00002349 /* If the btree is already in a write-transaction, or it
2350 ** is already in a read-transaction and a read-transaction
2351 ** is requested, this is a no-op.
2352 */
danielk1977aef0bf62005-12-30 16:28:01 +00002353 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00002354 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002355 }
drhb8ef32c2005-03-14 02:01:49 +00002356
2357 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00002358 if( pBt->readOnly && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00002359 rc = SQLITE_READONLY;
2360 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002361 }
2362
danielk1977404ca072009-03-16 13:19:36 +00002363#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +00002364 /* If another database handle has already opened a write transaction
2365 ** on this shared-btree structure and a second write transaction is
danielk1977404ca072009-03-16 13:19:36 +00002366 ** requested, return SQLITE_LOCKED.
danielk1977aef0bf62005-12-30 16:28:01 +00002367 */
danielk1977404ca072009-03-16 13:19:36 +00002368 if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
2369 pBlock = pBt->pWriter->db;
2370 }else if( wrflag>1 ){
danielk1977641b0f42007-12-21 04:47:25 +00002371 BtLock *pIter;
2372 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
2373 if( pIter->pBtree!=p ){
danielk1977404ca072009-03-16 13:19:36 +00002374 pBlock = pIter->pBtree->db;
2375 break;
danielk1977641b0f42007-12-21 04:47:25 +00002376 }
2377 }
2378 }
danielk1977404ca072009-03-16 13:19:36 +00002379 if( pBlock ){
2380 sqlite3ConnectionBlocked(p->db, pBlock);
2381 rc = SQLITE_LOCKED_SHAREDCACHE;
2382 goto trans_begun;
2383 }
danielk1977641b0f42007-12-21 04:47:25 +00002384#endif
2385
danielk1977602b4662009-07-02 07:47:33 +00002386 /* Any read-only or read-write transaction implies a read-lock on
2387 ** page 1. So if some other shared-cache client already has a write-lock
2388 ** on page 1, the transaction cannot be opened. */
2389 if( SQLITE_OK!=(rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK)) ){
2390 goto trans_begun;
2391 }
2392
drhb8ef32c2005-03-14 02:01:49 +00002393 do {
danielk1977295dc102009-04-01 19:07:03 +00002394 /* Call lockBtree() until either pBt->pPage1 is populated or
2395 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
2396 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
2397 ** reading page 1 it discovers that the page-size of the database
2398 ** file is not pBt->pageSize. In this case lockBtree() will update
2399 ** pBt->pageSize to the page-size of the file on disk.
2400 */
2401 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
drh309169a2007-04-24 17:27:51 +00002402
drhb8ef32c2005-03-14 02:01:49 +00002403 if( rc==SQLITE_OK && wrflag ){
drh309169a2007-04-24 17:27:51 +00002404 if( pBt->readOnly ){
2405 rc = SQLITE_READONLY;
2406 }else{
danielk1977d8293352009-04-30 09:10:37 +00002407 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
drh309169a2007-04-24 17:27:51 +00002408 if( rc==SQLITE_OK ){
2409 rc = newDatabase(pBt);
2410 }
drhb8ef32c2005-03-14 02:01:49 +00002411 }
2412 }
2413
danielk1977bd434552009-03-18 10:33:00 +00002414 if( rc!=SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00002415 unlockBtreeIfUnused(pBt);
2416 }
danielk1977aef0bf62005-12-30 16:28:01 +00002417 }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
danielk19771ceedd32008-11-19 10:22:33 +00002418 btreeInvokeBusyHandler(pBt) );
danielk1977aef0bf62005-12-30 16:28:01 +00002419
2420 if( rc==SQLITE_OK ){
2421 if( p->inTrans==TRANS_NONE ){
2422 pBt->nTransaction++;
danielk1977602b4662009-07-02 07:47:33 +00002423#ifndef SQLITE_OMIT_SHARED_CACHE
2424 if( p->sharable ){
2425 assert( p->lock.pBtree==p && p->lock.iTable==1 );
2426 p->lock.eLock = READ_LOCK;
2427 p->lock.pNext = pBt->pLock;
2428 pBt->pLock = &p->lock;
2429 }
2430#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002431 }
2432 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
2433 if( p->inTrans>pBt->inTransaction ){
2434 pBt->inTransaction = p->inTrans;
2435 }
danielk1977641b0f42007-12-21 04:47:25 +00002436#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977404ca072009-03-16 13:19:36 +00002437 if( wrflag ){
2438 assert( !pBt->pWriter );
2439 pBt->pWriter = p;
shaneca18d202009-03-23 02:34:32 +00002440 pBt->isExclusive = (u8)(wrflag>1);
danielk1977641b0f42007-12-21 04:47:25 +00002441 }
2442#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002443 }
2444
drhd677b3d2007-08-20 22:48:41 +00002445
2446trans_begun:
danielk1977fd7f0452008-12-17 17:30:26 +00002447 if( rc==SQLITE_OK && wrflag ){
danielk197712dd5492008-12-18 15:45:07 +00002448 /* This call makes sure that the pager has the correct number of
2449 ** open savepoints. If the second parameter is greater than 0 and
2450 ** the sub-journal is not already open, then it will be opened here.
2451 */
danielk1977fd7f0452008-12-17 17:30:26 +00002452 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
2453 }
danielk197712dd5492008-12-18 15:45:07 +00002454
danielk1977aef0bf62005-12-30 16:28:01 +00002455 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002456 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00002457 return rc;
drha059ad02001-04-17 20:09:11 +00002458}
2459
danielk1977687566d2004-11-02 12:56:41 +00002460#ifndef SQLITE_OMIT_AUTOVACUUM
2461
2462/*
2463** Set the pointer-map entries for all children of page pPage. Also, if
2464** pPage contains cells that point to overflow pages, set the pointer
2465** map entries for the overflow pages as well.
2466*/
2467static int setChildPtrmaps(MemPage *pPage){
2468 int i; /* Counter variable */
2469 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00002470 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00002471 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00002472 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002473 Pgno pgno = pPage->pgno;
2474
drh1fee73e2007-08-29 04:00:57 +00002475 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197771d5d2c2008-09-29 11:49:47 +00002476 rc = sqlite3BtreeInitPage(pPage);
danielk19772df71c72007-05-24 07:22:42 +00002477 if( rc!=SQLITE_OK ){
2478 goto set_child_ptrmaps_out;
2479 }
danielk1977687566d2004-11-02 12:56:41 +00002480 nCell = pPage->nCell;
2481
2482 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002483 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002484
danielk197726836652005-01-17 01:33:13 +00002485 rc = ptrmapPutOvflPtr(pPage, pCell);
2486 if( rc!=SQLITE_OK ){
2487 goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002488 }
danielk197726836652005-01-17 01:33:13 +00002489
danielk1977687566d2004-11-02 12:56:41 +00002490 if( !pPage->leaf ){
2491 Pgno childPgno = get4byte(pCell);
2492 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
danielk197700a696d2008-09-29 16:41:31 +00002493 if( rc!=SQLITE_OK ) goto set_child_ptrmaps_out;
danielk1977687566d2004-11-02 12:56:41 +00002494 }
2495 }
2496
2497 if( !pPage->leaf ){
2498 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
2499 rc = ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno);
2500 }
2501
2502set_child_ptrmaps_out:
2503 pPage->isInit = isInitOrig;
2504 return rc;
2505}
2506
2507/*
danielk1977fa542f12009-04-02 18:28:08 +00002508** Somewhere on pPage, which is guaranteed to be a btree page, not an overflow
danielk1977687566d2004-11-02 12:56:41 +00002509** page, is a pointer to page iFrom. Modify this pointer so that it points to
2510** iTo. Parameter eType describes the type of pointer to be modified, as
2511** follows:
2512**
2513** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
2514** page of pPage.
2515**
2516** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
2517** page pointed to by one of the cells on pPage.
2518**
2519** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
2520** overflow page in the list.
2521*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00002522static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00002523 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00002524 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977687566d2004-11-02 12:56:41 +00002525 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00002526 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00002527 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00002528 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002529 }
danielk1977f78fc082004-11-02 14:40:32 +00002530 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00002531 }else{
drhf49661a2008-12-10 16:45:50 +00002532 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002533 int i;
2534 int nCell;
2535
danielk197771d5d2c2008-09-29 11:49:47 +00002536 sqlite3BtreeInitPage(pPage);
danielk1977687566d2004-11-02 12:56:41 +00002537 nCell = pPage->nCell;
2538
danielk1977687566d2004-11-02 12:56:41 +00002539 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002540 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002541 if( eType==PTRMAP_OVERFLOW1 ){
2542 CellInfo info;
drh16a9b832007-05-05 18:39:25 +00002543 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
danielk1977687566d2004-11-02 12:56:41 +00002544 if( info.iOverflow ){
2545 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
2546 put4byte(&pCell[info.iOverflow], iTo);
2547 break;
2548 }
2549 }
2550 }else{
2551 if( get4byte(pCell)==iFrom ){
2552 put4byte(pCell, iTo);
2553 break;
2554 }
2555 }
2556 }
2557
2558 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00002559 if( eType!=PTRMAP_BTREE ||
2560 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00002561 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002562 }
danielk1977687566d2004-11-02 12:56:41 +00002563 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
2564 }
2565
2566 pPage->isInit = isInitOrig;
2567 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002568 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002569}
2570
danielk1977003ba062004-11-04 02:57:33 +00002571
danielk19777701e812005-01-10 12:59:51 +00002572/*
2573** Move the open database page pDbPage to location iFreePage in the
2574** database. The pDbPage reference remains valid.
2575*/
danielk1977003ba062004-11-04 02:57:33 +00002576static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00002577 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00002578 MemPage *pDbPage, /* Open page to move */
2579 u8 eType, /* Pointer map 'type' entry for pDbPage */
2580 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
danielk19774c999992008-07-16 18:17:55 +00002581 Pgno iFreePage, /* The location to move pDbPage to */
2582 int isCommit
danielk1977003ba062004-11-04 02:57:33 +00002583){
2584 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
2585 Pgno iDbPage = pDbPage->pgno;
2586 Pager *pPager = pBt->pPager;
2587 int rc;
2588
danielk1977a0bf2652004-11-04 14:30:04 +00002589 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
2590 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00002591 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00002592 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00002593
drh85b623f2007-12-13 21:54:09 +00002594 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00002595 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
2596 iDbPage, iFreePage, iPtrPage, eType));
danielk19774c999992008-07-16 18:17:55 +00002597 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
danielk1977003ba062004-11-04 02:57:33 +00002598 if( rc!=SQLITE_OK ){
2599 return rc;
2600 }
2601 pDbPage->pgno = iFreePage;
2602
2603 /* If pDbPage was a btree-page, then it may have child pages and/or cells
2604 ** that point to overflow pages. The pointer map entries for all these
2605 ** pages need to be changed.
2606 **
2607 ** If pDbPage is an overflow page, then the first 4 bytes may store a
2608 ** pointer to a subsequent overflow page. If this is the case, then
2609 ** the pointer map needs to be updated for the subsequent overflow page.
2610 */
danielk1977a0bf2652004-11-04 14:30:04 +00002611 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00002612 rc = setChildPtrmaps(pDbPage);
2613 if( rc!=SQLITE_OK ){
2614 return rc;
2615 }
2616 }else{
2617 Pgno nextOvfl = get4byte(pDbPage->aData);
2618 if( nextOvfl!=0 ){
danielk1977003ba062004-11-04 02:57:33 +00002619 rc = ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage);
2620 if( rc!=SQLITE_OK ){
2621 return rc;
2622 }
2623 }
2624 }
2625
2626 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
2627 ** that it points at iFreePage. Also fix the pointer map entry for
2628 ** iPtrPage.
2629 */
danielk1977a0bf2652004-11-04 14:30:04 +00002630 if( eType!=PTRMAP_ROOTPAGE ){
drh16a9b832007-05-05 18:39:25 +00002631 rc = sqlite3BtreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00002632 if( rc!=SQLITE_OK ){
2633 return rc;
2634 }
danielk19773b8a05f2007-03-19 17:44:26 +00002635 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00002636 if( rc!=SQLITE_OK ){
2637 releasePage(pPtrPage);
2638 return rc;
2639 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002640 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00002641 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00002642 if( rc==SQLITE_OK ){
2643 rc = ptrmapPut(pBt, iFreePage, eType, iPtrPage);
2644 }
danielk1977003ba062004-11-04 02:57:33 +00002645 }
danielk1977003ba062004-11-04 02:57:33 +00002646 return rc;
2647}
2648
danielk1977dddbcdc2007-04-26 14:42:34 +00002649/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00002650static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00002651
2652/*
danielk1977dddbcdc2007-04-26 14:42:34 +00002653** Perform a single step of an incremental-vacuum. If successful,
2654** return SQLITE_OK. If there is no work to do (and therefore no
2655** point in calling this function again), return SQLITE_DONE.
2656**
2657** More specificly, this function attempts to re-organize the
2658** database so that the last page of the file currently in use
2659** is no longer in use.
2660**
2661** If the nFin parameter is non-zero, the implementation assumes
2662** that the caller will keep calling incrVacuumStep() until
2663** it returns SQLITE_DONE or an error, and that nFin is the
2664** number of pages the database file will contain after this
2665** process is complete.
2666*/
danielk19773460d192008-12-27 15:23:13 +00002667static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
danielk1977dddbcdc2007-04-26 14:42:34 +00002668 Pgno nFreeList; /* Number of pages still on the free-list */
2669
drh1fee73e2007-08-29 04:00:57 +00002670 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977fa542f12009-04-02 18:28:08 +00002671 assert( iLastPg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00002672
2673 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
2674 int rc;
2675 u8 eType;
2676 Pgno iPtrPage;
2677
2678 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977fa542f12009-04-02 18:28:08 +00002679 if( nFreeList==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00002680 return SQLITE_DONE;
2681 }
2682
2683 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
2684 if( rc!=SQLITE_OK ){
2685 return rc;
2686 }
2687 if( eType==PTRMAP_ROOTPAGE ){
2688 return SQLITE_CORRUPT_BKPT;
2689 }
2690
2691 if( eType==PTRMAP_FREEPAGE ){
2692 if( nFin==0 ){
2693 /* Remove the page from the files free-list. This is not required
danielk19774ef24492007-05-23 09:52:41 +00002694 ** if nFin is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00002695 ** truncated to zero after this function returns, so it doesn't
2696 ** matter if it still contains some garbage entries.
2697 */
2698 Pgno iFreePg;
2699 MemPage *pFreePg;
2700 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
2701 if( rc!=SQLITE_OK ){
2702 return rc;
2703 }
2704 assert( iFreePg==iLastPg );
2705 releasePage(pFreePg);
2706 }
2707 } else {
2708 Pgno iFreePg; /* Index of free page to move pLastPg to */
2709 MemPage *pLastPg;
2710
drh16a9b832007-05-05 18:39:25 +00002711 rc = sqlite3BtreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002712 if( rc!=SQLITE_OK ){
2713 return rc;
2714 }
2715
danielk1977b4626a32007-04-28 15:47:43 +00002716 /* If nFin is zero, this loop runs exactly once and page pLastPg
2717 ** is swapped with the first free page pulled off the free list.
2718 **
2719 ** On the other hand, if nFin is greater than zero, then keep
2720 ** looping until a free-page located within the first nFin pages
2721 ** of the file is found.
2722 */
danielk1977dddbcdc2007-04-26 14:42:34 +00002723 do {
2724 MemPage *pFreePg;
2725 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
2726 if( rc!=SQLITE_OK ){
2727 releasePage(pLastPg);
2728 return rc;
2729 }
2730 releasePage(pFreePg);
2731 }while( nFin!=0 && iFreePg>nFin );
2732 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00002733
2734 rc = sqlite3PagerWrite(pLastPg->pDbPage);
danielk1977662278e2007-11-05 15:30:12 +00002735 if( rc==SQLITE_OK ){
danielk19774c999992008-07-16 18:17:55 +00002736 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
danielk1977662278e2007-11-05 15:30:12 +00002737 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002738 releasePage(pLastPg);
2739 if( rc!=SQLITE_OK ){
2740 return rc;
danielk1977662278e2007-11-05 15:30:12 +00002741 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002742 }
2743 }
2744
danielk19773460d192008-12-27 15:23:13 +00002745 if( nFin==0 ){
2746 iLastPg--;
2747 while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
danielk1977f4027782009-03-30 18:50:04 +00002748 if( PTRMAP_ISPAGE(pBt, iLastPg) ){
2749 MemPage *pPg;
2750 int rc = sqlite3BtreeGetPage(pBt, iLastPg, &pPg, 0);
2751 if( rc!=SQLITE_OK ){
2752 return rc;
2753 }
2754 rc = sqlite3PagerWrite(pPg->pDbPage);
2755 releasePage(pPg);
2756 if( rc!=SQLITE_OK ){
2757 return rc;
2758 }
2759 }
danielk19773460d192008-12-27 15:23:13 +00002760 iLastPg--;
2761 }
2762 sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
danielk1977dddbcdc2007-04-26 14:42:34 +00002763 }
2764 return SQLITE_OK;
2765}
2766
2767/*
2768** A write-transaction must be opened before calling this function.
2769** It performs a single unit of work towards an incremental vacuum.
2770**
2771** If the incremental vacuum is finished after this function has run,
shanebe217792009-03-05 04:20:31 +00002772** SQLITE_DONE is returned. If it is not finished, but no error occurred,
danielk1977dddbcdc2007-04-26 14:42:34 +00002773** SQLITE_OK is returned. Otherwise an SQLite error code.
2774*/
2775int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002776 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002777 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002778
2779 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00002780 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
2781 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002782 rc = SQLITE_DONE;
2783 }else{
2784 invalidateAllOverflowCache(pBt);
danielk1977bea2a942009-01-20 17:06:27 +00002785 rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt));
danielk1977dddbcdc2007-04-26 14:42:34 +00002786 }
drhd677b3d2007-08-20 22:48:41 +00002787 sqlite3BtreeLeave(p);
2788 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002789}
2790
2791/*
danielk19773b8a05f2007-03-19 17:44:26 +00002792** This routine is called prior to sqlite3PagerCommit when a transaction
danielk1977687566d2004-11-02 12:56:41 +00002793** is commited for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00002794**
2795** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
2796** the database file should be truncated to during the commit process.
2797** i.e. the database has been reorganized so that only the first *pnTrunc
2798** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00002799*/
danielk19773460d192008-12-27 15:23:13 +00002800static int autoVacuumCommit(BtShared *pBt){
danielk1977dddbcdc2007-04-26 14:42:34 +00002801 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002802 Pager *pPager = pBt->pPager;
drhf94a1732008-09-30 17:18:17 +00002803 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002804
drh1fee73e2007-08-29 04:00:57 +00002805 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00002806 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00002807 assert(pBt->autoVacuum);
2808 if( !pBt->incrVacuum ){
danielk19773460d192008-12-27 15:23:13 +00002809 Pgno nFin;
2810 Pgno nFree;
2811 Pgno nPtrmap;
2812 Pgno iFree;
2813 const int pgsz = pBt->pageSize;
2814 Pgno nOrig = pagerPagecount(pBt);
danielk1977687566d2004-11-02 12:56:41 +00002815
danielk1977ef165ce2009-04-06 17:50:03 +00002816 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
2817 /* It is not possible to create a database for which the final page
2818 ** is either a pointer-map page or the pending-byte page. If one
2819 ** is encountered, this indicates corruption.
2820 */
danielk19773460d192008-12-27 15:23:13 +00002821 return SQLITE_CORRUPT_BKPT;
2822 }
danielk1977ef165ce2009-04-06 17:50:03 +00002823
danielk19773460d192008-12-27 15:23:13 +00002824 nFree = get4byte(&pBt->pPage1->aData[36]);
2825 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+pgsz/5)/(pgsz/5);
2826 nFin = nOrig - nFree - nPtrmap;
danielk1977ef165ce2009-04-06 17:50:03 +00002827 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
danielk19773460d192008-12-27 15:23:13 +00002828 nFin--;
2829 }
2830 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
2831 nFin--;
danielk1977dddbcdc2007-04-26 14:42:34 +00002832 }
drhc5e47ac2009-06-04 00:11:56 +00002833 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
danielk1977687566d2004-11-02 12:56:41 +00002834
danielk19773460d192008-12-27 15:23:13 +00002835 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
2836 rc = incrVacuumStep(pBt, nFin, iFree);
danielk1977dddbcdc2007-04-26 14:42:34 +00002837 }
danielk19773460d192008-12-27 15:23:13 +00002838 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00002839 rc = SQLITE_OK;
danielk19773460d192008-12-27 15:23:13 +00002840 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
2841 put4byte(&pBt->pPage1->aData[32], 0);
2842 put4byte(&pBt->pPage1->aData[36], 0);
2843 sqlite3PagerTruncateImage(pBt->pPager, nFin);
danielk1977dddbcdc2007-04-26 14:42:34 +00002844 }
2845 if( rc!=SQLITE_OK ){
2846 sqlite3PagerRollback(pPager);
2847 }
danielk1977687566d2004-11-02 12:56:41 +00002848 }
2849
danielk19773b8a05f2007-03-19 17:44:26 +00002850 assert( nRef==sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002851 return rc;
2852}
danielk1977dddbcdc2007-04-26 14:42:34 +00002853
danielk1977a50d9aa2009-06-08 14:49:45 +00002854#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
2855# define setChildPtrmaps(x) SQLITE_OK
2856#endif
danielk1977687566d2004-11-02 12:56:41 +00002857
2858/*
drh80e35f42007-03-30 14:06:34 +00002859** This routine does the first phase of a two-phase commit. This routine
2860** causes a rollback journal to be created (if it does not already exist)
2861** and populated with enough information so that if a power loss occurs
2862** the database can be restored to its original state by playing back
2863** the journal. Then the contents of the journal are flushed out to
2864** the disk. After the journal is safely on oxide, the changes to the
2865** database are written into the database file and flushed to oxide.
2866** At the end of this call, the rollback journal still exists on the
2867** disk and we are still holding all locks, so the transaction has not
drh51898cf2009-04-19 20:51:06 +00002868** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
drh80e35f42007-03-30 14:06:34 +00002869** commit process.
2870**
2871** This call is a no-op if no write-transaction is currently active on pBt.
2872**
2873** Otherwise, sync the database file for the btree pBt. zMaster points to
2874** the name of a master journal file that should be written into the
2875** individual journal file, or is NULL, indicating no master journal file
2876** (single database transaction).
2877**
2878** When this is called, the master journal should already have been
2879** created, populated with this journal pointer and synced to disk.
2880**
2881** Once this is routine has returned, the only thing required to commit
2882** the write-transaction for this database file is to delete the journal.
2883*/
2884int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
2885 int rc = SQLITE_OK;
2886 if( p->inTrans==TRANS_WRITE ){
2887 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002888 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00002889#ifndef SQLITE_OMIT_AUTOVACUUM
2890 if( pBt->autoVacuum ){
danielk19773460d192008-12-27 15:23:13 +00002891 rc = autoVacuumCommit(pBt);
drh80e35f42007-03-30 14:06:34 +00002892 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002893 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002894 return rc;
2895 }
2896 }
2897#endif
drh49b9d332009-01-02 18:10:42 +00002898 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
drhd677b3d2007-08-20 22:48:41 +00002899 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002900 }
2901 return rc;
2902}
2903
2904/*
drh2aa679f2001-06-25 02:11:07 +00002905** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00002906**
drh6e345992007-03-30 11:12:08 +00002907** This routine implements the second phase of a 2-phase commit. The
drh51898cf2009-04-19 20:51:06 +00002908** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
2909** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
2910** routine did all the work of writing information out to disk and flushing the
drh6e345992007-03-30 11:12:08 +00002911** contents so that they are written onto the disk platter. All this
drh51898cf2009-04-19 20:51:06 +00002912** routine has to do is delete or truncate or zero the header in the
2913** the rollback journal (which causes the transaction to commit) and
2914** drop locks.
drh6e345992007-03-30 11:12:08 +00002915**
drh5e00f6c2001-09-13 13:46:56 +00002916** This will release the write lock on the database file. If there
2917** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00002918*/
drh80e35f42007-03-30 14:06:34 +00002919int sqlite3BtreeCommitPhaseTwo(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002920 BtShared *pBt = p->pBt;
2921
drhd677b3d2007-08-20 22:48:41 +00002922 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002923 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002924
2925 /* If the handle has a write-transaction open, commit the shared-btrees
2926 ** transaction and set the shared state to TRANS_READ.
2927 */
2928 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00002929 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00002930 assert( pBt->inTransaction==TRANS_WRITE );
2931 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00002932 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
danielk19777f7bc662006-01-23 13:47:47 +00002933 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002934 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002935 return rc;
2936 }
danielk1977aef0bf62005-12-30 16:28:01 +00002937 pBt->inTransaction = TRANS_READ;
danielk1977ee5741e2004-05-31 10:01:34 +00002938 }
danielk1977aef0bf62005-12-30 16:28:01 +00002939
2940 /* If the handle has any kind of transaction open, decrement the transaction
2941 ** count of the shared btree. If the transaction count reaches 0, set
2942 ** the shared state to TRANS_NONE. The unlockBtreeIfUnused() call below
2943 ** will unlock the pager.
2944 */
2945 if( p->inTrans!=TRANS_NONE ){
danielk1977fa542f12009-04-02 18:28:08 +00002946 clearAllSharedCacheTableLocks(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002947 pBt->nTransaction--;
2948 if( 0==pBt->nTransaction ){
2949 pBt->inTransaction = TRANS_NONE;
2950 }
2951 }
2952
drh51898cf2009-04-19 20:51:06 +00002953 /* Set the current transaction state to TRANS_NONE and unlock
danielk1977aef0bf62005-12-30 16:28:01 +00002954 ** the pager if this call closed the only read or write transaction.
2955 */
danielk1977bea2a942009-01-20 17:06:27 +00002956 btreeClearHasContent(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002957 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00002958 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002959
2960 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002961 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00002962 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00002963}
2964
drh80e35f42007-03-30 14:06:34 +00002965/*
2966** Do both phases of a commit.
2967*/
2968int sqlite3BtreeCommit(Btree *p){
2969 int rc;
drhd677b3d2007-08-20 22:48:41 +00002970 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00002971 rc = sqlite3BtreeCommitPhaseOne(p, 0);
2972 if( rc==SQLITE_OK ){
2973 rc = sqlite3BtreeCommitPhaseTwo(p);
2974 }
drhd677b3d2007-08-20 22:48:41 +00002975 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002976 return rc;
2977}
2978
danielk1977fbcd5852004-06-15 02:44:18 +00002979#ifndef NDEBUG
2980/*
2981** Return the number of write-cursors open on this handle. This is for use
2982** in assert() expressions, so it is only compiled if NDEBUG is not
2983** defined.
drhfb982642007-08-30 01:19:59 +00002984**
2985** For the purposes of this routine, a write-cursor is any cursor that
2986** is capable of writing to the databse. That means the cursor was
2987** originally opened for writing and the cursor has not be disabled
2988** by having its state changed to CURSOR_FAULT.
danielk1977fbcd5852004-06-15 02:44:18 +00002989*/
danielk1977aef0bf62005-12-30 16:28:01 +00002990static int countWriteCursors(BtShared *pBt){
danielk1977fbcd5852004-06-15 02:44:18 +00002991 BtCursor *pCur;
2992 int r = 0;
2993 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drhfb982642007-08-30 01:19:59 +00002994 if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
danielk1977fbcd5852004-06-15 02:44:18 +00002995 }
2996 return r;
2997}
2998#endif
2999
drhc39e0002004-05-07 23:50:57 +00003000/*
drhfb982642007-08-30 01:19:59 +00003001** This routine sets the state to CURSOR_FAULT and the error
3002** code to errCode for every cursor on BtShared that pBtree
3003** references.
3004**
3005** Every cursor is tripped, including cursors that belong
3006** to other database connections that happen to be sharing
3007** the cache with pBtree.
3008**
3009** This routine gets called when a rollback occurs.
3010** All cursors using the same cache must be tripped
3011** to prevent them from trying to use the btree after
3012** the rollback. The rollback may have deleted tables
3013** or moved root pages, so it is not sufficient to
3014** save the state of the cursor. The cursor must be
3015** invalidated.
3016*/
3017void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
3018 BtCursor *p;
3019 sqlite3BtreeEnter(pBtree);
3020 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
danielk1977bc2ca9e2008-11-13 14:28:28 +00003021 int i;
danielk1977be51a652008-10-08 17:58:48 +00003022 sqlite3BtreeClearCursor(p);
drhfb982642007-08-30 01:19:59 +00003023 p->eState = CURSOR_FAULT;
3024 p->skip = errCode;
danielk1977bc2ca9e2008-11-13 14:28:28 +00003025 for(i=0; i<=p->iPage; i++){
3026 releasePage(p->apPage[i]);
3027 p->apPage[i] = 0;
3028 }
drhfb982642007-08-30 01:19:59 +00003029 }
3030 sqlite3BtreeLeave(pBtree);
3031}
3032
3033/*
drhecdc7532001-09-23 02:35:53 +00003034** Rollback the transaction in progress. All cursors will be
3035** invalided by this operation. Any attempt to use a cursor
3036** that was open at the beginning of this operation will result
3037** in an error.
drh5e00f6c2001-09-13 13:46:56 +00003038**
3039** This will release the write lock on the database file. If there
3040** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00003041*/
danielk1977aef0bf62005-12-30 16:28:01 +00003042int sqlite3BtreeRollback(Btree *p){
danielk19778d34dfd2006-01-24 16:37:57 +00003043 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003044 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00003045 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00003046
drhd677b3d2007-08-20 22:48:41 +00003047 sqlite3BtreeEnter(p);
danielk19772b8c13e2006-01-24 14:21:24 +00003048 rc = saveAllCursors(pBt, 0, 0);
danielk19778d34dfd2006-01-24 16:37:57 +00003049#ifndef SQLITE_OMIT_SHARED_CACHE
danielk19772b8c13e2006-01-24 14:21:24 +00003050 if( rc!=SQLITE_OK ){
shanebe217792009-03-05 04:20:31 +00003051 /* This is a horrible situation. An IO or malloc() error occurred whilst
danielk19778d34dfd2006-01-24 16:37:57 +00003052 ** trying to save cursor positions. If this is an automatic rollback (as
3053 ** the result of a constraint, malloc() failure or IO error) then
3054 ** the cache may be internally inconsistent (not contain valid trees) so
3055 ** we cannot simply return the error to the caller. Instead, abort
3056 ** all queries that may be using any of the cursors that failed to save.
3057 */
drhfb982642007-08-30 01:19:59 +00003058 sqlite3BtreeTripAllCursors(p, rc);
danielk19772b8c13e2006-01-24 14:21:24 +00003059 }
danielk19778d34dfd2006-01-24 16:37:57 +00003060#endif
danielk1977aef0bf62005-12-30 16:28:01 +00003061 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003062
3063 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00003064 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00003065
danielk19778d34dfd2006-01-24 16:37:57 +00003066 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00003067 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00003068 if( rc2!=SQLITE_OK ){
3069 rc = rc2;
3070 }
3071
drh24cd67e2004-05-10 16:18:47 +00003072 /* The rollback may have destroyed the pPage1->aData value. So
drh16a9b832007-05-05 18:39:25 +00003073 ** call sqlite3BtreeGetPage() on page 1 again to make
3074 ** sure pPage1->aData is set correctly. */
3075 if( sqlite3BtreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh24cd67e2004-05-10 16:18:47 +00003076 releasePage(pPage1);
3077 }
danielk1977fbcd5852004-06-15 02:44:18 +00003078 assert( countWriteCursors(pBt)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00003079 pBt->inTransaction = TRANS_READ;
drh24cd67e2004-05-10 16:18:47 +00003080 }
danielk1977aef0bf62005-12-30 16:28:01 +00003081
3082 if( p->inTrans!=TRANS_NONE ){
danielk1977fa542f12009-04-02 18:28:08 +00003083 clearAllSharedCacheTableLocks(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003084 assert( pBt->nTransaction>0 );
3085 pBt->nTransaction--;
3086 if( 0==pBt->nTransaction ){
3087 pBt->inTransaction = TRANS_NONE;
3088 }
3089 }
3090
danielk1977bea2a942009-01-20 17:06:27 +00003091 btreeClearHasContent(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00003092 p->inTrans = TRANS_NONE;
drh5e00f6c2001-09-13 13:46:56 +00003093 unlockBtreeIfUnused(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00003094
3095 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00003096 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00003097 return rc;
3098}
3099
3100/*
danielk1977bd434552009-03-18 10:33:00 +00003101** Start a statement subtransaction. The subtransaction can can be rolled
3102** back independently of the main transaction. You must start a transaction
3103** before starting a subtransaction. The subtransaction is ended automatically
3104** if the main transaction commits or rolls back.
drhab01f612004-05-22 02:55:23 +00003105**
3106** Statement subtransactions are used around individual SQL statements
3107** that are contained within a BEGIN...COMMIT block. If a constraint
3108** error occurs within the statement, the effect of that one statement
3109** can be rolled back without having to rollback the entire transaction.
danielk1977bd434552009-03-18 10:33:00 +00003110**
3111** A statement sub-transaction is implemented as an anonymous savepoint. The
3112** value passed as the second parameter is the total number of savepoints,
3113** including the new anonymous savepoint, open on the B-Tree. i.e. if there
3114** are no active savepoints and no other statement-transactions open,
3115** iStatement is 1. This anonymous savepoint can be released or rolled back
3116** using the sqlite3BtreeSavepoint() function.
drh663fc632002-02-02 18:49:19 +00003117*/
danielk1977bd434552009-03-18 10:33:00 +00003118int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
drh663fc632002-02-02 18:49:19 +00003119 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003120 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003121 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00003122 assert( p->inTrans==TRANS_WRITE );
drh64022502009-01-09 14:11:04 +00003123 assert( pBt->readOnly==0 );
danielk1977bd434552009-03-18 10:33:00 +00003124 assert( iStatement>0 );
3125 assert( iStatement>p->db->nSavepoint );
3126 if( NEVER(p->inTrans!=TRANS_WRITE || pBt->readOnly) ){
drh64022502009-01-09 14:11:04 +00003127 rc = SQLITE_INTERNAL;
drhd677b3d2007-08-20 22:48:41 +00003128 }else{
3129 assert( pBt->inTransaction==TRANS_WRITE );
drh64022502009-01-09 14:11:04 +00003130 /* At the pager level, a statement transaction is a savepoint with
3131 ** an index greater than all savepoints created explicitly using
3132 ** SQL statements. It is illegal to open, release or rollback any
3133 ** such savepoints while the statement transaction savepoint is active.
3134 */
danielk1977bd434552009-03-18 10:33:00 +00003135 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
danielk197797a227c2006-01-20 16:32:04 +00003136 }
drhd677b3d2007-08-20 22:48:41 +00003137 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00003138 return rc;
3139}
3140
3141/*
danielk1977fd7f0452008-12-17 17:30:26 +00003142** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
3143** or SAVEPOINT_RELEASE. This function either releases or rolls back the
danielk197712dd5492008-12-18 15:45:07 +00003144** savepoint identified by parameter iSavepoint, depending on the value
3145** of op.
3146**
3147** Normally, iSavepoint is greater than or equal to zero. However, if op is
3148** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
3149** contents of the entire transaction are rolled back. This is different
3150** from a normal transaction rollback, as no locks are released and the
3151** transaction remains open.
danielk1977fd7f0452008-12-17 17:30:26 +00003152*/
3153int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
3154 int rc = SQLITE_OK;
3155 if( p && p->inTrans==TRANS_WRITE ){
3156 BtShared *pBt = p->pBt;
danielk1977fd7f0452008-12-17 17:30:26 +00003157 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
3158 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
3159 sqlite3BtreeEnter(p);
danielk1977fd7f0452008-12-17 17:30:26 +00003160 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
drh9f0bbf92009-01-02 21:08:09 +00003161 if( rc==SQLITE_OK ){
3162 rc = newDatabase(pBt);
3163 }
danielk1977fd7f0452008-12-17 17:30:26 +00003164 sqlite3BtreeLeave(p);
3165 }
3166 return rc;
3167}
3168
3169/*
drh8b2f49b2001-06-08 00:21:52 +00003170** Create a new cursor for the BTree whose root is on the page
3171** iTable. The act of acquiring a cursor gets a read lock on
3172** the database file.
drh1bee3d72001-10-15 00:44:35 +00003173**
3174** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00003175** If wrFlag==1, then the cursor can be used for reading or for
3176** writing if other conditions for writing are also met. These
3177** are the conditions that must be met in order for writing to
3178** be allowed:
drh6446c4d2001-12-15 14:22:18 +00003179**
drhf74b8d92002-09-01 23:20:45 +00003180** 1: The cursor must have been opened with wrFlag==1
3181**
drhfe5d71d2007-03-19 11:54:10 +00003182** 2: Other database connections that share the same pager cache
3183** but which are not in the READ_UNCOMMITTED state may not have
3184** cursors open with wrFlag==0 on the same table. Otherwise
3185** the changes made by this write cursor would be visible to
3186** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00003187**
3188** 3: The database must be writable (not on read-only media)
3189**
3190** 4: There must be an active transaction.
3191**
drh6446c4d2001-12-15 14:22:18 +00003192** No checking is done to make sure that page iTable really is the
3193** root page of a b-tree. If it is not, then the cursor acquired
3194** will not work correctly.
danielk197771d5d2c2008-09-29 11:49:47 +00003195**
3196** It is assumed that the sqlite3BtreeCursorSize() bytes of memory
3197** pointed to by pCur have been zeroed by the caller.
drha059ad02001-04-17 20:09:11 +00003198*/
drhd677b3d2007-08-20 22:48:41 +00003199static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00003200 Btree *p, /* The btree */
3201 int iTable, /* Root page of table to open */
3202 int wrFlag, /* 1 to write. 0 read-only */
3203 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
3204 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00003205){
drha059ad02001-04-17 20:09:11 +00003206 int rc;
danielk197789d40042008-11-17 14:20:56 +00003207 Pgno nPage;
danielk1977aef0bf62005-12-30 16:28:01 +00003208 BtShared *pBt = p->pBt;
drhecdc7532001-09-23 02:35:53 +00003209
drh1fee73e2007-08-29 04:00:57 +00003210 assert( sqlite3BtreeHoldsMutex(p) );
drhf49661a2008-12-10 16:45:50 +00003211 assert( wrFlag==0 || wrFlag==1 );
danielk197796d48e92009-06-29 06:00:37 +00003212
danielk1977602b4662009-07-02 07:47:33 +00003213 /* The following assert statements verify that if this is a sharable
3214 ** b-tree database, the connection is holding the required table locks,
3215 ** and that no other connection has any open cursor that conflicts with
3216 ** this lock. */
3217 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
danielk197796d48e92009-06-29 06:00:37 +00003218 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
3219
3220 if( NEVER(wrFlag && pBt->readOnly) ){
3221 return SQLITE_READONLY;
drha0c9a112004-03-10 13:42:37 +00003222 }
danielk1977aef0bf62005-12-30 16:28:01 +00003223
drh4b70f112004-05-02 21:12:19 +00003224 if( pBt->pPage1==0 ){
danielk1977aef0bf62005-12-30 16:28:01 +00003225 rc = lockBtreeWithRetry(p);
drha059ad02001-04-17 20:09:11 +00003226 if( rc!=SQLITE_OK ){
drha059ad02001-04-17 20:09:11 +00003227 return rc;
3228 }
3229 }
drh8b2f49b2001-06-08 00:21:52 +00003230 pCur->pgnoRoot = (Pgno)iTable;
danielk197789d40042008-11-17 14:20:56 +00003231 rc = sqlite3PagerPagecount(pBt->pPager, (int *)&nPage);
3232 if( rc!=SQLITE_OK ){
3233 return rc;
3234 }
3235 if( iTable==1 && nPage==0 ){
drh24cd67e2004-05-10 16:18:47 +00003236 rc = SQLITE_EMPTY;
3237 goto create_cursor_exception;
3238 }
danielk197771d5d2c2008-09-29 11:49:47 +00003239 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
drhbd03cae2001-06-02 02:40:57 +00003240 if( rc!=SQLITE_OK ){
3241 goto create_cursor_exception;
drha059ad02001-04-17 20:09:11 +00003242 }
danielk1977aef0bf62005-12-30 16:28:01 +00003243
danielk1977aef0bf62005-12-30 16:28:01 +00003244 /* Now that no other errors can occur, finish filling in the BtCursor
3245 ** variables, link the cursor into the BtShared list and set *ppCur (the
3246 ** output argument to this function).
3247 */
drh1e968a02008-03-25 00:22:21 +00003248 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00003249 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00003250 pCur->pBt = pBt;
drhf49661a2008-12-10 16:45:50 +00003251 pCur->wrFlag = (u8)wrFlag;
drha059ad02001-04-17 20:09:11 +00003252 pCur->pNext = pBt->pCursor;
3253 if( pCur->pNext ){
3254 pCur->pNext->pPrev = pCur;
3255 }
3256 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00003257 pCur->eState = CURSOR_INVALID;
drh7f751222009-03-17 22:33:00 +00003258 pCur->cachedRowid = 0;
drhbd03cae2001-06-02 02:40:57 +00003259
danielk1977aef0bf62005-12-30 16:28:01 +00003260 return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003261
drhbd03cae2001-06-02 02:40:57 +00003262create_cursor_exception:
danielk197771d5d2c2008-09-29 11:49:47 +00003263 releasePage(pCur->apPage[0]);
drh5e00f6c2001-09-13 13:46:56 +00003264 unlockBtreeIfUnused(pBt);
drhbd03cae2001-06-02 02:40:57 +00003265 return rc;
drha059ad02001-04-17 20:09:11 +00003266}
drhd677b3d2007-08-20 22:48:41 +00003267int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00003268 Btree *p, /* The btree */
3269 int iTable, /* Root page of table to open */
3270 int wrFlag, /* 1 to write. 0 read-only */
3271 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
3272 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00003273){
3274 int rc;
3275 sqlite3BtreeEnter(p);
danielk1977cd3e8f72008-03-25 09:47:35 +00003276 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
drhd677b3d2007-08-20 22:48:41 +00003277 sqlite3BtreeLeave(p);
3278 return rc;
3279}
drh7f751222009-03-17 22:33:00 +00003280
3281/*
3282** Return the size of a BtCursor object in bytes.
3283**
3284** This interfaces is needed so that users of cursors can preallocate
3285** sufficient storage to hold a cursor. The BtCursor object is opaque
3286** to users so they cannot do the sizeof() themselves - they must call
3287** this routine.
3288*/
3289int sqlite3BtreeCursorSize(void){
danielk1977cd3e8f72008-03-25 09:47:35 +00003290 return sizeof(BtCursor);
3291}
3292
drh7f751222009-03-17 22:33:00 +00003293/*
3294** Set the cached rowid value of every cursor in the same database file
3295** as pCur and having the same root page number as pCur. The value is
3296** set to iRowid.
3297**
3298** Only positive rowid values are considered valid for this cache.
3299** The cache is initialized to zero, indicating an invalid cache.
3300** A btree will work fine with zero or negative rowids. We just cannot
3301** cache zero or negative rowids, which means tables that use zero or
3302** negative rowids might run a little slower. But in practice, zero
3303** or negative rowids are very uncommon so this should not be a problem.
3304*/
3305void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
3306 BtCursor *p;
3307 for(p=pCur->pBt->pCursor; p; p=p->pNext){
3308 if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
3309 }
3310 assert( pCur->cachedRowid==iRowid );
3311}
drhd677b3d2007-08-20 22:48:41 +00003312
drh7f751222009-03-17 22:33:00 +00003313/*
3314** Return the cached rowid for the given cursor. A negative or zero
3315** return value indicates that the rowid cache is invalid and should be
3316** ignored. If the rowid cache has never before been set, then a
3317** zero is returned.
3318*/
3319sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
3320 return pCur->cachedRowid;
3321}
drha059ad02001-04-17 20:09:11 +00003322
3323/*
drh5e00f6c2001-09-13 13:46:56 +00003324** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00003325** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00003326*/
drh3aac2dd2004-04-26 14:10:20 +00003327int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00003328 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00003329 if( pBtree ){
danielk197771d5d2c2008-09-29 11:49:47 +00003330 int i;
danielk1977cd3e8f72008-03-25 09:47:35 +00003331 BtShared *pBt = pCur->pBt;
3332 sqlite3BtreeEnter(pBtree);
danielk1977be51a652008-10-08 17:58:48 +00003333 sqlite3BtreeClearCursor(pCur);
danielk1977cd3e8f72008-03-25 09:47:35 +00003334 if( pCur->pPrev ){
3335 pCur->pPrev->pNext = pCur->pNext;
3336 }else{
3337 pBt->pCursor = pCur->pNext;
3338 }
3339 if( pCur->pNext ){
3340 pCur->pNext->pPrev = pCur->pPrev;
3341 }
danielk197771d5d2c2008-09-29 11:49:47 +00003342 for(i=0; i<=pCur->iPage; i++){
3343 releasePage(pCur->apPage[i]);
3344 }
danielk1977cd3e8f72008-03-25 09:47:35 +00003345 unlockBtreeIfUnused(pBt);
3346 invalidateOverflowCache(pCur);
3347 /* sqlite3_free(pCur); */
3348 sqlite3BtreeLeave(pBtree);
drha059ad02001-04-17 20:09:11 +00003349 }
drh8c42ca92001-06-22 19:15:00 +00003350 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003351}
3352
drh0d588bb2009-06-17 13:09:38 +00003353#ifdef SQLITE_TEST
drh7e3b0a02001-04-28 16:52:40 +00003354/*
drh5e2f8b92001-05-28 00:41:15 +00003355** Make a temporary cursor by filling in the fields of pTempCur.
3356** The temporary cursor is not on the cursor list for the Btree.
3357*/
drh16a9b832007-05-05 18:39:25 +00003358void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
danielk197771d5d2c2008-09-29 11:49:47 +00003359 int i;
drh1fee73e2007-08-29 04:00:57 +00003360 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00003361 memcpy(pTempCur, pCur, sizeof(BtCursor));
drh5e2f8b92001-05-28 00:41:15 +00003362 pTempCur->pNext = 0;
3363 pTempCur->pPrev = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003364 for(i=0; i<=pTempCur->iPage; i++){
3365 sqlite3PagerRef(pTempCur->apPage[i]->pDbPage);
drhecdc7532001-09-23 02:35:53 +00003366 }
danielk197736e20932008-11-26 07:40:30 +00003367 assert( pTempCur->pKey==0 );
drh5e2f8b92001-05-28 00:41:15 +00003368}
drh0d588bb2009-06-17 13:09:38 +00003369#endif /* SQLITE_TEST */
drh5e2f8b92001-05-28 00:41:15 +00003370
drh0d588bb2009-06-17 13:09:38 +00003371#ifdef SQLITE_TEST
drh5e2f8b92001-05-28 00:41:15 +00003372/*
drhbd03cae2001-06-02 02:40:57 +00003373** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
drh5e2f8b92001-05-28 00:41:15 +00003374** function above.
3375*/
drh16a9b832007-05-05 18:39:25 +00003376void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
danielk197771d5d2c2008-09-29 11:49:47 +00003377 int i;
drh1fee73e2007-08-29 04:00:57 +00003378 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00003379 for(i=0; i<=pCur->iPage; i++){
3380 sqlite3PagerUnref(pCur->apPage[i]->pDbPage);
drhecdc7532001-09-23 02:35:53 +00003381 }
danielk197736e20932008-11-26 07:40:30 +00003382 sqlite3_free(pCur->pKey);
drh5e2f8b92001-05-28 00:41:15 +00003383}
drh0d588bb2009-06-17 13:09:38 +00003384#endif /* SQLITE_TEST */
drh7f751222009-03-17 22:33:00 +00003385
drh5e2f8b92001-05-28 00:41:15 +00003386/*
drh86057612007-06-26 01:04:48 +00003387** Make sure the BtCursor* given in the argument has a valid
3388** BtCursor.info structure. If it is not already valid, call
danielk19771cc5ed82007-05-16 17:28:43 +00003389** sqlite3BtreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00003390**
3391** BtCursor.info is a cache of the information in the current cell.
drh16a9b832007-05-05 18:39:25 +00003392** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
drh86057612007-06-26 01:04:48 +00003393**
3394** 2007-06-25: There is a bug in some versions of MSVC that cause the
3395** compiler to crash when getCellInfo() is implemented as a macro.
3396** But there is a measureable speed advantage to using the macro on gcc
3397** (when less compiler optimizations like -Os or -O0 are used and the
3398** compiler is not doing agressive inlining.) So we use a real function
3399** for MSVC and a macro for everything else. Ticket #2457.
drh9188b382004-05-14 21:12:22 +00003400*/
drh9188b382004-05-14 21:12:22 +00003401#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00003402 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00003403 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00003404 int iPage = pCur->iPage;
drh51c6d962004-06-06 00:42:25 +00003405 memset(&info, 0, sizeof(info));
danielk197771d5d2c2008-09-29 11:49:47 +00003406 sqlite3BtreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
drh9188b382004-05-14 21:12:22 +00003407 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00003408 }
danielk19771cc5ed82007-05-16 17:28:43 +00003409#else
3410 #define assertCellInfo(x)
3411#endif
drh86057612007-06-26 01:04:48 +00003412#ifdef _MSC_VER
3413 /* Use a real function in MSVC to work around bugs in that compiler. */
3414 static void getCellInfo(BtCursor *pCur){
3415 if( pCur->info.nSize==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003416 int iPage = pCur->iPage;
3417 sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
drha2c20e42008-03-29 16:01:04 +00003418 pCur->validNKey = 1;
drh86057612007-06-26 01:04:48 +00003419 }else{
3420 assertCellInfo(pCur);
3421 }
3422 }
3423#else /* if not _MSC_VER */
3424 /* Use a macro in all other compilers so that the function is inlined */
danielk197771d5d2c2008-09-29 11:49:47 +00003425#define getCellInfo(pCur) \
3426 if( pCur->info.nSize==0 ){ \
3427 int iPage = pCur->iPage; \
3428 sqlite3BtreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
3429 pCur->validNKey = 1; \
3430 }else{ \
3431 assertCellInfo(pCur); \
drh86057612007-06-26 01:04:48 +00003432 }
3433#endif /* _MSC_VER */
drh9188b382004-05-14 21:12:22 +00003434
3435/*
drh3aac2dd2004-04-26 14:10:20 +00003436** Set *pSize to the size of the buffer needed to hold the value of
3437** the key for the current entry. If the cursor is not pointing
3438** to a valid entry, *pSize is set to 0.
3439**
drh4b70f112004-05-02 21:12:19 +00003440** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00003441** itself, not the number of bytes in the key.
drh7e3b0a02001-04-28 16:52:40 +00003442*/
drh4a1c3802004-05-12 15:15:47 +00003443int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drhd677b3d2007-08-20 22:48:41 +00003444 int rc;
3445
drh1fee73e2007-08-29 04:00:57 +00003446 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003447 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003448 if( rc==SQLITE_OK ){
3449 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3450 if( pCur->eState==CURSOR_INVALID ){
3451 *pSize = 0;
3452 }else{
drh86057612007-06-26 01:04:48 +00003453 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00003454 *pSize = pCur->info.nKey;
3455 }
drh72f82862001-05-24 21:06:34 +00003456 }
danielk1977da184232006-01-05 11:34:32 +00003457 return rc;
drha059ad02001-04-17 20:09:11 +00003458}
drh2af926b2001-05-15 00:39:25 +00003459
drh72f82862001-05-24 21:06:34 +00003460/*
drh0e1c19e2004-05-11 00:58:56 +00003461** Set *pSize to the number of bytes of data in the entry the
3462** cursor currently points to. Always return SQLITE_OK.
3463** Failure is not possible. If the cursor is not currently
3464** pointing to an entry (which can happen, for example, if
3465** the database is empty) then *pSize is set to 0.
3466*/
3467int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drhd677b3d2007-08-20 22:48:41 +00003468 int rc;
3469
drh1fee73e2007-08-29 04:00:57 +00003470 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003471 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003472 if( rc==SQLITE_OK ){
3473 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3474 if( pCur->eState==CURSOR_INVALID ){
3475 /* Not pointing at a valid entry - set *pSize to 0. */
3476 *pSize = 0;
3477 }else{
drh86057612007-06-26 01:04:48 +00003478 getCellInfo(pCur);
danielk1977da184232006-01-05 11:34:32 +00003479 *pSize = pCur->info.nData;
3480 }
drh0e1c19e2004-05-11 00:58:56 +00003481 }
danielk1977da184232006-01-05 11:34:32 +00003482 return rc;
drh0e1c19e2004-05-11 00:58:56 +00003483}
3484
3485/*
danielk1977d04417962007-05-02 13:16:30 +00003486** Given the page number of an overflow page in the database (parameter
3487** ovfl), this function finds the page number of the next page in the
3488** linked list of overflow pages. If possible, it uses the auto-vacuum
3489** pointer-map data instead of reading the content of page ovfl to do so.
3490**
3491** If an error occurs an SQLite error code is returned. Otherwise:
3492**
danielk1977bea2a942009-01-20 17:06:27 +00003493** The page number of the next overflow page in the linked list is
3494** written to *pPgnoNext. If page ovfl is the last page in its linked
3495** list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003496**
danielk1977bea2a942009-01-20 17:06:27 +00003497** If ppPage is not NULL, and a reference to the MemPage object corresponding
3498** to page number pOvfl was obtained, then *ppPage is set to point to that
3499** reference. It is the responsibility of the caller to call releasePage()
3500** on *ppPage to free the reference. In no reference was obtained (because
3501** the pointer-map was used to obtain the value for *pPgnoNext), then
3502** *ppPage is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003503*/
3504static int getOverflowPage(
3505 BtShared *pBt,
3506 Pgno ovfl, /* Overflow page */
danielk1977bea2a942009-01-20 17:06:27 +00003507 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
danielk1977d04417962007-05-02 13:16:30 +00003508 Pgno *pPgnoNext /* OUT: Next overflow page number */
3509){
3510 Pgno next = 0;
danielk1977bea2a942009-01-20 17:06:27 +00003511 MemPage *pPage = 0;
drh1bd10f82008-12-10 21:19:56 +00003512 int rc = SQLITE_OK;
danielk1977d04417962007-05-02 13:16:30 +00003513
drh1fee73e2007-08-29 04:00:57 +00003514 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bea2a942009-01-20 17:06:27 +00003515 assert(pPgnoNext);
danielk1977d04417962007-05-02 13:16:30 +00003516
3517#ifndef SQLITE_OMIT_AUTOVACUUM
3518 /* Try to find the next page in the overflow list using the
3519 ** autovacuum pointer-map pages. Guess that the next page in
3520 ** the overflow list is page number (ovfl+1). If that guess turns
3521 ** out to be wrong, fall back to loading the data of page
3522 ** number ovfl to determine the next page number.
3523 */
3524 if( pBt->autoVacuum ){
3525 Pgno pgno;
3526 Pgno iGuess = ovfl+1;
3527 u8 eType;
3528
3529 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
3530 iGuess++;
3531 }
3532
danielk197789d40042008-11-17 14:20:56 +00003533 if( iGuess<=pagerPagecount(pBt) ){
danielk1977d04417962007-05-02 13:16:30 +00003534 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
danielk1977bea2a942009-01-20 17:06:27 +00003535 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
danielk1977d04417962007-05-02 13:16:30 +00003536 next = iGuess;
danielk1977bea2a942009-01-20 17:06:27 +00003537 rc = SQLITE_DONE;
danielk1977d04417962007-05-02 13:16:30 +00003538 }
3539 }
3540 }
3541#endif
3542
danielk1977bea2a942009-01-20 17:06:27 +00003543 if( rc==SQLITE_OK ){
3544 rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, 0);
danielk1977d04417962007-05-02 13:16:30 +00003545 assert(rc==SQLITE_OK || pPage==0);
3546 if( next==0 && rc==SQLITE_OK ){
3547 next = get4byte(pPage->aData);
3548 }
danielk1977443c0592009-01-16 15:21:05 +00003549 }
danielk197745d68822009-01-16 16:23:38 +00003550
danielk1977bea2a942009-01-20 17:06:27 +00003551 *pPgnoNext = next;
3552 if( ppPage ){
3553 *ppPage = pPage;
3554 }else{
3555 releasePage(pPage);
3556 }
3557 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
danielk1977d04417962007-05-02 13:16:30 +00003558}
3559
danielk1977da107192007-05-04 08:32:13 +00003560/*
3561** Copy data from a buffer to a page, or from a page to a buffer.
3562**
3563** pPayload is a pointer to data stored on database page pDbPage.
3564** If argument eOp is false, then nByte bytes of data are copied
3565** from pPayload to the buffer pointed at by pBuf. If eOp is true,
3566** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
3567** of data are copied from the buffer pBuf to pPayload.
3568**
3569** SQLITE_OK is returned on success, otherwise an error code.
3570*/
3571static int copyPayload(
3572 void *pPayload, /* Pointer to page data */
3573 void *pBuf, /* Pointer to buffer */
3574 int nByte, /* Number of bytes to copy */
3575 int eOp, /* 0 -> copy from page, 1 -> copy to page */
3576 DbPage *pDbPage /* Page containing pPayload */
3577){
3578 if( eOp ){
3579 /* Copy data from buffer to page (a write operation) */
3580 int rc = sqlite3PagerWrite(pDbPage);
3581 if( rc!=SQLITE_OK ){
3582 return rc;
3583 }
3584 memcpy(pPayload, pBuf, nByte);
3585 }else{
3586 /* Copy data from page to buffer (a read operation) */
3587 memcpy(pBuf, pPayload, nByte);
3588 }
3589 return SQLITE_OK;
3590}
danielk1977d04417962007-05-02 13:16:30 +00003591
3592/*
danielk19779f8d6402007-05-02 17:48:45 +00003593** This function is used to read or overwrite payload information
3594** for the entry that the pCur cursor is pointing to. If the eOp
3595** parameter is 0, this is a read operation (data copied into
3596** buffer pBuf). If it is non-zero, a write (data copied from
3597** buffer pBuf).
3598**
3599** A total of "amt" bytes are read or written beginning at "offset".
3600** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00003601**
3602** This routine does not make a distinction between key and data.
danielk19779f8d6402007-05-02 17:48:45 +00003603** It just reads or writes bytes from the payload area. Data might
3604** appear on the main page or be scattered out on multiple overflow
3605** pages.
danielk1977da107192007-05-04 08:32:13 +00003606**
danielk1977dcbb5d32007-05-04 18:36:44 +00003607** If the BtCursor.isIncrblobHandle flag is set, and the current
danielk1977da107192007-05-04 08:32:13 +00003608** cursor entry uses one or more overflow pages, this function
3609** allocates space for and lazily popluates the overflow page-list
3610** cache array (BtCursor.aOverflow). Subsequent calls use this
3611** cache to make seeking to the supplied offset more efficient.
3612**
3613** Once an overflow page-list cache has been allocated, it may be
3614** invalidated if some other cursor writes to the same table, or if
3615** the cursor is moved to a different row. Additionally, in auto-vacuum
3616** mode, the following events may invalidate an overflow page-list cache.
3617**
3618** * An incremental vacuum,
3619** * A commit in auto_vacuum="full" mode,
3620** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00003621*/
danielk19779f8d6402007-05-02 17:48:45 +00003622static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00003623 BtCursor *pCur, /* Cursor pointing to entry to read from */
danielk197789d40042008-11-17 14:20:56 +00003624 u32 offset, /* Begin reading this far into payload */
3625 u32 amt, /* Read this many bytes */
drh3aac2dd2004-04-26 14:10:20 +00003626 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00003627 int skipKey, /* offset begins at data if this is true */
3628 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00003629){
3630 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00003631 int rc = SQLITE_OK;
drhfa1a98a2004-05-14 19:08:17 +00003632 u32 nKey;
danielk19772dec9702007-05-02 16:48:37 +00003633 int iIdx = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003634 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
danielk19770d065412008-11-12 18:21:36 +00003635 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
drh3aac2dd2004-04-26 14:10:20 +00003636
danielk1977da107192007-05-04 08:32:13 +00003637 assert( pPage );
danielk1977da184232006-01-05 11:34:32 +00003638 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003639 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh1fee73e2007-08-29 04:00:57 +00003640 assert( cursorHoldsMutex(pCur) );
danielk1977da107192007-05-04 08:32:13 +00003641
drh86057612007-06-26 01:04:48 +00003642 getCellInfo(pCur);
drh366fda62006-01-13 02:35:09 +00003643 aPayload = pCur->info.pCell + pCur->info.nHeader;
drhf49661a2008-12-10 16:45:50 +00003644 nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
danielk1977da107192007-05-04 08:32:13 +00003645
drh3aac2dd2004-04-26 14:10:20 +00003646 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003647 offset += nKey;
drh3aac2dd2004-04-26 14:10:20 +00003648 }
danielk19770d065412008-11-12 18:21:36 +00003649 if( offset+amt > nKey+pCur->info.nData
3650 || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
3651 ){
danielk1977da107192007-05-04 08:32:13 +00003652 /* Trying to read or write past the end of the data is an error */
danielk197767fd7a92008-09-10 17:53:35 +00003653 return SQLITE_CORRUPT_BKPT;
drh3aac2dd2004-04-26 14:10:20 +00003654 }
danielk1977da107192007-05-04 08:32:13 +00003655
3656 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00003657 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00003658 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00003659 if( a+offset>pCur->info.nLocal ){
3660 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00003661 }
danielk1977da107192007-05-04 08:32:13 +00003662 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00003663 offset = 0;
drha34b6762004-05-07 13:30:42 +00003664 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00003665 amt -= a;
drhdd793422001-06-28 01:54:48 +00003666 }else{
drhfa1a98a2004-05-14 19:08:17 +00003667 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00003668 }
danielk1977da107192007-05-04 08:32:13 +00003669
3670 if( rc==SQLITE_OK && amt>0 ){
danielk197789d40042008-11-17 14:20:56 +00003671 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
danielk1977da107192007-05-04 08:32:13 +00003672 Pgno nextPage;
3673
drhfa1a98a2004-05-14 19:08:17 +00003674 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00003675
danielk19772dec9702007-05-02 16:48:37 +00003676#ifndef SQLITE_OMIT_INCRBLOB
danielk1977dcbb5d32007-05-04 18:36:44 +00003677 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
danielk1977da107192007-05-04 08:32:13 +00003678 ** has not been allocated, allocate it now. The array is sized at
3679 ** one entry for each overflow page in the overflow chain. The
3680 ** page number of the first overflow page is stored in aOverflow[0],
3681 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
3682 ** (the cache is lazily populated).
3683 */
danielk1977dcbb5d32007-05-04 18:36:44 +00003684 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
danielk19772dec9702007-05-02 16:48:37 +00003685 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
drh17435752007-08-16 04:30:38 +00003686 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
danielk19772dec9702007-05-02 16:48:37 +00003687 if( nOvfl && !pCur->aOverflow ){
danielk1977da107192007-05-04 08:32:13 +00003688 rc = SQLITE_NOMEM;
danielk19772dec9702007-05-02 16:48:37 +00003689 }
3690 }
danielk1977da107192007-05-04 08:32:13 +00003691
3692 /* If the overflow page-list cache has been allocated and the
3693 ** entry for the first required overflow page is valid, skip
3694 ** directly to it.
3695 */
danielk19772dec9702007-05-02 16:48:37 +00003696 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
3697 iIdx = (offset/ovflSize);
3698 nextPage = pCur->aOverflow[iIdx];
3699 offset = (offset%ovflSize);
3700 }
3701#endif
danielk1977da107192007-05-04 08:32:13 +00003702
3703 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
3704
3705#ifndef SQLITE_OMIT_INCRBLOB
3706 /* If required, populate the overflow page-list cache. */
3707 if( pCur->aOverflow ){
3708 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
3709 pCur->aOverflow[iIdx] = nextPage;
3710 }
3711#endif
3712
danielk1977d04417962007-05-02 13:16:30 +00003713 if( offset>=ovflSize ){
3714 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00003715 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00003716 ** data is not required. So first try to lookup the overflow
3717 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00003718 ** function.
danielk1977d04417962007-05-02 13:16:30 +00003719 */
danielk19772dec9702007-05-02 16:48:37 +00003720#ifndef SQLITE_OMIT_INCRBLOB
danielk1977da107192007-05-04 08:32:13 +00003721 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
3722 nextPage = pCur->aOverflow[iIdx+1];
3723 } else
danielk19772dec9702007-05-02 16:48:37 +00003724#endif
danielk1977da107192007-05-04 08:32:13 +00003725 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
danielk1977da107192007-05-04 08:32:13 +00003726 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00003727 }else{
danielk19779f8d6402007-05-02 17:48:45 +00003728 /* Need to read this page properly. It contains some of the
3729 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00003730 */
3731 DbPage *pDbPage;
danielk1977cfe9a692004-06-16 12:00:29 +00003732 int a = amt;
danielk1977d04417962007-05-02 13:16:30 +00003733 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
danielk1977da107192007-05-04 08:32:13 +00003734 if( rc==SQLITE_OK ){
3735 aPayload = sqlite3PagerGetData(pDbPage);
3736 nextPage = get4byte(aPayload);
3737 if( a + offset > ovflSize ){
3738 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00003739 }
danielk1977da107192007-05-04 08:32:13 +00003740 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
3741 sqlite3PagerUnref(pDbPage);
3742 offset = 0;
3743 amt -= a;
3744 pBuf += a;
danielk19779f8d6402007-05-02 17:48:45 +00003745 }
danielk1977cfe9a692004-06-16 12:00:29 +00003746 }
drh2af926b2001-05-15 00:39:25 +00003747 }
drh2af926b2001-05-15 00:39:25 +00003748 }
danielk1977cfe9a692004-06-16 12:00:29 +00003749
danielk1977da107192007-05-04 08:32:13 +00003750 if( rc==SQLITE_OK && amt>0 ){
drh49285702005-09-17 15:20:26 +00003751 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00003752 }
danielk1977da107192007-05-04 08:32:13 +00003753 return rc;
drh2af926b2001-05-15 00:39:25 +00003754}
3755
drh72f82862001-05-24 21:06:34 +00003756/*
drh3aac2dd2004-04-26 14:10:20 +00003757** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003758** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003759** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00003760**
drh3aac2dd2004-04-26 14:10:20 +00003761** Return SQLITE_OK on success or an error code if anything goes
3762** wrong. An error is returned if "offset+amt" is larger than
3763** the available payload.
drh72f82862001-05-24 21:06:34 +00003764*/
drha34b6762004-05-07 13:30:42 +00003765int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003766 int rc;
3767
drh1fee73e2007-08-29 04:00:57 +00003768 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003769 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003770 if( rc==SQLITE_OK ){
3771 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003772 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3773 if( pCur->apPage[0]->intKey ){
danielk1977da184232006-01-05 11:34:32 +00003774 return SQLITE_CORRUPT_BKPT;
3775 }
danielk197771d5d2c2008-09-29 11:49:47 +00003776 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh16a9b832007-05-05 18:39:25 +00003777 rc = accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0, 0);
drh6575a222005-03-10 17:06:34 +00003778 }
danielk1977da184232006-01-05 11:34:32 +00003779 return rc;
drh3aac2dd2004-04-26 14:10:20 +00003780}
3781
3782/*
drh3aac2dd2004-04-26 14:10:20 +00003783** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003784** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003785** begins at "offset".
3786**
3787** Return SQLITE_OK on success or an error code if anything goes
3788** wrong. An error is returned if "offset+amt" is larger than
3789** the available payload.
drh72f82862001-05-24 21:06:34 +00003790*/
drh3aac2dd2004-04-26 14:10:20 +00003791int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003792 int rc;
3793
danielk19773588ceb2008-06-10 17:30:26 +00003794#ifndef SQLITE_OMIT_INCRBLOB
3795 if ( pCur->eState==CURSOR_INVALID ){
3796 return SQLITE_ABORT;
3797 }
3798#endif
3799
drh1fee73e2007-08-29 04:00:57 +00003800 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003801 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003802 if( rc==SQLITE_OK ){
3803 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003804 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3805 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh16a9b832007-05-05 18:39:25 +00003806 rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
danielk1977da184232006-01-05 11:34:32 +00003807 }
3808 return rc;
drh2af926b2001-05-15 00:39:25 +00003809}
3810
drh72f82862001-05-24 21:06:34 +00003811/*
drh0e1c19e2004-05-11 00:58:56 +00003812** Return a pointer to payload information from the entry that the
3813** pCur cursor is pointing to. The pointer is to the beginning of
3814** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00003815** skipKey==1. The number of bytes of available key/data is written
3816** into *pAmt. If *pAmt==0, then the value returned will not be
3817** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00003818**
3819** This routine is an optimization. It is common for the entire key
3820** and data to fit on the local page and for there to be no overflow
3821** pages. When that is so, this routine can be used to access the
3822** key and data without making a copy. If the key and/or data spills
drh7f751222009-03-17 22:33:00 +00003823** onto overflow pages, then accessPayload() must be used to reassemble
drh0e1c19e2004-05-11 00:58:56 +00003824** the key/data and copy it into a preallocated buffer.
3825**
3826** The pointer returned by this routine looks directly into the cached
3827** page of the database. The data might change or move the next time
3828** any btree routine is called.
3829*/
3830static const unsigned char *fetchPayload(
3831 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00003832 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00003833 int skipKey /* read beginning at data if this is true */
3834){
3835 unsigned char *aPayload;
3836 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00003837 u32 nKey;
danielk197789d40042008-11-17 14:20:56 +00003838 u32 nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003839
danielk197771d5d2c2008-09-29 11:49:47 +00003840 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
danielk1977da184232006-01-05 11:34:32 +00003841 assert( pCur->eState==CURSOR_VALID );
drh1fee73e2007-08-29 04:00:57 +00003842 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00003843 pPage = pCur->apPage[pCur->iPage];
3844 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh86057612007-06-26 01:04:48 +00003845 getCellInfo(pCur);
drh43605152004-05-29 21:46:49 +00003846 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00003847 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00003848 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00003849 nKey = 0;
3850 }else{
drhf49661a2008-12-10 16:45:50 +00003851 nKey = (int)pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00003852 }
drh0e1c19e2004-05-11 00:58:56 +00003853 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003854 aPayload += nKey;
3855 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00003856 }else{
drhfa1a98a2004-05-14 19:08:17 +00003857 nLocal = pCur->info.nLocal;
drhe51c44f2004-05-30 20:46:09 +00003858 if( nLocal>nKey ){
3859 nLocal = nKey;
3860 }
drh0e1c19e2004-05-11 00:58:56 +00003861 }
drhe51c44f2004-05-30 20:46:09 +00003862 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003863 return aPayload;
3864}
3865
3866
3867/*
drhe51c44f2004-05-30 20:46:09 +00003868** For the entry that cursor pCur is point to, return as
3869** many bytes of the key or data as are available on the local
3870** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00003871**
3872** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00003873** or be destroyed on the next call to any Btree routine,
3874** including calls from other threads against the same cache.
3875** Hence, a mutex on the BtShared should be held prior to calling
3876** this routine.
drh0e1c19e2004-05-11 00:58:56 +00003877**
3878** These routines is used to get quick access to key and data
3879** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00003880*/
drhe51c44f2004-05-30 20:46:09 +00003881const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
danielk19774b0aa4c2009-05-28 11:05:57 +00003882 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh1fee73e2007-08-29 04:00:57 +00003883 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003884 if( pCur->eState==CURSOR_VALID ){
3885 return (const void*)fetchPayload(pCur, pAmt, 0);
3886 }
3887 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003888}
drhe51c44f2004-05-30 20:46:09 +00003889const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
danielk19774b0aa4c2009-05-28 11:05:57 +00003890 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh1fee73e2007-08-29 04:00:57 +00003891 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003892 if( pCur->eState==CURSOR_VALID ){
3893 return (const void*)fetchPayload(pCur, pAmt, 1);
3894 }
3895 return 0;
drh0e1c19e2004-05-11 00:58:56 +00003896}
3897
3898
3899/*
drh8178a752003-01-05 21:41:40 +00003900** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00003901** page number of the child page to move to.
drh72f82862001-05-24 21:06:34 +00003902*/
drh3aac2dd2004-04-26 14:10:20 +00003903static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00003904 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003905 int i = pCur->iPage;
drh72f82862001-05-24 21:06:34 +00003906 MemPage *pNewPage;
drhd0679ed2007-08-28 22:24:34 +00003907 BtShared *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00003908
drh1fee73e2007-08-29 04:00:57 +00003909 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003910 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003911 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
3912 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
3913 return SQLITE_CORRUPT_BKPT;
3914 }
3915 rc = getAndInitPage(pBt, newPgno, &pNewPage);
drh6019e162001-07-02 17:51:45 +00003916 if( rc ) return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003917 pCur->apPage[i+1] = pNewPage;
3918 pCur->aiIdx[i+1] = 0;
3919 pCur->iPage++;
3920
drh271efa52004-05-30 19:19:05 +00003921 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003922 pCur->validNKey = 0;
drh4be295b2003-12-16 03:44:47 +00003923 if( pNewPage->nCell<1 ){
drh49285702005-09-17 15:20:26 +00003924 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00003925 }
drh72f82862001-05-24 21:06:34 +00003926 return SQLITE_OK;
3927}
3928
danielk1977bf93c562008-09-29 15:53:25 +00003929#ifndef NDEBUG
3930/*
3931** Page pParent is an internal (non-leaf) tree page. This function
3932** asserts that page number iChild is the left-child if the iIdx'th
3933** cell in page pParent. Or, if iIdx is equal to the total number of
3934** cells in pParent, that page number iChild is the right-child of
3935** the page.
3936*/
3937static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
3938 assert( iIdx<=pParent->nCell );
3939 if( iIdx==pParent->nCell ){
3940 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
3941 }else{
3942 assert( get4byte(findCell(pParent, iIdx))==iChild );
3943 }
3944}
3945#else
3946# define assertParentIndex(x,y,z)
3947#endif
3948
drh72f82862001-05-24 21:06:34 +00003949/*
drh5e2f8b92001-05-28 00:41:15 +00003950** Move the cursor up to the parent page.
3951**
3952** pCur->idx is set to the cell index that contains the pointer
3953** to the page we are coming from. If we are coming from the
3954** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00003955** the largest cell index.
drh72f82862001-05-24 21:06:34 +00003956*/
drh16a9b832007-05-05 18:39:25 +00003957void sqlite3BtreeMoveToParent(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00003958 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003959 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003960 assert( pCur->iPage>0 );
3961 assert( pCur->apPage[pCur->iPage] );
danielk1977bf93c562008-09-29 15:53:25 +00003962 assertParentIndex(
3963 pCur->apPage[pCur->iPage-1],
3964 pCur->aiIdx[pCur->iPage-1],
3965 pCur->apPage[pCur->iPage]->pgno
3966 );
danielk197771d5d2c2008-09-29 11:49:47 +00003967 releasePage(pCur->apPage[pCur->iPage]);
3968 pCur->iPage--;
drh271efa52004-05-30 19:19:05 +00003969 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003970 pCur->validNKey = 0;
drh72f82862001-05-24 21:06:34 +00003971}
3972
3973/*
3974** Move the cursor to the root page
3975*/
drh5e2f8b92001-05-28 00:41:15 +00003976static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00003977 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00003978 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003979 Btree *p = pCur->pBtree;
3980 BtShared *pBt = p->pBt;
drhbd03cae2001-06-02 02:40:57 +00003981
drh1fee73e2007-08-29 04:00:57 +00003982 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +00003983 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
3984 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
3985 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
3986 if( pCur->eState>=CURSOR_REQUIRESEEK ){
3987 if( pCur->eState==CURSOR_FAULT ){
3988 return pCur->skip;
3989 }
danielk1977be51a652008-10-08 17:58:48 +00003990 sqlite3BtreeClearCursor(pCur);
drhbf700f32007-03-31 02:36:44 +00003991 }
danielk197771d5d2c2008-09-29 11:49:47 +00003992
3993 if( pCur->iPage>=0 ){
3994 int i;
3995 for(i=1; i<=pCur->iPage; i++){
3996 releasePage(pCur->apPage[i]);
danielk1977d9f6c532008-09-19 16:39:38 +00003997 }
drh777e4c42006-01-13 04:31:58 +00003998 }else{
3999 if(
danielk197771d5d2c2008-09-29 11:49:47 +00004000 SQLITE_OK!=(rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]))
drh777e4c42006-01-13 04:31:58 +00004001 ){
4002 pCur->eState = CURSOR_INVALID;
4003 return rc;
4004 }
drhc39e0002004-05-07 23:50:57 +00004005 }
danielk197771d5d2c2008-09-29 11:49:47 +00004006
4007 pRoot = pCur->apPage[0];
4008 assert( pRoot->pgno==pCur->pgnoRoot );
4009 pCur->iPage = 0;
4010 pCur->aiIdx[0] = 0;
drh271efa52004-05-30 19:19:05 +00004011 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004012 pCur->atLast = 0;
4013 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004014
drh8856d6a2004-04-29 14:42:46 +00004015 if( pRoot->nCell==0 && !pRoot->leaf ){
4016 Pgno subpage;
drhc85240d2009-06-04 16:14:33 +00004017 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
drh8856d6a2004-04-29 14:42:46 +00004018 assert( pRoot->pgno==1 );
drh43605152004-05-29 21:46:49 +00004019 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
drh8856d6a2004-04-29 14:42:46 +00004020 assert( subpage>0 );
danielk1977da184232006-01-05 11:34:32 +00004021 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00004022 rc = moveToChild(pCur, subpage);
danielk197771d5d2c2008-09-29 11:49:47 +00004023 }else{
4024 pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
drh8856d6a2004-04-29 14:42:46 +00004025 }
4026 return rc;
drh72f82862001-05-24 21:06:34 +00004027}
drh2af926b2001-05-15 00:39:25 +00004028
drh5e2f8b92001-05-28 00:41:15 +00004029/*
4030** Move the cursor down to the left-most leaf entry beneath the
4031** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00004032**
4033** The left-most leaf is the one with the smallest key - the first
4034** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00004035*/
4036static int moveToLeftmost(BtCursor *pCur){
4037 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00004038 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00004039 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00004040
drh1fee73e2007-08-29 04:00:57 +00004041 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004042 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004043 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
4044 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
4045 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
drh8178a752003-01-05 21:41:40 +00004046 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00004047 }
drhd677b3d2007-08-20 22:48:41 +00004048 return rc;
drh5e2f8b92001-05-28 00:41:15 +00004049}
4050
drh2dcc9aa2002-12-04 13:40:25 +00004051/*
4052** Move the cursor down to the right-most leaf entry beneath the
4053** page to which it is currently pointing. Notice the difference
4054** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
4055** finds the left-most entry beneath the *entry* whereas moveToRightmost()
4056** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00004057**
4058** The right-most entry is the one with the largest key - the last
4059** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00004060*/
4061static int moveToRightmost(BtCursor *pCur){
4062 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00004063 int rc = SQLITE_OK;
drh1bd10f82008-12-10 21:19:56 +00004064 MemPage *pPage = 0;
drh2dcc9aa2002-12-04 13:40:25 +00004065
drh1fee73e2007-08-29 04:00:57 +00004066 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004067 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004068 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
drh43605152004-05-29 21:46:49 +00004069 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
danielk197771d5d2c2008-09-29 11:49:47 +00004070 pCur->aiIdx[pCur->iPage] = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00004071 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00004072 }
drhd677b3d2007-08-20 22:48:41 +00004073 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00004074 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
drhd677b3d2007-08-20 22:48:41 +00004075 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004076 pCur->validNKey = 0;
drhd677b3d2007-08-20 22:48:41 +00004077 }
danielk1977518002e2008-09-05 05:02:46 +00004078 return rc;
drh2dcc9aa2002-12-04 13:40:25 +00004079}
4080
drh5e00f6c2001-09-13 13:46:56 +00004081/* Move the cursor to the first entry in the table. Return SQLITE_OK
4082** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00004083** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00004084*/
drh3aac2dd2004-04-26 14:10:20 +00004085int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00004086 int rc;
drhd677b3d2007-08-20 22:48:41 +00004087
drh1fee73e2007-08-29 04:00:57 +00004088 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004089 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00004090 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004091 if( rc==SQLITE_OK ){
4092 if( pCur->eState==CURSOR_INVALID ){
danielk197771d5d2c2008-09-29 11:49:47 +00004093 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00004094 *pRes = 1;
4095 rc = SQLITE_OK;
4096 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004097 assert( pCur->apPage[pCur->iPage]->nCell>0 );
drhd677b3d2007-08-20 22:48:41 +00004098 *pRes = 0;
4099 rc = moveToLeftmost(pCur);
4100 }
drh5e00f6c2001-09-13 13:46:56 +00004101 }
drh5e00f6c2001-09-13 13:46:56 +00004102 return rc;
4103}
drh5e2f8b92001-05-28 00:41:15 +00004104
drh9562b552002-02-19 15:00:07 +00004105/* Move the cursor to the last entry in the table. Return SQLITE_OK
4106** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00004107** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00004108*/
drh3aac2dd2004-04-26 14:10:20 +00004109int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00004110 int rc;
drhd677b3d2007-08-20 22:48:41 +00004111
drh1fee73e2007-08-29 04:00:57 +00004112 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004113 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19773f632d52009-05-02 10:03:09 +00004114
4115 /* If the cursor already points to the last entry, this is a no-op. */
4116 if( CURSOR_VALID==pCur->eState && pCur->atLast ){
4117#ifdef SQLITE_DEBUG
4118 /* This block serves to assert() that the cursor really does point
4119 ** to the last entry in the b-tree. */
4120 int ii;
4121 for(ii=0; ii<pCur->iPage; ii++){
4122 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
4123 }
4124 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
4125 assert( pCur->apPage[pCur->iPage]->leaf );
4126#endif
4127 return SQLITE_OK;
4128 }
4129
drh9562b552002-02-19 15:00:07 +00004130 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004131 if( rc==SQLITE_OK ){
4132 if( CURSOR_INVALID==pCur->eState ){
danielk197771d5d2c2008-09-29 11:49:47 +00004133 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00004134 *pRes = 1;
4135 }else{
4136 assert( pCur->eState==CURSOR_VALID );
4137 *pRes = 0;
4138 rc = moveToRightmost(pCur);
drhf49661a2008-12-10 16:45:50 +00004139 pCur->atLast = rc==SQLITE_OK ?1:0;
drhd677b3d2007-08-20 22:48:41 +00004140 }
drh9562b552002-02-19 15:00:07 +00004141 }
drh9562b552002-02-19 15:00:07 +00004142 return rc;
4143}
4144
drhe14006d2008-03-25 17:23:32 +00004145/* Move the cursor so that it points to an entry near the key
drhe63d9992008-08-13 19:11:48 +00004146** specified by pIdxKey or intKey. Return a success code.
drh72f82862001-05-24 21:06:34 +00004147**
drhe63d9992008-08-13 19:11:48 +00004148** For INTKEY tables, the intKey parameter is used. pIdxKey
4149** must be NULL. For index tables, pIdxKey is used and intKey
4150** is ignored.
drh3aac2dd2004-04-26 14:10:20 +00004151**
drh5e2f8b92001-05-28 00:41:15 +00004152** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00004153** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00004154** were present. The cursor might point to an entry that comes
4155** before or after the key.
4156**
drh64022502009-01-09 14:11:04 +00004157** An integer is written into *pRes which is the result of
4158** comparing the key with the entry to which the cursor is
4159** pointing. The meaning of the integer written into
4160** *pRes is as follows:
drhbd03cae2001-06-02 02:40:57 +00004161**
4162** *pRes<0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004163** is smaller than intKey/pIdxKey or if the table is empty
drh1a844c32002-12-04 22:29:28 +00004164** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00004165**
4166** *pRes==0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004167** exactly matches intKey/pIdxKey.
drhbd03cae2001-06-02 02:40:57 +00004168**
4169** *pRes>0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004170** is larger than intKey/pIdxKey.
drhd677b3d2007-08-20 22:48:41 +00004171**
drha059ad02001-04-17 20:09:11 +00004172*/
drhe63d9992008-08-13 19:11:48 +00004173int sqlite3BtreeMovetoUnpacked(
4174 BtCursor *pCur, /* The cursor to be moved */
4175 UnpackedRecord *pIdxKey, /* Unpacked index key */
4176 i64 intKey, /* The table key */
4177 int biasRight, /* If true, bias the search to the high end */
4178 int *pRes /* Write search results here */
drhe4d90812007-03-29 05:51:49 +00004179){
drh72f82862001-05-24 21:06:34 +00004180 int rc;
drhd677b3d2007-08-20 22:48:41 +00004181
drh1fee73e2007-08-29 04:00:57 +00004182 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004183 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drha2c20e42008-03-29 16:01:04 +00004184
4185 /* If the cursor is already positioned at the point we are trying
4186 ** to move to, then just return without doing any work */
danielk197771d5d2c2008-09-29 11:49:47 +00004187 if( pCur->eState==CURSOR_VALID && pCur->validNKey
4188 && pCur->apPage[0]->intKey
4189 ){
drhe63d9992008-08-13 19:11:48 +00004190 if( pCur->info.nKey==intKey ){
drha2c20e42008-03-29 16:01:04 +00004191 *pRes = 0;
4192 return SQLITE_OK;
4193 }
drhe63d9992008-08-13 19:11:48 +00004194 if( pCur->atLast && pCur->info.nKey<intKey ){
drha2c20e42008-03-29 16:01:04 +00004195 *pRes = -1;
4196 return SQLITE_OK;
4197 }
4198 }
4199
drh5e2f8b92001-05-28 00:41:15 +00004200 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004201 if( rc ){
4202 return rc;
4203 }
danielk197771d5d2c2008-09-29 11:49:47 +00004204 assert( pCur->apPage[pCur->iPage] );
4205 assert( pCur->apPage[pCur->iPage]->isInit );
danielk1977da184232006-01-05 11:34:32 +00004206 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00004207 *pRes = -1;
danielk197771d5d2c2008-09-29 11:49:47 +00004208 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhc39e0002004-05-07 23:50:57 +00004209 return SQLITE_OK;
4210 }
danielk197771d5d2c2008-09-29 11:49:47 +00004211 assert( pCur->apPage[0]->intKey || pIdxKey );
drh14684382006-11-30 13:05:29 +00004212 for(;;){
drh72f82862001-05-24 21:06:34 +00004213 int lwr, upr;
4214 Pgno chldPg;
danielk197771d5d2c2008-09-29 11:49:47 +00004215 MemPage *pPage = pCur->apPage[pCur->iPage];
drh1a844c32002-12-04 22:29:28 +00004216 int c = -1; /* pRes return if table is empty must be -1 */
drh72f82862001-05-24 21:06:34 +00004217 lwr = 0;
4218 upr = pPage->nCell-1;
drh64022502009-01-09 14:11:04 +00004219 if( (!pPage->intKey && pIdxKey==0) || upr<0 ){
drh1e968a02008-03-25 00:22:21 +00004220 rc = SQLITE_CORRUPT_BKPT;
4221 goto moveto_finish;
drh4eec4c12005-01-21 00:22:37 +00004222 }
drhe4d90812007-03-29 05:51:49 +00004223 if( biasRight ){
drhf49661a2008-12-10 16:45:50 +00004224 pCur->aiIdx[pCur->iPage] = (u16)upr;
drhe4d90812007-03-29 05:51:49 +00004225 }else{
drhf49661a2008-12-10 16:45:50 +00004226 pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
drhe4d90812007-03-29 05:51:49 +00004227 }
drh64022502009-01-09 14:11:04 +00004228 for(;;){
danielk197711c327a2009-05-04 19:01:26 +00004229 int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
4230 u8 *pCell; /* Pointer to current cell in pPage */
4231
drh366fda62006-01-13 02:35:09 +00004232 pCur->info.nSize = 0;
danielk197711c327a2009-05-04 19:01:26 +00004233 pCell = findCell(pPage, idx) + pPage->childPtrSize;
drh3aac2dd2004-04-26 14:10:20 +00004234 if( pPage->intKey ){
danielk197711c327a2009-05-04 19:01:26 +00004235 i64 nCellKey;
drhd172f862006-01-12 15:01:15 +00004236 if( pPage->hasData ){
danielk1977bab45c62006-01-16 15:14:27 +00004237 u32 dummy;
shane3f8d5cf2008-04-24 19:15:09 +00004238 pCell += getVarint32(pCell, dummy);
drhd172f862006-01-12 15:01:15 +00004239 }
drha2c20e42008-03-29 16:01:04 +00004240 getVarint(pCell, (u64*)&nCellKey);
drhe63d9992008-08-13 19:11:48 +00004241 if( nCellKey==intKey ){
drh3aac2dd2004-04-26 14:10:20 +00004242 c = 0;
drhe63d9992008-08-13 19:11:48 +00004243 }else if( nCellKey<intKey ){
drh41eb9e92008-04-02 18:33:07 +00004244 c = -1;
4245 }else{
drhe63d9992008-08-13 19:11:48 +00004246 assert( nCellKey>intKey );
drh41eb9e92008-04-02 18:33:07 +00004247 c = +1;
drh3aac2dd2004-04-26 14:10:20 +00004248 }
danielk197711c327a2009-05-04 19:01:26 +00004249 pCur->validNKey = 1;
4250 pCur->info.nKey = nCellKey;
drh3aac2dd2004-04-26 14:10:20 +00004251 }else{
danielk197711c327a2009-05-04 19:01:26 +00004252 /* The maximum supported page-size is 32768 bytes. This means that
4253 ** the maximum number of record bytes stored on an index B-Tree
4254 ** page is at most 8198 bytes, which may be stored as a 2-byte
4255 ** varint. This information is used to attempt to avoid parsing
4256 ** the entire cell by checking for the cases where the record is
4257 ** stored entirely within the b-tree page by inspecting the first
4258 ** 2 bytes of the cell.
4259 */
4260 int nCell = pCell[0];
4261 if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
4262 /* This branch runs if the record-size field of the cell is a
4263 ** single byte varint and the record fits entirely on the main
4264 ** b-tree page. */
4265 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
4266 }else if( !(pCell[1] & 0x80)
4267 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
4268 ){
4269 /* The record-size field is a 2 byte varint and the record
4270 ** fits entirely on the main b-tree page. */
4271 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
drhe51c44f2004-05-30 20:46:09 +00004272 }else{
danielk197711c327a2009-05-04 19:01:26 +00004273 /* The record flows over onto one or more overflow pages. In
4274 ** this case the whole cell needs to be parsed, a buffer allocated
4275 ** and accessPayload() used to retrieve the record into the
4276 ** buffer before VdbeRecordCompare() can be called. */
4277 void *pCellKey;
4278 u8 * const pCellBody = pCell - pPage->childPtrSize;
4279 sqlite3BtreeParseCellPtr(pPage, pCellBody, &pCur->info);
shane60a4b532009-05-06 18:57:09 +00004280 nCell = (int)pCur->info.nKey;
danielk197711c327a2009-05-04 19:01:26 +00004281 pCellKey = sqlite3Malloc( nCell );
danielk19776507ecb2008-03-25 09:56:44 +00004282 if( pCellKey==0 ){
4283 rc = SQLITE_NOMEM;
4284 goto moveto_finish;
4285 }
danielk197711c327a2009-05-04 19:01:26 +00004286 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0, 0);
4287 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
drhfacf0302008-06-17 15:12:00 +00004288 sqlite3_free(pCellKey);
drh1e968a02008-03-25 00:22:21 +00004289 if( rc ) goto moveto_finish;
drhe51c44f2004-05-30 20:46:09 +00004290 }
drh3aac2dd2004-04-26 14:10:20 +00004291 }
drh72f82862001-05-24 21:06:34 +00004292 if( c==0 ){
drh44845222008-07-17 18:39:57 +00004293 if( pPage->intKey && !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00004294 lwr = idx;
drhfc70e6f2004-05-12 21:11:27 +00004295 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00004296 break;
4297 }else{
drh64022502009-01-09 14:11:04 +00004298 *pRes = 0;
drh1e968a02008-03-25 00:22:21 +00004299 rc = SQLITE_OK;
4300 goto moveto_finish;
drh8b18dd42004-05-12 19:18:15 +00004301 }
drh72f82862001-05-24 21:06:34 +00004302 }
4303 if( c<0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00004304 lwr = idx+1;
drh72f82862001-05-24 21:06:34 +00004305 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004306 upr = idx-1;
drh72f82862001-05-24 21:06:34 +00004307 }
drhf1d68b32007-03-29 04:43:26 +00004308 if( lwr>upr ){
4309 break;
4310 }
drhf49661a2008-12-10 16:45:50 +00004311 pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
drh72f82862001-05-24 21:06:34 +00004312 }
4313 assert( lwr==upr+1 );
danielk197771d5d2c2008-09-29 11:49:47 +00004314 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00004315 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00004316 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00004317 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00004318 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00004319 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00004320 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00004321 }
4322 if( chldPg==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00004323 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh72f82862001-05-24 21:06:34 +00004324 if( pRes ) *pRes = c;
drh1e968a02008-03-25 00:22:21 +00004325 rc = SQLITE_OK;
4326 goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00004327 }
drhf49661a2008-12-10 16:45:50 +00004328 pCur->aiIdx[pCur->iPage] = (u16)lwr;
drh271efa52004-05-30 19:19:05 +00004329 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004330 pCur->validNKey = 0;
drh8178a752003-01-05 21:41:40 +00004331 rc = moveToChild(pCur, chldPg);
drh1e968a02008-03-25 00:22:21 +00004332 if( rc ) goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00004333 }
drh1e968a02008-03-25 00:22:21 +00004334moveto_finish:
drhe63d9992008-08-13 19:11:48 +00004335 return rc;
4336}
4337
4338/*
4339** In this version of BtreeMoveto, pKey is a packed index record
4340** such as is generated by the OP_MakeRecord opcode. Unpack the
4341** record and then call BtreeMovetoUnpacked() to do the work.
4342*/
4343int sqlite3BtreeMoveto(
4344 BtCursor *pCur, /* Cursor open on the btree to be searched */
4345 const void *pKey, /* Packed key if the btree is an index */
4346 i64 nKey, /* Integer key for tables. Size of pKey for indices */
4347 int bias, /* Bias search to the high end */
4348 int *pRes /* Write search results here */
4349){
4350 int rc; /* Status code */
4351 UnpackedRecord *pIdxKey; /* Unpacked index key */
drh8c5d1522009-04-10 00:56:28 +00004352 char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
4353
drhe63d9992008-08-13 19:11:48 +00004354
drhe14006d2008-03-25 17:23:32 +00004355 if( pKey ){
drhf49661a2008-12-10 16:45:50 +00004356 assert( nKey==(i64)(int)nKey );
4357 pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
drh23f79d02008-08-20 22:06:47 +00004358 aSpace, sizeof(aSpace));
drhe63d9992008-08-13 19:11:48 +00004359 if( pIdxKey==0 ) return SQLITE_NOMEM;
4360 }else{
4361 pIdxKey = 0;
4362 }
4363 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
4364 if( pKey ){
4365 sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
drhe14006d2008-03-25 17:23:32 +00004366 }
drh1e968a02008-03-25 00:22:21 +00004367 return rc;
drh72f82862001-05-24 21:06:34 +00004368}
4369
drhd677b3d2007-08-20 22:48:41 +00004370
drh72f82862001-05-24 21:06:34 +00004371/*
drhc39e0002004-05-07 23:50:57 +00004372** Return TRUE if the cursor is not pointing at an entry of the table.
4373**
4374** TRUE will be returned after a call to sqlite3BtreeNext() moves
4375** past the last entry in the table or sqlite3BtreePrev() moves past
4376** the first entry. TRUE is also returned if the table is empty.
4377*/
4378int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00004379 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
4380 ** have been deleted? This API will need to change to return an error code
4381 ** as well as the boolean result value.
4382 */
4383 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00004384}
4385
4386/*
drhbd03cae2001-06-02 02:40:57 +00004387** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00004388** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00004389** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00004390** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00004391*/
drhd094db12008-04-03 21:46:57 +00004392int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00004393 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00004394 int idx;
danielk197797a227c2006-01-20 16:32:04 +00004395 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00004396
drh1fee73e2007-08-29 04:00:57 +00004397 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004398 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004399 if( rc!=SQLITE_OK ){
4400 return rc;
4401 }
drh8c4d3a62007-04-06 01:03:32 +00004402 assert( pRes!=0 );
drh8c4d3a62007-04-06 01:03:32 +00004403 if( CURSOR_INVALID==pCur->eState ){
4404 *pRes = 1;
4405 return SQLITE_OK;
4406 }
danielk1977da184232006-01-05 11:34:32 +00004407 if( pCur->skip>0 ){
4408 pCur->skip = 0;
4409 *pRes = 0;
4410 return SQLITE_OK;
4411 }
4412 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00004413
danielk197771d5d2c2008-09-29 11:49:47 +00004414 pPage = pCur->apPage[pCur->iPage];
4415 idx = ++pCur->aiIdx[pCur->iPage];
4416 assert( pPage->isInit );
4417 assert( idx<=pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00004418
drh271efa52004-05-30 19:19:05 +00004419 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004420 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004421 if( idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00004422 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004423 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00004424 if( rc ) return rc;
4425 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00004426 *pRes = 0;
4427 return rc;
drh72f82862001-05-24 21:06:34 +00004428 }
drh5e2f8b92001-05-28 00:41:15 +00004429 do{
danielk197771d5d2c2008-09-29 11:49:47 +00004430 if( pCur->iPage==0 ){
drh8c1238a2003-01-02 14:43:55 +00004431 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00004432 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00004433 return SQLITE_OK;
4434 }
drh16a9b832007-05-05 18:39:25 +00004435 sqlite3BtreeMoveToParent(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00004436 pPage = pCur->apPage[pCur->iPage];
4437 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00004438 *pRes = 0;
drh44845222008-07-17 18:39:57 +00004439 if( pPage->intKey ){
drh8b18dd42004-05-12 19:18:15 +00004440 rc = sqlite3BtreeNext(pCur, pRes);
4441 }else{
4442 rc = SQLITE_OK;
4443 }
4444 return rc;
drh8178a752003-01-05 21:41:40 +00004445 }
4446 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00004447 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00004448 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00004449 }
drh5e2f8b92001-05-28 00:41:15 +00004450 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00004451 return rc;
drh72f82862001-05-24 21:06:34 +00004452}
drhd677b3d2007-08-20 22:48:41 +00004453
drh72f82862001-05-24 21:06:34 +00004454
drh3b7511c2001-05-26 13:15:44 +00004455/*
drh2dcc9aa2002-12-04 13:40:25 +00004456** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00004457** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00004458** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00004459** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00004460*/
drhd094db12008-04-03 21:46:57 +00004461int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00004462 int rc;
drh8178a752003-01-05 21:41:40 +00004463 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00004464
drh1fee73e2007-08-29 04:00:57 +00004465 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004466 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004467 if( rc!=SQLITE_OK ){
4468 return rc;
4469 }
drha2c20e42008-03-29 16:01:04 +00004470 pCur->atLast = 0;
drh8c4d3a62007-04-06 01:03:32 +00004471 if( CURSOR_INVALID==pCur->eState ){
4472 *pRes = 1;
4473 return SQLITE_OK;
4474 }
danielk1977da184232006-01-05 11:34:32 +00004475 if( pCur->skip<0 ){
4476 pCur->skip = 0;
4477 *pRes = 0;
4478 return SQLITE_OK;
4479 }
4480 pCur->skip = 0;
danielk1977da184232006-01-05 11:34:32 +00004481
danielk197771d5d2c2008-09-29 11:49:47 +00004482 pPage = pCur->apPage[pCur->iPage];
4483 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00004484 if( !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00004485 int idx = pCur->aiIdx[pCur->iPage];
4486 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
drhd677b3d2007-08-20 22:48:41 +00004487 if( rc ){
4488 return rc;
4489 }
drh2dcc9aa2002-12-04 13:40:25 +00004490 rc = moveToRightmost(pCur);
4491 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004492 while( pCur->aiIdx[pCur->iPage]==0 ){
4493 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00004494 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00004495 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00004496 return SQLITE_OK;
4497 }
drh16a9b832007-05-05 18:39:25 +00004498 sqlite3BtreeMoveToParent(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00004499 }
drh271efa52004-05-30 19:19:05 +00004500 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004501 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004502
4503 pCur->aiIdx[pCur->iPage]--;
4504 pPage = pCur->apPage[pCur->iPage];
drh44845222008-07-17 18:39:57 +00004505 if( pPage->intKey && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00004506 rc = sqlite3BtreePrevious(pCur, pRes);
4507 }else{
4508 rc = SQLITE_OK;
4509 }
drh2dcc9aa2002-12-04 13:40:25 +00004510 }
drh8178a752003-01-05 21:41:40 +00004511 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00004512 return rc;
4513}
4514
4515/*
drh3b7511c2001-05-26 13:15:44 +00004516** Allocate a new page from the database file.
4517**
danielk19773b8a05f2007-03-19 17:44:26 +00004518** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00004519** has already been called on the new page.) The new page has also
4520** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00004521** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00004522**
4523** SQLITE_OK is returned on success. Any other return value indicates
4524** an error. *ppPage and *pPgno are undefined in the event of an error.
danielk19773b8a05f2007-03-19 17:44:26 +00004525** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00004526**
drh199e3cf2002-07-18 11:01:47 +00004527** If the "nearby" parameter is not 0, then a (feeble) effort is made to
4528** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00004529** attempt to keep related pages close to each other in the database file,
4530** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00004531**
4532** If the "exact" parameter is not 0, and the page-number nearby exists
4533** anywhere on the free-list, then it is guarenteed to be returned. This
4534** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00004535*/
drh4f0c5872007-03-26 22:05:01 +00004536static int allocateBtreePage(
danielk1977aef0bf62005-12-30 16:28:01 +00004537 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00004538 MemPage **ppPage,
4539 Pgno *pPgno,
4540 Pgno nearby,
4541 u8 exact
4542){
drh3aac2dd2004-04-26 14:10:20 +00004543 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00004544 int rc;
drh35cd6432009-06-05 14:17:21 +00004545 u32 n; /* Number of pages on the freelist */
drh042d6a12009-06-17 13:57:16 +00004546 u32 k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00004547 MemPage *pTrunk = 0;
4548 MemPage *pPrevTrunk = 0;
drh1662b5a2009-06-04 19:06:09 +00004549 Pgno mxPage; /* Total size of the database file */
drh30e58752002-03-02 20:41:57 +00004550
drh1fee73e2007-08-29 04:00:57 +00004551 assert( sqlite3_mutex_held(pBt->mutex) );
drh3aac2dd2004-04-26 14:10:20 +00004552 pPage1 = pBt->pPage1;
drh1662b5a2009-06-04 19:06:09 +00004553 mxPage = pagerPagecount(pBt);
drh3aac2dd2004-04-26 14:10:20 +00004554 n = get4byte(&pPage1->aData[36]);
drh1662b5a2009-06-04 19:06:09 +00004555 if( n>mxPage ){
4556 return SQLITE_CORRUPT_BKPT;
4557 }
drh3aac2dd2004-04-26 14:10:20 +00004558 if( n>0 ){
drh91025292004-05-03 19:49:32 +00004559 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00004560 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004561 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
4562
4563 /* If the 'exact' parameter was true and a query of the pointer-map
4564 ** shows that the page 'nearby' is somewhere on the free-list, then
4565 ** the entire-list will be searched for that page.
4566 */
4567#ifndef SQLITE_OMIT_AUTOVACUUM
drh1662b5a2009-06-04 19:06:09 +00004568 if( exact && nearby<=mxPage ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004569 u8 eType;
4570 assert( nearby>0 );
4571 assert( pBt->autoVacuum );
4572 rc = ptrmapGet(pBt, nearby, &eType, 0);
4573 if( rc ) return rc;
4574 if( eType==PTRMAP_FREEPAGE ){
4575 searchList = 1;
4576 }
4577 *pPgno = nearby;
4578 }
4579#endif
4580
4581 /* Decrement the free-list count by 1. Set iTrunk to the index of the
4582 ** first free-list trunk page. iPrevTrunk is initially 1.
4583 */
danielk19773b8a05f2007-03-19 17:44:26 +00004584 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00004585 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004586 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004587
4588 /* The code within this loop is run only once if the 'searchList' variable
4589 ** is not true. Otherwise, it runs once for each trunk-page on the
4590 ** free-list until the page 'nearby' is located.
4591 */
4592 do {
4593 pPrevTrunk = pTrunk;
4594 if( pPrevTrunk ){
4595 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00004596 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004597 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00004598 }
drh1662b5a2009-06-04 19:06:09 +00004599 if( iTrunk>mxPage ){
4600 rc = SQLITE_CORRUPT_BKPT;
4601 }else{
4602 rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
4603 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004604 if( rc ){
drhd3627af2006-12-18 18:34:51 +00004605 pTrunk = 0;
4606 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004607 }
4608
4609 k = get4byte(&pTrunk->aData[4]);
4610 if( k==0 && !searchList ){
4611 /* The trunk has no leaves and the list is not being searched.
4612 ** So extract the trunk page itself and use it as the newly
4613 ** allocated page */
4614 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00004615 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004616 if( rc ){
4617 goto end_allocate_page;
4618 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004619 *pPgno = iTrunk;
4620 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4621 *ppPage = pTrunk;
4622 pTrunk = 0;
4623 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh042d6a12009-06-17 13:57:16 +00004624 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004625 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00004626 rc = SQLITE_CORRUPT_BKPT;
4627 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004628#ifndef SQLITE_OMIT_AUTOVACUUM
4629 }else if( searchList && nearby==iTrunk ){
4630 /* The list is being searched and this trunk page is the page
4631 ** to allocate, regardless of whether it has leaves.
4632 */
4633 assert( *pPgno==iTrunk );
4634 *ppPage = pTrunk;
4635 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00004636 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004637 if( rc ){
4638 goto end_allocate_page;
4639 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004640 if( k==0 ){
4641 if( !pPrevTrunk ){
4642 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4643 }else{
4644 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
4645 }
4646 }else{
4647 /* The trunk page is required by the caller but it contains
4648 ** pointers to free-list leaves. The first leaf becomes a trunk
4649 ** page in this case.
4650 */
4651 MemPage *pNewTrunk;
4652 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh1662b5a2009-06-04 19:06:09 +00004653 if( iNewTrunk>mxPage ){
4654 rc = SQLITE_CORRUPT_BKPT;
4655 goto end_allocate_page;
4656 }
drh16a9b832007-05-05 18:39:25 +00004657 rc = sqlite3BtreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004658 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00004659 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004660 }
danielk19773b8a05f2007-03-19 17:44:26 +00004661 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004662 if( rc!=SQLITE_OK ){
4663 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00004664 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004665 }
4666 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
4667 put4byte(&pNewTrunk->aData[4], k-1);
4668 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00004669 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004670 if( !pPrevTrunk ){
drhc5053fb2008-11-27 02:22:10 +00004671 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
danielk1977cb1a7eb2004-11-05 12:27:02 +00004672 put4byte(&pPage1->aData[32], iNewTrunk);
4673 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00004674 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004675 if( rc ){
4676 goto end_allocate_page;
4677 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004678 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
4679 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004680 }
4681 pTrunk = 0;
4682 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
4683#endif
danielk1977e5765212009-06-17 11:13:28 +00004684 }else if( k>0 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004685 /* Extract a leaf from the trunk */
drh042d6a12009-06-17 13:57:16 +00004686 u32 closest;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004687 Pgno iPage;
4688 unsigned char *aData = pTrunk->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00004689 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004690 if( rc ){
4691 goto end_allocate_page;
4692 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004693 if( nearby>0 ){
drh042d6a12009-06-17 13:57:16 +00004694 u32 i;
4695 int dist;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004696 closest = 0;
4697 dist = get4byte(&aData[8]) - nearby;
4698 if( dist<0 ) dist = -dist;
4699 for(i=1; i<k; i++){
4700 int d2 = get4byte(&aData[8+i*4]) - nearby;
4701 if( d2<0 ) d2 = -d2;
4702 if( d2<dist ){
4703 closest = i;
4704 dist = d2;
4705 }
4706 }
4707 }else{
4708 closest = 0;
4709 }
4710
4711 iPage = get4byte(&aData[8+closest*4]);
drh1662b5a2009-06-04 19:06:09 +00004712 if( iPage>mxPage ){
4713 rc = SQLITE_CORRUPT_BKPT;
4714 goto end_allocate_page;
4715 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004716 if( !searchList || iPage==nearby ){
danielk1977bea2a942009-01-20 17:06:27 +00004717 int noContent;
danielk197789d40042008-11-17 14:20:56 +00004718 Pgno nPage;
shane1f9e6aa2008-06-09 19:27:11 +00004719 *pPgno = iPage;
danielk197789d40042008-11-17 14:20:56 +00004720 nPage = pagerPagecount(pBt);
danielk19774dbaa892009-06-16 16:50:22 +00004721 if( iPage>nPage ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004722 /* Free page off the end of the file */
danielk197743e377a2008-05-05 12:09:32 +00004723 rc = SQLITE_CORRUPT_BKPT;
4724 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004725 }
4726 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
4727 ": %d more free pages\n",
4728 *pPgno, closest+1, k, pTrunk->pgno, n-1));
4729 if( closest<k-1 ){
4730 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
4731 }
4732 put4byte(&aData[4], k-1);
drhc5053fb2008-11-27 02:22:10 +00004733 assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
danielk1977bea2a942009-01-20 17:06:27 +00004734 noContent = !btreeGetHasContent(pBt, *pPgno);
4735 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, noContent);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004736 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00004737 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004738 if( rc!=SQLITE_OK ){
4739 releasePage(*ppPage);
4740 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004741 }
4742 searchList = 0;
4743 }
drhee696e22004-08-30 16:52:17 +00004744 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004745 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00004746 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004747 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00004748 }else{
drh3aac2dd2004-04-26 14:10:20 +00004749 /* There are no pages on the freelist, so create a new page at the
4750 ** end of the file */
danielk197789d40042008-11-17 14:20:56 +00004751 int nPage = pagerPagecount(pBt);
danielk1977ad0132d2008-06-07 08:58:22 +00004752 *pPgno = nPage + 1;
danielk1977afcdd022004-10-31 16:25:42 +00004753
danielk1977bea2a942009-01-20 17:06:27 +00004754 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
4755 (*pPgno)++;
4756 }
4757
danielk1977afcdd022004-10-31 16:25:42 +00004758#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977266664d2006-02-10 08:24:21 +00004759 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00004760 /* If *pPgno refers to a pointer-map page, allocate two new pages
4761 ** at the end of the file instead of one. The first allocated page
4762 ** becomes a new pointer-map page, the second is used by the caller.
4763 */
danielk1977ac861692009-03-28 10:54:22 +00004764 MemPage *pPg = 0;
danielk1977afcdd022004-10-31 16:25:42 +00004765 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00004766 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk1977ac861692009-03-28 10:54:22 +00004767 rc = sqlite3BtreeGetPage(pBt, *pPgno, &pPg, 0);
4768 if( rc==SQLITE_OK ){
4769 rc = sqlite3PagerWrite(pPg->pDbPage);
4770 releasePage(pPg);
4771 }
4772 if( rc ) return rc;
danielk1977afcdd022004-10-31 16:25:42 +00004773 (*pPgno)++;
drh72190432008-01-31 14:54:43 +00004774 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
danielk1977afcdd022004-10-31 16:25:42 +00004775 }
4776#endif
4777
danielk1977599fcba2004-11-08 07:13:13 +00004778 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh16a9b832007-05-05 18:39:25 +00004779 rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 0);
drh3b7511c2001-05-26 13:15:44 +00004780 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00004781 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004782 if( rc!=SQLITE_OK ){
4783 releasePage(*ppPage);
4784 }
drh3a4c1412004-05-09 20:40:11 +00004785 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00004786 }
danielk1977599fcba2004-11-08 07:13:13 +00004787
4788 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00004789
4790end_allocate_page:
4791 releasePage(pTrunk);
4792 releasePage(pPrevTrunk);
danielk1977b247c212008-11-21 09:09:01 +00004793 if( rc==SQLITE_OK ){
4794 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
4795 releasePage(*ppPage);
4796 return SQLITE_CORRUPT_BKPT;
4797 }
4798 (*ppPage)->isInit = 0;
danielk1977a50d9aa2009-06-08 14:49:45 +00004799 }else{
4800 *ppPage = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00004801 }
drh3b7511c2001-05-26 13:15:44 +00004802 return rc;
4803}
4804
4805/*
danielk1977bea2a942009-01-20 17:06:27 +00004806** This function is used to add page iPage to the database file free-list.
4807** It is assumed that the page is not already a part of the free-list.
drh5e2f8b92001-05-28 00:41:15 +00004808**
danielk1977bea2a942009-01-20 17:06:27 +00004809** The value passed as the second argument to this function is optional.
4810** If the caller happens to have a pointer to the MemPage object
4811** corresponding to page iPage handy, it may pass it as the second value.
4812** Otherwise, it may pass NULL.
4813**
4814** If a pointer to a MemPage object is passed as the second argument,
4815** its reference count is not altered by this function.
drh3b7511c2001-05-26 13:15:44 +00004816*/
danielk1977bea2a942009-01-20 17:06:27 +00004817static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
4818 MemPage *pTrunk = 0; /* Free-list trunk page */
4819 Pgno iTrunk = 0; /* Page number of free-list trunk page */
4820 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
4821 MemPage *pPage; /* Page being freed. May be NULL. */
4822 int rc; /* Return Code */
4823 int nFree; /* Initial number of pages on free-list */
drh8b2f49b2001-06-08 00:21:52 +00004824
danielk1977bea2a942009-01-20 17:06:27 +00004825 assert( sqlite3_mutex_held(pBt->mutex) );
4826 assert( iPage>1 );
4827 assert( !pMemPage || pMemPage->pgno==iPage );
4828
4829 if( pMemPage ){
4830 pPage = pMemPage;
4831 sqlite3PagerRef(pPage->pDbPage);
4832 }else{
4833 pPage = btreePageLookup(pBt, iPage);
4834 }
drh3aac2dd2004-04-26 14:10:20 +00004835
drha34b6762004-05-07 13:30:42 +00004836 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00004837 rc = sqlite3PagerWrite(pPage1->pDbPage);
danielk1977bea2a942009-01-20 17:06:27 +00004838 if( rc ) goto freepage_out;
4839 nFree = get4byte(&pPage1->aData[36]);
4840 put4byte(&pPage1->aData[36], nFree+1);
drh3aac2dd2004-04-26 14:10:20 +00004841
drhfcce93f2006-02-22 03:08:32 +00004842#ifdef SQLITE_SECURE_DELETE
4843 /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
4844 ** always fully overwrite deleted information with zeros.
4845 */
danielk1977bea2a942009-01-20 17:06:27 +00004846 if( (!pPage && (rc = sqlite3BtreeGetPage(pBt, iPage, &pPage, 0)))
4847 || (rc = sqlite3PagerWrite(pPage->pDbPage))
4848 ){
4849 goto freepage_out;
4850 }
drhfcce93f2006-02-22 03:08:32 +00004851 memset(pPage->aData, 0, pPage->pBt->pageSize);
4852#endif
4853
danielk1977687566d2004-11-02 12:56:41 +00004854 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00004855 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00004856 */
danielk197785d90ca2008-07-19 14:25:15 +00004857 if( ISAUTOVACUUM ){
danielk1977bea2a942009-01-20 17:06:27 +00004858 rc = ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0);
4859 if( rc ) goto freepage_out;
danielk1977687566d2004-11-02 12:56:41 +00004860 }
danielk1977687566d2004-11-02 12:56:41 +00004861
danielk1977bea2a942009-01-20 17:06:27 +00004862 /* Now manipulate the actual database free-list structure. There are two
4863 ** possibilities. If the free-list is currently empty, or if the first
4864 ** trunk page in the free-list is full, then this page will become a
4865 ** new free-list trunk page. Otherwise, it will become a leaf of the
4866 ** first trunk page in the current free-list. This block tests if it
4867 ** is possible to add the page as a new free-list leaf.
4868 */
4869 if( nFree!=0 ){
4870 int nLeaf; /* Initial number of leaf cells on trunk page */
4871
4872 iTrunk = get4byte(&pPage1->aData[32]);
4873 rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
4874 if( rc!=SQLITE_OK ){
4875 goto freepage_out;
4876 }
4877
4878 nLeaf = get4byte(&pTrunk->aData[4]);
4879 if( nLeaf<0 ){
4880 rc = SQLITE_CORRUPT_BKPT;
4881 goto freepage_out;
4882 }
4883 if( nLeaf<pBt->usableSize/4 - 8 ){
4884 /* In this case there is room on the trunk page to insert the page
4885 ** being freed as a new leaf.
drh45b1fac2008-07-04 17:52:42 +00004886 **
4887 ** Note that the trunk page is not really full until it contains
4888 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
4889 ** coded. But due to a coding error in versions of SQLite prior to
4890 ** 3.6.0, databases with freelist trunk pages holding more than
4891 ** usableSize/4 - 8 entries will be reported as corrupt. In order
4892 ** to maintain backwards compatibility with older versions of SQLite,
4893 ** we will contain to restrict the number of entries to usableSize/4 - 8
4894 ** for now. At some point in the future (once everyone has upgraded
4895 ** to 3.6.0 or later) we should consider fixing the conditional above
4896 ** to read "usableSize/4-2" instead of "usableSize/4-8".
4897 */
danielk19773b8a05f2007-03-19 17:44:26 +00004898 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00004899 if( rc==SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00004900 put4byte(&pTrunk->aData[4], nLeaf+1);
4901 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
drhfcce93f2006-02-22 03:08:32 +00004902#ifndef SQLITE_SECURE_DELETE
danielk1977bea2a942009-01-20 17:06:27 +00004903 if( pPage ){
4904 sqlite3PagerDontWrite(pPage->pDbPage);
4905 }
drhfcce93f2006-02-22 03:08:32 +00004906#endif
danielk1977bea2a942009-01-20 17:06:27 +00004907 rc = btreeSetHasContent(pBt, iPage);
drhf5345442007-04-09 12:45:02 +00004908 }
drh3a4c1412004-05-09 20:40:11 +00004909 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
danielk1977bea2a942009-01-20 17:06:27 +00004910 goto freepage_out;
drh3aac2dd2004-04-26 14:10:20 +00004911 }
drh3b7511c2001-05-26 13:15:44 +00004912 }
danielk1977bea2a942009-01-20 17:06:27 +00004913
4914 /* If control flows to this point, then it was not possible to add the
4915 ** the page being freed as a leaf page of the first trunk in the free-list.
4916 ** Possibly because the free-list is empty, or possibly because the
4917 ** first trunk in the free-list is full. Either way, the page being freed
4918 ** will become the new first trunk page in the free-list.
4919 */
shane63207ab2009-02-04 01:49:30 +00004920 if( ((!pPage) && (0 != (rc = sqlite3BtreeGetPage(pBt, iPage, &pPage, 0))))
4921 || (0 != (rc = sqlite3PagerWrite(pPage->pDbPage)))
danielk1977bea2a942009-01-20 17:06:27 +00004922 ){
4923 goto freepage_out;
4924 }
4925 put4byte(pPage->aData, iTrunk);
4926 put4byte(&pPage->aData[4], 0);
4927 put4byte(&pPage1->aData[32], iPage);
4928 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
4929
4930freepage_out:
4931 if( pPage ){
4932 pPage->isInit = 0;
4933 }
4934 releasePage(pPage);
4935 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00004936 return rc;
4937}
danielk1977bea2a942009-01-20 17:06:27 +00004938static int freePage(MemPage *pPage){
4939 return freePage2(pPage->pBt, pPage, pPage->pgno);
4940}
drh3b7511c2001-05-26 13:15:44 +00004941
4942/*
drh3aac2dd2004-04-26 14:10:20 +00004943** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00004944*/
drh3aac2dd2004-04-26 14:10:20 +00004945static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00004946 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00004947 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00004948 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00004949 int rc;
drh94440812007-03-06 11:42:19 +00004950 int nOvfl;
shane63207ab2009-02-04 01:49:30 +00004951 u16 ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00004952
drh1fee73e2007-08-29 04:00:57 +00004953 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh16a9b832007-05-05 18:39:25 +00004954 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004955 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00004956 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00004957 }
drh6f11bef2004-05-13 01:12:56 +00004958 ovflPgno = get4byte(&pCell[info.iOverflow]);
shane63207ab2009-02-04 01:49:30 +00004959 assert( pBt->usableSize > 4 );
drh94440812007-03-06 11:42:19 +00004960 ovflPageSize = pBt->usableSize - 4;
drh72365832007-03-06 15:53:44 +00004961 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
4962 assert( ovflPgno==0 || nOvfl>0 );
4963 while( nOvfl-- ){
shane63207ab2009-02-04 01:49:30 +00004964 Pgno iNext = 0;
danielk1977bea2a942009-01-20 17:06:27 +00004965 MemPage *pOvfl = 0;
danielk1977e589a672009-04-11 16:06:15 +00004966 if( ovflPgno<2 || ovflPgno>pagerPagecount(pBt) ){
4967 /* 0 is not a legal page number and page 1 cannot be an
4968 ** overflow page. Therefore if ovflPgno<2 or past the end of the
4969 ** file the database must be corrupt. */
drh49285702005-09-17 15:20:26 +00004970 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00004971 }
danielk1977bea2a942009-01-20 17:06:27 +00004972 if( nOvfl ){
4973 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
4974 if( rc ) return rc;
4975 }
4976 rc = freePage2(pBt, pOvfl, ovflPgno);
4977 if( pOvfl ){
4978 sqlite3PagerUnref(pOvfl->pDbPage);
4979 }
drh3b7511c2001-05-26 13:15:44 +00004980 if( rc ) return rc;
danielk1977bea2a942009-01-20 17:06:27 +00004981 ovflPgno = iNext;
drh3b7511c2001-05-26 13:15:44 +00004982 }
drh5e2f8b92001-05-28 00:41:15 +00004983 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00004984}
4985
4986/*
drh91025292004-05-03 19:49:32 +00004987** Create the byte sequence used to represent a cell on page pPage
4988** and write that byte sequence into pCell[]. Overflow pages are
4989** allocated and filled in as necessary. The calling procedure
4990** is responsible for making sure sufficient space has been allocated
4991** for pCell[].
4992**
4993** Note that pCell does not necessary need to point to the pPage->aData
4994** area. pCell might point to some temporary storage. The cell will
4995** be constructed in this temporary area then copied into pPage->aData
4996** later.
drh3b7511c2001-05-26 13:15:44 +00004997*/
4998static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00004999 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00005000 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00005001 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00005002 const void *pData,int nData, /* The data */
drhb026e052007-05-02 01:34:31 +00005003 int nZero, /* Extra zero bytes to append to pData */
drh4b70f112004-05-02 21:12:19 +00005004 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00005005){
drh3b7511c2001-05-26 13:15:44 +00005006 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00005007 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00005008 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00005009 int spaceLeft;
5010 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00005011 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00005012 unsigned char *pPrior;
5013 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00005014 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00005015 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00005016 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00005017 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00005018
drh1fee73e2007-08-29 04:00:57 +00005019 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00005020
drhc5053fb2008-11-27 02:22:10 +00005021 /* pPage is not necessarily writeable since pCell might be auxiliary
5022 ** buffer space that is separate from the pPage buffer area */
5023 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
5024 || sqlite3PagerIswriteable(pPage->pDbPage) );
5025
drh91025292004-05-03 19:49:32 +00005026 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00005027 nHeader = 0;
drh91025292004-05-03 19:49:32 +00005028 if( !pPage->leaf ){
5029 nHeader += 4;
5030 }
drh8b18dd42004-05-12 19:18:15 +00005031 if( pPage->hasData ){
drhb026e052007-05-02 01:34:31 +00005032 nHeader += putVarint(&pCell[nHeader], nData+nZero);
drh6f11bef2004-05-13 01:12:56 +00005033 }else{
drhb026e052007-05-02 01:34:31 +00005034 nData = nZero = 0;
drh91025292004-05-03 19:49:32 +00005035 }
drh6f11bef2004-05-13 01:12:56 +00005036 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh16a9b832007-05-05 18:39:25 +00005037 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005038 assert( info.nHeader==nHeader );
5039 assert( info.nKey==nKey );
danielk197789d40042008-11-17 14:20:56 +00005040 assert( info.nData==(u32)(nData+nZero) );
drh6f11bef2004-05-13 01:12:56 +00005041
5042 /* Fill in the payload */
drhb026e052007-05-02 01:34:31 +00005043 nPayload = nData + nZero;
drh3aac2dd2004-04-26 14:10:20 +00005044 if( pPage->intKey ){
5045 pSrc = pData;
5046 nSrc = nData;
drh91025292004-05-03 19:49:32 +00005047 nData = 0;
drhf49661a2008-12-10 16:45:50 +00005048 }else{
drh20abac22009-01-28 20:21:17 +00005049 if( nKey>0x7fffffff || pKey==0 ){
5050 return SQLITE_CORRUPT;
5051 }
drhf49661a2008-12-10 16:45:50 +00005052 nPayload += (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00005053 pSrc = pKey;
drhf49661a2008-12-10 16:45:50 +00005054 nSrc = (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00005055 }
drh6f11bef2004-05-13 01:12:56 +00005056 *pnSize = info.nSize;
5057 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00005058 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00005059 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00005060
drh3b7511c2001-05-26 13:15:44 +00005061 while( nPayload>0 ){
5062 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00005063#ifndef SQLITE_OMIT_AUTOVACUUM
5064 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00005065 if( pBt->autoVacuum ){
5066 do{
5067 pgnoOvfl++;
5068 } while(
5069 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
5070 );
danielk1977b39f70b2007-05-17 18:28:11 +00005071 }
danielk1977afcdd022004-10-31 16:25:42 +00005072#endif
drhf49661a2008-12-10 16:45:50 +00005073 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00005074#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00005075 /* If the database supports auto-vacuum, and the second or subsequent
5076 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00005077 ** for that page now.
5078 **
5079 ** If this is the first overflow page, then write a partial entry
5080 ** to the pointer-map. If we write nothing to this pointer-map slot,
5081 ** then the optimistic overflow chain processing in clearCell()
5082 ** may misinterpret the uninitialised values and delete the
5083 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00005084 */
danielk19774ef24492007-05-23 09:52:41 +00005085 if( pBt->autoVacuum && rc==SQLITE_OK ){
5086 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
5087 rc = ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap);
danielk197789a4be82007-05-23 13:34:32 +00005088 if( rc ){
5089 releasePage(pOvfl);
5090 }
danielk1977afcdd022004-10-31 16:25:42 +00005091 }
5092#endif
drh3b7511c2001-05-26 13:15:44 +00005093 if( rc ){
drh9b171272004-05-08 02:03:22 +00005094 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00005095 return rc;
5096 }
drhc5053fb2008-11-27 02:22:10 +00005097
5098 /* If pToRelease is not zero than pPrior points into the data area
5099 ** of pToRelease. Make sure pToRelease is still writeable. */
5100 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
5101
5102 /* If pPrior is part of the data area of pPage, then make sure pPage
5103 ** is still writeable */
5104 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
5105 || sqlite3PagerIswriteable(pPage->pDbPage) );
5106
drh3aac2dd2004-04-26 14:10:20 +00005107 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00005108 releasePage(pToRelease);
5109 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00005110 pPrior = pOvfl->aData;
5111 put4byte(pPrior, 0);
5112 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00005113 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00005114 }
5115 n = nPayload;
5116 if( n>spaceLeft ) n = spaceLeft;
drhc5053fb2008-11-27 02:22:10 +00005117
5118 /* If pToRelease is not zero than pPayload points into the data area
5119 ** of pToRelease. Make sure pToRelease is still writeable. */
5120 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
5121
5122 /* If pPayload is part of the data area of pPage, then make sure pPage
5123 ** is still writeable */
5124 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
5125 || sqlite3PagerIswriteable(pPage->pDbPage) );
5126
drhb026e052007-05-02 01:34:31 +00005127 if( nSrc>0 ){
5128 if( n>nSrc ) n = nSrc;
5129 assert( pSrc );
5130 memcpy(pPayload, pSrc, n);
5131 }else{
5132 memset(pPayload, 0, n);
5133 }
drh3b7511c2001-05-26 13:15:44 +00005134 nPayload -= n;
drhde647132004-05-07 17:57:49 +00005135 pPayload += n;
drh9b171272004-05-08 02:03:22 +00005136 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00005137 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00005138 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00005139 if( nSrc==0 ){
5140 nSrc = nData;
5141 pSrc = pData;
5142 }
drhdd793422001-06-28 01:54:48 +00005143 }
drh9b171272004-05-08 02:03:22 +00005144 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00005145 return SQLITE_OK;
5146}
5147
drh14acc042001-06-10 19:56:58 +00005148/*
5149** Remove the i-th cell from pPage. This routine effects pPage only.
5150** The cell content is not freed or deallocated. It is assumed that
5151** the cell content has been copied someplace else. This routine just
5152** removes the reference to the cell from pPage.
5153**
5154** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00005155*/
shane0af3f892008-11-12 04:55:34 +00005156static int dropCell(MemPage *pPage, int idx, int sz){
drh43605152004-05-29 21:46:49 +00005157 int i; /* Loop counter */
5158 int pc; /* Offset to cell content of cell being deleted */
5159 u8 *data; /* pPage->aData */
5160 u8 *ptr; /* Used to move bytes around within data[] */
shanedcc50b72008-11-13 18:29:50 +00005161 int rc; /* The return code */
drh43605152004-05-29 21:46:49 +00005162
drh8c42ca92001-06-22 19:15:00 +00005163 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00005164 assert( sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00005165 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00005166 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00005167 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00005168 ptr = &data[pPage->cellOffset + 2*idx];
shane0af3f892008-11-12 04:55:34 +00005169 pc = get2byte(ptr);
drhc5053fb2008-11-27 02:22:10 +00005170 if( (pc<pPage->hdrOffset+6+(pPage->leaf?0:4))
5171 || (pc+sz>pPage->pBt->usableSize) ){
shane0af3f892008-11-12 04:55:34 +00005172 return SQLITE_CORRUPT_BKPT;
5173 }
shanedcc50b72008-11-13 18:29:50 +00005174 rc = freeSpace(pPage, pc, sz);
5175 if( rc!=SQLITE_OK ){
5176 return rc;
5177 }
drh43605152004-05-29 21:46:49 +00005178 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
5179 ptr[0] = ptr[2];
5180 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00005181 }
5182 pPage->nCell--;
drh43605152004-05-29 21:46:49 +00005183 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
5184 pPage->nFree += 2;
shane0af3f892008-11-12 04:55:34 +00005185 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00005186}
5187
5188/*
5189** Insert a new cell on pPage at cell index "i". pCell points to the
5190** content of the cell.
5191**
5192** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00005193** will not fit, then make a copy of the cell content into pTemp if
5194** pTemp is not null. Regardless of pTemp, allocate a new entry
5195** in pPage->aOvfl[] and make it point to the cell content (either
5196** in pTemp or the original pCell) and also record its index.
5197** Allocating a new entry in pPage->aCell[] implies that
5198** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00005199**
5200** If nSkip is non-zero, then do not copy the first nSkip bytes of the
5201** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00005202** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00005203** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00005204*/
danielk1977e80463b2004-11-03 03:01:16 +00005205static int insertCell(
drh24cd67e2004-05-10 16:18:47 +00005206 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00005207 int i, /* New cell becomes the i-th cell of the page */
5208 u8 *pCell, /* Content of the new cell */
5209 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00005210 u8 *pTemp, /* Temp storage space for pCell, if needed */
danielk19774dbaa892009-06-16 16:50:22 +00005211 Pgno iChild /* If non-zero, replace first 4 bytes with this value */
drh24cd67e2004-05-10 16:18:47 +00005212){
drh43605152004-05-29 21:46:49 +00005213 int idx; /* Where to write new cell content in data[] */
5214 int j; /* Loop counter */
5215 int top; /* First byte of content for any cell in data[] */
5216 int end; /* First byte past the last cell pointer in data[] */
5217 int ins; /* Index in data[] where new cell pointer is inserted */
5218 int hdr; /* Offset into data[] of the page header */
5219 int cellOffset; /* Address of first cell pointer in data[] */
5220 u8 *data; /* The content of the whole page */
5221 u8 *ptr; /* Used for moving information around in data[] */
5222
danielk19774dbaa892009-06-16 16:50:22 +00005223 int nSkip = (iChild ? 4 : 0);
5224
drh43605152004-05-29 21:46:49 +00005225 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
drhf49661a2008-12-10 16:45:50 +00005226 assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
5227 assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
drh43605152004-05-29 21:46:49 +00005228 assert( sz==cellSizePtr(pPage, pCell) );
drh1fee73e2007-08-29 04:00:57 +00005229 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +00005230 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00005231 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00005232 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00005233 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00005234 }
danielk19774dbaa892009-06-16 16:50:22 +00005235 if( iChild ){
5236 put4byte(pCell, iChild);
5237 }
drh43605152004-05-29 21:46:49 +00005238 j = pPage->nOverflow++;
danielk197789d40042008-11-17 14:20:56 +00005239 assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
drh43605152004-05-29 21:46:49 +00005240 pPage->aOvfl[j].pCell = pCell;
drhf49661a2008-12-10 16:45:50 +00005241 pPage->aOvfl[j].idx = (u16)i;
drh14acc042001-06-10 19:56:58 +00005242 }else{
danielk19776e465eb2007-08-21 13:11:00 +00005243 int rc = sqlite3PagerWrite(pPage->pDbPage);
5244 if( rc!=SQLITE_OK ){
5245 return rc;
5246 }
5247 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00005248 data = pPage->aData;
5249 hdr = pPage->hdrOffset;
5250 top = get2byte(&data[hdr+5]);
5251 cellOffset = pPage->cellOffset;
5252 end = cellOffset + 2*pPage->nCell + 2;
5253 ins = cellOffset + 2*i;
5254 if( end > top - sz ){
shane0af3f892008-11-12 04:55:34 +00005255 rc = defragmentPage(pPage);
5256 if( rc!=SQLITE_OK ){
5257 return rc;
5258 }
drh43605152004-05-29 21:46:49 +00005259 top = get2byte(&data[hdr+5]);
5260 assert( end + sz <= top );
5261 }
5262 idx = allocateSpace(pPage, sz);
5263 assert( idx>0 );
5264 assert( end <= get2byte(&data[hdr+5]) );
shane0af3f892008-11-12 04:55:34 +00005265 if (idx+sz > pPage->pBt->usableSize) {
shane34ac18d2008-11-11 22:18:20 +00005266 return SQLITE_CORRUPT_BKPT;
shane0af3f892008-11-12 04:55:34 +00005267 }
drh43605152004-05-29 21:46:49 +00005268 pPage->nCell++;
shane36840fd2009-06-26 16:32:13 +00005269 pPage->nFree = pPage->nFree - (u16)(2 + sz);
danielk1977a3ad5e72005-01-07 08:56:44 +00005270 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
danielk19774dbaa892009-06-16 16:50:22 +00005271 if( iChild ){
5272 put4byte(&data[idx], iChild);
5273 }
drh43605152004-05-29 21:46:49 +00005274 for(j=end-2, ptr=&data[j]; j>ins; j-=2, ptr-=2){
5275 ptr[0] = ptr[-2];
5276 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00005277 }
drh43605152004-05-29 21:46:49 +00005278 put2byte(&data[ins], idx);
5279 put2byte(&data[hdr+3], pPage->nCell);
danielk1977a19df672004-11-03 11:37:07 +00005280#ifndef SQLITE_OMIT_AUTOVACUUM
5281 if( pPage->pBt->autoVacuum ){
5282 /* The cell may contain a pointer to an overflow page. If so, write
5283 ** the entry for the overflow page into the pointer map.
5284 */
danielk197746aa38f2009-06-25 16:11:05 +00005285 return ptrmapPutOvflPtr(pPage, pCell);
danielk1977a19df672004-11-03 11:37:07 +00005286 }
5287#endif
drh14acc042001-06-10 19:56:58 +00005288 }
danielk1977e80463b2004-11-03 03:01:16 +00005289
danielk1977e80463b2004-11-03 03:01:16 +00005290 return SQLITE_OK;
drh14acc042001-06-10 19:56:58 +00005291}
5292
5293/*
drhfa1a98a2004-05-14 19:08:17 +00005294** Add a list of cells to a page. The page should be initially empty.
5295** The cells are guaranteed to fit on the page.
5296*/
5297static void assemblePage(
5298 MemPage *pPage, /* The page to be assemblied */
5299 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00005300 u8 **apCell, /* Pointers to cell bodies */
drha9121e42008-02-19 14:59:35 +00005301 u16 *aSize /* Sizes of the cells */
drhfa1a98a2004-05-14 19:08:17 +00005302){
5303 int i; /* Loop counter */
danielk1977fad91942009-04-29 17:49:59 +00005304 u8 *pCellptr; /* Address of next cell pointer */
drh43605152004-05-29 21:46:49 +00005305 int cellbody; /* Address of next cell body */
danielk1977fad91942009-04-29 17:49:59 +00005306 u8 * const data = pPage->aData; /* Pointer to data for pPage */
5307 const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
5308 const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
drhfa1a98a2004-05-14 19:08:17 +00005309
drh43605152004-05-29 21:46:49 +00005310 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00005311 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00005312 assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
drhc5053fb2008-11-27 02:22:10 +00005313 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977fad91942009-04-29 17:49:59 +00005314
5315 /* Check that the page has just been zeroed by zeroPage() */
5316 assert( pPage->nCell==0 );
5317 assert( get2byte(&data[hdr+5])==nUsable );
5318
5319 pCellptr = &data[pPage->cellOffset + nCell*2];
5320 cellbody = nUsable;
5321 for(i=nCell-1; i>=0; i--){
5322 pCellptr -= 2;
5323 cellbody -= aSize[i];
5324 put2byte(pCellptr, cellbody);
5325 memcpy(&data[cellbody], apCell[i], aSize[i]);
drhfa1a98a2004-05-14 19:08:17 +00005326 }
danielk1977fad91942009-04-29 17:49:59 +00005327 put2byte(&data[hdr+3], nCell);
5328 put2byte(&data[hdr+5], cellbody);
5329 pPage->nFree -= (nCell*2 + nUsable - cellbody);
drhf49661a2008-12-10 16:45:50 +00005330 pPage->nCell = (u16)nCell;
drhfa1a98a2004-05-14 19:08:17 +00005331}
5332
drh14acc042001-06-10 19:56:58 +00005333/*
drhc3b70572003-01-04 19:44:07 +00005334** The following parameters determine how many adjacent pages get involved
5335** in a balancing operation. NN is the number of neighbors on either side
5336** of the page that participate in the balancing operation. NB is the
5337** total number of pages that participate, including the target page and
5338** NN neighbors on either side.
5339**
5340** The minimum value of NN is 1 (of course). Increasing NN above 1
5341** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
5342** in exchange for a larger degradation in INSERT and UPDATE performance.
5343** The value of NN appears to give the best results overall.
5344*/
5345#define NN 1 /* Number of neighbors on either side of pPage */
5346#define NB (NN*2+1) /* Total pages involved in the balance */
5347
danielk1977ac245ec2005-01-14 13:50:11 +00005348
drh615ae552005-01-16 23:21:00 +00005349#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00005350/*
5351** This version of balance() handles the common special case where
5352** a new entry is being inserted on the extreme right-end of the
5353** tree, in other words, when the new entry will become the largest
5354** entry in the tree.
5355**
5356** Instead of trying balance the 3 right-most leaf pages, just add
5357** a new page to the right-hand side and put the one new entry in
5358** that page. This leaves the right side of the tree somewhat
5359** unbalanced. But odds are that we will be inserting new entries
5360** at the end soon afterwards so the nearly empty page will quickly
5361** fill up. On average.
5362**
5363** pPage is the leaf page which is the right-most page in the tree.
5364** pParent is its parent. pPage must have a single overflow entry
5365** which is also the right-most entry on the page.
danielk1977a50d9aa2009-06-08 14:49:45 +00005366**
5367** The pSpace buffer is used to store a temporary copy of the divider
5368** cell that will be inserted into pParent. Such a cell consists of a 4
5369** byte page number followed by a variable length integer. In other
5370** words, at most 13 bytes. Hence the pSpace buffer must be at
5371** least 13 bytes in size.
drhf222e712005-01-14 22:55:49 +00005372*/
danielk1977a50d9aa2009-06-08 14:49:45 +00005373static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
5374 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
danielk19774dbaa892009-06-16 16:50:22 +00005375 MemPage *pNew; /* Newly allocated page */
danielk19776f235cc2009-06-04 14:46:08 +00005376 int rc; /* Return Code */
5377 Pgno pgnoNew; /* Page number of pNew */
danielk1977ac245ec2005-01-14 13:50:11 +00005378
drh1fee73e2007-08-29 04:00:57 +00005379 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk1977a50d9aa2009-06-08 14:49:45 +00005380 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00005381 assert( pPage->nOverflow==1 );
5382
drhd46b6c22009-06-04 17:02:51 +00005383 if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
drhd677b3d2007-08-20 22:48:41 +00005384
danielk1977a50d9aa2009-06-08 14:49:45 +00005385 /* Allocate a new page. This page will become the right-sibling of
5386 ** pPage. Make the parent page writable, so that the new divider cell
5387 ** may be inserted. If both these operations are successful, proceed.
5388 */
drh4f0c5872007-03-26 22:05:01 +00005389 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk19774dbaa892009-06-16 16:50:22 +00005390
danielk1977eaa06f62008-09-18 17:34:44 +00005391 if( rc==SQLITE_OK ){
danielk1977a50d9aa2009-06-08 14:49:45 +00005392
5393 u8 *pOut = &pSpace[4];
danielk19776f235cc2009-06-04 14:46:08 +00005394 u8 *pCell = pPage->aOvfl[0].pCell;
5395 u16 szCell = cellSizePtr(pPage, pCell);
5396 u8 *pStop;
5397
drhc5053fb2008-11-27 02:22:10 +00005398 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00005399 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
5400 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
danielk1977eaa06f62008-09-18 17:34:44 +00005401 assemblePage(pNew, 1, &pCell, &szCell);
danielk19774dbaa892009-06-16 16:50:22 +00005402
5403 /* If this is an auto-vacuum database, update the pointer map
5404 ** with entries for the new page, and any pointer from the
5405 ** cell on the page to an overflow page. If either of these
5406 ** operations fails, the return code is set, but the contents
5407 ** of the parent page are still manipulated by thh code below.
5408 ** That is Ok, at this point the parent page is guaranteed to
5409 ** be marked as dirty. Returning an error code will cause a
5410 ** rollback, undoing any changes made to the parent page.
5411 */
5412 if( ISAUTOVACUUM ){
5413 rc = ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno);
5414 if( szCell>pNew->minLocal && rc==SQLITE_OK ){
5415 rc = ptrmapPutOvflPtr(pNew, pCell);
5416 }
5417 }
danielk1977eaa06f62008-09-18 17:34:44 +00005418
danielk19776f235cc2009-06-04 14:46:08 +00005419 /* Create a divider cell to insert into pParent. The divider cell
5420 ** consists of a 4-byte page number (the page number of pPage) and
5421 ** a variable length key value (which must be the same value as the
5422 ** largest key on pPage).
danielk1977eaa06f62008-09-18 17:34:44 +00005423 **
danielk19776f235cc2009-06-04 14:46:08 +00005424 ** To find the largest key value on pPage, first find the right-most
5425 ** cell on pPage. The first two fields of this cell are the
5426 ** record-length (a variable length integer at most 32-bits in size)
5427 ** and the key value (a variable length integer, may have any value).
5428 ** The first of the while(...) loops below skips over the record-length
5429 ** field. The second while(...) loop copies the key value from the
danielk1977a50d9aa2009-06-08 14:49:45 +00005430 ** cell on pPage into the pSpace buffer.
danielk1977eaa06f62008-09-18 17:34:44 +00005431 */
danielk1977eaa06f62008-09-18 17:34:44 +00005432 pCell = findCell(pPage, pPage->nCell-1);
danielk19776f235cc2009-06-04 14:46:08 +00005433 pStop = &pCell[9];
5434 while( (*(pCell++)&0x80) && pCell<pStop );
5435 pStop = &pCell[9];
5436 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
5437
danielk19774dbaa892009-06-16 16:50:22 +00005438 /* Insert the new divider cell into pParent. */
5439 insertCell(pParent,pParent->nCell,pSpace,(int)(pOut-pSpace),0,pPage->pgno);
danielk19776f235cc2009-06-04 14:46:08 +00005440
5441 /* Set the right-child pointer of pParent to point to the new page. */
danielk1977eaa06f62008-09-18 17:34:44 +00005442 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
5443
danielk1977e08a3c42008-09-18 18:17:03 +00005444 /* Release the reference to the new page. */
5445 releasePage(pNew);
danielk1977ac11ee62005-01-15 12:45:51 +00005446 }
5447
danielk1977eaa06f62008-09-18 17:34:44 +00005448 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00005449}
drh615ae552005-01-16 23:21:00 +00005450#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00005451
danielk19774dbaa892009-06-16 16:50:22 +00005452#if 0
drhc3b70572003-01-04 19:44:07 +00005453/*
danielk19774dbaa892009-06-16 16:50:22 +00005454** This function does not contribute anything to the operation of SQLite.
5455** it is sometimes activated temporarily while debugging code responsible
5456** for setting pointer-map entries.
5457*/
5458static int ptrmapCheckPages(MemPage **apPage, int nPage){
5459 int i, j;
5460 for(i=0; i<nPage; i++){
5461 Pgno n;
5462 u8 e;
5463 MemPage *pPage = apPage[i];
5464 BtShared *pBt = pPage->pBt;
5465 assert( pPage->isInit );
5466
5467 for(j=0; j<pPage->nCell; j++){
5468 CellInfo info;
5469 u8 *z;
5470
5471 z = findCell(pPage, j);
5472 sqlite3BtreeParseCellPtr(pPage, z, &info);
5473 if( info.iOverflow ){
5474 Pgno ovfl = get4byte(&z[info.iOverflow]);
5475 ptrmapGet(pBt, ovfl, &e, &n);
5476 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
5477 }
5478 if( !pPage->leaf ){
5479 Pgno child = get4byte(z);
5480 ptrmapGet(pBt, child, &e, &n);
5481 assert( n==pPage->pgno && e==PTRMAP_BTREE );
5482 }
5483 }
5484 if( !pPage->leaf ){
5485 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5486 ptrmapGet(pBt, child, &e, &n);
5487 assert( n==pPage->pgno && e==PTRMAP_BTREE );
5488 }
5489 }
5490 return 1;
5491}
5492#endif
5493
danielk1977cd581a72009-06-23 15:43:39 +00005494/*
5495** This function is used to copy the contents of the b-tree node stored
5496** on page pFrom to page pTo. If page pFrom was not a leaf page, then
5497** the pointer-map entries for each child page are updated so that the
5498** parent page stored in the pointer map is page pTo. If pFrom contained
5499** any cells with overflow page pointers, then the corresponding pointer
5500** map entries are also updated so that the parent page is page pTo.
5501**
5502** If pFrom is currently carrying any overflow cells (entries in the
5503** MemPage.aOvfl[] array), they are not copied to pTo.
5504**
5505** Before returning, page pTo is reinitialized using sqlite3BtreeInitPage().
5506**
5507** The performance of this function is not critical. It is only used by
5508** the balance_shallower() and balance_deeper() procedures, neither of
5509** which are called often under normal circumstances.
5510*/
5511static int copyNodeContent(MemPage *pFrom, MemPage *pTo){
5512 BtShared * const pBt = pFrom->pBt;
5513 u8 * const aFrom = pFrom->aData;
5514 u8 * const aTo = pTo->aData;
5515 int const iFromHdr = pFrom->hdrOffset;
5516 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
5517 int rc = SQLITE_OK;
5518 int iData;
5519
5520 assert( pFrom->isInit );
5521 assert( pFrom->nFree>=iToHdr );
5522 assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
5523
5524 /* Copy the b-tree node content from page pFrom to page pTo. */
5525 iData = get2byte(&aFrom[iFromHdr+5]);
5526 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
5527 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
5528
5529 /* Reinitialize page pTo so that the contents of the MemPage structure
5530 ** match the new data. The initialization of pTo "cannot" fail, as the
5531 ** data copied from pFrom is known to be valid. */
5532 pTo->isInit = 0;
5533 TESTONLY(rc = ) sqlite3BtreeInitPage(pTo);
5534 assert( rc==SQLITE_OK );
5535
5536 /* If this is an auto-vacuum database, update the pointer-map entries
5537 ** for any b-tree or overflow pages that pTo now contains the pointers to. */
5538 if( ISAUTOVACUUM ){
5539 rc = setChildPtrmaps(pTo);
5540 }
5541 return rc;
5542}
5543
5544/*
danielk19774dbaa892009-06-16 16:50:22 +00005545** This routine redistributes cells on the iParentIdx'th child of pParent
5546** (hereafter "the page") and up to 2 siblings so that all pages have about the
5547** same amount of free space. Usually a single sibling on either side of the
5548** page are used in the balancing, though both siblings might come from one
5549** side if the page is the first or last child of its parent. If the page
5550** has fewer than 2 siblings (something which can only happen if the page
5551** is a root page or a child of a root page) then all available siblings
5552** participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00005553**
danielk19774dbaa892009-06-16 16:50:22 +00005554** The number of siblings of the page might be increased or decreased by
5555** one or two in an effort to keep pages nearly full but not over full.
drh14acc042001-06-10 19:56:58 +00005556**
danielk19774dbaa892009-06-16 16:50:22 +00005557** Note that when this routine is called, some of the cells on the page
5558** might not actually be stored in MemPage.aData[]. This can happen
5559** if the page is overfull. This routine ensures that all cells allocated
5560** to the page and its siblings fit into MemPage.aData[] before returning.
drh14acc042001-06-10 19:56:58 +00005561**
danielk19774dbaa892009-06-16 16:50:22 +00005562** In the course of balancing the page and its siblings, cells may be
5563** inserted into or removed from the parent page (pParent). Doing so
5564** may cause the parent page to become overfull or underfull. If this
5565** happens, it is the responsibility of the caller to invoke the correct
5566** balancing routine to fix this problem (see the balance() routine).
drh8c42ca92001-06-22 19:15:00 +00005567**
drh5e00f6c2001-09-13 13:46:56 +00005568** If this routine fails for any reason, it might leave the database
danielk19776067a9b2009-06-09 09:41:00 +00005569** in a corrupted state. So if this routine fails, the database should
drh5e00f6c2001-09-13 13:46:56 +00005570** be rolled back.
danielk19774dbaa892009-06-16 16:50:22 +00005571**
5572** The third argument to this function, aOvflSpace, is a pointer to a
5573** buffer page-size bytes in size. If, in inserting cells into the parent
5574** page (pParent), the parent page becomes overfull, this buffer is
5575** used to store the parents overflow cells. Because this function inserts
5576** a maximum of four divider cells into the parent page, and the maximum
5577** size of a cell stored within an internal node is always less than 1/4
5578** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
5579** enough for all overflow cells.
5580**
5581** If aOvflSpace is set to a null pointer, this function returns
5582** SQLITE_NOMEM.
drh8b2f49b2001-06-08 00:21:52 +00005583*/
danielk19774dbaa892009-06-16 16:50:22 +00005584static int balance_nonroot(
5585 MemPage *pParent, /* Parent page of siblings being balanced */
5586 int iParentIdx, /* Index of "the page" in pParent */
danielk1977cd581a72009-06-23 15:43:39 +00005587 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
5588 int isRoot /* True if pParent is a root-page */
danielk19774dbaa892009-06-16 16:50:22 +00005589){
drh16a9b832007-05-05 18:39:25 +00005590 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00005591 int nCell = 0; /* Number of cells in apCell[] */
5592 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
danielk1977a4124bd2008-12-23 10:37:47 +00005593 int nNew = 0; /* Number of pages in apNew[] */
danielk19774dbaa892009-06-16 16:50:22 +00005594 int nOld; /* Number of pages in apOld[] */
drh14acc042001-06-10 19:56:58 +00005595 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00005596 int nxDiv; /* Next divider slot in pParent->aCell[] */
shane85095702009-06-15 16:27:08 +00005597 int rc = SQLITE_OK; /* The return code */
shane36840fd2009-06-26 16:32:13 +00005598 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00005599 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00005600 int usableSpace; /* Bytes in pPage beyond the header */
5601 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00005602 int subtotal; /* Subtotal of bytes in cells on one page */
drhe5ae5732008-06-15 02:51:47 +00005603 int iSpace1 = 0; /* First unused byte of aSpace1[] */
danielk19776067a9b2009-06-09 09:41:00 +00005604 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
drhfacf0302008-06-17 15:12:00 +00005605 int szScratch; /* Size of scratch memory requested */
drhc3b70572003-01-04 19:44:07 +00005606 MemPage *apOld[NB]; /* pPage and up to two siblings */
drh4b70f112004-05-02 21:12:19 +00005607 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00005608 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
danielk19774dbaa892009-06-16 16:50:22 +00005609 u8 *pRight; /* Location in parent of right-sibling pointer */
5610 u8 *apDiv[NB-1]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00005611 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
5612 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00005613 u8 **apCell = 0; /* All cells begin balanced */
drha9121e42008-02-19 14:59:35 +00005614 u16 *szCell; /* Local size of all cells in apCell[] */
danielk19774dbaa892009-06-16 16:50:22 +00005615 u8 *aSpace1; /* Space for copies of dividers cells */
5616 Pgno pgno; /* Temp var to store a page number in */
drh8b2f49b2001-06-08 00:21:52 +00005617
danielk1977a50d9aa2009-06-08 14:49:45 +00005618 pBt = pParent->pBt;
5619 assert( sqlite3_mutex_held(pBt->mutex) );
5620 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977474b7cc2008-07-09 11:49:46 +00005621
danielk1977e5765212009-06-17 11:13:28 +00005622#if 0
drh43605152004-05-29 21:46:49 +00005623 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
danielk1977e5765212009-06-17 11:13:28 +00005624#endif
drh2e38c322004-09-03 18:38:44 +00005625
danielk19774dbaa892009-06-16 16:50:22 +00005626 /* At this point pParent may have at most one overflow cell. And if
5627 ** this overflow cell is present, it must be the cell with
5628 ** index iParentIdx. This scenario comes about when this function
5629 ** is called (indirectly) from sqlite3BtreeDelete(). */
5630 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
5631 assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
5632
danielk197711a8a862009-06-17 11:49:52 +00005633 if( !aOvflSpace ){
5634 return SQLITE_NOMEM;
5635 }
5636
danielk1977a50d9aa2009-06-08 14:49:45 +00005637 /* Find the sibling pages to balance. Also locate the cells in pParent
5638 ** that divide the siblings. An attempt is made to find NN siblings on
5639 ** either side of pPage. More siblings are taken from one side, however,
5640 ** if there are fewer than NN siblings on the other side. If pParent
danielk19774dbaa892009-06-16 16:50:22 +00005641 ** has NB or fewer children then all children of pParent are taken.
5642 **
5643 ** This loop also drops the divider cells from the parent page. This
5644 ** way, the remainder of the function does not have to deal with any
5645 ** overflow cells in the parent page, as if one existed it has already
5646 ** been removed. */
5647 i = pParent->nOverflow + pParent->nCell;
5648 if( i<2 ){
drhc3b70572003-01-04 19:44:07 +00005649 nxDiv = 0;
danielk19774dbaa892009-06-16 16:50:22 +00005650 nOld = i+1;
5651 }else{
5652 nOld = 3;
5653 if( iParentIdx==0 ){
5654 nxDiv = 0;
5655 }else if( iParentIdx==i ){
5656 nxDiv = i-2;
drh14acc042001-06-10 19:56:58 +00005657 }else{
danielk19774dbaa892009-06-16 16:50:22 +00005658 nxDiv = iParentIdx-1;
drh8b2f49b2001-06-08 00:21:52 +00005659 }
danielk19774dbaa892009-06-16 16:50:22 +00005660 i = 2;
5661 }
5662 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
5663 pRight = &pParent->aData[pParent->hdrOffset+8];
5664 }else{
5665 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
5666 }
5667 pgno = get4byte(pRight);
5668 while( 1 ){
5669 rc = getAndInitPage(pBt, pgno, &apOld[i]);
5670 if( rc ){
5671 memset(apOld, 0, i*sizeof(MemPage*));
5672 goto balance_cleanup;
5673 }
danielk1977634f2982005-03-28 08:44:07 +00005674 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
danielk19774dbaa892009-06-16 16:50:22 +00005675 if( (i--)==0 ) break;
5676
5677 if( pParent->nOverflow && i+nxDiv==pParent->aOvfl[0].idx ){
5678 apDiv[i] = pParent->aOvfl[0].pCell;
5679 pgno = get4byte(apDiv[i]);
5680 szNew[i] = cellSizePtr(pParent, apDiv[i]);
5681 pParent->nOverflow = 0;
5682 }else{
5683 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
5684 pgno = get4byte(apDiv[i]);
5685 szNew[i] = cellSizePtr(pParent, apDiv[i]);
5686
5687 /* Drop the cell from the parent page. apDiv[i] still points to
5688 ** the cell within the parent, even though it has been dropped.
5689 ** This is safe because dropping a cell only overwrites the first
5690 ** four bytes of it, and this function does not need the first
5691 ** four bytes of the divider cell. So the pointer is safe to use
danielk197711a8a862009-06-17 11:49:52 +00005692 ** later on.
5693 **
5694 ** Unless SQLite is compiled in secure-delete mode. In this case,
5695 ** the dropCell() routine will overwrite the entire cell with zeroes.
5696 ** In this case, temporarily copy the cell into the aOvflSpace[]
5697 ** buffer. It will be copied out again as soon as the aSpace[] buffer
5698 ** is allocated. */
5699#ifdef SQLITE_SECURE_DELETE
5700 memcpy(&aOvflSpace[apDiv[i]-pParent->aData], apDiv[i], szNew[i]);
5701 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
5702#endif
danielk19774dbaa892009-06-16 16:50:22 +00005703 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i]);
5704 }
drh8b2f49b2001-06-08 00:21:52 +00005705 }
5706
drha9121e42008-02-19 14:59:35 +00005707 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00005708 ** alignment */
drha9121e42008-02-19 14:59:35 +00005709 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00005710
drh8b2f49b2001-06-08 00:21:52 +00005711 /*
danielk1977634f2982005-03-28 08:44:07 +00005712 ** Allocate space for memory structures
5713 */
danielk19774dbaa892009-06-16 16:50:22 +00005714 k = pBt->pageSize + ROUND8(sizeof(MemPage));
drhfacf0302008-06-17 15:12:00 +00005715 szScratch =
drha9121e42008-02-19 14:59:35 +00005716 nMaxCells*sizeof(u8*) /* apCell */
5717 + nMaxCells*sizeof(u16) /* szCell */
drhe5ae5732008-06-15 02:51:47 +00005718 + pBt->pageSize /* aSpace1 */
danielk19774dbaa892009-06-16 16:50:22 +00005719 + k*nOld; /* Page copies (apCopy) */
drhfacf0302008-06-17 15:12:00 +00005720 apCell = sqlite3ScratchMalloc( szScratch );
danielk197711a8a862009-06-17 11:49:52 +00005721 if( apCell==0 ){
danielk1977634f2982005-03-28 08:44:07 +00005722 rc = SQLITE_NOMEM;
5723 goto balance_cleanup;
5724 }
drha9121e42008-02-19 14:59:35 +00005725 szCell = (u16*)&apCell[nMaxCells];
danielk19774dbaa892009-06-16 16:50:22 +00005726 aSpace1 = (u8*)&szCell[nMaxCells];
drhea598cb2009-04-05 12:22:08 +00005727 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
drh14acc042001-06-10 19:56:58 +00005728
5729 /*
5730 ** Load pointers to all cells on sibling pages and the divider cells
5731 ** into the local apCell[] array. Make copies of the divider cells
danielk19774dbaa892009-06-16 16:50:22 +00005732 ** into space obtained from aSpace1[] and remove the the divider Cells
drhb6f41482004-05-14 01:58:11 +00005733 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00005734 **
5735 ** If the siblings are on leaf pages, then the child pointers of the
5736 ** divider cells are stripped from the cells before they are copied
drhe5ae5732008-06-15 02:51:47 +00005737 ** into aSpace1[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00005738 ** child pointers. If siblings are not leaves, then all cell in
5739 ** apCell[] include child pointers. Either way, all cells in apCell[]
5740 ** are alike.
drh96f5b762004-05-16 16:24:36 +00005741 **
5742 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
5743 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00005744 */
danielk1977a50d9aa2009-06-08 14:49:45 +00005745 leafCorrection = apOld[0]->leaf*4;
5746 leafData = apOld[0]->hasData;
drh8b2f49b2001-06-08 00:21:52 +00005747 for(i=0; i<nOld; i++){
danielk19774dbaa892009-06-16 16:50:22 +00005748 int limit;
5749
5750 /* Before doing anything else, take a copy of the i'th original sibling
5751 ** The rest of this function will use data from the copies rather
5752 ** that the original pages since the original pages will be in the
5753 ** process of being overwritten. */
5754 MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
5755 memcpy(pOld, apOld[i], sizeof(MemPage));
5756 pOld->aData = (void*)&pOld[1];
5757 memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
5758
5759 limit = pOld->nCell+pOld->nOverflow;
drh43605152004-05-29 21:46:49 +00005760 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00005761 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00005762 apCell[nCell] = findOverflowCell(pOld, j);
5763 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk19774dbaa892009-06-16 16:50:22 +00005764 nCell++;
5765 }
5766 if( i<nOld-1 && !leafData){
shane36840fd2009-06-26 16:32:13 +00005767 u16 sz = (u16)szNew[i];
danielk19774dbaa892009-06-16 16:50:22 +00005768 u8 *pTemp;
5769 assert( nCell<nMaxCells );
5770 szCell[nCell] = sz;
5771 pTemp = &aSpace1[iSpace1];
5772 iSpace1 += sz;
5773 assert( sz<=pBt->pageSize/4 );
5774 assert( iSpace1<=pBt->pageSize );
5775 memcpy(pTemp, apDiv[i], sz);
5776 apCell[nCell] = pTemp+leafCorrection;
5777 assert( leafCorrection==0 || leafCorrection==4 );
shane36840fd2009-06-26 16:32:13 +00005778 szCell[nCell] = szCell[nCell] - leafCorrection;
danielk19774dbaa892009-06-16 16:50:22 +00005779 if( !pOld->leaf ){
5780 assert( leafCorrection==0 );
5781 assert( pOld->hdrOffset==0 );
5782 /* The right pointer of the child page pOld becomes the left
5783 ** pointer of the divider cell */
5784 memcpy(apCell[nCell], &pOld->aData[8], 4);
5785 }else{
5786 assert( leafCorrection==4 );
5787 if( szCell[nCell]<4 ){
5788 /* Do not allow any cells smaller than 4 bytes. */
5789 szCell[nCell] = 4;
danielk1977ac11ee62005-01-15 12:45:51 +00005790 }
5791 }
drh14acc042001-06-10 19:56:58 +00005792 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00005793 }
drh8b2f49b2001-06-08 00:21:52 +00005794 }
5795
5796 /*
drh6019e162001-07-02 17:51:45 +00005797 ** Figure out the number of pages needed to hold all nCell cells.
5798 ** Store this number in "k". Also compute szNew[] which is the total
5799 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00005800 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00005801 ** cntNew[k] should equal nCell.
5802 **
drh96f5b762004-05-16 16:24:36 +00005803 ** Values computed by this block:
5804 **
5805 ** k: The total number of sibling pages
5806 ** szNew[i]: Spaced used on the i-th sibling page.
5807 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
5808 ** the right of the i-th sibling page.
5809 ** usableSpace: Number of bytes of space available on each sibling.
5810 **
drh8b2f49b2001-06-08 00:21:52 +00005811 */
drh43605152004-05-29 21:46:49 +00005812 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00005813 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00005814 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00005815 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00005816 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00005817 szNew[k] = subtotal - szCell[i];
5818 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00005819 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00005820 subtotal = 0;
5821 k++;
drheac74422009-06-14 12:47:11 +00005822 if( k>NB+1 ){ rc = SQLITE_CORRUPT; goto balance_cleanup; }
drh6019e162001-07-02 17:51:45 +00005823 }
5824 }
5825 szNew[k] = subtotal;
5826 cntNew[k] = nCell;
5827 k++;
drh96f5b762004-05-16 16:24:36 +00005828
5829 /*
5830 ** The packing computed by the previous block is biased toward the siblings
5831 ** on the left side. The left siblings are always nearly full, while the
5832 ** right-most sibling might be nearly empty. This block of code attempts
5833 ** to adjust the packing of siblings to get a better balance.
5834 **
5835 ** This adjustment is more than an optimization. The packing above might
5836 ** be so out of balance as to be illegal. For example, the right-most
5837 ** sibling might be completely empty. This adjustment is not optional.
5838 */
drh6019e162001-07-02 17:51:45 +00005839 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00005840 int szRight = szNew[i]; /* Size of sibling on the right */
5841 int szLeft = szNew[i-1]; /* Size of sibling on the left */
5842 int r; /* Index of right-most cell in left sibling */
5843 int d; /* Index of first cell to the left of right sibling */
5844
5845 r = cntNew[i-1] - 1;
5846 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00005847 assert( d<nMaxCells );
5848 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00005849 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
5850 szRight += szCell[d] + 2;
5851 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00005852 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00005853 r = cntNew[i-1] - 1;
5854 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00005855 }
drh96f5b762004-05-16 16:24:36 +00005856 szNew[i] = szRight;
5857 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00005858 }
drh09d0deb2005-08-02 17:13:09 +00005859
danielk19776f235cc2009-06-04 14:46:08 +00005860 /* Either we found one or more cells (cntnew[0])>0) or pPage is
drh09d0deb2005-08-02 17:13:09 +00005861 ** a virtual root page. A virtual root page is when the real root
5862 ** page is page 1 and we are the only child of that page.
5863 */
5864 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00005865
danielk1977e5765212009-06-17 11:13:28 +00005866 TRACE(("BALANCE: old: %d %d %d ",
5867 apOld[0]->pgno,
5868 nOld>=2 ? apOld[1]->pgno : 0,
5869 nOld>=3 ? apOld[2]->pgno : 0
5870 ));
5871
drh8b2f49b2001-06-08 00:21:52 +00005872 /*
drh6b308672002-07-08 02:16:37 +00005873 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00005874 */
drheac74422009-06-14 12:47:11 +00005875 if( apOld[0]->pgno<=1 ){
5876 rc = SQLITE_CORRUPT;
5877 goto balance_cleanup;
5878 }
danielk1977a50d9aa2009-06-08 14:49:45 +00005879 pageFlags = apOld[0]->aData[0];
drh14acc042001-06-10 19:56:58 +00005880 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00005881 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00005882 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00005883 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00005884 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00005885 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00005886 nNew++;
danielk197728129562005-01-11 10:25:06 +00005887 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00005888 }else{
drh7aa8f852006-03-28 00:24:44 +00005889 assert( i>0 );
danielk19774dbaa892009-06-16 16:50:22 +00005890 rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
drh6b308672002-07-08 02:16:37 +00005891 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00005892 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00005893 nNew++;
danielk19774dbaa892009-06-16 16:50:22 +00005894
5895 /* Set the pointer-map entry for the new sibling page. */
5896 if( ISAUTOVACUUM ){
5897 rc = ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno);
5898 if( rc!=SQLITE_OK ){
5899 goto balance_cleanup;
5900 }
5901 }
drh6b308672002-07-08 02:16:37 +00005902 }
drh8b2f49b2001-06-08 00:21:52 +00005903 }
5904
danielk1977299b1872004-11-22 10:02:10 +00005905 /* Free any old pages that were not reused as new pages.
5906 */
5907 while( i<nOld ){
5908 rc = freePage(apOld[i]);
5909 if( rc ) goto balance_cleanup;
5910 releasePage(apOld[i]);
5911 apOld[i] = 0;
5912 i++;
5913 }
5914
drh8b2f49b2001-06-08 00:21:52 +00005915 /*
drhf9ffac92002-03-02 19:00:31 +00005916 ** Put the new pages in accending order. This helps to
5917 ** keep entries in the disk file in order so that a scan
5918 ** of the table is a linear scan through the file. That
5919 ** in turn helps the operating system to deliver pages
5920 ** from the disk more rapidly.
5921 **
5922 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00005923 ** n is never more than NB (a small constant), that should
5924 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00005925 **
drhc3b70572003-01-04 19:44:07 +00005926 ** When NB==3, this one optimization makes the database
5927 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00005928 */
5929 for(i=0; i<k-1; i++){
danielk19774dbaa892009-06-16 16:50:22 +00005930 int minV = apNew[i]->pgno;
drhf9ffac92002-03-02 19:00:31 +00005931 int minI = i;
5932 for(j=i+1; j<k; j++){
danielk19774dbaa892009-06-16 16:50:22 +00005933 if( apNew[j]->pgno<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00005934 minI = j;
danielk19774dbaa892009-06-16 16:50:22 +00005935 minV = apNew[j]->pgno;
drhf9ffac92002-03-02 19:00:31 +00005936 }
5937 }
5938 if( minI>i ){
5939 int t;
5940 MemPage *pT;
danielk19774dbaa892009-06-16 16:50:22 +00005941 t = apNew[i]->pgno;
drhf9ffac92002-03-02 19:00:31 +00005942 pT = apNew[i];
drhf9ffac92002-03-02 19:00:31 +00005943 apNew[i] = apNew[minI];
drhf9ffac92002-03-02 19:00:31 +00005944 apNew[minI] = pT;
5945 }
5946 }
danielk1977e5765212009-06-17 11:13:28 +00005947 TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
danielk19774dbaa892009-06-16 16:50:22 +00005948 apNew[0]->pgno, szNew[0],
5949 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
5950 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
5951 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
5952 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
5953
5954 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
5955 put4byte(pRight, apNew[nNew-1]->pgno);
drh24cd67e2004-05-10 16:18:47 +00005956
drhf9ffac92002-03-02 19:00:31 +00005957 /*
drh14acc042001-06-10 19:56:58 +00005958 ** Evenly distribute the data in apCell[] across the new pages.
5959 ** Insert divider cells into pParent as necessary.
5960 */
5961 j = 0;
5962 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00005963 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00005964 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00005965 assert( j<nMaxCells );
drh10131482008-07-11 03:34:09 +00005966 zeroPage(pNew, pageFlags);
drhfa1a98a2004-05-14 19:08:17 +00005967 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00005968 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00005969 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00005970
danielk1977ac11ee62005-01-15 12:45:51 +00005971 j = cntNew[i];
5972
5973 /* If the sibling page assembled above was not the right-most sibling,
5974 ** insert a divider cell into the parent page.
5975 */
danielk19771c3d2bf2009-06-23 16:40:17 +00005976 assert( i<nNew-1 || j==nCell );
5977 if( j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00005978 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00005979 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00005980 int sz;
danielk1977634f2982005-03-28 08:44:07 +00005981
5982 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00005983 pCell = apCell[j];
5984 sz = szCell[j] + leafCorrection;
danielk19776067a9b2009-06-09 09:41:00 +00005985 pTemp = &aOvflSpace[iOvflSpace];
drh4b70f112004-05-02 21:12:19 +00005986 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00005987 memcpy(&pNew->aData[8], pCell, 4);
drh8b18dd42004-05-12 19:18:15 +00005988 }else if( leafData ){
drhfd131da2007-08-07 17:13:03 +00005989 /* If the tree is a leaf-data tree, and the siblings are leaves,
danielk1977ac11ee62005-01-15 12:45:51 +00005990 ** then there is no divider cell in apCell[]. Instead, the divider
5991 ** cell consists of the integer key for the right-most cell of
5992 ** the sibling-page assembled above only.
5993 */
drh6f11bef2004-05-13 01:12:56 +00005994 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00005995 j--;
drh16a9b832007-05-05 18:39:25 +00005996 sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
drhe5ae5732008-06-15 02:51:47 +00005997 pCell = pTemp;
danielk19774dbaa892009-06-16 16:50:22 +00005998 sz = 4 + putVarint(&pCell[4], info.nKey);
drh8b18dd42004-05-12 19:18:15 +00005999 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00006000 }else{
6001 pCell -= 4;
danielk19774aeff622007-05-12 09:30:47 +00006002 /* Obscure case for non-leaf-data trees: If the cell at pCell was
drh85b623f2007-12-13 21:54:09 +00006003 ** previously stored on a leaf node, and its reported size was 4
danielk19774aeff622007-05-12 09:30:47 +00006004 ** bytes, then it may actually be smaller than this
6005 ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
drh85b623f2007-12-13 21:54:09 +00006006 ** any cell). But it is important to pass the correct size to
danielk19774aeff622007-05-12 09:30:47 +00006007 ** insertCell(), so reparse the cell now.
6008 **
6009 ** Note that this can never happen in an SQLite data file, as all
6010 ** cells are at least 4 bytes. It only happens in b-trees used
6011 ** to evaluate "IN (SELECT ...)" and similar clauses.
6012 */
6013 if( szCell[j]==4 ){
6014 assert(leafCorrection==4);
6015 sz = cellSizePtr(pParent, pCell);
6016 }
drh4b70f112004-05-02 21:12:19 +00006017 }
danielk19776067a9b2009-06-09 09:41:00 +00006018 iOvflSpace += sz;
drhe5ae5732008-06-15 02:51:47 +00006019 assert( sz<=pBt->pageSize/4 );
danielk19776067a9b2009-06-09 09:41:00 +00006020 assert( iOvflSpace<=pBt->pageSize );
danielk19774dbaa892009-06-16 16:50:22 +00006021 rc = insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno);
danielk1977e80463b2004-11-03 03:01:16 +00006022 if( rc!=SQLITE_OK ) goto balance_cleanup;
drhc5053fb2008-11-27 02:22:10 +00006023 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk197785d90ca2008-07-19 14:25:15 +00006024
drh14acc042001-06-10 19:56:58 +00006025 j++;
6026 nxDiv++;
6027 }
6028 }
drh6019e162001-07-02 17:51:45 +00006029 assert( j==nCell );
drh7aa8f852006-03-28 00:24:44 +00006030 assert( nOld>0 );
6031 assert( nNew>0 );
drh4b70f112004-05-02 21:12:19 +00006032 if( (pageFlags & PTF_LEAF)==0 ){
danielk197787c52b52008-07-19 11:49:07 +00006033 u8 *zChild = &apCopy[nOld-1]->aData[8];
6034 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
drh14acc042001-06-10 19:56:58 +00006035 }
6036
danielk197713bd99f2009-06-24 05:40:34 +00006037 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
6038 /* The root page of the b-tree now contains no cells. The only sibling
6039 ** page is the right-child of the parent. Copy the contents of the
6040 ** child page into the parent, decreasing the overall height of the
6041 ** b-tree structure by one. This is described as the "balance-shallower"
6042 ** sub-algorithm in some documentation.
6043 **
6044 ** If this is an auto-vacuum database, the call to copyNodeContent()
6045 ** sets all pointer-map entries corresponding to database image pages
6046 ** for which the pointer is stored within the content being copied.
6047 **
6048 ** The second assert below verifies that the child page is defragmented
6049 ** (it must be, as it was just reconstructed using assemblePage()). This
6050 ** is important if the parent page happens to be page 1 of the database
6051 ** image. */
6052 assert( nNew==1 );
6053 assert( apNew[0]->nFree ==
6054 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
6055 );
6056 if( SQLITE_OK==(rc = copyNodeContent(apNew[0], pParent)) ){
6057 rc = freePage(apNew[0]);
6058 }
6059 }else if( ISAUTOVACUUM ){
6060 /* Fix the pointer-map entries for all the cells that were shifted around.
6061 ** There are several different types of pointer-map entries that need to
6062 ** be dealt with by this routine. Some of these have been set already, but
6063 ** many have not. The following is a summary:
6064 **
6065 ** 1) The entries associated with new sibling pages that were not
6066 ** siblings when this function was called. These have already
6067 ** been set. We don't need to worry about old siblings that were
6068 ** moved to the free-list - the freePage() code has taken care
6069 ** of those.
6070 **
6071 ** 2) The pointer-map entries associated with the first overflow
6072 ** page in any overflow chains used by new divider cells. These
6073 ** have also already been taken care of by the insertCell() code.
6074 **
6075 ** 3) If the sibling pages are not leaves, then the child pages of
6076 ** cells stored on the sibling pages may need to be updated.
6077 **
6078 ** 4) If the sibling pages are not internal intkey nodes, then any
6079 ** overflow pages used by these cells may need to be updated
6080 ** (internal intkey nodes never contain pointers to overflow pages).
6081 **
6082 ** 5) If the sibling pages are not leaves, then the pointer-map
6083 ** entries for the right-child pages of each sibling may need
6084 ** to be updated.
6085 **
6086 ** Cases 1 and 2 are dealt with above by other code. The next
6087 ** block deals with cases 3 and 4 and the one after that, case 5. Since
6088 ** setting a pointer map entry is a relatively expensive operation, this
6089 ** code only sets pointer map entries for child or overflow pages that have
6090 ** actually moved between pages. */
danielk19774dbaa892009-06-16 16:50:22 +00006091 MemPage *pNew = apNew[0];
6092 MemPage *pOld = apCopy[0];
6093 int nOverflow = pOld->nOverflow;
6094 int iNextOld = pOld->nCell + nOverflow;
6095 int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
6096 j = 0; /* Current 'old' sibling page */
6097 k = 0; /* Current 'new' sibling page */
6098 for(i=0; i<nCell && rc==SQLITE_OK; i++){
6099 int isDivider = 0;
6100 while( i==iNextOld ){
6101 /* Cell i is the cell immediately following the last cell on old
6102 ** sibling page j. If the siblings are not leaf pages of an
6103 ** intkey b-tree, then cell i was a divider cell. */
6104 pOld = apCopy[++j];
6105 iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
6106 if( pOld->nOverflow ){
6107 nOverflow = pOld->nOverflow;
6108 iOverflow = i + !leafData + pOld->aOvfl[0].idx;
6109 }
6110 isDivider = !leafData;
6111 }
6112
6113 assert(nOverflow>0 || iOverflow<i );
6114 assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
6115 assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
6116 if( i==iOverflow ){
6117 isDivider = 1;
6118 if( (--nOverflow)>0 ){
6119 iOverflow++;
6120 }
6121 }
6122
6123 if( i==cntNew[k] ){
6124 /* Cell i is the cell immediately following the last cell on new
6125 ** sibling page k. If the siblings are not leaf pages of an
6126 ** intkey b-tree, then cell i is a divider cell. */
6127 pNew = apNew[++k];
6128 if( !leafData ) continue;
6129 }
6130 assert( rc==SQLITE_OK );
6131 assert( j<nOld );
6132 assert( k<nNew );
6133
6134 /* If the cell was originally divider cell (and is not now) or
6135 ** an overflow cell, or if the cell was located on a different sibling
6136 ** page before the balancing, then the pointer map entries associated
6137 ** with any child or overflow pages need to be updated. */
6138 if( isDivider || pOld->pgno!=pNew->pgno ){
6139 if( !leafCorrection ){
6140 rc = ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno);
6141 }
6142 if( szCell[i]>pNew->minLocal && rc==SQLITE_OK ){
6143 rc = ptrmapPutOvflPtr(pNew, apCell[i]);
6144 }
6145 }
6146 }
6147
6148 if( !leafCorrection ){
6149 for(i=0; rc==SQLITE_OK && i<nNew; i++){
6150 rc = ptrmapPut(
6151 pBt, get4byte(&apNew[i]->aData[8]), PTRMAP_BTREE, apNew[i]->pgno);
6152 }
6153 }
6154
6155#if 0
6156 /* The ptrmapCheckPages() contains assert() statements that verify that
6157 ** all pointer map pages are set correctly. This is helpful while
6158 ** debugging. This is usually disabled because a corrupt database may
6159 ** cause an assert() statement to fail. */
6160 ptrmapCheckPages(apNew, nNew);
6161 ptrmapCheckPages(&pParent, 1);
6162#endif
6163 }
6164
danielk197771d5d2c2008-09-29 11:49:47 +00006165 assert( pParent->isInit );
danielk1977e5765212009-06-17 11:13:28 +00006166 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
6167 nOld, nNew, nCell));
danielk1977cd581a72009-06-23 15:43:39 +00006168
drh8b2f49b2001-06-08 00:21:52 +00006169 /*
drh14acc042001-06-10 19:56:58 +00006170 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00006171 */
drh14acc042001-06-10 19:56:58 +00006172balance_cleanup:
drhfacf0302008-06-17 15:12:00 +00006173 sqlite3ScratchFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00006174 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00006175 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00006176 }
drh14acc042001-06-10 19:56:58 +00006177 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00006178 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00006179 }
danielk1977eaa06f62008-09-18 17:34:44 +00006180
drh8b2f49b2001-06-08 00:21:52 +00006181 return rc;
6182}
6183
drh43605152004-05-29 21:46:49 +00006184
6185/*
danielk1977a50d9aa2009-06-08 14:49:45 +00006186** This function is called when the root page of a b-tree structure is
6187** overfull (has one or more overflow pages).
drh43605152004-05-29 21:46:49 +00006188**
danielk1977a50d9aa2009-06-08 14:49:45 +00006189** A new child page is allocated and the contents of the current root
6190** page, including overflow cells, are copied into the child. The root
6191** page is then overwritten to make it an empty page with the right-child
6192** pointer pointing to the new page.
6193**
6194** Before returning, all pointer-map entries corresponding to pages
6195** that the new child-page now contains pointers to are updated. The
6196** entry corresponding to the new right-child pointer of the root
6197** page is also updated.
6198**
6199** If successful, *ppChild is set to contain a reference to the child
6200** page and SQLITE_OK is returned. In this case the caller is required
6201** to call releasePage() on *ppChild exactly once. If an error occurs,
6202** an error code is returned and *ppChild is set to 0.
drh43605152004-05-29 21:46:49 +00006203*/
danielk1977a50d9aa2009-06-08 14:49:45 +00006204static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
6205 int rc; /* Return value from subprocedures */
6206 MemPage *pChild = 0; /* Pointer to a new child page */
6207 Pgno pgnoChild; /* Page number of the new child page */
6208 BtShared *pBt = pRoot->pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00006209
danielk1977a50d9aa2009-06-08 14:49:45 +00006210 assert( pRoot->nOverflow>0 );
drh1fee73e2007-08-29 04:00:57 +00006211 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bc2ca9e2008-11-13 14:28:28 +00006212
danielk1977a50d9aa2009-06-08 14:49:45 +00006213 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
6214 ** page that will become the new right-child of pPage. Copy the contents
6215 ** of the node stored on pRoot into the new child page.
6216 */
6217 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pRoot->pDbPage))
6218 || SQLITE_OK!=(rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0))
6219 || SQLITE_OK!=(rc = copyNodeContent(pRoot, pChild))
6220 || (ISAUTOVACUUM &&
6221 SQLITE_OK!=(rc = ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno)))
6222 ){
6223 *ppChild = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00006224 releasePage(pChild);
danielk1977a50d9aa2009-06-08 14:49:45 +00006225 return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00006226 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006227 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
6228 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
6229 assert( pChild->nCell==pRoot->nCell );
danielk197771d5d2c2008-09-29 11:49:47 +00006230
danielk1977a50d9aa2009-06-08 14:49:45 +00006231 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
6232
6233 /* Copy the overflow cells from pRoot to pChild */
6234 memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
6235 pChild->nOverflow = pRoot->nOverflow;
danielk1977a50d9aa2009-06-08 14:49:45 +00006236
6237 /* Zero the contents of pRoot. Then install pChild as the right-child. */
6238 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
6239 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
6240
6241 *ppChild = pChild;
6242 return SQLITE_OK;
drh43605152004-05-29 21:46:49 +00006243}
6244
6245/*
danielk197771d5d2c2008-09-29 11:49:47 +00006246** The page that pCur currently points to has just been modified in
6247** some way. This function figures out if this modification means the
6248** tree needs to be balanced, and if so calls the appropriate balancing
danielk1977a50d9aa2009-06-08 14:49:45 +00006249** routine. Balancing routines are:
6250**
6251** balance_quick()
danielk1977a50d9aa2009-06-08 14:49:45 +00006252** balance_deeper()
6253** balance_nonroot()
drh43605152004-05-29 21:46:49 +00006254*/
danielk1977a50d9aa2009-06-08 14:49:45 +00006255static int balance(BtCursor *pCur){
drh43605152004-05-29 21:46:49 +00006256 int rc = SQLITE_OK;
danielk1977a50d9aa2009-06-08 14:49:45 +00006257 const int nMin = pCur->pBt->usableSize * 2 / 3;
6258 u8 aBalanceQuickSpace[13];
6259 u8 *pFree = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00006260
shane75ac1de2009-06-09 18:58:52 +00006261 TESTONLY( int balance_quick_called = 0 );
6262 TESTONLY( int balance_deeper_called = 0 );
danielk1977a50d9aa2009-06-08 14:49:45 +00006263
6264 do {
6265 int iPage = pCur->iPage;
6266 MemPage *pPage = pCur->apPage[iPage];
6267
6268 if( iPage==0 ){
6269 if( pPage->nOverflow ){
6270 /* The root page of the b-tree is overfull. In this case call the
6271 ** balance_deeper() function to create a new child for the root-page
6272 ** and copy the current contents of the root-page to it. The
6273 ** next iteration of the do-loop will balance the child page.
6274 */
6275 assert( (balance_deeper_called++)==0 );
6276 rc = balance_deeper(pPage, &pCur->apPage[1]);
6277 if( rc==SQLITE_OK ){
6278 pCur->iPage = 1;
6279 pCur->aiIdx[0] = 0;
6280 pCur->aiIdx[1] = 0;
6281 assert( pCur->apPage[1]->nOverflow );
6282 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006283 }else{
danielk1977a50d9aa2009-06-08 14:49:45 +00006284 break;
6285 }
6286 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
6287 break;
6288 }else{
6289 MemPage * const pParent = pCur->apPage[iPage-1];
6290 int const iIdx = pCur->aiIdx[iPage-1];
6291
6292 rc = sqlite3PagerWrite(pParent->pDbPage);
6293 if( rc==SQLITE_OK ){
6294#ifndef SQLITE_OMIT_QUICKBALANCE
6295 if( pPage->hasData
6296 && pPage->nOverflow==1
6297 && pPage->aOvfl[0].idx==pPage->nCell
6298 && pParent->pgno!=1
6299 && pParent->nCell==iIdx
6300 ){
6301 /* Call balance_quick() to create a new sibling of pPage on which
6302 ** to store the overflow cell. balance_quick() inserts a new cell
6303 ** into pParent, which may cause pParent overflow. If this
6304 ** happens, the next interation of the do-loop will balance pParent
6305 ** use either balance_nonroot() or balance_deeper(). Until this
6306 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
6307 ** buffer.
6308 **
6309 ** The purpose of the following assert() is to check that only a
6310 ** single call to balance_quick() is made for each call to this
6311 ** function. If this were not verified, a subtle bug involving reuse
6312 ** of the aBalanceQuickSpace[] might sneak in.
6313 */
6314 assert( (balance_quick_called++)==0 );
6315 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
6316 }else
6317#endif
6318 {
6319 /* In this case, call balance_nonroot() to redistribute cells
6320 ** between pPage and up to 2 of its sibling pages. This involves
6321 ** modifying the contents of pParent, which may cause pParent to
6322 ** become overfull or underfull. The next iteration of the do-loop
6323 ** will balance the parent page to correct this.
6324 **
6325 ** If the parent page becomes overfull, the overflow cell or cells
6326 ** are stored in the pSpace buffer allocated immediately below.
6327 ** A subsequent iteration of the do-loop will deal with this by
6328 ** calling balance_nonroot() (balance_deeper() may be called first,
6329 ** but it doesn't deal with overflow cells - just moves them to a
6330 ** different page). Once this subsequent call to balance_nonroot()
6331 ** has completed, it is safe to release the pSpace buffer used by
6332 ** the previous call, as the overflow cell data will have been
6333 ** copied either into the body of a database page or into the new
6334 ** pSpace buffer passed to the latter call to balance_nonroot().
6335 */
6336 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
danielk1977cd581a72009-06-23 15:43:39 +00006337 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
danielk1977a50d9aa2009-06-08 14:49:45 +00006338 if( pFree ){
6339 /* If pFree is not NULL, it points to the pSpace buffer used
6340 ** by a previous call to balance_nonroot(). Its contents are
6341 ** now stored either on real database pages or within the
6342 ** new pSpace buffer, so it may be safely freed here. */
6343 sqlite3PageFree(pFree);
6344 }
6345
danielk19774dbaa892009-06-16 16:50:22 +00006346 /* The pSpace buffer will be freed after the next call to
6347 ** balance_nonroot(), or just before this function returns, whichever
6348 ** comes first. */
danielk1977a50d9aa2009-06-08 14:49:45 +00006349 pFree = pSpace;
danielk1977a50d9aa2009-06-08 14:49:45 +00006350 }
6351 }
6352
6353 pPage->nOverflow = 0;
6354
6355 /* The next iteration of the do-loop balances the parent page. */
6356 releasePage(pPage);
6357 pCur->iPage--;
drh43605152004-05-29 21:46:49 +00006358 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006359 }while( rc==SQLITE_OK );
6360
6361 if( pFree ){
6362 sqlite3PageFree(pFree);
drh43605152004-05-29 21:46:49 +00006363 }
6364 return rc;
6365}
6366
drhf74b8d92002-09-01 23:20:45 +00006367
6368/*
drh3b7511c2001-05-26 13:15:44 +00006369** Insert a new record into the BTree. The key is given by (pKey,nKey)
6370** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00006371** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00006372** is left pointing at a random location.
6373**
6374** For an INTKEY table, only the nKey value of the key is used. pKey is
6375** ignored. For a ZERODATA table, the pData and nData are both ignored.
danielk1977de630352009-05-04 11:42:29 +00006376**
6377** If the seekResult parameter is non-zero, then a successful call to
6378** sqlite3BtreeMoveto() to seek cursor pCur to (pKey, nKey) has already
6379** been performed. seekResult is the search result returned (a negative
6380** number if pCur points at an entry that is smaller than (pKey, nKey), or
6381** a positive value if pCur points at an etry that is larger than
6382** (pKey, nKey)).
6383**
6384** If the seekResult parameter is 0, then cursor pCur may point to any
6385** entry or to no entry at all. In this case this function has to seek
6386** the cursor before the new key can be inserted.
drh3b7511c2001-05-26 13:15:44 +00006387*/
drh3aac2dd2004-04-26 14:10:20 +00006388int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00006389 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00006390 const void *pKey, i64 nKey, /* The key of the new record */
drhe4d90812007-03-29 05:51:49 +00006391 const void *pData, int nData, /* The data of the new record */
drhb026e052007-05-02 01:34:31 +00006392 int nZero, /* Number of extra 0 bytes to append to data */
danielk1977de630352009-05-04 11:42:29 +00006393 int appendBias, /* True if this is likely an append */
6394 int seekResult /* Result of prior sqlite3BtreeMoveto() call */
drh3b7511c2001-05-26 13:15:44 +00006395){
drh3b7511c2001-05-26 13:15:44 +00006396 int rc;
danielk1977de630352009-05-04 11:42:29 +00006397 int loc = seekResult;
drh14acc042001-06-10 19:56:58 +00006398 int szNew;
danielk197771d5d2c2008-09-29 11:49:47 +00006399 int idx;
drh3b7511c2001-05-26 13:15:44 +00006400 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00006401 Btree *p = pCur->pBtree;
6402 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00006403 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00006404 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00006405
drh1fee73e2007-08-29 04:00:57 +00006406 assert( cursorHoldsMutex(pCur) );
drh64022502009-01-09 14:11:04 +00006407 assert( pBt->inTransaction==TRANS_WRITE );
drhf74b8d92002-09-01 23:20:45 +00006408 assert( !pBt->readOnly );
drh64022502009-01-09 14:11:04 +00006409 assert( pCur->wrFlag );
danielk197796d48e92009-06-29 06:00:37 +00006410 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
6411
6412 /* If this is an insert into a table b-tree, invalidate any incrblob
6413 ** cursors open on the row being replaced (assuming this is a replace
6414 ** operation - if it is not, the following is a no-op). */
6415 if( pCur->pKeyInfo==0 ){
6416 invalidateIncrblobCursors(p, pCur->pgnoRoot, nKey, 0);
drhf74b8d92002-09-01 23:20:45 +00006417 }
danielk197796d48e92009-06-29 06:00:37 +00006418
drhfb982642007-08-30 01:19:59 +00006419 if( pCur->eState==CURSOR_FAULT ){
6420 return pCur->skip;
6421 }
danielk1977da184232006-01-05 11:34:32 +00006422
danielk19779c3acf32009-05-02 07:36:49 +00006423 /* Save the positions of any other cursors open on this table.
6424 **
6425 ** In some cases, the call to sqlite3BtreeMoveto() below is a no-op. For
6426 ** example, when inserting data into a table with auto-generated integer
6427 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
6428 ** integer key to use. It then calls this function to actually insert the
6429 ** data into the intkey B-Tree. In this case sqlite3BtreeMoveto() recognizes
6430 ** that the cursor is already where it needs to be and returns without
6431 ** doing any work. To avoid thwarting these optimizations, it is important
6432 ** not to clear the cursor here.
6433 */
danielk1977de630352009-05-04 11:42:29 +00006434 if(
6435 SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur)) || (!loc &&
drhe63d9992008-08-13 19:11:48 +00006436 SQLITE_OK!=(rc = sqlite3BtreeMoveto(pCur, pKey, nKey, appendBias, &loc))
danielk1977de630352009-05-04 11:42:29 +00006437 )){
danielk1977da184232006-01-05 11:34:32 +00006438 return rc;
6439 }
danielk1977b980d2212009-06-22 18:03:51 +00006440 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
danielk1977da184232006-01-05 11:34:32 +00006441
danielk197771d5d2c2008-09-29 11:49:47 +00006442 pPage = pCur->apPage[pCur->iPage];
drh4a1c3802004-05-12 15:15:47 +00006443 assert( pPage->intKey || nKey>=0 );
drh44845222008-07-17 18:39:57 +00006444 assert( pPage->leaf || !pPage->intKey );
drh3a4c1412004-05-09 20:40:11 +00006445 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
6446 pCur->pgnoRoot, nKey, nData, pPage->pgno,
6447 loc==0 ? "overwrite" : "new entry"));
danielk197771d5d2c2008-09-29 11:49:47 +00006448 assert( pPage->isInit );
danielk197752ae7242008-03-25 14:24:56 +00006449 allocateTempSpace(pBt);
6450 newCell = pBt->pTmpSpace;
drh2e38c322004-09-03 18:38:44 +00006451 if( newCell==0 ) return SQLITE_NOMEM;
drhb026e052007-05-02 01:34:31 +00006452 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
drh2e38c322004-09-03 18:38:44 +00006453 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00006454 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00006455 assert( szNew<=MX_CELL_SIZE(pBt) );
danielk197771d5d2c2008-09-29 11:49:47 +00006456 idx = pCur->aiIdx[pCur->iPage];
danielk1977b980d2212009-06-22 18:03:51 +00006457 if( loc==0 ){
drha9121e42008-02-19 14:59:35 +00006458 u16 szOld;
danielk197771d5d2c2008-09-29 11:49:47 +00006459 assert( idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00006460 rc = sqlite3PagerWrite(pPage->pDbPage);
6461 if( rc ){
6462 goto end_insert;
6463 }
danielk197771d5d2c2008-09-29 11:49:47 +00006464 oldCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00006465 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006466 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00006467 }
drh43605152004-05-29 21:46:49 +00006468 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00006469 rc = clearCell(pPage, oldCell);
drh2e38c322004-09-03 18:38:44 +00006470 if( rc ) goto end_insert;
shane0af3f892008-11-12 04:55:34 +00006471 rc = dropCell(pPage, idx, szOld);
6472 if( rc!=SQLITE_OK ) {
6473 goto end_insert;
6474 }
drh7c717f72001-06-24 20:39:41 +00006475 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00006476 assert( pPage->leaf );
danielk197771d5d2c2008-09-29 11:49:47 +00006477 idx = ++pCur->aiIdx[pCur->iPage];
drh14acc042001-06-10 19:56:58 +00006478 }else{
drh4b70f112004-05-02 21:12:19 +00006479 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00006480 }
danielk197771d5d2c2008-09-29 11:49:47 +00006481 rc = insertCell(pPage, idx, newCell, szNew, 0, 0);
danielk19773f632d52009-05-02 10:03:09 +00006482 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
drh9bf9e9c2008-12-05 20:01:43 +00006483
danielk1977a50d9aa2009-06-08 14:49:45 +00006484 /* If no error has occured and pPage has an overflow cell, call balance()
6485 ** to redistribute the cells within the tree. Since balance() may move
6486 ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
6487 ** variables.
danielk19773f632d52009-05-02 10:03:09 +00006488 **
danielk1977a50d9aa2009-06-08 14:49:45 +00006489 ** Previous versions of SQLite called moveToRoot() to move the cursor
6490 ** back to the root page as balance() used to invalidate the contents
danielk197754109bb2009-06-23 11:22:29 +00006491 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
6492 ** set the cursor state to "invalid". This makes common insert operations
6493 ** slightly faster.
danielk19773f632d52009-05-02 10:03:09 +00006494 **
danielk1977a50d9aa2009-06-08 14:49:45 +00006495 ** There is a subtle but important optimization here too. When inserting
6496 ** multiple records into an intkey b-tree using a single cursor (as can
6497 ** happen while processing an "INSERT INTO ... SELECT" statement), it
6498 ** is advantageous to leave the cursor pointing to the last entry in
6499 ** the b-tree if possible. If the cursor is left pointing to the last
6500 ** entry in the table, and the next row inserted has an integer key
6501 ** larger than the largest existing key, it is possible to insert the
6502 ** row without seeking the cursor. This can be a big performance boost.
danielk19773f632d52009-05-02 10:03:09 +00006503 */
danielk1977a50d9aa2009-06-08 14:49:45 +00006504 pCur->info.nSize = 0;
6505 pCur->validNKey = 0;
6506 if( rc==SQLITE_OK && pPage->nOverflow ){
danielk1977a50d9aa2009-06-08 14:49:45 +00006507 rc = balance(pCur);
6508
6509 /* Must make sure nOverflow is reset to zero even if the balance()
danielk197754109bb2009-06-23 11:22:29 +00006510 ** fails. Internal data structure corruption will result otherwise.
6511 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
6512 ** from trying to save the current position of the cursor. */
danielk1977a50d9aa2009-06-08 14:49:45 +00006513 pCur->apPage[pCur->iPage]->nOverflow = 0;
danielk197754109bb2009-06-23 11:22:29 +00006514 pCur->eState = CURSOR_INVALID;
danielk19773f632d52009-05-02 10:03:09 +00006515 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006516 assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
drh9bf9e9c2008-12-05 20:01:43 +00006517
drh2e38c322004-09-03 18:38:44 +00006518end_insert:
drh5e2f8b92001-05-28 00:41:15 +00006519 return rc;
6520}
6521
6522/*
drh4b70f112004-05-02 21:12:19 +00006523** Delete the entry that the cursor is pointing to. The cursor
drhf94a1732008-09-30 17:18:17 +00006524** is left pointing at a arbitrary location.
drh3b7511c2001-05-26 13:15:44 +00006525*/
drh3aac2dd2004-04-26 14:10:20 +00006526int sqlite3BtreeDelete(BtCursor *pCur){
drhd677b3d2007-08-20 22:48:41 +00006527 Btree *p = pCur->pBtree;
danielk19774dbaa892009-06-16 16:50:22 +00006528 BtShared *pBt = p->pBt;
6529 int rc; /* Return code */
6530 MemPage *pPage; /* Page to delete cell from */
6531 unsigned char *pCell; /* Pointer to cell to delete */
6532 int iCellIdx; /* Index of cell to delete */
6533 int iCellDepth; /* Depth of node containing pCell */
drh8b2f49b2001-06-08 00:21:52 +00006534
drh1fee73e2007-08-29 04:00:57 +00006535 assert( cursorHoldsMutex(pCur) );
drh64022502009-01-09 14:11:04 +00006536 assert( pBt->inTransaction==TRANS_WRITE );
drhf74b8d92002-09-01 23:20:45 +00006537 assert( !pBt->readOnly );
drh64022502009-01-09 14:11:04 +00006538 assert( pCur->wrFlag );
danielk197796d48e92009-06-29 06:00:37 +00006539 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
6540 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
6541
danielk19774dbaa892009-06-16 16:50:22 +00006542 if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
6543 || NEVER(pCur->eState!=CURSOR_VALID)
6544 ){
6545 return SQLITE_ERROR; /* Something has gone awry. */
drhf74b8d92002-09-01 23:20:45 +00006546 }
danielk1977da184232006-01-05 11:34:32 +00006547
danielk197796d48e92009-06-29 06:00:37 +00006548 /* If this is a delete operation to remove a row from a table b-tree,
6549 ** invalidate any incrblob cursors open on the row being deleted. */
6550 if( pCur->pKeyInfo==0 ){
6551 invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
danielk19774dbaa892009-06-16 16:50:22 +00006552 }
6553
6554 iCellDepth = pCur->iPage;
6555 iCellIdx = pCur->aiIdx[iCellDepth];
6556 pPage = pCur->apPage[iCellDepth];
6557 pCell = findCell(pPage, iCellIdx);
6558
6559 /* If the page containing the entry to delete is not a leaf page, move
6560 ** the cursor to the largest entry in the tree that is smaller than
6561 ** the entry being deleted. This cell will replace the cell being deleted
6562 ** from the internal node. The 'previous' entry is used for this instead
6563 ** of the 'next' entry, as the previous entry is always a part of the
6564 ** sub-tree headed by the child page of the cell being deleted. This makes
6565 ** balancing the tree following the delete operation easier. */
6566 if( !pPage->leaf ){
6567 int notUsed;
6568 if( SQLITE_OK!=(rc = sqlite3BtreePrevious(pCur, &notUsed)) ){
6569 return rc;
6570 }
6571 }
6572
6573 /* Save the positions of any other cursors open on this table before
6574 ** making any modifications. Make the page containing the entry to be
6575 ** deleted writable. Then free any overflow pages associated with the
6576 ** entry and finally remove the cell itself from within the page. */
6577 if( SQLITE_OK!=(rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur))
6578 || SQLITE_OK!=(rc = sqlite3PagerWrite(pPage->pDbPage))
6579 || SQLITE_OK!=(rc = clearCell(pPage, pCell))
6580 || SQLITE_OK!=(rc = dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell)))
danielk1977da184232006-01-05 11:34:32 +00006581 ){
6582 return rc;
6583 }
danielk1977e6efa742004-11-10 11:55:10 +00006584
danielk19774dbaa892009-06-16 16:50:22 +00006585 /* If the cell deleted was not located on a leaf page, then the cursor
6586 ** is currently pointing to the largest entry in the sub-tree headed
6587 ** by the child-page of the cell that was just deleted from an internal
6588 ** node. The cell from the leaf node needs to be moved to the internal
6589 ** node to replace the deleted cell. */
drh4b70f112004-05-02 21:12:19 +00006590 if( !pPage->leaf ){
danielk19774dbaa892009-06-16 16:50:22 +00006591 MemPage *pLeaf = pCur->apPage[pCur->iPage];
6592 int nCell;
6593 Pgno n = pCur->apPage[iCellDepth+1]->pgno;
6594 unsigned char *pTmp;
danielk1977e6efa742004-11-10 11:55:10 +00006595
danielk19774dbaa892009-06-16 16:50:22 +00006596 pCell = findCell(pLeaf, pLeaf->nCell-1);
6597 nCell = cellSizePtr(pLeaf, pCell);
6598 assert( MX_CELL_SIZE(pBt)>=nCell );
danielk197771d5d2c2008-09-29 11:49:47 +00006599
danielk19774dbaa892009-06-16 16:50:22 +00006600 allocateTempSpace(pBt);
6601 pTmp = pBt->pTmpSpace;
danielk19772f78fc62008-09-30 09:31:45 +00006602
danielk19774dbaa892009-06-16 16:50:22 +00006603 if( SQLITE_OK!=(rc = sqlite3PagerWrite(pLeaf->pDbPage))
6604 || SQLITE_OK!=(rc = insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n))
6605 || SQLITE_OK!=(rc = dropCell(pLeaf, pLeaf->nCell-1, nCell))
6606 ){
6607 return rc;
shanedcc50b72008-11-13 18:29:50 +00006608 }
drh5e2f8b92001-05-28 00:41:15 +00006609 }
danielk19774dbaa892009-06-16 16:50:22 +00006610
6611 /* Balance the tree. If the entry deleted was located on a leaf page,
6612 ** then the cursor still points to that page. In this case the first
6613 ** call to balance() repairs the tree, and the if(...) condition is
6614 ** never true.
6615 **
6616 ** Otherwise, if the entry deleted was on an internal node page, then
6617 ** pCur is pointing to the leaf page from which a cell was removed to
6618 ** replace the cell deleted from the internal node. This is slightly
6619 ** tricky as the leaf node may be underfull, and the internal node may
6620 ** be either under or overfull. In this case run the balancing algorithm
6621 ** on the leaf node first. If the balance proceeds far enough up the
6622 ** tree that we can be sure that any problem in the internal node has
6623 ** been corrected, so be it. Otherwise, after balancing the leaf node,
6624 ** walk the cursor up the tree to the internal node and balance it as
6625 ** well. */
6626 rc = balance(pCur);
6627 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
6628 while( pCur->iPage>iCellDepth ){
6629 releasePage(pCur->apPage[pCur->iPage--]);
6630 }
6631 rc = balance(pCur);
6632 }
6633
danielk19776b456a22005-03-21 04:04:02 +00006634 if( rc==SQLITE_OK ){
6635 moveToRoot(pCur);
6636 }
drh5e2f8b92001-05-28 00:41:15 +00006637 return rc;
drh3b7511c2001-05-26 13:15:44 +00006638}
drh8b2f49b2001-06-08 00:21:52 +00006639
6640/*
drhc6b52df2002-01-04 03:09:29 +00006641** Create a new BTree table. Write into *piTable the page
6642** number for the root page of the new table.
6643**
drhab01f612004-05-22 02:55:23 +00006644** The type of type is determined by the flags parameter. Only the
6645** following values of flags are currently in use. Other values for
6646** flags might not work:
6647**
6648** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
6649** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00006650*/
drhd677b3d2007-08-20 22:48:41 +00006651static int btreeCreateTable(Btree *p, int *piTable, int flags){
danielk1977aef0bf62005-12-30 16:28:01 +00006652 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006653 MemPage *pRoot;
6654 Pgno pgnoRoot;
6655 int rc;
drhd677b3d2007-08-20 22:48:41 +00006656
drh1fee73e2007-08-29 04:00:57 +00006657 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00006658 assert( pBt->inTransaction==TRANS_WRITE );
danielk197728129562005-01-11 10:25:06 +00006659 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00006660
danielk1977003ba062004-11-04 02:57:33 +00006661#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00006662 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00006663 if( rc ){
6664 return rc;
6665 }
danielk1977003ba062004-11-04 02:57:33 +00006666#else
danielk1977687566d2004-11-02 12:56:41 +00006667 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00006668 Pgno pgnoMove; /* Move a page here to make room for the root-page */
6669 MemPage *pPageMove; /* The page to move to. */
6670
danielk197720713f32007-05-03 11:43:33 +00006671 /* Creating a new table may probably require moving an existing database
6672 ** to make room for the new tables root page. In case this page turns
6673 ** out to be an overflow page, delete all overflow page-map caches
6674 ** held by open cursors.
6675 */
danielk197792d4d7a2007-05-04 12:05:56 +00006676 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00006677
danielk1977003ba062004-11-04 02:57:33 +00006678 /* Read the value of meta[3] from the database to determine where the
6679 ** root page of the new table should go. meta[3] is the largest root-page
6680 ** created so far, so the new root-page is (meta[3]+1).
6681 */
danielk1977602b4662009-07-02 07:47:33 +00006682 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00006683 pgnoRoot++;
6684
danielk1977599fcba2004-11-08 07:13:13 +00006685 /* The new root-page may not be allocated on a pointer-map page, or the
6686 ** PENDING_BYTE page.
6687 */
drh72190432008-01-31 14:54:43 +00006688 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00006689 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00006690 pgnoRoot++;
6691 }
6692 assert( pgnoRoot>=3 );
6693
6694 /* Allocate a page. The page that currently resides at pgnoRoot will
6695 ** be moved to the allocated page (unless the allocated page happens
6696 ** to reside at pgnoRoot).
6697 */
drh4f0c5872007-03-26 22:05:01 +00006698 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00006699 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00006700 return rc;
6701 }
danielk1977003ba062004-11-04 02:57:33 +00006702
6703 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00006704 /* pgnoRoot is the page that will be used for the root-page of
6705 ** the new table (assuming an error did not occur). But we were
6706 ** allocated pgnoMove. If required (i.e. if it was not allocated
6707 ** by extending the file), the current page at position pgnoMove
6708 ** is already journaled.
6709 */
danielk1977003ba062004-11-04 02:57:33 +00006710 u8 eType;
6711 Pgno iPtrPage;
6712
6713 releasePage(pPageMove);
danielk1977f35843b2007-04-07 15:03:17 +00006714
6715 /* Move the page currently at pgnoRoot to pgnoMove. */
drh16a9b832007-05-05 18:39:25 +00006716 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006717 if( rc!=SQLITE_OK ){
6718 return rc;
6719 }
6720 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drh27731d72009-06-22 12:05:10 +00006721 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
6722 rc = SQLITE_CORRUPT_BKPT;
6723 }
6724 if( rc!=SQLITE_OK ){
danielk1977003ba062004-11-04 02:57:33 +00006725 releasePage(pRoot);
6726 return rc;
6727 }
drhccae6022005-02-26 17:31:26 +00006728 assert( eType!=PTRMAP_ROOTPAGE );
6729 assert( eType!=PTRMAP_FREEPAGE );
danielk19774c999992008-07-16 18:17:55 +00006730 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
danielk1977003ba062004-11-04 02:57:33 +00006731 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00006732
6733 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00006734 if( rc!=SQLITE_OK ){
6735 return rc;
6736 }
drh16a9b832007-05-05 18:39:25 +00006737 rc = sqlite3BtreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006738 if( rc!=SQLITE_OK ){
6739 return rc;
6740 }
danielk19773b8a05f2007-03-19 17:44:26 +00006741 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00006742 if( rc!=SQLITE_OK ){
6743 releasePage(pRoot);
6744 return rc;
6745 }
6746 }else{
6747 pRoot = pPageMove;
6748 }
6749
danielk197742741be2005-01-08 12:42:39 +00006750 /* Update the pointer-map and meta-data with the new root-page number. */
danielk1977003ba062004-11-04 02:57:33 +00006751 rc = ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0);
6752 if( rc ){
6753 releasePage(pRoot);
6754 return rc;
6755 }
danielk1977aef0bf62005-12-30 16:28:01 +00006756 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00006757 if( rc ){
6758 releasePage(pRoot);
6759 return rc;
6760 }
danielk197742741be2005-01-08 12:42:39 +00006761
danielk1977003ba062004-11-04 02:57:33 +00006762 }else{
drh4f0c5872007-03-26 22:05:01 +00006763 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00006764 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00006765 }
6766#endif
danielk19773b8a05f2007-03-19 17:44:26 +00006767 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhde647132004-05-07 17:57:49 +00006768 zeroPage(pRoot, flags | PTF_LEAF);
danielk19773b8a05f2007-03-19 17:44:26 +00006769 sqlite3PagerUnref(pRoot->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00006770 *piTable = (int)pgnoRoot;
6771 return SQLITE_OK;
6772}
drhd677b3d2007-08-20 22:48:41 +00006773int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
6774 int rc;
6775 sqlite3BtreeEnter(p);
6776 rc = btreeCreateTable(p, piTable, flags);
6777 sqlite3BtreeLeave(p);
6778 return rc;
6779}
drh8b2f49b2001-06-08 00:21:52 +00006780
6781/*
6782** Erase the given database page and all its children. Return
6783** the page to the freelist.
6784*/
drh4b70f112004-05-02 21:12:19 +00006785static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00006786 BtShared *pBt, /* The BTree that contains the table */
drh4b70f112004-05-02 21:12:19 +00006787 Pgno pgno, /* Page number to clear */
danielk1977c7af4842008-10-27 13:59:33 +00006788 int freePageFlag, /* Deallocate page if true */
6789 int *pnChange
drh4b70f112004-05-02 21:12:19 +00006790){
danielk19776b456a22005-03-21 04:04:02 +00006791 MemPage *pPage = 0;
drh8b2f49b2001-06-08 00:21:52 +00006792 int rc;
drh4b70f112004-05-02 21:12:19 +00006793 unsigned char *pCell;
6794 int i;
drh8b2f49b2001-06-08 00:21:52 +00006795
drh1fee73e2007-08-29 04:00:57 +00006796 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197789d40042008-11-17 14:20:56 +00006797 if( pgno>pagerPagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00006798 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00006799 }
6800
danielk197771d5d2c2008-09-29 11:49:47 +00006801 rc = getAndInitPage(pBt, pgno, &pPage);
danielk19776b456a22005-03-21 04:04:02 +00006802 if( rc ) goto cleardatabasepage_out;
drh4b70f112004-05-02 21:12:19 +00006803 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00006804 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00006805 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00006806 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00006807 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006808 }
drh4b70f112004-05-02 21:12:19 +00006809 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00006810 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006811 }
drha34b6762004-05-07 13:30:42 +00006812 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00006813 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00006814 if( rc ) goto cleardatabasepage_out;
danielk1977c7af4842008-10-27 13:59:33 +00006815 }else if( pnChange ){
6816 assert( pPage->intKey );
6817 *pnChange += pPage->nCell;
drh2aa679f2001-06-25 02:11:07 +00006818 }
6819 if( freePageFlag ){
drh4b70f112004-05-02 21:12:19 +00006820 rc = freePage(pPage);
danielk19773b8a05f2007-03-19 17:44:26 +00006821 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
drh3a4c1412004-05-09 20:40:11 +00006822 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00006823 }
danielk19776b456a22005-03-21 04:04:02 +00006824
6825cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00006826 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00006827 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006828}
6829
6830/*
drhab01f612004-05-22 02:55:23 +00006831** Delete all information from a single table in the database. iTable is
6832** the page number of the root of the table. After this routine returns,
6833** the root page is empty, but still exists.
6834**
6835** This routine will fail with SQLITE_LOCKED if there are any open
6836** read cursors on the table. Open write cursors are moved to the
6837** root of the table.
danielk1977c7af4842008-10-27 13:59:33 +00006838**
6839** If pnChange is not NULL, then table iTable must be an intkey table. The
6840** integer value pointed to by pnChange is incremented by the number of
6841** entries in the table.
drh8b2f49b2001-06-08 00:21:52 +00006842*/
danielk1977c7af4842008-10-27 13:59:33 +00006843int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
drh8b2f49b2001-06-08 00:21:52 +00006844 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00006845 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00006846 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00006847 assert( p->inTrans==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +00006848
6849 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
6850 ** is the root of a table b-tree - if it is not, the following call is
6851 ** a no-op). */
6852 invalidateIncrblobCursors(p, iTable, 0, 1);
6853
6854 if( SQLITE_OK==(rc = saveAllCursors(pBt, (Pgno)iTable, 0)) ){
danielk197762c14b32008-11-19 09:05:26 +00006855 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
drh8b2f49b2001-06-08 00:21:52 +00006856 }
drhd677b3d2007-08-20 22:48:41 +00006857 sqlite3BtreeLeave(p);
6858 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006859}
6860
6861/*
6862** Erase all information in a table and add the root of the table to
6863** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00006864** page 1) is never added to the freelist.
6865**
6866** This routine will fail with SQLITE_LOCKED if there are any open
6867** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00006868**
6869** If AUTOVACUUM is enabled and the page at iTable is not the last
6870** root page in the database file, then the last root page
6871** in the database file is moved into the slot formerly occupied by
6872** iTable and that last slot formerly occupied by the last root page
6873** is added to the freelist instead of iTable. In this say, all
6874** root pages are kept at the beginning of the database file, which
6875** is necessary for AUTOVACUUM to work right. *piMoved is set to the
6876** page number that used to be the last root page in the file before
6877** the move. If no page gets moved, *piMoved is set to 0.
6878** The last root page is recorded in meta[3] and the value of
6879** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00006880*/
danielk197789d40042008-11-17 14:20:56 +00006881static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00006882 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00006883 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00006884 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00006885
drh1fee73e2007-08-29 04:00:57 +00006886 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00006887 assert( p->inTrans==TRANS_WRITE );
danielk1977a0bf2652004-11-04 14:30:04 +00006888
danielk1977e6efa742004-11-10 11:55:10 +00006889 /* It is illegal to drop a table if any cursors are open on the
6890 ** database. This is because in auto-vacuum mode the backend may
6891 ** need to move another root-page to fill a gap left by the deleted
6892 ** root page. If an open cursor was using this page a problem would
6893 ** occur.
6894 */
6895 if( pBt->pCursor ){
danielk1977404ca072009-03-16 13:19:36 +00006896 sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
6897 return SQLITE_LOCKED_SHAREDCACHE;
drh5df72a52002-06-06 23:16:05 +00006898 }
danielk1977a0bf2652004-11-04 14:30:04 +00006899
drh16a9b832007-05-05 18:39:25 +00006900 rc = sqlite3BtreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00006901 if( rc ) return rc;
danielk1977c7af4842008-10-27 13:59:33 +00006902 rc = sqlite3BtreeClearTable(p, iTable, 0);
danielk19776b456a22005-03-21 04:04:02 +00006903 if( rc ){
6904 releasePage(pPage);
6905 return rc;
6906 }
danielk1977a0bf2652004-11-04 14:30:04 +00006907
drh205f48e2004-11-05 00:43:11 +00006908 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00006909
drh4b70f112004-05-02 21:12:19 +00006910 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00006911#ifdef SQLITE_OMIT_AUTOVACUUM
drha34b6762004-05-07 13:30:42 +00006912 rc = freePage(pPage);
danielk1977a0bf2652004-11-04 14:30:04 +00006913 releasePage(pPage);
6914#else
6915 if( pBt->autoVacuum ){
6916 Pgno maxRootPgno;
danielk1977602b4662009-07-02 07:47:33 +00006917 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006918
6919 if( iTable==maxRootPgno ){
6920 /* If the table being dropped is the table with the largest root-page
6921 ** number in the database, put the root page on the free list.
6922 */
6923 rc = freePage(pPage);
6924 releasePage(pPage);
6925 if( rc!=SQLITE_OK ){
6926 return rc;
6927 }
6928 }else{
6929 /* The table being dropped does not have the largest root-page
6930 ** number in the database. So move the page that does into the
6931 ** gap left by the deleted root-page.
6932 */
6933 MemPage *pMove;
6934 releasePage(pPage);
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 }
danielk19774c999992008-07-16 18:17:55 +00006939 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006940 releasePage(pMove);
6941 if( rc!=SQLITE_OK ){
6942 return rc;
6943 }
drh16a9b832007-05-05 18:39:25 +00006944 rc = sqlite3BtreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006945 if( rc!=SQLITE_OK ){
6946 return rc;
6947 }
6948 rc = freePage(pMove);
6949 releasePage(pMove);
6950 if( rc!=SQLITE_OK ){
6951 return rc;
6952 }
6953 *piMoved = maxRootPgno;
6954 }
6955
danielk1977599fcba2004-11-08 07:13:13 +00006956 /* Set the new 'max-root-page' value in the database header. This
6957 ** is the old value less one, less one more if that happens to
6958 ** be a root-page number, less one again if that is the
6959 ** PENDING_BYTE_PAGE.
6960 */
danielk197787a6e732004-11-05 12:58:25 +00006961 maxRootPgno--;
danielk1977599fcba2004-11-08 07:13:13 +00006962 if( maxRootPgno==PENDING_BYTE_PAGE(pBt) ){
6963 maxRootPgno--;
6964 }
danielk1977266664d2006-02-10 08:24:21 +00006965 if( maxRootPgno==PTRMAP_PAGENO(pBt, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00006966 maxRootPgno--;
6967 }
danielk1977599fcba2004-11-08 07:13:13 +00006968 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
6969
danielk1977aef0bf62005-12-30 16:28:01 +00006970 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006971 }else{
6972 rc = freePage(pPage);
6973 releasePage(pPage);
6974 }
6975#endif
drh2aa679f2001-06-25 02:11:07 +00006976 }else{
danielk1977a0bf2652004-11-04 14:30:04 +00006977 /* If sqlite3BtreeDropTable was called on page 1. */
drha34b6762004-05-07 13:30:42 +00006978 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00006979 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00006980 }
drh8b2f49b2001-06-08 00:21:52 +00006981 return rc;
6982}
drhd677b3d2007-08-20 22:48:41 +00006983int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
6984 int rc;
6985 sqlite3BtreeEnter(p);
6986 rc = btreeDropTable(p, iTable, piMoved);
6987 sqlite3BtreeLeave(p);
6988 return rc;
6989}
drh8b2f49b2001-06-08 00:21:52 +00006990
drh001bbcb2003-03-19 03:14:00 +00006991
drh8b2f49b2001-06-08 00:21:52 +00006992/*
danielk1977602b4662009-07-02 07:47:33 +00006993** This function may only be called if the b-tree connection already
6994** has a read or write transaction open on the database.
6995**
drh23e11ca2004-05-04 17:27:28 +00006996** Read the meta-information out of a database file. Meta[0]
6997** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00006998** through meta[15] are available for use by higher layers. Meta[0]
6999** is read-only, the others are read/write.
7000**
7001** The schema layer numbers meta values differently. At the schema
7002** layer (and the SetCookie and ReadCookie opcodes) the number of
7003** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00007004*/
danielk1977602b4662009-07-02 07:47:33 +00007005void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
danielk1977aef0bf62005-12-30 16:28:01 +00007006 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00007007
drhd677b3d2007-08-20 22:48:41 +00007008 sqlite3BtreeEnter(p);
danielk1977602b4662009-07-02 07:47:33 +00007009 assert( p->inTrans>TRANS_NONE );
7010 assert( SQLITE_OK==querySharedCacheTableLock(p, 1, READ_LOCK) );
7011 assert( pBt->pPage1 );
drh23e11ca2004-05-04 17:27:28 +00007012 assert( idx>=0 && idx<=15 );
danielk1977ea897302008-09-19 15:10:58 +00007013
danielk1977602b4662009-07-02 07:47:33 +00007014 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
drhae157872004-08-14 19:20:09 +00007015
danielk1977602b4662009-07-02 07:47:33 +00007016 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
7017 ** database, mark the database as read-only. */
danielk1977003ba062004-11-04 02:57:33 +00007018#ifdef SQLITE_OMIT_AUTOVACUUM
danielk19770d19f7a2009-06-03 11:25:07 +00007019 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00007020#endif
drhae157872004-08-14 19:20:09 +00007021
drhd677b3d2007-08-20 22:48:41 +00007022 sqlite3BtreeLeave(p);
drh8b2f49b2001-06-08 00:21:52 +00007023}
7024
7025/*
drh23e11ca2004-05-04 17:27:28 +00007026** Write meta-information back into the database. Meta[0] is
7027** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00007028*/
danielk1977aef0bf62005-12-30 16:28:01 +00007029int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
7030 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00007031 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00007032 int rc;
drh23e11ca2004-05-04 17:27:28 +00007033 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00007034 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00007035 assert( p->inTrans==TRANS_WRITE );
7036 assert( pBt->pPage1!=0 );
7037 pP1 = pBt->pPage1->aData;
7038 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
7039 if( rc==SQLITE_OK ){
7040 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +00007041#ifndef SQLITE_OMIT_AUTOVACUUM
danielk19770d19f7a2009-06-03 11:25:07 +00007042 if( idx==BTREE_INCR_VACUUM ){
drh64022502009-01-09 14:11:04 +00007043 assert( pBt->autoVacuum || iMeta==0 );
7044 assert( iMeta==0 || iMeta==1 );
7045 pBt->incrVacuum = (u8)iMeta;
drhd677b3d2007-08-20 22:48:41 +00007046 }
drh64022502009-01-09 14:11:04 +00007047#endif
drh5df72a52002-06-06 23:16:05 +00007048 }
drhd677b3d2007-08-20 22:48:41 +00007049 sqlite3BtreeLeave(p);
7050 return rc;
drh8b2f49b2001-06-08 00:21:52 +00007051}
drh8c42ca92001-06-22 19:15:00 +00007052
drhf328bc82004-05-10 23:29:49 +00007053/*
7054** Return the flag byte at the beginning of the page that the cursor
7055** is currently pointing to.
7056*/
7057int sqlite3BtreeFlags(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00007058 /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
drha3460582008-07-11 21:02:53 +00007059 ** restoreCursorPosition() here.
danielk1977da184232006-01-05 11:34:32 +00007060 */
danielk1977e448dc42008-01-02 11:50:51 +00007061 MemPage *pPage;
drha3460582008-07-11 21:02:53 +00007062 restoreCursorPosition(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00007063 pPage = pCur->apPage[pCur->iPage];
drh1fee73e2007-08-29 04:00:57 +00007064 assert( cursorHoldsMutex(pCur) );
drh64022502009-01-09 14:11:04 +00007065 assert( pPage!=0 );
drhd0679ed2007-08-28 22:24:34 +00007066 assert( pPage->pBt==pCur->pBt );
drh64022502009-01-09 14:11:04 +00007067 return pPage->aData[pPage->hdrOffset];
drhf328bc82004-05-10 23:29:49 +00007068}
7069
danielk1977a5533162009-02-24 10:01:51 +00007070#ifndef SQLITE_OMIT_BTREECOUNT
7071/*
7072** The first argument, pCur, is a cursor opened on some b-tree. Count the
7073** number of entries in the b-tree and write the result to *pnEntry.
7074**
7075** SQLITE_OK is returned if the operation is successfully executed.
7076** Otherwise, if an error is encountered (i.e. an IO error or database
7077** corruption) an SQLite error code is returned.
7078*/
7079int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
7080 i64 nEntry = 0; /* Value to return in *pnEntry */
7081 int rc; /* Return code */
7082 rc = moveToRoot(pCur);
7083
7084 /* Unless an error occurs, the following loop runs one iteration for each
7085 ** page in the B-Tree structure (not including overflow pages).
7086 */
7087 while( rc==SQLITE_OK ){
7088 int iIdx; /* Index of child node in parent */
7089 MemPage *pPage; /* Current page of the b-tree */
7090
7091 /* If this is a leaf page or the tree is not an int-key tree, then
7092 ** this page contains countable entries. Increment the entry counter
7093 ** accordingly.
7094 */
7095 pPage = pCur->apPage[pCur->iPage];
7096 if( pPage->leaf || !pPage->intKey ){
7097 nEntry += pPage->nCell;
7098 }
7099
7100 /* pPage is a leaf node. This loop navigates the cursor so that it
7101 ** points to the first interior cell that it points to the parent of
7102 ** the next page in the tree that has not yet been visited. The
7103 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
7104 ** of the page, or to the number of cells in the page if the next page
7105 ** to visit is the right-child of its parent.
7106 **
7107 ** If all pages in the tree have been visited, return SQLITE_OK to the
7108 ** caller.
7109 */
7110 if( pPage->leaf ){
7111 do {
7112 if( pCur->iPage==0 ){
7113 /* All pages of the b-tree have been visited. Return successfully. */
7114 *pnEntry = nEntry;
7115 return SQLITE_OK;
7116 }
7117 sqlite3BtreeMoveToParent(pCur);
7118 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
7119
7120 pCur->aiIdx[pCur->iPage]++;
7121 pPage = pCur->apPage[pCur->iPage];
7122 }
7123
7124 /* Descend to the child node of the cell that the cursor currently
7125 ** points at. This is the right-child if (iIdx==pPage->nCell).
7126 */
7127 iIdx = pCur->aiIdx[pCur->iPage];
7128 if( iIdx==pPage->nCell ){
7129 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
7130 }else{
7131 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
7132 }
7133 }
7134
shanebe217792009-03-05 04:20:31 +00007135 /* An error has occurred. Return an error code. */
danielk1977a5533162009-02-24 10:01:51 +00007136 return rc;
7137}
7138#endif
drhdd793422001-06-28 01:54:48 +00007139
drhdd793422001-06-28 01:54:48 +00007140/*
drh5eddca62001-06-30 21:53:53 +00007141** Return the pager associated with a BTree. This routine is used for
7142** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00007143*/
danielk1977aef0bf62005-12-30 16:28:01 +00007144Pager *sqlite3BtreePager(Btree *p){
7145 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00007146}
drh5eddca62001-06-30 21:53:53 +00007147
drhb7f91642004-10-31 02:22:47 +00007148#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007149/*
7150** Append a message to the error message string.
7151*/
drh2e38c322004-09-03 18:38:44 +00007152static void checkAppendMsg(
7153 IntegrityCk *pCheck,
7154 char *zMsg1,
7155 const char *zFormat,
7156 ...
7157){
7158 va_list ap;
drh1dcdbc02007-01-27 02:24:54 +00007159 if( !pCheck->mxErr ) return;
7160 pCheck->mxErr--;
7161 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00007162 va_start(ap, zFormat);
drhf089aa42008-07-08 19:34:06 +00007163 if( pCheck->errMsg.nChar ){
7164 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
drh5eddca62001-06-30 21:53:53 +00007165 }
drhf089aa42008-07-08 19:34:06 +00007166 if( zMsg1 ){
7167 sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
7168 }
7169 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
7170 va_end(ap);
drhc890fec2008-08-01 20:10:08 +00007171 if( pCheck->errMsg.mallocFailed ){
7172 pCheck->mallocFailed = 1;
7173 }
drh5eddca62001-06-30 21:53:53 +00007174}
drhb7f91642004-10-31 02:22:47 +00007175#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00007176
drhb7f91642004-10-31 02:22:47 +00007177#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007178/*
7179** Add 1 to the reference count for page iPage. If this is the second
7180** reference to the page, add an error message to pCheck->zErrMsg.
7181** Return 1 if there are 2 ore more references to the page and 0 if
7182** if this is the first reference to the page.
7183**
7184** Also check that the page number is in bounds.
7185*/
danielk197789d40042008-11-17 14:20:56 +00007186static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00007187 if( iPage==0 ) return 1;
danielk197789d40042008-11-17 14:20:56 +00007188 if( iPage>pCheck->nPage ){
drh2e38c322004-09-03 18:38:44 +00007189 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00007190 return 1;
7191 }
7192 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00007193 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00007194 return 1;
7195 }
7196 return (pCheck->anRef[iPage]++)>1;
7197}
7198
danielk1977afcdd022004-10-31 16:25:42 +00007199#ifndef SQLITE_OMIT_AUTOVACUUM
7200/*
7201** Check that the entry in the pointer-map for page iChild maps to
7202** page iParent, pointer type ptrType. If not, append an error message
7203** to pCheck.
7204*/
7205static void checkPtrmap(
7206 IntegrityCk *pCheck, /* Integrity check context */
7207 Pgno iChild, /* Child page number */
7208 u8 eType, /* Expected pointer map type */
7209 Pgno iParent, /* Expected pointer map parent page number */
7210 char *zContext /* Context description (used for error msg) */
7211){
7212 int rc;
7213 u8 ePtrmapType;
7214 Pgno iPtrmapParent;
7215
7216 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
7217 if( rc!=SQLITE_OK ){
drhb56cd552009-05-01 13:16:54 +00007218 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
danielk1977afcdd022004-10-31 16:25:42 +00007219 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
7220 return;
7221 }
7222
7223 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
7224 checkAppendMsg(pCheck, zContext,
7225 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
7226 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
7227 }
7228}
7229#endif
7230
drh5eddca62001-06-30 21:53:53 +00007231/*
7232** Check the integrity of the freelist or of an overflow page list.
7233** Verify that the number of pages on the list is N.
7234*/
drh30e58752002-03-02 20:41:57 +00007235static void checkList(
7236 IntegrityCk *pCheck, /* Integrity checking context */
7237 int isFreeList, /* True for a freelist. False for overflow page list */
7238 int iPage, /* Page number for first page in the list */
7239 int N, /* Expected number of pages in the list */
7240 char *zContext /* Context for error messages */
7241){
7242 int i;
drh3a4c1412004-05-09 20:40:11 +00007243 int expected = N;
7244 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00007245 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00007246 DbPage *pOvflPage;
7247 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00007248 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00007249 checkAppendMsg(pCheck, zContext,
7250 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00007251 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00007252 break;
7253 }
7254 if( checkRef(pCheck, iPage, zContext) ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00007255 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
drh2e38c322004-09-03 18:38:44 +00007256 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00007257 break;
7258 }
danielk19773b8a05f2007-03-19 17:44:26 +00007259 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00007260 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00007261 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00007262#ifndef SQLITE_OMIT_AUTOVACUUM
7263 if( pCheck->pBt->autoVacuum ){
7264 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
7265 }
7266#endif
drh45b1fac2008-07-04 17:52:42 +00007267 if( n>pCheck->pBt->usableSize/4-2 ){
drh2e38c322004-09-03 18:38:44 +00007268 checkAppendMsg(pCheck, zContext,
7269 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00007270 N--;
7271 }else{
7272 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00007273 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00007274#ifndef SQLITE_OMIT_AUTOVACUUM
7275 if( pCheck->pBt->autoVacuum ){
7276 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
7277 }
7278#endif
7279 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00007280 }
7281 N -= n;
drh30e58752002-03-02 20:41:57 +00007282 }
drh30e58752002-03-02 20:41:57 +00007283 }
danielk1977afcdd022004-10-31 16:25:42 +00007284#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00007285 else{
7286 /* If this database supports auto-vacuum and iPage is not the last
7287 ** page in this overflow list, check that the pointer-map entry for
7288 ** the following page matches iPage.
7289 */
7290 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00007291 i = get4byte(pOvflData);
danielk1977687566d2004-11-02 12:56:41 +00007292 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
7293 }
danielk1977afcdd022004-10-31 16:25:42 +00007294 }
7295#endif
danielk19773b8a05f2007-03-19 17:44:26 +00007296 iPage = get4byte(pOvflData);
7297 sqlite3PagerUnref(pOvflPage);
drh5eddca62001-06-30 21:53:53 +00007298 }
7299}
drhb7f91642004-10-31 02:22:47 +00007300#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00007301
drhb7f91642004-10-31 02:22:47 +00007302#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007303/*
7304** Do various sanity checks on a single page of a tree. Return
7305** the tree depth. Root pages return 0. Parents of root pages
7306** return 1, and so forth.
7307**
7308** These checks are done:
7309**
7310** 1. Make sure that cells and freeblocks do not overlap
7311** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00007312** NO 2. Make sure cell keys are in order.
7313** NO 3. Make sure no key is less than or equal to zLowerBound.
7314** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00007315** 5. Check the integrity of overflow pages.
7316** 6. Recursively call checkTreePage on all children.
7317** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00007318** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00007319** the root of the tree.
7320*/
7321static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00007322 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00007323 int iPage, /* Page number of the page to check */
drh74161702006-02-24 02:53:49 +00007324 char *zParentContext /* Parent context */
drh5eddca62001-06-30 21:53:53 +00007325){
7326 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00007327 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00007328 int hdr, cellStart;
7329 int nCell;
drhda200cc2004-05-09 11:51:38 +00007330 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00007331 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00007332 int usableSize;
drh5eddca62001-06-30 21:53:53 +00007333 char zContext[100];
shane0af3f892008-11-12 04:55:34 +00007334 char *hit = 0;
drh5eddca62001-06-30 21:53:53 +00007335
drh5bb3eb92007-05-04 13:15:55 +00007336 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
danielk1977ef73ee92004-11-06 12:26:07 +00007337
drh5eddca62001-06-30 21:53:53 +00007338 /* Check that the page exists
7339 */
drhd9cb6ac2005-10-20 07:28:17 +00007340 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00007341 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00007342 if( iPage==0 ) return 0;
7343 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drh16a9b832007-05-05 18:39:25 +00007344 if( (rc = sqlite3BtreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drhb56cd552009-05-01 13:16:54 +00007345 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
drh2e38c322004-09-03 18:38:44 +00007346 checkAppendMsg(pCheck, zContext,
7347 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00007348 return 0;
7349 }
danielk197771d5d2c2008-09-29 11:49:47 +00007350 if( (rc = sqlite3BtreeInitPage(pPage))!=0 ){
drh64022502009-01-09 14:11:04 +00007351 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
drh16a9b832007-05-05 18:39:25 +00007352 checkAppendMsg(pCheck, zContext,
7353 "sqlite3BtreeInitPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00007354 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00007355 return 0;
7356 }
7357
7358 /* Check out all the cells.
7359 */
7360 depth = 0;
drh1dcdbc02007-01-27 02:24:54 +00007361 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
drh6f11bef2004-05-13 01:12:56 +00007362 u8 *pCell;
danielk197789d40042008-11-17 14:20:56 +00007363 u32 sz;
drh6f11bef2004-05-13 01:12:56 +00007364 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00007365
7366 /* Check payload overflow pages
7367 */
drh5bb3eb92007-05-04 13:15:55 +00007368 sqlite3_snprintf(sizeof(zContext), zContext,
7369 "On tree page %d cell %d: ", iPage, i);
danielk19771cc5ed82007-05-16 17:28:43 +00007370 pCell = findCell(pPage,i);
drh16a9b832007-05-05 18:39:25 +00007371 sqlite3BtreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00007372 sz = info.nData;
drhf49661a2008-12-10 16:45:50 +00007373 if( !pPage->intKey ) sz += (int)info.nKey;
drh72365832007-03-06 15:53:44 +00007374 assert( sz==info.nPayload );
danielk19775be31f52009-03-30 13:53:43 +00007375 if( (sz>info.nLocal)
7376 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
7377 ){
drhb6f41482004-05-14 01:58:11 +00007378 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00007379 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
7380#ifndef SQLITE_OMIT_AUTOVACUUM
7381 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00007382 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00007383 }
7384#endif
7385 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00007386 }
7387
7388 /* Check sanity of left child page.
7389 */
drhda200cc2004-05-09 11:51:38 +00007390 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00007391 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00007392#ifndef SQLITE_OMIT_AUTOVACUUM
7393 if( pBt->autoVacuum ){
7394 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
7395 }
7396#endif
danielk197762c14b32008-11-19 09:05:26 +00007397 d2 = checkTreePage(pCheck, pgno, zContext);
drhda200cc2004-05-09 11:51:38 +00007398 if( i>0 && d2!=depth ){
7399 checkAppendMsg(pCheck, zContext, "Child page depth differs");
7400 }
7401 depth = d2;
drh5eddca62001-06-30 21:53:53 +00007402 }
drh5eddca62001-06-30 21:53:53 +00007403 }
drhda200cc2004-05-09 11:51:38 +00007404 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00007405 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh5bb3eb92007-05-04 13:15:55 +00007406 sqlite3_snprintf(sizeof(zContext), zContext,
7407 "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00007408#ifndef SQLITE_OMIT_AUTOVACUUM
7409 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00007410 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00007411 }
7412#endif
danielk197762c14b32008-11-19 09:05:26 +00007413 checkTreePage(pCheck, pgno, zContext);
drhda200cc2004-05-09 11:51:38 +00007414 }
drh5eddca62001-06-30 21:53:53 +00007415
7416 /* Check for complete coverage of the page
7417 */
drhda200cc2004-05-09 11:51:38 +00007418 data = pPage->aData;
7419 hdr = pPage->hdrOffset;
drhf7141992008-06-19 00:16:08 +00007420 hit = sqlite3PageMalloc( pBt->pageSize );
drhc890fec2008-08-01 20:10:08 +00007421 if( hit==0 ){
7422 pCheck->mallocFailed = 1;
7423 }else{
shane5780ebd2008-11-11 17:36:30 +00007424 u16 contentOffset = get2byte(&data[hdr+5]);
7425 if (contentOffset > usableSize) {
7426 checkAppendMsg(pCheck, 0,
7427 "Corruption detected in header on page %d",iPage,0);
shane0af3f892008-11-12 04:55:34 +00007428 goto check_page_abort;
shane5780ebd2008-11-11 17:36:30 +00007429 }
7430 memset(hit+contentOffset, 0, usableSize-contentOffset);
7431 memset(hit, 1, contentOffset);
drh2e38c322004-09-03 18:38:44 +00007432 nCell = get2byte(&data[hdr+3]);
7433 cellStart = hdr + 12 - 4*pPage->leaf;
7434 for(i=0; i<nCell; i++){
7435 int pc = get2byte(&data[cellStart+i*2]);
danielk1977daca5432008-08-25 11:57:16 +00007436 u16 size = 1024;
drh2e38c322004-09-03 18:38:44 +00007437 int j;
danielk1977daca5432008-08-25 11:57:16 +00007438 if( pc<=usableSize ){
7439 size = cellSizePtr(pPage, &data[pc]);
7440 }
danielk19777701e812005-01-10 12:59:51 +00007441 if( (pc+size-1)>=usableSize || pc<0 ){
7442 checkAppendMsg(pCheck, 0,
7443 "Corruption detected in cell %d on page %d",i,iPage,0);
7444 }else{
7445 for(j=pc+size-1; j>=pc; j--) hit[j]++;
7446 }
drh2e38c322004-09-03 18:38:44 +00007447 }
7448 for(cnt=0, i=get2byte(&data[hdr+1]); i>0 && i<usableSize && cnt<10000;
7449 cnt++){
7450 int size = get2byte(&data[i+2]);
7451 int j;
danielk19777701e812005-01-10 12:59:51 +00007452 if( (i+size-1)>=usableSize || i<0 ){
7453 checkAppendMsg(pCheck, 0,
7454 "Corruption detected in cell %d on page %d",i,iPage,0);
7455 }else{
7456 for(j=i+size-1; j>=i; j--) hit[j]++;
7457 }
drh2e38c322004-09-03 18:38:44 +00007458 i = get2byte(&data[i]);
7459 }
7460 for(i=cnt=0; i<usableSize; i++){
7461 if( hit[i]==0 ){
7462 cnt++;
7463 }else if( hit[i]>1 ){
7464 checkAppendMsg(pCheck, 0,
7465 "Multiple uses for byte %d of page %d", i, iPage);
7466 break;
7467 }
7468 }
7469 if( cnt!=data[hdr+7] ){
7470 checkAppendMsg(pCheck, 0,
7471 "Fragmented space is %d byte reported as %d on page %d",
7472 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00007473 }
7474 }
shane0af3f892008-11-12 04:55:34 +00007475check_page_abort:
7476 if (hit) sqlite3PageFree(hit);
drh6019e162001-07-02 17:51:45 +00007477
drh4b70f112004-05-02 21:12:19 +00007478 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00007479 return depth+1;
drh5eddca62001-06-30 21:53:53 +00007480}
drhb7f91642004-10-31 02:22:47 +00007481#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00007482
drhb7f91642004-10-31 02:22:47 +00007483#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007484/*
7485** This routine does a complete check of the given BTree file. aRoot[] is
7486** an array of pages numbers were each page number is the root page of
7487** a table. nRoot is the number of entries in aRoot.
7488**
drhc890fec2008-08-01 20:10:08 +00007489** Write the number of error seen in *pnErr. Except for some memory
drhe43ba702008-12-05 22:40:08 +00007490** allocation errors, an error message held in memory obtained from
drhc890fec2008-08-01 20:10:08 +00007491** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
drhe43ba702008-12-05 22:40:08 +00007492** returned. If a memory allocation error occurs, NULL is returned.
drh5eddca62001-06-30 21:53:53 +00007493*/
drh1dcdbc02007-01-27 02:24:54 +00007494char *sqlite3BtreeIntegrityCheck(
7495 Btree *p, /* The btree to be checked */
7496 int *aRoot, /* An array of root pages numbers for individual trees */
7497 int nRoot, /* Number of entries in aRoot[] */
7498 int mxErr, /* Stop reporting errors after this many */
7499 int *pnErr /* Write number of errors seen to this variable */
7500){
danielk197789d40042008-11-17 14:20:56 +00007501 Pgno i;
drh5eddca62001-06-30 21:53:53 +00007502 int nRef;
drhaaab5722002-02-19 13:39:21 +00007503 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00007504 BtShared *pBt = p->pBt;
drhf089aa42008-07-08 19:34:06 +00007505 char zErr[100];
drh5eddca62001-06-30 21:53:53 +00007506
drhd677b3d2007-08-20 22:48:41 +00007507 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00007508 nRef = sqlite3PagerRefcount(pBt->pPager);
danielk1977aef0bf62005-12-30 16:28:01 +00007509 if( lockBtreeWithRetry(p)!=SQLITE_OK ){
drhc890fec2008-08-01 20:10:08 +00007510 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00007511 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00007512 return sqlite3DbStrDup(0, "cannot acquire a read lock on the database");
drhefc251d2001-07-01 22:12:01 +00007513 }
drh5eddca62001-06-30 21:53:53 +00007514 sCheck.pBt = pBt;
7515 sCheck.pPager = pBt->pPager;
danielk197789d40042008-11-17 14:20:56 +00007516 sCheck.nPage = pagerPagecount(sCheck.pBt);
drh1dcdbc02007-01-27 02:24:54 +00007517 sCheck.mxErr = mxErr;
7518 sCheck.nErr = 0;
drhc890fec2008-08-01 20:10:08 +00007519 sCheck.mallocFailed = 0;
drh1dcdbc02007-01-27 02:24:54 +00007520 *pnErr = 0;
drh0de8c112002-07-06 16:32:14 +00007521 if( sCheck.nPage==0 ){
7522 unlockBtreeIfUnused(pBt);
drhd677b3d2007-08-20 22:48:41 +00007523 sqlite3BtreeLeave(p);
drh0de8c112002-07-06 16:32:14 +00007524 return 0;
7525 }
drhe5ae5732008-06-15 02:51:47 +00007526 sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00007527 if( !sCheck.anRef ){
7528 unlockBtreeIfUnused(pBt);
drh1dcdbc02007-01-27 02:24:54 +00007529 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00007530 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00007531 return 0;
danielk1977ac245ec2005-01-14 13:50:11 +00007532 }
drhda200cc2004-05-09 11:51:38 +00007533 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00007534 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00007535 if( i<=sCheck.nPage ){
7536 sCheck.anRef[i] = 1;
7537 }
drhf089aa42008-07-08 19:34:06 +00007538 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
drh5eddca62001-06-30 21:53:53 +00007539
7540 /* Check the integrity of the freelist
7541 */
drha34b6762004-05-07 13:30:42 +00007542 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
7543 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00007544
7545 /* Check all the tables.
7546 */
danielk197789d40042008-11-17 14:20:56 +00007547 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
drh4ff6dfa2002-03-03 23:06:00 +00007548 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00007549#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00007550 if( pBt->autoVacuum && aRoot[i]>1 ){
7551 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
7552 }
7553#endif
danielk197762c14b32008-11-19 09:05:26 +00007554 checkTreePage(&sCheck, aRoot[i], "List of tree roots: ");
drh5eddca62001-06-30 21:53:53 +00007555 }
7556
7557 /* Make sure every page in the file is referenced
7558 */
drh1dcdbc02007-01-27 02:24:54 +00007559 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00007560#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00007561 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00007562 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00007563 }
danielk1977afcdd022004-10-31 16:25:42 +00007564#else
7565 /* If the database supports auto-vacuum, make sure no tables contain
7566 ** references to pointer-map pages.
7567 */
7568 if( sCheck.anRef[i]==0 &&
danielk1977266664d2006-02-10 08:24:21 +00007569 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00007570 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
7571 }
7572 if( sCheck.anRef[i]!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00007573 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00007574 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
7575 }
7576#endif
drh5eddca62001-06-30 21:53:53 +00007577 }
7578
drh64022502009-01-09 14:11:04 +00007579 /* Make sure this analysis did not leave any unref() pages.
7580 ** This is an internal consistency check; an integrity check
7581 ** of the integrity check.
drh5eddca62001-06-30 21:53:53 +00007582 */
drh5e00f6c2001-09-13 13:46:56 +00007583 unlockBtreeIfUnused(pBt);
drh64022502009-01-09 14:11:04 +00007584 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
drh2e38c322004-09-03 18:38:44 +00007585 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00007586 "Outstanding page count goes from %d to %d during this analysis",
danielk19773b8a05f2007-03-19 17:44:26 +00007587 nRef, sqlite3PagerRefcount(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00007588 );
drh5eddca62001-06-30 21:53:53 +00007589 }
7590
7591 /* Clean up and report errors.
7592 */
drhd677b3d2007-08-20 22:48:41 +00007593 sqlite3BtreeLeave(p);
drh17435752007-08-16 04:30:38 +00007594 sqlite3_free(sCheck.anRef);
drhc890fec2008-08-01 20:10:08 +00007595 if( sCheck.mallocFailed ){
7596 sqlite3StrAccumReset(&sCheck.errMsg);
7597 *pnErr = sCheck.nErr+1;
7598 return 0;
7599 }
drh1dcdbc02007-01-27 02:24:54 +00007600 *pnErr = sCheck.nErr;
drhf089aa42008-07-08 19:34:06 +00007601 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
7602 return sqlite3StrAccumFinish(&sCheck.errMsg);
drh5eddca62001-06-30 21:53:53 +00007603}
drhb7f91642004-10-31 02:22:47 +00007604#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00007605
drh73509ee2003-04-06 20:44:45 +00007606/*
7607** Return the full pathname of the underlying database file.
drhd0679ed2007-08-28 22:24:34 +00007608**
7609** The pager filename is invariant as long as the pager is
7610** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +00007611*/
danielk1977aef0bf62005-12-30 16:28:01 +00007612const char *sqlite3BtreeGetFilename(Btree *p){
7613 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007614 return sqlite3PagerFilename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00007615}
7616
7617/*
danielk19775865e3d2004-06-14 06:03:57 +00007618** Return the pathname of the journal file for this database. The return
7619** value of this routine is the same regardless of whether the journal file
7620** has been created or not.
drhd0679ed2007-08-28 22:24:34 +00007621**
7622** The pager journal filename is invariant as long as the pager is
7623** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00007624*/
danielk1977aef0bf62005-12-30 16:28:01 +00007625const char *sqlite3BtreeGetJournalname(Btree *p){
7626 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007627 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00007628}
7629
danielk19771d850a72004-05-31 08:26:49 +00007630/*
7631** Return non-zero if a transaction is active.
7632*/
danielk1977aef0bf62005-12-30 16:28:01 +00007633int sqlite3BtreeIsInTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00007634 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00007635 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00007636}
7637
7638/*
danielk19772372c2b2006-06-27 16:34:56 +00007639** Return non-zero if a read (or write) transaction is active.
7640*/
7641int sqlite3BtreeIsInReadTrans(Btree *p){
drh64022502009-01-09 14:11:04 +00007642 assert( p );
drhe5fe6902007-12-07 18:55:28 +00007643 assert( sqlite3_mutex_held(p->db->mutex) );
drh64022502009-01-09 14:11:04 +00007644 return p->inTrans!=TRANS_NONE;
danielk19772372c2b2006-06-27 16:34:56 +00007645}
7646
danielk197704103022009-02-03 16:51:24 +00007647int sqlite3BtreeIsInBackup(Btree *p){
7648 assert( p );
7649 assert( sqlite3_mutex_held(p->db->mutex) );
7650 return p->nBackup!=0;
7651}
7652
danielk19772372c2b2006-06-27 16:34:56 +00007653/*
danielk1977da184232006-01-05 11:34:32 +00007654** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +00007655** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +00007656** purposes (for example, to store a high-level schema associated with
7657** the shared-btree). The btree layer manages reference counting issues.
7658**
7659** The first time this is called on a shared-btree, nBytes bytes of memory
7660** are allocated, zeroed, and returned to the caller. For each subsequent
7661** call the nBytes parameter is ignored and a pointer to the same blob
7662** of memory returned.
7663**
danielk1977171bfed2008-06-23 09:50:50 +00007664** If the nBytes parameter is 0 and the blob of memory has not yet been
7665** allocated, a null pointer is returned. If the blob has already been
7666** allocated, it is returned as normal.
7667**
danielk1977da184232006-01-05 11:34:32 +00007668** Just before the shared-btree is closed, the function passed as the
7669** xFree argument when the memory allocation was made is invoked on the
drh17435752007-08-16 04:30:38 +00007670** blob of allocated memory. This function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +00007671** on the memory, the btree layer does that.
7672*/
7673void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
7674 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +00007675 sqlite3BtreeEnter(p);
danielk1977171bfed2008-06-23 09:50:50 +00007676 if( !pBt->pSchema && nBytes ){
drh17435752007-08-16 04:30:38 +00007677 pBt->pSchema = sqlite3MallocZero(nBytes);
danielk1977da184232006-01-05 11:34:32 +00007678 pBt->xFreeSchema = xFree;
7679 }
drh27641702007-08-22 02:56:42 +00007680 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00007681 return pBt->pSchema;
7682}
7683
danielk1977c87d34d2006-01-06 13:00:28 +00007684/*
danielk1977404ca072009-03-16 13:19:36 +00007685** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
7686** btree as the argument handle holds an exclusive lock on the
7687** sqlite_master table. Otherwise SQLITE_OK.
danielk1977c87d34d2006-01-06 13:00:28 +00007688*/
7689int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +00007690 int rc;
drhe5fe6902007-12-07 18:55:28 +00007691 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +00007692 sqlite3BtreeEnter(p);
danielk1977404ca072009-03-16 13:19:36 +00007693 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
7694 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
drh27641702007-08-22 02:56:42 +00007695 sqlite3BtreeLeave(p);
7696 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +00007697}
7698
drha154dcd2006-03-22 22:10:07 +00007699
7700#ifndef SQLITE_OMIT_SHARED_CACHE
7701/*
7702** Obtain a lock on the table whose root page is iTab. The
7703** lock is a write lock if isWritelock is true or a read lock
7704** if it is false.
7705*/
danielk1977c00da102006-01-07 13:21:04 +00007706int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00007707 int rc = SQLITE_OK;
danielk1977602b4662009-07-02 07:47:33 +00007708 assert( p->inTrans!=TRANS_NONE );
drh6a9ad3d2008-04-02 16:29:30 +00007709 if( p->sharable ){
7710 u8 lockType = READ_LOCK + isWriteLock;
7711 assert( READ_LOCK+1==WRITE_LOCK );
7712 assert( isWriteLock==0 || isWriteLock==1 );
danielk1977602b4662009-07-02 07:47:33 +00007713
drh6a9ad3d2008-04-02 16:29:30 +00007714 sqlite3BtreeEnter(p);
drhc25eabe2009-02-24 18:57:31 +00007715 rc = querySharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00007716 if( rc==SQLITE_OK ){
drhc25eabe2009-02-24 18:57:31 +00007717 rc = setSharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00007718 }
7719 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +00007720 }
7721 return rc;
7722}
drha154dcd2006-03-22 22:10:07 +00007723#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00007724
danielk1977b4e9af92007-05-01 17:49:49 +00007725#ifndef SQLITE_OMIT_INCRBLOB
7726/*
7727** Argument pCsr must be a cursor opened for writing on an
7728** INTKEY table currently pointing at a valid table entry.
7729** This function modifies the data stored as part of that entry.
7730** Only the data content may only be modified, it is not possible
7731** to change the length of the data stored.
7732*/
danielk1977dcbb5d32007-05-04 18:36:44 +00007733int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
drh1fee73e2007-08-29 04:00:57 +00007734 assert( cursorHoldsMutex(pCsr) );
drhe5fe6902007-12-07 18:55:28 +00007735 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
danielk197796d48e92009-06-29 06:00:37 +00007736 assert( pCsr->isIncrblobHandle );
danielk19773588ceb2008-06-10 17:30:26 +00007737
drha3460582008-07-11 21:02:53 +00007738 restoreCursorPosition(pCsr);
danielk19773588ceb2008-06-10 17:30:26 +00007739 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
7740 if( pCsr->eState!=CURSOR_VALID ){
7741 return SQLITE_ABORT;
danielk1977dcbb5d32007-05-04 18:36:44 +00007742 }
7743
danielk1977d04417962007-05-02 13:16:30 +00007744 /* Check some preconditions:
danielk1977dcbb5d32007-05-04 18:36:44 +00007745 ** (a) the cursor is open for writing,
7746 ** (b) there is no read-lock on the table being modified and
7747 ** (c) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00007748 */
danielk1977d04417962007-05-02 13:16:30 +00007749 if( !pCsr->wrFlag ){
danielk1977dcbb5d32007-05-04 18:36:44 +00007750 return SQLITE_READONLY;
danielk1977d04417962007-05-02 13:16:30 +00007751 }
danielk197796d48e92009-06-29 06:00:37 +00007752 assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
7753 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
7754 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
7755
danielk197771d5d2c2008-09-29 11:49:47 +00007756 if( pCsr->eState==CURSOR_INVALID || !pCsr->apPage[pCsr->iPage]->intKey ){
danielk1977d04417962007-05-02 13:16:30 +00007757 return SQLITE_ERROR;
danielk1977b4e9af92007-05-01 17:49:49 +00007758 }
7759
danielk19779f8d6402007-05-02 17:48:45 +00007760 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 0, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00007761}
danielk19772dec9702007-05-02 16:48:37 +00007762
7763/*
7764** Set a flag on this cursor to cache the locations of pages from the
danielk1977da107192007-05-04 08:32:13 +00007765** overflow list for the current row. This is used by cursors opened
7766** for incremental blob IO only.
7767**
7768** This function sets a flag only. The actual page location cache
7769** (stored in BtCursor.aOverflow[]) is allocated and used by function
7770** accessPayload() (the worker function for sqlite3BtreeData() and
7771** sqlite3BtreePutData()).
danielk19772dec9702007-05-02 16:48:37 +00007772*/
7773void sqlite3BtreeCacheOverflow(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00007774 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00007775 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00007776 assert(!pCur->isIncrblobHandle);
danielk19772dec9702007-05-02 16:48:37 +00007777 assert(!pCur->aOverflow);
danielk1977dcbb5d32007-05-04 18:36:44 +00007778 pCur->isIncrblobHandle = 1;
danielk19772dec9702007-05-02 16:48:37 +00007779}
danielk1977b4e9af92007-05-01 17:49:49 +00007780#endif