blob: 71a2f96dabe339f321c1ccb610d6da01a2a3cb01 [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*************************************************************************
drheeb844a2009-08-08 18:01:07 +000012** $Id: btree.c,v 1.704 2009/08/08 18:01:08 drh Exp $
drh8b2f49b2001-06-08 00:21:52 +000013**
14** This file implements a external (disk-based) database using BTrees.
drha3152892007-05-05 11:48:52 +000015** See the header comment on "btreeInt.h" for additional information.
16** Including a description of file format and an overview of operation.
drha059ad02001-04-17 20:09:11 +000017*/
drha3152892007-05-05 11:48:52 +000018#include "btreeInt.h"
paulb95a8862003-04-01 21:16:41 +000019
drh8c42ca92001-06-22 19:15:00 +000020/*
drha3152892007-05-05 11:48:52 +000021** The header string that appears at the beginning of every
22** SQLite database.
drh556b2a22005-06-14 16:04:05 +000023*/
drh556b2a22005-06-14 16:04:05 +000024static const char zMagicHeader[] = SQLITE_FILE_HEADER;
drh08ed44e2001-04-29 23:32:55 +000025
drh8c42ca92001-06-22 19:15:00 +000026/*
drha3152892007-05-05 11:48:52 +000027** Set this global variable to 1 to enable tracing using the TRACE
28** macro.
drh615ae552005-01-16 23:21:00 +000029*/
drhe8f52c52008-07-12 14:52:20 +000030#if 0
danielk1977a50d9aa2009-06-08 14:49:45 +000031int sqlite3BtreeTrace=1; /* True to enable tracing */
drhe8f52c52008-07-12 14:52:20 +000032# define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
33#else
34# define TRACE(X)
drh615ae552005-01-16 23:21:00 +000035#endif
drh615ae552005-01-16 23:21:00 +000036
drh86f8c192007-08-22 00:39:19 +000037
38
drhe53831d2007-08-17 01:14:38 +000039#ifndef SQLITE_OMIT_SHARED_CACHE
40/*
danielk1977502b4e02008-09-02 14:07:24 +000041** A list of BtShared objects that are eligible for participation
42** in shared cache. This variable has file scope during normal builds,
43** but the test harness needs to access it so we make it global for
44** test builds.
drh7555d8e2009-03-20 13:15:30 +000045**
46** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
drhe53831d2007-08-17 01:14:38 +000047*/
48#ifdef SQLITE_TEST
drh78f82d12008-09-02 00:52:52 +000049BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
drhe53831d2007-08-17 01:14:38 +000050#else
drh78f82d12008-09-02 00:52:52 +000051static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
drhe53831d2007-08-17 01:14:38 +000052#endif
drhe53831d2007-08-17 01:14:38 +000053#endif /* SQLITE_OMIT_SHARED_CACHE */
54
55#ifndef SQLITE_OMIT_SHARED_CACHE
56/*
57** Enable or disable the shared pager and schema features.
58**
59** This routine has no effect on existing database connections.
60** The shared cache setting effects only future calls to
61** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
62*/
63int sqlite3_enable_shared_cache(int enable){
danielk1977502b4e02008-09-02 14:07:24 +000064 sqlite3GlobalConfig.sharedCacheEnabled = enable;
drhe53831d2007-08-17 01:14:38 +000065 return SQLITE_OK;
66}
67#endif
68
drhd677b3d2007-08-20 22:48:41 +000069
danielk1977aef0bf62005-12-30 16:28:01 +000070
71#ifdef SQLITE_OMIT_SHARED_CACHE
72 /*
drhc25eabe2009-02-24 18:57:31 +000073 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
74 ** and clearAllSharedCacheTableLocks()
danielk1977aef0bf62005-12-30 16:28:01 +000075 ** manipulate entries in the BtShared.pLock linked list used to store
76 ** shared-cache table level locks. If the library is compiled with the
77 ** shared-cache feature disabled, then there is only ever one user
danielk1977da184232006-01-05 11:34:32 +000078 ** of each BtShared structure and so this locking is not necessary.
79 ** So define the lock related functions as no-ops.
danielk1977aef0bf62005-12-30 16:28:01 +000080 */
drhc25eabe2009-02-24 18:57:31 +000081 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
82 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
83 #define clearAllSharedCacheTableLocks(a)
danielk197794b30732009-07-02 17:21:57 +000084 #define downgradeAllSharedCacheTableLocks(a)
danielk197796d48e92009-06-29 06:00:37 +000085 #define hasSharedCacheTableLock(a,b,c,d) 1
86 #define hasReadConflicts(a, b) 0
drhe53831d2007-08-17 01:14:38 +000087#endif
danielk1977aef0bf62005-12-30 16:28:01 +000088
drhe53831d2007-08-17 01:14:38 +000089#ifndef SQLITE_OMIT_SHARED_CACHE
danielk197796d48e92009-06-29 06:00:37 +000090
91#ifdef SQLITE_DEBUG
92/*
93** This function is only used as part of an assert() statement. It checks
94** that connection p holds the required locks to read or write to the
95** b-tree with root page iRoot. If so, true is returned. Otherwise, false.
96** For example, when writing to a table b-tree with root-page iRoot via
97** Btree connection pBtree:
98**
99** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
100**
101** When writing to an index b-tree that resides in a sharable database, the
102** caller should have first obtained a lock specifying the root page of
103** the corresponding table b-tree. This makes things a bit more complicated,
104** as this module treats each b-tree as a separate structure. To determine
105** the table b-tree corresponding to the index b-tree being written, this
106** function has to search through the database schema.
107**
108** Instead of a lock on the b-tree rooted at page iRoot, the caller may
109** hold a write-lock on the schema table (root page 1). This is also
110** acceptable.
111*/
112static int hasSharedCacheTableLock(
113 Btree *pBtree, /* Handle that must hold lock */
114 Pgno iRoot, /* Root page of b-tree */
115 int isIndex, /* True if iRoot is the root of an index b-tree */
116 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
117){
118 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
119 Pgno iTab = 0;
120 BtLock *pLock;
121
122 /* If this b-tree database is not shareable, or if the client is reading
123 ** and has the read-uncommitted flag set, then no lock is required.
124 ** In these cases return true immediately. If the client is reading
125 ** or writing an index b-tree, but the schema is not loaded, then return
126 ** true also. In this case the lock is required, but it is too difficult
127 ** to check if the client actually holds it. This doesn't happen very
128 ** often. */
129 if( (pBtree->sharable==0)
130 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
131 || (isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0 ))
132 ){
133 return 1;
134 }
135
136 /* Figure out the root-page that the lock should be held on. For table
137 ** b-trees, this is just the root page of the b-tree being read or
138 ** written. For index b-trees, it is the root page of the associated
139 ** table. */
140 if( isIndex ){
141 HashElem *p;
142 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
143 Index *pIdx = (Index *)sqliteHashData(p);
144 if( pIdx->tnum==iRoot ){
145 iTab = pIdx->pTable->tnum;
146 }
147 }
148 }else{
149 iTab = iRoot;
150 }
151
152 /* Search for the required lock. Either a write-lock on root-page iTab, a
153 ** write-lock on the schema table, or (if the client is reading) a
154 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
155 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
156 if( pLock->pBtree==pBtree
157 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
158 && pLock->eLock>=eLockType
159 ){
160 return 1;
161 }
162 }
163
164 /* Failed to find the required lock. */
165 return 0;
166}
167
168/*
169** This function is also used as part of assert() statements only. It
170** returns true if there exist one or more cursors open on the table
171** with root page iRoot that do not belong to either connection pBtree
172** or some other connection that has the read-uncommitted flag set.
173**
174** For example, before writing to page iRoot:
175**
176** assert( !hasReadConflicts(pBtree, iRoot) );
177*/
178static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
179 BtCursor *p;
180 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
181 if( p->pgnoRoot==iRoot
182 && p->pBtree!=pBtree
183 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
184 ){
185 return 1;
186 }
187 }
188 return 0;
189}
190#endif /* #ifdef SQLITE_DEBUG */
191
danielk1977da184232006-01-05 11:34:32 +0000192/*
danielk1977aef0bf62005-12-30 16:28:01 +0000193** Query to see if btree handle p may obtain a lock of type eLock
194** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
drhc25eabe2009-02-24 18:57:31 +0000195** SQLITE_OK if the lock may be obtained (by calling
196** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
danielk1977aef0bf62005-12-30 16:28:01 +0000197*/
drhc25eabe2009-02-24 18:57:31 +0000198static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
danielk1977aef0bf62005-12-30 16:28:01 +0000199 BtShared *pBt = p->pBt;
200 BtLock *pIter;
201
drh1fee73e2007-08-29 04:00:57 +0000202 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000203 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
204 assert( p->db!=0 );
danielk1977e0d9e6f2009-07-03 16:25:06 +0000205 assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
drhd677b3d2007-08-20 22:48:41 +0000206
danielk19775b413d72009-04-01 09:41:54 +0000207 /* If requesting a write-lock, then the Btree must have an open write
208 ** transaction on this file. And, obviously, for this to be so there
209 ** must be an open write transaction on the file itself.
210 */
211 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
212 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
213
danielk1977da184232006-01-05 11:34:32 +0000214 /* This is a no-op if the shared-cache is not enabled */
drhe53831d2007-08-17 01:14:38 +0000215 if( !p->sharable ){
danielk1977da184232006-01-05 11:34:32 +0000216 return SQLITE_OK;
217 }
218
danielk1977641b0f42007-12-21 04:47:25 +0000219 /* If some other connection is holding an exclusive lock, the
220 ** requested lock may not be obtained.
221 */
danielk1977404ca072009-03-16 13:19:36 +0000222 if( pBt->pWriter!=p && pBt->isExclusive ){
223 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
224 return SQLITE_LOCKED_SHAREDCACHE;
danielk1977641b0f42007-12-21 04:47:25 +0000225 }
226
danielk1977e0d9e6f2009-07-03 16:25:06 +0000227 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
228 /* The condition (pIter->eLock!=eLock) in the following if(...)
229 ** statement is a simplification of:
230 **
231 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
232 **
233 ** since we know that if eLock==WRITE_LOCK, then no other connection
234 ** may hold a WRITE_LOCK on any table in this file (since there can
235 ** only be a single writer).
236 */
237 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
238 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
239 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
240 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
241 if( eLock==WRITE_LOCK ){
242 assert( p==pBt->pWriter );
243 pBt->isPending = 1;
danielk1977da184232006-01-05 11:34:32 +0000244 }
danielk1977e0d9e6f2009-07-03 16:25:06 +0000245 return SQLITE_LOCKED_SHAREDCACHE;
danielk1977aef0bf62005-12-30 16:28:01 +0000246 }
247 }
248 return SQLITE_OK;
249}
drhe53831d2007-08-17 01:14:38 +0000250#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000251
drhe53831d2007-08-17 01:14:38 +0000252#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000253/*
254** Add a lock on the table with root-page iTable to the shared-btree used
255** by Btree handle p. Parameter eLock must be either READ_LOCK or
256** WRITE_LOCK.
257**
danielk19779d104862009-07-09 08:27:14 +0000258** This function assumes the following:
259**
260** (a) The specified b-tree connection handle is connected to a sharable
261** b-tree database (one with the BtShared.sharable) flag set, and
262**
263** (b) No other b-tree connection handle holds a lock that conflicts
264** with the requested lock (i.e. querySharedCacheTableLock() has
265** already been called and returned SQLITE_OK).
266**
267** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
268** is returned if a malloc attempt fails.
danielk1977aef0bf62005-12-30 16:28:01 +0000269*/
drhc25eabe2009-02-24 18:57:31 +0000270static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
danielk1977aef0bf62005-12-30 16:28:01 +0000271 BtShared *pBt = p->pBt;
272 BtLock *pLock = 0;
273 BtLock *pIter;
274
drh1fee73e2007-08-29 04:00:57 +0000275 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000276 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
277 assert( p->db!=0 );
drhd677b3d2007-08-20 22:48:41 +0000278
danielk1977e0d9e6f2009-07-03 16:25:06 +0000279 /* A connection with the read-uncommitted flag set will never try to
280 ** obtain a read-lock using this function. The only read-lock obtained
281 ** by a connection in read-uncommitted mode is on the sqlite_master
282 ** table, and that lock is obtained in BtreeBeginTrans(). */
283 assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
284
danielk19779d104862009-07-09 08:27:14 +0000285 /* This function should only be called on a sharable b-tree after it
286 ** has been determined that no other b-tree holds a conflicting lock. */
287 assert( p->sharable );
drhc25eabe2009-02-24 18:57:31 +0000288 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
danielk1977aef0bf62005-12-30 16:28:01 +0000289
290 /* First search the list for an existing lock on this table. */
291 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
292 if( pIter->iTable==iTable && pIter->pBtree==p ){
293 pLock = pIter;
294 break;
295 }
296 }
297
298 /* If the above search did not find a BtLock struct associating Btree p
299 ** with table iTable, allocate one and link it into the list.
300 */
301 if( !pLock ){
drh17435752007-08-16 04:30:38 +0000302 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
danielk1977aef0bf62005-12-30 16:28:01 +0000303 if( !pLock ){
304 return SQLITE_NOMEM;
305 }
306 pLock->iTable = iTable;
307 pLock->pBtree = p;
308 pLock->pNext = pBt->pLock;
309 pBt->pLock = pLock;
310 }
311
312 /* Set the BtLock.eLock variable to the maximum of the current lock
313 ** and the requested lock. This means if a write-lock was already held
314 ** and a read-lock requested, we don't incorrectly downgrade the lock.
315 */
316 assert( WRITE_LOCK>READ_LOCK );
danielk19775118b912005-12-30 16:31:53 +0000317 if( eLock>pLock->eLock ){
318 pLock->eLock = eLock;
319 }
danielk1977aef0bf62005-12-30 16:28:01 +0000320
321 return SQLITE_OK;
322}
drhe53831d2007-08-17 01:14:38 +0000323#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000324
drhe53831d2007-08-17 01:14:38 +0000325#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000326/*
drhc25eabe2009-02-24 18:57:31 +0000327** Release all the table locks (locks obtained via calls to
328** the setSharedCacheTableLock() procedure) held by Btree handle p.
danielk1977fa542f12009-04-02 18:28:08 +0000329**
330** This function assumes that handle p has an open read or write
331** transaction. If it does not, then the BtShared.isPending variable
332** may be incorrectly cleared.
danielk1977aef0bf62005-12-30 16:28:01 +0000333*/
drhc25eabe2009-02-24 18:57:31 +0000334static void clearAllSharedCacheTableLocks(Btree *p){
danielk1977641b0f42007-12-21 04:47:25 +0000335 BtShared *pBt = p->pBt;
336 BtLock **ppIter = &pBt->pLock;
danielk1977da184232006-01-05 11:34:32 +0000337
drh1fee73e2007-08-29 04:00:57 +0000338 assert( sqlite3BtreeHoldsMutex(p) );
drhe53831d2007-08-17 01:14:38 +0000339 assert( p->sharable || 0==*ppIter );
danielk1977fa542f12009-04-02 18:28:08 +0000340 assert( p->inTrans>0 );
danielk1977da184232006-01-05 11:34:32 +0000341
danielk1977aef0bf62005-12-30 16:28:01 +0000342 while( *ppIter ){
343 BtLock *pLock = *ppIter;
danielk1977404ca072009-03-16 13:19:36 +0000344 assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
danielk1977fa542f12009-04-02 18:28:08 +0000345 assert( pLock->pBtree->inTrans>=pLock->eLock );
danielk1977aef0bf62005-12-30 16:28:01 +0000346 if( pLock->pBtree==p ){
347 *ppIter = pLock->pNext;
danielk1977602b4662009-07-02 07:47:33 +0000348 assert( pLock->iTable!=1 || pLock==&p->lock );
349 if( pLock->iTable!=1 ){
350 sqlite3_free(pLock);
351 }
danielk1977aef0bf62005-12-30 16:28:01 +0000352 }else{
353 ppIter = &pLock->pNext;
354 }
355 }
danielk1977641b0f42007-12-21 04:47:25 +0000356
danielk1977404ca072009-03-16 13:19:36 +0000357 assert( pBt->isPending==0 || pBt->pWriter );
358 if( pBt->pWriter==p ){
359 pBt->pWriter = 0;
360 pBt->isExclusive = 0;
361 pBt->isPending = 0;
362 }else if( pBt->nTransaction==2 ){
363 /* This function is called when connection p is concluding its
364 ** transaction. If there currently exists a writer, and p is not
365 ** that writer, then the number of locks held by connections other
366 ** than the writer must be about to drop to zero. In this case
367 ** set the isPending flag to 0.
368 **
369 ** If there is not currently a writer, then BtShared.isPending must
370 ** be zero already. So this next line is harmless in that case.
371 */
372 pBt->isPending = 0;
danielk1977641b0f42007-12-21 04:47:25 +0000373 }
danielk1977aef0bf62005-12-30 16:28:01 +0000374}
danielk197794b30732009-07-02 17:21:57 +0000375
danielk1977e0d9e6f2009-07-03 16:25:06 +0000376/*
377** This function changes all write-locks held by connection p to read-locks.
378*/
danielk197794b30732009-07-02 17:21:57 +0000379static void downgradeAllSharedCacheTableLocks(Btree *p){
380 BtShared *pBt = p->pBt;
381 if( pBt->pWriter==p ){
382 BtLock *pLock;
383 pBt->pWriter = 0;
384 pBt->isExclusive = 0;
385 pBt->isPending = 0;
386 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
387 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
388 pLock->eLock = READ_LOCK;
389 }
390 }
391}
392
danielk1977aef0bf62005-12-30 16:28:01 +0000393#endif /* SQLITE_OMIT_SHARED_CACHE */
394
drh980b1a72006-08-16 16:42:48 +0000395static void releasePage(MemPage *pPage); /* Forward reference */
396
drh1fee73e2007-08-29 04:00:57 +0000397/*
398** Verify that the cursor holds a mutex on the BtShared
399*/
400#ifndef NDEBUG
401static int cursorHoldsMutex(BtCursor *p){
drhff0587c2007-08-29 17:43:19 +0000402 return sqlite3_mutex_held(p->pBt->mutex);
drh1fee73e2007-08-29 04:00:57 +0000403}
404#endif
405
406
danielk197792d4d7a2007-05-04 12:05:56 +0000407#ifndef SQLITE_OMIT_INCRBLOB
408/*
409** Invalidate the overflow page-list cache for cursor pCur, if any.
410*/
411static void invalidateOverflowCache(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000412 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000413 sqlite3_free(pCur->aOverflow);
danielk197792d4d7a2007-05-04 12:05:56 +0000414 pCur->aOverflow = 0;
415}
416
417/*
418** Invalidate the overflow page-list cache for all cursors opened
419** on the shared btree structure pBt.
420*/
421static void invalidateAllOverflowCache(BtShared *pBt){
422 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000423 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +0000424 for(p=pBt->pCursor; p; p=p->pNext){
425 invalidateOverflowCache(p);
426 }
427}
danielk197796d48e92009-06-29 06:00:37 +0000428
429/*
430** This function is called before modifying the contents of a table
431** b-tree to invalidate any incrblob cursors that are open on the
drheeb844a2009-08-08 18:01:07 +0000432** row or one of the rows being modified.
danielk197796d48e92009-06-29 06:00:37 +0000433**
434** If argument isClearTable is true, then the entire contents of the
435** table is about to be deleted. In this case invalidate all incrblob
436** cursors open on any row within the table with root-page pgnoRoot.
437**
438** Otherwise, if argument isClearTable is false, then the row with
439** rowid iRow is being replaced or deleted. In this case invalidate
440** only those incrblob cursors open on this specific row.
441*/
442static void invalidateIncrblobCursors(
443 Btree *pBtree, /* The database file to check */
danielk197796d48e92009-06-29 06:00:37 +0000444 i64 iRow, /* The rowid that might be changing */
445 int isClearTable /* True if all rows are being deleted */
446){
447 BtCursor *p;
448 BtShared *pBt = pBtree->pBt;
449 assert( sqlite3BtreeHoldsMutex(pBtree) );
450 for(p=pBt->pCursor; p; p=p->pNext){
451 if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
452 p->eState = CURSOR_INVALID;
453 }
454 }
455}
456
danielk197792d4d7a2007-05-04 12:05:56 +0000457#else
458 #define invalidateOverflowCache(x)
459 #define invalidateAllOverflowCache(x)
drheeb844a2009-08-08 18:01:07 +0000460 #define invalidateIncrblobCursors(x,y,z)
danielk197792d4d7a2007-05-04 12:05:56 +0000461#endif
462
drh980b1a72006-08-16 16:42:48 +0000463/*
danielk1977bea2a942009-01-20 17:06:27 +0000464** Set bit pgno of the BtShared.pHasContent bitvec. This is called
465** when a page that previously contained data becomes a free-list leaf
466** page.
467**
468** The BtShared.pHasContent bitvec exists to work around an obscure
469** bug caused by the interaction of two useful IO optimizations surrounding
470** free-list leaf pages:
471**
472** 1) When all data is deleted from a page and the page becomes
473** a free-list leaf page, the page is not written to the database
474** (as free-list leaf pages contain no meaningful data). Sometimes
475** such a page is not even journalled (as it will not be modified,
476** why bother journalling it?).
477**
478** 2) When a free-list leaf page is reused, its content is not read
479** from the database or written to the journal file (why should it
480** be, if it is not at all meaningful?).
481**
482** By themselves, these optimizations work fine and provide a handy
483** performance boost to bulk delete or insert operations. However, if
484** a page is moved to the free-list and then reused within the same
485** transaction, a problem comes up. If the page is not journalled when
486** it is moved to the free-list and it is also not journalled when it
487** is extracted from the free-list and reused, then the original data
488** may be lost. In the event of a rollback, it may not be possible
489** to restore the database to its original configuration.
490**
491** The solution is the BtShared.pHasContent bitvec. Whenever a page is
492** moved to become a free-list leaf page, the corresponding bit is
493** set in the bitvec. Whenever a leaf page is extracted from the free-list,
494** optimization 2 above is ommitted if the corresponding bit is already
495** set in BtShared.pHasContent. The contents of the bitvec are cleared
496** at the end of every transaction.
497*/
498static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
499 int rc = SQLITE_OK;
500 if( !pBt->pHasContent ){
drh4c301aa2009-07-15 17:25:45 +0000501 int nPage = 100;
502 sqlite3PagerPagecount(pBt->pPager, &nPage);
503 /* If sqlite3PagerPagecount() fails there is no harm because the
504 ** nPage variable is unchanged from its default value of 100 */
505 pBt->pHasContent = sqlite3BitvecCreate((u32)nPage);
506 if( !pBt->pHasContent ){
507 rc = SQLITE_NOMEM;
danielk1977bea2a942009-01-20 17:06:27 +0000508 }
509 }
510 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
511 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
512 }
513 return rc;
514}
515
516/*
517** Query the BtShared.pHasContent vector.
518**
519** This function is called when a free-list leaf page is removed from the
520** free-list for reuse. It returns false if it is safe to retrieve the
521** page from the pager layer with the 'no-content' flag set. True otherwise.
522*/
523static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
524 Bitvec *p = pBt->pHasContent;
525 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
526}
527
528/*
529** Clear (destroy) the BtShared.pHasContent bitvec. This should be
530** invoked at the conclusion of each write-transaction.
531*/
532static void btreeClearHasContent(BtShared *pBt){
533 sqlite3BitvecDestroy(pBt->pHasContent);
534 pBt->pHasContent = 0;
535}
536
537/*
drh980b1a72006-08-16 16:42:48 +0000538** Save the current cursor position in the variables BtCursor.nKey
539** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
drhea8ffdf2009-07-22 00:35:23 +0000540**
541** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
542** prior to calling this routine.
drh980b1a72006-08-16 16:42:48 +0000543*/
544static int saveCursorPosition(BtCursor *pCur){
545 int rc;
546
547 assert( CURSOR_VALID==pCur->eState );
548 assert( 0==pCur->pKey );
drh1fee73e2007-08-29 04:00:57 +0000549 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000550
551 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
drhea8ffdf2009-07-22 00:35:23 +0000552 assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
drh980b1a72006-08-16 16:42:48 +0000553
554 /* If this is an intKey table, then the above call to BtreeKeySize()
555 ** stores the integer key in pCur->nKey. In this case this value is
556 ** all that is required. Otherwise, if pCur is not open on an intKey
557 ** table, then malloc space for and store the pCur->nKey bytes of key
558 ** data.
559 */
drh4c301aa2009-07-15 17:25:45 +0000560 if( 0==pCur->apPage[0]->intKey ){
drhf49661a2008-12-10 16:45:50 +0000561 void *pKey = sqlite3Malloc( (int)pCur->nKey );
drh980b1a72006-08-16 16:42:48 +0000562 if( pKey ){
drhf49661a2008-12-10 16:45:50 +0000563 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
drh980b1a72006-08-16 16:42:48 +0000564 if( rc==SQLITE_OK ){
565 pCur->pKey = pKey;
566 }else{
drh17435752007-08-16 04:30:38 +0000567 sqlite3_free(pKey);
drh980b1a72006-08-16 16:42:48 +0000568 }
569 }else{
570 rc = SQLITE_NOMEM;
571 }
572 }
danielk197771d5d2c2008-09-29 11:49:47 +0000573 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
drh980b1a72006-08-16 16:42:48 +0000574
575 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +0000576 int i;
577 for(i=0; i<=pCur->iPage; i++){
578 releasePage(pCur->apPage[i]);
579 pCur->apPage[i] = 0;
580 }
581 pCur->iPage = -1;
drh980b1a72006-08-16 16:42:48 +0000582 pCur->eState = CURSOR_REQUIRESEEK;
583 }
584
danielk197792d4d7a2007-05-04 12:05:56 +0000585 invalidateOverflowCache(pCur);
drh980b1a72006-08-16 16:42:48 +0000586 return rc;
587}
588
589/*
590** Save the positions of all cursors except pExcept open on the table
591** with root-page iRoot. Usually, this is called just before cursor
592** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
593*/
594static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
595 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000596 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +0000597 assert( pExcept==0 || pExcept->pBt==pBt );
drh980b1a72006-08-16 16:42:48 +0000598 for(p=pBt->pCursor; p; p=p->pNext){
599 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
600 p->eState==CURSOR_VALID ){
601 int rc = saveCursorPosition(p);
602 if( SQLITE_OK!=rc ){
603 return rc;
604 }
605 }
606 }
607 return SQLITE_OK;
608}
609
610/*
drhbf700f32007-03-31 02:36:44 +0000611** Clear the current cursor position.
612*/
danielk1977be51a652008-10-08 17:58:48 +0000613void sqlite3BtreeClearCursor(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000614 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000615 sqlite3_free(pCur->pKey);
drhbf700f32007-03-31 02:36:44 +0000616 pCur->pKey = 0;
617 pCur->eState = CURSOR_INVALID;
618}
619
620/*
danielk19773509a652009-07-06 18:56:13 +0000621** In this version of BtreeMoveto, pKey is a packed index record
622** such as is generated by the OP_MakeRecord opcode. Unpack the
623** record and then call BtreeMovetoUnpacked() to do the work.
624*/
625static int btreeMoveto(
626 BtCursor *pCur, /* Cursor open on the btree to be searched */
627 const void *pKey, /* Packed key if the btree is an index */
628 i64 nKey, /* Integer key for tables. Size of pKey for indices */
629 int bias, /* Bias search to the high end */
630 int *pRes /* Write search results here */
631){
632 int rc; /* Status code */
633 UnpackedRecord *pIdxKey; /* Unpacked index key */
634 char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
635
636 if( pKey ){
637 assert( nKey==(i64)(int)nKey );
638 pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
639 aSpace, sizeof(aSpace));
640 if( pIdxKey==0 ) return SQLITE_NOMEM;
641 }else{
642 pIdxKey = 0;
643 }
644 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
645 if( pKey ){
646 sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
647 }
648 return rc;
649}
650
651/*
drh980b1a72006-08-16 16:42:48 +0000652** Restore the cursor to the position it was in (or as close to as possible)
653** when saveCursorPosition() was called. Note that this call deletes the
654** saved position info stored by saveCursorPosition(), so there can be
drha3460582008-07-11 21:02:53 +0000655** at most one effective restoreCursorPosition() call after each
drh980b1a72006-08-16 16:42:48 +0000656** saveCursorPosition().
drh980b1a72006-08-16 16:42:48 +0000657*/
danielk197730548662009-07-09 05:07:37 +0000658static int btreeRestoreCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +0000659 int rc;
drh1fee73e2007-08-29 04:00:57 +0000660 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +0000661 assert( pCur->eState>=CURSOR_REQUIRESEEK );
662 if( pCur->eState==CURSOR_FAULT ){
drh4c301aa2009-07-15 17:25:45 +0000663 return pCur->skipNext;
drhfb982642007-08-30 01:19:59 +0000664 }
drh980b1a72006-08-16 16:42:48 +0000665 pCur->eState = CURSOR_INVALID;
drh4c301aa2009-07-15 17:25:45 +0000666 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
drh980b1a72006-08-16 16:42:48 +0000667 if( rc==SQLITE_OK ){
drh17435752007-08-16 04:30:38 +0000668 sqlite3_free(pCur->pKey);
drh980b1a72006-08-16 16:42:48 +0000669 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +0000670 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drh980b1a72006-08-16 16:42:48 +0000671 }
672 return rc;
673}
674
drha3460582008-07-11 21:02:53 +0000675#define restoreCursorPosition(p) \
drhfb982642007-08-30 01:19:59 +0000676 (p->eState>=CURSOR_REQUIRESEEK ? \
danielk197730548662009-07-09 05:07:37 +0000677 btreeRestoreCursorPosition(p) : \
drh16a9b832007-05-05 18:39:25 +0000678 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +0000679
drha3460582008-07-11 21:02:53 +0000680/*
681** Determine whether or not a cursor has moved from the position it
drhdfe88ec2008-11-03 20:55:06 +0000682** was last placed at. Cursors can move when the row they are pointing
drha3460582008-07-11 21:02:53 +0000683** at is deleted out from under them.
684**
685** This routine returns an error code if something goes wrong. The
686** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
687*/
688int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
689 int rc;
690
691 rc = restoreCursorPosition(pCur);
692 if( rc ){
693 *pHasMoved = 1;
694 return rc;
695 }
drh4c301aa2009-07-15 17:25:45 +0000696 if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
drha3460582008-07-11 21:02:53 +0000697 *pHasMoved = 1;
698 }else{
699 *pHasMoved = 0;
700 }
701 return SQLITE_OK;
702}
703
danielk1977599fcba2004-11-08 07:13:13 +0000704#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000705/*
drha3152892007-05-05 11:48:52 +0000706** Given a page number of a regular database page, return the page
707** number for the pointer-map page that contains the entry for the
708** input page number.
danielk1977afcdd022004-10-31 16:25:42 +0000709*/
danielk1977266664d2006-02-10 08:24:21 +0000710static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
danielk197789d40042008-11-17 14:20:56 +0000711 int nPagesPerMapPage;
712 Pgno iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +0000713 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000714 nPagesPerMapPage = (pBt->usableSize/5)+1;
715 iPtrMap = (pgno-2)/nPagesPerMapPage;
716 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +0000717 if( ret==PENDING_BYTE_PAGE(pBt) ){
718 ret++;
719 }
720 return ret;
721}
danielk1977a19df672004-11-03 11:37:07 +0000722
danielk1977afcdd022004-10-31 16:25:42 +0000723/*
danielk1977afcdd022004-10-31 16:25:42 +0000724** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000725**
726** This routine updates the pointer map entry for page number 'key'
727** so that it maps to type 'eType' and parent page number 'pgno'.
drh98add2e2009-07-20 17:11:49 +0000728**
729** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
730** a no-op. If an error occurs, the appropriate error code is written
731** into *pRC.
danielk1977afcdd022004-10-31 16:25:42 +0000732*/
drh98add2e2009-07-20 17:11:49 +0000733static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
danielk19773b8a05f2007-03-19 17:44:26 +0000734 DbPage *pDbPage; /* The pointer map page */
735 u8 *pPtrmap; /* The pointer map data */
736 Pgno iPtrmap; /* The pointer map page number */
737 int offset; /* Offset in pointer map page */
drh98add2e2009-07-20 17:11:49 +0000738 int rc; /* Return code from subfunctions */
739
740 if( *pRC ) return;
danielk1977afcdd022004-10-31 16:25:42 +0000741
drh1fee73e2007-08-29 04:00:57 +0000742 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977266664d2006-02-10 08:24:21 +0000743 /* The master-journal page number must never be used as a pointer map page */
744 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
745
danielk1977ac11ee62005-01-15 12:45:51 +0000746 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000747 if( key==0 ){
drh98add2e2009-07-20 17:11:49 +0000748 *pRC = SQLITE_CORRUPT_BKPT;
749 return;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000750 }
danielk1977266664d2006-02-10 08:24:21 +0000751 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000752 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977687566d2004-11-02 12:56:41 +0000753 if( rc!=SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +0000754 *pRC = rc;
755 return;
danielk1977afcdd022004-10-31 16:25:42 +0000756 }
danielk19778c666b12008-07-18 09:34:57 +0000757 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drhacfc72b2009-06-05 18:44:15 +0000758 if( offset<0 ){
drh98add2e2009-07-20 17:11:49 +0000759 *pRC = SQLITE_CORRUPT_BKPT;
drh4925a552009-07-07 11:39:58 +0000760 goto ptrmap_exit;
drhacfc72b2009-06-05 18:44:15 +0000761 }
danielk19773b8a05f2007-03-19 17:44:26 +0000762 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000763
drh615ae552005-01-16 23:21:00 +0000764 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
765 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
drh98add2e2009-07-20 17:11:49 +0000766 *pRC= rc = sqlite3PagerWrite(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000767 if( rc==SQLITE_OK ){
768 pPtrmap[offset] = eType;
769 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000770 }
danielk1977afcdd022004-10-31 16:25:42 +0000771 }
772
drh4925a552009-07-07 11:39:58 +0000773ptrmap_exit:
danielk19773b8a05f2007-03-19 17:44:26 +0000774 sqlite3PagerUnref(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000775}
776
777/*
778** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000779**
780** This routine retrieves the pointer map entry for page 'key', writing
781** the type and parent page number to *pEType and *pPgno respectively.
782** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000783*/
danielk1977aef0bf62005-12-30 16:28:01 +0000784static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +0000785 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000786 int iPtrmap; /* Pointer map page index */
787 u8 *pPtrmap; /* Pointer map page data */
788 int offset; /* Offset of entry in pointer map */
789 int rc;
790
drh1fee73e2007-08-29 04:00:57 +0000791 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000792
danielk1977266664d2006-02-10 08:24:21 +0000793 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000794 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000795 if( rc!=0 ){
796 return rc;
797 }
danielk19773b8a05f2007-03-19 17:44:26 +0000798 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000799
danielk19778c666b12008-07-18 09:34:57 +0000800 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drh43617e92006-03-06 20:55:46 +0000801 assert( pEType!=0 );
802 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +0000803 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000804
danielk19773b8a05f2007-03-19 17:44:26 +0000805 sqlite3PagerUnref(pDbPage);
drh49285702005-09-17 15:20:26 +0000806 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000807 return SQLITE_OK;
808}
809
danielk197785d90ca2008-07-19 14:25:15 +0000810#else /* if defined SQLITE_OMIT_AUTOVACUUM */
drh98add2e2009-07-20 17:11:49 +0000811 #define ptrmapPut(w,x,y,z,rc)
danielk197785d90ca2008-07-19 14:25:15 +0000812 #define ptrmapGet(w,x,y,z) SQLITE_OK
drh98add2e2009-07-20 17:11:49 +0000813 #define ptrmapPutOvflPtr(x, y, rc)
danielk197785d90ca2008-07-19 14:25:15 +0000814#endif
danielk1977afcdd022004-10-31 16:25:42 +0000815
drh0d316a42002-08-11 20:10:47 +0000816/*
drh271efa52004-05-30 19:19:05 +0000817** Given a btree page and a cell index (0 means the first cell on
818** the page, 1 means the second cell, and so forth) return a pointer
819** to the cell content.
820**
821** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000822*/
drh1688c862008-07-18 02:44:17 +0000823#define findCell(P,I) \
824 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
drh43605152004-05-29 21:46:49 +0000825
826/*
drh93a960a2008-07-10 00:32:42 +0000827** This a more complex version of findCell() that works for
drh0a45c272009-07-08 01:49:11 +0000828** pages that do contain overflow cells.
drh43605152004-05-29 21:46:49 +0000829*/
830static u8 *findOverflowCell(MemPage *pPage, int iCell){
831 int i;
drh1fee73e2007-08-29 04:00:57 +0000832 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +0000833 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000834 int k;
835 struct _OvflCell *pOvfl;
836 pOvfl = &pPage->aOvfl[i];
837 k = pOvfl->idx;
838 if( k<=iCell ){
839 if( k==iCell ){
840 return pOvfl->pCell;
drh43605152004-05-29 21:46:49 +0000841 }
842 iCell--;
843 }
844 }
danielk19771cc5ed82007-05-16 17:28:43 +0000845 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000846}
847
848/*
849** Parse a cell content block and fill in the CellInfo structure. There
danielk197730548662009-07-09 05:07:37 +0000850** are two versions of this function. btreeParseCell() takes a
851** cell index as the second argument and btreeParseCellPtr()
drh16a9b832007-05-05 18:39:25 +0000852** takes a pointer to the body of the cell as its second argument.
danielk19771cc5ed82007-05-16 17:28:43 +0000853**
854** Within this file, the parseCell() macro can be called instead of
danielk197730548662009-07-09 05:07:37 +0000855** btreeParseCellPtr(). Using some compilers, this will be faster.
drh43605152004-05-29 21:46:49 +0000856*/
danielk197730548662009-07-09 05:07:37 +0000857static void btreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000858 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000859 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000860 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000861){
drhf49661a2008-12-10 16:45:50 +0000862 u16 n; /* Number bytes in cell content header */
drh271efa52004-05-30 19:19:05 +0000863 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000864
drh1fee73e2007-08-29 04:00:57 +0000865 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000866
drh43605152004-05-29 21:46:49 +0000867 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000868 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000869 n = pPage->childPtrSize;
870 assert( n==4-4*pPage->leaf );
drh504b6982006-01-22 21:52:56 +0000871 if( pPage->intKey ){
drh79df1f42008-07-18 00:57:33 +0000872 if( pPage->hasData ){
873 n += getVarint32(&pCell[n], nPayload);
874 }else{
875 nPayload = 0;
876 }
drh1bd10f82008-12-10 21:19:56 +0000877 n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
drh79df1f42008-07-18 00:57:33 +0000878 pInfo->nData = nPayload;
drh504b6982006-01-22 21:52:56 +0000879 }else{
drh79df1f42008-07-18 00:57:33 +0000880 pInfo->nData = 0;
881 n += getVarint32(&pCell[n], nPayload);
882 pInfo->nKey = nPayload;
drh6f11bef2004-05-13 01:12:56 +0000883 }
drh72365832007-03-06 15:53:44 +0000884 pInfo->nPayload = nPayload;
drh504b6982006-01-22 21:52:56 +0000885 pInfo->nHeader = n;
drh0a45c272009-07-08 01:49:11 +0000886 testcase( nPayload==pPage->maxLocal );
887 testcase( nPayload==pPage->maxLocal+1 );
drh79df1f42008-07-18 00:57:33 +0000888 if( likely(nPayload<=pPage->maxLocal) ){
drh271efa52004-05-30 19:19:05 +0000889 /* This is the (easy) common case where the entire payload fits
890 ** on the local page. No overflow is required.
891 */
892 int nSize; /* Total size of cell content in bytes */
drh79df1f42008-07-18 00:57:33 +0000893 nSize = nPayload + n;
drhf49661a2008-12-10 16:45:50 +0000894 pInfo->nLocal = (u16)nPayload;
drh6f11bef2004-05-13 01:12:56 +0000895 pInfo->iOverflow = 0;
drh79df1f42008-07-18 00:57:33 +0000896 if( (nSize & ~3)==0 ){
drh271efa52004-05-30 19:19:05 +0000897 nSize = 4; /* Minimum cell size is 4 */
drh43605152004-05-29 21:46:49 +0000898 }
drh1bd10f82008-12-10 21:19:56 +0000899 pInfo->nSize = (u16)nSize;
drh6f11bef2004-05-13 01:12:56 +0000900 }else{
drh271efa52004-05-30 19:19:05 +0000901 /* If the payload will not fit completely on the local page, we have
902 ** to decide how much to store locally and how much to spill onto
903 ** overflow pages. The strategy is to minimize the amount of unused
904 ** space on overflow pages while keeping the amount of local storage
905 ** in between minLocal and maxLocal.
906 **
907 ** Warning: changing the way overflow payload is distributed in any
908 ** way will result in an incompatible file format.
909 */
910 int minLocal; /* Minimum amount of payload held locally */
911 int maxLocal; /* Maximum amount of payload held locally */
912 int surplus; /* Overflow payload available for local storage */
913
914 minLocal = pPage->minLocal;
915 maxLocal = pPage->maxLocal;
916 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh0a45c272009-07-08 01:49:11 +0000917 testcase( surplus==maxLocal );
918 testcase( surplus==maxLocal+1 );
drh6f11bef2004-05-13 01:12:56 +0000919 if( surplus <= maxLocal ){
drhf49661a2008-12-10 16:45:50 +0000920 pInfo->nLocal = (u16)surplus;
drh6f11bef2004-05-13 01:12:56 +0000921 }else{
drhf49661a2008-12-10 16:45:50 +0000922 pInfo->nLocal = (u16)minLocal;
drh6f11bef2004-05-13 01:12:56 +0000923 }
drhf49661a2008-12-10 16:45:50 +0000924 pInfo->iOverflow = (u16)(pInfo->nLocal + n);
drh6f11bef2004-05-13 01:12:56 +0000925 pInfo->nSize = pInfo->iOverflow + 4;
926 }
drh3aac2dd2004-04-26 14:10:20 +0000927}
danielk19771cc5ed82007-05-16 17:28:43 +0000928#define parseCell(pPage, iCell, pInfo) \
danielk197730548662009-07-09 05:07:37 +0000929 btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
930static void btreeParseCell(
drh43605152004-05-29 21:46:49 +0000931 MemPage *pPage, /* Page containing the cell */
932 int iCell, /* The cell index. First cell is 0 */
933 CellInfo *pInfo /* Fill in this structure */
934){
danielk19771cc5ed82007-05-16 17:28:43 +0000935 parseCell(pPage, iCell, pInfo);
drh43605152004-05-29 21:46:49 +0000936}
drh3aac2dd2004-04-26 14:10:20 +0000937
938/*
drh43605152004-05-29 21:46:49 +0000939** Compute the total number of bytes that a Cell needs in the cell
940** data area of the btree-page. The return number includes the cell
941** data header and the local payload, but not any overflow page or
942** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +0000943*/
danielk1977ae5558b2009-04-29 11:31:47 +0000944static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
945 u8 *pIter = &pCell[pPage->childPtrSize];
946 u32 nSize;
947
948#ifdef SQLITE_DEBUG
949 /* The value returned by this function should always be the same as
950 ** the (CellInfo.nSize) value found by doing a full parse of the
951 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
952 ** this function verifies that this invariant is not violated. */
953 CellInfo debuginfo;
danielk197730548662009-07-09 05:07:37 +0000954 btreeParseCellPtr(pPage, pCell, &debuginfo);
danielk1977ae5558b2009-04-29 11:31:47 +0000955#endif
956
957 if( pPage->intKey ){
958 u8 *pEnd;
959 if( pPage->hasData ){
960 pIter += getVarint32(pIter, nSize);
961 }else{
962 nSize = 0;
963 }
964
965 /* pIter now points at the 64-bit integer key value, a variable length
966 ** integer. The following block moves pIter to point at the first byte
967 ** past the end of the key value. */
968 pEnd = &pIter[9];
969 while( (*pIter++)&0x80 && pIter<pEnd );
970 }else{
971 pIter += getVarint32(pIter, nSize);
972 }
973
drh0a45c272009-07-08 01:49:11 +0000974 testcase( nSize==pPage->maxLocal );
975 testcase( nSize==pPage->maxLocal+1 );
danielk1977ae5558b2009-04-29 11:31:47 +0000976 if( nSize>pPage->maxLocal ){
977 int minLocal = pPage->minLocal;
978 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
drh0a45c272009-07-08 01:49:11 +0000979 testcase( nSize==pPage->maxLocal );
980 testcase( nSize==pPage->maxLocal+1 );
danielk1977ae5558b2009-04-29 11:31:47 +0000981 if( nSize>pPage->maxLocal ){
982 nSize = minLocal;
983 }
984 nSize += 4;
985 }
shane75ac1de2009-06-09 18:58:52 +0000986 nSize += (u32)(pIter - pCell);
danielk1977ae5558b2009-04-29 11:31:47 +0000987
988 /* The minimum size of any cell is 4 bytes. */
989 if( nSize<4 ){
990 nSize = 4;
991 }
992
993 assert( nSize==debuginfo.nSize );
shane60a4b532009-05-06 18:57:09 +0000994 return (u16)nSize;
danielk1977ae5558b2009-04-29 11:31:47 +0000995}
danielk1977bc6ada42004-06-30 08:20:16 +0000996#ifndef NDEBUG
drha9121e42008-02-19 14:59:35 +0000997static u16 cellSize(MemPage *pPage, int iCell){
danielk1977ae5558b2009-04-29 11:31:47 +0000998 return cellSizePtr(pPage, findCell(pPage, iCell));
drh43605152004-05-29 21:46:49 +0000999}
danielk1977bc6ada42004-06-30 08:20:16 +00001000#endif
drh3b7511c2001-05-26 13:15:44 +00001001
danielk197779a40da2005-01-16 08:00:01 +00001002#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +00001003/*
danielk197726836652005-01-17 01:33:13 +00001004** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +00001005** to an overflow page, insert an entry into the pointer-map
1006** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +00001007*/
drh98add2e2009-07-20 17:11:49 +00001008static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
drhfa67c3c2008-07-11 02:21:40 +00001009 CellInfo info;
drh98add2e2009-07-20 17:11:49 +00001010 if( *pRC ) return;
drhfa67c3c2008-07-11 02:21:40 +00001011 assert( pCell!=0 );
danielk197730548662009-07-09 05:07:37 +00001012 btreeParseCellPtr(pPage, pCell, &info);
drhfa67c3c2008-07-11 02:21:40 +00001013 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk19774dbaa892009-06-16 16:50:22 +00001014 if( info.iOverflow ){
drhfa67c3c2008-07-11 02:21:40 +00001015 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
drh98add2e2009-07-20 17:11:49 +00001016 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
danielk1977ac11ee62005-01-15 12:45:51 +00001017 }
danielk1977ac11ee62005-01-15 12:45:51 +00001018}
danielk197779a40da2005-01-16 08:00:01 +00001019#endif
1020
danielk1977ac11ee62005-01-15 12:45:51 +00001021
drhda200cc2004-05-09 11:51:38 +00001022/*
drh72f82862001-05-24 21:06:34 +00001023** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +00001024** end of the page and all free space is collected into one
1025** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +00001026** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +00001027*/
shane0af3f892008-11-12 04:55:34 +00001028static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +00001029 int i; /* Loop counter */
1030 int pc; /* Address of a i-th cell */
drh43605152004-05-29 21:46:49 +00001031 int hdr; /* Offset to the page header */
1032 int size; /* Size of a cell */
1033 int usableSize; /* Number of usable bytes on a page */
1034 int cellOffset; /* Offset to the cell pointer array */
drh281b21d2008-08-22 12:57:08 +00001035 int cbrk; /* Offset to the cell content area */
drh43605152004-05-29 21:46:49 +00001036 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +00001037 unsigned char *data; /* The page data */
1038 unsigned char *temp; /* Temp area for cell content */
drh17146622009-07-07 17:38:38 +00001039 int iCellFirst; /* First allowable cell index */
1040 int iCellLast; /* Last possible cell index */
1041
drh2af926b2001-05-15 00:39:25 +00001042
danielk19773b8a05f2007-03-19 17:44:26 +00001043 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001044 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +00001045 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +00001046 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00001047 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh26b79942007-11-28 16:19:56 +00001048 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
drh43605152004-05-29 21:46:49 +00001049 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +00001050 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00001051 cellOffset = pPage->cellOffset;
1052 nCell = pPage->nCell;
1053 assert( nCell==get2byte(&data[hdr+3]) );
1054 usableSize = pPage->pBt->usableSize;
drh281b21d2008-08-22 12:57:08 +00001055 cbrk = get2byte(&data[hdr+5]);
1056 memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
1057 cbrk = usableSize;
drh17146622009-07-07 17:38:38 +00001058 iCellFirst = cellOffset + 2*nCell;
1059 iCellLast = usableSize - 4;
drh43605152004-05-29 21:46:49 +00001060 for(i=0; i<nCell; i++){
1061 u8 *pAddr; /* The i-th cell pointer */
1062 pAddr = &data[cellOffset + i*2];
1063 pc = get2byte(pAddr);
drh0a45c272009-07-08 01:49:11 +00001064 testcase( pc==iCellFirst );
1065 testcase( pc==iCellLast );
drh17146622009-07-07 17:38:38 +00001066#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
danielk197730548662009-07-09 05:07:37 +00001067 /* These conditions have already been verified in btreeInitPage()
drh17146622009-07-07 17:38:38 +00001068 ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
1069 */
1070 if( pc<iCellFirst || pc>iCellLast ){
shane0af3f892008-11-12 04:55:34 +00001071 return SQLITE_CORRUPT_BKPT;
1072 }
drh17146622009-07-07 17:38:38 +00001073#endif
1074 assert( pc>=iCellFirst && pc<=iCellLast );
drh43605152004-05-29 21:46:49 +00001075 size = cellSizePtr(pPage, &temp[pc]);
drh281b21d2008-08-22 12:57:08 +00001076 cbrk -= size;
drh17146622009-07-07 17:38:38 +00001077#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
1078 if( cbrk<iCellFirst ){
shane0af3f892008-11-12 04:55:34 +00001079 return SQLITE_CORRUPT_BKPT;
1080 }
drh17146622009-07-07 17:38:38 +00001081#else
1082 if( cbrk<iCellFirst || pc+size>usableSize ){
1083 return SQLITE_CORRUPT_BKPT;
1084 }
1085#endif
drh7157e1d2009-07-09 13:25:32 +00001086 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
drh0a45c272009-07-08 01:49:11 +00001087 testcase( cbrk+size==usableSize );
drh0a45c272009-07-08 01:49:11 +00001088 testcase( pc+size==usableSize );
drh281b21d2008-08-22 12:57:08 +00001089 memcpy(&data[cbrk], &temp[pc], size);
1090 put2byte(pAddr, cbrk);
drh2af926b2001-05-15 00:39:25 +00001091 }
drh17146622009-07-07 17:38:38 +00001092 assert( cbrk>=iCellFirst );
drh281b21d2008-08-22 12:57:08 +00001093 put2byte(&data[hdr+5], cbrk);
drh43605152004-05-29 21:46:49 +00001094 data[hdr+1] = 0;
1095 data[hdr+2] = 0;
1096 data[hdr+7] = 0;
drh17146622009-07-07 17:38:38 +00001097 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
drhc5053fb2008-11-27 02:22:10 +00001098 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh17146622009-07-07 17:38:38 +00001099 if( cbrk-iCellFirst!=pPage->nFree ){
danielk1977360e6342008-11-12 08:49:51 +00001100 return SQLITE_CORRUPT_BKPT;
1101 }
shane0af3f892008-11-12 04:55:34 +00001102 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +00001103}
1104
drha059ad02001-04-17 20:09:11 +00001105/*
danielk19776011a752009-04-01 16:25:32 +00001106** Allocate nByte bytes of space from within the B-Tree page passed
drh0a45c272009-07-08 01:49:11 +00001107** as the first argument. Write into *pIdx the index into pPage->aData[]
1108** of the first byte of allocated space. Return either SQLITE_OK or
1109** an error code (usually SQLITE_CORRUPT).
drhbd03cae2001-06-02 02:40:57 +00001110**
drh0a45c272009-07-08 01:49:11 +00001111** The caller guarantees that there is sufficient space to make the
1112** allocation. This routine might need to defragment in order to bring
1113** all the space together, however. This routine will avoid using
1114** the first two bytes past the cell pointer area since presumably this
1115** allocation is being made in order to insert a new cell, so we will
1116** also end up needing a new cell pointer.
drh7e3b0a02001-04-28 16:52:40 +00001117*/
drh0a45c272009-07-08 01:49:11 +00001118static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
danielk19776011a752009-04-01 16:25:32 +00001119 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1120 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
1121 int nFrag; /* Number of fragmented bytes on pPage */
drh0a45c272009-07-08 01:49:11 +00001122 int top; /* First byte of cell content area */
1123 int gap; /* First byte of gap between cell pointers and cell content */
1124 int rc; /* Integer return code */
drh43605152004-05-29 21:46:49 +00001125
danielk19773b8a05f2007-03-19 17:44:26 +00001126 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001127 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +00001128 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa67c3c2008-07-11 02:21:40 +00001129 assert( nByte>=0 ); /* Minimum cell size is 4 */
1130 assert( pPage->nFree>=nByte );
1131 assert( pPage->nOverflow==0 );
drhc314dc72009-07-21 11:52:34 +00001132 assert( nByte<pPage->pBt->usableSize-8 );
drh43605152004-05-29 21:46:49 +00001133
1134 nFrag = data[hdr+7];
drh0a45c272009-07-08 01:49:11 +00001135 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1136 gap = pPage->cellOffset + 2*pPage->nCell;
1137 top = get2byte(&data[hdr+5]);
drh7157e1d2009-07-09 13:25:32 +00001138 if( gap>top ) return SQLITE_CORRUPT_BKPT;
drh0a45c272009-07-08 01:49:11 +00001139 testcase( gap+2==top );
1140 testcase( gap+1==top );
1141 testcase( gap==top );
1142
danielk19776011a752009-04-01 16:25:32 +00001143 if( nFrag>=60 ){
drh0a45c272009-07-08 01:49:11 +00001144 /* Always defragment highly fragmented pages */
1145 rc = defragmentPage(pPage);
1146 if( rc ) return rc;
1147 top = get2byte(&data[hdr+5]);
1148 }else if( gap+2<=top ){
danielk19776011a752009-04-01 16:25:32 +00001149 /* Search the freelist looking for a free slot big enough to satisfy
1150 ** the request. The allocation is made from the first free slot in
1151 ** the list that is large enough to accomadate it.
1152 */
1153 int pc, addr;
1154 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
1155 int size = get2byte(&data[pc+2]); /* Size of free slot */
drh43605152004-05-29 21:46:49 +00001156 if( size>=nByte ){
drhf49661a2008-12-10 16:45:50 +00001157 int x = size - nByte;
drh0a45c272009-07-08 01:49:11 +00001158 testcase( x==4 );
1159 testcase( x==3 );
danielk19776011a752009-04-01 16:25:32 +00001160 if( x<4 ){
danielk1977fad91942009-04-29 17:49:59 +00001161 /* Remove the slot from the free-list. Update the number of
1162 ** fragmented bytes within the page. */
drh43605152004-05-29 21:46:49 +00001163 memcpy(&data[addr], &data[pc], 2);
drhf49661a2008-12-10 16:45:50 +00001164 data[hdr+7] = (u8)(nFrag + x);
drh43605152004-05-29 21:46:49 +00001165 }else{
danielk1977fad91942009-04-29 17:49:59 +00001166 /* The slot remains on the free-list. Reduce its size to account
1167 ** for the portion used by the new allocation. */
drhf49661a2008-12-10 16:45:50 +00001168 put2byte(&data[pc+2], x);
drh43605152004-05-29 21:46:49 +00001169 }
drh0a45c272009-07-08 01:49:11 +00001170 *pIdx = pc + x;
1171 return SQLITE_OK;
drh43605152004-05-29 21:46:49 +00001172 }
drh9e572e62004-04-23 23:43:10 +00001173 }
1174 }
drh43605152004-05-29 21:46:49 +00001175
drh0a45c272009-07-08 01:49:11 +00001176 /* Check to make sure there is enough space in the gap to satisfy
1177 ** the allocation. If not, defragment.
1178 */
1179 testcase( gap+2+nByte==top );
1180 if( gap+2+nByte>top ){
1181 rc = defragmentPage(pPage);
1182 if( rc ) return rc;
1183 top = get2byte(&data[hdr+5]);
1184 assert( gap+nByte<=top );
1185 }
1186
1187
drh43605152004-05-29 21:46:49 +00001188 /* Allocate memory from the gap in between the cell pointer array
drhc314dc72009-07-21 11:52:34 +00001189 ** and the cell content area. The btreeInitPage() call has already
1190 ** validated the freelist. Given that the freelist is valid, there
1191 ** is no way that the allocation can extend off the end of the page.
1192 ** The assert() below verifies the previous sentence.
drh43605152004-05-29 21:46:49 +00001193 */
drh0a45c272009-07-08 01:49:11 +00001194 top -= nByte;
drh43605152004-05-29 21:46:49 +00001195 put2byte(&data[hdr+5], top);
drhc314dc72009-07-21 11:52:34 +00001196 assert( top+nByte <= pPage->pBt->usableSize );
drh0a45c272009-07-08 01:49:11 +00001197 *pIdx = top;
1198 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001199}
1200
1201/*
drh9e572e62004-04-23 23:43:10 +00001202** Return a section of the pPage->aData to the freelist.
1203** The first byte of the new free block is pPage->aDisk[start]
1204** and the size of the block is "size" bytes.
drh306dc212001-05-21 13:45:10 +00001205**
1206** Most of the effort here is involved in coalesing adjacent
1207** free blocks into a single big free block.
drh7e3b0a02001-04-28 16:52:40 +00001208*/
shanedcc50b72008-11-13 18:29:50 +00001209static int freeSpace(MemPage *pPage, int start, int size){
drh43605152004-05-29 21:46:49 +00001210 int addr, pbegin, hdr;
drh0a45c272009-07-08 01:49:11 +00001211 int iLast; /* Largest possible freeblock offset */
drh9e572e62004-04-23 23:43:10 +00001212 unsigned char *data = pPage->aData;
drh2af926b2001-05-15 00:39:25 +00001213
drh9e572e62004-04-23 23:43:10 +00001214 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001215 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drhc046e3e2009-07-15 11:26:44 +00001216 assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
danielk1977bc6ada42004-06-30 08:20:16 +00001217 assert( (start + size)<=pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +00001218 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh34004ce2008-07-11 16:15:17 +00001219 assert( size>=0 ); /* Minimum cell size is 4 */
drh9e572e62004-04-23 23:43:10 +00001220
drhfcce93f2006-02-22 03:08:32 +00001221#ifdef SQLITE_SECURE_DELETE
1222 /* Overwrite deleted information with zeros when the SECURE_DELETE
1223 ** option is enabled at compile-time */
1224 memset(&data[start], 0, size);
1225#endif
1226
drh0a45c272009-07-08 01:49:11 +00001227 /* Add the space back into the linked list of freeblocks. Note that
danielk197730548662009-07-09 05:07:37 +00001228 ** even though the freeblock list was checked by btreeInitPage(),
1229 ** btreeInitPage() did not detect overlapping cells or
drhb908d762009-07-08 16:54:40 +00001230 ** freeblocks that overlapped cells. Nor does it detect when the
1231 ** cell content area exceeds the value in the page header. If these
1232 ** situations arise, then subsequent insert operations might corrupt
1233 ** the freelist. So we do need to check for corruption while scanning
1234 ** the freelist.
drh0a45c272009-07-08 01:49:11 +00001235 */
drh43605152004-05-29 21:46:49 +00001236 hdr = pPage->hdrOffset;
1237 addr = hdr + 1;
drh0a45c272009-07-08 01:49:11 +00001238 iLast = pPage->pBt->usableSize - 4;
drh35a25da2009-07-08 15:14:50 +00001239 assert( start<=iLast );
drh3aac2dd2004-04-26 14:10:20 +00001240 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
drh35a25da2009-07-08 15:14:50 +00001241 if( pbegin<addr+4 ){
shanedcc50b72008-11-13 18:29:50 +00001242 return SQLITE_CORRUPT_BKPT;
1243 }
drh3aac2dd2004-04-26 14:10:20 +00001244 addr = pbegin;
drh2af926b2001-05-15 00:39:25 +00001245 }
drh0a45c272009-07-08 01:49:11 +00001246 if( pbegin>iLast ){
shanedcc50b72008-11-13 18:29:50 +00001247 return SQLITE_CORRUPT_BKPT;
1248 }
drh3aac2dd2004-04-26 14:10:20 +00001249 assert( pbegin>addr || pbegin==0 );
drha34b6762004-05-07 13:30:42 +00001250 put2byte(&data[addr], start);
1251 put2byte(&data[start], pbegin);
1252 put2byte(&data[start+2], size);
shane36840fd2009-06-26 16:32:13 +00001253 pPage->nFree = pPage->nFree + (u16)size;
drh9e572e62004-04-23 23:43:10 +00001254
1255 /* Coalesce adjacent free blocks */
drh0a45c272009-07-08 01:49:11 +00001256 addr = hdr + 1;
drh3aac2dd2004-04-26 14:10:20 +00001257 while( (pbegin = get2byte(&data[addr]))>0 ){
drhf49661a2008-12-10 16:45:50 +00001258 int pnext, psize, x;
drh3aac2dd2004-04-26 14:10:20 +00001259 assert( pbegin>addr );
drh43605152004-05-29 21:46:49 +00001260 assert( pbegin<=pPage->pBt->usableSize-4 );
drh9e572e62004-04-23 23:43:10 +00001261 pnext = get2byte(&data[pbegin]);
1262 psize = get2byte(&data[pbegin+2]);
1263 if( pbegin + psize + 3 >= pnext && pnext>0 ){
1264 int frag = pnext - (pbegin+psize);
drh0a45c272009-07-08 01:49:11 +00001265 if( (frag<0) || (frag>(int)data[hdr+7]) ){
shanedcc50b72008-11-13 18:29:50 +00001266 return SQLITE_CORRUPT_BKPT;
1267 }
drh0a45c272009-07-08 01:49:11 +00001268 data[hdr+7] -= (u8)frag;
drhf49661a2008-12-10 16:45:50 +00001269 x = get2byte(&data[pnext]);
1270 put2byte(&data[pbegin], x);
1271 x = pnext + get2byte(&data[pnext+2]) - pbegin;
1272 put2byte(&data[pbegin+2], x);
drh9e572e62004-04-23 23:43:10 +00001273 }else{
drh3aac2dd2004-04-26 14:10:20 +00001274 addr = pbegin;
drh9e572e62004-04-23 23:43:10 +00001275 }
1276 }
drh7e3b0a02001-04-28 16:52:40 +00001277
drh43605152004-05-29 21:46:49 +00001278 /* If the cell content area begins with a freeblock, remove it. */
1279 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
1280 int top;
1281 pbegin = get2byte(&data[hdr+1]);
1282 memcpy(&data[hdr+1], &data[pbegin], 2);
drhf49661a2008-12-10 16:45:50 +00001283 top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
1284 put2byte(&data[hdr+5], top);
drh4b70f112004-05-02 21:12:19 +00001285 }
drhc5053fb2008-11-27 02:22:10 +00001286 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
shanedcc50b72008-11-13 18:29:50 +00001287 return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00001288}
1289
1290/*
drh271efa52004-05-30 19:19:05 +00001291** Decode the flags byte (the first byte of the header) for a page
1292** and initialize fields of the MemPage structure accordingly.
drh44845222008-07-17 18:39:57 +00001293**
1294** Only the following combinations are supported. Anything different
1295** indicates a corrupt database files:
1296**
1297** PTF_ZERODATA
1298** PTF_ZERODATA | PTF_LEAF
1299** PTF_LEAFDATA | PTF_INTKEY
1300** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
drh271efa52004-05-30 19:19:05 +00001301*/
drh44845222008-07-17 18:39:57 +00001302static int decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +00001303 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +00001304
1305 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +00001306 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00001307 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
drh44845222008-07-17 18:39:57 +00001308 flagByte &= ~PTF_LEAF;
1309 pPage->childPtrSize = 4-4*pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001310 pBt = pPage->pBt;
drh44845222008-07-17 18:39:57 +00001311 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
1312 pPage->intKey = 1;
1313 pPage->hasData = pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001314 pPage->maxLocal = pBt->maxLeaf;
1315 pPage->minLocal = pBt->minLeaf;
drh44845222008-07-17 18:39:57 +00001316 }else if( flagByte==PTF_ZERODATA ){
1317 pPage->intKey = 0;
1318 pPage->hasData = 0;
drh271efa52004-05-30 19:19:05 +00001319 pPage->maxLocal = pBt->maxLocal;
1320 pPage->minLocal = pBt->minLocal;
drh44845222008-07-17 18:39:57 +00001321 }else{
1322 return SQLITE_CORRUPT_BKPT;
drh271efa52004-05-30 19:19:05 +00001323 }
drh44845222008-07-17 18:39:57 +00001324 return SQLITE_OK;
drh271efa52004-05-30 19:19:05 +00001325}
1326
1327/*
drh7e3b0a02001-04-28 16:52:40 +00001328** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +00001329**
1330** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +00001331** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +00001332** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1333** guarantee that the page is well-formed. It only shows that
1334** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001335*/
danielk197730548662009-07-09 05:07:37 +00001336static int btreeInitPage(MemPage *pPage){
drh2af926b2001-05-15 00:39:25 +00001337
danielk197771d5d2c2008-09-29 11:49:47 +00001338 assert( pPage->pBt!=0 );
1339 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001340 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +00001341 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1342 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00001343
1344 if( !pPage->isInit ){
drhf49661a2008-12-10 16:45:50 +00001345 u16 pc; /* Address of a freeblock within pPage->aData[] */
1346 u8 hdr; /* Offset to beginning of page header */
danielk197771d5d2c2008-09-29 11:49:47 +00001347 u8 *data; /* Equal to pPage->aData */
1348 BtShared *pBt; /* The main btree structure */
drhf49661a2008-12-10 16:45:50 +00001349 u16 usableSize; /* Amount of usable space on each page */
1350 u16 cellOffset; /* Offset from start of page to first cell pointer */
1351 u16 nFree; /* Number of unused bytes on the page */
1352 u16 top; /* First byte of the cell content area */
drh0a45c272009-07-08 01:49:11 +00001353 int iCellFirst; /* First allowable cell or freeblock offset */
1354 int iCellLast; /* Last possible cell or freeblock offset */
danielk197771d5d2c2008-09-29 11:49:47 +00001355
1356 pBt = pPage->pBt;
1357
danielk1977eaa06f62008-09-18 17:34:44 +00001358 hdr = pPage->hdrOffset;
1359 data = pPage->aData;
1360 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
1361 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
1362 pPage->maskPage = pBt->pageSize - 1;
1363 pPage->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00001364 usableSize = pBt->usableSize;
1365 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
1366 top = get2byte(&data[hdr+5]);
1367 pPage->nCell = get2byte(&data[hdr+3]);
1368 if( pPage->nCell>MX_CELL(pBt) ){
1369 /* To many cells for a single page. The page must be corrupt */
1370 return SQLITE_CORRUPT_BKPT;
1371 }
drhb908d762009-07-08 16:54:40 +00001372 testcase( pPage->nCell==MX_CELL(pBt) );
drh69e931e2009-06-03 21:04:35 +00001373
1374 /* A malformed database page might cause use to read past the end
1375 ** of page when parsing a cell.
1376 **
1377 ** The following block of code checks early to see if a cell extends
1378 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
1379 ** returned if it does.
1380 */
drh0a45c272009-07-08 01:49:11 +00001381 iCellFirst = cellOffset + 2*pPage->nCell;
1382 iCellLast = usableSize - 4;
drh3b2a3fa2009-06-09 13:42:24 +00001383#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
drh69e931e2009-06-03 21:04:35 +00001384 {
drh69e931e2009-06-03 21:04:35 +00001385 int i; /* Index into the cell pointer array */
1386 int sz; /* Size of a cell */
1387
drh69e931e2009-06-03 21:04:35 +00001388 if( !pPage->leaf ) iCellLast--;
1389 for(i=0; i<pPage->nCell; i++){
1390 pc = get2byte(&data[cellOffset+i*2]);
drh0a45c272009-07-08 01:49:11 +00001391 testcase( pc==iCellFirst );
1392 testcase( pc==iCellLast );
drh69e931e2009-06-03 21:04:35 +00001393 if( pc<iCellFirst || pc>iCellLast ){
1394 return SQLITE_CORRUPT_BKPT;
1395 }
1396 sz = cellSizePtr(pPage, &data[pc]);
drh0a45c272009-07-08 01:49:11 +00001397 testcase( pc+sz==usableSize );
drh69e931e2009-06-03 21:04:35 +00001398 if( pc+sz>usableSize ){
1399 return SQLITE_CORRUPT_BKPT;
1400 }
1401 }
drh0a45c272009-07-08 01:49:11 +00001402 if( !pPage->leaf ) iCellLast++;
drh69e931e2009-06-03 21:04:35 +00001403 }
1404#endif
1405
danielk1977eaa06f62008-09-18 17:34:44 +00001406 /* Compute the total free space on the page */
1407 pc = get2byte(&data[hdr+1]);
danielk197793c829c2009-06-03 17:26:17 +00001408 nFree = data[hdr+7] + top;
danielk1977eaa06f62008-09-18 17:34:44 +00001409 while( pc>0 ){
drh1bd10f82008-12-10 21:19:56 +00001410 u16 next, size;
drh0a45c272009-07-08 01:49:11 +00001411 if( pc<iCellFirst || pc>iCellLast ){
danielk1977eaa06f62008-09-18 17:34:44 +00001412 /* Free block is off the page */
1413 return SQLITE_CORRUPT_BKPT;
1414 }
1415 next = get2byte(&data[pc]);
1416 size = get2byte(&data[pc+2]);
1417 if( next>0 && next<=pc+size+3 ){
drh0a45c272009-07-08 01:49:11 +00001418 /* Free blocks must be in ascending order */
danielk1977eaa06f62008-09-18 17:34:44 +00001419 return SQLITE_CORRUPT_BKPT;
1420 }
shane85095702009-06-15 16:27:08 +00001421 nFree = nFree + size;
danielk1977eaa06f62008-09-18 17:34:44 +00001422 pc = next;
1423 }
danielk197793c829c2009-06-03 17:26:17 +00001424
1425 /* At this point, nFree contains the sum of the offset to the start
1426 ** of the cell-content area plus the number of free bytes within
1427 ** the cell-content area. If this is greater than the usable-size
1428 ** of the page, then the page must be corrupted. This check also
1429 ** serves to verify that the offset to the start of the cell-content
1430 ** area, according to the page header, lies within the page.
1431 */
1432 if( nFree>usableSize ){
drh49285702005-09-17 15:20:26 +00001433 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001434 }
drh0a45c272009-07-08 01:49:11 +00001435 pPage->nFree = nFree - iCellFirst;
danielk197771d5d2c2008-09-29 11:49:47 +00001436 pPage->isInit = 1;
1437 }
drh9e572e62004-04-23 23:43:10 +00001438 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001439}
1440
1441/*
drh8b2f49b2001-06-08 00:21:52 +00001442** Set up a raw page so that it looks like a database page holding
1443** no entries.
drhbd03cae2001-06-02 02:40:57 +00001444*/
drh9e572e62004-04-23 23:43:10 +00001445static void zeroPage(MemPage *pPage, int flags){
1446 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001447 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00001448 u8 hdr = pPage->hdrOffset;
1449 u16 first;
drh9e572e62004-04-23 23:43:10 +00001450
danielk19773b8a05f2007-03-19 17:44:26 +00001451 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drhbf4bca52007-09-06 22:19:14 +00001452 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1453 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +00001454 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00001455 assert( sqlite3_mutex_held(pBt->mutex) );
drh1af4a6e2008-07-18 03:32:51 +00001456 /*memset(&data[hdr], 0, pBt->usableSize - hdr);*/
drh1bd10f82008-12-10 21:19:56 +00001457 data[hdr] = (char)flags;
1458 first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
drh43605152004-05-29 21:46:49 +00001459 memset(&data[hdr+1], 0, 4);
1460 data[hdr+7] = 0;
1461 put2byte(&data[hdr+5], pBt->usableSize);
drhb6f41482004-05-14 01:58:11 +00001462 pPage->nFree = pBt->usableSize - first;
drh271efa52004-05-30 19:19:05 +00001463 decodeFlags(pPage, flags);
drh9e572e62004-04-23 23:43:10 +00001464 pPage->hdrOffset = hdr;
drh43605152004-05-29 21:46:49 +00001465 pPage->cellOffset = first;
1466 pPage->nOverflow = 0;
drh1688c862008-07-18 02:44:17 +00001467 assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
1468 pPage->maskPage = pBt->pageSize - 1;
drh43605152004-05-29 21:46:49 +00001469 pPage->nCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001470 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00001471}
1472
drh897a8202008-09-18 01:08:15 +00001473
1474/*
1475** Convert a DbPage obtained from the pager into a MemPage used by
1476** the btree layer.
1477*/
1478static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
1479 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
1480 pPage->aData = sqlite3PagerGetData(pDbPage);
1481 pPage->pDbPage = pDbPage;
1482 pPage->pBt = pBt;
1483 pPage->pgno = pgno;
1484 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
1485 return pPage;
1486}
1487
drhbd03cae2001-06-02 02:40:57 +00001488/*
drh3aac2dd2004-04-26 14:10:20 +00001489** Get a page from the pager. Initialize the MemPage.pBt and
1490** MemPage.aData elements if needed.
drh538f5702007-04-13 02:14:30 +00001491**
1492** If the noContent flag is set, it means that we do not care about
1493** the content of the page at this time. So do not go to the disk
1494** to fetch the content. Just fill in the content with zeros for now.
1495** If in the future we call sqlite3PagerWrite() on this page, that
1496** means we have started to be concerned about content and the disk
1497** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00001498*/
danielk197730548662009-07-09 05:07:37 +00001499static int btreeGetPage(
drh16a9b832007-05-05 18:39:25 +00001500 BtShared *pBt, /* The btree */
1501 Pgno pgno, /* Number of the page to fetch */
1502 MemPage **ppPage, /* Return the page in this parameter */
1503 int noContent /* Do not load page content if true */
1504){
drh3aac2dd2004-04-26 14:10:20 +00001505 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001506 DbPage *pDbPage;
1507
drh1fee73e2007-08-29 04:00:57 +00001508 assert( sqlite3_mutex_held(pBt->mutex) );
drh538f5702007-04-13 02:14:30 +00001509 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
drh3aac2dd2004-04-26 14:10:20 +00001510 if( rc ) return rc;
drh897a8202008-09-18 01:08:15 +00001511 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
drh3aac2dd2004-04-26 14:10:20 +00001512 return SQLITE_OK;
1513}
1514
1515/*
danielk1977bea2a942009-01-20 17:06:27 +00001516** Retrieve a page from the pager cache. If the requested page is not
1517** already in the pager cache return NULL. Initialize the MemPage.pBt and
1518** MemPage.aData elements if needed.
1519*/
1520static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
1521 DbPage *pDbPage;
1522 assert( sqlite3_mutex_held(pBt->mutex) );
1523 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
1524 if( pDbPage ){
1525 return btreePageFromDbPage(pDbPage, pgno, pBt);
1526 }
1527 return 0;
1528}
1529
1530/*
danielk197789d40042008-11-17 14:20:56 +00001531** Return the size of the database file in pages. If there is any kind of
1532** error, return ((unsigned int)-1).
danielk197767fd7a92008-09-10 17:53:35 +00001533*/
danielk197789d40042008-11-17 14:20:56 +00001534static Pgno pagerPagecount(BtShared *pBt){
1535 int nPage = -1;
danielk197767fd7a92008-09-10 17:53:35 +00001536 int rc;
danielk197789d40042008-11-17 14:20:56 +00001537 assert( pBt->pPage1 );
1538 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1539 assert( rc==SQLITE_OK || nPage==-1 );
1540 return (Pgno)nPage;
danielk197767fd7a92008-09-10 17:53:35 +00001541}
1542
1543/*
danielk197789bc4bc2009-07-21 19:25:24 +00001544** Get a page from the pager and initialize it. This routine is just a
1545** convenience wrapper around separate calls to btreeGetPage() and
1546** btreeInitPage().
1547**
1548** If an error occurs, then the value *ppPage is set to is undefined. It
1549** may remain unchanged, or it may be set to an invalid value.
drhde647132004-05-07 17:57:49 +00001550*/
1551static int getAndInitPage(
danielk1977aef0bf62005-12-30 16:28:01 +00001552 BtShared *pBt, /* The database file */
drhde647132004-05-07 17:57:49 +00001553 Pgno pgno, /* Number of the page to get */
danielk197771d5d2c2008-09-29 11:49:47 +00001554 MemPage **ppPage /* Write the page pointer here */
drhde647132004-05-07 17:57:49 +00001555){
1556 int rc;
danielk197789bc4bc2009-07-21 19:25:24 +00001557 TESTONLY( Pgno iLastPg = pagerPagecount(pBt); )
drh1fee73e2007-08-29 04:00:57 +00001558 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197789bc4bc2009-07-21 19:25:24 +00001559
1560 rc = btreeGetPage(pBt, pgno, ppPage, 0);
1561 if( rc==SQLITE_OK ){
1562 rc = btreeInitPage(*ppPage);
1563 if( rc!=SQLITE_OK ){
1564 releasePage(*ppPage);
1565 }
drhee696e22004-08-30 16:52:17 +00001566 }
danielk19779f580ad2008-09-10 14:45:57 +00001567
danielk197789bc4bc2009-07-21 19:25:24 +00001568 /* If the requested page number was either 0 or greater than the page
1569 ** number of the last page in the database, this function should return
1570 ** SQLITE_CORRUPT or some other error (i.e. SQLITE_FULL). Check that this
1571 ** is the case. */
1572 assert( (pgno>0 && pgno<=iLastPg) || rc!=SQLITE_OK );
1573 testcase( pgno==0 );
1574 testcase( pgno==iLastPg );
1575
drhde647132004-05-07 17:57:49 +00001576 return rc;
1577}
1578
1579/*
drh3aac2dd2004-04-26 14:10:20 +00001580** Release a MemPage. This should be called once for each prior
danielk197730548662009-07-09 05:07:37 +00001581** call to btreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +00001582*/
drh4b70f112004-05-02 21:12:19 +00001583static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001584 if( pPage ){
drh30df0092008-12-23 15:58:06 +00001585 assert( pPage->nOverflow==0 || sqlite3PagerPageRefcount(pPage->pDbPage)>1 );
drh3aac2dd2004-04-26 14:10:20 +00001586 assert( pPage->aData );
1587 assert( pPage->pBt );
drhbf4bca52007-09-06 22:19:14 +00001588 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1589 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
drh1fee73e2007-08-29 04:00:57 +00001590 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001591 sqlite3PagerUnref(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00001592 }
1593}
1594
1595/*
drha6abd042004-06-09 17:37:22 +00001596** During a rollback, when the pager reloads information into the cache
1597** so that the cache is restored to its original state at the start of
1598** the transaction, for each page restored this routine is called.
1599**
1600** This routine needs to reset the extra data section at the end of the
1601** page to agree with the restored data.
1602*/
danielk1977eaa06f62008-09-18 17:34:44 +00001603static void pageReinit(DbPage *pData){
drh07d183d2005-05-01 22:52:42 +00001604 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00001605 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
danielk1977d217e6f2009-04-01 17:13:51 +00001606 assert( sqlite3PagerPageRefcount(pData)>0 );
danielk197771d5d2c2008-09-29 11:49:47 +00001607 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00001608 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00001609 pPage->isInit = 0;
danielk1977d217e6f2009-04-01 17:13:51 +00001610 if( sqlite3PagerPageRefcount(pData)>1 ){
drh5e8d8872009-03-30 17:19:48 +00001611 /* pPage might not be a btree page; it might be an overflow page
1612 ** or ptrmap page or a free page. In those cases, the following
danielk197730548662009-07-09 05:07:37 +00001613 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
drh5e8d8872009-03-30 17:19:48 +00001614 ** But no harm is done by this. And it is very important that
danielk197730548662009-07-09 05:07:37 +00001615 ** btreeInitPage() be called on every btree page so we make
drh5e8d8872009-03-30 17:19:48 +00001616 ** the call for every page that comes in for re-initing. */
danielk197730548662009-07-09 05:07:37 +00001617 btreeInitPage(pPage);
danielk197771d5d2c2008-09-29 11:49:47 +00001618 }
drha6abd042004-06-09 17:37:22 +00001619 }
1620}
1621
1622/*
drhe5fe6902007-12-07 18:55:28 +00001623** Invoke the busy handler for a btree.
1624*/
danielk19771ceedd32008-11-19 10:22:33 +00001625static int btreeInvokeBusyHandler(void *pArg){
drhe5fe6902007-12-07 18:55:28 +00001626 BtShared *pBt = (BtShared*)pArg;
1627 assert( pBt->db );
1628 assert( sqlite3_mutex_held(pBt->db->mutex) );
1629 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
1630}
1631
1632/*
drhad3e0102004-09-03 23:32:18 +00001633** Open a database file.
1634**
drh382c0242001-10-06 16:33:02 +00001635** zFilename is the name of the database file. If zFilename is NULL
drh1bee3d72001-10-15 00:44:35 +00001636** a new database with a random name is created. This randomly named
drh23e11ca2004-05-04 17:27:28 +00001637** database file will be deleted when sqlite3BtreeClose() is called.
drhe53831d2007-08-17 01:14:38 +00001638** If zFilename is ":memory:" then an in-memory database is created
1639** that is automatically destroyed when it is closed.
drhc47fd8e2009-04-30 13:30:32 +00001640**
1641** If the database is already opened in the same database connection
1642** and we are in shared cache mode, then the open will fail with an
1643** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
1644** objects in the same database connection since doing so will lead
1645** to problems with locking.
drha059ad02001-04-17 20:09:11 +00001646*/
drh23e11ca2004-05-04 17:27:28 +00001647int sqlite3BtreeOpen(
drh3aac2dd2004-04-26 14:10:20 +00001648 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00001649 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001650 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00001651 int flags, /* Options */
1652 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00001653){
drh7555d8e2009-03-20 13:15:30 +00001654 sqlite3_vfs *pVfs; /* The VFS to use for this btree */
1655 BtShared *pBt = 0; /* Shared part of btree structure */
1656 Btree *p; /* Handle to return */
1657 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
1658 int rc = SQLITE_OK; /* Result code from this function */
1659 u8 nReserve; /* Byte of unused space on each page */
1660 unsigned char zDbHeader[100]; /* Database header content */
danielk1977aef0bf62005-12-30 16:28:01 +00001661
1662 /* Set the variable isMemdb to true for an in-memory database, or
1663 ** false for a file-based database. This symbol is only required if
1664 ** either of the shared-data or autovacuum features are compiled
1665 ** into the library.
1666 */
1667#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
1668 #ifdef SQLITE_OMIT_MEMORYDB
drh980b1a72006-08-16 16:42:48 +00001669 const int isMemdb = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00001670 #else
drh980b1a72006-08-16 16:42:48 +00001671 const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
danielk1977aef0bf62005-12-30 16:28:01 +00001672 #endif
1673#endif
1674
drhe5fe6902007-12-07 18:55:28 +00001675 assert( db!=0 );
1676 assert( sqlite3_mutex_held(db->mutex) );
drh153c62c2007-08-24 03:51:33 +00001677
drhe5fe6902007-12-07 18:55:28 +00001678 pVfs = db->pVfs;
drh17435752007-08-16 04:30:38 +00001679 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00001680 if( !p ){
1681 return SQLITE_NOMEM;
1682 }
1683 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00001684 p->db = db;
danielk1977602b4662009-07-02 07:47:33 +00001685#ifndef SQLITE_OMIT_SHARED_CACHE
1686 p->lock.pBtree = p;
1687 p->lock.iTable = 1;
1688#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001689
drh198bf392006-01-06 21:52:49 +00001690#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001691 /*
1692 ** If this Btree is a candidate for shared cache, try to find an
1693 ** existing BtShared object that we can share with
1694 */
danielk197720c6cc22009-04-01 18:03:00 +00001695 if( isMemdb==0 && zFilename && zFilename[0] ){
danielk1977502b4e02008-09-02 14:07:24 +00001696 if( sqlite3GlobalConfig.sharedCacheEnabled ){
danielk1977adfb9b02007-09-17 07:02:56 +00001697 int nFullPathname = pVfs->mxPathname+1;
drhe5ae5732008-06-15 02:51:47 +00001698 char *zFullPathname = sqlite3Malloc(nFullPathname);
drhff0587c2007-08-29 17:43:19 +00001699 sqlite3_mutex *mutexShared;
1700 p->sharable = 1;
drhff0587c2007-08-29 17:43:19 +00001701 if( !zFullPathname ){
1702 sqlite3_free(p);
1703 return SQLITE_NOMEM;
1704 }
danielk1977adfb9b02007-09-17 07:02:56 +00001705 sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
drh7555d8e2009-03-20 13:15:30 +00001706 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
1707 sqlite3_mutex_enter(mutexOpen);
danielk197759f8c082008-06-18 17:09:10 +00001708 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhff0587c2007-08-29 17:43:19 +00001709 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001710 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
drhff0587c2007-08-29 17:43:19 +00001711 assert( pBt->nRef>0 );
1712 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
1713 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
drhc47fd8e2009-04-30 13:30:32 +00001714 int iDb;
1715 for(iDb=db->nDb-1; iDb>=0; iDb--){
1716 Btree *pExisting = db->aDb[iDb].pBt;
1717 if( pExisting && pExisting->pBt==pBt ){
1718 sqlite3_mutex_leave(mutexShared);
1719 sqlite3_mutex_leave(mutexOpen);
1720 sqlite3_free(zFullPathname);
1721 sqlite3_free(p);
1722 return SQLITE_CONSTRAINT;
1723 }
1724 }
drhff0587c2007-08-29 17:43:19 +00001725 p->pBt = pBt;
1726 pBt->nRef++;
1727 break;
1728 }
1729 }
1730 sqlite3_mutex_leave(mutexShared);
1731 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00001732 }
drhff0587c2007-08-29 17:43:19 +00001733#ifdef SQLITE_DEBUG
1734 else{
1735 /* In debug mode, we mark all persistent databases as sharable
1736 ** even when they are not. This exercises the locking code and
1737 ** gives more opportunity for asserts(sqlite3_mutex_held())
1738 ** statements to find locking problems.
1739 */
1740 p->sharable = 1;
1741 }
1742#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001743 }
1744#endif
drha059ad02001-04-17 20:09:11 +00001745 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00001746 /*
1747 ** The following asserts make sure that structures used by the btree are
1748 ** the right size. This is to guard against size changes that result
1749 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00001750 */
drhe53831d2007-08-17 01:14:38 +00001751 assert( sizeof(i64)==8 || sizeof(i64)==4 );
1752 assert( sizeof(u64)==8 || sizeof(u64)==4 );
1753 assert( sizeof(u32)==4 );
1754 assert( sizeof(u16)==2 );
1755 assert( sizeof(Pgno)==4 );
1756
1757 pBt = sqlite3MallocZero( sizeof(*pBt) );
1758 if( pBt==0 ){
1759 rc = SQLITE_NOMEM;
1760 goto btree_open_out;
1761 }
danielk197771d5d2c2008-09-29 11:49:47 +00001762 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
drh4775ecd2009-07-24 19:01:19 +00001763 EXTRA_SIZE, flags, vfsFlags, pageReinit);
drhe53831d2007-08-17 01:14:38 +00001764 if( rc==SQLITE_OK ){
1765 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
1766 }
1767 if( rc!=SQLITE_OK ){
1768 goto btree_open_out;
1769 }
danielk19772a50ff02009-04-10 09:47:06 +00001770 pBt->db = db;
danielk19771ceedd32008-11-19 10:22:33 +00001771 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
drhe53831d2007-08-17 01:14:38 +00001772 p->pBt = pBt;
1773
drhe53831d2007-08-17 01:14:38 +00001774 pBt->pCursor = 0;
1775 pBt->pPage1 = 0;
1776 pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
1777 pBt->pageSize = get2byte(&zDbHeader[16]);
1778 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1779 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00001780 pBt->pageSize = 0;
drhe53831d2007-08-17 01:14:38 +00001781#ifndef SQLITE_OMIT_AUTOVACUUM
1782 /* If the magic name ":memory:" will create an in-memory database, then
1783 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
1784 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
1785 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
1786 ** regular file-name. In this case the auto-vacuum applies as per normal.
1787 */
1788 if( zFilename && !isMemdb ){
1789 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
1790 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
1791 }
1792#endif
1793 nReserve = 0;
1794 }else{
1795 nReserve = zDbHeader[20];
drhe53831d2007-08-17 01:14:38 +00001796 pBt->pageSizeFixed = 1;
1797#ifndef SQLITE_OMIT_AUTOVACUUM
1798 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1799 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
1800#endif
1801 }
drhfa9601a2009-06-18 17:22:39 +00001802 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhc0b61812009-04-30 01:22:41 +00001803 if( rc ) goto btree_open_out;
drhe53831d2007-08-17 01:14:38 +00001804 pBt->usableSize = pBt->pageSize - nReserve;
1805 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
drhe53831d2007-08-17 01:14:38 +00001806
1807#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1808 /* Add the new BtShared object to the linked list sharable BtShareds.
1809 */
1810 if( p->sharable ){
1811 sqlite3_mutex *mutexShared;
1812 pBt->nRef = 1;
danielk197759f8c082008-06-18 17:09:10 +00001813 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
danielk1977075c23a2008-09-01 18:34:20 +00001814 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
danielk197759f8c082008-06-18 17:09:10 +00001815 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
drh3285db22007-09-03 22:00:39 +00001816 if( pBt->mutex==0 ){
1817 rc = SQLITE_NOMEM;
drhe5fe6902007-12-07 18:55:28 +00001818 db->mallocFailed = 0;
drh3285db22007-09-03 22:00:39 +00001819 goto btree_open_out;
1820 }
drhff0587c2007-08-29 17:43:19 +00001821 }
drhe53831d2007-08-17 01:14:38 +00001822 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00001823 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
1824 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
drhe53831d2007-08-17 01:14:38 +00001825 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00001826 }
drheee46cf2004-11-06 00:02:48 +00001827#endif
drh90f5ecb2004-07-22 01:19:35 +00001828 }
danielk1977aef0bf62005-12-30 16:28:01 +00001829
drhcfed7bc2006-03-13 14:28:05 +00001830#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001831 /* If the new Btree uses a sharable pBtShared, then link the new
1832 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00001833 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00001834 */
drhe53831d2007-08-17 01:14:38 +00001835 if( p->sharable ){
1836 int i;
1837 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00001838 for(i=0; i<db->nDb; i++){
1839 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00001840 while( pSib->pPrev ){ pSib = pSib->pPrev; }
1841 if( p->pBt<pSib->pBt ){
1842 p->pNext = pSib;
1843 p->pPrev = 0;
1844 pSib->pPrev = p;
1845 }else{
drhabddb0c2007-08-20 13:14:28 +00001846 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
drhe53831d2007-08-17 01:14:38 +00001847 pSib = pSib->pNext;
1848 }
1849 p->pNext = pSib->pNext;
1850 p->pPrev = pSib;
1851 if( p->pNext ){
1852 p->pNext->pPrev = p;
1853 }
1854 pSib->pNext = p;
1855 }
1856 break;
1857 }
1858 }
danielk1977aef0bf62005-12-30 16:28:01 +00001859 }
danielk1977aef0bf62005-12-30 16:28:01 +00001860#endif
1861 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00001862
1863btree_open_out:
1864 if( rc!=SQLITE_OK ){
1865 if( pBt && pBt->pPager ){
1866 sqlite3PagerClose(pBt->pPager);
1867 }
drh17435752007-08-16 04:30:38 +00001868 sqlite3_free(pBt);
1869 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00001870 *ppBtree = 0;
1871 }
drh7555d8e2009-03-20 13:15:30 +00001872 if( mutexOpen ){
1873 assert( sqlite3_mutex_held(mutexOpen) );
1874 sqlite3_mutex_leave(mutexOpen);
1875 }
danielk1977dddbcdc2007-04-26 14:42:34 +00001876 return rc;
drha059ad02001-04-17 20:09:11 +00001877}
1878
1879/*
drhe53831d2007-08-17 01:14:38 +00001880** Decrement the BtShared.nRef counter. When it reaches zero,
1881** remove the BtShared structure from the sharing list. Return
1882** true if the BtShared.nRef counter reaches zero and return
1883** false if it is still positive.
1884*/
1885static int removeFromSharingList(BtShared *pBt){
1886#ifndef SQLITE_OMIT_SHARED_CACHE
1887 sqlite3_mutex *pMaster;
1888 BtShared *pList;
1889 int removed = 0;
1890
drhd677b3d2007-08-20 22:48:41 +00001891 assert( sqlite3_mutex_notheld(pBt->mutex) );
danielk197759f8c082008-06-18 17:09:10 +00001892 pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhe53831d2007-08-17 01:14:38 +00001893 sqlite3_mutex_enter(pMaster);
1894 pBt->nRef--;
1895 if( pBt->nRef<=0 ){
drh78f82d12008-09-02 00:52:52 +00001896 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
1897 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
drhe53831d2007-08-17 01:14:38 +00001898 }else{
drh78f82d12008-09-02 00:52:52 +00001899 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
drh34004ce2008-07-11 16:15:17 +00001900 while( ALWAYS(pList) && pList->pNext!=pBt ){
drhe53831d2007-08-17 01:14:38 +00001901 pList=pList->pNext;
1902 }
drh34004ce2008-07-11 16:15:17 +00001903 if( ALWAYS(pList) ){
drhe53831d2007-08-17 01:14:38 +00001904 pList->pNext = pBt->pNext;
1905 }
1906 }
drh3285db22007-09-03 22:00:39 +00001907 if( SQLITE_THREADSAFE ){
1908 sqlite3_mutex_free(pBt->mutex);
1909 }
drhe53831d2007-08-17 01:14:38 +00001910 removed = 1;
1911 }
1912 sqlite3_mutex_leave(pMaster);
1913 return removed;
1914#else
1915 return 1;
1916#endif
1917}
1918
1919/*
drhf7141992008-06-19 00:16:08 +00001920** Make sure pBt->pTmpSpace points to an allocation of
1921** MX_CELL_SIZE(pBt) bytes.
1922*/
1923static void allocateTempSpace(BtShared *pBt){
1924 if( !pBt->pTmpSpace ){
1925 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
1926 }
1927}
1928
1929/*
1930** Free the pBt->pTmpSpace allocation
1931*/
1932static void freeTempSpace(BtShared *pBt){
1933 sqlite3PageFree( pBt->pTmpSpace);
1934 pBt->pTmpSpace = 0;
1935}
1936
1937/*
drha059ad02001-04-17 20:09:11 +00001938** Close an open database and invalidate all cursors.
1939*/
danielk1977aef0bf62005-12-30 16:28:01 +00001940int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00001941 BtShared *pBt = p->pBt;
1942 BtCursor *pCur;
1943
danielk1977aef0bf62005-12-30 16:28:01 +00001944 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00001945 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00001946 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001947 pCur = pBt->pCursor;
1948 while( pCur ){
1949 BtCursor *pTmp = pCur;
1950 pCur = pCur->pNext;
1951 if( pTmp->pBtree==p ){
1952 sqlite3BtreeCloseCursor(pTmp);
1953 }
drha059ad02001-04-17 20:09:11 +00001954 }
danielk1977aef0bf62005-12-30 16:28:01 +00001955
danielk19778d34dfd2006-01-24 16:37:57 +00001956 /* Rollback any active transaction and free the handle structure.
1957 ** The call to sqlite3BtreeRollback() drops any table-locks held by
1958 ** this handle.
1959 */
danielk1977b597f742006-01-15 11:39:18 +00001960 sqlite3BtreeRollback(p);
drhe53831d2007-08-17 01:14:38 +00001961 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00001962
danielk1977aef0bf62005-12-30 16:28:01 +00001963 /* If there are still other outstanding references to the shared-btree
1964 ** structure, return now. The remainder of this procedure cleans
1965 ** up the shared-btree.
1966 */
drhe53831d2007-08-17 01:14:38 +00001967 assert( p->wantToLock==0 && p->locked==0 );
1968 if( !p->sharable || removeFromSharingList(pBt) ){
1969 /* The pBt is no longer on the sharing list, so we can access
1970 ** it without having to hold the mutex.
1971 **
1972 ** Clean out and delete the BtShared object.
1973 */
1974 assert( !pBt->pCursor );
drhe53831d2007-08-17 01:14:38 +00001975 sqlite3PagerClose(pBt->pPager);
1976 if( pBt->xFreeSchema && pBt->pSchema ){
1977 pBt->xFreeSchema(pBt->pSchema);
1978 }
1979 sqlite3_free(pBt->pSchema);
drhf7141992008-06-19 00:16:08 +00001980 freeTempSpace(pBt);
drh65bbf292008-06-19 01:03:17 +00001981 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00001982 }
1983
drhe53831d2007-08-17 01:14:38 +00001984#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00001985 assert( p->wantToLock==0 );
1986 assert( p->locked==0 );
1987 if( p->pPrev ) p->pPrev->pNext = p->pNext;
1988 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00001989#endif
1990
drhe53831d2007-08-17 01:14:38 +00001991 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00001992 return SQLITE_OK;
1993}
1994
1995/*
drhda47d772002-12-02 04:25:19 +00001996** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00001997**
1998** The maximum number of cache pages is set to the absolute
1999** value of mxPage. If mxPage is negative, the pager will
2000** operate asynchronously - it will not stop to do fsync()s
2001** to insure data is written to the disk surface before
2002** continuing. Transactions still work if synchronous is off,
2003** and the database cannot be corrupted if this program
2004** crashes. But if the operating system crashes or there is
2005** an abrupt power failure when synchronous is off, the database
2006** could be left in an inconsistent and unrecoverable state.
2007** Synchronous is on by default so database corruption is not
2008** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00002009*/
danielk1977aef0bf62005-12-30 16:28:01 +00002010int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2011 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00002012 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002013 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00002014 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00002015 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00002016 return SQLITE_OK;
2017}
2018
2019/*
drh973b6e32003-02-12 14:09:42 +00002020** Change the way data is synced to disk in order to increase or decrease
2021** how well the database resists damage due to OS crashes and power
2022** failures. Level 1 is the same as asynchronous (no syncs() occur and
2023** there is a high probability of damage) Level 2 is the default. There
2024** is a very low but non-zero probability of damage. Level 3 reduces the
2025** probability of damage to near zero but with a write performance reduction.
2026*/
danielk197793758c82005-01-21 08:13:14 +00002027#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drhac530b12006-02-11 01:25:50 +00002028int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
danielk1977aef0bf62005-12-30 16:28:01 +00002029 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00002030 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002031 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00002032 sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
drhd677b3d2007-08-20 22:48:41 +00002033 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00002034 return SQLITE_OK;
2035}
danielk197793758c82005-01-21 08:13:14 +00002036#endif
drh973b6e32003-02-12 14:09:42 +00002037
drh2c8997b2005-08-27 16:36:48 +00002038/*
2039** Return TRUE if the given btree is set to safety level 1. In other
2040** words, return TRUE if no sync() occurs on the disk files.
2041*/
danielk1977aef0bf62005-12-30 16:28:01 +00002042int sqlite3BtreeSyncDisabled(Btree *p){
2043 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002044 int rc;
drhe5fe6902007-12-07 18:55:28 +00002045 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002046 sqlite3BtreeEnter(p);
drhd0679ed2007-08-28 22:24:34 +00002047 assert( pBt && pBt->pPager );
drhd677b3d2007-08-20 22:48:41 +00002048 rc = sqlite3PagerNosync(pBt->pPager);
2049 sqlite3BtreeLeave(p);
2050 return rc;
drh2c8997b2005-08-27 16:36:48 +00002051}
2052
danielk1977576ec6b2005-01-21 11:55:25 +00002053#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh973b6e32003-02-12 14:09:42 +00002054/*
drh90f5ecb2004-07-22 01:19:35 +00002055** Change the default pages size and the number of reserved bytes per page.
drhce4869f2009-04-02 20:16:58 +00002056** Or, if the page size has already been fixed, return SQLITE_READONLY
2057** without changing anything.
drh06f50212004-11-02 14:24:33 +00002058**
2059** The page size must be a power of 2 between 512 and 65536. If the page
2060** size supplied does not meet this constraint then the page size is not
2061** changed.
2062**
2063** Page sizes are constrained to be a power of two so that the region
2064** of the database file used for locking (beginning at PENDING_BYTE,
2065** the first byte past the 1GB boundary, 0x40000000) needs to occur
2066** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00002067**
2068** If parameter nReserve is less than zero, then the number of reserved
2069** bytes per page is left unchanged.
drhce4869f2009-04-02 20:16:58 +00002070**
2071** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
2072** and autovacuum mode can no longer be changed.
drh90f5ecb2004-07-22 01:19:35 +00002073*/
drhce4869f2009-04-02 20:16:58 +00002074int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
danielk1977a1644fd2007-08-29 12:31:25 +00002075 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002076 BtShared *pBt = p->pBt;
drhf49661a2008-12-10 16:45:50 +00002077 assert( nReserve>=-1 && nReserve<=255 );
drhd677b3d2007-08-20 22:48:41 +00002078 sqlite3BtreeEnter(p);
drh90f5ecb2004-07-22 01:19:35 +00002079 if( pBt->pageSizeFixed ){
drhd677b3d2007-08-20 22:48:41 +00002080 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00002081 return SQLITE_READONLY;
2082 }
2083 if( nReserve<0 ){
2084 nReserve = pBt->pageSize - pBt->usableSize;
2085 }
drhf49661a2008-12-10 16:45:50 +00002086 assert( nReserve>=0 && nReserve<=255 );
drh06f50212004-11-02 14:24:33 +00002087 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2088 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00002089 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002090 assert( !pBt->pPage1 && !pBt->pCursor );
drh1bd10f82008-12-10 21:19:56 +00002091 pBt->pageSize = (u16)pageSize;
drhf7141992008-06-19 00:16:08 +00002092 freeTempSpace(pBt);
drh90f5ecb2004-07-22 01:19:35 +00002093 }
drhfa9601a2009-06-18 17:22:39 +00002094 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhf49661a2008-12-10 16:45:50 +00002095 pBt->usableSize = pBt->pageSize - (u16)nReserve;
drhce4869f2009-04-02 20:16:58 +00002096 if( iFix ) pBt->pageSizeFixed = 1;
drhd677b3d2007-08-20 22:48:41 +00002097 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00002098 return rc;
drh90f5ecb2004-07-22 01:19:35 +00002099}
2100
2101/*
2102** Return the currently defined page size
2103*/
danielk1977aef0bf62005-12-30 16:28:01 +00002104int sqlite3BtreeGetPageSize(Btree *p){
2105 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00002106}
drh7f751222009-03-17 22:33:00 +00002107
2108/*
2109** Return the number of bytes of space at the end of every page that
2110** are intentually left unused. This is the "reserved" space that is
2111** sometimes used by extensions.
2112*/
danielk1977aef0bf62005-12-30 16:28:01 +00002113int sqlite3BtreeGetReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002114 int n;
2115 sqlite3BtreeEnter(p);
2116 n = p->pBt->pageSize - p->pBt->usableSize;
2117 sqlite3BtreeLeave(p);
2118 return n;
drh2011d5f2004-07-22 02:40:37 +00002119}
drhf8e632b2007-05-08 14:51:36 +00002120
2121/*
2122** Set the maximum page count for a database if mxPage is positive.
2123** No changes are made if mxPage is 0 or negative.
2124** Regardless of the value of mxPage, return the maximum page count.
2125*/
2126int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00002127 int n;
2128 sqlite3BtreeEnter(p);
2129 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
2130 sqlite3BtreeLeave(p);
2131 return n;
drhf8e632b2007-05-08 14:51:36 +00002132}
danielk1977576ec6b2005-01-21 11:55:25 +00002133#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00002134
2135/*
danielk1977951af802004-11-05 15:45:09 +00002136** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
2137** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
2138** is disabled. The default value for the auto-vacuum property is
2139** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
2140*/
danielk1977aef0bf62005-12-30 16:28:01 +00002141int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00002142#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002143 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00002144#else
danielk1977dddbcdc2007-04-26 14:42:34 +00002145 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002146 int rc = SQLITE_OK;
drh076d4662009-02-18 20:31:18 +00002147 u8 av = (u8)autoVacuum;
drhd677b3d2007-08-20 22:48:41 +00002148
2149 sqlite3BtreeEnter(p);
drh076d4662009-02-18 20:31:18 +00002150 if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002151 rc = SQLITE_READONLY;
2152 }else{
drh076d4662009-02-18 20:31:18 +00002153 pBt->autoVacuum = av ?1:0;
2154 pBt->incrVacuum = av==2 ?1:0;
danielk1977951af802004-11-05 15:45:09 +00002155 }
drhd677b3d2007-08-20 22:48:41 +00002156 sqlite3BtreeLeave(p);
2157 return rc;
danielk1977951af802004-11-05 15:45:09 +00002158#endif
2159}
2160
2161/*
2162** Return the value of the 'auto-vacuum' property. If auto-vacuum is
2163** enabled 1 is returned. Otherwise 0.
2164*/
danielk1977aef0bf62005-12-30 16:28:01 +00002165int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00002166#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002167 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00002168#else
drhd677b3d2007-08-20 22:48:41 +00002169 int rc;
2170 sqlite3BtreeEnter(p);
2171 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00002172 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
2173 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
2174 BTREE_AUTOVACUUM_INCR
2175 );
drhd677b3d2007-08-20 22:48:41 +00002176 sqlite3BtreeLeave(p);
2177 return rc;
danielk1977951af802004-11-05 15:45:09 +00002178#endif
2179}
2180
2181
2182/*
drha34b6762004-05-07 13:30:42 +00002183** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00002184** also acquire a readlock on that file.
2185**
2186** SQLITE_OK is returned on success. If the file is not a
2187** well-formed database file, then SQLITE_CORRUPT is returned.
2188** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00002189** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00002190*/
danielk1977aef0bf62005-12-30 16:28:01 +00002191static int lockBtree(BtShared *pBt){
danielk1977f653d782008-03-20 11:04:21 +00002192 int rc;
drh3aac2dd2004-04-26 14:10:20 +00002193 MemPage *pPage1;
danielk197793f7af92008-05-09 16:57:50 +00002194 int nPage;
drhd677b3d2007-08-20 22:48:41 +00002195
drh1fee73e2007-08-29 04:00:57 +00002196 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977295dc102009-04-01 19:07:03 +00002197 assert( pBt->pPage1==0 );
danielk197789bc4bc2009-07-21 19:25:24 +00002198 rc = sqlite3PagerSharedLock(pBt->pPager);
2199 if( rc!=SQLITE_OK ) return rc;
danielk197730548662009-07-09 05:07:37 +00002200 rc = btreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00002201 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00002202
2203 /* Do some checking to help insure the file we opened really is
2204 ** a valid database file.
2205 */
danielk1977ad0132d2008-06-07 08:58:22 +00002206 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
2207 if( rc!=SQLITE_OK ){
danielk197793f7af92008-05-09 16:57:50 +00002208 goto page1_init_failed;
2209 }else if( nPage>0 ){
danielk1977f653d782008-03-20 11:04:21 +00002210 int pageSize;
2211 int usableSize;
drhb6f41482004-05-14 01:58:11 +00002212 u8 *page1 = pPage1->aData;
danielk1977ad0132d2008-06-07 08:58:22 +00002213 rc = SQLITE_NOTADB;
drhb6f41482004-05-14 01:58:11 +00002214 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00002215 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00002216 }
drh309169a2007-04-24 17:27:51 +00002217 if( page1[18]>1 ){
2218 pBt->readOnly = 1;
2219 }
2220 if( page1[19]>1 ){
drhb6f41482004-05-14 01:58:11 +00002221 goto page1_init_failed;
2222 }
drhe5ae5732008-06-15 02:51:47 +00002223
2224 /* The maximum embedded fraction must be exactly 25%. And the minimum
2225 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
2226 ** The original design allowed these amounts to vary, but as of
2227 ** version 3.6.0, we require them to be fixed.
2228 */
2229 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
2230 goto page1_init_failed;
2231 }
drh07d183d2005-05-01 22:52:42 +00002232 pageSize = get2byte(&page1[16]);
drh7dc385e2007-09-06 23:39:36 +00002233 if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
2234 (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
2235 ){
drh07d183d2005-05-01 22:52:42 +00002236 goto page1_init_failed;
2237 }
2238 assert( (pageSize & 7)==0 );
danielk1977f653d782008-03-20 11:04:21 +00002239 usableSize = pageSize - page1[20];
2240 if( pageSize!=pBt->pageSize ){
2241 /* After reading the first page of the database assuming a page size
2242 ** of BtShared.pageSize, we have discovered that the page-size is
2243 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
2244 ** zero and return SQLITE_OK. The caller will call this function
2245 ** again with the correct page-size.
2246 */
2247 releasePage(pPage1);
drhf49661a2008-12-10 16:45:50 +00002248 pBt->usableSize = (u16)usableSize;
2249 pBt->pageSize = (u16)pageSize;
drhf7141992008-06-19 00:16:08 +00002250 freeTempSpace(pBt);
drhfa9601a2009-06-18 17:22:39 +00002251 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
2252 pageSize-usableSize);
drh5e483932009-07-10 16:51:30 +00002253 return rc;
danielk1977f653d782008-03-20 11:04:21 +00002254 }
drhb33e1b92009-06-18 11:29:20 +00002255 if( usableSize<480 ){
drhb6f41482004-05-14 01:58:11 +00002256 goto page1_init_failed;
2257 }
drh1bd10f82008-12-10 21:19:56 +00002258 pBt->pageSize = (u16)pageSize;
2259 pBt->usableSize = (u16)usableSize;
drh057cd3a2005-02-15 16:23:02 +00002260#ifndef SQLITE_OMIT_AUTOVACUUM
2261 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00002262 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00002263#endif
drh306dc212001-05-21 13:45:10 +00002264 }
drhb6f41482004-05-14 01:58:11 +00002265
2266 /* maxLocal is the maximum amount of payload to store locally for
2267 ** a cell. Make sure it is small enough so that at least minFanout
2268 ** cells can will fit on one page. We assume a 10-byte page header.
2269 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00002270 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00002271 ** 4-byte child pointer
2272 ** 9-byte nKey value
2273 ** 4-byte nData value
2274 ** 4-byte overflow page pointer
drh43605152004-05-29 21:46:49 +00002275 ** So a cell consists of a 2-byte poiner, a header which is as much as
2276 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
2277 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00002278 */
drhe5ae5732008-06-15 02:51:47 +00002279 pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
2280 pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
drh43605152004-05-29 21:46:49 +00002281 pBt->maxLeaf = pBt->usableSize - 35;
drhe5ae5732008-06-15 02:51:47 +00002282 pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
drh2e38c322004-09-03 18:38:44 +00002283 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00002284 pBt->pPage1 = pPage1;
drhb6f41482004-05-14 01:58:11 +00002285 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00002286
drh72f82862001-05-24 21:06:34 +00002287page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00002288 releasePage(pPage1);
2289 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00002290 return rc;
drh306dc212001-05-21 13:45:10 +00002291}
2292
2293/*
drhb8ca3072001-12-05 00:21:20 +00002294** If there are no outstanding cursors and we are not in the middle
2295** of a transaction but there is a read lock on the database, then
2296** this routine unrefs the first page of the database file which
2297** has the effect of releasing the read lock.
2298**
drhb8ca3072001-12-05 00:21:20 +00002299** If there is a transaction in progress, this routine is a no-op.
2300*/
danielk1977aef0bf62005-12-30 16:28:01 +00002301static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00002302 assert( sqlite3_mutex_held(pBt->mutex) );
danielk19771bc9ee92009-07-04 15:41:02 +00002303 assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
2304 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
danielk1977c1761e82009-06-25 09:40:03 +00002305 assert( pBt->pPage1->aData );
2306 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
2307 assert( pBt->pPage1->aData );
2308 releasePage(pBt->pPage1);
drh3aac2dd2004-04-26 14:10:20 +00002309 pBt->pPage1 = 0;
drhb8ca3072001-12-05 00:21:20 +00002310 }
2311}
2312
2313/*
drhe39f2f92009-07-23 01:43:59 +00002314** If pBt points to an empty file then convert that empty file
2315** into a new empty database by initializing the first page of
2316** the database.
drh8b2f49b2001-06-08 00:21:52 +00002317*/
danielk1977aef0bf62005-12-30 16:28:01 +00002318static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00002319 MemPage *pP1;
2320 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00002321 int rc;
danielk1977ad0132d2008-06-07 08:58:22 +00002322 int nPage;
drhd677b3d2007-08-20 22:48:41 +00002323
drh1fee73e2007-08-29 04:00:57 +00002324 assert( sqlite3_mutex_held(pBt->mutex) );
drhe39f2f92009-07-23 01:43:59 +00002325 /* The database size has already been measured and cached, so failure
2326 ** is impossible here. If the original size measurement failed, then
2327 ** processing aborts before entering this routine. */
danielk1977ad0132d2008-06-07 08:58:22 +00002328 rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
drhe39f2f92009-07-23 01:43:59 +00002329 if( NEVER(rc!=SQLITE_OK) || nPage>0 ){
danielk1977ad0132d2008-06-07 08:58:22 +00002330 return rc;
2331 }
drh3aac2dd2004-04-26 14:10:20 +00002332 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00002333 assert( pP1!=0 );
2334 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00002335 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00002336 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00002337 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
2338 assert( sizeof(zMagicHeader)==16 );
drhb6f41482004-05-14 01:58:11 +00002339 put2byte(&data[16], pBt->pageSize);
drh9e572e62004-04-23 23:43:10 +00002340 data[18] = 1;
2341 data[19] = 1;
drhf49661a2008-12-10 16:45:50 +00002342 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
2343 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
drhe5ae5732008-06-15 02:51:47 +00002344 data[21] = 64;
2345 data[22] = 32;
2346 data[23] = 32;
drhb6f41482004-05-14 01:58:11 +00002347 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00002348 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhf2a611c2004-09-05 00:33:43 +00002349 pBt->pageSizeFixed = 1;
danielk1977003ba062004-11-04 02:57:33 +00002350#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002351 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00002352 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00002353 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00002354 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00002355#endif
drh8b2f49b2001-06-08 00:21:52 +00002356 return SQLITE_OK;
2357}
2358
2359/*
danielk1977ee5741e2004-05-31 10:01:34 +00002360** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00002361** is started if the second argument is nonzero, otherwise a read-
2362** transaction. If the second argument is 2 or more and exclusive
2363** transaction is started, meaning that no other process is allowed
2364** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00002365** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00002366** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00002367**
danielk1977ee5741e2004-05-31 10:01:34 +00002368** A write-transaction must be started before attempting any
2369** changes to the database. None of the following routines
2370** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00002371**
drh23e11ca2004-05-04 17:27:28 +00002372** sqlite3BtreeCreateTable()
2373** sqlite3BtreeCreateIndex()
2374** sqlite3BtreeClearTable()
2375** sqlite3BtreeDropTable()
2376** sqlite3BtreeInsert()
2377** sqlite3BtreeDelete()
2378** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00002379**
drhb8ef32c2005-03-14 02:01:49 +00002380** If an initial attempt to acquire the lock fails because of lock contention
2381** and the database was previously unlocked, then invoke the busy handler
2382** if there is one. But if there was previously a read-lock, do not
2383** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
2384** returned when there is already a read-lock in order to avoid a deadlock.
2385**
2386** Suppose there are two processes A and B. A has a read lock and B has
2387** a reserved lock. B tries to promote to exclusive but is blocked because
2388** of A's read lock. A tries to promote to reserved but is blocked by B.
2389** One or the other of the two processes must give way or there can be
2390** no progress. By returning SQLITE_BUSY and not invoking the busy callback
2391** when A already has a read lock, we encourage A to give up and let B
2392** proceed.
drha059ad02001-04-17 20:09:11 +00002393*/
danielk1977aef0bf62005-12-30 16:28:01 +00002394int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
danielk1977404ca072009-03-16 13:19:36 +00002395 sqlite3 *pBlock = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00002396 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00002397 int rc = SQLITE_OK;
2398
drhd677b3d2007-08-20 22:48:41 +00002399 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002400 btreeIntegrity(p);
2401
danielk1977ee5741e2004-05-31 10:01:34 +00002402 /* If the btree is already in a write-transaction, or it
2403 ** is already in a read-transaction and a read-transaction
2404 ** is requested, this is a no-op.
2405 */
danielk1977aef0bf62005-12-30 16:28:01 +00002406 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00002407 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002408 }
drhb8ef32c2005-03-14 02:01:49 +00002409
2410 /* Write transactions are not possible on a read-only database */
danielk1977ee5741e2004-05-31 10:01:34 +00002411 if( pBt->readOnly && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00002412 rc = SQLITE_READONLY;
2413 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002414 }
2415
danielk1977404ca072009-03-16 13:19:36 +00002416#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +00002417 /* If another database handle has already opened a write transaction
2418 ** on this shared-btree structure and a second write transaction is
danielk1977404ca072009-03-16 13:19:36 +00002419 ** requested, return SQLITE_LOCKED.
danielk1977aef0bf62005-12-30 16:28:01 +00002420 */
danielk1977404ca072009-03-16 13:19:36 +00002421 if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
2422 pBlock = pBt->pWriter->db;
2423 }else if( wrflag>1 ){
danielk1977641b0f42007-12-21 04:47:25 +00002424 BtLock *pIter;
2425 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
2426 if( pIter->pBtree!=p ){
danielk1977404ca072009-03-16 13:19:36 +00002427 pBlock = pIter->pBtree->db;
2428 break;
danielk1977641b0f42007-12-21 04:47:25 +00002429 }
2430 }
2431 }
danielk1977404ca072009-03-16 13:19:36 +00002432 if( pBlock ){
2433 sqlite3ConnectionBlocked(p->db, pBlock);
2434 rc = SQLITE_LOCKED_SHAREDCACHE;
2435 goto trans_begun;
2436 }
danielk1977641b0f42007-12-21 04:47:25 +00002437#endif
2438
danielk1977602b4662009-07-02 07:47:33 +00002439 /* Any read-only or read-write transaction implies a read-lock on
2440 ** page 1. So if some other shared-cache client already has a write-lock
2441 ** on page 1, the transaction cannot be opened. */
drh4c301aa2009-07-15 17:25:45 +00002442 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
2443 if( SQLITE_OK!=rc ) goto trans_begun;
danielk1977602b4662009-07-02 07:47:33 +00002444
drhb8ef32c2005-03-14 02:01:49 +00002445 do {
danielk1977295dc102009-04-01 19:07:03 +00002446 /* Call lockBtree() until either pBt->pPage1 is populated or
2447 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
2448 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
2449 ** reading page 1 it discovers that the page-size of the database
2450 ** file is not pBt->pageSize. In this case lockBtree() will update
2451 ** pBt->pageSize to the page-size of the file on disk.
2452 */
2453 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
drh309169a2007-04-24 17:27:51 +00002454
drhb8ef32c2005-03-14 02:01:49 +00002455 if( rc==SQLITE_OK && wrflag ){
drh309169a2007-04-24 17:27:51 +00002456 if( pBt->readOnly ){
2457 rc = SQLITE_READONLY;
2458 }else{
danielk1977d8293352009-04-30 09:10:37 +00002459 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
drh309169a2007-04-24 17:27:51 +00002460 if( rc==SQLITE_OK ){
2461 rc = newDatabase(pBt);
2462 }
drhb8ef32c2005-03-14 02:01:49 +00002463 }
2464 }
2465
danielk1977bd434552009-03-18 10:33:00 +00002466 if( rc!=SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00002467 unlockBtreeIfUnused(pBt);
2468 }
danielk1977aef0bf62005-12-30 16:28:01 +00002469 }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
danielk19771ceedd32008-11-19 10:22:33 +00002470 btreeInvokeBusyHandler(pBt) );
danielk1977aef0bf62005-12-30 16:28:01 +00002471
2472 if( rc==SQLITE_OK ){
2473 if( p->inTrans==TRANS_NONE ){
2474 pBt->nTransaction++;
danielk1977602b4662009-07-02 07:47:33 +00002475#ifndef SQLITE_OMIT_SHARED_CACHE
2476 if( p->sharable ){
2477 assert( p->lock.pBtree==p && p->lock.iTable==1 );
2478 p->lock.eLock = READ_LOCK;
2479 p->lock.pNext = pBt->pLock;
2480 pBt->pLock = &p->lock;
2481 }
2482#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002483 }
2484 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
2485 if( p->inTrans>pBt->inTransaction ){
2486 pBt->inTransaction = p->inTrans;
2487 }
danielk1977641b0f42007-12-21 04:47:25 +00002488#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977404ca072009-03-16 13:19:36 +00002489 if( wrflag ){
2490 assert( !pBt->pWriter );
2491 pBt->pWriter = p;
shaneca18d202009-03-23 02:34:32 +00002492 pBt->isExclusive = (u8)(wrflag>1);
danielk1977641b0f42007-12-21 04:47:25 +00002493 }
2494#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002495 }
2496
drhd677b3d2007-08-20 22:48:41 +00002497
2498trans_begun:
danielk1977fd7f0452008-12-17 17:30:26 +00002499 if( rc==SQLITE_OK && wrflag ){
danielk197712dd5492008-12-18 15:45:07 +00002500 /* This call makes sure that the pager has the correct number of
2501 ** open savepoints. If the second parameter is greater than 0 and
2502 ** the sub-journal is not already open, then it will be opened here.
2503 */
danielk1977fd7f0452008-12-17 17:30:26 +00002504 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
2505 }
danielk197712dd5492008-12-18 15:45:07 +00002506
danielk1977aef0bf62005-12-30 16:28:01 +00002507 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002508 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00002509 return rc;
drha059ad02001-04-17 20:09:11 +00002510}
2511
danielk1977687566d2004-11-02 12:56:41 +00002512#ifndef SQLITE_OMIT_AUTOVACUUM
2513
2514/*
2515** Set the pointer-map entries for all children of page pPage. Also, if
2516** pPage contains cells that point to overflow pages, set the pointer
2517** map entries for the overflow pages as well.
2518*/
2519static int setChildPtrmaps(MemPage *pPage){
2520 int i; /* Counter variable */
2521 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00002522 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00002523 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00002524 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002525 Pgno pgno = pPage->pgno;
2526
drh1fee73e2007-08-29 04:00:57 +00002527 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197730548662009-07-09 05:07:37 +00002528 rc = btreeInitPage(pPage);
danielk19772df71c72007-05-24 07:22:42 +00002529 if( rc!=SQLITE_OK ){
2530 goto set_child_ptrmaps_out;
2531 }
danielk1977687566d2004-11-02 12:56:41 +00002532 nCell = pPage->nCell;
2533
2534 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002535 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002536
drh98add2e2009-07-20 17:11:49 +00002537 ptrmapPutOvflPtr(pPage, pCell, &rc);
danielk197726836652005-01-17 01:33:13 +00002538
danielk1977687566d2004-11-02 12:56:41 +00002539 if( !pPage->leaf ){
2540 Pgno childPgno = get4byte(pCell);
drh98add2e2009-07-20 17:11:49 +00002541 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00002542 }
2543 }
2544
2545 if( !pPage->leaf ){
2546 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh98add2e2009-07-20 17:11:49 +00002547 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00002548 }
2549
2550set_child_ptrmaps_out:
2551 pPage->isInit = isInitOrig;
2552 return rc;
2553}
2554
2555/*
drhf3aed592009-07-08 18:12:49 +00002556** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
2557** that it points to iTo. Parameter eType describes the type of pointer to
2558** be modified, as follows:
danielk1977687566d2004-11-02 12:56:41 +00002559**
2560** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
2561** page of pPage.
2562**
2563** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
2564** page pointed to by one of the cells on pPage.
2565**
2566** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
2567** overflow page in the list.
2568*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00002569static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00002570 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00002571 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977687566d2004-11-02 12:56:41 +00002572 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00002573 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00002574 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00002575 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002576 }
danielk1977f78fc082004-11-02 14:40:32 +00002577 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00002578 }else{
drhf49661a2008-12-10 16:45:50 +00002579 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002580 int i;
2581 int nCell;
2582
danielk197730548662009-07-09 05:07:37 +00002583 btreeInitPage(pPage);
danielk1977687566d2004-11-02 12:56:41 +00002584 nCell = pPage->nCell;
2585
danielk1977687566d2004-11-02 12:56:41 +00002586 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002587 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002588 if( eType==PTRMAP_OVERFLOW1 ){
2589 CellInfo info;
danielk197730548662009-07-09 05:07:37 +00002590 btreeParseCellPtr(pPage, pCell, &info);
danielk1977687566d2004-11-02 12:56:41 +00002591 if( info.iOverflow ){
2592 if( iFrom==get4byte(&pCell[info.iOverflow]) ){
2593 put4byte(&pCell[info.iOverflow], iTo);
2594 break;
2595 }
2596 }
2597 }else{
2598 if( get4byte(pCell)==iFrom ){
2599 put4byte(pCell, iTo);
2600 break;
2601 }
2602 }
2603 }
2604
2605 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00002606 if( eType!=PTRMAP_BTREE ||
2607 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00002608 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002609 }
danielk1977687566d2004-11-02 12:56:41 +00002610 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
2611 }
2612
2613 pPage->isInit = isInitOrig;
2614 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002615 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002616}
2617
danielk1977003ba062004-11-04 02:57:33 +00002618
danielk19777701e812005-01-10 12:59:51 +00002619/*
2620** Move the open database page pDbPage to location iFreePage in the
2621** database. The pDbPage reference remains valid.
drhe64ca7b2009-07-16 18:21:17 +00002622**
2623** The isCommit flag indicates that there is no need to remember that
2624** the journal needs to be sync()ed before database page pDbPage->pgno
2625** can be written to. The caller has already promised not to write to that
2626** page.
danielk19777701e812005-01-10 12:59:51 +00002627*/
danielk1977003ba062004-11-04 02:57:33 +00002628static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00002629 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00002630 MemPage *pDbPage, /* Open page to move */
2631 u8 eType, /* Pointer map 'type' entry for pDbPage */
2632 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
danielk19774c999992008-07-16 18:17:55 +00002633 Pgno iFreePage, /* The location to move pDbPage to */
drhe64ca7b2009-07-16 18:21:17 +00002634 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
danielk1977003ba062004-11-04 02:57:33 +00002635){
2636 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
2637 Pgno iDbPage = pDbPage->pgno;
2638 Pager *pPager = pBt->pPager;
2639 int rc;
2640
danielk1977a0bf2652004-11-04 14:30:04 +00002641 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
2642 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00002643 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00002644 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00002645
drh85b623f2007-12-13 21:54:09 +00002646 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00002647 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
2648 iDbPage, iFreePage, iPtrPage, eType));
danielk19774c999992008-07-16 18:17:55 +00002649 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
danielk1977003ba062004-11-04 02:57:33 +00002650 if( rc!=SQLITE_OK ){
2651 return rc;
2652 }
2653 pDbPage->pgno = iFreePage;
2654
2655 /* If pDbPage was a btree-page, then it may have child pages and/or cells
2656 ** that point to overflow pages. The pointer map entries for all these
2657 ** pages need to be changed.
2658 **
2659 ** If pDbPage is an overflow page, then the first 4 bytes may store a
2660 ** pointer to a subsequent overflow page. If this is the case, then
2661 ** the pointer map needs to be updated for the subsequent overflow page.
2662 */
danielk1977a0bf2652004-11-04 14:30:04 +00002663 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00002664 rc = setChildPtrmaps(pDbPage);
2665 if( rc!=SQLITE_OK ){
2666 return rc;
2667 }
2668 }else{
2669 Pgno nextOvfl = get4byte(pDbPage->aData);
2670 if( nextOvfl!=0 ){
drh98add2e2009-07-20 17:11:49 +00002671 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
danielk1977003ba062004-11-04 02:57:33 +00002672 if( rc!=SQLITE_OK ){
2673 return rc;
2674 }
2675 }
2676 }
2677
2678 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
2679 ** that it points at iFreePage. Also fix the pointer map entry for
2680 ** iPtrPage.
2681 */
danielk1977a0bf2652004-11-04 14:30:04 +00002682 if( eType!=PTRMAP_ROOTPAGE ){
danielk197730548662009-07-09 05:07:37 +00002683 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00002684 if( rc!=SQLITE_OK ){
2685 return rc;
2686 }
danielk19773b8a05f2007-03-19 17:44:26 +00002687 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00002688 if( rc!=SQLITE_OK ){
2689 releasePage(pPtrPage);
2690 return rc;
2691 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002692 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00002693 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00002694 if( rc==SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +00002695 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
danielk1977fdb7cdb2005-01-17 02:12:18 +00002696 }
danielk1977003ba062004-11-04 02:57:33 +00002697 }
danielk1977003ba062004-11-04 02:57:33 +00002698 return rc;
2699}
2700
danielk1977dddbcdc2007-04-26 14:42:34 +00002701/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00002702static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00002703
2704/*
danielk1977dddbcdc2007-04-26 14:42:34 +00002705** Perform a single step of an incremental-vacuum. If successful,
2706** return SQLITE_OK. If there is no work to do (and therefore no
2707** point in calling this function again), return SQLITE_DONE.
2708**
2709** More specificly, this function attempts to re-organize the
2710** database so that the last page of the file currently in use
2711** is no longer in use.
2712**
drhea8ffdf2009-07-22 00:35:23 +00002713** If the nFin parameter is non-zero, this function assumes
danielk1977dddbcdc2007-04-26 14:42:34 +00002714** that the caller will keep calling incrVacuumStep() until
2715** it returns SQLITE_DONE or an error, and that nFin is the
2716** number of pages the database file will contain after this
drhea8ffdf2009-07-22 00:35:23 +00002717** process is complete. If nFin is zero, it is assumed that
2718** incrVacuumStep() will be called a finite amount of times
2719** which may or may not empty the freelist. A full autovacuum
2720** has nFin>0. A "PRAGMA incremental_vacuum" has nFin==0.
danielk1977dddbcdc2007-04-26 14:42:34 +00002721*/
danielk19773460d192008-12-27 15:23:13 +00002722static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
danielk1977dddbcdc2007-04-26 14:42:34 +00002723 Pgno nFreeList; /* Number of pages still on the free-list */
2724
drh1fee73e2007-08-29 04:00:57 +00002725 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977fa542f12009-04-02 18:28:08 +00002726 assert( iLastPg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00002727
2728 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
2729 int rc;
2730 u8 eType;
2731 Pgno iPtrPage;
2732
2733 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977fa542f12009-04-02 18:28:08 +00002734 if( nFreeList==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00002735 return SQLITE_DONE;
2736 }
2737
2738 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
2739 if( rc!=SQLITE_OK ){
2740 return rc;
2741 }
2742 if( eType==PTRMAP_ROOTPAGE ){
2743 return SQLITE_CORRUPT_BKPT;
2744 }
2745
2746 if( eType==PTRMAP_FREEPAGE ){
2747 if( nFin==0 ){
2748 /* Remove the page from the files free-list. This is not required
danielk19774ef24492007-05-23 09:52:41 +00002749 ** if nFin is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00002750 ** truncated to zero after this function returns, so it doesn't
2751 ** matter if it still contains some garbage entries.
2752 */
2753 Pgno iFreePg;
2754 MemPage *pFreePg;
2755 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
2756 if( rc!=SQLITE_OK ){
2757 return rc;
2758 }
2759 assert( iFreePg==iLastPg );
2760 releasePage(pFreePg);
2761 }
2762 } else {
2763 Pgno iFreePg; /* Index of free page to move pLastPg to */
2764 MemPage *pLastPg;
2765
danielk197730548662009-07-09 05:07:37 +00002766 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00002767 if( rc!=SQLITE_OK ){
2768 return rc;
2769 }
2770
danielk1977b4626a32007-04-28 15:47:43 +00002771 /* If nFin is zero, this loop runs exactly once and page pLastPg
2772 ** is swapped with the first free page pulled off the free list.
2773 **
2774 ** On the other hand, if nFin is greater than zero, then keep
2775 ** looping until a free-page located within the first nFin pages
2776 ** of the file is found.
2777 */
danielk1977dddbcdc2007-04-26 14:42:34 +00002778 do {
2779 MemPage *pFreePg;
2780 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
2781 if( rc!=SQLITE_OK ){
2782 releasePage(pLastPg);
2783 return rc;
2784 }
2785 releasePage(pFreePg);
2786 }while( nFin!=0 && iFreePg>nFin );
2787 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00002788
2789 rc = sqlite3PagerWrite(pLastPg->pDbPage);
danielk1977662278e2007-11-05 15:30:12 +00002790 if( rc==SQLITE_OK ){
danielk19774c999992008-07-16 18:17:55 +00002791 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
danielk1977662278e2007-11-05 15:30:12 +00002792 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002793 releasePage(pLastPg);
2794 if( rc!=SQLITE_OK ){
2795 return rc;
danielk1977662278e2007-11-05 15:30:12 +00002796 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002797 }
2798 }
2799
danielk19773460d192008-12-27 15:23:13 +00002800 if( nFin==0 ){
2801 iLastPg--;
2802 while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
danielk1977f4027782009-03-30 18:50:04 +00002803 if( PTRMAP_ISPAGE(pBt, iLastPg) ){
2804 MemPage *pPg;
danielk197730548662009-07-09 05:07:37 +00002805 int rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
danielk1977f4027782009-03-30 18:50:04 +00002806 if( rc!=SQLITE_OK ){
2807 return rc;
2808 }
2809 rc = sqlite3PagerWrite(pPg->pDbPage);
2810 releasePage(pPg);
2811 if( rc!=SQLITE_OK ){
2812 return rc;
2813 }
2814 }
danielk19773460d192008-12-27 15:23:13 +00002815 iLastPg--;
2816 }
2817 sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
danielk1977dddbcdc2007-04-26 14:42:34 +00002818 }
2819 return SQLITE_OK;
2820}
2821
2822/*
2823** A write-transaction must be opened before calling this function.
2824** It performs a single unit of work towards an incremental vacuum.
2825**
2826** If the incremental vacuum is finished after this function has run,
shanebe217792009-03-05 04:20:31 +00002827** SQLITE_DONE is returned. If it is not finished, but no error occurred,
danielk1977dddbcdc2007-04-26 14:42:34 +00002828** SQLITE_OK is returned. Otherwise an SQLite error code.
2829*/
2830int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002831 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002832 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002833
2834 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00002835 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
2836 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002837 rc = SQLITE_DONE;
2838 }else{
2839 invalidateAllOverflowCache(pBt);
danielk1977bea2a942009-01-20 17:06:27 +00002840 rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt));
danielk1977dddbcdc2007-04-26 14:42:34 +00002841 }
drhd677b3d2007-08-20 22:48:41 +00002842 sqlite3BtreeLeave(p);
2843 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00002844}
2845
2846/*
danielk19773b8a05f2007-03-19 17:44:26 +00002847** This routine is called prior to sqlite3PagerCommit when a transaction
danielk1977687566d2004-11-02 12:56:41 +00002848** is commited for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00002849**
2850** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
2851** the database file should be truncated to during the commit process.
2852** i.e. the database has been reorganized so that only the first *pnTrunc
2853** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00002854*/
danielk19773460d192008-12-27 15:23:13 +00002855static int autoVacuumCommit(BtShared *pBt){
danielk1977dddbcdc2007-04-26 14:42:34 +00002856 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002857 Pager *pPager = pBt->pPager;
drhf94a1732008-09-30 17:18:17 +00002858 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002859
drh1fee73e2007-08-29 04:00:57 +00002860 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00002861 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00002862 assert(pBt->autoVacuum);
2863 if( !pBt->incrVacuum ){
drhea8ffdf2009-07-22 00:35:23 +00002864 Pgno nFin; /* Number of pages in database after autovacuuming */
2865 Pgno nFree; /* Number of pages on the freelist initially */
drh41d628c2009-07-11 17:04:08 +00002866 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
2867 Pgno iFree; /* The next page to be freed */
2868 int nEntry; /* Number of entries on one ptrmap page */
2869 Pgno nOrig; /* Database size before freeing */
danielk1977687566d2004-11-02 12:56:41 +00002870
drh41d628c2009-07-11 17:04:08 +00002871 nOrig = pagerPagecount(pBt);
danielk1977ef165ce2009-04-06 17:50:03 +00002872 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
2873 /* It is not possible to create a database for which the final page
2874 ** is either a pointer-map page or the pending-byte page. If one
2875 ** is encountered, this indicates corruption.
2876 */
danielk19773460d192008-12-27 15:23:13 +00002877 return SQLITE_CORRUPT_BKPT;
2878 }
danielk1977ef165ce2009-04-06 17:50:03 +00002879
danielk19773460d192008-12-27 15:23:13 +00002880 nFree = get4byte(&pBt->pPage1->aData[36]);
drh41d628c2009-07-11 17:04:08 +00002881 nEntry = pBt->usableSize/5;
2882 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
danielk19773460d192008-12-27 15:23:13 +00002883 nFin = nOrig - nFree - nPtrmap;
danielk1977ef165ce2009-04-06 17:50:03 +00002884 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
danielk19773460d192008-12-27 15:23:13 +00002885 nFin--;
2886 }
2887 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
2888 nFin--;
danielk1977dddbcdc2007-04-26 14:42:34 +00002889 }
drhc5e47ac2009-06-04 00:11:56 +00002890 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
danielk1977687566d2004-11-02 12:56:41 +00002891
danielk19773460d192008-12-27 15:23:13 +00002892 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
2893 rc = incrVacuumStep(pBt, nFin, iFree);
danielk1977dddbcdc2007-04-26 14:42:34 +00002894 }
danielk19773460d192008-12-27 15:23:13 +00002895 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00002896 rc = SQLITE_OK;
danielk19773460d192008-12-27 15:23:13 +00002897 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
2898 put4byte(&pBt->pPage1->aData[32], 0);
2899 put4byte(&pBt->pPage1->aData[36], 0);
2900 sqlite3PagerTruncateImage(pBt->pPager, nFin);
danielk1977dddbcdc2007-04-26 14:42:34 +00002901 }
2902 if( rc!=SQLITE_OK ){
2903 sqlite3PagerRollback(pPager);
2904 }
danielk1977687566d2004-11-02 12:56:41 +00002905 }
2906
danielk19773b8a05f2007-03-19 17:44:26 +00002907 assert( nRef==sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00002908 return rc;
2909}
danielk1977dddbcdc2007-04-26 14:42:34 +00002910
danielk1977a50d9aa2009-06-08 14:49:45 +00002911#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
2912# define setChildPtrmaps(x) SQLITE_OK
2913#endif
danielk1977687566d2004-11-02 12:56:41 +00002914
2915/*
drh80e35f42007-03-30 14:06:34 +00002916** This routine does the first phase of a two-phase commit. This routine
2917** causes a rollback journal to be created (if it does not already exist)
2918** and populated with enough information so that if a power loss occurs
2919** the database can be restored to its original state by playing back
2920** the journal. Then the contents of the journal are flushed out to
2921** the disk. After the journal is safely on oxide, the changes to the
2922** database are written into the database file and flushed to oxide.
2923** At the end of this call, the rollback journal still exists on the
2924** disk and we are still holding all locks, so the transaction has not
drh51898cf2009-04-19 20:51:06 +00002925** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
drh80e35f42007-03-30 14:06:34 +00002926** commit process.
2927**
2928** This call is a no-op if no write-transaction is currently active on pBt.
2929**
2930** Otherwise, sync the database file for the btree pBt. zMaster points to
2931** the name of a master journal file that should be written into the
2932** individual journal file, or is NULL, indicating no master journal file
2933** (single database transaction).
2934**
2935** When this is called, the master journal should already have been
2936** created, populated with this journal pointer and synced to disk.
2937**
2938** Once this is routine has returned, the only thing required to commit
2939** the write-transaction for this database file is to delete the journal.
2940*/
2941int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
2942 int rc = SQLITE_OK;
2943 if( p->inTrans==TRANS_WRITE ){
2944 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002945 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00002946#ifndef SQLITE_OMIT_AUTOVACUUM
2947 if( pBt->autoVacuum ){
danielk19773460d192008-12-27 15:23:13 +00002948 rc = autoVacuumCommit(pBt);
drh80e35f42007-03-30 14:06:34 +00002949 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00002950 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002951 return rc;
2952 }
2953 }
2954#endif
drh49b9d332009-01-02 18:10:42 +00002955 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
drhd677b3d2007-08-20 22:48:41 +00002956 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00002957 }
2958 return rc;
2959}
2960
2961/*
danielk197794b30732009-07-02 17:21:57 +00002962** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
2963** at the conclusion of a transaction.
2964*/
2965static void btreeEndTransaction(Btree *p){
2966 BtShared *pBt = p->pBt;
2967 BtCursor *pCsr;
2968 assert( sqlite3BtreeHoldsMutex(p) );
2969
2970 /* Search for a cursor held open by this b-tree connection. If one exists,
2971 ** then the transaction will be downgraded to a read-only transaction
2972 ** instead of actually concluded. A subsequent call to CommitPhaseTwo()
2973 ** or Rollback() will finish the transaction and unlock the database. */
2974 for(pCsr=pBt->pCursor; pCsr && pCsr->pBtree!=p; pCsr=pCsr->pNext);
2975 assert( pCsr==0 || p->inTrans>TRANS_NONE );
2976
2977 btreeClearHasContent(pBt);
2978 if( pCsr ){
2979 downgradeAllSharedCacheTableLocks(p);
2980 p->inTrans = TRANS_READ;
2981 }else{
2982 /* If the handle had any kind of transaction open, decrement the
2983 ** transaction count of the shared btree. If the transaction count
2984 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
2985 ** call below will unlock the pager. */
2986 if( p->inTrans!=TRANS_NONE ){
2987 clearAllSharedCacheTableLocks(p);
2988 pBt->nTransaction--;
2989 if( 0==pBt->nTransaction ){
2990 pBt->inTransaction = TRANS_NONE;
2991 }
2992 }
2993
2994 /* Set the current transaction state to TRANS_NONE and unlock the
2995 ** pager if this call closed the only read or write transaction. */
2996 p->inTrans = TRANS_NONE;
2997 unlockBtreeIfUnused(pBt);
2998 }
2999
3000 btreeIntegrity(p);
3001}
3002
3003/*
drh2aa679f2001-06-25 02:11:07 +00003004** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00003005**
drh6e345992007-03-30 11:12:08 +00003006** This routine implements the second phase of a 2-phase commit. The
drh51898cf2009-04-19 20:51:06 +00003007** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
3008** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
3009** routine did all the work of writing information out to disk and flushing the
drh6e345992007-03-30 11:12:08 +00003010** contents so that they are written onto the disk platter. All this
drh51898cf2009-04-19 20:51:06 +00003011** routine has to do is delete or truncate or zero the header in the
3012** the rollback journal (which causes the transaction to commit) and
3013** drop locks.
drh6e345992007-03-30 11:12:08 +00003014**
drh5e00f6c2001-09-13 13:46:56 +00003015** This will release the write lock on the database file. If there
3016** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00003017*/
drh80e35f42007-03-30 14:06:34 +00003018int sqlite3BtreeCommitPhaseTwo(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00003019 BtShared *pBt = p->pBt;
3020
drhd677b3d2007-08-20 22:48:41 +00003021 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003022 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003023
3024 /* If the handle has a write-transaction open, commit the shared-btrees
3025 ** transaction and set the shared state to TRANS_READ.
3026 */
3027 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00003028 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003029 assert( pBt->inTransaction==TRANS_WRITE );
3030 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00003031 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
danielk19777f7bc662006-01-23 13:47:47 +00003032 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00003033 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00003034 return rc;
3035 }
danielk1977aef0bf62005-12-30 16:28:01 +00003036 pBt->inTransaction = TRANS_READ;
danielk1977ee5741e2004-05-31 10:01:34 +00003037 }
danielk1977aef0bf62005-12-30 16:28:01 +00003038
danielk197794b30732009-07-02 17:21:57 +00003039 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00003040 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00003041 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003042}
3043
drh80e35f42007-03-30 14:06:34 +00003044/*
3045** Do both phases of a commit.
3046*/
3047int sqlite3BtreeCommit(Btree *p){
3048 int rc;
drhd677b3d2007-08-20 22:48:41 +00003049 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00003050 rc = sqlite3BtreeCommitPhaseOne(p, 0);
3051 if( rc==SQLITE_OK ){
3052 rc = sqlite3BtreeCommitPhaseTwo(p);
3053 }
drhd677b3d2007-08-20 22:48:41 +00003054 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003055 return rc;
3056}
3057
danielk1977fbcd5852004-06-15 02:44:18 +00003058#ifndef NDEBUG
3059/*
3060** Return the number of write-cursors open on this handle. This is for use
3061** in assert() expressions, so it is only compiled if NDEBUG is not
3062** defined.
drhfb982642007-08-30 01:19:59 +00003063**
3064** For the purposes of this routine, a write-cursor is any cursor that
3065** is capable of writing to the databse. That means the cursor was
3066** originally opened for writing and the cursor has not be disabled
3067** by having its state changed to CURSOR_FAULT.
danielk1977fbcd5852004-06-15 02:44:18 +00003068*/
danielk1977aef0bf62005-12-30 16:28:01 +00003069static int countWriteCursors(BtShared *pBt){
danielk1977fbcd5852004-06-15 02:44:18 +00003070 BtCursor *pCur;
3071 int r = 0;
3072 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drhfb982642007-08-30 01:19:59 +00003073 if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
danielk1977fbcd5852004-06-15 02:44:18 +00003074 }
3075 return r;
3076}
3077#endif
3078
drhc39e0002004-05-07 23:50:57 +00003079/*
drhfb982642007-08-30 01:19:59 +00003080** This routine sets the state to CURSOR_FAULT and the error
3081** code to errCode for every cursor on BtShared that pBtree
3082** references.
3083**
3084** Every cursor is tripped, including cursors that belong
3085** to other database connections that happen to be sharing
3086** the cache with pBtree.
3087**
3088** This routine gets called when a rollback occurs.
3089** All cursors using the same cache must be tripped
3090** to prevent them from trying to use the btree after
3091** the rollback. The rollback may have deleted tables
3092** or moved root pages, so it is not sufficient to
3093** save the state of the cursor. The cursor must be
3094** invalidated.
3095*/
3096void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
3097 BtCursor *p;
3098 sqlite3BtreeEnter(pBtree);
3099 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
danielk1977bc2ca9e2008-11-13 14:28:28 +00003100 int i;
danielk1977be51a652008-10-08 17:58:48 +00003101 sqlite3BtreeClearCursor(p);
drhfb982642007-08-30 01:19:59 +00003102 p->eState = CURSOR_FAULT;
drh4c301aa2009-07-15 17:25:45 +00003103 p->skipNext = errCode;
danielk1977bc2ca9e2008-11-13 14:28:28 +00003104 for(i=0; i<=p->iPage; i++){
3105 releasePage(p->apPage[i]);
3106 p->apPage[i] = 0;
3107 }
drhfb982642007-08-30 01:19:59 +00003108 }
3109 sqlite3BtreeLeave(pBtree);
3110}
3111
3112/*
drhecdc7532001-09-23 02:35:53 +00003113** Rollback the transaction in progress. All cursors will be
3114** invalided by this operation. Any attempt to use a cursor
3115** that was open at the beginning of this operation will result
3116** in an error.
drh5e00f6c2001-09-13 13:46:56 +00003117**
3118** This will release the write lock on the database file. If there
3119** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00003120*/
danielk1977aef0bf62005-12-30 16:28:01 +00003121int sqlite3BtreeRollback(Btree *p){
danielk19778d34dfd2006-01-24 16:37:57 +00003122 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003123 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00003124 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00003125
drhd677b3d2007-08-20 22:48:41 +00003126 sqlite3BtreeEnter(p);
danielk19772b8c13e2006-01-24 14:21:24 +00003127 rc = saveAllCursors(pBt, 0, 0);
danielk19778d34dfd2006-01-24 16:37:57 +00003128#ifndef SQLITE_OMIT_SHARED_CACHE
danielk19772b8c13e2006-01-24 14:21:24 +00003129 if( rc!=SQLITE_OK ){
shanebe217792009-03-05 04:20:31 +00003130 /* This is a horrible situation. An IO or malloc() error occurred whilst
danielk19778d34dfd2006-01-24 16:37:57 +00003131 ** trying to save cursor positions. If this is an automatic rollback (as
3132 ** the result of a constraint, malloc() failure or IO error) then
3133 ** the cache may be internally inconsistent (not contain valid trees) so
3134 ** we cannot simply return the error to the caller. Instead, abort
3135 ** all queries that may be using any of the cursors that failed to save.
3136 */
drhfb982642007-08-30 01:19:59 +00003137 sqlite3BtreeTripAllCursors(p, rc);
danielk19772b8c13e2006-01-24 14:21:24 +00003138 }
danielk19778d34dfd2006-01-24 16:37:57 +00003139#endif
danielk1977aef0bf62005-12-30 16:28:01 +00003140 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003141
3142 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00003143 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00003144
danielk19778d34dfd2006-01-24 16:37:57 +00003145 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00003146 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00003147 if( rc2!=SQLITE_OK ){
3148 rc = rc2;
3149 }
3150
drh24cd67e2004-05-10 16:18:47 +00003151 /* The rollback may have destroyed the pPage1->aData value. So
danielk197730548662009-07-09 05:07:37 +00003152 ** call btreeGetPage() on page 1 again to make
drh16a9b832007-05-05 18:39:25 +00003153 ** sure pPage1->aData is set correctly. */
danielk197730548662009-07-09 05:07:37 +00003154 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh24cd67e2004-05-10 16:18:47 +00003155 releasePage(pPage1);
3156 }
danielk1977fbcd5852004-06-15 02:44:18 +00003157 assert( countWriteCursors(pBt)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00003158 pBt->inTransaction = TRANS_READ;
drh24cd67e2004-05-10 16:18:47 +00003159 }
danielk1977aef0bf62005-12-30 16:28:01 +00003160
danielk197794b30732009-07-02 17:21:57 +00003161 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00003162 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00003163 return rc;
3164}
3165
3166/*
danielk1977bd434552009-03-18 10:33:00 +00003167** Start a statement subtransaction. The subtransaction can can be rolled
3168** back independently of the main transaction. You must start a transaction
3169** before starting a subtransaction. The subtransaction is ended automatically
3170** if the main transaction commits or rolls back.
drhab01f612004-05-22 02:55:23 +00003171**
3172** Statement subtransactions are used around individual SQL statements
3173** that are contained within a BEGIN...COMMIT block. If a constraint
3174** error occurs within the statement, the effect of that one statement
3175** can be rolled back without having to rollback the entire transaction.
danielk1977bd434552009-03-18 10:33:00 +00003176**
3177** A statement sub-transaction is implemented as an anonymous savepoint. The
3178** value passed as the second parameter is the total number of savepoints,
3179** including the new anonymous savepoint, open on the B-Tree. i.e. if there
3180** are no active savepoints and no other statement-transactions open,
3181** iStatement is 1. This anonymous savepoint can be released or rolled back
3182** using the sqlite3BtreeSavepoint() function.
drh663fc632002-02-02 18:49:19 +00003183*/
danielk1977bd434552009-03-18 10:33:00 +00003184int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
drh663fc632002-02-02 18:49:19 +00003185 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003186 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003187 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00003188 assert( p->inTrans==TRANS_WRITE );
drh64022502009-01-09 14:11:04 +00003189 assert( pBt->readOnly==0 );
danielk1977bd434552009-03-18 10:33:00 +00003190 assert( iStatement>0 );
3191 assert( iStatement>p->db->nSavepoint );
3192 if( NEVER(p->inTrans!=TRANS_WRITE || pBt->readOnly) ){
drh64022502009-01-09 14:11:04 +00003193 rc = SQLITE_INTERNAL;
drhd677b3d2007-08-20 22:48:41 +00003194 }else{
3195 assert( pBt->inTransaction==TRANS_WRITE );
drh64022502009-01-09 14:11:04 +00003196 /* At the pager level, a statement transaction is a savepoint with
3197 ** an index greater than all savepoints created explicitly using
3198 ** SQL statements. It is illegal to open, release or rollback any
3199 ** such savepoints while the statement transaction savepoint is active.
3200 */
danielk1977bd434552009-03-18 10:33:00 +00003201 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
danielk197797a227c2006-01-20 16:32:04 +00003202 }
drhd677b3d2007-08-20 22:48:41 +00003203 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00003204 return rc;
3205}
3206
3207/*
danielk1977fd7f0452008-12-17 17:30:26 +00003208** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
3209** or SAVEPOINT_RELEASE. This function either releases or rolls back the
danielk197712dd5492008-12-18 15:45:07 +00003210** savepoint identified by parameter iSavepoint, depending on the value
3211** of op.
3212**
3213** Normally, iSavepoint is greater than or equal to zero. However, if op is
3214** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
3215** contents of the entire transaction are rolled back. This is different
3216** from a normal transaction rollback, as no locks are released and the
3217** transaction remains open.
danielk1977fd7f0452008-12-17 17:30:26 +00003218*/
3219int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
3220 int rc = SQLITE_OK;
3221 if( p && p->inTrans==TRANS_WRITE ){
3222 BtShared *pBt = p->pBt;
danielk1977fd7f0452008-12-17 17:30:26 +00003223 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
3224 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
3225 sqlite3BtreeEnter(p);
danielk1977fd7f0452008-12-17 17:30:26 +00003226 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
drh9f0bbf92009-01-02 21:08:09 +00003227 if( rc==SQLITE_OK ){
3228 rc = newDatabase(pBt);
3229 }
danielk1977fd7f0452008-12-17 17:30:26 +00003230 sqlite3BtreeLeave(p);
3231 }
3232 return rc;
3233}
3234
3235/*
drh8b2f49b2001-06-08 00:21:52 +00003236** Create a new cursor for the BTree whose root is on the page
danielk19773e8add92009-07-04 17:16:00 +00003237** iTable. If a read-only cursor is requested, it is assumed that
3238** the caller already has at least a read-only transaction open
3239** on the database already. If a write-cursor is requested, then
3240** the caller is assumed to have an open write transaction.
drh1bee3d72001-10-15 00:44:35 +00003241**
3242** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00003243** If wrFlag==1, then the cursor can be used for reading or for
3244** writing if other conditions for writing are also met. These
3245** are the conditions that must be met in order for writing to
3246** be allowed:
drh6446c4d2001-12-15 14:22:18 +00003247**
drhf74b8d92002-09-01 23:20:45 +00003248** 1: The cursor must have been opened with wrFlag==1
3249**
drhfe5d71d2007-03-19 11:54:10 +00003250** 2: Other database connections that share the same pager cache
3251** but which are not in the READ_UNCOMMITTED state may not have
3252** cursors open with wrFlag==0 on the same table. Otherwise
3253** the changes made by this write cursor would be visible to
3254** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00003255**
3256** 3: The database must be writable (not on read-only media)
3257**
3258** 4: There must be an active transaction.
3259**
drh6446c4d2001-12-15 14:22:18 +00003260** No checking is done to make sure that page iTable really is the
3261** root page of a b-tree. If it is not, then the cursor acquired
3262** will not work correctly.
danielk197771d5d2c2008-09-29 11:49:47 +00003263**
3264** It is assumed that the sqlite3BtreeCursorSize() bytes of memory
3265** pointed to by pCur have been zeroed by the caller.
drha059ad02001-04-17 20:09:11 +00003266*/
drhd677b3d2007-08-20 22:48:41 +00003267static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00003268 Btree *p, /* The btree */
3269 int iTable, /* Root page of table to open */
3270 int wrFlag, /* 1 to write. 0 read-only */
3271 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
3272 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00003273){
danielk19773e8add92009-07-04 17:16:00 +00003274 BtShared *pBt = p->pBt; /* Shared b-tree handle */
drhecdc7532001-09-23 02:35:53 +00003275
drh1fee73e2007-08-29 04:00:57 +00003276 assert( sqlite3BtreeHoldsMutex(p) );
drhf49661a2008-12-10 16:45:50 +00003277 assert( wrFlag==0 || wrFlag==1 );
danielk197796d48e92009-06-29 06:00:37 +00003278
danielk1977602b4662009-07-02 07:47:33 +00003279 /* The following assert statements verify that if this is a sharable
3280 ** b-tree database, the connection is holding the required table locks,
3281 ** and that no other connection has any open cursor that conflicts with
3282 ** this lock. */
3283 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
danielk197796d48e92009-06-29 06:00:37 +00003284 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
3285
danielk19773e8add92009-07-04 17:16:00 +00003286 /* Assert that the caller has opened the required transaction. */
3287 assert( p->inTrans>TRANS_NONE );
3288 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
3289 assert( pBt->pPage1 && pBt->pPage1->aData );
3290
danielk197796d48e92009-06-29 06:00:37 +00003291 if( NEVER(wrFlag && pBt->readOnly) ){
3292 return SQLITE_READONLY;
drha0c9a112004-03-10 13:42:37 +00003293 }
danielk19773e8add92009-07-04 17:16:00 +00003294 if( iTable==1 && pagerPagecount(pBt)==0 ){
3295 return SQLITE_EMPTY;
3296 }
danielk1977aef0bf62005-12-30 16:28:01 +00003297
danielk1977aef0bf62005-12-30 16:28:01 +00003298 /* Now that no other errors can occur, finish filling in the BtCursor
danielk19773e8add92009-07-04 17:16:00 +00003299 ** variables and link the cursor into the BtShared list. */
danielk1977172114a2009-07-07 15:47:12 +00003300 pCur->pgnoRoot = (Pgno)iTable;
3301 pCur->iPage = -1;
drh1e968a02008-03-25 00:22:21 +00003302 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00003303 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00003304 pCur->pBt = pBt;
drhf49661a2008-12-10 16:45:50 +00003305 pCur->wrFlag = (u8)wrFlag;
drha059ad02001-04-17 20:09:11 +00003306 pCur->pNext = pBt->pCursor;
3307 if( pCur->pNext ){
3308 pCur->pNext->pPrev = pCur;
3309 }
3310 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00003311 pCur->eState = CURSOR_INVALID;
drh7f751222009-03-17 22:33:00 +00003312 pCur->cachedRowid = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00003313 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003314}
drhd677b3d2007-08-20 22:48:41 +00003315int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00003316 Btree *p, /* The btree */
3317 int iTable, /* Root page of table to open */
3318 int wrFlag, /* 1 to write. 0 read-only */
3319 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
3320 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00003321){
3322 int rc;
3323 sqlite3BtreeEnter(p);
danielk1977cd3e8f72008-03-25 09:47:35 +00003324 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
drhd677b3d2007-08-20 22:48:41 +00003325 sqlite3BtreeLeave(p);
3326 return rc;
3327}
drh7f751222009-03-17 22:33:00 +00003328
3329/*
3330** Return the size of a BtCursor object in bytes.
3331**
3332** This interfaces is needed so that users of cursors can preallocate
3333** sufficient storage to hold a cursor. The BtCursor object is opaque
3334** to users so they cannot do the sizeof() themselves - they must call
3335** this routine.
3336*/
3337int sqlite3BtreeCursorSize(void){
danielk1977cd3e8f72008-03-25 09:47:35 +00003338 return sizeof(BtCursor);
3339}
3340
drh7f751222009-03-17 22:33:00 +00003341/*
3342** Set the cached rowid value of every cursor in the same database file
3343** as pCur and having the same root page number as pCur. The value is
3344** set to iRowid.
3345**
3346** Only positive rowid values are considered valid for this cache.
3347** The cache is initialized to zero, indicating an invalid cache.
3348** A btree will work fine with zero or negative rowids. We just cannot
3349** cache zero or negative rowids, which means tables that use zero or
3350** negative rowids might run a little slower. But in practice, zero
3351** or negative rowids are very uncommon so this should not be a problem.
3352*/
3353void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
3354 BtCursor *p;
3355 for(p=pCur->pBt->pCursor; p; p=p->pNext){
3356 if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
3357 }
3358 assert( pCur->cachedRowid==iRowid );
3359}
drhd677b3d2007-08-20 22:48:41 +00003360
drh7f751222009-03-17 22:33:00 +00003361/*
3362** Return the cached rowid for the given cursor. A negative or zero
3363** return value indicates that the rowid cache is invalid and should be
3364** ignored. If the rowid cache has never before been set, then a
3365** zero is returned.
3366*/
3367sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
3368 return pCur->cachedRowid;
3369}
drha059ad02001-04-17 20:09:11 +00003370
3371/*
drh5e00f6c2001-09-13 13:46:56 +00003372** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00003373** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00003374*/
drh3aac2dd2004-04-26 14:10:20 +00003375int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00003376 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00003377 if( pBtree ){
danielk197771d5d2c2008-09-29 11:49:47 +00003378 int i;
danielk1977cd3e8f72008-03-25 09:47:35 +00003379 BtShared *pBt = pCur->pBt;
3380 sqlite3BtreeEnter(pBtree);
danielk1977be51a652008-10-08 17:58:48 +00003381 sqlite3BtreeClearCursor(pCur);
danielk1977cd3e8f72008-03-25 09:47:35 +00003382 if( pCur->pPrev ){
3383 pCur->pPrev->pNext = pCur->pNext;
3384 }else{
3385 pBt->pCursor = pCur->pNext;
3386 }
3387 if( pCur->pNext ){
3388 pCur->pNext->pPrev = pCur->pPrev;
3389 }
danielk197771d5d2c2008-09-29 11:49:47 +00003390 for(i=0; i<=pCur->iPage; i++){
3391 releasePage(pCur->apPage[i]);
3392 }
danielk1977cd3e8f72008-03-25 09:47:35 +00003393 unlockBtreeIfUnused(pBt);
3394 invalidateOverflowCache(pCur);
3395 /* sqlite3_free(pCur); */
3396 sqlite3BtreeLeave(pBtree);
drha059ad02001-04-17 20:09:11 +00003397 }
drh8c42ca92001-06-22 19:15:00 +00003398 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003399}
3400
drh5e2f8b92001-05-28 00:41:15 +00003401/*
drh86057612007-06-26 01:04:48 +00003402** Make sure the BtCursor* given in the argument has a valid
3403** BtCursor.info structure. If it is not already valid, call
danielk197730548662009-07-09 05:07:37 +00003404** btreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00003405**
3406** BtCursor.info is a cache of the information in the current cell.
danielk197730548662009-07-09 05:07:37 +00003407** Using this cache reduces the number of calls to btreeParseCell().
drh86057612007-06-26 01:04:48 +00003408**
3409** 2007-06-25: There is a bug in some versions of MSVC that cause the
3410** compiler to crash when getCellInfo() is implemented as a macro.
3411** But there is a measureable speed advantage to using the macro on gcc
3412** (when less compiler optimizations like -Os or -O0 are used and the
3413** compiler is not doing agressive inlining.) So we use a real function
3414** for MSVC and a macro for everything else. Ticket #2457.
drh9188b382004-05-14 21:12:22 +00003415*/
drh9188b382004-05-14 21:12:22 +00003416#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00003417 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00003418 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00003419 int iPage = pCur->iPage;
drh51c6d962004-06-06 00:42:25 +00003420 memset(&info, 0, sizeof(info));
danielk197730548662009-07-09 05:07:37 +00003421 btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
drh9188b382004-05-14 21:12:22 +00003422 assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00003423 }
danielk19771cc5ed82007-05-16 17:28:43 +00003424#else
3425 #define assertCellInfo(x)
3426#endif
drh86057612007-06-26 01:04:48 +00003427#ifdef _MSC_VER
3428 /* Use a real function in MSVC to work around bugs in that compiler. */
3429 static void getCellInfo(BtCursor *pCur){
3430 if( pCur->info.nSize==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003431 int iPage = pCur->iPage;
danielk197730548662009-07-09 05:07:37 +00003432 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
drha2c20e42008-03-29 16:01:04 +00003433 pCur->validNKey = 1;
drh86057612007-06-26 01:04:48 +00003434 }else{
3435 assertCellInfo(pCur);
3436 }
3437 }
3438#else /* if not _MSC_VER */
3439 /* Use a macro in all other compilers so that the function is inlined */
danielk197771d5d2c2008-09-29 11:49:47 +00003440#define getCellInfo(pCur) \
3441 if( pCur->info.nSize==0 ){ \
3442 int iPage = pCur->iPage; \
danielk197730548662009-07-09 05:07:37 +00003443 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
danielk197771d5d2c2008-09-29 11:49:47 +00003444 pCur->validNKey = 1; \
3445 }else{ \
3446 assertCellInfo(pCur); \
drh86057612007-06-26 01:04:48 +00003447 }
3448#endif /* _MSC_VER */
drh9188b382004-05-14 21:12:22 +00003449
drhea8ffdf2009-07-22 00:35:23 +00003450#ifndef NDEBUG /* The next routine used only within assert() statements */
3451/*
3452** Return true if the given BtCursor is valid. A valid cursor is one
3453** that is currently pointing to a row in a (non-empty) table.
3454** This is a verification routine is used only within assert() statements.
3455*/
3456int sqlite3BtreeCursorIsValid(BtCursor *pCur){
3457 return pCur && pCur->eState==CURSOR_VALID;
3458}
3459#endif /* NDEBUG */
3460
drh9188b382004-05-14 21:12:22 +00003461/*
drh3aac2dd2004-04-26 14:10:20 +00003462** Set *pSize to the size of the buffer needed to hold the value of
3463** the key for the current entry. If the cursor is not pointing
3464** to a valid entry, *pSize is set to 0.
3465**
drh4b70f112004-05-02 21:12:19 +00003466** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00003467** itself, not the number of bytes in the key.
drhea8ffdf2009-07-22 00:35:23 +00003468**
3469** The caller must position the cursor prior to invoking this routine.
3470**
3471** This routine cannot fail. It always returns SQLITE_OK.
drh7e3b0a02001-04-28 16:52:40 +00003472*/
drh4a1c3802004-05-12 15:15:47 +00003473int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drh1fee73e2007-08-29 04:00:57 +00003474 assert( cursorHoldsMutex(pCur) );
drhea8ffdf2009-07-22 00:35:23 +00003475 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3476 if( pCur->eState!=CURSOR_VALID ){
3477 *pSize = 0;
3478 }else{
3479 getCellInfo(pCur);
3480 *pSize = pCur->info.nKey;
drh72f82862001-05-24 21:06:34 +00003481 }
drhea8ffdf2009-07-22 00:35:23 +00003482 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003483}
drh2af926b2001-05-15 00:39:25 +00003484
drh72f82862001-05-24 21:06:34 +00003485/*
drh0e1c19e2004-05-11 00:58:56 +00003486** Set *pSize to the number of bytes of data in the entry the
drhea8ffdf2009-07-22 00:35:23 +00003487** cursor currently points to.
3488**
3489** The caller must guarantee that the cursor is pointing to a non-NULL
3490** valid entry. In other words, the calling procedure must guarantee
3491** that the cursor has Cursor.eState==CURSOR_VALID.
3492**
3493** Failure is not possible. This function always returns SQLITE_OK.
3494** It might just as well be a procedure (returning void) but we continue
3495** to return an integer result code for historical reasons.
drh0e1c19e2004-05-11 00:58:56 +00003496*/
3497int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drh1fee73e2007-08-29 04:00:57 +00003498 assert( cursorHoldsMutex(pCur) );
drhea8ffdf2009-07-22 00:35:23 +00003499 assert( pCur->eState==CURSOR_VALID );
3500 getCellInfo(pCur);
3501 *pSize = pCur->info.nData;
3502 return SQLITE_OK;
drh0e1c19e2004-05-11 00:58:56 +00003503}
3504
3505/*
danielk1977d04417962007-05-02 13:16:30 +00003506** Given the page number of an overflow page in the database (parameter
3507** ovfl), this function finds the page number of the next page in the
3508** linked list of overflow pages. If possible, it uses the auto-vacuum
3509** pointer-map data instead of reading the content of page ovfl to do so.
3510**
3511** If an error occurs an SQLite error code is returned. Otherwise:
3512**
danielk1977bea2a942009-01-20 17:06:27 +00003513** The page number of the next overflow page in the linked list is
3514** written to *pPgnoNext. If page ovfl is the last page in its linked
3515** list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003516**
danielk1977bea2a942009-01-20 17:06:27 +00003517** If ppPage is not NULL, and a reference to the MemPage object corresponding
3518** to page number pOvfl was obtained, then *ppPage is set to point to that
3519** reference. It is the responsibility of the caller to call releasePage()
3520** on *ppPage to free the reference. In no reference was obtained (because
3521** the pointer-map was used to obtain the value for *pPgnoNext), then
3522** *ppPage is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003523*/
3524static int getOverflowPage(
drhfa3be902009-07-07 02:44:07 +00003525 BtShared *pBt, /* The database file */
3526 Pgno ovfl, /* Current overflow page number */
danielk1977bea2a942009-01-20 17:06:27 +00003527 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
danielk1977d04417962007-05-02 13:16:30 +00003528 Pgno *pPgnoNext /* OUT: Next overflow page number */
3529){
3530 Pgno next = 0;
danielk1977bea2a942009-01-20 17:06:27 +00003531 MemPage *pPage = 0;
drh1bd10f82008-12-10 21:19:56 +00003532 int rc = SQLITE_OK;
danielk1977d04417962007-05-02 13:16:30 +00003533
drh1fee73e2007-08-29 04:00:57 +00003534 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bea2a942009-01-20 17:06:27 +00003535 assert(pPgnoNext);
danielk1977d04417962007-05-02 13:16:30 +00003536
3537#ifndef SQLITE_OMIT_AUTOVACUUM
3538 /* Try to find the next page in the overflow list using the
3539 ** autovacuum pointer-map pages. Guess that the next page in
3540 ** the overflow list is page number (ovfl+1). If that guess turns
3541 ** out to be wrong, fall back to loading the data of page
3542 ** number ovfl to determine the next page number.
3543 */
3544 if( pBt->autoVacuum ){
3545 Pgno pgno;
3546 Pgno iGuess = ovfl+1;
3547 u8 eType;
3548
3549 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
3550 iGuess++;
3551 }
3552
danielk197789d40042008-11-17 14:20:56 +00003553 if( iGuess<=pagerPagecount(pBt) ){
danielk1977d04417962007-05-02 13:16:30 +00003554 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
danielk1977bea2a942009-01-20 17:06:27 +00003555 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
danielk1977d04417962007-05-02 13:16:30 +00003556 next = iGuess;
danielk1977bea2a942009-01-20 17:06:27 +00003557 rc = SQLITE_DONE;
danielk1977d04417962007-05-02 13:16:30 +00003558 }
3559 }
3560 }
3561#endif
3562
danielk1977d8a3f3d2009-07-11 11:45:23 +00003563 assert( next==0 || rc==SQLITE_DONE );
danielk1977bea2a942009-01-20 17:06:27 +00003564 if( rc==SQLITE_OK ){
danielk197730548662009-07-09 05:07:37 +00003565 rc = btreeGetPage(pBt, ovfl, &pPage, 0);
danielk1977d8a3f3d2009-07-11 11:45:23 +00003566 assert( rc==SQLITE_OK || pPage==0 );
3567 if( rc==SQLITE_OK ){
danielk1977d04417962007-05-02 13:16:30 +00003568 next = get4byte(pPage->aData);
3569 }
danielk1977443c0592009-01-16 15:21:05 +00003570 }
danielk197745d68822009-01-16 16:23:38 +00003571
danielk1977bea2a942009-01-20 17:06:27 +00003572 *pPgnoNext = next;
3573 if( ppPage ){
3574 *ppPage = pPage;
3575 }else{
3576 releasePage(pPage);
3577 }
3578 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
danielk1977d04417962007-05-02 13:16:30 +00003579}
3580
danielk1977da107192007-05-04 08:32:13 +00003581/*
3582** Copy data from a buffer to a page, or from a page to a buffer.
3583**
3584** pPayload is a pointer to data stored on database page pDbPage.
3585** If argument eOp is false, then nByte bytes of data are copied
3586** from pPayload to the buffer pointed at by pBuf. If eOp is true,
3587** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
3588** of data are copied from the buffer pBuf to pPayload.
3589**
3590** SQLITE_OK is returned on success, otherwise an error code.
3591*/
3592static int copyPayload(
3593 void *pPayload, /* Pointer to page data */
3594 void *pBuf, /* Pointer to buffer */
3595 int nByte, /* Number of bytes to copy */
3596 int eOp, /* 0 -> copy from page, 1 -> copy to page */
3597 DbPage *pDbPage /* Page containing pPayload */
3598){
3599 if( eOp ){
3600 /* Copy data from buffer to page (a write operation) */
3601 int rc = sqlite3PagerWrite(pDbPage);
3602 if( rc!=SQLITE_OK ){
3603 return rc;
3604 }
3605 memcpy(pPayload, pBuf, nByte);
3606 }else{
3607 /* Copy data from page to buffer (a read operation) */
3608 memcpy(pBuf, pPayload, nByte);
3609 }
3610 return SQLITE_OK;
3611}
danielk1977d04417962007-05-02 13:16:30 +00003612
3613/*
danielk19779f8d6402007-05-02 17:48:45 +00003614** This function is used to read or overwrite payload information
3615** for the entry that the pCur cursor is pointing to. If the eOp
3616** parameter is 0, this is a read operation (data copied into
3617** buffer pBuf). If it is non-zero, a write (data copied from
3618** buffer pBuf).
3619**
3620** A total of "amt" bytes are read or written beginning at "offset".
3621** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00003622**
drh3bcdfd22009-07-12 02:32:21 +00003623** The content being read or written might appear on the main page
3624** or be scattered out on multiple overflow pages.
danielk1977da107192007-05-04 08:32:13 +00003625**
danielk1977dcbb5d32007-05-04 18:36:44 +00003626** If the BtCursor.isIncrblobHandle flag is set, and the current
danielk1977da107192007-05-04 08:32:13 +00003627** cursor entry uses one or more overflow pages, this function
3628** allocates space for and lazily popluates the overflow page-list
3629** cache array (BtCursor.aOverflow). Subsequent calls use this
3630** cache to make seeking to the supplied offset more efficient.
3631**
3632** Once an overflow page-list cache has been allocated, it may be
3633** invalidated if some other cursor writes to the same table, or if
3634** the cursor is moved to a different row. Additionally, in auto-vacuum
3635** mode, the following events may invalidate an overflow page-list cache.
3636**
3637** * An incremental vacuum,
3638** * A commit in auto_vacuum="full" mode,
3639** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00003640*/
danielk19779f8d6402007-05-02 17:48:45 +00003641static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00003642 BtCursor *pCur, /* Cursor pointing to entry to read from */
danielk197789d40042008-11-17 14:20:56 +00003643 u32 offset, /* Begin reading this far into payload */
3644 u32 amt, /* Read this many bytes */
drh3aac2dd2004-04-26 14:10:20 +00003645 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00003646 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00003647){
3648 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00003649 int rc = SQLITE_OK;
drhfa1a98a2004-05-14 19:08:17 +00003650 u32 nKey;
danielk19772dec9702007-05-02 16:48:37 +00003651 int iIdx = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00003652 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
danielk19770d065412008-11-12 18:21:36 +00003653 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
drh3aac2dd2004-04-26 14:10:20 +00003654
danielk1977da107192007-05-04 08:32:13 +00003655 assert( pPage );
danielk1977da184232006-01-05 11:34:32 +00003656 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003657 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh1fee73e2007-08-29 04:00:57 +00003658 assert( cursorHoldsMutex(pCur) );
danielk1977da107192007-05-04 08:32:13 +00003659
drh86057612007-06-26 01:04:48 +00003660 getCellInfo(pCur);
drh366fda62006-01-13 02:35:09 +00003661 aPayload = pCur->info.pCell + pCur->info.nHeader;
drhf49661a2008-12-10 16:45:50 +00003662 nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
danielk1977da107192007-05-04 08:32:13 +00003663
drh3bcdfd22009-07-12 02:32:21 +00003664 if( NEVER(offset+amt > nKey+pCur->info.nData)
danielk19770d065412008-11-12 18:21:36 +00003665 || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
3666 ){
danielk1977da107192007-05-04 08:32:13 +00003667 /* Trying to read or write past the end of the data is an error */
danielk197767fd7a92008-09-10 17:53:35 +00003668 return SQLITE_CORRUPT_BKPT;
drh3aac2dd2004-04-26 14:10:20 +00003669 }
danielk1977da107192007-05-04 08:32:13 +00003670
3671 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00003672 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00003673 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00003674 if( a+offset>pCur->info.nLocal ){
3675 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00003676 }
danielk1977da107192007-05-04 08:32:13 +00003677 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00003678 offset = 0;
drha34b6762004-05-07 13:30:42 +00003679 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00003680 amt -= a;
drhdd793422001-06-28 01:54:48 +00003681 }else{
drhfa1a98a2004-05-14 19:08:17 +00003682 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00003683 }
danielk1977da107192007-05-04 08:32:13 +00003684
3685 if( rc==SQLITE_OK && amt>0 ){
danielk197789d40042008-11-17 14:20:56 +00003686 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
danielk1977da107192007-05-04 08:32:13 +00003687 Pgno nextPage;
3688
drhfa1a98a2004-05-14 19:08:17 +00003689 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00003690
danielk19772dec9702007-05-02 16:48:37 +00003691#ifndef SQLITE_OMIT_INCRBLOB
danielk1977dcbb5d32007-05-04 18:36:44 +00003692 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
danielk1977da107192007-05-04 08:32:13 +00003693 ** has not been allocated, allocate it now. The array is sized at
3694 ** one entry for each overflow page in the overflow chain. The
3695 ** page number of the first overflow page is stored in aOverflow[0],
3696 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
3697 ** (the cache is lazily populated).
3698 */
danielk1977dcbb5d32007-05-04 18:36:44 +00003699 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
danielk19772dec9702007-05-02 16:48:37 +00003700 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
drh17435752007-08-16 04:30:38 +00003701 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
drh3bcdfd22009-07-12 02:32:21 +00003702 /* nOvfl is always positive. If it were zero, fetchPayload would have
3703 ** been used instead of this routine. */
3704 if( ALWAYS(nOvfl) && !pCur->aOverflow ){
danielk1977da107192007-05-04 08:32:13 +00003705 rc = SQLITE_NOMEM;
danielk19772dec9702007-05-02 16:48:37 +00003706 }
3707 }
danielk1977da107192007-05-04 08:32:13 +00003708
3709 /* If the overflow page-list cache has been allocated and the
3710 ** entry for the first required overflow page is valid, skip
3711 ** directly to it.
3712 */
danielk19772dec9702007-05-02 16:48:37 +00003713 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
3714 iIdx = (offset/ovflSize);
3715 nextPage = pCur->aOverflow[iIdx];
3716 offset = (offset%ovflSize);
3717 }
3718#endif
danielk1977da107192007-05-04 08:32:13 +00003719
3720 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
3721
3722#ifndef SQLITE_OMIT_INCRBLOB
3723 /* If required, populate the overflow page-list cache. */
3724 if( pCur->aOverflow ){
3725 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
3726 pCur->aOverflow[iIdx] = nextPage;
3727 }
3728#endif
3729
danielk1977d04417962007-05-02 13:16:30 +00003730 if( offset>=ovflSize ){
3731 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00003732 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00003733 ** data is not required. So first try to lookup the overflow
3734 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00003735 ** function.
danielk1977d04417962007-05-02 13:16:30 +00003736 */
danielk19772dec9702007-05-02 16:48:37 +00003737#ifndef SQLITE_OMIT_INCRBLOB
danielk1977da107192007-05-04 08:32:13 +00003738 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
3739 nextPage = pCur->aOverflow[iIdx+1];
3740 } else
danielk19772dec9702007-05-02 16:48:37 +00003741#endif
danielk1977da107192007-05-04 08:32:13 +00003742 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
danielk1977da107192007-05-04 08:32:13 +00003743 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00003744 }else{
danielk19779f8d6402007-05-02 17:48:45 +00003745 /* Need to read this page properly. It contains some of the
3746 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00003747 */
3748 DbPage *pDbPage;
danielk1977cfe9a692004-06-16 12:00:29 +00003749 int a = amt;
danielk1977d04417962007-05-02 13:16:30 +00003750 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
danielk1977da107192007-05-04 08:32:13 +00003751 if( rc==SQLITE_OK ){
3752 aPayload = sqlite3PagerGetData(pDbPage);
3753 nextPage = get4byte(aPayload);
3754 if( a + offset > ovflSize ){
3755 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00003756 }
danielk1977da107192007-05-04 08:32:13 +00003757 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
3758 sqlite3PagerUnref(pDbPage);
3759 offset = 0;
3760 amt -= a;
3761 pBuf += a;
danielk19779f8d6402007-05-02 17:48:45 +00003762 }
danielk1977cfe9a692004-06-16 12:00:29 +00003763 }
drh2af926b2001-05-15 00:39:25 +00003764 }
drh2af926b2001-05-15 00:39:25 +00003765 }
danielk1977cfe9a692004-06-16 12:00:29 +00003766
danielk1977da107192007-05-04 08:32:13 +00003767 if( rc==SQLITE_OK && amt>0 ){
drh49285702005-09-17 15:20:26 +00003768 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00003769 }
danielk1977da107192007-05-04 08:32:13 +00003770 return rc;
drh2af926b2001-05-15 00:39:25 +00003771}
3772
drh72f82862001-05-24 21:06:34 +00003773/*
drh3aac2dd2004-04-26 14:10:20 +00003774** Read part of the key associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003775** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003776** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00003777**
drh5d1a8722009-07-22 18:07:40 +00003778** The caller must ensure that pCur is pointing to a valid row
3779** in the table.
3780**
drh3aac2dd2004-04-26 14:10:20 +00003781** Return SQLITE_OK on success or an error code if anything goes
3782** wrong. An error is returned if "offset+amt" is larger than
3783** the available payload.
drh72f82862001-05-24 21:06:34 +00003784*/
drha34b6762004-05-07 13:30:42 +00003785int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drh1fee73e2007-08-29 04:00:57 +00003786 assert( cursorHoldsMutex(pCur) );
drh5d1a8722009-07-22 18:07:40 +00003787 assert( pCur->eState==CURSOR_VALID );
3788 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3789 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
3790 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
drh3aac2dd2004-04-26 14:10:20 +00003791}
3792
3793/*
drh3aac2dd2004-04-26 14:10:20 +00003794** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00003795** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00003796** begins at "offset".
3797**
3798** Return SQLITE_OK on success or an error code if anything goes
3799** wrong. An error is returned if "offset+amt" is larger than
3800** the available payload.
drh72f82862001-05-24 21:06:34 +00003801*/
drh3aac2dd2004-04-26 14:10:20 +00003802int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00003803 int rc;
3804
danielk19773588ceb2008-06-10 17:30:26 +00003805#ifndef SQLITE_OMIT_INCRBLOB
3806 if ( pCur->eState==CURSOR_INVALID ){
3807 return SQLITE_ABORT;
3808 }
3809#endif
3810
drh1fee73e2007-08-29 04:00:57 +00003811 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00003812 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00003813 if( rc==SQLITE_OK ){
3814 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003815 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
3816 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drhfb192682009-07-11 18:26:28 +00003817 rc = accessPayload(pCur, offset, amt, pBuf, 0);
danielk1977da184232006-01-05 11:34:32 +00003818 }
3819 return rc;
drh2af926b2001-05-15 00:39:25 +00003820}
3821
drh72f82862001-05-24 21:06:34 +00003822/*
drh0e1c19e2004-05-11 00:58:56 +00003823** Return a pointer to payload information from the entry that the
3824** pCur cursor is pointing to. The pointer is to the beginning of
3825** the key if skipKey==0 and it points to the beginning of data if
drhe51c44f2004-05-30 20:46:09 +00003826** skipKey==1. The number of bytes of available key/data is written
3827** into *pAmt. If *pAmt==0, then the value returned will not be
3828** a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00003829**
3830** This routine is an optimization. It is common for the entire key
3831** and data to fit on the local page and for there to be no overflow
3832** pages. When that is so, this routine can be used to access the
3833** key and data without making a copy. If the key and/or data spills
drh7f751222009-03-17 22:33:00 +00003834** onto overflow pages, then accessPayload() must be used to reassemble
drh0e1c19e2004-05-11 00:58:56 +00003835** the key/data and copy it into a preallocated buffer.
3836**
3837** The pointer returned by this routine looks directly into the cached
3838** page of the database. The data might change or move the next time
3839** any btree routine is called.
3840*/
3841static const unsigned char *fetchPayload(
3842 BtCursor *pCur, /* Cursor pointing to entry to read from */
drhe51c44f2004-05-30 20:46:09 +00003843 int *pAmt, /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00003844 int skipKey /* read beginning at data if this is true */
3845){
3846 unsigned char *aPayload;
3847 MemPage *pPage;
drhfa1a98a2004-05-14 19:08:17 +00003848 u32 nKey;
danielk197789d40042008-11-17 14:20:56 +00003849 u32 nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003850
danielk197771d5d2c2008-09-29 11:49:47 +00003851 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
danielk1977da184232006-01-05 11:34:32 +00003852 assert( pCur->eState==CURSOR_VALID );
drh1fee73e2007-08-29 04:00:57 +00003853 assert( cursorHoldsMutex(pCur) );
danielk197771d5d2c2008-09-29 11:49:47 +00003854 pPage = pCur->apPage[pCur->iPage];
3855 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drhfe3313f2009-07-21 19:02:20 +00003856 if( NEVER(pCur->info.nSize==0) ){
3857 btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
3858 &pCur->info);
3859 }
drh43605152004-05-29 21:46:49 +00003860 aPayload = pCur->info.pCell;
drhfa1a98a2004-05-14 19:08:17 +00003861 aPayload += pCur->info.nHeader;
drh0e1c19e2004-05-11 00:58:56 +00003862 if( pPage->intKey ){
drhfa1a98a2004-05-14 19:08:17 +00003863 nKey = 0;
3864 }else{
drhf49661a2008-12-10 16:45:50 +00003865 nKey = (int)pCur->info.nKey;
drh0e1c19e2004-05-11 00:58:56 +00003866 }
drh0e1c19e2004-05-11 00:58:56 +00003867 if( skipKey ){
drhfa1a98a2004-05-14 19:08:17 +00003868 aPayload += nKey;
3869 nLocal = pCur->info.nLocal - nKey;
drh0e1c19e2004-05-11 00:58:56 +00003870 }else{
drhfa1a98a2004-05-14 19:08:17 +00003871 nLocal = pCur->info.nLocal;
drhfe3313f2009-07-21 19:02:20 +00003872 assert( nLocal<=nKey );
drh0e1c19e2004-05-11 00:58:56 +00003873 }
drhe51c44f2004-05-30 20:46:09 +00003874 *pAmt = nLocal;
drh0e1c19e2004-05-11 00:58:56 +00003875 return aPayload;
3876}
3877
3878
3879/*
drhe51c44f2004-05-30 20:46:09 +00003880** For the entry that cursor pCur is point to, return as
3881** many bytes of the key or data as are available on the local
3882** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00003883**
3884** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00003885** or be destroyed on the next call to any Btree routine,
3886** including calls from other threads against the same cache.
3887** Hence, a mutex on the BtShared should be held prior to calling
3888** this routine.
drh0e1c19e2004-05-11 00:58:56 +00003889**
3890** These routines is used to get quick access to key and data
3891** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00003892*/
drhe51c44f2004-05-30 20:46:09 +00003893const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
drhfe3313f2009-07-21 19:02:20 +00003894 const void *p = 0;
danielk19774b0aa4c2009-05-28 11:05:57 +00003895 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh1fee73e2007-08-29 04:00:57 +00003896 assert( cursorHoldsMutex(pCur) );
drhfe3313f2009-07-21 19:02:20 +00003897 if( ALWAYS(pCur->eState==CURSOR_VALID) ){
3898 p = (const void*)fetchPayload(pCur, pAmt, 0);
danielk1977da184232006-01-05 11:34:32 +00003899 }
drhfe3313f2009-07-21 19:02:20 +00003900 return p;
drh0e1c19e2004-05-11 00:58:56 +00003901}
drhe51c44f2004-05-30 20:46:09 +00003902const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
drhfe3313f2009-07-21 19:02:20 +00003903 const void *p = 0;
danielk19774b0aa4c2009-05-28 11:05:57 +00003904 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh1fee73e2007-08-29 04:00:57 +00003905 assert( cursorHoldsMutex(pCur) );
drhfe3313f2009-07-21 19:02:20 +00003906 if( ALWAYS(pCur->eState==CURSOR_VALID) ){
3907 p = (const void*)fetchPayload(pCur, pAmt, 1);
danielk1977da184232006-01-05 11:34:32 +00003908 }
drhfe3313f2009-07-21 19:02:20 +00003909 return p;
drh0e1c19e2004-05-11 00:58:56 +00003910}
3911
3912
3913/*
drh8178a752003-01-05 21:41:40 +00003914** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00003915** page number of the child page to move to.
danielk1977a299d612009-07-13 11:22:10 +00003916**
3917** This function returns SQLITE_CORRUPT if the page-header flags field of
3918** the new child page does not match the flags field of the parent (i.e.
3919** if an intkey page appears to be the parent of a non-intkey page, or
3920** vice-versa).
drh72f82862001-05-24 21:06:34 +00003921*/
drh3aac2dd2004-04-26 14:10:20 +00003922static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00003923 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003924 int i = pCur->iPage;
drh72f82862001-05-24 21:06:34 +00003925 MemPage *pNewPage;
drhd0679ed2007-08-28 22:24:34 +00003926 BtShared *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00003927
drh1fee73e2007-08-29 04:00:57 +00003928 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003929 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003930 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
3931 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
3932 return SQLITE_CORRUPT_BKPT;
3933 }
3934 rc = getAndInitPage(pBt, newPgno, &pNewPage);
drh6019e162001-07-02 17:51:45 +00003935 if( rc ) return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00003936 pCur->apPage[i+1] = pNewPage;
3937 pCur->aiIdx[i+1] = 0;
3938 pCur->iPage++;
3939
drh271efa52004-05-30 19:19:05 +00003940 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003941 pCur->validNKey = 0;
danielk1977bd5969a2009-07-11 17:39:42 +00003942 if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
drh49285702005-09-17 15:20:26 +00003943 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00003944 }
drh72f82862001-05-24 21:06:34 +00003945 return SQLITE_OK;
3946}
3947
danielk1977bf93c562008-09-29 15:53:25 +00003948#ifndef NDEBUG
3949/*
3950** Page pParent is an internal (non-leaf) tree page. This function
3951** asserts that page number iChild is the left-child if the iIdx'th
3952** cell in page pParent. Or, if iIdx is equal to the total number of
3953** cells in pParent, that page number iChild is the right-child of
3954** the page.
3955*/
3956static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
3957 assert( iIdx<=pParent->nCell );
3958 if( iIdx==pParent->nCell ){
3959 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
3960 }else{
3961 assert( get4byte(findCell(pParent, iIdx))==iChild );
3962 }
3963}
3964#else
3965# define assertParentIndex(x,y,z)
3966#endif
3967
drh72f82862001-05-24 21:06:34 +00003968/*
drh5e2f8b92001-05-28 00:41:15 +00003969** Move the cursor up to the parent page.
3970**
3971** pCur->idx is set to the cell index that contains the pointer
3972** to the page we are coming from. If we are coming from the
3973** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00003974** the largest cell index.
drh72f82862001-05-24 21:06:34 +00003975*/
danielk197730548662009-07-09 05:07:37 +00003976static void moveToParent(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00003977 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00003978 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00003979 assert( pCur->iPage>0 );
3980 assert( pCur->apPage[pCur->iPage] );
danielk1977bf93c562008-09-29 15:53:25 +00003981 assertParentIndex(
3982 pCur->apPage[pCur->iPage-1],
3983 pCur->aiIdx[pCur->iPage-1],
3984 pCur->apPage[pCur->iPage]->pgno
3985 );
danielk197771d5d2c2008-09-29 11:49:47 +00003986 releasePage(pCur->apPage[pCur->iPage]);
3987 pCur->iPage--;
drh271efa52004-05-30 19:19:05 +00003988 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00003989 pCur->validNKey = 0;
drh72f82862001-05-24 21:06:34 +00003990}
3991
3992/*
danielk19778f880a82009-07-13 09:41:45 +00003993** Move the cursor to point to the root page of its b-tree structure.
3994**
3995** If the table has a virtual root page, then the cursor is moved to point
3996** to the virtual root page instead of the actual root page. A table has a
3997** virtual root page when the actual root page contains no cells and a
3998** single child page. This can only happen with the table rooted at page 1.
3999**
4000** If the b-tree structure is empty, the cursor state is set to
4001** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
4002** cell located on the root (or virtual root) page and the cursor state
4003** is set to CURSOR_VALID.
4004**
4005** If this function returns successfully, it may be assumed that the
4006** page-header flags indicate that the [virtual] root-page is the expected
4007** kind of b-tree page (i.e. if when opening the cursor the caller did not
4008** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
4009** indicating a table b-tree, or if the caller did specify a KeyInfo
4010** structure the flags byte is set to 0x02 or 0x0A, indicating an index
4011** b-tree).
drh72f82862001-05-24 21:06:34 +00004012*/
drh5e2f8b92001-05-28 00:41:15 +00004013static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00004014 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00004015 int rc = SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00004016 Btree *p = pCur->pBtree;
4017 BtShared *pBt = p->pBt;
drhbd03cae2001-06-02 02:40:57 +00004018
drh1fee73e2007-08-29 04:00:57 +00004019 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +00004020 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
4021 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
4022 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
4023 if( pCur->eState>=CURSOR_REQUIRESEEK ){
4024 if( pCur->eState==CURSOR_FAULT ){
drh4c301aa2009-07-15 17:25:45 +00004025 assert( pCur->skipNext!=SQLITE_OK );
4026 return pCur->skipNext;
drhfb982642007-08-30 01:19:59 +00004027 }
danielk1977be51a652008-10-08 17:58:48 +00004028 sqlite3BtreeClearCursor(pCur);
drhbf700f32007-03-31 02:36:44 +00004029 }
danielk197771d5d2c2008-09-29 11:49:47 +00004030
4031 if( pCur->iPage>=0 ){
4032 int i;
4033 for(i=1; i<=pCur->iPage; i++){
4034 releasePage(pCur->apPage[i]);
danielk1977d9f6c532008-09-19 16:39:38 +00004035 }
danielk1977172114a2009-07-07 15:47:12 +00004036 pCur->iPage = 0;
drh777e4c42006-01-13 04:31:58 +00004037 }else{
drh4c301aa2009-07-15 17:25:45 +00004038 rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
4039 if( rc!=SQLITE_OK ){
drh777e4c42006-01-13 04:31:58 +00004040 pCur->eState = CURSOR_INVALID;
4041 return rc;
4042 }
danielk1977172114a2009-07-07 15:47:12 +00004043 pCur->iPage = 0;
4044
4045 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
4046 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
4047 ** NULL, the caller expects a table b-tree. If this is not the case,
4048 ** return an SQLITE_CORRUPT error. */
4049 assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
4050 if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
4051 return SQLITE_CORRUPT_BKPT;
4052 }
drhc39e0002004-05-07 23:50:57 +00004053 }
danielk197771d5d2c2008-09-29 11:49:47 +00004054
danielk19778f880a82009-07-13 09:41:45 +00004055 /* Assert that the root page is of the correct type. This must be the
4056 ** case as the call to this function that loaded the root-page (either
4057 ** this call or a previous invocation) would have detected corruption
4058 ** if the assumption were not true, and it is not possible for the flags
4059 ** byte to have been modified while this cursor is holding a reference
4060 ** to the page. */
danielk197771d5d2c2008-09-29 11:49:47 +00004061 pRoot = pCur->apPage[0];
4062 assert( pRoot->pgno==pCur->pgnoRoot );
danielk19778f880a82009-07-13 09:41:45 +00004063 assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
4064
danielk197771d5d2c2008-09-29 11:49:47 +00004065 pCur->aiIdx[0] = 0;
drh271efa52004-05-30 19:19:05 +00004066 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004067 pCur->atLast = 0;
4068 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004069
drh8856d6a2004-04-29 14:42:46 +00004070 if( pRoot->nCell==0 && !pRoot->leaf ){
4071 Pgno subpage;
drhc85240d2009-06-04 16:14:33 +00004072 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
drh43605152004-05-29 21:46:49 +00004073 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
danielk1977da184232006-01-05 11:34:32 +00004074 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00004075 rc = moveToChild(pCur, subpage);
danielk197771d5d2c2008-09-29 11:49:47 +00004076 }else{
4077 pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
drh8856d6a2004-04-29 14:42:46 +00004078 }
4079 return rc;
drh72f82862001-05-24 21:06:34 +00004080}
drh2af926b2001-05-15 00:39:25 +00004081
drh5e2f8b92001-05-28 00:41:15 +00004082/*
4083** Move the cursor down to the left-most leaf entry beneath the
4084** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00004085**
4086** The left-most leaf is the one with the smallest key - the first
4087** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00004088*/
4089static int moveToLeftmost(BtCursor *pCur){
4090 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00004091 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00004092 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00004093
drh1fee73e2007-08-29 04:00:57 +00004094 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004095 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004096 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
4097 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
4098 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
drh8178a752003-01-05 21:41:40 +00004099 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00004100 }
drhd677b3d2007-08-20 22:48:41 +00004101 return rc;
drh5e2f8b92001-05-28 00:41:15 +00004102}
4103
drh2dcc9aa2002-12-04 13:40:25 +00004104/*
4105** Move the cursor down to the right-most leaf entry beneath the
4106** page to which it is currently pointing. Notice the difference
4107** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
4108** finds the left-most entry beneath the *entry* whereas moveToRightmost()
4109** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00004110**
4111** The right-most entry is the one with the largest key - the last
4112** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00004113*/
4114static int moveToRightmost(BtCursor *pCur){
4115 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00004116 int rc = SQLITE_OK;
drh1bd10f82008-12-10 21:19:56 +00004117 MemPage *pPage = 0;
drh2dcc9aa2002-12-04 13:40:25 +00004118
drh1fee73e2007-08-29 04:00:57 +00004119 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004120 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004121 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
drh43605152004-05-29 21:46:49 +00004122 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
danielk197771d5d2c2008-09-29 11:49:47 +00004123 pCur->aiIdx[pCur->iPage] = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00004124 rc = moveToChild(pCur, pgno);
drh2dcc9aa2002-12-04 13:40:25 +00004125 }
drhd677b3d2007-08-20 22:48:41 +00004126 if( rc==SQLITE_OK ){
danielk197771d5d2c2008-09-29 11:49:47 +00004127 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
drhd677b3d2007-08-20 22:48:41 +00004128 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004129 pCur->validNKey = 0;
drhd677b3d2007-08-20 22:48:41 +00004130 }
danielk1977518002e2008-09-05 05:02:46 +00004131 return rc;
drh2dcc9aa2002-12-04 13:40:25 +00004132}
4133
drh5e00f6c2001-09-13 13:46:56 +00004134/* Move the cursor to the first entry in the table. Return SQLITE_OK
4135** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00004136** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00004137*/
drh3aac2dd2004-04-26 14:10:20 +00004138int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00004139 int rc;
drhd677b3d2007-08-20 22:48:41 +00004140
drh1fee73e2007-08-29 04:00:57 +00004141 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004142 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00004143 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004144 if( rc==SQLITE_OK ){
4145 if( pCur->eState==CURSOR_INVALID ){
danielk197771d5d2c2008-09-29 11:49:47 +00004146 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00004147 *pRes = 1;
4148 rc = SQLITE_OK;
4149 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004150 assert( pCur->apPage[pCur->iPage]->nCell>0 );
drhd677b3d2007-08-20 22:48:41 +00004151 *pRes = 0;
4152 rc = moveToLeftmost(pCur);
4153 }
drh5e00f6c2001-09-13 13:46:56 +00004154 }
drh5e00f6c2001-09-13 13:46:56 +00004155 return rc;
4156}
drh5e2f8b92001-05-28 00:41:15 +00004157
drh9562b552002-02-19 15:00:07 +00004158/* Move the cursor to the last entry in the table. Return SQLITE_OK
4159** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00004160** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00004161*/
drh3aac2dd2004-04-26 14:10:20 +00004162int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00004163 int rc;
drhd677b3d2007-08-20 22:48:41 +00004164
drh1fee73e2007-08-29 04:00:57 +00004165 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004166 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19773f632d52009-05-02 10:03:09 +00004167
4168 /* If the cursor already points to the last entry, this is a no-op. */
4169 if( CURSOR_VALID==pCur->eState && pCur->atLast ){
4170#ifdef SQLITE_DEBUG
4171 /* This block serves to assert() that the cursor really does point
4172 ** to the last entry in the b-tree. */
4173 int ii;
4174 for(ii=0; ii<pCur->iPage; ii++){
4175 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
4176 }
4177 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
4178 assert( pCur->apPage[pCur->iPage]->leaf );
4179#endif
4180 return SQLITE_OK;
4181 }
4182
drh9562b552002-02-19 15:00:07 +00004183 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004184 if( rc==SQLITE_OK ){
4185 if( CURSOR_INVALID==pCur->eState ){
danielk197771d5d2c2008-09-29 11:49:47 +00004186 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00004187 *pRes = 1;
4188 }else{
4189 assert( pCur->eState==CURSOR_VALID );
4190 *pRes = 0;
4191 rc = moveToRightmost(pCur);
drhf49661a2008-12-10 16:45:50 +00004192 pCur->atLast = rc==SQLITE_OK ?1:0;
drhd677b3d2007-08-20 22:48:41 +00004193 }
drh9562b552002-02-19 15:00:07 +00004194 }
drh9562b552002-02-19 15:00:07 +00004195 return rc;
4196}
4197
drhe14006d2008-03-25 17:23:32 +00004198/* Move the cursor so that it points to an entry near the key
drhe63d9992008-08-13 19:11:48 +00004199** specified by pIdxKey or intKey. Return a success code.
drh72f82862001-05-24 21:06:34 +00004200**
drhe63d9992008-08-13 19:11:48 +00004201** For INTKEY tables, the intKey parameter is used. pIdxKey
4202** must be NULL. For index tables, pIdxKey is used and intKey
4203** is ignored.
drh3aac2dd2004-04-26 14:10:20 +00004204**
drh5e2f8b92001-05-28 00:41:15 +00004205** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00004206** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00004207** were present. The cursor might point to an entry that comes
4208** before or after the key.
4209**
drh64022502009-01-09 14:11:04 +00004210** An integer is written into *pRes which is the result of
4211** comparing the key with the entry to which the cursor is
4212** pointing. The meaning of the integer written into
4213** *pRes is as follows:
drhbd03cae2001-06-02 02:40:57 +00004214**
4215** *pRes<0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004216** is smaller than intKey/pIdxKey or if the table is empty
drh1a844c32002-12-04 22:29:28 +00004217** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00004218**
4219** *pRes==0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004220** exactly matches intKey/pIdxKey.
drhbd03cae2001-06-02 02:40:57 +00004221**
4222** *pRes>0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004223** is larger than intKey/pIdxKey.
drhd677b3d2007-08-20 22:48:41 +00004224**
drha059ad02001-04-17 20:09:11 +00004225*/
drhe63d9992008-08-13 19:11:48 +00004226int sqlite3BtreeMovetoUnpacked(
4227 BtCursor *pCur, /* The cursor to be moved */
4228 UnpackedRecord *pIdxKey, /* Unpacked index key */
4229 i64 intKey, /* The table key */
4230 int biasRight, /* If true, bias the search to the high end */
4231 int *pRes /* Write search results here */
drhe4d90812007-03-29 05:51:49 +00004232){
drh72f82862001-05-24 21:06:34 +00004233 int rc;
drhd677b3d2007-08-20 22:48:41 +00004234
drh1fee73e2007-08-29 04:00:57 +00004235 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004236 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19775cb09632009-07-09 11:36:01 +00004237 assert( pRes );
danielk19773fd7cf52009-07-13 07:30:52 +00004238 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
drha2c20e42008-03-29 16:01:04 +00004239
4240 /* If the cursor is already positioned at the point we are trying
4241 ** to move to, then just return without doing any work */
danielk197771d5d2c2008-09-29 11:49:47 +00004242 if( pCur->eState==CURSOR_VALID && pCur->validNKey
4243 && pCur->apPage[0]->intKey
4244 ){
drhe63d9992008-08-13 19:11:48 +00004245 if( pCur->info.nKey==intKey ){
drha2c20e42008-03-29 16:01:04 +00004246 *pRes = 0;
4247 return SQLITE_OK;
4248 }
drhe63d9992008-08-13 19:11:48 +00004249 if( pCur->atLast && pCur->info.nKey<intKey ){
drha2c20e42008-03-29 16:01:04 +00004250 *pRes = -1;
4251 return SQLITE_OK;
4252 }
4253 }
4254
drh5e2f8b92001-05-28 00:41:15 +00004255 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004256 if( rc ){
4257 return rc;
4258 }
danielk197771d5d2c2008-09-29 11:49:47 +00004259 assert( pCur->apPage[pCur->iPage] );
4260 assert( pCur->apPage[pCur->iPage]->isInit );
danielk1977171fff32009-07-11 05:06:51 +00004261 assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
danielk1977da184232006-01-05 11:34:32 +00004262 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00004263 *pRes = -1;
danielk197771d5d2c2008-09-29 11:49:47 +00004264 assert( pCur->apPage[pCur->iPage]->nCell==0 );
drhc39e0002004-05-07 23:50:57 +00004265 return SQLITE_OK;
4266 }
danielk197771d5d2c2008-09-29 11:49:47 +00004267 assert( pCur->apPage[0]->intKey || pIdxKey );
drh14684382006-11-30 13:05:29 +00004268 for(;;){
drh72f82862001-05-24 21:06:34 +00004269 int lwr, upr;
4270 Pgno chldPg;
danielk197771d5d2c2008-09-29 11:49:47 +00004271 MemPage *pPage = pCur->apPage[pCur->iPage];
danielk1977171fff32009-07-11 05:06:51 +00004272 int c;
4273
4274 /* pPage->nCell must be greater than zero. If this is the root-page
4275 ** the cursor would have been INVALID above and this for(;;) loop
4276 ** not run. If this is not the root-page, then the moveToChild() routine
danielk19773fd7cf52009-07-13 07:30:52 +00004277 ** would have already detected db corruption. Similarly, pPage must
4278 ** be the right kind (index or table) of b-tree page. Otherwise
4279 ** a moveToChild() or moveToRoot() call would have detected corruption. */
danielk1977171fff32009-07-11 05:06:51 +00004280 assert( pPage->nCell>0 );
danielk19773fd7cf52009-07-13 07:30:52 +00004281 assert( pPage->intKey==(pIdxKey==0) );
drh72f82862001-05-24 21:06:34 +00004282 lwr = 0;
4283 upr = pPage->nCell-1;
drhe4d90812007-03-29 05:51:49 +00004284 if( biasRight ){
drhf49661a2008-12-10 16:45:50 +00004285 pCur->aiIdx[pCur->iPage] = (u16)upr;
drhe4d90812007-03-29 05:51:49 +00004286 }else{
drhf49661a2008-12-10 16:45:50 +00004287 pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
drhe4d90812007-03-29 05:51:49 +00004288 }
drh64022502009-01-09 14:11:04 +00004289 for(;;){
danielk197711c327a2009-05-04 19:01:26 +00004290 int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
4291 u8 *pCell; /* Pointer to current cell in pPage */
4292
drh366fda62006-01-13 02:35:09 +00004293 pCur->info.nSize = 0;
danielk197711c327a2009-05-04 19:01:26 +00004294 pCell = findCell(pPage, idx) + pPage->childPtrSize;
drh3aac2dd2004-04-26 14:10:20 +00004295 if( pPage->intKey ){
danielk197711c327a2009-05-04 19:01:26 +00004296 i64 nCellKey;
drhd172f862006-01-12 15:01:15 +00004297 if( pPage->hasData ){
danielk1977bab45c62006-01-16 15:14:27 +00004298 u32 dummy;
shane3f8d5cf2008-04-24 19:15:09 +00004299 pCell += getVarint32(pCell, dummy);
drhd172f862006-01-12 15:01:15 +00004300 }
drha2c20e42008-03-29 16:01:04 +00004301 getVarint(pCell, (u64*)&nCellKey);
drhe63d9992008-08-13 19:11:48 +00004302 if( nCellKey==intKey ){
drh3aac2dd2004-04-26 14:10:20 +00004303 c = 0;
drhe63d9992008-08-13 19:11:48 +00004304 }else if( nCellKey<intKey ){
drh41eb9e92008-04-02 18:33:07 +00004305 c = -1;
4306 }else{
drhe63d9992008-08-13 19:11:48 +00004307 assert( nCellKey>intKey );
drh41eb9e92008-04-02 18:33:07 +00004308 c = +1;
drh3aac2dd2004-04-26 14:10:20 +00004309 }
danielk197711c327a2009-05-04 19:01:26 +00004310 pCur->validNKey = 1;
4311 pCur->info.nKey = nCellKey;
drh3aac2dd2004-04-26 14:10:20 +00004312 }else{
danielk197711c327a2009-05-04 19:01:26 +00004313 /* The maximum supported page-size is 32768 bytes. This means that
4314 ** the maximum number of record bytes stored on an index B-Tree
4315 ** page is at most 8198 bytes, which may be stored as a 2-byte
4316 ** varint. This information is used to attempt to avoid parsing
4317 ** the entire cell by checking for the cases where the record is
4318 ** stored entirely within the b-tree page by inspecting the first
4319 ** 2 bytes of the cell.
4320 */
4321 int nCell = pCell[0];
4322 if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
4323 /* This branch runs if the record-size field of the cell is a
4324 ** single byte varint and the record fits entirely on the main
4325 ** b-tree page. */
4326 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
4327 }else if( !(pCell[1] & 0x80)
4328 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
4329 ){
4330 /* The record-size field is a 2 byte varint and the record
4331 ** fits entirely on the main b-tree page. */
4332 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
drhe51c44f2004-05-30 20:46:09 +00004333 }else{
danielk197711c327a2009-05-04 19:01:26 +00004334 /* The record flows over onto one or more overflow pages. In
4335 ** this case the whole cell needs to be parsed, a buffer allocated
4336 ** and accessPayload() used to retrieve the record into the
4337 ** buffer before VdbeRecordCompare() can be called. */
4338 void *pCellKey;
4339 u8 * const pCellBody = pCell - pPage->childPtrSize;
danielk197730548662009-07-09 05:07:37 +00004340 btreeParseCellPtr(pPage, pCellBody, &pCur->info);
shane60a4b532009-05-06 18:57:09 +00004341 nCell = (int)pCur->info.nKey;
danielk197711c327a2009-05-04 19:01:26 +00004342 pCellKey = sqlite3Malloc( nCell );
danielk19776507ecb2008-03-25 09:56:44 +00004343 if( pCellKey==0 ){
4344 rc = SQLITE_NOMEM;
4345 goto moveto_finish;
4346 }
drhfb192682009-07-11 18:26:28 +00004347 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
danielk197711c327a2009-05-04 19:01:26 +00004348 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
drhfacf0302008-06-17 15:12:00 +00004349 sqlite3_free(pCellKey);
drh1e968a02008-03-25 00:22:21 +00004350 if( rc ) goto moveto_finish;
drhe51c44f2004-05-30 20:46:09 +00004351 }
drh3aac2dd2004-04-26 14:10:20 +00004352 }
drh72f82862001-05-24 21:06:34 +00004353 if( c==0 ){
drh44845222008-07-17 18:39:57 +00004354 if( pPage->intKey && !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00004355 lwr = idx;
drhfc70e6f2004-05-12 21:11:27 +00004356 upr = lwr - 1;
drh8b18dd42004-05-12 19:18:15 +00004357 break;
4358 }else{
drh64022502009-01-09 14:11:04 +00004359 *pRes = 0;
drh1e968a02008-03-25 00:22:21 +00004360 rc = SQLITE_OK;
4361 goto moveto_finish;
drh8b18dd42004-05-12 19:18:15 +00004362 }
drh72f82862001-05-24 21:06:34 +00004363 }
4364 if( c<0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00004365 lwr = idx+1;
drh72f82862001-05-24 21:06:34 +00004366 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004367 upr = idx-1;
drh72f82862001-05-24 21:06:34 +00004368 }
drhf1d68b32007-03-29 04:43:26 +00004369 if( lwr>upr ){
4370 break;
4371 }
drhf49661a2008-12-10 16:45:50 +00004372 pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
drh72f82862001-05-24 21:06:34 +00004373 }
4374 assert( lwr==upr+1 );
danielk197771d5d2c2008-09-29 11:49:47 +00004375 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00004376 if( pPage->leaf ){
drha34b6762004-05-07 13:30:42 +00004377 chldPg = 0;
drh3aac2dd2004-04-26 14:10:20 +00004378 }else if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00004379 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00004380 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00004381 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00004382 }
4383 if( chldPg==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00004384 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
danielk19775cb09632009-07-09 11:36:01 +00004385 *pRes = c;
drh1e968a02008-03-25 00:22:21 +00004386 rc = SQLITE_OK;
4387 goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00004388 }
drhf49661a2008-12-10 16:45:50 +00004389 pCur->aiIdx[pCur->iPage] = (u16)lwr;
drh271efa52004-05-30 19:19:05 +00004390 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004391 pCur->validNKey = 0;
drh8178a752003-01-05 21:41:40 +00004392 rc = moveToChild(pCur, chldPg);
drh1e968a02008-03-25 00:22:21 +00004393 if( rc ) goto moveto_finish;
drh72f82862001-05-24 21:06:34 +00004394 }
drh1e968a02008-03-25 00:22:21 +00004395moveto_finish:
drhe63d9992008-08-13 19:11:48 +00004396 return rc;
4397}
4398
drhd677b3d2007-08-20 22:48:41 +00004399
drh72f82862001-05-24 21:06:34 +00004400/*
drhc39e0002004-05-07 23:50:57 +00004401** Return TRUE if the cursor is not pointing at an entry of the table.
4402**
4403** TRUE will be returned after a call to sqlite3BtreeNext() moves
4404** past the last entry in the table or sqlite3BtreePrev() moves past
4405** the first entry. TRUE is also returned if the table is empty.
4406*/
4407int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00004408 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
4409 ** have been deleted? This API will need to change to return an error code
4410 ** as well as the boolean result value.
4411 */
4412 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00004413}
4414
4415/*
drhbd03cae2001-06-02 02:40:57 +00004416** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00004417** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00004418** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00004419** this routine was called, then set *pRes=1.
drh72f82862001-05-24 21:06:34 +00004420*/
drhd094db12008-04-03 21:46:57 +00004421int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00004422 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00004423 int idx;
danielk197797a227c2006-01-20 16:32:04 +00004424 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00004425
drh1fee73e2007-08-29 04:00:57 +00004426 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004427 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004428 if( rc!=SQLITE_OK ){
4429 return rc;
4430 }
drh8c4d3a62007-04-06 01:03:32 +00004431 assert( pRes!=0 );
drh8c4d3a62007-04-06 01:03:32 +00004432 if( CURSOR_INVALID==pCur->eState ){
4433 *pRes = 1;
4434 return SQLITE_OK;
4435 }
drh4c301aa2009-07-15 17:25:45 +00004436 if( pCur->skipNext>0 ){
4437 pCur->skipNext = 0;
danielk1977da184232006-01-05 11:34:32 +00004438 *pRes = 0;
4439 return SQLITE_OK;
4440 }
drh4c301aa2009-07-15 17:25:45 +00004441 pCur->skipNext = 0;
danielk1977da184232006-01-05 11:34:32 +00004442
danielk197771d5d2c2008-09-29 11:49:47 +00004443 pPage = pCur->apPage[pCur->iPage];
4444 idx = ++pCur->aiIdx[pCur->iPage];
4445 assert( pPage->isInit );
4446 assert( idx<=pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00004447
drh271efa52004-05-30 19:19:05 +00004448 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004449 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004450 if( idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00004451 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004452 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drh5e2f8b92001-05-28 00:41:15 +00004453 if( rc ) return rc;
4454 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00004455 *pRes = 0;
4456 return rc;
drh72f82862001-05-24 21:06:34 +00004457 }
drh5e2f8b92001-05-28 00:41:15 +00004458 do{
danielk197771d5d2c2008-09-29 11:49:47 +00004459 if( pCur->iPage==0 ){
drh8c1238a2003-01-02 14:43:55 +00004460 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00004461 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00004462 return SQLITE_OK;
4463 }
danielk197730548662009-07-09 05:07:37 +00004464 moveToParent(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00004465 pPage = pCur->apPage[pCur->iPage];
4466 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
drh8c1238a2003-01-02 14:43:55 +00004467 *pRes = 0;
drh44845222008-07-17 18:39:57 +00004468 if( pPage->intKey ){
drh8b18dd42004-05-12 19:18:15 +00004469 rc = sqlite3BtreeNext(pCur, pRes);
4470 }else{
4471 rc = SQLITE_OK;
4472 }
4473 return rc;
drh8178a752003-01-05 21:41:40 +00004474 }
4475 *pRes = 0;
drh3aac2dd2004-04-26 14:10:20 +00004476 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00004477 return SQLITE_OK;
drh72f82862001-05-24 21:06:34 +00004478 }
drh5e2f8b92001-05-28 00:41:15 +00004479 rc = moveToLeftmost(pCur);
drh8c1238a2003-01-02 14:43:55 +00004480 return rc;
drh72f82862001-05-24 21:06:34 +00004481}
drhd677b3d2007-08-20 22:48:41 +00004482
drh72f82862001-05-24 21:06:34 +00004483
drh3b7511c2001-05-26 13:15:44 +00004484/*
drh2dcc9aa2002-12-04 13:40:25 +00004485** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00004486** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00004487** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00004488** this routine was called, then set *pRes=1.
drh2dcc9aa2002-12-04 13:40:25 +00004489*/
drhd094db12008-04-03 21:46:57 +00004490int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00004491 int rc;
drh8178a752003-01-05 21:41:40 +00004492 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00004493
drh1fee73e2007-08-29 04:00:57 +00004494 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004495 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004496 if( rc!=SQLITE_OK ){
4497 return rc;
4498 }
drha2c20e42008-03-29 16:01:04 +00004499 pCur->atLast = 0;
drh8c4d3a62007-04-06 01:03:32 +00004500 if( CURSOR_INVALID==pCur->eState ){
4501 *pRes = 1;
4502 return SQLITE_OK;
4503 }
drh4c301aa2009-07-15 17:25:45 +00004504 if( pCur->skipNext<0 ){
4505 pCur->skipNext = 0;
danielk1977da184232006-01-05 11:34:32 +00004506 *pRes = 0;
4507 return SQLITE_OK;
4508 }
drh4c301aa2009-07-15 17:25:45 +00004509 pCur->skipNext = 0;
danielk1977da184232006-01-05 11:34:32 +00004510
danielk197771d5d2c2008-09-29 11:49:47 +00004511 pPage = pCur->apPage[pCur->iPage];
4512 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00004513 if( !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00004514 int idx = pCur->aiIdx[pCur->iPage];
4515 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
drhd677b3d2007-08-20 22:48:41 +00004516 if( rc ){
4517 return rc;
4518 }
drh2dcc9aa2002-12-04 13:40:25 +00004519 rc = moveToRightmost(pCur);
4520 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004521 while( pCur->aiIdx[pCur->iPage]==0 ){
4522 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00004523 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00004524 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00004525 return SQLITE_OK;
4526 }
danielk197730548662009-07-09 05:07:37 +00004527 moveToParent(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00004528 }
drh271efa52004-05-30 19:19:05 +00004529 pCur->info.nSize = 0;
drha2c20e42008-03-29 16:01:04 +00004530 pCur->validNKey = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004531
4532 pCur->aiIdx[pCur->iPage]--;
4533 pPage = pCur->apPage[pCur->iPage];
drh44845222008-07-17 18:39:57 +00004534 if( pPage->intKey && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00004535 rc = sqlite3BtreePrevious(pCur, pRes);
4536 }else{
4537 rc = SQLITE_OK;
4538 }
drh2dcc9aa2002-12-04 13:40:25 +00004539 }
drh8178a752003-01-05 21:41:40 +00004540 *pRes = 0;
drh2dcc9aa2002-12-04 13:40:25 +00004541 return rc;
4542}
4543
4544/*
drh3b7511c2001-05-26 13:15:44 +00004545** Allocate a new page from the database file.
4546**
danielk19773b8a05f2007-03-19 17:44:26 +00004547** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00004548** has already been called on the new page.) The new page has also
4549** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00004550** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00004551**
4552** SQLITE_OK is returned on success. Any other return value indicates
4553** an error. *ppPage and *pPgno are undefined in the event of an error.
danielk19773b8a05f2007-03-19 17:44:26 +00004554** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00004555**
drh199e3cf2002-07-18 11:01:47 +00004556** If the "nearby" parameter is not 0, then a (feeble) effort is made to
4557** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00004558** attempt to keep related pages close to each other in the database file,
4559** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00004560**
4561** If the "exact" parameter is not 0, and the page-number nearby exists
4562** anywhere on the free-list, then it is guarenteed to be returned. This
4563** is only used by auto-vacuum databases when allocating a new table.
drh3b7511c2001-05-26 13:15:44 +00004564*/
drh4f0c5872007-03-26 22:05:01 +00004565static int allocateBtreePage(
danielk1977aef0bf62005-12-30 16:28:01 +00004566 BtShared *pBt,
danielk1977cb1a7eb2004-11-05 12:27:02 +00004567 MemPage **ppPage,
4568 Pgno *pPgno,
4569 Pgno nearby,
4570 u8 exact
4571){
drh3aac2dd2004-04-26 14:10:20 +00004572 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00004573 int rc;
drh35cd6432009-06-05 14:17:21 +00004574 u32 n; /* Number of pages on the freelist */
drh042d6a12009-06-17 13:57:16 +00004575 u32 k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00004576 MemPage *pTrunk = 0;
4577 MemPage *pPrevTrunk = 0;
drh1662b5a2009-06-04 19:06:09 +00004578 Pgno mxPage; /* Total size of the database file */
drh30e58752002-03-02 20:41:57 +00004579
drh1fee73e2007-08-29 04:00:57 +00004580 assert( sqlite3_mutex_held(pBt->mutex) );
drh3aac2dd2004-04-26 14:10:20 +00004581 pPage1 = pBt->pPage1;
drh1662b5a2009-06-04 19:06:09 +00004582 mxPage = pagerPagecount(pBt);
drh3aac2dd2004-04-26 14:10:20 +00004583 n = get4byte(&pPage1->aData[36]);
drhdf35a082009-07-09 02:24:35 +00004584 testcase( n==mxPage-1 );
4585 if( n>=mxPage ){
drh1662b5a2009-06-04 19:06:09 +00004586 return SQLITE_CORRUPT_BKPT;
4587 }
drh3aac2dd2004-04-26 14:10:20 +00004588 if( n>0 ){
drh91025292004-05-03 19:49:32 +00004589 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00004590 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004591 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
4592
4593 /* If the 'exact' parameter was true and a query of the pointer-map
4594 ** shows that the page 'nearby' is somewhere on the free-list, then
4595 ** the entire-list will be searched for that page.
4596 */
4597#ifndef SQLITE_OMIT_AUTOVACUUM
drh1662b5a2009-06-04 19:06:09 +00004598 if( exact && nearby<=mxPage ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004599 u8 eType;
4600 assert( nearby>0 );
4601 assert( pBt->autoVacuum );
4602 rc = ptrmapGet(pBt, nearby, &eType, 0);
4603 if( rc ) return rc;
4604 if( eType==PTRMAP_FREEPAGE ){
4605 searchList = 1;
4606 }
4607 *pPgno = nearby;
4608 }
4609#endif
4610
4611 /* Decrement the free-list count by 1. Set iTrunk to the index of the
4612 ** first free-list trunk page. iPrevTrunk is initially 1.
4613 */
danielk19773b8a05f2007-03-19 17:44:26 +00004614 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00004615 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00004616 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004617
4618 /* The code within this loop is run only once if the 'searchList' variable
4619 ** is not true. Otherwise, it runs once for each trunk-page on the
4620 ** free-list until the page 'nearby' is located.
4621 */
4622 do {
4623 pPrevTrunk = pTrunk;
4624 if( pPrevTrunk ){
4625 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00004626 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00004627 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00004628 }
drhdf35a082009-07-09 02:24:35 +00004629 testcase( iTrunk==mxPage );
drh1662b5a2009-06-04 19:06:09 +00004630 if( iTrunk>mxPage ){
4631 rc = SQLITE_CORRUPT_BKPT;
4632 }else{
danielk197730548662009-07-09 05:07:37 +00004633 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
drh1662b5a2009-06-04 19:06:09 +00004634 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004635 if( rc ){
drhd3627af2006-12-18 18:34:51 +00004636 pTrunk = 0;
4637 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004638 }
4639
4640 k = get4byte(&pTrunk->aData[4]);
4641 if( k==0 && !searchList ){
4642 /* The trunk has no leaves and the list is not being searched.
4643 ** So extract the trunk page itself and use it as the newly
4644 ** allocated page */
4645 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00004646 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004647 if( rc ){
4648 goto end_allocate_page;
4649 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004650 *pPgno = iTrunk;
4651 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4652 *ppPage = pTrunk;
4653 pTrunk = 0;
4654 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh042d6a12009-06-17 13:57:16 +00004655 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004656 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00004657 rc = SQLITE_CORRUPT_BKPT;
4658 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004659#ifndef SQLITE_OMIT_AUTOVACUUM
4660 }else if( searchList && nearby==iTrunk ){
4661 /* The list is being searched and this trunk page is the page
4662 ** to allocate, regardless of whether it has leaves.
4663 */
4664 assert( *pPgno==iTrunk );
4665 *ppPage = pTrunk;
4666 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00004667 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004668 if( rc ){
4669 goto end_allocate_page;
4670 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004671 if( k==0 ){
4672 if( !pPrevTrunk ){
4673 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4674 }else{
4675 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
4676 }
4677 }else{
4678 /* The trunk page is required by the caller but it contains
4679 ** pointers to free-list leaves. The first leaf becomes a trunk
4680 ** page in this case.
4681 */
4682 MemPage *pNewTrunk;
4683 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh1662b5a2009-06-04 19:06:09 +00004684 if( iNewTrunk>mxPage ){
4685 rc = SQLITE_CORRUPT_BKPT;
4686 goto end_allocate_page;
4687 }
drhdf35a082009-07-09 02:24:35 +00004688 testcase( iNewTrunk==mxPage );
danielk197730548662009-07-09 05:07:37 +00004689 rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004690 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00004691 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004692 }
danielk19773b8a05f2007-03-19 17:44:26 +00004693 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004694 if( rc!=SQLITE_OK ){
4695 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00004696 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004697 }
4698 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
4699 put4byte(&pNewTrunk->aData[4], k-1);
4700 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00004701 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004702 if( !pPrevTrunk ){
drhc5053fb2008-11-27 02:22:10 +00004703 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
danielk1977cb1a7eb2004-11-05 12:27:02 +00004704 put4byte(&pPage1->aData[32], iNewTrunk);
4705 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00004706 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004707 if( rc ){
4708 goto end_allocate_page;
4709 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004710 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
4711 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004712 }
4713 pTrunk = 0;
4714 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
4715#endif
danielk1977e5765212009-06-17 11:13:28 +00004716 }else if( k>0 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00004717 /* Extract a leaf from the trunk */
drh042d6a12009-06-17 13:57:16 +00004718 u32 closest;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004719 Pgno iPage;
4720 unsigned char *aData = pTrunk->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00004721 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00004722 if( rc ){
4723 goto end_allocate_page;
4724 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004725 if( nearby>0 ){
drh042d6a12009-06-17 13:57:16 +00004726 u32 i;
4727 int dist;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004728 closest = 0;
4729 dist = get4byte(&aData[8]) - nearby;
4730 if( dist<0 ) dist = -dist;
4731 for(i=1; i<k; i++){
4732 int d2 = get4byte(&aData[8+i*4]) - nearby;
4733 if( d2<0 ) d2 = -d2;
4734 if( d2<dist ){
4735 closest = i;
4736 dist = d2;
4737 }
4738 }
4739 }else{
4740 closest = 0;
4741 }
4742
4743 iPage = get4byte(&aData[8+closest*4]);
drhdf35a082009-07-09 02:24:35 +00004744 testcase( iPage==mxPage );
drh1662b5a2009-06-04 19:06:09 +00004745 if( iPage>mxPage ){
4746 rc = SQLITE_CORRUPT_BKPT;
4747 goto end_allocate_page;
4748 }
drhdf35a082009-07-09 02:24:35 +00004749 testcase( iPage==mxPage );
danielk1977cb1a7eb2004-11-05 12:27:02 +00004750 if( !searchList || iPage==nearby ){
danielk1977bea2a942009-01-20 17:06:27 +00004751 int noContent;
shane1f9e6aa2008-06-09 19:27:11 +00004752 *pPgno = iPage;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004753 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
4754 ": %d more free pages\n",
4755 *pPgno, closest+1, k, pTrunk->pgno, n-1));
4756 if( closest<k-1 ){
4757 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
4758 }
4759 put4byte(&aData[4], k-1);
drhc5053fb2008-11-27 02:22:10 +00004760 assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
danielk1977bea2a942009-01-20 17:06:27 +00004761 noContent = !btreeGetHasContent(pBt, *pPgno);
danielk197730548662009-07-09 05:07:37 +00004762 rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
danielk1977cb1a7eb2004-11-05 12:27:02 +00004763 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00004764 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004765 if( rc!=SQLITE_OK ){
4766 releasePage(*ppPage);
4767 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004768 }
4769 searchList = 0;
4770 }
drhee696e22004-08-30 16:52:17 +00004771 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00004772 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00004773 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00004774 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00004775 }else{
drh3aac2dd2004-04-26 14:10:20 +00004776 /* There are no pages on the freelist, so create a new page at the
4777 ** end of the file */
danielk197789d40042008-11-17 14:20:56 +00004778 int nPage = pagerPagecount(pBt);
danielk1977ad0132d2008-06-07 08:58:22 +00004779 *pPgno = nPage + 1;
danielk1977afcdd022004-10-31 16:25:42 +00004780
danielk1977bea2a942009-01-20 17:06:27 +00004781 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
4782 (*pPgno)++;
4783 }
4784
danielk1977afcdd022004-10-31 16:25:42 +00004785#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977266664d2006-02-10 08:24:21 +00004786 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
danielk1977afcdd022004-10-31 16:25:42 +00004787 /* If *pPgno refers to a pointer-map page, allocate two new pages
4788 ** at the end of the file instead of one. The first allocated page
4789 ** becomes a new pointer-map page, the second is used by the caller.
4790 */
danielk1977ac861692009-03-28 10:54:22 +00004791 MemPage *pPg = 0;
danielk1977afcdd022004-10-31 16:25:42 +00004792 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
danielk1977599fcba2004-11-08 07:13:13 +00004793 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk197730548662009-07-09 05:07:37 +00004794 rc = btreeGetPage(pBt, *pPgno, &pPg, 0);
danielk1977ac861692009-03-28 10:54:22 +00004795 if( rc==SQLITE_OK ){
4796 rc = sqlite3PagerWrite(pPg->pDbPage);
4797 releasePage(pPg);
4798 }
4799 if( rc ) return rc;
danielk1977afcdd022004-10-31 16:25:42 +00004800 (*pPgno)++;
drh72190432008-01-31 14:54:43 +00004801 if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
danielk1977afcdd022004-10-31 16:25:42 +00004802 }
4803#endif
4804
danielk1977599fcba2004-11-08 07:13:13 +00004805 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
danielk197730548662009-07-09 05:07:37 +00004806 rc = btreeGetPage(pBt, *pPgno, ppPage, 0);
drh3b7511c2001-05-26 13:15:44 +00004807 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00004808 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00004809 if( rc!=SQLITE_OK ){
4810 releasePage(*ppPage);
4811 }
drh3a4c1412004-05-09 20:40:11 +00004812 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00004813 }
danielk1977599fcba2004-11-08 07:13:13 +00004814
4815 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00004816
4817end_allocate_page:
4818 releasePage(pTrunk);
4819 releasePage(pPrevTrunk);
danielk1977b247c212008-11-21 09:09:01 +00004820 if( rc==SQLITE_OK ){
4821 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
4822 releasePage(*ppPage);
4823 return SQLITE_CORRUPT_BKPT;
4824 }
4825 (*ppPage)->isInit = 0;
danielk1977a50d9aa2009-06-08 14:49:45 +00004826 }else{
4827 *ppPage = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00004828 }
drh3b7511c2001-05-26 13:15:44 +00004829 return rc;
4830}
4831
4832/*
danielk1977bea2a942009-01-20 17:06:27 +00004833** This function is used to add page iPage to the database file free-list.
4834** It is assumed that the page is not already a part of the free-list.
drh5e2f8b92001-05-28 00:41:15 +00004835**
danielk1977bea2a942009-01-20 17:06:27 +00004836** The value passed as the second argument to this function is optional.
4837** If the caller happens to have a pointer to the MemPage object
4838** corresponding to page iPage handy, it may pass it as the second value.
4839** Otherwise, it may pass NULL.
4840**
4841** If a pointer to a MemPage object is passed as the second argument,
4842** its reference count is not altered by this function.
drh3b7511c2001-05-26 13:15:44 +00004843*/
danielk1977bea2a942009-01-20 17:06:27 +00004844static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
4845 MemPage *pTrunk = 0; /* Free-list trunk page */
4846 Pgno iTrunk = 0; /* Page number of free-list trunk page */
4847 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
4848 MemPage *pPage; /* Page being freed. May be NULL. */
4849 int rc; /* Return Code */
4850 int nFree; /* Initial number of pages on free-list */
drh8b2f49b2001-06-08 00:21:52 +00004851
danielk1977bea2a942009-01-20 17:06:27 +00004852 assert( sqlite3_mutex_held(pBt->mutex) );
4853 assert( iPage>1 );
4854 assert( !pMemPage || pMemPage->pgno==iPage );
4855
4856 if( pMemPage ){
4857 pPage = pMemPage;
4858 sqlite3PagerRef(pPage->pDbPage);
4859 }else{
4860 pPage = btreePageLookup(pBt, iPage);
4861 }
drh3aac2dd2004-04-26 14:10:20 +00004862
drha34b6762004-05-07 13:30:42 +00004863 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00004864 rc = sqlite3PagerWrite(pPage1->pDbPage);
danielk1977bea2a942009-01-20 17:06:27 +00004865 if( rc ) goto freepage_out;
4866 nFree = get4byte(&pPage1->aData[36]);
4867 put4byte(&pPage1->aData[36], nFree+1);
drh3aac2dd2004-04-26 14:10:20 +00004868
drhfcce93f2006-02-22 03:08:32 +00004869#ifdef SQLITE_SECURE_DELETE
4870 /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
4871 ** always fully overwrite deleted information with zeros.
4872 */
danielk197730548662009-07-09 05:07:37 +00004873 if( (!pPage && (rc = btreeGetPage(pBt, iPage, &pPage, 0)))
danielk1977bea2a942009-01-20 17:06:27 +00004874 || (rc = sqlite3PagerWrite(pPage->pDbPage))
4875 ){
4876 goto freepage_out;
4877 }
drhfcce93f2006-02-22 03:08:32 +00004878 memset(pPage->aData, 0, pPage->pBt->pageSize);
4879#endif
4880
danielk1977687566d2004-11-02 12:56:41 +00004881 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00004882 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00004883 */
danielk197785d90ca2008-07-19 14:25:15 +00004884 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00004885 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
danielk1977bea2a942009-01-20 17:06:27 +00004886 if( rc ) goto freepage_out;
danielk1977687566d2004-11-02 12:56:41 +00004887 }
danielk1977687566d2004-11-02 12:56:41 +00004888
danielk1977bea2a942009-01-20 17:06:27 +00004889 /* Now manipulate the actual database free-list structure. There are two
4890 ** possibilities. If the free-list is currently empty, or if the first
4891 ** trunk page in the free-list is full, then this page will become a
4892 ** new free-list trunk page. Otherwise, it will become a leaf of the
4893 ** first trunk page in the current free-list. This block tests if it
4894 ** is possible to add the page as a new free-list leaf.
4895 */
4896 if( nFree!=0 ){
drhc046e3e2009-07-15 11:26:44 +00004897 u32 nLeaf; /* Initial number of leaf cells on trunk page */
danielk1977bea2a942009-01-20 17:06:27 +00004898
4899 iTrunk = get4byte(&pPage1->aData[32]);
danielk197730548662009-07-09 05:07:37 +00004900 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977bea2a942009-01-20 17:06:27 +00004901 if( rc!=SQLITE_OK ){
4902 goto freepage_out;
4903 }
4904
4905 nLeaf = get4byte(&pTrunk->aData[4]);
drheeb844a2009-08-08 18:01:07 +00004906 assert( pBt->usableSize>32 );
4907 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
danielk1977bea2a942009-01-20 17:06:27 +00004908 rc = SQLITE_CORRUPT_BKPT;
4909 goto freepage_out;
4910 }
drheeb844a2009-08-08 18:01:07 +00004911 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
danielk1977bea2a942009-01-20 17:06:27 +00004912 /* In this case there is room on the trunk page to insert the page
4913 ** being freed as a new leaf.
drh45b1fac2008-07-04 17:52:42 +00004914 **
4915 ** Note that the trunk page is not really full until it contains
4916 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
4917 ** coded. But due to a coding error in versions of SQLite prior to
4918 ** 3.6.0, databases with freelist trunk pages holding more than
4919 ** usableSize/4 - 8 entries will be reported as corrupt. In order
4920 ** to maintain backwards compatibility with older versions of SQLite,
drhc046e3e2009-07-15 11:26:44 +00004921 ** we will continue to restrict the number of entries to usableSize/4 - 8
drh45b1fac2008-07-04 17:52:42 +00004922 ** for now. At some point in the future (once everyone has upgraded
4923 ** to 3.6.0 or later) we should consider fixing the conditional above
4924 ** to read "usableSize/4-2" instead of "usableSize/4-8".
4925 */
danielk19773b8a05f2007-03-19 17:44:26 +00004926 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00004927 if( rc==SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00004928 put4byte(&pTrunk->aData[4], nLeaf+1);
4929 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
drhfcce93f2006-02-22 03:08:32 +00004930#ifndef SQLITE_SECURE_DELETE
danielk1977bea2a942009-01-20 17:06:27 +00004931 if( pPage ){
4932 sqlite3PagerDontWrite(pPage->pDbPage);
4933 }
drhfcce93f2006-02-22 03:08:32 +00004934#endif
danielk1977bea2a942009-01-20 17:06:27 +00004935 rc = btreeSetHasContent(pBt, iPage);
drhf5345442007-04-09 12:45:02 +00004936 }
drh3a4c1412004-05-09 20:40:11 +00004937 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
danielk1977bea2a942009-01-20 17:06:27 +00004938 goto freepage_out;
drh3aac2dd2004-04-26 14:10:20 +00004939 }
drh3b7511c2001-05-26 13:15:44 +00004940 }
danielk1977bea2a942009-01-20 17:06:27 +00004941
4942 /* If control flows to this point, then it was not possible to add the
4943 ** the page being freed as a leaf page of the first trunk in the free-list.
4944 ** Possibly because the free-list is empty, or possibly because the
4945 ** first trunk in the free-list is full. Either way, the page being freed
4946 ** will become the new first trunk page in the free-list.
4947 */
drhc046e3e2009-07-15 11:26:44 +00004948 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
4949 goto freepage_out;
4950 }
4951 rc = sqlite3PagerWrite(pPage->pDbPage);
4952 if( rc!=SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00004953 goto freepage_out;
4954 }
4955 put4byte(pPage->aData, iTrunk);
4956 put4byte(&pPage->aData[4], 0);
4957 put4byte(&pPage1->aData[32], iPage);
4958 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
4959
4960freepage_out:
4961 if( pPage ){
4962 pPage->isInit = 0;
4963 }
4964 releasePage(pPage);
4965 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00004966 return rc;
4967}
drhc314dc72009-07-21 11:52:34 +00004968static void freePage(MemPage *pPage, int *pRC){
4969 if( (*pRC)==SQLITE_OK ){
4970 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
4971 }
danielk1977bea2a942009-01-20 17:06:27 +00004972}
drh3b7511c2001-05-26 13:15:44 +00004973
4974/*
drh3aac2dd2004-04-26 14:10:20 +00004975** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00004976*/
drh3aac2dd2004-04-26 14:10:20 +00004977static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00004978 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00004979 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00004980 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00004981 int rc;
drh94440812007-03-06 11:42:19 +00004982 int nOvfl;
shane63207ab2009-02-04 01:49:30 +00004983 u16 ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00004984
drh1fee73e2007-08-29 04:00:57 +00004985 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197730548662009-07-09 05:07:37 +00004986 btreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00004987 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00004988 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00004989 }
drh6f11bef2004-05-13 01:12:56 +00004990 ovflPgno = get4byte(&pCell[info.iOverflow]);
shane63207ab2009-02-04 01:49:30 +00004991 assert( pBt->usableSize > 4 );
drh94440812007-03-06 11:42:19 +00004992 ovflPageSize = pBt->usableSize - 4;
drh72365832007-03-06 15:53:44 +00004993 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
4994 assert( ovflPgno==0 || nOvfl>0 );
4995 while( nOvfl-- ){
shane63207ab2009-02-04 01:49:30 +00004996 Pgno iNext = 0;
danielk1977bea2a942009-01-20 17:06:27 +00004997 MemPage *pOvfl = 0;
danielk1977e589a672009-04-11 16:06:15 +00004998 if( ovflPgno<2 || ovflPgno>pagerPagecount(pBt) ){
4999 /* 0 is not a legal page number and page 1 cannot be an
5000 ** overflow page. Therefore if ovflPgno<2 or past the end of the
5001 ** file the database must be corrupt. */
drh49285702005-09-17 15:20:26 +00005002 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00005003 }
danielk1977bea2a942009-01-20 17:06:27 +00005004 if( nOvfl ){
5005 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
5006 if( rc ) return rc;
5007 }
5008 rc = freePage2(pBt, pOvfl, ovflPgno);
5009 if( pOvfl ){
5010 sqlite3PagerUnref(pOvfl->pDbPage);
5011 }
drh3b7511c2001-05-26 13:15:44 +00005012 if( rc ) return rc;
danielk1977bea2a942009-01-20 17:06:27 +00005013 ovflPgno = iNext;
drh3b7511c2001-05-26 13:15:44 +00005014 }
drh5e2f8b92001-05-28 00:41:15 +00005015 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00005016}
5017
5018/*
drh91025292004-05-03 19:49:32 +00005019** Create the byte sequence used to represent a cell on page pPage
5020** and write that byte sequence into pCell[]. Overflow pages are
5021** allocated and filled in as necessary. The calling procedure
5022** is responsible for making sure sufficient space has been allocated
5023** for pCell[].
5024**
5025** Note that pCell does not necessary need to point to the pPage->aData
5026** area. pCell might point to some temporary storage. The cell will
5027** be constructed in this temporary area then copied into pPage->aData
5028** later.
drh3b7511c2001-05-26 13:15:44 +00005029*/
5030static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00005031 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00005032 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00005033 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00005034 const void *pData,int nData, /* The data */
drhb026e052007-05-02 01:34:31 +00005035 int nZero, /* Extra zero bytes to append to pData */
drh4b70f112004-05-02 21:12:19 +00005036 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00005037){
drh3b7511c2001-05-26 13:15:44 +00005038 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00005039 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00005040 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00005041 int spaceLeft;
5042 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00005043 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00005044 unsigned char *pPrior;
5045 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00005046 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00005047 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00005048 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00005049 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00005050
drh1fee73e2007-08-29 04:00:57 +00005051 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00005052
drhc5053fb2008-11-27 02:22:10 +00005053 /* pPage is not necessarily writeable since pCell might be auxiliary
5054 ** buffer space that is separate from the pPage buffer area */
5055 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
5056 || sqlite3PagerIswriteable(pPage->pDbPage) );
5057
drh91025292004-05-03 19:49:32 +00005058 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00005059 nHeader = 0;
drh91025292004-05-03 19:49:32 +00005060 if( !pPage->leaf ){
5061 nHeader += 4;
5062 }
drh8b18dd42004-05-12 19:18:15 +00005063 if( pPage->hasData ){
drhb026e052007-05-02 01:34:31 +00005064 nHeader += putVarint(&pCell[nHeader], nData+nZero);
drh6f11bef2004-05-13 01:12:56 +00005065 }else{
drhb026e052007-05-02 01:34:31 +00005066 nData = nZero = 0;
drh91025292004-05-03 19:49:32 +00005067 }
drh6f11bef2004-05-13 01:12:56 +00005068 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
danielk197730548662009-07-09 05:07:37 +00005069 btreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005070 assert( info.nHeader==nHeader );
5071 assert( info.nKey==nKey );
danielk197789d40042008-11-17 14:20:56 +00005072 assert( info.nData==(u32)(nData+nZero) );
drh6f11bef2004-05-13 01:12:56 +00005073
5074 /* Fill in the payload */
drhb026e052007-05-02 01:34:31 +00005075 nPayload = nData + nZero;
drh3aac2dd2004-04-26 14:10:20 +00005076 if( pPage->intKey ){
5077 pSrc = pData;
5078 nSrc = nData;
drh91025292004-05-03 19:49:32 +00005079 nData = 0;
drhf49661a2008-12-10 16:45:50 +00005080 }else{
danielk197731d31b82009-07-13 13:18:07 +00005081 if( NEVER(nKey>0x7fffffff || pKey==0) ){
5082 return SQLITE_CORRUPT_BKPT;
drh20abac22009-01-28 20:21:17 +00005083 }
drhf49661a2008-12-10 16:45:50 +00005084 nPayload += (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00005085 pSrc = pKey;
drhf49661a2008-12-10 16:45:50 +00005086 nSrc = (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00005087 }
drh6f11bef2004-05-13 01:12:56 +00005088 *pnSize = info.nSize;
5089 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00005090 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00005091 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00005092
drh3b7511c2001-05-26 13:15:44 +00005093 while( nPayload>0 ){
5094 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00005095#ifndef SQLITE_OMIT_AUTOVACUUM
5096 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00005097 if( pBt->autoVacuum ){
5098 do{
5099 pgnoOvfl++;
5100 } while(
5101 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
5102 );
danielk1977b39f70b2007-05-17 18:28:11 +00005103 }
danielk1977afcdd022004-10-31 16:25:42 +00005104#endif
drhf49661a2008-12-10 16:45:50 +00005105 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00005106#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00005107 /* If the database supports auto-vacuum, and the second or subsequent
5108 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00005109 ** for that page now.
5110 **
5111 ** If this is the first overflow page, then write a partial entry
5112 ** to the pointer-map. If we write nothing to this pointer-map slot,
5113 ** then the optimistic overflow chain processing in clearCell()
5114 ** may misinterpret the uninitialised values and delete the
5115 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00005116 */
danielk19774ef24492007-05-23 09:52:41 +00005117 if( pBt->autoVacuum && rc==SQLITE_OK ){
5118 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
drh98add2e2009-07-20 17:11:49 +00005119 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
danielk197789a4be82007-05-23 13:34:32 +00005120 if( rc ){
5121 releasePage(pOvfl);
5122 }
danielk1977afcdd022004-10-31 16:25:42 +00005123 }
5124#endif
drh3b7511c2001-05-26 13:15:44 +00005125 if( rc ){
drh9b171272004-05-08 02:03:22 +00005126 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00005127 return rc;
5128 }
drhc5053fb2008-11-27 02:22:10 +00005129
5130 /* If pToRelease is not zero than pPrior points into the data area
5131 ** of pToRelease. Make sure pToRelease is still writeable. */
5132 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
5133
5134 /* If pPrior is part of the data area of pPage, then make sure pPage
5135 ** is still writeable */
5136 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
5137 || sqlite3PagerIswriteable(pPage->pDbPage) );
5138
drh3aac2dd2004-04-26 14:10:20 +00005139 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00005140 releasePage(pToRelease);
5141 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00005142 pPrior = pOvfl->aData;
5143 put4byte(pPrior, 0);
5144 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00005145 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00005146 }
5147 n = nPayload;
5148 if( n>spaceLeft ) n = spaceLeft;
drhc5053fb2008-11-27 02:22:10 +00005149
5150 /* If pToRelease is not zero than pPayload points into the data area
5151 ** of pToRelease. Make sure pToRelease is still writeable. */
5152 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
5153
5154 /* If pPayload is part of the data area of pPage, then make sure pPage
5155 ** is still writeable */
5156 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
5157 || sqlite3PagerIswriteable(pPage->pDbPage) );
5158
drhb026e052007-05-02 01:34:31 +00005159 if( nSrc>0 ){
5160 if( n>nSrc ) n = nSrc;
5161 assert( pSrc );
5162 memcpy(pPayload, pSrc, n);
5163 }else{
5164 memset(pPayload, 0, n);
5165 }
drh3b7511c2001-05-26 13:15:44 +00005166 nPayload -= n;
drhde647132004-05-07 17:57:49 +00005167 pPayload += n;
drh9b171272004-05-08 02:03:22 +00005168 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00005169 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00005170 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00005171 if( nSrc==0 ){
5172 nSrc = nData;
5173 pSrc = pData;
5174 }
drhdd793422001-06-28 01:54:48 +00005175 }
drh9b171272004-05-08 02:03:22 +00005176 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00005177 return SQLITE_OK;
5178}
5179
drh14acc042001-06-10 19:56:58 +00005180/*
5181** Remove the i-th cell from pPage. This routine effects pPage only.
5182** The cell content is not freed or deallocated. It is assumed that
5183** the cell content has been copied someplace else. This routine just
5184** removes the reference to the cell from pPage.
5185**
5186** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00005187*/
drh98add2e2009-07-20 17:11:49 +00005188static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
drh43605152004-05-29 21:46:49 +00005189 int i; /* Loop counter */
5190 int pc; /* Offset to cell content of cell being deleted */
5191 u8 *data; /* pPage->aData */
5192 u8 *ptr; /* Used to move bytes around within data[] */
shanedcc50b72008-11-13 18:29:50 +00005193 int rc; /* The return code */
drhc314dc72009-07-21 11:52:34 +00005194 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
drh43605152004-05-29 21:46:49 +00005195
drh98add2e2009-07-20 17:11:49 +00005196 if( *pRC ) return;
5197
drh8c42ca92001-06-22 19:15:00 +00005198 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00005199 assert( sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00005200 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00005201 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00005202 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00005203 ptr = &data[pPage->cellOffset + 2*idx];
shane0af3f892008-11-12 04:55:34 +00005204 pc = get2byte(ptr);
drhc314dc72009-07-21 11:52:34 +00005205 hdr = pPage->hdrOffset;
5206 testcase( pc==get2byte(&data[hdr+5]) );
5207 testcase( pc+sz==pPage->pBt->usableSize );
5208 if( pc < get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
drh98add2e2009-07-20 17:11:49 +00005209 *pRC = SQLITE_CORRUPT_BKPT;
5210 return;
shane0af3f892008-11-12 04:55:34 +00005211 }
shanedcc50b72008-11-13 18:29:50 +00005212 rc = freeSpace(pPage, pc, sz);
drh98add2e2009-07-20 17:11:49 +00005213 if( rc ){
5214 *pRC = rc;
5215 return;
shanedcc50b72008-11-13 18:29:50 +00005216 }
drh43605152004-05-29 21:46:49 +00005217 for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
5218 ptr[0] = ptr[2];
5219 ptr[1] = ptr[3];
drh14acc042001-06-10 19:56:58 +00005220 }
5221 pPage->nCell--;
drhc314dc72009-07-21 11:52:34 +00005222 put2byte(&data[hdr+3], pPage->nCell);
drh43605152004-05-29 21:46:49 +00005223 pPage->nFree += 2;
drh14acc042001-06-10 19:56:58 +00005224}
5225
5226/*
5227** Insert a new cell on pPage at cell index "i". pCell points to the
5228** content of the cell.
5229**
5230** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00005231** will not fit, then make a copy of the cell content into pTemp if
5232** pTemp is not null. Regardless of pTemp, allocate a new entry
5233** in pPage->aOvfl[] and make it point to the cell content (either
5234** in pTemp or the original pCell) and also record its index.
5235** Allocating a new entry in pPage->aCell[] implies that
5236** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00005237**
5238** If nSkip is non-zero, then do not copy the first nSkip bytes of the
5239** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00005240** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00005241** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00005242*/
drh98add2e2009-07-20 17:11:49 +00005243static void insertCell(
drh24cd67e2004-05-10 16:18:47 +00005244 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00005245 int i, /* New cell becomes the i-th cell of the page */
5246 u8 *pCell, /* Content of the new cell */
5247 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00005248 u8 *pTemp, /* Temp storage space for pCell, if needed */
drh98add2e2009-07-20 17:11:49 +00005249 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
5250 int *pRC /* Read and write return code from here */
drh24cd67e2004-05-10 16:18:47 +00005251){
drh43605152004-05-29 21:46:49 +00005252 int idx; /* Where to write new cell content in data[] */
5253 int j; /* Loop counter */
drh43605152004-05-29 21:46:49 +00005254 int end; /* First byte past the last cell pointer in data[] */
5255 int ins; /* Index in data[] where new cell pointer is inserted */
drh43605152004-05-29 21:46:49 +00005256 int cellOffset; /* Address of first cell pointer in data[] */
5257 u8 *data; /* The content of the whole page */
5258 u8 *ptr; /* Used for moving information around in data[] */
5259
danielk19774dbaa892009-06-16 16:50:22 +00005260 int nSkip = (iChild ? 4 : 0);
5261
drh98add2e2009-07-20 17:11:49 +00005262 if( *pRC ) return;
5263
drh43605152004-05-29 21:46:49 +00005264 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
drhf49661a2008-12-10 16:45:50 +00005265 assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
5266 assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
drh43605152004-05-29 21:46:49 +00005267 assert( sz==cellSizePtr(pPage, pCell) );
drh1fee73e2007-08-29 04:00:57 +00005268 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +00005269 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00005270 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00005271 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00005272 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00005273 }
danielk19774dbaa892009-06-16 16:50:22 +00005274 if( iChild ){
5275 put4byte(pCell, iChild);
5276 }
drh43605152004-05-29 21:46:49 +00005277 j = pPage->nOverflow++;
danielk197789d40042008-11-17 14:20:56 +00005278 assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
drh43605152004-05-29 21:46:49 +00005279 pPage->aOvfl[j].pCell = pCell;
drhf49661a2008-12-10 16:45:50 +00005280 pPage->aOvfl[j].idx = (u16)i;
drh14acc042001-06-10 19:56:58 +00005281 }else{
danielk19776e465eb2007-08-21 13:11:00 +00005282 int rc = sqlite3PagerWrite(pPage->pDbPage);
5283 if( rc!=SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +00005284 *pRC = rc;
5285 return;
danielk19776e465eb2007-08-21 13:11:00 +00005286 }
5287 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00005288 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00005289 cellOffset = pPage->cellOffset;
drh0a45c272009-07-08 01:49:11 +00005290 end = cellOffset + 2*pPage->nCell;
drh43605152004-05-29 21:46:49 +00005291 ins = cellOffset + 2*i;
drh0a45c272009-07-08 01:49:11 +00005292 rc = allocateSpace(pPage, sz, &idx);
drh98add2e2009-07-20 17:11:49 +00005293 if( rc ){ *pRC = rc; return; }
drhc314dc72009-07-21 11:52:34 +00005294 /* The allocateSpace() routine guarantees the following two properties
5295 ** if it returns success */
5296 assert( idx >= end+2 );
5297 assert( idx+sz <= pPage->pBt->usableSize );
drh43605152004-05-29 21:46:49 +00005298 pPage->nCell++;
drh0a45c272009-07-08 01:49:11 +00005299 pPage->nFree -= (u16)(2 + sz);
danielk1977a3ad5e72005-01-07 08:56:44 +00005300 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
danielk19774dbaa892009-06-16 16:50:22 +00005301 if( iChild ){
5302 put4byte(&data[idx], iChild);
5303 }
drh0a45c272009-07-08 01:49:11 +00005304 for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
drh43605152004-05-29 21:46:49 +00005305 ptr[0] = ptr[-2];
5306 ptr[1] = ptr[-1];
drhda200cc2004-05-09 11:51:38 +00005307 }
drh43605152004-05-29 21:46:49 +00005308 put2byte(&data[ins], idx);
drh0a45c272009-07-08 01:49:11 +00005309 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
danielk1977a19df672004-11-03 11:37:07 +00005310#ifndef SQLITE_OMIT_AUTOVACUUM
5311 if( pPage->pBt->autoVacuum ){
5312 /* The cell may contain a pointer to an overflow page. If so, write
5313 ** the entry for the overflow page into the pointer map.
5314 */
drh98add2e2009-07-20 17:11:49 +00005315 ptrmapPutOvflPtr(pPage, pCell, pRC);
danielk1977a19df672004-11-03 11:37:07 +00005316 }
5317#endif
drh14acc042001-06-10 19:56:58 +00005318 }
5319}
5320
5321/*
drhfa1a98a2004-05-14 19:08:17 +00005322** Add a list of cells to a page. The page should be initially empty.
5323** The cells are guaranteed to fit on the page.
5324*/
5325static void assemblePage(
5326 MemPage *pPage, /* The page to be assemblied */
5327 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00005328 u8 **apCell, /* Pointers to cell bodies */
drha9121e42008-02-19 14:59:35 +00005329 u16 *aSize /* Sizes of the cells */
drhfa1a98a2004-05-14 19:08:17 +00005330){
5331 int i; /* Loop counter */
danielk1977fad91942009-04-29 17:49:59 +00005332 u8 *pCellptr; /* Address of next cell pointer */
drh43605152004-05-29 21:46:49 +00005333 int cellbody; /* Address of next cell body */
danielk1977fad91942009-04-29 17:49:59 +00005334 u8 * const data = pPage->aData; /* Pointer to data for pPage */
5335 const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
5336 const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
drhfa1a98a2004-05-14 19:08:17 +00005337
drh43605152004-05-29 21:46:49 +00005338 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00005339 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00005340 assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
drhc5053fb2008-11-27 02:22:10 +00005341 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977fad91942009-04-29 17:49:59 +00005342
5343 /* Check that the page has just been zeroed by zeroPage() */
5344 assert( pPage->nCell==0 );
5345 assert( get2byte(&data[hdr+5])==nUsable );
5346
5347 pCellptr = &data[pPage->cellOffset + nCell*2];
5348 cellbody = nUsable;
5349 for(i=nCell-1; i>=0; i--){
5350 pCellptr -= 2;
5351 cellbody -= aSize[i];
5352 put2byte(pCellptr, cellbody);
5353 memcpy(&data[cellbody], apCell[i], aSize[i]);
drhfa1a98a2004-05-14 19:08:17 +00005354 }
danielk1977fad91942009-04-29 17:49:59 +00005355 put2byte(&data[hdr+3], nCell);
5356 put2byte(&data[hdr+5], cellbody);
5357 pPage->nFree -= (nCell*2 + nUsable - cellbody);
drhf49661a2008-12-10 16:45:50 +00005358 pPage->nCell = (u16)nCell;
drhfa1a98a2004-05-14 19:08:17 +00005359}
5360
drh14acc042001-06-10 19:56:58 +00005361/*
drhc3b70572003-01-04 19:44:07 +00005362** The following parameters determine how many adjacent pages get involved
5363** in a balancing operation. NN is the number of neighbors on either side
5364** of the page that participate in the balancing operation. NB is the
5365** total number of pages that participate, including the target page and
5366** NN neighbors on either side.
5367**
5368** The minimum value of NN is 1 (of course). Increasing NN above 1
5369** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
5370** in exchange for a larger degradation in INSERT and UPDATE performance.
5371** The value of NN appears to give the best results overall.
5372*/
5373#define NN 1 /* Number of neighbors on either side of pPage */
5374#define NB (NN*2+1) /* Total pages involved in the balance */
5375
danielk1977ac245ec2005-01-14 13:50:11 +00005376
drh615ae552005-01-16 23:21:00 +00005377#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00005378/*
5379** This version of balance() handles the common special case where
5380** a new entry is being inserted on the extreme right-end of the
5381** tree, in other words, when the new entry will become the largest
5382** entry in the tree.
5383**
drhc314dc72009-07-21 11:52:34 +00005384** Instead of trying to balance the 3 right-most leaf pages, just add
drhf222e712005-01-14 22:55:49 +00005385** a new page to the right-hand side and put the one new entry in
5386** that page. This leaves the right side of the tree somewhat
5387** unbalanced. But odds are that we will be inserting new entries
5388** at the end soon afterwards so the nearly empty page will quickly
5389** fill up. On average.
5390**
5391** pPage is the leaf page which is the right-most page in the tree.
5392** pParent is its parent. pPage must have a single overflow entry
5393** which is also the right-most entry on the page.
danielk1977a50d9aa2009-06-08 14:49:45 +00005394**
5395** The pSpace buffer is used to store a temporary copy of the divider
5396** cell that will be inserted into pParent. Such a cell consists of a 4
5397** byte page number followed by a variable length integer. In other
5398** words, at most 13 bytes. Hence the pSpace buffer must be at
5399** least 13 bytes in size.
drhf222e712005-01-14 22:55:49 +00005400*/
danielk1977a50d9aa2009-06-08 14:49:45 +00005401static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
5402 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
danielk19774dbaa892009-06-16 16:50:22 +00005403 MemPage *pNew; /* Newly allocated page */
danielk19776f235cc2009-06-04 14:46:08 +00005404 int rc; /* Return Code */
5405 Pgno pgnoNew; /* Page number of pNew */
danielk1977ac245ec2005-01-14 13:50:11 +00005406
drh1fee73e2007-08-29 04:00:57 +00005407 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk1977a50d9aa2009-06-08 14:49:45 +00005408 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00005409 assert( pPage->nOverflow==1 );
5410
drh5d1a8722009-07-22 18:07:40 +00005411 if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
drhd677b3d2007-08-20 22:48:41 +00005412
danielk1977a50d9aa2009-06-08 14:49:45 +00005413 /* Allocate a new page. This page will become the right-sibling of
5414 ** pPage. Make the parent page writable, so that the new divider cell
5415 ** may be inserted. If both these operations are successful, proceed.
5416 */
drh4f0c5872007-03-26 22:05:01 +00005417 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk19774dbaa892009-06-16 16:50:22 +00005418
danielk1977eaa06f62008-09-18 17:34:44 +00005419 if( rc==SQLITE_OK ){
danielk1977a50d9aa2009-06-08 14:49:45 +00005420
5421 u8 *pOut = &pSpace[4];
danielk19776f235cc2009-06-04 14:46:08 +00005422 u8 *pCell = pPage->aOvfl[0].pCell;
5423 u16 szCell = cellSizePtr(pPage, pCell);
5424 u8 *pStop;
5425
drhc5053fb2008-11-27 02:22:10 +00005426 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00005427 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
5428 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
danielk1977eaa06f62008-09-18 17:34:44 +00005429 assemblePage(pNew, 1, &pCell, &szCell);
danielk19774dbaa892009-06-16 16:50:22 +00005430
5431 /* If this is an auto-vacuum database, update the pointer map
5432 ** with entries for the new page, and any pointer from the
5433 ** cell on the page to an overflow page. If either of these
5434 ** operations fails, the return code is set, but the contents
5435 ** of the parent page are still manipulated by thh code below.
5436 ** That is Ok, at this point the parent page is guaranteed to
5437 ** be marked as dirty. Returning an error code will cause a
5438 ** rollback, undoing any changes made to the parent page.
5439 */
5440 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00005441 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
5442 if( szCell>pNew->minLocal ){
5443 ptrmapPutOvflPtr(pNew, pCell, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00005444 }
5445 }
danielk1977eaa06f62008-09-18 17:34:44 +00005446
danielk19776f235cc2009-06-04 14:46:08 +00005447 /* Create a divider cell to insert into pParent. The divider cell
5448 ** consists of a 4-byte page number (the page number of pPage) and
5449 ** a variable length key value (which must be the same value as the
5450 ** largest key on pPage).
danielk1977eaa06f62008-09-18 17:34:44 +00005451 **
danielk19776f235cc2009-06-04 14:46:08 +00005452 ** To find the largest key value on pPage, first find the right-most
5453 ** cell on pPage. The first two fields of this cell are the
5454 ** record-length (a variable length integer at most 32-bits in size)
5455 ** and the key value (a variable length integer, may have any value).
5456 ** The first of the while(...) loops below skips over the record-length
5457 ** field. The second while(...) loop copies the key value from the
danielk1977a50d9aa2009-06-08 14:49:45 +00005458 ** cell on pPage into the pSpace buffer.
danielk1977eaa06f62008-09-18 17:34:44 +00005459 */
danielk1977eaa06f62008-09-18 17:34:44 +00005460 pCell = findCell(pPage, pPage->nCell-1);
danielk19776f235cc2009-06-04 14:46:08 +00005461 pStop = &pCell[9];
5462 while( (*(pCell++)&0x80) && pCell<pStop );
5463 pStop = &pCell[9];
5464 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
5465
danielk19774dbaa892009-06-16 16:50:22 +00005466 /* Insert the new divider cell into pParent. */
drh98add2e2009-07-20 17:11:49 +00005467 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
5468 0, pPage->pgno, &rc);
danielk19776f235cc2009-06-04 14:46:08 +00005469
5470 /* Set the right-child pointer of pParent to point to the new page. */
danielk1977eaa06f62008-09-18 17:34:44 +00005471 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
5472
danielk1977e08a3c42008-09-18 18:17:03 +00005473 /* Release the reference to the new page. */
5474 releasePage(pNew);
danielk1977ac11ee62005-01-15 12:45:51 +00005475 }
5476
danielk1977eaa06f62008-09-18 17:34:44 +00005477 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00005478}
drh615ae552005-01-16 23:21:00 +00005479#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00005480
danielk19774dbaa892009-06-16 16:50:22 +00005481#if 0
drhc3b70572003-01-04 19:44:07 +00005482/*
danielk19774dbaa892009-06-16 16:50:22 +00005483** This function does not contribute anything to the operation of SQLite.
5484** it is sometimes activated temporarily while debugging code responsible
5485** for setting pointer-map entries.
5486*/
5487static int ptrmapCheckPages(MemPage **apPage, int nPage){
5488 int i, j;
5489 for(i=0; i<nPage; i++){
5490 Pgno n;
5491 u8 e;
5492 MemPage *pPage = apPage[i];
5493 BtShared *pBt = pPage->pBt;
5494 assert( pPage->isInit );
5495
5496 for(j=0; j<pPage->nCell; j++){
5497 CellInfo info;
5498 u8 *z;
5499
5500 z = findCell(pPage, j);
danielk197730548662009-07-09 05:07:37 +00005501 btreeParseCellPtr(pPage, z, &info);
danielk19774dbaa892009-06-16 16:50:22 +00005502 if( info.iOverflow ){
5503 Pgno ovfl = get4byte(&z[info.iOverflow]);
5504 ptrmapGet(pBt, ovfl, &e, &n);
5505 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
5506 }
5507 if( !pPage->leaf ){
5508 Pgno child = get4byte(z);
5509 ptrmapGet(pBt, child, &e, &n);
5510 assert( n==pPage->pgno && e==PTRMAP_BTREE );
5511 }
5512 }
5513 if( !pPage->leaf ){
5514 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5515 ptrmapGet(pBt, child, &e, &n);
5516 assert( n==pPage->pgno && e==PTRMAP_BTREE );
5517 }
5518 }
5519 return 1;
5520}
5521#endif
5522
danielk1977cd581a72009-06-23 15:43:39 +00005523/*
5524** This function is used to copy the contents of the b-tree node stored
5525** on page pFrom to page pTo. If page pFrom was not a leaf page, then
5526** the pointer-map entries for each child page are updated so that the
5527** parent page stored in the pointer map is page pTo. If pFrom contained
5528** any cells with overflow page pointers, then the corresponding pointer
5529** map entries are also updated so that the parent page is page pTo.
5530**
5531** If pFrom is currently carrying any overflow cells (entries in the
5532** MemPage.aOvfl[] array), they are not copied to pTo.
5533**
danielk197730548662009-07-09 05:07:37 +00005534** Before returning, page pTo is reinitialized using btreeInitPage().
danielk1977cd581a72009-06-23 15:43:39 +00005535**
5536** The performance of this function is not critical. It is only used by
5537** the balance_shallower() and balance_deeper() procedures, neither of
5538** which are called often under normal circumstances.
5539*/
drhc314dc72009-07-21 11:52:34 +00005540static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
5541 if( (*pRC)==SQLITE_OK ){
5542 BtShared * const pBt = pFrom->pBt;
5543 u8 * const aFrom = pFrom->aData;
5544 u8 * const aTo = pTo->aData;
5545 int const iFromHdr = pFrom->hdrOffset;
5546 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
5547 TESTONLY(int rc;)
5548 int iData;
5549
5550
5551 assert( pFrom->isInit );
5552 assert( pFrom->nFree>=iToHdr );
5553 assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
5554
5555 /* Copy the b-tree node content from page pFrom to page pTo. */
5556 iData = get2byte(&aFrom[iFromHdr+5]);
5557 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
5558 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
5559
5560 /* Reinitialize page pTo so that the contents of the MemPage structure
5561 ** match the new data. The initialization of pTo "cannot" fail, as the
5562 ** data copied from pFrom is known to be valid. */
5563 pTo->isInit = 0;
5564 TESTONLY(rc = ) btreeInitPage(pTo);
5565 assert( rc==SQLITE_OK );
5566
5567 /* If this is an auto-vacuum database, update the pointer-map entries
5568 ** for any b-tree or overflow pages that pTo now contains the pointers to.
5569 */
5570 if( ISAUTOVACUUM ){
5571 *pRC = setChildPtrmaps(pTo);
5572 }
danielk1977cd581a72009-06-23 15:43:39 +00005573 }
danielk1977cd581a72009-06-23 15:43:39 +00005574}
5575
5576/*
danielk19774dbaa892009-06-16 16:50:22 +00005577** This routine redistributes cells on the iParentIdx'th child of pParent
5578** (hereafter "the page") and up to 2 siblings so that all pages have about the
5579** same amount of free space. Usually a single sibling on either side of the
5580** page are used in the balancing, though both siblings might come from one
5581** side if the page is the first or last child of its parent. If the page
5582** has fewer than 2 siblings (something which can only happen if the page
5583** is a root page or a child of a root page) then all available siblings
5584** participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00005585**
danielk19774dbaa892009-06-16 16:50:22 +00005586** The number of siblings of the page might be increased or decreased by
5587** one or two in an effort to keep pages nearly full but not over full.
drh14acc042001-06-10 19:56:58 +00005588**
danielk19774dbaa892009-06-16 16:50:22 +00005589** Note that when this routine is called, some of the cells on the page
5590** might not actually be stored in MemPage.aData[]. This can happen
5591** if the page is overfull. This routine ensures that all cells allocated
5592** to the page and its siblings fit into MemPage.aData[] before returning.
drh14acc042001-06-10 19:56:58 +00005593**
danielk19774dbaa892009-06-16 16:50:22 +00005594** In the course of balancing the page and its siblings, cells may be
5595** inserted into or removed from the parent page (pParent). Doing so
5596** may cause the parent page to become overfull or underfull. If this
5597** happens, it is the responsibility of the caller to invoke the correct
5598** balancing routine to fix this problem (see the balance() routine).
drh8c42ca92001-06-22 19:15:00 +00005599**
drh5e00f6c2001-09-13 13:46:56 +00005600** If this routine fails for any reason, it might leave the database
danielk19776067a9b2009-06-09 09:41:00 +00005601** in a corrupted state. So if this routine fails, the database should
drh5e00f6c2001-09-13 13:46:56 +00005602** be rolled back.
danielk19774dbaa892009-06-16 16:50:22 +00005603**
5604** The third argument to this function, aOvflSpace, is a pointer to a
drhcd09c532009-07-20 19:30:00 +00005605** buffer big enough to hold one page. If while inserting cells into the parent
5606** page (pParent) the parent page becomes overfull, this buffer is
5607** used to store the parent's overflow cells. Because this function inserts
danielk19774dbaa892009-06-16 16:50:22 +00005608** a maximum of four divider cells into the parent page, and the maximum
5609** size of a cell stored within an internal node is always less than 1/4
5610** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
5611** enough for all overflow cells.
5612**
5613** If aOvflSpace is set to a null pointer, this function returns
5614** SQLITE_NOMEM.
drh8b2f49b2001-06-08 00:21:52 +00005615*/
danielk19774dbaa892009-06-16 16:50:22 +00005616static int balance_nonroot(
5617 MemPage *pParent, /* Parent page of siblings being balanced */
5618 int iParentIdx, /* Index of "the page" in pParent */
danielk1977cd581a72009-06-23 15:43:39 +00005619 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
5620 int isRoot /* True if pParent is a root-page */
danielk19774dbaa892009-06-16 16:50:22 +00005621){
drh16a9b832007-05-05 18:39:25 +00005622 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00005623 int nCell = 0; /* Number of cells in apCell[] */
5624 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
danielk1977a4124bd2008-12-23 10:37:47 +00005625 int nNew = 0; /* Number of pages in apNew[] */
danielk19774dbaa892009-06-16 16:50:22 +00005626 int nOld; /* Number of pages in apOld[] */
drh14acc042001-06-10 19:56:58 +00005627 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00005628 int nxDiv; /* Next divider slot in pParent->aCell[] */
shane85095702009-06-15 16:27:08 +00005629 int rc = SQLITE_OK; /* The return code */
shane36840fd2009-06-26 16:32:13 +00005630 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00005631 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00005632 int usableSpace; /* Bytes in pPage beyond the header */
5633 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00005634 int subtotal; /* Subtotal of bytes in cells on one page */
drhe5ae5732008-06-15 02:51:47 +00005635 int iSpace1 = 0; /* First unused byte of aSpace1[] */
danielk19776067a9b2009-06-09 09:41:00 +00005636 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
drhfacf0302008-06-17 15:12:00 +00005637 int szScratch; /* Size of scratch memory requested */
drhc3b70572003-01-04 19:44:07 +00005638 MemPage *apOld[NB]; /* pPage and up to two siblings */
drh4b70f112004-05-02 21:12:19 +00005639 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00005640 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
danielk19774dbaa892009-06-16 16:50:22 +00005641 u8 *pRight; /* Location in parent of right-sibling pointer */
5642 u8 *apDiv[NB-1]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00005643 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
5644 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00005645 u8 **apCell = 0; /* All cells begin balanced */
drha9121e42008-02-19 14:59:35 +00005646 u16 *szCell; /* Local size of all cells in apCell[] */
danielk19774dbaa892009-06-16 16:50:22 +00005647 u8 *aSpace1; /* Space for copies of dividers cells */
5648 Pgno pgno; /* Temp var to store a page number in */
drh8b2f49b2001-06-08 00:21:52 +00005649
danielk1977a50d9aa2009-06-08 14:49:45 +00005650 pBt = pParent->pBt;
5651 assert( sqlite3_mutex_held(pBt->mutex) );
5652 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977474b7cc2008-07-09 11:49:46 +00005653
danielk1977e5765212009-06-17 11:13:28 +00005654#if 0
drh43605152004-05-29 21:46:49 +00005655 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
danielk1977e5765212009-06-17 11:13:28 +00005656#endif
drh2e38c322004-09-03 18:38:44 +00005657
danielk19774dbaa892009-06-16 16:50:22 +00005658 /* At this point pParent may have at most one overflow cell. And if
5659 ** this overflow cell is present, it must be the cell with
5660 ** index iParentIdx. This scenario comes about when this function
drhcd09c532009-07-20 19:30:00 +00005661 ** is called (indirectly) from sqlite3BtreeDelete().
5662 */
danielk19774dbaa892009-06-16 16:50:22 +00005663 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
5664 assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
5665
danielk197711a8a862009-06-17 11:49:52 +00005666 if( !aOvflSpace ){
5667 return SQLITE_NOMEM;
5668 }
5669
danielk1977a50d9aa2009-06-08 14:49:45 +00005670 /* Find the sibling pages to balance. Also locate the cells in pParent
5671 ** that divide the siblings. An attempt is made to find NN siblings on
5672 ** either side of pPage. More siblings are taken from one side, however,
5673 ** if there are fewer than NN siblings on the other side. If pParent
danielk19774dbaa892009-06-16 16:50:22 +00005674 ** has NB or fewer children then all children of pParent are taken.
5675 **
5676 ** This loop also drops the divider cells from the parent page. This
5677 ** way, the remainder of the function does not have to deal with any
drhcd09c532009-07-20 19:30:00 +00005678 ** overflow cells in the parent page, since if any existed they will
5679 ** have already been removed.
5680 */
danielk19774dbaa892009-06-16 16:50:22 +00005681 i = pParent->nOverflow + pParent->nCell;
5682 if( i<2 ){
drhc3b70572003-01-04 19:44:07 +00005683 nxDiv = 0;
danielk19774dbaa892009-06-16 16:50:22 +00005684 nOld = i+1;
5685 }else{
5686 nOld = 3;
5687 if( iParentIdx==0 ){
5688 nxDiv = 0;
5689 }else if( iParentIdx==i ){
5690 nxDiv = i-2;
drh14acc042001-06-10 19:56:58 +00005691 }else{
danielk19774dbaa892009-06-16 16:50:22 +00005692 nxDiv = iParentIdx-1;
drh8b2f49b2001-06-08 00:21:52 +00005693 }
danielk19774dbaa892009-06-16 16:50:22 +00005694 i = 2;
5695 }
5696 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
5697 pRight = &pParent->aData[pParent->hdrOffset+8];
5698 }else{
5699 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
5700 }
5701 pgno = get4byte(pRight);
5702 while( 1 ){
5703 rc = getAndInitPage(pBt, pgno, &apOld[i]);
5704 if( rc ){
danielk197789bc4bc2009-07-21 19:25:24 +00005705 memset(apOld, 0, (i+1)*sizeof(MemPage*));
danielk19774dbaa892009-06-16 16:50:22 +00005706 goto balance_cleanup;
5707 }
danielk1977634f2982005-03-28 08:44:07 +00005708 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
danielk19774dbaa892009-06-16 16:50:22 +00005709 if( (i--)==0 ) break;
5710
drhcd09c532009-07-20 19:30:00 +00005711 if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
danielk19774dbaa892009-06-16 16:50:22 +00005712 apDiv[i] = pParent->aOvfl[0].pCell;
5713 pgno = get4byte(apDiv[i]);
5714 szNew[i] = cellSizePtr(pParent, apDiv[i]);
5715 pParent->nOverflow = 0;
5716 }else{
5717 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
5718 pgno = get4byte(apDiv[i]);
5719 szNew[i] = cellSizePtr(pParent, apDiv[i]);
5720
5721 /* Drop the cell from the parent page. apDiv[i] still points to
5722 ** the cell within the parent, even though it has been dropped.
5723 ** This is safe because dropping a cell only overwrites the first
5724 ** four bytes of it, and this function does not need the first
5725 ** four bytes of the divider cell. So the pointer is safe to use
danielk197711a8a862009-06-17 11:49:52 +00005726 ** later on.
5727 **
5728 ** Unless SQLite is compiled in secure-delete mode. In this case,
5729 ** the dropCell() routine will overwrite the entire cell with zeroes.
5730 ** In this case, temporarily copy the cell into the aOvflSpace[]
5731 ** buffer. It will be copied out again as soon as the aSpace[] buffer
5732 ** is allocated. */
5733#ifdef SQLITE_SECURE_DELETE
5734 memcpy(&aOvflSpace[apDiv[i]-pParent->aData], apDiv[i], szNew[i]);
5735 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
5736#endif
drh98add2e2009-07-20 17:11:49 +00005737 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
danielk19774dbaa892009-06-16 16:50:22 +00005738 }
drh8b2f49b2001-06-08 00:21:52 +00005739 }
5740
drha9121e42008-02-19 14:59:35 +00005741 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00005742 ** alignment */
drha9121e42008-02-19 14:59:35 +00005743 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00005744
drh8b2f49b2001-06-08 00:21:52 +00005745 /*
danielk1977634f2982005-03-28 08:44:07 +00005746 ** Allocate space for memory structures
5747 */
danielk19774dbaa892009-06-16 16:50:22 +00005748 k = pBt->pageSize + ROUND8(sizeof(MemPage));
drhfacf0302008-06-17 15:12:00 +00005749 szScratch =
drha9121e42008-02-19 14:59:35 +00005750 nMaxCells*sizeof(u8*) /* apCell */
5751 + nMaxCells*sizeof(u16) /* szCell */
drhe5ae5732008-06-15 02:51:47 +00005752 + pBt->pageSize /* aSpace1 */
danielk19774dbaa892009-06-16 16:50:22 +00005753 + k*nOld; /* Page copies (apCopy) */
drhfacf0302008-06-17 15:12:00 +00005754 apCell = sqlite3ScratchMalloc( szScratch );
danielk197711a8a862009-06-17 11:49:52 +00005755 if( apCell==0 ){
danielk1977634f2982005-03-28 08:44:07 +00005756 rc = SQLITE_NOMEM;
5757 goto balance_cleanup;
5758 }
drha9121e42008-02-19 14:59:35 +00005759 szCell = (u16*)&apCell[nMaxCells];
danielk19774dbaa892009-06-16 16:50:22 +00005760 aSpace1 = (u8*)&szCell[nMaxCells];
drhea598cb2009-04-05 12:22:08 +00005761 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
drh14acc042001-06-10 19:56:58 +00005762
5763 /*
5764 ** Load pointers to all cells on sibling pages and the divider cells
5765 ** into the local apCell[] array. Make copies of the divider cells
danielk19774dbaa892009-06-16 16:50:22 +00005766 ** into space obtained from aSpace1[] and remove the the divider Cells
drhb6f41482004-05-14 01:58:11 +00005767 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00005768 **
5769 ** If the siblings are on leaf pages, then the child pointers of the
5770 ** divider cells are stripped from the cells before they are copied
drhe5ae5732008-06-15 02:51:47 +00005771 ** into aSpace1[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00005772 ** child pointers. If siblings are not leaves, then all cell in
5773 ** apCell[] include child pointers. Either way, all cells in apCell[]
5774 ** are alike.
drh96f5b762004-05-16 16:24:36 +00005775 **
5776 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
5777 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00005778 */
danielk1977a50d9aa2009-06-08 14:49:45 +00005779 leafCorrection = apOld[0]->leaf*4;
5780 leafData = apOld[0]->hasData;
drh8b2f49b2001-06-08 00:21:52 +00005781 for(i=0; i<nOld; i++){
danielk19774dbaa892009-06-16 16:50:22 +00005782 int limit;
5783
5784 /* Before doing anything else, take a copy of the i'th original sibling
5785 ** The rest of this function will use data from the copies rather
5786 ** that the original pages since the original pages will be in the
5787 ** process of being overwritten. */
5788 MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
5789 memcpy(pOld, apOld[i], sizeof(MemPage));
5790 pOld->aData = (void*)&pOld[1];
5791 memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
5792
5793 limit = pOld->nCell+pOld->nOverflow;
drh43605152004-05-29 21:46:49 +00005794 for(j=0; j<limit; j++){
danielk1977634f2982005-03-28 08:44:07 +00005795 assert( nCell<nMaxCells );
drh43605152004-05-29 21:46:49 +00005796 apCell[nCell] = findOverflowCell(pOld, j);
5797 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
danielk19774dbaa892009-06-16 16:50:22 +00005798 nCell++;
5799 }
5800 if( i<nOld-1 && !leafData){
shane36840fd2009-06-26 16:32:13 +00005801 u16 sz = (u16)szNew[i];
danielk19774dbaa892009-06-16 16:50:22 +00005802 u8 *pTemp;
5803 assert( nCell<nMaxCells );
5804 szCell[nCell] = sz;
5805 pTemp = &aSpace1[iSpace1];
5806 iSpace1 += sz;
5807 assert( sz<=pBt->pageSize/4 );
5808 assert( iSpace1<=pBt->pageSize );
5809 memcpy(pTemp, apDiv[i], sz);
5810 apCell[nCell] = pTemp+leafCorrection;
5811 assert( leafCorrection==0 || leafCorrection==4 );
shane36840fd2009-06-26 16:32:13 +00005812 szCell[nCell] = szCell[nCell] - leafCorrection;
danielk19774dbaa892009-06-16 16:50:22 +00005813 if( !pOld->leaf ){
5814 assert( leafCorrection==0 );
5815 assert( pOld->hdrOffset==0 );
5816 /* The right pointer of the child page pOld becomes the left
5817 ** pointer of the divider cell */
5818 memcpy(apCell[nCell], &pOld->aData[8], 4);
5819 }else{
5820 assert( leafCorrection==4 );
5821 if( szCell[nCell]<4 ){
5822 /* Do not allow any cells smaller than 4 bytes. */
5823 szCell[nCell] = 4;
danielk1977ac11ee62005-01-15 12:45:51 +00005824 }
5825 }
drh14acc042001-06-10 19:56:58 +00005826 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00005827 }
drh8b2f49b2001-06-08 00:21:52 +00005828 }
5829
5830 /*
drh6019e162001-07-02 17:51:45 +00005831 ** Figure out the number of pages needed to hold all nCell cells.
5832 ** Store this number in "k". Also compute szNew[] which is the total
5833 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00005834 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00005835 ** cntNew[k] should equal nCell.
5836 **
drh96f5b762004-05-16 16:24:36 +00005837 ** Values computed by this block:
5838 **
5839 ** k: The total number of sibling pages
5840 ** szNew[i]: Spaced used on the i-th sibling page.
5841 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
5842 ** the right of the i-th sibling page.
5843 ** usableSpace: Number of bytes of space available on each sibling.
5844 **
drh8b2f49b2001-06-08 00:21:52 +00005845 */
drh43605152004-05-29 21:46:49 +00005846 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00005847 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00005848 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00005849 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00005850 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00005851 szNew[k] = subtotal - szCell[i];
5852 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00005853 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00005854 subtotal = 0;
5855 k++;
drheac74422009-06-14 12:47:11 +00005856 if( k>NB+1 ){ rc = SQLITE_CORRUPT; goto balance_cleanup; }
drh6019e162001-07-02 17:51:45 +00005857 }
5858 }
5859 szNew[k] = subtotal;
5860 cntNew[k] = nCell;
5861 k++;
drh96f5b762004-05-16 16:24:36 +00005862
5863 /*
5864 ** The packing computed by the previous block is biased toward the siblings
5865 ** on the left side. The left siblings are always nearly full, while the
5866 ** right-most sibling might be nearly empty. This block of code attempts
5867 ** to adjust the packing of siblings to get a better balance.
5868 **
5869 ** This adjustment is more than an optimization. The packing above might
5870 ** be so out of balance as to be illegal. For example, the right-most
5871 ** sibling might be completely empty. This adjustment is not optional.
5872 */
drh6019e162001-07-02 17:51:45 +00005873 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00005874 int szRight = szNew[i]; /* Size of sibling on the right */
5875 int szLeft = szNew[i-1]; /* Size of sibling on the left */
5876 int r; /* Index of right-most cell in left sibling */
5877 int d; /* Index of first cell to the left of right sibling */
5878
5879 r = cntNew[i-1] - 1;
5880 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00005881 assert( d<nMaxCells );
5882 assert( r<nMaxCells );
drh43605152004-05-29 21:46:49 +00005883 while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
5884 szRight += szCell[d] + 2;
5885 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00005886 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00005887 r = cntNew[i-1] - 1;
5888 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00005889 }
drh96f5b762004-05-16 16:24:36 +00005890 szNew[i] = szRight;
5891 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00005892 }
drh09d0deb2005-08-02 17:13:09 +00005893
danielk19776f235cc2009-06-04 14:46:08 +00005894 /* Either we found one or more cells (cntnew[0])>0) or pPage is
drh09d0deb2005-08-02 17:13:09 +00005895 ** a virtual root page. A virtual root page is when the real root
5896 ** page is page 1 and we are the only child of that page.
5897 */
5898 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh8b2f49b2001-06-08 00:21:52 +00005899
danielk1977e5765212009-06-17 11:13:28 +00005900 TRACE(("BALANCE: old: %d %d %d ",
5901 apOld[0]->pgno,
5902 nOld>=2 ? apOld[1]->pgno : 0,
5903 nOld>=3 ? apOld[2]->pgno : 0
5904 ));
5905
drh8b2f49b2001-06-08 00:21:52 +00005906 /*
drh6b308672002-07-08 02:16:37 +00005907 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00005908 */
drheac74422009-06-14 12:47:11 +00005909 if( apOld[0]->pgno<=1 ){
5910 rc = SQLITE_CORRUPT;
5911 goto balance_cleanup;
5912 }
danielk1977a50d9aa2009-06-08 14:49:45 +00005913 pageFlags = apOld[0]->aData[0];
drh14acc042001-06-10 19:56:58 +00005914 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00005915 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00005916 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00005917 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00005918 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00005919 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00005920 nNew++;
danielk197728129562005-01-11 10:25:06 +00005921 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00005922 }else{
drh7aa8f852006-03-28 00:24:44 +00005923 assert( i>0 );
danielk19774dbaa892009-06-16 16:50:22 +00005924 rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
drh6b308672002-07-08 02:16:37 +00005925 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00005926 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00005927 nNew++;
danielk19774dbaa892009-06-16 16:50:22 +00005928
5929 /* Set the pointer-map entry for the new sibling page. */
5930 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00005931 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00005932 if( rc!=SQLITE_OK ){
5933 goto balance_cleanup;
5934 }
5935 }
drh6b308672002-07-08 02:16:37 +00005936 }
drh8b2f49b2001-06-08 00:21:52 +00005937 }
5938
danielk1977299b1872004-11-22 10:02:10 +00005939 /* Free any old pages that were not reused as new pages.
5940 */
5941 while( i<nOld ){
drhc314dc72009-07-21 11:52:34 +00005942 freePage(apOld[i], &rc);
danielk1977299b1872004-11-22 10:02:10 +00005943 if( rc ) goto balance_cleanup;
5944 releasePage(apOld[i]);
5945 apOld[i] = 0;
5946 i++;
5947 }
5948
drh8b2f49b2001-06-08 00:21:52 +00005949 /*
drhf9ffac92002-03-02 19:00:31 +00005950 ** Put the new pages in accending order. This helps to
5951 ** keep entries in the disk file in order so that a scan
5952 ** of the table is a linear scan through the file. That
5953 ** in turn helps the operating system to deliver pages
5954 ** from the disk more rapidly.
5955 **
5956 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00005957 ** n is never more than NB (a small constant), that should
5958 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00005959 **
drhc3b70572003-01-04 19:44:07 +00005960 ** When NB==3, this one optimization makes the database
5961 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00005962 */
5963 for(i=0; i<k-1; i++){
danielk19774dbaa892009-06-16 16:50:22 +00005964 int minV = apNew[i]->pgno;
drhf9ffac92002-03-02 19:00:31 +00005965 int minI = i;
5966 for(j=i+1; j<k; j++){
danielk19774dbaa892009-06-16 16:50:22 +00005967 if( apNew[j]->pgno<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00005968 minI = j;
danielk19774dbaa892009-06-16 16:50:22 +00005969 minV = apNew[j]->pgno;
drhf9ffac92002-03-02 19:00:31 +00005970 }
5971 }
5972 if( minI>i ){
5973 int t;
5974 MemPage *pT;
danielk19774dbaa892009-06-16 16:50:22 +00005975 t = apNew[i]->pgno;
drhf9ffac92002-03-02 19:00:31 +00005976 pT = apNew[i];
drhf9ffac92002-03-02 19:00:31 +00005977 apNew[i] = apNew[minI];
drhf9ffac92002-03-02 19:00:31 +00005978 apNew[minI] = pT;
5979 }
5980 }
danielk1977e5765212009-06-17 11:13:28 +00005981 TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
danielk19774dbaa892009-06-16 16:50:22 +00005982 apNew[0]->pgno, szNew[0],
5983 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
5984 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
5985 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
5986 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
5987
5988 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
5989 put4byte(pRight, apNew[nNew-1]->pgno);
drh24cd67e2004-05-10 16:18:47 +00005990
drhf9ffac92002-03-02 19:00:31 +00005991 /*
drh14acc042001-06-10 19:56:58 +00005992 ** Evenly distribute the data in apCell[] across the new pages.
5993 ** Insert divider cells into pParent as necessary.
5994 */
5995 j = 0;
5996 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00005997 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00005998 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00005999 assert( j<nMaxCells );
drh10131482008-07-11 03:34:09 +00006000 zeroPage(pNew, pageFlags);
drhfa1a98a2004-05-14 19:08:17 +00006001 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00006002 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00006003 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00006004
danielk1977ac11ee62005-01-15 12:45:51 +00006005 j = cntNew[i];
6006
6007 /* If the sibling page assembled above was not the right-most sibling,
6008 ** insert a divider cell into the parent page.
6009 */
danielk19771c3d2bf2009-06-23 16:40:17 +00006010 assert( i<nNew-1 || j==nCell );
6011 if( j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00006012 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00006013 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00006014 int sz;
danielk1977634f2982005-03-28 08:44:07 +00006015
6016 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00006017 pCell = apCell[j];
6018 sz = szCell[j] + leafCorrection;
danielk19776067a9b2009-06-09 09:41:00 +00006019 pTemp = &aOvflSpace[iOvflSpace];
drh4b70f112004-05-02 21:12:19 +00006020 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00006021 memcpy(&pNew->aData[8], pCell, 4);
drh8b18dd42004-05-12 19:18:15 +00006022 }else if( leafData ){
drhfd131da2007-08-07 17:13:03 +00006023 /* If the tree is a leaf-data tree, and the siblings are leaves,
danielk1977ac11ee62005-01-15 12:45:51 +00006024 ** then there is no divider cell in apCell[]. Instead, the divider
6025 ** cell consists of the integer key for the right-most cell of
6026 ** the sibling-page assembled above only.
6027 */
drh6f11bef2004-05-13 01:12:56 +00006028 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00006029 j--;
danielk197730548662009-07-09 05:07:37 +00006030 btreeParseCellPtr(pNew, apCell[j], &info);
drhe5ae5732008-06-15 02:51:47 +00006031 pCell = pTemp;
danielk19774dbaa892009-06-16 16:50:22 +00006032 sz = 4 + putVarint(&pCell[4], info.nKey);
drh8b18dd42004-05-12 19:18:15 +00006033 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00006034 }else{
6035 pCell -= 4;
danielk19774aeff622007-05-12 09:30:47 +00006036 /* Obscure case for non-leaf-data trees: If the cell at pCell was
drh85b623f2007-12-13 21:54:09 +00006037 ** previously stored on a leaf node, and its reported size was 4
danielk19774aeff622007-05-12 09:30:47 +00006038 ** bytes, then it may actually be smaller than this
danielk197730548662009-07-09 05:07:37 +00006039 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
drh85b623f2007-12-13 21:54:09 +00006040 ** any cell). But it is important to pass the correct size to
danielk19774aeff622007-05-12 09:30:47 +00006041 ** insertCell(), so reparse the cell now.
6042 **
6043 ** Note that this can never happen in an SQLite data file, as all
6044 ** cells are at least 4 bytes. It only happens in b-trees used
6045 ** to evaluate "IN (SELECT ...)" and similar clauses.
6046 */
6047 if( szCell[j]==4 ){
6048 assert(leafCorrection==4);
6049 sz = cellSizePtr(pParent, pCell);
6050 }
drh4b70f112004-05-02 21:12:19 +00006051 }
danielk19776067a9b2009-06-09 09:41:00 +00006052 iOvflSpace += sz;
drhe5ae5732008-06-15 02:51:47 +00006053 assert( sz<=pBt->pageSize/4 );
danielk19776067a9b2009-06-09 09:41:00 +00006054 assert( iOvflSpace<=pBt->pageSize );
drh98add2e2009-07-20 17:11:49 +00006055 insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
danielk1977e80463b2004-11-03 03:01:16 +00006056 if( rc!=SQLITE_OK ) goto balance_cleanup;
drhc5053fb2008-11-27 02:22:10 +00006057 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk197785d90ca2008-07-19 14:25:15 +00006058
drh14acc042001-06-10 19:56:58 +00006059 j++;
6060 nxDiv++;
6061 }
6062 }
drh6019e162001-07-02 17:51:45 +00006063 assert( j==nCell );
drh7aa8f852006-03-28 00:24:44 +00006064 assert( nOld>0 );
6065 assert( nNew>0 );
drh4b70f112004-05-02 21:12:19 +00006066 if( (pageFlags & PTF_LEAF)==0 ){
danielk197787c52b52008-07-19 11:49:07 +00006067 u8 *zChild = &apCopy[nOld-1]->aData[8];
6068 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
drh14acc042001-06-10 19:56:58 +00006069 }
6070
danielk197713bd99f2009-06-24 05:40:34 +00006071 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
6072 /* The root page of the b-tree now contains no cells. The only sibling
6073 ** page is the right-child of the parent. Copy the contents of the
6074 ** child page into the parent, decreasing the overall height of the
6075 ** b-tree structure by one. This is described as the "balance-shallower"
6076 ** sub-algorithm in some documentation.
6077 **
6078 ** If this is an auto-vacuum database, the call to copyNodeContent()
6079 ** sets all pointer-map entries corresponding to database image pages
6080 ** for which the pointer is stored within the content being copied.
6081 **
6082 ** The second assert below verifies that the child page is defragmented
6083 ** (it must be, as it was just reconstructed using assemblePage()). This
6084 ** is important if the parent page happens to be page 1 of the database
6085 ** image. */
6086 assert( nNew==1 );
6087 assert( apNew[0]->nFree ==
6088 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
6089 );
drhc314dc72009-07-21 11:52:34 +00006090 copyNodeContent(apNew[0], pParent, &rc);
6091 freePage(apNew[0], &rc);
danielk197713bd99f2009-06-24 05:40:34 +00006092 }else if( ISAUTOVACUUM ){
6093 /* Fix the pointer-map entries for all the cells that were shifted around.
6094 ** There are several different types of pointer-map entries that need to
6095 ** be dealt with by this routine. Some of these have been set already, but
6096 ** many have not. The following is a summary:
6097 **
6098 ** 1) The entries associated with new sibling pages that were not
6099 ** siblings when this function was called. These have already
6100 ** been set. We don't need to worry about old siblings that were
6101 ** moved to the free-list - the freePage() code has taken care
6102 ** of those.
6103 **
6104 ** 2) The pointer-map entries associated with the first overflow
6105 ** page in any overflow chains used by new divider cells. These
6106 ** have also already been taken care of by the insertCell() code.
6107 **
6108 ** 3) If the sibling pages are not leaves, then the child pages of
6109 ** cells stored on the sibling pages may need to be updated.
6110 **
6111 ** 4) If the sibling pages are not internal intkey nodes, then any
6112 ** overflow pages used by these cells may need to be updated
6113 ** (internal intkey nodes never contain pointers to overflow pages).
6114 **
6115 ** 5) If the sibling pages are not leaves, then the pointer-map
6116 ** entries for the right-child pages of each sibling may need
6117 ** to be updated.
6118 **
6119 ** Cases 1 and 2 are dealt with above by other code. The next
6120 ** block deals with cases 3 and 4 and the one after that, case 5. Since
6121 ** setting a pointer map entry is a relatively expensive operation, this
6122 ** code only sets pointer map entries for child or overflow pages that have
6123 ** actually moved between pages. */
danielk19774dbaa892009-06-16 16:50:22 +00006124 MemPage *pNew = apNew[0];
6125 MemPage *pOld = apCopy[0];
6126 int nOverflow = pOld->nOverflow;
6127 int iNextOld = pOld->nCell + nOverflow;
6128 int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
6129 j = 0; /* Current 'old' sibling page */
6130 k = 0; /* Current 'new' sibling page */
drhc314dc72009-07-21 11:52:34 +00006131 for(i=0; i<nCell; i++){
danielk19774dbaa892009-06-16 16:50:22 +00006132 int isDivider = 0;
6133 while( i==iNextOld ){
6134 /* Cell i is the cell immediately following the last cell on old
6135 ** sibling page j. If the siblings are not leaf pages of an
6136 ** intkey b-tree, then cell i was a divider cell. */
6137 pOld = apCopy[++j];
6138 iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
6139 if( pOld->nOverflow ){
6140 nOverflow = pOld->nOverflow;
6141 iOverflow = i + !leafData + pOld->aOvfl[0].idx;
6142 }
6143 isDivider = !leafData;
6144 }
6145
6146 assert(nOverflow>0 || iOverflow<i );
6147 assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
6148 assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
6149 if( i==iOverflow ){
6150 isDivider = 1;
6151 if( (--nOverflow)>0 ){
6152 iOverflow++;
6153 }
6154 }
6155
6156 if( i==cntNew[k] ){
6157 /* Cell i is the cell immediately following the last cell on new
6158 ** sibling page k. If the siblings are not leaf pages of an
6159 ** intkey b-tree, then cell i is a divider cell. */
6160 pNew = apNew[++k];
6161 if( !leafData ) continue;
6162 }
danielk19774dbaa892009-06-16 16:50:22 +00006163 assert( j<nOld );
6164 assert( k<nNew );
6165
6166 /* If the cell was originally divider cell (and is not now) or
6167 ** an overflow cell, or if the cell was located on a different sibling
6168 ** page before the balancing, then the pointer map entries associated
6169 ** with any child or overflow pages need to be updated. */
6170 if( isDivider || pOld->pgno!=pNew->pgno ){
6171 if( !leafCorrection ){
drh98add2e2009-07-20 17:11:49 +00006172 ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006173 }
drh98add2e2009-07-20 17:11:49 +00006174 if( szCell[i]>pNew->minLocal ){
6175 ptrmapPutOvflPtr(pNew, apCell[i], &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006176 }
6177 }
6178 }
6179
6180 if( !leafCorrection ){
drh98add2e2009-07-20 17:11:49 +00006181 for(i=0; i<nNew; i++){
6182 u32 key = get4byte(&apNew[i]->aData[8]);
6183 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006184 }
6185 }
6186
6187#if 0
6188 /* The ptrmapCheckPages() contains assert() statements that verify that
6189 ** all pointer map pages are set correctly. This is helpful while
6190 ** debugging. This is usually disabled because a corrupt database may
6191 ** cause an assert() statement to fail. */
6192 ptrmapCheckPages(apNew, nNew);
6193 ptrmapCheckPages(&pParent, 1);
6194#endif
6195 }
6196
danielk197771d5d2c2008-09-29 11:49:47 +00006197 assert( pParent->isInit );
danielk1977e5765212009-06-17 11:13:28 +00006198 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
6199 nOld, nNew, nCell));
danielk1977cd581a72009-06-23 15:43:39 +00006200
drh8b2f49b2001-06-08 00:21:52 +00006201 /*
drh14acc042001-06-10 19:56:58 +00006202 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00006203 */
drh14acc042001-06-10 19:56:58 +00006204balance_cleanup:
drhfacf0302008-06-17 15:12:00 +00006205 sqlite3ScratchFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00006206 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00006207 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00006208 }
drh14acc042001-06-10 19:56:58 +00006209 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00006210 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00006211 }
danielk1977eaa06f62008-09-18 17:34:44 +00006212
drh8b2f49b2001-06-08 00:21:52 +00006213 return rc;
6214}
6215
drh43605152004-05-29 21:46:49 +00006216
6217/*
danielk1977a50d9aa2009-06-08 14:49:45 +00006218** This function is called when the root page of a b-tree structure is
6219** overfull (has one or more overflow pages).
drh43605152004-05-29 21:46:49 +00006220**
danielk1977a50d9aa2009-06-08 14:49:45 +00006221** A new child page is allocated and the contents of the current root
6222** page, including overflow cells, are copied into the child. The root
6223** page is then overwritten to make it an empty page with the right-child
6224** pointer pointing to the new page.
6225**
6226** Before returning, all pointer-map entries corresponding to pages
6227** that the new child-page now contains pointers to are updated. The
6228** entry corresponding to the new right-child pointer of the root
6229** page is also updated.
6230**
6231** If successful, *ppChild is set to contain a reference to the child
6232** page and SQLITE_OK is returned. In this case the caller is required
6233** to call releasePage() on *ppChild exactly once. If an error occurs,
6234** an error code is returned and *ppChild is set to 0.
drh43605152004-05-29 21:46:49 +00006235*/
danielk1977a50d9aa2009-06-08 14:49:45 +00006236static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
6237 int rc; /* Return value from subprocedures */
6238 MemPage *pChild = 0; /* Pointer to a new child page */
6239 Pgno pgnoChild; /* Page number of the new child page */
6240 BtShared *pBt = pRoot->pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00006241
danielk1977a50d9aa2009-06-08 14:49:45 +00006242 assert( pRoot->nOverflow>0 );
drh1fee73e2007-08-29 04:00:57 +00006243 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bc2ca9e2008-11-13 14:28:28 +00006244
danielk1977a50d9aa2009-06-08 14:49:45 +00006245 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
6246 ** page that will become the new right-child of pPage. Copy the contents
6247 ** of the node stored on pRoot into the new child page.
6248 */
drh98add2e2009-07-20 17:11:49 +00006249 rc = sqlite3PagerWrite(pRoot->pDbPage);
6250 if( rc==SQLITE_OK ){
6251 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
drhc314dc72009-07-21 11:52:34 +00006252 copyNodeContent(pRoot, pChild, &rc);
6253 if( ISAUTOVACUUM ){
6254 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
drh98add2e2009-07-20 17:11:49 +00006255 }
6256 }
6257 if( rc ){
danielk1977a50d9aa2009-06-08 14:49:45 +00006258 *ppChild = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00006259 releasePage(pChild);
danielk1977a50d9aa2009-06-08 14:49:45 +00006260 return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00006261 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006262 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
6263 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
6264 assert( pChild->nCell==pRoot->nCell );
danielk197771d5d2c2008-09-29 11:49:47 +00006265
danielk1977a50d9aa2009-06-08 14:49:45 +00006266 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
6267
6268 /* Copy the overflow cells from pRoot to pChild */
6269 memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
6270 pChild->nOverflow = pRoot->nOverflow;
danielk1977a50d9aa2009-06-08 14:49:45 +00006271
6272 /* Zero the contents of pRoot. Then install pChild as the right-child. */
6273 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
6274 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
6275
6276 *ppChild = pChild;
6277 return SQLITE_OK;
drh43605152004-05-29 21:46:49 +00006278}
6279
6280/*
danielk197771d5d2c2008-09-29 11:49:47 +00006281** The page that pCur currently points to has just been modified in
6282** some way. This function figures out if this modification means the
6283** tree needs to be balanced, and if so calls the appropriate balancing
danielk1977a50d9aa2009-06-08 14:49:45 +00006284** routine. Balancing routines are:
6285**
6286** balance_quick()
danielk1977a50d9aa2009-06-08 14:49:45 +00006287** balance_deeper()
6288** balance_nonroot()
drh43605152004-05-29 21:46:49 +00006289*/
danielk1977a50d9aa2009-06-08 14:49:45 +00006290static int balance(BtCursor *pCur){
drh43605152004-05-29 21:46:49 +00006291 int rc = SQLITE_OK;
danielk1977a50d9aa2009-06-08 14:49:45 +00006292 const int nMin = pCur->pBt->usableSize * 2 / 3;
6293 u8 aBalanceQuickSpace[13];
6294 u8 *pFree = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00006295
shane75ac1de2009-06-09 18:58:52 +00006296 TESTONLY( int balance_quick_called = 0 );
6297 TESTONLY( int balance_deeper_called = 0 );
danielk1977a50d9aa2009-06-08 14:49:45 +00006298
6299 do {
6300 int iPage = pCur->iPage;
6301 MemPage *pPage = pCur->apPage[iPage];
6302
6303 if( iPage==0 ){
6304 if( pPage->nOverflow ){
6305 /* The root page of the b-tree is overfull. In this case call the
6306 ** balance_deeper() function to create a new child for the root-page
6307 ** and copy the current contents of the root-page to it. The
6308 ** next iteration of the do-loop will balance the child page.
6309 */
6310 assert( (balance_deeper_called++)==0 );
6311 rc = balance_deeper(pPage, &pCur->apPage[1]);
6312 if( rc==SQLITE_OK ){
6313 pCur->iPage = 1;
6314 pCur->aiIdx[0] = 0;
6315 pCur->aiIdx[1] = 0;
6316 assert( pCur->apPage[1]->nOverflow );
6317 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006318 }else{
danielk1977a50d9aa2009-06-08 14:49:45 +00006319 break;
6320 }
6321 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
6322 break;
6323 }else{
6324 MemPage * const pParent = pCur->apPage[iPage-1];
6325 int const iIdx = pCur->aiIdx[iPage-1];
6326
6327 rc = sqlite3PagerWrite(pParent->pDbPage);
6328 if( rc==SQLITE_OK ){
6329#ifndef SQLITE_OMIT_QUICKBALANCE
6330 if( pPage->hasData
6331 && pPage->nOverflow==1
6332 && pPage->aOvfl[0].idx==pPage->nCell
6333 && pParent->pgno!=1
6334 && pParent->nCell==iIdx
6335 ){
6336 /* Call balance_quick() to create a new sibling of pPage on which
6337 ** to store the overflow cell. balance_quick() inserts a new cell
6338 ** into pParent, which may cause pParent overflow. If this
6339 ** happens, the next interation of the do-loop will balance pParent
6340 ** use either balance_nonroot() or balance_deeper(). Until this
6341 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
6342 ** buffer.
6343 **
6344 ** The purpose of the following assert() is to check that only a
6345 ** single call to balance_quick() is made for each call to this
6346 ** function. If this were not verified, a subtle bug involving reuse
6347 ** of the aBalanceQuickSpace[] might sneak in.
6348 */
6349 assert( (balance_quick_called++)==0 );
6350 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
6351 }else
6352#endif
6353 {
6354 /* In this case, call balance_nonroot() to redistribute cells
6355 ** between pPage and up to 2 of its sibling pages. This involves
6356 ** modifying the contents of pParent, which may cause pParent to
6357 ** become overfull or underfull. The next iteration of the do-loop
6358 ** will balance the parent page to correct this.
6359 **
6360 ** If the parent page becomes overfull, the overflow cell or cells
6361 ** are stored in the pSpace buffer allocated immediately below.
6362 ** A subsequent iteration of the do-loop will deal with this by
6363 ** calling balance_nonroot() (balance_deeper() may be called first,
6364 ** but it doesn't deal with overflow cells - just moves them to a
6365 ** different page). Once this subsequent call to balance_nonroot()
6366 ** has completed, it is safe to release the pSpace buffer used by
6367 ** the previous call, as the overflow cell data will have been
6368 ** copied either into the body of a database page or into the new
6369 ** pSpace buffer passed to the latter call to balance_nonroot().
6370 */
6371 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
danielk1977cd581a72009-06-23 15:43:39 +00006372 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
danielk1977a50d9aa2009-06-08 14:49:45 +00006373 if( pFree ){
6374 /* If pFree is not NULL, it points to the pSpace buffer used
6375 ** by a previous call to balance_nonroot(). Its contents are
6376 ** now stored either on real database pages or within the
6377 ** new pSpace buffer, so it may be safely freed here. */
6378 sqlite3PageFree(pFree);
6379 }
6380
danielk19774dbaa892009-06-16 16:50:22 +00006381 /* The pSpace buffer will be freed after the next call to
6382 ** balance_nonroot(), or just before this function returns, whichever
6383 ** comes first. */
danielk1977a50d9aa2009-06-08 14:49:45 +00006384 pFree = pSpace;
danielk1977a50d9aa2009-06-08 14:49:45 +00006385 }
6386 }
6387
6388 pPage->nOverflow = 0;
6389
6390 /* The next iteration of the do-loop balances the parent page. */
6391 releasePage(pPage);
6392 pCur->iPage--;
drh43605152004-05-29 21:46:49 +00006393 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006394 }while( rc==SQLITE_OK );
6395
6396 if( pFree ){
6397 sqlite3PageFree(pFree);
drh43605152004-05-29 21:46:49 +00006398 }
6399 return rc;
6400}
6401
drhf74b8d92002-09-01 23:20:45 +00006402
6403/*
drh3b7511c2001-05-26 13:15:44 +00006404** Insert a new record into the BTree. The key is given by (pKey,nKey)
6405** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00006406** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00006407** is left pointing at a random location.
6408**
6409** For an INTKEY table, only the nKey value of the key is used. pKey is
6410** ignored. For a ZERODATA table, the pData and nData are both ignored.
danielk1977de630352009-05-04 11:42:29 +00006411**
6412** If the seekResult parameter is non-zero, then a successful call to
danielk19773509a652009-07-06 18:56:13 +00006413** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
danielk1977de630352009-05-04 11:42:29 +00006414** been performed. seekResult is the search result returned (a negative
6415** number if pCur points at an entry that is smaller than (pKey, nKey), or
6416** a positive value if pCur points at an etry that is larger than
6417** (pKey, nKey)).
6418**
6419** If the seekResult parameter is 0, then cursor pCur may point to any
6420** entry or to no entry at all. In this case this function has to seek
6421** the cursor before the new key can be inserted.
drh3b7511c2001-05-26 13:15:44 +00006422*/
drh3aac2dd2004-04-26 14:10:20 +00006423int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00006424 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00006425 const void *pKey, i64 nKey, /* The key of the new record */
drhe4d90812007-03-29 05:51:49 +00006426 const void *pData, int nData, /* The data of the new record */
drhb026e052007-05-02 01:34:31 +00006427 int nZero, /* Number of extra 0 bytes to append to data */
danielk1977de630352009-05-04 11:42:29 +00006428 int appendBias, /* True if this is likely an append */
danielk19773509a652009-07-06 18:56:13 +00006429 int seekResult /* Result of prior MovetoUnpacked() call */
drh3b7511c2001-05-26 13:15:44 +00006430){
drh3b7511c2001-05-26 13:15:44 +00006431 int rc;
danielk1977de630352009-05-04 11:42:29 +00006432 int loc = seekResult;
drh14acc042001-06-10 19:56:58 +00006433 int szNew;
danielk197771d5d2c2008-09-29 11:49:47 +00006434 int idx;
drh3b7511c2001-05-26 13:15:44 +00006435 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00006436 Btree *p = pCur->pBtree;
6437 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00006438 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00006439 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00006440
drh98add2e2009-07-20 17:11:49 +00006441 if( pCur->eState==CURSOR_FAULT ){
6442 assert( pCur->skipNext!=SQLITE_OK );
6443 return pCur->skipNext;
6444 }
6445
drh1fee73e2007-08-29 04:00:57 +00006446 assert( cursorHoldsMutex(pCur) );
danielk197731d31b82009-07-13 13:18:07 +00006447 assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
danielk197796d48e92009-06-29 06:00:37 +00006448 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
6449
danielk197731d31b82009-07-13 13:18:07 +00006450 /* Assert that the caller has been consistent. If this cursor was opened
6451 ** expecting an index b-tree, then the caller should be inserting blob
6452 ** keys with no associated data. If the cursor was opened expecting an
6453 ** intkey table, the caller should be inserting integer keys with a
6454 ** blob of associated data. */
6455 assert( (pKey==0)==(pCur->pKeyInfo==0) );
6456
danielk197796d48e92009-06-29 06:00:37 +00006457 /* If this is an insert into a table b-tree, invalidate any incrblob
6458 ** cursors open on the row being replaced (assuming this is a replace
6459 ** operation - if it is not, the following is a no-op). */
6460 if( pCur->pKeyInfo==0 ){
drheeb844a2009-08-08 18:01:07 +00006461 invalidateIncrblobCursors(p, nKey, 0);
drhf74b8d92002-09-01 23:20:45 +00006462 }
danielk197796d48e92009-06-29 06:00:37 +00006463
danielk19779c3acf32009-05-02 07:36:49 +00006464 /* Save the positions of any other cursors open on this table.
6465 **
danielk19773509a652009-07-06 18:56:13 +00006466 ** In some cases, the call to btreeMoveto() below is a no-op. For
danielk19779c3acf32009-05-02 07:36:49 +00006467 ** example, when inserting data into a table with auto-generated integer
6468 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
6469 ** integer key to use. It then calls this function to actually insert the
danielk19773509a652009-07-06 18:56:13 +00006470 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
danielk19779c3acf32009-05-02 07:36:49 +00006471 ** that the cursor is already where it needs to be and returns without
6472 ** doing any work. To avoid thwarting these optimizations, it is important
6473 ** not to clear the cursor here.
6474 */
drh4c301aa2009-07-15 17:25:45 +00006475 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
6476 if( rc ) return rc;
6477 if( !loc ){
6478 rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
6479 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00006480 }
danielk1977b980d2212009-06-22 18:03:51 +00006481 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
danielk1977da184232006-01-05 11:34:32 +00006482
danielk197771d5d2c2008-09-29 11:49:47 +00006483 pPage = pCur->apPage[pCur->iPage];
drh4a1c3802004-05-12 15:15:47 +00006484 assert( pPage->intKey || nKey>=0 );
drh44845222008-07-17 18:39:57 +00006485 assert( pPage->leaf || !pPage->intKey );
danielk19778f880a82009-07-13 09:41:45 +00006486
drh3a4c1412004-05-09 20:40:11 +00006487 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
6488 pCur->pgnoRoot, nKey, nData, pPage->pgno,
6489 loc==0 ? "overwrite" : "new entry"));
danielk197771d5d2c2008-09-29 11:49:47 +00006490 assert( pPage->isInit );
danielk197752ae7242008-03-25 14:24:56 +00006491 allocateTempSpace(pBt);
6492 newCell = pBt->pTmpSpace;
drh2e38c322004-09-03 18:38:44 +00006493 if( newCell==0 ) return SQLITE_NOMEM;
drhb026e052007-05-02 01:34:31 +00006494 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
drh2e38c322004-09-03 18:38:44 +00006495 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00006496 assert( szNew==cellSizePtr(pPage, newCell) );
drh2e38c322004-09-03 18:38:44 +00006497 assert( szNew<=MX_CELL_SIZE(pBt) );
danielk197771d5d2c2008-09-29 11:49:47 +00006498 idx = pCur->aiIdx[pCur->iPage];
danielk1977b980d2212009-06-22 18:03:51 +00006499 if( loc==0 ){
drha9121e42008-02-19 14:59:35 +00006500 u16 szOld;
danielk197771d5d2c2008-09-29 11:49:47 +00006501 assert( idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00006502 rc = sqlite3PagerWrite(pPage->pDbPage);
6503 if( rc ){
6504 goto end_insert;
6505 }
danielk197771d5d2c2008-09-29 11:49:47 +00006506 oldCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00006507 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00006508 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00006509 }
drh43605152004-05-29 21:46:49 +00006510 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00006511 rc = clearCell(pPage, oldCell);
drh98add2e2009-07-20 17:11:49 +00006512 dropCell(pPage, idx, szOld, &rc);
drh2e38c322004-09-03 18:38:44 +00006513 if( rc ) goto end_insert;
drh7c717f72001-06-24 20:39:41 +00006514 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00006515 assert( pPage->leaf );
danielk197771d5d2c2008-09-29 11:49:47 +00006516 idx = ++pCur->aiIdx[pCur->iPage];
drh14acc042001-06-10 19:56:58 +00006517 }else{
drh4b70f112004-05-02 21:12:19 +00006518 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00006519 }
drh98add2e2009-07-20 17:11:49 +00006520 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
danielk19773f632d52009-05-02 10:03:09 +00006521 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
drh9bf9e9c2008-12-05 20:01:43 +00006522
danielk1977a50d9aa2009-06-08 14:49:45 +00006523 /* If no error has occured and pPage has an overflow cell, call balance()
6524 ** to redistribute the cells within the tree. Since balance() may move
6525 ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
6526 ** variables.
danielk19773f632d52009-05-02 10:03:09 +00006527 **
danielk1977a50d9aa2009-06-08 14:49:45 +00006528 ** Previous versions of SQLite called moveToRoot() to move the cursor
6529 ** back to the root page as balance() used to invalidate the contents
danielk197754109bb2009-06-23 11:22:29 +00006530 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
6531 ** set the cursor state to "invalid". This makes common insert operations
6532 ** slightly faster.
danielk19773f632d52009-05-02 10:03:09 +00006533 **
danielk1977a50d9aa2009-06-08 14:49:45 +00006534 ** There is a subtle but important optimization here too. When inserting
6535 ** multiple records into an intkey b-tree using a single cursor (as can
6536 ** happen while processing an "INSERT INTO ... SELECT" statement), it
6537 ** is advantageous to leave the cursor pointing to the last entry in
6538 ** the b-tree if possible. If the cursor is left pointing to the last
6539 ** entry in the table, and the next row inserted has an integer key
6540 ** larger than the largest existing key, it is possible to insert the
6541 ** row without seeking the cursor. This can be a big performance boost.
danielk19773f632d52009-05-02 10:03:09 +00006542 */
danielk1977a50d9aa2009-06-08 14:49:45 +00006543 pCur->info.nSize = 0;
6544 pCur->validNKey = 0;
6545 if( rc==SQLITE_OK && pPage->nOverflow ){
danielk1977a50d9aa2009-06-08 14:49:45 +00006546 rc = balance(pCur);
6547
6548 /* Must make sure nOverflow is reset to zero even if the balance()
danielk197754109bb2009-06-23 11:22:29 +00006549 ** fails. Internal data structure corruption will result otherwise.
6550 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
6551 ** from trying to save the current position of the cursor. */
danielk1977a50d9aa2009-06-08 14:49:45 +00006552 pCur->apPage[pCur->iPage]->nOverflow = 0;
danielk197754109bb2009-06-23 11:22:29 +00006553 pCur->eState = CURSOR_INVALID;
danielk19773f632d52009-05-02 10:03:09 +00006554 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006555 assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
drh9bf9e9c2008-12-05 20:01:43 +00006556
drh2e38c322004-09-03 18:38:44 +00006557end_insert:
drh5e2f8b92001-05-28 00:41:15 +00006558 return rc;
6559}
6560
6561/*
drh4b70f112004-05-02 21:12:19 +00006562** Delete the entry that the cursor is pointing to. The cursor
drhf94a1732008-09-30 17:18:17 +00006563** is left pointing at a arbitrary location.
drh3b7511c2001-05-26 13:15:44 +00006564*/
drh3aac2dd2004-04-26 14:10:20 +00006565int sqlite3BtreeDelete(BtCursor *pCur){
drhd677b3d2007-08-20 22:48:41 +00006566 Btree *p = pCur->pBtree;
danielk19774dbaa892009-06-16 16:50:22 +00006567 BtShared *pBt = p->pBt;
6568 int rc; /* Return code */
6569 MemPage *pPage; /* Page to delete cell from */
6570 unsigned char *pCell; /* Pointer to cell to delete */
6571 int iCellIdx; /* Index of cell to delete */
6572 int iCellDepth; /* Depth of node containing pCell */
drh8b2f49b2001-06-08 00:21:52 +00006573
drh1fee73e2007-08-29 04:00:57 +00006574 assert( cursorHoldsMutex(pCur) );
drh64022502009-01-09 14:11:04 +00006575 assert( pBt->inTransaction==TRANS_WRITE );
drhf74b8d92002-09-01 23:20:45 +00006576 assert( !pBt->readOnly );
drh64022502009-01-09 14:11:04 +00006577 assert( pCur->wrFlag );
danielk197796d48e92009-06-29 06:00:37 +00006578 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
6579 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
6580
danielk19774dbaa892009-06-16 16:50:22 +00006581 if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
6582 || NEVER(pCur->eState!=CURSOR_VALID)
6583 ){
6584 return SQLITE_ERROR; /* Something has gone awry. */
drhf74b8d92002-09-01 23:20:45 +00006585 }
danielk1977da184232006-01-05 11:34:32 +00006586
danielk197796d48e92009-06-29 06:00:37 +00006587 /* If this is a delete operation to remove a row from a table b-tree,
6588 ** invalidate any incrblob cursors open on the row being deleted. */
6589 if( pCur->pKeyInfo==0 ){
drheeb844a2009-08-08 18:01:07 +00006590 invalidateIncrblobCursors(p, pCur->info.nKey, 0);
danielk19774dbaa892009-06-16 16:50:22 +00006591 }
6592
6593 iCellDepth = pCur->iPage;
6594 iCellIdx = pCur->aiIdx[iCellDepth];
6595 pPage = pCur->apPage[iCellDepth];
6596 pCell = findCell(pPage, iCellIdx);
6597
6598 /* If the page containing the entry to delete is not a leaf page, move
6599 ** the cursor to the largest entry in the tree that is smaller than
6600 ** the entry being deleted. This cell will replace the cell being deleted
6601 ** from the internal node. The 'previous' entry is used for this instead
6602 ** of the 'next' entry, as the previous entry is always a part of the
6603 ** sub-tree headed by the child page of the cell being deleted. This makes
6604 ** balancing the tree following the delete operation easier. */
6605 if( !pPage->leaf ){
6606 int notUsed;
drh4c301aa2009-07-15 17:25:45 +00006607 rc = sqlite3BtreePrevious(pCur, &notUsed);
6608 if( rc ) return rc;
danielk19774dbaa892009-06-16 16:50:22 +00006609 }
6610
6611 /* Save the positions of any other cursors open on this table before
6612 ** making any modifications. Make the page containing the entry to be
6613 ** deleted writable. Then free any overflow pages associated with the
drha4ec1d42009-07-11 13:13:11 +00006614 ** entry and finally remove the cell itself from within the page.
6615 */
6616 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
6617 if( rc ) return rc;
6618 rc = sqlite3PagerWrite(pPage->pDbPage);
6619 if( rc ) return rc;
6620 rc = clearCell(pPage, pCell);
drh98add2e2009-07-20 17:11:49 +00006621 dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
drha4ec1d42009-07-11 13:13:11 +00006622 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00006623
danielk19774dbaa892009-06-16 16:50:22 +00006624 /* If the cell deleted was not located on a leaf page, then the cursor
6625 ** is currently pointing to the largest entry in the sub-tree headed
6626 ** by the child-page of the cell that was just deleted from an internal
6627 ** node. The cell from the leaf node needs to be moved to the internal
6628 ** node to replace the deleted cell. */
drh4b70f112004-05-02 21:12:19 +00006629 if( !pPage->leaf ){
danielk19774dbaa892009-06-16 16:50:22 +00006630 MemPage *pLeaf = pCur->apPage[pCur->iPage];
6631 int nCell;
6632 Pgno n = pCur->apPage[iCellDepth+1]->pgno;
6633 unsigned char *pTmp;
danielk1977e6efa742004-11-10 11:55:10 +00006634
danielk19774dbaa892009-06-16 16:50:22 +00006635 pCell = findCell(pLeaf, pLeaf->nCell-1);
6636 nCell = cellSizePtr(pLeaf, pCell);
6637 assert( MX_CELL_SIZE(pBt)>=nCell );
danielk197771d5d2c2008-09-29 11:49:47 +00006638
danielk19774dbaa892009-06-16 16:50:22 +00006639 allocateTempSpace(pBt);
6640 pTmp = pBt->pTmpSpace;
danielk19772f78fc62008-09-30 09:31:45 +00006641
drha4ec1d42009-07-11 13:13:11 +00006642 rc = sqlite3PagerWrite(pLeaf->pDbPage);
drh98add2e2009-07-20 17:11:49 +00006643 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
6644 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
drha4ec1d42009-07-11 13:13:11 +00006645 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00006646 }
danielk19774dbaa892009-06-16 16:50:22 +00006647
6648 /* Balance the tree. If the entry deleted was located on a leaf page,
6649 ** then the cursor still points to that page. In this case the first
6650 ** call to balance() repairs the tree, and the if(...) condition is
6651 ** never true.
6652 **
6653 ** Otherwise, if the entry deleted was on an internal node page, then
6654 ** pCur is pointing to the leaf page from which a cell was removed to
6655 ** replace the cell deleted from the internal node. This is slightly
6656 ** tricky as the leaf node may be underfull, and the internal node may
6657 ** be either under or overfull. In this case run the balancing algorithm
6658 ** on the leaf node first. If the balance proceeds far enough up the
6659 ** tree that we can be sure that any problem in the internal node has
6660 ** been corrected, so be it. Otherwise, after balancing the leaf node,
6661 ** walk the cursor up the tree to the internal node and balance it as
6662 ** well. */
6663 rc = balance(pCur);
6664 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
6665 while( pCur->iPage>iCellDepth ){
6666 releasePage(pCur->apPage[pCur->iPage--]);
6667 }
6668 rc = balance(pCur);
6669 }
6670
danielk19776b456a22005-03-21 04:04:02 +00006671 if( rc==SQLITE_OK ){
6672 moveToRoot(pCur);
6673 }
drh5e2f8b92001-05-28 00:41:15 +00006674 return rc;
drh3b7511c2001-05-26 13:15:44 +00006675}
drh8b2f49b2001-06-08 00:21:52 +00006676
6677/*
drhc6b52df2002-01-04 03:09:29 +00006678** Create a new BTree table. Write into *piTable the page
6679** number for the root page of the new table.
6680**
drhab01f612004-05-22 02:55:23 +00006681** The type of type is determined by the flags parameter. Only the
6682** following values of flags are currently in use. Other values for
6683** flags might not work:
6684**
6685** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
6686** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00006687*/
drhd677b3d2007-08-20 22:48:41 +00006688static int btreeCreateTable(Btree *p, int *piTable, int flags){
danielk1977aef0bf62005-12-30 16:28:01 +00006689 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00006690 MemPage *pRoot;
6691 Pgno pgnoRoot;
6692 int rc;
drhd677b3d2007-08-20 22:48:41 +00006693
drh1fee73e2007-08-29 04:00:57 +00006694 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00006695 assert( pBt->inTransaction==TRANS_WRITE );
danielk197728129562005-01-11 10:25:06 +00006696 assert( !pBt->readOnly );
danielk1977e6efa742004-11-10 11:55:10 +00006697
danielk1977003ba062004-11-04 02:57:33 +00006698#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00006699 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00006700 if( rc ){
6701 return rc;
6702 }
danielk1977003ba062004-11-04 02:57:33 +00006703#else
danielk1977687566d2004-11-02 12:56:41 +00006704 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00006705 Pgno pgnoMove; /* Move a page here to make room for the root-page */
6706 MemPage *pPageMove; /* The page to move to. */
6707
danielk197720713f32007-05-03 11:43:33 +00006708 /* Creating a new table may probably require moving an existing database
6709 ** to make room for the new tables root page. In case this page turns
6710 ** out to be an overflow page, delete all overflow page-map caches
6711 ** held by open cursors.
6712 */
danielk197792d4d7a2007-05-04 12:05:56 +00006713 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00006714
danielk1977003ba062004-11-04 02:57:33 +00006715 /* Read the value of meta[3] from the database to determine where the
6716 ** root page of the new table should go. meta[3] is the largest root-page
6717 ** created so far, so the new root-page is (meta[3]+1).
6718 */
danielk1977602b4662009-07-02 07:47:33 +00006719 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00006720 pgnoRoot++;
6721
danielk1977599fcba2004-11-08 07:13:13 +00006722 /* The new root-page may not be allocated on a pointer-map page, or the
6723 ** PENDING_BYTE page.
6724 */
drh72190432008-01-31 14:54:43 +00006725 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00006726 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00006727 pgnoRoot++;
6728 }
6729 assert( pgnoRoot>=3 );
6730
6731 /* Allocate a page. The page that currently resides at pgnoRoot will
6732 ** be moved to the allocated page (unless the allocated page happens
6733 ** to reside at pgnoRoot).
6734 */
drh4f0c5872007-03-26 22:05:01 +00006735 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
danielk1977003ba062004-11-04 02:57:33 +00006736 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00006737 return rc;
6738 }
danielk1977003ba062004-11-04 02:57:33 +00006739
6740 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00006741 /* pgnoRoot is the page that will be used for the root-page of
6742 ** the new table (assuming an error did not occur). But we were
6743 ** allocated pgnoMove. If required (i.e. if it was not allocated
6744 ** by extending the file), the current page at position pgnoMove
6745 ** is already journaled.
6746 */
drheeb844a2009-08-08 18:01:07 +00006747 u8 eType = 0;
6748 Pgno iPtrPage = 0;
danielk1977003ba062004-11-04 02:57:33 +00006749
6750 releasePage(pPageMove);
danielk1977f35843b2007-04-07 15:03:17 +00006751
6752 /* Move the page currently at pgnoRoot to pgnoMove. */
danielk197730548662009-07-09 05:07:37 +00006753 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006754 if( rc!=SQLITE_OK ){
6755 return rc;
6756 }
6757 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drh27731d72009-06-22 12:05:10 +00006758 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
6759 rc = SQLITE_CORRUPT_BKPT;
6760 }
6761 if( rc!=SQLITE_OK ){
danielk1977003ba062004-11-04 02:57:33 +00006762 releasePage(pRoot);
6763 return rc;
6764 }
drhccae6022005-02-26 17:31:26 +00006765 assert( eType!=PTRMAP_ROOTPAGE );
6766 assert( eType!=PTRMAP_FREEPAGE );
danielk19774c999992008-07-16 18:17:55 +00006767 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
danielk1977003ba062004-11-04 02:57:33 +00006768 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00006769
6770 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00006771 if( rc!=SQLITE_OK ){
6772 return rc;
6773 }
danielk197730548662009-07-09 05:07:37 +00006774 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00006775 if( rc!=SQLITE_OK ){
6776 return rc;
6777 }
danielk19773b8a05f2007-03-19 17:44:26 +00006778 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00006779 if( rc!=SQLITE_OK ){
6780 releasePage(pRoot);
6781 return rc;
6782 }
6783 }else{
6784 pRoot = pPageMove;
6785 }
6786
danielk197742741be2005-01-08 12:42:39 +00006787 /* Update the pointer-map and meta-data with the new root-page number. */
drh98add2e2009-07-20 17:11:49 +00006788 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
danielk1977003ba062004-11-04 02:57:33 +00006789 if( rc ){
6790 releasePage(pRoot);
6791 return rc;
6792 }
danielk1977aef0bf62005-12-30 16:28:01 +00006793 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00006794 if( rc ){
6795 releasePage(pRoot);
6796 return rc;
6797 }
danielk197742741be2005-01-08 12:42:39 +00006798
danielk1977003ba062004-11-04 02:57:33 +00006799 }else{
drh4f0c5872007-03-26 22:05:01 +00006800 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00006801 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00006802 }
6803#endif
danielk19773b8a05f2007-03-19 17:44:26 +00006804 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhde647132004-05-07 17:57:49 +00006805 zeroPage(pRoot, flags | PTF_LEAF);
danielk19773b8a05f2007-03-19 17:44:26 +00006806 sqlite3PagerUnref(pRoot->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00006807 *piTable = (int)pgnoRoot;
6808 return SQLITE_OK;
6809}
drhd677b3d2007-08-20 22:48:41 +00006810int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
6811 int rc;
6812 sqlite3BtreeEnter(p);
6813 rc = btreeCreateTable(p, piTable, flags);
6814 sqlite3BtreeLeave(p);
6815 return rc;
6816}
drh8b2f49b2001-06-08 00:21:52 +00006817
6818/*
6819** Erase the given database page and all its children. Return
6820** the page to the freelist.
6821*/
drh4b70f112004-05-02 21:12:19 +00006822static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00006823 BtShared *pBt, /* The BTree that contains the table */
drh4b70f112004-05-02 21:12:19 +00006824 Pgno pgno, /* Page number to clear */
danielk1977c7af4842008-10-27 13:59:33 +00006825 int freePageFlag, /* Deallocate page if true */
6826 int *pnChange
drh4b70f112004-05-02 21:12:19 +00006827){
danielk1977146ba992009-07-22 14:08:13 +00006828 MemPage *pPage;
drh8b2f49b2001-06-08 00:21:52 +00006829 int rc;
drh4b70f112004-05-02 21:12:19 +00006830 unsigned char *pCell;
6831 int i;
drh8b2f49b2001-06-08 00:21:52 +00006832
drh1fee73e2007-08-29 04:00:57 +00006833 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197789d40042008-11-17 14:20:56 +00006834 if( pgno>pagerPagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00006835 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00006836 }
6837
danielk197771d5d2c2008-09-29 11:49:47 +00006838 rc = getAndInitPage(pBt, pgno, &pPage);
danielk1977146ba992009-07-22 14:08:13 +00006839 if( rc ) return rc;
drh4b70f112004-05-02 21:12:19 +00006840 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00006841 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00006842 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00006843 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00006844 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006845 }
drh4b70f112004-05-02 21:12:19 +00006846 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00006847 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00006848 }
drha34b6762004-05-07 13:30:42 +00006849 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00006850 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00006851 if( rc ) goto cleardatabasepage_out;
danielk1977c7af4842008-10-27 13:59:33 +00006852 }else if( pnChange ){
6853 assert( pPage->intKey );
6854 *pnChange += pPage->nCell;
drh2aa679f2001-06-25 02:11:07 +00006855 }
6856 if( freePageFlag ){
drhc314dc72009-07-21 11:52:34 +00006857 freePage(pPage, &rc);
danielk19773b8a05f2007-03-19 17:44:26 +00006858 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
drh3a4c1412004-05-09 20:40:11 +00006859 zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00006860 }
danielk19776b456a22005-03-21 04:04:02 +00006861
6862cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00006863 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00006864 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006865}
6866
6867/*
drhab01f612004-05-22 02:55:23 +00006868** Delete all information from a single table in the database. iTable is
6869** the page number of the root of the table. After this routine returns,
6870** the root page is empty, but still exists.
6871**
6872** This routine will fail with SQLITE_LOCKED if there are any open
6873** read cursors on the table. Open write cursors are moved to the
6874** root of the table.
danielk1977c7af4842008-10-27 13:59:33 +00006875**
6876** If pnChange is not NULL, then table iTable must be an intkey table. The
6877** integer value pointed to by pnChange is incremented by the number of
6878** entries in the table.
drh8b2f49b2001-06-08 00:21:52 +00006879*/
danielk1977c7af4842008-10-27 13:59:33 +00006880int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
drh8b2f49b2001-06-08 00:21:52 +00006881 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00006882 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00006883 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00006884 assert( p->inTrans==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +00006885
6886 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
6887 ** is the root of a table b-tree - if it is not, the following call is
6888 ** a no-op). */
drheeb844a2009-08-08 18:01:07 +00006889 invalidateIncrblobCursors(p, 0, 1);
danielk197796d48e92009-06-29 06:00:37 +00006890
drhc046e3e2009-07-15 11:26:44 +00006891 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
6892 if( SQLITE_OK==rc ){
danielk197762c14b32008-11-19 09:05:26 +00006893 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
drh8b2f49b2001-06-08 00:21:52 +00006894 }
drhd677b3d2007-08-20 22:48:41 +00006895 sqlite3BtreeLeave(p);
6896 return rc;
drh8b2f49b2001-06-08 00:21:52 +00006897}
6898
6899/*
6900** Erase all information in a table and add the root of the table to
6901** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00006902** page 1) is never added to the freelist.
6903**
6904** This routine will fail with SQLITE_LOCKED if there are any open
6905** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00006906**
6907** If AUTOVACUUM is enabled and the page at iTable is not the last
6908** root page in the database file, then the last root page
6909** in the database file is moved into the slot formerly occupied by
6910** iTable and that last slot formerly occupied by the last root page
6911** is added to the freelist instead of iTable. In this say, all
6912** root pages are kept at the beginning of the database file, which
6913** is necessary for AUTOVACUUM to work right. *piMoved is set to the
6914** page number that used to be the last root page in the file before
6915** the move. If no page gets moved, *piMoved is set to 0.
6916** The last root page is recorded in meta[3] and the value of
6917** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00006918*/
danielk197789d40042008-11-17 14:20:56 +00006919static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00006920 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00006921 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00006922 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00006923
drh1fee73e2007-08-29 04:00:57 +00006924 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00006925 assert( p->inTrans==TRANS_WRITE );
danielk1977a0bf2652004-11-04 14:30:04 +00006926
danielk1977e6efa742004-11-10 11:55:10 +00006927 /* It is illegal to drop a table if any cursors are open on the
6928 ** database. This is because in auto-vacuum mode the backend may
6929 ** need to move another root-page to fill a gap left by the deleted
6930 ** root page. If an open cursor was using this page a problem would
6931 ** occur.
drhc046e3e2009-07-15 11:26:44 +00006932 **
6933 ** This error is caught long before control reaches this point.
danielk1977e6efa742004-11-10 11:55:10 +00006934 */
drhc046e3e2009-07-15 11:26:44 +00006935 if( NEVER(pBt->pCursor) ){
danielk1977404ca072009-03-16 13:19:36 +00006936 sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
6937 return SQLITE_LOCKED_SHAREDCACHE;
drh5df72a52002-06-06 23:16:05 +00006938 }
danielk1977a0bf2652004-11-04 14:30:04 +00006939
danielk197730548662009-07-09 05:07:37 +00006940 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00006941 if( rc ) return rc;
danielk1977c7af4842008-10-27 13:59:33 +00006942 rc = sqlite3BtreeClearTable(p, iTable, 0);
danielk19776b456a22005-03-21 04:04:02 +00006943 if( rc ){
6944 releasePage(pPage);
6945 return rc;
6946 }
danielk1977a0bf2652004-11-04 14:30:04 +00006947
drh205f48e2004-11-05 00:43:11 +00006948 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00006949
drh4b70f112004-05-02 21:12:19 +00006950 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00006951#ifdef SQLITE_OMIT_AUTOVACUUM
drhc314dc72009-07-21 11:52:34 +00006952 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00006953 releasePage(pPage);
6954#else
6955 if( pBt->autoVacuum ){
6956 Pgno maxRootPgno;
danielk1977602b4662009-07-02 07:47:33 +00006957 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00006958
6959 if( iTable==maxRootPgno ){
6960 /* If the table being dropped is the table with the largest root-page
6961 ** number in the database, put the root page on the free list.
6962 */
drhc314dc72009-07-21 11:52:34 +00006963 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00006964 releasePage(pPage);
6965 if( rc!=SQLITE_OK ){
6966 return rc;
6967 }
6968 }else{
6969 /* The table being dropped does not have the largest root-page
6970 ** number in the database. So move the page that does into the
6971 ** gap left by the deleted root-page.
6972 */
6973 MemPage *pMove;
6974 releasePage(pPage);
danielk197730548662009-07-09 05:07:37 +00006975 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006976 if( rc!=SQLITE_OK ){
6977 return rc;
6978 }
danielk19774c999992008-07-16 18:17:55 +00006979 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00006980 releasePage(pMove);
6981 if( rc!=SQLITE_OK ){
6982 return rc;
6983 }
drhfe3313f2009-07-21 19:02:20 +00006984 pMove = 0;
danielk197730548662009-07-09 05:07:37 +00006985 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
drhc314dc72009-07-21 11:52:34 +00006986 freePage(pMove, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00006987 releasePage(pMove);
6988 if( rc!=SQLITE_OK ){
6989 return rc;
6990 }
6991 *piMoved = maxRootPgno;
6992 }
6993
danielk1977599fcba2004-11-08 07:13:13 +00006994 /* Set the new 'max-root-page' value in the database header. This
6995 ** is the old value less one, less one more if that happens to
6996 ** be a root-page number, less one again if that is the
6997 ** PENDING_BYTE_PAGE.
6998 */
danielk197787a6e732004-11-05 12:58:25 +00006999 maxRootPgno--;
drhe1849652009-07-15 18:15:22 +00007000 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
7001 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00007002 maxRootPgno--;
7003 }
danielk1977599fcba2004-11-08 07:13:13 +00007004 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
7005
danielk1977aef0bf62005-12-30 16:28:01 +00007006 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00007007 }else{
drhc314dc72009-07-21 11:52:34 +00007008 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00007009 releasePage(pPage);
7010 }
7011#endif
drh2aa679f2001-06-25 02:11:07 +00007012 }else{
drhc046e3e2009-07-15 11:26:44 +00007013 /* If sqlite3BtreeDropTable was called on page 1.
7014 ** This really never should happen except in a corrupt
7015 ** database.
7016 */
drha34b6762004-05-07 13:30:42 +00007017 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00007018 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00007019 }
drh8b2f49b2001-06-08 00:21:52 +00007020 return rc;
7021}
drhd677b3d2007-08-20 22:48:41 +00007022int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
7023 int rc;
7024 sqlite3BtreeEnter(p);
7025 rc = btreeDropTable(p, iTable, piMoved);
7026 sqlite3BtreeLeave(p);
7027 return rc;
7028}
drh8b2f49b2001-06-08 00:21:52 +00007029
drh001bbcb2003-03-19 03:14:00 +00007030
drh8b2f49b2001-06-08 00:21:52 +00007031/*
danielk1977602b4662009-07-02 07:47:33 +00007032** This function may only be called if the b-tree connection already
7033** has a read or write transaction open on the database.
7034**
drh23e11ca2004-05-04 17:27:28 +00007035** Read the meta-information out of a database file. Meta[0]
7036** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00007037** through meta[15] are available for use by higher layers. Meta[0]
7038** is read-only, the others are read/write.
7039**
7040** The schema layer numbers meta values differently. At the schema
7041** layer (and the SetCookie and ReadCookie opcodes) the number of
7042** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00007043*/
danielk1977602b4662009-07-02 07:47:33 +00007044void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
danielk1977aef0bf62005-12-30 16:28:01 +00007045 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00007046
drhd677b3d2007-08-20 22:48:41 +00007047 sqlite3BtreeEnter(p);
danielk1977602b4662009-07-02 07:47:33 +00007048 assert( p->inTrans>TRANS_NONE );
danielk1977e0d9e6f2009-07-03 16:25:06 +00007049 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
danielk1977602b4662009-07-02 07:47:33 +00007050 assert( pBt->pPage1 );
drh23e11ca2004-05-04 17:27:28 +00007051 assert( idx>=0 && idx<=15 );
danielk1977ea897302008-09-19 15:10:58 +00007052
danielk1977602b4662009-07-02 07:47:33 +00007053 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
drhae157872004-08-14 19:20:09 +00007054
danielk1977602b4662009-07-02 07:47:33 +00007055 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
7056 ** database, mark the database as read-only. */
danielk1977003ba062004-11-04 02:57:33 +00007057#ifdef SQLITE_OMIT_AUTOVACUUM
danielk19770d19f7a2009-06-03 11:25:07 +00007058 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
danielk1977003ba062004-11-04 02:57:33 +00007059#endif
drhae157872004-08-14 19:20:09 +00007060
drhd677b3d2007-08-20 22:48:41 +00007061 sqlite3BtreeLeave(p);
drh8b2f49b2001-06-08 00:21:52 +00007062}
7063
7064/*
drh23e11ca2004-05-04 17:27:28 +00007065** Write meta-information back into the database. Meta[0] is
7066** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00007067*/
danielk1977aef0bf62005-12-30 16:28:01 +00007068int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
7069 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00007070 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00007071 int rc;
drh23e11ca2004-05-04 17:27:28 +00007072 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00007073 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00007074 assert( p->inTrans==TRANS_WRITE );
7075 assert( pBt->pPage1!=0 );
7076 pP1 = pBt->pPage1->aData;
7077 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
7078 if( rc==SQLITE_OK ){
7079 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +00007080#ifndef SQLITE_OMIT_AUTOVACUUM
danielk19770d19f7a2009-06-03 11:25:07 +00007081 if( idx==BTREE_INCR_VACUUM ){
drh64022502009-01-09 14:11:04 +00007082 assert( pBt->autoVacuum || iMeta==0 );
7083 assert( iMeta==0 || iMeta==1 );
7084 pBt->incrVacuum = (u8)iMeta;
drhd677b3d2007-08-20 22:48:41 +00007085 }
drh64022502009-01-09 14:11:04 +00007086#endif
drh5df72a52002-06-06 23:16:05 +00007087 }
drhd677b3d2007-08-20 22:48:41 +00007088 sqlite3BtreeLeave(p);
7089 return rc;
drh8b2f49b2001-06-08 00:21:52 +00007090}
drh8c42ca92001-06-22 19:15:00 +00007091
danielk1977a5533162009-02-24 10:01:51 +00007092#ifndef SQLITE_OMIT_BTREECOUNT
7093/*
7094** The first argument, pCur, is a cursor opened on some b-tree. Count the
7095** number of entries in the b-tree and write the result to *pnEntry.
7096**
7097** SQLITE_OK is returned if the operation is successfully executed.
7098** Otherwise, if an error is encountered (i.e. an IO error or database
7099** corruption) an SQLite error code is returned.
7100*/
7101int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
7102 i64 nEntry = 0; /* Value to return in *pnEntry */
7103 int rc; /* Return code */
7104 rc = moveToRoot(pCur);
7105
7106 /* Unless an error occurs, the following loop runs one iteration for each
7107 ** page in the B-Tree structure (not including overflow pages).
7108 */
7109 while( rc==SQLITE_OK ){
7110 int iIdx; /* Index of child node in parent */
7111 MemPage *pPage; /* Current page of the b-tree */
7112
7113 /* If this is a leaf page or the tree is not an int-key tree, then
7114 ** this page contains countable entries. Increment the entry counter
7115 ** accordingly.
7116 */
7117 pPage = pCur->apPage[pCur->iPage];
7118 if( pPage->leaf || !pPage->intKey ){
7119 nEntry += pPage->nCell;
7120 }
7121
7122 /* pPage is a leaf node. This loop navigates the cursor so that it
7123 ** points to the first interior cell that it points to the parent of
7124 ** the next page in the tree that has not yet been visited. The
7125 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
7126 ** of the page, or to the number of cells in the page if the next page
7127 ** to visit is the right-child of its parent.
7128 **
7129 ** If all pages in the tree have been visited, return SQLITE_OK to the
7130 ** caller.
7131 */
7132 if( pPage->leaf ){
7133 do {
7134 if( pCur->iPage==0 ){
7135 /* All pages of the b-tree have been visited. Return successfully. */
7136 *pnEntry = nEntry;
7137 return SQLITE_OK;
7138 }
danielk197730548662009-07-09 05:07:37 +00007139 moveToParent(pCur);
danielk1977a5533162009-02-24 10:01:51 +00007140 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
7141
7142 pCur->aiIdx[pCur->iPage]++;
7143 pPage = pCur->apPage[pCur->iPage];
7144 }
7145
7146 /* Descend to the child node of the cell that the cursor currently
7147 ** points at. This is the right-child if (iIdx==pPage->nCell).
7148 */
7149 iIdx = pCur->aiIdx[pCur->iPage];
7150 if( iIdx==pPage->nCell ){
7151 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
7152 }else{
7153 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
7154 }
7155 }
7156
shanebe217792009-03-05 04:20:31 +00007157 /* An error has occurred. Return an error code. */
danielk1977a5533162009-02-24 10:01:51 +00007158 return rc;
7159}
7160#endif
drhdd793422001-06-28 01:54:48 +00007161
drhdd793422001-06-28 01:54:48 +00007162/*
drh5eddca62001-06-30 21:53:53 +00007163** Return the pager associated with a BTree. This routine is used for
7164** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00007165*/
danielk1977aef0bf62005-12-30 16:28:01 +00007166Pager *sqlite3BtreePager(Btree *p){
7167 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00007168}
drh5eddca62001-06-30 21:53:53 +00007169
drhb7f91642004-10-31 02:22:47 +00007170#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007171/*
7172** Append a message to the error message string.
7173*/
drh2e38c322004-09-03 18:38:44 +00007174static void checkAppendMsg(
7175 IntegrityCk *pCheck,
7176 char *zMsg1,
7177 const char *zFormat,
7178 ...
7179){
7180 va_list ap;
drh1dcdbc02007-01-27 02:24:54 +00007181 if( !pCheck->mxErr ) return;
7182 pCheck->mxErr--;
7183 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00007184 va_start(ap, zFormat);
drhf089aa42008-07-08 19:34:06 +00007185 if( pCheck->errMsg.nChar ){
7186 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
drh5eddca62001-06-30 21:53:53 +00007187 }
drhf089aa42008-07-08 19:34:06 +00007188 if( zMsg1 ){
7189 sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
7190 }
7191 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
7192 va_end(ap);
drhc890fec2008-08-01 20:10:08 +00007193 if( pCheck->errMsg.mallocFailed ){
7194 pCheck->mallocFailed = 1;
7195 }
drh5eddca62001-06-30 21:53:53 +00007196}
drhb7f91642004-10-31 02:22:47 +00007197#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00007198
drhb7f91642004-10-31 02:22:47 +00007199#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007200/*
7201** Add 1 to the reference count for page iPage. If this is the second
7202** reference to the page, add an error message to pCheck->zErrMsg.
7203** Return 1 if there are 2 ore more references to the page and 0 if
7204** if this is the first reference to the page.
7205**
7206** Also check that the page number is in bounds.
7207*/
danielk197789d40042008-11-17 14:20:56 +00007208static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00007209 if( iPage==0 ) return 1;
danielk197789d40042008-11-17 14:20:56 +00007210 if( iPage>pCheck->nPage ){
drh2e38c322004-09-03 18:38:44 +00007211 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00007212 return 1;
7213 }
7214 if( pCheck->anRef[iPage]==1 ){
drh2e38c322004-09-03 18:38:44 +00007215 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00007216 return 1;
7217 }
7218 return (pCheck->anRef[iPage]++)>1;
7219}
7220
danielk1977afcdd022004-10-31 16:25:42 +00007221#ifndef SQLITE_OMIT_AUTOVACUUM
7222/*
7223** Check that the entry in the pointer-map for page iChild maps to
7224** page iParent, pointer type ptrType. If not, append an error message
7225** to pCheck.
7226*/
7227static void checkPtrmap(
7228 IntegrityCk *pCheck, /* Integrity check context */
7229 Pgno iChild, /* Child page number */
7230 u8 eType, /* Expected pointer map type */
7231 Pgno iParent, /* Expected pointer map parent page number */
7232 char *zContext /* Context description (used for error msg) */
7233){
7234 int rc;
7235 u8 ePtrmapType;
7236 Pgno iPtrmapParent;
7237
7238 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
7239 if( rc!=SQLITE_OK ){
drhb56cd552009-05-01 13:16:54 +00007240 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
danielk1977afcdd022004-10-31 16:25:42 +00007241 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
7242 return;
7243 }
7244
7245 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
7246 checkAppendMsg(pCheck, zContext,
7247 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
7248 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
7249 }
7250}
7251#endif
7252
drh5eddca62001-06-30 21:53:53 +00007253/*
7254** Check the integrity of the freelist or of an overflow page list.
7255** Verify that the number of pages on the list is N.
7256*/
drh30e58752002-03-02 20:41:57 +00007257static void checkList(
7258 IntegrityCk *pCheck, /* Integrity checking context */
7259 int isFreeList, /* True for a freelist. False for overflow page list */
7260 int iPage, /* Page number for first page in the list */
7261 int N, /* Expected number of pages in the list */
7262 char *zContext /* Context for error messages */
7263){
7264 int i;
drh3a4c1412004-05-09 20:40:11 +00007265 int expected = N;
7266 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00007267 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00007268 DbPage *pOvflPage;
7269 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00007270 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00007271 checkAppendMsg(pCheck, zContext,
7272 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00007273 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00007274 break;
7275 }
7276 if( checkRef(pCheck, iPage, zContext) ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00007277 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
drh2e38c322004-09-03 18:38:44 +00007278 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00007279 break;
7280 }
danielk19773b8a05f2007-03-19 17:44:26 +00007281 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00007282 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00007283 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00007284#ifndef SQLITE_OMIT_AUTOVACUUM
7285 if( pCheck->pBt->autoVacuum ){
7286 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
7287 }
7288#endif
drh45b1fac2008-07-04 17:52:42 +00007289 if( n>pCheck->pBt->usableSize/4-2 ){
drh2e38c322004-09-03 18:38:44 +00007290 checkAppendMsg(pCheck, zContext,
7291 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00007292 N--;
7293 }else{
7294 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00007295 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00007296#ifndef SQLITE_OMIT_AUTOVACUUM
7297 if( pCheck->pBt->autoVacuum ){
7298 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
7299 }
7300#endif
7301 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00007302 }
7303 N -= n;
drh30e58752002-03-02 20:41:57 +00007304 }
drh30e58752002-03-02 20:41:57 +00007305 }
danielk1977afcdd022004-10-31 16:25:42 +00007306#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00007307 else{
7308 /* If this database supports auto-vacuum and iPage is not the last
7309 ** page in this overflow list, check that the pointer-map entry for
7310 ** the following page matches iPage.
7311 */
7312 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00007313 i = get4byte(pOvflData);
danielk1977687566d2004-11-02 12:56:41 +00007314 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
7315 }
danielk1977afcdd022004-10-31 16:25:42 +00007316 }
7317#endif
danielk19773b8a05f2007-03-19 17:44:26 +00007318 iPage = get4byte(pOvflData);
7319 sqlite3PagerUnref(pOvflPage);
drh5eddca62001-06-30 21:53:53 +00007320 }
7321}
drhb7f91642004-10-31 02:22:47 +00007322#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00007323
drhb7f91642004-10-31 02:22:47 +00007324#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007325/*
7326** Do various sanity checks on a single page of a tree. Return
7327** the tree depth. Root pages return 0. Parents of root pages
7328** return 1, and so forth.
7329**
7330** These checks are done:
7331**
7332** 1. Make sure that cells and freeblocks do not overlap
7333** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00007334** NO 2. Make sure cell keys are in order.
7335** NO 3. Make sure no key is less than or equal to zLowerBound.
7336** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00007337** 5. Check the integrity of overflow pages.
7338** 6. Recursively call checkTreePage on all children.
7339** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00007340** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00007341** the root of the tree.
7342*/
7343static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00007344 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00007345 int iPage, /* Page number of the page to check */
drh74161702006-02-24 02:53:49 +00007346 char *zParentContext /* Parent context */
drh5eddca62001-06-30 21:53:53 +00007347){
7348 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00007349 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00007350 int hdr, cellStart;
7351 int nCell;
drhda200cc2004-05-09 11:51:38 +00007352 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00007353 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00007354 int usableSize;
drh5eddca62001-06-30 21:53:53 +00007355 char zContext[100];
shane0af3f892008-11-12 04:55:34 +00007356 char *hit = 0;
drh5eddca62001-06-30 21:53:53 +00007357
drh5bb3eb92007-05-04 13:15:55 +00007358 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
danielk1977ef73ee92004-11-06 12:26:07 +00007359
drh5eddca62001-06-30 21:53:53 +00007360 /* Check that the page exists
7361 */
drhd9cb6ac2005-10-20 07:28:17 +00007362 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00007363 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00007364 if( iPage==0 ) return 0;
7365 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
danielk197730548662009-07-09 05:07:37 +00007366 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drh2e38c322004-09-03 18:38:44 +00007367 checkAppendMsg(pCheck, zContext,
7368 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00007369 return 0;
7370 }
danielk197793caf5a2009-07-11 06:55:33 +00007371
7372 /* Clear MemPage.isInit to make sure the corruption detection code in
7373 ** btreeInitPage() is executed. */
7374 pPage->isInit = 0;
danielk197730548662009-07-09 05:07:37 +00007375 if( (rc = btreeInitPage(pPage))!=0 ){
drh64022502009-01-09 14:11:04 +00007376 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
drh16a9b832007-05-05 18:39:25 +00007377 checkAppendMsg(pCheck, zContext,
danielk197730548662009-07-09 05:07:37 +00007378 "btreeInitPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00007379 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00007380 return 0;
7381 }
7382
7383 /* Check out all the cells.
7384 */
7385 depth = 0;
drh1dcdbc02007-01-27 02:24:54 +00007386 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
drh6f11bef2004-05-13 01:12:56 +00007387 u8 *pCell;
danielk197789d40042008-11-17 14:20:56 +00007388 u32 sz;
drh6f11bef2004-05-13 01:12:56 +00007389 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00007390
7391 /* Check payload overflow pages
7392 */
drh5bb3eb92007-05-04 13:15:55 +00007393 sqlite3_snprintf(sizeof(zContext), zContext,
7394 "On tree page %d cell %d: ", iPage, i);
danielk19771cc5ed82007-05-16 17:28:43 +00007395 pCell = findCell(pPage,i);
danielk197730548662009-07-09 05:07:37 +00007396 btreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00007397 sz = info.nData;
drhf49661a2008-12-10 16:45:50 +00007398 if( !pPage->intKey ) sz += (int)info.nKey;
drh72365832007-03-06 15:53:44 +00007399 assert( sz==info.nPayload );
danielk19775be31f52009-03-30 13:53:43 +00007400 if( (sz>info.nLocal)
7401 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
7402 ){
drhb6f41482004-05-14 01:58:11 +00007403 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00007404 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
7405#ifndef SQLITE_OMIT_AUTOVACUUM
7406 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00007407 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00007408 }
7409#endif
7410 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00007411 }
7412
7413 /* Check sanity of left child page.
7414 */
drhda200cc2004-05-09 11:51:38 +00007415 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00007416 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00007417#ifndef SQLITE_OMIT_AUTOVACUUM
7418 if( pBt->autoVacuum ){
7419 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
7420 }
7421#endif
danielk197762c14b32008-11-19 09:05:26 +00007422 d2 = checkTreePage(pCheck, pgno, zContext);
drhda200cc2004-05-09 11:51:38 +00007423 if( i>0 && d2!=depth ){
7424 checkAppendMsg(pCheck, zContext, "Child page depth differs");
7425 }
7426 depth = d2;
drh5eddca62001-06-30 21:53:53 +00007427 }
drh5eddca62001-06-30 21:53:53 +00007428 }
drhda200cc2004-05-09 11:51:38 +00007429 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00007430 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh5bb3eb92007-05-04 13:15:55 +00007431 sqlite3_snprintf(sizeof(zContext), zContext,
7432 "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00007433#ifndef SQLITE_OMIT_AUTOVACUUM
7434 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00007435 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
danielk1977afcdd022004-10-31 16:25:42 +00007436 }
7437#endif
danielk197762c14b32008-11-19 09:05:26 +00007438 checkTreePage(pCheck, pgno, zContext);
drhda200cc2004-05-09 11:51:38 +00007439 }
drh5eddca62001-06-30 21:53:53 +00007440
7441 /* Check for complete coverage of the page
7442 */
drhda200cc2004-05-09 11:51:38 +00007443 data = pPage->aData;
7444 hdr = pPage->hdrOffset;
drhf7141992008-06-19 00:16:08 +00007445 hit = sqlite3PageMalloc( pBt->pageSize );
drhc890fec2008-08-01 20:10:08 +00007446 if( hit==0 ){
7447 pCheck->mallocFailed = 1;
7448 }else{
shane5780ebd2008-11-11 17:36:30 +00007449 u16 contentOffset = get2byte(&data[hdr+5]);
drhd7c7ecd2009-07-14 17:48:06 +00007450 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
shane5780ebd2008-11-11 17:36:30 +00007451 memset(hit+contentOffset, 0, usableSize-contentOffset);
7452 memset(hit, 1, contentOffset);
drh2e38c322004-09-03 18:38:44 +00007453 nCell = get2byte(&data[hdr+3]);
7454 cellStart = hdr + 12 - 4*pPage->leaf;
7455 for(i=0; i<nCell; i++){
7456 int pc = get2byte(&data[cellStart+i*2]);
danielk1977daca5432008-08-25 11:57:16 +00007457 u16 size = 1024;
drh2e38c322004-09-03 18:38:44 +00007458 int j;
drh8c2bbb62009-07-10 02:52:20 +00007459 if( pc<=usableSize-4 ){
danielk1977daca5432008-08-25 11:57:16 +00007460 size = cellSizePtr(pPage, &data[pc]);
7461 }
drhd7c7ecd2009-07-14 17:48:06 +00007462 if( (pc+size-1)>=usableSize ){
danielk19777701e812005-01-10 12:59:51 +00007463 checkAppendMsg(pCheck, 0,
7464 "Corruption detected in cell %d on page %d",i,iPage,0);
7465 }else{
7466 for(j=pc+size-1; j>=pc; j--) hit[j]++;
7467 }
drh2e38c322004-09-03 18:38:44 +00007468 }
drh8c2bbb62009-07-10 02:52:20 +00007469 i = get2byte(&data[hdr+1]);
7470 while( i>0 ){
7471 int size, j;
7472 assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
7473 size = get2byte(&data[i+2]);
7474 assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
7475 for(j=i+size-1; j>=i; j--) hit[j]++;
7476 j = get2byte(&data[i]);
7477 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
7478 assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
7479 i = j;
drh2e38c322004-09-03 18:38:44 +00007480 }
7481 for(i=cnt=0; i<usableSize; i++){
7482 if( hit[i]==0 ){
7483 cnt++;
7484 }else if( hit[i]>1 ){
7485 checkAppendMsg(pCheck, 0,
7486 "Multiple uses for byte %d of page %d", i, iPage);
7487 break;
7488 }
7489 }
7490 if( cnt!=data[hdr+7] ){
7491 checkAppendMsg(pCheck, 0,
drh8c2bbb62009-07-10 02:52:20 +00007492 "Fragmentation of %d bytes reported as %d on page %d",
drh2e38c322004-09-03 18:38:44 +00007493 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00007494 }
7495 }
drh8c2bbb62009-07-10 02:52:20 +00007496 sqlite3PageFree(hit);
drh4b70f112004-05-02 21:12:19 +00007497 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00007498 return depth+1;
drh5eddca62001-06-30 21:53:53 +00007499}
drhb7f91642004-10-31 02:22:47 +00007500#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00007501
drhb7f91642004-10-31 02:22:47 +00007502#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007503/*
7504** This routine does a complete check of the given BTree file. aRoot[] is
7505** an array of pages numbers were each page number is the root page of
7506** a table. nRoot is the number of entries in aRoot.
7507**
danielk19773509a652009-07-06 18:56:13 +00007508** A read-only or read-write transaction must be opened before calling
7509** this function.
7510**
drhc890fec2008-08-01 20:10:08 +00007511** Write the number of error seen in *pnErr. Except for some memory
drhe43ba702008-12-05 22:40:08 +00007512** allocation errors, an error message held in memory obtained from
drhc890fec2008-08-01 20:10:08 +00007513** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
drhe43ba702008-12-05 22:40:08 +00007514** returned. If a memory allocation error occurs, NULL is returned.
drh5eddca62001-06-30 21:53:53 +00007515*/
drh1dcdbc02007-01-27 02:24:54 +00007516char *sqlite3BtreeIntegrityCheck(
7517 Btree *p, /* The btree to be checked */
7518 int *aRoot, /* An array of root pages numbers for individual trees */
7519 int nRoot, /* Number of entries in aRoot[] */
7520 int mxErr, /* Stop reporting errors after this many */
7521 int *pnErr /* Write number of errors seen to this variable */
7522){
danielk197789d40042008-11-17 14:20:56 +00007523 Pgno i;
drh5eddca62001-06-30 21:53:53 +00007524 int nRef;
drhaaab5722002-02-19 13:39:21 +00007525 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00007526 BtShared *pBt = p->pBt;
drhf089aa42008-07-08 19:34:06 +00007527 char zErr[100];
drh5eddca62001-06-30 21:53:53 +00007528
drhd677b3d2007-08-20 22:48:41 +00007529 sqlite3BtreeEnter(p);
danielk19773509a652009-07-06 18:56:13 +00007530 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
danielk19773b8a05f2007-03-19 17:44:26 +00007531 nRef = sqlite3PagerRefcount(pBt->pPager);
drh5eddca62001-06-30 21:53:53 +00007532 sCheck.pBt = pBt;
7533 sCheck.pPager = pBt->pPager;
danielk197789d40042008-11-17 14:20:56 +00007534 sCheck.nPage = pagerPagecount(sCheck.pBt);
drh1dcdbc02007-01-27 02:24:54 +00007535 sCheck.mxErr = mxErr;
7536 sCheck.nErr = 0;
drhc890fec2008-08-01 20:10:08 +00007537 sCheck.mallocFailed = 0;
drh1dcdbc02007-01-27 02:24:54 +00007538 *pnErr = 0;
drh0de8c112002-07-06 16:32:14 +00007539 if( sCheck.nPage==0 ){
drhd677b3d2007-08-20 22:48:41 +00007540 sqlite3BtreeLeave(p);
drh0de8c112002-07-06 16:32:14 +00007541 return 0;
7542 }
drhe5ae5732008-06-15 02:51:47 +00007543 sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
danielk1977ac245ec2005-01-14 13:50:11 +00007544 if( !sCheck.anRef ){
drh1dcdbc02007-01-27 02:24:54 +00007545 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00007546 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00007547 return 0;
danielk1977ac245ec2005-01-14 13:50:11 +00007548 }
drhda200cc2004-05-09 11:51:38 +00007549 for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
drh42cac6d2004-11-20 20:31:11 +00007550 i = PENDING_BYTE_PAGE(pBt);
drh1f595712004-06-15 01:40:29 +00007551 if( i<=sCheck.nPage ){
7552 sCheck.anRef[i] = 1;
7553 }
drhf089aa42008-07-08 19:34:06 +00007554 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
drh5eddca62001-06-30 21:53:53 +00007555
7556 /* Check the integrity of the freelist
7557 */
drha34b6762004-05-07 13:30:42 +00007558 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
7559 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00007560
7561 /* Check all the tables.
7562 */
danielk197789d40042008-11-17 14:20:56 +00007563 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
drh4ff6dfa2002-03-03 23:06:00 +00007564 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00007565#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00007566 if( pBt->autoVacuum && aRoot[i]>1 ){
7567 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
7568 }
7569#endif
danielk197762c14b32008-11-19 09:05:26 +00007570 checkTreePage(&sCheck, aRoot[i], "List of tree roots: ");
drh5eddca62001-06-30 21:53:53 +00007571 }
7572
7573 /* Make sure every page in the file is referenced
7574 */
drh1dcdbc02007-01-27 02:24:54 +00007575 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00007576#ifdef SQLITE_OMIT_AUTOVACUUM
drh5eddca62001-06-30 21:53:53 +00007577 if( sCheck.anRef[i]==0 ){
drh2e38c322004-09-03 18:38:44 +00007578 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00007579 }
danielk1977afcdd022004-10-31 16:25:42 +00007580#else
7581 /* If the database supports auto-vacuum, make sure no tables contain
7582 ** references to pointer-map pages.
7583 */
7584 if( sCheck.anRef[i]==0 &&
danielk1977266664d2006-02-10 08:24:21 +00007585 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00007586 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
7587 }
7588 if( sCheck.anRef[i]!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00007589 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00007590 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
7591 }
7592#endif
drh5eddca62001-06-30 21:53:53 +00007593 }
7594
drh64022502009-01-09 14:11:04 +00007595 /* Make sure this analysis did not leave any unref() pages.
7596 ** This is an internal consistency check; an integrity check
7597 ** of the integrity check.
drh5eddca62001-06-30 21:53:53 +00007598 */
drh64022502009-01-09 14:11:04 +00007599 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
drh2e38c322004-09-03 18:38:44 +00007600 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00007601 "Outstanding page count goes from %d to %d during this analysis",
danielk19773b8a05f2007-03-19 17:44:26 +00007602 nRef, sqlite3PagerRefcount(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00007603 );
drh5eddca62001-06-30 21:53:53 +00007604 }
7605
7606 /* Clean up and report errors.
7607 */
drhd677b3d2007-08-20 22:48:41 +00007608 sqlite3BtreeLeave(p);
drh17435752007-08-16 04:30:38 +00007609 sqlite3_free(sCheck.anRef);
drhc890fec2008-08-01 20:10:08 +00007610 if( sCheck.mallocFailed ){
7611 sqlite3StrAccumReset(&sCheck.errMsg);
7612 *pnErr = sCheck.nErr+1;
7613 return 0;
7614 }
drh1dcdbc02007-01-27 02:24:54 +00007615 *pnErr = sCheck.nErr;
drhf089aa42008-07-08 19:34:06 +00007616 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
7617 return sqlite3StrAccumFinish(&sCheck.errMsg);
drh5eddca62001-06-30 21:53:53 +00007618}
drhb7f91642004-10-31 02:22:47 +00007619#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00007620
drh73509ee2003-04-06 20:44:45 +00007621/*
7622** Return the full pathname of the underlying database file.
drhd0679ed2007-08-28 22:24:34 +00007623**
7624** The pager filename is invariant as long as the pager is
7625** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +00007626*/
danielk1977aef0bf62005-12-30 16:28:01 +00007627const char *sqlite3BtreeGetFilename(Btree *p){
7628 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007629 return sqlite3PagerFilename(p->pBt->pPager);
drh73509ee2003-04-06 20:44:45 +00007630}
7631
7632/*
danielk19775865e3d2004-06-14 06:03:57 +00007633** Return the pathname of the journal file for this database. The return
7634** value of this routine is the same regardless of whether the journal file
7635** has been created or not.
drhd0679ed2007-08-28 22:24:34 +00007636**
7637** The pager journal filename is invariant as long as the pager is
7638** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00007639*/
danielk1977aef0bf62005-12-30 16:28:01 +00007640const char *sqlite3BtreeGetJournalname(Btree *p){
7641 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00007642 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00007643}
7644
danielk19771d850a72004-05-31 08:26:49 +00007645/*
7646** Return non-zero if a transaction is active.
7647*/
danielk1977aef0bf62005-12-30 16:28:01 +00007648int sqlite3BtreeIsInTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00007649 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00007650 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00007651}
7652
7653/*
danielk19772372c2b2006-06-27 16:34:56 +00007654** Return non-zero if a read (or write) transaction is active.
7655*/
7656int sqlite3BtreeIsInReadTrans(Btree *p){
drh64022502009-01-09 14:11:04 +00007657 assert( p );
drhe5fe6902007-12-07 18:55:28 +00007658 assert( sqlite3_mutex_held(p->db->mutex) );
drh64022502009-01-09 14:11:04 +00007659 return p->inTrans!=TRANS_NONE;
danielk19772372c2b2006-06-27 16:34:56 +00007660}
7661
danielk197704103022009-02-03 16:51:24 +00007662int sqlite3BtreeIsInBackup(Btree *p){
7663 assert( p );
7664 assert( sqlite3_mutex_held(p->db->mutex) );
7665 return p->nBackup!=0;
7666}
7667
danielk19772372c2b2006-06-27 16:34:56 +00007668/*
danielk1977da184232006-01-05 11:34:32 +00007669** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +00007670** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +00007671** purposes (for example, to store a high-level schema associated with
7672** the shared-btree). The btree layer manages reference counting issues.
7673**
7674** The first time this is called on a shared-btree, nBytes bytes of memory
7675** are allocated, zeroed, and returned to the caller. For each subsequent
7676** call the nBytes parameter is ignored and a pointer to the same blob
7677** of memory returned.
7678**
danielk1977171bfed2008-06-23 09:50:50 +00007679** If the nBytes parameter is 0 and the blob of memory has not yet been
7680** allocated, a null pointer is returned. If the blob has already been
7681** allocated, it is returned as normal.
7682**
danielk1977da184232006-01-05 11:34:32 +00007683** Just before the shared-btree is closed, the function passed as the
7684** xFree argument when the memory allocation was made is invoked on the
drh17435752007-08-16 04:30:38 +00007685** blob of allocated memory. This function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +00007686** on the memory, the btree layer does that.
7687*/
7688void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
7689 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +00007690 sqlite3BtreeEnter(p);
danielk1977171bfed2008-06-23 09:50:50 +00007691 if( !pBt->pSchema && nBytes ){
drh17435752007-08-16 04:30:38 +00007692 pBt->pSchema = sqlite3MallocZero(nBytes);
danielk1977da184232006-01-05 11:34:32 +00007693 pBt->xFreeSchema = xFree;
7694 }
drh27641702007-08-22 02:56:42 +00007695 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00007696 return pBt->pSchema;
7697}
7698
danielk1977c87d34d2006-01-06 13:00:28 +00007699/*
danielk1977404ca072009-03-16 13:19:36 +00007700** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
7701** btree as the argument handle holds an exclusive lock on the
7702** sqlite_master table. Otherwise SQLITE_OK.
danielk1977c87d34d2006-01-06 13:00:28 +00007703*/
7704int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +00007705 int rc;
drhe5fe6902007-12-07 18:55:28 +00007706 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +00007707 sqlite3BtreeEnter(p);
danielk1977404ca072009-03-16 13:19:36 +00007708 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
7709 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
drh27641702007-08-22 02:56:42 +00007710 sqlite3BtreeLeave(p);
7711 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +00007712}
7713
drha154dcd2006-03-22 22:10:07 +00007714
7715#ifndef SQLITE_OMIT_SHARED_CACHE
7716/*
7717** Obtain a lock on the table whose root page is iTab. The
7718** lock is a write lock if isWritelock is true or a read lock
7719** if it is false.
7720*/
danielk1977c00da102006-01-07 13:21:04 +00007721int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00007722 int rc = SQLITE_OK;
danielk1977602b4662009-07-02 07:47:33 +00007723 assert( p->inTrans!=TRANS_NONE );
drh6a9ad3d2008-04-02 16:29:30 +00007724 if( p->sharable ){
7725 u8 lockType = READ_LOCK + isWriteLock;
7726 assert( READ_LOCK+1==WRITE_LOCK );
7727 assert( isWriteLock==0 || isWriteLock==1 );
danielk1977602b4662009-07-02 07:47:33 +00007728
drh6a9ad3d2008-04-02 16:29:30 +00007729 sqlite3BtreeEnter(p);
drhc25eabe2009-02-24 18:57:31 +00007730 rc = querySharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00007731 if( rc==SQLITE_OK ){
drhc25eabe2009-02-24 18:57:31 +00007732 rc = setSharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00007733 }
7734 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +00007735 }
7736 return rc;
7737}
drha154dcd2006-03-22 22:10:07 +00007738#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00007739
danielk1977b4e9af92007-05-01 17:49:49 +00007740#ifndef SQLITE_OMIT_INCRBLOB
7741/*
7742** Argument pCsr must be a cursor opened for writing on an
7743** INTKEY table currently pointing at a valid table entry.
7744** This function modifies the data stored as part of that entry.
danielk1977ecaecf92009-07-08 08:05:35 +00007745**
7746** Only the data content may only be modified, it is not possible to
7747** change the length of the data stored. If this function is called with
7748** parameters that attempt to write past the end of the existing data,
7749** no modifications are made and SQLITE_CORRUPT is returned.
danielk1977b4e9af92007-05-01 17:49:49 +00007750*/
danielk1977dcbb5d32007-05-04 18:36:44 +00007751int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
danielk1977c9000e62009-07-08 13:55:28 +00007752 int rc;
drh1fee73e2007-08-29 04:00:57 +00007753 assert( cursorHoldsMutex(pCsr) );
drhe5fe6902007-12-07 18:55:28 +00007754 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
danielk197796d48e92009-06-29 06:00:37 +00007755 assert( pCsr->isIncrblobHandle );
danielk19773588ceb2008-06-10 17:30:26 +00007756
danielk1977c9000e62009-07-08 13:55:28 +00007757 rc = restoreCursorPosition(pCsr);
7758 if( rc!=SQLITE_OK ){
7759 return rc;
7760 }
danielk19773588ceb2008-06-10 17:30:26 +00007761 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
7762 if( pCsr->eState!=CURSOR_VALID ){
7763 return SQLITE_ABORT;
danielk1977dcbb5d32007-05-04 18:36:44 +00007764 }
7765
danielk1977c9000e62009-07-08 13:55:28 +00007766 /* Check some assumptions:
danielk1977dcbb5d32007-05-04 18:36:44 +00007767 ** (a) the cursor is open for writing,
danielk1977c9000e62009-07-08 13:55:28 +00007768 ** (b) there is a read/write transaction open,
7769 ** (c) the connection holds a write-lock on the table (if required),
7770 ** (d) there are no conflicting read-locks, and
7771 ** (e) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00007772 */
danielk19774f029602009-07-08 18:45:37 +00007773 if( !pCsr->wrFlag ){
7774 return SQLITE_READONLY;
7775 }
danielk197796d48e92009-06-29 06:00:37 +00007776 assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
7777 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
7778 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
danielk1977c9000e62009-07-08 13:55:28 +00007779 assert( pCsr->apPage[pCsr->iPage]->intKey );
danielk1977b4e9af92007-05-01 17:49:49 +00007780
drhfb192682009-07-11 18:26:28 +00007781 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00007782}
danielk19772dec9702007-05-02 16:48:37 +00007783
7784/*
7785** Set a flag on this cursor to cache the locations of pages from the
danielk1977da107192007-05-04 08:32:13 +00007786** overflow list for the current row. This is used by cursors opened
7787** for incremental blob IO only.
7788**
7789** This function sets a flag only. The actual page location cache
7790** (stored in BtCursor.aOverflow[]) is allocated and used by function
7791** accessPayload() (the worker function for sqlite3BtreeData() and
7792** sqlite3BtreePutData()).
danielk19772dec9702007-05-02 16:48:37 +00007793*/
7794void sqlite3BtreeCacheOverflow(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00007795 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00007796 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk1977dcbb5d32007-05-04 18:36:44 +00007797 assert(!pCur->isIncrblobHandle);
danielk19772dec9702007-05-02 16:48:37 +00007798 assert(!pCur->aOverflow);
danielk1977dcbb5d32007-05-04 18:36:44 +00007799 pCur->isIncrblobHandle = 1;
danielk19772dec9702007-05-02 16:48:37 +00007800}
danielk1977b4e9af92007-05-01 17:49:49 +00007801#endif