blob: 103a1f3230f1c9b9ad74468ae35911a1530287aa [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*************************************************************************
drh8b2f49b2001-06-08 00:21:52 +000012** This file implements a external (disk-based) database using BTrees.
drha3152892007-05-05 11:48:52 +000013** See the header comment on "btreeInt.h" for additional information.
14** Including a description of file format and an overview of operation.
drha059ad02001-04-17 20:09:11 +000015*/
drha3152892007-05-05 11:48:52 +000016#include "btreeInt.h"
paulb95a8862003-04-01 21:16:41 +000017
drh8c42ca92001-06-22 19:15:00 +000018/*
drha3152892007-05-05 11:48:52 +000019** The header string that appears at the beginning of every
20** SQLite database.
drh556b2a22005-06-14 16:04:05 +000021*/
drh556b2a22005-06-14 16:04:05 +000022static const char zMagicHeader[] = SQLITE_FILE_HEADER;
drh08ed44e2001-04-29 23:32:55 +000023
drh8c42ca92001-06-22 19:15:00 +000024/*
drha3152892007-05-05 11:48:52 +000025** Set this global variable to 1 to enable tracing using the TRACE
26** macro.
drh615ae552005-01-16 23:21:00 +000027*/
drhe8f52c52008-07-12 14:52:20 +000028#if 0
danielk1977a50d9aa2009-06-08 14:49:45 +000029int sqlite3BtreeTrace=1; /* True to enable tracing */
drhe8f52c52008-07-12 14:52:20 +000030# define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
31#else
32# define TRACE(X)
drh615ae552005-01-16 23:21:00 +000033#endif
drh615ae552005-01-16 23:21:00 +000034
drh5d433ce2010-08-14 16:02:52 +000035/*
36** Extract a 2-byte big-endian integer from an array of unsigned bytes.
37** But if the value is zero, make it 65536.
38**
39** This routine is used to extract the "offset to cell content area" value
40** from the header of a btree page. If the page size is 65536 and the page
41** is empty, the offset should be 65536, but the 2-byte value stores zero.
42** This routine makes the necessary adjustment to 65536.
43*/
44#define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
drh86f8c192007-08-22 00:39:19 +000045
drhe53831d2007-08-17 01:14:38 +000046#ifndef SQLITE_OMIT_SHARED_CACHE
47/*
danielk1977502b4e02008-09-02 14:07:24 +000048** A list of BtShared objects that are eligible for participation
49** in shared cache. This variable has file scope during normal builds,
50** but the test harness needs to access it so we make it global for
51** test builds.
drh7555d8e2009-03-20 13:15:30 +000052**
53** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
drhe53831d2007-08-17 01:14:38 +000054*/
55#ifdef SQLITE_TEST
drh78f82d12008-09-02 00:52:52 +000056BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
drhe53831d2007-08-17 01:14:38 +000057#else
drh78f82d12008-09-02 00:52:52 +000058static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
drhe53831d2007-08-17 01:14:38 +000059#endif
drhe53831d2007-08-17 01:14:38 +000060#endif /* SQLITE_OMIT_SHARED_CACHE */
61
62#ifndef SQLITE_OMIT_SHARED_CACHE
63/*
64** Enable or disable the shared pager and schema features.
65**
66** This routine has no effect on existing database connections.
67** The shared cache setting effects only future calls to
68** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
69*/
70int sqlite3_enable_shared_cache(int enable){
danielk1977502b4e02008-09-02 14:07:24 +000071 sqlite3GlobalConfig.sharedCacheEnabled = enable;
drhe53831d2007-08-17 01:14:38 +000072 return SQLITE_OK;
73}
74#endif
75
drhd677b3d2007-08-20 22:48:41 +000076
danielk1977aef0bf62005-12-30 16:28:01 +000077
78#ifdef SQLITE_OMIT_SHARED_CACHE
79 /*
drhc25eabe2009-02-24 18:57:31 +000080 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
81 ** and clearAllSharedCacheTableLocks()
danielk1977aef0bf62005-12-30 16:28:01 +000082 ** manipulate entries in the BtShared.pLock linked list used to store
83 ** shared-cache table level locks. If the library is compiled with the
84 ** shared-cache feature disabled, then there is only ever one user
danielk1977da184232006-01-05 11:34:32 +000085 ** of each BtShared structure and so this locking is not necessary.
86 ** So define the lock related functions as no-ops.
danielk1977aef0bf62005-12-30 16:28:01 +000087 */
drhc25eabe2009-02-24 18:57:31 +000088 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
89 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
90 #define clearAllSharedCacheTableLocks(a)
danielk197794b30732009-07-02 17:21:57 +000091 #define downgradeAllSharedCacheTableLocks(a)
danielk197796d48e92009-06-29 06:00:37 +000092 #define hasSharedCacheTableLock(a,b,c,d) 1
93 #define hasReadConflicts(a, b) 0
drhe53831d2007-08-17 01:14:38 +000094#endif
danielk1977aef0bf62005-12-30 16:28:01 +000095
drhe53831d2007-08-17 01:14:38 +000096#ifndef SQLITE_OMIT_SHARED_CACHE
danielk197796d48e92009-06-29 06:00:37 +000097
98#ifdef SQLITE_DEBUG
99/*
drh0ee3dbe2009-10-16 15:05:18 +0000100**** This function is only used as part of an assert() statement. ***
101**
102** Check to see if pBtree holds the required locks to read or write to the
103** table with root page iRoot. Return 1 if it does and 0 if not.
104**
105** For example, when writing to a table with root-page iRoot via
danielk197796d48e92009-06-29 06:00:37 +0000106** Btree connection pBtree:
107**
108** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
109**
drh0ee3dbe2009-10-16 15:05:18 +0000110** When writing to an index that resides in a sharable database, the
danielk197796d48e92009-06-29 06:00:37 +0000111** caller should have first obtained a lock specifying the root page of
drh0ee3dbe2009-10-16 15:05:18 +0000112** the corresponding table. This makes things a bit more complicated,
113** as this module treats each table as a separate structure. To determine
114** the table corresponding to the index being written, this
danielk197796d48e92009-06-29 06:00:37 +0000115** function has to search through the database schema.
116**
drh0ee3dbe2009-10-16 15:05:18 +0000117** Instead of a lock on the table/index rooted at page iRoot, the caller may
danielk197796d48e92009-06-29 06:00:37 +0000118** hold a write-lock on the schema table (root page 1). This is also
119** acceptable.
120*/
121static int hasSharedCacheTableLock(
122 Btree *pBtree, /* Handle that must hold lock */
123 Pgno iRoot, /* Root page of b-tree */
124 int isIndex, /* True if iRoot is the root of an index b-tree */
125 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
126){
127 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
128 Pgno iTab = 0;
129 BtLock *pLock;
130
drh0ee3dbe2009-10-16 15:05:18 +0000131 /* If this database is not shareable, or if the client is reading
danielk197796d48e92009-06-29 06:00:37 +0000132 ** and has the read-uncommitted flag set, then no lock is required.
drh0ee3dbe2009-10-16 15:05:18 +0000133 ** Return true immediately.
134 */
danielk197796d48e92009-06-29 06:00:37 +0000135 if( (pBtree->sharable==0)
136 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
danielk197796d48e92009-06-29 06:00:37 +0000137 ){
138 return 1;
139 }
140
drh0ee3dbe2009-10-16 15:05:18 +0000141 /* If the client is reading or writing an index and the schema is
142 ** not loaded, then it is too difficult to actually check to see if
143 ** the correct locks are held. So do not bother - just return true.
144 ** This case does not come up very often anyhow.
145 */
146 if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
147 return 1;
148 }
149
danielk197796d48e92009-06-29 06:00:37 +0000150 /* Figure out the root-page that the lock should be held on. For table
151 ** b-trees, this is just the root page of the b-tree being read or
152 ** written. For index b-trees, it is the root page of the associated
153 ** table. */
154 if( isIndex ){
155 HashElem *p;
156 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
157 Index *pIdx = (Index *)sqliteHashData(p);
shane5eff7cf2009-08-10 03:57:58 +0000158 if( pIdx->tnum==(int)iRoot ){
159 iTab = pIdx->pTable->tnum;
danielk197796d48e92009-06-29 06:00:37 +0000160 }
161 }
162 }else{
163 iTab = iRoot;
164 }
165
166 /* Search for the required lock. Either a write-lock on root-page iTab, a
167 ** write-lock on the schema table, or (if the client is reading) a
168 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
169 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
170 if( pLock->pBtree==pBtree
171 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
172 && pLock->eLock>=eLockType
173 ){
174 return 1;
175 }
176 }
177
178 /* Failed to find the required lock. */
179 return 0;
180}
drh0ee3dbe2009-10-16 15:05:18 +0000181#endif /* SQLITE_DEBUG */
danielk197796d48e92009-06-29 06:00:37 +0000182
drh0ee3dbe2009-10-16 15:05:18 +0000183#ifdef SQLITE_DEBUG
danielk197796d48e92009-06-29 06:00:37 +0000184/*
drh0ee3dbe2009-10-16 15:05:18 +0000185**** This function may be used as part of assert() statements only. ****
danielk197796d48e92009-06-29 06:00:37 +0000186**
drh0ee3dbe2009-10-16 15:05:18 +0000187** Return true if it would be illegal for pBtree to write into the
188** table or index rooted at iRoot because other shared connections are
189** simultaneously reading that same table or index.
190**
191** It is illegal for pBtree to write if some other Btree object that
192** shares the same BtShared object is currently reading or writing
193** the iRoot table. Except, if the other Btree object has the
194** read-uncommitted flag set, then it is OK for the other object to
195** have a read cursor.
196**
197** For example, before writing to any part of the table or index
198** rooted at page iRoot, one should call:
danielk197796d48e92009-06-29 06:00:37 +0000199**
200** assert( !hasReadConflicts(pBtree, iRoot) );
201*/
202static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
203 BtCursor *p;
204 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
205 if( p->pgnoRoot==iRoot
206 && p->pBtree!=pBtree
207 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
208 ){
209 return 1;
210 }
211 }
212 return 0;
213}
214#endif /* #ifdef SQLITE_DEBUG */
215
danielk1977da184232006-01-05 11:34:32 +0000216/*
drh0ee3dbe2009-10-16 15:05:18 +0000217** Query to see if Btree handle p may obtain a lock of type eLock
danielk1977aef0bf62005-12-30 16:28:01 +0000218** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
drhc25eabe2009-02-24 18:57:31 +0000219** SQLITE_OK if the lock may be obtained (by calling
220** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
danielk1977aef0bf62005-12-30 16:28:01 +0000221*/
drhc25eabe2009-02-24 18:57:31 +0000222static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
danielk1977aef0bf62005-12-30 16:28:01 +0000223 BtShared *pBt = p->pBt;
224 BtLock *pIter;
225
drh1fee73e2007-08-29 04:00:57 +0000226 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000227 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
228 assert( p->db!=0 );
danielk1977e0d9e6f2009-07-03 16:25:06 +0000229 assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
drhd677b3d2007-08-20 22:48:41 +0000230
danielk19775b413d72009-04-01 09:41:54 +0000231 /* If requesting a write-lock, then the Btree must have an open write
232 ** transaction on this file. And, obviously, for this to be so there
233 ** must be an open write transaction on the file itself.
234 */
235 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
236 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
237
drh0ee3dbe2009-10-16 15:05:18 +0000238 /* This routine is a no-op if the shared-cache is not enabled */
drhe53831d2007-08-17 01:14:38 +0000239 if( !p->sharable ){
danielk1977da184232006-01-05 11:34:32 +0000240 return SQLITE_OK;
241 }
242
danielk1977641b0f42007-12-21 04:47:25 +0000243 /* If some other connection is holding an exclusive lock, the
244 ** requested lock may not be obtained.
245 */
danielk1977404ca072009-03-16 13:19:36 +0000246 if( pBt->pWriter!=p && pBt->isExclusive ){
247 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
248 return SQLITE_LOCKED_SHAREDCACHE;
danielk1977641b0f42007-12-21 04:47:25 +0000249 }
250
danielk1977e0d9e6f2009-07-03 16:25:06 +0000251 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
252 /* The condition (pIter->eLock!=eLock) in the following if(...)
253 ** statement is a simplification of:
254 **
255 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
256 **
257 ** since we know that if eLock==WRITE_LOCK, then no other connection
258 ** may hold a WRITE_LOCK on any table in this file (since there can
259 ** only be a single writer).
260 */
261 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
262 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
263 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
264 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
265 if( eLock==WRITE_LOCK ){
266 assert( p==pBt->pWriter );
267 pBt->isPending = 1;
danielk1977da184232006-01-05 11:34:32 +0000268 }
danielk1977e0d9e6f2009-07-03 16:25:06 +0000269 return SQLITE_LOCKED_SHAREDCACHE;
danielk1977aef0bf62005-12-30 16:28:01 +0000270 }
271 }
272 return SQLITE_OK;
273}
drhe53831d2007-08-17 01:14:38 +0000274#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000275
drhe53831d2007-08-17 01:14:38 +0000276#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000277/*
278** Add a lock on the table with root-page iTable to the shared-btree used
279** by Btree handle p. Parameter eLock must be either READ_LOCK or
280** WRITE_LOCK.
281**
danielk19779d104862009-07-09 08:27:14 +0000282** This function assumes the following:
283**
drh0ee3dbe2009-10-16 15:05:18 +0000284** (a) The specified Btree object p is connected to a sharable
285** database (one with the BtShared.sharable flag set), and
danielk19779d104862009-07-09 08:27:14 +0000286**
drh0ee3dbe2009-10-16 15:05:18 +0000287** (b) No other Btree objects hold a lock that conflicts
danielk19779d104862009-07-09 08:27:14 +0000288** with the requested lock (i.e. querySharedCacheTableLock() has
289** already been called and returned SQLITE_OK).
290**
291** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
292** is returned if a malloc attempt fails.
danielk1977aef0bf62005-12-30 16:28:01 +0000293*/
drhc25eabe2009-02-24 18:57:31 +0000294static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
danielk1977aef0bf62005-12-30 16:28:01 +0000295 BtShared *pBt = p->pBt;
296 BtLock *pLock = 0;
297 BtLock *pIter;
298
drh1fee73e2007-08-29 04:00:57 +0000299 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000300 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
301 assert( p->db!=0 );
drhd677b3d2007-08-20 22:48:41 +0000302
danielk1977e0d9e6f2009-07-03 16:25:06 +0000303 /* A connection with the read-uncommitted flag set will never try to
304 ** obtain a read-lock using this function. The only read-lock obtained
305 ** by a connection in read-uncommitted mode is on the sqlite_master
306 ** table, and that lock is obtained in BtreeBeginTrans(). */
307 assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
308
danielk19779d104862009-07-09 08:27:14 +0000309 /* This function should only be called on a sharable b-tree after it
310 ** has been determined that no other b-tree holds a conflicting lock. */
311 assert( p->sharable );
drhc25eabe2009-02-24 18:57:31 +0000312 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
danielk1977aef0bf62005-12-30 16:28:01 +0000313
314 /* First search the list for an existing lock on this table. */
315 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
316 if( pIter->iTable==iTable && pIter->pBtree==p ){
317 pLock = pIter;
318 break;
319 }
320 }
321
322 /* If the above search did not find a BtLock struct associating Btree p
323 ** with table iTable, allocate one and link it into the list.
324 */
325 if( !pLock ){
drh17435752007-08-16 04:30:38 +0000326 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
danielk1977aef0bf62005-12-30 16:28:01 +0000327 if( !pLock ){
328 return SQLITE_NOMEM;
329 }
330 pLock->iTable = iTable;
331 pLock->pBtree = p;
332 pLock->pNext = pBt->pLock;
333 pBt->pLock = pLock;
334 }
335
336 /* Set the BtLock.eLock variable to the maximum of the current lock
337 ** and the requested lock. This means if a write-lock was already held
338 ** and a read-lock requested, we don't incorrectly downgrade the lock.
339 */
340 assert( WRITE_LOCK>READ_LOCK );
danielk19775118b912005-12-30 16:31:53 +0000341 if( eLock>pLock->eLock ){
342 pLock->eLock = eLock;
343 }
danielk1977aef0bf62005-12-30 16:28:01 +0000344
345 return SQLITE_OK;
346}
drhe53831d2007-08-17 01:14:38 +0000347#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000348
drhe53831d2007-08-17 01:14:38 +0000349#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000350/*
drhc25eabe2009-02-24 18:57:31 +0000351** Release all the table locks (locks obtained via calls to
drh0ee3dbe2009-10-16 15:05:18 +0000352** the setSharedCacheTableLock() procedure) held by Btree object p.
danielk1977fa542f12009-04-02 18:28:08 +0000353**
drh0ee3dbe2009-10-16 15:05:18 +0000354** This function assumes that Btree p has an open read or write
danielk1977fa542f12009-04-02 18:28:08 +0000355** transaction. If it does not, then the BtShared.isPending variable
356** may be incorrectly cleared.
danielk1977aef0bf62005-12-30 16:28:01 +0000357*/
drhc25eabe2009-02-24 18:57:31 +0000358static void clearAllSharedCacheTableLocks(Btree *p){
danielk1977641b0f42007-12-21 04:47:25 +0000359 BtShared *pBt = p->pBt;
360 BtLock **ppIter = &pBt->pLock;
danielk1977da184232006-01-05 11:34:32 +0000361
drh1fee73e2007-08-29 04:00:57 +0000362 assert( sqlite3BtreeHoldsMutex(p) );
drhe53831d2007-08-17 01:14:38 +0000363 assert( p->sharable || 0==*ppIter );
danielk1977fa542f12009-04-02 18:28:08 +0000364 assert( p->inTrans>0 );
danielk1977da184232006-01-05 11:34:32 +0000365
danielk1977aef0bf62005-12-30 16:28:01 +0000366 while( *ppIter ){
367 BtLock *pLock = *ppIter;
danielk1977404ca072009-03-16 13:19:36 +0000368 assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
danielk1977fa542f12009-04-02 18:28:08 +0000369 assert( pLock->pBtree->inTrans>=pLock->eLock );
danielk1977aef0bf62005-12-30 16:28:01 +0000370 if( pLock->pBtree==p ){
371 *ppIter = pLock->pNext;
danielk1977602b4662009-07-02 07:47:33 +0000372 assert( pLock->iTable!=1 || pLock==&p->lock );
373 if( pLock->iTable!=1 ){
374 sqlite3_free(pLock);
375 }
danielk1977aef0bf62005-12-30 16:28:01 +0000376 }else{
377 ppIter = &pLock->pNext;
378 }
379 }
danielk1977641b0f42007-12-21 04:47:25 +0000380
danielk1977404ca072009-03-16 13:19:36 +0000381 assert( pBt->isPending==0 || pBt->pWriter );
382 if( pBt->pWriter==p ){
383 pBt->pWriter = 0;
384 pBt->isExclusive = 0;
385 pBt->isPending = 0;
386 }else if( pBt->nTransaction==2 ){
drh0ee3dbe2009-10-16 15:05:18 +0000387 /* This function is called when Btree p is concluding its
danielk1977404ca072009-03-16 13:19:36 +0000388 ** transaction. If there currently exists a writer, and p is not
389 ** that writer, then the number of locks held by connections other
390 ** than the writer must be about to drop to zero. In this case
391 ** set the isPending flag to 0.
392 **
393 ** If there is not currently a writer, then BtShared.isPending must
394 ** be zero already. So this next line is harmless in that case.
395 */
396 pBt->isPending = 0;
danielk1977641b0f42007-12-21 04:47:25 +0000397 }
danielk1977aef0bf62005-12-30 16:28:01 +0000398}
danielk197794b30732009-07-02 17:21:57 +0000399
danielk1977e0d9e6f2009-07-03 16:25:06 +0000400/*
drh0ee3dbe2009-10-16 15:05:18 +0000401** This function changes all write-locks held by Btree p into read-locks.
danielk1977e0d9e6f2009-07-03 16:25:06 +0000402*/
danielk197794b30732009-07-02 17:21:57 +0000403static void downgradeAllSharedCacheTableLocks(Btree *p){
404 BtShared *pBt = p->pBt;
405 if( pBt->pWriter==p ){
406 BtLock *pLock;
407 pBt->pWriter = 0;
408 pBt->isExclusive = 0;
409 pBt->isPending = 0;
410 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
411 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
412 pLock->eLock = READ_LOCK;
413 }
414 }
415}
416
danielk1977aef0bf62005-12-30 16:28:01 +0000417#endif /* SQLITE_OMIT_SHARED_CACHE */
418
drh980b1a72006-08-16 16:42:48 +0000419static void releasePage(MemPage *pPage); /* Forward reference */
420
drh1fee73e2007-08-29 04:00:57 +0000421/*
drh0ee3dbe2009-10-16 15:05:18 +0000422***** This routine is used inside of assert() only ****
423**
424** Verify that the cursor holds the mutex on its BtShared
drh1fee73e2007-08-29 04:00:57 +0000425*/
drh0ee3dbe2009-10-16 15:05:18 +0000426#ifdef SQLITE_DEBUG
drh1fee73e2007-08-29 04:00:57 +0000427static int cursorHoldsMutex(BtCursor *p){
drhff0587c2007-08-29 17:43:19 +0000428 return sqlite3_mutex_held(p->pBt->mutex);
drh1fee73e2007-08-29 04:00:57 +0000429}
430#endif
431
432
danielk197792d4d7a2007-05-04 12:05:56 +0000433#ifndef SQLITE_OMIT_INCRBLOB
434/*
435** Invalidate the overflow page-list cache for cursor pCur, if any.
436*/
437static void invalidateOverflowCache(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000438 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000439 sqlite3_free(pCur->aOverflow);
danielk197792d4d7a2007-05-04 12:05:56 +0000440 pCur->aOverflow = 0;
441}
442
443/*
444** Invalidate the overflow page-list cache for all cursors opened
445** on the shared btree structure pBt.
446*/
447static void invalidateAllOverflowCache(BtShared *pBt){
448 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000449 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +0000450 for(p=pBt->pCursor; p; p=p->pNext){
451 invalidateOverflowCache(p);
452 }
453}
danielk197796d48e92009-06-29 06:00:37 +0000454
455/*
456** This function is called before modifying the contents of a table
drh0ee3dbe2009-10-16 15:05:18 +0000457** to invalidate any incrblob cursors that are open on the
drheeb844a2009-08-08 18:01:07 +0000458** row or one of the rows being modified.
danielk197796d48e92009-06-29 06:00:37 +0000459**
460** If argument isClearTable is true, then the entire contents of the
461** table is about to be deleted. In this case invalidate all incrblob
462** cursors open on any row within the table with root-page pgnoRoot.
463**
464** Otherwise, if argument isClearTable is false, then the row with
465** rowid iRow is being replaced or deleted. In this case invalidate
drh0ee3dbe2009-10-16 15:05:18 +0000466** only those incrblob cursors open on that specific row.
danielk197796d48e92009-06-29 06:00:37 +0000467*/
468static void invalidateIncrblobCursors(
469 Btree *pBtree, /* The database file to check */
danielk197796d48e92009-06-29 06:00:37 +0000470 i64 iRow, /* The rowid that might be changing */
471 int isClearTable /* True if all rows are being deleted */
472){
473 BtCursor *p;
474 BtShared *pBt = pBtree->pBt;
475 assert( sqlite3BtreeHoldsMutex(pBtree) );
476 for(p=pBt->pCursor; p; p=p->pNext){
477 if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
478 p->eState = CURSOR_INVALID;
479 }
480 }
481}
482
danielk197792d4d7a2007-05-04 12:05:56 +0000483#else
drh0ee3dbe2009-10-16 15:05:18 +0000484 /* Stub functions when INCRBLOB is omitted */
danielk197792d4d7a2007-05-04 12:05:56 +0000485 #define invalidateOverflowCache(x)
486 #define invalidateAllOverflowCache(x)
drheeb844a2009-08-08 18:01:07 +0000487 #define invalidateIncrblobCursors(x,y,z)
drh0ee3dbe2009-10-16 15:05:18 +0000488#endif /* SQLITE_OMIT_INCRBLOB */
danielk197792d4d7a2007-05-04 12:05:56 +0000489
drh980b1a72006-08-16 16:42:48 +0000490/*
danielk1977bea2a942009-01-20 17:06:27 +0000491** Set bit pgno of the BtShared.pHasContent bitvec. This is called
492** when a page that previously contained data becomes a free-list leaf
493** page.
494**
495** The BtShared.pHasContent bitvec exists to work around an obscure
496** bug caused by the interaction of two useful IO optimizations surrounding
497** free-list leaf pages:
498**
499** 1) When all data is deleted from a page and the page becomes
500** a free-list leaf page, the page is not written to the database
501** (as free-list leaf pages contain no meaningful data). Sometimes
502** such a page is not even journalled (as it will not be modified,
503** why bother journalling it?).
504**
505** 2) When a free-list leaf page is reused, its content is not read
506** from the database or written to the journal file (why should it
507** be, if it is not at all meaningful?).
508**
509** By themselves, these optimizations work fine and provide a handy
510** performance boost to bulk delete or insert operations. However, if
511** a page is moved to the free-list and then reused within the same
512** transaction, a problem comes up. If the page is not journalled when
513** it is moved to the free-list and it is also not journalled when it
514** is extracted from the free-list and reused, then the original data
515** may be lost. In the event of a rollback, it may not be possible
516** to restore the database to its original configuration.
517**
518** The solution is the BtShared.pHasContent bitvec. Whenever a page is
519** moved to become a free-list leaf page, the corresponding bit is
520** set in the bitvec. Whenever a leaf page is extracted from the free-list,
drh0ee3dbe2009-10-16 15:05:18 +0000521** optimization 2 above is omitted if the corresponding bit is already
danielk1977bea2a942009-01-20 17:06:27 +0000522** set in BtShared.pHasContent. The contents of the bitvec are cleared
523** at the end of every transaction.
524*/
525static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
526 int rc = SQLITE_OK;
527 if( !pBt->pHasContent ){
drhdd3cd972010-03-27 17:12:36 +0000528 assert( pgno<=pBt->nPage );
529 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
drh4c301aa2009-07-15 17:25:45 +0000530 if( !pBt->pHasContent ){
531 rc = SQLITE_NOMEM;
danielk1977bea2a942009-01-20 17:06:27 +0000532 }
533 }
534 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
535 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
536 }
537 return rc;
538}
539
540/*
541** Query the BtShared.pHasContent vector.
542**
543** This function is called when a free-list leaf page is removed from the
544** free-list for reuse. It returns false if it is safe to retrieve the
545** page from the pager layer with the 'no-content' flag set. True otherwise.
546*/
547static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
548 Bitvec *p = pBt->pHasContent;
549 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
550}
551
552/*
553** Clear (destroy) the BtShared.pHasContent bitvec. This should be
554** invoked at the conclusion of each write-transaction.
555*/
556static void btreeClearHasContent(BtShared *pBt){
557 sqlite3BitvecDestroy(pBt->pHasContent);
558 pBt->pHasContent = 0;
559}
560
561/*
drh980b1a72006-08-16 16:42:48 +0000562** Save the current cursor position in the variables BtCursor.nKey
563** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
drhea8ffdf2009-07-22 00:35:23 +0000564**
565** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
566** prior to calling this routine.
drh980b1a72006-08-16 16:42:48 +0000567*/
568static int saveCursorPosition(BtCursor *pCur){
569 int rc;
570
571 assert( CURSOR_VALID==pCur->eState );
572 assert( 0==pCur->pKey );
drh1fee73e2007-08-29 04:00:57 +0000573 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000574
575 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
drhea8ffdf2009-07-22 00:35:23 +0000576 assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
drh980b1a72006-08-16 16:42:48 +0000577
578 /* If this is an intKey table, then the above call to BtreeKeySize()
579 ** stores the integer key in pCur->nKey. In this case this value is
580 ** all that is required. Otherwise, if pCur is not open on an intKey
581 ** table, then malloc space for and store the pCur->nKey bytes of key
582 ** data.
583 */
drh4c301aa2009-07-15 17:25:45 +0000584 if( 0==pCur->apPage[0]->intKey ){
drhf49661a2008-12-10 16:45:50 +0000585 void *pKey = sqlite3Malloc( (int)pCur->nKey );
drh980b1a72006-08-16 16:42:48 +0000586 if( pKey ){
drhf49661a2008-12-10 16:45:50 +0000587 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
drh980b1a72006-08-16 16:42:48 +0000588 if( rc==SQLITE_OK ){
589 pCur->pKey = pKey;
590 }else{
drh17435752007-08-16 04:30:38 +0000591 sqlite3_free(pKey);
drh980b1a72006-08-16 16:42:48 +0000592 }
593 }else{
594 rc = SQLITE_NOMEM;
595 }
596 }
danielk197771d5d2c2008-09-29 11:49:47 +0000597 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
drh980b1a72006-08-16 16:42:48 +0000598
599 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +0000600 int i;
601 for(i=0; i<=pCur->iPage; i++){
602 releasePage(pCur->apPage[i]);
603 pCur->apPage[i] = 0;
604 }
605 pCur->iPage = -1;
drh980b1a72006-08-16 16:42:48 +0000606 pCur->eState = CURSOR_REQUIRESEEK;
607 }
608
danielk197792d4d7a2007-05-04 12:05:56 +0000609 invalidateOverflowCache(pCur);
drh980b1a72006-08-16 16:42:48 +0000610 return rc;
611}
612
613/*
drh0ee3dbe2009-10-16 15:05:18 +0000614** Save the positions of all cursors (except pExcept) that are open on
615** the table with root-page iRoot. Usually, this is called just before cursor
drh980b1a72006-08-16 16:42:48 +0000616** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
617*/
618static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
619 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000620 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +0000621 assert( pExcept==0 || pExcept->pBt==pBt );
drh980b1a72006-08-16 16:42:48 +0000622 for(p=pBt->pCursor; p; p=p->pNext){
623 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
624 p->eState==CURSOR_VALID ){
625 int rc = saveCursorPosition(p);
626 if( SQLITE_OK!=rc ){
627 return rc;
628 }
629 }
630 }
631 return SQLITE_OK;
632}
633
634/*
drhbf700f32007-03-31 02:36:44 +0000635** Clear the current cursor position.
636*/
danielk1977be51a652008-10-08 17:58:48 +0000637void sqlite3BtreeClearCursor(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000638 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000639 sqlite3_free(pCur->pKey);
drhbf700f32007-03-31 02:36:44 +0000640 pCur->pKey = 0;
641 pCur->eState = CURSOR_INVALID;
642}
643
644/*
danielk19773509a652009-07-06 18:56:13 +0000645** In this version of BtreeMoveto, pKey is a packed index record
646** such as is generated by the OP_MakeRecord opcode. Unpack the
647** record and then call BtreeMovetoUnpacked() to do the work.
648*/
649static int btreeMoveto(
650 BtCursor *pCur, /* Cursor open on the btree to be searched */
651 const void *pKey, /* Packed key if the btree is an index */
652 i64 nKey, /* Integer key for tables. Size of pKey for indices */
653 int bias, /* Bias search to the high end */
654 int *pRes /* Write search results here */
655){
656 int rc; /* Status code */
657 UnpackedRecord *pIdxKey; /* Unpacked index key */
658 char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
659
660 if( pKey ){
661 assert( nKey==(i64)(int)nKey );
662 pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
663 aSpace, sizeof(aSpace));
664 if( pIdxKey==0 ) return SQLITE_NOMEM;
665 }else{
666 pIdxKey = 0;
667 }
668 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
669 if( pKey ){
670 sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
671 }
672 return rc;
673}
674
675/*
drh980b1a72006-08-16 16:42:48 +0000676** Restore the cursor to the position it was in (or as close to as possible)
677** when saveCursorPosition() was called. Note that this call deletes the
678** saved position info stored by saveCursorPosition(), so there can be
drha3460582008-07-11 21:02:53 +0000679** at most one effective restoreCursorPosition() call after each
drh980b1a72006-08-16 16:42:48 +0000680** saveCursorPosition().
drh980b1a72006-08-16 16:42:48 +0000681*/
danielk197730548662009-07-09 05:07:37 +0000682static int btreeRestoreCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +0000683 int rc;
drh1fee73e2007-08-29 04:00:57 +0000684 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +0000685 assert( pCur->eState>=CURSOR_REQUIRESEEK );
686 if( pCur->eState==CURSOR_FAULT ){
drh4c301aa2009-07-15 17:25:45 +0000687 return pCur->skipNext;
drhfb982642007-08-30 01:19:59 +0000688 }
drh980b1a72006-08-16 16:42:48 +0000689 pCur->eState = CURSOR_INVALID;
drh4c301aa2009-07-15 17:25:45 +0000690 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
drh980b1a72006-08-16 16:42:48 +0000691 if( rc==SQLITE_OK ){
drh17435752007-08-16 04:30:38 +0000692 sqlite3_free(pCur->pKey);
drh980b1a72006-08-16 16:42:48 +0000693 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +0000694 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drh980b1a72006-08-16 16:42:48 +0000695 }
696 return rc;
697}
698
drha3460582008-07-11 21:02:53 +0000699#define restoreCursorPosition(p) \
drhfb982642007-08-30 01:19:59 +0000700 (p->eState>=CURSOR_REQUIRESEEK ? \
danielk197730548662009-07-09 05:07:37 +0000701 btreeRestoreCursorPosition(p) : \
drh16a9b832007-05-05 18:39:25 +0000702 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +0000703
drha3460582008-07-11 21:02:53 +0000704/*
705** Determine whether or not a cursor has moved from the position it
drhdfe88ec2008-11-03 20:55:06 +0000706** was last placed at. Cursors can move when the row they are pointing
drha3460582008-07-11 21:02:53 +0000707** at is deleted out from under them.
708**
709** This routine returns an error code if something goes wrong. The
710** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
711*/
712int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
713 int rc;
714
715 rc = restoreCursorPosition(pCur);
716 if( rc ){
717 *pHasMoved = 1;
718 return rc;
719 }
drh4c301aa2009-07-15 17:25:45 +0000720 if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
drha3460582008-07-11 21:02:53 +0000721 *pHasMoved = 1;
722 }else{
723 *pHasMoved = 0;
724 }
725 return SQLITE_OK;
726}
727
danielk1977599fcba2004-11-08 07:13:13 +0000728#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000729/*
drha3152892007-05-05 11:48:52 +0000730** Given a page number of a regular database page, return the page
731** number for the pointer-map page that contains the entry for the
732** input page number.
drh5f77b2e2010-08-21 15:09:37 +0000733**
734** Return 0 (not a valid page) for pgno==1 since there is
735** no pointer map associated with page 1. The integrity_check logic
736** requires that ptrmapPageno(*,1)!=1.
danielk1977afcdd022004-10-31 16:25:42 +0000737*/
danielk1977266664d2006-02-10 08:24:21 +0000738static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
danielk197789d40042008-11-17 14:20:56 +0000739 int nPagesPerMapPage;
740 Pgno iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +0000741 assert( sqlite3_mutex_held(pBt->mutex) );
drh5f77b2e2010-08-21 15:09:37 +0000742 if( pgno<2 ) return 0;
drhd677b3d2007-08-20 22:48:41 +0000743 nPagesPerMapPage = (pBt->usableSize/5)+1;
744 iPtrMap = (pgno-2)/nPagesPerMapPage;
745 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +0000746 if( ret==PENDING_BYTE_PAGE(pBt) ){
747 ret++;
748 }
749 return ret;
750}
danielk1977a19df672004-11-03 11:37:07 +0000751
danielk1977afcdd022004-10-31 16:25:42 +0000752/*
danielk1977afcdd022004-10-31 16:25:42 +0000753** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000754**
755** This routine updates the pointer map entry for page number 'key'
756** so that it maps to type 'eType' and parent page number 'pgno'.
drh98add2e2009-07-20 17:11:49 +0000757**
758** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
759** a no-op. If an error occurs, the appropriate error code is written
760** into *pRC.
danielk1977afcdd022004-10-31 16:25:42 +0000761*/
drh98add2e2009-07-20 17:11:49 +0000762static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
danielk19773b8a05f2007-03-19 17:44:26 +0000763 DbPage *pDbPage; /* The pointer map page */
764 u8 *pPtrmap; /* The pointer map data */
765 Pgno iPtrmap; /* The pointer map page number */
766 int offset; /* Offset in pointer map page */
drh98add2e2009-07-20 17:11:49 +0000767 int rc; /* Return code from subfunctions */
768
769 if( *pRC ) return;
danielk1977afcdd022004-10-31 16:25:42 +0000770
drh1fee73e2007-08-29 04:00:57 +0000771 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977266664d2006-02-10 08:24:21 +0000772 /* The master-journal page number must never be used as a pointer map page */
773 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
774
danielk1977ac11ee62005-01-15 12:45:51 +0000775 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000776 if( key==0 ){
drh98add2e2009-07-20 17:11:49 +0000777 *pRC = SQLITE_CORRUPT_BKPT;
778 return;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000779 }
danielk1977266664d2006-02-10 08:24:21 +0000780 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000781 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977687566d2004-11-02 12:56:41 +0000782 if( rc!=SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +0000783 *pRC = rc;
784 return;
danielk1977afcdd022004-10-31 16:25:42 +0000785 }
danielk19778c666b12008-07-18 09:34:57 +0000786 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drhacfc72b2009-06-05 18:44:15 +0000787 if( offset<0 ){
drh98add2e2009-07-20 17:11:49 +0000788 *pRC = SQLITE_CORRUPT_BKPT;
drh4925a552009-07-07 11:39:58 +0000789 goto ptrmap_exit;
drhacfc72b2009-06-05 18:44:15 +0000790 }
danielk19773b8a05f2007-03-19 17:44:26 +0000791 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000792
drh615ae552005-01-16 23:21:00 +0000793 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
794 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
drh98add2e2009-07-20 17:11:49 +0000795 *pRC= rc = sqlite3PagerWrite(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000796 if( rc==SQLITE_OK ){
797 pPtrmap[offset] = eType;
798 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000799 }
danielk1977afcdd022004-10-31 16:25:42 +0000800 }
801
drh4925a552009-07-07 11:39:58 +0000802ptrmap_exit:
danielk19773b8a05f2007-03-19 17:44:26 +0000803 sqlite3PagerUnref(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000804}
805
806/*
807** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000808**
809** This routine retrieves the pointer map entry for page 'key', writing
810** the type and parent page number to *pEType and *pPgno respectively.
811** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000812*/
danielk1977aef0bf62005-12-30 16:28:01 +0000813static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +0000814 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000815 int iPtrmap; /* Pointer map page index */
816 u8 *pPtrmap; /* Pointer map page data */
817 int offset; /* Offset of entry in pointer map */
818 int rc;
819
drh1fee73e2007-08-29 04:00:57 +0000820 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000821
danielk1977266664d2006-02-10 08:24:21 +0000822 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000823 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000824 if( rc!=0 ){
825 return rc;
826 }
danielk19773b8a05f2007-03-19 17:44:26 +0000827 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000828
danielk19778c666b12008-07-18 09:34:57 +0000829 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drh43617e92006-03-06 20:55:46 +0000830 assert( pEType!=0 );
831 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +0000832 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000833
danielk19773b8a05f2007-03-19 17:44:26 +0000834 sqlite3PagerUnref(pDbPage);
drh49285702005-09-17 15:20:26 +0000835 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000836 return SQLITE_OK;
837}
838
danielk197785d90ca2008-07-19 14:25:15 +0000839#else /* if defined SQLITE_OMIT_AUTOVACUUM */
drh98add2e2009-07-20 17:11:49 +0000840 #define ptrmapPut(w,x,y,z,rc)
danielk197785d90ca2008-07-19 14:25:15 +0000841 #define ptrmapGet(w,x,y,z) SQLITE_OK
drh98add2e2009-07-20 17:11:49 +0000842 #define ptrmapPutOvflPtr(x, y, rc)
danielk197785d90ca2008-07-19 14:25:15 +0000843#endif
danielk1977afcdd022004-10-31 16:25:42 +0000844
drh0d316a42002-08-11 20:10:47 +0000845/*
drh271efa52004-05-30 19:19:05 +0000846** Given a btree page and a cell index (0 means the first cell on
847** the page, 1 means the second cell, and so forth) return a pointer
848** to the cell content.
849**
850** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000851*/
drh1688c862008-07-18 02:44:17 +0000852#define findCell(P,I) \
853 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
drh43605152004-05-29 21:46:49 +0000854
855/*
drh93a960a2008-07-10 00:32:42 +0000856** This a more complex version of findCell() that works for
drh0a45c272009-07-08 01:49:11 +0000857** pages that do contain overflow cells.
drh43605152004-05-29 21:46:49 +0000858*/
859static u8 *findOverflowCell(MemPage *pPage, int iCell){
860 int i;
drh1fee73e2007-08-29 04:00:57 +0000861 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +0000862 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000863 int k;
864 struct _OvflCell *pOvfl;
865 pOvfl = &pPage->aOvfl[i];
866 k = pOvfl->idx;
867 if( k<=iCell ){
868 if( k==iCell ){
869 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000870 }
871 iCell--;
872 }
873 }
danielk19771cc5ed82007-05-16 17:28:43 +0000874 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000875}
876
877/*
878** Parse a cell content block and fill in the CellInfo structure. There
danielk197730548662009-07-09 05:07:37 +0000879** are two versions of this function. btreeParseCell() takes a
880** cell index as the second argument and btreeParseCellPtr()
drh16a9b832007-05-05 18:39:25 +0000881** takes a pointer to the body of the cell as its second argument.
danielk19771cc5ed82007-05-16 17:28:43 +0000882**
883** Within this file, the parseCell() macro can be called instead of
danielk197730548662009-07-09 05:07:37 +0000884** btreeParseCellPtr(). Using some compilers, this will be faster.
drh43605152004-05-29 21:46:49 +0000885*/
danielk197730548662009-07-09 05:07:37 +0000886static void btreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000887 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000888 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000889 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000890){
drhf49661a2008-12-10 16:45:50 +0000891 u16 n; /* Number bytes in cell content header */
drh271efa52004-05-30 19:19:05 +0000892 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000893
drh1fee73e2007-08-29 04:00:57 +0000894 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000895
drh43605152004-05-29 21:46:49 +0000896 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000897 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000898 n = pPage->childPtrSize;
899 assert( n==4-4*pPage->leaf );
drh504b6982006-01-22 21:52:56 +0000900 if( pPage->intKey ){
drh79df1f42008-07-18 00:57:33 +0000901 if( pPage->hasData ){
902 n += getVarint32(&pCell[n], nPayload);
903 }else{
904 nPayload = 0;
905 }
drh1bd10f82008-12-10 21:19:56 +0000906 n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
drh79df1f42008-07-18 00:57:33 +0000907 pInfo->nData = nPayload;
drh504b6982006-01-22 21:52:56 +0000908 }else{
drh79df1f42008-07-18 00:57:33 +0000909 pInfo->nData = 0;
910 n += getVarint32(&pCell[n], nPayload);
911 pInfo->nKey = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000912 }
drh72365832007-03-06 15:53:44 +0000913 pInfo->nPayload = nPayload;
drh504b6982006-01-22 21:52:56 +0000914 pInfo->nHeader = n;
drh0a45c272009-07-08 01:49:11 +0000915 testcase( nPayload==pPage->maxLocal );
916 testcase( nPayload==pPage->maxLocal+1 );
drh79df1f42008-07-18 00:57:33 +0000917 if( likely(nPayload<=pPage->maxLocal) ){
drh271efa52004-05-30 19:19:05 +0000918 /* This is the (easy) common case where the entire payload fits
919 ** on the local page. No overflow is required.
920 */
drh41692e92011-01-25 04:34:51 +0000921 if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
drhf49661a2008-12-10 16:45:50 +0000922 pInfo->nLocal = (u16)nPayload;
drh6f11bef2004-05-13 01:12:56 +0000923 pInfo->iOverflow = 0;
drh6f11bef2004-05-13 01:12:56 +0000924 }else{
drh271efa52004-05-30 19:19:05 +0000925 /* If the payload will not fit completely on the local page, we have
926 ** to decide how much to store locally and how much to spill onto
927 ** overflow pages. The strategy is to minimize the amount of unused
928 ** space on overflow pages while keeping the amount of local storage
929 ** in between minLocal and maxLocal.
930 **
931 ** Warning: changing the way overflow payload is distributed in any
932 ** way will result in an incompatible file format.
933 */
934 int minLocal; /* Minimum amount of payload held locally */
935 int maxLocal; /* Maximum amount of payload held locally */
936 int surplus; /* Overflow payload available for local storage */
937
938 minLocal = pPage->minLocal;
939 maxLocal = pPage->maxLocal;
940 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh0a45c272009-07-08 01:49:11 +0000941 testcase( surplus==maxLocal );
942 testcase( surplus==maxLocal+1 );
drh6f11bef2004-05-13 01:12:56 +0000943 if( surplus <= maxLocal ){
drhf49661a2008-12-10 16:45:50 +0000944 pInfo->nLocal = (u16)surplus;
drh6f11bef2004-05-13 01:12:56 +0000945 }else{
drhf49661a2008-12-10 16:45:50 +0000946 pInfo->nLocal = (u16)minLocal;
drh6f11bef2004-05-13 01:12:56 +0000947 }
drhf49661a2008-12-10 16:45:50 +0000948 pInfo->iOverflow = (u16)(pInfo->nLocal + n);
drh6f11bef2004-05-13 01:12:56 +0000949 pInfo->nSize = pInfo->iOverflow + 4;
950 }
drh3aac2dd2004-04-26 14:10:20 +0000951}
danielk19771cc5ed82007-05-16 17:28:43 +0000952#define parseCell(pPage, iCell, pInfo) \
danielk197730548662009-07-09 05:07:37 +0000953 btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
954static void btreeParseCell(
drh43605152004-05-29 21:46:49 +0000955 MemPage *pPage, /* Page containing the cell */
956 int iCell, /* The cell index. First cell is 0 */
957 CellInfo *pInfo /* Fill in this structure */
958){
danielk19771cc5ed82007-05-16 17:28:43 +0000959 parseCell(pPage, iCell, pInfo);
drh43605152004-05-29 21:46:49 +0000960}
drh3aac2dd2004-04-26 14:10:20 +0000961
962/*
drh43605152004-05-29 21:46:49 +0000963** Compute the total number of bytes that a Cell needs in the cell
964** data area of the btree-page. The return number includes the cell
965** data header and the local payload, but not any overflow page or
966** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000967*/
danielk1977ae5558b2009-04-29 11:31:47 +0000968static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
969 u8 *pIter = &pCell[pPage->childPtrSize];
970 u32 nSize;
971
972#ifdef SQLITE_DEBUG
973 /* The value returned by this function should always be the same as
974 ** the (CellInfo.nSize) value found by doing a full parse of the
975 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
976 ** this function verifies that this invariant is not violated. */
977 CellInfo debuginfo;
danielk197730548662009-07-09 05:07:37 +0000978 btreeParseCellPtr(pPage, pCell, &debuginfo);
danielk1977ae5558b2009-04-29 11:31:47 +0000979#endif
980
981 if( pPage->intKey ){
982 u8 *pEnd;
983 if( pPage->hasData ){
984 pIter += getVarint32(pIter, nSize);
985 }else{
986 nSize = 0;
987 }
988
989 /* pIter now points at the 64-bit integer key value, a variable length
990 ** integer. The following block moves pIter to point at the first byte
991 ** past the end of the key value. */
992 pEnd = &pIter[9];
993 while( (*pIter++)&0x80 && pIter<pEnd );
994 }else{
995 pIter += getVarint32(pIter, nSize);
996 }
997
drh0a45c272009-07-08 01:49:11 +0000998 testcase( nSize==pPage->maxLocal );
999 testcase( nSize==pPage->maxLocal+1 );
danielk1977ae5558b2009-04-29 11:31:47 +00001000 if( nSize>pPage->maxLocal ){
1001 int minLocal = pPage->minLocal;
1002 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
drh0a45c272009-07-08 01:49:11 +00001003 testcase( nSize==pPage->maxLocal );
1004 testcase( nSize==pPage->maxLocal+1 );
danielk1977ae5558b2009-04-29 11:31:47 +00001005 if( nSize>pPage->maxLocal ){
1006 nSize = minLocal;
1007 }
1008 nSize += 4;
1009 }
shane75ac1de2009-06-09 18:58:52 +00001010 nSize += (u32)(pIter - pCell);
danielk1977ae5558b2009-04-29 11:31:47 +00001011
1012 /* The minimum size of any cell is 4 bytes. */
1013 if( nSize<4 ){
1014 nSize = 4;
1015 }
1016
1017 assert( nSize==debuginfo.nSize );
shane60a4b532009-05-06 18:57:09 +00001018 return (u16)nSize;
danielk1977ae5558b2009-04-29 11:31:47 +00001019}
drh0ee3dbe2009-10-16 15:05:18 +00001020
1021#ifdef SQLITE_DEBUG
1022/* This variation on cellSizePtr() is used inside of assert() statements
1023** only. */
drha9121e42008-02-19 14:59:35 +00001024static u16 cellSize(MemPage *pPage, int iCell){
danielk1977ae5558b2009-04-29 11:31:47 +00001025 return cellSizePtr(pPage, findCell(pPage, iCell));
drh43605152004-05-29 21:46:49 +00001026}
danielk1977bc6ada42004-06-30 08:20:16 +00001027#endif
drh3b7511c2001-05-26 13:15:44 +00001028
danielk197779a40da2005-01-16 08:00:01 +00001029#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +00001030/*
danielk197726836652005-01-17 01:33:13 +00001031** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +00001032** to an overflow page, insert an entry into the pointer-map
1033** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +00001034*/
drh98add2e2009-07-20 17:11:49 +00001035static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
drhfa67c3c2008-07-11 02:21:40 +00001036 CellInfo info;
drh98add2e2009-07-20 17:11:49 +00001037 if( *pRC ) return;
drhfa67c3c2008-07-11 02:21:40 +00001038 assert( pCell!=0 );
danielk197730548662009-07-09 05:07:37 +00001039 btreeParseCellPtr(pPage, pCell, &info);
drhfa67c3c2008-07-11 02:21:40 +00001040 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk19774dbaa892009-06-16 16:50:22 +00001041 if( info.iOverflow ){
drhfa67c3c2008-07-11 02:21:40 +00001042 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
drh98add2e2009-07-20 17:11:49 +00001043 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
danielk1977ac11ee62005-01-15 12:45:51 +00001044 }
danielk1977ac11ee62005-01-15 12:45:51 +00001045}
danielk197779a40da2005-01-16 08:00:01 +00001046#endif
1047
danielk1977ac11ee62005-01-15 12:45:51 +00001048
drhda200cc2004-05-09 11:51:38 +00001049/*
drh72f82862001-05-24 21:06:34 +00001050** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +00001051** end of the page and all free space is collected into one
1052** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +00001053** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +00001054*/
shane0af3f892008-11-12 04:55:34 +00001055static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +00001056 int i; /* Loop counter */
1057 int pc; /* Address of a i-th cell */
drh43605152004-05-29 21:46:49 +00001058 int hdr; /* Offset to the page header */
1059 int size; /* Size of a cell */
1060 int usableSize; /* Number of usable bytes on a page */
1061 int cellOffset; /* Offset to the cell pointer array */
drh281b21d2008-08-22 12:57:08 +00001062 int cbrk; /* Offset to the cell content area */
drh43605152004-05-29 21:46:49 +00001063 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +00001064 unsigned char *data; /* The page data */
1065 unsigned char *temp; /* Temp area for cell content */
drh17146622009-07-07 17:38:38 +00001066 int iCellFirst; /* First allowable cell index */
1067 int iCellLast; /* Last possible cell index */
1068
drh2af926b2001-05-15 00:39:25 +00001069
danielk19773b8a05f2007-03-19 17:44:26 +00001070 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001071 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +00001072 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +00001073 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00001074 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh26b79942007-11-28 16:19:56 +00001075 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
drh43605152004-05-29 21:46:49 +00001076 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +00001077 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00001078 cellOffset = pPage->cellOffset;
1079 nCell = pPage->nCell;
1080 assert( nCell==get2byte(&data[hdr+3]) );
1081 usableSize = pPage->pBt->usableSize;
drh281b21d2008-08-22 12:57:08 +00001082 cbrk = get2byte(&data[hdr+5]);
1083 memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
1084 cbrk = usableSize;
drh17146622009-07-07 17:38:38 +00001085 iCellFirst = cellOffset + 2*nCell;
1086 iCellLast = usableSize - 4;
drh43605152004-05-29 21:46:49 +00001087 for(i=0; i<nCell; i++){
1088 u8 *pAddr; /* The i-th cell pointer */
1089 pAddr = &data[cellOffset + i*2];
1090 pc = get2byte(pAddr);
drh0a45c272009-07-08 01:49:11 +00001091 testcase( pc==iCellFirst );
1092 testcase( pc==iCellLast );
drh17146622009-07-07 17:38:38 +00001093#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
danielk197730548662009-07-09 05:07:37 +00001094 /* These conditions have already been verified in btreeInitPage()
drh17146622009-07-07 17:38:38 +00001095 ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
1096 */
1097 if( pc<iCellFirst || pc>iCellLast ){
shane0af3f892008-11-12 04:55:34 +00001098 return SQLITE_CORRUPT_BKPT;
1099 }
drh17146622009-07-07 17:38:38 +00001100#endif
1101 assert( pc>=iCellFirst && pc<=iCellLast );
drh43605152004-05-29 21:46:49 +00001102 size = cellSizePtr(pPage, &temp[pc]);
drh281b21d2008-08-22 12:57:08 +00001103 cbrk -= size;
drh17146622009-07-07 17:38:38 +00001104#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
1105 if( cbrk<iCellFirst ){
shane0af3f892008-11-12 04:55:34 +00001106 return SQLITE_CORRUPT_BKPT;
1107 }
drh17146622009-07-07 17:38:38 +00001108#else
1109 if( cbrk<iCellFirst || pc+size>usableSize ){
1110 return SQLITE_CORRUPT_BKPT;
1111 }
1112#endif
drh7157e1d2009-07-09 13:25:32 +00001113 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
drh0a45c272009-07-08 01:49:11 +00001114 testcase( cbrk+size==usableSize );
drh0a45c272009-07-08 01:49:11 +00001115 testcase( pc+size==usableSize );
drh281b21d2008-08-22 12:57:08 +00001116 memcpy(&data[cbrk], &temp[pc], size);
1117 put2byte(pAddr, cbrk);
drh2af926b2001-05-15 00:39:25 +00001118 }
drh17146622009-07-07 17:38:38 +00001119 assert( cbrk>=iCellFirst );
drh281b21d2008-08-22 12:57:08 +00001120 put2byte(&data[hdr+5], cbrk);
drh43605152004-05-29 21:46:49 +00001121 data[hdr+1] = 0;
1122 data[hdr+2] = 0;
1123 data[hdr+7] = 0;
drh17146622009-07-07 17:38:38 +00001124 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
drhc5053fb2008-11-27 02:22:10 +00001125 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh17146622009-07-07 17:38:38 +00001126 if( cbrk-iCellFirst!=pPage->nFree ){
danielk1977360e6342008-11-12 08:49:51 +00001127 return SQLITE_CORRUPT_BKPT;
1128 }
shane0af3f892008-11-12 04:55:34 +00001129 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +00001130}
1131
drha059ad02001-04-17 20:09:11 +00001132/*
danielk19776011a752009-04-01 16:25:32 +00001133** Allocate nByte bytes of space from within the B-Tree page passed
drh0a45c272009-07-08 01:49:11 +00001134** as the first argument. Write into *pIdx the index into pPage->aData[]
1135** of the first byte of allocated space. Return either SQLITE_OK or
1136** an error code (usually SQLITE_CORRUPT).
drhbd03cae2001-06-02 02:40:57 +00001137**
drh0a45c272009-07-08 01:49:11 +00001138** The caller guarantees that there is sufficient space to make the
1139** allocation. This routine might need to defragment in order to bring
1140** all the space together, however. This routine will avoid using
1141** the first two bytes past the cell pointer area since presumably this
1142** allocation is being made in order to insert a new cell, so we will
1143** also end up needing a new cell pointer.
drh7e3b0a02001-04-28 16:52:40 +00001144*/
drh0a45c272009-07-08 01:49:11 +00001145static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
danielk19776011a752009-04-01 16:25:32 +00001146 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1147 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
1148 int nFrag; /* Number of fragmented bytes on pPage */
drh0a45c272009-07-08 01:49:11 +00001149 int top; /* First byte of cell content area */
1150 int gap; /* First byte of gap between cell pointers and cell content */
1151 int rc; /* Integer return code */
drh00ce3942009-12-06 03:35:51 +00001152 int usableSize; /* Usable size of the page */
drh43605152004-05-29 21:46:49 +00001153
danielk19773b8a05f2007-03-19 17:44:26 +00001154 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001155 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +00001156 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa67c3c2008-07-11 02:21:40 +00001157 assert( nByte>=0 ); /* Minimum cell size is 4 */
1158 assert( pPage->nFree>=nByte );
1159 assert( pPage->nOverflow==0 );
drh00ce3942009-12-06 03:35:51 +00001160 usableSize = pPage->pBt->usableSize;
1161 assert( nByte < usableSize-8 );
drh43605152004-05-29 21:46:49 +00001162
1163 nFrag = data[hdr+7];
drh0a45c272009-07-08 01:49:11 +00001164 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1165 gap = pPage->cellOffset + 2*pPage->nCell;
drh5d433ce2010-08-14 16:02:52 +00001166 top = get2byteNotZero(&data[hdr+5]);
drh7157e1d2009-07-09 13:25:32 +00001167 if( gap>top ) return SQLITE_CORRUPT_BKPT;
drh0a45c272009-07-08 01:49:11 +00001168 testcase( gap+2==top );
1169 testcase( gap+1==top );
1170 testcase( gap==top );
1171
danielk19776011a752009-04-01 16:25:32 +00001172 if( nFrag>=60 ){
drh0a45c272009-07-08 01:49:11 +00001173 /* Always defragment highly fragmented pages */
1174 rc = defragmentPage(pPage);
1175 if( rc ) return rc;
drh5d433ce2010-08-14 16:02:52 +00001176 top = get2byteNotZero(&data[hdr+5]);
drh0a45c272009-07-08 01:49:11 +00001177 }else if( gap+2<=top ){
danielk19776011a752009-04-01 16:25:32 +00001178 /* Search the freelist looking for a free slot big enough to satisfy
1179 ** the request. The allocation is made from the first free slot in
1180 ** the list that is large enough to accomadate it.
1181 */
1182 int pc, addr;
1183 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
drh00ce3942009-12-06 03:35:51 +00001184 int size; /* Size of the free slot */
1185 if( pc>usableSize-4 || pc<addr+4 ){
1186 return SQLITE_CORRUPT_BKPT;
1187 }
1188 size = get2byte(&data[pc+2]);
drh43605152004-05-29 21:46:49 +00001189 if( size>=nByte ){
drhf49661a2008-12-10 16:45:50 +00001190 int x = size - nByte;
drh0a45c272009-07-08 01:49:11 +00001191 testcase( x==4 );
1192 testcase( x==3 );
danielk19776011a752009-04-01 16:25:32 +00001193 if( x<4 ){
danielk1977fad91942009-04-29 17:49:59 +00001194 /* Remove the slot from the free-list. Update the number of
1195 ** fragmented bytes within the page. */
drh43605152004-05-29 21:46:49 +00001196 memcpy(&data[addr], &data[pc], 2);
drhf49661a2008-12-10 16:45:50 +00001197 data[hdr+7] = (u8)(nFrag + x);
drh00ce3942009-12-06 03:35:51 +00001198 }else if( size+pc > usableSize ){
1199 return SQLITE_CORRUPT_BKPT;
drh43605152004-05-29 21:46:49 +00001200 }else{
danielk1977fad91942009-04-29 17:49:59 +00001201 /* The slot remains on the free-list. Reduce its size to account
1202 ** for the portion used by the new allocation. */
drhf49661a2008-12-10 16:45:50 +00001203 put2byte(&data[pc+2], x);
drh43605152004-05-29 21:46:49 +00001204 }
drh0a45c272009-07-08 01:49:11 +00001205 *pIdx = pc + x;
1206 return SQLITE_OK;
drh43605152004-05-29 21:46:49 +00001207 }
drh9e572e62004-04-23 23:43:10 +00001208 }
1209 }
drh43605152004-05-29 21:46:49 +00001210
drh0a45c272009-07-08 01:49:11 +00001211 /* Check to make sure there is enough space in the gap to satisfy
1212 ** the allocation. If not, defragment.
1213 */
1214 testcase( gap+2+nByte==top );
1215 if( gap+2+nByte>top ){
1216 rc = defragmentPage(pPage);
1217 if( rc ) return rc;
drh5d433ce2010-08-14 16:02:52 +00001218 top = get2byteNotZero(&data[hdr+5]);
drh0a45c272009-07-08 01:49:11 +00001219 assert( gap+nByte<=top );
1220 }
1221
1222
drh43605152004-05-29 21:46:49 +00001223 /* Allocate memory from the gap in between the cell pointer array
drhc314dc72009-07-21 11:52:34 +00001224 ** and the cell content area. The btreeInitPage() call has already
1225 ** validated the freelist. Given that the freelist is valid, there
1226 ** is no way that the allocation can extend off the end of the page.
1227 ** The assert() below verifies the previous sentence.
drh43605152004-05-29 21:46:49 +00001228 */
drh0a45c272009-07-08 01:49:11 +00001229 top -= nByte;
drh43605152004-05-29 21:46:49 +00001230 put2byte(&data[hdr+5], top);
drhfcd71b62011-04-05 22:08:24 +00001231 assert( top+nByte <= (int)pPage->pBt->usableSize );
drh0a45c272009-07-08 01:49:11 +00001232 *pIdx = top;
1233 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001234}
1235
1236/*
drh9e572e62004-04-23 23:43:10 +00001237** Return a section of the pPage->aData to the freelist.
1238** The first byte of the new free block is pPage->aDisk[start]
1239** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +00001240**
1241** Most of the effort here is involved in coalesing adjacent
1242** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +00001243*/
shanedcc50b72008-11-13 18:29:50 +00001244static int freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +00001245 int addr, pbegin, hdr;
drh0a45c272009-07-08 01:49:11 +00001246 int iLast; /* Largest possible freeblock offset */
drh9e572e62004-04-23 23:43:10 +00001247 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +00001248
drh9e572e62004-04-23 23:43:10 +00001249 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001250 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drhc046e3e2009-07-15 11:26:44 +00001251 assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
drhfcd71b62011-04-05 22:08:24 +00001252 assert( (start + size) <= (int)pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +00001253 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh34004ce2008-07-11 16:15:17 +00001254 assert( size>=0 ); /* Minimum cell size is 4 */
drh9e572e62004-04-23 23:43:10 +00001255
drh5b47efa2010-02-12 18:18:39 +00001256 if( pPage->pBt->secureDelete ){
1257 /* Overwrite deleted information with zeros when the secure_delete
1258 ** option is enabled */
1259 memset(&data[start], 0, size);
1260 }
drhfcce93f2006-02-22 03:08:32 +00001261
drh0a45c272009-07-08 01:49:11 +00001262 /* Add the space back into the linked list of freeblocks. Note that
danielk197730548662009-07-09 05:07:37 +00001263 ** even though the freeblock list was checked by btreeInitPage(),
1264 ** btreeInitPage() did not detect overlapping cells or
drhb908d762009-07-08 16:54:40 +00001265 ** freeblocks that overlapped cells. Nor does it detect when the
1266 ** cell content area exceeds the value in the page header. If these
1267 ** situations arise, then subsequent insert operations might corrupt
1268 ** the freelist. So we do need to check for corruption while scanning
1269 ** the freelist.
drh0a45c272009-07-08 01:49:11 +00001270 */
drh43605152004-05-29 21:46:49 +00001271 hdr = pPage->hdrOffset;
1272 addr = hdr + 1;
drh0a45c272009-07-08 01:49:11 +00001273 iLast = pPage->pBt->usableSize - 4;
drh35a25da2009-07-08 15:14:50 +00001274 assert( start<=iLast );
drh3aac2dd2004-04-26 14:10:20 +00001275 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drh35a25da2009-07-08 15:14:50 +00001276 if( pbegin<addr+4 ){
shanedcc50b72008-11-13 18:29:50 +00001277 return SQLITE_CORRUPT_BKPT;
1278 }
drh3aac2dd2004-04-26 14:10:20 +00001279 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +00001280 }
drh0a45c272009-07-08 01:49:11 +00001281 if( pbegin>iLast ){
shanedcc50b72008-11-13 18:29:50 +00001282 return SQLITE_CORRUPT_BKPT;
1283 }
drh3aac2dd2004-04-26 14:10:20 +00001284 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +00001285 put2byte(&data[addr], start);
1286 put2byte(&data[start], pbegin);
1287 put2byte(&data[start+2], size);
shane36840fd2009-06-26 16:32:13 +00001288 pPage->nFree = pPage->nFree + (u16)size;
drh9e572e62004-04-23 23:43:10 +00001289
1290 /* Coalesce adjacent free blocks */
drh0a45c272009-07-08 01:49:11 +00001291 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +00001292 while( (pbegin = get2byte(&data[addr]))>0 ){
drhf49661a2008-12-10 16:45:50 +00001293 int pnext, psize, x;
drh3aac2dd2004-04-26 14:10:20 +00001294 assert( pbegin>addr );
drhfcd71b62011-04-05 22:08:24 +00001295 assert( pbegin <= (int)pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +00001296 pnext = get2byte(&data[pbegin]);
1297 psize = get2byte(&data[pbegin+2]);
1298 if( pbegin + psize + 3 >= pnext && pnext>0 ){
1299 int frag = pnext - (pbegin+psize);
drh0a45c272009-07-08 01:49:11 +00001300 if( (frag<0) || (frag>(int)data[hdr+7]) ){
shanedcc50b72008-11-13 18:29:50 +00001301 return SQLITE_CORRUPT_BKPT;
1302 }
drh0a45c272009-07-08 01:49:11 +00001303 data[hdr+7] -= (u8)frag;
drhf49661a2008-12-10 16:45:50 +00001304 x = get2byte(&data[pnext]);
1305 put2byte(&data[pbegin], x);
1306 x = pnext + get2byte(&data[pnext+2]) - pbegin;
1307 put2byte(&data[pbegin+2], x);
drh9e572e62004-04-23 23:43:10 +00001308 }else{
drh3aac2dd2004-04-26 14:10:20 +00001309 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +00001310 }
1311 }
drh7e3b0a02001-04-28 16:52:40 +00001312
drh43605152004-05-29 21:46:49 +00001313 /* If the cell content area begins with a freeblock, remove it. */
1314 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
1315 int top;
1316 pbegin = get2byte(&data[hdr+1]);
1317 memcpy(&data[hdr+1], &data[pbegin], 2);
drhf49661a2008-12-10 16:45:50 +00001318 top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
1319 put2byte(&data[hdr+5], top);
drh4b70f112004-05-02 21:12:19 +00001320 }
drhc5053fb2008-11-27 02:22:10 +00001321 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
shanedcc50b72008-11-13 18:29:50 +00001322 return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00001323}
1324
1325/*
drh271efa52004-05-30 19:19:05 +00001326** Decode the flags byte (the first byte of the header) for a page
1327** and initialize fields of the MemPage structure accordingly.
drh44845222008-07-17 18:39:57 +00001328**
1329** Only the following combinations are supported. Anything different
1330** indicates a corrupt database files:
1331**
1332** PTF_ZERODATA
1333** PTF_ZERODATA | PTF_LEAF
1334** PTF_LEAFDATA | PTF_INTKEY
1335** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
drh271efa52004-05-30 19:19:05 +00001336*/
drh44845222008-07-17 18:39:57 +00001337static int decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +00001338 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +00001339
1340 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +00001341 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00001342 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
drh44845222008-07-17 18:39:57 +00001343 flagByte &= ~PTF_LEAF;
1344 pPage->childPtrSize = 4-4*pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001345 pBt = pPage->pBt;
drh44845222008-07-17 18:39:57 +00001346 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
1347 pPage->intKey = 1;
1348 pPage->hasData = pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001349 pPage->maxLocal = pBt->maxLeaf;
1350 pPage->minLocal = pBt->minLeaf;
drh44845222008-07-17 18:39:57 +00001351 }else if( flagByte==PTF_ZERODATA ){
1352 pPage->intKey = 0;
1353 pPage->hasData = 0;
drh271efa52004-05-30 19:19:05 +00001354 pPage->maxLocal = pBt->maxLocal;
1355 pPage->minLocal = pBt->minLocal;
drh44845222008-07-17 18:39:57 +00001356 }else{
1357 return SQLITE_CORRUPT_BKPT;
drh271efa52004-05-30 19:19:05 +00001358 }
drh44845222008-07-17 18:39:57 +00001359 return SQLITE_OK;
drh271efa52004-05-30 19:19:05 +00001360}
1361
1362/*
drh7e3b0a02001-04-28 16:52:40 +00001363** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +00001364**
1365** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +00001366** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +00001367** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1368** guarantee that the page is well-formed. It only shows that
1369** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001370*/
danielk197730548662009-07-09 05:07:37 +00001371static int btreeInitPage(MemPage *pPage){
drh2af926b2001-05-15 00:39:25 +00001372
danielk197771d5d2c2008-09-29 11:49:47 +00001373 assert( pPage->pBt!=0 );
1374 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001375 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +00001376 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1377 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00001378
1379 if( !pPage->isInit ){
drhf49661a2008-12-10 16:45:50 +00001380 u16 pc; /* Address of a freeblock within pPage->aData[] */
1381 u8 hdr; /* Offset to beginning of page header */
danielk197771d5d2c2008-09-29 11:49:47 +00001382 u8 *data; /* Equal to pPage->aData */
1383 BtShared *pBt; /* The main btree structure */
drhb2eced52010-08-12 02:41:12 +00001384 int usableSize; /* Amount of usable space on each page */
shaneh1df2db72010-08-18 02:28:48 +00001385 u16 cellOffset; /* Offset from start of page to first cell pointer */
drhb2eced52010-08-12 02:41:12 +00001386 int nFree; /* Number of unused bytes on the page */
1387 int top; /* First byte of the cell content area */
drh0a45c272009-07-08 01:49:11 +00001388 int iCellFirst; /* First allowable cell or freeblock offset */
1389 int iCellLast; /* Last possible cell or freeblock offset */
danielk197771d5d2c2008-09-29 11:49:47 +00001390
1391 pBt = pPage->pBt;
1392
danielk1977eaa06f62008-09-18 17:34:44 +00001393 hdr = pPage->hdrOffset;
1394 data = pPage->aData;
1395 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
drhb2eced52010-08-12 02:41:12 +00001396 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
1397 pPage->maskPage = (u16)(pBt->pageSize - 1);
danielk1977eaa06f62008-09-18 17:34:44 +00001398 pPage->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00001399 usableSize = pBt->usableSize;
1400 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
drh5d433ce2010-08-14 16:02:52 +00001401 top = get2byteNotZero(&data[hdr+5]);
danielk1977eaa06f62008-09-18 17:34:44 +00001402 pPage->nCell = get2byte(&data[hdr+3]);
1403 if( pPage->nCell>MX_CELL(pBt) ){
1404 /* To many cells for a single page. The page must be corrupt */
1405 return SQLITE_CORRUPT_BKPT;
1406 }
drhb908d762009-07-08 16:54:40 +00001407 testcase( pPage->nCell==MX_CELL(pBt) );
drh69e931e2009-06-03 21:04:35 +00001408
shane5eff7cf2009-08-10 03:57:58 +00001409 /* A malformed database page might cause us to read past the end
drh69e931e2009-06-03 21:04:35 +00001410 ** of page when parsing a cell.
1411 **
1412 ** The following block of code checks early to see if a cell extends
1413 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
1414 ** returned if it does.
1415 */
drh0a45c272009-07-08 01:49:11 +00001416 iCellFirst = cellOffset + 2*pPage->nCell;
1417 iCellLast = usableSize - 4;
drh3b2a3fa2009-06-09 13:42:24 +00001418#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
drh69e931e2009-06-03 21:04:35 +00001419 {
drh69e931e2009-06-03 21:04:35 +00001420 int i; /* Index into the cell pointer array */
1421 int sz; /* Size of a cell */
1422
drh69e931e2009-06-03 21:04:35 +00001423 if( !pPage->leaf ) iCellLast--;
1424 for(i=0; i<pPage->nCell; i++){
1425 pc = get2byte(&data[cellOffset+i*2]);
drh0a45c272009-07-08 01:49:11 +00001426 testcase( pc==iCellFirst );
1427 testcase( pc==iCellLast );
drh69e931e2009-06-03 21:04:35 +00001428 if( pc<iCellFirst || pc>iCellLast ){
1429 return SQLITE_CORRUPT_BKPT;
1430 }
1431 sz = cellSizePtr(pPage, &data[pc]);
drh0a45c272009-07-08 01:49:11 +00001432 testcase( pc+sz==usableSize );
drh69e931e2009-06-03 21:04:35 +00001433 if( pc+sz>usableSize ){
1434 return SQLITE_CORRUPT_BKPT;
1435 }
1436 }
drh0a45c272009-07-08 01:49:11 +00001437 if( !pPage->leaf ) iCellLast++;
drh69e931e2009-06-03 21:04:35 +00001438 }
1439#endif
1440
danielk1977eaa06f62008-09-18 17:34:44 +00001441 /* Compute the total free space on the page */
1442 pc = get2byte(&data[hdr+1]);
danielk197793c829c2009-06-03 17:26:17 +00001443 nFree = data[hdr+7] + top;
danielk1977eaa06f62008-09-18 17:34:44 +00001444 while( pc>0 ){
drh1bd10f82008-12-10 21:19:56 +00001445 u16 next, size;
drh0a45c272009-07-08 01:49:11 +00001446 if( pc<iCellFirst || pc>iCellLast ){
dan4361e792009-08-14 17:01:22 +00001447 /* Start of free block is off the page */
danielk1977eaa06f62008-09-18 17:34:44 +00001448 return SQLITE_CORRUPT_BKPT;
1449 }
1450 next = get2byte(&data[pc]);
1451 size = get2byte(&data[pc+2]);
dan4361e792009-08-14 17:01:22 +00001452 if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
1453 /* Free blocks must be in ascending order. And the last byte of
1454 ** the free-block must lie on the database page. */
danielk1977eaa06f62008-09-18 17:34:44 +00001455 return SQLITE_CORRUPT_BKPT;
1456 }
shane85095702009-06-15 16:27:08 +00001457 nFree = nFree + size;
danielk1977eaa06f62008-09-18 17:34:44 +00001458 pc = next;
1459 }
danielk197793c829c2009-06-03 17:26:17 +00001460
1461 /* At this point, nFree contains the sum of the offset to the start
1462 ** of the cell-content area plus the number of free bytes within
1463 ** the cell-content area. If this is greater than the usable-size
1464 ** of the page, then the page must be corrupted. This check also
1465 ** serves to verify that the offset to the start of the cell-content
1466 ** area, according to the page header, lies within the page.
1467 */
1468 if( nFree>usableSize ){
drh49285702005-09-17 15:20:26 +00001469 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001470 }
shane5eff7cf2009-08-10 03:57:58 +00001471 pPage->nFree = (u16)(nFree - iCellFirst);
danielk197771d5d2c2008-09-29 11:49:47 +00001472 pPage->isInit = 1;
1473 }
drh9e572e62004-04-23 23:43:10 +00001474 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001475}
1476
1477/*
drh8b2f49b2001-06-08 00:21:52 +00001478** Set up a raw page so that it looks like a database page holding
1479** no entries.
drhbd03cae2001-06-02 02:40:57 +00001480*/
drh9e572e62004-04-23 23:43:10 +00001481static void zeroPage(MemPage *pPage, int flags){
1482 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001483 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00001484 u8 hdr = pPage->hdrOffset;
1485 u16 first;
drh9e572e62004-04-23 23:43:10 +00001486
danielk19773b8a05f2007-03-19 17:44:26 +00001487 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drhbf4bca52007-09-06 22:19:14 +00001488 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1489 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +00001490 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00001491 assert( sqlite3_mutex_held(pBt->mutex) );
drh5b47efa2010-02-12 18:18:39 +00001492 if( pBt->secureDelete ){
1493 memset(&data[hdr], 0, pBt->usableSize - hdr);
1494 }
drh1bd10f82008-12-10 21:19:56 +00001495 data[hdr] = (char)flags;
1496 first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
drh43605152004-05-29 21:46:49 +00001497 memset(&data[hdr+1], 0, 4);
1498 data[hdr+7] = 0;
1499 put2byte(&data[hdr+5], pBt->usableSize);
shaneh1df2db72010-08-18 02:28:48 +00001500 pPage->nFree = (u16)(pBt->usableSize - first);
drh271efa52004-05-30 19:19:05 +00001501 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +00001502 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +00001503 pPage->cellOffset = first;
1504 pPage->nOverflow = 0;
drhb2eced52010-08-12 02:41:12 +00001505 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
1506 pPage->maskPage = (u16)(pBt->pageSize - 1);
drh43605152004-05-29 21:46:49 +00001507 pPage->nCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001508 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00001509}
1510
drh897a8202008-09-18 01:08:15 +00001511
1512/*
1513** Convert a DbPage obtained from the pager into a MemPage used by
1514** the btree layer.
1515*/
1516static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
1517 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
1518 pPage->aData = sqlite3PagerGetData(pDbPage);
1519 pPage->pDbPage = pDbPage;
1520 pPage->pBt = pBt;
1521 pPage->pgno = pgno;
1522 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
1523 return pPage;
1524}
1525
drhbd03cae2001-06-02 02:40:57 +00001526/*
drh3aac2dd2004-04-26 14:10:20 +00001527** Get a page from the pager. Initialize the MemPage.pBt and
1528** MemPage.aData elements if needed.
drh538f5702007-04-13 02:14:30 +00001529**
1530** If the noContent flag is set, it means that we do not care about
1531** the content of the page at this time. So do not go to the disk
1532** to fetch the content. Just fill in the content with zeros for now.
1533** If in the future we call sqlite3PagerWrite() on this page, that
1534** means we have started to be concerned about content and the disk
1535** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00001536*/
danielk197730548662009-07-09 05:07:37 +00001537static int btreeGetPage(
drh16a9b832007-05-05 18:39:25 +00001538 BtShared *pBt, /* The btree */
1539 Pgno pgno, /* Number of the page to fetch */
1540 MemPage **ppPage, /* Return the page in this parameter */
1541 int noContent /* Do not load page content if true */
1542){
drh3aac2dd2004-04-26 14:10:20 +00001543 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001544 DbPage *pDbPage;
1545
drh1fee73e2007-08-29 04:00:57 +00001546 assert( sqlite3_mutex_held(pBt->mutex) );
drh538f5702007-04-13 02:14:30 +00001547 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
drh3aac2dd2004-04-26 14:10:20 +00001548 if( rc ) return rc;
drh897a8202008-09-18 01:08:15 +00001549 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
drh3aac2dd2004-04-26 14:10:20 +00001550 return SQLITE_OK;
1551}
1552
1553/*
danielk1977bea2a942009-01-20 17:06:27 +00001554** Retrieve a page from the pager cache. If the requested page is not
1555** already in the pager cache return NULL. Initialize the MemPage.pBt and
1556** MemPage.aData elements if needed.
1557*/
1558static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
1559 DbPage *pDbPage;
1560 assert( sqlite3_mutex_held(pBt->mutex) );
1561 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
1562 if( pDbPage ){
1563 return btreePageFromDbPage(pDbPage, pgno, pBt);
1564 }
1565 return 0;
1566}
1567
1568/*
danielk197789d40042008-11-17 14:20:56 +00001569** Return the size of the database file in pages. If there is any kind of
1570** error, return ((unsigned int)-1).
danielk197767fd7a92008-09-10 17:53:35 +00001571*/
drhb1299152010-03-30 22:58:33 +00001572static Pgno btreePagecount(BtShared *pBt){
1573 return pBt->nPage;
1574}
1575u32 sqlite3BtreeLastPage(Btree *p){
1576 assert( sqlite3BtreeHoldsMutex(p) );
1577 assert( ((p->pBt->nPage)&0x8000000)==0 );
1578 return (int)btreePagecount(p->pBt);
danielk197767fd7a92008-09-10 17:53:35 +00001579}
1580
1581/*
danielk197789bc4bc2009-07-21 19:25:24 +00001582** Get a page from the pager and initialize it. This routine is just a
1583** convenience wrapper around separate calls to btreeGetPage() and
1584** btreeInitPage().
1585**
1586** If an error occurs, then the value *ppPage is set to is undefined. It
1587** may remain unchanged, or it may be set to an invalid value.
drhde647132004-05-07 17:57:49 +00001588*/
1589static int getAndInitPage(
danielk1977aef0bf62005-12-30 16:28:01 +00001590 BtShared *pBt, /* The database file */
drhde647132004-05-07 17:57:49 +00001591 Pgno pgno, /* Number of the page to get */
danielk197771d5d2c2008-09-29 11:49:47 +00001592 MemPage **ppPage /* Write the page pointer here */
drhde647132004-05-07 17:57:49 +00001593){
1594 int rc;
drh1fee73e2007-08-29 04:00:57 +00001595 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197789bc4bc2009-07-21 19:25:24 +00001596
danba3cbf32010-06-30 04:29:03 +00001597 if( pgno>btreePagecount(pBt) ){
1598 rc = SQLITE_CORRUPT_BKPT;
1599 }else{
1600 rc = btreeGetPage(pBt, pgno, ppPage, 0);
1601 if( rc==SQLITE_OK ){
1602 rc = btreeInitPage(*ppPage);
1603 if( rc!=SQLITE_OK ){
1604 releasePage(*ppPage);
1605 }
danielk197789bc4bc2009-07-21 19:25:24 +00001606 }
drhee696e22004-08-30 16:52:17 +00001607 }
danba3cbf32010-06-30 04:29:03 +00001608
1609 testcase( pgno==0 );
1610 assert( pgno!=0 || rc==SQLITE_CORRUPT );
drhde647132004-05-07 17:57:49 +00001611 return rc;
1612}
1613
1614/*
drh3aac2dd2004-04-26 14:10:20 +00001615** Release a MemPage. This should be called once for each prior
danielk197730548662009-07-09 05:07:37 +00001616** call to btreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +00001617*/
drh4b70f112004-05-02 21:12:19 +00001618static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001619 if( pPage ){
1620 assert( pPage->aData );
1621 assert( pPage->pBt );
drhbf4bca52007-09-06 22:19:14 +00001622 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1623 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
drh1fee73e2007-08-29 04:00:57 +00001624 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001625 sqlite3PagerUnref(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00001626 }
1627}
1628
1629/*
drha6abd042004-06-09 17:37:22 +00001630** During a rollback, when the pager reloads information into the cache
1631** so that the cache is restored to its original state at the start of
1632** the transaction, for each page restored this routine is called.
1633**
1634** This routine needs to reset the extra data section at the end of the
1635** page to agree with the restored data.
1636*/
danielk1977eaa06f62008-09-18 17:34:44 +00001637static void pageReinit(DbPage *pData){
drh07d183d2005-05-01 22:52:42 +00001638 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00001639 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
danielk1977d217e6f2009-04-01 17:13:51 +00001640 assert( sqlite3PagerPageRefcount(pData)>0 );
danielk197771d5d2c2008-09-29 11:49:47 +00001641 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00001642 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00001643 pPage->isInit = 0;
danielk1977d217e6f2009-04-01 17:13:51 +00001644 if( sqlite3PagerPageRefcount(pData)>1 ){
drh5e8d8872009-03-30 17:19:48 +00001645 /* pPage might not be a btree page; it might be an overflow page
1646 ** or ptrmap page or a free page. In those cases, the following
danielk197730548662009-07-09 05:07:37 +00001647 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
drh5e8d8872009-03-30 17:19:48 +00001648 ** But no harm is done by this. And it is very important that
danielk197730548662009-07-09 05:07:37 +00001649 ** btreeInitPage() be called on every btree page so we make
drh5e8d8872009-03-30 17:19:48 +00001650 ** the call for every page that comes in for re-initing. */
danielk197730548662009-07-09 05:07:37 +00001651 btreeInitPage(pPage);
danielk197771d5d2c2008-09-29 11:49:47 +00001652 }
drha6abd042004-06-09 17:37:22 +00001653 }
1654}
1655
1656/*
drhe5fe6902007-12-07 18:55:28 +00001657** Invoke the busy handler for a btree.
1658*/
danielk19771ceedd32008-11-19 10:22:33 +00001659static int btreeInvokeBusyHandler(void *pArg){
drhe5fe6902007-12-07 18:55:28 +00001660 BtShared *pBt = (BtShared*)pArg;
1661 assert( pBt->db );
1662 assert( sqlite3_mutex_held(pBt->db->mutex) );
1663 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
1664}
1665
1666/*
drhad3e0102004-09-03 23:32:18 +00001667** Open a database file.
1668**
drh382c0242001-10-06 16:33:02 +00001669** zFilename is the name of the database file. If zFilename is NULL
drh75c014c2010-08-30 15:02:28 +00001670** then an ephemeral database is created. The ephemeral database might
1671** be exclusively in memory, or it might use a disk-based memory cache.
1672** Either way, the ephemeral database will be automatically deleted
1673** when sqlite3BtreeClose() is called.
1674**
drhe53831d2007-08-17 01:14:38 +00001675** If zFilename is ":memory:" then an in-memory database is created
1676** that is automatically destroyed when it is closed.
drhc47fd8e2009-04-30 13:30:32 +00001677**
drh75c014c2010-08-30 15:02:28 +00001678** The "flags" parameter is a bitmask that might contain bits
1679** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK. The BTREE_NO_READLOCK
1680** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
1681** These flags are passed through into sqlite3PagerOpen() and must
1682** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
1683**
drhc47fd8e2009-04-30 13:30:32 +00001684** If the database is already opened in the same database connection
1685** and we are in shared cache mode, then the open will fail with an
1686** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
1687** objects in the same database connection since doing so will lead
1688** to problems with locking.
drha059ad02001-04-17 20:09:11 +00001689*/
drh23e11ca2004-05-04 17:27:28 +00001690int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001691 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00001692 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001693 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00001694 int flags, /* Options */
1695 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00001696){
drh7555d8e2009-03-20 13:15:30 +00001697 sqlite3_vfs *pVfs; /* The VFS to use for this btree */
1698 BtShared *pBt = 0; /* Shared part of btree structure */
1699 Btree *p; /* Handle to return */
1700 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
1701 int rc = SQLITE_OK; /* Result code from this function */
1702 u8 nReserve; /* Byte of unused space on each page */
1703 unsigned char zDbHeader[100]; /* Database header content */
danielk1977aef0bf62005-12-30 16:28:01 +00001704
drh75c014c2010-08-30 15:02:28 +00001705 /* True if opening an ephemeral, temporary database */
1706 const int isTempDb = zFilename==0 || zFilename[0]==0;
1707
danielk1977aef0bf62005-12-30 16:28:01 +00001708 /* Set the variable isMemdb to true for an in-memory database, or
drhb0a7c9c2010-12-06 21:09:59 +00001709 ** false for a file-based database.
danielk1977aef0bf62005-12-30 16:28:01 +00001710 */
drhb0a7c9c2010-12-06 21:09:59 +00001711#ifdef SQLITE_OMIT_MEMORYDB
1712 const int isMemdb = 0;
1713#else
1714 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
1715 || (isTempDb && sqlite3TempInMemory(db));
danielk1977aef0bf62005-12-30 16:28:01 +00001716#endif
1717
drhe5fe6902007-12-07 18:55:28 +00001718 assert( db!=0 );
1719 assert( sqlite3_mutex_held(db->mutex) );
drhd4187c72010-08-30 22:15:45 +00001720 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
1721
1722 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
1723 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
1724
1725 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
1726 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
drh153c62c2007-08-24 03:51:33 +00001727
drh75c014c2010-08-30 15:02:28 +00001728 if( db->flags & SQLITE_NoReadlock ){
1729 flags |= BTREE_NO_READLOCK;
1730 }
1731 if( isMemdb ){
1732 flags |= BTREE_MEMORY;
1733 }
1734 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
1735 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
1736 }
drhe5fe6902007-12-07 18:55:28 +00001737 pVfs = db->pVfs;
drh17435752007-08-16 04:30:38 +00001738 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00001739 if( !p ){
1740 return SQLITE_NOMEM;
1741 }
1742 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00001743 p->db = db;
danielk1977602b4662009-07-02 07:47:33 +00001744#ifndef SQLITE_OMIT_SHARED_CACHE
1745 p->lock.pBtree = p;
1746 p->lock.iTable = 1;
1747#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001748
drh198bf392006-01-06 21:52:49 +00001749#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001750 /*
1751 ** If this Btree is a candidate for shared cache, try to find an
1752 ** existing BtShared object that we can share with
1753 */
drh75c014c2010-08-30 15:02:28 +00001754 if( isMemdb==0 && isTempDb==0 ){
drhf1f12682009-09-09 14:17:52 +00001755 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
danielk1977adfb9b02007-09-17 07:02:56 +00001756 int nFullPathname = pVfs->mxPathname+1;
drhe5ae5732008-06-15 02:51:47 +00001757 char *zFullPathname = sqlite3Malloc(nFullPathname);
drhff0587c2007-08-29 17:43:19 +00001758 sqlite3_mutex *mutexShared;
1759 p->sharable = 1;
drhff0587c2007-08-29 17:43:19 +00001760 if( !zFullPathname ){
1761 sqlite3_free(p);
1762 return SQLITE_NOMEM;
1763 }
danielk1977adfb9b02007-09-17 07:02:56 +00001764 sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
drh7555d8e2009-03-20 13:15:30 +00001765 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
1766 sqlite3_mutex_enter(mutexOpen);
danielk197759f8c082008-06-18 17:09:10 +00001767 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhff0587c2007-08-29 17:43:19 +00001768 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001769 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
drhff0587c2007-08-29 17:43:19 +00001770 assert( pBt->nRef>0 );
1771 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
1772 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
drhc47fd8e2009-04-30 13:30:32 +00001773 int iDb;
1774 for(iDb=db->nDb-1; iDb>=0; iDb--){
1775 Btree *pExisting = db->aDb[iDb].pBt;
1776 if( pExisting && pExisting->pBt==pBt ){
1777 sqlite3_mutex_leave(mutexShared);
1778 sqlite3_mutex_leave(mutexOpen);
1779 sqlite3_free(zFullPathname);
1780 sqlite3_free(p);
1781 return SQLITE_CONSTRAINT;
1782 }
1783 }
drhff0587c2007-08-29 17:43:19 +00001784 p->pBt = pBt;
1785 pBt->nRef++;
1786 break;
1787 }
1788 }
1789 sqlite3_mutex_leave(mutexShared);
1790 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00001791 }
drhff0587c2007-08-29 17:43:19 +00001792#ifdef SQLITE_DEBUG
1793 else{
1794 /* In debug mode, we mark all persistent databases as sharable
1795 ** even when they are not. This exercises the locking code and
1796 ** gives more opportunity for asserts(sqlite3_mutex_held())
1797 ** statements to find locking problems.
1798 */
1799 p->sharable = 1;
1800 }
1801#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001802 }
1803#endif
drha059ad02001-04-17 20:09:11 +00001804 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00001805 /*
1806 ** The following asserts make sure that structures used by the btree are
1807 ** the right size. This is to guard against size changes that result
1808 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00001809 */
drhe53831d2007-08-17 01:14:38 +00001810 assert( sizeof(i64)==8 || sizeof(i64)==4 );
1811 assert( sizeof(u64)==8 || sizeof(u64)==4 );
1812 assert( sizeof(u32)==4 );
1813 assert( sizeof(u16)==2 );
1814 assert( sizeof(Pgno)==4 );
1815
1816 pBt = sqlite3MallocZero( sizeof(*pBt) );
1817 if( pBt==0 ){
1818 rc = SQLITE_NOMEM;
1819 goto btree_open_out;
1820 }
danielk197771d5d2c2008-09-29 11:49:47 +00001821 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
drh4775ecd2009-07-24 19:01:19 +00001822 EXTRA_SIZE, flags, vfsFlags, pageReinit);
drhe53831d2007-08-17 01:14:38 +00001823 if( rc==SQLITE_OK ){
1824 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
1825 }
1826 if( rc!=SQLITE_OK ){
1827 goto btree_open_out;
1828 }
shanehbd2aaf92010-09-01 02:38:21 +00001829 pBt->openFlags = (u8)flags;
danielk19772a50ff02009-04-10 09:47:06 +00001830 pBt->db = db;
danielk19771ceedd32008-11-19 10:22:33 +00001831 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
drhe53831d2007-08-17 01:14:38 +00001832 p->pBt = pBt;
1833
drhe53831d2007-08-17 01:14:38 +00001834 pBt->pCursor = 0;
1835 pBt->pPage1 = 0;
1836 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
drh5b47efa2010-02-12 18:18:39 +00001837#ifdef SQLITE_SECURE_DELETE
1838 pBt->secureDelete = 1;
1839#endif
drhb2eced52010-08-12 02:41:12 +00001840 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
drhe53831d2007-08-17 01:14:38 +00001841 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1842 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00001843 pBt->pageSize = 0;
drhe53831d2007-08-17 01:14:38 +00001844#ifndef SQLITE_OMIT_AUTOVACUUM
1845 /* If the magic name ":memory:" will create an in-memory database, then
1846 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
1847 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
1848 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
1849 ** regular file-name. In this case the auto-vacuum applies as per normal.
1850 */
1851 if( zFilename && !isMemdb ){
1852 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
1853 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
1854 }
1855#endif
1856 nReserve = 0;
1857 }else{
1858 nReserve = zDbHeader[20];
drhe53831d2007-08-17 01:14:38 +00001859 pBt->pageSizeFixed = 1;
1860#ifndef SQLITE_OMIT_AUTOVACUUM
1861 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1862 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
1863#endif
1864 }
drhfa9601a2009-06-18 17:22:39 +00001865 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhc0b61812009-04-30 01:22:41 +00001866 if( rc ) goto btree_open_out;
drhe53831d2007-08-17 01:14:38 +00001867 pBt->usableSize = pBt->pageSize - nReserve;
1868 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
drhe53831d2007-08-17 01:14:38 +00001869
1870#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1871 /* Add the new BtShared object to the linked list sharable BtShareds.
1872 */
1873 if( p->sharable ){
1874 sqlite3_mutex *mutexShared;
1875 pBt->nRef = 1;
danielk197759f8c082008-06-18 17:09:10 +00001876 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
danielk1977075c23a2008-09-01 18:34:20 +00001877 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
danielk197759f8c082008-06-18 17:09:10 +00001878 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
drh3285db22007-09-03 22:00:39 +00001879 if( pBt->mutex==0 ){
1880 rc = SQLITE_NOMEM;
drhe5fe6902007-12-07 18:55:28 +00001881 db->mallocFailed = 0;
drh3285db22007-09-03 22:00:39 +00001882 goto btree_open_out;
1883 }
drhff0587c2007-08-29 17:43:19 +00001884 }
drhe53831d2007-08-17 01:14:38 +00001885 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001886 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
1887 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
drhe53831d2007-08-17 01:14:38 +00001888 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00001889 }
drheee46cf2004-11-06 00:02:48 +00001890#endif
drh90f5ecb2004-07-22 01:19:35 +00001891 }
danielk1977aef0bf62005-12-30 16:28:01 +00001892
drhcfed7bc2006-03-13 14:28:05 +00001893#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001894 /* If the new Btree uses a sharable pBtShared, then link the new
1895 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00001896 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00001897 */
drhe53831d2007-08-17 01:14:38 +00001898 if( p->sharable ){
1899 int i;
1900 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00001901 for(i=0; i<db->nDb; i++){
1902 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00001903 while( pSib->pPrev ){ pSib = pSib->pPrev; }
1904 if( p->pBt<pSib->pBt ){
1905 p->pNext = pSib;
1906 p->pPrev = 0;
1907 pSib->pPrev = p;
1908 }else{
drhabddb0c2007-08-20 13:14:28 +00001909 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
drhe53831d2007-08-17 01:14:38 +00001910 pSib = pSib->pNext;
1911 }
1912 p->pNext = pSib->pNext;
1913 p->pPrev = pSib;
1914 if( p->pNext ){
1915 p->pNext->pPrev = p;
1916 }
1917 pSib->pNext = p;
1918 }
1919 break;
1920 }
1921 }
danielk1977aef0bf62005-12-30 16:28:01 +00001922 }
danielk1977aef0bf62005-12-30 16:28:01 +00001923#endif
1924 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00001925
1926btree_open_out:
1927 if( rc!=SQLITE_OK ){
1928 if( pBt && pBt->pPager ){
1929 sqlite3PagerClose(pBt->pPager);
1930 }
drh17435752007-08-16 04:30:38 +00001931 sqlite3_free(pBt);
1932 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00001933 *ppBtree = 0;
drh75c014c2010-08-30 15:02:28 +00001934 }else{
1935 /* If the B-Tree was successfully opened, set the pager-cache size to the
1936 ** default value. Except, when opening on an existing shared pager-cache,
1937 ** do not change the pager-cache size.
1938 */
1939 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
1940 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
1941 }
danielk1977dddbcdc2007-04-26 14:42:34 +00001942 }
drh7555d8e2009-03-20 13:15:30 +00001943 if( mutexOpen ){
1944 assert( sqlite3_mutex_held(mutexOpen) );
1945 sqlite3_mutex_leave(mutexOpen);
1946 }
danielk1977dddbcdc2007-04-26 14:42:34 +00001947 return rc;
drha059ad02001-04-17 20:09:11 +00001948}
1949
1950/*
drhe53831d2007-08-17 01:14:38 +00001951** Decrement the BtShared.nRef counter. When it reaches zero,
1952** remove the BtShared structure from the sharing list. Return
1953** true if the BtShared.nRef counter reaches zero and return
1954** false if it is still positive.
1955*/
1956static int removeFromSharingList(BtShared *pBt){
1957#ifndef SQLITE_OMIT_SHARED_CACHE
1958 sqlite3_mutex *pMaster;
1959 BtShared *pList;
1960 int removed = 0;
1961
drhd677b3d2007-08-20 22:48:41 +00001962 assert( sqlite3_mutex_notheld(pBt->mutex) );
danielk197759f8c082008-06-18 17:09:10 +00001963 pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhe53831d2007-08-17 01:14:38 +00001964 sqlite3_mutex_enter(pMaster);
1965 pBt->nRef--;
1966 if( pBt->nRef<=0 ){
drh78f82d12008-09-02 00:52:52 +00001967 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
1968 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
drhe53831d2007-08-17 01:14:38 +00001969 }else{
drh78f82d12008-09-02 00:52:52 +00001970 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
drh34004ce2008-07-11 16:15:17 +00001971 while( ALWAYS(pList) && pList->pNext!=pBt ){
drhe53831d2007-08-17 01:14:38 +00001972 pList=pList->pNext;
1973 }
drh34004ce2008-07-11 16:15:17 +00001974 if( ALWAYS(pList) ){
drhe53831d2007-08-17 01:14:38 +00001975 pList->pNext = pBt->pNext;
1976 }
1977 }
drh3285db22007-09-03 22:00:39 +00001978 if( SQLITE_THREADSAFE ){
1979 sqlite3_mutex_free(pBt->mutex);
1980 }
drhe53831d2007-08-17 01:14:38 +00001981 removed = 1;
1982 }
1983 sqlite3_mutex_leave(pMaster);
1984 return removed;
1985#else
1986 return 1;
1987#endif
1988}
1989
1990/*
drhf7141992008-06-19 00:16:08 +00001991** Make sure pBt->pTmpSpace points to an allocation of
1992** MX_CELL_SIZE(pBt) bytes.
1993*/
1994static void allocateTempSpace(BtShared *pBt){
1995 if( !pBt->pTmpSpace ){
1996 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
1997 }
1998}
1999
2000/*
2001** Free the pBt->pTmpSpace allocation
2002*/
2003static void freeTempSpace(BtShared *pBt){
2004 sqlite3PageFree( pBt->pTmpSpace);
2005 pBt->pTmpSpace = 0;
2006}
2007
2008/*
drha059ad02001-04-17 20:09:11 +00002009** Close an open database and invalidate all cursors.
2010*/
danielk1977aef0bf62005-12-30 16:28:01 +00002011int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002012 BtShared *pBt = p->pBt;
2013 BtCursor *pCur;
2014
danielk1977aef0bf62005-12-30 16:28:01 +00002015 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00002016 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00002017 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002018 pCur = pBt->pCursor;
2019 while( pCur ){
2020 BtCursor *pTmp = pCur;
2021 pCur = pCur->pNext;
2022 if( pTmp->pBtree==p ){
2023 sqlite3BtreeCloseCursor(pTmp);
2024 }
drha059ad02001-04-17 20:09:11 +00002025 }
danielk1977aef0bf62005-12-30 16:28:01 +00002026
danielk19778d34dfd2006-01-24 16:37:57 +00002027 /* Rollback any active transaction and free the handle structure.
2028 ** The call to sqlite3BtreeRollback() drops any table-locks held by
2029 ** this handle.
2030 */
danielk1977b597f742006-01-15 11:39:18 +00002031 sqlite3BtreeRollback(p);
drhe53831d2007-08-17 01:14:38 +00002032 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002033
danielk1977aef0bf62005-12-30 16:28:01 +00002034 /* If there are still other outstanding references to the shared-btree
2035 ** structure, return now. The remainder of this procedure cleans
2036 ** up the shared-btree.
2037 */
drhe53831d2007-08-17 01:14:38 +00002038 assert( p->wantToLock==0 && p->locked==0 );
2039 if( !p->sharable || removeFromSharingList(pBt) ){
2040 /* The pBt is no longer on the sharing list, so we can access
2041 ** it without having to hold the mutex.
2042 **
2043 ** Clean out and delete the BtShared object.
2044 */
2045 assert( !pBt->pCursor );
drhe53831d2007-08-17 01:14:38 +00002046 sqlite3PagerClose(pBt->pPager);
2047 if( pBt->xFreeSchema && pBt->pSchema ){
2048 pBt->xFreeSchema(pBt->pSchema);
2049 }
drhb9755982010-07-24 16:34:37 +00002050 sqlite3DbFree(0, pBt->pSchema);
drhf7141992008-06-19 00:16:08 +00002051 freeTempSpace(pBt);
drh65bbf292008-06-19 01:03:17 +00002052 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002053 }
2054
drhe53831d2007-08-17 01:14:38 +00002055#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00002056 assert( p->wantToLock==0 );
2057 assert( p->locked==0 );
2058 if( p->pPrev ) p->pPrev->pNext = p->pNext;
2059 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00002060#endif
2061
drhe53831d2007-08-17 01:14:38 +00002062 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00002063 return SQLITE_OK;
2064}
2065
2066/*
drhda47d772002-12-02 04:25:19 +00002067** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00002068**
2069** The maximum number of cache pages is set to the absolute
2070** value of mxPage. If mxPage is negative, the pager will
2071** operate asynchronously - it will not stop to do fsync()s
2072** to insure data is written to the disk surface before
2073** continuing. Transactions still work if synchronous is off,
2074** and the database cannot be corrupted if this program
2075** crashes. But if the operating system crashes or there is
2076** an abrupt power failure when synchronous is off, the database
2077** could be left in an inconsistent and unrecoverable state.
2078** Synchronous is on by default so database corruption is not
2079** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00002080*/
danielk1977aef0bf62005-12-30 16:28:01 +00002081int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2082 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00002083 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002084 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00002085 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00002086 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00002087 return SQLITE_OK;
2088}
2089
2090/*
drh973b6e32003-02-12 14:09:42 +00002091** Change the way data is synced to disk in order to increase or decrease
2092** how well the database resists damage due to OS crashes and power
2093** failures. Level 1 is the same as asynchronous (no syncs() occur and
2094** there is a high probability of damage) Level 2 is the default. There
2095** is a very low but non-zero probability of damage. Level 3 reduces the
2096** probability of damage to near zero but with a write performance reduction.
2097*/
danielk197793758c82005-01-21 08:13:14 +00002098#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drhc97d8462010-11-19 18:23:35 +00002099int sqlite3BtreeSetSafetyLevel(
2100 Btree *p, /* The btree to set the safety level on */
2101 int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */
2102 int fullSync, /* PRAGMA fullfsync. */
2103 int ckptFullSync /* PRAGMA checkpoint_fullfync */
2104){
danielk1977aef0bf62005-12-30 16:28:01 +00002105 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00002106 assert( sqlite3_mutex_held(p->db->mutex) );
drhc97d8462010-11-19 18:23:35 +00002107 assert( level>=1 && level<=3 );
drhd677b3d2007-08-20 22:48:41 +00002108 sqlite3BtreeEnter(p);
drhc97d8462010-11-19 18:23:35 +00002109 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
drhd677b3d2007-08-20 22:48:41 +00002110 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00002111 return SQLITE_OK;
2112}
danielk197793758c82005-01-21 08:13:14 +00002113#endif
drh973b6e32003-02-12 14:09:42 +00002114
drh2c8997b2005-08-27 16:36:48 +00002115/*
2116** Return TRUE if the given btree is set to safety level 1. In other
2117** words, return TRUE if no sync() occurs on the disk files.
2118*/
danielk1977aef0bf62005-12-30 16:28:01 +00002119int sqlite3BtreeSyncDisabled(Btree *p){
2120 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002121 int rc;
drhe5fe6902007-12-07 18:55:28 +00002122 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002123 sqlite3BtreeEnter(p);
drhd0679ed2007-08-28 22:24:34 +00002124 assert( pBt && pBt->pPager );
drhd677b3d2007-08-20 22:48:41 +00002125 rc = sqlite3PagerNosync(pBt->pPager);
2126 sqlite3BtreeLeave(p);
2127 return rc;
drh2c8997b2005-08-27 16:36:48 +00002128}
2129
drh973b6e32003-02-12 14:09:42 +00002130/*
drh90f5ecb2004-07-22 01:19:35 +00002131** Change the default pages size and the number of reserved bytes per page.
drhce4869f2009-04-02 20:16:58 +00002132** Or, if the page size has already been fixed, return SQLITE_READONLY
2133** without changing anything.
drh06f50212004-11-02 14:24:33 +00002134**
2135** The page size must be a power of 2 between 512 and 65536. If the page
2136** size supplied does not meet this constraint then the page size is not
2137** changed.
2138**
2139** Page sizes are constrained to be a power of two so that the region
2140** of the database file used for locking (beginning at PENDING_BYTE,
2141** the first byte past the 1GB boundary, 0x40000000) needs to occur
2142** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00002143**
2144** If parameter nReserve is less than zero, then the number of reserved
2145** bytes per page is left unchanged.
drhce4869f2009-04-02 20:16:58 +00002146**
2147** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
2148** and autovacuum mode can no longer be changed.
drh90f5ecb2004-07-22 01:19:35 +00002149*/
drhce4869f2009-04-02 20:16:58 +00002150int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
danielk1977a1644fd2007-08-29 12:31:25 +00002151 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002152 BtShared *pBt = p->pBt;
drhf49661a2008-12-10 16:45:50 +00002153 assert( nReserve>=-1 && nReserve<=255 );
drhd677b3d2007-08-20 22:48:41 +00002154 sqlite3BtreeEnter(p);
drh90f5ecb2004-07-22 01:19:35 +00002155 if( pBt->pageSizeFixed ){
drhd677b3d2007-08-20 22:48:41 +00002156 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00002157 return SQLITE_READONLY;
2158 }
2159 if( nReserve<0 ){
2160 nReserve = pBt->pageSize - pBt->usableSize;
2161 }
drhf49661a2008-12-10 16:45:50 +00002162 assert( nReserve>=0 && nReserve<=255 );
drh06f50212004-11-02 14:24:33 +00002163 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2164 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00002165 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002166 assert( !pBt->pPage1 && !pBt->pCursor );
drhb2eced52010-08-12 02:41:12 +00002167 pBt->pageSize = (u32)pageSize;
drhf7141992008-06-19 00:16:08 +00002168 freeTempSpace(pBt);
drh90f5ecb2004-07-22 01:19:35 +00002169 }
drhfa9601a2009-06-18 17:22:39 +00002170 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhf49661a2008-12-10 16:45:50 +00002171 pBt->usableSize = pBt->pageSize - (u16)nReserve;
drhce4869f2009-04-02 20:16:58 +00002172 if( iFix ) pBt->pageSizeFixed = 1;
drhd677b3d2007-08-20 22:48:41 +00002173 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00002174 return rc;
drh90f5ecb2004-07-22 01:19:35 +00002175}
2176
2177/*
2178** Return the currently defined page size
2179*/
danielk1977aef0bf62005-12-30 16:28:01 +00002180int sqlite3BtreeGetPageSize(Btree *p){
2181 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00002182}
drh7f751222009-03-17 22:33:00 +00002183
danbb2b4412011-04-06 17:54:31 +00002184#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh7f751222009-03-17 22:33:00 +00002185/*
2186** Return the number of bytes of space at the end of every page that
2187** are intentually left unused. This is the "reserved" space that is
2188** sometimes used by extensions.
2189*/
danielk1977aef0bf62005-12-30 16:28:01 +00002190int sqlite3BtreeGetReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002191 int n;
2192 sqlite3BtreeEnter(p);
2193 n = p->pBt->pageSize - p->pBt->usableSize;
2194 sqlite3BtreeLeave(p);
2195 return n;
drh2011d5f2004-07-22 02:40:37 +00002196}
drhf8e632b2007-05-08 14:51:36 +00002197
2198/*
2199** Set the maximum page count for a database if mxPage is positive.
2200** No changes are made if mxPage is 0 or negative.
2201** Regardless of the value of mxPage, return the maximum page count.
2202*/
2203int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00002204 int n;
2205 sqlite3BtreeEnter(p);
2206 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
2207 sqlite3BtreeLeave(p);
2208 return n;
drhf8e632b2007-05-08 14:51:36 +00002209}
drh5b47efa2010-02-12 18:18:39 +00002210
2211/*
2212** Set the secureDelete flag if newFlag is 0 or 1. If newFlag is -1,
2213** then make no changes. Always return the value of the secureDelete
2214** setting after the change.
2215*/
2216int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
2217 int b;
drhaf034ed2010-02-12 19:46:26 +00002218 if( p==0 ) return 0;
drh5b47efa2010-02-12 18:18:39 +00002219 sqlite3BtreeEnter(p);
2220 if( newFlag>=0 ){
2221 p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
2222 }
2223 b = p->pBt->secureDelete;
2224 sqlite3BtreeLeave(p);
2225 return b;
2226}
danielk1977576ec6b2005-01-21 11:55:25 +00002227#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00002228
2229/*
danielk1977951af802004-11-05 15:45:09 +00002230** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
2231** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
2232** is disabled. The default value for the auto-vacuum property is
2233** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
2234*/
danielk1977aef0bf62005-12-30 16:28:01 +00002235int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00002236#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002237 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00002238#else
danielk1977dddbcdc2007-04-26 14:42:34 +00002239 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002240 int rc = SQLITE_OK;
drh076d4662009-02-18 20:31:18 +00002241 u8 av = (u8)autoVacuum;
drhd677b3d2007-08-20 22:48:41 +00002242
2243 sqlite3BtreeEnter(p);
drh076d4662009-02-18 20:31:18 +00002244 if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002245 rc = SQLITE_READONLY;
2246 }else{
drh076d4662009-02-18 20:31:18 +00002247 pBt->autoVacuum = av ?1:0;
2248 pBt->incrVacuum = av==2 ?1:0;
danielk1977951af802004-11-05 15:45:09 +00002249 }
drhd677b3d2007-08-20 22:48:41 +00002250 sqlite3BtreeLeave(p);
2251 return rc;
danielk1977951af802004-11-05 15:45:09 +00002252#endif
2253}
2254
2255/*
2256** Return the value of the 'auto-vacuum' property. If auto-vacuum is
2257** enabled 1 is returned. Otherwise 0.
2258*/
danielk1977aef0bf62005-12-30 16:28:01 +00002259int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00002260#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002261 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00002262#else
drhd677b3d2007-08-20 22:48:41 +00002263 int rc;
2264 sqlite3BtreeEnter(p);
2265 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00002266 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
2267 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
2268 BTREE_AUTOVACUUM_INCR
2269 );
drhd677b3d2007-08-20 22:48:41 +00002270 sqlite3BtreeLeave(p);
2271 return rc;
danielk1977951af802004-11-05 15:45:09 +00002272#endif
2273}
2274
2275
2276/*
drha34b6762004-05-07 13:30:42 +00002277** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00002278** also acquire a readlock on that file.
2279**
2280** SQLITE_OK is returned on success. If the file is not a
2281** well-formed database file, then SQLITE_CORRUPT is returned.
2282** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00002283** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00002284*/
danielk1977aef0bf62005-12-30 16:28:01 +00002285static int lockBtree(BtShared *pBt){
drhc2a4bab2010-04-02 12:46:45 +00002286 int rc; /* Result code from subfunctions */
2287 MemPage *pPage1; /* Page 1 of the database file */
2288 int nPage; /* Number of pages in the database */
2289 int nPageFile = 0; /* Number of pages in the database file */
2290 int nPageHeader; /* Number of pages in the database according to hdr */
drhd677b3d2007-08-20 22:48:41 +00002291
drh1fee73e2007-08-29 04:00:57 +00002292 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977295dc102009-04-01 19:07:03 +00002293 assert( pBt->pPage1==0 );
danielk197789bc4bc2009-07-21 19:25:24 +00002294 rc = sqlite3PagerSharedLock(pBt->pPager);
2295 if( rc!=SQLITE_OK ) return rc;
danielk197730548662009-07-09 05:07:37 +00002296 rc = btreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00002297 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00002298
2299 /* Do some checking to help insure the file we opened really is
2300 ** a valid database file.
2301 */
drhc2a4bab2010-04-02 12:46:45 +00002302 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
drh8fb8b532010-08-14 17:12:04 +00002303 sqlite3PagerPagecount(pBt->pPager, &nPageFile);
drhb28e59b2010-06-17 02:13:39 +00002304 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
drhc2a4bab2010-04-02 12:46:45 +00002305 nPage = nPageFile;
drh97b59a52010-03-31 02:31:33 +00002306 }
2307 if( nPage>0 ){
drh43b18e12010-08-17 19:40:08 +00002308 u32 pageSize;
2309 u32 usableSize;
drhb6f41482004-05-14 01:58:11 +00002310 u8 *page1 = pPage1->aData;
danielk1977ad0132d2008-06-07 08:58:22 +00002311 rc = SQLITE_NOTADB;
drhb6f41482004-05-14 01:58:11 +00002312 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00002313 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00002314 }
dan5cf53532010-05-01 16:40:20 +00002315
2316#ifdef SQLITE_OMIT_WAL
2317 if( page1[18]>1 ){
2318 pBt->readOnly = 1;
2319 }
2320 if( page1[19]>1 ){
2321 goto page1_init_failed;
2322 }
2323#else
dane04dc882010-04-20 18:53:15 +00002324 if( page1[18]>2 ){
drh309169a2007-04-24 17:27:51 +00002325 pBt->readOnly = 1;
2326 }
dane04dc882010-04-20 18:53:15 +00002327 if( page1[19]>2 ){
drhb6f41482004-05-14 01:58:11 +00002328 goto page1_init_failed;
2329 }
drhe5ae5732008-06-15 02:51:47 +00002330
dana470aeb2010-04-21 11:43:38 +00002331 /* If the write version is set to 2, this database should be accessed
2332 ** in WAL mode. If the log is not already open, open it now. Then
2333 ** return SQLITE_OK and return without populating BtShared.pPage1.
2334 ** The caller detects this and calls this function again. This is
2335 ** required as the version of page 1 currently in the page1 buffer
2336 ** may not be the latest version - there may be a newer one in the log
2337 ** file.
2338 */
danb9780022010-04-21 18:37:57 +00002339 if( page1[19]==2 && pBt->doNotUseWAL==0 ){
dane04dc882010-04-20 18:53:15 +00002340 int isOpen = 0;
drh7ed91f22010-04-29 22:34:07 +00002341 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
dane04dc882010-04-20 18:53:15 +00002342 if( rc!=SQLITE_OK ){
2343 goto page1_init_failed;
2344 }else if( isOpen==0 ){
2345 releasePage(pPage1);
2346 return SQLITE_OK;
2347 }
dan8b5444b2010-04-27 14:37:47 +00002348 rc = SQLITE_NOTADB;
dane04dc882010-04-20 18:53:15 +00002349 }
dan5cf53532010-05-01 16:40:20 +00002350#endif
dane04dc882010-04-20 18:53:15 +00002351
drhe5ae5732008-06-15 02:51:47 +00002352 /* The maximum embedded fraction must be exactly 25%. And the minimum
2353 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
2354 ** The original design allowed these amounts to vary, but as of
2355 ** version 3.6.0, we require them to be fixed.
2356 */
2357 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
2358 goto page1_init_failed;
2359 }
drhb2eced52010-08-12 02:41:12 +00002360 pageSize = (page1[16]<<8) | (page1[17]<<16);
2361 if( ((pageSize-1)&pageSize)!=0
2362 || pageSize>SQLITE_MAX_PAGE_SIZE
2363 || pageSize<=256
drh7dc385e2007-09-06 23:39:36 +00002364 ){
drh07d183d2005-05-01 22:52:42 +00002365 goto page1_init_failed;
2366 }
2367 assert( (pageSize & 7)==0 );
danielk1977f653d782008-03-20 11:04:21 +00002368 usableSize = pageSize - page1[20];
shaneh1df2db72010-08-18 02:28:48 +00002369 if( (u32)pageSize!=pBt->pageSize ){
danielk1977f653d782008-03-20 11:04:21 +00002370 /* After reading the first page of the database assuming a page size
2371 ** of BtShared.pageSize, we have discovered that the page-size is
2372 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
2373 ** zero and return SQLITE_OK. The caller will call this function
2374 ** again with the correct page-size.
2375 */
2376 releasePage(pPage1);
drh43b18e12010-08-17 19:40:08 +00002377 pBt->usableSize = usableSize;
2378 pBt->pageSize = pageSize;
drhf7141992008-06-19 00:16:08 +00002379 freeTempSpace(pBt);
drhfa9601a2009-06-18 17:22:39 +00002380 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
2381 pageSize-usableSize);
drh5e483932009-07-10 16:51:30 +00002382 return rc;
danielk1977f653d782008-03-20 11:04:21 +00002383 }
danecac6702011-02-09 18:19:20 +00002384 if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
drhc2a4bab2010-04-02 12:46:45 +00002385 rc = SQLITE_CORRUPT_BKPT;
2386 goto page1_init_failed;
2387 }
drhb33e1b92009-06-18 11:29:20 +00002388 if( usableSize<480 ){
drhb6f41482004-05-14 01:58:11 +00002389 goto page1_init_failed;
2390 }
drh43b18e12010-08-17 19:40:08 +00002391 pBt->pageSize = pageSize;
2392 pBt->usableSize = usableSize;
drh057cd3a2005-02-15 16:23:02 +00002393#ifndef SQLITE_OMIT_AUTOVACUUM
2394 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00002395 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00002396#endif
drh306dc212001-05-21 13:45:10 +00002397 }
drhb6f41482004-05-14 01:58:11 +00002398
2399 /* maxLocal is the maximum amount of payload to store locally for
2400 ** a cell. Make sure it is small enough so that at least minFanout
2401 ** cells can will fit on one page. We assume a 10-byte page header.
2402 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00002403 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00002404 ** 4-byte child pointer
2405 ** 9-byte nKey value
2406 ** 4-byte nData value
2407 ** 4-byte overflow page pointer
drhe22e03e2010-08-18 21:19:03 +00002408 ** So a cell consists of a 2-byte pointer, a header which is as much as
drh43605152004-05-29 21:46:49 +00002409 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
2410 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00002411 */
shaneh1df2db72010-08-18 02:28:48 +00002412 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
2413 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
2414 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
2415 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
drh2e38c322004-09-03 18:38:44 +00002416 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00002417 pBt->pPage1 = pPage1;
drhdd3cd972010-03-27 17:12:36 +00002418 pBt->nPage = nPage;
drhb6f41482004-05-14 01:58:11 +00002419 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00002420
drh72f82862001-05-24 21:06:34 +00002421page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00002422 releasePage(pPage1);
2423 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00002424 return rc;
drh306dc212001-05-21 13:45:10 +00002425}
2426
2427/*
drhb8ca3072001-12-05 00:21:20 +00002428** If there are no outstanding cursors and we are not in the middle
2429** of a transaction but there is a read lock on the database, then
2430** this routine unrefs the first page of the database file which
2431** has the effect of releasing the read lock.
2432**
drhb8ca3072001-12-05 00:21:20 +00002433** If there is a transaction in progress, this routine is a no-op.
2434*/
danielk1977aef0bf62005-12-30 16:28:01 +00002435static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00002436 assert( sqlite3_mutex_held(pBt->mutex) );
danielk19771bc9ee92009-07-04 15:41:02 +00002437 assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
2438 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
danielk1977c1761e82009-06-25 09:40:03 +00002439 assert( pBt->pPage1->aData );
2440 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
2441 assert( pBt->pPage1->aData );
2442 releasePage(pBt->pPage1);
drh3aac2dd2004-04-26 14:10:20 +00002443 pBt->pPage1 = 0;
drhb8ca3072001-12-05 00:21:20 +00002444 }
2445}
2446
2447/*
drhe39f2f92009-07-23 01:43:59 +00002448** If pBt points to an empty file then convert that empty file
2449** into a new empty database by initializing the first page of
2450** the database.
drh8b2f49b2001-06-08 00:21:52 +00002451*/
danielk1977aef0bf62005-12-30 16:28:01 +00002452static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00002453 MemPage *pP1;
2454 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00002455 int rc;
drhd677b3d2007-08-20 22:48:41 +00002456
drh1fee73e2007-08-29 04:00:57 +00002457 assert( sqlite3_mutex_held(pBt->mutex) );
drhdd3cd972010-03-27 17:12:36 +00002458 if( pBt->nPage>0 ){
2459 return SQLITE_OK;
danielk1977ad0132d2008-06-07 08:58:22 +00002460 }
drh3aac2dd2004-04-26 14:10:20 +00002461 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00002462 assert( pP1!=0 );
2463 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00002464 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00002465 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00002466 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
2467 assert( sizeof(zMagicHeader)==16 );
shaneh1df2db72010-08-18 02:28:48 +00002468 data[16] = (u8)((pBt->pageSize>>8)&0xff);
2469 data[17] = (u8)((pBt->pageSize>>16)&0xff);
drh9e572e62004-04-23 23:43:10 +00002470 data[18] = 1;
2471 data[19] = 1;
drhf49661a2008-12-10 16:45:50 +00002472 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
2473 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
drhe5ae5732008-06-15 02:51:47 +00002474 data[21] = 64;
2475 data[22] = 32;
2476 data[23] = 32;
drhb6f41482004-05-14 01:58:11 +00002477 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00002478 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00002479 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00002480#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002481 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00002482 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00002483 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00002484 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00002485#endif
drhdd3cd972010-03-27 17:12:36 +00002486 pBt->nPage = 1;
2487 data[31] = 1;
drh8b2f49b2001-06-08 00:21:52 +00002488 return SQLITE_OK;
2489}
2490
2491/*
danielk1977ee5741e2004-05-31 10:01:34 +00002492** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00002493** is started if the second argument is nonzero, otherwise a read-
2494** transaction. If the second argument is 2 or more and exclusive
2495** transaction is started, meaning that no other process is allowed
2496** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00002497** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00002498** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00002499**
danielk1977ee5741e2004-05-31 10:01:34 +00002500** A write-transaction must be started before attempting any
2501** changes to the database. None of the following routines
2502** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00002503**
drh23e11ca2004-05-04 17:27:28 +00002504** sqlite3BtreeCreateTable()
2505** sqlite3BtreeCreateIndex()
2506** sqlite3BtreeClearTable()
2507** sqlite3BtreeDropTable()
2508** sqlite3BtreeInsert()
2509** sqlite3BtreeDelete()
2510** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00002511**
drhb8ef32c2005-03-14 02:01:49 +00002512** If an initial attempt to acquire the lock fails because of lock contention
2513** and the database was previously unlocked, then invoke the busy handler
2514** if there is one. But if there was previously a read-lock, do not
2515** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
2516** returned when there is already a read-lock in order to avoid a deadlock.
2517**
2518** Suppose there are two processes A and B. A has a read lock and B has
2519** a reserved lock. B tries to promote to exclusive but is blocked because
2520** of A's read lock. A tries to promote to reserved but is blocked by B.
2521** One or the other of the two processes must give way or there can be
2522** no progress. By returning SQLITE_BUSY and not invoking the busy callback
2523** when A already has a read lock, we encourage A to give up and let B
2524** proceed.
drha059ad02001-04-17 20:09:11 +00002525*/
danielk1977aef0bf62005-12-30 16:28:01 +00002526int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
danielk1977404ca072009-03-16 13:19:36 +00002527 sqlite3 *pBlock = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00002528 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00002529 int rc = SQLITE_OK;
2530
drhd677b3d2007-08-20 22:48:41 +00002531 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002532 btreeIntegrity(p);
2533
danielk1977ee5741e2004-05-31 10:01:34 +00002534 /* If the btree is already in a write-transaction, or it
2535 ** is already in a read-transaction and a read-transaction
2536 ** is requested, this is a no-op.
2537 */
danielk1977aef0bf62005-12-30 16:28:01 +00002538 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00002539 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002540 }
drhb8ef32c2005-03-14 02:01:49 +00002541
2542 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00002543 if( pBt->readOnly && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00002544 rc = SQLITE_READONLY;
2545 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002546 }
2547
danielk1977404ca072009-03-16 13:19:36 +00002548#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +00002549 /* If another database handle has already opened a write transaction
2550 ** on this shared-btree structure and a second write transaction is
danielk1977404ca072009-03-16 13:19:36 +00002551 ** requested, return SQLITE_LOCKED.
danielk1977aef0bf62005-12-30 16:28:01 +00002552 */
danielk1977404ca072009-03-16 13:19:36 +00002553 if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
2554 pBlock = pBt->pWriter->db;
2555 }else if( wrflag>1 ){
danielk1977641b0f42007-12-21 04:47:25 +00002556 BtLock *pIter;
2557 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
2558 if( pIter->pBtree!=p ){
danielk1977404ca072009-03-16 13:19:36 +00002559 pBlock = pIter->pBtree->db;
2560 break;
danielk1977641b0f42007-12-21 04:47:25 +00002561 }
2562 }
2563 }
danielk1977404ca072009-03-16 13:19:36 +00002564 if( pBlock ){
2565 sqlite3ConnectionBlocked(p->db, pBlock);
2566 rc = SQLITE_LOCKED_SHAREDCACHE;
2567 goto trans_begun;
2568 }
danielk1977641b0f42007-12-21 04:47:25 +00002569#endif
2570
danielk1977602b4662009-07-02 07:47:33 +00002571 /* Any read-only or read-write transaction implies a read-lock on
2572 ** page 1. So if some other shared-cache client already has a write-lock
2573 ** on page 1, the transaction cannot be opened. */
drh4c301aa2009-07-15 17:25:45 +00002574 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
2575 if( SQLITE_OK!=rc ) goto trans_begun;
danielk1977602b4662009-07-02 07:47:33 +00002576
shaneh5eba1f62010-07-02 17:05:03 +00002577 pBt->initiallyEmpty = (u8)(pBt->nPage==0);
drhb8ef32c2005-03-14 02:01:49 +00002578 do {
danielk1977295dc102009-04-01 19:07:03 +00002579 /* Call lockBtree() until either pBt->pPage1 is populated or
2580 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
2581 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
2582 ** reading page 1 it discovers that the page-size of the database
2583 ** file is not pBt->pageSize. In this case lockBtree() will update
2584 ** pBt->pageSize to the page-size of the file on disk.
2585 */
2586 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
drh309169a2007-04-24 17:27:51 +00002587
drhb8ef32c2005-03-14 02:01:49 +00002588 if( rc==SQLITE_OK && wrflag ){
drh309169a2007-04-24 17:27:51 +00002589 if( pBt->readOnly ){
2590 rc = SQLITE_READONLY;
2591 }else{
danielk1977d8293352009-04-30 09:10:37 +00002592 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
drh309169a2007-04-24 17:27:51 +00002593 if( rc==SQLITE_OK ){
2594 rc = newDatabase(pBt);
2595 }
drhb8ef32c2005-03-14 02:01:49 +00002596 }
2597 }
2598
danielk1977bd434552009-03-18 10:33:00 +00002599 if( rc!=SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00002600 unlockBtreeIfUnused(pBt);
2601 }
danf9b76712010-06-01 14:12:45 +00002602 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
danielk19771ceedd32008-11-19 10:22:33 +00002603 btreeInvokeBusyHandler(pBt) );
danielk1977aef0bf62005-12-30 16:28:01 +00002604
2605 if( rc==SQLITE_OK ){
2606 if( p->inTrans==TRANS_NONE ){
2607 pBt->nTransaction++;
danielk1977602b4662009-07-02 07:47:33 +00002608#ifndef SQLITE_OMIT_SHARED_CACHE
2609 if( p->sharable ){
2610 assert( p->lock.pBtree==p && p->lock.iTable==1 );
2611 p->lock.eLock = READ_LOCK;
2612 p->lock.pNext = pBt->pLock;
2613 pBt->pLock = &p->lock;
2614 }
2615#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002616 }
2617 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
2618 if( p->inTrans>pBt->inTransaction ){
2619 pBt->inTransaction = p->inTrans;
2620 }
danielk1977404ca072009-03-16 13:19:36 +00002621 if( wrflag ){
dan59257dc2010-08-04 11:34:31 +00002622 MemPage *pPage1 = pBt->pPage1;
2623#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977404ca072009-03-16 13:19:36 +00002624 assert( !pBt->pWriter );
2625 pBt->pWriter = p;
shaneca18d202009-03-23 02:34:32 +00002626 pBt->isExclusive = (u8)(wrflag>1);
danielk1977641b0f42007-12-21 04:47:25 +00002627#endif
dan59257dc2010-08-04 11:34:31 +00002628
2629 /* If the db-size header field is incorrect (as it may be if an old
2630 ** client has been writing the database file), update it now. Doing
2631 ** this sooner rather than later means the database size can safely
2632 ** re-read the database size from page 1 if a savepoint or transaction
2633 ** rollback occurs within the transaction.
2634 */
2635 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
2636 rc = sqlite3PagerWrite(pPage1->pDbPage);
2637 if( rc==SQLITE_OK ){
2638 put4byte(&pPage1->aData[28], pBt->nPage);
2639 }
2640 }
2641 }
danielk1977aef0bf62005-12-30 16:28:01 +00002642 }
2643
drhd677b3d2007-08-20 22:48:41 +00002644
2645trans_begun:
danielk1977fd7f0452008-12-17 17:30:26 +00002646 if( rc==SQLITE_OK && wrflag ){
danielk197712dd5492008-12-18 15:45:07 +00002647 /* This call makes sure that the pager has the correct number of
2648 ** open savepoints. If the second parameter is greater than 0 and
2649 ** the sub-journal is not already open, then it will be opened here.
2650 */
danielk1977fd7f0452008-12-17 17:30:26 +00002651 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
2652 }
danielk197712dd5492008-12-18 15:45:07 +00002653
danielk1977aef0bf62005-12-30 16:28:01 +00002654 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002655 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00002656 return rc;
drha059ad02001-04-17 20:09:11 +00002657}
2658
danielk1977687566d2004-11-02 12:56:41 +00002659#ifndef SQLITE_OMIT_AUTOVACUUM
2660
2661/*
2662** Set the pointer-map entries for all children of page pPage. Also, if
2663** pPage contains cells that point to overflow pages, set the pointer
2664** map entries for the overflow pages as well.
2665*/
2666static int setChildPtrmaps(MemPage *pPage){
2667 int i; /* Counter variable */
2668 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00002669 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00002670 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00002671 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002672 Pgno pgno = pPage->pgno;
2673
drh1fee73e2007-08-29 04:00:57 +00002674 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197730548662009-07-09 05:07:37 +00002675 rc = btreeInitPage(pPage);
danielk19772df71c72007-05-24 07:22:42 +00002676 if( rc!=SQLITE_OK ){
2677 goto set_child_ptrmaps_out;
2678 }
danielk1977687566d2004-11-02 12:56:41 +00002679 nCell = pPage->nCell;
2680
2681 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002682 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002683
drh98add2e2009-07-20 17:11:49 +00002684 ptrmapPutOvflPtr(pPage, pCell, &rc);
danielk197726836652005-01-17 01:33:13 +00002685
danielk1977687566d2004-11-02 12:56:41 +00002686 if( !pPage->leaf ){
2687 Pgno childPgno = get4byte(pCell);
drh98add2e2009-07-20 17:11:49 +00002688 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00002689 }
2690 }
2691
2692 if( !pPage->leaf ){
2693 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh98add2e2009-07-20 17:11:49 +00002694 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00002695 }
2696
2697set_child_ptrmaps_out:
2698 pPage->isInit = isInitOrig;
2699 return rc;
2700}
2701
2702/*
drhf3aed592009-07-08 18:12:49 +00002703** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
2704** that it points to iTo. Parameter eType describes the type of pointer to
2705** be modified, as follows:
danielk1977687566d2004-11-02 12:56:41 +00002706**
2707** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
2708** page of pPage.
2709**
2710** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
2711** page pointed to by one of the cells on pPage.
2712**
2713** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
2714** overflow page in the list.
2715*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00002716static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00002717 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00002718 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977687566d2004-11-02 12:56:41 +00002719 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00002720 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00002721 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00002722 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002723 }
danielk1977f78fc082004-11-02 14:40:32 +00002724 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00002725 }else{
drhf49661a2008-12-10 16:45:50 +00002726 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002727 int i;
2728 int nCell;
2729
danielk197730548662009-07-09 05:07:37 +00002730 btreeInitPage(pPage);
danielk1977687566d2004-11-02 12:56:41 +00002731 nCell = pPage->nCell;
2732
danielk1977687566d2004-11-02 12:56:41 +00002733 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002734 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002735 if( eType==PTRMAP_OVERFLOW1 ){
2736 CellInfo info;
danielk197730548662009-07-09 05:07:37 +00002737 btreeParseCellPtr(pPage, pCell, &info);
danielk1977687566d2004-11-02 12:56:41 +00002738 if( info.iOverflow ){
2739 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
2740 put4byte(&pCell[info.iOverflow], iTo);
2741 break;
2742 }
2743 }
2744 }else{
2745 if( get4byte(pCell)==iFrom ){
2746 put4byte(pCell, iTo);
2747 break;
2748 }
2749 }
2750 }
2751
2752 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00002753 if( eType!=PTRMAP_BTREE ||
2754 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00002755 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002756 }
danielk1977687566d2004-11-02 12:56:41 +00002757 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
2758 }
2759
2760 pPage->isInit = isInitOrig;
2761 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002762 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002763}
2764
danielk1977003ba062004-11-04 02:57:33 +00002765
danielk19777701e812005-01-10 12:59:51 +00002766/*
2767** Move the open database page pDbPage to location iFreePage in the
2768** database. The pDbPage reference remains valid.
drhe64ca7b2009-07-16 18:21:17 +00002769**
2770** The isCommit flag indicates that there is no need to remember that
2771** the journal needs to be sync()ed before database page pDbPage->pgno
2772** can be written to. The caller has already promised not to write to that
2773** page.
danielk19777701e812005-01-10 12:59:51 +00002774*/
danielk1977003ba062004-11-04 02:57:33 +00002775static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00002776 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00002777 MemPage *pDbPage, /* Open page to move */
2778 u8 eType, /* Pointer map 'type' entry for pDbPage */
2779 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
danielk19774c999992008-07-16 18:17:55 +00002780 Pgno iFreePage, /* The location to move pDbPage to */
drhe64ca7b2009-07-16 18:21:17 +00002781 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
danielk1977003ba062004-11-04 02:57:33 +00002782){
2783 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
2784 Pgno iDbPage = pDbPage->pgno;
2785 Pager *pPager = pBt->pPager;
2786 int rc;
2787
danielk1977a0bf2652004-11-04 14:30:04 +00002788 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
2789 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00002790 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00002791 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00002792
drh85b623f2007-12-13 21:54:09 +00002793 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00002794 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
2795 iDbPage, iFreePage, iPtrPage, eType));
danielk19774c999992008-07-16 18:17:55 +00002796 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
danielk1977003ba062004-11-04 02:57:33 +00002797 if( rc!=SQLITE_OK ){
2798 return rc;
2799 }
2800 pDbPage->pgno = iFreePage;
2801
2802 /* If pDbPage was a btree-page, then it may have child pages and/or cells
2803 ** that point to overflow pages. The pointer map entries for all these
2804 ** pages need to be changed.
2805 **
2806 ** If pDbPage is an overflow page, then the first 4 bytes may store a
2807 ** pointer to a subsequent overflow page. If this is the case, then
2808 ** the pointer map needs to be updated for the subsequent overflow page.
2809 */
danielk1977a0bf2652004-11-04 14:30:04 +00002810 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00002811 rc = setChildPtrmaps(pDbPage);
2812 if( rc!=SQLITE_OK ){
2813 return rc;
2814 }
2815 }else{
2816 Pgno nextOvfl = get4byte(pDbPage->aData);
2817 if( nextOvfl!=0 ){
drh98add2e2009-07-20 17:11:49 +00002818 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
danielk1977003ba062004-11-04 02:57:33 +00002819 if( rc!=SQLITE_OK ){
2820 return rc;
2821 }
2822 }
2823 }
2824
2825 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
2826 ** that it points at iFreePage. Also fix the pointer map entry for
2827 ** iPtrPage.
2828 */
danielk1977a0bf2652004-11-04 14:30:04 +00002829 if( eType!=PTRMAP_ROOTPAGE ){
danielk197730548662009-07-09 05:07:37 +00002830 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00002831 if( rc!=SQLITE_OK ){
2832 return rc;
2833 }
danielk19773b8a05f2007-03-19 17:44:26 +00002834 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00002835 if( rc!=SQLITE_OK ){
2836 releasePage(pPtrPage);
2837 return rc;
2838 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002839 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00002840 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00002841 if( rc==SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +00002842 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
danielk1977fdb7cdb2005-01-17 02:12:18 +00002843 }
danielk1977003ba062004-11-04 02:57:33 +00002844 }
danielk1977003ba062004-11-04 02:57:33 +00002845 return rc;
2846}
2847
danielk1977dddbcdc2007-04-26 14:42:34 +00002848/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00002849static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00002850
2851/*
danielk1977dddbcdc2007-04-26 14:42:34 +00002852** Perform a single step of an incremental-vacuum. If successful,
2853** return SQLITE_OK. If there is no work to do (and therefore no
2854** point in calling this function again), return SQLITE_DONE.
2855**
2856** More specificly, this function attempts to re-organize the
2857** database so that the last page of the file currently in use
2858** is no longer in use.
2859**
drhea8ffdf2009-07-22 00:35:23 +00002860** If the nFin parameter is non-zero, this function assumes
danielk1977dddbcdc2007-04-26 14:42:34 +00002861** that the caller will keep calling incrVacuumStep() until
2862** it returns SQLITE_DONE or an error, and that nFin is the
2863** number of pages the database file will contain after this
drhea8ffdf2009-07-22 00:35:23 +00002864** process is complete. If nFin is zero, it is assumed that
2865** incrVacuumStep() will be called a finite amount of times
2866** which may or may not empty the freelist. A full autovacuum
2867** has nFin>0. A "PRAGMA incremental_vacuum" has nFin==0.
danielk1977dddbcdc2007-04-26 14:42:34 +00002868*/
danielk19773460d192008-12-27 15:23:13 +00002869static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
danielk1977dddbcdc2007-04-26 14:42:34 +00002870 Pgno nFreeList; /* Number of pages still on the free-list */
drhdd3cd972010-03-27 17:12:36 +00002871 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002872
drh1fee73e2007-08-29 04:00:57 +00002873 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977fa542f12009-04-02 18:28:08 +00002874 assert( iLastPg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00002875
2876 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
danielk1977dddbcdc2007-04-26 14:42:34 +00002877 u8 eType;
2878 Pgno iPtrPage;
2879
2880 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977fa542f12009-04-02 18:28:08 +00002881 if( nFreeList==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00002882 return SQLITE_DONE;
2883 }
2884
2885 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
2886 if( rc!=SQLITE_OK ){
2887 return rc;
2888 }
2889 if( eType==PTRMAP_ROOTPAGE ){
2890 return SQLITE_CORRUPT_BKPT;
2891 }
2892
2893 if( eType==PTRMAP_FREEPAGE ){
2894 if( nFin==0 ){
2895 /* Remove the page from the files free-list. This is not required
danielk19774ef24492007-05-23 09:52:41 +00002896 ** if nFin is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00002897 ** truncated to zero after this function returns, so it doesn't
2898 ** matter if it still contains some garbage entries.
2899 */
2900 Pgno iFreePg;
2901 MemPage *pFreePg;
2902 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
2903 if( rc!=SQLITE_OK ){
2904 return rc;
2905 }
2906 assert( iFreePg==iLastPg );
2907 releasePage(pFreePg);
2908 }
2909 } else {
2910 Pgno iFreePg; /* Index of free page to move pLastPg to */
2911 MemPage *pLastPg;
2912
danielk197730548662009-07-09 05:07:37 +00002913 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002914 if( rc!=SQLITE_OK ){
2915 return rc;
2916 }
2917
danielk1977b4626a32007-04-28 15:47:43 +00002918 /* If nFin is zero, this loop runs exactly once and page pLastPg
2919 ** is swapped with the first free page pulled off the free list.
2920 **
2921 ** On the other hand, if nFin is greater than zero, then keep
2922 ** looping until a free-page located within the first nFin pages
2923 ** of the file is found.
2924 */
danielk1977dddbcdc2007-04-26 14:42:34 +00002925 do {
2926 MemPage *pFreePg;
2927 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
2928 if( rc!=SQLITE_OK ){
2929 releasePage(pLastPg);
2930 return rc;
2931 }
2932 releasePage(pFreePg);
2933 }while( nFin!=0 && iFreePg>nFin );
2934 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00002935
2936 rc = sqlite3PagerWrite(pLastPg->pDbPage);
danielk1977662278e2007-11-05 15:30:12 +00002937 if( rc==SQLITE_OK ){
danielk19774c999992008-07-16 18:17:55 +00002938 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
danielk1977662278e2007-11-05 15:30:12 +00002939 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002940 releasePage(pLastPg);
2941 if( rc!=SQLITE_OK ){
2942 return rc;
danielk1977662278e2007-11-05 15:30:12 +00002943 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002944 }
2945 }
2946
danielk19773460d192008-12-27 15:23:13 +00002947 if( nFin==0 ){
2948 iLastPg--;
2949 while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
danielk1977f4027782009-03-30 18:50:04 +00002950 if( PTRMAP_ISPAGE(pBt, iLastPg) ){
2951 MemPage *pPg;
drhdd3cd972010-03-27 17:12:36 +00002952 rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
danielk1977f4027782009-03-30 18:50:04 +00002953 if( rc!=SQLITE_OK ){
2954 return rc;
2955 }
2956 rc = sqlite3PagerWrite(pPg->pDbPage);
2957 releasePage(pPg);
2958 if( rc!=SQLITE_OK ){
2959 return rc;
2960 }
2961 }
danielk19773460d192008-12-27 15:23:13 +00002962 iLastPg--;
2963 }
2964 sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
drhdd3cd972010-03-27 17:12:36 +00002965 pBt->nPage = iLastPg;
danielk1977dddbcdc2007-04-26 14:42:34 +00002966 }
2967 return SQLITE_OK;
2968}
2969
2970/*
2971** A write-transaction must be opened before calling this function.
2972** It performs a single unit of work towards an incremental vacuum.
2973**
2974** If the incremental vacuum is finished after this function has run,
shanebe217792009-03-05 04:20:31 +00002975** SQLITE_DONE is returned. If it is not finished, but no error occurred,
danielk1977dddbcdc2007-04-26 14:42:34 +00002976** SQLITE_OK is returned. Otherwise an SQLite error code.
2977*/
2978int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002979 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002980 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002981
2982 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00002983 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
2984 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002985 rc = SQLITE_DONE;
2986 }else{
2987 invalidateAllOverflowCache(pBt);
drhb1299152010-03-30 22:58:33 +00002988 rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
drhdd3cd972010-03-27 17:12:36 +00002989 if( rc==SQLITE_OK ){
2990 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
2991 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
2992 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002993 }
drhd677b3d2007-08-20 22:48:41 +00002994 sqlite3BtreeLeave(p);
2995 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002996}
2997
2998/*
danielk19773b8a05f2007-03-19 17:44:26 +00002999** This routine is called prior to sqlite3PagerCommit when a transaction
danielk1977687566d2004-11-02 12:56:41 +00003000** is commited for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00003001**
3002** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
3003** the database file should be truncated to during the commit process.
3004** i.e. the database has been reorganized so that only the first *pnTrunc
3005** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00003006*/
danielk19773460d192008-12-27 15:23:13 +00003007static int autoVacuumCommit(BtShared *pBt){
danielk1977dddbcdc2007-04-26 14:42:34 +00003008 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00003009 Pager *pPager = pBt->pPager;
drhf94a1732008-09-30 17:18:17 +00003010 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00003011
drh1fee73e2007-08-29 04:00:57 +00003012 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00003013 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00003014 assert(pBt->autoVacuum);
3015 if( !pBt->incrVacuum ){
drhea8ffdf2009-07-22 00:35:23 +00003016 Pgno nFin; /* Number of pages in database after autovacuuming */
3017 Pgno nFree; /* Number of pages on the freelist initially */
drh41d628c2009-07-11 17:04:08 +00003018 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
3019 Pgno iFree; /* The next page to be freed */
3020 int nEntry; /* Number of entries on one ptrmap page */
3021 Pgno nOrig; /* Database size before freeing */
danielk1977687566d2004-11-02 12:56:41 +00003022
drhb1299152010-03-30 22:58:33 +00003023 nOrig = btreePagecount(pBt);
danielk1977ef165ce2009-04-06 17:50:03 +00003024 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
3025 /* It is not possible to create a database for which the final page
3026 ** is either a pointer-map page or the pending-byte page. If one
3027 ** is encountered, this indicates corruption.
3028 */
danielk19773460d192008-12-27 15:23:13 +00003029 return SQLITE_CORRUPT_BKPT;
3030 }
danielk1977ef165ce2009-04-06 17:50:03 +00003031
danielk19773460d192008-12-27 15:23:13 +00003032 nFree = get4byte(&pBt->pPage1->aData[36]);
drh41d628c2009-07-11 17:04:08 +00003033 nEntry = pBt->usableSize/5;
3034 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
danielk19773460d192008-12-27 15:23:13 +00003035 nFin = nOrig - nFree - nPtrmap;
danielk1977ef165ce2009-04-06 17:50:03 +00003036 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
danielk19773460d192008-12-27 15:23:13 +00003037 nFin--;
3038 }
3039 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
3040 nFin--;
danielk1977dddbcdc2007-04-26 14:42:34 +00003041 }
drhc5e47ac2009-06-04 00:11:56 +00003042 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
danielk1977687566d2004-11-02 12:56:41 +00003043
danielk19773460d192008-12-27 15:23:13 +00003044 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
3045 rc = incrVacuumStep(pBt, nFin, iFree);
danielk1977dddbcdc2007-04-26 14:42:34 +00003046 }
danielk19773460d192008-12-27 15:23:13 +00003047 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
danielk19773460d192008-12-27 15:23:13 +00003048 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3049 put4byte(&pBt->pPage1->aData[32], 0);
3050 put4byte(&pBt->pPage1->aData[36], 0);
drhdd3cd972010-03-27 17:12:36 +00003051 put4byte(&pBt->pPage1->aData[28], nFin);
danielk19773460d192008-12-27 15:23:13 +00003052 sqlite3PagerTruncateImage(pBt->pPager, nFin);
drhdd3cd972010-03-27 17:12:36 +00003053 pBt->nPage = nFin;
danielk1977dddbcdc2007-04-26 14:42:34 +00003054 }
3055 if( rc!=SQLITE_OK ){
3056 sqlite3PagerRollback(pPager);
3057 }
danielk1977687566d2004-11-02 12:56:41 +00003058 }
3059
danielk19773b8a05f2007-03-19 17:44:26 +00003060 assert( nRef==sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00003061 return rc;
3062}
danielk1977dddbcdc2007-04-26 14:42:34 +00003063
danielk1977a50d9aa2009-06-08 14:49:45 +00003064#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
3065# define setChildPtrmaps(x) SQLITE_OK
3066#endif
danielk1977687566d2004-11-02 12:56:41 +00003067
3068/*
drh80e35f42007-03-30 14:06:34 +00003069** This routine does the first phase of a two-phase commit. This routine
3070** causes a rollback journal to be created (if it does not already exist)
3071** and populated with enough information so that if a power loss occurs
3072** the database can be restored to its original state by playing back
3073** the journal. Then the contents of the journal are flushed out to
3074** the disk. After the journal is safely on oxide, the changes to the
3075** database are written into the database file and flushed to oxide.
3076** At the end of this call, the rollback journal still exists on the
3077** disk and we are still holding all locks, so the transaction has not
drh51898cf2009-04-19 20:51:06 +00003078** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
drh80e35f42007-03-30 14:06:34 +00003079** commit process.
3080**
3081** This call is a no-op if no write-transaction is currently active on pBt.
3082**
3083** Otherwise, sync the database file for the btree pBt. zMaster points to
3084** the name of a master journal file that should be written into the
3085** individual journal file, or is NULL, indicating no master journal file
3086** (single database transaction).
3087**
3088** When this is called, the master journal should already have been
3089** created, populated with this journal pointer and synced to disk.
3090**
3091** Once this is routine has returned, the only thing required to commit
3092** the write-transaction for this database file is to delete the journal.
3093*/
3094int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
3095 int rc = SQLITE_OK;
3096 if( p->inTrans==TRANS_WRITE ){
3097 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003098 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00003099#ifndef SQLITE_OMIT_AUTOVACUUM
3100 if( pBt->autoVacuum ){
danielk19773460d192008-12-27 15:23:13 +00003101 rc = autoVacuumCommit(pBt);
drh80e35f42007-03-30 14:06:34 +00003102 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00003103 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003104 return rc;
3105 }
3106 }
3107#endif
drh49b9d332009-01-02 18:10:42 +00003108 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
drhd677b3d2007-08-20 22:48:41 +00003109 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003110 }
3111 return rc;
3112}
3113
3114/*
danielk197794b30732009-07-02 17:21:57 +00003115** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
3116** at the conclusion of a transaction.
3117*/
3118static void btreeEndTransaction(Btree *p){
3119 BtShared *pBt = p->pBt;
danielk197794b30732009-07-02 17:21:57 +00003120 assert( sqlite3BtreeHoldsMutex(p) );
3121
danielk197794b30732009-07-02 17:21:57 +00003122 btreeClearHasContent(pBt);
danfa401de2009-10-16 14:55:03 +00003123 if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
3124 /* If there are other active statements that belong to this database
3125 ** handle, downgrade to a read-only transaction. The other statements
3126 ** may still be reading from the database. */
danielk197794b30732009-07-02 17:21:57 +00003127 downgradeAllSharedCacheTableLocks(p);
3128 p->inTrans = TRANS_READ;
3129 }else{
3130 /* If the handle had any kind of transaction open, decrement the
3131 ** transaction count of the shared btree. If the transaction count
3132 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
3133 ** call below will unlock the pager. */
3134 if( p->inTrans!=TRANS_NONE ){
3135 clearAllSharedCacheTableLocks(p);
3136 pBt->nTransaction--;
3137 if( 0==pBt->nTransaction ){
3138 pBt->inTransaction = TRANS_NONE;
3139 }
3140 }
3141
3142 /* Set the current transaction state to TRANS_NONE and unlock the
3143 ** pager if this call closed the only read or write transaction. */
3144 p->inTrans = TRANS_NONE;
3145 unlockBtreeIfUnused(pBt);
3146 }
3147
3148 btreeIntegrity(p);
3149}
3150
3151/*
drh2aa679f2001-06-25 02:11:07 +00003152** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00003153**
drh6e345992007-03-30 11:12:08 +00003154** This routine implements the second phase of a 2-phase commit. The
drh51898cf2009-04-19 20:51:06 +00003155** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
3156** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
3157** routine did all the work of writing information out to disk and flushing the
drh6e345992007-03-30 11:12:08 +00003158** contents so that they are written onto the disk platter. All this
drh51898cf2009-04-19 20:51:06 +00003159** routine has to do is delete or truncate or zero the header in the
3160** the rollback journal (which causes the transaction to commit) and
3161** drop locks.
drh6e345992007-03-30 11:12:08 +00003162**
dan60939d02011-03-29 15:40:55 +00003163** Normally, if an error occurs while the pager layer is attempting to
3164** finalize the underlying journal file, this function returns an error and
3165** the upper layer will attempt a rollback. However, if the second argument
3166** is non-zero then this b-tree transaction is part of a multi-file
3167** transaction. In this case, the transaction has already been committed
3168** (by deleting a master journal file) and the caller will ignore this
3169** functions return code. So, even if an error occurs in the pager layer,
3170** reset the b-tree objects internal state to indicate that the write
3171** transaction has been closed. This is quite safe, as the pager will have
3172** transitioned to the error state.
3173**
drh5e00f6c2001-09-13 13:46:56 +00003174** This will release the write lock on the database file. If there
3175** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00003176*/
dan60939d02011-03-29 15:40:55 +00003177int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
danielk1977aef0bf62005-12-30 16:28:01 +00003178
drh075ed302010-10-14 01:17:30 +00003179 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003180 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003181 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003182
3183 /* If the handle has a write-transaction open, commit the shared-btrees
3184 ** transaction and set the shared state to TRANS_READ.
3185 */
3186 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00003187 int rc;
drh075ed302010-10-14 01:17:30 +00003188 BtShared *pBt = p->pBt;
danielk1977aef0bf62005-12-30 16:28:01 +00003189 assert( pBt->inTransaction==TRANS_WRITE );
3190 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00003191 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
dan60939d02011-03-29 15:40:55 +00003192 if( rc!=SQLITE_OK && bCleanup==0 ){
drhd677b3d2007-08-20 22:48:41 +00003193 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00003194 return rc;
3195 }
danielk1977aef0bf62005-12-30 16:28:01 +00003196 pBt->inTransaction = TRANS_READ;
danielk1977ee5741e2004-05-31 10:01:34 +00003197 }
danielk1977aef0bf62005-12-30 16:28:01 +00003198
danielk197794b30732009-07-02 17:21:57 +00003199 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00003200 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00003201 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003202}
3203
drh80e35f42007-03-30 14:06:34 +00003204/*
3205** Do both phases of a commit.
3206*/
3207int sqlite3BtreeCommit(Btree *p){
3208 int rc;
drhd677b3d2007-08-20 22:48:41 +00003209 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00003210 rc = sqlite3BtreeCommitPhaseOne(p, 0);
3211 if( rc==SQLITE_OK ){
dan60939d02011-03-29 15:40:55 +00003212 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
drh80e35f42007-03-30 14:06:34 +00003213 }
drhd677b3d2007-08-20 22:48:41 +00003214 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003215 return rc;
3216}
3217
danielk1977fbcd5852004-06-15 02:44:18 +00003218#ifndef NDEBUG
3219/*
3220** Return the number of write-cursors open on this handle. This is for use
3221** in assert() expressions, so it is only compiled if NDEBUG is not
3222** defined.
drhfb982642007-08-30 01:19:59 +00003223**
3224** For the purposes of this routine, a write-cursor is any cursor that
3225** is capable of writing to the databse. That means the cursor was
3226** originally opened for writing and the cursor has not be disabled
3227** by having its state changed to CURSOR_FAULT.
danielk1977fbcd5852004-06-15 02:44:18 +00003228*/
danielk1977aef0bf62005-12-30 16:28:01 +00003229static int countWriteCursors(BtShared *pBt){
danielk1977fbcd5852004-06-15 02:44:18 +00003230 BtCursor *pCur;
3231 int r = 0;
3232 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drhfb982642007-08-30 01:19:59 +00003233 if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
danielk1977fbcd5852004-06-15 02:44:18 +00003234 }
3235 return r;
3236}
3237#endif
3238
drhc39e0002004-05-07 23:50:57 +00003239/*
drhfb982642007-08-30 01:19:59 +00003240** This routine sets the state to CURSOR_FAULT and the error
3241** code to errCode for every cursor on BtShared that pBtree
3242** references.
3243**
3244** Every cursor is tripped, including cursors that belong
3245** to other database connections that happen to be sharing
3246** the cache with pBtree.
3247**
3248** This routine gets called when a rollback occurs.
3249** All cursors using the same cache must be tripped
3250** to prevent them from trying to use the btree after
3251** the rollback. The rollback may have deleted tables
3252** or moved root pages, so it is not sufficient to
3253** save the state of the cursor. The cursor must be
3254** invalidated.
3255*/
3256void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
3257 BtCursor *p;
3258 sqlite3BtreeEnter(pBtree);
3259 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
danielk1977bc2ca9e2008-11-13 14:28:28 +00003260 int i;
danielk1977be51a652008-10-08 17:58:48 +00003261 sqlite3BtreeClearCursor(p);
drhfb982642007-08-30 01:19:59 +00003262 p->eState = CURSOR_FAULT;
drh4c301aa2009-07-15 17:25:45 +00003263 p->skipNext = errCode;
danielk1977bc2ca9e2008-11-13 14:28:28 +00003264 for(i=0; i<=p->iPage; i++){
3265 releasePage(p->apPage[i]);
3266 p->apPage[i] = 0;
3267 }
drhfb982642007-08-30 01:19:59 +00003268 }
3269 sqlite3BtreeLeave(pBtree);
3270}
3271
3272/*
drhecdc7532001-09-23 02:35:53 +00003273** Rollback the transaction in progress. All cursors will be
3274** invalided by this operation. Any attempt to use a cursor
3275** that was open at the beginning of this operation will result
3276** in an error.
drh5e00f6c2001-09-13 13:46:56 +00003277**
3278** This will release the write lock on the database file. If there
3279** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00003280*/
danielk1977aef0bf62005-12-30 16:28:01 +00003281int sqlite3BtreeRollback(Btree *p){
danielk19778d34dfd2006-01-24 16:37:57 +00003282 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003283 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00003284 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00003285
drhd677b3d2007-08-20 22:48:41 +00003286 sqlite3BtreeEnter(p);
danielk19772b8c13e2006-01-24 14:21:24 +00003287 rc = saveAllCursors(pBt, 0, 0);
danielk19778d34dfd2006-01-24 16:37:57 +00003288#ifndef SQLITE_OMIT_SHARED_CACHE
danielk19772b8c13e2006-01-24 14:21:24 +00003289 if( rc!=SQLITE_OK ){
shanebe217792009-03-05 04:20:31 +00003290 /* This is a horrible situation. An IO or malloc() error occurred whilst
danielk19778d34dfd2006-01-24 16:37:57 +00003291 ** trying to save cursor positions. If this is an automatic rollback (as
3292 ** the result of a constraint, malloc() failure or IO error) then
3293 ** the cache may be internally inconsistent (not contain valid trees) so
3294 ** we cannot simply return the error to the caller. Instead, abort
3295 ** all queries that may be using any of the cursors that failed to save.
3296 */
drhfb982642007-08-30 01:19:59 +00003297 sqlite3BtreeTripAllCursors(p, rc);
danielk19772b8c13e2006-01-24 14:21:24 +00003298 }
danielk19778d34dfd2006-01-24 16:37:57 +00003299#endif
danielk1977aef0bf62005-12-30 16:28:01 +00003300 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003301
3302 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00003303 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00003304
danielk19778d34dfd2006-01-24 16:37:57 +00003305 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00003306 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00003307 if( rc2!=SQLITE_OK ){
3308 rc = rc2;
3309 }
3310
drh24cd67e2004-05-10 16:18:47 +00003311 /* The rollback may have destroyed the pPage1->aData value. So
danielk197730548662009-07-09 05:07:37 +00003312 ** call btreeGetPage() on page 1 again to make
drh16a9b832007-05-05 18:39:25 +00003313 ** sure pPage1->aData is set correctly. */
danielk197730548662009-07-09 05:07:37 +00003314 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh1f5b4672010-04-01 02:22:19 +00003315 int nPage = get4byte(28+(u8*)pPage1->aData);
3316 testcase( nPage==0 );
3317 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
3318 testcase( pBt->nPage!=nPage );
3319 pBt->nPage = nPage;
drh24cd67e2004-05-10 16:18:47 +00003320 releasePage(pPage1);
3321 }
danielk1977fbcd5852004-06-15 02:44:18 +00003322 assert( countWriteCursors(pBt)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00003323 pBt->inTransaction = TRANS_READ;
drh24cd67e2004-05-10 16:18:47 +00003324 }
danielk1977aef0bf62005-12-30 16:28:01 +00003325
danielk197794b30732009-07-02 17:21:57 +00003326 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00003327 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00003328 return rc;
3329}
3330
3331/*
danielk1977bd434552009-03-18 10:33:00 +00003332** Start a statement subtransaction. The subtransaction can can be rolled
3333** back independently of the main transaction. You must start a transaction
3334** before starting a subtransaction. The subtransaction is ended automatically
3335** if the main transaction commits or rolls back.
drhab01f612004-05-22 02:55:23 +00003336**
3337** Statement subtransactions are used around individual SQL statements
3338** that are contained within a BEGIN...COMMIT block. If a constraint
3339** error occurs within the statement, the effect of that one statement
3340** can be rolled back without having to rollback the entire transaction.
danielk1977bd434552009-03-18 10:33:00 +00003341**
3342** A statement sub-transaction is implemented as an anonymous savepoint. The
3343** value passed as the second parameter is the total number of savepoints,
3344** including the new anonymous savepoint, open on the B-Tree. i.e. if there
3345** are no active savepoints and no other statement-transactions open,
3346** iStatement is 1. This anonymous savepoint can be released or rolled back
3347** using the sqlite3BtreeSavepoint() function.
drh663fc632002-02-02 18:49:19 +00003348*/
danielk1977bd434552009-03-18 10:33:00 +00003349int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
drh663fc632002-02-02 18:49:19 +00003350 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003351 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003352 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00003353 assert( p->inTrans==TRANS_WRITE );
drh64022502009-01-09 14:11:04 +00003354 assert( pBt->readOnly==0 );
danielk1977bd434552009-03-18 10:33:00 +00003355 assert( iStatement>0 );
3356 assert( iStatement>p->db->nSavepoint );
drh5e0ccc22010-03-29 19:36:52 +00003357 assert( pBt->inTransaction==TRANS_WRITE );
3358 /* At the pager level, a statement transaction is a savepoint with
3359 ** an index greater than all savepoints created explicitly using
3360 ** SQL statements. It is illegal to open, release or rollback any
3361 ** such savepoints while the statement transaction savepoint is active.
3362 */
3363 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
drhd677b3d2007-08-20 22:48:41 +00003364 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00003365 return rc;
3366}
3367
3368/*
danielk1977fd7f0452008-12-17 17:30:26 +00003369** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
3370** or SAVEPOINT_RELEASE. This function either releases or rolls back the
danielk197712dd5492008-12-18 15:45:07 +00003371** savepoint identified by parameter iSavepoint, depending on the value
3372** of op.
3373**
3374** Normally, iSavepoint is greater than or equal to zero. However, if op is
3375** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
3376** contents of the entire transaction are rolled back. This is different
3377** from a normal transaction rollback, as no locks are released and the
3378** transaction remains open.
danielk1977fd7f0452008-12-17 17:30:26 +00003379*/
3380int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
3381 int rc = SQLITE_OK;
3382 if( p && p->inTrans==TRANS_WRITE ){
3383 BtShared *pBt = p->pBt;
danielk1977fd7f0452008-12-17 17:30:26 +00003384 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
3385 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
3386 sqlite3BtreeEnter(p);
danielk1977fd7f0452008-12-17 17:30:26 +00003387 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
drh9f0bbf92009-01-02 21:08:09 +00003388 if( rc==SQLITE_OK ){
drh25a80ad2010-03-29 21:13:12 +00003389 if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
drh9f0bbf92009-01-02 21:08:09 +00003390 rc = newDatabase(pBt);
drhdd3cd972010-03-27 17:12:36 +00003391 pBt->nPage = get4byte(28 + pBt->pPage1->aData);
drhb9b49bf2010-08-05 03:21:39 +00003392
3393 /* The database size was written into the offset 28 of the header
3394 ** when the transaction started, so we know that the value at offset
3395 ** 28 is nonzero. */
3396 assert( pBt->nPage>0 );
drh9f0bbf92009-01-02 21:08:09 +00003397 }
danielk1977fd7f0452008-12-17 17:30:26 +00003398 sqlite3BtreeLeave(p);
3399 }
3400 return rc;
3401}
3402
3403/*
drh8b2f49b2001-06-08 00:21:52 +00003404** Create a new cursor for the BTree whose root is on the page
danielk19773e8add92009-07-04 17:16:00 +00003405** iTable. If a read-only cursor is requested, it is assumed that
3406** the caller already has at least a read-only transaction open
3407** on the database already. If a write-cursor is requested, then
3408** the caller is assumed to have an open write transaction.
drh1bee3d72001-10-15 00:44:35 +00003409**
3410** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00003411** If wrFlag==1, then the cursor can be used for reading or for
3412** writing if other conditions for writing are also met. These
3413** are the conditions that must be met in order for writing to
3414** be allowed:
drh6446c4d2001-12-15 14:22:18 +00003415**
drhf74b8d92002-09-01 23:20:45 +00003416** 1: The cursor must have been opened with wrFlag==1
3417**
drhfe5d71d2007-03-19 11:54:10 +00003418** 2: Other database connections that share the same pager cache
3419** but which are not in the READ_UNCOMMITTED state may not have
3420** cursors open with wrFlag==0 on the same table. Otherwise
3421** the changes made by this write cursor would be visible to
3422** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00003423**
3424** 3: The database must be writable (not on read-only media)
3425**
3426** 4: There must be an active transaction.
3427**
drh6446c4d2001-12-15 14:22:18 +00003428** No checking is done to make sure that page iTable really is the
3429** root page of a b-tree. If it is not, then the cursor acquired
3430** will not work correctly.
danielk197771d5d2c2008-09-29 11:49:47 +00003431**
drhf25a5072009-11-18 23:01:25 +00003432** It is assumed that the sqlite3BtreeCursorZero() has been called
3433** on pCur to initialize the memory space prior to invoking this routine.
drha059ad02001-04-17 20:09:11 +00003434*/
drhd677b3d2007-08-20 22:48:41 +00003435static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00003436 Btree *p, /* The btree */
3437 int iTable, /* Root page of table to open */
3438 int wrFlag, /* 1 to write. 0 read-only */
3439 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
3440 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00003441){
danielk19773e8add92009-07-04 17:16:00 +00003442 BtShared *pBt = p->pBt; /* Shared b-tree handle */
drhecdc7532001-09-23 02:35:53 +00003443
drh1fee73e2007-08-29 04:00:57 +00003444 assert( sqlite3BtreeHoldsMutex(p) );
drhf49661a2008-12-10 16:45:50 +00003445 assert( wrFlag==0 || wrFlag==1 );
danielk197796d48e92009-06-29 06:00:37 +00003446
danielk1977602b4662009-07-02 07:47:33 +00003447 /* The following assert statements verify that if this is a sharable
3448 ** b-tree database, the connection is holding the required table locks,
3449 ** and that no other connection has any open cursor that conflicts with
3450 ** this lock. */
3451 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
danielk197796d48e92009-06-29 06:00:37 +00003452 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
3453
danielk19773e8add92009-07-04 17:16:00 +00003454 /* Assert that the caller has opened the required transaction. */
3455 assert( p->inTrans>TRANS_NONE );
3456 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
3457 assert( pBt->pPage1 && pBt->pPage1->aData );
3458
danielk197796d48e92009-06-29 06:00:37 +00003459 if( NEVER(wrFlag && pBt->readOnly) ){
3460 return SQLITE_READONLY;
drha0c9a112004-03-10 13:42:37 +00003461 }
drhb1299152010-03-30 22:58:33 +00003462 if( iTable==1 && btreePagecount(pBt)==0 ){
danielk19773e8add92009-07-04 17:16:00 +00003463 return SQLITE_EMPTY;
3464 }
danielk1977aef0bf62005-12-30 16:28:01 +00003465
danielk1977aef0bf62005-12-30 16:28:01 +00003466 /* Now that no other errors can occur, finish filling in the BtCursor
danielk19773e8add92009-07-04 17:16:00 +00003467 ** variables and link the cursor into the BtShared list. */
danielk1977172114a2009-07-07 15:47:12 +00003468 pCur->pgnoRoot = (Pgno)iTable;
3469 pCur->iPage = -1;
drh1e968a02008-03-25 00:22:21 +00003470 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00003471 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00003472 pCur->pBt = pBt;
drhf49661a2008-12-10 16:45:50 +00003473 pCur->wrFlag = (u8)wrFlag;
drha059ad02001-04-17 20:09:11 +00003474 pCur->pNext = pBt->pCursor;
3475 if( pCur->pNext ){
3476 pCur->pNext->pPrev = pCur;
3477 }
3478 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00003479 pCur->eState = CURSOR_INVALID;
drh7f751222009-03-17 22:33:00 +00003480 pCur->cachedRowid = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00003481 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003482}
drhd677b3d2007-08-20 22:48:41 +00003483int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00003484 Btree *p, /* The btree */
3485 int iTable, /* Root page of table to open */
3486 int wrFlag, /* 1 to write. 0 read-only */
3487 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
3488 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00003489){
3490 int rc;
3491 sqlite3BtreeEnter(p);
danielk1977cd3e8f72008-03-25 09:47:35 +00003492 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
drhd677b3d2007-08-20 22:48:41 +00003493 sqlite3BtreeLeave(p);
3494 return rc;
3495}
drh7f751222009-03-17 22:33:00 +00003496
3497/*
3498** Return the size of a BtCursor object in bytes.
3499**
3500** This interfaces is needed so that users of cursors can preallocate
3501** sufficient storage to hold a cursor. The BtCursor object is opaque
3502** to users so they cannot do the sizeof() themselves - they must call
3503** this routine.
3504*/
3505int sqlite3BtreeCursorSize(void){
drhc54055b2009-11-13 17:05:53 +00003506 return ROUND8(sizeof(BtCursor));
danielk1977cd3e8f72008-03-25 09:47:35 +00003507}
3508
drh7f751222009-03-17 22:33:00 +00003509/*
drhf25a5072009-11-18 23:01:25 +00003510** Initialize memory that will be converted into a BtCursor object.
3511**
3512** The simple approach here would be to memset() the entire object
3513** to zero. But it turns out that the apPage[] and aiIdx[] arrays
3514** do not need to be zeroed and they are large, so we can save a lot
3515** of run-time by skipping the initialization of those elements.
3516*/
3517void sqlite3BtreeCursorZero(BtCursor *p){
3518 memset(p, 0, offsetof(BtCursor, iPage));
3519}
3520
3521/*
drh7f751222009-03-17 22:33:00 +00003522** Set the cached rowid value of every cursor in the same database file
3523** as pCur and having the same root page number as pCur. The value is
3524** set to iRowid.
3525**
3526** Only positive rowid values are considered valid for this cache.
3527** The cache is initialized to zero, indicating an invalid cache.
3528** A btree will work fine with zero or negative rowids. We just cannot
3529** cache zero or negative rowids, which means tables that use zero or
3530** negative rowids might run a little slower. But in practice, zero
3531** or negative rowids are very uncommon so this should not be a problem.
3532*/
3533void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
3534 BtCursor *p;
3535 for(p=pCur->pBt->pCursor; p; p=p->pNext){
3536 if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
3537 }
3538 assert( pCur->cachedRowid==iRowid );
3539}
drhd677b3d2007-08-20 22:48:41 +00003540
drh7f751222009-03-17 22:33:00 +00003541/*
3542** Return the cached rowid for the given cursor. A negative or zero
3543** return value indicates that the rowid cache is invalid and should be
3544** ignored. If the rowid cache has never before been set, then a
3545** zero is returned.
3546*/
3547sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
3548 return pCur->cachedRowid;
3549}
drha059ad02001-04-17 20:09:11 +00003550
3551/*
drh5e00f6c2001-09-13 13:46:56 +00003552** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00003553** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00003554*/
drh3aac2dd2004-04-26 14:10:20 +00003555int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00003556 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00003557 if( pBtree ){
danielk197771d5d2c2008-09-29 11:49:47 +00003558 int i;
danielk1977cd3e8f72008-03-25 09:47:35 +00003559 BtShared *pBt = pCur->pBt;
3560 sqlite3BtreeEnter(pBtree);
danielk1977be51a652008-10-08 17:58:48 +00003561 sqlite3BtreeClearCursor(pCur);
danielk1977cd3e8f72008-03-25 09:47:35 +00003562 if( pCur->pPrev ){
3563 pCur->pPrev->pNext = pCur->pNext;
3564 }else{
3565 pBt->pCursor = pCur->pNext;
3566 }
3567 if( pCur->pNext ){
3568 pCur->pNext->pPrev = pCur->pPrev;
3569 }
danielk197771d5d2c2008-09-29 11:49:47 +00003570 for(i=0; i<=pCur->iPage; i++){
3571 releasePage(pCur->apPage[i]);
3572 }
danielk1977cd3e8f72008-03-25 09:47:35 +00003573 unlockBtreeIfUnused(pBt);
3574 invalidateOverflowCache(pCur);
3575 /* sqlite3_free(pCur); */
3576 sqlite3BtreeLeave(pBtree);
drha059ad02001-04-17 20:09:11 +00003577 }
drh8c42ca92001-06-22 19:15:00 +00003578 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003579}
3580
drh5e2f8b92001-05-28 00:41:15 +00003581/*
drh86057612007-06-26 01:04:48 +00003582** Make sure the BtCursor* given in the argument has a valid
3583** BtCursor.info structure. If it is not already valid, call
danielk197730548662009-07-09 05:07:37 +00003584** btreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00003585**
3586** BtCursor.info is a cache of the information in the current cell.
danielk197730548662009-07-09 05:07:37 +00003587** Using this cache reduces the number of calls to btreeParseCell().
drh86057612007-06-26 01:04:48 +00003588**
3589** 2007-06-25: There is a bug in some versions of MSVC that cause the
3590** compiler to crash when getCellInfo() is implemented as a macro.
3591** But there is a measureable speed advantage to using the macro on gcc
3592** (when less compiler optimizations like -Os or -O0 are used and the
3593** compiler is not doing agressive inlining.) So we use a real function
3594** for MSVC and a macro for everything else. Ticket #2457.
drh9188b382004-05-14 21:12:22 +00003595*/
drh9188b382004-05-14 21:12:22 +00003596#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00003597 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00003598 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00003599 int iPage = pCur->iPage;
drh51c6d962004-06-06 00:42:25 +00003600 memset(&info, 0, sizeof(info));
danielk197730548662009-07-09 05:07:37 +00003601 btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
drh9188b382004-05-14 21:12:22 +00003602 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00003603 }
danielk19771cc5ed82007-05-16 17:28:43 +00003604#else
3605 #define assertCellInfo(x)
3606#endif
drh86057612007-06-26 01:04:48 +00003607#ifdef _MSC_VER
3608 /* Use a real function in MSVC to work around bugs in that compiler. */
3609 static void getCellInfo(BtCursor *pCur){
3610 if( pCur->info.nSize==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003611 int iPage = pCur->iPage;
danielk197730548662009-07-09 05:07:37 +00003612 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
drha2c20e42008-03-29 16:01:04 +00003613 pCur->validNKey = 1;
drh86057612007-06-26 01:04:48 +00003614 }else{
3615 assertCellInfo(pCur);
3616 }
3617 }
3618#else /* if not _MSC_VER */
3619 /* Use a macro in all other compilers so that the function is inlined */
danielk197771d5d2c2008-09-29 11:49:47 +00003620#define getCellInfo(pCur) \
3621 if( pCur->info.nSize==0 ){ \
3622 int iPage = pCur->iPage; \
danielk197730548662009-07-09 05:07:37 +00003623 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
danielk197771d5d2c2008-09-29 11:49:47 +00003624 pCur->validNKey = 1; \
3625 }else{ \
3626 assertCellInfo(pCur); \
drh86057612007-06-26 01:04:48 +00003627 }
3628#endif /* _MSC_VER */
drh9188b382004-05-14 21:12:22 +00003629
drhea8ffdf2009-07-22 00:35:23 +00003630#ifndef NDEBUG /* The next routine used only within assert() statements */
3631/*
3632** Return true if the given BtCursor is valid. A valid cursor is one
3633** that is currently pointing to a row in a (non-empty) table.
3634** This is a verification routine is used only within assert() statements.
3635*/
3636int sqlite3BtreeCursorIsValid(BtCursor *pCur){
3637 return pCur && pCur->eState==CURSOR_VALID;
3638}
3639#endif /* NDEBUG */
3640
drh9188b382004-05-14 21:12:22 +00003641/*
drh3aac2dd2004-04-26 14:10:20 +00003642** Set *pSize to the size of the buffer needed to hold the value of
3643** the key for the current entry. If the cursor is not pointing
3644** to a valid entry, *pSize is set to 0.
3645**
drh4b70f112004-05-02 21:12:19 +00003646** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00003647** itself, not the number of bytes in the key.
drhea8ffdf2009-07-22 00:35:23 +00003648**
3649** The caller must position the cursor prior to invoking this routine.
3650**
3651** This routine cannot fail. It always returns SQLITE_OK.
drh7e3b0a02001-04-28 16:52:40 +00003652*/
drh4a1c3802004-05-12 15:15:47 +00003653int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drh1fee73e2007-08-29 04:00:57 +00003654 assert( cursorHoldsMutex(pCur) );
drhea8ffdf2009-07-22 00:35:23 +00003655 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3656 if( pCur->eState!=CURSOR_VALID ){
3657 *pSize = 0;
3658 }else{
3659 getCellInfo(pCur);
3660 *pSize = pCur->info.nKey;
drh72f82862001-05-24 21:06:34 +00003661 }
drhea8ffdf2009-07-22 00:35:23 +00003662 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003663}
drh2af926b2001-05-15 00:39:25 +00003664
drh72f82862001-05-24 21:06:34 +00003665/*
drh0e1c19e2004-05-11 00:58:56 +00003666** Set *pSize to the number of bytes of data in the entry the
drhea8ffdf2009-07-22 00:35:23 +00003667** cursor currently points to.
3668**
3669** The caller must guarantee that the cursor is pointing to a non-NULL
3670** valid entry. In other words, the calling procedure must guarantee
3671** that the cursor has Cursor.eState==CURSOR_VALID.
3672**
3673** Failure is not possible. This function always returns SQLITE_OK.
3674** It might just as well be a procedure (returning void) but we continue
3675** to return an integer result code for historical reasons.
drh0e1c19e2004-05-11 00:58:56 +00003676*/
3677int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drh1fee73e2007-08-29 04:00:57 +00003678 assert( cursorHoldsMutex(pCur) );
drhea8ffdf2009-07-22 00:35:23 +00003679 assert( pCur->eState==CURSOR_VALID );
3680 getCellInfo(pCur);
3681 *pSize = pCur->info.nData;
3682 return SQLITE_OK;
drh0e1c19e2004-05-11 00:58:56 +00003683}
3684
3685/*
danielk1977d04417962007-05-02 13:16:30 +00003686** Given the page number of an overflow page in the database (parameter
3687** ovfl), this function finds the page number of the next page in the
3688** linked list of overflow pages. If possible, it uses the auto-vacuum
3689** pointer-map data instead of reading the content of page ovfl to do so.
3690**
3691** If an error occurs an SQLite error code is returned. Otherwise:
3692**
danielk1977bea2a942009-01-20 17:06:27 +00003693** The page number of the next overflow page in the linked list is
3694** written to *pPgnoNext. If page ovfl is the last page in its linked
3695** list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003696**
danielk1977bea2a942009-01-20 17:06:27 +00003697** If ppPage is not NULL, and a reference to the MemPage object corresponding
3698** to page number pOvfl was obtained, then *ppPage is set to point to that
3699** reference. It is the responsibility of the caller to call releasePage()
3700** on *ppPage to free the reference. In no reference was obtained (because
3701** the pointer-map was used to obtain the value for *pPgnoNext), then
3702** *ppPage is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003703*/
3704static int getOverflowPage(
drhfa3be902009-07-07 02:44:07 +00003705 BtShared *pBt, /* The database file */
3706 Pgno ovfl, /* Current overflow page number */
danielk1977bea2a942009-01-20 17:06:27 +00003707 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
danielk1977d04417962007-05-02 13:16:30 +00003708 Pgno *pPgnoNext /* OUT: Next overflow page number */
3709){
3710 Pgno next = 0;
danielk1977bea2a942009-01-20 17:06:27 +00003711 MemPage *pPage = 0;
drh1bd10f82008-12-10 21:19:56 +00003712 int rc = SQLITE_OK;
danielk1977d04417962007-05-02 13:16:30 +00003713
drh1fee73e2007-08-29 04:00:57 +00003714 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bea2a942009-01-20 17:06:27 +00003715 assert(pPgnoNext);
danielk1977d04417962007-05-02 13:16:30 +00003716
3717#ifndef SQLITE_OMIT_AUTOVACUUM
3718 /* Try to find the next page in the overflow list using the
3719 ** autovacuum pointer-map pages. Guess that the next page in
3720 ** the overflow list is page number (ovfl+1). If that guess turns
3721 ** out to be wrong, fall back to loading the data of page
3722 ** number ovfl to determine the next page number.
3723 */
3724 if( pBt->autoVacuum ){
3725 Pgno pgno;
3726 Pgno iGuess = ovfl+1;
3727 u8 eType;
3728
3729 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
3730 iGuess++;
3731 }
3732
drhb1299152010-03-30 22:58:33 +00003733 if( iGuess<=btreePagecount(pBt) ){
danielk1977d04417962007-05-02 13:16:30 +00003734 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
danielk1977bea2a942009-01-20 17:06:27 +00003735 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
danielk1977d04417962007-05-02 13:16:30 +00003736 next = iGuess;
danielk1977bea2a942009-01-20 17:06:27 +00003737 rc = SQLITE_DONE;
danielk1977d04417962007-05-02 13:16:30 +00003738 }
3739 }
3740 }
3741#endif
3742
danielk1977d8a3f3d2009-07-11 11:45:23 +00003743 assert( next==0 || rc==SQLITE_DONE );
danielk1977bea2a942009-01-20 17:06:27 +00003744 if( rc==SQLITE_OK ){
danielk197730548662009-07-09 05:07:37 +00003745 rc = btreeGetPage(pBt, ovfl, &pPage, 0);
danielk1977d8a3f3d2009-07-11 11:45:23 +00003746 assert( rc==SQLITE_OK || pPage==0 );
3747 if( rc==SQLITE_OK ){
danielk1977d04417962007-05-02 13:16:30 +00003748 next = get4byte(pPage->aData);
3749 }
danielk1977443c0592009-01-16 15:21:05 +00003750 }
danielk197745d68822009-01-16 16:23:38 +00003751
danielk1977bea2a942009-01-20 17:06:27 +00003752 *pPgnoNext = next;
3753 if( ppPage ){
3754 *ppPage = pPage;
3755 }else{
3756 releasePage(pPage);
3757 }
3758 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
danielk1977d04417962007-05-02 13:16:30 +00003759}
3760
danielk1977da107192007-05-04 08:32:13 +00003761/*
3762** Copy data from a buffer to a page, or from a page to a buffer.
3763**
3764** pPayload is a pointer to data stored on database page pDbPage.
3765** If argument eOp is false, then nByte bytes of data are copied
3766** from pPayload to the buffer pointed at by pBuf. If eOp is true,
3767** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
3768** of data are copied from the buffer pBuf to pPayload.
3769**
3770** SQLITE_OK is returned on success, otherwise an error code.
3771*/
3772static int copyPayload(
3773 void *pPayload, /* Pointer to page data */
3774 void *pBuf, /* Pointer to buffer */
3775 int nByte, /* Number of bytes to copy */
3776 int eOp, /* 0 -> copy from page, 1 -> copy to page */
3777 DbPage *pDbPage /* Page containing pPayload */
3778){
3779 if( eOp ){
3780 /* Copy data from buffer to page (a write operation) */
3781 int rc = sqlite3PagerWrite(pDbPage);
3782 if( rc!=SQLITE_OK ){
3783 return rc;
3784 }
3785 memcpy(pPayload, pBuf, nByte);
3786 }else{
3787 /* Copy data from page to buffer (a read operation) */
3788 memcpy(pBuf, pPayload, nByte);
3789 }
3790 return SQLITE_OK;
3791}
danielk1977d04417962007-05-02 13:16:30 +00003792
3793/*
danielk19779f8d6402007-05-02 17:48:45 +00003794** This function is used to read or overwrite payload information
3795** for the entry that the pCur cursor is pointing to. If the eOp
3796** parameter is 0, this is a read operation (data copied into
3797** buffer pBuf). If it is non-zero, a write (data copied from
3798** buffer pBuf).
3799**
3800** A total of "amt" bytes are read or written beginning at "offset".
3801** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00003802**
drh3bcdfd22009-07-12 02:32:21 +00003803** The content being read or written might appear on the main page
3804** or be scattered out on multiple overflow pages.
danielk1977da107192007-05-04 08:32:13 +00003805**
danielk1977dcbb5d32007-05-04 18:36:44 +00003806** If the BtCursor.isIncrblobHandle flag is set, and the current
danielk1977da107192007-05-04 08:32:13 +00003807** cursor entry uses one or more overflow pages, this function
3808** allocates space for and lazily popluates the overflow page-list
3809** cache array (BtCursor.aOverflow). Subsequent calls use this
3810** cache to make seeking to the supplied offset more efficient.
3811**
3812** Once an overflow page-list cache has been allocated, it may be
3813** invalidated if some other cursor writes to the same table, or if
3814** the cursor is moved to a different row. Additionally, in auto-vacuum
3815** mode, the following events may invalidate an overflow page-list cache.
3816**
3817** * An incremental vacuum,
3818** * A commit in auto_vacuum="full" mode,
3819** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00003820*/
danielk19779f8d6402007-05-02 17:48:45 +00003821static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00003822 BtCursor *pCur, /* Cursor pointing to entry to read from */
danielk197789d40042008-11-17 14:20:56 +00003823 u32 offset, /* Begin reading this far into payload */
3824 u32 amt, /* Read this many bytes */
drh3aac2dd2004-04-26 14:10:20 +00003825 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00003826 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00003827){
3828 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00003829 int rc = SQLITE_OK;
drhfa1a98a2004-05-14 19:08:17 +00003830 u32 nKey;
danielk19772dec9702007-05-02 16:48:37 +00003831 int iIdx = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003832 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
danielk19770d065412008-11-12 18:21:36 +00003833 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
drh3aac2dd2004-04-26 14:10:20 +00003834
danielk1977da107192007-05-04 08:32:13 +00003835 assert( pPage );
danielk1977da184232006-01-05 11:34:32 +00003836 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003837 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh1fee73e2007-08-29 04:00:57 +00003838 assert( cursorHoldsMutex(pCur) );
danielk1977da107192007-05-04 08:32:13 +00003839
drh86057612007-06-26 01:04:48 +00003840 getCellInfo(pCur);
drh366fda62006-01-13 02:35:09 +00003841 aPayload = pCur->info.pCell + pCur->info.nHeader;
drhf49661a2008-12-10 16:45:50 +00003842 nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
danielk1977da107192007-05-04 08:32:13 +00003843
drh3bcdfd22009-07-12 02:32:21 +00003844 if( NEVER(offset+amt > nKey+pCur->info.nData)
danielk19770d065412008-11-12 18:21:36 +00003845 || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
3846 ){
danielk1977da107192007-05-04 08:32:13 +00003847 /* Trying to read or write past the end of the data is an error */
danielk197767fd7a92008-09-10 17:53:35 +00003848 return SQLITE_CORRUPT_BKPT;
drh3aac2dd2004-04-26 14:10:20 +00003849 }
danielk1977da107192007-05-04 08:32:13 +00003850
3851 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00003852 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00003853 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00003854 if( a+offset>pCur->info.nLocal ){
3855 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00003856 }
danielk1977da107192007-05-04 08:32:13 +00003857 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00003858 offset = 0;
drha34b6762004-05-07 13:30:42 +00003859 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00003860 amt -= a;
drhdd793422001-06-28 01:54:48 +00003861 }else{
drhfa1a98a2004-05-14 19:08:17 +00003862 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00003863 }
danielk1977da107192007-05-04 08:32:13 +00003864
3865 if( rc==SQLITE_OK && amt>0 ){
danielk197789d40042008-11-17 14:20:56 +00003866 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
danielk1977da107192007-05-04 08:32:13 +00003867 Pgno nextPage;
3868
drhfa1a98a2004-05-14 19:08:17 +00003869 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00003870
danielk19772dec9702007-05-02 16:48:37 +00003871#ifndef SQLITE_OMIT_INCRBLOB
danielk1977dcbb5d32007-05-04 18:36:44 +00003872 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
danielk1977da107192007-05-04 08:32:13 +00003873 ** has not been allocated, allocate it now. The array is sized at
3874 ** one entry for each overflow page in the overflow chain. The
3875 ** page number of the first overflow page is stored in aOverflow[0],
3876 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
3877 ** (the cache is lazily populated).
3878 */
danielk1977dcbb5d32007-05-04 18:36:44 +00003879 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
danielk19772dec9702007-05-02 16:48:37 +00003880 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
drh17435752007-08-16 04:30:38 +00003881 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
drh3bcdfd22009-07-12 02:32:21 +00003882 /* nOvfl is always positive. If it were zero, fetchPayload would have
3883 ** been used instead of this routine. */
3884 if( ALWAYS(nOvfl) && !pCur->aOverflow ){
danielk1977da107192007-05-04 08:32:13 +00003885 rc = SQLITE_NOMEM;
danielk19772dec9702007-05-02 16:48:37 +00003886 }
3887 }
danielk1977da107192007-05-04 08:32:13 +00003888
3889 /* If the overflow page-list cache has been allocated and the
3890 ** entry for the first required overflow page is valid, skip
3891 ** directly to it.
3892 */
danielk19772dec9702007-05-02 16:48:37 +00003893 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
3894 iIdx = (offset/ovflSize);
3895 nextPage = pCur->aOverflow[iIdx];
3896 offset = (offset%ovflSize);
3897 }
3898#endif
danielk1977da107192007-05-04 08:32:13 +00003899
3900 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
3901
3902#ifndef SQLITE_OMIT_INCRBLOB
3903 /* If required, populate the overflow page-list cache. */
3904 if( pCur->aOverflow ){
3905 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
3906 pCur->aOverflow[iIdx] = nextPage;
3907 }
3908#endif
3909
danielk1977d04417962007-05-02 13:16:30 +00003910 if( offset>=ovflSize ){
3911 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00003912 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00003913 ** data is not required. So first try to lookup the overflow
3914 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00003915 ** function.
danielk1977d04417962007-05-02 13:16:30 +00003916 */
danielk19772dec9702007-05-02 16:48:37 +00003917#ifndef SQLITE_OMIT_INCRBLOB
danielk1977da107192007-05-04 08:32:13 +00003918 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
3919 nextPage = pCur->aOverflow[iIdx+1];
3920 } else
danielk19772dec9702007-05-02 16:48:37 +00003921#endif
danielk1977da107192007-05-04 08:32:13 +00003922 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
danielk1977da107192007-05-04 08:32:13 +00003923 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00003924 }else{
danielk19779f8d6402007-05-02 17:48:45 +00003925 /* Need to read this page properly. It contains some of the
3926 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00003927 */
3928 DbPage *pDbPage;
danielk1977cfe9a692004-06-16 12:00:29 +00003929 int a = amt;
danielk1977d04417962007-05-02 13:16:30 +00003930 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
danielk1977da107192007-05-04 08:32:13 +00003931 if( rc==SQLITE_OK ){
3932 aPayload = sqlite3PagerGetData(pDbPage);
3933 nextPage = get4byte(aPayload);
3934 if( a + offset > ovflSize ){
3935 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00003936 }
danielk1977da107192007-05-04 08:32:13 +00003937 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
3938 sqlite3PagerUnref(pDbPage);
3939 offset = 0;
3940 amt -= a;
3941 pBuf += a;
danielk19779f8d6402007-05-02 17:48:45 +00003942 }
danielk1977cfe9a692004-06-16 12:00:29 +00003943 }
drh2af926b2001-05-15 00:39:25 +00003944 }
drh2af926b2001-05-15 00:39:25 +00003945 }
danielk1977cfe9a692004-06-16 12:00:29 +00003946
danielk1977da107192007-05-04 08:32:13 +00003947 if( rc==SQLITE_OK && amt>0 ){
drh49285702005-09-17 15:20:26 +00003948 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00003949 }
danielk1977da107192007-05-04 08:32:13 +00003950 return rc;
drh2af926b2001-05-15 00:39:25 +00003951}
3952
drh72f82862001-05-24 21:06:34 +00003953/*
drh3aac2dd2004-04-26 14:10:20 +00003954** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003955** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003956** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00003957**
drh5d1a8722009-07-22 18:07:40 +00003958** The caller must ensure that pCur is pointing to a valid row
3959** in the table.
3960**
drh3aac2dd2004-04-26 14:10:20 +00003961** Return SQLITE_OK on success or an error code if anything goes
3962** wrong. An error is returned if "offset+amt" is larger than
3963** the available payload.
drh72f82862001-05-24 21:06:34 +00003964*/
drha34b6762004-05-07 13:30:42 +00003965int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drh1fee73e2007-08-29 04:00:57 +00003966 assert( cursorHoldsMutex(pCur) );
drh5d1a8722009-07-22 18:07:40 +00003967 assert( pCur->eState==CURSOR_VALID );
3968 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3969 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
3970 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
drh3aac2dd2004-04-26 14:10:20 +00003971}
3972
3973/*
drh3aac2dd2004-04-26 14:10:20 +00003974** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003975** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003976** begins at "offset".
3977**
3978** Return SQLITE_OK on success or an error code if anything goes
3979** wrong. An error is returned if "offset+amt" is larger than
3980** the available payload.
drh72f82862001-05-24 21:06:34 +00003981*/
drh3aac2dd2004-04-26 14:10:20 +00003982int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003983 int rc;
3984
danielk19773588ceb2008-06-10 17:30:26 +00003985#ifndef SQLITE_OMIT_INCRBLOB
3986 if ( pCur->eState==CURSOR_INVALID ){
3987 return SQLITE_ABORT;
3988 }
3989#endif
3990
drh1fee73e2007-08-29 04:00:57 +00003991 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003992 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003993 if( rc==SQLITE_OK ){
3994 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003995 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3996 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drhfb192682009-07-11 18:26:28 +00003997 rc = accessPayload(pCur, offset, amt, pBuf, 0);
danielk1977da184232006-01-05 11:34:32 +00003998 }
3999 return rc;
drh2af926b2001-05-15 00:39:25 +00004000}
4001
drh72f82862001-05-24 21:06:34 +00004002/*
drh0e1c19e2004-05-11 00:58:56 +00004003** Return a pointer to payload information from the entry that the
4004** pCur cursor is pointing to. The pointer is to the beginning of
4005** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00004006** skipKey==1. The number of bytes of available key/data is written
4007** into *pAmt. If *pAmt==0, then the value returned will not be
4008** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00004009**
4010** This routine is an optimization. It is common for the entire key
4011** and data to fit on the local page and for there to be no overflow
4012** pages. When that is so, this routine can be used to access the
4013** key and data without making a copy. If the key and/or data spills
drh7f751222009-03-17 22:33:00 +00004014** onto overflow pages, then accessPayload() must be used to reassemble
drh0e1c19e2004-05-11 00:58:56 +00004015** the key/data and copy it into a preallocated buffer.
4016**
4017** The pointer returned by this routine looks directly into the cached
4018** page of the database. The data might change or move the next time
4019** any btree routine is called.
4020*/
4021static const unsigned char *fetchPayload(
4022 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00004023 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00004024 int skipKey /* read beginning at data if this is true */
4025){
4026 unsigned char *aPayload;
4027 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00004028 u32 nKey;
danielk197789d40042008-11-17 14:20:56 +00004029 u32 nLocal;
drh0e1c19e2004-05-11 00:58:56 +00004030
danielk197771d5d2c2008-09-29 11:49:47 +00004031 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
danielk1977da184232006-01-05 11:34:32 +00004032 assert( pCur->eState==CURSOR_VALID );
drh1fee73e2007-08-29 04:00:57 +00004033 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00004034 pPage = pCur->apPage[pCur->iPage];
4035 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drhfe3313f2009-07-21 19:02:20 +00004036 if( NEVER(pCur->info.nSize==0) ){
4037 btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
4038 &pCur->info);
4039 }
drh43605152004-05-29 21:46:49 +00004040 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00004041 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00004042 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00004043 nKey = 0;
4044 }else{
drhf49661a2008-12-10 16:45:50 +00004045 nKey = (int)pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00004046 }
drh0e1c19e2004-05-11 00:58:56 +00004047 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00004048 aPayload += nKey;
4049 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00004050 }else{
drhfa1a98a2004-05-14 19:08:17 +00004051 nLocal = pCur->info.nLocal;
drhfe3313f2009-07-21 19:02:20 +00004052 assert( nLocal<=nKey );
drh0e1c19e2004-05-11 00:58:56 +00004053 }
drhe51c44f2004-05-30 20:46:09 +00004054 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00004055 return aPayload;
4056}
4057
4058
4059/*
drhe51c44f2004-05-30 20:46:09 +00004060** For the entry that cursor pCur is point to, return as
4061** many bytes of the key or data as are available on the local
4062** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00004063**
4064** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00004065** or be destroyed on the next call to any Btree routine,
4066** including calls from other threads against the same cache.
4067** Hence, a mutex on the BtShared should be held prior to calling
4068** this routine.
drh0e1c19e2004-05-11 00:58:56 +00004069**
4070** These routines is used to get quick access to key and data
4071** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00004072*/
drhe51c44f2004-05-30 20:46:09 +00004073const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
drhfe3313f2009-07-21 19:02:20 +00004074 const void *p = 0;
danielk19774b0aa4c2009-05-28 11:05:57 +00004075 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh1fee73e2007-08-29 04:00:57 +00004076 assert( cursorHoldsMutex(pCur) );
drhfe3313f2009-07-21 19:02:20 +00004077 if( ALWAYS(pCur->eState==CURSOR_VALID) ){
4078 p = (const void*)fetchPayload(pCur, pAmt, 0);
danielk1977da184232006-01-05 11:34:32 +00004079 }
drhfe3313f2009-07-21 19:02:20 +00004080 return p;
drh0e1c19e2004-05-11 00:58:56 +00004081}
drhe51c44f2004-05-30 20:46:09 +00004082const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
drhfe3313f2009-07-21 19:02:20 +00004083 const void *p = 0;
danielk19774b0aa4c2009-05-28 11:05:57 +00004084 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh1fee73e2007-08-29 04:00:57 +00004085 assert( cursorHoldsMutex(pCur) );
drhfe3313f2009-07-21 19:02:20 +00004086 if( ALWAYS(pCur->eState==CURSOR_VALID) ){
4087 p = (const void*)fetchPayload(pCur, pAmt, 1);
danielk1977da184232006-01-05 11:34:32 +00004088 }
drhfe3313f2009-07-21 19:02:20 +00004089 return p;
drh0e1c19e2004-05-11 00:58:56 +00004090}
4091
4092
4093/*
drh8178a752003-01-05 21:41:40 +00004094** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00004095** page number of the child page to move to.
danielk1977a299d612009-07-13 11:22:10 +00004096**
4097** This function returns SQLITE_CORRUPT if the page-header flags field of
4098** the new child page does not match the flags field of the parent (i.e.
4099** if an intkey page appears to be the parent of a non-intkey page, or
4100** vice-versa).
drh72f82862001-05-24 21:06:34 +00004101*/
drh3aac2dd2004-04-26 14:10:20 +00004102static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00004103 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00004104 int i = pCur->iPage;
drh72f82862001-05-24 21:06:34 +00004105 MemPage *pNewPage;
drhd0679ed2007-08-28 22:24:34 +00004106 BtShared *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00004107
drh1fee73e2007-08-29 04:00:57 +00004108 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004109 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004110 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
4111 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
4112 return SQLITE_CORRUPT_BKPT;
4113 }
4114 rc = getAndInitPage(pBt, newPgno, &pNewPage);
drh6019e162001-07-02 17:51:45 +00004115 if( rc ) return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00004116 pCur->apPage[i+1] = pNewPage;
4117 pCur->aiIdx[i+1] = 0;
4118 pCur->iPage++;
4119
drh271efa52004-05-30 19:19:05 +00004120 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004121 pCur->validNKey = 0;
danielk1977bd5969a2009-07-11 17:39:42 +00004122 if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
drh49285702005-09-17 15:20:26 +00004123 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00004124 }
drh72f82862001-05-24 21:06:34 +00004125 return SQLITE_OK;
4126}
4127
danielk1977bf93c562008-09-29 15:53:25 +00004128#ifndef NDEBUG
4129/*
4130** Page pParent is an internal (non-leaf) tree page. This function
4131** asserts that page number iChild is the left-child if the iIdx'th
4132** cell in page pParent. Or, if iIdx is equal to the total number of
4133** cells in pParent, that page number iChild is the right-child of
4134** the page.
4135*/
4136static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
4137 assert( iIdx<=pParent->nCell );
4138 if( iIdx==pParent->nCell ){
4139 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
4140 }else{
4141 assert( get4byte(findCell(pParent, iIdx))==iChild );
4142 }
4143}
4144#else
4145# define assertParentIndex(x,y,z)
4146#endif
4147
drh72f82862001-05-24 21:06:34 +00004148/*
drh5e2f8b92001-05-28 00:41:15 +00004149** Move the cursor up to the parent page.
4150**
4151** pCur->idx is set to the cell index that contains the pointer
4152** to the page we are coming from. If we are coming from the
4153** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00004154** the largest cell index.
drh72f82862001-05-24 21:06:34 +00004155*/
danielk197730548662009-07-09 05:07:37 +00004156static void moveToParent(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00004157 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004158 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004159 assert( pCur->iPage>0 );
4160 assert( pCur->apPage[pCur->iPage] );
danielk1977bf93c562008-09-29 15:53:25 +00004161 assertParentIndex(
4162 pCur->apPage[pCur->iPage-1],
4163 pCur->aiIdx[pCur->iPage-1],
4164 pCur->apPage[pCur->iPage]->pgno
4165 );
danielk197771d5d2c2008-09-29 11:49:47 +00004166 releasePage(pCur->apPage[pCur->iPage]);
4167 pCur->iPage--;
drh271efa52004-05-30 19:19:05 +00004168 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004169 pCur->validNKey = 0;
drh72f82862001-05-24 21:06:34 +00004170}
4171
4172/*
danielk19778f880a82009-07-13 09:41:45 +00004173** Move the cursor to point to the root page of its b-tree structure.
4174**
4175** If the table has a virtual root page, then the cursor is moved to point
4176** to the virtual root page instead of the actual root page. A table has a
4177** virtual root page when the actual root page contains no cells and a
4178** single child page. This can only happen with the table rooted at page 1.
4179**
4180** If the b-tree structure is empty, the cursor state is set to
4181** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
4182** cell located on the root (or virtual root) page and the cursor state
4183** is set to CURSOR_VALID.
4184**
4185** If this function returns successfully, it may be assumed that the
4186** page-header flags indicate that the [virtual] root-page is the expected
4187** kind of b-tree page (i.e. if when opening the cursor the caller did not
4188** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
4189** indicating a table b-tree, or if the caller did specify a KeyInfo
4190** structure the flags byte is set to 0x02 or 0x0A, indicating an index
4191** b-tree).
drh72f82862001-05-24 21:06:34 +00004192*/
drh5e2f8b92001-05-28 00:41:15 +00004193static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00004194 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00004195 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00004196 Btree *p = pCur->pBtree;
4197 BtShared *pBt = p->pBt;
drhbd03cae2001-06-02 02:40:57 +00004198
drh1fee73e2007-08-29 04:00:57 +00004199 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +00004200 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
4201 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
4202 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
4203 if( pCur->eState>=CURSOR_REQUIRESEEK ){
4204 if( pCur->eState==CURSOR_FAULT ){
drh4c301aa2009-07-15 17:25:45 +00004205 assert( pCur->skipNext!=SQLITE_OK );
4206 return pCur->skipNext;
drhfb982642007-08-30 01:19:59 +00004207 }
danielk1977be51a652008-10-08 17:58:48 +00004208 sqlite3BtreeClearCursor(pCur);
drhbf700f32007-03-31 02:36:44 +00004209 }
danielk197771d5d2c2008-09-29 11:49:47 +00004210
4211 if( pCur->iPage>=0 ){
4212 int i;
4213 for(i=1; i<=pCur->iPage; i++){
4214 releasePage(pCur->apPage[i]);
danielk1977d9f6c532008-09-19 16:39:38 +00004215 }
danielk1977172114a2009-07-07 15:47:12 +00004216 pCur->iPage = 0;
drh777e4c42006-01-13 04:31:58 +00004217 }else{
drh4c301aa2009-07-15 17:25:45 +00004218 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
4219 if( rc!=SQLITE_OK ){
drh777e4c42006-01-13 04:31:58 +00004220 pCur->eState = CURSOR_INVALID;
4221 return rc;
4222 }
danielk1977172114a2009-07-07 15:47:12 +00004223 pCur->iPage = 0;
4224
4225 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
4226 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
4227 ** NULL, the caller expects a table b-tree. If this is not the case,
4228 ** return an SQLITE_CORRUPT error. */
4229 assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
4230 if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
4231 return SQLITE_CORRUPT_BKPT;
4232 }
drhc39e0002004-05-07 23:50:57 +00004233 }
danielk197771d5d2c2008-09-29 11:49:47 +00004234
danielk19778f880a82009-07-13 09:41:45 +00004235 /* Assert that the root page is of the correct type. This must be the
4236 ** case as the call to this function that loaded the root-page (either
4237 ** this call or a previous invocation) would have detected corruption
4238 ** if the assumption were not true, and it is not possible for the flags
4239 ** byte to have been modified while this cursor is holding a reference
4240 ** to the page. */
danielk197771d5d2c2008-09-29 11:49:47 +00004241 pRoot = pCur->apPage[0];
4242 assert( pRoot->pgno==pCur->pgnoRoot );
danielk19778f880a82009-07-13 09:41:45 +00004243 assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
4244
danielk197771d5d2c2008-09-29 11:49:47 +00004245 pCur->aiIdx[0] = 0;
drh271efa52004-05-30 19:19:05 +00004246 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004247 pCur->atLast = 0;
4248 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004249
drh8856d6a2004-04-29 14:42:46 +00004250 if( pRoot->nCell==0 && !pRoot->leaf ){
4251 Pgno subpage;
drhc85240d2009-06-04 16:14:33 +00004252 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
drh43605152004-05-29 21:46:49 +00004253 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
danielk1977da184232006-01-05 11:34:32 +00004254 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00004255 rc = moveToChild(pCur, subpage);
danielk197771d5d2c2008-09-29 11:49:47 +00004256 }else{
4257 pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
drh8856d6a2004-04-29 14:42:46 +00004258 }
4259 return rc;
drh72f82862001-05-24 21:06:34 +00004260}
drh2af926b2001-05-15 00:39:25 +00004261
drh5e2f8b92001-05-28 00:41:15 +00004262/*
4263** Move the cursor down to the left-most leaf entry beneath the
4264** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00004265**
4266** The left-most leaf is the one with the smallest key - the first
4267** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00004268*/
4269static int moveToLeftmost(BtCursor *pCur){
4270 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00004271 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00004272 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00004273
drh1fee73e2007-08-29 04:00:57 +00004274 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004275 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004276 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
4277 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
4278 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
drh8178a752003-01-05 21:41:40 +00004279 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00004280 }
drhd677b3d2007-08-20 22:48:41 +00004281 return rc;
drh5e2f8b92001-05-28 00:41:15 +00004282}
4283
drh2dcc9aa2002-12-04 13:40:25 +00004284/*
4285** Move the cursor down to the right-most leaf entry beneath the
4286** page to which it is currently pointing. Notice the difference
4287** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
4288** finds the left-most entry beneath the *entry* whereas moveToRightmost()
4289** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00004290**
4291** The right-most entry is the one with the largest key - the last
4292** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00004293*/
4294static int moveToRightmost(BtCursor *pCur){
4295 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00004296 int rc = SQLITE_OK;
drh1bd10f82008-12-10 21:19:56 +00004297 MemPage *pPage = 0;
drh2dcc9aa2002-12-04 13:40:25 +00004298
drh1fee73e2007-08-29 04:00:57 +00004299 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004300 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004301 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
drh43605152004-05-29 21:46:49 +00004302 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
danielk197771d5d2c2008-09-29 11:49:47 +00004303 pCur->aiIdx[pCur->iPage] = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00004304 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00004305 }
drhd677b3d2007-08-20 22:48:41 +00004306 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00004307 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
drhd677b3d2007-08-20 22:48:41 +00004308 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004309 pCur->validNKey = 0;
drhd677b3d2007-08-20 22:48:41 +00004310 }
danielk1977518002e2008-09-05 05:02:46 +00004311 return rc;
drh2dcc9aa2002-12-04 13:40:25 +00004312}
4313
drh5e00f6c2001-09-13 13:46:56 +00004314/* Move the cursor to the first entry in the table. Return SQLITE_OK
4315** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00004316** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00004317*/
drh3aac2dd2004-04-26 14:10:20 +00004318int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00004319 int rc;
drhd677b3d2007-08-20 22:48:41 +00004320
drh1fee73e2007-08-29 04:00:57 +00004321 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004322 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00004323 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004324 if( rc==SQLITE_OK ){
4325 if( pCur->eState==CURSOR_INVALID ){
danielk197771d5d2c2008-09-29 11:49:47 +00004326 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00004327 *pRes = 1;
drhd677b3d2007-08-20 22:48:41 +00004328 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004329 assert( pCur->apPage[pCur->iPage]->nCell>0 );
drhd677b3d2007-08-20 22:48:41 +00004330 *pRes = 0;
4331 rc = moveToLeftmost(pCur);
4332 }
drh5e00f6c2001-09-13 13:46:56 +00004333 }
drh5e00f6c2001-09-13 13:46:56 +00004334 return rc;
4335}
drh5e2f8b92001-05-28 00:41:15 +00004336
drh9562b552002-02-19 15:00:07 +00004337/* Move the cursor to the last entry in the table. Return SQLITE_OK
4338** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00004339** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00004340*/
drh3aac2dd2004-04-26 14:10:20 +00004341int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00004342 int rc;
drhd677b3d2007-08-20 22:48:41 +00004343
drh1fee73e2007-08-29 04:00:57 +00004344 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004345 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19773f632d52009-05-02 10:03:09 +00004346
4347 /* If the cursor already points to the last entry, this is a no-op. */
4348 if( CURSOR_VALID==pCur->eState && pCur->atLast ){
4349#ifdef SQLITE_DEBUG
4350 /* This block serves to assert() that the cursor really does point
4351 ** to the last entry in the b-tree. */
4352 int ii;
4353 for(ii=0; ii<pCur->iPage; ii++){
4354 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
4355 }
4356 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
4357 assert( pCur->apPage[pCur->iPage]->leaf );
4358#endif
4359 return SQLITE_OK;
4360 }
4361
drh9562b552002-02-19 15:00:07 +00004362 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004363 if( rc==SQLITE_OK ){
4364 if( CURSOR_INVALID==pCur->eState ){
danielk197771d5d2c2008-09-29 11:49:47 +00004365 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00004366 *pRes = 1;
4367 }else{
4368 assert( pCur->eState==CURSOR_VALID );
4369 *pRes = 0;
4370 rc = moveToRightmost(pCur);
drhf49661a2008-12-10 16:45:50 +00004371 pCur->atLast = rc==SQLITE_OK ?1:0;
drhd677b3d2007-08-20 22:48:41 +00004372 }
drh9562b552002-02-19 15:00:07 +00004373 }
drh9562b552002-02-19 15:00:07 +00004374 return rc;
4375}
4376
drhe14006d2008-03-25 17:23:32 +00004377/* Move the cursor so that it points to an entry near the key
drhe63d9992008-08-13 19:11:48 +00004378** specified by pIdxKey or intKey. Return a success code.
drh72f82862001-05-24 21:06:34 +00004379**
drhe63d9992008-08-13 19:11:48 +00004380** For INTKEY tables, the intKey parameter is used. pIdxKey
4381** must be NULL. For index tables, pIdxKey is used and intKey
4382** is ignored.
drh3aac2dd2004-04-26 14:10:20 +00004383**
drh5e2f8b92001-05-28 00:41:15 +00004384** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00004385** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00004386** were present. The cursor might point to an entry that comes
4387** before or after the key.
4388**
drh64022502009-01-09 14:11:04 +00004389** An integer is written into *pRes which is the result of
4390** comparing the key with the entry to which the cursor is
4391** pointing. The meaning of the integer written into
4392** *pRes is as follows:
drhbd03cae2001-06-02 02:40:57 +00004393**
4394** *pRes<0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004395** is smaller than intKey/pIdxKey or if the table is empty
drh1a844c32002-12-04 22:29:28 +00004396** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00004397**
4398** *pRes==0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004399** exactly matches intKey/pIdxKey.
drhbd03cae2001-06-02 02:40:57 +00004400**
4401** *pRes>0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004402** is larger than intKey/pIdxKey.
drhd677b3d2007-08-20 22:48:41 +00004403**
drha059ad02001-04-17 20:09:11 +00004404*/
drhe63d9992008-08-13 19:11:48 +00004405int sqlite3BtreeMovetoUnpacked(
4406 BtCursor *pCur, /* The cursor to be moved */
4407 UnpackedRecord *pIdxKey, /* Unpacked index key */
4408 i64 intKey, /* The table key */
4409 int biasRight, /* If true, bias the search to the high end */
4410 int *pRes /* Write search results here */
drhe4d90812007-03-29 05:51:49 +00004411){
drh72f82862001-05-24 21:06:34 +00004412 int rc;
drhd677b3d2007-08-20 22:48:41 +00004413
drh1fee73e2007-08-29 04:00:57 +00004414 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004415 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19775cb09632009-07-09 11:36:01 +00004416 assert( pRes );
danielk19773fd7cf52009-07-13 07:30:52 +00004417 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
drha2c20e42008-03-29 16:01:04 +00004418
4419 /* If the cursor is already positioned at the point we are trying
4420 ** to move to, then just return without doing any work */
danielk197771d5d2c2008-09-29 11:49:47 +00004421 if( pCur->eState==CURSOR_VALID && pCur->validNKey
4422 && pCur->apPage[0]->intKey
4423 ){
drhe63d9992008-08-13 19:11:48 +00004424 if( pCur->info.nKey==intKey ){
drha2c20e42008-03-29 16:01:04 +00004425 *pRes = 0;
4426 return SQLITE_OK;
4427 }
drhe63d9992008-08-13 19:11:48 +00004428 if( pCur->atLast && pCur->info.nKey<intKey ){
drha2c20e42008-03-29 16:01:04 +00004429 *pRes = -1;
4430 return SQLITE_OK;
4431 }
4432 }
4433
drh5e2f8b92001-05-28 00:41:15 +00004434 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004435 if( rc ){
4436 return rc;
4437 }
danielk197771d5d2c2008-09-29 11:49:47 +00004438 assert( pCur->apPage[pCur->iPage] );
4439 assert( pCur->apPage[pCur->iPage]->isInit );
danielk1977171fff32009-07-11 05:06:51 +00004440 assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
danielk1977da184232006-01-05 11:34:32 +00004441 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00004442 *pRes = -1;
danielk197771d5d2c2008-09-29 11:49:47 +00004443 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhc39e0002004-05-07 23:50:57 +00004444 return SQLITE_OK;
4445 }
danielk197771d5d2c2008-09-29 11:49:47 +00004446 assert( pCur->apPage[0]->intKey || pIdxKey );
drh14684382006-11-30 13:05:29 +00004447 for(;;){
drh72f82862001-05-24 21:06:34 +00004448 int lwr, upr;
4449 Pgno chldPg;
danielk197771d5d2c2008-09-29 11:49:47 +00004450 MemPage *pPage = pCur->apPage[pCur->iPage];
danielk1977171fff32009-07-11 05:06:51 +00004451 int c;
4452
4453 /* pPage->nCell must be greater than zero. If this is the root-page
4454 ** the cursor would have been INVALID above and this for(;;) loop
4455 ** not run. If this is not the root-page, then the moveToChild() routine
danielk19773fd7cf52009-07-13 07:30:52 +00004456 ** would have already detected db corruption. Similarly, pPage must
4457 ** be the right kind (index or table) of b-tree page. Otherwise
4458 ** a moveToChild() or moveToRoot() call would have detected corruption. */
danielk1977171fff32009-07-11 05:06:51 +00004459 assert( pPage->nCell>0 );
danielk19773fd7cf52009-07-13 07:30:52 +00004460 assert( pPage->intKey==(pIdxKey==0) );
drh72f82862001-05-24 21:06:34 +00004461 lwr = 0;
4462 upr = pPage->nCell-1;
drhe4d90812007-03-29 05:51:49 +00004463 if( biasRight ){
drhf49661a2008-12-10 16:45:50 +00004464 pCur->aiIdx[pCur->iPage] = (u16)upr;
drhe4d90812007-03-29 05:51:49 +00004465 }else{
drhf49661a2008-12-10 16:45:50 +00004466 pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
drhe4d90812007-03-29 05:51:49 +00004467 }
drh64022502009-01-09 14:11:04 +00004468 for(;;){
danielk197711c327a2009-05-04 19:01:26 +00004469 int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
4470 u8 *pCell; /* Pointer to current cell in pPage */
4471
drh366fda62006-01-13 02:35:09 +00004472 pCur->info.nSize = 0;
danielk197711c327a2009-05-04 19:01:26 +00004473 pCell = findCell(pPage, idx) + pPage->childPtrSize;
drh3aac2dd2004-04-26 14:10:20 +00004474 if( pPage->intKey ){
danielk197711c327a2009-05-04 19:01:26 +00004475 i64 nCellKey;
drhd172f862006-01-12 15:01:15 +00004476 if( pPage->hasData ){
danielk1977bab45c62006-01-16 15:14:27 +00004477 u32 dummy;
shane3f8d5cf2008-04-24 19:15:09 +00004478 pCell += getVarint32(pCell, dummy);
drhd172f862006-01-12 15:01:15 +00004479 }
drha2c20e42008-03-29 16:01:04 +00004480 getVarint(pCell, (u64*)&nCellKey);
drhe63d9992008-08-13 19:11:48 +00004481 if( nCellKey==intKey ){
drh3aac2dd2004-04-26 14:10:20 +00004482 c = 0;
drhe63d9992008-08-13 19:11:48 +00004483 }else if( nCellKey<intKey ){
drh41eb9e92008-04-02 18:33:07 +00004484 c = -1;
4485 }else{
drhe63d9992008-08-13 19:11:48 +00004486 assert( nCellKey>intKey );
drh41eb9e92008-04-02 18:33:07 +00004487 c = +1;
drh3aac2dd2004-04-26 14:10:20 +00004488 }
danielk197711c327a2009-05-04 19:01:26 +00004489 pCur->validNKey = 1;
4490 pCur->info.nKey = nCellKey;
drh3aac2dd2004-04-26 14:10:20 +00004491 }else{
drhb2eced52010-08-12 02:41:12 +00004492 /* The maximum supported page-size is 65536 bytes. This means that
danielk197711c327a2009-05-04 19:01:26 +00004493 ** the maximum number of record bytes stored on an index B-Tree
drhb2eced52010-08-12 02:41:12 +00004494 ** page is less than 16384 bytes and may be stored as a 2-byte
danielk197711c327a2009-05-04 19:01:26 +00004495 ** varint. This information is used to attempt to avoid parsing
4496 ** the entire cell by checking for the cases where the record is
4497 ** stored entirely within the b-tree page by inspecting the first
4498 ** 2 bytes of the cell.
4499 */
4500 int nCell = pCell[0];
4501 if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
4502 /* This branch runs if the record-size field of the cell is a
4503 ** single byte varint and the record fits entirely on the main
4504 ** b-tree page. */
4505 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
4506 }else if( !(pCell[1] & 0x80)
4507 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
4508 ){
4509 /* The record-size field is a 2 byte varint and the record
4510 ** fits entirely on the main b-tree page. */
4511 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
drhe51c44f2004-05-30 20:46:09 +00004512 }else{
danielk197711c327a2009-05-04 19:01:26 +00004513 /* The record flows over onto one or more overflow pages. In
4514 ** this case the whole cell needs to be parsed, a buffer allocated
4515 ** and accessPayload() used to retrieve the record into the
4516 ** buffer before VdbeRecordCompare() can be called. */
4517 void *pCellKey;
4518 u8 * const pCellBody = pCell - pPage->childPtrSize;
danielk197730548662009-07-09 05:07:37 +00004519 btreeParseCellPtr(pPage, pCellBody, &pCur->info);
shane60a4b532009-05-06 18:57:09 +00004520 nCell = (int)pCur->info.nKey;
danielk197711c327a2009-05-04 19:01:26 +00004521 pCellKey = sqlite3Malloc( nCell );
danielk19776507ecb2008-03-25 09:56:44 +00004522 if( pCellKey==0 ){
4523 rc = SQLITE_NOMEM;
4524 goto moveto_finish;
4525 }
drhfb192682009-07-11 18:26:28 +00004526 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
drhec9b31f2009-08-25 13:53:49 +00004527 if( rc ){
4528 sqlite3_free(pCellKey);
4529 goto moveto_finish;
4530 }
danielk197711c327a2009-05-04 19:01:26 +00004531 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
drhfacf0302008-06-17 15:12:00 +00004532 sqlite3_free(pCellKey);
drhe51c44f2004-05-30 20:46:09 +00004533 }
drh3aac2dd2004-04-26 14:10:20 +00004534 }
drh72f82862001-05-24 21:06:34 +00004535 if( c==0 ){
drh44845222008-07-17 18:39:57 +00004536 if( pPage->intKey && !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00004537 lwr = idx;
drhfc70e6f2004-05-12 21:11:27 +00004538 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00004539 break;
4540 }else{
drh64022502009-01-09 14:11:04 +00004541 *pRes = 0;
drh1e968a02008-03-25 00:22:21 +00004542 rc = SQLITE_OK;
4543 goto moveto_finish;
drh8b18dd42004-05-12 19:18:15 +00004544 }
drh72f82862001-05-24 21:06:34 +00004545 }
4546 if( c<0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00004547 lwr = idx+1;
drh72f82862001-05-24 21:06:34 +00004548 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004549 upr = idx-1;
drh72f82862001-05-24 21:06:34 +00004550 }
drhf1d68b32007-03-29 04:43:26 +00004551 if( lwr>upr ){
4552 break;
4553 }
drhf49661a2008-12-10 16:45:50 +00004554 pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
drh72f82862001-05-24 21:06:34 +00004555 }
4556 assert( lwr==upr+1 );
danielk197771d5d2c2008-09-29 11:49:47 +00004557 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00004558 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00004559 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00004560 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00004561 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00004562 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00004563 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00004564 }
4565 if( chldPg==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00004566 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
danielk19775cb09632009-07-09 11:36:01 +00004567 *pRes = c;
drh1e968a02008-03-25 00:22:21 +00004568 rc = SQLITE_OK;
4569 goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00004570 }
drhf49661a2008-12-10 16:45:50 +00004571 pCur->aiIdx[pCur->iPage] = (u16)lwr;
drh271efa52004-05-30 19:19:05 +00004572 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004573 pCur->validNKey = 0;
drh8178a752003-01-05 21:41:40 +00004574 rc = moveToChild(pCur, chldPg);
drh1e968a02008-03-25 00:22:21 +00004575 if( rc ) goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00004576 }
drh1e968a02008-03-25 00:22:21 +00004577moveto_finish:
drhe63d9992008-08-13 19:11:48 +00004578 return rc;
4579}
4580
drhd677b3d2007-08-20 22:48:41 +00004581
drh72f82862001-05-24 21:06:34 +00004582/*
drhc39e0002004-05-07 23:50:57 +00004583** Return TRUE if the cursor is not pointing at an entry of the table.
4584**
4585** TRUE will be returned after a call to sqlite3BtreeNext() moves
4586** past the last entry in the table or sqlite3BtreePrev() moves past
4587** the first entry. TRUE is also returned if the table is empty.
4588*/
4589int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00004590 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
4591 ** have been deleted? This API will need to change to return an error code
4592 ** as well as the boolean result value.
4593 */
4594 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00004595}
4596
4597/*
drhbd03cae2001-06-02 02:40:57 +00004598** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00004599** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00004600** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00004601** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00004602*/
drhd094db12008-04-03 21:46:57 +00004603int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00004604 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00004605 int idx;
danielk197797a227c2006-01-20 16:32:04 +00004606 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00004607
drh1fee73e2007-08-29 04:00:57 +00004608 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004609 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004610 if( rc!=SQLITE_OK ){
4611 return rc;
4612 }
drh8c4d3a62007-04-06 01:03:32 +00004613 assert( pRes!=0 );
drh8c4d3a62007-04-06 01:03:32 +00004614 if( CURSOR_INVALID==pCur->eState ){
4615 *pRes = 1;
4616 return SQLITE_OK;
4617 }
drh4c301aa2009-07-15 17:25:45 +00004618 if( pCur->skipNext>0 ){
4619 pCur->skipNext = 0;
danielk1977da184232006-01-05 11:34:32 +00004620 *pRes = 0;
4621 return SQLITE_OK;
4622 }
drh4c301aa2009-07-15 17:25:45 +00004623 pCur->skipNext = 0;
danielk1977da184232006-01-05 11:34:32 +00004624
danielk197771d5d2c2008-09-29 11:49:47 +00004625 pPage = pCur->apPage[pCur->iPage];
4626 idx = ++pCur->aiIdx[pCur->iPage];
4627 assert( pPage->isInit );
4628 assert( idx<=pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00004629
drh271efa52004-05-30 19:19:05 +00004630 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004631 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004632 if( idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00004633 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004634 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00004635 if( rc ) return rc;
4636 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00004637 *pRes = 0;
4638 return rc;
drh72f82862001-05-24 21:06:34 +00004639 }
drh5e2f8b92001-05-28 00:41:15 +00004640 do{
danielk197771d5d2c2008-09-29 11:49:47 +00004641 if( pCur->iPage==0 ){
drh8c1238a2003-01-02 14:43:55 +00004642 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00004643 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00004644 return SQLITE_OK;
4645 }
danielk197730548662009-07-09 05:07:37 +00004646 moveToParent(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00004647 pPage = pCur->apPage[pCur->iPage];
4648 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00004649 *pRes = 0;
drh44845222008-07-17 18:39:57 +00004650 if( pPage->intKey ){
drh8b18dd42004-05-12 19:18:15 +00004651 rc = sqlite3BtreeNext(pCur, pRes);
4652 }else{
4653 rc = SQLITE_OK;
4654 }
4655 return rc;
drh8178a752003-01-05 21:41:40 +00004656 }
4657 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00004658 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00004659 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00004660 }
drh5e2f8b92001-05-28 00:41:15 +00004661 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00004662 return rc;
drh72f82862001-05-24 21:06:34 +00004663}
drhd677b3d2007-08-20 22:48:41 +00004664
drh72f82862001-05-24 21:06:34 +00004665
drh3b7511c2001-05-26 13:15:44 +00004666/*
drh2dcc9aa2002-12-04 13:40:25 +00004667** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00004668** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00004669** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00004670** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00004671*/
drhd094db12008-04-03 21:46:57 +00004672int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00004673 int rc;
drh8178a752003-01-05 21:41:40 +00004674 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00004675
drh1fee73e2007-08-29 04:00:57 +00004676 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004677 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004678 if( rc!=SQLITE_OK ){
4679 return rc;
4680 }
drha2c20e42008-03-29 16:01:04 +00004681 pCur->atLast = 0;
drh8c4d3a62007-04-06 01:03:32 +00004682 if( CURSOR_INVALID==pCur->eState ){
4683 *pRes = 1;
4684 return SQLITE_OK;
4685 }
drh4c301aa2009-07-15 17:25:45 +00004686 if( pCur->skipNext<0 ){
4687 pCur->skipNext = 0;
danielk1977da184232006-01-05 11:34:32 +00004688 *pRes = 0;
4689 return SQLITE_OK;
4690 }
drh4c301aa2009-07-15 17:25:45 +00004691 pCur->skipNext = 0;
danielk1977da184232006-01-05 11:34:32 +00004692
danielk197771d5d2c2008-09-29 11:49:47 +00004693 pPage = pCur->apPage[pCur->iPage];
4694 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00004695 if( !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00004696 int idx = pCur->aiIdx[pCur->iPage];
4697 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
drhd677b3d2007-08-20 22:48:41 +00004698 if( rc ){
4699 return rc;
4700 }
drh2dcc9aa2002-12-04 13:40:25 +00004701 rc = moveToRightmost(pCur);
4702 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004703 while( pCur->aiIdx[pCur->iPage]==0 ){
4704 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00004705 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00004706 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00004707 return SQLITE_OK;
4708 }
danielk197730548662009-07-09 05:07:37 +00004709 moveToParent(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00004710 }
drh271efa52004-05-30 19:19:05 +00004711 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004712 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004713
4714 pCur->aiIdx[pCur->iPage]--;
4715 pPage = pCur->apPage[pCur->iPage];
drh44845222008-07-17 18:39:57 +00004716 if( pPage->intKey && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00004717 rc = sqlite3BtreePrevious(pCur, pRes);
4718 }else{
4719 rc = SQLITE_OK;
4720 }
drh2dcc9aa2002-12-04 13:40:25 +00004721 }
drh8178a752003-01-05 21:41:40 +00004722 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00004723 return rc;
4724}
4725
4726/*
drh3b7511c2001-05-26 13:15:44 +00004727** Allocate a new page from the database file.
4728**
danielk19773b8a05f2007-03-19 17:44:26 +00004729** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00004730** has already been called on the new page.) The new page has also
4731** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00004732** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00004733**
4734** SQLITE_OK is returned on success. Any other return value indicates
4735** an error. *ppPage and *pPgno are undefined in the event of an error.
danielk19773b8a05f2007-03-19 17:44:26 +00004736** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00004737**
drh199e3cf2002-07-18 11:01:47 +00004738** If the "nearby" parameter is not 0, then a (feeble) effort is made to
4739** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00004740** attempt to keep related pages close to each other in the database file,
4741** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00004742**
4743** If the "exact" parameter is not 0, and the page-number nearby exists
4744** anywhere on the free-list, then it is guarenteed to be returned. This
4745** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00004746*/
drh4f0c5872007-03-26 22:05:01 +00004747static int allocateBtreePage(
danielk1977aef0bf62005-12-30 16:28:01 +00004748 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00004749 MemPage **ppPage,
4750 Pgno *pPgno,
4751 Pgno nearby,
4752 u8 exact
4753){
drh3aac2dd2004-04-26 14:10:20 +00004754 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00004755 int rc;
drh35cd6432009-06-05 14:17:21 +00004756 u32 n; /* Number of pages on the freelist */
drh042d6a12009-06-17 13:57:16 +00004757 u32 k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00004758 MemPage *pTrunk = 0;
4759 MemPage *pPrevTrunk = 0;
drh1662b5a2009-06-04 19:06:09 +00004760 Pgno mxPage; /* Total size of the database file */
drh30e58752002-03-02 20:41:57 +00004761
drh1fee73e2007-08-29 04:00:57 +00004762 assert( sqlite3_mutex_held(pBt->mutex) );
drh3aac2dd2004-04-26 14:10:20 +00004763 pPage1 = pBt->pPage1;
drhb1299152010-03-30 22:58:33 +00004764 mxPage = btreePagecount(pBt);
drh3aac2dd2004-04-26 14:10:20 +00004765 n = get4byte(&pPage1->aData[36]);
drhdf35a082009-07-09 02:24:35 +00004766 testcase( n==mxPage-1 );
4767 if( n>=mxPage ){
drh1662b5a2009-06-04 19:06:09 +00004768 return SQLITE_CORRUPT_BKPT;
4769 }
drh3aac2dd2004-04-26 14:10:20 +00004770 if( n>0 ){
drh91025292004-05-03 19:49:32 +00004771 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00004772 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004773 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
4774
4775 /* If the 'exact' parameter was true and a query of the pointer-map
4776 ** shows that the page 'nearby' is somewhere on the free-list, then
4777 ** the entire-list will be searched for that page.
4778 */
4779#ifndef SQLITE_OMIT_AUTOVACUUM
drh1662b5a2009-06-04 19:06:09 +00004780 if( exact && nearby<=mxPage ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004781 u8 eType;
4782 assert( nearby>0 );
4783 assert( pBt->autoVacuum );
4784 rc = ptrmapGet(pBt, nearby, &eType, 0);
4785 if( rc ) return rc;
4786 if( eType==PTRMAP_FREEPAGE ){
4787 searchList = 1;
4788 }
4789 *pPgno = nearby;
4790 }
4791#endif
4792
4793 /* Decrement the free-list count by 1. Set iTrunk to the index of the
4794 ** first free-list trunk page. iPrevTrunk is initially 1.
4795 */
danielk19773b8a05f2007-03-19 17:44:26 +00004796 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00004797 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004798 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004799
4800 /* The code within this loop is run only once if the 'searchList' variable
4801 ** is not true. Otherwise, it runs once for each trunk-page on the
4802 ** free-list until the page 'nearby' is located.
4803 */
4804 do {
4805 pPrevTrunk = pTrunk;
4806 if( pPrevTrunk ){
4807 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00004808 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004809 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00004810 }
drhdf35a082009-07-09 02:24:35 +00004811 testcase( iTrunk==mxPage );
drh1662b5a2009-06-04 19:06:09 +00004812 if( iTrunk>mxPage ){
4813 rc = SQLITE_CORRUPT_BKPT;
4814 }else{
danielk197730548662009-07-09 05:07:37 +00004815 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
drh1662b5a2009-06-04 19:06:09 +00004816 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004817 if( rc ){
drhd3627af2006-12-18 18:34:51 +00004818 pTrunk = 0;
4819 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004820 }
4821
drh93b4fc72011-04-07 14:47:01 +00004822 k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
danielk1977cb1a7eb2004-11-05 12:27:02 +00004823 if( k==0 && !searchList ){
4824 /* The trunk has no leaves and the list is not being searched.
4825 ** So extract the trunk page itself and use it as the newly
4826 ** allocated page */
4827 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00004828 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004829 if( rc ){
4830 goto end_allocate_page;
4831 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004832 *pPgno = iTrunk;
4833 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4834 *ppPage = pTrunk;
4835 pTrunk = 0;
4836 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh042d6a12009-06-17 13:57:16 +00004837 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004838 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00004839 rc = SQLITE_CORRUPT_BKPT;
4840 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004841#ifndef SQLITE_OMIT_AUTOVACUUM
4842 }else if( searchList && nearby==iTrunk ){
4843 /* The list is being searched and this trunk page is the page
4844 ** to allocate, regardless of whether it has leaves.
4845 */
4846 assert( *pPgno==iTrunk );
4847 *ppPage = pTrunk;
4848 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00004849 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004850 if( rc ){
4851 goto end_allocate_page;
4852 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004853 if( k==0 ){
4854 if( !pPrevTrunk ){
4855 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4856 }else{
danf48c3552010-08-23 15:41:24 +00004857 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
4858 if( rc!=SQLITE_OK ){
4859 goto end_allocate_page;
4860 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004861 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
4862 }
4863 }else{
4864 /* The trunk page is required by the caller but it contains
4865 ** pointers to free-list leaves. The first leaf becomes a trunk
4866 ** page in this case.
4867 */
4868 MemPage *pNewTrunk;
4869 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh1662b5a2009-06-04 19:06:09 +00004870 if( iNewTrunk>mxPage ){
4871 rc = SQLITE_CORRUPT_BKPT;
4872 goto end_allocate_page;
4873 }
drhdf35a082009-07-09 02:24:35 +00004874 testcase( iNewTrunk==mxPage );
danielk197730548662009-07-09 05:07:37 +00004875 rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004876 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00004877 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004878 }
danielk19773b8a05f2007-03-19 17:44:26 +00004879 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004880 if( rc!=SQLITE_OK ){
4881 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00004882 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004883 }
4884 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
4885 put4byte(&pNewTrunk->aData[4], k-1);
4886 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00004887 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004888 if( !pPrevTrunk ){
drhc5053fb2008-11-27 02:22:10 +00004889 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
danielk1977cb1a7eb2004-11-05 12:27:02 +00004890 put4byte(&pPage1->aData[32], iNewTrunk);
4891 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00004892 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004893 if( rc ){
4894 goto end_allocate_page;
4895 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004896 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
4897 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004898 }
4899 pTrunk = 0;
4900 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
4901#endif
danielk1977e5765212009-06-17 11:13:28 +00004902 }else if( k>0 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004903 /* Extract a leaf from the trunk */
drh042d6a12009-06-17 13:57:16 +00004904 u32 closest;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004905 Pgno iPage;
4906 unsigned char *aData = pTrunk->aData;
4907 if( nearby>0 ){
drh042d6a12009-06-17 13:57:16 +00004908 u32 i;
4909 int dist;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004910 closest = 0;
drhd50ffc42011-03-08 02:38:28 +00004911 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004912 for(i=1; i<k; i++){
drhd50ffc42011-03-08 02:38:28 +00004913 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004914 if( d2<dist ){
4915 closest = i;
4916 dist = d2;
4917 }
4918 }
4919 }else{
4920 closest = 0;
4921 }
4922
4923 iPage = get4byte(&aData[8+closest*4]);
drhdf35a082009-07-09 02:24:35 +00004924 testcase( iPage==mxPage );
drh1662b5a2009-06-04 19:06:09 +00004925 if( iPage>mxPage ){
4926 rc = SQLITE_CORRUPT_BKPT;
4927 goto end_allocate_page;
4928 }
drhdf35a082009-07-09 02:24:35 +00004929 testcase( iPage==mxPage );
danielk1977cb1a7eb2004-11-05 12:27:02 +00004930 if( !searchList || iPage==nearby ){
danielk1977bea2a942009-01-20 17:06:27 +00004931 int noContent;
shane1f9e6aa2008-06-09 19:27:11 +00004932 *pPgno = iPage;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004933 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
4934 ": %d more free pages\n",
4935 *pPgno, closest+1, k, pTrunk->pgno, n-1));
drh93b4fc72011-04-07 14:47:01 +00004936 rc = sqlite3PagerWrite(pTrunk->pDbPage);
4937 if( rc ) goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004938 if( closest<k-1 ){
4939 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
4940 }
4941 put4byte(&aData[4], k-1);
danielk1977bea2a942009-01-20 17:06:27 +00004942 noContent = !btreeGetHasContent(pBt, *pPgno);
danielk197730548662009-07-09 05:07:37 +00004943 rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004944 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00004945 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004946 if( rc!=SQLITE_OK ){
4947 releasePage(*ppPage);
4948 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004949 }
4950 searchList = 0;
4951 }
drhee696e22004-08-30 16:52:17 +00004952 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004953 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00004954 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004955 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00004956 }else{
drh3aac2dd2004-04-26 14:10:20 +00004957 /* There are no pages on the freelist, so create a new page at the
4958 ** end of the file */
drhdd3cd972010-03-27 17:12:36 +00004959 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
4960 if( rc ) return rc;
4961 pBt->nPage++;
4962 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
danielk1977bea2a942009-01-20 17:06:27 +00004963
danielk1977afcdd022004-10-31 16:25:42 +00004964#ifndef SQLITE_OMIT_AUTOVACUUM
drhdd3cd972010-03-27 17:12:36 +00004965 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
danielk1977afcdd022004-10-31 16:25:42 +00004966 /* If *pPgno refers to a pointer-map page, allocate two new pages
4967 ** at the end of the file instead of one. The first allocated page
4968 ** becomes a new pointer-map page, the second is used by the caller.
4969 */
danielk1977ac861692009-03-28 10:54:22 +00004970 MemPage *pPg = 0;
drhdd3cd972010-03-27 17:12:36 +00004971 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
4972 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
drh5e0ccc22010-03-29 19:36:52 +00004973 rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
danielk1977ac861692009-03-28 10:54:22 +00004974 if( rc==SQLITE_OK ){
4975 rc = sqlite3PagerWrite(pPg->pDbPage);
4976 releasePage(pPg);
4977 }
4978 if( rc ) return rc;
drhdd3cd972010-03-27 17:12:36 +00004979 pBt->nPage++;
4980 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
danielk1977afcdd022004-10-31 16:25:42 +00004981 }
4982#endif
drhdd3cd972010-03-27 17:12:36 +00004983 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
4984 *pPgno = pBt->nPage;
danielk1977afcdd022004-10-31 16:25:42 +00004985
danielk1977599fcba2004-11-08 07:13:13 +00004986 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drh5e0ccc22010-03-29 19:36:52 +00004987 rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
drh3b7511c2001-05-26 13:15:44 +00004988 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00004989 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004990 if( rc!=SQLITE_OK ){
4991 releasePage(*ppPage);
4992 }
drh3a4c1412004-05-09 20:40:11 +00004993 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00004994 }
danielk1977599fcba2004-11-08 07:13:13 +00004995
4996 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00004997
4998end_allocate_page:
4999 releasePage(pTrunk);
5000 releasePage(pPrevTrunk);
danielk1977b247c212008-11-21 09:09:01 +00005001 if( rc==SQLITE_OK ){
5002 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
5003 releasePage(*ppPage);
5004 return SQLITE_CORRUPT_BKPT;
5005 }
5006 (*ppPage)->isInit = 0;
danielk1977a50d9aa2009-06-08 14:49:45 +00005007 }else{
5008 *ppPage = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00005009 }
drh93b4fc72011-04-07 14:47:01 +00005010 assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
drh3b7511c2001-05-26 13:15:44 +00005011 return rc;
5012}
5013
5014/*
danielk1977bea2a942009-01-20 17:06:27 +00005015** This function is used to add page iPage to the database file free-list.
5016** It is assumed that the page is not already a part of the free-list.
drh5e2f8b92001-05-28 00:41:15 +00005017**
danielk1977bea2a942009-01-20 17:06:27 +00005018** The value passed as the second argument to this function is optional.
5019** If the caller happens to have a pointer to the MemPage object
5020** corresponding to page iPage handy, it may pass it as the second value.
5021** Otherwise, it may pass NULL.
5022**
5023** If a pointer to a MemPage object is passed as the second argument,
5024** its reference count is not altered by this function.
drh3b7511c2001-05-26 13:15:44 +00005025*/
danielk1977bea2a942009-01-20 17:06:27 +00005026static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
5027 MemPage *pTrunk = 0; /* Free-list trunk page */
5028 Pgno iTrunk = 0; /* Page number of free-list trunk page */
5029 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
5030 MemPage *pPage; /* Page being freed. May be NULL. */
5031 int rc; /* Return Code */
5032 int nFree; /* Initial number of pages on free-list */
drh8b2f49b2001-06-08 00:21:52 +00005033
danielk1977bea2a942009-01-20 17:06:27 +00005034 assert( sqlite3_mutex_held(pBt->mutex) );
5035 assert( iPage>1 );
5036 assert( !pMemPage || pMemPage->pgno==iPage );
5037
5038 if( pMemPage ){
5039 pPage = pMemPage;
5040 sqlite3PagerRef(pPage->pDbPage);
5041 }else{
5042 pPage = btreePageLookup(pBt, iPage);
5043 }
drh3aac2dd2004-04-26 14:10:20 +00005044
drha34b6762004-05-07 13:30:42 +00005045 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00005046 rc = sqlite3PagerWrite(pPage1->pDbPage);
danielk1977bea2a942009-01-20 17:06:27 +00005047 if( rc ) goto freepage_out;
5048 nFree = get4byte(&pPage1->aData[36]);
5049 put4byte(&pPage1->aData[36], nFree+1);
drh3aac2dd2004-04-26 14:10:20 +00005050
drh5b47efa2010-02-12 18:18:39 +00005051 if( pBt->secureDelete ){
5052 /* If the secure_delete option is enabled, then
5053 ** always fully overwrite deleted information with zeros.
5054 */
shaneh84f4b2f2010-02-26 01:46:54 +00005055 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
5056 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
drh5b47efa2010-02-12 18:18:39 +00005057 ){
5058 goto freepage_out;
5059 }
5060 memset(pPage->aData, 0, pPage->pBt->pageSize);
danielk1977bea2a942009-01-20 17:06:27 +00005061 }
drhfcce93f2006-02-22 03:08:32 +00005062
danielk1977687566d2004-11-02 12:56:41 +00005063 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00005064 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00005065 */
danielk197785d90ca2008-07-19 14:25:15 +00005066 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00005067 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
danielk1977bea2a942009-01-20 17:06:27 +00005068 if( rc ) goto freepage_out;
danielk1977687566d2004-11-02 12:56:41 +00005069 }
danielk1977687566d2004-11-02 12:56:41 +00005070
danielk1977bea2a942009-01-20 17:06:27 +00005071 /* Now manipulate the actual database free-list structure. There are two
5072 ** possibilities. If the free-list is currently empty, or if the first
5073 ** trunk page in the free-list is full, then this page will become a
5074 ** new free-list trunk page. Otherwise, it will become a leaf of the
5075 ** first trunk page in the current free-list. This block tests if it
5076 ** is possible to add the page as a new free-list leaf.
5077 */
5078 if( nFree!=0 ){
drhc046e3e2009-07-15 11:26:44 +00005079 u32 nLeaf; /* Initial number of leaf cells on trunk page */
danielk1977bea2a942009-01-20 17:06:27 +00005080
5081 iTrunk = get4byte(&pPage1->aData[32]);
danielk197730548662009-07-09 05:07:37 +00005082 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977bea2a942009-01-20 17:06:27 +00005083 if( rc!=SQLITE_OK ){
5084 goto freepage_out;
5085 }
5086
5087 nLeaf = get4byte(&pTrunk->aData[4]);
drheeb844a2009-08-08 18:01:07 +00005088 assert( pBt->usableSize>32 );
5089 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
danielk1977bea2a942009-01-20 17:06:27 +00005090 rc = SQLITE_CORRUPT_BKPT;
5091 goto freepage_out;
5092 }
drheeb844a2009-08-08 18:01:07 +00005093 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
danielk1977bea2a942009-01-20 17:06:27 +00005094 /* In this case there is room on the trunk page to insert the page
5095 ** being freed as a new leaf.
drh45b1fac2008-07-04 17:52:42 +00005096 **
5097 ** Note that the trunk page is not really full until it contains
5098 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
5099 ** coded. But due to a coding error in versions of SQLite prior to
5100 ** 3.6.0, databases with freelist trunk pages holding more than
5101 ** usableSize/4 - 8 entries will be reported as corrupt. In order
5102 ** to maintain backwards compatibility with older versions of SQLite,
drhc046e3e2009-07-15 11:26:44 +00005103 ** we will continue to restrict the number of entries to usableSize/4 - 8
drh45b1fac2008-07-04 17:52:42 +00005104 ** for now. At some point in the future (once everyone has upgraded
5105 ** to 3.6.0 or later) we should consider fixing the conditional above
5106 ** to read "usableSize/4-2" instead of "usableSize/4-8".
5107 */
danielk19773b8a05f2007-03-19 17:44:26 +00005108 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00005109 if( rc==SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00005110 put4byte(&pTrunk->aData[4], nLeaf+1);
5111 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
drh5b47efa2010-02-12 18:18:39 +00005112 if( pPage && !pBt->secureDelete ){
danielk1977bea2a942009-01-20 17:06:27 +00005113 sqlite3PagerDontWrite(pPage->pDbPage);
5114 }
danielk1977bea2a942009-01-20 17:06:27 +00005115 rc = btreeSetHasContent(pBt, iPage);
drhf5345442007-04-09 12:45:02 +00005116 }
drh3a4c1412004-05-09 20:40:11 +00005117 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
danielk1977bea2a942009-01-20 17:06:27 +00005118 goto freepage_out;
drh3aac2dd2004-04-26 14:10:20 +00005119 }
drh3b7511c2001-05-26 13:15:44 +00005120 }
danielk1977bea2a942009-01-20 17:06:27 +00005121
5122 /* If control flows to this point, then it was not possible to add the
5123 ** the page being freed as a leaf page of the first trunk in the free-list.
5124 ** Possibly because the free-list is empty, or possibly because the
5125 ** first trunk in the free-list is full. Either way, the page being freed
5126 ** will become the new first trunk page in the free-list.
5127 */
drhc046e3e2009-07-15 11:26:44 +00005128 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
5129 goto freepage_out;
5130 }
5131 rc = sqlite3PagerWrite(pPage->pDbPage);
5132 if( rc!=SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00005133 goto freepage_out;
5134 }
5135 put4byte(pPage->aData, iTrunk);
5136 put4byte(&pPage->aData[4], 0);
5137 put4byte(&pPage1->aData[32], iPage);
5138 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
5139
5140freepage_out:
5141 if( pPage ){
5142 pPage->isInit = 0;
5143 }
5144 releasePage(pPage);
5145 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00005146 return rc;
5147}
drhc314dc72009-07-21 11:52:34 +00005148static void freePage(MemPage *pPage, int *pRC){
5149 if( (*pRC)==SQLITE_OK ){
5150 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
5151 }
danielk1977bea2a942009-01-20 17:06:27 +00005152}
drh3b7511c2001-05-26 13:15:44 +00005153
5154/*
drh3aac2dd2004-04-26 14:10:20 +00005155** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00005156*/
drh3aac2dd2004-04-26 14:10:20 +00005157static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00005158 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00005159 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00005160 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00005161 int rc;
drh94440812007-03-06 11:42:19 +00005162 int nOvfl;
shaneh1df2db72010-08-18 02:28:48 +00005163 u32 ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00005164
drh1fee73e2007-08-29 04:00:57 +00005165 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197730548662009-07-09 05:07:37 +00005166 btreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005167 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00005168 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00005169 }
drh6f11bef2004-05-13 01:12:56 +00005170 ovflPgno = get4byte(&pCell[info.iOverflow]);
shane63207ab2009-02-04 01:49:30 +00005171 assert( pBt->usableSize > 4 );
drh94440812007-03-06 11:42:19 +00005172 ovflPageSize = pBt->usableSize - 4;
drh72365832007-03-06 15:53:44 +00005173 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
5174 assert( ovflPgno==0 || nOvfl>0 );
5175 while( nOvfl-- ){
shane63207ab2009-02-04 01:49:30 +00005176 Pgno iNext = 0;
danielk1977bea2a942009-01-20 17:06:27 +00005177 MemPage *pOvfl = 0;
drhb1299152010-03-30 22:58:33 +00005178 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
danielk1977e589a672009-04-11 16:06:15 +00005179 /* 0 is not a legal page number and page 1 cannot be an
5180 ** overflow page. Therefore if ovflPgno<2 or past the end of the
5181 ** file the database must be corrupt. */
drh49285702005-09-17 15:20:26 +00005182 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00005183 }
danielk1977bea2a942009-01-20 17:06:27 +00005184 if( nOvfl ){
5185 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
5186 if( rc ) return rc;
5187 }
dan887d4b22010-02-25 12:09:16 +00005188
shaneh1da207e2010-03-09 14:41:12 +00005189 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
dan887d4b22010-02-25 12:09:16 +00005190 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
5191 ){
5192 /* There is no reason any cursor should have an outstanding reference
5193 ** to an overflow page belonging to a cell that is being deleted/updated.
5194 ** So if there exists more than one reference to this page, then it
5195 ** must not really be an overflow page and the database must be corrupt.
5196 ** It is helpful to detect this before calling freePage2(), as
5197 ** freePage2() may zero the page contents if secure-delete mode is
5198 ** enabled. If this 'overflow' page happens to be a page that the
5199 ** caller is iterating through or using in some other way, this
5200 ** can be problematic.
5201 */
5202 rc = SQLITE_CORRUPT_BKPT;
5203 }else{
5204 rc = freePage2(pBt, pOvfl, ovflPgno);
5205 }
5206
danielk1977bea2a942009-01-20 17:06:27 +00005207 if( pOvfl ){
5208 sqlite3PagerUnref(pOvfl->pDbPage);
5209 }
drh3b7511c2001-05-26 13:15:44 +00005210 if( rc ) return rc;
danielk1977bea2a942009-01-20 17:06:27 +00005211 ovflPgno = iNext;
drh3b7511c2001-05-26 13:15:44 +00005212 }
drh5e2f8b92001-05-28 00:41:15 +00005213 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00005214}
5215
5216/*
drh91025292004-05-03 19:49:32 +00005217** Create the byte sequence used to represent a cell on page pPage
5218** and write that byte sequence into pCell[]. Overflow pages are
5219** allocated and filled in as necessary. The calling procedure
5220** is responsible for making sure sufficient space has been allocated
5221** for pCell[].
5222**
5223** Note that pCell does not necessary need to point to the pPage->aData
5224** area. pCell might point to some temporary storage. The cell will
5225** be constructed in this temporary area then copied into pPage->aData
5226** later.
drh3b7511c2001-05-26 13:15:44 +00005227*/
5228static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00005229 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00005230 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00005231 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00005232 const void *pData,int nData, /* The data */
drhb026e052007-05-02 01:34:31 +00005233 int nZero, /* Extra zero bytes to append to pData */
drh4b70f112004-05-02 21:12:19 +00005234 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00005235){
drh3b7511c2001-05-26 13:15:44 +00005236 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00005237 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00005238 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00005239 int spaceLeft;
5240 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00005241 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00005242 unsigned char *pPrior;
5243 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00005244 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00005245 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00005246 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00005247 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00005248
drh1fee73e2007-08-29 04:00:57 +00005249 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00005250
drhc5053fb2008-11-27 02:22:10 +00005251 /* pPage is not necessarily writeable since pCell might be auxiliary
5252 ** buffer space that is separate from the pPage buffer area */
5253 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
5254 || sqlite3PagerIswriteable(pPage->pDbPage) );
5255
drh91025292004-05-03 19:49:32 +00005256 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00005257 nHeader = 0;
drh91025292004-05-03 19:49:32 +00005258 if( !pPage->leaf ){
5259 nHeader += 4;
5260 }
drh8b18dd42004-05-12 19:18:15 +00005261 if( pPage->hasData ){
drhb026e052007-05-02 01:34:31 +00005262 nHeader += putVarint(&pCell[nHeader], nData+nZero);
drh6f11bef2004-05-13 01:12:56 +00005263 }else{
drhb026e052007-05-02 01:34:31 +00005264 nData = nZero = 0;
drh91025292004-05-03 19:49:32 +00005265 }
drh6f11bef2004-05-13 01:12:56 +00005266 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
danielk197730548662009-07-09 05:07:37 +00005267 btreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005268 assert( info.nHeader==nHeader );
5269 assert( info.nKey==nKey );
danielk197789d40042008-11-17 14:20:56 +00005270 assert( info.nData==(u32)(nData+nZero) );
drh6f11bef2004-05-13 01:12:56 +00005271
5272 /* Fill in the payload */
drhb026e052007-05-02 01:34:31 +00005273 nPayload = nData + nZero;
drh3aac2dd2004-04-26 14:10:20 +00005274 if( pPage->intKey ){
5275 pSrc = pData;
5276 nSrc = nData;
drh91025292004-05-03 19:49:32 +00005277 nData = 0;
drhf49661a2008-12-10 16:45:50 +00005278 }else{
danielk197731d31b82009-07-13 13:18:07 +00005279 if( NEVER(nKey>0x7fffffff || pKey==0) ){
5280 return SQLITE_CORRUPT_BKPT;
drh20abac22009-01-28 20:21:17 +00005281 }
drhf49661a2008-12-10 16:45:50 +00005282 nPayload += (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00005283 pSrc = pKey;
drhf49661a2008-12-10 16:45:50 +00005284 nSrc = (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00005285 }
drh6f11bef2004-05-13 01:12:56 +00005286 *pnSize = info.nSize;
5287 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00005288 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00005289 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00005290
drh3b7511c2001-05-26 13:15:44 +00005291 while( nPayload>0 ){
5292 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00005293#ifndef SQLITE_OMIT_AUTOVACUUM
5294 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00005295 if( pBt->autoVacuum ){
5296 do{
5297 pgnoOvfl++;
5298 } while(
5299 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
5300 );
danielk1977b39f70b2007-05-17 18:28:11 +00005301 }
danielk1977afcdd022004-10-31 16:25:42 +00005302#endif
drhf49661a2008-12-10 16:45:50 +00005303 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00005304#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00005305 /* If the database supports auto-vacuum, and the second or subsequent
5306 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00005307 ** for that page now.
5308 **
5309 ** If this is the first overflow page, then write a partial entry
5310 ** to the pointer-map. If we write nothing to this pointer-map slot,
5311 ** then the optimistic overflow chain processing in clearCell()
5312 ** may misinterpret the uninitialised values and delete the
5313 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00005314 */
danielk19774ef24492007-05-23 09:52:41 +00005315 if( pBt->autoVacuum && rc==SQLITE_OK ){
5316 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
drh98add2e2009-07-20 17:11:49 +00005317 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
danielk197789a4be82007-05-23 13:34:32 +00005318 if( rc ){
5319 releasePage(pOvfl);
5320 }
danielk1977afcdd022004-10-31 16:25:42 +00005321 }
5322#endif
drh3b7511c2001-05-26 13:15:44 +00005323 if( rc ){
drh9b171272004-05-08 02:03:22 +00005324 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00005325 return rc;
5326 }
drhc5053fb2008-11-27 02:22:10 +00005327
5328 /* If pToRelease is not zero than pPrior points into the data area
5329 ** of pToRelease. Make sure pToRelease is still writeable. */
5330 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
5331
5332 /* If pPrior is part of the data area of pPage, then make sure pPage
5333 ** is still writeable */
5334 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
5335 || sqlite3PagerIswriteable(pPage->pDbPage) );
5336
drh3aac2dd2004-04-26 14:10:20 +00005337 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00005338 releasePage(pToRelease);
5339 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00005340 pPrior = pOvfl->aData;
5341 put4byte(pPrior, 0);
5342 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00005343 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00005344 }
5345 n = nPayload;
5346 if( n>spaceLeft ) n = spaceLeft;
drhc5053fb2008-11-27 02:22:10 +00005347
5348 /* If pToRelease is not zero than pPayload points into the data area
5349 ** of pToRelease. Make sure pToRelease is still writeable. */
5350 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
5351
5352 /* If pPayload is part of the data area of pPage, then make sure pPage
5353 ** is still writeable */
5354 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
5355 || sqlite3PagerIswriteable(pPage->pDbPage) );
5356
drhb026e052007-05-02 01:34:31 +00005357 if( nSrc>0 ){
5358 if( n>nSrc ) n = nSrc;
5359 assert( pSrc );
5360 memcpy(pPayload, pSrc, n);
5361 }else{
5362 memset(pPayload, 0, n);
5363 }
drh3b7511c2001-05-26 13:15:44 +00005364 nPayload -= n;
drhde647132004-05-07 17:57:49 +00005365 pPayload += n;
drh9b171272004-05-08 02:03:22 +00005366 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00005367 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00005368 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00005369 if( nSrc==0 ){
5370 nSrc = nData;
5371 pSrc = pData;
5372 }
drhdd793422001-06-28 01:54:48 +00005373 }
drh9b171272004-05-08 02:03:22 +00005374 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00005375 return SQLITE_OK;
5376}
5377
drh14acc042001-06-10 19:56:58 +00005378/*
5379** Remove the i-th cell from pPage. This routine effects pPage only.
5380** The cell content is not freed or deallocated. It is assumed that
5381** the cell content has been copied someplace else. This routine just
5382** removes the reference to the cell from pPage.
5383**
5384** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00005385*/
drh98add2e2009-07-20 17:11:49 +00005386static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
drh43605152004-05-29 21:46:49 +00005387 int i; /* Loop counter */
drh43b18e12010-08-17 19:40:08 +00005388 u32 pc; /* Offset to cell content of cell being deleted */
drh43605152004-05-29 21:46:49 +00005389 u8 *data; /* pPage->aData */
5390 u8 *ptr; /* Used to move bytes around within data[] */
shanedcc50b72008-11-13 18:29:50 +00005391 int rc; /* The return code */
drhc314dc72009-07-21 11:52:34 +00005392 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
drh43605152004-05-29 21:46:49 +00005393
drh98add2e2009-07-20 17:11:49 +00005394 if( *pRC ) return;
5395
drh8c42ca92001-06-22 19:15:00 +00005396 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00005397 assert( sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00005398 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00005399 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00005400 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00005401 ptr = &data[pPage->cellOffset + 2*idx];
shane0af3f892008-11-12 04:55:34 +00005402 pc = get2byte(ptr);
drhc314dc72009-07-21 11:52:34 +00005403 hdr = pPage->hdrOffset;
5404 testcase( pc==get2byte(&data[hdr+5]) );
5405 testcase( pc+sz==pPage->pBt->usableSize );
drh43b18e12010-08-17 19:40:08 +00005406 if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
drh98add2e2009-07-20 17:11:49 +00005407 *pRC = SQLITE_CORRUPT_BKPT;
5408 return;
shane0af3f892008-11-12 04:55:34 +00005409 }
shanedcc50b72008-11-13 18:29:50 +00005410 rc = freeSpace(pPage, pc, sz);
drh98add2e2009-07-20 17:11:49 +00005411 if( rc ){
5412 *pRC = rc;
5413 return;
shanedcc50b72008-11-13 18:29:50 +00005414 }
drh43605152004-05-29 21:46:49 +00005415 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
5416 ptr[0] = ptr[2];
5417 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00005418 }
5419 pPage->nCell--;
drhc314dc72009-07-21 11:52:34 +00005420 put2byte(&data[hdr+3], pPage->nCell);
drh43605152004-05-29 21:46:49 +00005421 pPage->nFree += 2;
drh14acc042001-06-10 19:56:58 +00005422}
5423
5424/*
5425** Insert a new cell on pPage at cell index "i". pCell points to the
5426** content of the cell.
5427**
5428** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00005429** will not fit, then make a copy of the cell content into pTemp if
5430** pTemp is not null. Regardless of pTemp, allocate a new entry
5431** in pPage->aOvfl[] and make it point to the cell content (either
5432** in pTemp or the original pCell) and also record its index.
5433** Allocating a new entry in pPage->aCell[] implies that
5434** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00005435**
5436** If nSkip is non-zero, then do not copy the first nSkip bytes of the
5437** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00005438** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00005439** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00005440*/
drh98add2e2009-07-20 17:11:49 +00005441static void insertCell(
drh24cd67e2004-05-10 16:18:47 +00005442 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00005443 int i, /* New cell becomes the i-th cell of the page */
5444 u8 *pCell, /* Content of the new cell */
5445 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00005446 u8 *pTemp, /* Temp storage space for pCell, if needed */
drh98add2e2009-07-20 17:11:49 +00005447 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
5448 int *pRC /* Read and write return code from here */
drh24cd67e2004-05-10 16:18:47 +00005449){
drh383d30f2010-02-26 13:07:37 +00005450 int idx = 0; /* Where to write new cell content in data[] */
drh43605152004-05-29 21:46:49 +00005451 int j; /* Loop counter */
drh43605152004-05-29 21:46:49 +00005452 int end; /* First byte past the last cell pointer in data[] */
5453 int ins; /* Index in data[] where new cell pointer is inserted */
drh43605152004-05-29 21:46:49 +00005454 int cellOffset; /* Address of first cell pointer in data[] */
5455 u8 *data; /* The content of the whole page */
5456 u8 *ptr; /* Used for moving information around in data[] */
5457
danielk19774dbaa892009-06-16 16:50:22 +00005458 int nSkip = (iChild ? 4 : 0);
5459
drh98add2e2009-07-20 17:11:49 +00005460 if( *pRC ) return;
5461
drh43605152004-05-29 21:46:49 +00005462 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
drhb2eced52010-08-12 02:41:12 +00005463 assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
drhf49661a2008-12-10 16:45:50 +00005464 assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
drh1fee73e2007-08-29 04:00:57 +00005465 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc9b9b8a2009-12-03 21:26:52 +00005466 /* The cell should normally be sized correctly. However, when moving a
5467 ** malformed cell from a leaf page to an interior page, if the cell size
5468 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
5469 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
5470 ** the term after the || in the following assert(). */
5471 assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
drh43605152004-05-29 21:46:49 +00005472 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00005473 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00005474 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00005475 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00005476 }
danielk19774dbaa892009-06-16 16:50:22 +00005477 if( iChild ){
5478 put4byte(pCell, iChild);
5479 }
drh43605152004-05-29 21:46:49 +00005480 j = pPage->nOverflow++;
danielk197789d40042008-11-17 14:20:56 +00005481 assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
drh43605152004-05-29 21:46:49 +00005482 pPage->aOvfl[j].pCell = pCell;
drhf49661a2008-12-10 16:45:50 +00005483 pPage->aOvfl[j].idx = (u16)i;
drh14acc042001-06-10 19:56:58 +00005484 }else{
danielk19776e465eb2007-08-21 13:11:00 +00005485 int rc = sqlite3PagerWrite(pPage->pDbPage);
5486 if( rc!=SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +00005487 *pRC = rc;
5488 return;
danielk19776e465eb2007-08-21 13:11:00 +00005489 }
5490 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00005491 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00005492 cellOffset = pPage->cellOffset;
drh0a45c272009-07-08 01:49:11 +00005493 end = cellOffset + 2*pPage->nCell;
drh43605152004-05-29 21:46:49 +00005494 ins = cellOffset + 2*i;
drh0a45c272009-07-08 01:49:11 +00005495 rc = allocateSpace(pPage, sz, &idx);
drh98add2e2009-07-20 17:11:49 +00005496 if( rc ){ *pRC = rc; return; }
drhc314dc72009-07-21 11:52:34 +00005497 /* The allocateSpace() routine guarantees the following two properties
5498 ** if it returns success */
5499 assert( idx >= end+2 );
drhfcd71b62011-04-05 22:08:24 +00005500 assert( idx+sz <= (int)pPage->pBt->usableSize );
drh43605152004-05-29 21:46:49 +00005501 pPage->nCell++;
drh0a45c272009-07-08 01:49:11 +00005502 pPage->nFree -= (u16)(2 + sz);
danielk1977a3ad5e72005-01-07 08:56:44 +00005503 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
danielk19774dbaa892009-06-16 16:50:22 +00005504 if( iChild ){
5505 put4byte(&data[idx], iChild);
5506 }
drh0a45c272009-07-08 01:49:11 +00005507 for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
drh43605152004-05-29 21:46:49 +00005508 ptr[0] = ptr[-2];
5509 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00005510 }
drh43605152004-05-29 21:46:49 +00005511 put2byte(&data[ins], idx);
drh0a45c272009-07-08 01:49:11 +00005512 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
danielk1977a19df672004-11-03 11:37:07 +00005513#ifndef SQLITE_OMIT_AUTOVACUUM
5514 if( pPage->pBt->autoVacuum ){
5515 /* The cell may contain a pointer to an overflow page. If so, write
5516 ** the entry for the overflow page into the pointer map.
5517 */
drh98add2e2009-07-20 17:11:49 +00005518 ptrmapPutOvflPtr(pPage, pCell, pRC);
danielk1977a19df672004-11-03 11:37:07 +00005519 }
5520#endif
drh14acc042001-06-10 19:56:58 +00005521 }
5522}
5523
5524/*
drhfa1a98a2004-05-14 19:08:17 +00005525** Add a list of cells to a page. The page should be initially empty.
5526** The cells are guaranteed to fit on the page.
5527*/
5528static void assemblePage(
5529 MemPage *pPage, /* The page to be assemblied */
5530 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00005531 u8 **apCell, /* Pointers to cell bodies */
drha9121e42008-02-19 14:59:35 +00005532 u16 *aSize /* Sizes of the cells */
drhfa1a98a2004-05-14 19:08:17 +00005533){
5534 int i; /* Loop counter */
danielk1977fad91942009-04-29 17:49:59 +00005535 u8 *pCellptr; /* Address of next cell pointer */
drh43605152004-05-29 21:46:49 +00005536 int cellbody; /* Address of next cell body */
danielk1977fad91942009-04-29 17:49:59 +00005537 u8 * const data = pPage->aData; /* Pointer to data for pPage */
5538 const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
5539 const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
drhfa1a98a2004-05-14 19:08:17 +00005540
drh43605152004-05-29 21:46:49 +00005541 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00005542 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfcd71b62011-04-05 22:08:24 +00005543 assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
5544 && (int)MX_CELL(pPage->pBt)<=10921);
drhc5053fb2008-11-27 02:22:10 +00005545 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977fad91942009-04-29 17:49:59 +00005546
5547 /* Check that the page has just been zeroed by zeroPage() */
5548 assert( pPage->nCell==0 );
drh5d433ce2010-08-14 16:02:52 +00005549 assert( get2byteNotZero(&data[hdr+5])==nUsable );
danielk1977fad91942009-04-29 17:49:59 +00005550
5551 pCellptr = &data[pPage->cellOffset + nCell*2];
5552 cellbody = nUsable;
5553 for(i=nCell-1; i>=0; i--){
5554 pCellptr -= 2;
5555 cellbody -= aSize[i];
5556 put2byte(pCellptr, cellbody);
5557 memcpy(&data[cellbody], apCell[i], aSize[i]);
drhfa1a98a2004-05-14 19:08:17 +00005558 }
danielk1977fad91942009-04-29 17:49:59 +00005559 put2byte(&data[hdr+3], nCell);
5560 put2byte(&data[hdr+5], cellbody);
5561 pPage->nFree -= (nCell*2 + nUsable - cellbody);
drhf49661a2008-12-10 16:45:50 +00005562 pPage->nCell = (u16)nCell;
drhfa1a98a2004-05-14 19:08:17 +00005563}
5564
drh14acc042001-06-10 19:56:58 +00005565/*
drhc3b70572003-01-04 19:44:07 +00005566** The following parameters determine how many adjacent pages get involved
5567** in a balancing operation. NN is the number of neighbors on either side
5568** of the page that participate in the balancing operation. NB is the
5569** total number of pages that participate, including the target page and
5570** NN neighbors on either side.
5571**
5572** The minimum value of NN is 1 (of course). Increasing NN above 1
5573** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
5574** in exchange for a larger degradation in INSERT and UPDATE performance.
5575** The value of NN appears to give the best results overall.
5576*/
5577#define NN 1 /* Number of neighbors on either side of pPage */
5578#define NB (NN*2+1) /* Total pages involved in the balance */
5579
danielk1977ac245ec2005-01-14 13:50:11 +00005580
drh615ae552005-01-16 23:21:00 +00005581#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00005582/*
5583** This version of balance() handles the common special case where
5584** a new entry is being inserted on the extreme right-end of the
5585** tree, in other words, when the new entry will become the largest
5586** entry in the tree.
5587**
drhc314dc72009-07-21 11:52:34 +00005588** Instead of trying to balance the 3 right-most leaf pages, just add
drhf222e712005-01-14 22:55:49 +00005589** a new page to the right-hand side and put the one new entry in
5590** that page. This leaves the right side of the tree somewhat
5591** unbalanced. But odds are that we will be inserting new entries
5592** at the end soon afterwards so the nearly empty page will quickly
5593** fill up. On average.
5594**
5595** pPage is the leaf page which is the right-most page in the tree.
5596** pParent is its parent. pPage must have a single overflow entry
5597** which is also the right-most entry on the page.
danielk1977a50d9aa2009-06-08 14:49:45 +00005598**
5599** The pSpace buffer is used to store a temporary copy of the divider
5600** cell that will be inserted into pParent. Such a cell consists of a 4
5601** byte page number followed by a variable length integer. In other
5602** words, at most 13 bytes. Hence the pSpace buffer must be at
5603** least 13 bytes in size.
drhf222e712005-01-14 22:55:49 +00005604*/
danielk1977a50d9aa2009-06-08 14:49:45 +00005605static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
5606 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
danielk19774dbaa892009-06-16 16:50:22 +00005607 MemPage *pNew; /* Newly allocated page */
danielk19776f235cc2009-06-04 14:46:08 +00005608 int rc; /* Return Code */
5609 Pgno pgnoNew; /* Page number of pNew */
danielk1977ac245ec2005-01-14 13:50:11 +00005610
drh1fee73e2007-08-29 04:00:57 +00005611 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk1977a50d9aa2009-06-08 14:49:45 +00005612 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00005613 assert( pPage->nOverflow==1 );
5614
drh5d433ce2010-08-14 16:02:52 +00005615 /* This error condition is now caught prior to reaching this function */
drh6b47fca2010-08-19 14:22:42 +00005616 if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
drhd677b3d2007-08-20 22:48:41 +00005617
danielk1977a50d9aa2009-06-08 14:49:45 +00005618 /* Allocate a new page. This page will become the right-sibling of
5619 ** pPage. Make the parent page writable, so that the new divider cell
5620 ** may be inserted. If both these operations are successful, proceed.
5621 */
drh4f0c5872007-03-26 22:05:01 +00005622 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk19774dbaa892009-06-16 16:50:22 +00005623
danielk1977eaa06f62008-09-18 17:34:44 +00005624 if( rc==SQLITE_OK ){
danielk1977a50d9aa2009-06-08 14:49:45 +00005625
5626 u8 *pOut = &pSpace[4];
danielk19776f235cc2009-06-04 14:46:08 +00005627 u8 *pCell = pPage->aOvfl[0].pCell;
5628 u16 szCell = cellSizePtr(pPage, pCell);
5629 u8 *pStop;
5630
drhc5053fb2008-11-27 02:22:10 +00005631 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00005632 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
5633 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
danielk1977eaa06f62008-09-18 17:34:44 +00005634 assemblePage(pNew, 1, &pCell, &szCell);
danielk19774dbaa892009-06-16 16:50:22 +00005635
5636 /* If this is an auto-vacuum database, update the pointer map
5637 ** with entries for the new page, and any pointer from the
5638 ** cell on the page to an overflow page. If either of these
5639 ** operations fails, the return code is set, but the contents
5640 ** of the parent page are still manipulated by thh code below.
5641 ** That is Ok, at this point the parent page is guaranteed to
5642 ** be marked as dirty. Returning an error code will cause a
5643 ** rollback, undoing any changes made to the parent page.
5644 */
5645 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00005646 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
5647 if( szCell>pNew->minLocal ){
5648 ptrmapPutOvflPtr(pNew, pCell, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00005649 }
5650 }
danielk1977eaa06f62008-09-18 17:34:44 +00005651
danielk19776f235cc2009-06-04 14:46:08 +00005652 /* Create a divider cell to insert into pParent. The divider cell
5653 ** consists of a 4-byte page number (the page number of pPage) and
5654 ** a variable length key value (which must be the same value as the
5655 ** largest key on pPage).
danielk1977eaa06f62008-09-18 17:34:44 +00005656 **
danielk19776f235cc2009-06-04 14:46:08 +00005657 ** To find the largest key value on pPage, first find the right-most
5658 ** cell on pPage. The first two fields of this cell are the
5659 ** record-length (a variable length integer at most 32-bits in size)
5660 ** and the key value (a variable length integer, may have any value).
5661 ** The first of the while(...) loops below skips over the record-length
5662 ** field. The second while(...) loop copies the key value from the
danielk1977a50d9aa2009-06-08 14:49:45 +00005663 ** cell on pPage into the pSpace buffer.
danielk1977eaa06f62008-09-18 17:34:44 +00005664 */
danielk1977eaa06f62008-09-18 17:34:44 +00005665 pCell = findCell(pPage, pPage->nCell-1);
danielk19776f235cc2009-06-04 14:46:08 +00005666 pStop = &pCell[9];
5667 while( (*(pCell++)&0x80) && pCell<pStop );
5668 pStop = &pCell[9];
5669 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
5670
danielk19774dbaa892009-06-16 16:50:22 +00005671 /* Insert the new divider cell into pParent. */
drh98add2e2009-07-20 17:11:49 +00005672 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
5673 0, pPage->pgno, &rc);
danielk19776f235cc2009-06-04 14:46:08 +00005674
5675 /* Set the right-child pointer of pParent to point to the new page. */
danielk1977eaa06f62008-09-18 17:34:44 +00005676 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
5677
danielk1977e08a3c42008-09-18 18:17:03 +00005678 /* Release the reference to the new page. */
5679 releasePage(pNew);
danielk1977ac11ee62005-01-15 12:45:51 +00005680 }
5681
danielk1977eaa06f62008-09-18 17:34:44 +00005682 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00005683}
drh615ae552005-01-16 23:21:00 +00005684#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00005685
danielk19774dbaa892009-06-16 16:50:22 +00005686#if 0
drhc3b70572003-01-04 19:44:07 +00005687/*
danielk19774dbaa892009-06-16 16:50:22 +00005688** This function does not contribute anything to the operation of SQLite.
5689** it is sometimes activated temporarily while debugging code responsible
5690** for setting pointer-map entries.
5691*/
5692static int ptrmapCheckPages(MemPage **apPage, int nPage){
5693 int i, j;
5694 for(i=0; i<nPage; i++){
5695 Pgno n;
5696 u8 e;
5697 MemPage *pPage = apPage[i];
5698 BtShared *pBt = pPage->pBt;
5699 assert( pPage->isInit );
5700
5701 for(j=0; j<pPage->nCell; j++){
5702 CellInfo info;
5703 u8 *z;
5704
5705 z = findCell(pPage, j);
danielk197730548662009-07-09 05:07:37 +00005706 btreeParseCellPtr(pPage, z, &info);
danielk19774dbaa892009-06-16 16:50:22 +00005707 if( info.iOverflow ){
5708 Pgno ovfl = get4byte(&z[info.iOverflow]);
5709 ptrmapGet(pBt, ovfl, &e, &n);
5710 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
5711 }
5712 if( !pPage->leaf ){
5713 Pgno child = get4byte(z);
5714 ptrmapGet(pBt, child, &e, &n);
5715 assert( n==pPage->pgno && e==PTRMAP_BTREE );
5716 }
5717 }
5718 if( !pPage->leaf ){
5719 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5720 ptrmapGet(pBt, child, &e, &n);
5721 assert( n==pPage->pgno && e==PTRMAP_BTREE );
5722 }
5723 }
5724 return 1;
5725}
5726#endif
5727
danielk1977cd581a72009-06-23 15:43:39 +00005728/*
5729** This function is used to copy the contents of the b-tree node stored
5730** on page pFrom to page pTo. If page pFrom was not a leaf page, then
5731** the pointer-map entries for each child page are updated so that the
5732** parent page stored in the pointer map is page pTo. If pFrom contained
5733** any cells with overflow page pointers, then the corresponding pointer
5734** map entries are also updated so that the parent page is page pTo.
5735**
5736** If pFrom is currently carrying any overflow cells (entries in the
5737** MemPage.aOvfl[] array), they are not copied to pTo.
5738**
danielk197730548662009-07-09 05:07:37 +00005739** Before returning, page pTo is reinitialized using btreeInitPage().
danielk1977cd581a72009-06-23 15:43:39 +00005740**
5741** The performance of this function is not critical. It is only used by
5742** the balance_shallower() and balance_deeper() procedures, neither of
5743** which are called often under normal circumstances.
5744*/
drhc314dc72009-07-21 11:52:34 +00005745static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
5746 if( (*pRC)==SQLITE_OK ){
5747 BtShared * const pBt = pFrom->pBt;
5748 u8 * const aFrom = pFrom->aData;
5749 u8 * const aTo = pTo->aData;
5750 int const iFromHdr = pFrom->hdrOffset;
5751 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
drhdc9b5f82009-12-05 18:34:08 +00005752 int rc;
drhc314dc72009-07-21 11:52:34 +00005753 int iData;
5754
5755
5756 assert( pFrom->isInit );
5757 assert( pFrom->nFree>=iToHdr );
drhfcd71b62011-04-05 22:08:24 +00005758 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
drhc314dc72009-07-21 11:52:34 +00005759
5760 /* Copy the b-tree node content from page pFrom to page pTo. */
5761 iData = get2byte(&aFrom[iFromHdr+5]);
5762 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
5763 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
5764
5765 /* Reinitialize page pTo so that the contents of the MemPage structure
dan89e060e2009-12-05 18:03:50 +00005766 ** match the new data. The initialization of pTo can actually fail under
5767 ** fairly obscure circumstances, even though it is a copy of initialized
5768 ** page pFrom.
5769 */
drhc314dc72009-07-21 11:52:34 +00005770 pTo->isInit = 0;
dan89e060e2009-12-05 18:03:50 +00005771 rc = btreeInitPage(pTo);
5772 if( rc!=SQLITE_OK ){
5773 *pRC = rc;
5774 return;
5775 }
drhc314dc72009-07-21 11:52:34 +00005776
5777 /* If this is an auto-vacuum database, update the pointer-map entries
5778 ** for any b-tree or overflow pages that pTo now contains the pointers to.
5779 */
5780 if( ISAUTOVACUUM ){
5781 *pRC = setChildPtrmaps(pTo);
5782 }
danielk1977cd581a72009-06-23 15:43:39 +00005783 }
danielk1977cd581a72009-06-23 15:43:39 +00005784}
5785
5786/*
danielk19774dbaa892009-06-16 16:50:22 +00005787** This routine redistributes cells on the iParentIdx'th child of pParent
5788** (hereafter "the page") and up to 2 siblings so that all pages have about the
5789** same amount of free space. Usually a single sibling on either side of the
5790** page are used in the balancing, though both siblings might come from one
5791** side if the page is the first or last child of its parent. If the page
5792** has fewer than 2 siblings (something which can only happen if the page
5793** is a root page or a child of a root page) then all available siblings
5794** participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00005795**
danielk19774dbaa892009-06-16 16:50:22 +00005796** The number of siblings of the page might be increased or decreased by
5797** one or two in an effort to keep pages nearly full but not over full.
drh14acc042001-06-10 19:56:58 +00005798**
danielk19774dbaa892009-06-16 16:50:22 +00005799** Note that when this routine is called, some of the cells on the page
5800** might not actually be stored in MemPage.aData[]. This can happen
5801** if the page is overfull. This routine ensures that all cells allocated
5802** to the page and its siblings fit into MemPage.aData[] before returning.
drh14acc042001-06-10 19:56:58 +00005803**
danielk19774dbaa892009-06-16 16:50:22 +00005804** In the course of balancing the page and its siblings, cells may be
5805** inserted into or removed from the parent page (pParent). Doing so
5806** may cause the parent page to become overfull or underfull. If this
5807** happens, it is the responsibility of the caller to invoke the correct
5808** balancing routine to fix this problem (see the balance() routine).
drh8c42ca92001-06-22 19:15:00 +00005809**
drh5e00f6c2001-09-13 13:46:56 +00005810** If this routine fails for any reason, it might leave the database
danielk19776067a9b2009-06-09 09:41:00 +00005811** in a corrupted state. So if this routine fails, the database should
drh5e00f6c2001-09-13 13:46:56 +00005812** be rolled back.
danielk19774dbaa892009-06-16 16:50:22 +00005813**
5814** The third argument to this function, aOvflSpace, is a pointer to a
drhcd09c532009-07-20 19:30:00 +00005815** buffer big enough to hold one page. If while inserting cells into the parent
5816** page (pParent) the parent page becomes overfull, this buffer is
5817** used to store the parent's overflow cells. Because this function inserts
danielk19774dbaa892009-06-16 16:50:22 +00005818** a maximum of four divider cells into the parent page, and the maximum
5819** size of a cell stored within an internal node is always less than 1/4
5820** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
5821** enough for all overflow cells.
5822**
5823** If aOvflSpace is set to a null pointer, this function returns
5824** SQLITE_NOMEM.
drh8b2f49b2001-06-08 00:21:52 +00005825*/
danielk19774dbaa892009-06-16 16:50:22 +00005826static int balance_nonroot(
5827 MemPage *pParent, /* Parent page of siblings being balanced */
5828 int iParentIdx, /* Index of "the page" in pParent */
danielk1977cd581a72009-06-23 15:43:39 +00005829 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
5830 int isRoot /* True if pParent is a root-page */
danielk19774dbaa892009-06-16 16:50:22 +00005831){
drh16a9b832007-05-05 18:39:25 +00005832 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00005833 int nCell = 0; /* Number of cells in apCell[] */
5834 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
danielk1977a4124bd2008-12-23 10:37:47 +00005835 int nNew = 0; /* Number of pages in apNew[] */
danielk19774dbaa892009-06-16 16:50:22 +00005836 int nOld; /* Number of pages in apOld[] */
drh14acc042001-06-10 19:56:58 +00005837 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00005838 int nxDiv; /* Next divider slot in pParent->aCell[] */
shane85095702009-06-15 16:27:08 +00005839 int rc = SQLITE_OK; /* The return code */
shane36840fd2009-06-26 16:32:13 +00005840 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00005841 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00005842 int usableSpace; /* Bytes in pPage beyond the header */
5843 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00005844 int subtotal; /* Subtotal of bytes in cells on one page */
drhe5ae5732008-06-15 02:51:47 +00005845 int iSpace1 = 0; /* First unused byte of aSpace1[] */
danielk19776067a9b2009-06-09 09:41:00 +00005846 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
drhfacf0302008-06-17 15:12:00 +00005847 int szScratch; /* Size of scratch memory requested */
drhc3b70572003-01-04 19:44:07 +00005848 MemPage *apOld[NB]; /* pPage and up to two siblings */
drh4b70f112004-05-02 21:12:19 +00005849 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00005850 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
danielk19774dbaa892009-06-16 16:50:22 +00005851 u8 *pRight; /* Location in parent of right-sibling pointer */
5852 u8 *apDiv[NB-1]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00005853 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
5854 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00005855 u8 **apCell = 0; /* All cells begin balanced */
drha9121e42008-02-19 14:59:35 +00005856 u16 *szCell; /* Local size of all cells in apCell[] */
danielk19774dbaa892009-06-16 16:50:22 +00005857 u8 *aSpace1; /* Space for copies of dividers cells */
5858 Pgno pgno; /* Temp var to store a page number in */
drh8b2f49b2001-06-08 00:21:52 +00005859
danielk1977a50d9aa2009-06-08 14:49:45 +00005860 pBt = pParent->pBt;
5861 assert( sqlite3_mutex_held(pBt->mutex) );
5862 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977474b7cc2008-07-09 11:49:46 +00005863
danielk1977e5765212009-06-17 11:13:28 +00005864#if 0
drh43605152004-05-29 21:46:49 +00005865 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
danielk1977e5765212009-06-17 11:13:28 +00005866#endif
drh2e38c322004-09-03 18:38:44 +00005867
danielk19774dbaa892009-06-16 16:50:22 +00005868 /* At this point pParent may have at most one overflow cell. And if
5869 ** this overflow cell is present, it must be the cell with
5870 ** index iParentIdx. This scenario comes about when this function
drhcd09c532009-07-20 19:30:00 +00005871 ** is called (indirectly) from sqlite3BtreeDelete().
5872 */
danielk19774dbaa892009-06-16 16:50:22 +00005873 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
5874 assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
5875
danielk197711a8a862009-06-17 11:49:52 +00005876 if( !aOvflSpace ){
5877 return SQLITE_NOMEM;
5878 }
5879
danielk1977a50d9aa2009-06-08 14:49:45 +00005880 /* Find the sibling pages to balance. Also locate the cells in pParent
5881 ** that divide the siblings. An attempt is made to find NN siblings on
5882 ** either side of pPage. More siblings are taken from one side, however,
5883 ** if there are fewer than NN siblings on the other side. If pParent
danielk19774dbaa892009-06-16 16:50:22 +00005884 ** has NB or fewer children then all children of pParent are taken.
5885 **
5886 ** This loop also drops the divider cells from the parent page. This
5887 ** way, the remainder of the function does not have to deal with any
drhcd09c532009-07-20 19:30:00 +00005888 ** overflow cells in the parent page, since if any existed they will
5889 ** have already been removed.
5890 */
danielk19774dbaa892009-06-16 16:50:22 +00005891 i = pParent->nOverflow + pParent->nCell;
5892 if( i<2 ){
drhc3b70572003-01-04 19:44:07 +00005893 nxDiv = 0;
danielk19774dbaa892009-06-16 16:50:22 +00005894 nOld = i+1;
5895 }else{
5896 nOld = 3;
5897 if( iParentIdx==0 ){
5898 nxDiv = 0;
5899 }else if( iParentIdx==i ){
5900 nxDiv = i-2;
drh14acc042001-06-10 19:56:58 +00005901 }else{
danielk19774dbaa892009-06-16 16:50:22 +00005902 nxDiv = iParentIdx-1;
drh8b2f49b2001-06-08 00:21:52 +00005903 }
danielk19774dbaa892009-06-16 16:50:22 +00005904 i = 2;
5905 }
5906 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
5907 pRight = &pParent->aData[pParent->hdrOffset+8];
5908 }else{
5909 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
5910 }
5911 pgno = get4byte(pRight);
5912 while( 1 ){
5913 rc = getAndInitPage(pBt, pgno, &apOld[i]);
5914 if( rc ){
danielk197789bc4bc2009-07-21 19:25:24 +00005915 memset(apOld, 0, (i+1)*sizeof(MemPage*));
danielk19774dbaa892009-06-16 16:50:22 +00005916 goto balance_cleanup;
5917 }
danielk1977634f2982005-03-28 08:44:07 +00005918 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
danielk19774dbaa892009-06-16 16:50:22 +00005919 if( (i--)==0 ) break;
5920
drhcd09c532009-07-20 19:30:00 +00005921 if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
danielk19774dbaa892009-06-16 16:50:22 +00005922 apDiv[i] = pParent->aOvfl[0].pCell;
5923 pgno = get4byte(apDiv[i]);
5924 szNew[i] = cellSizePtr(pParent, apDiv[i]);
5925 pParent->nOverflow = 0;
5926 }else{
5927 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
5928 pgno = get4byte(apDiv[i]);
5929 szNew[i] = cellSizePtr(pParent, apDiv[i]);
5930
5931 /* Drop the cell from the parent page. apDiv[i] still points to
5932 ** the cell within the parent, even though it has been dropped.
5933 ** This is safe because dropping a cell only overwrites the first
5934 ** four bytes of it, and this function does not need the first
5935 ** four bytes of the divider cell. So the pointer is safe to use
danielk197711a8a862009-06-17 11:49:52 +00005936 ** later on.
5937 **
5938 ** Unless SQLite is compiled in secure-delete mode. In this case,
5939 ** the dropCell() routine will overwrite the entire cell with zeroes.
5940 ** In this case, temporarily copy the cell into the aOvflSpace[]
5941 ** buffer. It will be copied out again as soon as the aSpace[] buffer
5942 ** is allocated. */
drh5b47efa2010-02-12 18:18:39 +00005943 if( pBt->secureDelete ){
shaneh1da207e2010-03-09 14:41:12 +00005944 int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
drh43b18e12010-08-17 19:40:08 +00005945 if( (iOff+szNew[i])>(int)pBt->usableSize ){
dan2ed11e72010-02-26 15:09:19 +00005946 rc = SQLITE_CORRUPT_BKPT;
5947 memset(apOld, 0, (i+1)*sizeof(MemPage*));
5948 goto balance_cleanup;
5949 }else{
5950 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
5951 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
5952 }
drh5b47efa2010-02-12 18:18:39 +00005953 }
drh98add2e2009-07-20 17:11:49 +00005954 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
danielk19774dbaa892009-06-16 16:50:22 +00005955 }
drh8b2f49b2001-06-08 00:21:52 +00005956 }
5957
drha9121e42008-02-19 14:59:35 +00005958 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00005959 ** alignment */
drha9121e42008-02-19 14:59:35 +00005960 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00005961
drh8b2f49b2001-06-08 00:21:52 +00005962 /*
danielk1977634f2982005-03-28 08:44:07 +00005963 ** Allocate space for memory structures
5964 */
danielk19774dbaa892009-06-16 16:50:22 +00005965 k = pBt->pageSize + ROUND8(sizeof(MemPage));
drhfacf0302008-06-17 15:12:00 +00005966 szScratch =
drha9121e42008-02-19 14:59:35 +00005967 nMaxCells*sizeof(u8*) /* apCell */
5968 + nMaxCells*sizeof(u16) /* szCell */
drhe5ae5732008-06-15 02:51:47 +00005969 + pBt->pageSize /* aSpace1 */
danielk19774dbaa892009-06-16 16:50:22 +00005970 + k*nOld; /* Page copies (apCopy) */
drhfacf0302008-06-17 15:12:00 +00005971 apCell = sqlite3ScratchMalloc( szScratch );
danielk197711a8a862009-06-17 11:49:52 +00005972 if( apCell==0 ){
danielk1977634f2982005-03-28 08:44:07 +00005973 rc = SQLITE_NOMEM;
5974 goto balance_cleanup;
5975 }
drha9121e42008-02-19 14:59:35 +00005976 szCell = (u16*)&apCell[nMaxCells];
danielk19774dbaa892009-06-16 16:50:22 +00005977 aSpace1 = (u8*)&szCell[nMaxCells];
drhea598cb2009-04-05 12:22:08 +00005978 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
drh14acc042001-06-10 19:56:58 +00005979
5980 /*
5981 ** Load pointers to all cells on sibling pages and the divider cells
5982 ** into the local apCell[] array. Make copies of the divider cells
danielk19774dbaa892009-06-16 16:50:22 +00005983 ** into space obtained from aSpace1[] and remove the the divider Cells
drhb6f41482004-05-14 01:58:11 +00005984 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00005985 **
5986 ** If the siblings are on leaf pages, then the child pointers of the
5987 ** divider cells are stripped from the cells before they are copied
drhe5ae5732008-06-15 02:51:47 +00005988 ** into aSpace1[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00005989 ** child pointers. If siblings are not leaves, then all cell in
5990 ** apCell[] include child pointers. Either way, all cells in apCell[]
5991 ** are alike.
drh96f5b762004-05-16 16:24:36 +00005992 **
5993 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
5994 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00005995 */
danielk1977a50d9aa2009-06-08 14:49:45 +00005996 leafCorrection = apOld[0]->leaf*4;
5997 leafData = apOld[0]->hasData;
drh8b2f49b2001-06-08 00:21:52 +00005998 for(i=0; i<nOld; i++){
danielk19774dbaa892009-06-16 16:50:22 +00005999 int limit;
6000
6001 /* Before doing anything else, take a copy of the i'th original sibling
6002 ** The rest of this function will use data from the copies rather
6003 ** that the original pages since the original pages will be in the
6004 ** process of being overwritten. */
6005 MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
6006 memcpy(pOld, apOld[i], sizeof(MemPage));
6007 pOld->aData = (void*)&pOld[1];
6008 memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
6009
6010 limit = pOld->nCell+pOld->nOverflow;
drh43605152004-05-29 21:46:49 +00006011 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00006012 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00006013 apCell[nCell] = findOverflowCell(pOld, j);
6014 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk19774dbaa892009-06-16 16:50:22 +00006015 nCell++;
6016 }
6017 if( i<nOld-1 && !leafData){
shane36840fd2009-06-26 16:32:13 +00006018 u16 sz = (u16)szNew[i];
danielk19774dbaa892009-06-16 16:50:22 +00006019 u8 *pTemp;
6020 assert( nCell<nMaxCells );
6021 szCell[nCell] = sz;
6022 pTemp = &aSpace1[iSpace1];
6023 iSpace1 += sz;
drhe22e03e2010-08-18 21:19:03 +00006024 assert( sz<=pBt->maxLocal+23 );
drhfcd71b62011-04-05 22:08:24 +00006025 assert( iSpace1 <= (int)pBt->pageSize );
danielk19774dbaa892009-06-16 16:50:22 +00006026 memcpy(pTemp, apDiv[i], sz);
6027 apCell[nCell] = pTemp+leafCorrection;
6028 assert( leafCorrection==0 || leafCorrection==4 );
shane36840fd2009-06-26 16:32:13 +00006029 szCell[nCell] = szCell[nCell] - leafCorrection;
danielk19774dbaa892009-06-16 16:50:22 +00006030 if( !pOld->leaf ){
6031 assert( leafCorrection==0 );
6032 assert( pOld->hdrOffset==0 );
6033 /* The right pointer of the child page pOld becomes the left
6034 ** pointer of the divider cell */
6035 memcpy(apCell[nCell], &pOld->aData[8], 4);
6036 }else{
6037 assert( leafCorrection==4 );
6038 if( szCell[nCell]<4 ){
6039 /* Do not allow any cells smaller than 4 bytes. */
6040 szCell[nCell] = 4;
danielk1977ac11ee62005-01-15 12:45:51 +00006041 }
6042 }
drh14acc042001-06-10 19:56:58 +00006043 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00006044 }
drh8b2f49b2001-06-08 00:21:52 +00006045 }
6046
6047 /*
drh6019e162001-07-02 17:51:45 +00006048 ** Figure out the number of pages needed to hold all nCell cells.
6049 ** Store this number in "k". Also compute szNew[] which is the total
6050 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00006051 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00006052 ** cntNew[k] should equal nCell.
6053 **
drh96f5b762004-05-16 16:24:36 +00006054 ** Values computed by this block:
6055 **
6056 ** k: The total number of sibling pages
6057 ** szNew[i]: Spaced used on the i-th sibling page.
6058 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
6059 ** the right of the i-th sibling page.
6060 ** usableSpace: Number of bytes of space available on each sibling.
6061 **
drh8b2f49b2001-06-08 00:21:52 +00006062 */
drh43605152004-05-29 21:46:49 +00006063 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00006064 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00006065 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00006066 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00006067 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00006068 szNew[k] = subtotal - szCell[i];
6069 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00006070 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00006071 subtotal = 0;
6072 k++;
drh9978c972010-02-23 17:36:32 +00006073 if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
drh6019e162001-07-02 17:51:45 +00006074 }
6075 }
6076 szNew[k] = subtotal;
6077 cntNew[k] = nCell;
6078 k++;
drh96f5b762004-05-16 16:24:36 +00006079
6080 /*
6081 ** The packing computed by the previous block is biased toward the siblings
6082 ** on the left side. The left siblings are always nearly full, while the
6083 ** right-most sibling might be nearly empty. This block of code attempts
6084 ** to adjust the packing of siblings to get a better balance.
6085 **
6086 ** This adjustment is more than an optimization. The packing above might
6087 ** be so out of balance as to be illegal. For example, the right-most
6088 ** sibling might be completely empty. This adjustment is not optional.
6089 */
drh6019e162001-07-02 17:51:45 +00006090 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00006091 int szRight = szNew[i]; /* Size of sibling on the right */
6092 int szLeft = szNew[i-1]; /* Size of sibling on the left */
6093 int r; /* Index of right-most cell in left sibling */
6094 int d; /* Index of first cell to the left of right sibling */
6095
6096 r = cntNew[i-1] - 1;
6097 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00006098 assert( d<nMaxCells );
6099 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00006100 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
6101 szRight += szCell[d] + 2;
6102 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00006103 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00006104 r = cntNew[i-1] - 1;
6105 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00006106 }
drh96f5b762004-05-16 16:24:36 +00006107 szNew[i] = szRight;
6108 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00006109 }
drh09d0deb2005-08-02 17:13:09 +00006110
danielk19776f235cc2009-06-04 14:46:08 +00006111 /* Either we found one or more cells (cntnew[0])>0) or pPage is
drh09d0deb2005-08-02 17:13:09 +00006112 ** a virtual root page. A virtual root page is when the real root
6113 ** page is page 1 and we are the only child of that page.
6114 */
6115 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00006116
danielk1977e5765212009-06-17 11:13:28 +00006117 TRACE(("BALANCE: old: %d %d %d ",
6118 apOld[0]->pgno,
6119 nOld>=2 ? apOld[1]->pgno : 0,
6120 nOld>=3 ? apOld[2]->pgno : 0
6121 ));
6122
drh8b2f49b2001-06-08 00:21:52 +00006123 /*
drh6b308672002-07-08 02:16:37 +00006124 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00006125 */
drheac74422009-06-14 12:47:11 +00006126 if( apOld[0]->pgno<=1 ){
drh9978c972010-02-23 17:36:32 +00006127 rc = SQLITE_CORRUPT_BKPT;
drheac74422009-06-14 12:47:11 +00006128 goto balance_cleanup;
6129 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006130 pageFlags = apOld[0]->aData[0];
drh14acc042001-06-10 19:56:58 +00006131 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00006132 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00006133 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00006134 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00006135 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00006136 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00006137 nNew++;
danielk197728129562005-01-11 10:25:06 +00006138 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00006139 }else{
drh7aa8f852006-03-28 00:24:44 +00006140 assert( i>0 );
danielk19774dbaa892009-06-16 16:50:22 +00006141 rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
drh6b308672002-07-08 02:16:37 +00006142 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00006143 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00006144 nNew++;
danielk19774dbaa892009-06-16 16:50:22 +00006145
6146 /* Set the pointer-map entry for the new sibling page. */
6147 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00006148 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006149 if( rc!=SQLITE_OK ){
6150 goto balance_cleanup;
6151 }
6152 }
drh6b308672002-07-08 02:16:37 +00006153 }
drh8b2f49b2001-06-08 00:21:52 +00006154 }
6155
danielk1977299b1872004-11-22 10:02:10 +00006156 /* Free any old pages that were not reused as new pages.
6157 */
6158 while( i<nOld ){
drhc314dc72009-07-21 11:52:34 +00006159 freePage(apOld[i], &rc);
danielk1977299b1872004-11-22 10:02:10 +00006160 if( rc ) goto balance_cleanup;
6161 releasePage(apOld[i]);
6162 apOld[i] = 0;
6163 i++;
6164 }
6165
drh8b2f49b2001-06-08 00:21:52 +00006166 /*
drhf9ffac92002-03-02 19:00:31 +00006167 ** Put the new pages in accending order. This helps to
6168 ** keep entries in the disk file in order so that a scan
6169 ** of the table is a linear scan through the file. That
6170 ** in turn helps the operating system to deliver pages
6171 ** from the disk more rapidly.
6172 **
6173 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00006174 ** n is never more than NB (a small constant), that should
6175 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00006176 **
drhc3b70572003-01-04 19:44:07 +00006177 ** When NB==3, this one optimization makes the database
6178 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00006179 */
6180 for(i=0; i<k-1; i++){
danielk19774dbaa892009-06-16 16:50:22 +00006181 int minV = apNew[i]->pgno;
drhf9ffac92002-03-02 19:00:31 +00006182 int minI = i;
6183 for(j=i+1; j<k; j++){
danielk19774dbaa892009-06-16 16:50:22 +00006184 if( apNew[j]->pgno<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00006185 minI = j;
danielk19774dbaa892009-06-16 16:50:22 +00006186 minV = apNew[j]->pgno;
drhf9ffac92002-03-02 19:00:31 +00006187 }
6188 }
6189 if( minI>i ){
drhf9ffac92002-03-02 19:00:31 +00006190 MemPage *pT;
drhf9ffac92002-03-02 19:00:31 +00006191 pT = apNew[i];
drhf9ffac92002-03-02 19:00:31 +00006192 apNew[i] = apNew[minI];
drhf9ffac92002-03-02 19:00:31 +00006193 apNew[minI] = pT;
6194 }
6195 }
danielk1977e5765212009-06-17 11:13:28 +00006196 TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
danielk19774dbaa892009-06-16 16:50:22 +00006197 apNew[0]->pgno, szNew[0],
6198 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
6199 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
6200 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
6201 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
6202
6203 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
6204 put4byte(pRight, apNew[nNew-1]->pgno);
drh24cd67e2004-05-10 16:18:47 +00006205
drhf9ffac92002-03-02 19:00:31 +00006206 /*
drh14acc042001-06-10 19:56:58 +00006207 ** Evenly distribute the data in apCell[] across the new pages.
6208 ** Insert divider cells into pParent as necessary.
6209 */
6210 j = 0;
6211 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00006212 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00006213 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00006214 assert( j<nMaxCells );
drh10131482008-07-11 03:34:09 +00006215 zeroPage(pNew, pageFlags);
drhfa1a98a2004-05-14 19:08:17 +00006216 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00006217 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00006218 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00006219
danielk1977ac11ee62005-01-15 12:45:51 +00006220 j = cntNew[i];
6221
6222 /* If the sibling page assembled above was not the right-most sibling,
6223 ** insert a divider cell into the parent page.
6224 */
danielk19771c3d2bf2009-06-23 16:40:17 +00006225 assert( i<nNew-1 || j==nCell );
6226 if( j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00006227 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00006228 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00006229 int sz;
danielk1977634f2982005-03-28 08:44:07 +00006230
6231 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00006232 pCell = apCell[j];
6233 sz = szCell[j] + leafCorrection;
danielk19776067a9b2009-06-09 09:41:00 +00006234 pTemp = &aOvflSpace[iOvflSpace];
drh4b70f112004-05-02 21:12:19 +00006235 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00006236 memcpy(&pNew->aData[8], pCell, 4);
drh8b18dd42004-05-12 19:18:15 +00006237 }else if( leafData ){
drhfd131da2007-08-07 17:13:03 +00006238 /* If the tree is a leaf-data tree, and the siblings are leaves,
danielk1977ac11ee62005-01-15 12:45:51 +00006239 ** then there is no divider cell in apCell[]. Instead, the divider
6240 ** cell consists of the integer key for the right-most cell of
6241 ** the sibling-page assembled above only.
6242 */
drh6f11bef2004-05-13 01:12:56 +00006243 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00006244 j--;
danielk197730548662009-07-09 05:07:37 +00006245 btreeParseCellPtr(pNew, apCell[j], &info);
drhe5ae5732008-06-15 02:51:47 +00006246 pCell = pTemp;
danielk19774dbaa892009-06-16 16:50:22 +00006247 sz = 4 + putVarint(&pCell[4], info.nKey);
drh8b18dd42004-05-12 19:18:15 +00006248 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00006249 }else{
6250 pCell -= 4;
danielk19774aeff622007-05-12 09:30:47 +00006251 /* Obscure case for non-leaf-data trees: If the cell at pCell was
drh85b623f2007-12-13 21:54:09 +00006252 ** previously stored on a leaf node, and its reported size was 4
danielk19774aeff622007-05-12 09:30:47 +00006253 ** bytes, then it may actually be smaller than this
danielk197730548662009-07-09 05:07:37 +00006254 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
drh85b623f2007-12-13 21:54:09 +00006255 ** any cell). But it is important to pass the correct size to
danielk19774aeff622007-05-12 09:30:47 +00006256 ** insertCell(), so reparse the cell now.
6257 **
6258 ** Note that this can never happen in an SQLite data file, as all
6259 ** cells are at least 4 bytes. It only happens in b-trees used
6260 ** to evaluate "IN (SELECT ...)" and similar clauses.
6261 */
6262 if( szCell[j]==4 ){
6263 assert(leafCorrection==4);
6264 sz = cellSizePtr(pParent, pCell);
6265 }
drh4b70f112004-05-02 21:12:19 +00006266 }
danielk19776067a9b2009-06-09 09:41:00 +00006267 iOvflSpace += sz;
drhe22e03e2010-08-18 21:19:03 +00006268 assert( sz<=pBt->maxLocal+23 );
drhfcd71b62011-04-05 22:08:24 +00006269 assert( iOvflSpace <= (int)pBt->pageSize );
drh98add2e2009-07-20 17:11:49 +00006270 insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
danielk1977e80463b2004-11-03 03:01:16 +00006271 if( rc!=SQLITE_OK ) goto balance_cleanup;
drhc5053fb2008-11-27 02:22:10 +00006272 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk197785d90ca2008-07-19 14:25:15 +00006273
drh14acc042001-06-10 19:56:58 +00006274 j++;
6275 nxDiv++;
6276 }
6277 }
drh6019e162001-07-02 17:51:45 +00006278 assert( j==nCell );
drh7aa8f852006-03-28 00:24:44 +00006279 assert( nOld>0 );
6280 assert( nNew>0 );
drh4b70f112004-05-02 21:12:19 +00006281 if( (pageFlags & PTF_LEAF)==0 ){
danielk197787c52b52008-07-19 11:49:07 +00006282 u8 *zChild = &apCopy[nOld-1]->aData[8];
6283 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
drh14acc042001-06-10 19:56:58 +00006284 }
6285
danielk197713bd99f2009-06-24 05:40:34 +00006286 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
6287 /* The root page of the b-tree now contains no cells. The only sibling
6288 ** page is the right-child of the parent. Copy the contents of the
6289 ** child page into the parent, decreasing the overall height of the
6290 ** b-tree structure by one. This is described as the "balance-shallower"
6291 ** sub-algorithm in some documentation.
6292 **
6293 ** If this is an auto-vacuum database, the call to copyNodeContent()
6294 ** sets all pointer-map entries corresponding to database image pages
6295 ** for which the pointer is stored within the content being copied.
6296 **
6297 ** The second assert below verifies that the child page is defragmented
6298 ** (it must be, as it was just reconstructed using assemblePage()). This
6299 ** is important if the parent page happens to be page 1 of the database
6300 ** image. */
6301 assert( nNew==1 );
6302 assert( apNew[0]->nFree ==
6303 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
6304 );
drhc314dc72009-07-21 11:52:34 +00006305 copyNodeContent(apNew[0], pParent, &rc);
6306 freePage(apNew[0], &rc);
danielk197713bd99f2009-06-24 05:40:34 +00006307 }else if( ISAUTOVACUUM ){
6308 /* Fix the pointer-map entries for all the cells that were shifted around.
6309 ** There are several different types of pointer-map entries that need to
6310 ** be dealt with by this routine. Some of these have been set already, but
6311 ** many have not. The following is a summary:
6312 **
6313 ** 1) The entries associated with new sibling pages that were not
6314 ** siblings when this function was called. These have already
6315 ** been set. We don't need to worry about old siblings that were
6316 ** moved to the free-list - the freePage() code has taken care
6317 ** of those.
6318 **
6319 ** 2) The pointer-map entries associated with the first overflow
6320 ** page in any overflow chains used by new divider cells. These
6321 ** have also already been taken care of by the insertCell() code.
6322 **
6323 ** 3) If the sibling pages are not leaves, then the child pages of
6324 ** cells stored on the sibling pages may need to be updated.
6325 **
6326 ** 4) If the sibling pages are not internal intkey nodes, then any
6327 ** overflow pages used by these cells may need to be updated
6328 ** (internal intkey nodes never contain pointers to overflow pages).
6329 **
6330 ** 5) If the sibling pages are not leaves, then the pointer-map
6331 ** entries for the right-child pages of each sibling may need
6332 ** to be updated.
6333 **
6334 ** Cases 1 and 2 are dealt with above by other code. The next
6335 ** block deals with cases 3 and 4 and the one after that, case 5. Since
6336 ** setting a pointer map entry is a relatively expensive operation, this
6337 ** code only sets pointer map entries for child or overflow pages that have
6338 ** actually moved between pages. */
danielk19774dbaa892009-06-16 16:50:22 +00006339 MemPage *pNew = apNew[0];
6340 MemPage *pOld = apCopy[0];
6341 int nOverflow = pOld->nOverflow;
6342 int iNextOld = pOld->nCell + nOverflow;
6343 int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
6344 j = 0; /* Current 'old' sibling page */
6345 k = 0; /* Current 'new' sibling page */
drhc314dc72009-07-21 11:52:34 +00006346 for(i=0; i<nCell; i++){
danielk19774dbaa892009-06-16 16:50:22 +00006347 int isDivider = 0;
6348 while( i==iNextOld ){
6349 /* Cell i is the cell immediately following the last cell on old
6350 ** sibling page j. If the siblings are not leaf pages of an
6351 ** intkey b-tree, then cell i was a divider cell. */
6352 pOld = apCopy[++j];
6353 iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
6354 if( pOld->nOverflow ){
6355 nOverflow = pOld->nOverflow;
6356 iOverflow = i + !leafData + pOld->aOvfl[0].idx;
6357 }
6358 isDivider = !leafData;
6359 }
6360
6361 assert(nOverflow>0 || iOverflow<i );
6362 assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
6363 assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
6364 if( i==iOverflow ){
6365 isDivider = 1;
6366 if( (--nOverflow)>0 ){
6367 iOverflow++;
6368 }
6369 }
6370
6371 if( i==cntNew[k] ){
6372 /* Cell i is the cell immediately following the last cell on new
6373 ** sibling page k. If the siblings are not leaf pages of an
6374 ** intkey b-tree, then cell i is a divider cell. */
6375 pNew = apNew[++k];
6376 if( !leafData ) continue;
6377 }
danielk19774dbaa892009-06-16 16:50:22 +00006378 assert( j<nOld );
6379 assert( k<nNew );
6380
6381 /* If the cell was originally divider cell (and is not now) or
6382 ** an overflow cell, or if the cell was located on a different sibling
6383 ** page before the balancing, then the pointer map entries associated
6384 ** with any child or overflow pages need to be updated. */
6385 if( isDivider || pOld->pgno!=pNew->pgno ){
6386 if( !leafCorrection ){
drh98add2e2009-07-20 17:11:49 +00006387 ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006388 }
drh98add2e2009-07-20 17:11:49 +00006389 if( szCell[i]>pNew->minLocal ){
6390 ptrmapPutOvflPtr(pNew, apCell[i], &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006391 }
6392 }
6393 }
6394
6395 if( !leafCorrection ){
drh98add2e2009-07-20 17:11:49 +00006396 for(i=0; i<nNew; i++){
6397 u32 key = get4byte(&apNew[i]->aData[8]);
6398 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006399 }
6400 }
6401
6402#if 0
6403 /* The ptrmapCheckPages() contains assert() statements that verify that
6404 ** all pointer map pages are set correctly. This is helpful while
6405 ** debugging. This is usually disabled because a corrupt database may
6406 ** cause an assert() statement to fail. */
6407 ptrmapCheckPages(apNew, nNew);
6408 ptrmapCheckPages(&pParent, 1);
6409#endif
6410 }
6411
danielk197771d5d2c2008-09-29 11:49:47 +00006412 assert( pParent->isInit );
danielk1977e5765212009-06-17 11:13:28 +00006413 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
6414 nOld, nNew, nCell));
danielk1977cd581a72009-06-23 15:43:39 +00006415
drh8b2f49b2001-06-08 00:21:52 +00006416 /*
drh14acc042001-06-10 19:56:58 +00006417 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00006418 */
drh14acc042001-06-10 19:56:58 +00006419balance_cleanup:
drhfacf0302008-06-17 15:12:00 +00006420 sqlite3ScratchFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00006421 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00006422 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00006423 }
drh14acc042001-06-10 19:56:58 +00006424 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00006425 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00006426 }
danielk1977eaa06f62008-09-18 17:34:44 +00006427
drh8b2f49b2001-06-08 00:21:52 +00006428 return rc;
6429}
6430
drh43605152004-05-29 21:46:49 +00006431
6432/*
danielk1977a50d9aa2009-06-08 14:49:45 +00006433** This function is called when the root page of a b-tree structure is
6434** overfull (has one or more overflow pages).
drh43605152004-05-29 21:46:49 +00006435**
danielk1977a50d9aa2009-06-08 14:49:45 +00006436** A new child page is allocated and the contents of the current root
6437** page, including overflow cells, are copied into the child. The root
6438** page is then overwritten to make it an empty page with the right-child
6439** pointer pointing to the new page.
6440**
6441** Before returning, all pointer-map entries corresponding to pages
6442** that the new child-page now contains pointers to are updated. The
6443** entry corresponding to the new right-child pointer of the root
6444** page is also updated.
6445**
6446** If successful, *ppChild is set to contain a reference to the child
6447** page and SQLITE_OK is returned. In this case the caller is required
6448** to call releasePage() on *ppChild exactly once. If an error occurs,
6449** an error code is returned and *ppChild is set to 0.
drh43605152004-05-29 21:46:49 +00006450*/
danielk1977a50d9aa2009-06-08 14:49:45 +00006451static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
6452 int rc; /* Return value from subprocedures */
6453 MemPage *pChild = 0; /* Pointer to a new child page */
shane5eff7cf2009-08-10 03:57:58 +00006454 Pgno pgnoChild = 0; /* Page number of the new child page */
danielk1977a50d9aa2009-06-08 14:49:45 +00006455 BtShared *pBt = pRoot->pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00006456
danielk1977a50d9aa2009-06-08 14:49:45 +00006457 assert( pRoot->nOverflow>0 );
drh1fee73e2007-08-29 04:00:57 +00006458 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bc2ca9e2008-11-13 14:28:28 +00006459
danielk1977a50d9aa2009-06-08 14:49:45 +00006460 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
6461 ** page that will become the new right-child of pPage. Copy the contents
6462 ** of the node stored on pRoot into the new child page.
6463 */
drh98add2e2009-07-20 17:11:49 +00006464 rc = sqlite3PagerWrite(pRoot->pDbPage);
6465 if( rc==SQLITE_OK ){
6466 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
drhc314dc72009-07-21 11:52:34 +00006467 copyNodeContent(pRoot, pChild, &rc);
6468 if( ISAUTOVACUUM ){
6469 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
drh98add2e2009-07-20 17:11:49 +00006470 }
6471 }
6472 if( rc ){
danielk1977a50d9aa2009-06-08 14:49:45 +00006473 *ppChild = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00006474 releasePage(pChild);
danielk1977a50d9aa2009-06-08 14:49:45 +00006475 return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00006476 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006477 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
6478 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
6479 assert( pChild->nCell==pRoot->nCell );
danielk197771d5d2c2008-09-29 11:49:47 +00006480
danielk1977a50d9aa2009-06-08 14:49:45 +00006481 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
6482
6483 /* Copy the overflow cells from pRoot to pChild */
6484 memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
6485 pChild->nOverflow = pRoot->nOverflow;
danielk1977a50d9aa2009-06-08 14:49:45 +00006486
6487 /* Zero the contents of pRoot. Then install pChild as the right-child. */
6488 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
6489 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
6490
6491 *ppChild = pChild;
6492 return SQLITE_OK;
drh43605152004-05-29 21:46:49 +00006493}
6494
6495/*
danielk197771d5d2c2008-09-29 11:49:47 +00006496** The page that pCur currently points to has just been modified in
6497** some way. This function figures out if this modification means the
6498** tree needs to be balanced, and if so calls the appropriate balancing
danielk1977a50d9aa2009-06-08 14:49:45 +00006499** routine. Balancing routines are:
6500**
6501** balance_quick()
danielk1977a50d9aa2009-06-08 14:49:45 +00006502** balance_deeper()
6503** balance_nonroot()
drh43605152004-05-29 21:46:49 +00006504*/
danielk1977a50d9aa2009-06-08 14:49:45 +00006505static int balance(BtCursor *pCur){
drh43605152004-05-29 21:46:49 +00006506 int rc = SQLITE_OK;
danielk1977a50d9aa2009-06-08 14:49:45 +00006507 const int nMin = pCur->pBt->usableSize * 2 / 3;
6508 u8 aBalanceQuickSpace[13];
6509 u8 *pFree = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00006510
shane75ac1de2009-06-09 18:58:52 +00006511 TESTONLY( int balance_quick_called = 0 );
6512 TESTONLY( int balance_deeper_called = 0 );
danielk1977a50d9aa2009-06-08 14:49:45 +00006513
6514 do {
6515 int iPage = pCur->iPage;
6516 MemPage *pPage = pCur->apPage[iPage];
6517
6518 if( iPage==0 ){
6519 if( pPage->nOverflow ){
6520 /* The root page of the b-tree is overfull. In this case call the
6521 ** balance_deeper() function to create a new child for the root-page
6522 ** and copy the current contents of the root-page to it. The
6523 ** next iteration of the do-loop will balance the child page.
6524 */
6525 assert( (balance_deeper_called++)==0 );
6526 rc = balance_deeper(pPage, &pCur->apPage[1]);
6527 if( rc==SQLITE_OK ){
6528 pCur->iPage = 1;
6529 pCur->aiIdx[0] = 0;
6530 pCur->aiIdx[1] = 0;
6531 assert( pCur->apPage[1]->nOverflow );
6532 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006533 }else{
danielk1977a50d9aa2009-06-08 14:49:45 +00006534 break;
6535 }
6536 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
6537 break;
6538 }else{
6539 MemPage * const pParent = pCur->apPage[iPage-1];
6540 int const iIdx = pCur->aiIdx[iPage-1];
6541
6542 rc = sqlite3PagerWrite(pParent->pDbPage);
6543 if( rc==SQLITE_OK ){
6544#ifndef SQLITE_OMIT_QUICKBALANCE
6545 if( pPage->hasData
6546 && pPage->nOverflow==1
6547 && pPage->aOvfl[0].idx==pPage->nCell
6548 && pParent->pgno!=1
6549 && pParent->nCell==iIdx
6550 ){
6551 /* Call balance_quick() to create a new sibling of pPage on which
6552 ** to store the overflow cell. balance_quick() inserts a new cell
6553 ** into pParent, which may cause pParent overflow. If this
6554 ** happens, the next interation of the do-loop will balance pParent
6555 ** use either balance_nonroot() or balance_deeper(). Until this
6556 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
6557 ** buffer.
6558 **
6559 ** The purpose of the following assert() is to check that only a
6560 ** single call to balance_quick() is made for each call to this
6561 ** function. If this were not verified, a subtle bug involving reuse
6562 ** of the aBalanceQuickSpace[] might sneak in.
6563 */
6564 assert( (balance_quick_called++)==0 );
6565 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
6566 }else
6567#endif
6568 {
6569 /* In this case, call balance_nonroot() to redistribute cells
6570 ** between pPage and up to 2 of its sibling pages. This involves
6571 ** modifying the contents of pParent, which may cause pParent to
6572 ** become overfull or underfull. The next iteration of the do-loop
6573 ** will balance the parent page to correct this.
6574 **
6575 ** If the parent page becomes overfull, the overflow cell or cells
6576 ** are stored in the pSpace buffer allocated immediately below.
6577 ** A subsequent iteration of the do-loop will deal with this by
6578 ** calling balance_nonroot() (balance_deeper() may be called first,
6579 ** but it doesn't deal with overflow cells - just moves them to a
6580 ** different page). Once this subsequent call to balance_nonroot()
6581 ** has completed, it is safe to release the pSpace buffer used by
6582 ** the previous call, as the overflow cell data will have been
6583 ** copied either into the body of a database page or into the new
6584 ** pSpace buffer passed to the latter call to balance_nonroot().
6585 */
6586 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
danielk1977cd581a72009-06-23 15:43:39 +00006587 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
danielk1977a50d9aa2009-06-08 14:49:45 +00006588 if( pFree ){
6589 /* If pFree is not NULL, it points to the pSpace buffer used
6590 ** by a previous call to balance_nonroot(). Its contents are
6591 ** now stored either on real database pages or within the
6592 ** new pSpace buffer, so it may be safely freed here. */
6593 sqlite3PageFree(pFree);
6594 }
6595
danielk19774dbaa892009-06-16 16:50:22 +00006596 /* The pSpace buffer will be freed after the next call to
6597 ** balance_nonroot(), or just before this function returns, whichever
6598 ** comes first. */
danielk1977a50d9aa2009-06-08 14:49:45 +00006599 pFree = pSpace;
danielk1977a50d9aa2009-06-08 14:49:45 +00006600 }
6601 }
6602
6603 pPage->nOverflow = 0;
6604
6605 /* The next iteration of the do-loop balances the parent page. */
6606 releasePage(pPage);
6607 pCur->iPage--;
drh43605152004-05-29 21:46:49 +00006608 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006609 }while( rc==SQLITE_OK );
6610
6611 if( pFree ){
6612 sqlite3PageFree(pFree);
drh43605152004-05-29 21:46:49 +00006613 }
6614 return rc;
6615}
6616
drhf74b8d92002-09-01 23:20:45 +00006617
6618/*
drh3b7511c2001-05-26 13:15:44 +00006619** Insert a new record into the BTree. The key is given by (pKey,nKey)
6620** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00006621** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00006622** is left pointing at a random location.
6623**
6624** For an INTKEY table, only the nKey value of the key is used. pKey is
6625** ignored. For a ZERODATA table, the pData and nData are both ignored.
danielk1977de630352009-05-04 11:42:29 +00006626**
6627** If the seekResult parameter is non-zero, then a successful call to
danielk19773509a652009-07-06 18:56:13 +00006628** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
danielk1977de630352009-05-04 11:42:29 +00006629** been performed. seekResult is the search result returned (a negative
6630** number if pCur points at an entry that is smaller than (pKey, nKey), or
6631** a positive value if pCur points at an etry that is larger than
6632** (pKey, nKey)).
6633**
drh3e9ca092009-09-08 01:14:48 +00006634** If the seekResult parameter is non-zero, then the caller guarantees that
6635** cursor pCur is pointing at the existing copy of a row that is to be
6636** overwritten. If the seekResult parameter is 0, then cursor pCur may
6637** point to any entry or to no entry at all and so this function has to seek
danielk1977de630352009-05-04 11:42:29 +00006638** the cursor before the new key can be inserted.
drh3b7511c2001-05-26 13:15:44 +00006639*/
drh3aac2dd2004-04-26 14:10:20 +00006640int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00006641 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00006642 const void *pKey, i64 nKey, /* The key of the new record */
drhe4d90812007-03-29 05:51:49 +00006643 const void *pData, int nData, /* The data of the new record */
drhb026e052007-05-02 01:34:31 +00006644 int nZero, /* Number of extra 0 bytes to append to data */
danielk1977de630352009-05-04 11:42:29 +00006645 int appendBias, /* True if this is likely an append */
danielk19773509a652009-07-06 18:56:13 +00006646 int seekResult /* Result of prior MovetoUnpacked() call */
drh3b7511c2001-05-26 13:15:44 +00006647){
drh3b7511c2001-05-26 13:15:44 +00006648 int rc;
drh3e9ca092009-09-08 01:14:48 +00006649 int loc = seekResult; /* -1: before desired location +1: after */
drh1d452e12009-11-01 19:26:59 +00006650 int szNew = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00006651 int idx;
drh3b7511c2001-05-26 13:15:44 +00006652 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00006653 Btree *p = pCur->pBtree;
6654 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00006655 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00006656 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00006657
drh98add2e2009-07-20 17:11:49 +00006658 if( pCur->eState==CURSOR_FAULT ){
6659 assert( pCur->skipNext!=SQLITE_OK );
6660 return pCur->skipNext;
6661 }
6662
drh1fee73e2007-08-29 04:00:57 +00006663 assert( cursorHoldsMutex(pCur) );
danielk197731d31b82009-07-13 13:18:07 +00006664 assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
danielk197796d48e92009-06-29 06:00:37 +00006665 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
6666
danielk197731d31b82009-07-13 13:18:07 +00006667 /* Assert that the caller has been consistent. If this cursor was opened
6668 ** expecting an index b-tree, then the caller should be inserting blob
6669 ** keys with no associated data. If the cursor was opened expecting an
6670 ** intkey table, the caller should be inserting integer keys with a
6671 ** blob of associated data. */
6672 assert( (pKey==0)==(pCur->pKeyInfo==0) );
6673
danielk197796d48e92009-06-29 06:00:37 +00006674 /* If this is an insert into a table b-tree, invalidate any incrblob
6675 ** cursors open on the row being replaced (assuming this is a replace
6676 ** operation - if it is not, the following is a no-op). */
6677 if( pCur->pKeyInfo==0 ){
drheeb844a2009-08-08 18:01:07 +00006678 invalidateIncrblobCursors(p, nKey, 0);
drhf74b8d92002-09-01 23:20:45 +00006679 }
danielk197796d48e92009-06-29 06:00:37 +00006680
danielk19779c3acf32009-05-02 07:36:49 +00006681 /* Save the positions of any other cursors open on this table.
6682 **
danielk19773509a652009-07-06 18:56:13 +00006683 ** In some cases, the call to btreeMoveto() below is a no-op. For
danielk19779c3acf32009-05-02 07:36:49 +00006684 ** example, when inserting data into a table with auto-generated integer
6685 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
6686 ** integer key to use. It then calls this function to actually insert the
danielk19773509a652009-07-06 18:56:13 +00006687 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
danielk19779c3acf32009-05-02 07:36:49 +00006688 ** that the cursor is already where it needs to be and returns without
6689 ** doing any work. To avoid thwarting these optimizations, it is important
6690 ** not to clear the cursor here.
6691 */
drh4c301aa2009-07-15 17:25:45 +00006692 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
6693 if( rc ) return rc;
6694 if( !loc ){
6695 rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
6696 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00006697 }
danielk1977b980d2212009-06-22 18:03:51 +00006698 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
danielk1977da184232006-01-05 11:34:32 +00006699
danielk197771d5d2c2008-09-29 11:49:47 +00006700 pPage = pCur->apPage[pCur->iPage];
drh4a1c3802004-05-12 15:15:47 +00006701 assert( pPage->intKey || nKey>=0 );
drh44845222008-07-17 18:39:57 +00006702 assert( pPage->leaf || !pPage->intKey );
danielk19778f880a82009-07-13 09:41:45 +00006703
drh3a4c1412004-05-09 20:40:11 +00006704 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
6705 pCur->pgnoRoot, nKey, nData, pPage->pgno,
6706 loc==0 ? "overwrite" : "new entry"));
danielk197771d5d2c2008-09-29 11:49:47 +00006707 assert( pPage->isInit );
danielk197752ae7242008-03-25 14:24:56 +00006708 allocateTempSpace(pBt);
6709 newCell = pBt->pTmpSpace;
drh2e38c322004-09-03 18:38:44 +00006710 if( newCell==0 ) return SQLITE_NOMEM;
drhb026e052007-05-02 01:34:31 +00006711 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
drh2e38c322004-09-03 18:38:44 +00006712 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00006713 assert( szNew==cellSizePtr(pPage, newCell) );
drhfcd71b62011-04-05 22:08:24 +00006714 assert( szNew <= MX_CELL_SIZE(pBt) );
danielk197771d5d2c2008-09-29 11:49:47 +00006715 idx = pCur->aiIdx[pCur->iPage];
danielk1977b980d2212009-06-22 18:03:51 +00006716 if( loc==0 ){
drha9121e42008-02-19 14:59:35 +00006717 u16 szOld;
danielk197771d5d2c2008-09-29 11:49:47 +00006718 assert( idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00006719 rc = sqlite3PagerWrite(pPage->pDbPage);
6720 if( rc ){
6721 goto end_insert;
6722 }
danielk197771d5d2c2008-09-29 11:49:47 +00006723 oldCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00006724 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006725 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00006726 }
drh43605152004-05-29 21:46:49 +00006727 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00006728 rc = clearCell(pPage, oldCell);
drh98add2e2009-07-20 17:11:49 +00006729 dropCell(pPage, idx, szOld, &rc);
drh2e38c322004-09-03 18:38:44 +00006730 if( rc ) goto end_insert;
drh7c717f72001-06-24 20:39:41 +00006731 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00006732 assert( pPage->leaf );
danielk197771d5d2c2008-09-29 11:49:47 +00006733 idx = ++pCur->aiIdx[pCur->iPage];
drh14acc042001-06-10 19:56:58 +00006734 }else{
drh4b70f112004-05-02 21:12:19 +00006735 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00006736 }
drh98add2e2009-07-20 17:11:49 +00006737 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
danielk19773f632d52009-05-02 10:03:09 +00006738 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
drh9bf9e9c2008-12-05 20:01:43 +00006739
danielk1977a50d9aa2009-06-08 14:49:45 +00006740 /* If no error has occured and pPage has an overflow cell, call balance()
6741 ** to redistribute the cells within the tree. Since balance() may move
6742 ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
6743 ** variables.
danielk19773f632d52009-05-02 10:03:09 +00006744 **
danielk1977a50d9aa2009-06-08 14:49:45 +00006745 ** Previous versions of SQLite called moveToRoot() to move the cursor
6746 ** back to the root page as balance() used to invalidate the contents
danielk197754109bb2009-06-23 11:22:29 +00006747 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
6748 ** set the cursor state to "invalid". This makes common insert operations
6749 ** slightly faster.
danielk19773f632d52009-05-02 10:03:09 +00006750 **
danielk1977a50d9aa2009-06-08 14:49:45 +00006751 ** There is a subtle but important optimization here too. When inserting
6752 ** multiple records into an intkey b-tree using a single cursor (as can
6753 ** happen while processing an "INSERT INTO ... SELECT" statement), it
6754 ** is advantageous to leave the cursor pointing to the last entry in
6755 ** the b-tree if possible. If the cursor is left pointing to the last
6756 ** entry in the table, and the next row inserted has an integer key
6757 ** larger than the largest existing key, it is possible to insert the
6758 ** row without seeking the cursor. This can be a big performance boost.
danielk19773f632d52009-05-02 10:03:09 +00006759 */
danielk1977a50d9aa2009-06-08 14:49:45 +00006760 pCur->info.nSize = 0;
6761 pCur->validNKey = 0;
6762 if( rc==SQLITE_OK && pPage->nOverflow ){
danielk1977a50d9aa2009-06-08 14:49:45 +00006763 rc = balance(pCur);
6764
6765 /* Must make sure nOverflow is reset to zero even if the balance()
danielk197754109bb2009-06-23 11:22:29 +00006766 ** fails. Internal data structure corruption will result otherwise.
6767 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
6768 ** from trying to save the current position of the cursor. */
danielk1977a50d9aa2009-06-08 14:49:45 +00006769 pCur->apPage[pCur->iPage]->nOverflow = 0;
danielk197754109bb2009-06-23 11:22:29 +00006770 pCur->eState = CURSOR_INVALID;
danielk19773f632d52009-05-02 10:03:09 +00006771 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006772 assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
drh9bf9e9c2008-12-05 20:01:43 +00006773
drh2e38c322004-09-03 18:38:44 +00006774end_insert:
drh5e2f8b92001-05-28 00:41:15 +00006775 return rc;
6776}
6777
6778/*
drh4b70f112004-05-02 21:12:19 +00006779** Delete the entry that the cursor is pointing to. The cursor
drhf94a1732008-09-30 17:18:17 +00006780** is left pointing at a arbitrary location.
drh3b7511c2001-05-26 13:15:44 +00006781*/
drh3aac2dd2004-04-26 14:10:20 +00006782int sqlite3BtreeDelete(BtCursor *pCur){
drhd677b3d2007-08-20 22:48:41 +00006783 Btree *p = pCur->pBtree;
danielk19774dbaa892009-06-16 16:50:22 +00006784 BtShared *pBt = p->pBt;
6785 int rc; /* Return code */
6786 MemPage *pPage; /* Page to delete cell from */
6787 unsigned char *pCell; /* Pointer to cell to delete */
6788 int iCellIdx; /* Index of cell to delete */
6789 int iCellDepth; /* Depth of node containing pCell */
drh8b2f49b2001-06-08 00:21:52 +00006790
drh1fee73e2007-08-29 04:00:57 +00006791 assert( cursorHoldsMutex(pCur) );
drh64022502009-01-09 14:11:04 +00006792 assert( pBt->inTransaction==TRANS_WRITE );
drhf74b8d92002-09-01 23:20:45 +00006793 assert( !pBt->readOnly );
drh64022502009-01-09 14:11:04 +00006794 assert( pCur->wrFlag );
danielk197796d48e92009-06-29 06:00:37 +00006795 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
6796 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
6797
danielk19774dbaa892009-06-16 16:50:22 +00006798 if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
6799 || NEVER(pCur->eState!=CURSOR_VALID)
6800 ){
6801 return SQLITE_ERROR; /* Something has gone awry. */
drhf74b8d92002-09-01 23:20:45 +00006802 }
danielk1977da184232006-01-05 11:34:32 +00006803
danielk197796d48e92009-06-29 06:00:37 +00006804 /* If this is a delete operation to remove a row from a table b-tree,
6805 ** invalidate any incrblob cursors open on the row being deleted. */
6806 if( pCur->pKeyInfo==0 ){
drheeb844a2009-08-08 18:01:07 +00006807 invalidateIncrblobCursors(p, pCur->info.nKey, 0);
danielk19774dbaa892009-06-16 16:50:22 +00006808 }
6809
6810 iCellDepth = pCur->iPage;
6811 iCellIdx = pCur->aiIdx[iCellDepth];
6812 pPage = pCur->apPage[iCellDepth];
6813 pCell = findCell(pPage, iCellIdx);
6814
6815 /* If the page containing the entry to delete is not a leaf page, move
6816 ** the cursor to the largest entry in the tree that is smaller than
6817 ** the entry being deleted. This cell will replace the cell being deleted
6818 ** from the internal node. The 'previous' entry is used for this instead
6819 ** of the 'next' entry, as the previous entry is always a part of the
6820 ** sub-tree headed by the child page of the cell being deleted. This makes
6821 ** balancing the tree following the delete operation easier. */
6822 if( !pPage->leaf ){
6823 int notUsed;
drh4c301aa2009-07-15 17:25:45 +00006824 rc = sqlite3BtreePrevious(pCur, &notUsed);
6825 if( rc ) return rc;
danielk19774dbaa892009-06-16 16:50:22 +00006826 }
6827
6828 /* Save the positions of any other cursors open on this table before
6829 ** making any modifications. Make the page containing the entry to be
6830 ** deleted writable. Then free any overflow pages associated with the
drha4ec1d42009-07-11 13:13:11 +00006831 ** entry and finally remove the cell itself from within the page.
6832 */
6833 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
6834 if( rc ) return rc;
6835 rc = sqlite3PagerWrite(pPage->pDbPage);
6836 if( rc ) return rc;
6837 rc = clearCell(pPage, pCell);
drh98add2e2009-07-20 17:11:49 +00006838 dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
drha4ec1d42009-07-11 13:13:11 +00006839 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00006840
danielk19774dbaa892009-06-16 16:50:22 +00006841 /* If the cell deleted was not located on a leaf page, then the cursor
6842 ** is currently pointing to the largest entry in the sub-tree headed
6843 ** by the child-page of the cell that was just deleted from an internal
6844 ** node. The cell from the leaf node needs to be moved to the internal
6845 ** node to replace the deleted cell. */
drh4b70f112004-05-02 21:12:19 +00006846 if( !pPage->leaf ){
danielk19774dbaa892009-06-16 16:50:22 +00006847 MemPage *pLeaf = pCur->apPage[pCur->iPage];
6848 int nCell;
6849 Pgno n = pCur->apPage[iCellDepth+1]->pgno;
6850 unsigned char *pTmp;
danielk1977e6efa742004-11-10 11:55:10 +00006851
danielk19774dbaa892009-06-16 16:50:22 +00006852 pCell = findCell(pLeaf, pLeaf->nCell-1);
6853 nCell = cellSizePtr(pLeaf, pCell);
drhfcd71b62011-04-05 22:08:24 +00006854 assert( MX_CELL_SIZE(pBt) >= nCell );
danielk197771d5d2c2008-09-29 11:49:47 +00006855
danielk19774dbaa892009-06-16 16:50:22 +00006856 allocateTempSpace(pBt);
6857 pTmp = pBt->pTmpSpace;
danielk19772f78fc62008-09-30 09:31:45 +00006858
drha4ec1d42009-07-11 13:13:11 +00006859 rc = sqlite3PagerWrite(pLeaf->pDbPage);
drh98add2e2009-07-20 17:11:49 +00006860 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
6861 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
drha4ec1d42009-07-11 13:13:11 +00006862 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00006863 }
danielk19774dbaa892009-06-16 16:50:22 +00006864
6865 /* Balance the tree. If the entry deleted was located on a leaf page,
6866 ** then the cursor still points to that page. In this case the first
6867 ** call to balance() repairs the tree, and the if(...) condition is
6868 ** never true.
6869 **
6870 ** Otherwise, if the entry deleted was on an internal node page, then
6871 ** pCur is pointing to the leaf page from which a cell was removed to
6872 ** replace the cell deleted from the internal node. This is slightly
6873 ** tricky as the leaf node may be underfull, and the internal node may
6874 ** be either under or overfull. In this case run the balancing algorithm
6875 ** on the leaf node first. If the balance proceeds far enough up the
6876 ** tree that we can be sure that any problem in the internal node has
6877 ** been corrected, so be it. Otherwise, after balancing the leaf node,
6878 ** walk the cursor up the tree to the internal node and balance it as
6879 ** well. */
6880 rc = balance(pCur);
6881 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
6882 while( pCur->iPage>iCellDepth ){
6883 releasePage(pCur->apPage[pCur->iPage--]);
6884 }
6885 rc = balance(pCur);
6886 }
6887
danielk19776b456a22005-03-21 04:04:02 +00006888 if( rc==SQLITE_OK ){
6889 moveToRoot(pCur);
6890 }
drh5e2f8b92001-05-28 00:41:15 +00006891 return rc;
drh3b7511c2001-05-26 13:15:44 +00006892}
drh8b2f49b2001-06-08 00:21:52 +00006893
6894/*
drhc6b52df2002-01-04 03:09:29 +00006895** Create a new BTree table. Write into *piTable the page
6896** number for the root page of the new table.
6897**
drhab01f612004-05-22 02:55:23 +00006898** The type of type is determined by the flags parameter. Only the
6899** following values of flags are currently in use. Other values for
6900** flags might not work:
6901**
6902** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
6903** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00006904*/
drhd4187c72010-08-30 22:15:45 +00006905static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
danielk1977aef0bf62005-12-30 16:28:01 +00006906 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006907 MemPage *pRoot;
6908 Pgno pgnoRoot;
6909 int rc;
drhd4187c72010-08-30 22:15:45 +00006910 int ptfFlags; /* Page-type flage for the root page of new table */
drhd677b3d2007-08-20 22:48:41 +00006911
drh1fee73e2007-08-29 04:00:57 +00006912 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00006913 assert( pBt->inTransaction==TRANS_WRITE );
danielk197728129562005-01-11 10:25:06 +00006914 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00006915
danielk1977003ba062004-11-04 02:57:33 +00006916#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00006917 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00006918 if( rc ){
6919 return rc;
6920 }
danielk1977003ba062004-11-04 02:57:33 +00006921#else
danielk1977687566d2004-11-02 12:56:41 +00006922 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00006923 Pgno pgnoMove; /* Move a page here to make room for the root-page */
6924 MemPage *pPageMove; /* The page to move to. */
6925
danielk197720713f32007-05-03 11:43:33 +00006926 /* Creating a new table may probably require moving an existing database
6927 ** to make room for the new tables root page. In case this page turns
6928 ** out to be an overflow page, delete all overflow page-map caches
6929 ** held by open cursors.
6930 */
danielk197792d4d7a2007-05-04 12:05:56 +00006931 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00006932
danielk1977003ba062004-11-04 02:57:33 +00006933 /* Read the value of meta[3] from the database to determine where the
6934 ** root page of the new table should go. meta[3] is the largest root-page
6935 ** created so far, so the new root-page is (meta[3]+1).
6936 */
danielk1977602b4662009-07-02 07:47:33 +00006937 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00006938 pgnoRoot++;
6939
danielk1977599fcba2004-11-08 07:13:13 +00006940 /* The new root-page may not be allocated on a pointer-map page, or the
6941 ** PENDING_BYTE page.
6942 */
drh72190432008-01-31 14:54:43 +00006943 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00006944 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00006945 pgnoRoot++;
6946 }
6947 assert( pgnoRoot>=3 );
6948
6949 /* Allocate a page. The page that currently resides at pgnoRoot will
6950 ** be moved to the allocated page (unless the allocated page happens
6951 ** to reside at pgnoRoot).
6952 */
drh4f0c5872007-03-26 22:05:01 +00006953 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00006954 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00006955 return rc;
6956 }
danielk1977003ba062004-11-04 02:57:33 +00006957
6958 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00006959 /* pgnoRoot is the page that will be used for the root-page of
6960 ** the new table (assuming an error did not occur). But we were
6961 ** allocated pgnoMove. If required (i.e. if it was not allocated
6962 ** by extending the file), the current page at position pgnoMove
6963 ** is already journaled.
6964 */
drheeb844a2009-08-08 18:01:07 +00006965 u8 eType = 0;
6966 Pgno iPtrPage = 0;
danielk1977003ba062004-11-04 02:57:33 +00006967
6968 releasePage(pPageMove);
danielk1977f35843b2007-04-07 15:03:17 +00006969
6970 /* Move the page currently at pgnoRoot to pgnoMove. */
danielk197730548662009-07-09 05:07:37 +00006971 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006972 if( rc!=SQLITE_OK ){
6973 return rc;
6974 }
6975 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drh27731d72009-06-22 12:05:10 +00006976 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
6977 rc = SQLITE_CORRUPT_BKPT;
6978 }
6979 if( rc!=SQLITE_OK ){
danielk1977003ba062004-11-04 02:57:33 +00006980 releasePage(pRoot);
6981 return rc;
6982 }
drhccae6022005-02-26 17:31:26 +00006983 assert( eType!=PTRMAP_ROOTPAGE );
6984 assert( eType!=PTRMAP_FREEPAGE );
danielk19774c999992008-07-16 18:17:55 +00006985 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
danielk1977003ba062004-11-04 02:57:33 +00006986 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00006987
6988 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00006989 if( rc!=SQLITE_OK ){
6990 return rc;
6991 }
danielk197730548662009-07-09 05:07:37 +00006992 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006993 if( rc!=SQLITE_OK ){
6994 return rc;
6995 }
danielk19773b8a05f2007-03-19 17:44:26 +00006996 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00006997 if( rc!=SQLITE_OK ){
6998 releasePage(pRoot);
6999 return rc;
7000 }
7001 }else{
7002 pRoot = pPageMove;
7003 }
7004
danielk197742741be2005-01-08 12:42:39 +00007005 /* Update the pointer-map and meta-data with the new root-page number. */
drh98add2e2009-07-20 17:11:49 +00007006 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
danielk1977003ba062004-11-04 02:57:33 +00007007 if( rc ){
7008 releasePage(pRoot);
7009 return rc;
7010 }
drhbf592832010-03-30 15:51:12 +00007011
7012 /* When the new root page was allocated, page 1 was made writable in
7013 ** order either to increase the database filesize, or to decrement the
7014 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
7015 */
7016 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
danielk1977aef0bf62005-12-30 16:28:01 +00007017 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
drhbf592832010-03-30 15:51:12 +00007018 if( NEVER(rc) ){
danielk1977003ba062004-11-04 02:57:33 +00007019 releasePage(pRoot);
7020 return rc;
7021 }
danielk197742741be2005-01-08 12:42:39 +00007022
danielk1977003ba062004-11-04 02:57:33 +00007023 }else{
drh4f0c5872007-03-26 22:05:01 +00007024 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00007025 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00007026 }
7027#endif
danielk19773b8a05f2007-03-19 17:44:26 +00007028 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhd4187c72010-08-30 22:15:45 +00007029 if( createTabFlags & BTREE_INTKEY ){
7030 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
7031 }else{
7032 ptfFlags = PTF_ZERODATA | PTF_LEAF;
7033 }
7034 zeroPage(pRoot, ptfFlags);
danielk19773b8a05f2007-03-19 17:44:26 +00007035 sqlite3PagerUnref(pRoot->pDbPage);
drhd4187c72010-08-30 22:15:45 +00007036 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
drh8b2f49b2001-06-08 00:21:52 +00007037 *piTable = (int)pgnoRoot;
7038 return SQLITE_OK;
7039}
drhd677b3d2007-08-20 22:48:41 +00007040int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
7041 int rc;
7042 sqlite3BtreeEnter(p);
7043 rc = btreeCreateTable(p, piTable, flags);
7044 sqlite3BtreeLeave(p);
7045 return rc;
7046}
drh8b2f49b2001-06-08 00:21:52 +00007047
7048/*
7049** Erase the given database page and all its children. Return
7050** the page to the freelist.
7051*/
drh4b70f112004-05-02 21:12:19 +00007052static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00007053 BtShared *pBt, /* The BTree that contains the table */
drh7ab641f2009-11-24 02:37:02 +00007054 Pgno pgno, /* Page number to clear */
7055 int freePageFlag, /* Deallocate page if true */
7056 int *pnChange /* Add number of Cells freed to this counter */
drh4b70f112004-05-02 21:12:19 +00007057){
danielk1977146ba992009-07-22 14:08:13 +00007058 MemPage *pPage;
drh8b2f49b2001-06-08 00:21:52 +00007059 int rc;
drh4b70f112004-05-02 21:12:19 +00007060 unsigned char *pCell;
7061 int i;
drh8b2f49b2001-06-08 00:21:52 +00007062
drh1fee73e2007-08-29 04:00:57 +00007063 assert( sqlite3_mutex_held(pBt->mutex) );
drhb1299152010-03-30 22:58:33 +00007064 if( pgno>btreePagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00007065 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00007066 }
7067
danielk197771d5d2c2008-09-29 11:49:47 +00007068 rc = getAndInitPage(pBt, pgno, &pPage);
danielk1977146ba992009-07-22 14:08:13 +00007069 if( rc ) return rc;
drh4b70f112004-05-02 21:12:19 +00007070 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00007071 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00007072 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00007073 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00007074 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00007075 }
drh4b70f112004-05-02 21:12:19 +00007076 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00007077 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00007078 }
drha34b6762004-05-07 13:30:42 +00007079 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00007080 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00007081 if( rc ) goto cleardatabasepage_out;
danielk1977c7af4842008-10-27 13:59:33 +00007082 }else if( pnChange ){
7083 assert( pPage->intKey );
7084 *pnChange += pPage->nCell;
drh2aa679f2001-06-25 02:11:07 +00007085 }
7086 if( freePageFlag ){
drhc314dc72009-07-21 11:52:34 +00007087 freePage(pPage, &rc);
danielk19773b8a05f2007-03-19 17:44:26 +00007088 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
drh3a4c1412004-05-09 20:40:11 +00007089 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00007090 }
danielk19776b456a22005-03-21 04:04:02 +00007091
7092cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00007093 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00007094 return rc;
drh8b2f49b2001-06-08 00:21:52 +00007095}
7096
7097/*
drhab01f612004-05-22 02:55:23 +00007098** Delete all information from a single table in the database. iTable is
7099** the page number of the root of the table. After this routine returns,
7100** the root page is empty, but still exists.
7101**
7102** This routine will fail with SQLITE_LOCKED if there are any open
7103** read cursors on the table. Open write cursors are moved to the
7104** root of the table.
danielk1977c7af4842008-10-27 13:59:33 +00007105**
7106** If pnChange is not NULL, then table iTable must be an intkey table. The
7107** integer value pointed to by pnChange is incremented by the number of
7108** entries in the table.
drh8b2f49b2001-06-08 00:21:52 +00007109*/
danielk1977c7af4842008-10-27 13:59:33 +00007110int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
drh8b2f49b2001-06-08 00:21:52 +00007111 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00007112 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00007113 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00007114 assert( p->inTrans==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +00007115
7116 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
7117 ** is the root of a table b-tree - if it is not, the following call is
7118 ** a no-op). */
drheeb844a2009-08-08 18:01:07 +00007119 invalidateIncrblobCursors(p, 0, 1);
danielk197796d48e92009-06-29 06:00:37 +00007120
drhc046e3e2009-07-15 11:26:44 +00007121 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
7122 if( SQLITE_OK==rc ){
danielk197762c14b32008-11-19 09:05:26 +00007123 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
drh8b2f49b2001-06-08 00:21:52 +00007124 }
drhd677b3d2007-08-20 22:48:41 +00007125 sqlite3BtreeLeave(p);
7126 return rc;
drh8b2f49b2001-06-08 00:21:52 +00007127}
7128
7129/*
7130** Erase all information in a table and add the root of the table to
7131** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00007132** page 1) is never added to the freelist.
7133**
7134** This routine will fail with SQLITE_LOCKED if there are any open
7135** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00007136**
7137** If AUTOVACUUM is enabled and the page at iTable is not the last
7138** root page in the database file, then the last root page
7139** in the database file is moved into the slot formerly occupied by
7140** iTable and that last slot formerly occupied by the last root page
7141** is added to the freelist instead of iTable. In this say, all
7142** root pages are kept at the beginning of the database file, which
7143** is necessary for AUTOVACUUM to work right. *piMoved is set to the
7144** page number that used to be the last root page in the file before
7145** the move. If no page gets moved, *piMoved is set to 0.
7146** The last root page is recorded in meta[3] and the value of
7147** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00007148*/
danielk197789d40042008-11-17 14:20:56 +00007149static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00007150 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00007151 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00007152 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00007153
drh1fee73e2007-08-29 04:00:57 +00007154 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00007155 assert( p->inTrans==TRANS_WRITE );
danielk1977a0bf2652004-11-04 14:30:04 +00007156
danielk1977e6efa742004-11-10 11:55:10 +00007157 /* It is illegal to drop a table if any cursors are open on the
7158 ** database. This is because in auto-vacuum mode the backend may
7159 ** need to move another root-page to fill a gap left by the deleted
7160 ** root page. If an open cursor was using this page a problem would
7161 ** occur.
drhc046e3e2009-07-15 11:26:44 +00007162 **
7163 ** This error is caught long before control reaches this point.
danielk1977e6efa742004-11-10 11:55:10 +00007164 */
drhc046e3e2009-07-15 11:26:44 +00007165 if( NEVER(pBt->pCursor) ){
danielk1977404ca072009-03-16 13:19:36 +00007166 sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
7167 return SQLITE_LOCKED_SHAREDCACHE;
drh5df72a52002-06-06 23:16:05 +00007168 }
danielk1977a0bf2652004-11-04 14:30:04 +00007169
danielk197730548662009-07-09 05:07:37 +00007170 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00007171 if( rc ) return rc;
danielk1977c7af4842008-10-27 13:59:33 +00007172 rc = sqlite3BtreeClearTable(p, iTable, 0);
danielk19776b456a22005-03-21 04:04:02 +00007173 if( rc ){
7174 releasePage(pPage);
7175 return rc;
7176 }
danielk1977a0bf2652004-11-04 14:30:04 +00007177
drh205f48e2004-11-05 00:43:11 +00007178 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00007179
drh4b70f112004-05-02 21:12:19 +00007180 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00007181#ifdef SQLITE_OMIT_AUTOVACUUM
drhc314dc72009-07-21 11:52:34 +00007182 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00007183 releasePage(pPage);
7184#else
7185 if( pBt->autoVacuum ){
7186 Pgno maxRootPgno;
danielk1977602b4662009-07-02 07:47:33 +00007187 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00007188
7189 if( iTable==maxRootPgno ){
7190 /* If the table being dropped is the table with the largest root-page
7191 ** number in the database, put the root page on the free list.
7192 */
drhc314dc72009-07-21 11:52:34 +00007193 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00007194 releasePage(pPage);
7195 if( rc!=SQLITE_OK ){
7196 return rc;
7197 }
7198 }else{
7199 /* The table being dropped does not have the largest root-page
7200 ** number in the database. So move the page that does into the
7201 ** gap left by the deleted root-page.
7202 */
7203 MemPage *pMove;
7204 releasePage(pPage);
danielk197730548662009-07-09 05:07:37 +00007205 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00007206 if( rc!=SQLITE_OK ){
7207 return rc;
7208 }
danielk19774c999992008-07-16 18:17:55 +00007209 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00007210 releasePage(pMove);
7211 if( rc!=SQLITE_OK ){
7212 return rc;
7213 }
drhfe3313f2009-07-21 19:02:20 +00007214 pMove = 0;
danielk197730548662009-07-09 05:07:37 +00007215 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
drhc314dc72009-07-21 11:52:34 +00007216 freePage(pMove, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00007217 releasePage(pMove);
7218 if( rc!=SQLITE_OK ){
7219 return rc;
7220 }
7221 *piMoved = maxRootPgno;
7222 }
7223
danielk1977599fcba2004-11-08 07:13:13 +00007224 /* Set the new 'max-root-page' value in the database header. This
7225 ** is the old value less one, less one more if that happens to
7226 ** be a root-page number, less one again if that is the
7227 ** PENDING_BYTE_PAGE.
7228 */
danielk197787a6e732004-11-05 12:58:25 +00007229 maxRootPgno--;
drhe1849652009-07-15 18:15:22 +00007230 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
7231 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00007232 maxRootPgno--;
7233 }
danielk1977599fcba2004-11-08 07:13:13 +00007234 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
7235
danielk1977aef0bf62005-12-30 16:28:01 +00007236 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00007237 }else{
drhc314dc72009-07-21 11:52:34 +00007238 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00007239 releasePage(pPage);
7240 }
7241#endif
drh2aa679f2001-06-25 02:11:07 +00007242 }else{
drhc046e3e2009-07-15 11:26:44 +00007243 /* If sqlite3BtreeDropTable was called on page 1.
7244 ** This really never should happen except in a corrupt
7245 ** database.
7246 */
drha34b6762004-05-07 13:30:42 +00007247 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00007248 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00007249 }
drh8b2f49b2001-06-08 00:21:52 +00007250 return rc;
7251}
drhd677b3d2007-08-20 22:48:41 +00007252int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
7253 int rc;
7254 sqlite3BtreeEnter(p);
7255 rc = btreeDropTable(p, iTable, piMoved);
7256 sqlite3BtreeLeave(p);
7257 return rc;
7258}
drh8b2f49b2001-06-08 00:21:52 +00007259
drh001bbcb2003-03-19 03:14:00 +00007260
drh8b2f49b2001-06-08 00:21:52 +00007261/*
danielk1977602b4662009-07-02 07:47:33 +00007262** This function may only be called if the b-tree connection already
7263** has a read or write transaction open on the database.
7264**
drh23e11ca2004-05-04 17:27:28 +00007265** Read the meta-information out of a database file. Meta[0]
7266** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00007267** through meta[15] are available for use by higher layers. Meta[0]
7268** is read-only, the others are read/write.
7269**
7270** The schema layer numbers meta values differently. At the schema
7271** layer (and the SetCookie and ReadCookie opcodes) the number of
7272** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00007273*/
danielk1977602b4662009-07-02 07:47:33 +00007274void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
danielk1977aef0bf62005-12-30 16:28:01 +00007275 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00007276
drhd677b3d2007-08-20 22:48:41 +00007277 sqlite3BtreeEnter(p);
danielk1977602b4662009-07-02 07:47:33 +00007278 assert( p->inTrans>TRANS_NONE );
danielk1977e0d9e6f2009-07-03 16:25:06 +00007279 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
danielk1977602b4662009-07-02 07:47:33 +00007280 assert( pBt->pPage1 );
drh23e11ca2004-05-04 17:27:28 +00007281 assert( idx>=0 && idx<=15 );
danielk1977ea897302008-09-19 15:10:58 +00007282
danielk1977602b4662009-07-02 07:47:33 +00007283 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
drhae157872004-08-14 19:20:09 +00007284
danielk1977602b4662009-07-02 07:47:33 +00007285 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
7286 ** database, mark the database as read-only. */
danielk1977003ba062004-11-04 02:57:33 +00007287#ifdef SQLITE_OMIT_AUTOVACUUM
danielk19770d19f7a2009-06-03 11:25:07 +00007288 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00007289#endif
drhae157872004-08-14 19:20:09 +00007290
drhd677b3d2007-08-20 22:48:41 +00007291 sqlite3BtreeLeave(p);
drh8b2f49b2001-06-08 00:21:52 +00007292}
7293
7294/*
drh23e11ca2004-05-04 17:27:28 +00007295** Write meta-information back into the database. Meta[0] is
7296** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00007297*/
danielk1977aef0bf62005-12-30 16:28:01 +00007298int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
7299 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00007300 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00007301 int rc;
drh23e11ca2004-05-04 17:27:28 +00007302 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00007303 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00007304 assert( p->inTrans==TRANS_WRITE );
7305 assert( pBt->pPage1!=0 );
7306 pP1 = pBt->pPage1->aData;
7307 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
7308 if( rc==SQLITE_OK ){
7309 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +00007310#ifndef SQLITE_OMIT_AUTOVACUUM
danielk19770d19f7a2009-06-03 11:25:07 +00007311 if( idx==BTREE_INCR_VACUUM ){
drh64022502009-01-09 14:11:04 +00007312 assert( pBt->autoVacuum || iMeta==0 );
7313 assert( iMeta==0 || iMeta==1 );
7314 pBt->incrVacuum = (u8)iMeta;
drhd677b3d2007-08-20 22:48:41 +00007315 }
drh64022502009-01-09 14:11:04 +00007316#endif
drh5df72a52002-06-06 23:16:05 +00007317 }
drhd677b3d2007-08-20 22:48:41 +00007318 sqlite3BtreeLeave(p);
7319 return rc;
drh8b2f49b2001-06-08 00:21:52 +00007320}
drh8c42ca92001-06-22 19:15:00 +00007321
danielk1977a5533162009-02-24 10:01:51 +00007322#ifndef SQLITE_OMIT_BTREECOUNT
7323/*
7324** The first argument, pCur, is a cursor opened on some b-tree. Count the
7325** number of entries in the b-tree and write the result to *pnEntry.
7326**
7327** SQLITE_OK is returned if the operation is successfully executed.
7328** Otherwise, if an error is encountered (i.e. an IO error or database
7329** corruption) an SQLite error code is returned.
7330*/
7331int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
7332 i64 nEntry = 0; /* Value to return in *pnEntry */
7333 int rc; /* Return code */
7334 rc = moveToRoot(pCur);
7335
7336 /* Unless an error occurs, the following loop runs one iteration for each
7337 ** page in the B-Tree structure (not including overflow pages).
7338 */
7339 while( rc==SQLITE_OK ){
7340 int iIdx; /* Index of child node in parent */
7341 MemPage *pPage; /* Current page of the b-tree */
7342
7343 /* If this is a leaf page or the tree is not an int-key tree, then
7344 ** this page contains countable entries. Increment the entry counter
7345 ** accordingly.
7346 */
7347 pPage = pCur->apPage[pCur->iPage];
7348 if( pPage->leaf || !pPage->intKey ){
7349 nEntry += pPage->nCell;
7350 }
7351
7352 /* pPage is a leaf node. This loop navigates the cursor so that it
7353 ** points to the first interior cell that it points to the parent of
7354 ** the next page in the tree that has not yet been visited. The
7355 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
7356 ** of the page, or to the number of cells in the page if the next page
7357 ** to visit is the right-child of its parent.
7358 **
7359 ** If all pages in the tree have been visited, return SQLITE_OK to the
7360 ** caller.
7361 */
7362 if( pPage->leaf ){
7363 do {
7364 if( pCur->iPage==0 ){
7365 /* All pages of the b-tree have been visited. Return successfully. */
7366 *pnEntry = nEntry;
7367 return SQLITE_OK;
7368 }
danielk197730548662009-07-09 05:07:37 +00007369 moveToParent(pCur);
danielk1977a5533162009-02-24 10:01:51 +00007370 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
7371
7372 pCur->aiIdx[pCur->iPage]++;
7373 pPage = pCur->apPage[pCur->iPage];
7374 }
7375
7376 /* Descend to the child node of the cell that the cursor currently
7377 ** points at. This is the right-child if (iIdx==pPage->nCell).
7378 */
7379 iIdx = pCur->aiIdx[pCur->iPage];
7380 if( iIdx==pPage->nCell ){
7381 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
7382 }else{
7383 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
7384 }
7385 }
7386
shanebe217792009-03-05 04:20:31 +00007387 /* An error has occurred. Return an error code. */
danielk1977a5533162009-02-24 10:01:51 +00007388 return rc;
7389}
7390#endif
drhdd793422001-06-28 01:54:48 +00007391
drhdd793422001-06-28 01:54:48 +00007392/*
drh5eddca62001-06-30 21:53:53 +00007393** Return the pager associated with a BTree. This routine is used for
7394** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00007395*/
danielk1977aef0bf62005-12-30 16:28:01 +00007396Pager *sqlite3BtreePager(Btree *p){
7397 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00007398}
drh5eddca62001-06-30 21:53:53 +00007399
drhb7f91642004-10-31 02:22:47 +00007400#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007401/*
7402** Append a message to the error message string.
7403*/
drh2e38c322004-09-03 18:38:44 +00007404static void checkAppendMsg(
7405 IntegrityCk *pCheck,
7406 char *zMsg1,
7407 const char *zFormat,
7408 ...
7409){
7410 va_list ap;
drh1dcdbc02007-01-27 02:24:54 +00007411 if( !pCheck->mxErr ) return;
7412 pCheck->mxErr--;
7413 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00007414 va_start(ap, zFormat);
drhf089aa42008-07-08 19:34:06 +00007415 if( pCheck->errMsg.nChar ){
7416 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
drh5eddca62001-06-30 21:53:53 +00007417 }
drhf089aa42008-07-08 19:34:06 +00007418 if( zMsg1 ){
7419 sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
7420 }
7421 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
7422 va_end(ap);
drhc890fec2008-08-01 20:10:08 +00007423 if( pCheck->errMsg.mallocFailed ){
7424 pCheck->mallocFailed = 1;
7425 }
drh5eddca62001-06-30 21:53:53 +00007426}
drhb7f91642004-10-31 02:22:47 +00007427#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00007428
drhb7f91642004-10-31 02:22:47 +00007429#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007430/*
7431** Add 1 to the reference count for page iPage. If this is the second
7432** reference to the page, add an error message to pCheck->zErrMsg.
7433** Return 1 if there are 2 ore more references to the page and 0 if
7434** if this is the first reference to the page.
7435**
7436** Also check that the page number is in bounds.
7437*/
danielk197789d40042008-11-17 14:20:56 +00007438static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00007439 if( iPage==0 ) return 1;
danielk197789d40042008-11-17 14:20:56 +00007440 if( iPage>pCheck->nPage ){
drh2e38c322004-09-03 18:38:44 +00007441 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00007442 return 1;
7443 }
7444 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00007445 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00007446 return 1;
7447 }
7448 return (pCheck->anRef[iPage]++)>1;
7449}
7450
danielk1977afcdd022004-10-31 16:25:42 +00007451#ifndef SQLITE_OMIT_AUTOVACUUM
7452/*
7453** Check that the entry in the pointer-map for page iChild maps to
7454** page iParent, pointer type ptrType. If not, append an error message
7455** to pCheck.
7456*/
7457static void checkPtrmap(
7458 IntegrityCk *pCheck, /* Integrity check context */
7459 Pgno iChild, /* Child page number */
7460 u8 eType, /* Expected pointer map type */
7461 Pgno iParent, /* Expected pointer map parent page number */
7462 char *zContext /* Context description (used for error msg) */
7463){
7464 int rc;
7465 u8 ePtrmapType;
7466 Pgno iPtrmapParent;
7467
7468 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
7469 if( rc!=SQLITE_OK ){
drhb56cd552009-05-01 13:16:54 +00007470 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
danielk1977afcdd022004-10-31 16:25:42 +00007471 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
7472 return;
7473 }
7474
7475 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
7476 checkAppendMsg(pCheck, zContext,
7477 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
7478 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
7479 }
7480}
7481#endif
7482
drh5eddca62001-06-30 21:53:53 +00007483/*
7484** Check the integrity of the freelist or of an overflow page list.
7485** Verify that the number of pages on the list is N.
7486*/
drh30e58752002-03-02 20:41:57 +00007487static void checkList(
7488 IntegrityCk *pCheck, /* Integrity checking context */
7489 int isFreeList, /* True for a freelist. False for overflow page list */
7490 int iPage, /* Page number for first page in the list */
7491 int N, /* Expected number of pages in the list */
7492 char *zContext /* Context for error messages */
7493){
7494 int i;
drh3a4c1412004-05-09 20:40:11 +00007495 int expected = N;
7496 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00007497 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00007498 DbPage *pOvflPage;
7499 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00007500 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00007501 checkAppendMsg(pCheck, zContext,
7502 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00007503 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00007504 break;
7505 }
7506 if( checkRef(pCheck, iPage, zContext) ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00007507 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
drh2e38c322004-09-03 18:38:44 +00007508 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00007509 break;
7510 }
danielk19773b8a05f2007-03-19 17:44:26 +00007511 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00007512 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00007513 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00007514#ifndef SQLITE_OMIT_AUTOVACUUM
7515 if( pCheck->pBt->autoVacuum ){
7516 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
7517 }
7518#endif
drh43b18e12010-08-17 19:40:08 +00007519 if( n>(int)pCheck->pBt->usableSize/4-2 ){
drh2e38c322004-09-03 18:38:44 +00007520 checkAppendMsg(pCheck, zContext,
7521 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00007522 N--;
7523 }else{
7524 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00007525 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00007526#ifndef SQLITE_OMIT_AUTOVACUUM
7527 if( pCheck->pBt->autoVacuum ){
7528 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
7529 }
7530#endif
7531 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00007532 }
7533 N -= n;
drh30e58752002-03-02 20:41:57 +00007534 }
drh30e58752002-03-02 20:41:57 +00007535 }
danielk1977afcdd022004-10-31 16:25:42 +00007536#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00007537 else{
7538 /* If this database supports auto-vacuum and iPage is not the last
7539 ** page in this overflow list, check that the pointer-map entry for
7540 ** the following page matches iPage.
7541 */
7542 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00007543 i = get4byte(pOvflData);
danielk1977687566d2004-11-02 12:56:41 +00007544 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
7545 }
danielk1977afcdd022004-10-31 16:25:42 +00007546 }
7547#endif
danielk19773b8a05f2007-03-19 17:44:26 +00007548 iPage = get4byte(pOvflData);
7549 sqlite3PagerUnref(pOvflPage);
drh5eddca62001-06-30 21:53:53 +00007550 }
7551}
drhb7f91642004-10-31 02:22:47 +00007552#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00007553
drhb7f91642004-10-31 02:22:47 +00007554#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007555/*
7556** Do various sanity checks on a single page of a tree. Return
7557** the tree depth. Root pages return 0. Parents of root pages
7558** return 1, and so forth.
7559**
7560** These checks are done:
7561**
7562** 1. Make sure that cells and freeblocks do not overlap
7563** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00007564** NO 2. Make sure cell keys are in order.
7565** NO 3. Make sure no key is less than or equal to zLowerBound.
7566** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00007567** 5. Check the integrity of overflow pages.
7568** 6. Recursively call checkTreePage on all children.
7569** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00007570** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00007571** the root of the tree.
7572*/
7573static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00007574 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00007575 int iPage, /* Page number of the page to check */
shaneh195475d2010-02-19 04:28:08 +00007576 char *zParentContext, /* Parent context */
7577 i64 *pnParentMinKey,
7578 i64 *pnParentMaxKey
drh5eddca62001-06-30 21:53:53 +00007579){
7580 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00007581 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00007582 int hdr, cellStart;
7583 int nCell;
drhda200cc2004-05-09 11:51:38 +00007584 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00007585 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00007586 int usableSize;
drh5eddca62001-06-30 21:53:53 +00007587 char zContext[100];
shane0af3f892008-11-12 04:55:34 +00007588 char *hit = 0;
shaneh195475d2010-02-19 04:28:08 +00007589 i64 nMinKey = 0;
7590 i64 nMaxKey = 0;
drh5eddca62001-06-30 21:53:53 +00007591
drh5bb3eb92007-05-04 13:15:55 +00007592 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
danielk1977ef73ee92004-11-06 12:26:07 +00007593
drh5eddca62001-06-30 21:53:53 +00007594 /* Check that the page exists
7595 */
drhd9cb6ac2005-10-20 07:28:17 +00007596 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00007597 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00007598 if( iPage==0 ) return 0;
7599 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
danielk197730548662009-07-09 05:07:37 +00007600 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drh2e38c322004-09-03 18:38:44 +00007601 checkAppendMsg(pCheck, zContext,
7602 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00007603 return 0;
7604 }
danielk197793caf5a2009-07-11 06:55:33 +00007605
7606 /* Clear MemPage.isInit to make sure the corruption detection code in
7607 ** btreeInitPage() is executed. */
7608 pPage->isInit = 0;
danielk197730548662009-07-09 05:07:37 +00007609 if( (rc = btreeInitPage(pPage))!=0 ){
drh64022502009-01-09 14:11:04 +00007610 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
drh16a9b832007-05-05 18:39:25 +00007611 checkAppendMsg(pCheck, zContext,
danielk197730548662009-07-09 05:07:37 +00007612 "btreeInitPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00007613 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00007614 return 0;
7615 }
7616
7617 /* Check out all the cells.
7618 */
7619 depth = 0;
drh1dcdbc02007-01-27 02:24:54 +00007620 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
drh6f11bef2004-05-13 01:12:56 +00007621 u8 *pCell;
danielk197789d40042008-11-17 14:20:56 +00007622 u32 sz;
drh6f11bef2004-05-13 01:12:56 +00007623 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00007624
7625 /* Check payload overflow pages
7626 */
drh5bb3eb92007-05-04 13:15:55 +00007627 sqlite3_snprintf(sizeof(zContext), zContext,
7628 "On tree page %d cell %d: ", iPage, i);
danielk19771cc5ed82007-05-16 17:28:43 +00007629 pCell = findCell(pPage,i);
danielk197730548662009-07-09 05:07:37 +00007630 btreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00007631 sz = info.nData;
drhf49661a2008-12-10 16:45:50 +00007632 if( !pPage->intKey ) sz += (int)info.nKey;
shaneh195475d2010-02-19 04:28:08 +00007633 /* For intKey pages, check that the keys are in order.
7634 */
7635 else if( i==0 ) nMinKey = nMaxKey = info.nKey;
7636 else{
7637 if( info.nKey <= nMaxKey ){
7638 checkAppendMsg(pCheck, zContext,
7639 "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
7640 }
7641 nMaxKey = info.nKey;
7642 }
drh72365832007-03-06 15:53:44 +00007643 assert( sz==info.nPayload );
danielk19775be31f52009-03-30 13:53:43 +00007644 if( (sz>info.nLocal)
7645 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
7646 ){
drhb6f41482004-05-14 01:58:11 +00007647 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00007648 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
7649#ifndef SQLITE_OMIT_AUTOVACUUM
7650 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00007651 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00007652 }
7653#endif
7654 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00007655 }
7656
7657 /* Check sanity of left child page.
7658 */
drhda200cc2004-05-09 11:51:38 +00007659 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00007660 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00007661#ifndef SQLITE_OMIT_AUTOVACUUM
7662 if( pBt->autoVacuum ){
7663 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
7664 }
7665#endif
shaneh195475d2010-02-19 04:28:08 +00007666 d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
drhda200cc2004-05-09 11:51:38 +00007667 if( i>0 && d2!=depth ){
7668 checkAppendMsg(pCheck, zContext, "Child page depth differs");
7669 }
7670 depth = d2;
drh5eddca62001-06-30 21:53:53 +00007671 }
drh5eddca62001-06-30 21:53:53 +00007672 }
shaneh195475d2010-02-19 04:28:08 +00007673
drhda200cc2004-05-09 11:51:38 +00007674 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00007675 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh5bb3eb92007-05-04 13:15:55 +00007676 sqlite3_snprintf(sizeof(zContext), zContext,
7677 "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00007678#ifndef SQLITE_OMIT_AUTOVACUUM
7679 if( pBt->autoVacuum ){
shaneh195475d2010-02-19 04:28:08 +00007680 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00007681 }
7682#endif
shaneh195475d2010-02-19 04:28:08 +00007683 checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
drhda200cc2004-05-09 11:51:38 +00007684 }
drh5eddca62001-06-30 21:53:53 +00007685
shaneh195475d2010-02-19 04:28:08 +00007686 /* For intKey leaf pages, check that the min/max keys are in order
7687 ** with any left/parent/right pages.
7688 */
7689 if( pPage->leaf && pPage->intKey ){
7690 /* if we are a left child page */
7691 if( pnParentMinKey ){
7692 /* if we are the left most child page */
7693 if( !pnParentMaxKey ){
7694 if( nMaxKey > *pnParentMinKey ){
7695 checkAppendMsg(pCheck, zContext,
7696 "Rowid %lld out of order (max larger than parent min of %lld)",
7697 nMaxKey, *pnParentMinKey);
7698 }
7699 }else{
7700 if( nMinKey <= *pnParentMinKey ){
7701 checkAppendMsg(pCheck, zContext,
7702 "Rowid %lld out of order (min less than parent min of %lld)",
7703 nMinKey, *pnParentMinKey);
7704 }
7705 if( nMaxKey > *pnParentMaxKey ){
7706 checkAppendMsg(pCheck, zContext,
7707 "Rowid %lld out of order (max larger than parent max of %lld)",
7708 nMaxKey, *pnParentMaxKey);
7709 }
7710 *pnParentMinKey = nMaxKey;
7711 }
7712 /* else if we're a right child page */
7713 } else if( pnParentMaxKey ){
7714 if( nMinKey <= *pnParentMaxKey ){
7715 checkAppendMsg(pCheck, zContext,
7716 "Rowid %lld out of order (min less than parent max of %lld)",
7717 nMinKey, *pnParentMaxKey);
7718 }
7719 }
7720 }
7721
drh5eddca62001-06-30 21:53:53 +00007722 /* Check for complete coverage of the page
7723 */
drhda200cc2004-05-09 11:51:38 +00007724 data = pPage->aData;
7725 hdr = pPage->hdrOffset;
drhf7141992008-06-19 00:16:08 +00007726 hit = sqlite3PageMalloc( pBt->pageSize );
drhc890fec2008-08-01 20:10:08 +00007727 if( hit==0 ){
7728 pCheck->mallocFailed = 1;
7729 }else{
drh5d433ce2010-08-14 16:02:52 +00007730 int contentOffset = get2byteNotZero(&data[hdr+5]);
drhd7c7ecd2009-07-14 17:48:06 +00007731 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
shane5780ebd2008-11-11 17:36:30 +00007732 memset(hit+contentOffset, 0, usableSize-contentOffset);
7733 memset(hit, 1, contentOffset);
drh2e38c322004-09-03 18:38:44 +00007734 nCell = get2byte(&data[hdr+3]);
7735 cellStart = hdr + 12 - 4*pPage->leaf;
7736 for(i=0; i<nCell; i++){
7737 int pc = get2byte(&data[cellStart+i*2]);
drh9b78f792010-08-14 21:21:24 +00007738 u32 size = 65536;
drh2e38c322004-09-03 18:38:44 +00007739 int j;
drh8c2bbb62009-07-10 02:52:20 +00007740 if( pc<=usableSize-4 ){
danielk1977daca5432008-08-25 11:57:16 +00007741 size = cellSizePtr(pPage, &data[pc]);
7742 }
drh43b18e12010-08-17 19:40:08 +00007743 if( (int)(pc+size-1)>=usableSize ){
danielk19777701e812005-01-10 12:59:51 +00007744 checkAppendMsg(pCheck, 0,
shaneh195475d2010-02-19 04:28:08 +00007745 "Corruption detected in cell %d on page %d",i,iPage);
danielk19777701e812005-01-10 12:59:51 +00007746 }else{
7747 for(j=pc+size-1; j>=pc; j--) hit[j]++;
7748 }
drh2e38c322004-09-03 18:38:44 +00007749 }
drh8c2bbb62009-07-10 02:52:20 +00007750 i = get2byte(&data[hdr+1]);
7751 while( i>0 ){
7752 int size, j;
7753 assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
7754 size = get2byte(&data[i+2]);
7755 assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
7756 for(j=i+size-1; j>=i; j--) hit[j]++;
7757 j = get2byte(&data[i]);
7758 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
7759 assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
7760 i = j;
drh2e38c322004-09-03 18:38:44 +00007761 }
7762 for(i=cnt=0; i<usableSize; i++){
7763 if( hit[i]==0 ){
7764 cnt++;
7765 }else if( hit[i]>1 ){
7766 checkAppendMsg(pCheck, 0,
7767 "Multiple uses for byte %d of page %d", i, iPage);
7768 break;
7769 }
7770 }
7771 if( cnt!=data[hdr+7] ){
7772 checkAppendMsg(pCheck, 0,
drh8c2bbb62009-07-10 02:52:20 +00007773 "Fragmentation of %d bytes reported as %d on page %d",
drh2e38c322004-09-03 18:38:44 +00007774 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00007775 }
7776 }
drh8c2bbb62009-07-10 02:52:20 +00007777 sqlite3PageFree(hit);
drh4b70f112004-05-02 21:12:19 +00007778 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00007779 return depth+1;
drh5eddca62001-06-30 21:53:53 +00007780}
drhb7f91642004-10-31 02:22:47 +00007781#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00007782
drhb7f91642004-10-31 02:22:47 +00007783#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007784/*
7785** This routine does a complete check of the given BTree file. aRoot[] is
7786** an array of pages numbers were each page number is the root page of
7787** a table. nRoot is the number of entries in aRoot.
7788**
danielk19773509a652009-07-06 18:56:13 +00007789** A read-only or read-write transaction must be opened before calling
7790** this function.
7791**
drhc890fec2008-08-01 20:10:08 +00007792** Write the number of error seen in *pnErr. Except for some memory
drhe43ba702008-12-05 22:40:08 +00007793** allocation errors, an error message held in memory obtained from
drhc890fec2008-08-01 20:10:08 +00007794** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
drhe43ba702008-12-05 22:40:08 +00007795** returned. If a memory allocation error occurs, NULL is returned.
drh5eddca62001-06-30 21:53:53 +00007796*/
drh1dcdbc02007-01-27 02:24:54 +00007797char *sqlite3BtreeIntegrityCheck(
7798 Btree *p, /* The btree to be checked */
7799 int *aRoot, /* An array of root pages numbers for individual trees */
7800 int nRoot, /* Number of entries in aRoot[] */
7801 int mxErr, /* Stop reporting errors after this many */
7802 int *pnErr /* Write number of errors seen to this variable */
7803){
danielk197789d40042008-11-17 14:20:56 +00007804 Pgno i;
drh5eddca62001-06-30 21:53:53 +00007805 int nRef;
drhaaab5722002-02-19 13:39:21 +00007806 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00007807 BtShared *pBt = p->pBt;
drhf089aa42008-07-08 19:34:06 +00007808 char zErr[100];
drh5eddca62001-06-30 21:53:53 +00007809
drhd677b3d2007-08-20 22:48:41 +00007810 sqlite3BtreeEnter(p);
danielk19773509a652009-07-06 18:56:13 +00007811 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
danielk19773b8a05f2007-03-19 17:44:26 +00007812 nRef = sqlite3PagerRefcount(pBt->pPager);
drh5eddca62001-06-30 21:53:53 +00007813 sCheck.pBt = pBt;
7814 sCheck.pPager = pBt->pPager;
drhb1299152010-03-30 22:58:33 +00007815 sCheck.nPage = btreePagecount(sCheck.pBt);
drh1dcdbc02007-01-27 02:24:54 +00007816 sCheck.mxErr = mxErr;
7817 sCheck.nErr = 0;
drhc890fec2008-08-01 20:10:08 +00007818 sCheck.mallocFailed = 0;
drh1dcdbc02007-01-27 02:24:54 +00007819 *pnErr = 0;
drh0de8c112002-07-06 16:32:14 +00007820 if( sCheck.nPage==0 ){
drhd677b3d2007-08-20 22:48:41 +00007821 sqlite3BtreeLeave(p);
drh0de8c112002-07-06 16:32:14 +00007822 return 0;
7823 }
drhe5ae5732008-06-15 02:51:47 +00007824 sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00007825 if( !sCheck.anRef ){
drh1dcdbc02007-01-27 02:24:54 +00007826 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00007827 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00007828 return 0;
danielk1977ac245ec2005-01-14 13:50:11 +00007829 }
drhda200cc2004-05-09 11:51:38 +00007830 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00007831 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00007832 if( i<=sCheck.nPage ){
7833 sCheck.anRef[i] = 1;
7834 }
drhf089aa42008-07-08 19:34:06 +00007835 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
drhb9755982010-07-24 16:34:37 +00007836 sCheck.errMsg.useMalloc = 2;
drh5eddca62001-06-30 21:53:53 +00007837
7838 /* Check the integrity of the freelist
7839 */
drha34b6762004-05-07 13:30:42 +00007840 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
7841 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00007842
7843 /* Check all the tables.
7844 */
danielk197789d40042008-11-17 14:20:56 +00007845 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
drh4ff6dfa2002-03-03 23:06:00 +00007846 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00007847#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00007848 if( pBt->autoVacuum && aRoot[i]>1 ){
7849 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
7850 }
7851#endif
shaneh195475d2010-02-19 04:28:08 +00007852 checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
drh5eddca62001-06-30 21:53:53 +00007853 }
7854
7855 /* Make sure every page in the file is referenced
7856 */
drh1dcdbc02007-01-27 02:24:54 +00007857 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00007858#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00007859 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00007860 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00007861 }
danielk1977afcdd022004-10-31 16:25:42 +00007862#else
7863 /* If the database supports auto-vacuum, make sure no tables contain
7864 ** references to pointer-map pages.
7865 */
7866 if( sCheck.anRef[i]==0 &&
danielk1977266664d2006-02-10 08:24:21 +00007867 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00007868 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
7869 }
7870 if( sCheck.anRef[i]!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00007871 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00007872 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
7873 }
7874#endif
drh5eddca62001-06-30 21:53:53 +00007875 }
7876
drh64022502009-01-09 14:11:04 +00007877 /* Make sure this analysis did not leave any unref() pages.
7878 ** This is an internal consistency check; an integrity check
7879 ** of the integrity check.
drh5eddca62001-06-30 21:53:53 +00007880 */
drh64022502009-01-09 14:11:04 +00007881 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
drh2e38c322004-09-03 18:38:44 +00007882 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00007883 "Outstanding page count goes from %d to %d during this analysis",
danielk19773b8a05f2007-03-19 17:44:26 +00007884 nRef, sqlite3PagerRefcount(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00007885 );
drh5eddca62001-06-30 21:53:53 +00007886 }
7887
7888 /* Clean up and report errors.
7889 */
drhd677b3d2007-08-20 22:48:41 +00007890 sqlite3BtreeLeave(p);
drh17435752007-08-16 04:30:38 +00007891 sqlite3_free(sCheck.anRef);
drhc890fec2008-08-01 20:10:08 +00007892 if( sCheck.mallocFailed ){
7893 sqlite3StrAccumReset(&sCheck.errMsg);
7894 *pnErr = sCheck.nErr+1;
7895 return 0;
7896 }
drh1dcdbc02007-01-27 02:24:54 +00007897 *pnErr = sCheck.nErr;
drhf089aa42008-07-08 19:34:06 +00007898 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
7899 return sqlite3StrAccumFinish(&sCheck.errMsg);
drh5eddca62001-06-30 21:53:53 +00007900}
drhb7f91642004-10-31 02:22:47 +00007901#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00007902
drh73509ee2003-04-06 20:44:45 +00007903/*
7904** Return the full pathname of the underlying database file.
drhd0679ed2007-08-28 22:24:34 +00007905**
7906** The pager filename is invariant as long as the pager is
7907** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +00007908*/
danielk1977aef0bf62005-12-30 16:28:01 +00007909const char *sqlite3BtreeGetFilename(Btree *p){
7910 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007911 return sqlite3PagerFilename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00007912}
7913
7914/*
danielk19775865e3d2004-06-14 06:03:57 +00007915** Return the pathname of the journal file for this database. The return
7916** value of this routine is the same regardless of whether the journal file
7917** has been created or not.
drhd0679ed2007-08-28 22:24:34 +00007918**
7919** The pager journal filename is invariant as long as the pager is
7920** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00007921*/
danielk1977aef0bf62005-12-30 16:28:01 +00007922const char *sqlite3BtreeGetJournalname(Btree *p){
7923 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007924 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00007925}
7926
danielk19771d850a72004-05-31 08:26:49 +00007927/*
7928** Return non-zero if a transaction is active.
7929*/
danielk1977aef0bf62005-12-30 16:28:01 +00007930int sqlite3BtreeIsInTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00007931 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00007932 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00007933}
7934
dana550f2d2010-08-02 10:47:05 +00007935#ifndef SQLITE_OMIT_WAL
7936/*
7937** Run a checkpoint on the Btree passed as the first argument.
7938**
7939** Return SQLITE_LOCKED if this or any other connection has an open
7940** transaction on the shared-cache the argument Btree is connected to.
dana58f26f2010-11-16 18:56:51 +00007941**
dancdc1f042010-11-18 12:11:05 +00007942** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
dana550f2d2010-08-02 10:47:05 +00007943*/
dancdc1f042010-11-18 12:11:05 +00007944int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
dana550f2d2010-08-02 10:47:05 +00007945 int rc = SQLITE_OK;
7946 if( p ){
7947 BtShared *pBt = p->pBt;
7948 sqlite3BtreeEnter(p);
7949 if( pBt->inTransaction!=TRANS_NONE ){
7950 rc = SQLITE_LOCKED;
7951 }else{
dancdc1f042010-11-18 12:11:05 +00007952 rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
dana550f2d2010-08-02 10:47:05 +00007953 }
7954 sqlite3BtreeLeave(p);
7955 }
7956 return rc;
7957}
7958#endif
7959
danielk19771d850a72004-05-31 08:26:49 +00007960/*
danielk19772372c2b2006-06-27 16:34:56 +00007961** Return non-zero if a read (or write) transaction is active.
7962*/
7963int sqlite3BtreeIsInReadTrans(Btree *p){
drh64022502009-01-09 14:11:04 +00007964 assert( p );
drhe5fe6902007-12-07 18:55:28 +00007965 assert( sqlite3_mutex_held(p->db->mutex) );
drh64022502009-01-09 14:11:04 +00007966 return p->inTrans!=TRANS_NONE;
danielk19772372c2b2006-06-27 16:34:56 +00007967}
7968
danielk197704103022009-02-03 16:51:24 +00007969int sqlite3BtreeIsInBackup(Btree *p){
7970 assert( p );
7971 assert( sqlite3_mutex_held(p->db->mutex) );
7972 return p->nBackup!=0;
7973}
7974
danielk19772372c2b2006-06-27 16:34:56 +00007975/*
danielk1977da184232006-01-05 11:34:32 +00007976** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +00007977** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +00007978** purposes (for example, to store a high-level schema associated with
7979** the shared-btree). The btree layer manages reference counting issues.
7980**
7981** The first time this is called on a shared-btree, nBytes bytes of memory
7982** are allocated, zeroed, and returned to the caller. For each subsequent
7983** call the nBytes parameter is ignored and a pointer to the same blob
7984** of memory returned.
7985**
danielk1977171bfed2008-06-23 09:50:50 +00007986** If the nBytes parameter is 0 and the blob of memory has not yet been
7987** allocated, a null pointer is returned. If the blob has already been
7988** allocated, it is returned as normal.
7989**
danielk1977da184232006-01-05 11:34:32 +00007990** Just before the shared-btree is closed, the function passed as the
7991** xFree argument when the memory allocation was made is invoked on the
drh4fa7d7c2011-04-03 02:41:00 +00007992** blob of allocated memory. The xFree function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +00007993** on the memory, the btree layer does that.
7994*/
7995void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
7996 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +00007997 sqlite3BtreeEnter(p);
danielk1977171bfed2008-06-23 09:50:50 +00007998 if( !pBt->pSchema && nBytes ){
drhb9755982010-07-24 16:34:37 +00007999 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
danielk1977da184232006-01-05 11:34:32 +00008000 pBt->xFreeSchema = xFree;
8001 }
drh27641702007-08-22 02:56:42 +00008002 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00008003 return pBt->pSchema;
8004}
8005
danielk1977c87d34d2006-01-06 13:00:28 +00008006/*
danielk1977404ca072009-03-16 13:19:36 +00008007** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
8008** btree as the argument handle holds an exclusive lock on the
8009** sqlite_master table. Otherwise SQLITE_OK.
danielk1977c87d34d2006-01-06 13:00:28 +00008010*/
8011int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +00008012 int rc;
drhe5fe6902007-12-07 18:55:28 +00008013 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +00008014 sqlite3BtreeEnter(p);
danielk1977404ca072009-03-16 13:19:36 +00008015 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
8016 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
drh27641702007-08-22 02:56:42 +00008017 sqlite3BtreeLeave(p);
8018 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +00008019}
8020
drha154dcd2006-03-22 22:10:07 +00008021
8022#ifndef SQLITE_OMIT_SHARED_CACHE
8023/*
8024** Obtain a lock on the table whose root page is iTab. The
8025** lock is a write lock if isWritelock is true or a read lock
8026** if it is false.
8027*/
danielk1977c00da102006-01-07 13:21:04 +00008028int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00008029 int rc = SQLITE_OK;
danielk1977602b4662009-07-02 07:47:33 +00008030 assert( p->inTrans!=TRANS_NONE );
drh6a9ad3d2008-04-02 16:29:30 +00008031 if( p->sharable ){
8032 u8 lockType = READ_LOCK + isWriteLock;
8033 assert( READ_LOCK+1==WRITE_LOCK );
8034 assert( isWriteLock==0 || isWriteLock==1 );
danielk1977602b4662009-07-02 07:47:33 +00008035
drh6a9ad3d2008-04-02 16:29:30 +00008036 sqlite3BtreeEnter(p);
drhc25eabe2009-02-24 18:57:31 +00008037 rc = querySharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00008038 if( rc==SQLITE_OK ){
drhc25eabe2009-02-24 18:57:31 +00008039 rc = setSharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00008040 }
8041 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +00008042 }
8043 return rc;
8044}
drha154dcd2006-03-22 22:10:07 +00008045#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00008046
danielk1977b4e9af92007-05-01 17:49:49 +00008047#ifndef SQLITE_OMIT_INCRBLOB
8048/*
8049** Argument pCsr must be a cursor opened for writing on an
8050** INTKEY table currently pointing at a valid table entry.
8051** This function modifies the data stored as part of that entry.
danielk1977ecaecf92009-07-08 08:05:35 +00008052**
8053** Only the data content may only be modified, it is not possible to
8054** change the length of the data stored. If this function is called with
8055** parameters that attempt to write past the end of the existing data,
8056** no modifications are made and SQLITE_CORRUPT is returned.
danielk1977b4e9af92007-05-01 17:49:49 +00008057*/
danielk1977dcbb5d32007-05-04 18:36:44 +00008058int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
danielk1977c9000e62009-07-08 13:55:28 +00008059 int rc;
drh1fee73e2007-08-29 04:00:57 +00008060 assert( cursorHoldsMutex(pCsr) );
drhe5fe6902007-12-07 18:55:28 +00008061 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
danielk197796d48e92009-06-29 06:00:37 +00008062 assert( pCsr->isIncrblobHandle );
danielk19773588ceb2008-06-10 17:30:26 +00008063
danielk1977c9000e62009-07-08 13:55:28 +00008064 rc = restoreCursorPosition(pCsr);
8065 if( rc!=SQLITE_OK ){
8066 return rc;
8067 }
danielk19773588ceb2008-06-10 17:30:26 +00008068 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
8069 if( pCsr->eState!=CURSOR_VALID ){
8070 return SQLITE_ABORT;
danielk1977dcbb5d32007-05-04 18:36:44 +00008071 }
8072
danielk1977c9000e62009-07-08 13:55:28 +00008073 /* Check some assumptions:
danielk1977dcbb5d32007-05-04 18:36:44 +00008074 ** (a) the cursor is open for writing,
danielk1977c9000e62009-07-08 13:55:28 +00008075 ** (b) there is a read/write transaction open,
8076 ** (c) the connection holds a write-lock on the table (if required),
8077 ** (d) there are no conflicting read-locks, and
8078 ** (e) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00008079 */
danielk19774f029602009-07-08 18:45:37 +00008080 if( !pCsr->wrFlag ){
8081 return SQLITE_READONLY;
8082 }
danielk197796d48e92009-06-29 06:00:37 +00008083 assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
8084 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
8085 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
danielk1977c9000e62009-07-08 13:55:28 +00008086 assert( pCsr->apPage[pCsr->iPage]->intKey );
danielk1977b4e9af92007-05-01 17:49:49 +00008087
drhfb192682009-07-11 18:26:28 +00008088 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00008089}
danielk19772dec9702007-05-02 16:48:37 +00008090
8091/*
8092** Set a flag on this cursor to cache the locations of pages from the
danielk1977da107192007-05-04 08:32:13 +00008093** overflow list for the current row. This is used by cursors opened
8094** for incremental blob IO only.
8095**
8096** This function sets a flag only. The actual page location cache
8097** (stored in BtCursor.aOverflow[]) is allocated and used by function
8098** accessPayload() (the worker function for sqlite3BtreeData() and
8099** sqlite3BtreePutData()).
danielk19772dec9702007-05-02 16:48:37 +00008100*/
8101void sqlite3BtreeCacheOverflow(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00008102 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00008103 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
dan4e76cc32010-10-20 18:56:04 +00008104 invalidateOverflowCache(pCur);
danielk1977dcbb5d32007-05-04 18:36:44 +00008105 pCur->isIncrblobHandle = 1;
danielk19772dec9702007-05-02 16:48:37 +00008106}
danielk1977b4e9af92007-05-01 17:49:49 +00008107#endif
dane04dc882010-04-20 18:53:15 +00008108
8109/*
8110** Set both the "read version" (single byte at byte offset 18) and
8111** "write version" (single byte at byte offset 19) fields in the database
8112** header to iVersion.
8113*/
8114int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
8115 BtShared *pBt = pBtree->pBt;
8116 int rc; /* Return code */
8117
danb9780022010-04-21 18:37:57 +00008118 assert( pBtree->inTrans==TRANS_NONE );
dane04dc882010-04-20 18:53:15 +00008119 assert( iVersion==1 || iVersion==2 );
8120
danb9780022010-04-21 18:37:57 +00008121 /* If setting the version fields to 1, do not automatically open the
8122 ** WAL connection, even if the version fields are currently set to 2.
8123 */
shaneh5eba1f62010-07-02 17:05:03 +00008124 pBt->doNotUseWAL = (u8)(iVersion==1);
danb9780022010-04-21 18:37:57 +00008125
8126 rc = sqlite3BtreeBeginTrans(pBtree, 0);
dane04dc882010-04-20 18:53:15 +00008127 if( rc==SQLITE_OK ){
8128 u8 *aData = pBt->pPage1->aData;
danb9780022010-04-21 18:37:57 +00008129 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
danede6eb82010-04-22 06:27:04 +00008130 rc = sqlite3BtreeBeginTrans(pBtree, 2);
danb9780022010-04-21 18:37:57 +00008131 if( rc==SQLITE_OK ){
8132 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
8133 if( rc==SQLITE_OK ){
8134 aData[18] = (u8)iVersion;
8135 aData[19] = (u8)iVersion;
8136 }
8137 }
8138 }
dane04dc882010-04-20 18:53:15 +00008139 }
8140
danb9780022010-04-21 18:37:57 +00008141 pBt->doNotUseWAL = 0;
dane04dc882010-04-20 18:53:15 +00008142 return rc;
8143}