blob: f9f76c2ebbc0b59483d5ee4029956b816326069e [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*************************************************************************
peter.d.reid60ec9142014-09-06 16:39:46 +000012** This file implements an external (disk-based) database using BTrees.
drha3152892007-05-05 11:48:52 +000013** See the header comment on "btreeInt.h" for additional information.
14** Including a description of file format and an overview of operation.
drha059ad02001-04-17 20:09:11 +000015*/
drha3152892007-05-05 11:48:52 +000016#include "btreeInt.h"
paulb95a8862003-04-01 21:16:41 +000017
drh8c42ca92001-06-22 19:15:00 +000018/*
drha3152892007-05-05 11:48:52 +000019** The header string that appears at the beginning of every
20** SQLite database.
drh556b2a22005-06-14 16:04:05 +000021*/
drh556b2a22005-06-14 16:04:05 +000022static const char zMagicHeader[] = SQLITE_FILE_HEADER;
drh08ed44e2001-04-29 23:32:55 +000023
drh8c42ca92001-06-22 19:15:00 +000024/*
drha3152892007-05-05 11:48:52 +000025** Set this global variable to 1 to enable tracing using the TRACE
26** macro.
drh615ae552005-01-16 23:21:00 +000027*/
drhe8f52c52008-07-12 14:52:20 +000028#if 0
danielk1977a50d9aa2009-06-08 14:49:45 +000029int sqlite3BtreeTrace=1; /* True to enable tracing */
drhe8f52c52008-07-12 14:52:20 +000030# define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
31#else
32# define TRACE(X)
drh615ae552005-01-16 23:21:00 +000033#endif
drh615ae552005-01-16 23:21:00 +000034
drh5d433ce2010-08-14 16:02:52 +000035/*
36** Extract a 2-byte big-endian integer from an array of unsigned bytes.
37** But if the value is zero, make it 65536.
38**
39** This routine is used to extract the "offset to cell content area" value
40** from the header of a btree page. If the page size is 65536 and the page
41** is empty, the offset should be 65536, but the 2-byte value stores zero.
42** This routine makes the necessary adjustment to 65536.
43*/
44#define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
drh86f8c192007-08-22 00:39:19 +000045
dan09ff9e12013-03-11 11:49:03 +000046/*
47** Values passed as the 5th argument to allocateBtreePage()
48*/
49#define BTALLOC_ANY 0 /* Allocate any page */
50#define BTALLOC_EXACT 1 /* Allocate exact page if possible */
51#define BTALLOC_LE 2 /* Allocate any page <= the parameter */
52
53/*
54** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
55** defined, or 0 if it is. For example:
56**
57** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
58*/
59#ifndef SQLITE_OMIT_AUTOVACUUM
60#define IfNotOmitAV(expr) (expr)
61#else
62#define IfNotOmitAV(expr) 0
63#endif
64
drhe53831d2007-08-17 01:14:38 +000065#ifndef SQLITE_OMIT_SHARED_CACHE
66/*
danielk1977502b4e02008-09-02 14:07:24 +000067** A list of BtShared objects that are eligible for participation
68** in shared cache. This variable has file scope during normal builds,
69** but the test harness needs to access it so we make it global for
70** test builds.
drh7555d8e2009-03-20 13:15:30 +000071**
72** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
drhe53831d2007-08-17 01:14:38 +000073*/
74#ifdef SQLITE_TEST
drh78f82d12008-09-02 00:52:52 +000075BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
drhe53831d2007-08-17 01:14:38 +000076#else
drh78f82d12008-09-02 00:52:52 +000077static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
drhe53831d2007-08-17 01:14:38 +000078#endif
drhe53831d2007-08-17 01:14:38 +000079#endif /* SQLITE_OMIT_SHARED_CACHE */
80
81#ifndef SQLITE_OMIT_SHARED_CACHE
82/*
83** Enable or disable the shared pager and schema features.
84**
85** This routine has no effect on existing database connections.
86** The shared cache setting effects only future calls to
87** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
88*/
89int sqlite3_enable_shared_cache(int enable){
danielk1977502b4e02008-09-02 14:07:24 +000090 sqlite3GlobalConfig.sharedCacheEnabled = enable;
drhe53831d2007-08-17 01:14:38 +000091 return SQLITE_OK;
92}
93#endif
94
drhd677b3d2007-08-20 22:48:41 +000095
danielk1977aef0bf62005-12-30 16:28:01 +000096
97#ifdef SQLITE_OMIT_SHARED_CACHE
98 /*
drhc25eabe2009-02-24 18:57:31 +000099 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
100 ** and clearAllSharedCacheTableLocks()
danielk1977aef0bf62005-12-30 16:28:01 +0000101 ** manipulate entries in the BtShared.pLock linked list used to store
102 ** shared-cache table level locks. If the library is compiled with the
103 ** shared-cache feature disabled, then there is only ever one user
danielk1977da184232006-01-05 11:34:32 +0000104 ** of each BtShared structure and so this locking is not necessary.
105 ** So define the lock related functions as no-ops.
danielk1977aef0bf62005-12-30 16:28:01 +0000106 */
drhc25eabe2009-02-24 18:57:31 +0000107 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
108 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
109 #define clearAllSharedCacheTableLocks(a)
danielk197794b30732009-07-02 17:21:57 +0000110 #define downgradeAllSharedCacheTableLocks(a)
danielk197796d48e92009-06-29 06:00:37 +0000111 #define hasSharedCacheTableLock(a,b,c,d) 1
112 #define hasReadConflicts(a, b) 0
drhe53831d2007-08-17 01:14:38 +0000113#endif
danielk1977aef0bf62005-12-30 16:28:01 +0000114
drhe53831d2007-08-17 01:14:38 +0000115#ifndef SQLITE_OMIT_SHARED_CACHE
danielk197796d48e92009-06-29 06:00:37 +0000116
117#ifdef SQLITE_DEBUG
118/*
drh0ee3dbe2009-10-16 15:05:18 +0000119**** This function is only used as part of an assert() statement. ***
120**
121** Check to see if pBtree holds the required locks to read or write to the
122** table with root page iRoot. Return 1 if it does and 0 if not.
123**
124** For example, when writing to a table with root-page iRoot via
danielk197796d48e92009-06-29 06:00:37 +0000125** Btree connection pBtree:
126**
127** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
128**
drh0ee3dbe2009-10-16 15:05:18 +0000129** When writing to an index that resides in a sharable database, the
danielk197796d48e92009-06-29 06:00:37 +0000130** caller should have first obtained a lock specifying the root page of
drh0ee3dbe2009-10-16 15:05:18 +0000131** the corresponding table. This makes things a bit more complicated,
132** as this module treats each table as a separate structure. To determine
133** the table corresponding to the index being written, this
danielk197796d48e92009-06-29 06:00:37 +0000134** function has to search through the database schema.
135**
drh0ee3dbe2009-10-16 15:05:18 +0000136** Instead of a lock on the table/index rooted at page iRoot, the caller may
danielk197796d48e92009-06-29 06:00:37 +0000137** hold a write-lock on the schema table (root page 1). This is also
138** acceptable.
139*/
140static int hasSharedCacheTableLock(
141 Btree *pBtree, /* Handle that must hold lock */
142 Pgno iRoot, /* Root page of b-tree */
143 int isIndex, /* True if iRoot is the root of an index b-tree */
144 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
145){
146 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
147 Pgno iTab = 0;
148 BtLock *pLock;
149
drh0ee3dbe2009-10-16 15:05:18 +0000150 /* If this database is not shareable, or if the client is reading
danielk197796d48e92009-06-29 06:00:37 +0000151 ** and has the read-uncommitted flag set, then no lock is required.
drh0ee3dbe2009-10-16 15:05:18 +0000152 ** Return true immediately.
153 */
danielk197796d48e92009-06-29 06:00:37 +0000154 if( (pBtree->sharable==0)
155 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
danielk197796d48e92009-06-29 06:00:37 +0000156 ){
157 return 1;
158 }
159
drh0ee3dbe2009-10-16 15:05:18 +0000160 /* If the client is reading or writing an index and the schema is
161 ** not loaded, then it is too difficult to actually check to see if
162 ** the correct locks are held. So do not bother - just return true.
163 ** This case does not come up very often anyhow.
164 */
drh2c5e35f2014-08-05 11:04:21 +0000165 if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
drh0ee3dbe2009-10-16 15:05:18 +0000166 return 1;
167 }
168
danielk197796d48e92009-06-29 06:00:37 +0000169 /* Figure out the root-page that the lock should be held on. For table
170 ** b-trees, this is just the root page of the b-tree being read or
171 ** written. For index b-trees, it is the root page of the associated
172 ** table. */
173 if( isIndex ){
174 HashElem *p;
175 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
176 Index *pIdx = (Index *)sqliteHashData(p);
shane5eff7cf2009-08-10 03:57:58 +0000177 if( pIdx->tnum==(int)iRoot ){
178 iTab = pIdx->pTable->tnum;
danielk197796d48e92009-06-29 06:00:37 +0000179 }
180 }
181 }else{
182 iTab = iRoot;
183 }
184
185 /* Search for the required lock. Either a write-lock on root-page iTab, a
186 ** write-lock on the schema table, or (if the client is reading) a
187 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
188 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
189 if( pLock->pBtree==pBtree
190 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
191 && pLock->eLock>=eLockType
192 ){
193 return 1;
194 }
195 }
196
197 /* Failed to find the required lock. */
198 return 0;
199}
drh0ee3dbe2009-10-16 15:05:18 +0000200#endif /* SQLITE_DEBUG */
danielk197796d48e92009-06-29 06:00:37 +0000201
drh0ee3dbe2009-10-16 15:05:18 +0000202#ifdef SQLITE_DEBUG
danielk197796d48e92009-06-29 06:00:37 +0000203/*
drh0ee3dbe2009-10-16 15:05:18 +0000204**** This function may be used as part of assert() statements only. ****
danielk197796d48e92009-06-29 06:00:37 +0000205**
drh0ee3dbe2009-10-16 15:05:18 +0000206** Return true if it would be illegal for pBtree to write into the
207** table or index rooted at iRoot because other shared connections are
208** simultaneously reading that same table or index.
209**
210** It is illegal for pBtree to write if some other Btree object that
211** shares the same BtShared object is currently reading or writing
212** the iRoot table. Except, if the other Btree object has the
213** read-uncommitted flag set, then it is OK for the other object to
214** have a read cursor.
215**
216** For example, before writing to any part of the table or index
217** rooted at page iRoot, one should call:
danielk197796d48e92009-06-29 06:00:37 +0000218**
219** assert( !hasReadConflicts(pBtree, iRoot) );
220*/
221static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
222 BtCursor *p;
223 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
224 if( p->pgnoRoot==iRoot
225 && p->pBtree!=pBtree
226 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
227 ){
228 return 1;
229 }
230 }
231 return 0;
232}
233#endif /* #ifdef SQLITE_DEBUG */
234
danielk1977da184232006-01-05 11:34:32 +0000235/*
drh0ee3dbe2009-10-16 15:05:18 +0000236** Query to see if Btree handle p may obtain a lock of type eLock
danielk1977aef0bf62005-12-30 16:28:01 +0000237** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
drhc25eabe2009-02-24 18:57:31 +0000238** SQLITE_OK if the lock may be obtained (by calling
239** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
danielk1977aef0bf62005-12-30 16:28:01 +0000240*/
drhc25eabe2009-02-24 18:57:31 +0000241static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
danielk1977aef0bf62005-12-30 16:28:01 +0000242 BtShared *pBt = p->pBt;
243 BtLock *pIter;
244
drh1fee73e2007-08-29 04:00:57 +0000245 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000246 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
247 assert( p->db!=0 );
danielk1977e0d9e6f2009-07-03 16:25:06 +0000248 assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
drhd677b3d2007-08-20 22:48:41 +0000249
danielk19775b413d72009-04-01 09:41:54 +0000250 /* If requesting a write-lock, then the Btree must have an open write
251 ** transaction on this file. And, obviously, for this to be so there
252 ** must be an open write transaction on the file itself.
253 */
254 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
255 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
256
drh0ee3dbe2009-10-16 15:05:18 +0000257 /* This routine is a no-op if the shared-cache is not enabled */
drhe53831d2007-08-17 01:14:38 +0000258 if( !p->sharable ){
danielk1977da184232006-01-05 11:34:32 +0000259 return SQLITE_OK;
260 }
261
danielk1977641b0f42007-12-21 04:47:25 +0000262 /* If some other connection is holding an exclusive lock, the
263 ** requested lock may not be obtained.
264 */
drhc9166342012-01-05 23:32:06 +0000265 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
danielk1977404ca072009-03-16 13:19:36 +0000266 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
267 return SQLITE_LOCKED_SHAREDCACHE;
danielk1977641b0f42007-12-21 04:47:25 +0000268 }
269
danielk1977e0d9e6f2009-07-03 16:25:06 +0000270 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
271 /* The condition (pIter->eLock!=eLock) in the following if(...)
272 ** statement is a simplification of:
273 **
274 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
275 **
276 ** since we know that if eLock==WRITE_LOCK, then no other connection
277 ** may hold a WRITE_LOCK on any table in this file (since there can
278 ** only be a single writer).
279 */
280 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
281 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
282 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
283 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
284 if( eLock==WRITE_LOCK ){
285 assert( p==pBt->pWriter );
drhc9166342012-01-05 23:32:06 +0000286 pBt->btsFlags |= BTS_PENDING;
danielk1977da184232006-01-05 11:34:32 +0000287 }
danielk1977e0d9e6f2009-07-03 16:25:06 +0000288 return SQLITE_LOCKED_SHAREDCACHE;
danielk1977aef0bf62005-12-30 16:28:01 +0000289 }
290 }
291 return SQLITE_OK;
292}
drhe53831d2007-08-17 01:14:38 +0000293#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000294
drhe53831d2007-08-17 01:14:38 +0000295#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000296/*
297** Add a lock on the table with root-page iTable to the shared-btree used
298** by Btree handle p. Parameter eLock must be either READ_LOCK or
299** WRITE_LOCK.
300**
danielk19779d104862009-07-09 08:27:14 +0000301** This function assumes the following:
302**
drh0ee3dbe2009-10-16 15:05:18 +0000303** (a) The specified Btree object p is connected to a sharable
304** database (one with the BtShared.sharable flag set), and
danielk19779d104862009-07-09 08:27:14 +0000305**
drh0ee3dbe2009-10-16 15:05:18 +0000306** (b) No other Btree objects hold a lock that conflicts
danielk19779d104862009-07-09 08:27:14 +0000307** with the requested lock (i.e. querySharedCacheTableLock() has
308** already been called and returned SQLITE_OK).
309**
310** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
311** is returned if a malloc attempt fails.
danielk1977aef0bf62005-12-30 16:28:01 +0000312*/
drhc25eabe2009-02-24 18:57:31 +0000313static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
danielk1977aef0bf62005-12-30 16:28:01 +0000314 BtShared *pBt = p->pBt;
315 BtLock *pLock = 0;
316 BtLock *pIter;
317
drh1fee73e2007-08-29 04:00:57 +0000318 assert( sqlite3BtreeHoldsMutex(p) );
drhfa67c3c2008-07-11 02:21:40 +0000319 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
320 assert( p->db!=0 );
drhd677b3d2007-08-20 22:48:41 +0000321
danielk1977e0d9e6f2009-07-03 16:25:06 +0000322 /* A connection with the read-uncommitted flag set will never try to
323 ** obtain a read-lock using this function. The only read-lock obtained
324 ** by a connection in read-uncommitted mode is on the sqlite_master
325 ** table, and that lock is obtained in BtreeBeginTrans(). */
326 assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
327
danielk19779d104862009-07-09 08:27:14 +0000328 /* This function should only be called on a sharable b-tree after it
329 ** has been determined that no other b-tree holds a conflicting lock. */
330 assert( p->sharable );
drhc25eabe2009-02-24 18:57:31 +0000331 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
danielk1977aef0bf62005-12-30 16:28:01 +0000332
333 /* First search the list for an existing lock on this table. */
334 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
335 if( pIter->iTable==iTable && pIter->pBtree==p ){
336 pLock = pIter;
337 break;
338 }
339 }
340
341 /* If the above search did not find a BtLock struct associating Btree p
342 ** with table iTable, allocate one and link it into the list.
343 */
344 if( !pLock ){
drh17435752007-08-16 04:30:38 +0000345 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
danielk1977aef0bf62005-12-30 16:28:01 +0000346 if( !pLock ){
347 return SQLITE_NOMEM;
348 }
349 pLock->iTable = iTable;
350 pLock->pBtree = p;
351 pLock->pNext = pBt->pLock;
352 pBt->pLock = pLock;
353 }
354
355 /* Set the BtLock.eLock variable to the maximum of the current lock
356 ** and the requested lock. This means if a write-lock was already held
357 ** and a read-lock requested, we don't incorrectly downgrade the lock.
358 */
359 assert( WRITE_LOCK>READ_LOCK );
danielk19775118b912005-12-30 16:31:53 +0000360 if( eLock>pLock->eLock ){
361 pLock->eLock = eLock;
362 }
danielk1977aef0bf62005-12-30 16:28:01 +0000363
364 return SQLITE_OK;
365}
drhe53831d2007-08-17 01:14:38 +0000366#endif /* !SQLITE_OMIT_SHARED_CACHE */
danielk1977aef0bf62005-12-30 16:28:01 +0000367
drhe53831d2007-08-17 01:14:38 +0000368#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +0000369/*
drhc25eabe2009-02-24 18:57:31 +0000370** Release all the table locks (locks obtained via calls to
drh0ee3dbe2009-10-16 15:05:18 +0000371** the setSharedCacheTableLock() procedure) held by Btree object p.
danielk1977fa542f12009-04-02 18:28:08 +0000372**
drh0ee3dbe2009-10-16 15:05:18 +0000373** This function assumes that Btree p has an open read or write
drhc9166342012-01-05 23:32:06 +0000374** transaction. If it does not, then the BTS_PENDING flag
danielk1977fa542f12009-04-02 18:28:08 +0000375** may be incorrectly cleared.
danielk1977aef0bf62005-12-30 16:28:01 +0000376*/
drhc25eabe2009-02-24 18:57:31 +0000377static void clearAllSharedCacheTableLocks(Btree *p){
danielk1977641b0f42007-12-21 04:47:25 +0000378 BtShared *pBt = p->pBt;
379 BtLock **ppIter = &pBt->pLock;
danielk1977da184232006-01-05 11:34:32 +0000380
drh1fee73e2007-08-29 04:00:57 +0000381 assert( sqlite3BtreeHoldsMutex(p) );
drhe53831d2007-08-17 01:14:38 +0000382 assert( p->sharable || 0==*ppIter );
danielk1977fa542f12009-04-02 18:28:08 +0000383 assert( p->inTrans>0 );
danielk1977da184232006-01-05 11:34:32 +0000384
danielk1977aef0bf62005-12-30 16:28:01 +0000385 while( *ppIter ){
386 BtLock *pLock = *ppIter;
drhc9166342012-01-05 23:32:06 +0000387 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
danielk1977fa542f12009-04-02 18:28:08 +0000388 assert( pLock->pBtree->inTrans>=pLock->eLock );
danielk1977aef0bf62005-12-30 16:28:01 +0000389 if( pLock->pBtree==p ){
390 *ppIter = pLock->pNext;
danielk1977602b4662009-07-02 07:47:33 +0000391 assert( pLock->iTable!=1 || pLock==&p->lock );
392 if( pLock->iTable!=1 ){
393 sqlite3_free(pLock);
394 }
danielk1977aef0bf62005-12-30 16:28:01 +0000395 }else{
396 ppIter = &pLock->pNext;
397 }
398 }
danielk1977641b0f42007-12-21 04:47:25 +0000399
drhc9166342012-01-05 23:32:06 +0000400 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
danielk1977404ca072009-03-16 13:19:36 +0000401 if( pBt->pWriter==p ){
402 pBt->pWriter = 0;
drhc9166342012-01-05 23:32:06 +0000403 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
danielk1977404ca072009-03-16 13:19:36 +0000404 }else if( pBt->nTransaction==2 ){
drh0ee3dbe2009-10-16 15:05:18 +0000405 /* This function is called when Btree p is concluding its
danielk1977404ca072009-03-16 13:19:36 +0000406 ** transaction. If there currently exists a writer, and p is not
407 ** that writer, then the number of locks held by connections other
408 ** than the writer must be about to drop to zero. In this case
drhc9166342012-01-05 23:32:06 +0000409 ** set the BTS_PENDING flag to 0.
danielk1977404ca072009-03-16 13:19:36 +0000410 **
drhc9166342012-01-05 23:32:06 +0000411 ** If there is not currently a writer, then BTS_PENDING must
danielk1977404ca072009-03-16 13:19:36 +0000412 ** be zero already. So this next line is harmless in that case.
413 */
drhc9166342012-01-05 23:32:06 +0000414 pBt->btsFlags &= ~BTS_PENDING;
danielk1977641b0f42007-12-21 04:47:25 +0000415 }
danielk1977aef0bf62005-12-30 16:28:01 +0000416}
danielk197794b30732009-07-02 17:21:57 +0000417
danielk1977e0d9e6f2009-07-03 16:25:06 +0000418/*
drh0ee3dbe2009-10-16 15:05:18 +0000419** This function changes all write-locks held by Btree p into read-locks.
danielk1977e0d9e6f2009-07-03 16:25:06 +0000420*/
danielk197794b30732009-07-02 17:21:57 +0000421static void downgradeAllSharedCacheTableLocks(Btree *p){
422 BtShared *pBt = p->pBt;
423 if( pBt->pWriter==p ){
424 BtLock *pLock;
425 pBt->pWriter = 0;
drhc9166342012-01-05 23:32:06 +0000426 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
danielk197794b30732009-07-02 17:21:57 +0000427 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
428 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
429 pLock->eLock = READ_LOCK;
430 }
431 }
432}
433
danielk1977aef0bf62005-12-30 16:28:01 +0000434#endif /* SQLITE_OMIT_SHARED_CACHE */
435
drh980b1a72006-08-16 16:42:48 +0000436static void releasePage(MemPage *pPage); /* Forward reference */
437
drh1fee73e2007-08-29 04:00:57 +0000438/*
drh0ee3dbe2009-10-16 15:05:18 +0000439***** This routine is used inside of assert() only ****
440**
441** Verify that the cursor holds the mutex on its BtShared
drh1fee73e2007-08-29 04:00:57 +0000442*/
drh0ee3dbe2009-10-16 15:05:18 +0000443#ifdef SQLITE_DEBUG
drh1fee73e2007-08-29 04:00:57 +0000444static int cursorHoldsMutex(BtCursor *p){
drhff0587c2007-08-29 17:43:19 +0000445 return sqlite3_mutex_held(p->pBt->mutex);
drh1fee73e2007-08-29 04:00:57 +0000446}
447#endif
448
danielk197792d4d7a2007-05-04 12:05:56 +0000449/*
dan5a500af2014-03-11 20:33:04 +0000450** Invalidate the overflow cache of the cursor passed as the first argument.
451** on the shared btree structure pBt.
danielk197792d4d7a2007-05-04 12:05:56 +0000452*/
drh036dbec2014-03-11 23:40:44 +0000453#define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
danielk197792d4d7a2007-05-04 12:05:56 +0000454
455/*
456** Invalidate the overflow page-list cache for all cursors opened
457** on the shared btree structure pBt.
458*/
459static void invalidateAllOverflowCache(BtShared *pBt){
460 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000461 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +0000462 for(p=pBt->pCursor; p; p=p->pNext){
463 invalidateOverflowCache(p);
464 }
465}
danielk197796d48e92009-06-29 06:00:37 +0000466
dan5a500af2014-03-11 20:33:04 +0000467#ifndef SQLITE_OMIT_INCRBLOB
danielk197796d48e92009-06-29 06:00:37 +0000468/*
469** This function is called before modifying the contents of a table
drh0ee3dbe2009-10-16 15:05:18 +0000470** to invalidate any incrblob cursors that are open on the
drheeb844a2009-08-08 18:01:07 +0000471** row or one of the rows being modified.
danielk197796d48e92009-06-29 06:00:37 +0000472**
473** If argument isClearTable is true, then the entire contents of the
474** table is about to be deleted. In this case invalidate all incrblob
475** cursors open on any row within the table with root-page pgnoRoot.
476**
477** Otherwise, if argument isClearTable is false, then the row with
478** rowid iRow is being replaced or deleted. In this case invalidate
drh0ee3dbe2009-10-16 15:05:18 +0000479** only those incrblob cursors open on that specific row.
danielk197796d48e92009-06-29 06:00:37 +0000480*/
481static void invalidateIncrblobCursors(
482 Btree *pBtree, /* The database file to check */
danielk197796d48e92009-06-29 06:00:37 +0000483 i64 iRow, /* The rowid that might be changing */
484 int isClearTable /* True if all rows are being deleted */
485){
486 BtCursor *p;
487 BtShared *pBt = pBtree->pBt;
488 assert( sqlite3BtreeHoldsMutex(pBtree) );
489 for(p=pBt->pCursor; p; p=p->pNext){
drh3f387402014-09-24 01:23:00 +0000490 if( (p->curFlags & BTCF_Incrblob)!=0
491 && (isClearTable || p->info.nKey==iRow)
492 ){
danielk197796d48e92009-06-29 06:00:37 +0000493 p->eState = CURSOR_INVALID;
494 }
495 }
496}
497
danielk197792d4d7a2007-05-04 12:05:56 +0000498#else
dan5a500af2014-03-11 20:33:04 +0000499 /* Stub function when INCRBLOB is omitted */
drheeb844a2009-08-08 18:01:07 +0000500 #define invalidateIncrblobCursors(x,y,z)
drh0ee3dbe2009-10-16 15:05:18 +0000501#endif /* SQLITE_OMIT_INCRBLOB */
danielk197792d4d7a2007-05-04 12:05:56 +0000502
drh980b1a72006-08-16 16:42:48 +0000503/*
danielk1977bea2a942009-01-20 17:06:27 +0000504** Set bit pgno of the BtShared.pHasContent bitvec. This is called
505** when a page that previously contained data becomes a free-list leaf
506** page.
507**
508** The BtShared.pHasContent bitvec exists to work around an obscure
509** bug caused by the interaction of two useful IO optimizations surrounding
510** free-list leaf pages:
511**
512** 1) When all data is deleted from a page and the page becomes
513** a free-list leaf page, the page is not written to the database
514** (as free-list leaf pages contain no meaningful data). Sometimes
515** such a page is not even journalled (as it will not be modified,
516** why bother journalling it?).
517**
518** 2) When a free-list leaf page is reused, its content is not read
519** from the database or written to the journal file (why should it
520** be, if it is not at all meaningful?).
521**
522** By themselves, these optimizations work fine and provide a handy
523** performance boost to bulk delete or insert operations. However, if
524** a page is moved to the free-list and then reused within the same
525** transaction, a problem comes up. If the page is not journalled when
526** it is moved to the free-list and it is also not journalled when it
527** is extracted from the free-list and reused, then the original data
528** may be lost. In the event of a rollback, it may not be possible
529** to restore the database to its original configuration.
530**
531** The solution is the BtShared.pHasContent bitvec. Whenever a page is
532** moved to become a free-list leaf page, the corresponding bit is
533** set in the bitvec. Whenever a leaf page is extracted from the free-list,
drh0ee3dbe2009-10-16 15:05:18 +0000534** optimization 2 above is omitted if the corresponding bit is already
danielk1977bea2a942009-01-20 17:06:27 +0000535** set in BtShared.pHasContent. The contents of the bitvec are cleared
536** at the end of every transaction.
537*/
538static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
539 int rc = SQLITE_OK;
540 if( !pBt->pHasContent ){
drhdd3cd972010-03-27 17:12:36 +0000541 assert( pgno<=pBt->nPage );
542 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
drh4c301aa2009-07-15 17:25:45 +0000543 if( !pBt->pHasContent ){
544 rc = SQLITE_NOMEM;
danielk1977bea2a942009-01-20 17:06:27 +0000545 }
546 }
547 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
548 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
549 }
550 return rc;
551}
552
553/*
554** Query the BtShared.pHasContent vector.
555**
556** This function is called when a free-list leaf page is removed from the
557** free-list for reuse. It returns false if it is safe to retrieve the
558** page from the pager layer with the 'no-content' flag set. True otherwise.
559*/
560static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
561 Bitvec *p = pBt->pHasContent;
562 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
563}
564
565/*
566** Clear (destroy) the BtShared.pHasContent bitvec. This should be
567** invoked at the conclusion of each write-transaction.
568*/
569static void btreeClearHasContent(BtShared *pBt){
570 sqlite3BitvecDestroy(pBt->pHasContent);
571 pBt->pHasContent = 0;
572}
573
574/*
drh138eeeb2013-03-27 03:15:23 +0000575** Release all of the apPage[] pages for a cursor.
576*/
577static void btreeReleaseAllCursorPages(BtCursor *pCur){
578 int i;
579 for(i=0; i<=pCur->iPage; i++){
580 releasePage(pCur->apPage[i]);
581 pCur->apPage[i] = 0;
582 }
583 pCur->iPage = -1;
584}
585
586
587/*
drh980b1a72006-08-16 16:42:48 +0000588** Save the current cursor position in the variables BtCursor.nKey
589** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
drhea8ffdf2009-07-22 00:35:23 +0000590**
591** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
592** prior to calling this routine.
drh980b1a72006-08-16 16:42:48 +0000593*/
594static int saveCursorPosition(BtCursor *pCur){
595 int rc;
596
597 assert( CURSOR_VALID==pCur->eState );
598 assert( 0==pCur->pKey );
drh1fee73e2007-08-29 04:00:57 +0000599 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000600
601 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
drhea8ffdf2009-07-22 00:35:23 +0000602 assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
drh980b1a72006-08-16 16:42:48 +0000603
604 /* If this is an intKey table, then the above call to BtreeKeySize()
605 ** stores the integer key in pCur->nKey. In this case this value is
606 ** all that is required. Otherwise, if pCur is not open on an intKey
607 ** table, then malloc space for and store the pCur->nKey bytes of key
608 ** data.
609 */
drh4c301aa2009-07-15 17:25:45 +0000610 if( 0==pCur->apPage[0]->intKey ){
drhda4ca9d2014-09-09 17:27:35 +0000611 void *pKey = sqlite3Malloc( pCur->nKey );
drh980b1a72006-08-16 16:42:48 +0000612 if( pKey ){
drhf49661a2008-12-10 16:45:50 +0000613 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
drh980b1a72006-08-16 16:42:48 +0000614 if( rc==SQLITE_OK ){
615 pCur->pKey = pKey;
616 }else{
drh17435752007-08-16 04:30:38 +0000617 sqlite3_free(pKey);
drh980b1a72006-08-16 16:42:48 +0000618 }
619 }else{
620 rc = SQLITE_NOMEM;
621 }
622 }
danielk197771d5d2c2008-09-29 11:49:47 +0000623 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
drh980b1a72006-08-16 16:42:48 +0000624
625 if( rc==SQLITE_OK ){
drh138eeeb2013-03-27 03:15:23 +0000626 btreeReleaseAllCursorPages(pCur);
drh980b1a72006-08-16 16:42:48 +0000627 pCur->eState = CURSOR_REQUIRESEEK;
628 }
629
danielk197792d4d7a2007-05-04 12:05:56 +0000630 invalidateOverflowCache(pCur);
drh980b1a72006-08-16 16:42:48 +0000631 return rc;
632}
633
drh637f3d82014-08-22 22:26:07 +0000634/* Forward reference */
635static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
636
drh980b1a72006-08-16 16:42:48 +0000637/*
drh0ee3dbe2009-10-16 15:05:18 +0000638** Save the positions of all cursors (except pExcept) that are open on
drh637f3d82014-08-22 22:26:07 +0000639** the table with root-page iRoot. "Saving the cursor position" means that
640** the location in the btree is remembered in such a way that it can be
641** moved back to the same spot after the btree has been modified. This
642** routine is called just before cursor pExcept is used to modify the
643** table, for example in BtreeDelete() or BtreeInsert().
644**
645** Implementation note: This routine merely checks to see if any cursors
646** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
647** event that cursors are in need to being saved.
drh980b1a72006-08-16 16:42:48 +0000648*/
649static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
drh3bdffdd2014-08-23 19:08:09 +0000650 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000651 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +0000652 assert( pExcept==0 || pExcept->pBt==pBt );
drh980b1a72006-08-16 16:42:48 +0000653 for(p=pBt->pCursor; p; p=p->pNext){
drh637f3d82014-08-22 22:26:07 +0000654 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
655 }
656 return p ? saveCursorsOnList(p, iRoot, pExcept) : SQLITE_OK;
657}
658
659/* This helper routine to saveAllCursors does the actual work of saving
660** the cursors if and when a cursor is found that actually requires saving.
661** The common case is that no cursors need to be saved, so this routine is
662** broken out from its caller to avoid unnecessary stack pointer movement.
663*/
664static int SQLITE_NOINLINE saveCursorsOnList(
drh3f387402014-09-24 01:23:00 +0000665 BtCursor *p, /* The first cursor that needs saving */
666 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
667 BtCursor *pExcept /* Do not save this cursor */
drh637f3d82014-08-22 22:26:07 +0000668){
669 do{
drh138eeeb2013-03-27 03:15:23 +0000670 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
671 if( p->eState==CURSOR_VALID ){
672 int rc = saveCursorPosition(p);
673 if( SQLITE_OK!=rc ){
674 return rc;
675 }
676 }else{
677 testcase( p->iPage>0 );
678 btreeReleaseAllCursorPages(p);
drh980b1a72006-08-16 16:42:48 +0000679 }
680 }
drh637f3d82014-08-22 22:26:07 +0000681 p = p->pNext;
682 }while( p );
drh980b1a72006-08-16 16:42:48 +0000683 return SQLITE_OK;
684}
685
686/*
drhbf700f32007-03-31 02:36:44 +0000687** Clear the current cursor position.
688*/
danielk1977be51a652008-10-08 17:58:48 +0000689void sqlite3BtreeClearCursor(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000690 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000691 sqlite3_free(pCur->pKey);
drhbf700f32007-03-31 02:36:44 +0000692 pCur->pKey = 0;
693 pCur->eState = CURSOR_INVALID;
694}
695
696/*
danielk19773509a652009-07-06 18:56:13 +0000697** In this version of BtreeMoveto, pKey is a packed index record
698** such as is generated by the OP_MakeRecord opcode. Unpack the
699** record and then call BtreeMovetoUnpacked() to do the work.
700*/
701static int btreeMoveto(
702 BtCursor *pCur, /* Cursor open on the btree to be searched */
703 const void *pKey, /* Packed key if the btree is an index */
704 i64 nKey, /* Integer key for tables. Size of pKey for indices */
705 int bias, /* Bias search to the high end */
706 int *pRes /* Write search results here */
707){
708 int rc; /* Status code */
709 UnpackedRecord *pIdxKey; /* Unpacked index key */
drhb4139222013-11-06 14:36:08 +0000710 char aSpace[200]; /* Temp space for pIdxKey - to avoid a malloc */
dan03e9cfc2011-09-05 14:20:27 +0000711 char *pFree = 0;
danielk19773509a652009-07-06 18:56:13 +0000712
713 if( pKey ){
714 assert( nKey==(i64)(int)nKey );
dan03e9cfc2011-09-05 14:20:27 +0000715 pIdxKey = sqlite3VdbeAllocUnpackedRecord(
716 pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
717 );
danielk19773509a652009-07-06 18:56:13 +0000718 if( pIdxKey==0 ) return SQLITE_NOMEM;
mistachkin0fe5f952011-09-14 18:19:08 +0000719 sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
drh094b7582013-11-30 12:49:28 +0000720 if( pIdxKey->nField==0 ){
721 sqlite3DbFree(pCur->pKeyInfo->db, pFree);
722 return SQLITE_CORRUPT_BKPT;
723 }
danielk19773509a652009-07-06 18:56:13 +0000724 }else{
725 pIdxKey = 0;
726 }
727 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
dan42acb3e2011-09-05 20:16:38 +0000728 if( pFree ){
dan03e9cfc2011-09-05 14:20:27 +0000729 sqlite3DbFree(pCur->pKeyInfo->db, pFree);
danielk19773509a652009-07-06 18:56:13 +0000730 }
731 return rc;
732}
733
734/*
drh980b1a72006-08-16 16:42:48 +0000735** Restore the cursor to the position it was in (or as close to as possible)
736** when saveCursorPosition() was called. Note that this call deletes the
737** saved position info stored by saveCursorPosition(), so there can be
drha3460582008-07-11 21:02:53 +0000738** at most one effective restoreCursorPosition() call after each
drh980b1a72006-08-16 16:42:48 +0000739** saveCursorPosition().
drh980b1a72006-08-16 16:42:48 +0000740*/
danielk197730548662009-07-09 05:07:37 +0000741static int btreeRestoreCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +0000742 int rc;
drh1fee73e2007-08-29 04:00:57 +0000743 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +0000744 assert( pCur->eState>=CURSOR_REQUIRESEEK );
745 if( pCur->eState==CURSOR_FAULT ){
drh4c301aa2009-07-15 17:25:45 +0000746 return pCur->skipNext;
drhfb982642007-08-30 01:19:59 +0000747 }
drh980b1a72006-08-16 16:42:48 +0000748 pCur->eState = CURSOR_INVALID;
drh4c301aa2009-07-15 17:25:45 +0000749 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
drh980b1a72006-08-16 16:42:48 +0000750 if( rc==SQLITE_OK ){
drh17435752007-08-16 04:30:38 +0000751 sqlite3_free(pCur->pKey);
drh980b1a72006-08-16 16:42:48 +0000752 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +0000753 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drh9b47ee32013-08-20 03:13:51 +0000754 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
755 pCur->eState = CURSOR_SKIPNEXT;
756 }
drh980b1a72006-08-16 16:42:48 +0000757 }
758 return rc;
759}
760
drha3460582008-07-11 21:02:53 +0000761#define restoreCursorPosition(p) \
drhfb982642007-08-30 01:19:59 +0000762 (p->eState>=CURSOR_REQUIRESEEK ? \
danielk197730548662009-07-09 05:07:37 +0000763 btreeRestoreCursorPosition(p) : \
drh16a9b832007-05-05 18:39:25 +0000764 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +0000765
drha3460582008-07-11 21:02:53 +0000766/*
drh6848dad2014-08-22 23:33:03 +0000767** Determine whether or not a cursor has moved from the position where
768** it was last placed, or has been invalidated for any other reason.
769** Cursors can move when the row they are pointing at is deleted out
770** from under them, for example. Cursor might also move if a btree
771** is rebalanced.
drha3460582008-07-11 21:02:53 +0000772**
drh6848dad2014-08-22 23:33:03 +0000773** Calling this routine with a NULL cursor pointer returns false.
drh86dd3712014-03-25 11:00:21 +0000774**
drh6848dad2014-08-22 23:33:03 +0000775** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
776** back to where it ought to be if this routine returns true.
drha3460582008-07-11 21:02:53 +0000777*/
drh6848dad2014-08-22 23:33:03 +0000778int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
drhc22284f2014-10-13 16:02:20 +0000779 return pCur->eState!=CURSOR_VALID;
drh6848dad2014-08-22 23:33:03 +0000780}
781
782/*
783** This routine restores a cursor back to its original position after it
784** has been moved by some outside activity (such as a btree rebalance or
785** a row having been deleted out from under the cursor).
786**
787** On success, the *pDifferentRow parameter is false if the cursor is left
788** pointing at exactly the same row. *pDifferntRow is the row the cursor
789** was pointing to has been deleted, forcing the cursor to point to some
790** nearby row.
791**
792** This routine should only be called for a cursor that just returned
793** TRUE from sqlite3BtreeCursorHasMoved().
794*/
795int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
drha3460582008-07-11 21:02:53 +0000796 int rc;
797
drh6848dad2014-08-22 23:33:03 +0000798 assert( pCur!=0 );
799 assert( pCur->eState!=CURSOR_VALID );
drha3460582008-07-11 21:02:53 +0000800 rc = restoreCursorPosition(pCur);
801 if( rc ){
drh6848dad2014-08-22 23:33:03 +0000802 *pDifferentRow = 1;
drha3460582008-07-11 21:02:53 +0000803 return rc;
804 }
drh9b47ee32013-08-20 03:13:51 +0000805 if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
drh6848dad2014-08-22 23:33:03 +0000806 *pDifferentRow = 1;
drha3460582008-07-11 21:02:53 +0000807 }else{
drh6848dad2014-08-22 23:33:03 +0000808 *pDifferentRow = 0;
drha3460582008-07-11 21:02:53 +0000809 }
810 return SQLITE_OK;
811}
812
danielk1977599fcba2004-11-08 07:13:13 +0000813#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000814/*
drha3152892007-05-05 11:48:52 +0000815** Given a page number of a regular database page, return the page
816** number for the pointer-map page that contains the entry for the
817** input page number.
drh5f77b2e2010-08-21 15:09:37 +0000818**
819** Return 0 (not a valid page) for pgno==1 since there is
820** no pointer map associated with page 1. The integrity_check logic
821** requires that ptrmapPageno(*,1)!=1.
danielk1977afcdd022004-10-31 16:25:42 +0000822*/
danielk1977266664d2006-02-10 08:24:21 +0000823static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
danielk197789d40042008-11-17 14:20:56 +0000824 int nPagesPerMapPage;
825 Pgno iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +0000826 assert( sqlite3_mutex_held(pBt->mutex) );
drh5f77b2e2010-08-21 15:09:37 +0000827 if( pgno<2 ) return 0;
drhd677b3d2007-08-20 22:48:41 +0000828 nPagesPerMapPage = (pBt->usableSize/5)+1;
829 iPtrMap = (pgno-2)/nPagesPerMapPage;
830 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +0000831 if( ret==PENDING_BYTE_PAGE(pBt) ){
832 ret++;
833 }
834 return ret;
835}
danielk1977a19df672004-11-03 11:37:07 +0000836
danielk1977afcdd022004-10-31 16:25:42 +0000837/*
danielk1977afcdd022004-10-31 16:25:42 +0000838** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000839**
840** This routine updates the pointer map entry for page number 'key'
841** so that it maps to type 'eType' and parent page number 'pgno'.
drh98add2e2009-07-20 17:11:49 +0000842**
843** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
844** a no-op. If an error occurs, the appropriate error code is written
845** into *pRC.
danielk1977afcdd022004-10-31 16:25:42 +0000846*/
drh98add2e2009-07-20 17:11:49 +0000847static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
danielk19773b8a05f2007-03-19 17:44:26 +0000848 DbPage *pDbPage; /* The pointer map page */
849 u8 *pPtrmap; /* The pointer map data */
850 Pgno iPtrmap; /* The pointer map page number */
851 int offset; /* Offset in pointer map page */
drh98add2e2009-07-20 17:11:49 +0000852 int rc; /* Return code from subfunctions */
853
854 if( *pRC ) return;
danielk1977afcdd022004-10-31 16:25:42 +0000855
drh1fee73e2007-08-29 04:00:57 +0000856 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977266664d2006-02-10 08:24:21 +0000857 /* The master-journal page number must never be used as a pointer map page */
858 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
859
danielk1977ac11ee62005-01-15 12:45:51 +0000860 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000861 if( key==0 ){
drh98add2e2009-07-20 17:11:49 +0000862 *pRC = SQLITE_CORRUPT_BKPT;
863 return;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000864 }
danielk1977266664d2006-02-10 08:24:21 +0000865 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000866 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977687566d2004-11-02 12:56:41 +0000867 if( rc!=SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +0000868 *pRC = rc;
869 return;
danielk1977afcdd022004-10-31 16:25:42 +0000870 }
danielk19778c666b12008-07-18 09:34:57 +0000871 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drhacfc72b2009-06-05 18:44:15 +0000872 if( offset<0 ){
drh98add2e2009-07-20 17:11:49 +0000873 *pRC = SQLITE_CORRUPT_BKPT;
drh4925a552009-07-07 11:39:58 +0000874 goto ptrmap_exit;
drhacfc72b2009-06-05 18:44:15 +0000875 }
drhfc243732011-05-17 15:21:56 +0000876 assert( offset <= (int)pBt->usableSize-5 );
danielk19773b8a05f2007-03-19 17:44:26 +0000877 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000878
drh615ae552005-01-16 23:21:00 +0000879 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
880 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
drh98add2e2009-07-20 17:11:49 +0000881 *pRC= rc = sqlite3PagerWrite(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000882 if( rc==SQLITE_OK ){
883 pPtrmap[offset] = eType;
884 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000885 }
danielk1977afcdd022004-10-31 16:25:42 +0000886 }
887
drh4925a552009-07-07 11:39:58 +0000888ptrmap_exit:
danielk19773b8a05f2007-03-19 17:44:26 +0000889 sqlite3PagerUnref(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000890}
891
892/*
893** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000894**
895** This routine retrieves the pointer map entry for page 'key', writing
896** the type and parent page number to *pEType and *pPgno respectively.
897** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000898*/
danielk1977aef0bf62005-12-30 16:28:01 +0000899static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +0000900 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000901 int iPtrmap; /* Pointer map page index */
902 u8 *pPtrmap; /* Pointer map page data */
903 int offset; /* Offset of entry in pointer map */
904 int rc;
905
drh1fee73e2007-08-29 04:00:57 +0000906 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000907
danielk1977266664d2006-02-10 08:24:21 +0000908 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000909 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000910 if( rc!=0 ){
911 return rc;
912 }
danielk19773b8a05f2007-03-19 17:44:26 +0000913 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000914
danielk19778c666b12008-07-18 09:34:57 +0000915 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drhfc243732011-05-17 15:21:56 +0000916 if( offset<0 ){
917 sqlite3PagerUnref(pDbPage);
918 return SQLITE_CORRUPT_BKPT;
919 }
920 assert( offset <= (int)pBt->usableSize-5 );
drh43617e92006-03-06 20:55:46 +0000921 assert( pEType!=0 );
922 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +0000923 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000924
danielk19773b8a05f2007-03-19 17:44:26 +0000925 sqlite3PagerUnref(pDbPage);
drh49285702005-09-17 15:20:26 +0000926 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000927 return SQLITE_OK;
928}
929
danielk197785d90ca2008-07-19 14:25:15 +0000930#else /* if defined SQLITE_OMIT_AUTOVACUUM */
drh98add2e2009-07-20 17:11:49 +0000931 #define ptrmapPut(w,x,y,z,rc)
danielk197785d90ca2008-07-19 14:25:15 +0000932 #define ptrmapGet(w,x,y,z) SQLITE_OK
drh98add2e2009-07-20 17:11:49 +0000933 #define ptrmapPutOvflPtr(x, y, rc)
danielk197785d90ca2008-07-19 14:25:15 +0000934#endif
danielk1977afcdd022004-10-31 16:25:42 +0000935
drh0d316a42002-08-11 20:10:47 +0000936/*
drh271efa52004-05-30 19:19:05 +0000937** Given a btree page and a cell index (0 means the first cell on
938** the page, 1 means the second cell, and so forth) return a pointer
939** to the cell content.
940**
941** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000942*/
drh1688c862008-07-18 02:44:17 +0000943#define findCell(P,I) \
drh3def2352011-11-11 00:27:15 +0000944 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
drh68f2a572011-06-03 17:50:49 +0000945#define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
946
drh43605152004-05-29 21:46:49 +0000947
948/*
drh93a960a2008-07-10 00:32:42 +0000949** This a more complex version of findCell() that works for
drh0a45c272009-07-08 01:49:11 +0000950** pages that do contain overflow cells.
drh43605152004-05-29 21:46:49 +0000951*/
952static u8 *findOverflowCell(MemPage *pPage, int iCell){
953 int i;
drh1fee73e2007-08-29 04:00:57 +0000954 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +0000955 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000956 int k;
drh2cbd78b2012-02-02 19:37:18 +0000957 k = pPage->aiOvfl[i];
drh6d08b4d2004-07-20 12:45:22 +0000958 if( k<=iCell ){
959 if( k==iCell ){
drh2cbd78b2012-02-02 19:37:18 +0000960 return pPage->apOvfl[i];
drh43605152004-05-29 21:46:49 +0000961 }
962 iCell--;
963 }
964 }
danielk19771cc5ed82007-05-16 17:28:43 +0000965 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000966}
967
968/*
969** Parse a cell content block and fill in the CellInfo structure. There
danielk197730548662009-07-09 05:07:37 +0000970** are two versions of this function. btreeParseCell() takes a
971** cell index as the second argument and btreeParseCellPtr()
drh16a9b832007-05-05 18:39:25 +0000972** takes a pointer to the body of the cell as its second argument.
drh43605152004-05-29 21:46:49 +0000973*/
danielk197730548662009-07-09 05:07:37 +0000974static void btreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000975 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000976 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000977 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000978){
drh3e28ff52014-09-24 00:59:08 +0000979 u8 *pIter; /* For scanning through pCell */
drh271efa52004-05-30 19:19:05 +0000980 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000981
drh1fee73e2007-08-29 04:00:57 +0000982 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhab01f612004-05-22 02:55:23 +0000983 assert( pPage->leaf==0 || pPage->leaf==1 );
drh3e28ff52014-09-24 00:59:08 +0000984 if( pPage->intKeyLeaf ){
985 assert( pPage->childPtrSize==0 );
986 pIter = pCell + getVarint32(pCell, nPayload);
drhab1cc582014-09-23 21:25:19 +0000987 pIter += getVarint(pIter, (u64*)&pInfo->nKey);
drh3e28ff52014-09-24 00:59:08 +0000988 }else if( pPage->noPayload ){
989 assert( pPage->childPtrSize==4 );
990 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
991 pInfo->nPayload = 0;
992 pInfo->nLocal = 0;
993 pInfo->iOverflow = 0;
994 pInfo->pPayload = 0;
995 return;
drh504b6982006-01-22 21:52:56 +0000996 }else{
drh3e28ff52014-09-24 00:59:08 +0000997 pIter = pCell + pPage->childPtrSize;
drhab1cc582014-09-23 21:25:19 +0000998 pIter += getVarint32(pIter, nPayload);
drh79df1f42008-07-18 00:57:33 +0000999 pInfo->nKey = nPayload;
drh6f11bef2004-05-13 01:12:56 +00001000 }
drh72365832007-03-06 15:53:44 +00001001 pInfo->nPayload = nPayload;
drhab1cc582014-09-23 21:25:19 +00001002 pInfo->pPayload = pIter;
drh0a45c272009-07-08 01:49:11 +00001003 testcase( nPayload==pPage->maxLocal );
1004 testcase( nPayload==pPage->maxLocal+1 );
drhab1cc582014-09-23 21:25:19 +00001005 if( nPayload<=pPage->maxLocal ){
drh271efa52004-05-30 19:19:05 +00001006 /* This is the (easy) common case where the entire payload fits
1007 ** on the local page. No overflow is required.
1008 */
drhab1cc582014-09-23 21:25:19 +00001009 pInfo->nSize = nPayload + (u16)(pIter - pCell);
1010 if( pInfo->nSize<4 ) pInfo->nSize = 4;
drhf49661a2008-12-10 16:45:50 +00001011 pInfo->nLocal = (u16)nPayload;
drh6f11bef2004-05-13 01:12:56 +00001012 pInfo->iOverflow = 0;
drh6f11bef2004-05-13 01:12:56 +00001013 }else{
drh271efa52004-05-30 19:19:05 +00001014 /* If the payload will not fit completely on the local page, we have
1015 ** to decide how much to store locally and how much to spill onto
1016 ** overflow pages. The strategy is to minimize the amount of unused
1017 ** space on overflow pages while keeping the amount of local storage
1018 ** in between minLocal and maxLocal.
1019 **
1020 ** Warning: changing the way overflow payload is distributed in any
1021 ** way will result in an incompatible file format.
1022 */
1023 int minLocal; /* Minimum amount of payload held locally */
1024 int maxLocal; /* Maximum amount of payload held locally */
1025 int surplus; /* Overflow payload available for local storage */
1026
1027 minLocal = pPage->minLocal;
1028 maxLocal = pPage->maxLocal;
1029 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh0a45c272009-07-08 01:49:11 +00001030 testcase( surplus==maxLocal );
1031 testcase( surplus==maxLocal+1 );
drh6f11bef2004-05-13 01:12:56 +00001032 if( surplus <= maxLocal ){
drhf49661a2008-12-10 16:45:50 +00001033 pInfo->nLocal = (u16)surplus;
drh6f11bef2004-05-13 01:12:56 +00001034 }else{
drhf49661a2008-12-10 16:45:50 +00001035 pInfo->nLocal = (u16)minLocal;
drh6f11bef2004-05-13 01:12:56 +00001036 }
drhab1cc582014-09-23 21:25:19 +00001037 pInfo->iOverflow = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell);
drh6f11bef2004-05-13 01:12:56 +00001038 pInfo->nSize = pInfo->iOverflow + 4;
1039 }
drh3aac2dd2004-04-26 14:10:20 +00001040}
danielk197730548662009-07-09 05:07:37 +00001041static void btreeParseCell(
drh43605152004-05-29 21:46:49 +00001042 MemPage *pPage, /* Page containing the cell */
1043 int iCell, /* The cell index. First cell is 0 */
1044 CellInfo *pInfo /* Fill in this structure */
1045){
drhc4683832014-09-23 23:12:53 +00001046 btreeParseCellPtr(pPage, findCell(pPage, iCell), pInfo);
drh43605152004-05-29 21:46:49 +00001047}
drh3aac2dd2004-04-26 14:10:20 +00001048
1049/*
drh43605152004-05-29 21:46:49 +00001050** Compute the total number of bytes that a Cell needs in the cell
1051** data area of the btree-page. The return number includes the cell
1052** data header and the local payload, but not any overflow page or
1053** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +00001054*/
danielk1977ae5558b2009-04-29 11:31:47 +00001055static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
drh3f387402014-09-24 01:23:00 +00001056 u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
1057 u8 *pEnd; /* End mark for a varint */
1058 u32 nSize; /* Size value to return */
danielk1977ae5558b2009-04-29 11:31:47 +00001059
1060#ifdef SQLITE_DEBUG
1061 /* The value returned by this function should always be the same as
1062 ** the (CellInfo.nSize) value found by doing a full parse of the
1063 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1064 ** this function verifies that this invariant is not violated. */
1065 CellInfo debuginfo;
danielk197730548662009-07-09 05:07:37 +00001066 btreeParseCellPtr(pPage, pCell, &debuginfo);
danielk1977ae5558b2009-04-29 11:31:47 +00001067#endif
1068
drh3e28ff52014-09-24 00:59:08 +00001069 if( pPage->noPayload ){
1070 pEnd = &pIter[9];
1071 while( (*pIter++)&0x80 && pIter<pEnd );
1072 assert( pPage->childPtrSize==4 );
1073 return (u16)(pIter - pCell);
drhdc41d602014-09-22 19:51:35 +00001074 }
drh3e28ff52014-09-24 00:59:08 +00001075 nSize = *pIter;
1076 if( nSize>=0x80 ){
1077 pEnd = &pIter[9];
1078 nSize &= 0x7f;
1079 do{
1080 nSize = (nSize<<7) | (*++pIter & 0x7f);
1081 }while( *(pIter)>=0x80 && pIter<pEnd );
1082 }
1083 pIter++;
drhdc41d602014-09-22 19:51:35 +00001084 if( pPage->intKey ){
danielk1977ae5558b2009-04-29 11:31:47 +00001085 /* pIter now points at the 64-bit integer key value, a variable length
1086 ** integer. The following block moves pIter to point at the first byte
1087 ** past the end of the key value. */
1088 pEnd = &pIter[9];
1089 while( (*pIter++)&0x80 && pIter<pEnd );
danielk1977ae5558b2009-04-29 11:31:47 +00001090 }
drh0a45c272009-07-08 01:49:11 +00001091 testcase( nSize==pPage->maxLocal );
1092 testcase( nSize==pPage->maxLocal+1 );
drh3e28ff52014-09-24 00:59:08 +00001093 if( nSize<=pPage->maxLocal ){
1094 nSize += (u32)(pIter - pCell);
1095 if( nSize<4 ) nSize = 4;
1096 }else{
danielk1977ae5558b2009-04-29 11:31:47 +00001097 int minLocal = pPage->minLocal;
1098 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
drh0a45c272009-07-08 01:49:11 +00001099 testcase( nSize==pPage->maxLocal );
1100 testcase( nSize==pPage->maxLocal+1 );
danielk1977ae5558b2009-04-29 11:31:47 +00001101 if( nSize>pPage->maxLocal ){
1102 nSize = minLocal;
1103 }
drh3e28ff52014-09-24 00:59:08 +00001104 nSize += 4 + (u16)(pIter - pCell);
danielk1977ae5558b2009-04-29 11:31:47 +00001105 }
drhdc41d602014-09-22 19:51:35 +00001106 assert( nSize==debuginfo.nSize || CORRUPT_DB );
shane60a4b532009-05-06 18:57:09 +00001107 return (u16)nSize;
danielk1977ae5558b2009-04-29 11:31:47 +00001108}
drh0ee3dbe2009-10-16 15:05:18 +00001109
1110#ifdef SQLITE_DEBUG
1111/* This variation on cellSizePtr() is used inside of assert() statements
1112** only. */
drha9121e42008-02-19 14:59:35 +00001113static u16 cellSize(MemPage *pPage, int iCell){
danielk1977ae5558b2009-04-29 11:31:47 +00001114 return cellSizePtr(pPage, findCell(pPage, iCell));
drh43605152004-05-29 21:46:49 +00001115}
danielk1977bc6ada42004-06-30 08:20:16 +00001116#endif
drh3b7511c2001-05-26 13:15:44 +00001117
danielk197779a40da2005-01-16 08:00:01 +00001118#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +00001119/*
danielk197726836652005-01-17 01:33:13 +00001120** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +00001121** to an overflow page, insert an entry into the pointer-map
1122** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +00001123*/
drh98add2e2009-07-20 17:11:49 +00001124static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
drhfa67c3c2008-07-11 02:21:40 +00001125 CellInfo info;
drh98add2e2009-07-20 17:11:49 +00001126 if( *pRC ) return;
drhfa67c3c2008-07-11 02:21:40 +00001127 assert( pCell!=0 );
danielk197730548662009-07-09 05:07:37 +00001128 btreeParseCellPtr(pPage, pCell, &info);
danielk19774dbaa892009-06-16 16:50:22 +00001129 if( info.iOverflow ){
drhfa67c3c2008-07-11 02:21:40 +00001130 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
drh98add2e2009-07-20 17:11:49 +00001131 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
danielk1977ac11ee62005-01-15 12:45:51 +00001132 }
danielk1977ac11ee62005-01-15 12:45:51 +00001133}
danielk197779a40da2005-01-16 08:00:01 +00001134#endif
1135
danielk1977ac11ee62005-01-15 12:45:51 +00001136
drhda200cc2004-05-09 11:51:38 +00001137/*
drh72f82862001-05-24 21:06:34 +00001138** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +00001139** end of the page and all free space is collected into one
1140** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +00001141** pointer array and the cell content area.
drhfdab0262014-11-20 15:30:50 +00001142**
1143** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
1144** b-tree page so that there are no freeblocks or fragment bytes, all
1145** unused bytes are contained in the unallocated space region, and all
1146** cells are packed tightly at the end of the page.
drh365d68f2001-05-11 11:02:46 +00001147*/
shane0af3f892008-11-12 04:55:34 +00001148static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +00001149 int i; /* Loop counter */
peter.d.reid60ec9142014-09-06 16:39:46 +00001150 int pc; /* Address of the i-th cell */
drh43605152004-05-29 21:46:49 +00001151 int hdr; /* Offset to the page header */
1152 int size; /* Size of a cell */
1153 int usableSize; /* Number of usable bytes on a page */
1154 int cellOffset; /* Offset to the cell pointer array */
drh281b21d2008-08-22 12:57:08 +00001155 int cbrk; /* Offset to the cell content area */
drh43605152004-05-29 21:46:49 +00001156 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +00001157 unsigned char *data; /* The page data */
1158 unsigned char *temp; /* Temp area for cell content */
drh588400b2014-09-27 05:00:25 +00001159 unsigned char *src; /* Source of content */
drh17146622009-07-07 17:38:38 +00001160 int iCellFirst; /* First allowable cell index */
1161 int iCellLast; /* Last possible cell index */
1162
drh2af926b2001-05-15 00:39:25 +00001163
danielk19773b8a05f2007-03-19 17:44:26 +00001164 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001165 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +00001166 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +00001167 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00001168 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh588400b2014-09-27 05:00:25 +00001169 temp = 0;
1170 src = data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +00001171 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00001172 cellOffset = pPage->cellOffset;
1173 nCell = pPage->nCell;
1174 assert( nCell==get2byte(&data[hdr+3]) );
1175 usableSize = pPage->pBt->usableSize;
drh281b21d2008-08-22 12:57:08 +00001176 cbrk = usableSize;
drh17146622009-07-07 17:38:38 +00001177 iCellFirst = cellOffset + 2*nCell;
1178 iCellLast = usableSize - 4;
drh43605152004-05-29 21:46:49 +00001179 for(i=0; i<nCell; i++){
1180 u8 *pAddr; /* The i-th cell pointer */
1181 pAddr = &data[cellOffset + i*2];
1182 pc = get2byte(pAddr);
drh0a45c272009-07-08 01:49:11 +00001183 testcase( pc==iCellFirst );
1184 testcase( pc==iCellLast );
drh17146622009-07-07 17:38:38 +00001185#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
danielk197730548662009-07-09 05:07:37 +00001186 /* These conditions have already been verified in btreeInitPage()
drh17146622009-07-07 17:38:38 +00001187 ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
1188 */
1189 if( pc<iCellFirst || pc>iCellLast ){
shane0af3f892008-11-12 04:55:34 +00001190 return SQLITE_CORRUPT_BKPT;
1191 }
drh17146622009-07-07 17:38:38 +00001192#endif
1193 assert( pc>=iCellFirst && pc<=iCellLast );
drh588400b2014-09-27 05:00:25 +00001194 size = cellSizePtr(pPage, &src[pc]);
drh281b21d2008-08-22 12:57:08 +00001195 cbrk -= size;
drh17146622009-07-07 17:38:38 +00001196#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
1197 if( cbrk<iCellFirst ){
shane0af3f892008-11-12 04:55:34 +00001198 return SQLITE_CORRUPT_BKPT;
1199 }
drh17146622009-07-07 17:38:38 +00001200#else
1201 if( cbrk<iCellFirst || pc+size>usableSize ){
1202 return SQLITE_CORRUPT_BKPT;
1203 }
1204#endif
drh7157e1d2009-07-09 13:25:32 +00001205 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
drh0a45c272009-07-08 01:49:11 +00001206 testcase( cbrk+size==usableSize );
drh0a45c272009-07-08 01:49:11 +00001207 testcase( pc+size==usableSize );
drh281b21d2008-08-22 12:57:08 +00001208 put2byte(pAddr, cbrk);
drh588400b2014-09-27 05:00:25 +00001209 if( temp==0 ){
1210 int x;
1211 if( cbrk==pc ) continue;
1212 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
1213 x = get2byte(&data[hdr+5]);
1214 memcpy(&temp[x], &data[x], (cbrk+size) - x);
1215 src = temp;
1216 }
1217 memcpy(&data[cbrk], &src[pc], size);
drh2af926b2001-05-15 00:39:25 +00001218 }
drh17146622009-07-07 17:38:38 +00001219 assert( cbrk>=iCellFirst );
drh281b21d2008-08-22 12:57:08 +00001220 put2byte(&data[hdr+5], cbrk);
drh43605152004-05-29 21:46:49 +00001221 data[hdr+1] = 0;
1222 data[hdr+2] = 0;
1223 data[hdr+7] = 0;
drh17146622009-07-07 17:38:38 +00001224 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
drhc5053fb2008-11-27 02:22:10 +00001225 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh17146622009-07-07 17:38:38 +00001226 if( cbrk-iCellFirst!=pPage->nFree ){
danielk1977360e6342008-11-12 08:49:51 +00001227 return SQLITE_CORRUPT_BKPT;
1228 }
shane0af3f892008-11-12 04:55:34 +00001229 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +00001230}
1231
drha059ad02001-04-17 20:09:11 +00001232/*
dan8e9ba0c2014-10-14 17:27:04 +00001233** Search the free-list on page pPg for space to store a cell nByte bytes in
1234** size. If one can be found, return a pointer to the space and remove it
1235** from the free-list.
1236**
1237** If no suitable space can be found on the free-list, return NULL.
1238**
drhba0f9992014-10-30 20:48:44 +00001239** This function may detect corruption within pPg. If corruption is
1240** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
dan61e94c92014-10-27 08:02:16 +00001241**
1242** If a slot of at least nByte bytes is found but cannot be used because
1243** there are already at least 60 fragmented bytes on the page, return NULL.
1244** In this case, if pbDefrag parameter is not NULL, set *pbDefrag to true.
dan8e9ba0c2014-10-14 17:27:04 +00001245*/
dan61e94c92014-10-27 08:02:16 +00001246static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc, int *pbDefrag){
dan8e9ba0c2014-10-14 17:27:04 +00001247 const int hdr = pPg->hdrOffset;
1248 u8 * const aData = pPg->aData;
1249 int iAddr;
1250 int pc;
1251 int usableSize = pPg->pBt->usableSize;
1252
1253 for(iAddr=hdr+1; (pc = get2byte(&aData[iAddr]))>0; iAddr=pc){
1254 int size; /* Size of the free slot */
drh113762a2014-11-19 16:36:25 +00001255 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
1256 ** increasing offset. */
dan8e9ba0c2014-10-14 17:27:04 +00001257 if( pc>usableSize-4 || pc<iAddr+4 ){
drhba0f9992014-10-30 20:48:44 +00001258 *pRc = SQLITE_CORRUPT_BKPT;
dan8e9ba0c2014-10-14 17:27:04 +00001259 return 0;
1260 }
drh113762a2014-11-19 16:36:25 +00001261 /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
1262 ** freeblock form a big-endian integer which is the size of the freeblock
1263 ** in bytes, including the 4-byte header. */
dan8e9ba0c2014-10-14 17:27:04 +00001264 size = get2byte(&aData[pc+2]);
1265 if( size>=nByte ){
1266 int x = size - nByte;
1267 testcase( x==4 );
1268 testcase( x==3 );
1269 if( x<4 ){
drhfdab0262014-11-20 15:30:50 +00001270 /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
1271 ** number of bytes in fragments may not exceed 60. */
dan61e94c92014-10-27 08:02:16 +00001272 if( aData[hdr+7]>=60 ){
1273 if( pbDefrag ) *pbDefrag = 1;
1274 return 0;
1275 }
dan8e9ba0c2014-10-14 17:27:04 +00001276 /* Remove the slot from the free-list. Update the number of
1277 ** fragmented bytes within the page. */
1278 memcpy(&aData[iAddr], &aData[pc], 2);
1279 aData[hdr+7] += (u8)x;
1280 }else if( size+pc > usableSize ){
drhba0f9992014-10-30 20:48:44 +00001281 *pRc = SQLITE_CORRUPT_BKPT;
dan8e9ba0c2014-10-14 17:27:04 +00001282 return 0;
1283 }else{
1284 /* The slot remains on the free-list. Reduce its size to account
1285 ** for the portion used by the new allocation. */
1286 put2byte(&aData[pc+2], x);
1287 }
1288 return &aData[pc + x];
1289 }
1290 }
1291
1292 return 0;
1293}
1294
1295/*
danielk19776011a752009-04-01 16:25:32 +00001296** Allocate nByte bytes of space from within the B-Tree page passed
drh0a45c272009-07-08 01:49:11 +00001297** as the first argument. Write into *pIdx the index into pPage->aData[]
1298** of the first byte of allocated space. Return either SQLITE_OK or
1299** an error code (usually SQLITE_CORRUPT).
drhbd03cae2001-06-02 02:40:57 +00001300**
drh0a45c272009-07-08 01:49:11 +00001301** The caller guarantees that there is sufficient space to make the
1302** allocation. This routine might need to defragment in order to bring
1303** all the space together, however. This routine will avoid using
1304** the first two bytes past the cell pointer area since presumably this
1305** allocation is being made in order to insert a new cell, so we will
1306** also end up needing a new cell pointer.
drh7e3b0a02001-04-28 16:52:40 +00001307*/
drh0a45c272009-07-08 01:49:11 +00001308static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
danielk19776011a752009-04-01 16:25:32 +00001309 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1310 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
drh0a45c272009-07-08 01:49:11 +00001311 int top; /* First byte of cell content area */
drhfefa0942014-11-05 21:21:08 +00001312 int rc = SQLITE_OK; /* Integer return code */
drh0a45c272009-07-08 01:49:11 +00001313 int gap; /* First byte of gap between cell pointers and cell content */
drh43605152004-05-29 21:46:49 +00001314
danielk19773b8a05f2007-03-19 17:44:26 +00001315 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001316 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +00001317 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa67c3c2008-07-11 02:21:40 +00001318 assert( nByte>=0 ); /* Minimum cell size is 4 */
1319 assert( pPage->nFree>=nByte );
1320 assert( pPage->nOverflow==0 );
mistachkina95d8ca2014-10-27 19:42:02 +00001321 assert( nByte < (int)(pPage->pBt->usableSize-8) );
drh43605152004-05-29 21:46:49 +00001322
drh0a45c272009-07-08 01:49:11 +00001323 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1324 gap = pPage->cellOffset + 2*pPage->nCell;
drh75b31dc2014-08-20 00:54:46 +00001325 assert( gap<=65536 );
drhfdab0262014-11-20 15:30:50 +00001326 /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
1327 ** and the reserved space is zero (the usual value for reserved space)
1328 ** then the cell content offset of an empty page wants to be 65536.
1329 ** However, that integer is too large to be stored in a 2-byte unsigned
1330 ** integer, so a value of 0 is used in its place. */
1331 top = get2byteNotZero(&data[hdr+5]);
1332 if( gap>top ) return SQLITE_CORRUPT_BKPT;
drh4c04f3c2014-08-20 11:56:14 +00001333
1334 /* If there is enough space between gap and top for one more cell pointer
1335 ** array entry offset, and if the freelist is not empty, then search the
1336 ** freelist looking for a free slot big enough to satisfy the request.
1337 */
drh0a45c272009-07-08 01:49:11 +00001338 testcase( gap+2==top );
1339 testcase( gap+1==top );
1340 testcase( gap==top );
drh4c04f3c2014-08-20 11:56:14 +00001341 if( gap+2<=top && (data[hdr+1] || data[hdr+2]) ){
dan61e94c92014-10-27 08:02:16 +00001342 int bDefrag = 0;
1343 u8 *pSpace = pageFindSlot(pPage, nByte, &rc, &bDefrag);
dan8e9ba0c2014-10-14 17:27:04 +00001344 if( rc ) return rc;
dan61e94c92014-10-27 08:02:16 +00001345 if( bDefrag ) goto defragment_page;
dan8e9ba0c2014-10-14 17:27:04 +00001346 if( pSpace ){
drhfefa0942014-11-05 21:21:08 +00001347 assert( pSpace>=data && (pSpace - data)<65536 );
1348 *pIdx = (int)(pSpace - data);
dan8e9ba0c2014-10-14 17:27:04 +00001349 return SQLITE_OK;
drh9e572e62004-04-23 23:43:10 +00001350 }
1351 }
drh43605152004-05-29 21:46:49 +00001352
drh4c04f3c2014-08-20 11:56:14 +00001353 /* The request could not be fulfilled using a freelist slot. Check
1354 ** to see if defragmentation is necessary.
drh0a45c272009-07-08 01:49:11 +00001355 */
1356 testcase( gap+2+nByte==top );
1357 if( gap+2+nByte>top ){
dan61e94c92014-10-27 08:02:16 +00001358 defragment_page:
drh1fd2d7d2014-12-02 16:16:47 +00001359 assert( pPage->nCell>0 || CORRUPT_DB );
drh0a45c272009-07-08 01:49:11 +00001360 rc = defragmentPage(pPage);
1361 if( rc ) return rc;
drh5d433ce2010-08-14 16:02:52 +00001362 top = get2byteNotZero(&data[hdr+5]);
drh0a45c272009-07-08 01:49:11 +00001363 assert( gap+nByte<=top );
1364 }
1365
1366
drh43605152004-05-29 21:46:49 +00001367 /* Allocate memory from the gap in between the cell pointer array
drhc314dc72009-07-21 11:52:34 +00001368 ** and the cell content area. The btreeInitPage() call has already
1369 ** validated the freelist. Given that the freelist is valid, there
1370 ** is no way that the allocation can extend off the end of the page.
1371 ** The assert() below verifies the previous sentence.
drh43605152004-05-29 21:46:49 +00001372 */
drh0a45c272009-07-08 01:49:11 +00001373 top -= nByte;
drh43605152004-05-29 21:46:49 +00001374 put2byte(&data[hdr+5], top);
drhfcd71b62011-04-05 22:08:24 +00001375 assert( top+nByte <= (int)pPage->pBt->usableSize );
drh0a45c272009-07-08 01:49:11 +00001376 *pIdx = top;
1377 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001378}
1379
1380/*
drh9e572e62004-04-23 23:43:10 +00001381** Return a section of the pPage->aData to the freelist.
drh7fb91642014-08-20 14:37:09 +00001382** The first byte of the new free block is pPage->aData[iStart]
1383** and the size of the block is iSize bytes.
drh306dc212001-05-21 13:45:10 +00001384**
drh5f5c7532014-08-20 17:56:27 +00001385** Adjacent freeblocks are coalesced.
1386**
1387** Note that even though the freeblock list was checked by btreeInitPage(),
1388** that routine will not detect overlap between cells or freeblocks. Nor
1389** does it detect cells or freeblocks that encrouch into the reserved bytes
1390** at the end of the page. So do additional corruption checks inside this
1391** routine and return SQLITE_CORRUPT if any problems are found.
drh7e3b0a02001-04-28 16:52:40 +00001392*/
drh5f5c7532014-08-20 17:56:27 +00001393static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
drh3f387402014-09-24 01:23:00 +00001394 u16 iPtr; /* Address of ptr to next freeblock */
drh5f5c7532014-08-20 17:56:27 +00001395 u16 iFreeBlk; /* Address of the next freeblock */
1396 u8 hdr; /* Page header size. 0 or 100 */
1397 u8 nFrag = 0; /* Reduction in fragmentation */
1398 u16 iOrigSize = iSize; /* Original value of iSize */
1399 u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
1400 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
drh7fb91642014-08-20 14:37:09 +00001401 unsigned char *data = pPage->aData; /* Page content */
drh2af926b2001-05-15 00:39:25 +00001402
drh9e572e62004-04-23 23:43:10 +00001403 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001404 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh7fb91642014-08-20 14:37:09 +00001405 assert( iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
dan23eba452014-10-24 18:43:57 +00001406 assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +00001407 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh7fb91642014-08-20 14:37:09 +00001408 assert( iSize>=4 ); /* Minimum cell size is 4 */
drh5f5c7532014-08-20 17:56:27 +00001409 assert( iStart<=iLast );
drh9e572e62004-04-23 23:43:10 +00001410
drh5f5c7532014-08-20 17:56:27 +00001411 /* Overwrite deleted information with zeros when the secure_delete
1412 ** option is enabled */
drhc9166342012-01-05 23:32:06 +00001413 if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
drh7fb91642014-08-20 14:37:09 +00001414 memset(&data[iStart], 0, iSize);
drh5b47efa2010-02-12 18:18:39 +00001415 }
drhfcce93f2006-02-22 03:08:32 +00001416
drh5f5c7532014-08-20 17:56:27 +00001417 /* The list of freeblocks must be in ascending order. Find the
1418 ** spot on the list where iStart should be inserted.
drh0a45c272009-07-08 01:49:11 +00001419 */
drh43605152004-05-29 21:46:49 +00001420 hdr = pPage->hdrOffset;
drh7fb91642014-08-20 14:37:09 +00001421 iPtr = hdr + 1;
drh7bc4c452014-08-20 18:43:44 +00001422 if( data[iPtr+1]==0 && data[iPtr]==0 ){
1423 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
1424 }else{
1425 while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
1426 if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
1427 iPtr = iFreeBlk;
drh9e572e62004-04-23 23:43:10 +00001428 }
drh7bc4c452014-08-20 18:43:44 +00001429 if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
1430 assert( iFreeBlk>iPtr || iFreeBlk==0 );
1431
1432 /* At this point:
1433 ** iFreeBlk: First freeblock after iStart, or zero if none
1434 ** iPtr: The address of a pointer iFreeBlk
1435 **
1436 ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
1437 */
1438 if( iFreeBlk && iEnd+3>=iFreeBlk ){
1439 nFrag = iFreeBlk - iEnd;
1440 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
1441 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
1442 iSize = iEnd - iStart;
1443 iFreeBlk = get2byte(&data[iFreeBlk]);
1444 }
1445
drh3f387402014-09-24 01:23:00 +00001446 /* If iPtr is another freeblock (that is, if iPtr is not the freelist
1447 ** pointer in the page header) then check to see if iStart should be
1448 ** coalesced onto the end of iPtr.
drh7bc4c452014-08-20 18:43:44 +00001449 */
1450 if( iPtr>hdr+1 ){
1451 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
1452 if( iPtrEnd+3>=iStart ){
1453 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
1454 nFrag += iStart - iPtrEnd;
1455 iSize = iEnd - iPtr;
1456 iStart = iPtr;
1457 }
1458 }
1459 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
1460 data[hdr+7] -= nFrag;
drh9e572e62004-04-23 23:43:10 +00001461 }
drh7bc4c452014-08-20 18:43:44 +00001462 if( iStart==get2byte(&data[hdr+5]) ){
drh5f5c7532014-08-20 17:56:27 +00001463 /* The new freeblock is at the beginning of the cell content area,
1464 ** so just extend the cell content area rather than create another
1465 ** freelist entry */
drh7bc4c452014-08-20 18:43:44 +00001466 if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
drh5f5c7532014-08-20 17:56:27 +00001467 put2byte(&data[hdr+1], iFreeBlk);
1468 put2byte(&data[hdr+5], iEnd);
1469 }else{
1470 /* Insert the new freeblock into the freelist */
1471 put2byte(&data[iPtr], iStart);
1472 put2byte(&data[iStart], iFreeBlk);
1473 put2byte(&data[iStart+2], iSize);
drh4b70f112004-05-02 21:12:19 +00001474 }
drh5f5c7532014-08-20 17:56:27 +00001475 pPage->nFree += iOrigSize;
shanedcc50b72008-11-13 18:29:50 +00001476 return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00001477}
1478
1479/*
drh271efa52004-05-30 19:19:05 +00001480** Decode the flags byte (the first byte of the header) for a page
1481** and initialize fields of the MemPage structure accordingly.
drh44845222008-07-17 18:39:57 +00001482**
1483** Only the following combinations are supported. Anything different
1484** indicates a corrupt database files:
1485**
1486** PTF_ZERODATA
1487** PTF_ZERODATA | PTF_LEAF
1488** PTF_LEAFDATA | PTF_INTKEY
1489** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
drh271efa52004-05-30 19:19:05 +00001490*/
drh44845222008-07-17 18:39:57 +00001491static int decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +00001492 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +00001493
1494 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +00001495 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00001496 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
drh44845222008-07-17 18:39:57 +00001497 flagByte &= ~PTF_LEAF;
1498 pPage->childPtrSize = 4-4*pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001499 pBt = pPage->pBt;
drh44845222008-07-17 18:39:57 +00001500 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
drhfdab0262014-11-20 15:30:50 +00001501 /* EVIDENCE-OF: R-03640-13415 A value of 5 means the page is an interior
1502 ** table b-tree page. */
1503 assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
1504 /* EVIDENCE-OF: R-20501-61796 A value of 13 means the page is a leaf
1505 ** table b-tree page. */
1506 assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
drh44845222008-07-17 18:39:57 +00001507 pPage->intKey = 1;
drh3e28ff52014-09-24 00:59:08 +00001508 pPage->intKeyLeaf = pPage->leaf;
1509 pPage->noPayload = !pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001510 pPage->maxLocal = pBt->maxLeaf;
1511 pPage->minLocal = pBt->minLeaf;
drh44845222008-07-17 18:39:57 +00001512 }else if( flagByte==PTF_ZERODATA ){
drhfdab0262014-11-20 15:30:50 +00001513 /* EVIDENCE-OF: R-27225-53936 A value of 2 means the page is an interior
1514 ** index b-tree page. */
1515 assert( (PTF_ZERODATA)==2 );
1516 /* EVIDENCE-OF: R-16571-11615 A value of 10 means the page is a leaf
1517 ** index b-tree page. */
1518 assert( (PTF_ZERODATA|PTF_LEAF)==10 );
drh44845222008-07-17 18:39:57 +00001519 pPage->intKey = 0;
drh3e28ff52014-09-24 00:59:08 +00001520 pPage->intKeyLeaf = 0;
1521 pPage->noPayload = 0;
drh271efa52004-05-30 19:19:05 +00001522 pPage->maxLocal = pBt->maxLocal;
1523 pPage->minLocal = pBt->minLocal;
drh44845222008-07-17 18:39:57 +00001524 }else{
drhfdab0262014-11-20 15:30:50 +00001525 /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
1526 ** an error. */
drh44845222008-07-17 18:39:57 +00001527 return SQLITE_CORRUPT_BKPT;
drh271efa52004-05-30 19:19:05 +00001528 }
drhc9166342012-01-05 23:32:06 +00001529 pPage->max1bytePayload = pBt->max1bytePayload;
drh44845222008-07-17 18:39:57 +00001530 return SQLITE_OK;
drh271efa52004-05-30 19:19:05 +00001531}
1532
1533/*
drh7e3b0a02001-04-28 16:52:40 +00001534** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +00001535**
1536** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +00001537** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +00001538** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1539** guarantee that the page is well-formed. It only shows that
1540** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001541*/
danielk197730548662009-07-09 05:07:37 +00001542static int btreeInitPage(MemPage *pPage){
drh2af926b2001-05-15 00:39:25 +00001543
danielk197771d5d2c2008-09-29 11:49:47 +00001544 assert( pPage->pBt!=0 );
1545 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001546 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +00001547 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1548 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00001549
1550 if( !pPage->isInit ){
drhf49661a2008-12-10 16:45:50 +00001551 u16 pc; /* Address of a freeblock within pPage->aData[] */
1552 u8 hdr; /* Offset to beginning of page header */
danielk197771d5d2c2008-09-29 11:49:47 +00001553 u8 *data; /* Equal to pPage->aData */
1554 BtShared *pBt; /* The main btree structure */
drhb2eced52010-08-12 02:41:12 +00001555 int usableSize; /* Amount of usable space on each page */
shaneh1df2db72010-08-18 02:28:48 +00001556 u16 cellOffset; /* Offset from start of page to first cell pointer */
drhb2eced52010-08-12 02:41:12 +00001557 int nFree; /* Number of unused bytes on the page */
1558 int top; /* First byte of the cell content area */
drh0a45c272009-07-08 01:49:11 +00001559 int iCellFirst; /* First allowable cell or freeblock offset */
1560 int iCellLast; /* Last possible cell or freeblock offset */
danielk197771d5d2c2008-09-29 11:49:47 +00001561
1562 pBt = pPage->pBt;
1563
danielk1977eaa06f62008-09-18 17:34:44 +00001564 hdr = pPage->hdrOffset;
1565 data = pPage->aData;
drhfdab0262014-11-20 15:30:50 +00001566 /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
1567 ** the b-tree page type. */
danielk1977eaa06f62008-09-18 17:34:44 +00001568 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
drhb2eced52010-08-12 02:41:12 +00001569 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
1570 pPage->maskPage = (u16)(pBt->pageSize - 1);
danielk1977eaa06f62008-09-18 17:34:44 +00001571 pPage->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00001572 usableSize = pBt->usableSize;
drhfdab0262014-11-20 15:30:50 +00001573 pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
drh3def2352011-11-11 00:27:15 +00001574 pPage->aDataEnd = &data[usableSize];
1575 pPage->aCellIdx = &data[cellOffset];
drhfdab0262014-11-20 15:30:50 +00001576 /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
1577 ** the start of the cell content area. A zero value for this integer is
1578 ** interpreted as 65536. */
drh5d433ce2010-08-14 16:02:52 +00001579 top = get2byteNotZero(&data[hdr+5]);
drhfdab0262014-11-20 15:30:50 +00001580 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
1581 ** number of cells on the page. */
danielk1977eaa06f62008-09-18 17:34:44 +00001582 pPage->nCell = get2byte(&data[hdr+3]);
1583 if( pPage->nCell>MX_CELL(pBt) ){
1584 /* To many cells for a single page. The page must be corrupt */
1585 return SQLITE_CORRUPT_BKPT;
1586 }
drhb908d762009-07-08 16:54:40 +00001587 testcase( pPage->nCell==MX_CELL(pBt) );
drhfdab0262014-11-20 15:30:50 +00001588 /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
1589 ** possible for a root page of a table that contains no rows) then the
1590 ** offset to the cell content area will equal the page size minus the
1591 ** bytes of reserved space. */
1592 assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
drh69e931e2009-06-03 21:04:35 +00001593
shane5eff7cf2009-08-10 03:57:58 +00001594 /* A malformed database page might cause us to read past the end
drh69e931e2009-06-03 21:04:35 +00001595 ** of page when parsing a cell.
1596 **
1597 ** The following block of code checks early to see if a cell extends
1598 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
1599 ** returned if it does.
1600 */
drh0a45c272009-07-08 01:49:11 +00001601 iCellFirst = cellOffset + 2*pPage->nCell;
1602 iCellLast = usableSize - 4;
drh3b2a3fa2009-06-09 13:42:24 +00001603#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
drh69e931e2009-06-03 21:04:35 +00001604 {
drh69e931e2009-06-03 21:04:35 +00001605 int i; /* Index into the cell pointer array */
1606 int sz; /* Size of a cell */
1607
drh69e931e2009-06-03 21:04:35 +00001608 if( !pPage->leaf ) iCellLast--;
1609 for(i=0; i<pPage->nCell; i++){
1610 pc = get2byte(&data[cellOffset+i*2]);
drh0a45c272009-07-08 01:49:11 +00001611 testcase( pc==iCellFirst );
1612 testcase( pc==iCellLast );
drh69e931e2009-06-03 21:04:35 +00001613 if( pc<iCellFirst || pc>iCellLast ){
1614 return SQLITE_CORRUPT_BKPT;
1615 }
1616 sz = cellSizePtr(pPage, &data[pc]);
drh0a45c272009-07-08 01:49:11 +00001617 testcase( pc+sz==usableSize );
drh69e931e2009-06-03 21:04:35 +00001618 if( pc+sz>usableSize ){
1619 return SQLITE_CORRUPT_BKPT;
1620 }
1621 }
drh0a45c272009-07-08 01:49:11 +00001622 if( !pPage->leaf ) iCellLast++;
drh69e931e2009-06-03 21:04:35 +00001623 }
1624#endif
1625
drhfdab0262014-11-20 15:30:50 +00001626 /* Compute the total free space on the page
1627 ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
1628 ** start of the first freeblock on the page, or is zero if there are no
1629 ** freeblocks. */
danielk1977eaa06f62008-09-18 17:34:44 +00001630 pc = get2byte(&data[hdr+1]);
drhfdab0262014-11-20 15:30:50 +00001631 nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
danielk1977eaa06f62008-09-18 17:34:44 +00001632 while( pc>0 ){
drh1bd10f82008-12-10 21:19:56 +00001633 u16 next, size;
drh0a45c272009-07-08 01:49:11 +00001634 if( pc<iCellFirst || pc>iCellLast ){
drhfdab0262014-11-20 15:30:50 +00001635 /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
1636 ** always be at least one cell before the first freeblock.
1637 **
1638 ** Or, the freeblock is off the end of the page
1639 */
danielk1977eaa06f62008-09-18 17:34:44 +00001640 return SQLITE_CORRUPT_BKPT;
1641 }
1642 next = get2byte(&data[pc]);
1643 size = get2byte(&data[pc+2]);
dan4361e792009-08-14 17:01:22 +00001644 if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
1645 /* Free blocks must be in ascending order. And the last byte of
drhf2f105d2012-08-20 15:53:54 +00001646 ** the free-block must lie on the database page. */
danielk1977eaa06f62008-09-18 17:34:44 +00001647 return SQLITE_CORRUPT_BKPT;
1648 }
shane85095702009-06-15 16:27:08 +00001649 nFree = nFree + size;
danielk1977eaa06f62008-09-18 17:34:44 +00001650 pc = next;
1651 }
danielk197793c829c2009-06-03 17:26:17 +00001652
1653 /* At this point, nFree contains the sum of the offset to the start
1654 ** of the cell-content area plus the number of free bytes within
1655 ** the cell-content area. If this is greater than the usable-size
1656 ** of the page, then the page must be corrupted. This check also
1657 ** serves to verify that the offset to the start of the cell-content
1658 ** area, according to the page header, lies within the page.
1659 */
1660 if( nFree>usableSize ){
drh49285702005-09-17 15:20:26 +00001661 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001662 }
shane5eff7cf2009-08-10 03:57:58 +00001663 pPage->nFree = (u16)(nFree - iCellFirst);
danielk197771d5d2c2008-09-29 11:49:47 +00001664 pPage->isInit = 1;
1665 }
drh9e572e62004-04-23 23:43:10 +00001666 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001667}
1668
1669/*
drh8b2f49b2001-06-08 00:21:52 +00001670** Set up a raw page so that it looks like a database page holding
1671** no entries.
drhbd03cae2001-06-02 02:40:57 +00001672*/
drh9e572e62004-04-23 23:43:10 +00001673static void zeroPage(MemPage *pPage, int flags){
1674 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001675 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00001676 u8 hdr = pPage->hdrOffset;
1677 u16 first;
drh9e572e62004-04-23 23:43:10 +00001678
danielk19773b8a05f2007-03-19 17:44:26 +00001679 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drhbf4bca52007-09-06 22:19:14 +00001680 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1681 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +00001682 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00001683 assert( sqlite3_mutex_held(pBt->mutex) );
drhc9166342012-01-05 23:32:06 +00001684 if( pBt->btsFlags & BTS_SECURE_DELETE ){
drh5b47efa2010-02-12 18:18:39 +00001685 memset(&data[hdr], 0, pBt->usableSize - hdr);
1686 }
drh1bd10f82008-12-10 21:19:56 +00001687 data[hdr] = (char)flags;
drhfe485992014-02-12 23:52:16 +00001688 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
drh43605152004-05-29 21:46:49 +00001689 memset(&data[hdr+1], 0, 4);
1690 data[hdr+7] = 0;
1691 put2byte(&data[hdr+5], pBt->usableSize);
shaneh1df2db72010-08-18 02:28:48 +00001692 pPage->nFree = (u16)(pBt->usableSize - first);
drh271efa52004-05-30 19:19:05 +00001693 decodeFlags(pPage, flags);
drh43605152004-05-29 21:46:49 +00001694 pPage->cellOffset = first;
drh3def2352011-11-11 00:27:15 +00001695 pPage->aDataEnd = &data[pBt->usableSize];
1696 pPage->aCellIdx = &data[first];
drh43605152004-05-29 21:46:49 +00001697 pPage->nOverflow = 0;
drhb2eced52010-08-12 02:41:12 +00001698 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
1699 pPage->maskPage = (u16)(pBt->pageSize - 1);
drh43605152004-05-29 21:46:49 +00001700 pPage->nCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001701 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00001702}
1703
drh897a8202008-09-18 01:08:15 +00001704
1705/*
1706** Convert a DbPage obtained from the pager into a MemPage used by
1707** the btree layer.
1708*/
1709static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
1710 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
1711 pPage->aData = sqlite3PagerGetData(pDbPage);
1712 pPage->pDbPage = pDbPage;
1713 pPage->pBt = pBt;
1714 pPage->pgno = pgno;
1715 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
1716 return pPage;
1717}
1718
drhbd03cae2001-06-02 02:40:57 +00001719/*
drh3aac2dd2004-04-26 14:10:20 +00001720** Get a page from the pager. Initialize the MemPage.pBt and
1721** MemPage.aData elements if needed.
drh538f5702007-04-13 02:14:30 +00001722**
1723** If the noContent flag is set, it means that we do not care about
1724** the content of the page at this time. So do not go to the disk
1725** to fetch the content. Just fill in the content with zeros for now.
1726** If in the future we call sqlite3PagerWrite() on this page, that
1727** means we have started to be concerned about content and the disk
1728** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00001729*/
danielk197730548662009-07-09 05:07:37 +00001730static int btreeGetPage(
drh16a9b832007-05-05 18:39:25 +00001731 BtShared *pBt, /* The btree */
1732 Pgno pgno, /* Number of the page to fetch */
1733 MemPage **ppPage, /* Return the page in this parameter */
drhb00fc3b2013-08-21 23:42:32 +00001734 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
drh16a9b832007-05-05 18:39:25 +00001735){
drh3aac2dd2004-04-26 14:10:20 +00001736 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001737 DbPage *pDbPage;
1738
drhb00fc3b2013-08-21 23:42:32 +00001739 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
drh1fee73e2007-08-29 04:00:57 +00001740 assert( sqlite3_mutex_held(pBt->mutex) );
dan11dcd112013-03-15 18:29:18 +00001741 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
drh3aac2dd2004-04-26 14:10:20 +00001742 if( rc ) return rc;
drh897a8202008-09-18 01:08:15 +00001743 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
drh3aac2dd2004-04-26 14:10:20 +00001744 return SQLITE_OK;
1745}
1746
1747/*
danielk1977bea2a942009-01-20 17:06:27 +00001748** Retrieve a page from the pager cache. If the requested page is not
1749** already in the pager cache return NULL. Initialize the MemPage.pBt and
1750** MemPage.aData elements if needed.
1751*/
1752static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
1753 DbPage *pDbPage;
1754 assert( sqlite3_mutex_held(pBt->mutex) );
1755 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
1756 if( pDbPage ){
1757 return btreePageFromDbPage(pDbPage, pgno, pBt);
1758 }
1759 return 0;
1760}
1761
1762/*
danielk197789d40042008-11-17 14:20:56 +00001763** Return the size of the database file in pages. If there is any kind of
1764** error, return ((unsigned int)-1).
danielk197767fd7a92008-09-10 17:53:35 +00001765*/
drhb1299152010-03-30 22:58:33 +00001766static Pgno btreePagecount(BtShared *pBt){
1767 return pBt->nPage;
1768}
1769u32 sqlite3BtreeLastPage(Btree *p){
1770 assert( sqlite3BtreeHoldsMutex(p) );
1771 assert( ((p->pBt->nPage)&0x8000000)==0 );
drheac5bd72014-07-25 21:35:39 +00001772 return btreePagecount(p->pBt);
danielk197767fd7a92008-09-10 17:53:35 +00001773}
1774
1775/*
danielk197789bc4bc2009-07-21 19:25:24 +00001776** Get a page from the pager and initialize it. This routine is just a
1777** convenience wrapper around separate calls to btreeGetPage() and
1778** btreeInitPage().
1779**
1780** If an error occurs, then the value *ppPage is set to is undefined. It
1781** may remain unchanged, or it may be set to an invalid value.
drhde647132004-05-07 17:57:49 +00001782*/
1783static int getAndInitPage(
dan11dcd112013-03-15 18:29:18 +00001784 BtShared *pBt, /* The database file */
1785 Pgno pgno, /* Number of the page to get */
1786 MemPage **ppPage, /* Write the page pointer here */
drhb00fc3b2013-08-21 23:42:32 +00001787 int bReadonly /* PAGER_GET_READONLY or 0 */
drhde647132004-05-07 17:57:49 +00001788){
1789 int rc;
drh1fee73e2007-08-29 04:00:57 +00001790 assert( sqlite3_mutex_held(pBt->mutex) );
drhb00fc3b2013-08-21 23:42:32 +00001791 assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
danielk197789bc4bc2009-07-21 19:25:24 +00001792
danba3cbf32010-06-30 04:29:03 +00001793 if( pgno>btreePagecount(pBt) ){
1794 rc = SQLITE_CORRUPT_BKPT;
1795 }else{
drhb00fc3b2013-08-21 23:42:32 +00001796 rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
drh29f2bad2013-12-09 01:04:54 +00001797 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
danba3cbf32010-06-30 04:29:03 +00001798 rc = btreeInitPage(*ppPage);
1799 if( rc!=SQLITE_OK ){
1800 releasePage(*ppPage);
1801 }
danielk197789bc4bc2009-07-21 19:25:24 +00001802 }
drhee696e22004-08-30 16:52:17 +00001803 }
danba3cbf32010-06-30 04:29:03 +00001804
1805 testcase( pgno==0 );
1806 assert( pgno!=0 || rc==SQLITE_CORRUPT );
drhde647132004-05-07 17:57:49 +00001807 return rc;
1808}
1809
1810/*
drh3aac2dd2004-04-26 14:10:20 +00001811** Release a MemPage. This should be called once for each prior
danielk197730548662009-07-09 05:07:37 +00001812** call to btreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +00001813*/
drh4b70f112004-05-02 21:12:19 +00001814static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001815 if( pPage ){
1816 assert( pPage->aData );
1817 assert( pPage->pBt );
drhda8a3302013-12-13 19:35:21 +00001818 assert( pPage->pDbPage!=0 );
drhbf4bca52007-09-06 22:19:14 +00001819 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1820 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
drh1fee73e2007-08-29 04:00:57 +00001821 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda8a3302013-12-13 19:35:21 +00001822 sqlite3PagerUnrefNotNull(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00001823 }
1824}
1825
1826/*
drha6abd042004-06-09 17:37:22 +00001827** During a rollback, when the pager reloads information into the cache
1828** so that the cache is restored to its original state at the start of
1829** the transaction, for each page restored this routine is called.
1830**
1831** This routine needs to reset the extra data section at the end of the
1832** page to agree with the restored data.
1833*/
danielk1977eaa06f62008-09-18 17:34:44 +00001834static void pageReinit(DbPage *pData){
drh07d183d2005-05-01 22:52:42 +00001835 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00001836 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
danielk1977d217e6f2009-04-01 17:13:51 +00001837 assert( sqlite3PagerPageRefcount(pData)>0 );
danielk197771d5d2c2008-09-29 11:49:47 +00001838 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00001839 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00001840 pPage->isInit = 0;
danielk1977d217e6f2009-04-01 17:13:51 +00001841 if( sqlite3PagerPageRefcount(pData)>1 ){
drh5e8d8872009-03-30 17:19:48 +00001842 /* pPage might not be a btree page; it might be an overflow page
1843 ** or ptrmap page or a free page. In those cases, the following
danielk197730548662009-07-09 05:07:37 +00001844 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
drh5e8d8872009-03-30 17:19:48 +00001845 ** But no harm is done by this. And it is very important that
danielk197730548662009-07-09 05:07:37 +00001846 ** btreeInitPage() be called on every btree page so we make
drh5e8d8872009-03-30 17:19:48 +00001847 ** the call for every page that comes in for re-initing. */
danielk197730548662009-07-09 05:07:37 +00001848 btreeInitPage(pPage);
danielk197771d5d2c2008-09-29 11:49:47 +00001849 }
drha6abd042004-06-09 17:37:22 +00001850 }
1851}
1852
1853/*
drhe5fe6902007-12-07 18:55:28 +00001854** Invoke the busy handler for a btree.
1855*/
danielk19771ceedd32008-11-19 10:22:33 +00001856static int btreeInvokeBusyHandler(void *pArg){
drhe5fe6902007-12-07 18:55:28 +00001857 BtShared *pBt = (BtShared*)pArg;
1858 assert( pBt->db );
1859 assert( sqlite3_mutex_held(pBt->db->mutex) );
1860 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
1861}
1862
1863/*
drhad3e0102004-09-03 23:32:18 +00001864** Open a database file.
1865**
drh382c0242001-10-06 16:33:02 +00001866** zFilename is the name of the database file. If zFilename is NULL
drh75c014c2010-08-30 15:02:28 +00001867** then an ephemeral database is created. The ephemeral database might
1868** be exclusively in memory, or it might use a disk-based memory cache.
1869** Either way, the ephemeral database will be automatically deleted
1870** when sqlite3BtreeClose() is called.
1871**
drhe53831d2007-08-17 01:14:38 +00001872** If zFilename is ":memory:" then an in-memory database is created
1873** that is automatically destroyed when it is closed.
drhc47fd8e2009-04-30 13:30:32 +00001874**
drh33f111d2012-01-17 15:29:14 +00001875** The "flags" parameter is a bitmask that might contain bits like
1876** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
drh75c014c2010-08-30 15:02:28 +00001877**
drhc47fd8e2009-04-30 13:30:32 +00001878** If the database is already opened in the same database connection
1879** and we are in shared cache mode, then the open will fail with an
1880** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
1881** objects in the same database connection since doing so will lead
1882** to problems with locking.
drha059ad02001-04-17 20:09:11 +00001883*/
drh23e11ca2004-05-04 17:27:28 +00001884int sqlite3BtreeOpen(
dan3a6d8ae2011-04-23 15:54:54 +00001885 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
drh3aac2dd2004-04-26 14:10:20 +00001886 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00001887 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001888 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00001889 int flags, /* Options */
1890 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00001891){
drh7555d8e2009-03-20 13:15:30 +00001892 BtShared *pBt = 0; /* Shared part of btree structure */
1893 Btree *p; /* Handle to return */
1894 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
1895 int rc = SQLITE_OK; /* Result code from this function */
1896 u8 nReserve; /* Byte of unused space on each page */
1897 unsigned char zDbHeader[100]; /* Database header content */
danielk1977aef0bf62005-12-30 16:28:01 +00001898
drh75c014c2010-08-30 15:02:28 +00001899 /* True if opening an ephemeral, temporary database */
1900 const int isTempDb = zFilename==0 || zFilename[0]==0;
1901
danielk1977aef0bf62005-12-30 16:28:01 +00001902 /* Set the variable isMemdb to true for an in-memory database, or
drhb0a7c9c2010-12-06 21:09:59 +00001903 ** false for a file-based database.
danielk1977aef0bf62005-12-30 16:28:01 +00001904 */
drhb0a7c9c2010-12-06 21:09:59 +00001905#ifdef SQLITE_OMIT_MEMORYDB
1906 const int isMemdb = 0;
1907#else
1908 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
drh9c67b2a2012-05-28 13:58:00 +00001909 || (isTempDb && sqlite3TempInMemory(db))
1910 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
danielk1977aef0bf62005-12-30 16:28:01 +00001911#endif
1912
drhe5fe6902007-12-07 18:55:28 +00001913 assert( db!=0 );
dan3a6d8ae2011-04-23 15:54:54 +00001914 assert( pVfs!=0 );
drhe5fe6902007-12-07 18:55:28 +00001915 assert( sqlite3_mutex_held(db->mutex) );
drhd4187c72010-08-30 22:15:45 +00001916 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
1917
1918 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
1919 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
1920
1921 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
1922 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
drh153c62c2007-08-24 03:51:33 +00001923
drh75c014c2010-08-30 15:02:28 +00001924 if( isMemdb ){
1925 flags |= BTREE_MEMORY;
1926 }
1927 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
1928 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
1929 }
drh17435752007-08-16 04:30:38 +00001930 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00001931 if( !p ){
1932 return SQLITE_NOMEM;
1933 }
1934 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00001935 p->db = db;
danielk1977602b4662009-07-02 07:47:33 +00001936#ifndef SQLITE_OMIT_SHARED_CACHE
1937 p->lock.pBtree = p;
1938 p->lock.iTable = 1;
1939#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001940
drh198bf392006-01-06 21:52:49 +00001941#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001942 /*
1943 ** If this Btree is a candidate for shared cache, try to find an
1944 ** existing BtShared object that we can share with
1945 */
drh4ab9d252012-05-26 20:08:49 +00001946 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
drhf1f12682009-09-09 14:17:52 +00001947 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
danielk1977adfb9b02007-09-17 07:02:56 +00001948 int nFullPathname = pVfs->mxPathname+1;
drhe5ae5732008-06-15 02:51:47 +00001949 char *zFullPathname = sqlite3Malloc(nFullPathname);
drh30ddce62011-10-15 00:16:30 +00001950 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
drhff0587c2007-08-29 17:43:19 +00001951 p->sharable = 1;
drhff0587c2007-08-29 17:43:19 +00001952 if( !zFullPathname ){
1953 sqlite3_free(p);
1954 return SQLITE_NOMEM;
1955 }
drhafc8b7f2012-05-26 18:06:38 +00001956 if( isMemdb ){
1957 memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
1958 }else{
1959 rc = sqlite3OsFullPathname(pVfs, zFilename,
1960 nFullPathname, zFullPathname);
1961 if( rc ){
1962 sqlite3_free(zFullPathname);
1963 sqlite3_free(p);
1964 return rc;
1965 }
drh070ad6b2011-11-17 11:43:19 +00001966 }
drh30ddce62011-10-15 00:16:30 +00001967#if SQLITE_THREADSAFE
drh7555d8e2009-03-20 13:15:30 +00001968 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
1969 sqlite3_mutex_enter(mutexOpen);
danielk197759f8c082008-06-18 17:09:10 +00001970 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhff0587c2007-08-29 17:43:19 +00001971 sqlite3_mutex_enter(mutexShared);
drh30ddce62011-10-15 00:16:30 +00001972#endif
drh78f82d12008-09-02 00:52:52 +00001973 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
drhff0587c2007-08-29 17:43:19 +00001974 assert( pBt->nRef>0 );
drhd4e0bb02012-05-27 01:19:04 +00001975 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
drhff0587c2007-08-29 17:43:19 +00001976 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
drhc47fd8e2009-04-30 13:30:32 +00001977 int iDb;
1978 for(iDb=db->nDb-1; iDb>=0; iDb--){
1979 Btree *pExisting = db->aDb[iDb].pBt;
1980 if( pExisting && pExisting->pBt==pBt ){
1981 sqlite3_mutex_leave(mutexShared);
1982 sqlite3_mutex_leave(mutexOpen);
1983 sqlite3_free(zFullPathname);
1984 sqlite3_free(p);
1985 return SQLITE_CONSTRAINT;
1986 }
1987 }
drhff0587c2007-08-29 17:43:19 +00001988 p->pBt = pBt;
1989 pBt->nRef++;
1990 break;
1991 }
1992 }
1993 sqlite3_mutex_leave(mutexShared);
1994 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00001995 }
drhff0587c2007-08-29 17:43:19 +00001996#ifdef SQLITE_DEBUG
1997 else{
1998 /* In debug mode, we mark all persistent databases as sharable
1999 ** even when they are not. This exercises the locking code and
2000 ** gives more opportunity for asserts(sqlite3_mutex_held())
2001 ** statements to find locking problems.
2002 */
2003 p->sharable = 1;
2004 }
2005#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002006 }
2007#endif
drha059ad02001-04-17 20:09:11 +00002008 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00002009 /*
2010 ** The following asserts make sure that structures used by the btree are
2011 ** the right size. This is to guard against size changes that result
2012 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00002013 */
drhe53831d2007-08-17 01:14:38 +00002014 assert( sizeof(i64)==8 || sizeof(i64)==4 );
2015 assert( sizeof(u64)==8 || sizeof(u64)==4 );
2016 assert( sizeof(u32)==4 );
2017 assert( sizeof(u16)==2 );
2018 assert( sizeof(Pgno)==4 );
2019
2020 pBt = sqlite3MallocZero( sizeof(*pBt) );
2021 if( pBt==0 ){
2022 rc = SQLITE_NOMEM;
2023 goto btree_open_out;
2024 }
danielk197771d5d2c2008-09-29 11:49:47 +00002025 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
drh4775ecd2009-07-24 19:01:19 +00002026 EXTRA_SIZE, flags, vfsFlags, pageReinit);
drhe53831d2007-08-17 01:14:38 +00002027 if( rc==SQLITE_OK ){
drh9b4c59f2013-04-15 17:03:42 +00002028 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
drhe53831d2007-08-17 01:14:38 +00002029 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
2030 }
2031 if( rc!=SQLITE_OK ){
2032 goto btree_open_out;
2033 }
shanehbd2aaf92010-09-01 02:38:21 +00002034 pBt->openFlags = (u8)flags;
danielk19772a50ff02009-04-10 09:47:06 +00002035 pBt->db = db;
danielk19771ceedd32008-11-19 10:22:33 +00002036 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
drhe53831d2007-08-17 01:14:38 +00002037 p->pBt = pBt;
2038
drhe53831d2007-08-17 01:14:38 +00002039 pBt->pCursor = 0;
2040 pBt->pPage1 = 0;
drhc9166342012-01-05 23:32:06 +00002041 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
drh5b47efa2010-02-12 18:18:39 +00002042#ifdef SQLITE_SECURE_DELETE
drhc9166342012-01-05 23:32:06 +00002043 pBt->btsFlags |= BTS_SECURE_DELETE;
drh5b47efa2010-02-12 18:18:39 +00002044#endif
drh113762a2014-11-19 16:36:25 +00002045 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2046 ** determined by the 2-byte integer located at an offset of 16 bytes from
2047 ** the beginning of the database file. */
drhb2eced52010-08-12 02:41:12 +00002048 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
drhe53831d2007-08-17 01:14:38 +00002049 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
2050 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002051 pBt->pageSize = 0;
drhe53831d2007-08-17 01:14:38 +00002052#ifndef SQLITE_OMIT_AUTOVACUUM
2053 /* If the magic name ":memory:" will create an in-memory database, then
2054 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
2055 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
2056 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
2057 ** regular file-name. In this case the auto-vacuum applies as per normal.
2058 */
2059 if( zFilename && !isMemdb ){
2060 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
2061 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
2062 }
2063#endif
2064 nReserve = 0;
2065 }else{
drh113762a2014-11-19 16:36:25 +00002066 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2067 ** determined by the one-byte unsigned integer found at an offset of 20
2068 ** into the database file header. */
drhe53831d2007-08-17 01:14:38 +00002069 nReserve = zDbHeader[20];
drhc9166342012-01-05 23:32:06 +00002070 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
drhe53831d2007-08-17 01:14:38 +00002071#ifndef SQLITE_OMIT_AUTOVACUUM
2072 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
2073 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
2074#endif
2075 }
drhfa9601a2009-06-18 17:22:39 +00002076 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhc0b61812009-04-30 01:22:41 +00002077 if( rc ) goto btree_open_out;
drhe53831d2007-08-17 01:14:38 +00002078 pBt->usableSize = pBt->pageSize - nReserve;
2079 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
drhe53831d2007-08-17 01:14:38 +00002080
2081#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2082 /* Add the new BtShared object to the linked list sharable BtShareds.
2083 */
2084 if( p->sharable ){
drh30ddce62011-10-15 00:16:30 +00002085 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
drhe53831d2007-08-17 01:14:38 +00002086 pBt->nRef = 1;
drh30ddce62011-10-15 00:16:30 +00002087 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
danielk1977075c23a2008-09-01 18:34:20 +00002088 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
danielk197759f8c082008-06-18 17:09:10 +00002089 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
drh3285db22007-09-03 22:00:39 +00002090 if( pBt->mutex==0 ){
2091 rc = SQLITE_NOMEM;
drhe5fe6902007-12-07 18:55:28 +00002092 db->mallocFailed = 0;
drh3285db22007-09-03 22:00:39 +00002093 goto btree_open_out;
2094 }
drhff0587c2007-08-29 17:43:19 +00002095 }
drhe53831d2007-08-17 01:14:38 +00002096 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00002097 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2098 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
drhe53831d2007-08-17 01:14:38 +00002099 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00002100 }
drheee46cf2004-11-06 00:02:48 +00002101#endif
drh90f5ecb2004-07-22 01:19:35 +00002102 }
danielk1977aef0bf62005-12-30 16:28:01 +00002103
drhcfed7bc2006-03-13 14:28:05 +00002104#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00002105 /* If the new Btree uses a sharable pBtShared, then link the new
2106 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00002107 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00002108 */
drhe53831d2007-08-17 01:14:38 +00002109 if( p->sharable ){
2110 int i;
2111 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00002112 for(i=0; i<db->nDb; i++){
2113 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00002114 while( pSib->pPrev ){ pSib = pSib->pPrev; }
2115 if( p->pBt<pSib->pBt ){
2116 p->pNext = pSib;
2117 p->pPrev = 0;
2118 pSib->pPrev = p;
2119 }else{
drhabddb0c2007-08-20 13:14:28 +00002120 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
drhe53831d2007-08-17 01:14:38 +00002121 pSib = pSib->pNext;
2122 }
2123 p->pNext = pSib->pNext;
2124 p->pPrev = pSib;
2125 if( p->pNext ){
2126 p->pNext->pPrev = p;
2127 }
2128 pSib->pNext = p;
2129 }
2130 break;
2131 }
2132 }
danielk1977aef0bf62005-12-30 16:28:01 +00002133 }
danielk1977aef0bf62005-12-30 16:28:01 +00002134#endif
2135 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00002136
2137btree_open_out:
2138 if( rc!=SQLITE_OK ){
2139 if( pBt && pBt->pPager ){
2140 sqlite3PagerClose(pBt->pPager);
2141 }
drh17435752007-08-16 04:30:38 +00002142 sqlite3_free(pBt);
2143 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00002144 *ppBtree = 0;
drh75c014c2010-08-30 15:02:28 +00002145 }else{
2146 /* If the B-Tree was successfully opened, set the pager-cache size to the
2147 ** default value. Except, when opening on an existing shared pager-cache,
2148 ** do not change the pager-cache size.
2149 */
2150 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
2151 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
2152 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002153 }
drh7555d8e2009-03-20 13:15:30 +00002154 if( mutexOpen ){
2155 assert( sqlite3_mutex_held(mutexOpen) );
2156 sqlite3_mutex_leave(mutexOpen);
2157 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002158 return rc;
drha059ad02001-04-17 20:09:11 +00002159}
2160
2161/*
drhe53831d2007-08-17 01:14:38 +00002162** Decrement the BtShared.nRef counter. When it reaches zero,
2163** remove the BtShared structure from the sharing list. Return
2164** true if the BtShared.nRef counter reaches zero and return
2165** false if it is still positive.
2166*/
2167static int removeFromSharingList(BtShared *pBt){
2168#ifndef SQLITE_OMIT_SHARED_CACHE
drh30ddce62011-10-15 00:16:30 +00002169 MUTEX_LOGIC( sqlite3_mutex *pMaster; )
drhe53831d2007-08-17 01:14:38 +00002170 BtShared *pList;
2171 int removed = 0;
2172
drhd677b3d2007-08-20 22:48:41 +00002173 assert( sqlite3_mutex_notheld(pBt->mutex) );
drh30ddce62011-10-15 00:16:30 +00002174 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
drhe53831d2007-08-17 01:14:38 +00002175 sqlite3_mutex_enter(pMaster);
2176 pBt->nRef--;
2177 if( pBt->nRef<=0 ){
drh78f82d12008-09-02 00:52:52 +00002178 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2179 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
drhe53831d2007-08-17 01:14:38 +00002180 }else{
drh78f82d12008-09-02 00:52:52 +00002181 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
drh34004ce2008-07-11 16:15:17 +00002182 while( ALWAYS(pList) && pList->pNext!=pBt ){
drhe53831d2007-08-17 01:14:38 +00002183 pList=pList->pNext;
2184 }
drh34004ce2008-07-11 16:15:17 +00002185 if( ALWAYS(pList) ){
drhe53831d2007-08-17 01:14:38 +00002186 pList->pNext = pBt->pNext;
2187 }
2188 }
drh3285db22007-09-03 22:00:39 +00002189 if( SQLITE_THREADSAFE ){
2190 sqlite3_mutex_free(pBt->mutex);
2191 }
drhe53831d2007-08-17 01:14:38 +00002192 removed = 1;
2193 }
2194 sqlite3_mutex_leave(pMaster);
2195 return removed;
2196#else
2197 return 1;
2198#endif
2199}
2200
2201/*
drhf7141992008-06-19 00:16:08 +00002202** Make sure pBt->pTmpSpace points to an allocation of
drh92787cf2014-10-15 11:55:51 +00002203** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
2204** pointer.
drhf7141992008-06-19 00:16:08 +00002205*/
2206static void allocateTempSpace(BtShared *pBt){
2207 if( !pBt->pTmpSpace ){
2208 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
dan14285b72013-10-16 11:39:07 +00002209
2210 /* One of the uses of pBt->pTmpSpace is to format cells before
2211 ** inserting them into a leaf page (function fillInCell()). If
2212 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
2213 ** by the various routines that manipulate binary cells. Which
2214 ** can mean that fillInCell() only initializes the first 2 or 3
2215 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
2216 ** it into a database page. This is not actually a problem, but it
2217 ** does cause a valgrind error when the 1 or 2 bytes of unitialized
2218 ** data is passed to system call write(). So to avoid this error,
drh92787cf2014-10-15 11:55:51 +00002219 ** zero the first 4 bytes of temp space here.
2220 **
2221 ** Also: Provide four bytes of initialized space before the
2222 ** beginning of pTmpSpace as an area available to prepend the
2223 ** left-child pointer to the beginning of a cell.
2224 */
2225 if( pBt->pTmpSpace ){
2226 memset(pBt->pTmpSpace, 0, 8);
2227 pBt->pTmpSpace += 4;
2228 }
drhf7141992008-06-19 00:16:08 +00002229 }
2230}
2231
2232/*
2233** Free the pBt->pTmpSpace allocation
2234*/
2235static void freeTempSpace(BtShared *pBt){
drh92787cf2014-10-15 11:55:51 +00002236 if( pBt->pTmpSpace ){
2237 pBt->pTmpSpace -= 4;
2238 sqlite3PageFree(pBt->pTmpSpace);
2239 pBt->pTmpSpace = 0;
2240 }
drhf7141992008-06-19 00:16:08 +00002241}
2242
2243/*
drha059ad02001-04-17 20:09:11 +00002244** Close an open database and invalidate all cursors.
2245*/
danielk1977aef0bf62005-12-30 16:28:01 +00002246int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002247 BtShared *pBt = p->pBt;
2248 BtCursor *pCur;
2249
danielk1977aef0bf62005-12-30 16:28:01 +00002250 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00002251 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00002252 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002253 pCur = pBt->pCursor;
2254 while( pCur ){
2255 BtCursor *pTmp = pCur;
2256 pCur = pCur->pNext;
2257 if( pTmp->pBtree==p ){
2258 sqlite3BtreeCloseCursor(pTmp);
2259 }
drha059ad02001-04-17 20:09:11 +00002260 }
danielk1977aef0bf62005-12-30 16:28:01 +00002261
danielk19778d34dfd2006-01-24 16:37:57 +00002262 /* Rollback any active transaction and free the handle structure.
2263 ** The call to sqlite3BtreeRollback() drops any table-locks held by
2264 ** this handle.
2265 */
drh47b7fc72014-11-11 01:33:57 +00002266 sqlite3BtreeRollback(p, SQLITE_OK, 0);
drhe53831d2007-08-17 01:14:38 +00002267 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002268
danielk1977aef0bf62005-12-30 16:28:01 +00002269 /* If there are still other outstanding references to the shared-btree
2270 ** structure, return now. The remainder of this procedure cleans
2271 ** up the shared-btree.
2272 */
drhe53831d2007-08-17 01:14:38 +00002273 assert( p->wantToLock==0 && p->locked==0 );
2274 if( !p->sharable || removeFromSharingList(pBt) ){
2275 /* The pBt is no longer on the sharing list, so we can access
2276 ** it without having to hold the mutex.
2277 **
2278 ** Clean out and delete the BtShared object.
2279 */
2280 assert( !pBt->pCursor );
drhe53831d2007-08-17 01:14:38 +00002281 sqlite3PagerClose(pBt->pPager);
2282 if( pBt->xFreeSchema && pBt->pSchema ){
2283 pBt->xFreeSchema(pBt->pSchema);
2284 }
drhb9755982010-07-24 16:34:37 +00002285 sqlite3DbFree(0, pBt->pSchema);
drhf7141992008-06-19 00:16:08 +00002286 freeTempSpace(pBt);
drh65bbf292008-06-19 01:03:17 +00002287 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002288 }
2289
drhe53831d2007-08-17 01:14:38 +00002290#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00002291 assert( p->wantToLock==0 );
2292 assert( p->locked==0 );
2293 if( p->pPrev ) p->pPrev->pNext = p->pNext;
2294 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00002295#endif
2296
drhe53831d2007-08-17 01:14:38 +00002297 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00002298 return SQLITE_OK;
2299}
2300
2301/*
drhda47d772002-12-02 04:25:19 +00002302** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00002303**
2304** The maximum number of cache pages is set to the absolute
2305** value of mxPage. If mxPage is negative, the pager will
2306** operate asynchronously - it will not stop to do fsync()s
2307** to insure data is written to the disk surface before
2308** continuing. Transactions still work if synchronous is off,
2309** and the database cannot be corrupted if this program
2310** crashes. But if the operating system crashes or there is
2311** an abrupt power failure when synchronous is off, the database
2312** could be left in an inconsistent and unrecoverable state.
2313** Synchronous is on by default so database corruption is not
2314** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00002315*/
danielk1977aef0bf62005-12-30 16:28:01 +00002316int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2317 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00002318 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002319 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00002320 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00002321 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00002322 return SQLITE_OK;
2323}
2324
drh18c7e402014-03-14 11:46:10 +00002325#if SQLITE_MAX_MMAP_SIZE>0
drhf57b14a2001-09-14 18:54:08 +00002326/*
dan5d8a1372013-03-19 19:28:06 +00002327** Change the limit on the amount of the database file that may be
2328** memory mapped.
2329*/
drh9b4c59f2013-04-15 17:03:42 +00002330int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
dan5d8a1372013-03-19 19:28:06 +00002331 BtShared *pBt = p->pBt;
2332 assert( sqlite3_mutex_held(p->db->mutex) );
2333 sqlite3BtreeEnter(p);
drh9b4c59f2013-04-15 17:03:42 +00002334 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
dan5d8a1372013-03-19 19:28:06 +00002335 sqlite3BtreeLeave(p);
2336 return SQLITE_OK;
2337}
drh18c7e402014-03-14 11:46:10 +00002338#endif /* SQLITE_MAX_MMAP_SIZE>0 */
dan5d8a1372013-03-19 19:28:06 +00002339
2340/*
drh973b6e32003-02-12 14:09:42 +00002341** Change the way data is synced to disk in order to increase or decrease
2342** how well the database resists damage due to OS crashes and power
2343** failures. Level 1 is the same as asynchronous (no syncs() occur and
2344** there is a high probability of damage) Level 2 is the default. There
2345** is a very low but non-zero probability of damage. Level 3 reduces the
2346** probability of damage to near zero but with a write performance reduction.
2347*/
danielk197793758c82005-01-21 08:13:14 +00002348#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drh40c39412013-08-16 20:42:20 +00002349int sqlite3BtreeSetPagerFlags(
drhc97d8462010-11-19 18:23:35 +00002350 Btree *p, /* The btree to set the safety level on */
drh40c39412013-08-16 20:42:20 +00002351 unsigned pgFlags /* Various PAGER_* flags */
drhc97d8462010-11-19 18:23:35 +00002352){
danielk1977aef0bf62005-12-30 16:28:01 +00002353 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00002354 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002355 sqlite3BtreeEnter(p);
drh40c39412013-08-16 20:42:20 +00002356 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
drhd677b3d2007-08-20 22:48:41 +00002357 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00002358 return SQLITE_OK;
2359}
danielk197793758c82005-01-21 08:13:14 +00002360#endif
drh973b6e32003-02-12 14:09:42 +00002361
drh2c8997b2005-08-27 16:36:48 +00002362/*
2363** Return TRUE if the given btree is set to safety level 1. In other
2364** words, return TRUE if no sync() occurs on the disk files.
2365*/
danielk1977aef0bf62005-12-30 16:28:01 +00002366int sqlite3BtreeSyncDisabled(Btree *p){
2367 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002368 int rc;
drhe5fe6902007-12-07 18:55:28 +00002369 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002370 sqlite3BtreeEnter(p);
drhd0679ed2007-08-28 22:24:34 +00002371 assert( pBt && pBt->pPager );
drhd677b3d2007-08-20 22:48:41 +00002372 rc = sqlite3PagerNosync(pBt->pPager);
2373 sqlite3BtreeLeave(p);
2374 return rc;
drh2c8997b2005-08-27 16:36:48 +00002375}
2376
drh973b6e32003-02-12 14:09:42 +00002377/*
drh90f5ecb2004-07-22 01:19:35 +00002378** Change the default pages size and the number of reserved bytes per page.
drhce4869f2009-04-02 20:16:58 +00002379** Or, if the page size has already been fixed, return SQLITE_READONLY
2380** without changing anything.
drh06f50212004-11-02 14:24:33 +00002381**
2382** The page size must be a power of 2 between 512 and 65536. If the page
2383** size supplied does not meet this constraint then the page size is not
2384** changed.
2385**
2386** Page sizes are constrained to be a power of two so that the region
2387** of the database file used for locking (beginning at PENDING_BYTE,
2388** the first byte past the 1GB boundary, 0x40000000) needs to occur
2389** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00002390**
2391** If parameter nReserve is less than zero, then the number of reserved
2392** bytes per page is left unchanged.
drhce4869f2009-04-02 20:16:58 +00002393**
drhc9166342012-01-05 23:32:06 +00002394** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
drhce4869f2009-04-02 20:16:58 +00002395** and autovacuum mode can no longer be changed.
drh90f5ecb2004-07-22 01:19:35 +00002396*/
drhce4869f2009-04-02 20:16:58 +00002397int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
danielk1977a1644fd2007-08-29 12:31:25 +00002398 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002399 BtShared *pBt = p->pBt;
drhf49661a2008-12-10 16:45:50 +00002400 assert( nReserve>=-1 && nReserve<=255 );
drhd677b3d2007-08-20 22:48:41 +00002401 sqlite3BtreeEnter(p);
drhc9166342012-01-05 23:32:06 +00002402 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
drhd677b3d2007-08-20 22:48:41 +00002403 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00002404 return SQLITE_READONLY;
2405 }
2406 if( nReserve<0 ){
2407 nReserve = pBt->pageSize - pBt->usableSize;
2408 }
drhf49661a2008-12-10 16:45:50 +00002409 assert( nReserve>=0 && nReserve<=255 );
drh06f50212004-11-02 14:24:33 +00002410 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2411 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00002412 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002413 assert( !pBt->pPage1 && !pBt->pCursor );
drhb2eced52010-08-12 02:41:12 +00002414 pBt->pageSize = (u32)pageSize;
drhf7141992008-06-19 00:16:08 +00002415 freeTempSpace(pBt);
drh90f5ecb2004-07-22 01:19:35 +00002416 }
drhfa9601a2009-06-18 17:22:39 +00002417 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhf49661a2008-12-10 16:45:50 +00002418 pBt->usableSize = pBt->pageSize - (u16)nReserve;
drhc9166342012-01-05 23:32:06 +00002419 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
drhd677b3d2007-08-20 22:48:41 +00002420 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00002421 return rc;
drh90f5ecb2004-07-22 01:19:35 +00002422}
2423
2424/*
2425** Return the currently defined page size
2426*/
danielk1977aef0bf62005-12-30 16:28:01 +00002427int sqlite3BtreeGetPageSize(Btree *p){
2428 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00002429}
drh7f751222009-03-17 22:33:00 +00002430
drha1f38532012-10-01 12:44:26 +00002431#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
dan0094f372012-09-28 20:23:42 +00002432/*
2433** This function is similar to sqlite3BtreeGetReserve(), except that it
2434** may only be called if it is guaranteed that the b-tree mutex is already
2435** held.
2436**
2437** This is useful in one special case in the backup API code where it is
2438** known that the shared b-tree mutex is held, but the mutex on the
2439** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
2440** were to be called, it might collide with some other operation on the
mistachkin48864df2013-03-21 21:20:32 +00002441** database handle that owns *p, causing undefined behavior.
dan0094f372012-09-28 20:23:42 +00002442*/
2443int sqlite3BtreeGetReserveNoMutex(Btree *p){
2444 assert( sqlite3_mutex_held(p->pBt->mutex) );
2445 return p->pBt->pageSize - p->pBt->usableSize;
2446}
drha1f38532012-10-01 12:44:26 +00002447#endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
dan0094f372012-09-28 20:23:42 +00002448
danbb2b4412011-04-06 17:54:31 +00002449#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh7f751222009-03-17 22:33:00 +00002450/*
2451** Return the number of bytes of space at the end of every page that
2452** are intentually left unused. This is the "reserved" space that is
2453** sometimes used by extensions.
2454*/
danielk1977aef0bf62005-12-30 16:28:01 +00002455int sqlite3BtreeGetReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002456 int n;
2457 sqlite3BtreeEnter(p);
2458 n = p->pBt->pageSize - p->pBt->usableSize;
2459 sqlite3BtreeLeave(p);
2460 return n;
drh2011d5f2004-07-22 02:40:37 +00002461}
drhf8e632b2007-05-08 14:51:36 +00002462
2463/*
2464** Set the maximum page count for a database if mxPage is positive.
2465** No changes are made if mxPage is 0 or negative.
2466** Regardless of the value of mxPage, return the maximum page count.
2467*/
2468int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00002469 int n;
2470 sqlite3BtreeEnter(p);
2471 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
2472 sqlite3BtreeLeave(p);
2473 return n;
drhf8e632b2007-05-08 14:51:36 +00002474}
drh5b47efa2010-02-12 18:18:39 +00002475
2476/*
drhc9166342012-01-05 23:32:06 +00002477** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
2478** then make no changes. Always return the value of the BTS_SECURE_DELETE
drh5b47efa2010-02-12 18:18:39 +00002479** setting after the change.
2480*/
2481int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
2482 int b;
drhaf034ed2010-02-12 19:46:26 +00002483 if( p==0 ) return 0;
drh5b47efa2010-02-12 18:18:39 +00002484 sqlite3BtreeEnter(p);
2485 if( newFlag>=0 ){
drhc9166342012-01-05 23:32:06 +00002486 p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
2487 if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
drh5b47efa2010-02-12 18:18:39 +00002488 }
drhc9166342012-01-05 23:32:06 +00002489 b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
drh5b47efa2010-02-12 18:18:39 +00002490 sqlite3BtreeLeave(p);
2491 return b;
2492}
danielk1977576ec6b2005-01-21 11:55:25 +00002493#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00002494
2495/*
danielk1977951af802004-11-05 15:45:09 +00002496** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
2497** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
2498** is disabled. The default value for the auto-vacuum property is
2499** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
2500*/
danielk1977aef0bf62005-12-30 16:28:01 +00002501int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00002502#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002503 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00002504#else
danielk1977dddbcdc2007-04-26 14:42:34 +00002505 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002506 int rc = SQLITE_OK;
drh076d4662009-02-18 20:31:18 +00002507 u8 av = (u8)autoVacuum;
drhd677b3d2007-08-20 22:48:41 +00002508
2509 sqlite3BtreeEnter(p);
drhc9166342012-01-05 23:32:06 +00002510 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002511 rc = SQLITE_READONLY;
2512 }else{
drh076d4662009-02-18 20:31:18 +00002513 pBt->autoVacuum = av ?1:0;
2514 pBt->incrVacuum = av==2 ?1:0;
danielk1977951af802004-11-05 15:45:09 +00002515 }
drhd677b3d2007-08-20 22:48:41 +00002516 sqlite3BtreeLeave(p);
2517 return rc;
danielk1977951af802004-11-05 15:45:09 +00002518#endif
2519}
2520
2521/*
2522** Return the value of the 'auto-vacuum' property. If auto-vacuum is
2523** enabled 1 is returned. Otherwise 0.
2524*/
danielk1977aef0bf62005-12-30 16:28:01 +00002525int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00002526#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002527 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00002528#else
drhd677b3d2007-08-20 22:48:41 +00002529 int rc;
2530 sqlite3BtreeEnter(p);
2531 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00002532 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
2533 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
2534 BTREE_AUTOVACUUM_INCR
2535 );
drhd677b3d2007-08-20 22:48:41 +00002536 sqlite3BtreeLeave(p);
2537 return rc;
danielk1977951af802004-11-05 15:45:09 +00002538#endif
2539}
2540
2541
2542/*
drha34b6762004-05-07 13:30:42 +00002543** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00002544** also acquire a readlock on that file.
2545**
2546** SQLITE_OK is returned on success. If the file is not a
2547** well-formed database file, then SQLITE_CORRUPT is returned.
2548** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00002549** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00002550*/
danielk1977aef0bf62005-12-30 16:28:01 +00002551static int lockBtree(BtShared *pBt){
drhc2a4bab2010-04-02 12:46:45 +00002552 int rc; /* Result code from subfunctions */
2553 MemPage *pPage1; /* Page 1 of the database file */
2554 int nPage; /* Number of pages in the database */
2555 int nPageFile = 0; /* Number of pages in the database file */
2556 int nPageHeader; /* Number of pages in the database according to hdr */
drhd677b3d2007-08-20 22:48:41 +00002557
drh1fee73e2007-08-29 04:00:57 +00002558 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977295dc102009-04-01 19:07:03 +00002559 assert( pBt->pPage1==0 );
danielk197789bc4bc2009-07-21 19:25:24 +00002560 rc = sqlite3PagerSharedLock(pBt->pPager);
2561 if( rc!=SQLITE_OK ) return rc;
drhb00fc3b2013-08-21 23:42:32 +00002562 rc = btreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00002563 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00002564
2565 /* Do some checking to help insure the file we opened really is
2566 ** a valid database file.
2567 */
drhc2a4bab2010-04-02 12:46:45 +00002568 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
drh8fb8b532010-08-14 17:12:04 +00002569 sqlite3PagerPagecount(pBt->pPager, &nPageFile);
drhb28e59b2010-06-17 02:13:39 +00002570 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
drhc2a4bab2010-04-02 12:46:45 +00002571 nPage = nPageFile;
drh97b59a52010-03-31 02:31:33 +00002572 }
2573 if( nPage>0 ){
drh43b18e12010-08-17 19:40:08 +00002574 u32 pageSize;
2575 u32 usableSize;
drhb6f41482004-05-14 01:58:11 +00002576 u8 *page1 = pPage1->aData;
danielk1977ad0132d2008-06-07 08:58:22 +00002577 rc = SQLITE_NOTADB;
drh113762a2014-11-19 16:36:25 +00002578 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
2579 ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
2580 ** 61 74 20 33 00. */
drhb6f41482004-05-14 01:58:11 +00002581 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00002582 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00002583 }
dan5cf53532010-05-01 16:40:20 +00002584
2585#ifdef SQLITE_OMIT_WAL
2586 if( page1[18]>1 ){
drhc9166342012-01-05 23:32:06 +00002587 pBt->btsFlags |= BTS_READ_ONLY;
dan5cf53532010-05-01 16:40:20 +00002588 }
2589 if( page1[19]>1 ){
2590 goto page1_init_failed;
2591 }
2592#else
dane04dc882010-04-20 18:53:15 +00002593 if( page1[18]>2 ){
drhc9166342012-01-05 23:32:06 +00002594 pBt->btsFlags |= BTS_READ_ONLY;
drh309169a2007-04-24 17:27:51 +00002595 }
dane04dc882010-04-20 18:53:15 +00002596 if( page1[19]>2 ){
drhb6f41482004-05-14 01:58:11 +00002597 goto page1_init_failed;
2598 }
drhe5ae5732008-06-15 02:51:47 +00002599
dana470aeb2010-04-21 11:43:38 +00002600 /* If the write version is set to 2, this database should be accessed
2601 ** in WAL mode. If the log is not already open, open it now. Then
2602 ** return SQLITE_OK and return without populating BtShared.pPage1.
2603 ** The caller detects this and calls this function again. This is
2604 ** required as the version of page 1 currently in the page1 buffer
2605 ** may not be the latest version - there may be a newer one in the log
2606 ** file.
2607 */
drhc9166342012-01-05 23:32:06 +00002608 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
dane04dc882010-04-20 18:53:15 +00002609 int isOpen = 0;
drh7ed91f22010-04-29 22:34:07 +00002610 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
dane04dc882010-04-20 18:53:15 +00002611 if( rc!=SQLITE_OK ){
2612 goto page1_init_failed;
2613 }else if( isOpen==0 ){
2614 releasePage(pPage1);
2615 return SQLITE_OK;
2616 }
dan8b5444b2010-04-27 14:37:47 +00002617 rc = SQLITE_NOTADB;
dane04dc882010-04-20 18:53:15 +00002618 }
dan5cf53532010-05-01 16:40:20 +00002619#endif
dane04dc882010-04-20 18:53:15 +00002620
drh113762a2014-11-19 16:36:25 +00002621 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
2622 ** fractions and the leaf payload fraction values must be 64, 32, and 32.
2623 **
drhe5ae5732008-06-15 02:51:47 +00002624 ** The original design allowed these amounts to vary, but as of
2625 ** version 3.6.0, we require them to be fixed.
2626 */
2627 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
2628 goto page1_init_failed;
2629 }
drh113762a2014-11-19 16:36:25 +00002630 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2631 ** determined by the 2-byte integer located at an offset of 16 bytes from
2632 ** the beginning of the database file. */
drhb2eced52010-08-12 02:41:12 +00002633 pageSize = (page1[16]<<8) | (page1[17]<<16);
drh113762a2014-11-19 16:36:25 +00002634 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
2635 ** between 512 and 65536 inclusive. */
drhb2eced52010-08-12 02:41:12 +00002636 if( ((pageSize-1)&pageSize)!=0
2637 || pageSize>SQLITE_MAX_PAGE_SIZE
2638 || pageSize<=256
drh7dc385e2007-09-06 23:39:36 +00002639 ){
drh07d183d2005-05-01 22:52:42 +00002640 goto page1_init_failed;
2641 }
2642 assert( (pageSize & 7)==0 );
drh113762a2014-11-19 16:36:25 +00002643 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
2644 ** integer at offset 20 is the number of bytes of space at the end of
2645 ** each page to reserve for extensions.
2646 **
2647 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2648 ** determined by the one-byte unsigned integer found at an offset of 20
2649 ** into the database file header. */
danielk1977f653d782008-03-20 11:04:21 +00002650 usableSize = pageSize - page1[20];
shaneh1df2db72010-08-18 02:28:48 +00002651 if( (u32)pageSize!=pBt->pageSize ){
danielk1977f653d782008-03-20 11:04:21 +00002652 /* After reading the first page of the database assuming a page size
2653 ** of BtShared.pageSize, we have discovered that the page-size is
2654 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
2655 ** zero and return SQLITE_OK. The caller will call this function
2656 ** again with the correct page-size.
2657 */
2658 releasePage(pPage1);
drh43b18e12010-08-17 19:40:08 +00002659 pBt->usableSize = usableSize;
2660 pBt->pageSize = pageSize;
drhf7141992008-06-19 00:16:08 +00002661 freeTempSpace(pBt);
drhfa9601a2009-06-18 17:22:39 +00002662 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
2663 pageSize-usableSize);
drh5e483932009-07-10 16:51:30 +00002664 return rc;
danielk1977f653d782008-03-20 11:04:21 +00002665 }
danecac6702011-02-09 18:19:20 +00002666 if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
drhc2a4bab2010-04-02 12:46:45 +00002667 rc = SQLITE_CORRUPT_BKPT;
2668 goto page1_init_failed;
2669 }
drh113762a2014-11-19 16:36:25 +00002670 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
2671 ** be less than 480. In other words, if the page size is 512, then the
2672 ** reserved space size cannot exceed 32. */
drhb33e1b92009-06-18 11:29:20 +00002673 if( usableSize<480 ){
drhb6f41482004-05-14 01:58:11 +00002674 goto page1_init_failed;
2675 }
drh43b18e12010-08-17 19:40:08 +00002676 pBt->pageSize = pageSize;
2677 pBt->usableSize = usableSize;
drh057cd3a2005-02-15 16:23:02 +00002678#ifndef SQLITE_OMIT_AUTOVACUUM
2679 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00002680 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00002681#endif
drh306dc212001-05-21 13:45:10 +00002682 }
drhb6f41482004-05-14 01:58:11 +00002683
2684 /* maxLocal is the maximum amount of payload to store locally for
2685 ** a cell. Make sure it is small enough so that at least minFanout
2686 ** cells can will fit on one page. We assume a 10-byte page header.
2687 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00002688 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00002689 ** 4-byte child pointer
2690 ** 9-byte nKey value
2691 ** 4-byte nData value
2692 ** 4-byte overflow page pointer
drhe22e03e2010-08-18 21:19:03 +00002693 ** So a cell consists of a 2-byte pointer, a header which is as much as
drh43605152004-05-29 21:46:49 +00002694 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
2695 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00002696 */
shaneh1df2db72010-08-18 02:28:48 +00002697 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
2698 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
2699 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
2700 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
drhc9166342012-01-05 23:32:06 +00002701 if( pBt->maxLocal>127 ){
2702 pBt->max1bytePayload = 127;
2703 }else{
mistachkin0547e2f2012-01-08 00:54:02 +00002704 pBt->max1bytePayload = (u8)pBt->maxLocal;
drhc9166342012-01-05 23:32:06 +00002705 }
drh2e38c322004-09-03 18:38:44 +00002706 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00002707 pBt->pPage1 = pPage1;
drhdd3cd972010-03-27 17:12:36 +00002708 pBt->nPage = nPage;
drhb6f41482004-05-14 01:58:11 +00002709 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00002710
drh72f82862001-05-24 21:06:34 +00002711page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00002712 releasePage(pPage1);
2713 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00002714 return rc;
drh306dc212001-05-21 13:45:10 +00002715}
2716
drh85ec3b62013-05-14 23:12:06 +00002717#ifndef NDEBUG
2718/*
2719** Return the number of cursors open on pBt. This is for use
2720** in assert() expressions, so it is only compiled if NDEBUG is not
2721** defined.
2722**
2723** Only write cursors are counted if wrOnly is true. If wrOnly is
2724** false then all cursors are counted.
2725**
2726** For the purposes of this routine, a cursor is any cursor that
peter.d.reid60ec9142014-09-06 16:39:46 +00002727** is capable of reading or writing to the database. Cursors that
drh85ec3b62013-05-14 23:12:06 +00002728** have been tripped into the CURSOR_FAULT state are not counted.
2729*/
2730static int countValidCursors(BtShared *pBt, int wrOnly){
2731 BtCursor *pCur;
2732 int r = 0;
2733 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drh036dbec2014-03-11 23:40:44 +00002734 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
2735 && pCur->eState!=CURSOR_FAULT ) r++;
drh85ec3b62013-05-14 23:12:06 +00002736 }
2737 return r;
2738}
2739#endif
2740
drh306dc212001-05-21 13:45:10 +00002741/*
drhb8ca3072001-12-05 00:21:20 +00002742** If there are no outstanding cursors and we are not in the middle
2743** of a transaction but there is a read lock on the database, then
2744** this routine unrefs the first page of the database file which
2745** has the effect of releasing the read lock.
2746**
drhb8ca3072001-12-05 00:21:20 +00002747** If there is a transaction in progress, this routine is a no-op.
2748*/
danielk1977aef0bf62005-12-30 16:28:01 +00002749static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00002750 assert( sqlite3_mutex_held(pBt->mutex) );
drh85ec3b62013-05-14 23:12:06 +00002751 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
danielk19771bc9ee92009-07-04 15:41:02 +00002752 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
drhb2325b72014-09-24 18:31:07 +00002753 MemPage *pPage1 = pBt->pPage1;
2754 assert( pPage1->aData );
danielk1977c1761e82009-06-25 09:40:03 +00002755 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
drh3aac2dd2004-04-26 14:10:20 +00002756 pBt->pPage1 = 0;
drhb2325b72014-09-24 18:31:07 +00002757 releasePage(pPage1);
drhb8ca3072001-12-05 00:21:20 +00002758 }
2759}
2760
2761/*
drhe39f2f92009-07-23 01:43:59 +00002762** If pBt points to an empty file then convert that empty file
2763** into a new empty database by initializing the first page of
2764** the database.
drh8b2f49b2001-06-08 00:21:52 +00002765*/
danielk1977aef0bf62005-12-30 16:28:01 +00002766static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00002767 MemPage *pP1;
2768 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00002769 int rc;
drhd677b3d2007-08-20 22:48:41 +00002770
drh1fee73e2007-08-29 04:00:57 +00002771 assert( sqlite3_mutex_held(pBt->mutex) );
drhdd3cd972010-03-27 17:12:36 +00002772 if( pBt->nPage>0 ){
2773 return SQLITE_OK;
danielk1977ad0132d2008-06-07 08:58:22 +00002774 }
drh3aac2dd2004-04-26 14:10:20 +00002775 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00002776 assert( pP1!=0 );
2777 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00002778 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00002779 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00002780 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
2781 assert( sizeof(zMagicHeader)==16 );
shaneh1df2db72010-08-18 02:28:48 +00002782 data[16] = (u8)((pBt->pageSize>>8)&0xff);
2783 data[17] = (u8)((pBt->pageSize>>16)&0xff);
drh9e572e62004-04-23 23:43:10 +00002784 data[18] = 1;
2785 data[19] = 1;
drhf49661a2008-12-10 16:45:50 +00002786 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
2787 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
drhe5ae5732008-06-15 02:51:47 +00002788 data[21] = 64;
2789 data[22] = 32;
2790 data[23] = 32;
drhb6f41482004-05-14 01:58:11 +00002791 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00002792 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhc9166342012-01-05 23:32:06 +00002793 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
danielk1977003ba062004-11-04 02:57:33 +00002794#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002795 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00002796 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00002797 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00002798 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00002799#endif
drhdd3cd972010-03-27 17:12:36 +00002800 pBt->nPage = 1;
2801 data[31] = 1;
drh8b2f49b2001-06-08 00:21:52 +00002802 return SQLITE_OK;
2803}
2804
2805/*
danb483eba2012-10-13 19:58:11 +00002806** Initialize the first page of the database file (creating a database
2807** consisting of a single page and no schema objects). Return SQLITE_OK
2808** if successful, or an SQLite error code otherwise.
2809*/
2810int sqlite3BtreeNewDb(Btree *p){
2811 int rc;
2812 sqlite3BtreeEnter(p);
2813 p->pBt->nPage = 0;
2814 rc = newDatabase(p->pBt);
2815 sqlite3BtreeLeave(p);
2816 return rc;
2817}
2818
2819/*
danielk1977ee5741e2004-05-31 10:01:34 +00002820** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00002821** is started if the second argument is nonzero, otherwise a read-
2822** transaction. If the second argument is 2 or more and exclusive
2823** transaction is started, meaning that no other process is allowed
2824** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00002825** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00002826** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00002827**
danielk1977ee5741e2004-05-31 10:01:34 +00002828** A write-transaction must be started before attempting any
2829** changes to the database. None of the following routines
2830** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00002831**
drh23e11ca2004-05-04 17:27:28 +00002832** sqlite3BtreeCreateTable()
2833** sqlite3BtreeCreateIndex()
2834** sqlite3BtreeClearTable()
2835** sqlite3BtreeDropTable()
2836** sqlite3BtreeInsert()
2837** sqlite3BtreeDelete()
2838** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00002839**
drhb8ef32c2005-03-14 02:01:49 +00002840** If an initial attempt to acquire the lock fails because of lock contention
2841** and the database was previously unlocked, then invoke the busy handler
2842** if there is one. But if there was previously a read-lock, do not
2843** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
2844** returned when there is already a read-lock in order to avoid a deadlock.
2845**
2846** Suppose there are two processes A and B. A has a read lock and B has
2847** a reserved lock. B tries to promote to exclusive but is blocked because
2848** of A's read lock. A tries to promote to reserved but is blocked by B.
2849** One or the other of the two processes must give way or there can be
2850** no progress. By returning SQLITE_BUSY and not invoking the busy callback
2851** when A already has a read lock, we encourage A to give up and let B
2852** proceed.
drha059ad02001-04-17 20:09:11 +00002853*/
danielk1977aef0bf62005-12-30 16:28:01 +00002854int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
danielk1977404ca072009-03-16 13:19:36 +00002855 sqlite3 *pBlock = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00002856 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00002857 int rc = SQLITE_OK;
2858
drhd677b3d2007-08-20 22:48:41 +00002859 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002860 btreeIntegrity(p);
2861
danielk1977ee5741e2004-05-31 10:01:34 +00002862 /* If the btree is already in a write-transaction, or it
2863 ** is already in a read-transaction and a read-transaction
2864 ** is requested, this is a no-op.
2865 */
danielk1977aef0bf62005-12-30 16:28:01 +00002866 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00002867 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002868 }
dan56c517a2013-09-26 11:04:33 +00002869 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
drhb8ef32c2005-03-14 02:01:49 +00002870
2871 /* Write transactions are not possible on a read-only database */
drhc9166342012-01-05 23:32:06 +00002872 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00002873 rc = SQLITE_READONLY;
2874 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002875 }
2876
danielk1977404ca072009-03-16 13:19:36 +00002877#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +00002878 /* If another database handle has already opened a write transaction
2879 ** on this shared-btree structure and a second write transaction is
danielk1977404ca072009-03-16 13:19:36 +00002880 ** requested, return SQLITE_LOCKED.
danielk1977aef0bf62005-12-30 16:28:01 +00002881 */
drhc9166342012-01-05 23:32:06 +00002882 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
2883 || (pBt->btsFlags & BTS_PENDING)!=0
2884 ){
danielk1977404ca072009-03-16 13:19:36 +00002885 pBlock = pBt->pWriter->db;
2886 }else if( wrflag>1 ){
danielk1977641b0f42007-12-21 04:47:25 +00002887 BtLock *pIter;
2888 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
2889 if( pIter->pBtree!=p ){
danielk1977404ca072009-03-16 13:19:36 +00002890 pBlock = pIter->pBtree->db;
2891 break;
danielk1977641b0f42007-12-21 04:47:25 +00002892 }
2893 }
2894 }
danielk1977404ca072009-03-16 13:19:36 +00002895 if( pBlock ){
2896 sqlite3ConnectionBlocked(p->db, pBlock);
2897 rc = SQLITE_LOCKED_SHAREDCACHE;
2898 goto trans_begun;
2899 }
danielk1977641b0f42007-12-21 04:47:25 +00002900#endif
2901
danielk1977602b4662009-07-02 07:47:33 +00002902 /* Any read-only or read-write transaction implies a read-lock on
2903 ** page 1. So if some other shared-cache client already has a write-lock
2904 ** on page 1, the transaction cannot be opened. */
drh4c301aa2009-07-15 17:25:45 +00002905 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
2906 if( SQLITE_OK!=rc ) goto trans_begun;
danielk1977602b4662009-07-02 07:47:33 +00002907
drhc9166342012-01-05 23:32:06 +00002908 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
2909 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
drhb8ef32c2005-03-14 02:01:49 +00002910 do {
danielk1977295dc102009-04-01 19:07:03 +00002911 /* Call lockBtree() until either pBt->pPage1 is populated or
2912 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
2913 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
2914 ** reading page 1 it discovers that the page-size of the database
2915 ** file is not pBt->pageSize. In this case lockBtree() will update
2916 ** pBt->pageSize to the page-size of the file on disk.
2917 */
2918 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
drh309169a2007-04-24 17:27:51 +00002919
drhb8ef32c2005-03-14 02:01:49 +00002920 if( rc==SQLITE_OK && wrflag ){
drhc9166342012-01-05 23:32:06 +00002921 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
drh309169a2007-04-24 17:27:51 +00002922 rc = SQLITE_READONLY;
2923 }else{
danielk1977d8293352009-04-30 09:10:37 +00002924 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
drh309169a2007-04-24 17:27:51 +00002925 if( rc==SQLITE_OK ){
2926 rc = newDatabase(pBt);
2927 }
drhb8ef32c2005-03-14 02:01:49 +00002928 }
2929 }
2930
danielk1977bd434552009-03-18 10:33:00 +00002931 if( rc!=SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00002932 unlockBtreeIfUnused(pBt);
2933 }
danf9b76712010-06-01 14:12:45 +00002934 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
danielk19771ceedd32008-11-19 10:22:33 +00002935 btreeInvokeBusyHandler(pBt) );
danielk1977aef0bf62005-12-30 16:28:01 +00002936
2937 if( rc==SQLITE_OK ){
2938 if( p->inTrans==TRANS_NONE ){
2939 pBt->nTransaction++;
danielk1977602b4662009-07-02 07:47:33 +00002940#ifndef SQLITE_OMIT_SHARED_CACHE
2941 if( p->sharable ){
drhf2f105d2012-08-20 15:53:54 +00002942 assert( p->lock.pBtree==p && p->lock.iTable==1 );
danielk1977602b4662009-07-02 07:47:33 +00002943 p->lock.eLock = READ_LOCK;
2944 p->lock.pNext = pBt->pLock;
2945 pBt->pLock = &p->lock;
2946 }
2947#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002948 }
2949 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
2950 if( p->inTrans>pBt->inTransaction ){
2951 pBt->inTransaction = p->inTrans;
2952 }
danielk1977404ca072009-03-16 13:19:36 +00002953 if( wrflag ){
dan59257dc2010-08-04 11:34:31 +00002954 MemPage *pPage1 = pBt->pPage1;
2955#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977404ca072009-03-16 13:19:36 +00002956 assert( !pBt->pWriter );
2957 pBt->pWriter = p;
drhc9166342012-01-05 23:32:06 +00002958 pBt->btsFlags &= ~BTS_EXCLUSIVE;
2959 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
danielk1977641b0f42007-12-21 04:47:25 +00002960#endif
dan59257dc2010-08-04 11:34:31 +00002961
2962 /* If the db-size header field is incorrect (as it may be if an old
2963 ** client has been writing the database file), update it now. Doing
2964 ** this sooner rather than later means the database size can safely
2965 ** re-read the database size from page 1 if a savepoint or transaction
2966 ** rollback occurs within the transaction.
2967 */
2968 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
2969 rc = sqlite3PagerWrite(pPage1->pDbPage);
2970 if( rc==SQLITE_OK ){
2971 put4byte(&pPage1->aData[28], pBt->nPage);
2972 }
2973 }
2974 }
danielk1977aef0bf62005-12-30 16:28:01 +00002975 }
2976
drhd677b3d2007-08-20 22:48:41 +00002977
2978trans_begun:
danielk1977fd7f0452008-12-17 17:30:26 +00002979 if( rc==SQLITE_OK && wrflag ){
danielk197712dd5492008-12-18 15:45:07 +00002980 /* This call makes sure that the pager has the correct number of
2981 ** open savepoints. If the second parameter is greater than 0 and
2982 ** the sub-journal is not already open, then it will be opened here.
2983 */
danielk1977fd7f0452008-12-17 17:30:26 +00002984 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
2985 }
danielk197712dd5492008-12-18 15:45:07 +00002986
danielk1977aef0bf62005-12-30 16:28:01 +00002987 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002988 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00002989 return rc;
drha059ad02001-04-17 20:09:11 +00002990}
2991
danielk1977687566d2004-11-02 12:56:41 +00002992#ifndef SQLITE_OMIT_AUTOVACUUM
2993
2994/*
2995** Set the pointer-map entries for all children of page pPage. Also, if
2996** pPage contains cells that point to overflow pages, set the pointer
2997** map entries for the overflow pages as well.
2998*/
2999static int setChildPtrmaps(MemPage *pPage){
3000 int i; /* Counter variable */
3001 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00003002 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00003003 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00003004 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00003005 Pgno pgno = pPage->pgno;
3006
drh1fee73e2007-08-29 04:00:57 +00003007 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197730548662009-07-09 05:07:37 +00003008 rc = btreeInitPage(pPage);
danielk19772df71c72007-05-24 07:22:42 +00003009 if( rc!=SQLITE_OK ){
3010 goto set_child_ptrmaps_out;
3011 }
danielk1977687566d2004-11-02 12:56:41 +00003012 nCell = pPage->nCell;
3013
3014 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00003015 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00003016
drh98add2e2009-07-20 17:11:49 +00003017 ptrmapPutOvflPtr(pPage, pCell, &rc);
danielk197726836652005-01-17 01:33:13 +00003018
danielk1977687566d2004-11-02 12:56:41 +00003019 if( !pPage->leaf ){
3020 Pgno childPgno = get4byte(pCell);
drh98add2e2009-07-20 17:11:49 +00003021 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00003022 }
3023 }
3024
3025 if( !pPage->leaf ){
3026 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh98add2e2009-07-20 17:11:49 +00003027 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00003028 }
3029
3030set_child_ptrmaps_out:
3031 pPage->isInit = isInitOrig;
3032 return rc;
3033}
3034
3035/*
drhf3aed592009-07-08 18:12:49 +00003036** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
3037** that it points to iTo. Parameter eType describes the type of pointer to
3038** be modified, as follows:
danielk1977687566d2004-11-02 12:56:41 +00003039**
3040** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
3041** page of pPage.
3042**
3043** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3044** page pointed to by one of the cells on pPage.
3045**
3046** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3047** overflow page in the list.
3048*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00003049static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00003050 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00003051 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977687566d2004-11-02 12:56:41 +00003052 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00003053 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00003054 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00003055 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00003056 }
danielk1977f78fc082004-11-02 14:40:32 +00003057 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00003058 }else{
drhf49661a2008-12-10 16:45:50 +00003059 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00003060 int i;
3061 int nCell;
3062
danielk197730548662009-07-09 05:07:37 +00003063 btreeInitPage(pPage);
danielk1977687566d2004-11-02 12:56:41 +00003064 nCell = pPage->nCell;
3065
danielk1977687566d2004-11-02 12:56:41 +00003066 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00003067 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00003068 if( eType==PTRMAP_OVERFLOW1 ){
3069 CellInfo info;
danielk197730548662009-07-09 05:07:37 +00003070 btreeParseCellPtr(pPage, pCell, &info);
drhe42a9b42011-08-31 13:27:19 +00003071 if( info.iOverflow
3072 && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
3073 && iFrom==get4byte(&pCell[info.iOverflow])
3074 ){
3075 put4byte(&pCell[info.iOverflow], iTo);
3076 break;
danielk1977687566d2004-11-02 12:56:41 +00003077 }
3078 }else{
3079 if( get4byte(pCell)==iFrom ){
3080 put4byte(pCell, iTo);
3081 break;
3082 }
3083 }
3084 }
3085
3086 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00003087 if( eType!=PTRMAP_BTREE ||
3088 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00003089 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00003090 }
danielk1977687566d2004-11-02 12:56:41 +00003091 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3092 }
3093
3094 pPage->isInit = isInitOrig;
3095 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00003096 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00003097}
3098
danielk1977003ba062004-11-04 02:57:33 +00003099
danielk19777701e812005-01-10 12:59:51 +00003100/*
3101** Move the open database page pDbPage to location iFreePage in the
3102** database. The pDbPage reference remains valid.
drhe64ca7b2009-07-16 18:21:17 +00003103**
3104** The isCommit flag indicates that there is no need to remember that
3105** the journal needs to be sync()ed before database page pDbPage->pgno
3106** can be written to. The caller has already promised not to write to that
3107** page.
danielk19777701e812005-01-10 12:59:51 +00003108*/
danielk1977003ba062004-11-04 02:57:33 +00003109static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00003110 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00003111 MemPage *pDbPage, /* Open page to move */
3112 u8 eType, /* Pointer map 'type' entry for pDbPage */
3113 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
danielk19774c999992008-07-16 18:17:55 +00003114 Pgno iFreePage, /* The location to move pDbPage to */
drhe64ca7b2009-07-16 18:21:17 +00003115 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
danielk1977003ba062004-11-04 02:57:33 +00003116){
3117 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
3118 Pgno iDbPage = pDbPage->pgno;
3119 Pager *pPager = pBt->pPager;
3120 int rc;
3121
danielk1977a0bf2652004-11-04 14:30:04 +00003122 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3123 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00003124 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00003125 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00003126
drh85b623f2007-12-13 21:54:09 +00003127 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00003128 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
3129 iDbPage, iFreePage, iPtrPage, eType));
danielk19774c999992008-07-16 18:17:55 +00003130 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
danielk1977003ba062004-11-04 02:57:33 +00003131 if( rc!=SQLITE_OK ){
3132 return rc;
3133 }
3134 pDbPage->pgno = iFreePage;
3135
3136 /* If pDbPage was a btree-page, then it may have child pages and/or cells
3137 ** that point to overflow pages. The pointer map entries for all these
3138 ** pages need to be changed.
3139 **
3140 ** If pDbPage is an overflow page, then the first 4 bytes may store a
3141 ** pointer to a subsequent overflow page. If this is the case, then
3142 ** the pointer map needs to be updated for the subsequent overflow page.
3143 */
danielk1977a0bf2652004-11-04 14:30:04 +00003144 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00003145 rc = setChildPtrmaps(pDbPage);
3146 if( rc!=SQLITE_OK ){
3147 return rc;
3148 }
3149 }else{
3150 Pgno nextOvfl = get4byte(pDbPage->aData);
3151 if( nextOvfl!=0 ){
drh98add2e2009-07-20 17:11:49 +00003152 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
danielk1977003ba062004-11-04 02:57:33 +00003153 if( rc!=SQLITE_OK ){
3154 return rc;
3155 }
3156 }
3157 }
3158
3159 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3160 ** that it points at iFreePage. Also fix the pointer map entry for
3161 ** iPtrPage.
3162 */
danielk1977a0bf2652004-11-04 14:30:04 +00003163 if( eType!=PTRMAP_ROOTPAGE ){
drhb00fc3b2013-08-21 23:42:32 +00003164 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00003165 if( rc!=SQLITE_OK ){
3166 return rc;
3167 }
danielk19773b8a05f2007-03-19 17:44:26 +00003168 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00003169 if( rc!=SQLITE_OK ){
3170 releasePage(pPtrPage);
3171 return rc;
3172 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00003173 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00003174 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00003175 if( rc==SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +00003176 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
danielk1977fdb7cdb2005-01-17 02:12:18 +00003177 }
danielk1977003ba062004-11-04 02:57:33 +00003178 }
danielk1977003ba062004-11-04 02:57:33 +00003179 return rc;
3180}
3181
danielk1977dddbcdc2007-04-26 14:42:34 +00003182/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00003183static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00003184
3185/*
dan51f0b6d2013-02-22 20:16:34 +00003186** Perform a single step of an incremental-vacuum. If successful, return
3187** SQLITE_OK. If there is no work to do (and therefore no point in
3188** calling this function again), return SQLITE_DONE. Or, if an error
3189** occurs, return some other error code.
danielk1977dddbcdc2007-04-26 14:42:34 +00003190**
peter.d.reid60ec9142014-09-06 16:39:46 +00003191** More specifically, this function attempts to re-organize the database so
dan51f0b6d2013-02-22 20:16:34 +00003192** that the last page of the file currently in use is no longer in use.
danielk1977dddbcdc2007-04-26 14:42:34 +00003193**
dan51f0b6d2013-02-22 20:16:34 +00003194** Parameter nFin is the number of pages that this database would contain
3195** were this function called until it returns SQLITE_DONE.
3196**
3197** If the bCommit parameter is non-zero, this function assumes that the
3198** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
peter.d.reid60ec9142014-09-06 16:39:46 +00003199** or an error. bCommit is passed true for an auto-vacuum-on-commit
dan51f0b6d2013-02-22 20:16:34 +00003200** operation, or false for an incremental vacuum.
danielk1977dddbcdc2007-04-26 14:42:34 +00003201*/
dan51f0b6d2013-02-22 20:16:34 +00003202static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
danielk1977dddbcdc2007-04-26 14:42:34 +00003203 Pgno nFreeList; /* Number of pages still on the free-list */
drhdd3cd972010-03-27 17:12:36 +00003204 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003205
drh1fee73e2007-08-29 04:00:57 +00003206 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977fa542f12009-04-02 18:28:08 +00003207 assert( iLastPg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00003208
3209 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003210 u8 eType;
3211 Pgno iPtrPage;
3212
3213 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977fa542f12009-04-02 18:28:08 +00003214 if( nFreeList==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003215 return SQLITE_DONE;
3216 }
3217
3218 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3219 if( rc!=SQLITE_OK ){
3220 return rc;
3221 }
3222 if( eType==PTRMAP_ROOTPAGE ){
3223 return SQLITE_CORRUPT_BKPT;
3224 }
3225
3226 if( eType==PTRMAP_FREEPAGE ){
dan51f0b6d2013-02-22 20:16:34 +00003227 if( bCommit==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003228 /* Remove the page from the files free-list. This is not required
dan51f0b6d2013-02-22 20:16:34 +00003229 ** if bCommit is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00003230 ** truncated to zero after this function returns, so it doesn't
3231 ** matter if it still contains some garbage entries.
3232 */
3233 Pgno iFreePg;
3234 MemPage *pFreePg;
dan51f0b6d2013-02-22 20:16:34 +00003235 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
danielk1977dddbcdc2007-04-26 14:42:34 +00003236 if( rc!=SQLITE_OK ){
3237 return rc;
3238 }
3239 assert( iFreePg==iLastPg );
3240 releasePage(pFreePg);
3241 }
3242 } else {
3243 Pgno iFreePg; /* Index of free page to move pLastPg to */
3244 MemPage *pLastPg;
dan51f0b6d2013-02-22 20:16:34 +00003245 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
3246 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
danielk1977dddbcdc2007-04-26 14:42:34 +00003247
drhb00fc3b2013-08-21 23:42:32 +00003248 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00003249 if( rc!=SQLITE_OK ){
3250 return rc;
3251 }
3252
dan51f0b6d2013-02-22 20:16:34 +00003253 /* If bCommit is zero, this loop runs exactly once and page pLastPg
danielk1977b4626a32007-04-28 15:47:43 +00003254 ** is swapped with the first free page pulled off the free list.
3255 **
dan51f0b6d2013-02-22 20:16:34 +00003256 ** On the other hand, if bCommit is greater than zero, then keep
danielk1977b4626a32007-04-28 15:47:43 +00003257 ** looping until a free-page located within the first nFin pages
3258 ** of the file is found.
3259 */
dan51f0b6d2013-02-22 20:16:34 +00003260 if( bCommit==0 ){
3261 eMode = BTALLOC_LE;
3262 iNear = nFin;
3263 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003264 do {
3265 MemPage *pFreePg;
dan51f0b6d2013-02-22 20:16:34 +00003266 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
danielk1977dddbcdc2007-04-26 14:42:34 +00003267 if( rc!=SQLITE_OK ){
3268 releasePage(pLastPg);
3269 return rc;
3270 }
3271 releasePage(pFreePg);
dan51f0b6d2013-02-22 20:16:34 +00003272 }while( bCommit && iFreePg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00003273 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00003274
dane1df4e32013-03-05 11:27:04 +00003275 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
danielk1977dddbcdc2007-04-26 14:42:34 +00003276 releasePage(pLastPg);
3277 if( rc!=SQLITE_OK ){
3278 return rc;
danielk1977662278e2007-11-05 15:30:12 +00003279 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003280 }
3281 }
3282
dan51f0b6d2013-02-22 20:16:34 +00003283 if( bCommit==0 ){
danbc1a3c62013-02-23 16:40:46 +00003284 do {
danielk19773460d192008-12-27 15:23:13 +00003285 iLastPg--;
danbc1a3c62013-02-23 16:40:46 +00003286 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
3287 pBt->bDoTruncate = 1;
drhdd3cd972010-03-27 17:12:36 +00003288 pBt->nPage = iLastPg;
danielk1977dddbcdc2007-04-26 14:42:34 +00003289 }
3290 return SQLITE_OK;
3291}
3292
3293/*
dan51f0b6d2013-02-22 20:16:34 +00003294** The database opened by the first argument is an auto-vacuum database
3295** nOrig pages in size containing nFree free pages. Return the expected
3296** size of the database in pages following an auto-vacuum operation.
3297*/
3298static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
3299 int nEntry; /* Number of entries on one ptrmap page */
3300 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
3301 Pgno nFin; /* Return value */
3302
3303 nEntry = pBt->usableSize/5;
3304 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
3305 nFin = nOrig - nFree - nPtrmap;
3306 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
3307 nFin--;
3308 }
3309 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
3310 nFin--;
3311 }
dan51f0b6d2013-02-22 20:16:34 +00003312
3313 return nFin;
3314}
3315
3316/*
danielk1977dddbcdc2007-04-26 14:42:34 +00003317** A write-transaction must be opened before calling this function.
3318** It performs a single unit of work towards an incremental vacuum.
3319**
3320** If the incremental vacuum is finished after this function has run,
shanebe217792009-03-05 04:20:31 +00003321** SQLITE_DONE is returned. If it is not finished, but no error occurred,
danielk1977dddbcdc2007-04-26 14:42:34 +00003322** SQLITE_OK is returned. Otherwise an SQLite error code.
3323*/
3324int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00003325 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003326 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003327
3328 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00003329 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
3330 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00003331 rc = SQLITE_DONE;
3332 }else{
dan51f0b6d2013-02-22 20:16:34 +00003333 Pgno nOrig = btreePagecount(pBt);
3334 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
3335 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
3336
dan91384712013-02-24 11:50:43 +00003337 if( nOrig<nFin ){
3338 rc = SQLITE_CORRUPT_BKPT;
3339 }else if( nFree>0 ){
dan11dcd112013-03-15 18:29:18 +00003340 rc = saveAllCursors(pBt, 0, 0);
3341 if( rc==SQLITE_OK ){
3342 invalidateAllOverflowCache(pBt);
3343 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
3344 }
dan51f0b6d2013-02-22 20:16:34 +00003345 if( rc==SQLITE_OK ){
3346 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3347 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
3348 }
3349 }else{
3350 rc = SQLITE_DONE;
drhdd3cd972010-03-27 17:12:36 +00003351 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003352 }
drhd677b3d2007-08-20 22:48:41 +00003353 sqlite3BtreeLeave(p);
3354 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003355}
3356
3357/*
danielk19773b8a05f2007-03-19 17:44:26 +00003358** This routine is called prior to sqlite3PagerCommit when a transaction
drhf7b54962013-05-28 12:11:54 +00003359** is committed for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00003360**
3361** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
3362** the database file should be truncated to during the commit process.
3363** i.e. the database has been reorganized so that only the first *pnTrunc
3364** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00003365*/
danielk19773460d192008-12-27 15:23:13 +00003366static int autoVacuumCommit(BtShared *pBt){
danielk1977dddbcdc2007-04-26 14:42:34 +00003367 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00003368 Pager *pPager = pBt->pPager;
drhf94a1732008-09-30 17:18:17 +00003369 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00003370
drh1fee73e2007-08-29 04:00:57 +00003371 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00003372 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00003373 assert(pBt->autoVacuum);
3374 if( !pBt->incrVacuum ){
drhea8ffdf2009-07-22 00:35:23 +00003375 Pgno nFin; /* Number of pages in database after autovacuuming */
3376 Pgno nFree; /* Number of pages on the freelist initially */
drh41d628c2009-07-11 17:04:08 +00003377 Pgno iFree; /* The next page to be freed */
drh41d628c2009-07-11 17:04:08 +00003378 Pgno nOrig; /* Database size before freeing */
danielk1977687566d2004-11-02 12:56:41 +00003379
drhb1299152010-03-30 22:58:33 +00003380 nOrig = btreePagecount(pBt);
danielk1977ef165ce2009-04-06 17:50:03 +00003381 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
3382 /* It is not possible to create a database for which the final page
3383 ** is either a pointer-map page or the pending-byte page. If one
3384 ** is encountered, this indicates corruption.
3385 */
danielk19773460d192008-12-27 15:23:13 +00003386 return SQLITE_CORRUPT_BKPT;
3387 }
danielk1977ef165ce2009-04-06 17:50:03 +00003388
danielk19773460d192008-12-27 15:23:13 +00003389 nFree = get4byte(&pBt->pPage1->aData[36]);
dan51f0b6d2013-02-22 20:16:34 +00003390 nFin = finalDbSize(pBt, nOrig, nFree);
drhc5e47ac2009-06-04 00:11:56 +00003391 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
dan0aed84d2013-03-26 14:16:20 +00003392 if( nFin<nOrig ){
3393 rc = saveAllCursors(pBt, 0, 0);
3394 }
danielk19773460d192008-12-27 15:23:13 +00003395 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
dan51f0b6d2013-02-22 20:16:34 +00003396 rc = incrVacuumStep(pBt, nFin, iFree, 1);
danielk1977dddbcdc2007-04-26 14:42:34 +00003397 }
danielk19773460d192008-12-27 15:23:13 +00003398 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
danielk19773460d192008-12-27 15:23:13 +00003399 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3400 put4byte(&pBt->pPage1->aData[32], 0);
3401 put4byte(&pBt->pPage1->aData[36], 0);
drhdd3cd972010-03-27 17:12:36 +00003402 put4byte(&pBt->pPage1->aData[28], nFin);
danbc1a3c62013-02-23 16:40:46 +00003403 pBt->bDoTruncate = 1;
drhdd3cd972010-03-27 17:12:36 +00003404 pBt->nPage = nFin;
danielk1977dddbcdc2007-04-26 14:42:34 +00003405 }
3406 if( rc!=SQLITE_OK ){
3407 sqlite3PagerRollback(pPager);
3408 }
danielk1977687566d2004-11-02 12:56:41 +00003409 }
3410
dan0aed84d2013-03-26 14:16:20 +00003411 assert( nRef>=sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00003412 return rc;
3413}
danielk1977dddbcdc2007-04-26 14:42:34 +00003414
danielk1977a50d9aa2009-06-08 14:49:45 +00003415#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
3416# define setChildPtrmaps(x) SQLITE_OK
3417#endif
danielk1977687566d2004-11-02 12:56:41 +00003418
3419/*
drh80e35f42007-03-30 14:06:34 +00003420** This routine does the first phase of a two-phase commit. This routine
3421** causes a rollback journal to be created (if it does not already exist)
3422** and populated with enough information so that if a power loss occurs
3423** the database can be restored to its original state by playing back
3424** the journal. Then the contents of the journal are flushed out to
3425** the disk. After the journal is safely on oxide, the changes to the
3426** database are written into the database file and flushed to oxide.
3427** At the end of this call, the rollback journal still exists on the
3428** disk and we are still holding all locks, so the transaction has not
drh51898cf2009-04-19 20:51:06 +00003429** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
drh80e35f42007-03-30 14:06:34 +00003430** commit process.
3431**
3432** This call is a no-op if no write-transaction is currently active on pBt.
3433**
3434** Otherwise, sync the database file for the btree pBt. zMaster points to
3435** the name of a master journal file that should be written into the
3436** individual journal file, or is NULL, indicating no master journal file
3437** (single database transaction).
3438**
3439** When this is called, the master journal should already have been
3440** created, populated with this journal pointer and synced to disk.
3441**
3442** Once this is routine has returned, the only thing required to commit
3443** the write-transaction for this database file is to delete the journal.
3444*/
3445int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
3446 int rc = SQLITE_OK;
3447 if( p->inTrans==TRANS_WRITE ){
3448 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003449 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00003450#ifndef SQLITE_OMIT_AUTOVACUUM
3451 if( pBt->autoVacuum ){
danielk19773460d192008-12-27 15:23:13 +00003452 rc = autoVacuumCommit(pBt);
drh80e35f42007-03-30 14:06:34 +00003453 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00003454 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003455 return rc;
3456 }
3457 }
danbc1a3c62013-02-23 16:40:46 +00003458 if( pBt->bDoTruncate ){
3459 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
3460 }
drh80e35f42007-03-30 14:06:34 +00003461#endif
drh49b9d332009-01-02 18:10:42 +00003462 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
drhd677b3d2007-08-20 22:48:41 +00003463 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003464 }
3465 return rc;
3466}
3467
3468/*
danielk197794b30732009-07-02 17:21:57 +00003469** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
3470** at the conclusion of a transaction.
3471*/
3472static void btreeEndTransaction(Btree *p){
3473 BtShared *pBt = p->pBt;
drh1713afb2013-06-28 01:24:57 +00003474 sqlite3 *db = p->db;
danielk197794b30732009-07-02 17:21:57 +00003475 assert( sqlite3BtreeHoldsMutex(p) );
3476
danbc1a3c62013-02-23 16:40:46 +00003477#ifndef SQLITE_OMIT_AUTOVACUUM
3478 pBt->bDoTruncate = 0;
3479#endif
danc0537fe2013-06-28 19:41:43 +00003480 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
danfa401de2009-10-16 14:55:03 +00003481 /* If there are other active statements that belong to this database
3482 ** handle, downgrade to a read-only transaction. The other statements
3483 ** may still be reading from the database. */
danielk197794b30732009-07-02 17:21:57 +00003484 downgradeAllSharedCacheTableLocks(p);
3485 p->inTrans = TRANS_READ;
3486 }else{
3487 /* If the handle had any kind of transaction open, decrement the
3488 ** transaction count of the shared btree. If the transaction count
3489 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
3490 ** call below will unlock the pager. */
3491 if( p->inTrans!=TRANS_NONE ){
3492 clearAllSharedCacheTableLocks(p);
3493 pBt->nTransaction--;
3494 if( 0==pBt->nTransaction ){
3495 pBt->inTransaction = TRANS_NONE;
3496 }
3497 }
3498
3499 /* Set the current transaction state to TRANS_NONE and unlock the
3500 ** pager if this call closed the only read or write transaction. */
3501 p->inTrans = TRANS_NONE;
3502 unlockBtreeIfUnused(pBt);
3503 }
3504
3505 btreeIntegrity(p);
3506}
3507
3508/*
drh2aa679f2001-06-25 02:11:07 +00003509** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00003510**
drh6e345992007-03-30 11:12:08 +00003511** This routine implements the second phase of a 2-phase commit. The
drh51898cf2009-04-19 20:51:06 +00003512** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
3513** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
3514** routine did all the work of writing information out to disk and flushing the
drh6e345992007-03-30 11:12:08 +00003515** contents so that they are written onto the disk platter. All this
drh51898cf2009-04-19 20:51:06 +00003516** routine has to do is delete or truncate or zero the header in the
3517** the rollback journal (which causes the transaction to commit) and
3518** drop locks.
drh6e345992007-03-30 11:12:08 +00003519**
dan60939d02011-03-29 15:40:55 +00003520** Normally, if an error occurs while the pager layer is attempting to
3521** finalize the underlying journal file, this function returns an error and
3522** the upper layer will attempt a rollback. However, if the second argument
3523** is non-zero then this b-tree transaction is part of a multi-file
3524** transaction. In this case, the transaction has already been committed
3525** (by deleting a master journal file) and the caller will ignore this
3526** functions return code. So, even if an error occurs in the pager layer,
3527** reset the b-tree objects internal state to indicate that the write
3528** transaction has been closed. This is quite safe, as the pager will have
3529** transitioned to the error state.
3530**
drh5e00f6c2001-09-13 13:46:56 +00003531** This will release the write lock on the database file. If there
3532** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00003533*/
dan60939d02011-03-29 15:40:55 +00003534int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
danielk1977aef0bf62005-12-30 16:28:01 +00003535
drh075ed302010-10-14 01:17:30 +00003536 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003537 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003538 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003539
3540 /* If the handle has a write-transaction open, commit the shared-btrees
3541 ** transaction and set the shared state to TRANS_READ.
3542 */
3543 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00003544 int rc;
drh075ed302010-10-14 01:17:30 +00003545 BtShared *pBt = p->pBt;
danielk1977aef0bf62005-12-30 16:28:01 +00003546 assert( pBt->inTransaction==TRANS_WRITE );
3547 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00003548 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
dan60939d02011-03-29 15:40:55 +00003549 if( rc!=SQLITE_OK && bCleanup==0 ){
drhd677b3d2007-08-20 22:48:41 +00003550 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00003551 return rc;
3552 }
drh3da9c042014-12-22 18:41:21 +00003553 p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
danielk1977aef0bf62005-12-30 16:28:01 +00003554 pBt->inTransaction = TRANS_READ;
danbf0e57a2013-05-14 20:36:31 +00003555 btreeClearHasContent(pBt);
danielk1977ee5741e2004-05-31 10:01:34 +00003556 }
danielk1977aef0bf62005-12-30 16:28:01 +00003557
danielk197794b30732009-07-02 17:21:57 +00003558 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00003559 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00003560 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003561}
3562
drh80e35f42007-03-30 14:06:34 +00003563/*
3564** Do both phases of a commit.
3565*/
3566int sqlite3BtreeCommit(Btree *p){
3567 int rc;
drhd677b3d2007-08-20 22:48:41 +00003568 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00003569 rc = sqlite3BtreeCommitPhaseOne(p, 0);
3570 if( rc==SQLITE_OK ){
dan60939d02011-03-29 15:40:55 +00003571 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
drh80e35f42007-03-30 14:06:34 +00003572 }
drhd677b3d2007-08-20 22:48:41 +00003573 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003574 return rc;
3575}
3576
drhc39e0002004-05-07 23:50:57 +00003577/*
drhfb982642007-08-30 01:19:59 +00003578** This routine sets the state to CURSOR_FAULT and the error
drh47b7fc72014-11-11 01:33:57 +00003579** code to errCode for every cursor on any BtShared that pBtree
3580** references. Or if the writeOnly flag is set to 1, then only
3581** trip write cursors and leave read cursors unchanged.
drhfb982642007-08-30 01:19:59 +00003582**
drh47b7fc72014-11-11 01:33:57 +00003583** Every cursor is a candidate to be tripped, including cursors
3584** that belong to other database connections that happen to be
3585** sharing the cache with pBtree.
drhfb982642007-08-30 01:19:59 +00003586**
dan80231042014-11-12 14:56:02 +00003587** This routine gets called when a rollback occurs. If the writeOnly
3588** flag is true, then only write-cursors need be tripped - read-only
3589** cursors save their current positions so that they may continue
3590** following the rollback. Or, if writeOnly is false, all cursors are
3591** tripped. In general, writeOnly is false if the transaction being
3592** rolled back modified the database schema. In this case b-tree root
3593** pages may be moved or deleted from the database altogether, making
3594** it unsafe for read cursors to continue.
3595**
3596** If the writeOnly flag is true and an error is encountered while
3597** saving the current position of a read-only cursor, all cursors,
3598** including all read-cursors are tripped.
3599**
3600** SQLITE_OK is returned if successful, or if an error occurs while
3601** saving a cursor position, an SQLite error code.
drhfb982642007-08-30 01:19:59 +00003602*/
dan80231042014-11-12 14:56:02 +00003603int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
drhfb982642007-08-30 01:19:59 +00003604 BtCursor *p;
dan80231042014-11-12 14:56:02 +00003605 int rc = SQLITE_OK;
3606
drh47b7fc72014-11-11 01:33:57 +00003607 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
dan80231042014-11-12 14:56:02 +00003608 if( pBtree ){
3609 sqlite3BtreeEnter(pBtree);
3610 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
3611 int i;
3612 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
3613 if( p->eState==CURSOR_VALID ){
drhbea3b972014-11-18 20:22:05 +00003614 rc = saveCursorPosition(p);
dan80231042014-11-12 14:56:02 +00003615 if( rc!=SQLITE_OK ){
3616 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
3617 break;
3618 }
3619 }
3620 }else{
3621 sqlite3BtreeClearCursor(p);
3622 p->eState = CURSOR_FAULT;
3623 p->skipNext = errCode;
3624 }
3625 for(i=0; i<=p->iPage; i++){
3626 releasePage(p->apPage[i]);
3627 p->apPage[i] = 0;
3628 }
danielk1977bc2ca9e2008-11-13 14:28:28 +00003629 }
dan80231042014-11-12 14:56:02 +00003630 sqlite3BtreeLeave(pBtree);
drhfb982642007-08-30 01:19:59 +00003631 }
dan80231042014-11-12 14:56:02 +00003632 return rc;
drhfb982642007-08-30 01:19:59 +00003633}
3634
3635/*
drh47b7fc72014-11-11 01:33:57 +00003636** Rollback the transaction in progress.
3637**
3638** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
3639** Only write cursors are tripped if writeOnly is true but all cursors are
3640** tripped if writeOnly is false. Any attempt to use
3641** a tripped cursor will result in an error.
drh5e00f6c2001-09-13 13:46:56 +00003642**
3643** This will release the write lock on the database file. If there
3644** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00003645*/
drh47b7fc72014-11-11 01:33:57 +00003646int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
danielk19778d34dfd2006-01-24 16:37:57 +00003647 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003648 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00003649 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00003650
drh47b7fc72014-11-11 01:33:57 +00003651 assert( writeOnly==1 || writeOnly==0 );
3652 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
drhd677b3d2007-08-20 22:48:41 +00003653 sqlite3BtreeEnter(p);
drh0f198a72012-02-13 16:43:16 +00003654 if( tripCode==SQLITE_OK ){
3655 rc = tripCode = saveAllCursors(pBt, 0, 0);
drh47b7fc72014-11-11 01:33:57 +00003656 if( rc ) writeOnly = 0;
drh0f198a72012-02-13 16:43:16 +00003657 }else{
3658 rc = SQLITE_OK;
danielk19772b8c13e2006-01-24 14:21:24 +00003659 }
drh0f198a72012-02-13 16:43:16 +00003660 if( tripCode ){
dan80231042014-11-12 14:56:02 +00003661 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
3662 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
3663 if( rc2!=SQLITE_OK ) rc = rc2;
drh0f198a72012-02-13 16:43:16 +00003664 }
danielk1977aef0bf62005-12-30 16:28:01 +00003665 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003666
3667 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00003668 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00003669
danielk19778d34dfd2006-01-24 16:37:57 +00003670 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00003671 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00003672 if( rc2!=SQLITE_OK ){
3673 rc = rc2;
3674 }
3675
drh24cd67e2004-05-10 16:18:47 +00003676 /* The rollback may have destroyed the pPage1->aData value. So
danielk197730548662009-07-09 05:07:37 +00003677 ** call btreeGetPage() on page 1 again to make
drh16a9b832007-05-05 18:39:25 +00003678 ** sure pPage1->aData is set correctly. */
drhb00fc3b2013-08-21 23:42:32 +00003679 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh1f5b4672010-04-01 02:22:19 +00003680 int nPage = get4byte(28+(u8*)pPage1->aData);
3681 testcase( nPage==0 );
3682 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
3683 testcase( pBt->nPage!=nPage );
3684 pBt->nPage = nPage;
drh24cd67e2004-05-10 16:18:47 +00003685 releasePage(pPage1);
3686 }
drh85ec3b62013-05-14 23:12:06 +00003687 assert( countValidCursors(pBt, 1)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00003688 pBt->inTransaction = TRANS_READ;
danbf0e57a2013-05-14 20:36:31 +00003689 btreeClearHasContent(pBt);
drh24cd67e2004-05-10 16:18:47 +00003690 }
danielk1977aef0bf62005-12-30 16:28:01 +00003691
danielk197794b30732009-07-02 17:21:57 +00003692 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00003693 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00003694 return rc;
3695}
3696
3697/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003698** Start a statement subtransaction. The subtransaction can be rolled
danielk1977bd434552009-03-18 10:33:00 +00003699** back independently of the main transaction. You must start a transaction
3700** before starting a subtransaction. The subtransaction is ended automatically
3701** if the main transaction commits or rolls back.
drhab01f612004-05-22 02:55:23 +00003702**
3703** Statement subtransactions are used around individual SQL statements
3704** that are contained within a BEGIN...COMMIT block. If a constraint
3705** error occurs within the statement, the effect of that one statement
3706** can be rolled back without having to rollback the entire transaction.
danielk1977bd434552009-03-18 10:33:00 +00003707**
3708** A statement sub-transaction is implemented as an anonymous savepoint. The
3709** value passed as the second parameter is the total number of savepoints,
3710** including the new anonymous savepoint, open on the B-Tree. i.e. if there
3711** are no active savepoints and no other statement-transactions open,
3712** iStatement is 1. This anonymous savepoint can be released or rolled back
3713** using the sqlite3BtreeSavepoint() function.
drh663fc632002-02-02 18:49:19 +00003714*/
danielk1977bd434552009-03-18 10:33:00 +00003715int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
drh663fc632002-02-02 18:49:19 +00003716 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003717 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003718 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00003719 assert( p->inTrans==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00003720 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk1977bd434552009-03-18 10:33:00 +00003721 assert( iStatement>0 );
3722 assert( iStatement>p->db->nSavepoint );
drh5e0ccc22010-03-29 19:36:52 +00003723 assert( pBt->inTransaction==TRANS_WRITE );
3724 /* At the pager level, a statement transaction is a savepoint with
3725 ** an index greater than all savepoints created explicitly using
3726 ** SQL statements. It is illegal to open, release or rollback any
3727 ** such savepoints while the statement transaction savepoint is active.
3728 */
3729 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
drhd677b3d2007-08-20 22:48:41 +00003730 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00003731 return rc;
3732}
3733
3734/*
danielk1977fd7f0452008-12-17 17:30:26 +00003735** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
3736** or SAVEPOINT_RELEASE. This function either releases or rolls back the
danielk197712dd5492008-12-18 15:45:07 +00003737** savepoint identified by parameter iSavepoint, depending on the value
3738** of op.
3739**
3740** Normally, iSavepoint is greater than or equal to zero. However, if op is
3741** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
3742** contents of the entire transaction are rolled back. This is different
3743** from a normal transaction rollback, as no locks are released and the
3744** transaction remains open.
danielk1977fd7f0452008-12-17 17:30:26 +00003745*/
3746int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
3747 int rc = SQLITE_OK;
3748 if( p && p->inTrans==TRANS_WRITE ){
3749 BtShared *pBt = p->pBt;
danielk1977fd7f0452008-12-17 17:30:26 +00003750 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
3751 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
3752 sqlite3BtreeEnter(p);
danielk1977fd7f0452008-12-17 17:30:26 +00003753 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
drh9f0bbf92009-01-02 21:08:09 +00003754 if( rc==SQLITE_OK ){
drhc9166342012-01-05 23:32:06 +00003755 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
3756 pBt->nPage = 0;
3757 }
drh9f0bbf92009-01-02 21:08:09 +00003758 rc = newDatabase(pBt);
drhdd3cd972010-03-27 17:12:36 +00003759 pBt->nPage = get4byte(28 + pBt->pPage1->aData);
drhb9b49bf2010-08-05 03:21:39 +00003760
3761 /* The database size was written into the offset 28 of the header
3762 ** when the transaction started, so we know that the value at offset
3763 ** 28 is nonzero. */
3764 assert( pBt->nPage>0 );
drh9f0bbf92009-01-02 21:08:09 +00003765 }
danielk1977fd7f0452008-12-17 17:30:26 +00003766 sqlite3BtreeLeave(p);
3767 }
3768 return rc;
3769}
3770
3771/*
drh8b2f49b2001-06-08 00:21:52 +00003772** Create a new cursor for the BTree whose root is on the page
danielk19773e8add92009-07-04 17:16:00 +00003773** iTable. If a read-only cursor is requested, it is assumed that
3774** the caller already has at least a read-only transaction open
3775** on the database already. If a write-cursor is requested, then
3776** the caller is assumed to have an open write transaction.
drh1bee3d72001-10-15 00:44:35 +00003777**
3778** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00003779** If wrFlag==1, then the cursor can be used for reading or for
3780** writing if other conditions for writing are also met. These
3781** are the conditions that must be met in order for writing to
3782** be allowed:
drh6446c4d2001-12-15 14:22:18 +00003783**
drhf74b8d92002-09-01 23:20:45 +00003784** 1: The cursor must have been opened with wrFlag==1
3785**
drhfe5d71d2007-03-19 11:54:10 +00003786** 2: Other database connections that share the same pager cache
3787** but which are not in the READ_UNCOMMITTED state may not have
3788** cursors open with wrFlag==0 on the same table. Otherwise
3789** the changes made by this write cursor would be visible to
3790** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00003791**
3792** 3: The database must be writable (not on read-only media)
3793**
3794** 4: There must be an active transaction.
3795**
drh6446c4d2001-12-15 14:22:18 +00003796** No checking is done to make sure that page iTable really is the
3797** root page of a b-tree. If it is not, then the cursor acquired
3798** will not work correctly.
danielk197771d5d2c2008-09-29 11:49:47 +00003799**
drhf25a5072009-11-18 23:01:25 +00003800** It is assumed that the sqlite3BtreeCursorZero() has been called
3801** on pCur to initialize the memory space prior to invoking this routine.
drha059ad02001-04-17 20:09:11 +00003802*/
drhd677b3d2007-08-20 22:48:41 +00003803static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00003804 Btree *p, /* The btree */
3805 int iTable, /* Root page of table to open */
3806 int wrFlag, /* 1 to write. 0 read-only */
3807 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
3808 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00003809){
danielk19773e8add92009-07-04 17:16:00 +00003810 BtShared *pBt = p->pBt; /* Shared b-tree handle */
drhecdc7532001-09-23 02:35:53 +00003811
drh1fee73e2007-08-29 04:00:57 +00003812 assert( sqlite3BtreeHoldsMutex(p) );
drhf49661a2008-12-10 16:45:50 +00003813 assert( wrFlag==0 || wrFlag==1 );
danielk197796d48e92009-06-29 06:00:37 +00003814
danielk1977602b4662009-07-02 07:47:33 +00003815 /* The following assert statements verify that if this is a sharable
3816 ** b-tree database, the connection is holding the required table locks,
3817 ** and that no other connection has any open cursor that conflicts with
3818 ** this lock. */
3819 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
danielk197796d48e92009-06-29 06:00:37 +00003820 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
3821
danielk19773e8add92009-07-04 17:16:00 +00003822 /* Assert that the caller has opened the required transaction. */
3823 assert( p->inTrans>TRANS_NONE );
3824 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
3825 assert( pBt->pPage1 && pBt->pPage1->aData );
3826
drhc9166342012-01-05 23:32:06 +00003827 if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
danielk197796d48e92009-06-29 06:00:37 +00003828 return SQLITE_READONLY;
drha0c9a112004-03-10 13:42:37 +00003829 }
drh3fbb0222014-09-24 19:47:27 +00003830 if( wrFlag ){
3831 allocateTempSpace(pBt);
3832 if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM;
3833 }
drhb1299152010-03-30 22:58:33 +00003834 if( iTable==1 && btreePagecount(pBt)==0 ){
dana205a482011-08-27 18:48:57 +00003835 assert( wrFlag==0 );
3836 iTable = 0;
danielk19773e8add92009-07-04 17:16:00 +00003837 }
danielk1977aef0bf62005-12-30 16:28:01 +00003838
danielk1977aef0bf62005-12-30 16:28:01 +00003839 /* Now that no other errors can occur, finish filling in the BtCursor
danielk19773e8add92009-07-04 17:16:00 +00003840 ** variables and link the cursor into the BtShared list. */
danielk1977172114a2009-07-07 15:47:12 +00003841 pCur->pgnoRoot = (Pgno)iTable;
3842 pCur->iPage = -1;
drh1e968a02008-03-25 00:22:21 +00003843 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00003844 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00003845 pCur->pBt = pBt;
drh4c417182014-03-31 23:57:41 +00003846 assert( wrFlag==0 || wrFlag==BTCF_WriteFlag );
3847 pCur->curFlags = wrFlag;
drha059ad02001-04-17 20:09:11 +00003848 pCur->pNext = pBt->pCursor;
3849 if( pCur->pNext ){
3850 pCur->pNext->pPrev = pCur;
3851 }
3852 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00003853 pCur->eState = CURSOR_INVALID;
danielk1977aef0bf62005-12-30 16:28:01 +00003854 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003855}
drhd677b3d2007-08-20 22:48:41 +00003856int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00003857 Btree *p, /* The btree */
3858 int iTable, /* Root page of table to open */
3859 int wrFlag, /* 1 to write. 0 read-only */
3860 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
3861 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00003862){
3863 int rc;
3864 sqlite3BtreeEnter(p);
danielk1977cd3e8f72008-03-25 09:47:35 +00003865 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
drhd677b3d2007-08-20 22:48:41 +00003866 sqlite3BtreeLeave(p);
3867 return rc;
3868}
drh7f751222009-03-17 22:33:00 +00003869
3870/*
3871** Return the size of a BtCursor object in bytes.
3872**
3873** This interfaces is needed so that users of cursors can preallocate
3874** sufficient storage to hold a cursor. The BtCursor object is opaque
3875** to users so they cannot do the sizeof() themselves - they must call
3876** this routine.
3877*/
3878int sqlite3BtreeCursorSize(void){
drhc54055b2009-11-13 17:05:53 +00003879 return ROUND8(sizeof(BtCursor));
danielk1977cd3e8f72008-03-25 09:47:35 +00003880}
3881
drh7f751222009-03-17 22:33:00 +00003882/*
drhf25a5072009-11-18 23:01:25 +00003883** Initialize memory that will be converted into a BtCursor object.
3884**
3885** The simple approach here would be to memset() the entire object
3886** to zero. But it turns out that the apPage[] and aiIdx[] arrays
3887** do not need to be zeroed and they are large, so we can save a lot
3888** of run-time by skipping the initialization of those elements.
3889*/
3890void sqlite3BtreeCursorZero(BtCursor *p){
3891 memset(p, 0, offsetof(BtCursor, iPage));
3892}
3893
3894/*
drh5e00f6c2001-09-13 13:46:56 +00003895** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00003896** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00003897*/
drh3aac2dd2004-04-26 14:10:20 +00003898int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00003899 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00003900 if( pBtree ){
danielk197771d5d2c2008-09-29 11:49:47 +00003901 int i;
danielk1977cd3e8f72008-03-25 09:47:35 +00003902 BtShared *pBt = pCur->pBt;
3903 sqlite3BtreeEnter(pBtree);
danielk1977be51a652008-10-08 17:58:48 +00003904 sqlite3BtreeClearCursor(pCur);
danielk1977cd3e8f72008-03-25 09:47:35 +00003905 if( pCur->pPrev ){
3906 pCur->pPrev->pNext = pCur->pNext;
3907 }else{
3908 pBt->pCursor = pCur->pNext;
3909 }
3910 if( pCur->pNext ){
3911 pCur->pNext->pPrev = pCur->pPrev;
3912 }
danielk197771d5d2c2008-09-29 11:49:47 +00003913 for(i=0; i<=pCur->iPage; i++){
3914 releasePage(pCur->apPage[i]);
3915 }
danielk1977cd3e8f72008-03-25 09:47:35 +00003916 unlockBtreeIfUnused(pBt);
dan85753662014-12-11 16:38:18 +00003917 sqlite3_free(pCur->aOverflow);
danielk1977cd3e8f72008-03-25 09:47:35 +00003918 /* sqlite3_free(pCur); */
3919 sqlite3BtreeLeave(pBtree);
drha059ad02001-04-17 20:09:11 +00003920 }
drh8c42ca92001-06-22 19:15:00 +00003921 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003922}
3923
drh5e2f8b92001-05-28 00:41:15 +00003924/*
drh86057612007-06-26 01:04:48 +00003925** Make sure the BtCursor* given in the argument has a valid
3926** BtCursor.info structure. If it is not already valid, call
danielk197730548662009-07-09 05:07:37 +00003927** btreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00003928**
3929** BtCursor.info is a cache of the information in the current cell.
danielk197730548662009-07-09 05:07:37 +00003930** Using this cache reduces the number of calls to btreeParseCell().
drh86057612007-06-26 01:04:48 +00003931**
3932** 2007-06-25: There is a bug in some versions of MSVC that cause the
3933** compiler to crash when getCellInfo() is implemented as a macro.
3934** But there is a measureable speed advantage to using the macro on gcc
3935** (when less compiler optimizations like -Os or -O0 are used and the
peter.d.reid60ec9142014-09-06 16:39:46 +00003936** compiler is not doing aggressive inlining.) So we use a real function
drh86057612007-06-26 01:04:48 +00003937** for MSVC and a macro for everything else. Ticket #2457.
drh9188b382004-05-14 21:12:22 +00003938*/
drh9188b382004-05-14 21:12:22 +00003939#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00003940 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00003941 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00003942 int iPage = pCur->iPage;
drh51c6d962004-06-06 00:42:25 +00003943 memset(&info, 0, sizeof(info));
danielk197730548662009-07-09 05:07:37 +00003944 btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
dan7df42ab2014-01-20 18:25:44 +00003945 assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00003946 }
danielk19771cc5ed82007-05-16 17:28:43 +00003947#else
3948 #define assertCellInfo(x)
3949#endif
drh86057612007-06-26 01:04:48 +00003950#ifdef _MSC_VER
3951 /* Use a real function in MSVC to work around bugs in that compiler. */
3952 static void getCellInfo(BtCursor *pCur){
3953 if( pCur->info.nSize==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003954 int iPage = pCur->iPage;
danielk197730548662009-07-09 05:07:37 +00003955 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
drh036dbec2014-03-11 23:40:44 +00003956 pCur->curFlags |= BTCF_ValidNKey;
drh86057612007-06-26 01:04:48 +00003957 }else{
3958 assertCellInfo(pCur);
3959 }
3960 }
3961#else /* if not _MSC_VER */
3962 /* Use a macro in all other compilers so that the function is inlined */
danielk197771d5d2c2008-09-29 11:49:47 +00003963#define getCellInfo(pCur) \
3964 if( pCur->info.nSize==0 ){ \
3965 int iPage = pCur->iPage; \
drh036dbec2014-03-11 23:40:44 +00003966 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
3967 pCur->curFlags |= BTCF_ValidNKey; \
danielk197771d5d2c2008-09-29 11:49:47 +00003968 }else{ \
3969 assertCellInfo(pCur); \
drh86057612007-06-26 01:04:48 +00003970 }
3971#endif /* _MSC_VER */
drh9188b382004-05-14 21:12:22 +00003972
drhea8ffdf2009-07-22 00:35:23 +00003973#ifndef NDEBUG /* The next routine used only within assert() statements */
3974/*
3975** Return true if the given BtCursor is valid. A valid cursor is one
3976** that is currently pointing to a row in a (non-empty) table.
3977** This is a verification routine is used only within assert() statements.
3978*/
3979int sqlite3BtreeCursorIsValid(BtCursor *pCur){
3980 return pCur && pCur->eState==CURSOR_VALID;
3981}
3982#endif /* NDEBUG */
3983
drh9188b382004-05-14 21:12:22 +00003984/*
drh3aac2dd2004-04-26 14:10:20 +00003985** Set *pSize to the size of the buffer needed to hold the value of
3986** the key for the current entry. If the cursor is not pointing
3987** to a valid entry, *pSize is set to 0.
3988**
drh4b70f112004-05-02 21:12:19 +00003989** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00003990** itself, not the number of bytes in the key.
drhea8ffdf2009-07-22 00:35:23 +00003991**
3992** The caller must position the cursor prior to invoking this routine.
3993**
3994** This routine cannot fail. It always returns SQLITE_OK.
drh7e3b0a02001-04-28 16:52:40 +00003995*/
drh4a1c3802004-05-12 15:15:47 +00003996int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drh1fee73e2007-08-29 04:00:57 +00003997 assert( cursorHoldsMutex(pCur) );
drhc5352b92014-11-17 20:33:07 +00003998 assert( pCur->eState==CURSOR_VALID );
3999 getCellInfo(pCur);
4000 *pSize = pCur->info.nKey;
drhea8ffdf2009-07-22 00:35:23 +00004001 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00004002}
drh2af926b2001-05-15 00:39:25 +00004003
drh72f82862001-05-24 21:06:34 +00004004/*
drh0e1c19e2004-05-11 00:58:56 +00004005** Set *pSize to the number of bytes of data in the entry the
drhea8ffdf2009-07-22 00:35:23 +00004006** cursor currently points to.
4007**
4008** The caller must guarantee that the cursor is pointing to a non-NULL
4009** valid entry. In other words, the calling procedure must guarantee
4010** that the cursor has Cursor.eState==CURSOR_VALID.
4011**
4012** Failure is not possible. This function always returns SQLITE_OK.
4013** It might just as well be a procedure (returning void) but we continue
4014** to return an integer result code for historical reasons.
drh0e1c19e2004-05-11 00:58:56 +00004015*/
4016int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drh1fee73e2007-08-29 04:00:57 +00004017 assert( cursorHoldsMutex(pCur) );
drhea8ffdf2009-07-22 00:35:23 +00004018 assert( pCur->eState==CURSOR_VALID );
drh3e28ff52014-09-24 00:59:08 +00004019 assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 );
drhea8ffdf2009-07-22 00:35:23 +00004020 getCellInfo(pCur);
drhab1cc582014-09-23 21:25:19 +00004021 *pSize = pCur->info.nPayload;
drhea8ffdf2009-07-22 00:35:23 +00004022 return SQLITE_OK;
drh0e1c19e2004-05-11 00:58:56 +00004023}
4024
4025/*
danielk1977d04417962007-05-02 13:16:30 +00004026** Given the page number of an overflow page in the database (parameter
4027** ovfl), this function finds the page number of the next page in the
4028** linked list of overflow pages. If possible, it uses the auto-vacuum
4029** pointer-map data instead of reading the content of page ovfl to do so.
4030**
4031** If an error occurs an SQLite error code is returned. Otherwise:
4032**
danielk1977bea2a942009-01-20 17:06:27 +00004033** The page number of the next overflow page in the linked list is
4034** written to *pPgnoNext. If page ovfl is the last page in its linked
4035** list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00004036**
danielk1977bea2a942009-01-20 17:06:27 +00004037** If ppPage is not NULL, and a reference to the MemPage object corresponding
4038** to page number pOvfl was obtained, then *ppPage is set to point to that
4039** reference. It is the responsibility of the caller to call releasePage()
4040** on *ppPage to free the reference. In no reference was obtained (because
4041** the pointer-map was used to obtain the value for *pPgnoNext), then
4042** *ppPage is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00004043*/
4044static int getOverflowPage(
drhfa3be902009-07-07 02:44:07 +00004045 BtShared *pBt, /* The database file */
4046 Pgno ovfl, /* Current overflow page number */
danielk1977bea2a942009-01-20 17:06:27 +00004047 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
danielk1977d04417962007-05-02 13:16:30 +00004048 Pgno *pPgnoNext /* OUT: Next overflow page number */
4049){
4050 Pgno next = 0;
danielk1977bea2a942009-01-20 17:06:27 +00004051 MemPage *pPage = 0;
drh1bd10f82008-12-10 21:19:56 +00004052 int rc = SQLITE_OK;
danielk1977d04417962007-05-02 13:16:30 +00004053
drh1fee73e2007-08-29 04:00:57 +00004054 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bea2a942009-01-20 17:06:27 +00004055 assert(pPgnoNext);
danielk1977d04417962007-05-02 13:16:30 +00004056
4057#ifndef SQLITE_OMIT_AUTOVACUUM
4058 /* Try to find the next page in the overflow list using the
4059 ** autovacuum pointer-map pages. Guess that the next page in
4060 ** the overflow list is page number (ovfl+1). If that guess turns
4061 ** out to be wrong, fall back to loading the data of page
4062 ** number ovfl to determine the next page number.
4063 */
4064 if( pBt->autoVacuum ){
4065 Pgno pgno;
4066 Pgno iGuess = ovfl+1;
4067 u8 eType;
4068
4069 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
4070 iGuess++;
4071 }
4072
drhb1299152010-03-30 22:58:33 +00004073 if( iGuess<=btreePagecount(pBt) ){
danielk1977d04417962007-05-02 13:16:30 +00004074 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
danielk1977bea2a942009-01-20 17:06:27 +00004075 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
danielk1977d04417962007-05-02 13:16:30 +00004076 next = iGuess;
danielk1977bea2a942009-01-20 17:06:27 +00004077 rc = SQLITE_DONE;
danielk1977d04417962007-05-02 13:16:30 +00004078 }
4079 }
4080 }
4081#endif
4082
danielk1977d8a3f3d2009-07-11 11:45:23 +00004083 assert( next==0 || rc==SQLITE_DONE );
danielk1977bea2a942009-01-20 17:06:27 +00004084 if( rc==SQLITE_OK ){
drhb00fc3b2013-08-21 23:42:32 +00004085 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
danielk1977d8a3f3d2009-07-11 11:45:23 +00004086 assert( rc==SQLITE_OK || pPage==0 );
4087 if( rc==SQLITE_OK ){
danielk1977d04417962007-05-02 13:16:30 +00004088 next = get4byte(pPage->aData);
4089 }
danielk1977443c0592009-01-16 15:21:05 +00004090 }
danielk197745d68822009-01-16 16:23:38 +00004091
danielk1977bea2a942009-01-20 17:06:27 +00004092 *pPgnoNext = next;
4093 if( ppPage ){
4094 *ppPage = pPage;
4095 }else{
4096 releasePage(pPage);
4097 }
4098 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
danielk1977d04417962007-05-02 13:16:30 +00004099}
4100
danielk1977da107192007-05-04 08:32:13 +00004101/*
4102** Copy data from a buffer to a page, or from a page to a buffer.
4103**
4104** pPayload is a pointer to data stored on database page pDbPage.
4105** If argument eOp is false, then nByte bytes of data are copied
4106** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4107** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4108** of data are copied from the buffer pBuf to pPayload.
4109**
4110** SQLITE_OK is returned on success, otherwise an error code.
4111*/
4112static int copyPayload(
4113 void *pPayload, /* Pointer to page data */
4114 void *pBuf, /* Pointer to buffer */
4115 int nByte, /* Number of bytes to copy */
4116 int eOp, /* 0 -> copy from page, 1 -> copy to page */
4117 DbPage *pDbPage /* Page containing pPayload */
4118){
4119 if( eOp ){
4120 /* Copy data from buffer to page (a write operation) */
4121 int rc = sqlite3PagerWrite(pDbPage);
4122 if( rc!=SQLITE_OK ){
4123 return rc;
4124 }
4125 memcpy(pPayload, pBuf, nByte);
4126 }else{
4127 /* Copy data from page to buffer (a read operation) */
4128 memcpy(pBuf, pPayload, nByte);
4129 }
4130 return SQLITE_OK;
4131}
danielk1977d04417962007-05-02 13:16:30 +00004132
4133/*
danielk19779f8d6402007-05-02 17:48:45 +00004134** This function is used to read or overwrite payload information
dan5a500af2014-03-11 20:33:04 +00004135** for the entry that the pCur cursor is pointing to. The eOp
4136** argument is interpreted as follows:
4137**
4138** 0: The operation is a read. Populate the overflow cache.
4139** 1: The operation is a write. Populate the overflow cache.
4140** 2: The operation is a read. Do not populate the overflow cache.
danielk19779f8d6402007-05-02 17:48:45 +00004141**
4142** A total of "amt" bytes are read or written beginning at "offset".
4143** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00004144**
drh3bcdfd22009-07-12 02:32:21 +00004145** The content being read or written might appear on the main page
4146** or be scattered out on multiple overflow pages.
danielk1977da107192007-05-04 08:32:13 +00004147**
dan5a500af2014-03-11 20:33:04 +00004148** If the current cursor entry uses one or more overflow pages and the
4149** eOp argument is not 2, this function may allocate space for and lazily
peter.d.reid60ec9142014-09-06 16:39:46 +00004150** populates the overflow page-list cache array (BtCursor.aOverflow).
dan5a500af2014-03-11 20:33:04 +00004151** Subsequent calls use this cache to make seeking to the supplied offset
4152** more efficient.
danielk1977da107192007-05-04 08:32:13 +00004153**
4154** Once an overflow page-list cache has been allocated, it may be
4155** invalidated if some other cursor writes to the same table, or if
4156** the cursor is moved to a different row. Additionally, in auto-vacuum
4157** mode, the following events may invalidate an overflow page-list cache.
4158**
4159** * An incremental vacuum,
4160** * A commit in auto_vacuum="full" mode,
4161** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00004162*/
danielk19779f8d6402007-05-02 17:48:45 +00004163static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00004164 BtCursor *pCur, /* Cursor pointing to entry to read from */
danielk197789d40042008-11-17 14:20:56 +00004165 u32 offset, /* Begin reading this far into payload */
4166 u32 amt, /* Read this many bytes */
drh3aac2dd2004-04-26 14:10:20 +00004167 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00004168 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00004169){
4170 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00004171 int rc = SQLITE_OK;
danielk19772dec9702007-05-02 16:48:37 +00004172 int iIdx = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004173 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
danielk19770d065412008-11-12 18:21:36 +00004174 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
drh4c417182014-03-31 23:57:41 +00004175#ifdef SQLITE_DIRECT_OVERFLOW_READ
dan9501a642014-10-01 12:01:10 +00004176 unsigned char * const pBufStart = pBuf;
drh3f387402014-09-24 01:23:00 +00004177 int bEnd; /* True if reading to end of data */
drh4c417182014-03-31 23:57:41 +00004178#endif
drh3aac2dd2004-04-26 14:10:20 +00004179
danielk1977da107192007-05-04 08:32:13 +00004180 assert( pPage );
danielk1977da184232006-01-05 11:34:32 +00004181 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004182 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh1fee73e2007-08-29 04:00:57 +00004183 assert( cursorHoldsMutex(pCur) );
drh3f387402014-09-24 01:23:00 +00004184 assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */
danielk1977da107192007-05-04 08:32:13 +00004185
drh86057612007-06-26 01:04:48 +00004186 getCellInfo(pCur);
drhab1cc582014-09-23 21:25:19 +00004187 aPayload = pCur->info.pPayload;
drh4c417182014-03-31 23:57:41 +00004188#ifdef SQLITE_DIRECT_OVERFLOW_READ
drhab1cc582014-09-23 21:25:19 +00004189 bEnd = offset+amt==pCur->info.nPayload;
drh4c417182014-03-31 23:57:41 +00004190#endif
drhab1cc582014-09-23 21:25:19 +00004191 assert( offset+amt <= pCur->info.nPayload );
danielk1977da107192007-05-04 08:32:13 +00004192
drhab1cc582014-09-23 21:25:19 +00004193 if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){
danielk1977da107192007-05-04 08:32:13 +00004194 /* Trying to read or write past the end of the data is an error */
danielk197767fd7a92008-09-10 17:53:35 +00004195 return SQLITE_CORRUPT_BKPT;
drh3aac2dd2004-04-26 14:10:20 +00004196 }
danielk1977da107192007-05-04 08:32:13 +00004197
4198 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00004199 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00004200 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00004201 if( a+offset>pCur->info.nLocal ){
4202 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00004203 }
dan5a500af2014-03-11 20:33:04 +00004204 rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00004205 offset = 0;
drha34b6762004-05-07 13:30:42 +00004206 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00004207 amt -= a;
drhdd793422001-06-28 01:54:48 +00004208 }else{
drhfa1a98a2004-05-14 19:08:17 +00004209 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00004210 }
danielk1977da107192007-05-04 08:32:13 +00004211
dan85753662014-12-11 16:38:18 +00004212
danielk1977da107192007-05-04 08:32:13 +00004213 if( rc==SQLITE_OK && amt>0 ){
danielk197789d40042008-11-17 14:20:56 +00004214 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
danielk1977da107192007-05-04 08:32:13 +00004215 Pgno nextPage;
4216
drhfa1a98a2004-05-14 19:08:17 +00004217 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00004218
drha38c9512014-04-01 01:24:34 +00004219 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
4220 ** Except, do not allocate aOverflow[] for eOp==2.
4221 **
4222 ** The aOverflow[] array is sized at one entry for each overflow page
4223 ** in the overflow chain. The page number of the first overflow page is
4224 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
4225 ** means "not yet known" (the cache is lazily populated).
danielk1977da107192007-05-04 08:32:13 +00004226 */
drh036dbec2014-03-11 23:40:44 +00004227 if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
danielk19772dec9702007-05-02 16:48:37 +00004228 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
dan5a500af2014-03-11 20:33:04 +00004229 if( nOvfl>pCur->nOvflAlloc ){
dan85753662014-12-11 16:38:18 +00004230 Pgno *aNew = (Pgno*)sqlite3Realloc(
4231 pCur->aOverflow, nOvfl*2*sizeof(Pgno)
dan5a500af2014-03-11 20:33:04 +00004232 );
4233 if( aNew==0 ){
4234 rc = SQLITE_NOMEM;
4235 }else{
4236 pCur->nOvflAlloc = nOvfl*2;
4237 pCur->aOverflow = aNew;
4238 }
4239 }
4240 if( rc==SQLITE_OK ){
4241 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
drh036dbec2014-03-11 23:40:44 +00004242 pCur->curFlags |= BTCF_ValidOvfl;
danielk19772dec9702007-05-02 16:48:37 +00004243 }
4244 }
danielk1977da107192007-05-04 08:32:13 +00004245
4246 /* If the overflow page-list cache has been allocated and the
4247 ** entry for the first required overflow page is valid, skip
4248 ** directly to it.
4249 */
drh3f387402014-09-24 01:23:00 +00004250 if( (pCur->curFlags & BTCF_ValidOvfl)!=0
4251 && pCur->aOverflow[offset/ovflSize]
4252 ){
danielk19772dec9702007-05-02 16:48:37 +00004253 iIdx = (offset/ovflSize);
4254 nextPage = pCur->aOverflow[iIdx];
4255 offset = (offset%ovflSize);
4256 }
danielk1977da107192007-05-04 08:32:13 +00004257
4258 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
4259
danielk1977da107192007-05-04 08:32:13 +00004260 /* If required, populate the overflow page-list cache. */
drh036dbec2014-03-11 23:40:44 +00004261 if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
danielk1977da107192007-05-04 08:32:13 +00004262 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
4263 pCur->aOverflow[iIdx] = nextPage;
4264 }
danielk1977da107192007-05-04 08:32:13 +00004265
danielk1977d04417962007-05-02 13:16:30 +00004266 if( offset>=ovflSize ){
4267 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00004268 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00004269 ** data is not required. So first try to lookup the overflow
4270 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00004271 ** function.
drha38c9512014-04-01 01:24:34 +00004272 **
4273 ** Note that the aOverflow[] array must be allocated because eOp!=2
4274 ** here. If eOp==2, then offset==0 and this branch is never taken.
danielk1977d04417962007-05-02 13:16:30 +00004275 */
drha38c9512014-04-01 01:24:34 +00004276 assert( eOp!=2 );
4277 assert( pCur->curFlags & BTCF_ValidOvfl );
dan85753662014-12-11 16:38:18 +00004278 assert( pCur->pBtree->db==pBt->db );
drha38c9512014-04-01 01:24:34 +00004279 if( pCur->aOverflow[iIdx+1] ){
danielk1977da107192007-05-04 08:32:13 +00004280 nextPage = pCur->aOverflow[iIdx+1];
drha38c9512014-04-01 01:24:34 +00004281 }else{
danielk1977da107192007-05-04 08:32:13 +00004282 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
drha38c9512014-04-01 01:24:34 +00004283 }
danielk1977da107192007-05-04 08:32:13 +00004284 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00004285 }else{
danielk19779f8d6402007-05-02 17:48:45 +00004286 /* Need to read this page properly. It contains some of the
4287 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00004288 */
danf4ba1092011-10-08 14:57:07 +00004289#ifdef SQLITE_DIRECT_OVERFLOW_READ
4290 sqlite3_file *fd;
4291#endif
danielk1977cfe9a692004-06-16 12:00:29 +00004292 int a = amt;
danf4ba1092011-10-08 14:57:07 +00004293 if( a + offset > ovflSize ){
4294 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00004295 }
danf4ba1092011-10-08 14:57:07 +00004296
4297#ifdef SQLITE_DIRECT_OVERFLOW_READ
4298 /* If all the following are true:
4299 **
4300 ** 1) this is a read operation, and
4301 ** 2) data is required from the start of this overflow page, and
4302 ** 3) the database is file-backed, and
4303 ** 4) there is no open write-transaction, and
4304 ** 5) the database is not a WAL database,
dan9bc21b52014-03-20 18:56:35 +00004305 ** 6) all data from the page is being read.
dan9501a642014-10-01 12:01:10 +00004306 ** 7) at least 4 bytes have already been read into the output buffer
danf4ba1092011-10-08 14:57:07 +00004307 **
4308 ** then data can be read directly from the database file into the
4309 ** output buffer, bypassing the page-cache altogether. This speeds
4310 ** up loading large records that span many overflow pages.
4311 */
dan5a500af2014-03-11 20:33:04 +00004312 if( (eOp&0x01)==0 /* (1) */
danf4ba1092011-10-08 14:57:07 +00004313 && offset==0 /* (2) */
dan9bc21b52014-03-20 18:56:35 +00004314 && (bEnd || a==ovflSize) /* (6) */
danf4ba1092011-10-08 14:57:07 +00004315 && pBt->inTransaction==TRANS_READ /* (4) */
4316 && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
4317 && pBt->pPage1->aData[19]==0x01 /* (5) */
dan9501a642014-10-01 12:01:10 +00004318 && &pBuf[-4]>=pBufStart /* (7) */
danf4ba1092011-10-08 14:57:07 +00004319 ){
4320 u8 aSave[4];
4321 u8 *aWrite = &pBuf[-4];
dan9501a642014-10-01 12:01:10 +00004322 assert( aWrite>=pBufStart ); /* hence (7) */
danf4ba1092011-10-08 14:57:07 +00004323 memcpy(aSave, aWrite, 4);
dan27d47fb2011-12-21 17:00:16 +00004324 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
danf4ba1092011-10-08 14:57:07 +00004325 nextPage = get4byte(aWrite);
4326 memcpy(aWrite, aSave, 4);
4327 }else
4328#endif
4329
4330 {
4331 DbPage *pDbPage;
dan11dcd112013-03-15 18:29:18 +00004332 rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
dan5a500af2014-03-11 20:33:04 +00004333 ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
dan11dcd112013-03-15 18:29:18 +00004334 );
danf4ba1092011-10-08 14:57:07 +00004335 if( rc==SQLITE_OK ){
4336 aPayload = sqlite3PagerGetData(pDbPage);
4337 nextPage = get4byte(aPayload);
dan5a500af2014-03-11 20:33:04 +00004338 rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
danf4ba1092011-10-08 14:57:07 +00004339 sqlite3PagerUnref(pDbPage);
4340 offset = 0;
4341 }
4342 }
4343 amt -= a;
4344 pBuf += a;
danielk1977cfe9a692004-06-16 12:00:29 +00004345 }
drh2af926b2001-05-15 00:39:25 +00004346 }
drh2af926b2001-05-15 00:39:25 +00004347 }
danielk1977cfe9a692004-06-16 12:00:29 +00004348
danielk1977da107192007-05-04 08:32:13 +00004349 if( rc==SQLITE_OK && amt>0 ){
drh49285702005-09-17 15:20:26 +00004350 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00004351 }
danielk1977da107192007-05-04 08:32:13 +00004352 return rc;
drh2af926b2001-05-15 00:39:25 +00004353}
4354
drh72f82862001-05-24 21:06:34 +00004355/*
drh3aac2dd2004-04-26 14:10:20 +00004356** Read part of the key associated with cursor pCur. Exactly
peter.d.reid60ec9142014-09-06 16:39:46 +00004357** "amt" bytes will be transferred into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00004358** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00004359**
drh5d1a8722009-07-22 18:07:40 +00004360** The caller must ensure that pCur is pointing to a valid row
4361** in the table.
4362**
drh3aac2dd2004-04-26 14:10:20 +00004363** Return SQLITE_OK on success or an error code if anything goes
4364** wrong. An error is returned if "offset+amt" is larger than
4365** the available payload.
drh72f82862001-05-24 21:06:34 +00004366*/
drha34b6762004-05-07 13:30:42 +00004367int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drh1fee73e2007-08-29 04:00:57 +00004368 assert( cursorHoldsMutex(pCur) );
drh5d1a8722009-07-22 18:07:40 +00004369 assert( pCur->eState==CURSOR_VALID );
4370 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
4371 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
4372 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
drh3aac2dd2004-04-26 14:10:20 +00004373}
4374
4375/*
drh3aac2dd2004-04-26 14:10:20 +00004376** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00004377** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00004378** begins at "offset".
4379**
4380** Return SQLITE_OK on success or an error code if anything goes
4381** wrong. An error is returned if "offset+amt" is larger than
4382** the available payload.
drh72f82862001-05-24 21:06:34 +00004383*/
drh3aac2dd2004-04-26 14:10:20 +00004384int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00004385 int rc;
4386
danielk19773588ceb2008-06-10 17:30:26 +00004387#ifndef SQLITE_OMIT_INCRBLOB
4388 if ( pCur->eState==CURSOR_INVALID ){
4389 return SQLITE_ABORT;
4390 }
4391#endif
4392
drh1fee73e2007-08-29 04:00:57 +00004393 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004394 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004395 if( rc==SQLITE_OK ){
4396 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004397 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
4398 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drhfb192682009-07-11 18:26:28 +00004399 rc = accessPayload(pCur, offset, amt, pBuf, 0);
danielk1977da184232006-01-05 11:34:32 +00004400 }
4401 return rc;
drh2af926b2001-05-15 00:39:25 +00004402}
4403
drh72f82862001-05-24 21:06:34 +00004404/*
drh0e1c19e2004-05-11 00:58:56 +00004405** Return a pointer to payload information from the entry that the
4406** pCur cursor is pointing to. The pointer is to the beginning of
drh2a8d2262013-12-09 20:43:22 +00004407** the key if index btrees (pPage->intKey==0) and is the data for
4408** table btrees (pPage->intKey==1). The number of bytes of available
4409** key/data is written into *pAmt. If *pAmt==0, then the value
4410** returned will not be a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00004411**
4412** This routine is an optimization. It is common for the entire key
4413** and data to fit on the local page and for there to be no overflow
4414** pages. When that is so, this routine can be used to access the
4415** key and data without making a copy. If the key and/or data spills
drh7f751222009-03-17 22:33:00 +00004416** onto overflow pages, then accessPayload() must be used to reassemble
drh0e1c19e2004-05-11 00:58:56 +00004417** the key/data and copy it into a preallocated buffer.
4418**
4419** The pointer returned by this routine looks directly into the cached
4420** page of the database. The data might change or move the next time
4421** any btree routine is called.
4422*/
drh2a8d2262013-12-09 20:43:22 +00004423static const void *fetchPayload(
drh0e1c19e2004-05-11 00:58:56 +00004424 BtCursor *pCur, /* Cursor pointing to entry to read from */
drh2a8d2262013-12-09 20:43:22 +00004425 u32 *pAmt /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00004426){
danielk197771d5d2c2008-09-29 11:49:47 +00004427 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
danielk1977da184232006-01-05 11:34:32 +00004428 assert( pCur->eState==CURSOR_VALID );
drh2a8d2262013-12-09 20:43:22 +00004429 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh1fee73e2007-08-29 04:00:57 +00004430 assert( cursorHoldsMutex(pCur) );
drh2a8d2262013-12-09 20:43:22 +00004431 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh86dd3712014-03-25 11:00:21 +00004432 assert( pCur->info.nSize>0 );
drh2a8d2262013-12-09 20:43:22 +00004433 *pAmt = pCur->info.nLocal;
drhab1cc582014-09-23 21:25:19 +00004434 return (void*)pCur->info.pPayload;
drh0e1c19e2004-05-11 00:58:56 +00004435}
4436
4437
4438/*
drhe51c44f2004-05-30 20:46:09 +00004439** For the entry that cursor pCur is point to, return as
4440** many bytes of the key or data as are available on the local
4441** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00004442**
4443** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00004444** or be destroyed on the next call to any Btree routine,
4445** including calls from other threads against the same cache.
4446** Hence, a mutex on the BtShared should be held prior to calling
4447** this routine.
drh0e1c19e2004-05-11 00:58:56 +00004448**
4449** These routines is used to get quick access to key and data
4450** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00004451*/
drh501932c2013-11-21 21:59:53 +00004452const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
drh2a8d2262013-12-09 20:43:22 +00004453 return fetchPayload(pCur, pAmt);
drh0e1c19e2004-05-11 00:58:56 +00004454}
drh501932c2013-11-21 21:59:53 +00004455const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
drh2a8d2262013-12-09 20:43:22 +00004456 return fetchPayload(pCur, pAmt);
drh0e1c19e2004-05-11 00:58:56 +00004457}
4458
4459
4460/*
drh8178a752003-01-05 21:41:40 +00004461** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00004462** page number of the child page to move to.
danielk1977a299d612009-07-13 11:22:10 +00004463**
4464** This function returns SQLITE_CORRUPT if the page-header flags field of
4465** the new child page does not match the flags field of the parent (i.e.
4466** if an intkey page appears to be the parent of a non-intkey page, or
4467** vice-versa).
drh72f82862001-05-24 21:06:34 +00004468*/
drh3aac2dd2004-04-26 14:10:20 +00004469static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00004470 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00004471 int i = pCur->iPage;
drh72f82862001-05-24 21:06:34 +00004472 MemPage *pNewPage;
drhd0679ed2007-08-28 22:24:34 +00004473 BtShared *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00004474
drh1fee73e2007-08-29 04:00:57 +00004475 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004476 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004477 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
dan11dcd112013-03-15 18:29:18 +00004478 assert( pCur->iPage>=0 );
danielk197771d5d2c2008-09-29 11:49:47 +00004479 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
4480 return SQLITE_CORRUPT_BKPT;
4481 }
drhb00fc3b2013-08-21 23:42:32 +00004482 rc = getAndInitPage(pBt, newPgno, &pNewPage,
drh036dbec2014-03-11 23:40:44 +00004483 (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
drh6019e162001-07-02 17:51:45 +00004484 if( rc ) return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00004485 pCur->apPage[i+1] = pNewPage;
4486 pCur->aiIdx[i+1] = 0;
4487 pCur->iPage++;
4488
drh271efa52004-05-30 19:19:05 +00004489 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004490 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
danielk1977bd5969a2009-07-11 17:39:42 +00004491 if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
drh49285702005-09-17 15:20:26 +00004492 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00004493 }
drh72f82862001-05-24 21:06:34 +00004494 return SQLITE_OK;
4495}
4496
danbb246c42012-01-12 14:25:55 +00004497#if 0
danielk1977bf93c562008-09-29 15:53:25 +00004498/*
4499** Page pParent is an internal (non-leaf) tree page. This function
4500** asserts that page number iChild is the left-child if the iIdx'th
4501** cell in page pParent. Or, if iIdx is equal to the total number of
4502** cells in pParent, that page number iChild is the right-child of
4503** the page.
4504*/
4505static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
4506 assert( iIdx<=pParent->nCell );
4507 if( iIdx==pParent->nCell ){
4508 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
4509 }else{
4510 assert( get4byte(findCell(pParent, iIdx))==iChild );
4511 }
4512}
4513#else
4514# define assertParentIndex(x,y,z)
4515#endif
4516
drh72f82862001-05-24 21:06:34 +00004517/*
drh5e2f8b92001-05-28 00:41:15 +00004518** Move the cursor up to the parent page.
4519**
4520** pCur->idx is set to the cell index that contains the pointer
4521** to the page we are coming from. If we are coming from the
4522** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00004523** the largest cell index.
drh72f82862001-05-24 21:06:34 +00004524*/
danielk197730548662009-07-09 05:07:37 +00004525static void moveToParent(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00004526 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004527 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004528 assert( pCur->iPage>0 );
4529 assert( pCur->apPage[pCur->iPage] );
danbb246c42012-01-12 14:25:55 +00004530
4531 /* UPDATE: It is actually possible for the condition tested by the assert
4532 ** below to be untrue if the database file is corrupt. This can occur if
4533 ** one cursor has modified page pParent while a reference to it is held
4534 ** by a second cursor. Which can only happen if a single page is linked
4535 ** into more than one b-tree structure in a corrupt database. */
4536#if 0
danielk1977bf93c562008-09-29 15:53:25 +00004537 assertParentIndex(
4538 pCur->apPage[pCur->iPage-1],
4539 pCur->aiIdx[pCur->iPage-1],
4540 pCur->apPage[pCur->iPage]->pgno
4541 );
danbb246c42012-01-12 14:25:55 +00004542#endif
dan6c2688c2012-01-12 15:05:03 +00004543 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
danbb246c42012-01-12 14:25:55 +00004544
danielk197771d5d2c2008-09-29 11:49:47 +00004545 releasePage(pCur->apPage[pCur->iPage]);
4546 pCur->iPage--;
drh271efa52004-05-30 19:19:05 +00004547 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004548 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
drh72f82862001-05-24 21:06:34 +00004549}
4550
4551/*
danielk19778f880a82009-07-13 09:41:45 +00004552** Move the cursor to point to the root page of its b-tree structure.
4553**
4554** If the table has a virtual root page, then the cursor is moved to point
4555** to the virtual root page instead of the actual root page. A table has a
4556** virtual root page when the actual root page contains no cells and a
4557** single child page. This can only happen with the table rooted at page 1.
4558**
4559** If the b-tree structure is empty, the cursor state is set to
4560** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
4561** cell located on the root (or virtual root) page and the cursor state
4562** is set to CURSOR_VALID.
4563**
4564** If this function returns successfully, it may be assumed that the
4565** page-header flags indicate that the [virtual] root-page is the expected
4566** kind of b-tree page (i.e. if when opening the cursor the caller did not
4567** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
4568** indicating a table b-tree, or if the caller did specify a KeyInfo
4569** structure the flags byte is set to 0x02 or 0x0A, indicating an index
4570** b-tree).
drh72f82862001-05-24 21:06:34 +00004571*/
drh5e2f8b92001-05-28 00:41:15 +00004572static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00004573 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00004574 int rc = SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00004575
drh1fee73e2007-08-29 04:00:57 +00004576 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +00004577 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
4578 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
4579 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
4580 if( pCur->eState>=CURSOR_REQUIRESEEK ){
4581 if( pCur->eState==CURSOR_FAULT ){
drh4c301aa2009-07-15 17:25:45 +00004582 assert( pCur->skipNext!=SQLITE_OK );
4583 return pCur->skipNext;
drhfb982642007-08-30 01:19:59 +00004584 }
danielk1977be51a652008-10-08 17:58:48 +00004585 sqlite3BtreeClearCursor(pCur);
drhbf700f32007-03-31 02:36:44 +00004586 }
danielk197771d5d2c2008-09-29 11:49:47 +00004587
4588 if( pCur->iPage>=0 ){
drh4e8fe3f2013-12-06 23:25:27 +00004589 while( pCur->iPage ) releasePage(pCur->apPage[pCur->iPage--]);
dana205a482011-08-27 18:48:57 +00004590 }else if( pCur->pgnoRoot==0 ){
4591 pCur->eState = CURSOR_INVALID;
4592 return SQLITE_OK;
drh777e4c42006-01-13 04:31:58 +00004593 }else{
drh4e8fe3f2013-12-06 23:25:27 +00004594 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
drh036dbec2014-03-11 23:40:44 +00004595 (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
drh4c301aa2009-07-15 17:25:45 +00004596 if( rc!=SQLITE_OK ){
drh777e4c42006-01-13 04:31:58 +00004597 pCur->eState = CURSOR_INVALID;
4598 return rc;
4599 }
danielk1977172114a2009-07-07 15:47:12 +00004600 pCur->iPage = 0;
drhc39e0002004-05-07 23:50:57 +00004601 }
danielk197771d5d2c2008-09-29 11:49:47 +00004602 pRoot = pCur->apPage[0];
4603 assert( pRoot->pgno==pCur->pgnoRoot );
dan7df42ab2014-01-20 18:25:44 +00004604
4605 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
4606 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
4607 ** NULL, the caller expects a table b-tree. If this is not the case,
4608 ** return an SQLITE_CORRUPT error.
4609 **
4610 ** Earlier versions of SQLite assumed that this test could not fail
4611 ** if the root page was already loaded when this function was called (i.e.
4612 ** if pCur->iPage>=0). But this is not so if the database is corrupted
4613 ** in such a way that page pRoot is linked into a second b-tree table
4614 ** (or the freelist). */
4615 assert( pRoot->intKey==1 || pRoot->intKey==0 );
4616 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
4617 return SQLITE_CORRUPT_BKPT;
4618 }
danielk19778f880a82009-07-13 09:41:45 +00004619
danielk197771d5d2c2008-09-29 11:49:47 +00004620 pCur->aiIdx[0] = 0;
drh271efa52004-05-30 19:19:05 +00004621 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004622 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
danielk197771d5d2c2008-09-29 11:49:47 +00004623
drh4e8fe3f2013-12-06 23:25:27 +00004624 if( pRoot->nCell>0 ){
4625 pCur->eState = CURSOR_VALID;
4626 }else if( !pRoot->leaf ){
drh8856d6a2004-04-29 14:42:46 +00004627 Pgno subpage;
drhc85240d2009-06-04 16:14:33 +00004628 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
drh43605152004-05-29 21:46:49 +00004629 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
danielk1977da184232006-01-05 11:34:32 +00004630 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00004631 rc = moveToChild(pCur, subpage);
danielk197771d5d2c2008-09-29 11:49:47 +00004632 }else{
drh4e8fe3f2013-12-06 23:25:27 +00004633 pCur->eState = CURSOR_INVALID;
drh8856d6a2004-04-29 14:42:46 +00004634 }
4635 return rc;
drh72f82862001-05-24 21:06:34 +00004636}
drh2af926b2001-05-15 00:39:25 +00004637
drh5e2f8b92001-05-28 00:41:15 +00004638/*
4639** Move the cursor down to the left-most leaf entry beneath the
4640** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00004641**
4642** The left-most leaf is the one with the smallest key - the first
4643** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00004644*/
4645static int moveToLeftmost(BtCursor *pCur){
4646 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00004647 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00004648 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00004649
drh1fee73e2007-08-29 04:00:57 +00004650 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004651 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004652 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
4653 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
4654 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
drh8178a752003-01-05 21:41:40 +00004655 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00004656 }
drhd677b3d2007-08-20 22:48:41 +00004657 return rc;
drh5e2f8b92001-05-28 00:41:15 +00004658}
4659
drh2dcc9aa2002-12-04 13:40:25 +00004660/*
4661** Move the cursor down to the right-most leaf entry beneath the
4662** page to which it is currently pointing. Notice the difference
4663** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
4664** finds the left-most entry beneath the *entry* whereas moveToRightmost()
4665** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00004666**
4667** The right-most entry is the one with the largest key - the last
4668** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00004669*/
4670static int moveToRightmost(BtCursor *pCur){
4671 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00004672 int rc = SQLITE_OK;
drh1bd10f82008-12-10 21:19:56 +00004673 MemPage *pPage = 0;
drh2dcc9aa2002-12-04 13:40:25 +00004674
drh1fee73e2007-08-29 04:00:57 +00004675 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004676 assert( pCur->eState==CURSOR_VALID );
drhee6438d2014-09-01 13:29:32 +00004677 while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
drh43605152004-05-29 21:46:49 +00004678 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
danielk197771d5d2c2008-09-29 11:49:47 +00004679 pCur->aiIdx[pCur->iPage] = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00004680 rc = moveToChild(pCur, pgno);
drhee6438d2014-09-01 13:29:32 +00004681 if( rc ) return rc;
drh2dcc9aa2002-12-04 13:40:25 +00004682 }
drhee6438d2014-09-01 13:29:32 +00004683 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
4684 assert( pCur->info.nSize==0 );
4685 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
4686 return SQLITE_OK;
drh2dcc9aa2002-12-04 13:40:25 +00004687}
4688
drh5e00f6c2001-09-13 13:46:56 +00004689/* Move the cursor to the first entry in the table. Return SQLITE_OK
4690** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00004691** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00004692*/
drh3aac2dd2004-04-26 14:10:20 +00004693int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00004694 int rc;
drhd677b3d2007-08-20 22:48:41 +00004695
drh1fee73e2007-08-29 04:00:57 +00004696 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004697 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00004698 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004699 if( rc==SQLITE_OK ){
4700 if( pCur->eState==CURSOR_INVALID ){
dana205a482011-08-27 18:48:57 +00004701 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00004702 *pRes = 1;
drhd677b3d2007-08-20 22:48:41 +00004703 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004704 assert( pCur->apPage[pCur->iPage]->nCell>0 );
drhd677b3d2007-08-20 22:48:41 +00004705 *pRes = 0;
4706 rc = moveToLeftmost(pCur);
4707 }
drh5e00f6c2001-09-13 13:46:56 +00004708 }
drh5e00f6c2001-09-13 13:46:56 +00004709 return rc;
4710}
drh5e2f8b92001-05-28 00:41:15 +00004711
drh9562b552002-02-19 15:00:07 +00004712/* Move the cursor to the last entry in the table. Return SQLITE_OK
4713** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00004714** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00004715*/
drh3aac2dd2004-04-26 14:10:20 +00004716int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00004717 int rc;
drhd677b3d2007-08-20 22:48:41 +00004718
drh1fee73e2007-08-29 04:00:57 +00004719 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004720 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19773f632d52009-05-02 10:03:09 +00004721
4722 /* If the cursor already points to the last entry, this is a no-op. */
drh036dbec2014-03-11 23:40:44 +00004723 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
danielk19773f632d52009-05-02 10:03:09 +00004724#ifdef SQLITE_DEBUG
4725 /* This block serves to assert() that the cursor really does point
4726 ** to the last entry in the b-tree. */
4727 int ii;
4728 for(ii=0; ii<pCur->iPage; ii++){
4729 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
4730 }
4731 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
4732 assert( pCur->apPage[pCur->iPage]->leaf );
4733#endif
4734 return SQLITE_OK;
4735 }
4736
drh9562b552002-02-19 15:00:07 +00004737 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004738 if( rc==SQLITE_OK ){
4739 if( CURSOR_INVALID==pCur->eState ){
dana205a482011-08-27 18:48:57 +00004740 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00004741 *pRes = 1;
4742 }else{
4743 assert( pCur->eState==CURSOR_VALID );
4744 *pRes = 0;
4745 rc = moveToRightmost(pCur);
drh036dbec2014-03-11 23:40:44 +00004746 if( rc==SQLITE_OK ){
4747 pCur->curFlags |= BTCF_AtLast;
4748 }else{
4749 pCur->curFlags &= ~BTCF_AtLast;
4750 }
4751
drhd677b3d2007-08-20 22:48:41 +00004752 }
drh9562b552002-02-19 15:00:07 +00004753 }
drh9562b552002-02-19 15:00:07 +00004754 return rc;
4755}
4756
drhe14006d2008-03-25 17:23:32 +00004757/* Move the cursor so that it points to an entry near the key
drhe63d9992008-08-13 19:11:48 +00004758** specified by pIdxKey or intKey. Return a success code.
drh72f82862001-05-24 21:06:34 +00004759**
drhe63d9992008-08-13 19:11:48 +00004760** For INTKEY tables, the intKey parameter is used. pIdxKey
4761** must be NULL. For index tables, pIdxKey is used and intKey
4762** is ignored.
drh3aac2dd2004-04-26 14:10:20 +00004763**
drh5e2f8b92001-05-28 00:41:15 +00004764** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00004765** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00004766** were present. The cursor might point to an entry that comes
4767** before or after the key.
4768**
drh64022502009-01-09 14:11:04 +00004769** An integer is written into *pRes which is the result of
4770** comparing the key with the entry to which the cursor is
4771** pointing. The meaning of the integer written into
4772** *pRes is as follows:
drhbd03cae2001-06-02 02:40:57 +00004773**
4774** *pRes<0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004775** is smaller than intKey/pIdxKey or if the table is empty
drh1a844c32002-12-04 22:29:28 +00004776** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00004777**
4778** *pRes==0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004779** exactly matches intKey/pIdxKey.
drhbd03cae2001-06-02 02:40:57 +00004780**
4781** *pRes>0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004782** is larger than intKey/pIdxKey.
drhd677b3d2007-08-20 22:48:41 +00004783**
drha059ad02001-04-17 20:09:11 +00004784*/
drhe63d9992008-08-13 19:11:48 +00004785int sqlite3BtreeMovetoUnpacked(
4786 BtCursor *pCur, /* The cursor to be moved */
4787 UnpackedRecord *pIdxKey, /* Unpacked index key */
4788 i64 intKey, /* The table key */
4789 int biasRight, /* If true, bias the search to the high end */
4790 int *pRes /* Write search results here */
drhe4d90812007-03-29 05:51:49 +00004791){
drh72f82862001-05-24 21:06:34 +00004792 int rc;
dan3b9330f2014-02-27 20:44:18 +00004793 RecordCompare xRecordCompare;
drhd677b3d2007-08-20 22:48:41 +00004794
drh1fee73e2007-08-29 04:00:57 +00004795 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004796 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19775cb09632009-07-09 11:36:01 +00004797 assert( pRes );
danielk19773fd7cf52009-07-13 07:30:52 +00004798 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
drha2c20e42008-03-29 16:01:04 +00004799
4800 /* If the cursor is already positioned at the point we are trying
4801 ** to move to, then just return without doing any work */
drh036dbec2014-03-11 23:40:44 +00004802 if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
danielk197771d5d2c2008-09-29 11:49:47 +00004803 && pCur->apPage[0]->intKey
4804 ){
drhe63d9992008-08-13 19:11:48 +00004805 if( pCur->info.nKey==intKey ){
drha2c20e42008-03-29 16:01:04 +00004806 *pRes = 0;
4807 return SQLITE_OK;
4808 }
drh036dbec2014-03-11 23:40:44 +00004809 if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
drha2c20e42008-03-29 16:01:04 +00004810 *pRes = -1;
4811 return SQLITE_OK;
4812 }
4813 }
4814
dan1fed5da2014-02-25 21:01:25 +00004815 if( pIdxKey ){
4816 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
dan38fdead2014-04-01 10:19:02 +00004817 pIdxKey->errCode = 0;
dan3b9330f2014-02-27 20:44:18 +00004818 assert( pIdxKey->default_rc==1
4819 || pIdxKey->default_rc==0
4820 || pIdxKey->default_rc==-1
4821 );
drh13a747e2014-03-03 21:46:55 +00004822 }else{
drhb6e8fd12014-03-06 01:56:33 +00004823 xRecordCompare = 0; /* All keys are integers */
dan1fed5da2014-02-25 21:01:25 +00004824 }
4825
drh5e2f8b92001-05-28 00:41:15 +00004826 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004827 if( rc ){
4828 return rc;
4829 }
dana205a482011-08-27 18:48:57 +00004830 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
4831 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
4832 assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
danielk1977da184232006-01-05 11:34:32 +00004833 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00004834 *pRes = -1;
dana205a482011-08-27 18:48:57 +00004835 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
drhc39e0002004-05-07 23:50:57 +00004836 return SQLITE_OK;
4837 }
danielk197771d5d2c2008-09-29 11:49:47 +00004838 assert( pCur->apPage[0]->intKey || pIdxKey );
drh14684382006-11-30 13:05:29 +00004839 for(;;){
drhec3e6b12013-11-25 02:38:55 +00004840 int lwr, upr, idx, c;
drh72f82862001-05-24 21:06:34 +00004841 Pgno chldPg;
danielk197771d5d2c2008-09-29 11:49:47 +00004842 MemPage *pPage = pCur->apPage[pCur->iPage];
drhec3e6b12013-11-25 02:38:55 +00004843 u8 *pCell; /* Pointer to current cell in pPage */
danielk1977171fff32009-07-11 05:06:51 +00004844
4845 /* pPage->nCell must be greater than zero. If this is the root-page
4846 ** the cursor would have been INVALID above and this for(;;) loop
4847 ** not run. If this is not the root-page, then the moveToChild() routine
danielk19773fd7cf52009-07-13 07:30:52 +00004848 ** would have already detected db corruption. Similarly, pPage must
4849 ** be the right kind (index or table) of b-tree page. Otherwise
4850 ** a moveToChild() or moveToRoot() call would have detected corruption. */
danielk1977171fff32009-07-11 05:06:51 +00004851 assert( pPage->nCell>0 );
danielk19773fd7cf52009-07-13 07:30:52 +00004852 assert( pPage->intKey==(pIdxKey==0) );
drh72f82862001-05-24 21:06:34 +00004853 lwr = 0;
4854 upr = pPage->nCell-1;
drhebf10b12013-11-25 17:38:26 +00004855 assert( biasRight==0 || biasRight==1 );
4856 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
drhd793f442013-11-25 14:10:15 +00004857 pCur->aiIdx[pCur->iPage] = (u16)idx;
dana4660bd2014-03-04 16:05:25 +00004858 if( xRecordCompare==0 ){
drhec3e6b12013-11-25 02:38:55 +00004859 for(;;){
danielk197711c327a2009-05-04 19:01:26 +00004860 i64 nCellKey;
drhec3e6b12013-11-25 02:38:55 +00004861 pCell = findCell(pPage, idx) + pPage->childPtrSize;
drh3e28ff52014-09-24 00:59:08 +00004862 if( pPage->intKeyLeaf ){
drh9b2fc612013-11-25 20:14:13 +00004863 while( 0x80 <= *(pCell++) ){
4864 if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
4865 }
drhd172f862006-01-12 15:01:15 +00004866 }
drha2c20e42008-03-29 16:01:04 +00004867 getVarint(pCell, (u64*)&nCellKey);
drhbb933ef2013-11-25 15:01:38 +00004868 if( nCellKey<intKey ){
4869 lwr = idx+1;
4870 if( lwr>upr ){ c = -1; break; }
4871 }else if( nCellKey>intKey ){
4872 upr = idx-1;
4873 if( lwr>upr ){ c = +1; break; }
4874 }else{
4875 assert( nCellKey==intKey );
drh036dbec2014-03-11 23:40:44 +00004876 pCur->curFlags |= BTCF_ValidNKey;
drhec3e6b12013-11-25 02:38:55 +00004877 pCur->info.nKey = nCellKey;
drhd793f442013-11-25 14:10:15 +00004878 pCur->aiIdx[pCur->iPage] = (u16)idx;
drhec3e6b12013-11-25 02:38:55 +00004879 if( !pPage->leaf ){
4880 lwr = idx;
drhebf10b12013-11-25 17:38:26 +00004881 goto moveto_next_layer;
drhec3e6b12013-11-25 02:38:55 +00004882 }else{
4883 *pRes = 0;
4884 rc = SQLITE_OK;
4885 goto moveto_finish;
4886 }
drhd793f442013-11-25 14:10:15 +00004887 }
drhebf10b12013-11-25 17:38:26 +00004888 assert( lwr+upr>=0 );
4889 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
drhec3e6b12013-11-25 02:38:55 +00004890 }
4891 }else{
4892 for(;;){
4893 int nCell;
drhec3e6b12013-11-25 02:38:55 +00004894 pCell = findCell(pPage, idx) + pPage->childPtrSize;
4895
drhb2eced52010-08-12 02:41:12 +00004896 /* The maximum supported page-size is 65536 bytes. This means that
danielk197711c327a2009-05-04 19:01:26 +00004897 ** the maximum number of record bytes stored on an index B-Tree
drhb2eced52010-08-12 02:41:12 +00004898 ** page is less than 16384 bytes and may be stored as a 2-byte
danielk197711c327a2009-05-04 19:01:26 +00004899 ** varint. This information is used to attempt to avoid parsing
4900 ** the entire cell by checking for the cases where the record is
4901 ** stored entirely within the b-tree page by inspecting the first
4902 ** 2 bytes of the cell.
4903 */
drhec3e6b12013-11-25 02:38:55 +00004904 nCell = pCell[0];
drh72b8ef62013-12-06 22:44:51 +00004905 if( nCell<=pPage->max1bytePayload ){
danielk197711c327a2009-05-04 19:01:26 +00004906 /* This branch runs if the record-size field of the cell is a
4907 ** single byte varint and the record fits entirely on the main
4908 ** b-tree page. */
drh3def2352011-11-11 00:27:15 +00004909 testcase( pCell+nCell+1==pPage->aDataEnd );
drh75179de2014-09-16 14:37:35 +00004910 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
danielk197711c327a2009-05-04 19:01:26 +00004911 }else if( !(pCell[1] & 0x80)
4912 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
4913 ){
4914 /* The record-size field is a 2 byte varint and the record
4915 ** fits entirely on the main b-tree page. */
drh3def2352011-11-11 00:27:15 +00004916 testcase( pCell+nCell+2==pPage->aDataEnd );
drh75179de2014-09-16 14:37:35 +00004917 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
drhe51c44f2004-05-30 20:46:09 +00004918 }else{
danielk197711c327a2009-05-04 19:01:26 +00004919 /* The record flows over onto one or more overflow pages. In
4920 ** this case the whole cell needs to be parsed, a buffer allocated
4921 ** and accessPayload() used to retrieve the record into the
4922 ** buffer before VdbeRecordCompare() can be called. */
4923 void *pCellKey;
4924 u8 * const pCellBody = pCell - pPage->childPtrSize;
danielk197730548662009-07-09 05:07:37 +00004925 btreeParseCellPtr(pPage, pCellBody, &pCur->info);
shane60a4b532009-05-06 18:57:09 +00004926 nCell = (int)pCur->info.nKey;
danielk197711c327a2009-05-04 19:01:26 +00004927 pCellKey = sqlite3Malloc( nCell );
danielk19776507ecb2008-03-25 09:56:44 +00004928 if( pCellKey==0 ){
4929 rc = SQLITE_NOMEM;
4930 goto moveto_finish;
4931 }
drhd793f442013-11-25 14:10:15 +00004932 pCur->aiIdx[pCur->iPage] = (u16)idx;
dan5a500af2014-03-11 20:33:04 +00004933 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
drhec9b31f2009-08-25 13:53:49 +00004934 if( rc ){
4935 sqlite3_free(pCellKey);
4936 goto moveto_finish;
4937 }
drh75179de2014-09-16 14:37:35 +00004938 c = xRecordCompare(nCell, pCellKey, pIdxKey);
drhfacf0302008-06-17 15:12:00 +00004939 sqlite3_free(pCellKey);
drhe51c44f2004-05-30 20:46:09 +00004940 }
dan38fdead2014-04-01 10:19:02 +00004941 assert(
4942 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
dana7bf23c2014-05-02 17:12:41 +00004943 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
dan38fdead2014-04-01 10:19:02 +00004944 );
drhbb933ef2013-11-25 15:01:38 +00004945 if( c<0 ){
4946 lwr = idx+1;
4947 }else if( c>0 ){
4948 upr = idx-1;
4949 }else{
4950 assert( c==0 );
drh64022502009-01-09 14:11:04 +00004951 *pRes = 0;
drh1e968a02008-03-25 00:22:21 +00004952 rc = SQLITE_OK;
drhd793f442013-11-25 14:10:15 +00004953 pCur->aiIdx[pCur->iPage] = (u16)idx;
dan38fdead2014-04-01 10:19:02 +00004954 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
drh1e968a02008-03-25 00:22:21 +00004955 goto moveto_finish;
drh8b18dd42004-05-12 19:18:15 +00004956 }
drhebf10b12013-11-25 17:38:26 +00004957 if( lwr>upr ) break;
4958 assert( lwr+upr>=0 );
4959 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
drh72f82862001-05-24 21:06:34 +00004960 }
drh72f82862001-05-24 21:06:34 +00004961 }
drhb07028f2011-10-14 21:49:18 +00004962 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
danielk197771d5d2c2008-09-29 11:49:47 +00004963 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00004964 if( pPage->leaf ){
drhec3e6b12013-11-25 02:38:55 +00004965 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drhbb933ef2013-11-25 15:01:38 +00004966 pCur->aiIdx[pCur->iPage] = (u16)idx;
drhec3e6b12013-11-25 02:38:55 +00004967 *pRes = c;
4968 rc = SQLITE_OK;
4969 goto moveto_finish;
drhebf10b12013-11-25 17:38:26 +00004970 }
4971moveto_next_layer:
4972 if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00004973 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00004974 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00004975 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00004976 }
drhf49661a2008-12-10 16:45:50 +00004977 pCur->aiIdx[pCur->iPage] = (u16)lwr;
drh8178a752003-01-05 21:41:40 +00004978 rc = moveToChild(pCur, chldPg);
drhec3e6b12013-11-25 02:38:55 +00004979 if( rc ) break;
drh72f82862001-05-24 21:06:34 +00004980 }
drh1e968a02008-03-25 00:22:21 +00004981moveto_finish:
drhd2022b02013-11-25 16:23:52 +00004982 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004983 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
drhe63d9992008-08-13 19:11:48 +00004984 return rc;
4985}
4986
drhd677b3d2007-08-20 22:48:41 +00004987
drh72f82862001-05-24 21:06:34 +00004988/*
drhc39e0002004-05-07 23:50:57 +00004989** Return TRUE if the cursor is not pointing at an entry of the table.
4990**
4991** TRUE will be returned after a call to sqlite3BtreeNext() moves
4992** past the last entry in the table or sqlite3BtreePrev() moves past
4993** the first entry. TRUE is also returned if the table is empty.
4994*/
4995int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00004996 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
4997 ** have been deleted? This API will need to change to return an error code
4998 ** as well as the boolean result value.
4999 */
5000 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00005001}
5002
5003/*
drhbd03cae2001-06-02 02:40:57 +00005004** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00005005** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00005006** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00005007** this routine was called, then set *pRes=1.
drhe39a7322014-02-03 14:04:11 +00005008**
drhee6438d2014-09-01 13:29:32 +00005009** The main entry point is sqlite3BtreeNext(). That routine is optimized
5010** for the common case of merely incrementing the cell counter BtCursor.aiIdx
5011** to the next cell on the current page. The (slower) btreeNext() helper
5012** routine is called when it is necessary to move to a different page or
5013** to restore the cursor.
5014**
drhe39a7322014-02-03 14:04:11 +00005015** The calling function will set *pRes to 0 or 1. The initial *pRes value
5016** will be 1 if the cursor being stepped corresponds to an SQL index and
5017** if this routine could have been skipped if that SQL index had been
5018** a unique index. Otherwise the caller will have set *pRes to zero.
5019** Zero is the common case. The btree implementation is free to use the
5020** initial *pRes value as a hint to improve performance, but the current
5021** SQLite btree implementation does not. (Note that the comdb2 btree
5022** implementation does use this hint, however.)
drh72f82862001-05-24 21:06:34 +00005023*/
drhee6438d2014-09-01 13:29:32 +00005024static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00005025 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00005026 int idx;
danielk197797a227c2006-01-20 16:32:04 +00005027 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00005028
drh1fee73e2007-08-29 04:00:57 +00005029 assert( cursorHoldsMutex(pCur) );
drh9b47ee32013-08-20 03:13:51 +00005030 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
drhee6438d2014-09-01 13:29:32 +00005031 assert( *pRes==0 );
drhf66f26a2013-08-19 20:04:10 +00005032 if( pCur->eState!=CURSOR_VALID ){
drhee6438d2014-09-01 13:29:32 +00005033 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
drhf66f26a2013-08-19 20:04:10 +00005034 rc = restoreCursorPosition(pCur);
5035 if( rc!=SQLITE_OK ){
5036 return rc;
5037 }
5038 if( CURSOR_INVALID==pCur->eState ){
5039 *pRes = 1;
5040 return SQLITE_OK;
5041 }
drh9b47ee32013-08-20 03:13:51 +00005042 if( pCur->skipNext ){
5043 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
5044 pCur->eState = CURSOR_VALID;
5045 if( pCur->skipNext>0 ){
5046 pCur->skipNext = 0;
drh9b47ee32013-08-20 03:13:51 +00005047 return SQLITE_OK;
5048 }
drhf66f26a2013-08-19 20:04:10 +00005049 pCur->skipNext = 0;
drhf66f26a2013-08-19 20:04:10 +00005050 }
danielk1977da184232006-01-05 11:34:32 +00005051 }
danielk1977da184232006-01-05 11:34:32 +00005052
danielk197771d5d2c2008-09-29 11:49:47 +00005053 pPage = pCur->apPage[pCur->iPage];
5054 idx = ++pCur->aiIdx[pCur->iPage];
5055 assert( pPage->isInit );
danbb246c42012-01-12 14:25:55 +00005056
5057 /* If the database file is corrupt, it is possible for the value of idx
5058 ** to be invalid here. This can only occur if a second cursor modifies
5059 ** the page while cursor pCur is holding a reference to it. Which can
5060 ** only happen if the database is corrupt in such a way as to link the
5061 ** page into more than one b-tree structure. */
5062 testcase( idx>pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00005063
danielk197771d5d2c2008-09-29 11:49:47 +00005064 if( idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00005065 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00005066 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drhee6438d2014-09-01 13:29:32 +00005067 if( rc ) return rc;
5068 return moveToLeftmost(pCur);
drh72f82862001-05-24 21:06:34 +00005069 }
drh5e2f8b92001-05-28 00:41:15 +00005070 do{
danielk197771d5d2c2008-09-29 11:49:47 +00005071 if( pCur->iPage==0 ){
drh8c1238a2003-01-02 14:43:55 +00005072 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00005073 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00005074 return SQLITE_OK;
5075 }
danielk197730548662009-07-09 05:07:37 +00005076 moveToParent(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00005077 pPage = pCur->apPage[pCur->iPage];
5078 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
drh44845222008-07-17 18:39:57 +00005079 if( pPage->intKey ){
drhee6438d2014-09-01 13:29:32 +00005080 return sqlite3BtreeNext(pCur, pRes);
drh8b18dd42004-05-12 19:18:15 +00005081 }else{
drhee6438d2014-09-01 13:29:32 +00005082 return SQLITE_OK;
drh8b18dd42004-05-12 19:18:15 +00005083 }
drh8178a752003-01-05 21:41:40 +00005084 }
drh3aac2dd2004-04-26 14:10:20 +00005085 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00005086 return SQLITE_OK;
drhee6438d2014-09-01 13:29:32 +00005087 }else{
5088 return moveToLeftmost(pCur);
drh72f82862001-05-24 21:06:34 +00005089 }
drh72f82862001-05-24 21:06:34 +00005090}
drhee6438d2014-09-01 13:29:32 +00005091int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
5092 MemPage *pPage;
5093 assert( cursorHoldsMutex(pCur) );
5094 assert( pRes!=0 );
5095 assert( *pRes==0 || *pRes==1 );
5096 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5097 pCur->info.nSize = 0;
5098 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5099 *pRes = 0;
5100 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
5101 pPage = pCur->apPage[pCur->iPage];
5102 if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
5103 pCur->aiIdx[pCur->iPage]--;
5104 return btreeNext(pCur, pRes);
5105 }
5106 if( pPage->leaf ){
5107 return SQLITE_OK;
5108 }else{
5109 return moveToLeftmost(pCur);
5110 }
5111}
drh72f82862001-05-24 21:06:34 +00005112
drh3b7511c2001-05-26 13:15:44 +00005113/*
drh2dcc9aa2002-12-04 13:40:25 +00005114** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00005115** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00005116** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00005117** this routine was called, then set *pRes=1.
drhe39a7322014-02-03 14:04:11 +00005118**
drhee6438d2014-09-01 13:29:32 +00005119** The main entry point is sqlite3BtreePrevious(). That routine is optimized
5120** for the common case of merely decrementing the cell counter BtCursor.aiIdx
drh3f387402014-09-24 01:23:00 +00005121** to the previous cell on the current page. The (slower) btreePrevious()
5122** helper routine is called when it is necessary to move to a different page
5123** or to restore the cursor.
drhee6438d2014-09-01 13:29:32 +00005124**
drhe39a7322014-02-03 14:04:11 +00005125** The calling function will set *pRes to 0 or 1. The initial *pRes value
5126** will be 1 if the cursor being stepped corresponds to an SQL index and
5127** if this routine could have been skipped if that SQL index had been
5128** a unique index. Otherwise the caller will have set *pRes to zero.
5129** Zero is the common case. The btree implementation is free to use the
5130** initial *pRes value as a hint to improve performance, but the current
5131** SQLite btree implementation does not. (Note that the comdb2 btree
5132** implementation does use this hint, however.)
drh2dcc9aa2002-12-04 13:40:25 +00005133*/
drhee6438d2014-09-01 13:29:32 +00005134static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00005135 int rc;
drh8178a752003-01-05 21:41:40 +00005136 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00005137
drh1fee73e2007-08-29 04:00:57 +00005138 assert( cursorHoldsMutex(pCur) );
drh9b47ee32013-08-20 03:13:51 +00005139 assert( pRes!=0 );
drhee6438d2014-09-01 13:29:32 +00005140 assert( *pRes==0 );
drh9b47ee32013-08-20 03:13:51 +00005141 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
drhee6438d2014-09-01 13:29:32 +00005142 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
5143 assert( pCur->info.nSize==0 );
drhf66f26a2013-08-19 20:04:10 +00005144 if( pCur->eState!=CURSOR_VALID ){
drh7682a472014-09-29 15:00:28 +00005145 rc = restoreCursorPosition(pCur);
drhee6438d2014-09-01 13:29:32 +00005146 if( rc!=SQLITE_OK ){
5147 return rc;
drhf66f26a2013-08-19 20:04:10 +00005148 }
5149 if( CURSOR_INVALID==pCur->eState ){
5150 *pRes = 1;
5151 return SQLITE_OK;
5152 }
drh9b47ee32013-08-20 03:13:51 +00005153 if( pCur->skipNext ){
5154 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
5155 pCur->eState = CURSOR_VALID;
5156 if( pCur->skipNext<0 ){
5157 pCur->skipNext = 0;
drh9b47ee32013-08-20 03:13:51 +00005158 return SQLITE_OK;
5159 }
drhf66f26a2013-08-19 20:04:10 +00005160 pCur->skipNext = 0;
drhf66f26a2013-08-19 20:04:10 +00005161 }
danielk1977da184232006-01-05 11:34:32 +00005162 }
danielk1977da184232006-01-05 11:34:32 +00005163
danielk197771d5d2c2008-09-29 11:49:47 +00005164 pPage = pCur->apPage[pCur->iPage];
5165 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00005166 if( !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00005167 int idx = pCur->aiIdx[pCur->iPage];
5168 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
drhee6438d2014-09-01 13:29:32 +00005169 if( rc ) return rc;
drh2dcc9aa2002-12-04 13:40:25 +00005170 rc = moveToRightmost(pCur);
5171 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00005172 while( pCur->aiIdx[pCur->iPage]==0 ){
5173 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00005174 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00005175 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00005176 return SQLITE_OK;
5177 }
danielk197730548662009-07-09 05:07:37 +00005178 moveToParent(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00005179 }
drhee6438d2014-09-01 13:29:32 +00005180 assert( pCur->info.nSize==0 );
5181 assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00005182
5183 pCur->aiIdx[pCur->iPage]--;
5184 pPage = pCur->apPage[pCur->iPage];
drh44845222008-07-17 18:39:57 +00005185 if( pPage->intKey && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00005186 rc = sqlite3BtreePrevious(pCur, pRes);
5187 }else{
5188 rc = SQLITE_OK;
5189 }
drh2dcc9aa2002-12-04 13:40:25 +00005190 }
drh2dcc9aa2002-12-04 13:40:25 +00005191 return rc;
5192}
drhee6438d2014-09-01 13:29:32 +00005193int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
5194 assert( cursorHoldsMutex(pCur) );
5195 assert( pRes!=0 );
5196 assert( *pRes==0 || *pRes==1 );
5197 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5198 *pRes = 0;
5199 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
5200 pCur->info.nSize = 0;
5201 if( pCur->eState!=CURSOR_VALID
5202 || pCur->aiIdx[pCur->iPage]==0
5203 || pCur->apPage[pCur->iPage]->leaf==0
5204 ){
5205 return btreePrevious(pCur, pRes);
5206 }
5207 pCur->aiIdx[pCur->iPage]--;
5208 return SQLITE_OK;
5209}
drh2dcc9aa2002-12-04 13:40:25 +00005210
5211/*
drh3b7511c2001-05-26 13:15:44 +00005212** Allocate a new page from the database file.
5213**
danielk19773b8a05f2007-03-19 17:44:26 +00005214** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00005215** has already been called on the new page.) The new page has also
5216** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00005217** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00005218**
5219** SQLITE_OK is returned on success. Any other return value indicates
5220** an error. *ppPage and *pPgno are undefined in the event of an error.
danielk19773b8a05f2007-03-19 17:44:26 +00005221** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00005222**
drh82e647d2013-03-02 03:25:55 +00005223** If the "nearby" parameter is not 0, then an effort is made to
drh199e3cf2002-07-18 11:01:47 +00005224** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00005225** attempt to keep related pages close to each other in the database file,
5226** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00005227**
drh82e647d2013-03-02 03:25:55 +00005228** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
5229** anywhere on the free-list, then it is guaranteed to be returned. If
5230** eMode is BTALLOC_LT then the page returned will be less than or equal
5231** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
5232** are no restrictions on which page is returned.
drh3b7511c2001-05-26 13:15:44 +00005233*/
drh4f0c5872007-03-26 22:05:01 +00005234static int allocateBtreePage(
drh82e647d2013-03-02 03:25:55 +00005235 BtShared *pBt, /* The btree */
5236 MemPage **ppPage, /* Store pointer to the allocated page here */
5237 Pgno *pPgno, /* Store the page number here */
5238 Pgno nearby, /* Search for a page near this one */
5239 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005240){
drh3aac2dd2004-04-26 14:10:20 +00005241 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00005242 int rc;
drh35cd6432009-06-05 14:17:21 +00005243 u32 n; /* Number of pages on the freelist */
drh042d6a12009-06-17 13:57:16 +00005244 u32 k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00005245 MemPage *pTrunk = 0;
5246 MemPage *pPrevTrunk = 0;
drh1662b5a2009-06-04 19:06:09 +00005247 Pgno mxPage; /* Total size of the database file */
drh30e58752002-03-02 20:41:57 +00005248
drh1fee73e2007-08-29 04:00:57 +00005249 assert( sqlite3_mutex_held(pBt->mutex) );
dan09ff9e12013-03-11 11:49:03 +00005250 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
drh3aac2dd2004-04-26 14:10:20 +00005251 pPage1 = pBt->pPage1;
drhb1299152010-03-30 22:58:33 +00005252 mxPage = btreePagecount(pBt);
drh113762a2014-11-19 16:36:25 +00005253 /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
5254 ** stores stores the total number of pages on the freelist. */
drh3aac2dd2004-04-26 14:10:20 +00005255 n = get4byte(&pPage1->aData[36]);
drhdf35a082009-07-09 02:24:35 +00005256 testcase( n==mxPage-1 );
5257 if( n>=mxPage ){
drh1662b5a2009-06-04 19:06:09 +00005258 return SQLITE_CORRUPT_BKPT;
5259 }
drh3aac2dd2004-04-26 14:10:20 +00005260 if( n>0 ){
drh91025292004-05-03 19:49:32 +00005261 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005262 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005263 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
5264
drh82e647d2013-03-02 03:25:55 +00005265 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00005266 ** shows that the page 'nearby' is somewhere on the free-list, then
5267 ** the entire-list will be searched for that page.
5268 */
5269#ifndef SQLITE_OMIT_AUTOVACUUM
dan51f0b6d2013-02-22 20:16:34 +00005270 if( eMode==BTALLOC_EXACT ){
5271 if( nearby<=mxPage ){
5272 u8 eType;
5273 assert( nearby>0 );
5274 assert( pBt->autoVacuum );
5275 rc = ptrmapGet(pBt, nearby, &eType, 0);
5276 if( rc ) return rc;
5277 if( eType==PTRMAP_FREEPAGE ){
5278 searchList = 1;
5279 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005280 }
dan51f0b6d2013-02-22 20:16:34 +00005281 }else if( eMode==BTALLOC_LE ){
5282 searchList = 1;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005283 }
5284#endif
5285
5286 /* Decrement the free-list count by 1. Set iTrunk to the index of the
5287 ** first free-list trunk page. iPrevTrunk is initially 1.
5288 */
danielk19773b8a05f2007-03-19 17:44:26 +00005289 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00005290 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00005291 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005292
5293 /* The code within this loop is run only once if the 'searchList' variable
5294 ** is not true. Otherwise, it runs once for each trunk-page on the
drh82e647d2013-03-02 03:25:55 +00005295 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
5296 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
danielk1977cb1a7eb2004-11-05 12:27:02 +00005297 */
5298 do {
5299 pPrevTrunk = pTrunk;
5300 if( pPrevTrunk ){
drh113762a2014-11-19 16:36:25 +00005301 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
5302 ** is the page number of the next freelist trunk page in the list or
5303 ** zero if this is the last freelist trunk page. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005304 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00005305 }else{
drh113762a2014-11-19 16:36:25 +00005306 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
5307 ** stores the page number of the first page of the freelist, or zero if
5308 ** the freelist is empty. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005309 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00005310 }
drhdf35a082009-07-09 02:24:35 +00005311 testcase( iTrunk==mxPage );
drh1662b5a2009-06-04 19:06:09 +00005312 if( iTrunk>mxPage ){
5313 rc = SQLITE_CORRUPT_BKPT;
5314 }else{
drhb00fc3b2013-08-21 23:42:32 +00005315 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
drh1662b5a2009-06-04 19:06:09 +00005316 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005317 if( rc ){
drhd3627af2006-12-18 18:34:51 +00005318 pTrunk = 0;
5319 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005320 }
drhb07028f2011-10-14 21:49:18 +00005321 assert( pTrunk!=0 );
5322 assert( pTrunk->aData!=0 );
drh113762a2014-11-19 16:36:25 +00005323 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
5324 ** is the number of leaf page pointers to follow. */
5325 k = get4byte(&pTrunk->aData[4]);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005326 if( k==0 && !searchList ){
5327 /* The trunk has no leaves and the list is not being searched.
5328 ** So extract the trunk page itself and use it as the newly
5329 ** allocated page */
5330 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00005331 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00005332 if( rc ){
5333 goto end_allocate_page;
5334 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005335 *pPgno = iTrunk;
5336 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5337 *ppPage = pTrunk;
5338 pTrunk = 0;
5339 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh042d6a12009-06-17 13:57:16 +00005340 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00005341 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00005342 rc = SQLITE_CORRUPT_BKPT;
5343 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005344#ifndef SQLITE_OMIT_AUTOVACUUM
dan51f0b6d2013-02-22 20:16:34 +00005345 }else if( searchList
5346 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
5347 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00005348 /* The list is being searched and this trunk page is the page
5349 ** to allocate, regardless of whether it has leaves.
5350 */
dan51f0b6d2013-02-22 20:16:34 +00005351 *pPgno = iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005352 *ppPage = pTrunk;
5353 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00005354 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00005355 if( rc ){
5356 goto end_allocate_page;
5357 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005358 if( k==0 ){
5359 if( !pPrevTrunk ){
5360 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5361 }else{
danf48c3552010-08-23 15:41:24 +00005362 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
5363 if( rc!=SQLITE_OK ){
5364 goto end_allocate_page;
5365 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005366 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
5367 }
5368 }else{
5369 /* The trunk page is required by the caller but it contains
5370 ** pointers to free-list leaves. The first leaf becomes a trunk
5371 ** page in this case.
5372 */
5373 MemPage *pNewTrunk;
5374 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh1662b5a2009-06-04 19:06:09 +00005375 if( iNewTrunk>mxPage ){
5376 rc = SQLITE_CORRUPT_BKPT;
5377 goto end_allocate_page;
5378 }
drhdf35a082009-07-09 02:24:35 +00005379 testcase( iNewTrunk==mxPage );
drhb00fc3b2013-08-21 23:42:32 +00005380 rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005381 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00005382 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005383 }
danielk19773b8a05f2007-03-19 17:44:26 +00005384 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005385 if( rc!=SQLITE_OK ){
5386 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00005387 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005388 }
5389 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
5390 put4byte(&pNewTrunk->aData[4], k-1);
5391 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00005392 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005393 if( !pPrevTrunk ){
drhc5053fb2008-11-27 02:22:10 +00005394 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
danielk1977cb1a7eb2004-11-05 12:27:02 +00005395 put4byte(&pPage1->aData[32], iNewTrunk);
5396 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00005397 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00005398 if( rc ){
5399 goto end_allocate_page;
5400 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005401 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
5402 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005403 }
5404 pTrunk = 0;
5405 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
5406#endif
danielk1977e5765212009-06-17 11:13:28 +00005407 }else if( k>0 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00005408 /* Extract a leaf from the trunk */
drh042d6a12009-06-17 13:57:16 +00005409 u32 closest;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005410 Pgno iPage;
5411 unsigned char *aData = pTrunk->aData;
5412 if( nearby>0 ){
drh042d6a12009-06-17 13:57:16 +00005413 u32 i;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005414 closest = 0;
danf38b65a2013-02-22 20:57:47 +00005415 if( eMode==BTALLOC_LE ){
5416 for(i=0; i<k; i++){
5417 iPage = get4byte(&aData[8+i*4]);
dan87ade192013-02-23 17:49:16 +00005418 if( iPage<=nearby ){
danf38b65a2013-02-22 20:57:47 +00005419 closest = i;
5420 break;
5421 }
5422 }
5423 }else{
5424 int dist;
5425 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
5426 for(i=1; i<k; i++){
5427 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
5428 if( d2<dist ){
5429 closest = i;
5430 dist = d2;
5431 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005432 }
5433 }
5434 }else{
5435 closest = 0;
5436 }
5437
5438 iPage = get4byte(&aData[8+closest*4]);
drhdf35a082009-07-09 02:24:35 +00005439 testcase( iPage==mxPage );
drh1662b5a2009-06-04 19:06:09 +00005440 if( iPage>mxPage ){
5441 rc = SQLITE_CORRUPT_BKPT;
5442 goto end_allocate_page;
5443 }
drhdf35a082009-07-09 02:24:35 +00005444 testcase( iPage==mxPage );
dan51f0b6d2013-02-22 20:16:34 +00005445 if( !searchList
5446 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
5447 ){
danielk1977bea2a942009-01-20 17:06:27 +00005448 int noContent;
shane1f9e6aa2008-06-09 19:27:11 +00005449 *pPgno = iPage;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005450 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
5451 ": %d more free pages\n",
5452 *pPgno, closest+1, k, pTrunk->pgno, n-1));
drh93b4fc72011-04-07 14:47:01 +00005453 rc = sqlite3PagerWrite(pTrunk->pDbPage);
5454 if( rc ) goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005455 if( closest<k-1 ){
5456 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
5457 }
5458 put4byte(&aData[4], k-1);
drh3f387402014-09-24 01:23:00 +00005459 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
drhb00fc3b2013-08-21 23:42:32 +00005460 rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005461 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00005462 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00005463 if( rc!=SQLITE_OK ){
5464 releasePage(*ppPage);
5465 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005466 }
5467 searchList = 0;
5468 }
drhee696e22004-08-30 16:52:17 +00005469 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005470 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00005471 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005472 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00005473 }else{
danbc1a3c62013-02-23 16:40:46 +00005474 /* There are no pages on the freelist, so append a new page to the
5475 ** database image.
5476 **
5477 ** Normally, new pages allocated by this block can be requested from the
5478 ** pager layer with the 'no-content' flag set. This prevents the pager
5479 ** from trying to read the pages content from disk. However, if the
5480 ** current transaction has already run one or more incremental-vacuum
5481 ** steps, then the page we are about to allocate may contain content
5482 ** that is required in the event of a rollback. In this case, do
5483 ** not set the no-content flag. This causes the pager to load and journal
5484 ** the current page content before overwriting it.
5485 **
5486 ** Note that the pager will not actually attempt to load or journal
5487 ** content for any page that really does lie past the end of the database
5488 ** file on disk. So the effects of disabling the no-content optimization
5489 ** here are confined to those pages that lie between the end of the
5490 ** database image and the end of the database file.
5491 */
drh3f387402014-09-24 01:23:00 +00005492 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
danbc1a3c62013-02-23 16:40:46 +00005493
drhdd3cd972010-03-27 17:12:36 +00005494 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
5495 if( rc ) return rc;
5496 pBt->nPage++;
5497 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
danielk1977bea2a942009-01-20 17:06:27 +00005498
danielk1977afcdd022004-10-31 16:25:42 +00005499#ifndef SQLITE_OMIT_AUTOVACUUM
drhdd3cd972010-03-27 17:12:36 +00005500 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
danielk1977afcdd022004-10-31 16:25:42 +00005501 /* If *pPgno refers to a pointer-map page, allocate two new pages
5502 ** at the end of the file instead of one. The first allocated page
5503 ** becomes a new pointer-map page, the second is used by the caller.
5504 */
danielk1977ac861692009-03-28 10:54:22 +00005505 MemPage *pPg = 0;
drhdd3cd972010-03-27 17:12:36 +00005506 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
5507 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
drhb00fc3b2013-08-21 23:42:32 +00005508 rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
danielk1977ac861692009-03-28 10:54:22 +00005509 if( rc==SQLITE_OK ){
5510 rc = sqlite3PagerWrite(pPg->pDbPage);
5511 releasePage(pPg);
5512 }
5513 if( rc ) return rc;
drhdd3cd972010-03-27 17:12:36 +00005514 pBt->nPage++;
5515 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
danielk1977afcdd022004-10-31 16:25:42 +00005516 }
5517#endif
drhdd3cd972010-03-27 17:12:36 +00005518 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
5519 *pPgno = pBt->nPage;
danielk1977afcdd022004-10-31 16:25:42 +00005520
danielk1977599fcba2004-11-08 07:13:13 +00005521 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhb00fc3b2013-08-21 23:42:32 +00005522 rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
drh3b7511c2001-05-26 13:15:44 +00005523 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00005524 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00005525 if( rc!=SQLITE_OK ){
5526 releasePage(*ppPage);
5527 }
drh3a4c1412004-05-09 20:40:11 +00005528 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00005529 }
danielk1977599fcba2004-11-08 07:13:13 +00005530
5531 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00005532
5533end_allocate_page:
5534 releasePage(pTrunk);
5535 releasePage(pPrevTrunk);
danielk1977b247c212008-11-21 09:09:01 +00005536 if( rc==SQLITE_OK ){
5537 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
5538 releasePage(*ppPage);
dan7df42ab2014-01-20 18:25:44 +00005539 *ppPage = 0;
danielk1977b247c212008-11-21 09:09:01 +00005540 return SQLITE_CORRUPT_BKPT;
5541 }
5542 (*ppPage)->isInit = 0;
danielk1977a50d9aa2009-06-08 14:49:45 +00005543 }else{
5544 *ppPage = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00005545 }
drh93b4fc72011-04-07 14:47:01 +00005546 assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
drh3b7511c2001-05-26 13:15:44 +00005547 return rc;
5548}
5549
5550/*
danielk1977bea2a942009-01-20 17:06:27 +00005551** This function is used to add page iPage to the database file free-list.
5552** It is assumed that the page is not already a part of the free-list.
drh5e2f8b92001-05-28 00:41:15 +00005553**
danielk1977bea2a942009-01-20 17:06:27 +00005554** The value passed as the second argument to this function is optional.
5555** If the caller happens to have a pointer to the MemPage object
5556** corresponding to page iPage handy, it may pass it as the second value.
5557** Otherwise, it may pass NULL.
5558**
5559** If a pointer to a MemPage object is passed as the second argument,
5560** its reference count is not altered by this function.
drh3b7511c2001-05-26 13:15:44 +00005561*/
danielk1977bea2a942009-01-20 17:06:27 +00005562static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
5563 MemPage *pTrunk = 0; /* Free-list trunk page */
5564 Pgno iTrunk = 0; /* Page number of free-list trunk page */
5565 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
5566 MemPage *pPage; /* Page being freed. May be NULL. */
5567 int rc; /* Return Code */
5568 int nFree; /* Initial number of pages on free-list */
drh8b2f49b2001-06-08 00:21:52 +00005569
danielk1977bea2a942009-01-20 17:06:27 +00005570 assert( sqlite3_mutex_held(pBt->mutex) );
5571 assert( iPage>1 );
5572 assert( !pMemPage || pMemPage->pgno==iPage );
5573
5574 if( pMemPage ){
5575 pPage = pMemPage;
5576 sqlite3PagerRef(pPage->pDbPage);
5577 }else{
5578 pPage = btreePageLookup(pBt, iPage);
5579 }
drh3aac2dd2004-04-26 14:10:20 +00005580
drha34b6762004-05-07 13:30:42 +00005581 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00005582 rc = sqlite3PagerWrite(pPage1->pDbPage);
danielk1977bea2a942009-01-20 17:06:27 +00005583 if( rc ) goto freepage_out;
5584 nFree = get4byte(&pPage1->aData[36]);
5585 put4byte(&pPage1->aData[36], nFree+1);
drh3aac2dd2004-04-26 14:10:20 +00005586
drhc9166342012-01-05 23:32:06 +00005587 if( pBt->btsFlags & BTS_SECURE_DELETE ){
drh5b47efa2010-02-12 18:18:39 +00005588 /* If the secure_delete option is enabled, then
5589 ** always fully overwrite deleted information with zeros.
5590 */
drhb00fc3b2013-08-21 23:42:32 +00005591 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
shaneh84f4b2f2010-02-26 01:46:54 +00005592 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
drh5b47efa2010-02-12 18:18:39 +00005593 ){
5594 goto freepage_out;
5595 }
5596 memset(pPage->aData, 0, pPage->pBt->pageSize);
danielk1977bea2a942009-01-20 17:06:27 +00005597 }
drhfcce93f2006-02-22 03:08:32 +00005598
danielk1977687566d2004-11-02 12:56:41 +00005599 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00005600 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00005601 */
danielk197785d90ca2008-07-19 14:25:15 +00005602 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00005603 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
danielk1977bea2a942009-01-20 17:06:27 +00005604 if( rc ) goto freepage_out;
danielk1977687566d2004-11-02 12:56:41 +00005605 }
danielk1977687566d2004-11-02 12:56:41 +00005606
danielk1977bea2a942009-01-20 17:06:27 +00005607 /* Now manipulate the actual database free-list structure. There are two
5608 ** possibilities. If the free-list is currently empty, or if the first
5609 ** trunk page in the free-list is full, then this page will become a
5610 ** new free-list trunk page. Otherwise, it will become a leaf of the
5611 ** first trunk page in the current free-list. This block tests if it
5612 ** is possible to add the page as a new free-list leaf.
5613 */
5614 if( nFree!=0 ){
drhc046e3e2009-07-15 11:26:44 +00005615 u32 nLeaf; /* Initial number of leaf cells on trunk page */
danielk1977bea2a942009-01-20 17:06:27 +00005616
5617 iTrunk = get4byte(&pPage1->aData[32]);
drhb00fc3b2013-08-21 23:42:32 +00005618 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977bea2a942009-01-20 17:06:27 +00005619 if( rc!=SQLITE_OK ){
5620 goto freepage_out;
5621 }
5622
5623 nLeaf = get4byte(&pTrunk->aData[4]);
drheeb844a2009-08-08 18:01:07 +00005624 assert( pBt->usableSize>32 );
5625 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
danielk1977bea2a942009-01-20 17:06:27 +00005626 rc = SQLITE_CORRUPT_BKPT;
5627 goto freepage_out;
5628 }
drheeb844a2009-08-08 18:01:07 +00005629 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
danielk1977bea2a942009-01-20 17:06:27 +00005630 /* In this case there is room on the trunk page to insert the page
5631 ** being freed as a new leaf.
drh45b1fac2008-07-04 17:52:42 +00005632 **
5633 ** Note that the trunk page is not really full until it contains
5634 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
5635 ** coded. But due to a coding error in versions of SQLite prior to
5636 ** 3.6.0, databases with freelist trunk pages holding more than
5637 ** usableSize/4 - 8 entries will be reported as corrupt. In order
5638 ** to maintain backwards compatibility with older versions of SQLite,
drhc046e3e2009-07-15 11:26:44 +00005639 ** we will continue to restrict the number of entries to usableSize/4 - 8
drh45b1fac2008-07-04 17:52:42 +00005640 ** for now. At some point in the future (once everyone has upgraded
5641 ** to 3.6.0 or later) we should consider fixing the conditional above
5642 ** to read "usableSize/4-2" instead of "usableSize/4-8".
drh113762a2014-11-19 16:36:25 +00005643 **
5644 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
5645 ** avoid using the last six entries in the freelist trunk page array in
5646 ** order that database files created by newer versions of SQLite can be
5647 ** read by older versions of SQLite.
drh45b1fac2008-07-04 17:52:42 +00005648 */
danielk19773b8a05f2007-03-19 17:44:26 +00005649 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00005650 if( rc==SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00005651 put4byte(&pTrunk->aData[4], nLeaf+1);
5652 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
drhc9166342012-01-05 23:32:06 +00005653 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
danielk1977bea2a942009-01-20 17:06:27 +00005654 sqlite3PagerDontWrite(pPage->pDbPage);
5655 }
danielk1977bea2a942009-01-20 17:06:27 +00005656 rc = btreeSetHasContent(pBt, iPage);
drhf5345442007-04-09 12:45:02 +00005657 }
drh3a4c1412004-05-09 20:40:11 +00005658 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
danielk1977bea2a942009-01-20 17:06:27 +00005659 goto freepage_out;
drh3aac2dd2004-04-26 14:10:20 +00005660 }
drh3b7511c2001-05-26 13:15:44 +00005661 }
danielk1977bea2a942009-01-20 17:06:27 +00005662
5663 /* If control flows to this point, then it was not possible to add the
5664 ** the page being freed as a leaf page of the first trunk in the free-list.
5665 ** Possibly because the free-list is empty, or possibly because the
5666 ** first trunk in the free-list is full. Either way, the page being freed
5667 ** will become the new first trunk page in the free-list.
5668 */
drhb00fc3b2013-08-21 23:42:32 +00005669 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
drhc046e3e2009-07-15 11:26:44 +00005670 goto freepage_out;
5671 }
5672 rc = sqlite3PagerWrite(pPage->pDbPage);
5673 if( rc!=SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00005674 goto freepage_out;
5675 }
5676 put4byte(pPage->aData, iTrunk);
5677 put4byte(&pPage->aData[4], 0);
5678 put4byte(&pPage1->aData[32], iPage);
5679 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
5680
5681freepage_out:
5682 if( pPage ){
5683 pPage->isInit = 0;
5684 }
5685 releasePage(pPage);
5686 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00005687 return rc;
5688}
drhc314dc72009-07-21 11:52:34 +00005689static void freePage(MemPage *pPage, int *pRC){
5690 if( (*pRC)==SQLITE_OK ){
5691 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
5692 }
danielk1977bea2a942009-01-20 17:06:27 +00005693}
drh3b7511c2001-05-26 13:15:44 +00005694
5695/*
drh9bfdc252014-09-24 02:05:41 +00005696** Free any overflow pages associated with the given Cell. Write the
5697** local Cell size (the number of bytes on the original page, omitting
5698** overflow) into *pnSize.
drh3b7511c2001-05-26 13:15:44 +00005699*/
drh9bfdc252014-09-24 02:05:41 +00005700static int clearCell(
5701 MemPage *pPage, /* The page that contains the Cell */
5702 unsigned char *pCell, /* First byte of the Cell */
5703 u16 *pnSize /* Write the size of the Cell here */
5704){
danielk1977aef0bf62005-12-30 16:28:01 +00005705 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00005706 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00005707 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00005708 int rc;
drh94440812007-03-06 11:42:19 +00005709 int nOvfl;
shaneh1df2db72010-08-18 02:28:48 +00005710 u32 ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00005711
drh1fee73e2007-08-29 04:00:57 +00005712 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197730548662009-07-09 05:07:37 +00005713 btreeParseCellPtr(pPage, pCell, &info);
drh9bfdc252014-09-24 02:05:41 +00005714 *pnSize = info.nSize;
drh6f11bef2004-05-13 01:12:56 +00005715 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00005716 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00005717 }
drhe42a9b42011-08-31 13:27:19 +00005718 if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
mistachkin70a1b712012-09-28 18:13:35 +00005719 return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
drhe42a9b42011-08-31 13:27:19 +00005720 }
drh6f11bef2004-05-13 01:12:56 +00005721 ovflPgno = get4byte(&pCell[info.iOverflow]);
shane63207ab2009-02-04 01:49:30 +00005722 assert( pBt->usableSize > 4 );
drh94440812007-03-06 11:42:19 +00005723 ovflPageSize = pBt->usableSize - 4;
drh72365832007-03-06 15:53:44 +00005724 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
5725 assert( ovflPgno==0 || nOvfl>0 );
5726 while( nOvfl-- ){
shane63207ab2009-02-04 01:49:30 +00005727 Pgno iNext = 0;
danielk1977bea2a942009-01-20 17:06:27 +00005728 MemPage *pOvfl = 0;
drhb1299152010-03-30 22:58:33 +00005729 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
danielk1977e589a672009-04-11 16:06:15 +00005730 /* 0 is not a legal page number and page 1 cannot be an
5731 ** overflow page. Therefore if ovflPgno<2 or past the end of the
5732 ** file the database must be corrupt. */
drh49285702005-09-17 15:20:26 +00005733 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00005734 }
danielk1977bea2a942009-01-20 17:06:27 +00005735 if( nOvfl ){
5736 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
5737 if( rc ) return rc;
5738 }
dan887d4b22010-02-25 12:09:16 +00005739
shaneh1da207e2010-03-09 14:41:12 +00005740 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
dan887d4b22010-02-25 12:09:16 +00005741 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
5742 ){
5743 /* There is no reason any cursor should have an outstanding reference
5744 ** to an overflow page belonging to a cell that is being deleted/updated.
5745 ** So if there exists more than one reference to this page, then it
5746 ** must not really be an overflow page and the database must be corrupt.
5747 ** It is helpful to detect this before calling freePage2(), as
5748 ** freePage2() may zero the page contents if secure-delete mode is
5749 ** enabled. If this 'overflow' page happens to be a page that the
5750 ** caller is iterating through or using in some other way, this
5751 ** can be problematic.
5752 */
5753 rc = SQLITE_CORRUPT_BKPT;
5754 }else{
5755 rc = freePage2(pBt, pOvfl, ovflPgno);
5756 }
5757
danielk1977bea2a942009-01-20 17:06:27 +00005758 if( pOvfl ){
5759 sqlite3PagerUnref(pOvfl->pDbPage);
5760 }
drh3b7511c2001-05-26 13:15:44 +00005761 if( rc ) return rc;
danielk1977bea2a942009-01-20 17:06:27 +00005762 ovflPgno = iNext;
drh3b7511c2001-05-26 13:15:44 +00005763 }
drh5e2f8b92001-05-28 00:41:15 +00005764 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00005765}
5766
5767/*
drh91025292004-05-03 19:49:32 +00005768** Create the byte sequence used to represent a cell on page pPage
5769** and write that byte sequence into pCell[]. Overflow pages are
5770** allocated and filled in as necessary. The calling procedure
5771** is responsible for making sure sufficient space has been allocated
5772** for pCell[].
5773**
5774** Note that pCell does not necessary need to point to the pPage->aData
5775** area. pCell might point to some temporary storage. The cell will
5776** be constructed in this temporary area then copied into pPage->aData
5777** later.
drh3b7511c2001-05-26 13:15:44 +00005778*/
5779static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00005780 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00005781 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00005782 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00005783 const void *pData,int nData, /* The data */
drhb026e052007-05-02 01:34:31 +00005784 int nZero, /* Extra zero bytes to append to pData */
drh4b70f112004-05-02 21:12:19 +00005785 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00005786){
drh3b7511c2001-05-26 13:15:44 +00005787 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00005788 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00005789 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00005790 int spaceLeft;
5791 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00005792 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00005793 unsigned char *pPrior;
5794 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00005795 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00005796 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00005797 int nHeader;
drh3b7511c2001-05-26 13:15:44 +00005798
drh1fee73e2007-08-29 04:00:57 +00005799 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00005800
drhc5053fb2008-11-27 02:22:10 +00005801 /* pPage is not necessarily writeable since pCell might be auxiliary
5802 ** buffer space that is separate from the pPage buffer area */
5803 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
5804 || sqlite3PagerIswriteable(pPage->pDbPage) );
5805
drh91025292004-05-03 19:49:32 +00005806 /* Fill in the header. */
drh6200c882014-09-23 22:36:25 +00005807 nHeader = pPage->childPtrSize;
5808 nPayload = nData + nZero;
drh3e28ff52014-09-24 00:59:08 +00005809 if( pPage->intKeyLeaf ){
drh6200c882014-09-23 22:36:25 +00005810 nHeader += putVarint32(&pCell[nHeader], nPayload);
drh6f11bef2004-05-13 01:12:56 +00005811 }else{
drh6200c882014-09-23 22:36:25 +00005812 assert( nData==0 );
5813 assert( nZero==0 );
drh91025292004-05-03 19:49:32 +00005814 }
drh6f11bef2004-05-13 01:12:56 +00005815 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
drh6f11bef2004-05-13 01:12:56 +00005816
drh6200c882014-09-23 22:36:25 +00005817 /* Fill in the payload size */
drh3aac2dd2004-04-26 14:10:20 +00005818 if( pPage->intKey ){
5819 pSrc = pData;
5820 nSrc = nData;
drh91025292004-05-03 19:49:32 +00005821 nData = 0;
drhf49661a2008-12-10 16:45:50 +00005822 }else{
danielk197731d31b82009-07-13 13:18:07 +00005823 if( NEVER(nKey>0x7fffffff || pKey==0) ){
5824 return SQLITE_CORRUPT_BKPT;
drh20abac22009-01-28 20:21:17 +00005825 }
drh6200c882014-09-23 22:36:25 +00005826 nPayload = (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00005827 pSrc = pKey;
drhf49661a2008-12-10 16:45:50 +00005828 nSrc = (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00005829 }
drh6200c882014-09-23 22:36:25 +00005830 if( nPayload<=pPage->maxLocal ){
5831 n = nHeader + nPayload;
5832 testcase( n==3 );
5833 testcase( n==4 );
5834 if( n<4 ) n = 4;
5835 *pnSize = n;
5836 spaceLeft = nPayload;
5837 pPrior = pCell;
5838 }else{
5839 int mn = pPage->minLocal;
5840 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
5841 testcase( n==pPage->maxLocal );
5842 testcase( n==pPage->maxLocal+1 );
5843 if( n > pPage->maxLocal ) n = mn;
5844 spaceLeft = n;
5845 *pnSize = n + nHeader + 4;
5846 pPrior = &pCell[nHeader+n];
5847 }
drh3aac2dd2004-04-26 14:10:20 +00005848 pPayload = &pCell[nHeader];
drh3b7511c2001-05-26 13:15:44 +00005849
drh6200c882014-09-23 22:36:25 +00005850 /* At this point variables should be set as follows:
5851 **
5852 ** nPayload Total payload size in bytes
5853 ** pPayload Begin writing payload here
5854 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
5855 ** that means content must spill into overflow pages.
5856 ** *pnSize Size of the local cell (not counting overflow pages)
5857 ** pPrior Where to write the pgno of the first overflow page
5858 **
5859 ** Use a call to btreeParseCellPtr() to verify that the values above
5860 ** were computed correctly.
5861 */
5862#if SQLITE_DEBUG
5863 {
5864 CellInfo info;
5865 btreeParseCellPtr(pPage, pCell, &info);
5866 assert( nHeader=(int)(info.pPayload - pCell) );
5867 assert( info.nKey==nKey );
5868 assert( *pnSize == info.nSize );
5869 assert( spaceLeft == info.nLocal );
5870 assert( pPrior == &pCell[info.iOverflow] );
5871 }
5872#endif
5873
5874 /* Write the payload into the local Cell and any extra into overflow pages */
drh3b7511c2001-05-26 13:15:44 +00005875 while( nPayload>0 ){
5876 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00005877#ifndef SQLITE_OMIT_AUTOVACUUM
5878 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00005879 if( pBt->autoVacuum ){
5880 do{
5881 pgnoOvfl++;
5882 } while(
5883 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
5884 );
danielk1977b39f70b2007-05-17 18:28:11 +00005885 }
danielk1977afcdd022004-10-31 16:25:42 +00005886#endif
drhf49661a2008-12-10 16:45:50 +00005887 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00005888#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00005889 /* If the database supports auto-vacuum, and the second or subsequent
5890 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00005891 ** for that page now.
5892 **
5893 ** If this is the first overflow page, then write a partial entry
5894 ** to the pointer-map. If we write nothing to this pointer-map slot,
5895 ** then the optimistic overflow chain processing in clearCell()
mistachkin48864df2013-03-21 21:20:32 +00005896 ** may misinterpret the uninitialized values and delete the
danielk19774ef24492007-05-23 09:52:41 +00005897 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00005898 */
danielk19774ef24492007-05-23 09:52:41 +00005899 if( pBt->autoVacuum && rc==SQLITE_OK ){
5900 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
drh98add2e2009-07-20 17:11:49 +00005901 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
danielk197789a4be82007-05-23 13:34:32 +00005902 if( rc ){
5903 releasePage(pOvfl);
5904 }
danielk1977afcdd022004-10-31 16:25:42 +00005905 }
5906#endif
drh3b7511c2001-05-26 13:15:44 +00005907 if( rc ){
drh9b171272004-05-08 02:03:22 +00005908 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00005909 return rc;
5910 }
drhc5053fb2008-11-27 02:22:10 +00005911
5912 /* If pToRelease is not zero than pPrior points into the data area
5913 ** of pToRelease. Make sure pToRelease is still writeable. */
5914 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
5915
5916 /* If pPrior is part of the data area of pPage, then make sure pPage
5917 ** is still writeable */
5918 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
5919 || sqlite3PagerIswriteable(pPage->pDbPage) );
5920
drh3aac2dd2004-04-26 14:10:20 +00005921 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00005922 releasePage(pToRelease);
5923 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00005924 pPrior = pOvfl->aData;
5925 put4byte(pPrior, 0);
5926 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00005927 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00005928 }
5929 n = nPayload;
5930 if( n>spaceLeft ) n = spaceLeft;
drhc5053fb2008-11-27 02:22:10 +00005931
5932 /* If pToRelease is not zero than pPayload points into the data area
5933 ** of pToRelease. Make sure pToRelease is still writeable. */
5934 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
5935
5936 /* If pPayload is part of the data area of pPage, then make sure pPage
5937 ** is still writeable */
5938 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
5939 || sqlite3PagerIswriteable(pPage->pDbPage) );
5940
drhb026e052007-05-02 01:34:31 +00005941 if( nSrc>0 ){
5942 if( n>nSrc ) n = nSrc;
5943 assert( pSrc );
5944 memcpy(pPayload, pSrc, n);
5945 }else{
5946 memset(pPayload, 0, n);
5947 }
drh3b7511c2001-05-26 13:15:44 +00005948 nPayload -= n;
drhde647132004-05-07 17:57:49 +00005949 pPayload += n;
drh9b171272004-05-08 02:03:22 +00005950 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00005951 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00005952 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00005953 if( nSrc==0 ){
5954 nSrc = nData;
5955 pSrc = pData;
5956 }
drhdd793422001-06-28 01:54:48 +00005957 }
drh9b171272004-05-08 02:03:22 +00005958 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00005959 return SQLITE_OK;
5960}
5961
drh14acc042001-06-10 19:56:58 +00005962/*
5963** Remove the i-th cell from pPage. This routine effects pPage only.
5964** The cell content is not freed or deallocated. It is assumed that
5965** the cell content has been copied someplace else. This routine just
5966** removes the reference to the cell from pPage.
5967**
5968** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00005969*/
drh98add2e2009-07-20 17:11:49 +00005970static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
drh43b18e12010-08-17 19:40:08 +00005971 u32 pc; /* Offset to cell content of cell being deleted */
drh43605152004-05-29 21:46:49 +00005972 u8 *data; /* pPage->aData */
5973 u8 *ptr; /* Used to move bytes around within data[] */
shanedcc50b72008-11-13 18:29:50 +00005974 int rc; /* The return code */
drhc314dc72009-07-21 11:52:34 +00005975 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
drh43605152004-05-29 21:46:49 +00005976
drh98add2e2009-07-20 17:11:49 +00005977 if( *pRC ) return;
5978
drh8c42ca92001-06-22 19:15:00 +00005979 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00005980 assert( sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00005981 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00005982 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00005983 data = pPage->aData;
drh3def2352011-11-11 00:27:15 +00005984 ptr = &pPage->aCellIdx[2*idx];
shane0af3f892008-11-12 04:55:34 +00005985 pc = get2byte(ptr);
drhc314dc72009-07-21 11:52:34 +00005986 hdr = pPage->hdrOffset;
5987 testcase( pc==get2byte(&data[hdr+5]) );
5988 testcase( pc+sz==pPage->pBt->usableSize );
drh43b18e12010-08-17 19:40:08 +00005989 if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
drh98add2e2009-07-20 17:11:49 +00005990 *pRC = SQLITE_CORRUPT_BKPT;
5991 return;
shane0af3f892008-11-12 04:55:34 +00005992 }
shanedcc50b72008-11-13 18:29:50 +00005993 rc = freeSpace(pPage, pc, sz);
drh98add2e2009-07-20 17:11:49 +00005994 if( rc ){
5995 *pRC = rc;
5996 return;
shanedcc50b72008-11-13 18:29:50 +00005997 }
drh14acc042001-06-10 19:56:58 +00005998 pPage->nCell--;
drhfdab0262014-11-20 15:30:50 +00005999 if( pPage->nCell==0 ){
6000 memset(&data[hdr+1], 0, 4);
6001 data[hdr+7] = 0;
6002 put2byte(&data[hdr+5], pPage->pBt->usableSize);
6003 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
6004 - pPage->childPtrSize - 8;
6005 }else{
6006 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
6007 put2byte(&data[hdr+3], pPage->nCell);
6008 pPage->nFree += 2;
6009 }
drh14acc042001-06-10 19:56:58 +00006010}
6011
6012/*
6013** Insert a new cell on pPage at cell index "i". pCell points to the
6014** content of the cell.
6015**
6016** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00006017** will not fit, then make a copy of the cell content into pTemp if
6018** pTemp is not null. Regardless of pTemp, allocate a new entry
drh2cbd78b2012-02-02 19:37:18 +00006019** in pPage->apOvfl[] and make it point to the cell content (either
drh43605152004-05-29 21:46:49 +00006020** in pTemp or the original pCell) and also record its index.
6021** Allocating a new entry in pPage->aCell[] implies that
6022** pPage->nOverflow is incremented.
drh14acc042001-06-10 19:56:58 +00006023*/
drh98add2e2009-07-20 17:11:49 +00006024static void insertCell(
drh24cd67e2004-05-10 16:18:47 +00006025 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00006026 int i, /* New cell becomes the i-th cell of the page */
6027 u8 *pCell, /* Content of the new cell */
6028 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00006029 u8 *pTemp, /* Temp storage space for pCell, if needed */
drh98add2e2009-07-20 17:11:49 +00006030 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
6031 int *pRC /* Read and write return code from here */
drh24cd67e2004-05-10 16:18:47 +00006032){
drh383d30f2010-02-26 13:07:37 +00006033 int idx = 0; /* Where to write new cell content in data[] */
drh43605152004-05-29 21:46:49 +00006034 int j; /* Loop counter */
drh43605152004-05-29 21:46:49 +00006035 int end; /* First byte past the last cell pointer in data[] */
6036 int ins; /* Index in data[] where new cell pointer is inserted */
drh43605152004-05-29 21:46:49 +00006037 int cellOffset; /* Address of first cell pointer in data[] */
6038 u8 *data; /* The content of the whole page */
danielk19774dbaa892009-06-16 16:50:22 +00006039
drh98add2e2009-07-20 17:11:49 +00006040 if( *pRC ) return;
6041
drh43605152004-05-29 21:46:49 +00006042 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
danf216e322014-08-14 19:53:37 +00006043 assert( MX_CELL(pPage->pBt)<=10921 );
6044 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
drh2cbd78b2012-02-02 19:37:18 +00006045 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
6046 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
drh1fee73e2007-08-29 04:00:57 +00006047 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc9b9b8a2009-12-03 21:26:52 +00006048 /* The cell should normally be sized correctly. However, when moving a
6049 ** malformed cell from a leaf page to an interior page, if the cell size
6050 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
6051 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
6052 ** the term after the || in the following assert(). */
6053 assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
drh43605152004-05-29 21:46:49 +00006054 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00006055 if( pTemp ){
drhd6176c42014-10-11 17:22:55 +00006056 memcpy(pTemp, pCell, sz);
drh43605152004-05-29 21:46:49 +00006057 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00006058 }
danielk19774dbaa892009-06-16 16:50:22 +00006059 if( iChild ){
6060 put4byte(pCell, iChild);
6061 }
drh43605152004-05-29 21:46:49 +00006062 j = pPage->nOverflow++;
drh2cbd78b2012-02-02 19:37:18 +00006063 assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
6064 pPage->apOvfl[j] = pCell;
6065 pPage->aiOvfl[j] = (u16)i;
drh14acc042001-06-10 19:56:58 +00006066 }else{
danielk19776e465eb2007-08-21 13:11:00 +00006067 int rc = sqlite3PagerWrite(pPage->pDbPage);
6068 if( rc!=SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +00006069 *pRC = rc;
6070 return;
danielk19776e465eb2007-08-21 13:11:00 +00006071 }
6072 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00006073 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00006074 cellOffset = pPage->cellOffset;
drh0a45c272009-07-08 01:49:11 +00006075 end = cellOffset + 2*pPage->nCell;
drh43605152004-05-29 21:46:49 +00006076 ins = cellOffset + 2*i;
drh0a45c272009-07-08 01:49:11 +00006077 rc = allocateSpace(pPage, sz, &idx);
drh98add2e2009-07-20 17:11:49 +00006078 if( rc ){ *pRC = rc; return; }
drhc314dc72009-07-21 11:52:34 +00006079 /* The allocateSpace() routine guarantees the following two properties
6080 ** if it returns success */
6081 assert( idx >= end+2 );
drhfcd71b62011-04-05 22:08:24 +00006082 assert( idx+sz <= (int)pPage->pBt->usableSize );
drh43605152004-05-29 21:46:49 +00006083 pPage->nCell++;
drh0a45c272009-07-08 01:49:11 +00006084 pPage->nFree -= (u16)(2 + sz);
drhd6176c42014-10-11 17:22:55 +00006085 memcpy(&data[idx], pCell, sz);
danielk19774dbaa892009-06-16 16:50:22 +00006086 if( iChild ){
6087 put4byte(&data[idx], iChild);
6088 }
drh8f518832013-12-09 02:32:19 +00006089 memmove(&data[ins+2], &data[ins], end-ins);
drh43605152004-05-29 21:46:49 +00006090 put2byte(&data[ins], idx);
drh0a45c272009-07-08 01:49:11 +00006091 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
danielk1977a19df672004-11-03 11:37:07 +00006092#ifndef SQLITE_OMIT_AUTOVACUUM
6093 if( pPage->pBt->autoVacuum ){
6094 /* The cell may contain a pointer to an overflow page. If so, write
6095 ** the entry for the overflow page into the pointer map.
6096 */
drh98add2e2009-07-20 17:11:49 +00006097 ptrmapPutOvflPtr(pPage, pCell, pRC);
danielk1977a19df672004-11-03 11:37:07 +00006098 }
6099#endif
drh14acc042001-06-10 19:56:58 +00006100 }
6101}
6102
6103/*
dan8e9ba0c2014-10-14 17:27:04 +00006104** Array apCell[] contains pointers to nCell b-tree page cells. The
6105** szCell[] array contains the size in bytes of each cell. This function
6106** replaces the current contents of page pPg with the contents of the cell
6107** array.
6108**
6109** Some of the cells in apCell[] may currently be stored in pPg. This
6110** function works around problems caused by this by making a copy of any
6111** such cells before overwriting the page data.
6112**
6113** The MemPage.nFree field is invalidated by this function. It is the
6114** responsibility of the caller to set it correctly.
drhfa1a98a2004-05-14 19:08:17 +00006115*/
dan33ea4862014-10-09 19:35:37 +00006116static void rebuildPage(
6117 MemPage *pPg, /* Edit this page */
dan33ea4862014-10-09 19:35:37 +00006118 int nCell, /* Final number of cells on page */
dan09c68402014-10-11 20:00:24 +00006119 u8 **apCell, /* Array of cells */
6120 u16 *szCell /* Array of cell sizes */
dan33ea4862014-10-09 19:35:37 +00006121){
6122 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
6123 u8 * const aData = pPg->aData; /* Pointer to data for pPg */
6124 const int usableSize = pPg->pBt->usableSize;
6125 u8 * const pEnd = &aData[usableSize];
6126 int i;
6127 u8 *pCellptr = pPg->aCellIdx;
6128 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6129 u8 *pData;
6130
6131 i = get2byte(&aData[hdr+5]);
6132 memcpy(&pTmp[i], &aData[i], usableSize - i);
dan33ea4862014-10-09 19:35:37 +00006133
dan8e9ba0c2014-10-14 17:27:04 +00006134 pData = pEnd;
dan33ea4862014-10-09 19:35:37 +00006135 for(i=0; i<nCell; i++){
6136 u8 *pCell = apCell[i];
6137 if( pCell>aData && pCell<pEnd ){
6138 pCell = &pTmp[pCell - aData];
6139 }
6140 pData -= szCell[i];
6141 memcpy(pData, pCell, szCell[i]);
6142 put2byte(pCellptr, (pData - aData));
6143 pCellptr += 2;
6144 assert( szCell[i]==cellSizePtr(pPg, pCell) );
6145 }
6146
dand7b545b2014-10-13 18:03:27 +00006147 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
dan33ea4862014-10-09 19:35:37 +00006148 pPg->nCell = nCell;
6149 pPg->nOverflow = 0;
6150
6151 put2byte(&aData[hdr+1], 0);
6152 put2byte(&aData[hdr+3], pPg->nCell);
6153 put2byte(&aData[hdr+5], pData - aData);
6154 aData[hdr+7] = 0x00;
6155}
6156
dan8e9ba0c2014-10-14 17:27:04 +00006157/*
6158** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
6159** contains the size in bytes of each such cell. This function attempts to
6160** add the cells stored in the array to page pPg. If it cannot (because
6161** the page needs to be defragmented before the cells will fit), non-zero
6162** is returned. Otherwise, if the cells are added successfully, zero is
6163** returned.
6164**
6165** Argument pCellptr points to the first entry in the cell-pointer array
6166** (part of page pPg) to populate. After cell apCell[0] is written to the
6167** page body, a 16-bit offset is written to pCellptr. And so on, for each
6168** cell in the array. It is the responsibility of the caller to ensure
6169** that it is safe to overwrite this part of the cell-pointer array.
6170**
6171** When this function is called, *ppData points to the start of the
6172** content area on page pPg. If the size of the content area is extended,
6173** *ppData is updated to point to the new start of the content area
6174** before returning.
6175**
6176** Finally, argument pBegin points to the byte immediately following the
6177** end of the space required by this page for the cell-pointer area (for
6178** all cells - not just those inserted by the current call). If the content
6179** area must be extended to before this point in order to accomodate all
6180** cells in apCell[], then the cells do not fit and non-zero is returned.
6181*/
dand7b545b2014-10-13 18:03:27 +00006182static int pageInsertArray(
dan8e9ba0c2014-10-14 17:27:04 +00006183 MemPage *pPg, /* Page to add cells to */
6184 u8 *pBegin, /* End of cell-pointer array */
6185 u8 **ppData, /* IN/OUT: Page content -area pointer */
6186 u8 *pCellptr, /* Pointer to cell-pointer area */
6187 int nCell, /* Number of cells to add to pPg */
dand7b545b2014-10-13 18:03:27 +00006188 u8 **apCell, /* Array of cells */
6189 u16 *szCell /* Array of cell sizes */
6190){
6191 int i;
6192 u8 *aData = pPg->aData;
6193 u8 *pData = *ppData;
dan8e9ba0c2014-10-14 17:27:04 +00006194 const int bFreelist = aData[1] || aData[2];
dan23eba452014-10-24 18:43:57 +00006195 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
dand7b545b2014-10-13 18:03:27 +00006196 for(i=0; i<nCell; i++){
6197 int sz = szCell[i];
drhba0f9992014-10-30 20:48:44 +00006198 int rc;
dand7b545b2014-10-13 18:03:27 +00006199 u8 *pSlot;
drhba0f9992014-10-30 20:48:44 +00006200 if( bFreelist==0 || (pSlot = pageFindSlot(pPg, sz, &rc, 0))==0 ){
dand7b545b2014-10-13 18:03:27 +00006201 pData -= sz;
6202 if( pData<pBegin ) return 1;
6203 pSlot = pData;
6204 }
6205 memcpy(pSlot, apCell[i], sz);
6206 put2byte(pCellptr, (pSlot - aData));
6207 pCellptr += 2;
6208 }
6209 *ppData = pData;
6210 return 0;
6211}
6212
dan8e9ba0c2014-10-14 17:27:04 +00006213/*
6214** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
6215** contains the size in bytes of each such cell. This function adds the
6216** space associated with each cell in the array that is currently stored
6217** within the body of pPg to the pPg free-list. The cell-pointers and other
6218** fields of the page are not updated.
6219**
6220** This function returns the total number of cells added to the free-list.
6221*/
dand7b545b2014-10-13 18:03:27 +00006222static int pageFreeArray(
6223 MemPage *pPg, /* Page to edit */
6224 int nCell, /* Cells to delete */
6225 u8 **apCell, /* Array of cells */
6226 u16 *szCell /* Array of cell sizes */
6227){
6228 u8 * const aData = pPg->aData;
6229 u8 * const pEnd = &aData[pPg->pBt->usableSize];
dan89ca0b32014-10-25 20:36:28 +00006230 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
dand7b545b2014-10-13 18:03:27 +00006231 int nRet = 0;
6232 int i;
6233 u8 *pFree = 0;
6234 int szFree = 0;
6235
6236 for(i=0; i<nCell; i++){
6237 u8 *pCell = apCell[i];
dan89ca0b32014-10-25 20:36:28 +00006238 if( pCell>=pStart && pCell<pEnd ){
dand7b545b2014-10-13 18:03:27 +00006239 int sz = szCell[i];
6240 if( pFree!=(pCell + sz) ){
drhfefa0942014-11-05 21:21:08 +00006241 if( pFree ){
6242 assert( pFree>aData && (pFree - aData)<65536 );
6243 freeSpace(pPg, (u16)(pFree - aData), szFree);
6244 }
dand7b545b2014-10-13 18:03:27 +00006245 pFree = pCell;
6246 szFree = sz;
dan89ca0b32014-10-25 20:36:28 +00006247 if( pFree+sz>pEnd ) return 0;
dand7b545b2014-10-13 18:03:27 +00006248 }else{
6249 pFree = pCell;
6250 szFree += sz;
6251 }
6252 nRet++;
6253 }
6254 }
drhfefa0942014-11-05 21:21:08 +00006255 if( pFree ){
6256 assert( pFree>aData && (pFree - aData)<65536 );
6257 freeSpace(pPg, (u16)(pFree - aData), szFree);
6258 }
dand7b545b2014-10-13 18:03:27 +00006259 return nRet;
6260}
6261
dand7b545b2014-10-13 18:03:27 +00006262/*
drh5ab63772014-11-27 03:46:04 +00006263** apCell[] and szCell[] contains pointers to and sizes of all cells in the
6264** pages being balanced. The current page, pPg, has pPg->nCell cells starting
6265** with apCell[iOld]. After balancing, this page should hold nNew cells
6266** starting at apCell[iNew].
6267**
6268** This routine makes the necessary adjustments to pPg so that it contains
6269** the correct cells after being balanced.
6270**
dand7b545b2014-10-13 18:03:27 +00006271** The pPg->nFree field is invalid when this function returns. It is the
6272** responsibility of the caller to set it correctly.
6273*/
dan09c68402014-10-11 20:00:24 +00006274static void editPage(
6275 MemPage *pPg, /* Edit this page */
6276 int iOld, /* Index of first cell currently on page */
6277 int iNew, /* Index of new first cell on page */
6278 int nNew, /* Final number of cells on page */
6279 u8 **apCell, /* Array of cells */
6280 u16 *szCell /* Array of cell sizes */
6281){
dand7b545b2014-10-13 18:03:27 +00006282 u8 * const aData = pPg->aData;
6283 const int hdr = pPg->hdrOffset;
6284 u8 *pBegin = &pPg->aCellIdx[nNew * 2];
6285 int nCell = pPg->nCell; /* Cells stored on pPg */
6286 u8 *pData;
6287 u8 *pCellptr;
6288 int i;
6289 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
6290 int iNewEnd = iNew + nNew;
dan09c68402014-10-11 20:00:24 +00006291
6292#ifdef SQLITE_DEBUG
dand7b545b2014-10-13 18:03:27 +00006293 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6294 memcpy(pTmp, aData, pPg->pBt->usableSize);
dan09c68402014-10-11 20:00:24 +00006295#endif
6296
dand7b545b2014-10-13 18:03:27 +00006297 /* Remove cells from the start and end of the page */
6298 if( iOld<iNew ){
6299 int nShift = pageFreeArray(
6300 pPg, iNew-iOld, &apCell[iOld], &szCell[iOld]
6301 );
6302 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
6303 nCell -= nShift;
6304 }
6305 if( iNewEnd < iOldEnd ){
6306 nCell -= pageFreeArray(
6307 pPg, iOldEnd-iNewEnd, &apCell[iNewEnd], &szCell[iNewEnd]
6308 );
6309 }
dan09c68402014-10-11 20:00:24 +00006310
drh5ab63772014-11-27 03:46:04 +00006311 pData = &aData[get2byteNotZero(&aData[hdr+5])];
dand7b545b2014-10-13 18:03:27 +00006312 if( pData<pBegin ) goto editpage_fail;
6313
6314 /* Add cells to the start of the page */
6315 if( iNew<iOld ){
drh5ab63772014-11-27 03:46:04 +00006316 int nAdd = MIN(nNew,iOld-iNew);
6317 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
dand7b545b2014-10-13 18:03:27 +00006318 pCellptr = pPg->aCellIdx;
6319 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
6320 if( pageInsertArray(
6321 pPg, pBegin, &pData, pCellptr,
6322 nAdd, &apCell[iNew], &szCell[iNew]
6323 ) ) goto editpage_fail;
6324 nCell += nAdd;
6325 }
6326
6327 /* Add any overflow cells */
6328 for(i=0; i<pPg->nOverflow; i++){
6329 int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
6330 if( iCell>=0 && iCell<nNew ){
drhfefa0942014-11-05 21:21:08 +00006331 pCellptr = &pPg->aCellIdx[iCell * 2];
dand7b545b2014-10-13 18:03:27 +00006332 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
6333 nCell++;
6334 if( pageInsertArray(
6335 pPg, pBegin, &pData, pCellptr,
6336 1, &apCell[iCell + iNew], &szCell[iCell + iNew]
6337 ) ) goto editpage_fail;
dan09c68402014-10-11 20:00:24 +00006338 }
dand7b545b2014-10-13 18:03:27 +00006339 }
dan09c68402014-10-11 20:00:24 +00006340
dand7b545b2014-10-13 18:03:27 +00006341 /* Append cells to the end of the page */
6342 pCellptr = &pPg->aCellIdx[nCell*2];
6343 if( pageInsertArray(
6344 pPg, pBegin, &pData, pCellptr,
6345 nNew-nCell, &apCell[iNew+nCell], &szCell[iNew+nCell]
6346 ) ) goto editpage_fail;
dan09c68402014-10-11 20:00:24 +00006347
dand7b545b2014-10-13 18:03:27 +00006348 pPg->nCell = nNew;
6349 pPg->nOverflow = 0;
dan09c68402014-10-11 20:00:24 +00006350
dand7b545b2014-10-13 18:03:27 +00006351 put2byte(&aData[hdr+3], pPg->nCell);
6352 put2byte(&aData[hdr+5], pData - aData);
dan09c68402014-10-11 20:00:24 +00006353
6354#ifdef SQLITE_DEBUG
dan23eba452014-10-24 18:43:57 +00006355 for(i=0; i<nNew && !CORRUPT_DB; i++){
dand7b545b2014-10-13 18:03:27 +00006356 u8 *pCell = apCell[i+iNew];
6357 int iOff = get2byte(&pPg->aCellIdx[i*2]);
6358 if( pCell>=aData && pCell<&aData[pPg->pBt->usableSize] ){
6359 pCell = &pTmp[pCell - aData];
dan09c68402014-10-11 20:00:24 +00006360 }
dand7b545b2014-10-13 18:03:27 +00006361 assert( 0==memcmp(pCell, &aData[iOff], szCell[i+iNew]) );
6362 }
dan09c68402014-10-11 20:00:24 +00006363#endif
6364
dand7b545b2014-10-13 18:03:27 +00006365 return;
dan09c68402014-10-11 20:00:24 +00006366 editpage_fail:
dan09c68402014-10-11 20:00:24 +00006367 /* Unable to edit this page. Rebuild it from scratch instead. */
6368 rebuildPage(pPg, nNew, &apCell[iNew], &szCell[iNew]);
6369}
6370
drh14acc042001-06-10 19:56:58 +00006371/*
drhc3b70572003-01-04 19:44:07 +00006372** The following parameters determine how many adjacent pages get involved
6373** in a balancing operation. NN is the number of neighbors on either side
6374** of the page that participate in the balancing operation. NB is the
6375** total number of pages that participate, including the target page and
6376** NN neighbors on either side.
6377**
6378** The minimum value of NN is 1 (of course). Increasing NN above 1
6379** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
6380** in exchange for a larger degradation in INSERT and UPDATE performance.
6381** The value of NN appears to give the best results overall.
6382*/
6383#define NN 1 /* Number of neighbors on either side of pPage */
6384#define NB (NN*2+1) /* Total pages involved in the balance */
6385
danielk1977ac245ec2005-01-14 13:50:11 +00006386
drh615ae552005-01-16 23:21:00 +00006387#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00006388/*
6389** This version of balance() handles the common special case where
6390** a new entry is being inserted on the extreme right-end of the
6391** tree, in other words, when the new entry will become the largest
6392** entry in the tree.
6393**
drhc314dc72009-07-21 11:52:34 +00006394** Instead of trying to balance the 3 right-most leaf pages, just add
drhf222e712005-01-14 22:55:49 +00006395** a new page to the right-hand side and put the one new entry in
6396** that page. This leaves the right side of the tree somewhat
6397** unbalanced. But odds are that we will be inserting new entries
6398** at the end soon afterwards so the nearly empty page will quickly
6399** fill up. On average.
6400**
6401** pPage is the leaf page which is the right-most page in the tree.
6402** pParent is its parent. pPage must have a single overflow entry
6403** which is also the right-most entry on the page.
danielk1977a50d9aa2009-06-08 14:49:45 +00006404**
6405** The pSpace buffer is used to store a temporary copy of the divider
6406** cell that will be inserted into pParent. Such a cell consists of a 4
6407** byte page number followed by a variable length integer. In other
6408** words, at most 13 bytes. Hence the pSpace buffer must be at
6409** least 13 bytes in size.
drhf222e712005-01-14 22:55:49 +00006410*/
danielk1977a50d9aa2009-06-08 14:49:45 +00006411static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
6412 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
danielk19774dbaa892009-06-16 16:50:22 +00006413 MemPage *pNew; /* Newly allocated page */
danielk19776f235cc2009-06-04 14:46:08 +00006414 int rc; /* Return Code */
6415 Pgno pgnoNew; /* Page number of pNew */
danielk1977ac245ec2005-01-14 13:50:11 +00006416
drh1fee73e2007-08-29 04:00:57 +00006417 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk1977a50d9aa2009-06-08 14:49:45 +00006418 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00006419 assert( pPage->nOverflow==1 );
6420
drh5d433ce2010-08-14 16:02:52 +00006421 /* This error condition is now caught prior to reaching this function */
drh1fd2d7d2014-12-02 16:16:47 +00006422 if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
drhd677b3d2007-08-20 22:48:41 +00006423
danielk1977a50d9aa2009-06-08 14:49:45 +00006424 /* Allocate a new page. This page will become the right-sibling of
6425 ** pPage. Make the parent page writable, so that the new divider cell
6426 ** may be inserted. If both these operations are successful, proceed.
6427 */
drh4f0c5872007-03-26 22:05:01 +00006428 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk19774dbaa892009-06-16 16:50:22 +00006429
danielk1977eaa06f62008-09-18 17:34:44 +00006430 if( rc==SQLITE_OK ){
danielk1977a50d9aa2009-06-08 14:49:45 +00006431
6432 u8 *pOut = &pSpace[4];
drh2cbd78b2012-02-02 19:37:18 +00006433 u8 *pCell = pPage->apOvfl[0];
danielk19776f235cc2009-06-04 14:46:08 +00006434 u16 szCell = cellSizePtr(pPage, pCell);
6435 u8 *pStop;
6436
drhc5053fb2008-11-27 02:22:10 +00006437 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00006438 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
6439 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
dan8e9ba0c2014-10-14 17:27:04 +00006440 rebuildPage(pNew, 1, &pCell, &szCell);
6441 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
danielk19774dbaa892009-06-16 16:50:22 +00006442
6443 /* If this is an auto-vacuum database, update the pointer map
6444 ** with entries for the new page, and any pointer from the
6445 ** cell on the page to an overflow page. If either of these
6446 ** operations fails, the return code is set, but the contents
6447 ** of the parent page are still manipulated by thh code below.
6448 ** That is Ok, at this point the parent page is guaranteed to
6449 ** be marked as dirty. Returning an error code will cause a
6450 ** rollback, undoing any changes made to the parent page.
6451 */
6452 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00006453 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
6454 if( szCell>pNew->minLocal ){
6455 ptrmapPutOvflPtr(pNew, pCell, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006456 }
6457 }
danielk1977eaa06f62008-09-18 17:34:44 +00006458
danielk19776f235cc2009-06-04 14:46:08 +00006459 /* Create a divider cell to insert into pParent. The divider cell
6460 ** consists of a 4-byte page number (the page number of pPage) and
6461 ** a variable length key value (which must be the same value as the
6462 ** largest key on pPage).
danielk1977eaa06f62008-09-18 17:34:44 +00006463 **
danielk19776f235cc2009-06-04 14:46:08 +00006464 ** To find the largest key value on pPage, first find the right-most
6465 ** cell on pPage. The first two fields of this cell are the
6466 ** record-length (a variable length integer at most 32-bits in size)
6467 ** and the key value (a variable length integer, may have any value).
6468 ** The first of the while(...) loops below skips over the record-length
6469 ** field. The second while(...) loop copies the key value from the
danielk1977a50d9aa2009-06-08 14:49:45 +00006470 ** cell on pPage into the pSpace buffer.
danielk1977eaa06f62008-09-18 17:34:44 +00006471 */
danielk1977eaa06f62008-09-18 17:34:44 +00006472 pCell = findCell(pPage, pPage->nCell-1);
danielk19776f235cc2009-06-04 14:46:08 +00006473 pStop = &pCell[9];
6474 while( (*(pCell++)&0x80) && pCell<pStop );
6475 pStop = &pCell[9];
6476 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
6477
danielk19774dbaa892009-06-16 16:50:22 +00006478 /* Insert the new divider cell into pParent. */
drh98add2e2009-07-20 17:11:49 +00006479 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
6480 0, pPage->pgno, &rc);
danielk19776f235cc2009-06-04 14:46:08 +00006481
6482 /* Set the right-child pointer of pParent to point to the new page. */
danielk1977eaa06f62008-09-18 17:34:44 +00006483 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
6484
danielk1977e08a3c42008-09-18 18:17:03 +00006485 /* Release the reference to the new page. */
6486 releasePage(pNew);
danielk1977ac11ee62005-01-15 12:45:51 +00006487 }
6488
danielk1977eaa06f62008-09-18 17:34:44 +00006489 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00006490}
drh615ae552005-01-16 23:21:00 +00006491#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00006492
dane6593d82014-10-24 16:40:49 +00006493#if 0
drhc3b70572003-01-04 19:44:07 +00006494/*
danielk19774dbaa892009-06-16 16:50:22 +00006495** This function does not contribute anything to the operation of SQLite.
6496** it is sometimes activated temporarily while debugging code responsible
6497** for setting pointer-map entries.
6498*/
6499static int ptrmapCheckPages(MemPage **apPage, int nPage){
6500 int i, j;
6501 for(i=0; i<nPage; i++){
6502 Pgno n;
6503 u8 e;
6504 MemPage *pPage = apPage[i];
6505 BtShared *pBt = pPage->pBt;
6506 assert( pPage->isInit );
6507
6508 for(j=0; j<pPage->nCell; j++){
6509 CellInfo info;
6510 u8 *z;
6511
6512 z = findCell(pPage, j);
danielk197730548662009-07-09 05:07:37 +00006513 btreeParseCellPtr(pPage, z, &info);
danielk19774dbaa892009-06-16 16:50:22 +00006514 if( info.iOverflow ){
6515 Pgno ovfl = get4byte(&z[info.iOverflow]);
6516 ptrmapGet(pBt, ovfl, &e, &n);
6517 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
6518 }
6519 if( !pPage->leaf ){
6520 Pgno child = get4byte(z);
6521 ptrmapGet(pBt, child, &e, &n);
6522 assert( n==pPage->pgno && e==PTRMAP_BTREE );
6523 }
6524 }
6525 if( !pPage->leaf ){
6526 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
6527 ptrmapGet(pBt, child, &e, &n);
6528 assert( n==pPage->pgno && e==PTRMAP_BTREE );
6529 }
6530 }
6531 return 1;
6532}
6533#endif
6534
danielk1977cd581a72009-06-23 15:43:39 +00006535/*
6536** This function is used to copy the contents of the b-tree node stored
6537** on page pFrom to page pTo. If page pFrom was not a leaf page, then
6538** the pointer-map entries for each child page are updated so that the
6539** parent page stored in the pointer map is page pTo. If pFrom contained
6540** any cells with overflow page pointers, then the corresponding pointer
6541** map entries are also updated so that the parent page is page pTo.
6542**
6543** If pFrom is currently carrying any overflow cells (entries in the
drh2cbd78b2012-02-02 19:37:18 +00006544** MemPage.apOvfl[] array), they are not copied to pTo.
danielk1977cd581a72009-06-23 15:43:39 +00006545**
danielk197730548662009-07-09 05:07:37 +00006546** Before returning, page pTo is reinitialized using btreeInitPage().
danielk1977cd581a72009-06-23 15:43:39 +00006547**
6548** The performance of this function is not critical. It is only used by
6549** the balance_shallower() and balance_deeper() procedures, neither of
6550** which are called often under normal circumstances.
6551*/
drhc314dc72009-07-21 11:52:34 +00006552static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
6553 if( (*pRC)==SQLITE_OK ){
6554 BtShared * const pBt = pFrom->pBt;
6555 u8 * const aFrom = pFrom->aData;
6556 u8 * const aTo = pTo->aData;
6557 int const iFromHdr = pFrom->hdrOffset;
6558 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
drhdc9b5f82009-12-05 18:34:08 +00006559 int rc;
drhc314dc72009-07-21 11:52:34 +00006560 int iData;
6561
6562
6563 assert( pFrom->isInit );
6564 assert( pFrom->nFree>=iToHdr );
drhfcd71b62011-04-05 22:08:24 +00006565 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
drhc314dc72009-07-21 11:52:34 +00006566
6567 /* Copy the b-tree node content from page pFrom to page pTo. */
6568 iData = get2byte(&aFrom[iFromHdr+5]);
6569 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
6570 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
6571
6572 /* Reinitialize page pTo so that the contents of the MemPage structure
dan89e060e2009-12-05 18:03:50 +00006573 ** match the new data. The initialization of pTo can actually fail under
6574 ** fairly obscure circumstances, even though it is a copy of initialized
6575 ** page pFrom.
6576 */
drhc314dc72009-07-21 11:52:34 +00006577 pTo->isInit = 0;
dan89e060e2009-12-05 18:03:50 +00006578 rc = btreeInitPage(pTo);
6579 if( rc!=SQLITE_OK ){
6580 *pRC = rc;
6581 return;
6582 }
drhc314dc72009-07-21 11:52:34 +00006583
6584 /* If this is an auto-vacuum database, update the pointer-map entries
6585 ** for any b-tree or overflow pages that pTo now contains the pointers to.
6586 */
6587 if( ISAUTOVACUUM ){
6588 *pRC = setChildPtrmaps(pTo);
6589 }
danielk1977cd581a72009-06-23 15:43:39 +00006590 }
danielk1977cd581a72009-06-23 15:43:39 +00006591}
6592
6593/*
danielk19774dbaa892009-06-16 16:50:22 +00006594** This routine redistributes cells on the iParentIdx'th child of pParent
6595** (hereafter "the page") and up to 2 siblings so that all pages have about the
6596** same amount of free space. Usually a single sibling on either side of the
6597** page are used in the balancing, though both siblings might come from one
6598** side if the page is the first or last child of its parent. If the page
6599** has fewer than 2 siblings (something which can only happen if the page
6600** is a root page or a child of a root page) then all available siblings
6601** participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00006602**
danielk19774dbaa892009-06-16 16:50:22 +00006603** The number of siblings of the page might be increased or decreased by
6604** one or two in an effort to keep pages nearly full but not over full.
drh14acc042001-06-10 19:56:58 +00006605**
danielk19774dbaa892009-06-16 16:50:22 +00006606** Note that when this routine is called, some of the cells on the page
6607** might not actually be stored in MemPage.aData[]. This can happen
6608** if the page is overfull. This routine ensures that all cells allocated
6609** to the page and its siblings fit into MemPage.aData[] before returning.
drh14acc042001-06-10 19:56:58 +00006610**
danielk19774dbaa892009-06-16 16:50:22 +00006611** In the course of balancing the page and its siblings, cells may be
6612** inserted into or removed from the parent page (pParent). Doing so
6613** may cause the parent page to become overfull or underfull. If this
6614** happens, it is the responsibility of the caller to invoke the correct
6615** balancing routine to fix this problem (see the balance() routine).
drh8c42ca92001-06-22 19:15:00 +00006616**
drh5e00f6c2001-09-13 13:46:56 +00006617** If this routine fails for any reason, it might leave the database
danielk19776067a9b2009-06-09 09:41:00 +00006618** in a corrupted state. So if this routine fails, the database should
drh5e00f6c2001-09-13 13:46:56 +00006619** be rolled back.
danielk19774dbaa892009-06-16 16:50:22 +00006620**
6621** The third argument to this function, aOvflSpace, is a pointer to a
drhcd09c532009-07-20 19:30:00 +00006622** buffer big enough to hold one page. If while inserting cells into the parent
6623** page (pParent) the parent page becomes overfull, this buffer is
6624** used to store the parent's overflow cells. Because this function inserts
danielk19774dbaa892009-06-16 16:50:22 +00006625** a maximum of four divider cells into the parent page, and the maximum
6626** size of a cell stored within an internal node is always less than 1/4
6627** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
6628** enough for all overflow cells.
6629**
6630** If aOvflSpace is set to a null pointer, this function returns
6631** SQLITE_NOMEM.
drh8b2f49b2001-06-08 00:21:52 +00006632*/
mistachkine7c54162012-10-02 22:54:27 +00006633#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
6634#pragma optimize("", off)
6635#endif
danielk19774dbaa892009-06-16 16:50:22 +00006636static int balance_nonroot(
6637 MemPage *pParent, /* Parent page of siblings being balanced */
6638 int iParentIdx, /* Index of "the page" in pParent */
danielk1977cd581a72009-06-23 15:43:39 +00006639 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
dan428c2182012-08-06 18:50:11 +00006640 int isRoot, /* True if pParent is a root-page */
6641 int bBulk /* True if this call is part of a bulk load */
danielk19774dbaa892009-06-16 16:50:22 +00006642){
drh16a9b832007-05-05 18:39:25 +00006643 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00006644 int nCell = 0; /* Number of cells in apCell[] */
6645 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
danielk1977a4124bd2008-12-23 10:37:47 +00006646 int nNew = 0; /* Number of pages in apNew[] */
danielk19774dbaa892009-06-16 16:50:22 +00006647 int nOld; /* Number of pages in apOld[] */
drh14acc042001-06-10 19:56:58 +00006648 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00006649 int nxDiv; /* Next divider slot in pParent->aCell[] */
shane85095702009-06-15 16:27:08 +00006650 int rc = SQLITE_OK; /* The return code */
shane36840fd2009-06-26 16:32:13 +00006651 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00006652 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00006653 int usableSpace; /* Bytes in pPage beyond the header */
6654 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00006655 int subtotal; /* Subtotal of bytes in cells on one page */
drhe5ae5732008-06-15 02:51:47 +00006656 int iSpace1 = 0; /* First unused byte of aSpace1[] */
danielk19776067a9b2009-06-09 09:41:00 +00006657 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
drhfacf0302008-06-17 15:12:00 +00006658 int szScratch; /* Size of scratch memory requested */
drhc3b70572003-01-04 19:44:07 +00006659 MemPage *apOld[NB]; /* pPage and up to two siblings */
drha2fce642004-06-05 00:01:44 +00006660 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
danielk19774dbaa892009-06-16 16:50:22 +00006661 u8 *pRight; /* Location in parent of right-sibling pointer */
6662 u8 *apDiv[NB-1]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00006663 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
dan09c68402014-10-11 20:00:24 +00006664 int cntOld[NB+2]; /* Old index in aCell[] after i-th page */
drh2a0df922014-10-30 23:14:56 +00006665 int szNew[NB+2]; /* Combined size of cells placed on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00006666 u8 **apCell = 0; /* All cells begin balanced */
drha9121e42008-02-19 14:59:35 +00006667 u16 *szCell; /* Local size of all cells in apCell[] */
danielk19774dbaa892009-06-16 16:50:22 +00006668 u8 *aSpace1; /* Space for copies of dividers cells */
6669 Pgno pgno; /* Temp var to store a page number in */
dane6593d82014-10-24 16:40:49 +00006670 u8 abDone[NB+2]; /* True after i'th new page is populated */
6671 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
drh00fe08a2014-10-31 00:05:23 +00006672 Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
dane6593d82014-10-24 16:40:49 +00006673 u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
dan33ea4862014-10-09 19:35:37 +00006674
6675 memset(abDone, 0, sizeof(abDone));
danielk1977a50d9aa2009-06-08 14:49:45 +00006676 pBt = pParent->pBt;
6677 assert( sqlite3_mutex_held(pBt->mutex) );
6678 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977474b7cc2008-07-09 11:49:46 +00006679
danielk1977e5765212009-06-17 11:13:28 +00006680#if 0
drh43605152004-05-29 21:46:49 +00006681 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
danielk1977e5765212009-06-17 11:13:28 +00006682#endif
drh2e38c322004-09-03 18:38:44 +00006683
danielk19774dbaa892009-06-16 16:50:22 +00006684 /* At this point pParent may have at most one overflow cell. And if
6685 ** this overflow cell is present, it must be the cell with
6686 ** index iParentIdx. This scenario comes about when this function
drhcd09c532009-07-20 19:30:00 +00006687 ** is called (indirectly) from sqlite3BtreeDelete().
6688 */
danielk19774dbaa892009-06-16 16:50:22 +00006689 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
drh2cbd78b2012-02-02 19:37:18 +00006690 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
danielk19774dbaa892009-06-16 16:50:22 +00006691
danielk197711a8a862009-06-17 11:49:52 +00006692 if( !aOvflSpace ){
6693 return SQLITE_NOMEM;
6694 }
6695
danielk1977a50d9aa2009-06-08 14:49:45 +00006696 /* Find the sibling pages to balance. Also locate the cells in pParent
6697 ** that divide the siblings. An attempt is made to find NN siblings on
6698 ** either side of pPage. More siblings are taken from one side, however,
6699 ** if there are fewer than NN siblings on the other side. If pParent
danielk19774dbaa892009-06-16 16:50:22 +00006700 ** has NB or fewer children then all children of pParent are taken.
6701 **
6702 ** This loop also drops the divider cells from the parent page. This
6703 ** way, the remainder of the function does not have to deal with any
drhcd09c532009-07-20 19:30:00 +00006704 ** overflow cells in the parent page, since if any existed they will
6705 ** have already been removed.
6706 */
danielk19774dbaa892009-06-16 16:50:22 +00006707 i = pParent->nOverflow + pParent->nCell;
6708 if( i<2 ){
drhc3b70572003-01-04 19:44:07 +00006709 nxDiv = 0;
danielk19774dbaa892009-06-16 16:50:22 +00006710 }else{
dan7d6885a2012-08-08 14:04:56 +00006711 assert( bBulk==0 || bBulk==1 );
danielk19774dbaa892009-06-16 16:50:22 +00006712 if( iParentIdx==0 ){
6713 nxDiv = 0;
6714 }else if( iParentIdx==i ){
dan7d6885a2012-08-08 14:04:56 +00006715 nxDiv = i-2+bBulk;
drh14acc042001-06-10 19:56:58 +00006716 }else{
dan7d6885a2012-08-08 14:04:56 +00006717 assert( bBulk==0 );
danielk19774dbaa892009-06-16 16:50:22 +00006718 nxDiv = iParentIdx-1;
drh8b2f49b2001-06-08 00:21:52 +00006719 }
dan7d6885a2012-08-08 14:04:56 +00006720 i = 2-bBulk;
danielk19774dbaa892009-06-16 16:50:22 +00006721 }
dan7d6885a2012-08-08 14:04:56 +00006722 nOld = i+1;
danielk19774dbaa892009-06-16 16:50:22 +00006723 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
6724 pRight = &pParent->aData[pParent->hdrOffset+8];
6725 }else{
6726 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
6727 }
6728 pgno = get4byte(pRight);
6729 while( 1 ){
dan11dcd112013-03-15 18:29:18 +00006730 rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
danielk19774dbaa892009-06-16 16:50:22 +00006731 if( rc ){
danielk197789bc4bc2009-07-21 19:25:24 +00006732 memset(apOld, 0, (i+1)*sizeof(MemPage*));
danielk19774dbaa892009-06-16 16:50:22 +00006733 goto balance_cleanup;
6734 }
danielk1977634f2982005-03-28 08:44:07 +00006735 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
danielk19774dbaa892009-06-16 16:50:22 +00006736 if( (i--)==0 ) break;
6737
drh2cbd78b2012-02-02 19:37:18 +00006738 if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
6739 apDiv[i] = pParent->apOvfl[0];
danielk19774dbaa892009-06-16 16:50:22 +00006740 pgno = get4byte(apDiv[i]);
6741 szNew[i] = cellSizePtr(pParent, apDiv[i]);
6742 pParent->nOverflow = 0;
6743 }else{
6744 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
6745 pgno = get4byte(apDiv[i]);
6746 szNew[i] = cellSizePtr(pParent, apDiv[i]);
6747
6748 /* Drop the cell from the parent page. apDiv[i] still points to
6749 ** the cell within the parent, even though it has been dropped.
6750 ** This is safe because dropping a cell only overwrites the first
6751 ** four bytes of it, and this function does not need the first
6752 ** four bytes of the divider cell. So the pointer is safe to use
danielk197711a8a862009-06-17 11:49:52 +00006753 ** later on.
6754 **
drh8a575d92011-10-12 17:00:28 +00006755 ** But not if we are in secure-delete mode. In secure-delete mode,
danielk197711a8a862009-06-17 11:49:52 +00006756 ** the dropCell() routine will overwrite the entire cell with zeroes.
6757 ** In this case, temporarily copy the cell into the aOvflSpace[]
6758 ** buffer. It will be copied out again as soon as the aSpace[] buffer
6759 ** is allocated. */
drhc9166342012-01-05 23:32:06 +00006760 if( pBt->btsFlags & BTS_SECURE_DELETE ){
drh8a575d92011-10-12 17:00:28 +00006761 int iOff;
6762
6763 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
drh43b18e12010-08-17 19:40:08 +00006764 if( (iOff+szNew[i])>(int)pBt->usableSize ){
dan2ed11e72010-02-26 15:09:19 +00006765 rc = SQLITE_CORRUPT_BKPT;
6766 memset(apOld, 0, (i+1)*sizeof(MemPage*));
6767 goto balance_cleanup;
6768 }else{
6769 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
6770 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
6771 }
drh5b47efa2010-02-12 18:18:39 +00006772 }
drh98add2e2009-07-20 17:11:49 +00006773 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006774 }
drh8b2f49b2001-06-08 00:21:52 +00006775 }
6776
drha9121e42008-02-19 14:59:35 +00006777 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00006778 ** alignment */
drha9121e42008-02-19 14:59:35 +00006779 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00006780
drh8b2f49b2001-06-08 00:21:52 +00006781 /*
danielk1977634f2982005-03-28 08:44:07 +00006782 ** Allocate space for memory structures
6783 */
drhfacf0302008-06-17 15:12:00 +00006784 szScratch =
drha9121e42008-02-19 14:59:35 +00006785 nMaxCells*sizeof(u8*) /* apCell */
6786 + nMaxCells*sizeof(u16) /* szCell */
dan33ea4862014-10-09 19:35:37 +00006787 + pBt->pageSize; /* aSpace1 */
drh5279d342014-11-04 13:41:32 +00006788
drhcbd55b02014-11-04 14:22:27 +00006789 /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
6790 ** that is more than 6 times the database page size. */
mistachkin0fbd7352014-12-09 04:26:56 +00006791 assert( szScratch<=6*(int)pBt->pageSize );
drhfacf0302008-06-17 15:12:00 +00006792 apCell = sqlite3ScratchMalloc( szScratch );
danielk197711a8a862009-06-17 11:49:52 +00006793 if( apCell==0 ){
danielk1977634f2982005-03-28 08:44:07 +00006794 rc = SQLITE_NOMEM;
6795 goto balance_cleanup;
6796 }
drha9121e42008-02-19 14:59:35 +00006797 szCell = (u16*)&apCell[nMaxCells];
danielk19774dbaa892009-06-16 16:50:22 +00006798 aSpace1 = (u8*)&szCell[nMaxCells];
drhea598cb2009-04-05 12:22:08 +00006799 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
drh14acc042001-06-10 19:56:58 +00006800
6801 /*
6802 ** Load pointers to all cells on sibling pages and the divider cells
6803 ** into the local apCell[] array. Make copies of the divider cells
dan33ea4862014-10-09 19:35:37 +00006804 ** into space obtained from aSpace1[]. The divider cells have already
6805 ** been removed from pParent.
drh4b70f112004-05-02 21:12:19 +00006806 **
6807 ** If the siblings are on leaf pages, then the child pointers of the
6808 ** divider cells are stripped from the cells before they are copied
drhe5ae5732008-06-15 02:51:47 +00006809 ** into aSpace1[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00006810 ** child pointers. If siblings are not leaves, then all cell in
6811 ** apCell[] include child pointers. Either way, all cells in apCell[]
6812 ** are alike.
drh96f5b762004-05-16 16:24:36 +00006813 **
6814 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
6815 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00006816 */
danielk1977a50d9aa2009-06-08 14:49:45 +00006817 leafCorrection = apOld[0]->leaf*4;
drh3e28ff52014-09-24 00:59:08 +00006818 leafData = apOld[0]->intKeyLeaf;
drh8b2f49b2001-06-08 00:21:52 +00006819 for(i=0; i<nOld; i++){
danielk19774dbaa892009-06-16 16:50:22 +00006820 int limit;
dan33ea4862014-10-09 19:35:37 +00006821 MemPage *pOld = apOld[i];
danielk19774dbaa892009-06-16 16:50:22 +00006822
6823 limit = pOld->nCell+pOld->nOverflow;
drh68f2a572011-06-03 17:50:49 +00006824 if( pOld->nOverflow>0 ){
6825 for(j=0; j<limit; j++){
6826 assert( nCell<nMaxCells );
6827 apCell[nCell] = findOverflowCell(pOld, j);
6828 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
6829 nCell++;
6830 }
6831 }else{
6832 u8 *aData = pOld->aData;
6833 u16 maskPage = pOld->maskPage;
6834 u16 cellOffset = pOld->cellOffset;
6835 for(j=0; j<limit; j++){
6836 assert( nCell<nMaxCells );
6837 apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
6838 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
6839 nCell++;
6840 }
6841 }
dan09c68402014-10-11 20:00:24 +00006842 cntOld[i] = nCell;
danielk19774dbaa892009-06-16 16:50:22 +00006843 if( i<nOld-1 && !leafData){
shane36840fd2009-06-26 16:32:13 +00006844 u16 sz = (u16)szNew[i];
danielk19774dbaa892009-06-16 16:50:22 +00006845 u8 *pTemp;
6846 assert( nCell<nMaxCells );
6847 szCell[nCell] = sz;
6848 pTemp = &aSpace1[iSpace1];
6849 iSpace1 += sz;
drhe22e03e2010-08-18 21:19:03 +00006850 assert( sz<=pBt->maxLocal+23 );
drhfcd71b62011-04-05 22:08:24 +00006851 assert( iSpace1 <= (int)pBt->pageSize );
danielk19774dbaa892009-06-16 16:50:22 +00006852 memcpy(pTemp, apDiv[i], sz);
6853 apCell[nCell] = pTemp+leafCorrection;
6854 assert( leafCorrection==0 || leafCorrection==4 );
shane36840fd2009-06-26 16:32:13 +00006855 szCell[nCell] = szCell[nCell] - leafCorrection;
danielk19774dbaa892009-06-16 16:50:22 +00006856 if( !pOld->leaf ){
6857 assert( leafCorrection==0 );
6858 assert( pOld->hdrOffset==0 );
6859 /* The right pointer of the child page pOld becomes the left
6860 ** pointer of the divider cell */
6861 memcpy(apCell[nCell], &pOld->aData[8], 4);
6862 }else{
6863 assert( leafCorrection==4 );
6864 if( szCell[nCell]<4 ){
dan8f1eb8a2014-12-06 14:56:49 +00006865 /* Do not allow any cells smaller than 4 bytes. If a smaller cell
6866 ** does exist, pad it with 0x00 bytes. */
6867 assert( szCell[nCell]==3 );
danee7172f2014-12-24 18:11:50 +00006868 assert( apCell[nCell]==&aSpace1[iSpace1-3] );
6869 aSpace1[iSpace1++] = 0x00;
danielk19774dbaa892009-06-16 16:50:22 +00006870 szCell[nCell] = 4;
danielk1977ac11ee62005-01-15 12:45:51 +00006871 }
6872 }
drh14acc042001-06-10 19:56:58 +00006873 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00006874 }
drh8b2f49b2001-06-08 00:21:52 +00006875 }
6876
6877 /*
drh6019e162001-07-02 17:51:45 +00006878 ** Figure out the number of pages needed to hold all nCell cells.
6879 ** Store this number in "k". Also compute szNew[] which is the total
6880 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00006881 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00006882 ** cntNew[k] should equal nCell.
6883 **
drh96f5b762004-05-16 16:24:36 +00006884 ** Values computed by this block:
6885 **
6886 ** k: The total number of sibling pages
6887 ** szNew[i]: Spaced used on the i-th sibling page.
6888 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
6889 ** the right of the i-th sibling page.
6890 ** usableSpace: Number of bytes of space available on each sibling.
6891 **
drh8b2f49b2001-06-08 00:21:52 +00006892 */
drh43605152004-05-29 21:46:49 +00006893 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00006894 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00006895 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00006896 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00006897 if( subtotal > usableSpace ){
dand7b545b2014-10-13 18:03:27 +00006898 szNew[k] = subtotal - szCell[i] - 2;
drh6019e162001-07-02 17:51:45 +00006899 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00006900 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00006901 subtotal = 0;
6902 k++;
drh9978c972010-02-23 17:36:32 +00006903 if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
drh6019e162001-07-02 17:51:45 +00006904 }
6905 }
6906 szNew[k] = subtotal;
6907 cntNew[k] = nCell;
6908 k++;
drh96f5b762004-05-16 16:24:36 +00006909
6910 /*
6911 ** The packing computed by the previous block is biased toward the siblings
drh2a0df922014-10-30 23:14:56 +00006912 ** on the left side (siblings with smaller keys). The left siblings are
6913 ** always nearly full, while the right-most sibling might be nearly empty.
6914 ** The next block of code attempts to adjust the packing of siblings to
6915 ** get a better balance.
drh96f5b762004-05-16 16:24:36 +00006916 **
6917 ** This adjustment is more than an optimization. The packing above might
6918 ** be so out of balance as to be illegal. For example, the right-most
6919 ** sibling might be completely empty. This adjustment is not optional.
6920 */
drh6019e162001-07-02 17:51:45 +00006921 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00006922 int szRight = szNew[i]; /* Size of sibling on the right */
6923 int szLeft = szNew[i-1]; /* Size of sibling on the left */
6924 int r; /* Index of right-most cell in left sibling */
6925 int d; /* Index of first cell to the left of right sibling */
6926
6927 r = cntNew[i-1] - 1;
6928 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00006929 assert( d<nMaxCells );
6930 assert( r<nMaxCells );
danf64cc492012-08-08 11:55:15 +00006931 while( szRight==0
6932 || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
6933 ){
drh43605152004-05-29 21:46:49 +00006934 szRight += szCell[d] + 2;
6935 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00006936 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00006937 r = cntNew[i-1] - 1;
6938 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00006939 }
drh96f5b762004-05-16 16:24:36 +00006940 szNew[i] = szRight;
6941 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00006942 }
drh09d0deb2005-08-02 17:13:09 +00006943
drh2a0df922014-10-30 23:14:56 +00006944 /* Sanity check: For a non-corrupt database file one of the follwing
6945 ** must be true:
6946 ** (1) We found one or more cells (cntNew[0])>0), or
6947 ** (2) pPage is a virtual root page. A virtual root page is when
6948 ** the real root page is page 1 and we are the only child of
6949 ** that page.
drh09d0deb2005-08-02 17:13:09 +00006950 */
drh2a0df922014-10-30 23:14:56 +00006951 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
dan33ea4862014-10-09 19:35:37 +00006952 TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
6953 apOld[0]->pgno, apOld[0]->nCell,
6954 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
6955 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
danielk1977e5765212009-06-17 11:13:28 +00006956 ));
6957
drh8b2f49b2001-06-08 00:21:52 +00006958 /*
drh6b308672002-07-08 02:16:37 +00006959 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00006960 */
drheac74422009-06-14 12:47:11 +00006961 if( apOld[0]->pgno<=1 ){
drh9978c972010-02-23 17:36:32 +00006962 rc = SQLITE_CORRUPT_BKPT;
drheac74422009-06-14 12:47:11 +00006963 goto balance_cleanup;
6964 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006965 pageFlags = apOld[0]->aData[0];
drh14acc042001-06-10 19:56:58 +00006966 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00006967 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00006968 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00006969 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00006970 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00006971 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00006972 nNew++;
danielk197728129562005-01-11 10:25:06 +00006973 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00006974 }else{
drh7aa8f852006-03-28 00:24:44 +00006975 assert( i>0 );
dan428c2182012-08-06 18:50:11 +00006976 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
drh6b308672002-07-08 02:16:37 +00006977 if( rc ) goto balance_cleanup;
dan33ea4862014-10-09 19:35:37 +00006978 zeroPage(pNew, pageFlags);
drhda200cc2004-05-09 11:51:38 +00006979 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00006980 nNew++;
dan09c68402014-10-11 20:00:24 +00006981 cntOld[i] = nCell;
danielk19774dbaa892009-06-16 16:50:22 +00006982
6983 /* Set the pointer-map entry for the new sibling page. */
6984 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00006985 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006986 if( rc!=SQLITE_OK ){
6987 goto balance_cleanup;
6988 }
6989 }
drh6b308672002-07-08 02:16:37 +00006990 }
drh8b2f49b2001-06-08 00:21:52 +00006991 }
6992
6993 /*
dan33ea4862014-10-09 19:35:37 +00006994 ** Reassign page numbers so that the new pages are in ascending order.
6995 ** This helps to keep entries in the disk file in order so that a scan
6996 ** of the table is closer to a linear scan through the file. That in turn
6997 ** helps the operating system to deliver pages from the disk more rapidly.
drhf9ffac92002-03-02 19:00:31 +00006998 **
dan33ea4862014-10-09 19:35:37 +00006999 ** An O(n^2) insertion sort algorithm is used, but since n is never more
7000 ** than (NB+2) (a small constant), that should not be a problem.
drhf9ffac92002-03-02 19:00:31 +00007001 **
dan33ea4862014-10-09 19:35:37 +00007002 ** When NB==3, this one optimization makes the database about 25% faster
7003 ** for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00007004 */
dan33ea4862014-10-09 19:35:37 +00007005 for(i=0; i<nNew; i++){
drh00fe08a2014-10-31 00:05:23 +00007006 aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
dan33ea4862014-10-09 19:35:37 +00007007 aPgFlags[i] = apNew[i]->pDbPage->flags;
dan89ca0b32014-10-25 20:36:28 +00007008 for(j=0; j<i; j++){
7009 if( aPgno[j]==aPgno[i] ){
7010 /* This branch is taken if the set of sibling pages somehow contains
7011 ** duplicate entries. This can happen if the database is corrupt.
7012 ** It would be simpler to detect this as part of the loop below, but
drhba0f9992014-10-30 20:48:44 +00007013 ** we do the detection here in order to avoid populating the pager
7014 ** cache with two separate objects associated with the same
7015 ** page number. */
dan89ca0b32014-10-25 20:36:28 +00007016 assert( CORRUPT_DB );
7017 rc = SQLITE_CORRUPT_BKPT;
7018 goto balance_cleanup;
7019 }
7020 }
dan33ea4862014-10-09 19:35:37 +00007021 }
7022 for(i=0; i<nNew; i++){
dan31f4e992014-10-24 20:57:03 +00007023 int iBest = 0; /* aPgno[] index of page number to use */
dan31f4e992014-10-24 20:57:03 +00007024 for(j=1; j<nNew; j++){
drh00fe08a2014-10-31 00:05:23 +00007025 if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
drhf9ffac92002-03-02 19:00:31 +00007026 }
drh00fe08a2014-10-31 00:05:23 +00007027 pgno = aPgOrder[iBest];
7028 aPgOrder[iBest] = 0xffffffff;
dan31f4e992014-10-24 20:57:03 +00007029 if( iBest!=i ){
7030 if( iBest>i ){
7031 sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
7032 }
7033 sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
7034 apNew[i]->pgno = pgno;
drhf9ffac92002-03-02 19:00:31 +00007035 }
7036 }
dan33ea4862014-10-09 19:35:37 +00007037
7038 TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
7039 "%d(%d nc=%d) %d(%d nc=%d)\n",
7040 apNew[0]->pgno, szNew[0], cntNew[0],
danielk19774dbaa892009-06-16 16:50:22 +00007041 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
dan33ea4862014-10-09 19:35:37 +00007042 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
danielk19774dbaa892009-06-16 16:50:22 +00007043 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
dan33ea4862014-10-09 19:35:37 +00007044 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
danielk19774dbaa892009-06-16 16:50:22 +00007045 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
dan33ea4862014-10-09 19:35:37 +00007046 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
7047 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
7048 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
7049 ));
danielk19774dbaa892009-06-16 16:50:22 +00007050
7051 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7052 put4byte(pRight, apNew[nNew-1]->pgno);
drh24cd67e2004-05-10 16:18:47 +00007053
dan33ea4862014-10-09 19:35:37 +00007054 /* If the sibling pages are not leaves, ensure that the right-child pointer
7055 ** of the right-most new sibling page is set to the value that was
7056 ** originally in the same field of the right-most old sibling page. */
7057 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
7058 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
7059 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
7060 }
danielk1977ac11ee62005-01-15 12:45:51 +00007061
dan33ea4862014-10-09 19:35:37 +00007062 /* Make any required updates to pointer map entries associated with
7063 ** cells stored on sibling pages following the balance operation. Pointer
7064 ** map entries associated with divider cells are set by the insertCell()
7065 ** routine. The associated pointer map entries are:
7066 **
7067 ** a) if the cell contains a reference to an overflow chain, the
7068 ** entry associated with the first page in the overflow chain, and
7069 **
7070 ** b) if the sibling pages are not leaves, the child page associated
7071 ** with the cell.
7072 **
7073 ** If the sibling pages are not leaves, then the pointer map entry
7074 ** associated with the right-child of each sibling may also need to be
7075 ** updated. This happens below, after the sibling pages have been
7076 ** populated, not here.
7077 */
7078 if( ISAUTOVACUUM ){
7079 MemPage *pNew = apNew[0];
7080 u8 *aOld = pNew->aData;
7081 int cntOldNext = pNew->nCell + pNew->nOverflow;
7082 int usableSize = pBt->usableSize;
7083 int iNew = 0;
7084 int iOld = 0;
danielk1977634f2982005-03-28 08:44:07 +00007085
dan33ea4862014-10-09 19:35:37 +00007086 for(i=0; i<nCell; i++){
7087 u8 *pCell = apCell[i];
7088 if( i==cntOldNext ){
7089 MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
7090 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
7091 aOld = pOld->aData;
7092 }
7093 if( i==cntNew[iNew] ){
7094 pNew = apNew[++iNew];
7095 if( !leafData ) continue;
7096 }
7097
7098 /* Cell pCell is destined for new sibling page pNew. Originally, it
drhba0f9992014-10-30 20:48:44 +00007099 ** was either part of sibling page iOld (possibly an overflow cell),
dan33ea4862014-10-09 19:35:37 +00007100 ** or else the divider cell to the left of sibling page iOld. So,
7101 ** if sibling page iOld had the same page number as pNew, and if
7102 ** pCell really was a part of sibling page iOld (not a divider or
7103 ** overflow cell), we can skip updating the pointer map entries. */
drhd52d52b2014-12-06 02:05:44 +00007104 if( iOld>=nNew
7105 || pNew->pgno!=aPgno[iOld]
7106 || pCell<aOld
7107 || pCell>=&aOld[usableSize]
7108 ){
dan33ea4862014-10-09 19:35:37 +00007109 if( !leafCorrection ){
7110 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
7111 }
7112 if( szCell[i]>pNew->minLocal ){
7113 ptrmapPutOvflPtr(pNew, pCell, &rc);
danielk19774aeff622007-05-12 09:30:47 +00007114 }
drh4b70f112004-05-02 21:12:19 +00007115 }
drh14acc042001-06-10 19:56:58 +00007116 }
7117 }
dan33ea4862014-10-09 19:35:37 +00007118
7119 /* Insert new divider cells into pParent. */
7120 for(i=0; i<nNew-1; i++){
7121 u8 *pCell;
7122 u8 *pTemp;
7123 int sz;
7124 MemPage *pNew = apNew[i];
7125 j = cntNew[i];
7126
7127 assert( j<nMaxCells );
7128 pCell = apCell[j];
7129 sz = szCell[j] + leafCorrection;
7130 pTemp = &aOvflSpace[iOvflSpace];
7131 if( !pNew->leaf ){
7132 memcpy(&pNew->aData[8], pCell, 4);
7133 }else if( leafData ){
7134 /* If the tree is a leaf-data tree, and the siblings are leaves,
7135 ** then there is no divider cell in apCell[]. Instead, the divider
7136 ** cell consists of the integer key for the right-most cell of
7137 ** the sibling-page assembled above only.
7138 */
7139 CellInfo info;
7140 j--;
7141 btreeParseCellPtr(pNew, apCell[j], &info);
7142 pCell = pTemp;
7143 sz = 4 + putVarint(&pCell[4], info.nKey);
7144 pTemp = 0;
7145 }else{
7146 pCell -= 4;
7147 /* Obscure case for non-leaf-data trees: If the cell at pCell was
7148 ** previously stored on a leaf node, and its reported size was 4
7149 ** bytes, then it may actually be smaller than this
7150 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
7151 ** any cell). But it is important to pass the correct size to
7152 ** insertCell(), so reparse the cell now.
7153 **
7154 ** Note that this can never happen in an SQLite data file, as all
7155 ** cells are at least 4 bytes. It only happens in b-trees used
7156 ** to evaluate "IN (SELECT ...)" and similar clauses.
7157 */
7158 if( szCell[j]==4 ){
7159 assert(leafCorrection==4);
7160 sz = cellSizePtr(pParent, pCell);
7161 }
7162 }
7163 iOvflSpace += sz;
7164 assert( sz<=pBt->maxLocal+23 );
7165 assert( iOvflSpace <= (int)pBt->pageSize );
7166 insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
7167 if( rc!=SQLITE_OK ) goto balance_cleanup;
7168 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7169 }
7170
7171 /* Now update the actual sibling pages. The order in which they are updated
7172 ** is important, as this code needs to avoid disrupting any page from which
7173 ** cells may still to be read. In practice, this means:
7174 **
drhd836d422014-10-31 14:26:36 +00007175 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
7176 ** then it is not safe to update page apNew[iPg] until after
7177 ** the left-hand sibling apNew[iPg-1] has been updated.
dan33ea4862014-10-09 19:35:37 +00007178 **
drhd836d422014-10-31 14:26:36 +00007179 ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
7180 ** then it is not safe to update page apNew[iPg] until after
7181 ** the right-hand sibling apNew[iPg+1] has been updated.
dan33ea4862014-10-09 19:35:37 +00007182 **
7183 ** If neither of the above apply, the page is safe to update.
drhd836d422014-10-31 14:26:36 +00007184 **
7185 ** The iPg value in the following loop starts at nNew-1 goes down
7186 ** to 0, then back up to nNew-1 again, thus making two passes over
7187 ** the pages. On the initial downward pass, only condition (1) above
7188 ** needs to be tested because (2) will always be true from the previous
7189 ** step. On the upward pass, both conditions are always true, so the
7190 ** upwards pass simply processes pages that were missed on the downward
7191 ** pass.
dan33ea4862014-10-09 19:35:37 +00007192 */
drhbec021b2014-10-31 12:22:00 +00007193 for(i=1-nNew; i<nNew; i++){
7194 int iPg = i<0 ? -i : i;
drhbec021b2014-10-31 12:22:00 +00007195 assert( iPg>=0 && iPg<nNew );
drhd836d422014-10-31 14:26:36 +00007196 if( abDone[iPg] ) continue; /* Skip pages already processed */
7197 if( i>=0 /* On the upwards pass, or... */
7198 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
dan33ea4862014-10-09 19:35:37 +00007199 ){
dan09c68402014-10-11 20:00:24 +00007200 int iNew;
7201 int iOld;
7202 int nNewCell;
7203
drhd836d422014-10-31 14:26:36 +00007204 /* Verify condition (1): If cells are moving left, update iPg
7205 ** only after iPg-1 has already been updated. */
7206 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
7207
7208 /* Verify condition (2): If cells are moving right, update iPg
7209 ** only after iPg+1 has already been updated. */
7210 assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
7211
dan09c68402014-10-11 20:00:24 +00007212 if( iPg==0 ){
7213 iNew = iOld = 0;
7214 nNewCell = cntNew[0];
7215 }else{
7216 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : nCell;
7217 iNew = cntNew[iPg-1] + !leafData;
7218 nNewCell = cntNew[iPg] - iNew;
7219 }
7220
7221 editPage(apNew[iPg], iOld, iNew, nNewCell, apCell, szCell);
drhd836d422014-10-31 14:26:36 +00007222 abDone[iPg]++;
dand7b545b2014-10-13 18:03:27 +00007223 apNew[iPg]->nFree = usableSpace-szNew[iPg];
dan09c68402014-10-11 20:00:24 +00007224 assert( apNew[iPg]->nOverflow==0 );
7225 assert( apNew[iPg]->nCell==nNewCell );
dan33ea4862014-10-09 19:35:37 +00007226 }
7227 }
drhd836d422014-10-31 14:26:36 +00007228
7229 /* All pages have been processed exactly once */
dan33ea4862014-10-09 19:35:37 +00007230 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
7231
drh7aa8f852006-03-28 00:24:44 +00007232 assert( nOld>0 );
7233 assert( nNew>0 );
drh14acc042001-06-10 19:56:58 +00007234
danielk197713bd99f2009-06-24 05:40:34 +00007235 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
7236 /* The root page of the b-tree now contains no cells. The only sibling
7237 ** page is the right-child of the parent. Copy the contents of the
7238 ** child page into the parent, decreasing the overall height of the
7239 ** b-tree structure by one. This is described as the "balance-shallower"
7240 ** sub-algorithm in some documentation.
7241 **
7242 ** If this is an auto-vacuum database, the call to copyNodeContent()
7243 ** sets all pointer-map entries corresponding to database image pages
7244 ** for which the pointer is stored within the content being copied.
7245 **
drh768f2902014-10-31 02:51:41 +00007246 ** It is critical that the child page be defragmented before being
7247 ** copied into the parent, because if the parent is page 1 then it will
7248 ** by smaller than the child due to the database header, and so all the
7249 ** free space needs to be up front.
7250 */
danielk197713bd99f2009-06-24 05:40:34 +00007251 assert( nNew==1 );
dan89ca0b32014-10-25 20:36:28 +00007252 rc = defragmentPage(apNew[0]);
drh768f2902014-10-31 02:51:41 +00007253 testcase( rc!=SQLITE_OK );
7254 assert( apNew[0]->nFree ==
7255 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
7256 || rc!=SQLITE_OK
7257 );
7258 copyNodeContent(apNew[0], pParent, &rc);
7259 freePage(apNew[0], &rc);
dan33ea4862014-10-09 19:35:37 +00007260 }else if( ISAUTOVACUUM && !leafCorrection ){
7261 /* Fix the pointer map entries associated with the right-child of each
7262 ** sibling page. All other pointer map entries have already been taken
7263 ** care of. */
7264 for(i=0; i<nNew; i++){
7265 u32 key = get4byte(&apNew[i]->aData[8]);
7266 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00007267 }
dan33ea4862014-10-09 19:35:37 +00007268 }
danielk19774dbaa892009-06-16 16:50:22 +00007269
dan33ea4862014-10-09 19:35:37 +00007270 assert( pParent->isInit );
7271 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
7272 nOld, nNew, nCell));
danielk19774dbaa892009-06-16 16:50:22 +00007273
dan33ea4862014-10-09 19:35:37 +00007274 /* Free any old pages that were not reused as new pages.
7275 */
7276 for(i=nNew; i<nOld; i++){
7277 freePage(apOld[i], &rc);
7278 }
7279
dane6593d82014-10-24 16:40:49 +00007280#if 0
dan33ea4862014-10-09 19:35:37 +00007281 if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
danielk19774dbaa892009-06-16 16:50:22 +00007282 /* The ptrmapCheckPages() contains assert() statements that verify that
7283 ** all pointer map pages are set correctly. This is helpful while
7284 ** debugging. This is usually disabled because a corrupt database may
7285 ** cause an assert() statement to fail. */
7286 ptrmapCheckPages(apNew, nNew);
7287 ptrmapCheckPages(&pParent, 1);
danielk19774dbaa892009-06-16 16:50:22 +00007288 }
dan33ea4862014-10-09 19:35:37 +00007289#endif
danielk1977cd581a72009-06-23 15:43:39 +00007290
drh8b2f49b2001-06-08 00:21:52 +00007291 /*
drh14acc042001-06-10 19:56:58 +00007292 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00007293 */
drh14acc042001-06-10 19:56:58 +00007294balance_cleanup:
drhfacf0302008-06-17 15:12:00 +00007295 sqlite3ScratchFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00007296 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00007297 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00007298 }
drh14acc042001-06-10 19:56:58 +00007299 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00007300 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00007301 }
danielk1977eaa06f62008-09-18 17:34:44 +00007302
drh8b2f49b2001-06-08 00:21:52 +00007303 return rc;
7304}
mistachkine7c54162012-10-02 22:54:27 +00007305#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
7306#pragma optimize("", on)
7307#endif
drh8b2f49b2001-06-08 00:21:52 +00007308
drh43605152004-05-29 21:46:49 +00007309
7310/*
danielk1977a50d9aa2009-06-08 14:49:45 +00007311** This function is called when the root page of a b-tree structure is
7312** overfull (has one or more overflow pages).
drh43605152004-05-29 21:46:49 +00007313**
danielk1977a50d9aa2009-06-08 14:49:45 +00007314** A new child page is allocated and the contents of the current root
7315** page, including overflow cells, are copied into the child. The root
7316** page is then overwritten to make it an empty page with the right-child
7317** pointer pointing to the new page.
7318**
7319** Before returning, all pointer-map entries corresponding to pages
7320** that the new child-page now contains pointers to are updated. The
7321** entry corresponding to the new right-child pointer of the root
7322** page is also updated.
7323**
7324** If successful, *ppChild is set to contain a reference to the child
7325** page and SQLITE_OK is returned. In this case the caller is required
7326** to call releasePage() on *ppChild exactly once. If an error occurs,
7327** an error code is returned and *ppChild is set to 0.
drh43605152004-05-29 21:46:49 +00007328*/
danielk1977a50d9aa2009-06-08 14:49:45 +00007329static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
7330 int rc; /* Return value from subprocedures */
7331 MemPage *pChild = 0; /* Pointer to a new child page */
shane5eff7cf2009-08-10 03:57:58 +00007332 Pgno pgnoChild = 0; /* Page number of the new child page */
danielk1977a50d9aa2009-06-08 14:49:45 +00007333 BtShared *pBt = pRoot->pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00007334
danielk1977a50d9aa2009-06-08 14:49:45 +00007335 assert( pRoot->nOverflow>0 );
drh1fee73e2007-08-29 04:00:57 +00007336 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bc2ca9e2008-11-13 14:28:28 +00007337
danielk1977a50d9aa2009-06-08 14:49:45 +00007338 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
7339 ** page that will become the new right-child of pPage. Copy the contents
7340 ** of the node stored on pRoot into the new child page.
7341 */
drh98add2e2009-07-20 17:11:49 +00007342 rc = sqlite3PagerWrite(pRoot->pDbPage);
7343 if( rc==SQLITE_OK ){
7344 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
drhc314dc72009-07-21 11:52:34 +00007345 copyNodeContent(pRoot, pChild, &rc);
7346 if( ISAUTOVACUUM ){
7347 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
drh98add2e2009-07-20 17:11:49 +00007348 }
7349 }
7350 if( rc ){
danielk1977a50d9aa2009-06-08 14:49:45 +00007351 *ppChild = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00007352 releasePage(pChild);
danielk1977a50d9aa2009-06-08 14:49:45 +00007353 return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00007354 }
danielk1977a50d9aa2009-06-08 14:49:45 +00007355 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
7356 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
7357 assert( pChild->nCell==pRoot->nCell );
danielk197771d5d2c2008-09-29 11:49:47 +00007358
danielk1977a50d9aa2009-06-08 14:49:45 +00007359 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
7360
7361 /* Copy the overflow cells from pRoot to pChild */
drh2cbd78b2012-02-02 19:37:18 +00007362 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
7363 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
7364 memcpy(pChild->apOvfl, pRoot->apOvfl,
7365 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
danielk1977a50d9aa2009-06-08 14:49:45 +00007366 pChild->nOverflow = pRoot->nOverflow;
danielk1977a50d9aa2009-06-08 14:49:45 +00007367
7368 /* Zero the contents of pRoot. Then install pChild as the right-child. */
7369 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
7370 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
7371
7372 *ppChild = pChild;
7373 return SQLITE_OK;
drh43605152004-05-29 21:46:49 +00007374}
7375
7376/*
danielk197771d5d2c2008-09-29 11:49:47 +00007377** The page that pCur currently points to has just been modified in
7378** some way. This function figures out if this modification means the
7379** tree needs to be balanced, and if so calls the appropriate balancing
danielk1977a50d9aa2009-06-08 14:49:45 +00007380** routine. Balancing routines are:
7381**
7382** balance_quick()
danielk1977a50d9aa2009-06-08 14:49:45 +00007383** balance_deeper()
7384** balance_nonroot()
drh43605152004-05-29 21:46:49 +00007385*/
danielk1977a50d9aa2009-06-08 14:49:45 +00007386static int balance(BtCursor *pCur){
drh43605152004-05-29 21:46:49 +00007387 int rc = SQLITE_OK;
danielk1977a50d9aa2009-06-08 14:49:45 +00007388 const int nMin = pCur->pBt->usableSize * 2 / 3;
7389 u8 aBalanceQuickSpace[13];
7390 u8 *pFree = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00007391
shane75ac1de2009-06-09 18:58:52 +00007392 TESTONLY( int balance_quick_called = 0 );
7393 TESTONLY( int balance_deeper_called = 0 );
danielk1977a50d9aa2009-06-08 14:49:45 +00007394
7395 do {
7396 int iPage = pCur->iPage;
7397 MemPage *pPage = pCur->apPage[iPage];
7398
7399 if( iPage==0 ){
7400 if( pPage->nOverflow ){
7401 /* The root page of the b-tree is overfull. In this case call the
7402 ** balance_deeper() function to create a new child for the root-page
7403 ** and copy the current contents of the root-page to it. The
7404 ** next iteration of the do-loop will balance the child page.
7405 */
7406 assert( (balance_deeper_called++)==0 );
7407 rc = balance_deeper(pPage, &pCur->apPage[1]);
7408 if( rc==SQLITE_OK ){
7409 pCur->iPage = 1;
7410 pCur->aiIdx[0] = 0;
7411 pCur->aiIdx[1] = 0;
7412 assert( pCur->apPage[1]->nOverflow );
7413 }
danielk1977a50d9aa2009-06-08 14:49:45 +00007414 }else{
danielk1977a50d9aa2009-06-08 14:49:45 +00007415 break;
7416 }
7417 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
7418 break;
7419 }else{
7420 MemPage * const pParent = pCur->apPage[iPage-1];
7421 int const iIdx = pCur->aiIdx[iPage-1];
7422
7423 rc = sqlite3PagerWrite(pParent->pDbPage);
7424 if( rc==SQLITE_OK ){
7425#ifndef SQLITE_OMIT_QUICKBALANCE
drh3e28ff52014-09-24 00:59:08 +00007426 if( pPage->intKeyLeaf
danielk1977a50d9aa2009-06-08 14:49:45 +00007427 && pPage->nOverflow==1
drh2cbd78b2012-02-02 19:37:18 +00007428 && pPage->aiOvfl[0]==pPage->nCell
danielk1977a50d9aa2009-06-08 14:49:45 +00007429 && pParent->pgno!=1
7430 && pParent->nCell==iIdx
7431 ){
7432 /* Call balance_quick() to create a new sibling of pPage on which
7433 ** to store the overflow cell. balance_quick() inserts a new cell
7434 ** into pParent, which may cause pParent overflow. If this
peter.d.reid60ec9142014-09-06 16:39:46 +00007435 ** happens, the next iteration of the do-loop will balance pParent
danielk1977a50d9aa2009-06-08 14:49:45 +00007436 ** use either balance_nonroot() or balance_deeper(). Until this
7437 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
7438 ** buffer.
7439 **
7440 ** The purpose of the following assert() is to check that only a
7441 ** single call to balance_quick() is made for each call to this
7442 ** function. If this were not verified, a subtle bug involving reuse
7443 ** of the aBalanceQuickSpace[] might sneak in.
7444 */
7445 assert( (balance_quick_called++)==0 );
7446 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
7447 }else
7448#endif
7449 {
7450 /* In this case, call balance_nonroot() to redistribute cells
7451 ** between pPage and up to 2 of its sibling pages. This involves
7452 ** modifying the contents of pParent, which may cause pParent to
7453 ** become overfull or underfull. The next iteration of the do-loop
7454 ** will balance the parent page to correct this.
7455 **
7456 ** If the parent page becomes overfull, the overflow cell or cells
7457 ** are stored in the pSpace buffer allocated immediately below.
7458 ** A subsequent iteration of the do-loop will deal with this by
7459 ** calling balance_nonroot() (balance_deeper() may be called first,
7460 ** but it doesn't deal with overflow cells - just moves them to a
7461 ** different page). Once this subsequent call to balance_nonroot()
7462 ** has completed, it is safe to release the pSpace buffer used by
7463 ** the previous call, as the overflow cell data will have been
7464 ** copied either into the body of a database page or into the new
7465 ** pSpace buffer passed to the latter call to balance_nonroot().
7466 */
7467 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
dan428c2182012-08-06 18:50:11 +00007468 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
danielk1977a50d9aa2009-06-08 14:49:45 +00007469 if( pFree ){
7470 /* If pFree is not NULL, it points to the pSpace buffer used
7471 ** by a previous call to balance_nonroot(). Its contents are
7472 ** now stored either on real database pages or within the
7473 ** new pSpace buffer, so it may be safely freed here. */
7474 sqlite3PageFree(pFree);
7475 }
7476
danielk19774dbaa892009-06-16 16:50:22 +00007477 /* The pSpace buffer will be freed after the next call to
7478 ** balance_nonroot(), or just before this function returns, whichever
7479 ** comes first. */
danielk1977a50d9aa2009-06-08 14:49:45 +00007480 pFree = pSpace;
danielk1977a50d9aa2009-06-08 14:49:45 +00007481 }
7482 }
7483
7484 pPage->nOverflow = 0;
7485
7486 /* The next iteration of the do-loop balances the parent page. */
7487 releasePage(pPage);
7488 pCur->iPage--;
drh43605152004-05-29 21:46:49 +00007489 }
danielk1977a50d9aa2009-06-08 14:49:45 +00007490 }while( rc==SQLITE_OK );
7491
7492 if( pFree ){
7493 sqlite3PageFree(pFree);
drh43605152004-05-29 21:46:49 +00007494 }
7495 return rc;
7496}
7497
drhf74b8d92002-09-01 23:20:45 +00007498
7499/*
drh3b7511c2001-05-26 13:15:44 +00007500** Insert a new record into the BTree. The key is given by (pKey,nKey)
7501** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00007502** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00007503** is left pointing at a random location.
7504**
7505** For an INTKEY table, only the nKey value of the key is used. pKey is
7506** ignored. For a ZERODATA table, the pData and nData are both ignored.
danielk1977de630352009-05-04 11:42:29 +00007507**
7508** If the seekResult parameter is non-zero, then a successful call to
danielk19773509a652009-07-06 18:56:13 +00007509** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
danielk1977de630352009-05-04 11:42:29 +00007510** been performed. seekResult is the search result returned (a negative
7511** number if pCur points at an entry that is smaller than (pKey, nKey), or
peter.d.reid60ec9142014-09-06 16:39:46 +00007512** a positive value if pCur points at an entry that is larger than
danielk1977de630352009-05-04 11:42:29 +00007513** (pKey, nKey)).
7514**
drh3e9ca092009-09-08 01:14:48 +00007515** If the seekResult parameter is non-zero, then the caller guarantees that
7516** cursor pCur is pointing at the existing copy of a row that is to be
7517** overwritten. If the seekResult parameter is 0, then cursor pCur may
7518** point to any entry or to no entry at all and so this function has to seek
danielk1977de630352009-05-04 11:42:29 +00007519** the cursor before the new key can be inserted.
drh3b7511c2001-05-26 13:15:44 +00007520*/
drh3aac2dd2004-04-26 14:10:20 +00007521int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00007522 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00007523 const void *pKey, i64 nKey, /* The key of the new record */
drhe4d90812007-03-29 05:51:49 +00007524 const void *pData, int nData, /* The data of the new record */
drhb026e052007-05-02 01:34:31 +00007525 int nZero, /* Number of extra 0 bytes to append to data */
danielk1977de630352009-05-04 11:42:29 +00007526 int appendBias, /* True if this is likely an append */
danielk19773509a652009-07-06 18:56:13 +00007527 int seekResult /* Result of prior MovetoUnpacked() call */
drh3b7511c2001-05-26 13:15:44 +00007528){
drh3b7511c2001-05-26 13:15:44 +00007529 int rc;
drh3e9ca092009-09-08 01:14:48 +00007530 int loc = seekResult; /* -1: before desired location +1: after */
drh1d452e12009-11-01 19:26:59 +00007531 int szNew = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00007532 int idx;
drh3b7511c2001-05-26 13:15:44 +00007533 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00007534 Btree *p = pCur->pBtree;
7535 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00007536 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00007537 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00007538
drh98add2e2009-07-20 17:11:49 +00007539 if( pCur->eState==CURSOR_FAULT ){
7540 assert( pCur->skipNext!=SQLITE_OK );
7541 return pCur->skipNext;
7542 }
7543
drh1fee73e2007-08-29 04:00:57 +00007544 assert( cursorHoldsMutex(pCur) );
drh3f387402014-09-24 01:23:00 +00007545 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
7546 && pBt->inTransaction==TRANS_WRITE
drhc9166342012-01-05 23:32:06 +00007547 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk197796d48e92009-06-29 06:00:37 +00007548 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
7549
danielk197731d31b82009-07-13 13:18:07 +00007550 /* Assert that the caller has been consistent. If this cursor was opened
7551 ** expecting an index b-tree, then the caller should be inserting blob
7552 ** keys with no associated data. If the cursor was opened expecting an
7553 ** intkey table, the caller should be inserting integer keys with a
7554 ** blob of associated data. */
7555 assert( (pKey==0)==(pCur->pKeyInfo==0) );
7556
danielk19779c3acf32009-05-02 07:36:49 +00007557 /* Save the positions of any other cursors open on this table.
7558 **
danielk19773509a652009-07-06 18:56:13 +00007559 ** In some cases, the call to btreeMoveto() below is a no-op. For
danielk19779c3acf32009-05-02 07:36:49 +00007560 ** example, when inserting data into a table with auto-generated integer
7561 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
7562 ** integer key to use. It then calls this function to actually insert the
danielk19773509a652009-07-06 18:56:13 +00007563 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
danielk19779c3acf32009-05-02 07:36:49 +00007564 ** that the cursor is already where it needs to be and returns without
7565 ** doing any work. To avoid thwarting these optimizations, it is important
7566 ** not to clear the cursor here.
7567 */
drh4c301aa2009-07-15 17:25:45 +00007568 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
7569 if( rc ) return rc;
drhd60f4f42012-03-23 14:23:52 +00007570
drhd60f4f42012-03-23 14:23:52 +00007571 if( pCur->pKeyInfo==0 ){
drhe0670b62014-02-12 21:31:12 +00007572 /* If this is an insert into a table b-tree, invalidate any incrblob
7573 ** cursors open on the row being replaced */
drhd60f4f42012-03-23 14:23:52 +00007574 invalidateIncrblobCursors(p, nKey, 0);
drhe0670b62014-02-12 21:31:12 +00007575
7576 /* If the cursor is currently on the last row and we are appending a
7577 ** new row onto the end, set the "loc" to avoid an unnecessary btreeMoveto()
7578 ** call */
drh3f387402014-09-24 01:23:00 +00007579 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0
7580 && pCur->info.nKey==nKey-1 ){
drhe0670b62014-02-12 21:31:12 +00007581 loc = -1;
7582 }
drhd60f4f42012-03-23 14:23:52 +00007583 }
7584
drh4c301aa2009-07-15 17:25:45 +00007585 if( !loc ){
7586 rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
7587 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00007588 }
danielk1977b980d2212009-06-22 18:03:51 +00007589 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
danielk1977da184232006-01-05 11:34:32 +00007590
danielk197771d5d2c2008-09-29 11:49:47 +00007591 pPage = pCur->apPage[pCur->iPage];
drh4a1c3802004-05-12 15:15:47 +00007592 assert( pPage->intKey || nKey>=0 );
drh44845222008-07-17 18:39:57 +00007593 assert( pPage->leaf || !pPage->intKey );
danielk19778f880a82009-07-13 09:41:45 +00007594
drh3a4c1412004-05-09 20:40:11 +00007595 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
7596 pCur->pgnoRoot, nKey, nData, pPage->pgno,
7597 loc==0 ? "overwrite" : "new entry"));
danielk197771d5d2c2008-09-29 11:49:47 +00007598 assert( pPage->isInit );
danielk197752ae7242008-03-25 14:24:56 +00007599 newCell = pBt->pTmpSpace;
drh3fbb0222014-09-24 19:47:27 +00007600 assert( newCell!=0 );
drhb026e052007-05-02 01:34:31 +00007601 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
drh2e38c322004-09-03 18:38:44 +00007602 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00007603 assert( szNew==cellSizePtr(pPage, newCell) );
drhfcd71b62011-04-05 22:08:24 +00007604 assert( szNew <= MX_CELL_SIZE(pBt) );
danielk197771d5d2c2008-09-29 11:49:47 +00007605 idx = pCur->aiIdx[pCur->iPage];
danielk1977b980d2212009-06-22 18:03:51 +00007606 if( loc==0 ){
drha9121e42008-02-19 14:59:35 +00007607 u16 szOld;
danielk197771d5d2c2008-09-29 11:49:47 +00007608 assert( idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00007609 rc = sqlite3PagerWrite(pPage->pDbPage);
7610 if( rc ){
7611 goto end_insert;
7612 }
danielk197771d5d2c2008-09-29 11:49:47 +00007613 oldCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00007614 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00007615 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00007616 }
drh9bfdc252014-09-24 02:05:41 +00007617 rc = clearCell(pPage, oldCell, &szOld);
drh98add2e2009-07-20 17:11:49 +00007618 dropCell(pPage, idx, szOld, &rc);
drh2e38c322004-09-03 18:38:44 +00007619 if( rc ) goto end_insert;
drh7c717f72001-06-24 20:39:41 +00007620 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00007621 assert( pPage->leaf );
danielk197771d5d2c2008-09-29 11:49:47 +00007622 idx = ++pCur->aiIdx[pCur->iPage];
drh14acc042001-06-10 19:56:58 +00007623 }else{
drh4b70f112004-05-02 21:12:19 +00007624 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00007625 }
drh98add2e2009-07-20 17:11:49 +00007626 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
danielk19773f632d52009-05-02 10:03:09 +00007627 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
drh9bf9e9c2008-12-05 20:01:43 +00007628
mistachkin48864df2013-03-21 21:20:32 +00007629 /* If no error has occurred and pPage has an overflow cell, call balance()
danielk1977a50d9aa2009-06-08 14:49:45 +00007630 ** to redistribute the cells within the tree. Since balance() may move
drh036dbec2014-03-11 23:40:44 +00007631 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
danielk1977a50d9aa2009-06-08 14:49:45 +00007632 ** variables.
danielk19773f632d52009-05-02 10:03:09 +00007633 **
danielk1977a50d9aa2009-06-08 14:49:45 +00007634 ** Previous versions of SQLite called moveToRoot() to move the cursor
7635 ** back to the root page as balance() used to invalidate the contents
danielk197754109bb2009-06-23 11:22:29 +00007636 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
7637 ** set the cursor state to "invalid". This makes common insert operations
7638 ** slightly faster.
danielk19773f632d52009-05-02 10:03:09 +00007639 **
danielk1977a50d9aa2009-06-08 14:49:45 +00007640 ** There is a subtle but important optimization here too. When inserting
7641 ** multiple records into an intkey b-tree using a single cursor (as can
7642 ** happen while processing an "INSERT INTO ... SELECT" statement), it
7643 ** is advantageous to leave the cursor pointing to the last entry in
7644 ** the b-tree if possible. If the cursor is left pointing to the last
7645 ** entry in the table, and the next row inserted has an integer key
7646 ** larger than the largest existing key, it is possible to insert the
7647 ** row without seeking the cursor. This can be a big performance boost.
danielk19773f632d52009-05-02 10:03:09 +00007648 */
danielk1977a50d9aa2009-06-08 14:49:45 +00007649 pCur->info.nSize = 0;
danielk1977a50d9aa2009-06-08 14:49:45 +00007650 if( rc==SQLITE_OK && pPage->nOverflow ){
drh036dbec2014-03-11 23:40:44 +00007651 pCur->curFlags &= ~(BTCF_ValidNKey);
danielk1977a50d9aa2009-06-08 14:49:45 +00007652 rc = balance(pCur);
7653
7654 /* Must make sure nOverflow is reset to zero even if the balance()
danielk197754109bb2009-06-23 11:22:29 +00007655 ** fails. Internal data structure corruption will result otherwise.
7656 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
7657 ** from trying to save the current position of the cursor. */
danielk1977a50d9aa2009-06-08 14:49:45 +00007658 pCur->apPage[pCur->iPage]->nOverflow = 0;
danielk197754109bb2009-06-23 11:22:29 +00007659 pCur->eState = CURSOR_INVALID;
danielk19773f632d52009-05-02 10:03:09 +00007660 }
danielk1977a50d9aa2009-06-08 14:49:45 +00007661 assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
drh9bf9e9c2008-12-05 20:01:43 +00007662
drh2e38c322004-09-03 18:38:44 +00007663end_insert:
drh5e2f8b92001-05-28 00:41:15 +00007664 return rc;
7665}
7666
7667/*
drh4b70f112004-05-02 21:12:19 +00007668** Delete the entry that the cursor is pointing to. The cursor
peter.d.reid60ec9142014-09-06 16:39:46 +00007669** is left pointing at an arbitrary location.
drh3b7511c2001-05-26 13:15:44 +00007670*/
drh3aac2dd2004-04-26 14:10:20 +00007671int sqlite3BtreeDelete(BtCursor *pCur){
drhd677b3d2007-08-20 22:48:41 +00007672 Btree *p = pCur->pBtree;
danielk19774dbaa892009-06-16 16:50:22 +00007673 BtShared *pBt = p->pBt;
7674 int rc; /* Return code */
7675 MemPage *pPage; /* Page to delete cell from */
7676 unsigned char *pCell; /* Pointer to cell to delete */
7677 int iCellIdx; /* Index of cell to delete */
7678 int iCellDepth; /* Depth of node containing pCell */
drh9bfdc252014-09-24 02:05:41 +00007679 u16 szCell; /* Size of the cell being deleted */
drh8b2f49b2001-06-08 00:21:52 +00007680
drh1fee73e2007-08-29 04:00:57 +00007681 assert( cursorHoldsMutex(pCur) );
drh64022502009-01-09 14:11:04 +00007682 assert( pBt->inTransaction==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00007683 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
drh036dbec2014-03-11 23:40:44 +00007684 assert( pCur->curFlags & BTCF_WriteFlag );
danielk197796d48e92009-06-29 06:00:37 +00007685 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
7686 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
7687
danielk19774dbaa892009-06-16 16:50:22 +00007688 if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
7689 || NEVER(pCur->eState!=CURSOR_VALID)
7690 ){
7691 return SQLITE_ERROR; /* Something has gone awry. */
drhf74b8d92002-09-01 23:20:45 +00007692 }
danielk1977da184232006-01-05 11:34:32 +00007693
danielk19774dbaa892009-06-16 16:50:22 +00007694 iCellDepth = pCur->iPage;
7695 iCellIdx = pCur->aiIdx[iCellDepth];
7696 pPage = pCur->apPage[iCellDepth];
7697 pCell = findCell(pPage, iCellIdx);
7698
7699 /* If the page containing the entry to delete is not a leaf page, move
7700 ** the cursor to the largest entry in the tree that is smaller than
7701 ** the entry being deleted. This cell will replace the cell being deleted
7702 ** from the internal node. The 'previous' entry is used for this instead
7703 ** of the 'next' entry, as the previous entry is always a part of the
7704 ** sub-tree headed by the child page of the cell being deleted. This makes
7705 ** balancing the tree following the delete operation easier. */
7706 if( !pPage->leaf ){
drhe39a7322014-02-03 14:04:11 +00007707 int notUsed = 0;
drh4c301aa2009-07-15 17:25:45 +00007708 rc = sqlite3BtreePrevious(pCur, &notUsed);
7709 if( rc ) return rc;
danielk19774dbaa892009-06-16 16:50:22 +00007710 }
7711
7712 /* Save the positions of any other cursors open on this table before
7713 ** making any modifications. Make the page containing the entry to be
7714 ** deleted writable. Then free any overflow pages associated with the
drha4ec1d42009-07-11 13:13:11 +00007715 ** entry and finally remove the cell itself from within the page.
7716 */
7717 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
7718 if( rc ) return rc;
drhd60f4f42012-03-23 14:23:52 +00007719
7720 /* If this is a delete operation to remove a row from a table b-tree,
7721 ** invalidate any incrblob cursors open on the row being deleted. */
7722 if( pCur->pKeyInfo==0 ){
7723 invalidateIncrblobCursors(p, pCur->info.nKey, 0);
7724 }
7725
drha4ec1d42009-07-11 13:13:11 +00007726 rc = sqlite3PagerWrite(pPage->pDbPage);
7727 if( rc ) return rc;
drh9bfdc252014-09-24 02:05:41 +00007728 rc = clearCell(pPage, pCell, &szCell);
7729 dropCell(pPage, iCellIdx, szCell, &rc);
drha4ec1d42009-07-11 13:13:11 +00007730 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00007731
danielk19774dbaa892009-06-16 16:50:22 +00007732 /* If the cell deleted was not located on a leaf page, then the cursor
7733 ** is currently pointing to the largest entry in the sub-tree headed
7734 ** by the child-page of the cell that was just deleted from an internal
7735 ** node. The cell from the leaf node needs to be moved to the internal
7736 ** node to replace the deleted cell. */
drh4b70f112004-05-02 21:12:19 +00007737 if( !pPage->leaf ){
danielk19774dbaa892009-06-16 16:50:22 +00007738 MemPage *pLeaf = pCur->apPage[pCur->iPage];
7739 int nCell;
7740 Pgno n = pCur->apPage[iCellDepth+1]->pgno;
7741 unsigned char *pTmp;
danielk1977e6efa742004-11-10 11:55:10 +00007742
danielk19774dbaa892009-06-16 16:50:22 +00007743 pCell = findCell(pLeaf, pLeaf->nCell-1);
7744 nCell = cellSizePtr(pLeaf, pCell);
drhfcd71b62011-04-05 22:08:24 +00007745 assert( MX_CELL_SIZE(pBt) >= nCell );
danielk19774dbaa892009-06-16 16:50:22 +00007746 pTmp = pBt->pTmpSpace;
drh3fbb0222014-09-24 19:47:27 +00007747 assert( pTmp!=0 );
drha4ec1d42009-07-11 13:13:11 +00007748 rc = sqlite3PagerWrite(pLeaf->pDbPage);
drh98add2e2009-07-20 17:11:49 +00007749 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
7750 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
drha4ec1d42009-07-11 13:13:11 +00007751 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00007752 }
danielk19774dbaa892009-06-16 16:50:22 +00007753
7754 /* Balance the tree. If the entry deleted was located on a leaf page,
7755 ** then the cursor still points to that page. In this case the first
7756 ** call to balance() repairs the tree, and the if(...) condition is
7757 ** never true.
7758 **
7759 ** Otherwise, if the entry deleted was on an internal node page, then
7760 ** pCur is pointing to the leaf page from which a cell was removed to
7761 ** replace the cell deleted from the internal node. This is slightly
7762 ** tricky as the leaf node may be underfull, and the internal node may
7763 ** be either under or overfull. In this case run the balancing algorithm
7764 ** on the leaf node first. If the balance proceeds far enough up the
7765 ** tree that we can be sure that any problem in the internal node has
7766 ** been corrected, so be it. Otherwise, after balancing the leaf node,
7767 ** walk the cursor up the tree to the internal node and balance it as
7768 ** well. */
7769 rc = balance(pCur);
7770 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
7771 while( pCur->iPage>iCellDepth ){
7772 releasePage(pCur->apPage[pCur->iPage--]);
7773 }
7774 rc = balance(pCur);
7775 }
7776
danielk19776b456a22005-03-21 04:04:02 +00007777 if( rc==SQLITE_OK ){
7778 moveToRoot(pCur);
7779 }
drh5e2f8b92001-05-28 00:41:15 +00007780 return rc;
drh3b7511c2001-05-26 13:15:44 +00007781}
drh8b2f49b2001-06-08 00:21:52 +00007782
7783/*
drhc6b52df2002-01-04 03:09:29 +00007784** Create a new BTree table. Write into *piTable the page
7785** number for the root page of the new table.
7786**
drhab01f612004-05-22 02:55:23 +00007787** The type of type is determined by the flags parameter. Only the
7788** following values of flags are currently in use. Other values for
7789** flags might not work:
7790**
7791** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
7792** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00007793*/
drhd4187c72010-08-30 22:15:45 +00007794static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
danielk1977aef0bf62005-12-30 16:28:01 +00007795 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00007796 MemPage *pRoot;
7797 Pgno pgnoRoot;
7798 int rc;
drhd4187c72010-08-30 22:15:45 +00007799 int ptfFlags; /* Page-type flage for the root page of new table */
drhd677b3d2007-08-20 22:48:41 +00007800
drh1fee73e2007-08-29 04:00:57 +00007801 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00007802 assert( pBt->inTransaction==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00007803 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk1977e6efa742004-11-10 11:55:10 +00007804
danielk1977003ba062004-11-04 02:57:33 +00007805#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00007806 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00007807 if( rc ){
7808 return rc;
7809 }
danielk1977003ba062004-11-04 02:57:33 +00007810#else
danielk1977687566d2004-11-02 12:56:41 +00007811 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00007812 Pgno pgnoMove; /* Move a page here to make room for the root-page */
7813 MemPage *pPageMove; /* The page to move to. */
7814
danielk197720713f32007-05-03 11:43:33 +00007815 /* Creating a new table may probably require moving an existing database
7816 ** to make room for the new tables root page. In case this page turns
7817 ** out to be an overflow page, delete all overflow page-map caches
7818 ** held by open cursors.
7819 */
danielk197792d4d7a2007-05-04 12:05:56 +00007820 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00007821
danielk1977003ba062004-11-04 02:57:33 +00007822 /* Read the value of meta[3] from the database to determine where the
7823 ** root page of the new table should go. meta[3] is the largest root-page
7824 ** created so far, so the new root-page is (meta[3]+1).
7825 */
danielk1977602b4662009-07-02 07:47:33 +00007826 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00007827 pgnoRoot++;
7828
danielk1977599fcba2004-11-08 07:13:13 +00007829 /* The new root-page may not be allocated on a pointer-map page, or the
7830 ** PENDING_BYTE page.
7831 */
drh72190432008-01-31 14:54:43 +00007832 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00007833 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00007834 pgnoRoot++;
7835 }
7836 assert( pgnoRoot>=3 );
7837
7838 /* Allocate a page. The page that currently resides at pgnoRoot will
7839 ** be moved to the allocated page (unless the allocated page happens
7840 ** to reside at pgnoRoot).
7841 */
dan51f0b6d2013-02-22 20:16:34 +00007842 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
danielk1977003ba062004-11-04 02:57:33 +00007843 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00007844 return rc;
7845 }
danielk1977003ba062004-11-04 02:57:33 +00007846
7847 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00007848 /* pgnoRoot is the page that will be used for the root-page of
7849 ** the new table (assuming an error did not occur). But we were
7850 ** allocated pgnoMove. If required (i.e. if it was not allocated
7851 ** by extending the file), the current page at position pgnoMove
7852 ** is already journaled.
7853 */
drheeb844a2009-08-08 18:01:07 +00007854 u8 eType = 0;
7855 Pgno iPtrPage = 0;
danielk1977003ba062004-11-04 02:57:33 +00007856
danf7679ad2013-04-03 11:38:36 +00007857 /* Save the positions of any open cursors. This is required in
7858 ** case they are holding a reference to an xFetch reference
7859 ** corresponding to page pgnoRoot. */
7860 rc = saveAllCursors(pBt, 0, 0);
danielk1977003ba062004-11-04 02:57:33 +00007861 releasePage(pPageMove);
danf7679ad2013-04-03 11:38:36 +00007862 if( rc!=SQLITE_OK ){
7863 return rc;
7864 }
danielk1977f35843b2007-04-07 15:03:17 +00007865
7866 /* Move the page currently at pgnoRoot to pgnoMove. */
drhb00fc3b2013-08-21 23:42:32 +00007867 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00007868 if( rc!=SQLITE_OK ){
7869 return rc;
7870 }
7871 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drh27731d72009-06-22 12:05:10 +00007872 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
7873 rc = SQLITE_CORRUPT_BKPT;
7874 }
7875 if( rc!=SQLITE_OK ){
danielk1977003ba062004-11-04 02:57:33 +00007876 releasePage(pRoot);
7877 return rc;
7878 }
drhccae6022005-02-26 17:31:26 +00007879 assert( eType!=PTRMAP_ROOTPAGE );
7880 assert( eType!=PTRMAP_FREEPAGE );
danielk19774c999992008-07-16 18:17:55 +00007881 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
danielk1977003ba062004-11-04 02:57:33 +00007882 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00007883
7884 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00007885 if( rc!=SQLITE_OK ){
7886 return rc;
7887 }
drhb00fc3b2013-08-21 23:42:32 +00007888 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00007889 if( rc!=SQLITE_OK ){
7890 return rc;
7891 }
danielk19773b8a05f2007-03-19 17:44:26 +00007892 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00007893 if( rc!=SQLITE_OK ){
7894 releasePage(pRoot);
7895 return rc;
7896 }
7897 }else{
7898 pRoot = pPageMove;
7899 }
7900
danielk197742741be2005-01-08 12:42:39 +00007901 /* Update the pointer-map and meta-data with the new root-page number. */
drh98add2e2009-07-20 17:11:49 +00007902 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
danielk1977003ba062004-11-04 02:57:33 +00007903 if( rc ){
7904 releasePage(pRoot);
7905 return rc;
7906 }
drhbf592832010-03-30 15:51:12 +00007907
7908 /* When the new root page was allocated, page 1 was made writable in
7909 ** order either to increase the database filesize, or to decrement the
7910 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
7911 */
7912 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
danielk1977aef0bf62005-12-30 16:28:01 +00007913 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
drhbf592832010-03-30 15:51:12 +00007914 if( NEVER(rc) ){
danielk1977003ba062004-11-04 02:57:33 +00007915 releasePage(pRoot);
7916 return rc;
7917 }
danielk197742741be2005-01-08 12:42:39 +00007918
danielk1977003ba062004-11-04 02:57:33 +00007919 }else{
drh4f0c5872007-03-26 22:05:01 +00007920 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00007921 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00007922 }
7923#endif
danielk19773b8a05f2007-03-19 17:44:26 +00007924 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhd4187c72010-08-30 22:15:45 +00007925 if( createTabFlags & BTREE_INTKEY ){
7926 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
7927 }else{
7928 ptfFlags = PTF_ZERODATA | PTF_LEAF;
7929 }
7930 zeroPage(pRoot, ptfFlags);
danielk19773b8a05f2007-03-19 17:44:26 +00007931 sqlite3PagerUnref(pRoot->pDbPage);
drhd4187c72010-08-30 22:15:45 +00007932 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
drh8b2f49b2001-06-08 00:21:52 +00007933 *piTable = (int)pgnoRoot;
7934 return SQLITE_OK;
7935}
drhd677b3d2007-08-20 22:48:41 +00007936int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
7937 int rc;
7938 sqlite3BtreeEnter(p);
7939 rc = btreeCreateTable(p, piTable, flags);
7940 sqlite3BtreeLeave(p);
7941 return rc;
7942}
drh8b2f49b2001-06-08 00:21:52 +00007943
7944/*
7945** Erase the given database page and all its children. Return
7946** the page to the freelist.
7947*/
drh4b70f112004-05-02 21:12:19 +00007948static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00007949 BtShared *pBt, /* The BTree that contains the table */
drh7ab641f2009-11-24 02:37:02 +00007950 Pgno pgno, /* Page number to clear */
7951 int freePageFlag, /* Deallocate page if true */
7952 int *pnChange /* Add number of Cells freed to this counter */
drh4b70f112004-05-02 21:12:19 +00007953){
danielk1977146ba992009-07-22 14:08:13 +00007954 MemPage *pPage;
drh8b2f49b2001-06-08 00:21:52 +00007955 int rc;
drh4b70f112004-05-02 21:12:19 +00007956 unsigned char *pCell;
7957 int i;
dan8ce71842014-01-14 20:14:09 +00007958 int hdr;
drh9bfdc252014-09-24 02:05:41 +00007959 u16 szCell;
drh8b2f49b2001-06-08 00:21:52 +00007960
drh1fee73e2007-08-29 04:00:57 +00007961 assert( sqlite3_mutex_held(pBt->mutex) );
drhb1299152010-03-30 22:58:33 +00007962 if( pgno>btreePagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00007963 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00007964 }
7965
dan11dcd112013-03-15 18:29:18 +00007966 rc = getAndInitPage(pBt, pgno, &pPage, 0);
danielk1977146ba992009-07-22 14:08:13 +00007967 if( rc ) return rc;
dan8ce71842014-01-14 20:14:09 +00007968 hdr = pPage->hdrOffset;
drh4b70f112004-05-02 21:12:19 +00007969 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00007970 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00007971 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00007972 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00007973 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00007974 }
drh9bfdc252014-09-24 02:05:41 +00007975 rc = clearCell(pPage, pCell, &szCell);
danielk19776b456a22005-03-21 04:04:02 +00007976 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00007977 }
drha34b6762004-05-07 13:30:42 +00007978 if( !pPage->leaf ){
dan8ce71842014-01-14 20:14:09 +00007979 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00007980 if( rc ) goto cleardatabasepage_out;
danielk1977c7af4842008-10-27 13:59:33 +00007981 }else if( pnChange ){
7982 assert( pPage->intKey );
7983 *pnChange += pPage->nCell;
drh2aa679f2001-06-25 02:11:07 +00007984 }
7985 if( freePageFlag ){
drhc314dc72009-07-21 11:52:34 +00007986 freePage(pPage, &rc);
danielk19773b8a05f2007-03-19 17:44:26 +00007987 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
dan8ce71842014-01-14 20:14:09 +00007988 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00007989 }
danielk19776b456a22005-03-21 04:04:02 +00007990
7991cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00007992 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00007993 return rc;
drh8b2f49b2001-06-08 00:21:52 +00007994}
7995
7996/*
drhab01f612004-05-22 02:55:23 +00007997** Delete all information from a single table in the database. iTable is
7998** the page number of the root of the table. After this routine returns,
7999** the root page is empty, but still exists.
8000**
8001** This routine will fail with SQLITE_LOCKED if there are any open
8002** read cursors on the table. Open write cursors are moved to the
8003** root of the table.
danielk1977c7af4842008-10-27 13:59:33 +00008004**
8005** If pnChange is not NULL, then table iTable must be an intkey table. The
8006** integer value pointed to by pnChange is incremented by the number of
8007** entries in the table.
drh8b2f49b2001-06-08 00:21:52 +00008008*/
danielk1977c7af4842008-10-27 13:59:33 +00008009int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
drh8b2f49b2001-06-08 00:21:52 +00008010 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00008011 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00008012 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00008013 assert( p->inTrans==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +00008014
drhc046e3e2009-07-15 11:26:44 +00008015 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
drhd60f4f42012-03-23 14:23:52 +00008016
drhc046e3e2009-07-15 11:26:44 +00008017 if( SQLITE_OK==rc ){
drhd60f4f42012-03-23 14:23:52 +00008018 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
8019 ** is the root of a table b-tree - if it is not, the following call is
8020 ** a no-op). */
8021 invalidateIncrblobCursors(p, 0, 1);
danielk197762c14b32008-11-19 09:05:26 +00008022 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
drh8b2f49b2001-06-08 00:21:52 +00008023 }
drhd677b3d2007-08-20 22:48:41 +00008024 sqlite3BtreeLeave(p);
8025 return rc;
drh8b2f49b2001-06-08 00:21:52 +00008026}
8027
8028/*
drh079a3072014-03-19 14:10:55 +00008029** Delete all information from the single table that pCur is open on.
8030**
8031** This routine only work for pCur on an ephemeral table.
8032*/
8033int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
8034 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
8035}
8036
8037/*
drh8b2f49b2001-06-08 00:21:52 +00008038** Erase all information in a table and add the root of the table to
8039** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00008040** page 1) is never added to the freelist.
8041**
8042** This routine will fail with SQLITE_LOCKED if there are any open
8043** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00008044**
8045** If AUTOVACUUM is enabled and the page at iTable is not the last
8046** root page in the database file, then the last root page
8047** in the database file is moved into the slot formerly occupied by
8048** iTable and that last slot formerly occupied by the last root page
8049** is added to the freelist instead of iTable. In this say, all
8050** root pages are kept at the beginning of the database file, which
8051** is necessary for AUTOVACUUM to work right. *piMoved is set to the
8052** page number that used to be the last root page in the file before
8053** the move. If no page gets moved, *piMoved is set to 0.
8054** The last root page is recorded in meta[3] and the value of
8055** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00008056*/
danielk197789d40042008-11-17 14:20:56 +00008057static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00008058 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00008059 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00008060 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00008061
drh1fee73e2007-08-29 04:00:57 +00008062 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00008063 assert( p->inTrans==TRANS_WRITE );
danielk1977a0bf2652004-11-04 14:30:04 +00008064
danielk1977e6efa742004-11-10 11:55:10 +00008065 /* It is illegal to drop a table if any cursors are open on the
8066 ** database. This is because in auto-vacuum mode the backend may
8067 ** need to move another root-page to fill a gap left by the deleted
8068 ** root page. If an open cursor was using this page a problem would
8069 ** occur.
drhc046e3e2009-07-15 11:26:44 +00008070 **
8071 ** This error is caught long before control reaches this point.
danielk1977e6efa742004-11-10 11:55:10 +00008072 */
drhc046e3e2009-07-15 11:26:44 +00008073 if( NEVER(pBt->pCursor) ){
danielk1977404ca072009-03-16 13:19:36 +00008074 sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
8075 return SQLITE_LOCKED_SHAREDCACHE;
drh5df72a52002-06-06 23:16:05 +00008076 }
danielk1977a0bf2652004-11-04 14:30:04 +00008077
drhb00fc3b2013-08-21 23:42:32 +00008078 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00008079 if( rc ) return rc;
danielk1977c7af4842008-10-27 13:59:33 +00008080 rc = sqlite3BtreeClearTable(p, iTable, 0);
danielk19776b456a22005-03-21 04:04:02 +00008081 if( rc ){
8082 releasePage(pPage);
8083 return rc;
8084 }
danielk1977a0bf2652004-11-04 14:30:04 +00008085
drh205f48e2004-11-05 00:43:11 +00008086 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00008087
drh4b70f112004-05-02 21:12:19 +00008088 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00008089#ifdef SQLITE_OMIT_AUTOVACUUM
drhc314dc72009-07-21 11:52:34 +00008090 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00008091 releasePage(pPage);
8092#else
8093 if( pBt->autoVacuum ){
8094 Pgno maxRootPgno;
danielk1977602b4662009-07-02 07:47:33 +00008095 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00008096
8097 if( iTable==maxRootPgno ){
8098 /* If the table being dropped is the table with the largest root-page
8099 ** number in the database, put the root page on the free list.
8100 */
drhc314dc72009-07-21 11:52:34 +00008101 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00008102 releasePage(pPage);
8103 if( rc!=SQLITE_OK ){
8104 return rc;
8105 }
8106 }else{
8107 /* The table being dropped does not have the largest root-page
8108 ** number in the database. So move the page that does into the
8109 ** gap left by the deleted root-page.
8110 */
8111 MemPage *pMove;
8112 releasePage(pPage);
drhb00fc3b2013-08-21 23:42:32 +00008113 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00008114 if( rc!=SQLITE_OK ){
8115 return rc;
8116 }
danielk19774c999992008-07-16 18:17:55 +00008117 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00008118 releasePage(pMove);
8119 if( rc!=SQLITE_OK ){
8120 return rc;
8121 }
drhfe3313f2009-07-21 19:02:20 +00008122 pMove = 0;
drhb00fc3b2013-08-21 23:42:32 +00008123 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
drhc314dc72009-07-21 11:52:34 +00008124 freePage(pMove, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00008125 releasePage(pMove);
8126 if( rc!=SQLITE_OK ){
8127 return rc;
8128 }
8129 *piMoved = maxRootPgno;
8130 }
8131
danielk1977599fcba2004-11-08 07:13:13 +00008132 /* Set the new 'max-root-page' value in the database header. This
8133 ** is the old value less one, less one more if that happens to
8134 ** be a root-page number, less one again if that is the
8135 ** PENDING_BYTE_PAGE.
8136 */
danielk197787a6e732004-11-05 12:58:25 +00008137 maxRootPgno--;
drhe1849652009-07-15 18:15:22 +00008138 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
8139 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00008140 maxRootPgno--;
8141 }
danielk1977599fcba2004-11-08 07:13:13 +00008142 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
8143
danielk1977aef0bf62005-12-30 16:28:01 +00008144 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00008145 }else{
drhc314dc72009-07-21 11:52:34 +00008146 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00008147 releasePage(pPage);
8148 }
8149#endif
drh2aa679f2001-06-25 02:11:07 +00008150 }else{
drhc046e3e2009-07-15 11:26:44 +00008151 /* If sqlite3BtreeDropTable was called on page 1.
8152 ** This really never should happen except in a corrupt
8153 ** database.
8154 */
drha34b6762004-05-07 13:30:42 +00008155 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00008156 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00008157 }
drh8b2f49b2001-06-08 00:21:52 +00008158 return rc;
8159}
drhd677b3d2007-08-20 22:48:41 +00008160int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
8161 int rc;
8162 sqlite3BtreeEnter(p);
dan7733a4d2011-09-02 18:03:16 +00008163 rc = btreeDropTable(p, iTable, piMoved);
drhd677b3d2007-08-20 22:48:41 +00008164 sqlite3BtreeLeave(p);
8165 return rc;
8166}
drh8b2f49b2001-06-08 00:21:52 +00008167
drh001bbcb2003-03-19 03:14:00 +00008168
drh8b2f49b2001-06-08 00:21:52 +00008169/*
danielk1977602b4662009-07-02 07:47:33 +00008170** This function may only be called if the b-tree connection already
8171** has a read or write transaction open on the database.
8172**
drh23e11ca2004-05-04 17:27:28 +00008173** Read the meta-information out of a database file. Meta[0]
8174** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00008175** through meta[15] are available for use by higher layers. Meta[0]
8176** is read-only, the others are read/write.
8177**
8178** The schema layer numbers meta values differently. At the schema
8179** layer (and the SetCookie and ReadCookie opcodes) the number of
8180** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh91618562014-12-19 19:28:02 +00008181**
8182** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
8183** of reading the value out of the header, it instead loads the "DataVersion"
8184** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
8185** database file. It is a number computed by the pager. But its access
8186** pattern is the same as header meta values, and so it is convenient to
8187** read it from this routine.
drh8b2f49b2001-06-08 00:21:52 +00008188*/
danielk1977602b4662009-07-02 07:47:33 +00008189void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
danielk1977aef0bf62005-12-30 16:28:01 +00008190 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00008191
drhd677b3d2007-08-20 22:48:41 +00008192 sqlite3BtreeEnter(p);
danielk1977602b4662009-07-02 07:47:33 +00008193 assert( p->inTrans>TRANS_NONE );
danielk1977e0d9e6f2009-07-03 16:25:06 +00008194 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
danielk1977602b4662009-07-02 07:47:33 +00008195 assert( pBt->pPage1 );
drh23e11ca2004-05-04 17:27:28 +00008196 assert( idx>=0 && idx<=15 );
danielk1977ea897302008-09-19 15:10:58 +00008197
drh91618562014-12-19 19:28:02 +00008198 if( idx==BTREE_DATA_VERSION ){
drh3da9c042014-12-22 18:41:21 +00008199 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
drh91618562014-12-19 19:28:02 +00008200 }else{
8201 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
8202 }
drhae157872004-08-14 19:20:09 +00008203
danielk1977602b4662009-07-02 07:47:33 +00008204 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
8205 ** database, mark the database as read-only. */
danielk1977003ba062004-11-04 02:57:33 +00008206#ifdef SQLITE_OMIT_AUTOVACUUM
drhc9166342012-01-05 23:32:06 +00008207 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
8208 pBt->btsFlags |= BTS_READ_ONLY;
8209 }
danielk1977003ba062004-11-04 02:57:33 +00008210#endif
drhae157872004-08-14 19:20:09 +00008211
drhd677b3d2007-08-20 22:48:41 +00008212 sqlite3BtreeLeave(p);
drh8b2f49b2001-06-08 00:21:52 +00008213}
8214
8215/*
drh23e11ca2004-05-04 17:27:28 +00008216** Write meta-information back into the database. Meta[0] is
8217** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00008218*/
danielk1977aef0bf62005-12-30 16:28:01 +00008219int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
8220 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00008221 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00008222 int rc;
drh23e11ca2004-05-04 17:27:28 +00008223 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00008224 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00008225 assert( p->inTrans==TRANS_WRITE );
8226 assert( pBt->pPage1!=0 );
8227 pP1 = pBt->pPage1->aData;
8228 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
8229 if( rc==SQLITE_OK ){
8230 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +00008231#ifndef SQLITE_OMIT_AUTOVACUUM
danielk19770d19f7a2009-06-03 11:25:07 +00008232 if( idx==BTREE_INCR_VACUUM ){
drh64022502009-01-09 14:11:04 +00008233 assert( pBt->autoVacuum || iMeta==0 );
8234 assert( iMeta==0 || iMeta==1 );
8235 pBt->incrVacuum = (u8)iMeta;
drhd677b3d2007-08-20 22:48:41 +00008236 }
drh64022502009-01-09 14:11:04 +00008237#endif
drh5df72a52002-06-06 23:16:05 +00008238 }
drhd677b3d2007-08-20 22:48:41 +00008239 sqlite3BtreeLeave(p);
8240 return rc;
drh8b2f49b2001-06-08 00:21:52 +00008241}
drh8c42ca92001-06-22 19:15:00 +00008242
danielk1977a5533162009-02-24 10:01:51 +00008243#ifndef SQLITE_OMIT_BTREECOUNT
8244/*
8245** The first argument, pCur, is a cursor opened on some b-tree. Count the
8246** number of entries in the b-tree and write the result to *pnEntry.
8247**
8248** SQLITE_OK is returned if the operation is successfully executed.
8249** Otherwise, if an error is encountered (i.e. an IO error or database
8250** corruption) an SQLite error code is returned.
8251*/
8252int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
8253 i64 nEntry = 0; /* Value to return in *pnEntry */
8254 int rc; /* Return code */
dana205a482011-08-27 18:48:57 +00008255
8256 if( pCur->pgnoRoot==0 ){
8257 *pnEntry = 0;
8258 return SQLITE_OK;
8259 }
danielk1977a5533162009-02-24 10:01:51 +00008260 rc = moveToRoot(pCur);
8261
8262 /* Unless an error occurs, the following loop runs one iteration for each
8263 ** page in the B-Tree structure (not including overflow pages).
8264 */
8265 while( rc==SQLITE_OK ){
8266 int iIdx; /* Index of child node in parent */
8267 MemPage *pPage; /* Current page of the b-tree */
8268
8269 /* If this is a leaf page or the tree is not an int-key tree, then
8270 ** this page contains countable entries. Increment the entry counter
8271 ** accordingly.
8272 */
8273 pPage = pCur->apPage[pCur->iPage];
8274 if( pPage->leaf || !pPage->intKey ){
8275 nEntry += pPage->nCell;
8276 }
8277
8278 /* pPage is a leaf node. This loop navigates the cursor so that it
8279 ** points to the first interior cell that it points to the parent of
8280 ** the next page in the tree that has not yet been visited. The
8281 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
8282 ** of the page, or to the number of cells in the page if the next page
8283 ** to visit is the right-child of its parent.
8284 **
8285 ** If all pages in the tree have been visited, return SQLITE_OK to the
8286 ** caller.
8287 */
8288 if( pPage->leaf ){
8289 do {
8290 if( pCur->iPage==0 ){
8291 /* All pages of the b-tree have been visited. Return successfully. */
8292 *pnEntry = nEntry;
drh7efa4262014-12-16 00:08:31 +00008293 return moveToRoot(pCur);
danielk1977a5533162009-02-24 10:01:51 +00008294 }
danielk197730548662009-07-09 05:07:37 +00008295 moveToParent(pCur);
danielk1977a5533162009-02-24 10:01:51 +00008296 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
8297
8298 pCur->aiIdx[pCur->iPage]++;
8299 pPage = pCur->apPage[pCur->iPage];
8300 }
8301
8302 /* Descend to the child node of the cell that the cursor currently
8303 ** points at. This is the right-child if (iIdx==pPage->nCell).
8304 */
8305 iIdx = pCur->aiIdx[pCur->iPage];
8306 if( iIdx==pPage->nCell ){
8307 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
8308 }else{
8309 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
8310 }
8311 }
8312
shanebe217792009-03-05 04:20:31 +00008313 /* An error has occurred. Return an error code. */
danielk1977a5533162009-02-24 10:01:51 +00008314 return rc;
8315}
8316#endif
drhdd793422001-06-28 01:54:48 +00008317
drhdd793422001-06-28 01:54:48 +00008318/*
drh5eddca62001-06-30 21:53:53 +00008319** Return the pager associated with a BTree. This routine is used for
8320** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00008321*/
danielk1977aef0bf62005-12-30 16:28:01 +00008322Pager *sqlite3BtreePager(Btree *p){
8323 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00008324}
drh5eddca62001-06-30 21:53:53 +00008325
drhb7f91642004-10-31 02:22:47 +00008326#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00008327/*
8328** Append a message to the error message string.
8329*/
drh2e38c322004-09-03 18:38:44 +00008330static void checkAppendMsg(
8331 IntegrityCk *pCheck,
drh2e38c322004-09-03 18:38:44 +00008332 const char *zFormat,
8333 ...
8334){
8335 va_list ap;
drh867db832014-09-26 02:41:05 +00008336 char zBuf[200];
drh1dcdbc02007-01-27 02:24:54 +00008337 if( !pCheck->mxErr ) return;
8338 pCheck->mxErr--;
8339 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00008340 va_start(ap, zFormat);
drhf089aa42008-07-08 19:34:06 +00008341 if( pCheck->errMsg.nChar ){
8342 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
drh5eddca62001-06-30 21:53:53 +00008343 }
drh867db832014-09-26 02:41:05 +00008344 if( pCheck->zPfx ){
8345 sqlite3_snprintf(sizeof(zBuf), zBuf, pCheck->zPfx, pCheck->v1, pCheck->v2);
8346 sqlite3StrAccumAppendAll(&pCheck->errMsg, zBuf);
drhf089aa42008-07-08 19:34:06 +00008347 }
8348 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
8349 va_end(ap);
drhb49bc862013-08-21 21:12:10 +00008350 if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
drhc890fec2008-08-01 20:10:08 +00008351 pCheck->mallocFailed = 1;
8352 }
drh5eddca62001-06-30 21:53:53 +00008353}
drhb7f91642004-10-31 02:22:47 +00008354#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00008355
drhb7f91642004-10-31 02:22:47 +00008356#ifndef SQLITE_OMIT_INTEGRITY_CHECK
dan1235bb12012-04-03 17:43:28 +00008357
8358/*
8359** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
8360** corresponds to page iPg is already set.
8361*/
8362static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
8363 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
8364 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
8365}
8366
8367/*
8368** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
8369*/
8370static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
8371 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
8372 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
8373}
8374
8375
drh5eddca62001-06-30 21:53:53 +00008376/*
8377** Add 1 to the reference count for page iPage. If this is the second
8378** reference to the page, add an error message to pCheck->zErrMsg.
peter.d.reid60ec9142014-09-06 16:39:46 +00008379** Return 1 if there are 2 or more references to the page and 0 if
drh5eddca62001-06-30 21:53:53 +00008380** if this is the first reference to the page.
8381**
8382** Also check that the page number is in bounds.
8383*/
drh867db832014-09-26 02:41:05 +00008384static int checkRef(IntegrityCk *pCheck, Pgno iPage){
drh5eddca62001-06-30 21:53:53 +00008385 if( iPage==0 ) return 1;
danielk197789d40042008-11-17 14:20:56 +00008386 if( iPage>pCheck->nPage ){
drh867db832014-09-26 02:41:05 +00008387 checkAppendMsg(pCheck, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00008388 return 1;
8389 }
dan1235bb12012-04-03 17:43:28 +00008390 if( getPageReferenced(pCheck, iPage) ){
drh867db832014-09-26 02:41:05 +00008391 checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00008392 return 1;
8393 }
dan1235bb12012-04-03 17:43:28 +00008394 setPageReferenced(pCheck, iPage);
8395 return 0;
drh5eddca62001-06-30 21:53:53 +00008396}
8397
danielk1977afcdd022004-10-31 16:25:42 +00008398#ifndef SQLITE_OMIT_AUTOVACUUM
8399/*
8400** Check that the entry in the pointer-map for page iChild maps to
8401** page iParent, pointer type ptrType. If not, append an error message
8402** to pCheck.
8403*/
8404static void checkPtrmap(
8405 IntegrityCk *pCheck, /* Integrity check context */
8406 Pgno iChild, /* Child page number */
8407 u8 eType, /* Expected pointer map type */
drh867db832014-09-26 02:41:05 +00008408 Pgno iParent /* Expected pointer map parent page number */
danielk1977afcdd022004-10-31 16:25:42 +00008409){
8410 int rc;
8411 u8 ePtrmapType;
8412 Pgno iPtrmapParent;
8413
8414 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
8415 if( rc!=SQLITE_OK ){
drhb56cd552009-05-01 13:16:54 +00008416 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
drh867db832014-09-26 02:41:05 +00008417 checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
danielk1977afcdd022004-10-31 16:25:42 +00008418 return;
8419 }
8420
8421 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
drh867db832014-09-26 02:41:05 +00008422 checkAppendMsg(pCheck,
danielk1977afcdd022004-10-31 16:25:42 +00008423 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
8424 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
8425 }
8426}
8427#endif
8428
drh5eddca62001-06-30 21:53:53 +00008429/*
8430** Check the integrity of the freelist or of an overflow page list.
8431** Verify that the number of pages on the list is N.
8432*/
drh30e58752002-03-02 20:41:57 +00008433static void checkList(
8434 IntegrityCk *pCheck, /* Integrity checking context */
8435 int isFreeList, /* True for a freelist. False for overflow page list */
8436 int iPage, /* Page number for first page in the list */
drh867db832014-09-26 02:41:05 +00008437 int N /* Expected number of pages in the list */
drh30e58752002-03-02 20:41:57 +00008438){
8439 int i;
drh3a4c1412004-05-09 20:40:11 +00008440 int expected = N;
8441 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00008442 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00008443 DbPage *pOvflPage;
8444 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00008445 if( iPage<1 ){
drh867db832014-09-26 02:41:05 +00008446 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00008447 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00008448 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00008449 break;
8450 }
drh867db832014-09-26 02:41:05 +00008451 if( checkRef(pCheck, iPage) ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00008452 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
drh867db832014-09-26 02:41:05 +00008453 checkAppendMsg(pCheck, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00008454 break;
8455 }
danielk19773b8a05f2007-03-19 17:44:26 +00008456 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00008457 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00008458 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00008459#ifndef SQLITE_OMIT_AUTOVACUUM
8460 if( pCheck->pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00008461 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +00008462 }
8463#endif
drh43b18e12010-08-17 19:40:08 +00008464 if( n>(int)pCheck->pBt->usableSize/4-2 ){
drh867db832014-09-26 02:41:05 +00008465 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00008466 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00008467 N--;
8468 }else{
8469 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00008470 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00008471#ifndef SQLITE_OMIT_AUTOVACUUM
8472 if( pCheck->pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00008473 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +00008474 }
8475#endif
drh867db832014-09-26 02:41:05 +00008476 checkRef(pCheck, iFreePage);
drhee696e22004-08-30 16:52:17 +00008477 }
8478 N -= n;
drh30e58752002-03-02 20:41:57 +00008479 }
drh30e58752002-03-02 20:41:57 +00008480 }
danielk1977afcdd022004-10-31 16:25:42 +00008481#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00008482 else{
8483 /* If this database supports auto-vacuum and iPage is not the last
8484 ** page in this overflow list, check that the pointer-map entry for
8485 ** the following page matches iPage.
8486 */
8487 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00008488 i = get4byte(pOvflData);
drh867db832014-09-26 02:41:05 +00008489 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
danielk1977687566d2004-11-02 12:56:41 +00008490 }
danielk1977afcdd022004-10-31 16:25:42 +00008491 }
8492#endif
danielk19773b8a05f2007-03-19 17:44:26 +00008493 iPage = get4byte(pOvflData);
8494 sqlite3PagerUnref(pOvflPage);
drh5eddca62001-06-30 21:53:53 +00008495 }
8496}
drhb7f91642004-10-31 02:22:47 +00008497#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00008498
drhb7f91642004-10-31 02:22:47 +00008499#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00008500/*
8501** Do various sanity checks on a single page of a tree. Return
8502** the tree depth. Root pages return 0. Parents of root pages
8503** return 1, and so forth.
8504**
8505** These checks are done:
8506**
8507** 1. Make sure that cells and freeblocks do not overlap
8508** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00008509** NO 2. Make sure cell keys are in order.
8510** NO 3. Make sure no key is less than or equal to zLowerBound.
8511** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00008512** 5. Check the integrity of overflow pages.
8513** 6. Recursively call checkTreePage on all children.
8514** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00008515** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00008516** the root of the tree.
8517*/
8518static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00008519 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00008520 int iPage, /* Page number of the page to check */
shaneh195475d2010-02-19 04:28:08 +00008521 i64 *pnParentMinKey,
8522 i64 *pnParentMaxKey
drh5eddca62001-06-30 21:53:53 +00008523){
8524 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00008525 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00008526 int hdr, cellStart;
8527 int nCell;
drhda200cc2004-05-09 11:51:38 +00008528 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00008529 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00008530 int usableSize;
shane0af3f892008-11-12 04:55:34 +00008531 char *hit = 0;
shaneh195475d2010-02-19 04:28:08 +00008532 i64 nMinKey = 0;
8533 i64 nMaxKey = 0;
drh867db832014-09-26 02:41:05 +00008534 const char *saved_zPfx = pCheck->zPfx;
8535 int saved_v1 = pCheck->v1;
8536 int saved_v2 = pCheck->v2;
danielk1977ef73ee92004-11-06 12:26:07 +00008537
drh5eddca62001-06-30 21:53:53 +00008538 /* Check that the page exists
8539 */
drhd9cb6ac2005-10-20 07:28:17 +00008540 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00008541 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00008542 if( iPage==0 ) return 0;
drh867db832014-09-26 02:41:05 +00008543 if( checkRef(pCheck, iPage) ) return 0;
8544 pCheck->zPfx = "Page %d: ";
8545 pCheck->v1 = iPage;
drhb00fc3b2013-08-21 23:42:32 +00008546 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drh867db832014-09-26 02:41:05 +00008547 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00008548 "unable to get the page. error code=%d", rc);
drh867db832014-09-26 02:41:05 +00008549 depth = -1;
8550 goto end_of_check;
drh5eddca62001-06-30 21:53:53 +00008551 }
danielk197793caf5a2009-07-11 06:55:33 +00008552
8553 /* Clear MemPage.isInit to make sure the corruption detection code in
8554 ** btreeInitPage() is executed. */
8555 pPage->isInit = 0;
danielk197730548662009-07-09 05:07:37 +00008556 if( (rc = btreeInitPage(pPage))!=0 ){
drh64022502009-01-09 14:11:04 +00008557 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
drh867db832014-09-26 02:41:05 +00008558 checkAppendMsg(pCheck,
danielk197730548662009-07-09 05:07:37 +00008559 "btreeInitPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00008560 releasePage(pPage);
drh867db832014-09-26 02:41:05 +00008561 depth = -1;
8562 goto end_of_check;
drh5eddca62001-06-30 21:53:53 +00008563 }
8564
8565 /* Check out all the cells.
8566 */
8567 depth = 0;
drh1dcdbc02007-01-27 02:24:54 +00008568 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
drh6f11bef2004-05-13 01:12:56 +00008569 u8 *pCell;
danielk197789d40042008-11-17 14:20:56 +00008570 u32 sz;
drh6f11bef2004-05-13 01:12:56 +00008571 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00008572
8573 /* Check payload overflow pages
8574 */
drh867db832014-09-26 02:41:05 +00008575 pCheck->zPfx = "On tree page %d cell %d: ";
8576 pCheck->v1 = iPage;
8577 pCheck->v2 = i;
danielk19771cc5ed82007-05-16 17:28:43 +00008578 pCell = findCell(pPage,i);
danielk197730548662009-07-09 05:07:37 +00008579 btreeParseCellPtr(pPage, pCell, &info);
drhab1cc582014-09-23 21:25:19 +00008580 sz = info.nPayload;
shaneh195475d2010-02-19 04:28:08 +00008581 /* For intKey pages, check that the keys are in order.
8582 */
drhab1cc582014-09-23 21:25:19 +00008583 if( pPage->intKey ){
8584 if( i==0 ){
8585 nMinKey = nMaxKey = info.nKey;
8586 }else if( info.nKey <= nMaxKey ){
drh867db832014-09-26 02:41:05 +00008587 checkAppendMsg(pCheck,
drhab1cc582014-09-23 21:25:19 +00008588 "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
shaneh195475d2010-02-19 04:28:08 +00008589 }
8590 nMaxKey = info.nKey;
8591 }
danielk19775be31f52009-03-30 13:53:43 +00008592 if( (sz>info.nLocal)
8593 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
8594 ){
drhb6f41482004-05-14 01:58:11 +00008595 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00008596 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
8597#ifndef SQLITE_OMIT_AUTOVACUUM
8598 if( pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00008599 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
danielk1977afcdd022004-10-31 16:25:42 +00008600 }
8601#endif
drh867db832014-09-26 02:41:05 +00008602 checkList(pCheck, 0, pgnoOvfl, nPage);
drh5eddca62001-06-30 21:53:53 +00008603 }
8604
8605 /* Check sanity of left child page.
8606 */
drhda200cc2004-05-09 11:51:38 +00008607 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00008608 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00008609#ifndef SQLITE_OMIT_AUTOVACUUM
8610 if( pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00008611 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
danielk1977afcdd022004-10-31 16:25:42 +00008612 }
8613#endif
drh867db832014-09-26 02:41:05 +00008614 d2 = checkTreePage(pCheck, pgno, &nMinKey, i==0?NULL:&nMaxKey);
drhda200cc2004-05-09 11:51:38 +00008615 if( i>0 && d2!=depth ){
drh867db832014-09-26 02:41:05 +00008616 checkAppendMsg(pCheck, "Child page depth differs");
drhda200cc2004-05-09 11:51:38 +00008617 }
8618 depth = d2;
drh5eddca62001-06-30 21:53:53 +00008619 }
drh5eddca62001-06-30 21:53:53 +00008620 }
shaneh195475d2010-02-19 04:28:08 +00008621
drhda200cc2004-05-09 11:51:38 +00008622 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00008623 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh867db832014-09-26 02:41:05 +00008624 pCheck->zPfx = "On page %d at right child: ";
8625 pCheck->v1 = iPage;
danielk1977afcdd022004-10-31 16:25:42 +00008626#ifndef SQLITE_OMIT_AUTOVACUUM
8627 if( pBt->autoVacuum ){
drh867db832014-09-26 02:41:05 +00008628 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
danielk1977afcdd022004-10-31 16:25:42 +00008629 }
8630#endif
drh867db832014-09-26 02:41:05 +00008631 checkTreePage(pCheck, pgno, NULL, !pPage->nCell?NULL:&nMaxKey);
drhda200cc2004-05-09 11:51:38 +00008632 }
drh5eddca62001-06-30 21:53:53 +00008633
shaneh195475d2010-02-19 04:28:08 +00008634 /* For intKey leaf pages, check that the min/max keys are in order
8635 ** with any left/parent/right pages.
8636 */
drh867db832014-09-26 02:41:05 +00008637 pCheck->zPfx = "Page %d: ";
8638 pCheck->v1 = iPage;
shaneh195475d2010-02-19 04:28:08 +00008639 if( pPage->leaf && pPage->intKey ){
8640 /* if we are a left child page */
8641 if( pnParentMinKey ){
8642 /* if we are the left most child page */
8643 if( !pnParentMaxKey ){
8644 if( nMaxKey > *pnParentMinKey ){
drh867db832014-09-26 02:41:05 +00008645 checkAppendMsg(pCheck,
shaneh195475d2010-02-19 04:28:08 +00008646 "Rowid %lld out of order (max larger than parent min of %lld)",
8647 nMaxKey, *pnParentMinKey);
8648 }
8649 }else{
8650 if( nMinKey <= *pnParentMinKey ){
drh867db832014-09-26 02:41:05 +00008651 checkAppendMsg(pCheck,
shaneh195475d2010-02-19 04:28:08 +00008652 "Rowid %lld out of order (min less than parent min of %lld)",
8653 nMinKey, *pnParentMinKey);
8654 }
8655 if( nMaxKey > *pnParentMaxKey ){
drh867db832014-09-26 02:41:05 +00008656 checkAppendMsg(pCheck,
shaneh195475d2010-02-19 04:28:08 +00008657 "Rowid %lld out of order (max larger than parent max of %lld)",
8658 nMaxKey, *pnParentMaxKey);
8659 }
8660 *pnParentMinKey = nMaxKey;
8661 }
8662 /* else if we're a right child page */
8663 } else if( pnParentMaxKey ){
8664 if( nMinKey <= *pnParentMaxKey ){
drh867db832014-09-26 02:41:05 +00008665 checkAppendMsg(pCheck,
shaneh195475d2010-02-19 04:28:08 +00008666 "Rowid %lld out of order (min less than parent max of %lld)",
8667 nMinKey, *pnParentMaxKey);
8668 }
8669 }
8670 }
8671
drh5eddca62001-06-30 21:53:53 +00008672 /* Check for complete coverage of the page
8673 */
drhda200cc2004-05-09 11:51:38 +00008674 data = pPage->aData;
8675 hdr = pPage->hdrOffset;
drhf7141992008-06-19 00:16:08 +00008676 hit = sqlite3PageMalloc( pBt->pageSize );
drh867db832014-09-26 02:41:05 +00008677 pCheck->zPfx = 0;
drhc890fec2008-08-01 20:10:08 +00008678 if( hit==0 ){
8679 pCheck->mallocFailed = 1;
8680 }else{
drh5d433ce2010-08-14 16:02:52 +00008681 int contentOffset = get2byteNotZero(&data[hdr+5]);
drhd7c7ecd2009-07-14 17:48:06 +00008682 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
shane5780ebd2008-11-11 17:36:30 +00008683 memset(hit+contentOffset, 0, usableSize-contentOffset);
8684 memset(hit, 1, contentOffset);
drhfdab0262014-11-20 15:30:50 +00008685 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
8686 ** number of cells on the page. */
drh2e38c322004-09-03 18:38:44 +00008687 nCell = get2byte(&data[hdr+3]);
drhfdab0262014-11-20 15:30:50 +00008688 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
8689 ** immediately follows the b-tree page header. */
drh2e38c322004-09-03 18:38:44 +00008690 cellStart = hdr + 12 - 4*pPage->leaf;
drhfdab0262014-11-20 15:30:50 +00008691 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
8692 ** integer offsets to the cell contents. */
drh2e38c322004-09-03 18:38:44 +00008693 for(i=0; i<nCell; i++){
8694 int pc = get2byte(&data[cellStart+i*2]);
drh9b78f792010-08-14 21:21:24 +00008695 u32 size = 65536;
drh2e38c322004-09-03 18:38:44 +00008696 int j;
drh8c2bbb62009-07-10 02:52:20 +00008697 if( pc<=usableSize-4 ){
danielk1977daca5432008-08-25 11:57:16 +00008698 size = cellSizePtr(pPage, &data[pc]);
8699 }
drh43b18e12010-08-17 19:40:08 +00008700 if( (int)(pc+size-1)>=usableSize ){
drh867db832014-09-26 02:41:05 +00008701 pCheck->zPfx = 0;
8702 checkAppendMsg(pCheck,
shaneh195475d2010-02-19 04:28:08 +00008703 "Corruption detected in cell %d on page %d",i,iPage);
danielk19777701e812005-01-10 12:59:51 +00008704 }else{
8705 for(j=pc+size-1; j>=pc; j--) hit[j]++;
8706 }
drh2e38c322004-09-03 18:38:44 +00008707 }
drhfdab0262014-11-20 15:30:50 +00008708 /* EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
8709 ** is the offset of the first freeblock, or zero if there are no
8710 ** freeblocks on the page. */
drh8c2bbb62009-07-10 02:52:20 +00008711 i = get2byte(&data[hdr+1]);
8712 while( i>0 ){
8713 int size, j;
8714 assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
8715 size = get2byte(&data[i+2]);
8716 assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
8717 for(j=i+size-1; j>=i; j--) hit[j]++;
drhfdab0262014-11-20 15:30:50 +00008718 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
8719 ** big-endian integer which is the offset in the b-tree page of the next
8720 ** freeblock in the chain, or zero if the freeblock is the last on the
8721 ** chain. */
drh8c2bbb62009-07-10 02:52:20 +00008722 j = get2byte(&data[i]);
drhfdab0262014-11-20 15:30:50 +00008723 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
8724 ** increasing offset. */
drh8c2bbb62009-07-10 02:52:20 +00008725 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
8726 assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
8727 i = j;
drh2e38c322004-09-03 18:38:44 +00008728 }
8729 for(i=cnt=0; i<usableSize; i++){
8730 if( hit[i]==0 ){
8731 cnt++;
8732 }else if( hit[i]>1 ){
drh867db832014-09-26 02:41:05 +00008733 checkAppendMsg(pCheck,
drh2e38c322004-09-03 18:38:44 +00008734 "Multiple uses for byte %d of page %d", i, iPage);
8735 break;
8736 }
8737 }
drhfdab0262014-11-20 15:30:50 +00008738 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
8739 ** is stored in the fifth field of the b-tree page header.
8740 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
8741 ** number of fragmented free bytes within the cell content area.
8742 */
drh2e38c322004-09-03 18:38:44 +00008743 if( cnt!=data[hdr+7] ){
drh867db832014-09-26 02:41:05 +00008744 checkAppendMsg(pCheck,
drh8c2bbb62009-07-10 02:52:20 +00008745 "Fragmentation of %d bytes reported as %d on page %d",
drh2e38c322004-09-03 18:38:44 +00008746 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00008747 }
8748 }
drh8c2bbb62009-07-10 02:52:20 +00008749 sqlite3PageFree(hit);
drh4b70f112004-05-02 21:12:19 +00008750 releasePage(pPage);
drh867db832014-09-26 02:41:05 +00008751
8752end_of_check:
8753 pCheck->zPfx = saved_zPfx;
8754 pCheck->v1 = saved_v1;
8755 pCheck->v2 = saved_v2;
drhda200cc2004-05-09 11:51:38 +00008756 return depth+1;
drh5eddca62001-06-30 21:53:53 +00008757}
drhb7f91642004-10-31 02:22:47 +00008758#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00008759
drhb7f91642004-10-31 02:22:47 +00008760#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00008761/*
8762** This routine does a complete check of the given BTree file. aRoot[] is
8763** an array of pages numbers were each page number is the root page of
8764** a table. nRoot is the number of entries in aRoot.
8765**
danielk19773509a652009-07-06 18:56:13 +00008766** A read-only or read-write transaction must be opened before calling
8767** this function.
8768**
drhc890fec2008-08-01 20:10:08 +00008769** Write the number of error seen in *pnErr. Except for some memory
drhe43ba702008-12-05 22:40:08 +00008770** allocation errors, an error message held in memory obtained from
drhc890fec2008-08-01 20:10:08 +00008771** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
drhe43ba702008-12-05 22:40:08 +00008772** returned. If a memory allocation error occurs, NULL is returned.
drh5eddca62001-06-30 21:53:53 +00008773*/
drh1dcdbc02007-01-27 02:24:54 +00008774char *sqlite3BtreeIntegrityCheck(
8775 Btree *p, /* The btree to be checked */
8776 int *aRoot, /* An array of root pages numbers for individual trees */
8777 int nRoot, /* Number of entries in aRoot[] */
8778 int mxErr, /* Stop reporting errors after this many */
8779 int *pnErr /* Write number of errors seen to this variable */
8780){
danielk197789d40042008-11-17 14:20:56 +00008781 Pgno i;
drh5eddca62001-06-30 21:53:53 +00008782 int nRef;
drhaaab5722002-02-19 13:39:21 +00008783 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00008784 BtShared *pBt = p->pBt;
drhf089aa42008-07-08 19:34:06 +00008785 char zErr[100];
drh5eddca62001-06-30 21:53:53 +00008786
drhd677b3d2007-08-20 22:48:41 +00008787 sqlite3BtreeEnter(p);
danielk19773509a652009-07-06 18:56:13 +00008788 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
danielk19773b8a05f2007-03-19 17:44:26 +00008789 nRef = sqlite3PagerRefcount(pBt->pPager);
drh5eddca62001-06-30 21:53:53 +00008790 sCheck.pBt = pBt;
8791 sCheck.pPager = pBt->pPager;
drhb1299152010-03-30 22:58:33 +00008792 sCheck.nPage = btreePagecount(sCheck.pBt);
drh1dcdbc02007-01-27 02:24:54 +00008793 sCheck.mxErr = mxErr;
8794 sCheck.nErr = 0;
drhc890fec2008-08-01 20:10:08 +00008795 sCheck.mallocFailed = 0;
drh867db832014-09-26 02:41:05 +00008796 sCheck.zPfx = 0;
8797 sCheck.v1 = 0;
8798 sCheck.v2 = 0;
drh1dcdbc02007-01-27 02:24:54 +00008799 *pnErr = 0;
drh0de8c112002-07-06 16:32:14 +00008800 if( sCheck.nPage==0 ){
drhd677b3d2007-08-20 22:48:41 +00008801 sqlite3BtreeLeave(p);
drh0de8c112002-07-06 16:32:14 +00008802 return 0;
8803 }
dan1235bb12012-04-03 17:43:28 +00008804
8805 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
8806 if( !sCheck.aPgRef ){
drh1dcdbc02007-01-27 02:24:54 +00008807 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00008808 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00008809 return 0;
danielk1977ac245ec2005-01-14 13:50:11 +00008810 }
drh42cac6d2004-11-20 20:31:11 +00008811 i = PENDING_BYTE_PAGE(pBt);
dan1235bb12012-04-03 17:43:28 +00008812 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
drh32055c22012-12-12 14:30:03 +00008813 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
drhb9755982010-07-24 16:34:37 +00008814 sCheck.errMsg.useMalloc = 2;
drh5eddca62001-06-30 21:53:53 +00008815
8816 /* Check the integrity of the freelist
8817 */
drh867db832014-09-26 02:41:05 +00008818 sCheck.zPfx = "Main freelist: ";
drha34b6762004-05-07 13:30:42 +00008819 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
drh867db832014-09-26 02:41:05 +00008820 get4byte(&pBt->pPage1->aData[36]));
8821 sCheck.zPfx = 0;
drh5eddca62001-06-30 21:53:53 +00008822
8823 /* Check all the tables.
8824 */
danielk197789d40042008-11-17 14:20:56 +00008825 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
drh4ff6dfa2002-03-03 23:06:00 +00008826 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00008827#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00008828 if( pBt->autoVacuum && aRoot[i]>1 ){
drh867db832014-09-26 02:41:05 +00008829 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
danielk1977687566d2004-11-02 12:56:41 +00008830 }
8831#endif
drh867db832014-09-26 02:41:05 +00008832 sCheck.zPfx = "List of tree roots: ";
8833 checkTreePage(&sCheck, aRoot[i], NULL, NULL);
8834 sCheck.zPfx = 0;
drh5eddca62001-06-30 21:53:53 +00008835 }
8836
8837 /* Make sure every page in the file is referenced
8838 */
drh1dcdbc02007-01-27 02:24:54 +00008839 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00008840#ifdef SQLITE_OMIT_AUTOVACUUM
dan1235bb12012-04-03 17:43:28 +00008841 if( getPageReferenced(&sCheck, i)==0 ){
drh867db832014-09-26 02:41:05 +00008842 checkAppendMsg(&sCheck, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00008843 }
danielk1977afcdd022004-10-31 16:25:42 +00008844#else
8845 /* If the database supports auto-vacuum, make sure no tables contain
8846 ** references to pointer-map pages.
8847 */
dan1235bb12012-04-03 17:43:28 +00008848 if( getPageReferenced(&sCheck, i)==0 &&
danielk1977266664d2006-02-10 08:24:21 +00008849 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
drh867db832014-09-26 02:41:05 +00008850 checkAppendMsg(&sCheck, "Page %d is never used", i);
danielk1977afcdd022004-10-31 16:25:42 +00008851 }
dan1235bb12012-04-03 17:43:28 +00008852 if( getPageReferenced(&sCheck, i)!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00008853 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
drh867db832014-09-26 02:41:05 +00008854 checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
danielk1977afcdd022004-10-31 16:25:42 +00008855 }
8856#endif
drh5eddca62001-06-30 21:53:53 +00008857 }
8858
drh64022502009-01-09 14:11:04 +00008859 /* Make sure this analysis did not leave any unref() pages.
8860 ** This is an internal consistency check; an integrity check
8861 ** of the integrity check.
drh5eddca62001-06-30 21:53:53 +00008862 */
drh64022502009-01-09 14:11:04 +00008863 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
drh867db832014-09-26 02:41:05 +00008864 checkAppendMsg(&sCheck,
drh5eddca62001-06-30 21:53:53 +00008865 "Outstanding page count goes from %d to %d during this analysis",
danielk19773b8a05f2007-03-19 17:44:26 +00008866 nRef, sqlite3PagerRefcount(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00008867 );
drh5eddca62001-06-30 21:53:53 +00008868 }
8869
8870 /* Clean up and report errors.
8871 */
drhd677b3d2007-08-20 22:48:41 +00008872 sqlite3BtreeLeave(p);
dan1235bb12012-04-03 17:43:28 +00008873 sqlite3_free(sCheck.aPgRef);
drhc890fec2008-08-01 20:10:08 +00008874 if( sCheck.mallocFailed ){
8875 sqlite3StrAccumReset(&sCheck.errMsg);
8876 *pnErr = sCheck.nErr+1;
8877 return 0;
8878 }
drh1dcdbc02007-01-27 02:24:54 +00008879 *pnErr = sCheck.nErr;
drhf089aa42008-07-08 19:34:06 +00008880 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
8881 return sqlite3StrAccumFinish(&sCheck.errMsg);
drh5eddca62001-06-30 21:53:53 +00008882}
drhb7f91642004-10-31 02:22:47 +00008883#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00008884
drh73509ee2003-04-06 20:44:45 +00008885/*
drhd4e0bb02012-05-27 01:19:04 +00008886** Return the full pathname of the underlying database file. Return
8887** an empty string if the database is in-memory or a TEMP database.
drhd0679ed2007-08-28 22:24:34 +00008888**
8889** The pager filename is invariant as long as the pager is
8890** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +00008891*/
danielk1977aef0bf62005-12-30 16:28:01 +00008892const char *sqlite3BtreeGetFilename(Btree *p){
8893 assert( p->pBt->pPager!=0 );
drhd4e0bb02012-05-27 01:19:04 +00008894 return sqlite3PagerFilename(p->pBt->pPager, 1);
drh73509ee2003-04-06 20:44:45 +00008895}
8896
8897/*
danielk19775865e3d2004-06-14 06:03:57 +00008898** Return the pathname of the journal file for this database. The return
8899** value of this routine is the same regardless of whether the journal file
8900** has been created or not.
drhd0679ed2007-08-28 22:24:34 +00008901**
8902** The pager journal filename is invariant as long as the pager is
8903** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00008904*/
danielk1977aef0bf62005-12-30 16:28:01 +00008905const char *sqlite3BtreeGetJournalname(Btree *p){
8906 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00008907 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00008908}
8909
danielk19771d850a72004-05-31 08:26:49 +00008910/*
8911** Return non-zero if a transaction is active.
8912*/
danielk1977aef0bf62005-12-30 16:28:01 +00008913int sqlite3BtreeIsInTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00008914 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00008915 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00008916}
8917
dana550f2d2010-08-02 10:47:05 +00008918#ifndef SQLITE_OMIT_WAL
8919/*
8920** Run a checkpoint on the Btree passed as the first argument.
8921**
8922** Return SQLITE_LOCKED if this or any other connection has an open
8923** transaction on the shared-cache the argument Btree is connected to.
dana58f26f2010-11-16 18:56:51 +00008924**
dancdc1f042010-11-18 12:11:05 +00008925** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
dana550f2d2010-08-02 10:47:05 +00008926*/
dancdc1f042010-11-18 12:11:05 +00008927int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
dana550f2d2010-08-02 10:47:05 +00008928 int rc = SQLITE_OK;
8929 if( p ){
8930 BtShared *pBt = p->pBt;
8931 sqlite3BtreeEnter(p);
8932 if( pBt->inTransaction!=TRANS_NONE ){
8933 rc = SQLITE_LOCKED;
8934 }else{
dancdc1f042010-11-18 12:11:05 +00008935 rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
dana550f2d2010-08-02 10:47:05 +00008936 }
8937 sqlite3BtreeLeave(p);
8938 }
8939 return rc;
8940}
8941#endif
8942
danielk19771d850a72004-05-31 08:26:49 +00008943/*
danielk19772372c2b2006-06-27 16:34:56 +00008944** Return non-zero if a read (or write) transaction is active.
8945*/
8946int sqlite3BtreeIsInReadTrans(Btree *p){
drh64022502009-01-09 14:11:04 +00008947 assert( p );
drhe5fe6902007-12-07 18:55:28 +00008948 assert( sqlite3_mutex_held(p->db->mutex) );
drh64022502009-01-09 14:11:04 +00008949 return p->inTrans!=TRANS_NONE;
danielk19772372c2b2006-06-27 16:34:56 +00008950}
8951
danielk197704103022009-02-03 16:51:24 +00008952int sqlite3BtreeIsInBackup(Btree *p){
8953 assert( p );
8954 assert( sqlite3_mutex_held(p->db->mutex) );
8955 return p->nBackup!=0;
8956}
8957
danielk19772372c2b2006-06-27 16:34:56 +00008958/*
danielk1977da184232006-01-05 11:34:32 +00008959** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +00008960** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +00008961** purposes (for example, to store a high-level schema associated with
8962** the shared-btree). The btree layer manages reference counting issues.
8963**
8964** The first time this is called on a shared-btree, nBytes bytes of memory
8965** are allocated, zeroed, and returned to the caller. For each subsequent
8966** call the nBytes parameter is ignored and a pointer to the same blob
8967** of memory returned.
8968**
danielk1977171bfed2008-06-23 09:50:50 +00008969** If the nBytes parameter is 0 and the blob of memory has not yet been
8970** allocated, a null pointer is returned. If the blob has already been
8971** allocated, it is returned as normal.
8972**
danielk1977da184232006-01-05 11:34:32 +00008973** Just before the shared-btree is closed, the function passed as the
8974** xFree argument when the memory allocation was made is invoked on the
drh4fa7d7c2011-04-03 02:41:00 +00008975** blob of allocated memory. The xFree function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +00008976** on the memory, the btree layer does that.
8977*/
8978void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
8979 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +00008980 sqlite3BtreeEnter(p);
danielk1977171bfed2008-06-23 09:50:50 +00008981 if( !pBt->pSchema && nBytes ){
drhb9755982010-07-24 16:34:37 +00008982 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
danielk1977da184232006-01-05 11:34:32 +00008983 pBt->xFreeSchema = xFree;
8984 }
drh27641702007-08-22 02:56:42 +00008985 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00008986 return pBt->pSchema;
8987}
8988
danielk1977c87d34d2006-01-06 13:00:28 +00008989/*
danielk1977404ca072009-03-16 13:19:36 +00008990** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
8991** btree as the argument handle holds an exclusive lock on the
8992** sqlite_master table. Otherwise SQLITE_OK.
danielk1977c87d34d2006-01-06 13:00:28 +00008993*/
8994int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +00008995 int rc;
drhe5fe6902007-12-07 18:55:28 +00008996 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +00008997 sqlite3BtreeEnter(p);
danielk1977404ca072009-03-16 13:19:36 +00008998 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
8999 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
drh27641702007-08-22 02:56:42 +00009000 sqlite3BtreeLeave(p);
9001 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +00009002}
9003
drha154dcd2006-03-22 22:10:07 +00009004
9005#ifndef SQLITE_OMIT_SHARED_CACHE
9006/*
9007** Obtain a lock on the table whose root page is iTab. The
9008** lock is a write lock if isWritelock is true or a read lock
9009** if it is false.
9010*/
danielk1977c00da102006-01-07 13:21:04 +00009011int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00009012 int rc = SQLITE_OK;
danielk1977602b4662009-07-02 07:47:33 +00009013 assert( p->inTrans!=TRANS_NONE );
drh6a9ad3d2008-04-02 16:29:30 +00009014 if( p->sharable ){
9015 u8 lockType = READ_LOCK + isWriteLock;
9016 assert( READ_LOCK+1==WRITE_LOCK );
9017 assert( isWriteLock==0 || isWriteLock==1 );
danielk1977602b4662009-07-02 07:47:33 +00009018
drh6a9ad3d2008-04-02 16:29:30 +00009019 sqlite3BtreeEnter(p);
drhc25eabe2009-02-24 18:57:31 +00009020 rc = querySharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00009021 if( rc==SQLITE_OK ){
drhc25eabe2009-02-24 18:57:31 +00009022 rc = setSharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00009023 }
9024 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +00009025 }
9026 return rc;
9027}
drha154dcd2006-03-22 22:10:07 +00009028#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00009029
danielk1977b4e9af92007-05-01 17:49:49 +00009030#ifndef SQLITE_OMIT_INCRBLOB
9031/*
9032** Argument pCsr must be a cursor opened for writing on an
9033** INTKEY table currently pointing at a valid table entry.
9034** This function modifies the data stored as part of that entry.
danielk1977ecaecf92009-07-08 08:05:35 +00009035**
9036** Only the data content may only be modified, it is not possible to
9037** change the length of the data stored. If this function is called with
9038** parameters that attempt to write past the end of the existing data,
9039** no modifications are made and SQLITE_CORRUPT is returned.
danielk1977b4e9af92007-05-01 17:49:49 +00009040*/
danielk1977dcbb5d32007-05-04 18:36:44 +00009041int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
danielk1977c9000e62009-07-08 13:55:28 +00009042 int rc;
drh1fee73e2007-08-29 04:00:57 +00009043 assert( cursorHoldsMutex(pCsr) );
drhe5fe6902007-12-07 18:55:28 +00009044 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
drh036dbec2014-03-11 23:40:44 +00009045 assert( pCsr->curFlags & BTCF_Incrblob );
danielk19773588ceb2008-06-10 17:30:26 +00009046
danielk1977c9000e62009-07-08 13:55:28 +00009047 rc = restoreCursorPosition(pCsr);
9048 if( rc!=SQLITE_OK ){
9049 return rc;
9050 }
danielk19773588ceb2008-06-10 17:30:26 +00009051 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
9052 if( pCsr->eState!=CURSOR_VALID ){
9053 return SQLITE_ABORT;
danielk1977dcbb5d32007-05-04 18:36:44 +00009054 }
9055
dan227a1c42013-04-03 11:17:39 +00009056 /* Save the positions of all other cursors open on this table. This is
9057 ** required in case any of them are holding references to an xFetch
9058 ** version of the b-tree page modified by the accessPayload call below.
drh370c9f42013-04-03 20:04:04 +00009059 **
drh3f387402014-09-24 01:23:00 +00009060 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
drh370c9f42013-04-03 20:04:04 +00009061 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
9062 ** saveAllCursors can only return SQLITE_OK.
dan227a1c42013-04-03 11:17:39 +00009063 */
drh370c9f42013-04-03 20:04:04 +00009064 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
9065 assert( rc==SQLITE_OK );
dan227a1c42013-04-03 11:17:39 +00009066
danielk1977c9000e62009-07-08 13:55:28 +00009067 /* Check some assumptions:
danielk1977dcbb5d32007-05-04 18:36:44 +00009068 ** (a) the cursor is open for writing,
danielk1977c9000e62009-07-08 13:55:28 +00009069 ** (b) there is a read/write transaction open,
9070 ** (c) the connection holds a write-lock on the table (if required),
9071 ** (d) there are no conflicting read-locks, and
9072 ** (e) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00009073 */
drh036dbec2014-03-11 23:40:44 +00009074 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
danielk19774f029602009-07-08 18:45:37 +00009075 return SQLITE_READONLY;
9076 }
drhc9166342012-01-05 23:32:06 +00009077 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
9078 && pCsr->pBt->inTransaction==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +00009079 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
9080 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
danielk1977c9000e62009-07-08 13:55:28 +00009081 assert( pCsr->apPage[pCsr->iPage]->intKey );
danielk1977b4e9af92007-05-01 17:49:49 +00009082
drhfb192682009-07-11 18:26:28 +00009083 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00009084}
danielk19772dec9702007-05-02 16:48:37 +00009085
9086/*
dan5a500af2014-03-11 20:33:04 +00009087** Mark this cursor as an incremental blob cursor.
danielk19772dec9702007-05-02 16:48:37 +00009088*/
dan5a500af2014-03-11 20:33:04 +00009089void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
drh036dbec2014-03-11 23:40:44 +00009090 pCur->curFlags |= BTCF_Incrblob;
danielk19772dec9702007-05-02 16:48:37 +00009091}
danielk1977b4e9af92007-05-01 17:49:49 +00009092#endif
dane04dc882010-04-20 18:53:15 +00009093
9094/*
9095** Set both the "read version" (single byte at byte offset 18) and
9096** "write version" (single byte at byte offset 19) fields in the database
9097** header to iVersion.
9098*/
9099int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
9100 BtShared *pBt = pBtree->pBt;
9101 int rc; /* Return code */
9102
dane04dc882010-04-20 18:53:15 +00009103 assert( iVersion==1 || iVersion==2 );
9104
danb9780022010-04-21 18:37:57 +00009105 /* If setting the version fields to 1, do not automatically open the
9106 ** WAL connection, even if the version fields are currently set to 2.
9107 */
drhc9166342012-01-05 23:32:06 +00009108 pBt->btsFlags &= ~BTS_NO_WAL;
9109 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
danb9780022010-04-21 18:37:57 +00009110
9111 rc = sqlite3BtreeBeginTrans(pBtree, 0);
dane04dc882010-04-20 18:53:15 +00009112 if( rc==SQLITE_OK ){
9113 u8 *aData = pBt->pPage1->aData;
danb9780022010-04-21 18:37:57 +00009114 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
danede6eb82010-04-22 06:27:04 +00009115 rc = sqlite3BtreeBeginTrans(pBtree, 2);
danb9780022010-04-21 18:37:57 +00009116 if( rc==SQLITE_OK ){
9117 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
9118 if( rc==SQLITE_OK ){
9119 aData[18] = (u8)iVersion;
9120 aData[19] = (u8)iVersion;
9121 }
9122 }
9123 }
dane04dc882010-04-20 18:53:15 +00009124 }
9125
drhc9166342012-01-05 23:32:06 +00009126 pBt->btsFlags &= ~BTS_NO_WAL;
dane04dc882010-04-20 18:53:15 +00009127 return rc;
9128}
dan428c2182012-08-06 18:50:11 +00009129
9130/*
9131** set the mask of hint flags for cursor pCsr. Currently the only valid
9132** values are 0 and BTREE_BULKLOAD.
9133*/
9134void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
9135 assert( mask==BTREE_BULKLOAD || mask==0 );
9136 pCsr->hints = mask;
9137}
drh781597f2014-05-21 08:21:07 +00009138
9139/*
9140** Return true if the given Btree is read-only.
9141*/
9142int sqlite3BtreeIsReadonly(Btree *p){
9143 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
9144}
drhdef68892014-11-04 12:11:23 +00009145
9146/*
9147** Return the size of the header added to each page by this module.
9148*/
drh37c057b2014-12-30 00:57:29 +00009149int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }