blob: 522e945ac2a7f66fb2b46c3bf66e1446a060598c [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){
drh036dbec2014-03-11 23:40:44 +0000490 if( (p->curFlags & BTCF_Incrblob)!=0 && (isClearTable || p->info.nKey==iRow) ){
danielk197796d48e92009-06-29 06:00:37 +0000491 p->eState = CURSOR_INVALID;
492 }
493 }
494}
495
danielk197792d4d7a2007-05-04 12:05:56 +0000496#else
dan5a500af2014-03-11 20:33:04 +0000497 /* Stub function when INCRBLOB is omitted */
drheeb844a2009-08-08 18:01:07 +0000498 #define invalidateIncrblobCursors(x,y,z)
drh0ee3dbe2009-10-16 15:05:18 +0000499#endif /* SQLITE_OMIT_INCRBLOB */
danielk197792d4d7a2007-05-04 12:05:56 +0000500
drh980b1a72006-08-16 16:42:48 +0000501/*
danielk1977bea2a942009-01-20 17:06:27 +0000502** Set bit pgno of the BtShared.pHasContent bitvec. This is called
503** when a page that previously contained data becomes a free-list leaf
504** page.
505**
506** The BtShared.pHasContent bitvec exists to work around an obscure
507** bug caused by the interaction of two useful IO optimizations surrounding
508** free-list leaf pages:
509**
510** 1) When all data is deleted from a page and the page becomes
511** a free-list leaf page, the page is not written to the database
512** (as free-list leaf pages contain no meaningful data). Sometimes
513** such a page is not even journalled (as it will not be modified,
514** why bother journalling it?).
515**
516** 2) When a free-list leaf page is reused, its content is not read
517** from the database or written to the journal file (why should it
518** be, if it is not at all meaningful?).
519**
520** By themselves, these optimizations work fine and provide a handy
521** performance boost to bulk delete or insert operations. However, if
522** a page is moved to the free-list and then reused within the same
523** transaction, a problem comes up. If the page is not journalled when
524** it is moved to the free-list and it is also not journalled when it
525** is extracted from the free-list and reused, then the original data
526** may be lost. In the event of a rollback, it may not be possible
527** to restore the database to its original configuration.
528**
529** The solution is the BtShared.pHasContent bitvec. Whenever a page is
530** moved to become a free-list leaf page, the corresponding bit is
531** set in the bitvec. Whenever a leaf page is extracted from the free-list,
drh0ee3dbe2009-10-16 15:05:18 +0000532** optimization 2 above is omitted if the corresponding bit is already
danielk1977bea2a942009-01-20 17:06:27 +0000533** set in BtShared.pHasContent. The contents of the bitvec are cleared
534** at the end of every transaction.
535*/
536static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
537 int rc = SQLITE_OK;
538 if( !pBt->pHasContent ){
drhdd3cd972010-03-27 17:12:36 +0000539 assert( pgno<=pBt->nPage );
540 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
drh4c301aa2009-07-15 17:25:45 +0000541 if( !pBt->pHasContent ){
542 rc = SQLITE_NOMEM;
danielk1977bea2a942009-01-20 17:06:27 +0000543 }
544 }
545 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
546 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
547 }
548 return rc;
549}
550
551/*
552** Query the BtShared.pHasContent vector.
553**
554** This function is called when a free-list leaf page is removed from the
555** free-list for reuse. It returns false if it is safe to retrieve the
556** page from the pager layer with the 'no-content' flag set. True otherwise.
557*/
558static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
559 Bitvec *p = pBt->pHasContent;
560 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
561}
562
563/*
564** Clear (destroy) the BtShared.pHasContent bitvec. This should be
565** invoked at the conclusion of each write-transaction.
566*/
567static void btreeClearHasContent(BtShared *pBt){
568 sqlite3BitvecDestroy(pBt->pHasContent);
569 pBt->pHasContent = 0;
570}
571
572/*
drh138eeeb2013-03-27 03:15:23 +0000573** Release all of the apPage[] pages for a cursor.
574*/
575static void btreeReleaseAllCursorPages(BtCursor *pCur){
576 int i;
577 for(i=0; i<=pCur->iPage; i++){
578 releasePage(pCur->apPage[i]);
579 pCur->apPage[i] = 0;
580 }
581 pCur->iPage = -1;
582}
583
584
585/*
drh980b1a72006-08-16 16:42:48 +0000586** Save the current cursor position in the variables BtCursor.nKey
587** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
drhea8ffdf2009-07-22 00:35:23 +0000588**
589** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
590** prior to calling this routine.
drh980b1a72006-08-16 16:42:48 +0000591*/
592static int saveCursorPosition(BtCursor *pCur){
593 int rc;
594
595 assert( CURSOR_VALID==pCur->eState );
596 assert( 0==pCur->pKey );
drh1fee73e2007-08-29 04:00:57 +0000597 assert( cursorHoldsMutex(pCur) );
drh980b1a72006-08-16 16:42:48 +0000598
599 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
drhea8ffdf2009-07-22 00:35:23 +0000600 assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
drh980b1a72006-08-16 16:42:48 +0000601
602 /* If this is an intKey table, then the above call to BtreeKeySize()
603 ** stores the integer key in pCur->nKey. In this case this value is
604 ** all that is required. Otherwise, if pCur is not open on an intKey
605 ** table, then malloc space for and store the pCur->nKey bytes of key
606 ** data.
607 */
drh4c301aa2009-07-15 17:25:45 +0000608 if( 0==pCur->apPage[0]->intKey ){
drhda4ca9d2014-09-09 17:27:35 +0000609 void *pKey = sqlite3Malloc( pCur->nKey );
drh980b1a72006-08-16 16:42:48 +0000610 if( pKey ){
drhf49661a2008-12-10 16:45:50 +0000611 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
drh980b1a72006-08-16 16:42:48 +0000612 if( rc==SQLITE_OK ){
613 pCur->pKey = pKey;
614 }else{
drh17435752007-08-16 04:30:38 +0000615 sqlite3_free(pKey);
drh980b1a72006-08-16 16:42:48 +0000616 }
617 }else{
618 rc = SQLITE_NOMEM;
619 }
620 }
danielk197771d5d2c2008-09-29 11:49:47 +0000621 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
drh980b1a72006-08-16 16:42:48 +0000622
623 if( rc==SQLITE_OK ){
drh138eeeb2013-03-27 03:15:23 +0000624 btreeReleaseAllCursorPages(pCur);
drh980b1a72006-08-16 16:42:48 +0000625 pCur->eState = CURSOR_REQUIRESEEK;
626 }
627
danielk197792d4d7a2007-05-04 12:05:56 +0000628 invalidateOverflowCache(pCur);
drh980b1a72006-08-16 16:42:48 +0000629 return rc;
630}
631
drh637f3d82014-08-22 22:26:07 +0000632/* Forward reference */
633static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
634
drh980b1a72006-08-16 16:42:48 +0000635/*
drh0ee3dbe2009-10-16 15:05:18 +0000636** Save the positions of all cursors (except pExcept) that are open on
drh637f3d82014-08-22 22:26:07 +0000637** the table with root-page iRoot. "Saving the cursor position" means that
638** the location in the btree is remembered in such a way that it can be
639** moved back to the same spot after the btree has been modified. This
640** routine is called just before cursor pExcept is used to modify the
641** table, for example in BtreeDelete() or BtreeInsert().
642**
643** Implementation note: This routine merely checks to see if any cursors
644** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
645** event that cursors are in need to being saved.
drh980b1a72006-08-16 16:42:48 +0000646*/
647static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
drh3bdffdd2014-08-23 19:08:09 +0000648 BtCursor *p;
drh1fee73e2007-08-29 04:00:57 +0000649 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +0000650 assert( pExcept==0 || pExcept->pBt==pBt );
drh980b1a72006-08-16 16:42:48 +0000651 for(p=pBt->pCursor; p; p=p->pNext){
drh637f3d82014-08-22 22:26:07 +0000652 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
653 }
654 return p ? saveCursorsOnList(p, iRoot, pExcept) : SQLITE_OK;
655}
656
657/* This helper routine to saveAllCursors does the actual work of saving
658** the cursors if and when a cursor is found that actually requires saving.
659** The common case is that no cursors need to be saved, so this routine is
660** broken out from its caller to avoid unnecessary stack pointer movement.
661*/
662static int SQLITE_NOINLINE saveCursorsOnList(
663 BtCursor *p, /* The first cursor that needs saving */
664 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
665 BtCursor *pExcept /* Do not save this cursor */
666){
667 do{
drh138eeeb2013-03-27 03:15:23 +0000668 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
669 if( p->eState==CURSOR_VALID ){
670 int rc = saveCursorPosition(p);
671 if( SQLITE_OK!=rc ){
672 return rc;
673 }
674 }else{
675 testcase( p->iPage>0 );
676 btreeReleaseAllCursorPages(p);
drh980b1a72006-08-16 16:42:48 +0000677 }
678 }
drh637f3d82014-08-22 22:26:07 +0000679 p = p->pNext;
680 }while( p );
drh980b1a72006-08-16 16:42:48 +0000681 return SQLITE_OK;
682}
683
684/*
drhbf700f32007-03-31 02:36:44 +0000685** Clear the current cursor position.
686*/
danielk1977be51a652008-10-08 17:58:48 +0000687void sqlite3BtreeClearCursor(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +0000688 assert( cursorHoldsMutex(pCur) );
drh17435752007-08-16 04:30:38 +0000689 sqlite3_free(pCur->pKey);
drhbf700f32007-03-31 02:36:44 +0000690 pCur->pKey = 0;
691 pCur->eState = CURSOR_INVALID;
692}
693
694/*
danielk19773509a652009-07-06 18:56:13 +0000695** In this version of BtreeMoveto, pKey is a packed index record
696** such as is generated by the OP_MakeRecord opcode. Unpack the
697** record and then call BtreeMovetoUnpacked() to do the work.
698*/
699static int btreeMoveto(
700 BtCursor *pCur, /* Cursor open on the btree to be searched */
701 const void *pKey, /* Packed key if the btree is an index */
702 i64 nKey, /* Integer key for tables. Size of pKey for indices */
703 int bias, /* Bias search to the high end */
704 int *pRes /* Write search results here */
705){
706 int rc; /* Status code */
707 UnpackedRecord *pIdxKey; /* Unpacked index key */
drhb4139222013-11-06 14:36:08 +0000708 char aSpace[200]; /* Temp space for pIdxKey - to avoid a malloc */
dan03e9cfc2011-09-05 14:20:27 +0000709 char *pFree = 0;
danielk19773509a652009-07-06 18:56:13 +0000710
711 if( pKey ){
712 assert( nKey==(i64)(int)nKey );
dan03e9cfc2011-09-05 14:20:27 +0000713 pIdxKey = sqlite3VdbeAllocUnpackedRecord(
714 pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
715 );
danielk19773509a652009-07-06 18:56:13 +0000716 if( pIdxKey==0 ) return SQLITE_NOMEM;
mistachkin0fe5f952011-09-14 18:19:08 +0000717 sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
drh094b7582013-11-30 12:49:28 +0000718 if( pIdxKey->nField==0 ){
719 sqlite3DbFree(pCur->pKeyInfo->db, pFree);
720 return SQLITE_CORRUPT_BKPT;
721 }
danielk19773509a652009-07-06 18:56:13 +0000722 }else{
723 pIdxKey = 0;
724 }
725 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
dan42acb3e2011-09-05 20:16:38 +0000726 if( pFree ){
dan03e9cfc2011-09-05 14:20:27 +0000727 sqlite3DbFree(pCur->pKeyInfo->db, pFree);
danielk19773509a652009-07-06 18:56:13 +0000728 }
729 return rc;
730}
731
732/*
drh980b1a72006-08-16 16:42:48 +0000733** Restore the cursor to the position it was in (or as close to as possible)
734** when saveCursorPosition() was called. Note that this call deletes the
735** saved position info stored by saveCursorPosition(), so there can be
drha3460582008-07-11 21:02:53 +0000736** at most one effective restoreCursorPosition() call after each
drh980b1a72006-08-16 16:42:48 +0000737** saveCursorPosition().
drh980b1a72006-08-16 16:42:48 +0000738*/
danielk197730548662009-07-09 05:07:37 +0000739static int btreeRestoreCursorPosition(BtCursor *pCur){
drhbf700f32007-03-31 02:36:44 +0000740 int rc;
drh1fee73e2007-08-29 04:00:57 +0000741 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +0000742 assert( pCur->eState>=CURSOR_REQUIRESEEK );
743 if( pCur->eState==CURSOR_FAULT ){
drh4c301aa2009-07-15 17:25:45 +0000744 return pCur->skipNext;
drhfb982642007-08-30 01:19:59 +0000745 }
drh980b1a72006-08-16 16:42:48 +0000746 pCur->eState = CURSOR_INVALID;
drh4c301aa2009-07-15 17:25:45 +0000747 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
drh980b1a72006-08-16 16:42:48 +0000748 if( rc==SQLITE_OK ){
drh17435752007-08-16 04:30:38 +0000749 sqlite3_free(pCur->pKey);
drh980b1a72006-08-16 16:42:48 +0000750 pCur->pKey = 0;
drhbf700f32007-03-31 02:36:44 +0000751 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
drh9b47ee32013-08-20 03:13:51 +0000752 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
753 pCur->eState = CURSOR_SKIPNEXT;
754 }
drh980b1a72006-08-16 16:42:48 +0000755 }
756 return rc;
757}
758
drha3460582008-07-11 21:02:53 +0000759#define restoreCursorPosition(p) \
drhfb982642007-08-30 01:19:59 +0000760 (p->eState>=CURSOR_REQUIRESEEK ? \
danielk197730548662009-07-09 05:07:37 +0000761 btreeRestoreCursorPosition(p) : \
drh16a9b832007-05-05 18:39:25 +0000762 SQLITE_OK)
drh980b1a72006-08-16 16:42:48 +0000763
drha3460582008-07-11 21:02:53 +0000764/*
drh6848dad2014-08-22 23:33:03 +0000765** Determine whether or not a cursor has moved from the position where
766** it was last placed, or has been invalidated for any other reason.
767** Cursors can move when the row they are pointing at is deleted out
768** from under them, for example. Cursor might also move if a btree
769** is rebalanced.
drha3460582008-07-11 21:02:53 +0000770**
drh6848dad2014-08-22 23:33:03 +0000771** Calling this routine with a NULL cursor pointer returns false.
drh86dd3712014-03-25 11:00:21 +0000772**
drh6848dad2014-08-22 23:33:03 +0000773** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
774** back to where it ought to be if this routine returns true.
drha3460582008-07-11 21:02:53 +0000775*/
drh6848dad2014-08-22 23:33:03 +0000776int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
777 return pCur && pCur->eState!=CURSOR_VALID;
778}
779
780/*
781** This routine restores a cursor back to its original position after it
782** has been moved by some outside activity (such as a btree rebalance or
783** a row having been deleted out from under the cursor).
784**
785** On success, the *pDifferentRow parameter is false if the cursor is left
786** pointing at exactly the same row. *pDifferntRow is the row the cursor
787** was pointing to has been deleted, forcing the cursor to point to some
788** nearby row.
789**
790** This routine should only be called for a cursor that just returned
791** TRUE from sqlite3BtreeCursorHasMoved().
792*/
793int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
drha3460582008-07-11 21:02:53 +0000794 int rc;
795
drh6848dad2014-08-22 23:33:03 +0000796 assert( pCur!=0 );
797 assert( pCur->eState!=CURSOR_VALID );
drha3460582008-07-11 21:02:53 +0000798 rc = restoreCursorPosition(pCur);
799 if( rc ){
drh6848dad2014-08-22 23:33:03 +0000800 *pDifferentRow = 1;
drha3460582008-07-11 21:02:53 +0000801 return rc;
802 }
drh9b47ee32013-08-20 03:13:51 +0000803 if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
drh6848dad2014-08-22 23:33:03 +0000804 *pDifferentRow = 1;
drha3460582008-07-11 21:02:53 +0000805 }else{
drh6848dad2014-08-22 23:33:03 +0000806 *pDifferentRow = 0;
drha3460582008-07-11 21:02:53 +0000807 }
808 return SQLITE_OK;
809}
810
danielk1977599fcba2004-11-08 07:13:13 +0000811#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977afcdd022004-10-31 16:25:42 +0000812/*
drha3152892007-05-05 11:48:52 +0000813** Given a page number of a regular database page, return the page
814** number for the pointer-map page that contains the entry for the
815** input page number.
drh5f77b2e2010-08-21 15:09:37 +0000816**
817** Return 0 (not a valid page) for pgno==1 since there is
818** no pointer map associated with page 1. The integrity_check logic
819** requires that ptrmapPageno(*,1)!=1.
danielk1977afcdd022004-10-31 16:25:42 +0000820*/
danielk1977266664d2006-02-10 08:24:21 +0000821static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
danielk197789d40042008-11-17 14:20:56 +0000822 int nPagesPerMapPage;
823 Pgno iPtrMap, ret;
drh1fee73e2007-08-29 04:00:57 +0000824 assert( sqlite3_mutex_held(pBt->mutex) );
drh5f77b2e2010-08-21 15:09:37 +0000825 if( pgno<2 ) return 0;
drhd677b3d2007-08-20 22:48:41 +0000826 nPagesPerMapPage = (pBt->usableSize/5)+1;
827 iPtrMap = (pgno-2)/nPagesPerMapPage;
828 ret = (iPtrMap*nPagesPerMapPage) + 2;
danielk1977266664d2006-02-10 08:24:21 +0000829 if( ret==PENDING_BYTE_PAGE(pBt) ){
830 ret++;
831 }
832 return ret;
833}
danielk1977a19df672004-11-03 11:37:07 +0000834
danielk1977afcdd022004-10-31 16:25:42 +0000835/*
danielk1977afcdd022004-10-31 16:25:42 +0000836** Write an entry into the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000837**
838** This routine updates the pointer map entry for page number 'key'
839** so that it maps to type 'eType' and parent page number 'pgno'.
drh98add2e2009-07-20 17:11:49 +0000840**
841** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
842** a no-op. If an error occurs, the appropriate error code is written
843** into *pRC.
danielk1977afcdd022004-10-31 16:25:42 +0000844*/
drh98add2e2009-07-20 17:11:49 +0000845static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
danielk19773b8a05f2007-03-19 17:44:26 +0000846 DbPage *pDbPage; /* The pointer map page */
847 u8 *pPtrmap; /* The pointer map data */
848 Pgno iPtrmap; /* The pointer map page number */
849 int offset; /* Offset in pointer map page */
drh98add2e2009-07-20 17:11:49 +0000850 int rc; /* Return code from subfunctions */
851
852 if( *pRC ) return;
danielk1977afcdd022004-10-31 16:25:42 +0000853
drh1fee73e2007-08-29 04:00:57 +0000854 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977266664d2006-02-10 08:24:21 +0000855 /* The master-journal page number must never be used as a pointer map page */
856 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
857
danielk1977ac11ee62005-01-15 12:45:51 +0000858 assert( pBt->autoVacuum );
danielk1977fdb7cdb2005-01-17 02:12:18 +0000859 if( key==0 ){
drh98add2e2009-07-20 17:11:49 +0000860 *pRC = SQLITE_CORRUPT_BKPT;
861 return;
danielk1977fdb7cdb2005-01-17 02:12:18 +0000862 }
danielk1977266664d2006-02-10 08:24:21 +0000863 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000864 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977687566d2004-11-02 12:56:41 +0000865 if( rc!=SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +0000866 *pRC = rc;
867 return;
danielk1977afcdd022004-10-31 16:25:42 +0000868 }
danielk19778c666b12008-07-18 09:34:57 +0000869 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drhacfc72b2009-06-05 18:44:15 +0000870 if( offset<0 ){
drh98add2e2009-07-20 17:11:49 +0000871 *pRC = SQLITE_CORRUPT_BKPT;
drh4925a552009-07-07 11:39:58 +0000872 goto ptrmap_exit;
drhacfc72b2009-06-05 18:44:15 +0000873 }
drhfc243732011-05-17 15:21:56 +0000874 assert( offset <= (int)pBt->usableSize-5 );
danielk19773b8a05f2007-03-19 17:44:26 +0000875 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000876
drh615ae552005-01-16 23:21:00 +0000877 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
878 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
drh98add2e2009-07-20 17:11:49 +0000879 *pRC= rc = sqlite3PagerWrite(pDbPage);
danielk19775558a8a2005-01-17 07:53:44 +0000880 if( rc==SQLITE_OK ){
881 pPtrmap[offset] = eType;
882 put4byte(&pPtrmap[offset+1], parent);
danielk1977afcdd022004-10-31 16:25:42 +0000883 }
danielk1977afcdd022004-10-31 16:25:42 +0000884 }
885
drh4925a552009-07-07 11:39:58 +0000886ptrmap_exit:
danielk19773b8a05f2007-03-19 17:44:26 +0000887 sqlite3PagerUnref(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000888}
889
890/*
891** Read an entry from the pointer map.
danielk1977687566d2004-11-02 12:56:41 +0000892**
893** This routine retrieves the pointer map entry for page 'key', writing
894** the type and parent page number to *pEType and *pPgno respectively.
895** An error code is returned if something goes wrong, otherwise SQLITE_OK.
danielk1977afcdd022004-10-31 16:25:42 +0000896*/
danielk1977aef0bf62005-12-30 16:28:01 +0000897static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
danielk19773b8a05f2007-03-19 17:44:26 +0000898 DbPage *pDbPage; /* The pointer map page */
danielk1977afcdd022004-10-31 16:25:42 +0000899 int iPtrmap; /* Pointer map page index */
900 u8 *pPtrmap; /* Pointer map page data */
901 int offset; /* Offset of entry in pointer map */
902 int rc;
903
drh1fee73e2007-08-29 04:00:57 +0000904 assert( sqlite3_mutex_held(pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000905
danielk1977266664d2006-02-10 08:24:21 +0000906 iPtrmap = PTRMAP_PAGENO(pBt, key);
danielk19773b8a05f2007-03-19 17:44:26 +0000907 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000908 if( rc!=0 ){
909 return rc;
910 }
danielk19773b8a05f2007-03-19 17:44:26 +0000911 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
danielk1977afcdd022004-10-31 16:25:42 +0000912
danielk19778c666b12008-07-18 09:34:57 +0000913 offset = PTRMAP_PTROFFSET(iPtrmap, key);
drhfc243732011-05-17 15:21:56 +0000914 if( offset<0 ){
915 sqlite3PagerUnref(pDbPage);
916 return SQLITE_CORRUPT_BKPT;
917 }
918 assert( offset <= (int)pBt->usableSize-5 );
drh43617e92006-03-06 20:55:46 +0000919 assert( pEType!=0 );
920 *pEType = pPtrmap[offset];
danielk1977687566d2004-11-02 12:56:41 +0000921 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
danielk1977afcdd022004-10-31 16:25:42 +0000922
danielk19773b8a05f2007-03-19 17:44:26 +0000923 sqlite3PagerUnref(pDbPage);
drh49285702005-09-17 15:20:26 +0000924 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
danielk1977afcdd022004-10-31 16:25:42 +0000925 return SQLITE_OK;
926}
927
danielk197785d90ca2008-07-19 14:25:15 +0000928#else /* if defined SQLITE_OMIT_AUTOVACUUM */
drh98add2e2009-07-20 17:11:49 +0000929 #define ptrmapPut(w,x,y,z,rc)
danielk197785d90ca2008-07-19 14:25:15 +0000930 #define ptrmapGet(w,x,y,z) SQLITE_OK
drh98add2e2009-07-20 17:11:49 +0000931 #define ptrmapPutOvflPtr(x, y, rc)
danielk197785d90ca2008-07-19 14:25:15 +0000932#endif
danielk1977afcdd022004-10-31 16:25:42 +0000933
drh0d316a42002-08-11 20:10:47 +0000934/*
drh271efa52004-05-30 19:19:05 +0000935** Given a btree page and a cell index (0 means the first cell on
936** the page, 1 means the second cell, and so forth) return a pointer
937** to the cell content.
938**
939** This routine works only for pages that do not contain overflow cells.
drh3aac2dd2004-04-26 14:10:20 +0000940*/
drh1688c862008-07-18 02:44:17 +0000941#define findCell(P,I) \
drh3def2352011-11-11 00:27:15 +0000942 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
drh68f2a572011-06-03 17:50:49 +0000943#define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
944
drh43605152004-05-29 21:46:49 +0000945
946/*
drh93a960a2008-07-10 00:32:42 +0000947** This a more complex version of findCell() that works for
drh0a45c272009-07-08 01:49:11 +0000948** pages that do contain overflow cells.
drh43605152004-05-29 21:46:49 +0000949*/
950static u8 *findOverflowCell(MemPage *pPage, int iCell){
951 int i;
drh1fee73e2007-08-29 04:00:57 +0000952 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh43605152004-05-29 21:46:49 +0000953 for(i=pPage->nOverflow-1; i>=0; i--){
drh6d08b4d2004-07-20 12:45:22 +0000954 int k;
drh2cbd78b2012-02-02 19:37:18 +0000955 k = pPage->aiOvfl[i];
drh6d08b4d2004-07-20 12:45:22 +0000956 if( k<=iCell ){
957 if( k==iCell ){
drh2cbd78b2012-02-02 19:37:18 +0000958 return pPage->apOvfl[i];
drh43605152004-05-29 21:46:49 +0000959 }
960 iCell--;
961 }
962 }
danielk19771cc5ed82007-05-16 17:28:43 +0000963 return findCell(pPage, iCell);
drh43605152004-05-29 21:46:49 +0000964}
965
966/*
967** Parse a cell content block and fill in the CellInfo structure. There
danielk197730548662009-07-09 05:07:37 +0000968** are two versions of this function. btreeParseCell() takes a
969** cell index as the second argument and btreeParseCellPtr()
drh16a9b832007-05-05 18:39:25 +0000970** takes a pointer to the body of the cell as its second argument.
danielk19771cc5ed82007-05-16 17:28:43 +0000971**
972** Within this file, the parseCell() macro can be called instead of
danielk197730548662009-07-09 05:07:37 +0000973** btreeParseCellPtr(). Using some compilers, this will be faster.
drh43605152004-05-29 21:46:49 +0000974*/
danielk197730548662009-07-09 05:07:37 +0000975static void btreeParseCellPtr(
drh3aac2dd2004-04-26 14:10:20 +0000976 MemPage *pPage, /* Page containing the cell */
drh43605152004-05-29 21:46:49 +0000977 u8 *pCell, /* Pointer to the cell text. */
drh6f11bef2004-05-13 01:12:56 +0000978 CellInfo *pInfo /* Fill in this structure */
drh3aac2dd2004-04-26 14:10:20 +0000979){
drhf49661a2008-12-10 16:45:50 +0000980 u16 n; /* Number bytes in cell content header */
drh271efa52004-05-30 19:19:05 +0000981 u32 nPayload; /* Number of bytes of cell payload */
drh43605152004-05-29 21:46:49 +0000982
drh1fee73e2007-08-29 04:00:57 +0000983 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +0000984
drh43605152004-05-29 21:46:49 +0000985 pInfo->pCell = pCell;
drhab01f612004-05-22 02:55:23 +0000986 assert( pPage->leaf==0 || pPage->leaf==1 );
drh271efa52004-05-30 19:19:05 +0000987 n = pPage->childPtrSize;
988 assert( n==4-4*pPage->leaf );
drh504b6982006-01-22 21:52:56 +0000989 if( pPage->intKey ){
drh79df1f42008-07-18 00:57:33 +0000990 if( pPage->hasData ){
drh13c77bf2013-08-21 15:52:22 +0000991 assert( n==0 );
992 n = getVarint32(pCell, nPayload);
drh79df1f42008-07-18 00:57:33 +0000993 }else{
994 nPayload = 0;
995 }
drh1bd10f82008-12-10 21:19:56 +0000996 n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
drh79df1f42008-07-18 00:57:33 +0000997 pInfo->nData = nPayload;
drh504b6982006-01-22 21:52:56 +0000998 }else{
drh79df1f42008-07-18 00:57:33 +0000999 pInfo->nData = 0;
1000 n += getVarint32(&pCell[n], nPayload);
1001 pInfo->nKey = nPayload;
drh6f11bef2004-05-13 01:12:56 +00001002 }
drh72365832007-03-06 15:53:44 +00001003 pInfo->nPayload = nPayload;
drh504b6982006-01-22 21:52:56 +00001004 pInfo->nHeader = n;
drh0a45c272009-07-08 01:49:11 +00001005 testcase( nPayload==pPage->maxLocal );
1006 testcase( nPayload==pPage->maxLocal+1 );
drh79df1f42008-07-18 00:57:33 +00001007 if( likely(nPayload<=pPage->maxLocal) ){
drh271efa52004-05-30 19:19:05 +00001008 /* This is the (easy) common case where the entire payload fits
1009 ** on the local page. No overflow is required.
1010 */
drh41692e92011-01-25 04:34:51 +00001011 if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
drhf49661a2008-12-10 16:45:50 +00001012 pInfo->nLocal = (u16)nPayload;
drh6f11bef2004-05-13 01:12:56 +00001013 pInfo->iOverflow = 0;
drh6f11bef2004-05-13 01:12:56 +00001014 }else{
drh271efa52004-05-30 19:19:05 +00001015 /* If the payload will not fit completely on the local page, we have
1016 ** to decide how much to store locally and how much to spill onto
1017 ** overflow pages. The strategy is to minimize the amount of unused
1018 ** space on overflow pages while keeping the amount of local storage
1019 ** in between minLocal and maxLocal.
1020 **
1021 ** Warning: changing the way overflow payload is distributed in any
1022 ** way will result in an incompatible file format.
1023 */
1024 int minLocal; /* Minimum amount of payload held locally */
1025 int maxLocal; /* Maximum amount of payload held locally */
1026 int surplus; /* Overflow payload available for local storage */
1027
1028 minLocal = pPage->minLocal;
1029 maxLocal = pPage->maxLocal;
1030 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
drh0a45c272009-07-08 01:49:11 +00001031 testcase( surplus==maxLocal );
1032 testcase( surplus==maxLocal+1 );
drh6f11bef2004-05-13 01:12:56 +00001033 if( surplus <= maxLocal ){
drhf49661a2008-12-10 16:45:50 +00001034 pInfo->nLocal = (u16)surplus;
drh6f11bef2004-05-13 01:12:56 +00001035 }else{
drhf49661a2008-12-10 16:45:50 +00001036 pInfo->nLocal = (u16)minLocal;
drh6f11bef2004-05-13 01:12:56 +00001037 }
drhf49661a2008-12-10 16:45:50 +00001038 pInfo->iOverflow = (u16)(pInfo->nLocal + n);
drh6f11bef2004-05-13 01:12:56 +00001039 pInfo->nSize = pInfo->iOverflow + 4;
1040 }
drh3aac2dd2004-04-26 14:10:20 +00001041}
danielk19771cc5ed82007-05-16 17:28:43 +00001042#define parseCell(pPage, iCell, pInfo) \
danielk197730548662009-07-09 05:07:37 +00001043 btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
1044static void btreeParseCell(
drh43605152004-05-29 21:46:49 +00001045 MemPage *pPage, /* Page containing the cell */
1046 int iCell, /* The cell index. First cell is 0 */
1047 CellInfo *pInfo /* Fill in this structure */
1048){
danielk19771cc5ed82007-05-16 17:28:43 +00001049 parseCell(pPage, iCell, pInfo);
drh43605152004-05-29 21:46:49 +00001050}
drh3aac2dd2004-04-26 14:10:20 +00001051
1052/*
drh43605152004-05-29 21:46:49 +00001053** Compute the total number of bytes that a Cell needs in the cell
1054** data area of the btree-page. The return number includes the cell
1055** data header and the local payload, but not any overflow page or
1056** the space used by the cell pointer.
drh3b7511c2001-05-26 13:15:44 +00001057*/
danielk1977ae5558b2009-04-29 11:31:47 +00001058static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
1059 u8 *pIter = &pCell[pPage->childPtrSize];
1060 u32 nSize;
1061
1062#ifdef SQLITE_DEBUG
1063 /* The value returned by this function should always be the same as
1064 ** the (CellInfo.nSize) value found by doing a full parse of the
1065 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1066 ** this function verifies that this invariant is not violated. */
1067 CellInfo debuginfo;
danielk197730548662009-07-09 05:07:37 +00001068 btreeParseCellPtr(pPage, pCell, &debuginfo);
danielk1977ae5558b2009-04-29 11:31:47 +00001069#endif
1070
1071 if( pPage->intKey ){
1072 u8 *pEnd;
1073 if( pPage->hasData ){
1074 pIter += getVarint32(pIter, nSize);
1075 }else{
1076 nSize = 0;
1077 }
1078
1079 /* pIter now points at the 64-bit integer key value, a variable length
1080 ** integer. The following block moves pIter to point at the first byte
1081 ** past the end of the key value. */
1082 pEnd = &pIter[9];
1083 while( (*pIter++)&0x80 && pIter<pEnd );
1084 }else{
1085 pIter += getVarint32(pIter, nSize);
1086 }
1087
drh0a45c272009-07-08 01:49:11 +00001088 testcase( nSize==pPage->maxLocal );
1089 testcase( nSize==pPage->maxLocal+1 );
danielk1977ae5558b2009-04-29 11:31:47 +00001090 if( nSize>pPage->maxLocal ){
1091 int minLocal = pPage->minLocal;
1092 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
drh0a45c272009-07-08 01:49:11 +00001093 testcase( nSize==pPage->maxLocal );
1094 testcase( nSize==pPage->maxLocal+1 );
danielk1977ae5558b2009-04-29 11:31:47 +00001095 if( nSize>pPage->maxLocal ){
1096 nSize = minLocal;
1097 }
1098 nSize += 4;
1099 }
shane75ac1de2009-06-09 18:58:52 +00001100 nSize += (u32)(pIter - pCell);
danielk1977ae5558b2009-04-29 11:31:47 +00001101
1102 /* The minimum size of any cell is 4 bytes. */
1103 if( nSize<4 ){
1104 nSize = 4;
1105 }
1106
1107 assert( nSize==debuginfo.nSize );
shane60a4b532009-05-06 18:57:09 +00001108 return (u16)nSize;
danielk1977ae5558b2009-04-29 11:31:47 +00001109}
drh0ee3dbe2009-10-16 15:05:18 +00001110
1111#ifdef SQLITE_DEBUG
1112/* This variation on cellSizePtr() is used inside of assert() statements
1113** only. */
drha9121e42008-02-19 14:59:35 +00001114static u16 cellSize(MemPage *pPage, int iCell){
danielk1977ae5558b2009-04-29 11:31:47 +00001115 return cellSizePtr(pPage, findCell(pPage, iCell));
drh43605152004-05-29 21:46:49 +00001116}
danielk1977bc6ada42004-06-30 08:20:16 +00001117#endif
drh3b7511c2001-05-26 13:15:44 +00001118
danielk197779a40da2005-01-16 08:00:01 +00001119#ifndef SQLITE_OMIT_AUTOVACUUM
drh3b7511c2001-05-26 13:15:44 +00001120/*
danielk197726836652005-01-17 01:33:13 +00001121** If the cell pCell, part of page pPage contains a pointer
danielk197779a40da2005-01-16 08:00:01 +00001122** to an overflow page, insert an entry into the pointer-map
1123** for the overflow page.
danielk1977ac11ee62005-01-15 12:45:51 +00001124*/
drh98add2e2009-07-20 17:11:49 +00001125static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
drhfa67c3c2008-07-11 02:21:40 +00001126 CellInfo info;
drh98add2e2009-07-20 17:11:49 +00001127 if( *pRC ) return;
drhfa67c3c2008-07-11 02:21:40 +00001128 assert( pCell!=0 );
danielk197730548662009-07-09 05:07:37 +00001129 btreeParseCellPtr(pPage, pCell, &info);
drhfa67c3c2008-07-11 02:21:40 +00001130 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
danielk19774dbaa892009-06-16 16:50:22 +00001131 if( info.iOverflow ){
drhfa67c3c2008-07-11 02:21:40 +00001132 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
drh98add2e2009-07-20 17:11:49 +00001133 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
danielk1977ac11ee62005-01-15 12:45:51 +00001134 }
danielk1977ac11ee62005-01-15 12:45:51 +00001135}
danielk197779a40da2005-01-16 08:00:01 +00001136#endif
1137
danielk1977ac11ee62005-01-15 12:45:51 +00001138
drhda200cc2004-05-09 11:51:38 +00001139/*
drh72f82862001-05-24 21:06:34 +00001140** Defragment the page given. All Cells are moved to the
drh3a4a2d42005-11-24 14:24:28 +00001141** end of the page and all free space is collected into one
1142** big FreeBlk that occurs in between the header and cell
drh31beae92005-11-24 14:34:36 +00001143** pointer array and the cell content area.
drh365d68f2001-05-11 11:02:46 +00001144*/
shane0af3f892008-11-12 04:55:34 +00001145static int defragmentPage(MemPage *pPage){
drh43605152004-05-29 21:46:49 +00001146 int i; /* Loop counter */
peter.d.reid60ec9142014-09-06 16:39:46 +00001147 int pc; /* Address of the i-th cell */
drh43605152004-05-29 21:46:49 +00001148 int hdr; /* Offset to the page header */
1149 int size; /* Size of a cell */
1150 int usableSize; /* Number of usable bytes on a page */
1151 int cellOffset; /* Offset to the cell pointer array */
drh281b21d2008-08-22 12:57:08 +00001152 int cbrk; /* Offset to the cell content area */
drh43605152004-05-29 21:46:49 +00001153 int nCell; /* Number of cells on the page */
drh2e38c322004-09-03 18:38:44 +00001154 unsigned char *data; /* The page data */
1155 unsigned char *temp; /* Temp area for cell content */
drh17146622009-07-07 17:38:38 +00001156 int iCellFirst; /* First allowable cell index */
1157 int iCellLast; /* Last possible cell index */
1158
drh2af926b2001-05-15 00:39:25 +00001159
danielk19773b8a05f2007-03-19 17:44:26 +00001160 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001161 assert( pPage->pBt!=0 );
drh90f5ecb2004-07-22 01:19:35 +00001162 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
drh43605152004-05-29 21:46:49 +00001163 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00001164 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh26b79942007-11-28 16:19:56 +00001165 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
drh43605152004-05-29 21:46:49 +00001166 data = pPage->aData;
drh9e572e62004-04-23 23:43:10 +00001167 hdr = pPage->hdrOffset;
drh43605152004-05-29 21:46:49 +00001168 cellOffset = pPage->cellOffset;
1169 nCell = pPage->nCell;
1170 assert( nCell==get2byte(&data[hdr+3]) );
1171 usableSize = pPage->pBt->usableSize;
drh281b21d2008-08-22 12:57:08 +00001172 cbrk = get2byte(&data[hdr+5]);
1173 memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
1174 cbrk = usableSize;
drh17146622009-07-07 17:38:38 +00001175 iCellFirst = cellOffset + 2*nCell;
1176 iCellLast = usableSize - 4;
drh43605152004-05-29 21:46:49 +00001177 for(i=0; i<nCell; i++){
1178 u8 *pAddr; /* The i-th cell pointer */
1179 pAddr = &data[cellOffset + i*2];
1180 pc = get2byte(pAddr);
drh0a45c272009-07-08 01:49:11 +00001181 testcase( pc==iCellFirst );
1182 testcase( pc==iCellLast );
drh17146622009-07-07 17:38:38 +00001183#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
danielk197730548662009-07-09 05:07:37 +00001184 /* These conditions have already been verified in btreeInitPage()
drh17146622009-07-07 17:38:38 +00001185 ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
1186 */
1187 if( pc<iCellFirst || pc>iCellLast ){
shane0af3f892008-11-12 04:55:34 +00001188 return SQLITE_CORRUPT_BKPT;
1189 }
drh17146622009-07-07 17:38:38 +00001190#endif
1191 assert( pc>=iCellFirst && pc<=iCellLast );
drh43605152004-05-29 21:46:49 +00001192 size = cellSizePtr(pPage, &temp[pc]);
drh281b21d2008-08-22 12:57:08 +00001193 cbrk -= size;
drh17146622009-07-07 17:38:38 +00001194#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
1195 if( cbrk<iCellFirst ){
shane0af3f892008-11-12 04:55:34 +00001196 return SQLITE_CORRUPT_BKPT;
1197 }
drh17146622009-07-07 17:38:38 +00001198#else
1199 if( cbrk<iCellFirst || pc+size>usableSize ){
1200 return SQLITE_CORRUPT_BKPT;
1201 }
1202#endif
drh7157e1d2009-07-09 13:25:32 +00001203 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
drh0a45c272009-07-08 01:49:11 +00001204 testcase( cbrk+size==usableSize );
drh0a45c272009-07-08 01:49:11 +00001205 testcase( pc+size==usableSize );
drh281b21d2008-08-22 12:57:08 +00001206 memcpy(&data[cbrk], &temp[pc], size);
1207 put2byte(pAddr, cbrk);
drh2af926b2001-05-15 00:39:25 +00001208 }
drh17146622009-07-07 17:38:38 +00001209 assert( cbrk>=iCellFirst );
drh281b21d2008-08-22 12:57:08 +00001210 put2byte(&data[hdr+5], cbrk);
drh43605152004-05-29 21:46:49 +00001211 data[hdr+1] = 0;
1212 data[hdr+2] = 0;
1213 data[hdr+7] = 0;
drh17146622009-07-07 17:38:38 +00001214 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
drhc5053fb2008-11-27 02:22:10 +00001215 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh17146622009-07-07 17:38:38 +00001216 if( cbrk-iCellFirst!=pPage->nFree ){
danielk1977360e6342008-11-12 08:49:51 +00001217 return SQLITE_CORRUPT_BKPT;
1218 }
shane0af3f892008-11-12 04:55:34 +00001219 return SQLITE_OK;
drh365d68f2001-05-11 11:02:46 +00001220}
1221
drha059ad02001-04-17 20:09:11 +00001222/*
danielk19776011a752009-04-01 16:25:32 +00001223** Allocate nByte bytes of space from within the B-Tree page passed
drh0a45c272009-07-08 01:49:11 +00001224** as the first argument. Write into *pIdx the index into pPage->aData[]
1225** of the first byte of allocated space. Return either SQLITE_OK or
1226** an error code (usually SQLITE_CORRUPT).
drhbd03cae2001-06-02 02:40:57 +00001227**
drh0a45c272009-07-08 01:49:11 +00001228** The caller guarantees that there is sufficient space to make the
1229** allocation. This routine might need to defragment in order to bring
1230** all the space together, however. This routine will avoid using
1231** the first two bytes past the cell pointer area since presumably this
1232** allocation is being made in order to insert a new cell, so we will
1233** also end up needing a new cell pointer.
drh7e3b0a02001-04-28 16:52:40 +00001234*/
drh0a45c272009-07-08 01:49:11 +00001235static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
danielk19776011a752009-04-01 16:25:32 +00001236 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1237 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
drh0a45c272009-07-08 01:49:11 +00001238 int top; /* First byte of cell content area */
1239 int gap; /* First byte of gap between cell pointers and cell content */
1240 int rc; /* Integer return code */
drh00ce3942009-12-06 03:35:51 +00001241 int usableSize; /* Usable size of the page */
drh43605152004-05-29 21:46:49 +00001242
danielk19773b8a05f2007-03-19 17:44:26 +00001243 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh9e572e62004-04-23 23:43:10 +00001244 assert( pPage->pBt );
drh1fee73e2007-08-29 04:00:57 +00001245 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfa67c3c2008-07-11 02:21:40 +00001246 assert( nByte>=0 ); /* Minimum cell size is 4 */
1247 assert( pPage->nFree>=nByte );
1248 assert( pPage->nOverflow==0 );
drh00ce3942009-12-06 03:35:51 +00001249 usableSize = pPage->pBt->usableSize;
1250 assert( nByte < usableSize-8 );
drh43605152004-05-29 21:46:49 +00001251
drh0a45c272009-07-08 01:49:11 +00001252 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1253 gap = pPage->cellOffset + 2*pPage->nCell;
drh75b31dc2014-08-20 00:54:46 +00001254 assert( gap<=65536 );
1255 top = get2byte(&data[hdr+5]);
1256 if( gap>top ){
1257 if( top==0 ){
1258 top = 65536;
1259 }else{
1260 return SQLITE_CORRUPT_BKPT;
1261 }
1262 }
drh4c04f3c2014-08-20 11:56:14 +00001263
1264 /* If there is enough space between gap and top for one more cell pointer
1265 ** array entry offset, and if the freelist is not empty, then search the
1266 ** freelist looking for a free slot big enough to satisfy the request.
1267 */
drh0a45c272009-07-08 01:49:11 +00001268 testcase( gap+2==top );
1269 testcase( gap+1==top );
1270 testcase( gap==top );
drh4c04f3c2014-08-20 11:56:14 +00001271 if( gap+2<=top && (data[hdr+1] || data[hdr+2]) ){
danielk19776011a752009-04-01 16:25:32 +00001272 int pc, addr;
1273 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
drh00ce3942009-12-06 03:35:51 +00001274 int size; /* Size of the free slot */
1275 if( pc>usableSize-4 || pc<addr+4 ){
1276 return SQLITE_CORRUPT_BKPT;
1277 }
1278 size = get2byte(&data[pc+2]);
drh43605152004-05-29 21:46:49 +00001279 if( size>=nByte ){
drhf49661a2008-12-10 16:45:50 +00001280 int x = size - nByte;
drh0a45c272009-07-08 01:49:11 +00001281 testcase( x==4 );
1282 testcase( x==3 );
danielk19776011a752009-04-01 16:25:32 +00001283 if( x<4 ){
drh4c04f3c2014-08-20 11:56:14 +00001284 if( data[hdr+7]>=60 ) goto defragment_page;
danielk1977fad91942009-04-29 17:49:59 +00001285 /* Remove the slot from the free-list. Update the number of
1286 ** fragmented bytes within the page. */
drh43605152004-05-29 21:46:49 +00001287 memcpy(&data[addr], &data[pc], 2);
drh75b31dc2014-08-20 00:54:46 +00001288 data[hdr+7] += (u8)x;
drh00ce3942009-12-06 03:35:51 +00001289 }else if( size+pc > usableSize ){
1290 return SQLITE_CORRUPT_BKPT;
drh43605152004-05-29 21:46:49 +00001291 }else{
danielk1977fad91942009-04-29 17:49:59 +00001292 /* The slot remains on the free-list. Reduce its size to account
1293 ** for the portion used by the new allocation. */
drhf49661a2008-12-10 16:45:50 +00001294 put2byte(&data[pc+2], x);
drh43605152004-05-29 21:46:49 +00001295 }
drh0a45c272009-07-08 01:49:11 +00001296 *pIdx = pc + x;
1297 return SQLITE_OK;
drh43605152004-05-29 21:46:49 +00001298 }
drh9e572e62004-04-23 23:43:10 +00001299 }
1300 }
drh43605152004-05-29 21:46:49 +00001301
drh4c04f3c2014-08-20 11:56:14 +00001302 /* The request could not be fulfilled using a freelist slot. Check
1303 ** to see if defragmentation is necessary.
drh0a45c272009-07-08 01:49:11 +00001304 */
1305 testcase( gap+2+nByte==top );
1306 if( gap+2+nByte>top ){
drh4c04f3c2014-08-20 11:56:14 +00001307defragment_page:
drh90555262014-08-20 13:17:43 +00001308 testcase( pPage->nCell==0 );
drh0a45c272009-07-08 01:49:11 +00001309 rc = defragmentPage(pPage);
1310 if( rc ) return rc;
drh5d433ce2010-08-14 16:02:52 +00001311 top = get2byteNotZero(&data[hdr+5]);
drh0a45c272009-07-08 01:49:11 +00001312 assert( gap+nByte<=top );
1313 }
1314
1315
drh43605152004-05-29 21:46:49 +00001316 /* Allocate memory from the gap in between the cell pointer array
drhc314dc72009-07-21 11:52:34 +00001317 ** and the cell content area. The btreeInitPage() call has already
1318 ** validated the freelist. Given that the freelist is valid, there
1319 ** is no way that the allocation can extend off the end of the page.
1320 ** The assert() below verifies the previous sentence.
drh43605152004-05-29 21:46:49 +00001321 */
drh0a45c272009-07-08 01:49:11 +00001322 top -= nByte;
drh43605152004-05-29 21:46:49 +00001323 put2byte(&data[hdr+5], top);
drhfcd71b62011-04-05 22:08:24 +00001324 assert( top+nByte <= (int)pPage->pBt->usableSize );
drh0a45c272009-07-08 01:49:11 +00001325 *pIdx = top;
1326 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001327}
1328
1329/*
drh9e572e62004-04-23 23:43:10 +00001330** Return a section of the pPage->aData to the freelist.
drh7fb91642014-08-20 14:37:09 +00001331** The first byte of the new free block is pPage->aData[iStart]
1332** and the size of the block is iSize bytes.
drh306dc212001-05-21 13:45:10 +00001333**
drh5f5c7532014-08-20 17:56:27 +00001334** Adjacent freeblocks are coalesced.
1335**
1336** Note that even though the freeblock list was checked by btreeInitPage(),
1337** that routine will not detect overlap between cells or freeblocks. Nor
1338** does it detect cells or freeblocks that encrouch into the reserved bytes
1339** at the end of the page. So do additional corruption checks inside this
1340** routine and return SQLITE_CORRUPT if any problems are found.
drh7e3b0a02001-04-28 16:52:40 +00001341*/
drh5f5c7532014-08-20 17:56:27 +00001342static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
1343 u16 iPtr; /* Address of pointer to next freeblock */
1344 u16 iFreeBlk; /* Address of the next freeblock */
1345 u8 hdr; /* Page header size. 0 or 100 */
1346 u8 nFrag = 0; /* Reduction in fragmentation */
1347 u16 iOrigSize = iSize; /* Original value of iSize */
1348 u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
1349 u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
drh7fb91642014-08-20 14:37:09 +00001350 unsigned char *data = pPage->aData; /* Page content */
drh2af926b2001-05-15 00:39:25 +00001351
drh9e572e62004-04-23 23:43:10 +00001352 assert( pPage->pBt!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00001353 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh7fb91642014-08-20 14:37:09 +00001354 assert( iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
drh5f5c7532014-08-20 17:56:27 +00001355 assert( iEnd <= pPage->pBt->usableSize );
drh1fee73e2007-08-29 04:00:57 +00001356 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drh7fb91642014-08-20 14:37:09 +00001357 assert( iSize>=4 ); /* Minimum cell size is 4 */
drh5f5c7532014-08-20 17:56:27 +00001358 assert( iStart<=iLast );
drh9e572e62004-04-23 23:43:10 +00001359
drh5f5c7532014-08-20 17:56:27 +00001360 /* Overwrite deleted information with zeros when the secure_delete
1361 ** option is enabled */
drhc9166342012-01-05 23:32:06 +00001362 if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
drh7fb91642014-08-20 14:37:09 +00001363 memset(&data[iStart], 0, iSize);
drh5b47efa2010-02-12 18:18:39 +00001364 }
drhfcce93f2006-02-22 03:08:32 +00001365
drh5f5c7532014-08-20 17:56:27 +00001366 /* The list of freeblocks must be in ascending order. Find the
1367 ** spot on the list where iStart should be inserted.
drh0a45c272009-07-08 01:49:11 +00001368 */
drh43605152004-05-29 21:46:49 +00001369 hdr = pPage->hdrOffset;
drh7fb91642014-08-20 14:37:09 +00001370 iPtr = hdr + 1;
drh7bc4c452014-08-20 18:43:44 +00001371 if( data[iPtr+1]==0 && data[iPtr]==0 ){
1372 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
1373 }else{
1374 while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
1375 if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
1376 iPtr = iFreeBlk;
drh9e572e62004-04-23 23:43:10 +00001377 }
drh7bc4c452014-08-20 18:43:44 +00001378 if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
1379 assert( iFreeBlk>iPtr || iFreeBlk==0 );
1380
1381 /* At this point:
1382 ** iFreeBlk: First freeblock after iStart, or zero if none
1383 ** iPtr: The address of a pointer iFreeBlk
1384 **
1385 ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
1386 */
1387 if( iFreeBlk && iEnd+3>=iFreeBlk ){
1388 nFrag = iFreeBlk - iEnd;
1389 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
1390 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
1391 iSize = iEnd - iStart;
1392 iFreeBlk = get2byte(&data[iFreeBlk]);
1393 }
1394
1395 /* If iPtr is another freeblock (that is, if iPtr is not the freelist pointer
1396 ** in the page header) then check to see if iStart should be coalesced
1397 ** onto the end of iPtr.
1398 */
1399 if( iPtr>hdr+1 ){
1400 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
1401 if( iPtrEnd+3>=iStart ){
1402 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
1403 nFrag += iStart - iPtrEnd;
1404 iSize = iEnd - iPtr;
1405 iStart = iPtr;
1406 }
1407 }
1408 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
1409 data[hdr+7] -= nFrag;
drh9e572e62004-04-23 23:43:10 +00001410 }
drh7bc4c452014-08-20 18:43:44 +00001411 if( iStart==get2byte(&data[hdr+5]) ){
drh5f5c7532014-08-20 17:56:27 +00001412 /* The new freeblock is at the beginning of the cell content area,
1413 ** so just extend the cell content area rather than create another
1414 ** freelist entry */
drh7bc4c452014-08-20 18:43:44 +00001415 if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
drh5f5c7532014-08-20 17:56:27 +00001416 put2byte(&data[hdr+1], iFreeBlk);
1417 put2byte(&data[hdr+5], iEnd);
1418 }else{
1419 /* Insert the new freeblock into the freelist */
1420 put2byte(&data[iPtr], iStart);
1421 put2byte(&data[iStart], iFreeBlk);
1422 put2byte(&data[iStart+2], iSize);
drh4b70f112004-05-02 21:12:19 +00001423 }
drh5f5c7532014-08-20 17:56:27 +00001424 pPage->nFree += iOrigSize;
shanedcc50b72008-11-13 18:29:50 +00001425 return SQLITE_OK;
drh4b70f112004-05-02 21:12:19 +00001426}
1427
1428/*
drh271efa52004-05-30 19:19:05 +00001429** Decode the flags byte (the first byte of the header) for a page
1430** and initialize fields of the MemPage structure accordingly.
drh44845222008-07-17 18:39:57 +00001431**
1432** Only the following combinations are supported. Anything different
1433** indicates a corrupt database files:
1434**
1435** PTF_ZERODATA
1436** PTF_ZERODATA | PTF_LEAF
1437** PTF_LEAFDATA | PTF_INTKEY
1438** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
drh271efa52004-05-30 19:19:05 +00001439*/
drh44845222008-07-17 18:39:57 +00001440static int decodeFlags(MemPage *pPage, int flagByte){
danielk1977aef0bf62005-12-30 16:28:01 +00001441 BtShared *pBt; /* A copy of pPage->pBt */
drh271efa52004-05-30 19:19:05 +00001442
1443 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
drh1fee73e2007-08-29 04:00:57 +00001444 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhf49661a2008-12-10 16:45:50 +00001445 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
drh44845222008-07-17 18:39:57 +00001446 flagByte &= ~PTF_LEAF;
1447 pPage->childPtrSize = 4-4*pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001448 pBt = pPage->pBt;
drh44845222008-07-17 18:39:57 +00001449 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
1450 pPage->intKey = 1;
1451 pPage->hasData = pPage->leaf;
drh271efa52004-05-30 19:19:05 +00001452 pPage->maxLocal = pBt->maxLeaf;
1453 pPage->minLocal = pBt->minLeaf;
drh44845222008-07-17 18:39:57 +00001454 }else if( flagByte==PTF_ZERODATA ){
1455 pPage->intKey = 0;
1456 pPage->hasData = 0;
drh271efa52004-05-30 19:19:05 +00001457 pPage->maxLocal = pBt->maxLocal;
1458 pPage->minLocal = pBt->minLocal;
drh44845222008-07-17 18:39:57 +00001459 }else{
1460 return SQLITE_CORRUPT_BKPT;
drh271efa52004-05-30 19:19:05 +00001461 }
drhc9166342012-01-05 23:32:06 +00001462 pPage->max1bytePayload = pBt->max1bytePayload;
drh44845222008-07-17 18:39:57 +00001463 return SQLITE_OK;
drh271efa52004-05-30 19:19:05 +00001464}
1465
1466/*
drh7e3b0a02001-04-28 16:52:40 +00001467** Initialize the auxiliary information for a disk block.
drh72f82862001-05-24 21:06:34 +00001468**
1469** Return SQLITE_OK on success. If we see that the page does
drhda47d772002-12-02 04:25:19 +00001470** not contain a well-formed database page, then return
drh72f82862001-05-24 21:06:34 +00001471** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
1472** guarantee that the page is well-formed. It only shows that
1473** we failed to detect any corruption.
drh7e3b0a02001-04-28 16:52:40 +00001474*/
danielk197730548662009-07-09 05:07:37 +00001475static int btreeInitPage(MemPage *pPage){
drh2af926b2001-05-15 00:39:25 +00001476
danielk197771d5d2c2008-09-29 11:49:47 +00001477 assert( pPage->pBt!=0 );
1478 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk19773b8a05f2007-03-19 17:44:26 +00001479 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
drhbf4bca52007-09-06 22:19:14 +00001480 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
1481 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
danielk197771d5d2c2008-09-29 11:49:47 +00001482
1483 if( !pPage->isInit ){
drhf49661a2008-12-10 16:45:50 +00001484 u16 pc; /* Address of a freeblock within pPage->aData[] */
1485 u8 hdr; /* Offset to beginning of page header */
danielk197771d5d2c2008-09-29 11:49:47 +00001486 u8 *data; /* Equal to pPage->aData */
1487 BtShared *pBt; /* The main btree structure */
drhb2eced52010-08-12 02:41:12 +00001488 int usableSize; /* Amount of usable space on each page */
shaneh1df2db72010-08-18 02:28:48 +00001489 u16 cellOffset; /* Offset from start of page to first cell pointer */
drhb2eced52010-08-12 02:41:12 +00001490 int nFree; /* Number of unused bytes on the page */
1491 int top; /* First byte of the cell content area */
drh0a45c272009-07-08 01:49:11 +00001492 int iCellFirst; /* First allowable cell or freeblock offset */
1493 int iCellLast; /* Last possible cell or freeblock offset */
danielk197771d5d2c2008-09-29 11:49:47 +00001494
1495 pBt = pPage->pBt;
1496
danielk1977eaa06f62008-09-18 17:34:44 +00001497 hdr = pPage->hdrOffset;
1498 data = pPage->aData;
1499 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
drhb2eced52010-08-12 02:41:12 +00001500 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
1501 pPage->maskPage = (u16)(pBt->pageSize - 1);
danielk1977eaa06f62008-09-18 17:34:44 +00001502 pPage->nOverflow = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00001503 usableSize = pBt->usableSize;
1504 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
drh3def2352011-11-11 00:27:15 +00001505 pPage->aDataEnd = &data[usableSize];
1506 pPage->aCellIdx = &data[cellOffset];
drh5d433ce2010-08-14 16:02:52 +00001507 top = get2byteNotZero(&data[hdr+5]);
danielk1977eaa06f62008-09-18 17:34:44 +00001508 pPage->nCell = get2byte(&data[hdr+3]);
1509 if( pPage->nCell>MX_CELL(pBt) ){
1510 /* To many cells for a single page. The page must be corrupt */
1511 return SQLITE_CORRUPT_BKPT;
1512 }
drhb908d762009-07-08 16:54:40 +00001513 testcase( pPage->nCell==MX_CELL(pBt) );
drh69e931e2009-06-03 21:04:35 +00001514
shane5eff7cf2009-08-10 03:57:58 +00001515 /* A malformed database page might cause us to read past the end
drh69e931e2009-06-03 21:04:35 +00001516 ** of page when parsing a cell.
1517 **
1518 ** The following block of code checks early to see if a cell extends
1519 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
1520 ** returned if it does.
1521 */
drh0a45c272009-07-08 01:49:11 +00001522 iCellFirst = cellOffset + 2*pPage->nCell;
1523 iCellLast = usableSize - 4;
drh3b2a3fa2009-06-09 13:42:24 +00001524#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
drh69e931e2009-06-03 21:04:35 +00001525 {
drh69e931e2009-06-03 21:04:35 +00001526 int i; /* Index into the cell pointer array */
1527 int sz; /* Size of a cell */
1528
drh69e931e2009-06-03 21:04:35 +00001529 if( !pPage->leaf ) iCellLast--;
1530 for(i=0; i<pPage->nCell; i++){
1531 pc = get2byte(&data[cellOffset+i*2]);
drh0a45c272009-07-08 01:49:11 +00001532 testcase( pc==iCellFirst );
1533 testcase( pc==iCellLast );
drh69e931e2009-06-03 21:04:35 +00001534 if( pc<iCellFirst || pc>iCellLast ){
1535 return SQLITE_CORRUPT_BKPT;
1536 }
1537 sz = cellSizePtr(pPage, &data[pc]);
drh0a45c272009-07-08 01:49:11 +00001538 testcase( pc+sz==usableSize );
drh69e931e2009-06-03 21:04:35 +00001539 if( pc+sz>usableSize ){
1540 return SQLITE_CORRUPT_BKPT;
1541 }
1542 }
drh0a45c272009-07-08 01:49:11 +00001543 if( !pPage->leaf ) iCellLast++;
drh69e931e2009-06-03 21:04:35 +00001544 }
1545#endif
1546
danielk1977eaa06f62008-09-18 17:34:44 +00001547 /* Compute the total free space on the page */
1548 pc = get2byte(&data[hdr+1]);
danielk197793c829c2009-06-03 17:26:17 +00001549 nFree = data[hdr+7] + top;
danielk1977eaa06f62008-09-18 17:34:44 +00001550 while( pc>0 ){
drh1bd10f82008-12-10 21:19:56 +00001551 u16 next, size;
drh0a45c272009-07-08 01:49:11 +00001552 if( pc<iCellFirst || pc>iCellLast ){
dan4361e792009-08-14 17:01:22 +00001553 /* Start of free block is off the page */
danielk1977eaa06f62008-09-18 17:34:44 +00001554 return SQLITE_CORRUPT_BKPT;
1555 }
1556 next = get2byte(&data[pc]);
1557 size = get2byte(&data[pc+2]);
dan4361e792009-08-14 17:01:22 +00001558 if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
1559 /* Free blocks must be in ascending order. And the last byte of
drhf2f105d2012-08-20 15:53:54 +00001560 ** the free-block must lie on the database page. */
danielk1977eaa06f62008-09-18 17:34:44 +00001561 return SQLITE_CORRUPT_BKPT;
1562 }
shane85095702009-06-15 16:27:08 +00001563 nFree = nFree + size;
danielk1977eaa06f62008-09-18 17:34:44 +00001564 pc = next;
1565 }
danielk197793c829c2009-06-03 17:26:17 +00001566
1567 /* At this point, nFree contains the sum of the offset to the start
1568 ** of the cell-content area plus the number of free bytes within
1569 ** the cell-content area. If this is greater than the usable-size
1570 ** of the page, then the page must be corrupted. This check also
1571 ** serves to verify that the offset to the start of the cell-content
1572 ** area, according to the page header, lies within the page.
1573 */
1574 if( nFree>usableSize ){
drh49285702005-09-17 15:20:26 +00001575 return SQLITE_CORRUPT_BKPT;
drhee696e22004-08-30 16:52:17 +00001576 }
shane5eff7cf2009-08-10 03:57:58 +00001577 pPage->nFree = (u16)(nFree - iCellFirst);
danielk197771d5d2c2008-09-29 11:49:47 +00001578 pPage->isInit = 1;
1579 }
drh9e572e62004-04-23 23:43:10 +00001580 return SQLITE_OK;
drh7e3b0a02001-04-28 16:52:40 +00001581}
1582
1583/*
drh8b2f49b2001-06-08 00:21:52 +00001584** Set up a raw page so that it looks like a database page holding
1585** no entries.
drhbd03cae2001-06-02 02:40:57 +00001586*/
drh9e572e62004-04-23 23:43:10 +00001587static void zeroPage(MemPage *pPage, int flags){
1588 unsigned char *data = pPage->aData;
danielk1977aef0bf62005-12-30 16:28:01 +00001589 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00001590 u8 hdr = pPage->hdrOffset;
1591 u16 first;
drh9e572e62004-04-23 23:43:10 +00001592
danielk19773b8a05f2007-03-19 17:44:26 +00001593 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
drhbf4bca52007-09-06 22:19:14 +00001594 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1595 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
danielk19773b8a05f2007-03-19 17:44:26 +00001596 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00001597 assert( sqlite3_mutex_held(pBt->mutex) );
drhc9166342012-01-05 23:32:06 +00001598 if( pBt->btsFlags & BTS_SECURE_DELETE ){
drh5b47efa2010-02-12 18:18:39 +00001599 memset(&data[hdr], 0, pBt->usableSize - hdr);
1600 }
drh1bd10f82008-12-10 21:19:56 +00001601 data[hdr] = (char)flags;
drhfe485992014-02-12 23:52:16 +00001602 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
drh43605152004-05-29 21:46:49 +00001603 memset(&data[hdr+1], 0, 4);
1604 data[hdr+7] = 0;
1605 put2byte(&data[hdr+5], pBt->usableSize);
shaneh1df2db72010-08-18 02:28:48 +00001606 pPage->nFree = (u16)(pBt->usableSize - first);
drh271efa52004-05-30 19:19:05 +00001607 decodeFlags(pPage, flags);
drh43605152004-05-29 21:46:49 +00001608 pPage->cellOffset = first;
drh3def2352011-11-11 00:27:15 +00001609 pPage->aDataEnd = &data[pBt->usableSize];
1610 pPage->aCellIdx = &data[first];
drh43605152004-05-29 21:46:49 +00001611 pPage->nOverflow = 0;
drhb2eced52010-08-12 02:41:12 +00001612 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
1613 pPage->maskPage = (u16)(pBt->pageSize - 1);
drh43605152004-05-29 21:46:49 +00001614 pPage->nCell = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00001615 pPage->isInit = 1;
drhbd03cae2001-06-02 02:40:57 +00001616}
1617
drh897a8202008-09-18 01:08:15 +00001618
1619/*
1620** Convert a DbPage obtained from the pager into a MemPage used by
1621** the btree layer.
1622*/
1623static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
1624 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
1625 pPage->aData = sqlite3PagerGetData(pDbPage);
1626 pPage->pDbPage = pDbPage;
1627 pPage->pBt = pBt;
1628 pPage->pgno = pgno;
1629 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
1630 return pPage;
1631}
1632
drhbd03cae2001-06-02 02:40:57 +00001633/*
drh3aac2dd2004-04-26 14:10:20 +00001634** Get a page from the pager. Initialize the MemPage.pBt and
1635** MemPage.aData elements if needed.
drh538f5702007-04-13 02:14:30 +00001636**
1637** If the noContent flag is set, it means that we do not care about
1638** the content of the page at this time. So do not go to the disk
1639** to fetch the content. Just fill in the content with zeros for now.
1640** If in the future we call sqlite3PagerWrite() on this page, that
1641** means we have started to be concerned about content and the disk
1642** read should occur at that point.
drh3aac2dd2004-04-26 14:10:20 +00001643*/
danielk197730548662009-07-09 05:07:37 +00001644static int btreeGetPage(
drh16a9b832007-05-05 18:39:25 +00001645 BtShared *pBt, /* The btree */
1646 Pgno pgno, /* Number of the page to fetch */
1647 MemPage **ppPage, /* Return the page in this parameter */
drhb00fc3b2013-08-21 23:42:32 +00001648 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
drh16a9b832007-05-05 18:39:25 +00001649){
drh3aac2dd2004-04-26 14:10:20 +00001650 int rc;
danielk19773b8a05f2007-03-19 17:44:26 +00001651 DbPage *pDbPage;
1652
drhb00fc3b2013-08-21 23:42:32 +00001653 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
drh1fee73e2007-08-29 04:00:57 +00001654 assert( sqlite3_mutex_held(pBt->mutex) );
dan11dcd112013-03-15 18:29:18 +00001655 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
drh3aac2dd2004-04-26 14:10:20 +00001656 if( rc ) return rc;
drh897a8202008-09-18 01:08:15 +00001657 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
drh3aac2dd2004-04-26 14:10:20 +00001658 return SQLITE_OK;
1659}
1660
1661/*
danielk1977bea2a942009-01-20 17:06:27 +00001662** Retrieve a page from the pager cache. If the requested page is not
1663** already in the pager cache return NULL. Initialize the MemPage.pBt and
1664** MemPage.aData elements if needed.
1665*/
1666static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
1667 DbPage *pDbPage;
1668 assert( sqlite3_mutex_held(pBt->mutex) );
1669 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
1670 if( pDbPage ){
1671 return btreePageFromDbPage(pDbPage, pgno, pBt);
1672 }
1673 return 0;
1674}
1675
1676/*
danielk197789d40042008-11-17 14:20:56 +00001677** Return the size of the database file in pages. If there is any kind of
1678** error, return ((unsigned int)-1).
danielk197767fd7a92008-09-10 17:53:35 +00001679*/
drhb1299152010-03-30 22:58:33 +00001680static Pgno btreePagecount(BtShared *pBt){
1681 return pBt->nPage;
1682}
1683u32 sqlite3BtreeLastPage(Btree *p){
1684 assert( sqlite3BtreeHoldsMutex(p) );
1685 assert( ((p->pBt->nPage)&0x8000000)==0 );
drheac5bd72014-07-25 21:35:39 +00001686 return btreePagecount(p->pBt);
danielk197767fd7a92008-09-10 17:53:35 +00001687}
1688
1689/*
danielk197789bc4bc2009-07-21 19:25:24 +00001690** Get a page from the pager and initialize it. This routine is just a
1691** convenience wrapper around separate calls to btreeGetPage() and
1692** btreeInitPage().
1693**
1694** If an error occurs, then the value *ppPage is set to is undefined. It
1695** may remain unchanged, or it may be set to an invalid value.
drhde647132004-05-07 17:57:49 +00001696*/
1697static int getAndInitPage(
dan11dcd112013-03-15 18:29:18 +00001698 BtShared *pBt, /* The database file */
1699 Pgno pgno, /* Number of the page to get */
1700 MemPage **ppPage, /* Write the page pointer here */
drhb00fc3b2013-08-21 23:42:32 +00001701 int bReadonly /* PAGER_GET_READONLY or 0 */
drhde647132004-05-07 17:57:49 +00001702){
1703 int rc;
drh1fee73e2007-08-29 04:00:57 +00001704 assert( sqlite3_mutex_held(pBt->mutex) );
drhb00fc3b2013-08-21 23:42:32 +00001705 assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
danielk197789bc4bc2009-07-21 19:25:24 +00001706
danba3cbf32010-06-30 04:29:03 +00001707 if( pgno>btreePagecount(pBt) ){
1708 rc = SQLITE_CORRUPT_BKPT;
1709 }else{
drhb00fc3b2013-08-21 23:42:32 +00001710 rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
drh29f2bad2013-12-09 01:04:54 +00001711 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
danba3cbf32010-06-30 04:29:03 +00001712 rc = btreeInitPage(*ppPage);
1713 if( rc!=SQLITE_OK ){
1714 releasePage(*ppPage);
1715 }
danielk197789bc4bc2009-07-21 19:25:24 +00001716 }
drhee696e22004-08-30 16:52:17 +00001717 }
danba3cbf32010-06-30 04:29:03 +00001718
1719 testcase( pgno==0 );
1720 assert( pgno!=0 || rc==SQLITE_CORRUPT );
drhde647132004-05-07 17:57:49 +00001721 return rc;
1722}
1723
1724/*
drh3aac2dd2004-04-26 14:10:20 +00001725** Release a MemPage. This should be called once for each prior
danielk197730548662009-07-09 05:07:37 +00001726** call to btreeGetPage.
drh3aac2dd2004-04-26 14:10:20 +00001727*/
drh4b70f112004-05-02 21:12:19 +00001728static void releasePage(MemPage *pPage){
drh3aac2dd2004-04-26 14:10:20 +00001729 if( pPage ){
1730 assert( pPage->aData );
1731 assert( pPage->pBt );
drhda8a3302013-12-13 19:35:21 +00001732 assert( pPage->pDbPage!=0 );
drhbf4bca52007-09-06 22:19:14 +00001733 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
1734 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
drh1fee73e2007-08-29 04:00:57 +00001735 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda8a3302013-12-13 19:35:21 +00001736 sqlite3PagerUnrefNotNull(pPage->pDbPage);
drh3aac2dd2004-04-26 14:10:20 +00001737 }
1738}
1739
1740/*
drha6abd042004-06-09 17:37:22 +00001741** During a rollback, when the pager reloads information into the cache
1742** so that the cache is restored to its original state at the start of
1743** the transaction, for each page restored this routine is called.
1744**
1745** This routine needs to reset the extra data section at the end of the
1746** page to agree with the restored data.
1747*/
danielk1977eaa06f62008-09-18 17:34:44 +00001748static void pageReinit(DbPage *pData){
drh07d183d2005-05-01 22:52:42 +00001749 MemPage *pPage;
danielk19773b8a05f2007-03-19 17:44:26 +00001750 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
danielk1977d217e6f2009-04-01 17:13:51 +00001751 assert( sqlite3PagerPageRefcount(pData)>0 );
danielk197771d5d2c2008-09-29 11:49:47 +00001752 if( pPage->isInit ){
drh1fee73e2007-08-29 04:00:57 +00001753 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drha6abd042004-06-09 17:37:22 +00001754 pPage->isInit = 0;
danielk1977d217e6f2009-04-01 17:13:51 +00001755 if( sqlite3PagerPageRefcount(pData)>1 ){
drh5e8d8872009-03-30 17:19:48 +00001756 /* pPage might not be a btree page; it might be an overflow page
1757 ** or ptrmap page or a free page. In those cases, the following
danielk197730548662009-07-09 05:07:37 +00001758 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
drh5e8d8872009-03-30 17:19:48 +00001759 ** But no harm is done by this. And it is very important that
danielk197730548662009-07-09 05:07:37 +00001760 ** btreeInitPage() be called on every btree page so we make
drh5e8d8872009-03-30 17:19:48 +00001761 ** the call for every page that comes in for re-initing. */
danielk197730548662009-07-09 05:07:37 +00001762 btreeInitPage(pPage);
danielk197771d5d2c2008-09-29 11:49:47 +00001763 }
drha6abd042004-06-09 17:37:22 +00001764 }
1765}
1766
1767/*
drhe5fe6902007-12-07 18:55:28 +00001768** Invoke the busy handler for a btree.
1769*/
danielk19771ceedd32008-11-19 10:22:33 +00001770static int btreeInvokeBusyHandler(void *pArg){
drhe5fe6902007-12-07 18:55:28 +00001771 BtShared *pBt = (BtShared*)pArg;
1772 assert( pBt->db );
1773 assert( sqlite3_mutex_held(pBt->db->mutex) );
1774 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
1775}
1776
1777/*
drhad3e0102004-09-03 23:32:18 +00001778** Open a database file.
1779**
drh382c0242001-10-06 16:33:02 +00001780** zFilename is the name of the database file. If zFilename is NULL
drh75c014c2010-08-30 15:02:28 +00001781** then an ephemeral database is created. The ephemeral database might
1782** be exclusively in memory, or it might use a disk-based memory cache.
1783** Either way, the ephemeral database will be automatically deleted
1784** when sqlite3BtreeClose() is called.
1785**
drhe53831d2007-08-17 01:14:38 +00001786** If zFilename is ":memory:" then an in-memory database is created
1787** that is automatically destroyed when it is closed.
drhc47fd8e2009-04-30 13:30:32 +00001788**
drh33f111d2012-01-17 15:29:14 +00001789** The "flags" parameter is a bitmask that might contain bits like
1790** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
drh75c014c2010-08-30 15:02:28 +00001791**
drhc47fd8e2009-04-30 13:30:32 +00001792** If the database is already opened in the same database connection
1793** and we are in shared cache mode, then the open will fail with an
1794** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
1795** objects in the same database connection since doing so will lead
1796** to problems with locking.
drha059ad02001-04-17 20:09:11 +00001797*/
drh23e11ca2004-05-04 17:27:28 +00001798int sqlite3BtreeOpen(
dan3a6d8ae2011-04-23 15:54:54 +00001799 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
drh3aac2dd2004-04-26 14:10:20 +00001800 const char *zFilename, /* Name of the file containing the BTree database */
drhe5fe6902007-12-07 18:55:28 +00001801 sqlite3 *db, /* Associated database handle */
drh3aac2dd2004-04-26 14:10:20 +00001802 Btree **ppBtree, /* Pointer to new Btree object written here */
drh33f4e022007-09-03 15:19:34 +00001803 int flags, /* Options */
1804 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
drh6019e162001-07-02 17:51:45 +00001805){
drh7555d8e2009-03-20 13:15:30 +00001806 BtShared *pBt = 0; /* Shared part of btree structure */
1807 Btree *p; /* Handle to return */
1808 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
1809 int rc = SQLITE_OK; /* Result code from this function */
1810 u8 nReserve; /* Byte of unused space on each page */
1811 unsigned char zDbHeader[100]; /* Database header content */
danielk1977aef0bf62005-12-30 16:28:01 +00001812
drh75c014c2010-08-30 15:02:28 +00001813 /* True if opening an ephemeral, temporary database */
1814 const int isTempDb = zFilename==0 || zFilename[0]==0;
1815
danielk1977aef0bf62005-12-30 16:28:01 +00001816 /* Set the variable isMemdb to true for an in-memory database, or
drhb0a7c9c2010-12-06 21:09:59 +00001817 ** false for a file-based database.
danielk1977aef0bf62005-12-30 16:28:01 +00001818 */
drhb0a7c9c2010-12-06 21:09:59 +00001819#ifdef SQLITE_OMIT_MEMORYDB
1820 const int isMemdb = 0;
1821#else
1822 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
drh9c67b2a2012-05-28 13:58:00 +00001823 || (isTempDb && sqlite3TempInMemory(db))
1824 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
danielk1977aef0bf62005-12-30 16:28:01 +00001825#endif
1826
drhe5fe6902007-12-07 18:55:28 +00001827 assert( db!=0 );
dan3a6d8ae2011-04-23 15:54:54 +00001828 assert( pVfs!=0 );
drhe5fe6902007-12-07 18:55:28 +00001829 assert( sqlite3_mutex_held(db->mutex) );
drhd4187c72010-08-30 22:15:45 +00001830 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
1831
1832 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
1833 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
1834
1835 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
1836 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
drh153c62c2007-08-24 03:51:33 +00001837
drh75c014c2010-08-30 15:02:28 +00001838 if( isMemdb ){
1839 flags |= BTREE_MEMORY;
1840 }
1841 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
1842 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
1843 }
drh17435752007-08-16 04:30:38 +00001844 p = sqlite3MallocZero(sizeof(Btree));
danielk1977aef0bf62005-12-30 16:28:01 +00001845 if( !p ){
1846 return SQLITE_NOMEM;
1847 }
1848 p->inTrans = TRANS_NONE;
drhe5fe6902007-12-07 18:55:28 +00001849 p->db = db;
danielk1977602b4662009-07-02 07:47:33 +00001850#ifndef SQLITE_OMIT_SHARED_CACHE
1851 p->lock.pBtree = p;
1852 p->lock.iTable = 1;
1853#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001854
drh198bf392006-01-06 21:52:49 +00001855#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00001856 /*
1857 ** If this Btree is a candidate for shared cache, try to find an
1858 ** existing BtShared object that we can share with
1859 */
drh4ab9d252012-05-26 20:08:49 +00001860 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
drhf1f12682009-09-09 14:17:52 +00001861 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
danielk1977adfb9b02007-09-17 07:02:56 +00001862 int nFullPathname = pVfs->mxPathname+1;
drhe5ae5732008-06-15 02:51:47 +00001863 char *zFullPathname = sqlite3Malloc(nFullPathname);
drh30ddce62011-10-15 00:16:30 +00001864 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
drhff0587c2007-08-29 17:43:19 +00001865 p->sharable = 1;
drhff0587c2007-08-29 17:43:19 +00001866 if( !zFullPathname ){
1867 sqlite3_free(p);
1868 return SQLITE_NOMEM;
1869 }
drhafc8b7f2012-05-26 18:06:38 +00001870 if( isMemdb ){
1871 memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
1872 }else{
1873 rc = sqlite3OsFullPathname(pVfs, zFilename,
1874 nFullPathname, zFullPathname);
1875 if( rc ){
1876 sqlite3_free(zFullPathname);
1877 sqlite3_free(p);
1878 return rc;
1879 }
drh070ad6b2011-11-17 11:43:19 +00001880 }
drh30ddce62011-10-15 00:16:30 +00001881#if SQLITE_THREADSAFE
drh7555d8e2009-03-20 13:15:30 +00001882 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
1883 sqlite3_mutex_enter(mutexOpen);
danielk197759f8c082008-06-18 17:09:10 +00001884 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
drhff0587c2007-08-29 17:43:19 +00001885 sqlite3_mutex_enter(mutexShared);
drh30ddce62011-10-15 00:16:30 +00001886#endif
drh78f82d12008-09-02 00:52:52 +00001887 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
drhff0587c2007-08-29 17:43:19 +00001888 assert( pBt->nRef>0 );
drhd4e0bb02012-05-27 01:19:04 +00001889 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
drhff0587c2007-08-29 17:43:19 +00001890 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
drhc47fd8e2009-04-30 13:30:32 +00001891 int iDb;
1892 for(iDb=db->nDb-1; iDb>=0; iDb--){
1893 Btree *pExisting = db->aDb[iDb].pBt;
1894 if( pExisting && pExisting->pBt==pBt ){
1895 sqlite3_mutex_leave(mutexShared);
1896 sqlite3_mutex_leave(mutexOpen);
1897 sqlite3_free(zFullPathname);
1898 sqlite3_free(p);
1899 return SQLITE_CONSTRAINT;
1900 }
1901 }
drhff0587c2007-08-29 17:43:19 +00001902 p->pBt = pBt;
1903 pBt->nRef++;
1904 break;
1905 }
1906 }
1907 sqlite3_mutex_leave(mutexShared);
1908 sqlite3_free(zFullPathname);
danielk1977aef0bf62005-12-30 16:28:01 +00001909 }
drhff0587c2007-08-29 17:43:19 +00001910#ifdef SQLITE_DEBUG
1911 else{
1912 /* In debug mode, we mark all persistent databases as sharable
1913 ** even when they are not. This exercises the locking code and
1914 ** gives more opportunity for asserts(sqlite3_mutex_held())
1915 ** statements to find locking problems.
1916 */
1917 p->sharable = 1;
1918 }
1919#endif
danielk1977aef0bf62005-12-30 16:28:01 +00001920 }
1921#endif
drha059ad02001-04-17 20:09:11 +00001922 if( pBt==0 ){
drhe53831d2007-08-17 01:14:38 +00001923 /*
1924 ** The following asserts make sure that structures used by the btree are
1925 ** the right size. This is to guard against size changes that result
1926 ** when compiling on a different architecture.
danielk197703aded42004-11-22 05:26:27 +00001927 */
drhe53831d2007-08-17 01:14:38 +00001928 assert( sizeof(i64)==8 || sizeof(i64)==4 );
1929 assert( sizeof(u64)==8 || sizeof(u64)==4 );
1930 assert( sizeof(u32)==4 );
1931 assert( sizeof(u16)==2 );
1932 assert( sizeof(Pgno)==4 );
1933
1934 pBt = sqlite3MallocZero( sizeof(*pBt) );
1935 if( pBt==0 ){
1936 rc = SQLITE_NOMEM;
1937 goto btree_open_out;
1938 }
danielk197771d5d2c2008-09-29 11:49:47 +00001939 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
drh4775ecd2009-07-24 19:01:19 +00001940 EXTRA_SIZE, flags, vfsFlags, pageReinit);
drhe53831d2007-08-17 01:14:38 +00001941 if( rc==SQLITE_OK ){
drh9b4c59f2013-04-15 17:03:42 +00001942 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
drhe53831d2007-08-17 01:14:38 +00001943 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
1944 }
1945 if( rc!=SQLITE_OK ){
1946 goto btree_open_out;
1947 }
shanehbd2aaf92010-09-01 02:38:21 +00001948 pBt->openFlags = (u8)flags;
danielk19772a50ff02009-04-10 09:47:06 +00001949 pBt->db = db;
danielk19771ceedd32008-11-19 10:22:33 +00001950 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
drhe53831d2007-08-17 01:14:38 +00001951 p->pBt = pBt;
1952
drhe53831d2007-08-17 01:14:38 +00001953 pBt->pCursor = 0;
1954 pBt->pPage1 = 0;
drhc9166342012-01-05 23:32:06 +00001955 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
drh5b47efa2010-02-12 18:18:39 +00001956#ifdef SQLITE_SECURE_DELETE
drhc9166342012-01-05 23:32:06 +00001957 pBt->btsFlags |= BTS_SECURE_DELETE;
drh5b47efa2010-02-12 18:18:39 +00001958#endif
drhb2eced52010-08-12 02:41:12 +00001959 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
drhe53831d2007-08-17 01:14:38 +00001960 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1961 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00001962 pBt->pageSize = 0;
drhe53831d2007-08-17 01:14:38 +00001963#ifndef SQLITE_OMIT_AUTOVACUUM
1964 /* If the magic name ":memory:" will create an in-memory database, then
1965 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
1966 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
1967 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
1968 ** regular file-name. In this case the auto-vacuum applies as per normal.
1969 */
1970 if( zFilename && !isMemdb ){
1971 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
1972 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
1973 }
1974#endif
1975 nReserve = 0;
1976 }else{
1977 nReserve = zDbHeader[20];
drhc9166342012-01-05 23:32:06 +00001978 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
drhe53831d2007-08-17 01:14:38 +00001979#ifndef SQLITE_OMIT_AUTOVACUUM
1980 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
1981 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
1982#endif
1983 }
drhfa9601a2009-06-18 17:22:39 +00001984 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhc0b61812009-04-30 01:22:41 +00001985 if( rc ) goto btree_open_out;
drhe53831d2007-08-17 01:14:38 +00001986 pBt->usableSize = pBt->pageSize - nReserve;
1987 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
drhe53831d2007-08-17 01:14:38 +00001988
1989#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
1990 /* Add the new BtShared object to the linked list sharable BtShareds.
1991 */
1992 if( p->sharable ){
drh30ddce62011-10-15 00:16:30 +00001993 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
drhe53831d2007-08-17 01:14:38 +00001994 pBt->nRef = 1;
drh30ddce62011-10-15 00:16:30 +00001995 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
danielk1977075c23a2008-09-01 18:34:20 +00001996 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
danielk197759f8c082008-06-18 17:09:10 +00001997 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
drh3285db22007-09-03 22:00:39 +00001998 if( pBt->mutex==0 ){
1999 rc = SQLITE_NOMEM;
drhe5fe6902007-12-07 18:55:28 +00002000 db->mallocFailed = 0;
drh3285db22007-09-03 22:00:39 +00002001 goto btree_open_out;
2002 }
drhff0587c2007-08-29 17:43:19 +00002003 }
drhe53831d2007-08-17 01:14:38 +00002004 sqlite3_mutex_enter(mutexShared);
drh78f82d12008-09-02 00:52:52 +00002005 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2006 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
drhe53831d2007-08-17 01:14:38 +00002007 sqlite3_mutex_leave(mutexShared);
danielk1977951af802004-11-05 15:45:09 +00002008 }
drheee46cf2004-11-06 00:02:48 +00002009#endif
drh90f5ecb2004-07-22 01:19:35 +00002010 }
danielk1977aef0bf62005-12-30 16:28:01 +00002011
drhcfed7bc2006-03-13 14:28:05 +00002012#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
drhe53831d2007-08-17 01:14:38 +00002013 /* If the new Btree uses a sharable pBtShared, then link the new
2014 ** Btree into the list of all sharable Btrees for the same connection.
drhabddb0c2007-08-20 13:14:28 +00002015 ** The list is kept in ascending order by pBt address.
danielk197754f01982006-01-18 15:25:17 +00002016 */
drhe53831d2007-08-17 01:14:38 +00002017 if( p->sharable ){
2018 int i;
2019 Btree *pSib;
drhe5fe6902007-12-07 18:55:28 +00002020 for(i=0; i<db->nDb; i++){
2021 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
drhe53831d2007-08-17 01:14:38 +00002022 while( pSib->pPrev ){ pSib = pSib->pPrev; }
2023 if( p->pBt<pSib->pBt ){
2024 p->pNext = pSib;
2025 p->pPrev = 0;
2026 pSib->pPrev = p;
2027 }else{
drhabddb0c2007-08-20 13:14:28 +00002028 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
drhe53831d2007-08-17 01:14:38 +00002029 pSib = pSib->pNext;
2030 }
2031 p->pNext = pSib->pNext;
2032 p->pPrev = pSib;
2033 if( p->pNext ){
2034 p->pNext->pPrev = p;
2035 }
2036 pSib->pNext = p;
2037 }
2038 break;
2039 }
2040 }
danielk1977aef0bf62005-12-30 16:28:01 +00002041 }
danielk1977aef0bf62005-12-30 16:28:01 +00002042#endif
2043 *ppBtree = p;
danielk1977dddbcdc2007-04-26 14:42:34 +00002044
2045btree_open_out:
2046 if( rc!=SQLITE_OK ){
2047 if( pBt && pBt->pPager ){
2048 sqlite3PagerClose(pBt->pPager);
2049 }
drh17435752007-08-16 04:30:38 +00002050 sqlite3_free(pBt);
2051 sqlite3_free(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00002052 *ppBtree = 0;
drh75c014c2010-08-30 15:02:28 +00002053 }else{
2054 /* If the B-Tree was successfully opened, set the pager-cache size to the
2055 ** default value. Except, when opening on an existing shared pager-cache,
2056 ** do not change the pager-cache size.
2057 */
2058 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
2059 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
2060 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002061 }
drh7555d8e2009-03-20 13:15:30 +00002062 if( mutexOpen ){
2063 assert( sqlite3_mutex_held(mutexOpen) );
2064 sqlite3_mutex_leave(mutexOpen);
2065 }
danielk1977dddbcdc2007-04-26 14:42:34 +00002066 return rc;
drha059ad02001-04-17 20:09:11 +00002067}
2068
2069/*
drhe53831d2007-08-17 01:14:38 +00002070** Decrement the BtShared.nRef counter. When it reaches zero,
2071** remove the BtShared structure from the sharing list. Return
2072** true if the BtShared.nRef counter reaches zero and return
2073** false if it is still positive.
2074*/
2075static int removeFromSharingList(BtShared *pBt){
2076#ifndef SQLITE_OMIT_SHARED_CACHE
drh30ddce62011-10-15 00:16:30 +00002077 MUTEX_LOGIC( sqlite3_mutex *pMaster; )
drhe53831d2007-08-17 01:14:38 +00002078 BtShared *pList;
2079 int removed = 0;
2080
drhd677b3d2007-08-20 22:48:41 +00002081 assert( sqlite3_mutex_notheld(pBt->mutex) );
drh30ddce62011-10-15 00:16:30 +00002082 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
drhe53831d2007-08-17 01:14:38 +00002083 sqlite3_mutex_enter(pMaster);
2084 pBt->nRef--;
2085 if( pBt->nRef<=0 ){
drh78f82d12008-09-02 00:52:52 +00002086 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2087 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
drhe53831d2007-08-17 01:14:38 +00002088 }else{
drh78f82d12008-09-02 00:52:52 +00002089 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
drh34004ce2008-07-11 16:15:17 +00002090 while( ALWAYS(pList) && pList->pNext!=pBt ){
drhe53831d2007-08-17 01:14:38 +00002091 pList=pList->pNext;
2092 }
drh34004ce2008-07-11 16:15:17 +00002093 if( ALWAYS(pList) ){
drhe53831d2007-08-17 01:14:38 +00002094 pList->pNext = pBt->pNext;
2095 }
2096 }
drh3285db22007-09-03 22:00:39 +00002097 if( SQLITE_THREADSAFE ){
2098 sqlite3_mutex_free(pBt->mutex);
2099 }
drhe53831d2007-08-17 01:14:38 +00002100 removed = 1;
2101 }
2102 sqlite3_mutex_leave(pMaster);
2103 return removed;
2104#else
2105 return 1;
2106#endif
2107}
2108
2109/*
drhf7141992008-06-19 00:16:08 +00002110** Make sure pBt->pTmpSpace points to an allocation of
2111** MX_CELL_SIZE(pBt) bytes.
2112*/
2113static void allocateTempSpace(BtShared *pBt){
2114 if( !pBt->pTmpSpace ){
2115 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
dan14285b72013-10-16 11:39:07 +00002116
2117 /* One of the uses of pBt->pTmpSpace is to format cells before
2118 ** inserting them into a leaf page (function fillInCell()). If
2119 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
2120 ** by the various routines that manipulate binary cells. Which
2121 ** can mean that fillInCell() only initializes the first 2 or 3
2122 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
2123 ** it into a database page. This is not actually a problem, but it
2124 ** does cause a valgrind error when the 1 or 2 bytes of unitialized
2125 ** data is passed to system call write(). So to avoid this error,
2126 ** zero the first 4 bytes of temp space here. */
2127 if( pBt->pTmpSpace ) memset(pBt->pTmpSpace, 0, 4);
drhf7141992008-06-19 00:16:08 +00002128 }
2129}
2130
2131/*
2132** Free the pBt->pTmpSpace allocation
2133*/
2134static void freeTempSpace(BtShared *pBt){
2135 sqlite3PageFree( pBt->pTmpSpace);
2136 pBt->pTmpSpace = 0;
2137}
2138
2139/*
drha059ad02001-04-17 20:09:11 +00002140** Close an open database and invalidate all cursors.
2141*/
danielk1977aef0bf62005-12-30 16:28:01 +00002142int sqlite3BtreeClose(Btree *p){
danielk1977aef0bf62005-12-30 16:28:01 +00002143 BtShared *pBt = p->pBt;
2144 BtCursor *pCur;
2145
danielk1977aef0bf62005-12-30 16:28:01 +00002146 /* Close all cursors opened via this handle. */
drhe5fe6902007-12-07 18:55:28 +00002147 assert( sqlite3_mutex_held(p->db->mutex) );
drhe53831d2007-08-17 01:14:38 +00002148 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002149 pCur = pBt->pCursor;
2150 while( pCur ){
2151 BtCursor *pTmp = pCur;
2152 pCur = pCur->pNext;
2153 if( pTmp->pBtree==p ){
2154 sqlite3BtreeCloseCursor(pTmp);
2155 }
drha059ad02001-04-17 20:09:11 +00002156 }
danielk1977aef0bf62005-12-30 16:28:01 +00002157
danielk19778d34dfd2006-01-24 16:37:57 +00002158 /* Rollback any active transaction and free the handle structure.
2159 ** The call to sqlite3BtreeRollback() drops any table-locks held by
2160 ** this handle.
2161 */
drh0f198a72012-02-13 16:43:16 +00002162 sqlite3BtreeRollback(p, SQLITE_OK);
drhe53831d2007-08-17 01:14:38 +00002163 sqlite3BtreeLeave(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002164
danielk1977aef0bf62005-12-30 16:28:01 +00002165 /* If there are still other outstanding references to the shared-btree
2166 ** structure, return now. The remainder of this procedure cleans
2167 ** up the shared-btree.
2168 */
drhe53831d2007-08-17 01:14:38 +00002169 assert( p->wantToLock==0 && p->locked==0 );
2170 if( !p->sharable || removeFromSharingList(pBt) ){
2171 /* The pBt is no longer on the sharing list, so we can access
2172 ** it without having to hold the mutex.
2173 **
2174 ** Clean out and delete the BtShared object.
2175 */
2176 assert( !pBt->pCursor );
drhe53831d2007-08-17 01:14:38 +00002177 sqlite3PagerClose(pBt->pPager);
2178 if( pBt->xFreeSchema && pBt->pSchema ){
2179 pBt->xFreeSchema(pBt->pSchema);
2180 }
drhb9755982010-07-24 16:34:37 +00002181 sqlite3DbFree(0, pBt->pSchema);
drhf7141992008-06-19 00:16:08 +00002182 freeTempSpace(pBt);
drh65bbf292008-06-19 01:03:17 +00002183 sqlite3_free(pBt);
danielk1977aef0bf62005-12-30 16:28:01 +00002184 }
2185
drhe53831d2007-08-17 01:14:38 +00002186#ifndef SQLITE_OMIT_SHARED_CACHE
drhcab5ed72007-08-22 11:41:18 +00002187 assert( p->wantToLock==0 );
2188 assert( p->locked==0 );
2189 if( p->pPrev ) p->pPrev->pNext = p->pNext;
2190 if( p->pNext ) p->pNext->pPrev = p->pPrev;
danielk1977aef0bf62005-12-30 16:28:01 +00002191#endif
2192
drhe53831d2007-08-17 01:14:38 +00002193 sqlite3_free(p);
drha059ad02001-04-17 20:09:11 +00002194 return SQLITE_OK;
2195}
2196
2197/*
drhda47d772002-12-02 04:25:19 +00002198** Change the limit on the number of pages allowed in the cache.
drhcd61c282002-03-06 22:01:34 +00002199**
2200** The maximum number of cache pages is set to the absolute
2201** value of mxPage. If mxPage is negative, the pager will
2202** operate asynchronously - it will not stop to do fsync()s
2203** to insure data is written to the disk surface before
2204** continuing. Transactions still work if synchronous is off,
2205** and the database cannot be corrupted if this program
2206** crashes. But if the operating system crashes or there is
2207** an abrupt power failure when synchronous is off, the database
2208** could be left in an inconsistent and unrecoverable state.
2209** Synchronous is on by default so database corruption is not
2210** normally a worry.
drhf57b14a2001-09-14 18:54:08 +00002211*/
danielk1977aef0bf62005-12-30 16:28:01 +00002212int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
2213 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00002214 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002215 sqlite3BtreeEnter(p);
danielk19773b8a05f2007-03-19 17:44:26 +00002216 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
drhd677b3d2007-08-20 22:48:41 +00002217 sqlite3BtreeLeave(p);
drhf57b14a2001-09-14 18:54:08 +00002218 return SQLITE_OK;
2219}
2220
drh18c7e402014-03-14 11:46:10 +00002221#if SQLITE_MAX_MMAP_SIZE>0
drhf57b14a2001-09-14 18:54:08 +00002222/*
dan5d8a1372013-03-19 19:28:06 +00002223** Change the limit on the amount of the database file that may be
2224** memory mapped.
2225*/
drh9b4c59f2013-04-15 17:03:42 +00002226int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
dan5d8a1372013-03-19 19:28:06 +00002227 BtShared *pBt = p->pBt;
2228 assert( sqlite3_mutex_held(p->db->mutex) );
2229 sqlite3BtreeEnter(p);
drh9b4c59f2013-04-15 17:03:42 +00002230 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
dan5d8a1372013-03-19 19:28:06 +00002231 sqlite3BtreeLeave(p);
2232 return SQLITE_OK;
2233}
drh18c7e402014-03-14 11:46:10 +00002234#endif /* SQLITE_MAX_MMAP_SIZE>0 */
dan5d8a1372013-03-19 19:28:06 +00002235
2236/*
drh973b6e32003-02-12 14:09:42 +00002237** Change the way data is synced to disk in order to increase or decrease
2238** how well the database resists damage due to OS crashes and power
2239** failures. Level 1 is the same as asynchronous (no syncs() occur and
2240** there is a high probability of damage) Level 2 is the default. There
2241** is a very low but non-zero probability of damage. Level 3 reduces the
2242** probability of damage to near zero but with a write performance reduction.
2243*/
danielk197793758c82005-01-21 08:13:14 +00002244#ifndef SQLITE_OMIT_PAGER_PRAGMAS
drh40c39412013-08-16 20:42:20 +00002245int sqlite3BtreeSetPagerFlags(
drhc97d8462010-11-19 18:23:35 +00002246 Btree *p, /* The btree to set the safety level on */
drh40c39412013-08-16 20:42:20 +00002247 unsigned pgFlags /* Various PAGER_* flags */
drhc97d8462010-11-19 18:23:35 +00002248){
danielk1977aef0bf62005-12-30 16:28:01 +00002249 BtShared *pBt = p->pBt;
drhe5fe6902007-12-07 18:55:28 +00002250 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002251 sqlite3BtreeEnter(p);
drh40c39412013-08-16 20:42:20 +00002252 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
drhd677b3d2007-08-20 22:48:41 +00002253 sqlite3BtreeLeave(p);
drh973b6e32003-02-12 14:09:42 +00002254 return SQLITE_OK;
2255}
danielk197793758c82005-01-21 08:13:14 +00002256#endif
drh973b6e32003-02-12 14:09:42 +00002257
drh2c8997b2005-08-27 16:36:48 +00002258/*
2259** Return TRUE if the given btree is set to safety level 1. In other
2260** words, return TRUE if no sync() occurs on the disk files.
2261*/
danielk1977aef0bf62005-12-30 16:28:01 +00002262int sqlite3BtreeSyncDisabled(Btree *p){
2263 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002264 int rc;
drhe5fe6902007-12-07 18:55:28 +00002265 assert( sqlite3_mutex_held(p->db->mutex) );
drhd677b3d2007-08-20 22:48:41 +00002266 sqlite3BtreeEnter(p);
drhd0679ed2007-08-28 22:24:34 +00002267 assert( pBt && pBt->pPager );
drhd677b3d2007-08-20 22:48:41 +00002268 rc = sqlite3PagerNosync(pBt->pPager);
2269 sqlite3BtreeLeave(p);
2270 return rc;
drh2c8997b2005-08-27 16:36:48 +00002271}
2272
drh973b6e32003-02-12 14:09:42 +00002273/*
drh90f5ecb2004-07-22 01:19:35 +00002274** Change the default pages size and the number of reserved bytes per page.
drhce4869f2009-04-02 20:16:58 +00002275** Or, if the page size has already been fixed, return SQLITE_READONLY
2276** without changing anything.
drh06f50212004-11-02 14:24:33 +00002277**
2278** The page size must be a power of 2 between 512 and 65536. If the page
2279** size supplied does not meet this constraint then the page size is not
2280** changed.
2281**
2282** Page sizes are constrained to be a power of two so that the region
2283** of the database file used for locking (beginning at PENDING_BYTE,
2284** the first byte past the 1GB boundary, 0x40000000) needs to occur
2285** at the beginning of a page.
danielk197728129562005-01-11 10:25:06 +00002286**
2287** If parameter nReserve is less than zero, then the number of reserved
2288** bytes per page is left unchanged.
drhce4869f2009-04-02 20:16:58 +00002289**
drhc9166342012-01-05 23:32:06 +00002290** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
drhce4869f2009-04-02 20:16:58 +00002291** and autovacuum mode can no longer be changed.
drh90f5ecb2004-07-22 01:19:35 +00002292*/
drhce4869f2009-04-02 20:16:58 +00002293int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
danielk1977a1644fd2007-08-29 12:31:25 +00002294 int rc = SQLITE_OK;
danielk1977aef0bf62005-12-30 16:28:01 +00002295 BtShared *pBt = p->pBt;
drhf49661a2008-12-10 16:45:50 +00002296 assert( nReserve>=-1 && nReserve<=255 );
drhd677b3d2007-08-20 22:48:41 +00002297 sqlite3BtreeEnter(p);
drhc9166342012-01-05 23:32:06 +00002298 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
drhd677b3d2007-08-20 22:48:41 +00002299 sqlite3BtreeLeave(p);
drh90f5ecb2004-07-22 01:19:35 +00002300 return SQLITE_READONLY;
2301 }
2302 if( nReserve<0 ){
2303 nReserve = pBt->pageSize - pBt->usableSize;
2304 }
drhf49661a2008-12-10 16:45:50 +00002305 assert( nReserve>=0 && nReserve<=255 );
drh06f50212004-11-02 14:24:33 +00002306 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
2307 ((pageSize-1)&pageSize)==0 ){
drh07d183d2005-05-01 22:52:42 +00002308 assert( (pageSize & 7)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00002309 assert( !pBt->pPage1 && !pBt->pCursor );
drhb2eced52010-08-12 02:41:12 +00002310 pBt->pageSize = (u32)pageSize;
drhf7141992008-06-19 00:16:08 +00002311 freeTempSpace(pBt);
drh90f5ecb2004-07-22 01:19:35 +00002312 }
drhfa9601a2009-06-18 17:22:39 +00002313 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
drhf49661a2008-12-10 16:45:50 +00002314 pBt->usableSize = pBt->pageSize - (u16)nReserve;
drhc9166342012-01-05 23:32:06 +00002315 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
drhd677b3d2007-08-20 22:48:41 +00002316 sqlite3BtreeLeave(p);
danielk1977a1644fd2007-08-29 12:31:25 +00002317 return rc;
drh90f5ecb2004-07-22 01:19:35 +00002318}
2319
2320/*
2321** Return the currently defined page size
2322*/
danielk1977aef0bf62005-12-30 16:28:01 +00002323int sqlite3BtreeGetPageSize(Btree *p){
2324 return p->pBt->pageSize;
drh90f5ecb2004-07-22 01:19:35 +00002325}
drh7f751222009-03-17 22:33:00 +00002326
drha1f38532012-10-01 12:44:26 +00002327#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
dan0094f372012-09-28 20:23:42 +00002328/*
2329** This function is similar to sqlite3BtreeGetReserve(), except that it
2330** may only be called if it is guaranteed that the b-tree mutex is already
2331** held.
2332**
2333** This is useful in one special case in the backup API code where it is
2334** known that the shared b-tree mutex is held, but the mutex on the
2335** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
2336** were to be called, it might collide with some other operation on the
mistachkin48864df2013-03-21 21:20:32 +00002337** database handle that owns *p, causing undefined behavior.
dan0094f372012-09-28 20:23:42 +00002338*/
2339int sqlite3BtreeGetReserveNoMutex(Btree *p){
2340 assert( sqlite3_mutex_held(p->pBt->mutex) );
2341 return p->pBt->pageSize - p->pBt->usableSize;
2342}
drha1f38532012-10-01 12:44:26 +00002343#endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
dan0094f372012-09-28 20:23:42 +00002344
danbb2b4412011-04-06 17:54:31 +00002345#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
drh7f751222009-03-17 22:33:00 +00002346/*
2347** Return the number of bytes of space at the end of every page that
2348** are intentually left unused. This is the "reserved" space that is
2349** sometimes used by extensions.
2350*/
danielk1977aef0bf62005-12-30 16:28:01 +00002351int sqlite3BtreeGetReserve(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00002352 int n;
2353 sqlite3BtreeEnter(p);
2354 n = p->pBt->pageSize - p->pBt->usableSize;
2355 sqlite3BtreeLeave(p);
2356 return n;
drh2011d5f2004-07-22 02:40:37 +00002357}
drhf8e632b2007-05-08 14:51:36 +00002358
2359/*
2360** Set the maximum page count for a database if mxPage is positive.
2361** No changes are made if mxPage is 0 or negative.
2362** Regardless of the value of mxPage, return the maximum page count.
2363*/
2364int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
drhd677b3d2007-08-20 22:48:41 +00002365 int n;
2366 sqlite3BtreeEnter(p);
2367 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
2368 sqlite3BtreeLeave(p);
2369 return n;
drhf8e632b2007-05-08 14:51:36 +00002370}
drh5b47efa2010-02-12 18:18:39 +00002371
2372/*
drhc9166342012-01-05 23:32:06 +00002373** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
2374** then make no changes. Always return the value of the BTS_SECURE_DELETE
drh5b47efa2010-02-12 18:18:39 +00002375** setting after the change.
2376*/
2377int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
2378 int b;
drhaf034ed2010-02-12 19:46:26 +00002379 if( p==0 ) return 0;
drh5b47efa2010-02-12 18:18:39 +00002380 sqlite3BtreeEnter(p);
2381 if( newFlag>=0 ){
drhc9166342012-01-05 23:32:06 +00002382 p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
2383 if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
drh5b47efa2010-02-12 18:18:39 +00002384 }
drhc9166342012-01-05 23:32:06 +00002385 b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
drh5b47efa2010-02-12 18:18:39 +00002386 sqlite3BtreeLeave(p);
2387 return b;
2388}
danielk1977576ec6b2005-01-21 11:55:25 +00002389#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
drh90f5ecb2004-07-22 01:19:35 +00002390
2391/*
danielk1977951af802004-11-05 15:45:09 +00002392** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
2393** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
2394** is disabled. The default value for the auto-vacuum property is
2395** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
2396*/
danielk1977aef0bf62005-12-30 16:28:01 +00002397int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
danielk1977951af802004-11-05 15:45:09 +00002398#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002399 return SQLITE_READONLY;
danielk1977951af802004-11-05 15:45:09 +00002400#else
danielk1977dddbcdc2007-04-26 14:42:34 +00002401 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00002402 int rc = SQLITE_OK;
drh076d4662009-02-18 20:31:18 +00002403 u8 av = (u8)autoVacuum;
drhd677b3d2007-08-20 22:48:41 +00002404
2405 sqlite3BtreeEnter(p);
drhc9166342012-01-05 23:32:06 +00002406 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00002407 rc = SQLITE_READONLY;
2408 }else{
drh076d4662009-02-18 20:31:18 +00002409 pBt->autoVacuum = av ?1:0;
2410 pBt->incrVacuum = av==2 ?1:0;
danielk1977951af802004-11-05 15:45:09 +00002411 }
drhd677b3d2007-08-20 22:48:41 +00002412 sqlite3BtreeLeave(p);
2413 return rc;
danielk1977951af802004-11-05 15:45:09 +00002414#endif
2415}
2416
2417/*
2418** Return the value of the 'auto-vacuum' property. If auto-vacuum is
2419** enabled 1 is returned. Otherwise 0.
2420*/
danielk1977aef0bf62005-12-30 16:28:01 +00002421int sqlite3BtreeGetAutoVacuum(Btree *p){
danielk1977951af802004-11-05 15:45:09 +00002422#ifdef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002423 return BTREE_AUTOVACUUM_NONE;
danielk1977951af802004-11-05 15:45:09 +00002424#else
drhd677b3d2007-08-20 22:48:41 +00002425 int rc;
2426 sqlite3BtreeEnter(p);
2427 rc = (
danielk1977dddbcdc2007-04-26 14:42:34 +00002428 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
2429 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
2430 BTREE_AUTOVACUUM_INCR
2431 );
drhd677b3d2007-08-20 22:48:41 +00002432 sqlite3BtreeLeave(p);
2433 return rc;
danielk1977951af802004-11-05 15:45:09 +00002434#endif
2435}
2436
2437
2438/*
drha34b6762004-05-07 13:30:42 +00002439** Get a reference to pPage1 of the database file. This will
drh306dc212001-05-21 13:45:10 +00002440** also acquire a readlock on that file.
2441**
2442** SQLITE_OK is returned on success. If the file is not a
2443** well-formed database file, then SQLITE_CORRUPT is returned.
2444** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
drh4f0ee682007-03-30 20:43:40 +00002445** is returned if we run out of memory.
drh306dc212001-05-21 13:45:10 +00002446*/
danielk1977aef0bf62005-12-30 16:28:01 +00002447static int lockBtree(BtShared *pBt){
drhc2a4bab2010-04-02 12:46:45 +00002448 int rc; /* Result code from subfunctions */
2449 MemPage *pPage1; /* Page 1 of the database file */
2450 int nPage; /* Number of pages in the database */
2451 int nPageFile = 0; /* Number of pages in the database file */
2452 int nPageHeader; /* Number of pages in the database according to hdr */
drhd677b3d2007-08-20 22:48:41 +00002453
drh1fee73e2007-08-29 04:00:57 +00002454 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977295dc102009-04-01 19:07:03 +00002455 assert( pBt->pPage1==0 );
danielk197789bc4bc2009-07-21 19:25:24 +00002456 rc = sqlite3PagerSharedLock(pBt->pPager);
2457 if( rc!=SQLITE_OK ) return rc;
drhb00fc3b2013-08-21 23:42:32 +00002458 rc = btreeGetPage(pBt, 1, &pPage1, 0);
drh306dc212001-05-21 13:45:10 +00002459 if( rc!=SQLITE_OK ) return rc;
drh306dc212001-05-21 13:45:10 +00002460
2461 /* Do some checking to help insure the file we opened really is
2462 ** a valid database file.
2463 */
drhc2a4bab2010-04-02 12:46:45 +00002464 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
drh8fb8b532010-08-14 17:12:04 +00002465 sqlite3PagerPagecount(pBt->pPager, &nPageFile);
drhb28e59b2010-06-17 02:13:39 +00002466 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
drhc2a4bab2010-04-02 12:46:45 +00002467 nPage = nPageFile;
drh97b59a52010-03-31 02:31:33 +00002468 }
2469 if( nPage>0 ){
drh43b18e12010-08-17 19:40:08 +00002470 u32 pageSize;
2471 u32 usableSize;
drhb6f41482004-05-14 01:58:11 +00002472 u8 *page1 = pPage1->aData;
danielk1977ad0132d2008-06-07 08:58:22 +00002473 rc = SQLITE_NOTADB;
drhb6f41482004-05-14 01:58:11 +00002474 if( memcmp(page1, zMagicHeader, 16)!=0 ){
drh72f82862001-05-24 21:06:34 +00002475 goto page1_init_failed;
drh306dc212001-05-21 13:45:10 +00002476 }
dan5cf53532010-05-01 16:40:20 +00002477
2478#ifdef SQLITE_OMIT_WAL
2479 if( page1[18]>1 ){
drhc9166342012-01-05 23:32:06 +00002480 pBt->btsFlags |= BTS_READ_ONLY;
dan5cf53532010-05-01 16:40:20 +00002481 }
2482 if( page1[19]>1 ){
2483 goto page1_init_failed;
2484 }
2485#else
dane04dc882010-04-20 18:53:15 +00002486 if( page1[18]>2 ){
drhc9166342012-01-05 23:32:06 +00002487 pBt->btsFlags |= BTS_READ_ONLY;
drh309169a2007-04-24 17:27:51 +00002488 }
dane04dc882010-04-20 18:53:15 +00002489 if( page1[19]>2 ){
drhb6f41482004-05-14 01:58:11 +00002490 goto page1_init_failed;
2491 }
drhe5ae5732008-06-15 02:51:47 +00002492
dana470aeb2010-04-21 11:43:38 +00002493 /* If the write version is set to 2, this database should be accessed
2494 ** in WAL mode. If the log is not already open, open it now. Then
2495 ** return SQLITE_OK and return without populating BtShared.pPage1.
2496 ** The caller detects this and calls this function again. This is
2497 ** required as the version of page 1 currently in the page1 buffer
2498 ** may not be the latest version - there may be a newer one in the log
2499 ** file.
2500 */
drhc9166342012-01-05 23:32:06 +00002501 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
dane04dc882010-04-20 18:53:15 +00002502 int isOpen = 0;
drh7ed91f22010-04-29 22:34:07 +00002503 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
dane04dc882010-04-20 18:53:15 +00002504 if( rc!=SQLITE_OK ){
2505 goto page1_init_failed;
2506 }else if( isOpen==0 ){
2507 releasePage(pPage1);
2508 return SQLITE_OK;
2509 }
dan8b5444b2010-04-27 14:37:47 +00002510 rc = SQLITE_NOTADB;
dane04dc882010-04-20 18:53:15 +00002511 }
dan5cf53532010-05-01 16:40:20 +00002512#endif
dane04dc882010-04-20 18:53:15 +00002513
drhe5ae5732008-06-15 02:51:47 +00002514 /* The maximum embedded fraction must be exactly 25%. And the minimum
2515 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
2516 ** The original design allowed these amounts to vary, but as of
2517 ** version 3.6.0, we require them to be fixed.
2518 */
2519 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
2520 goto page1_init_failed;
2521 }
drhb2eced52010-08-12 02:41:12 +00002522 pageSize = (page1[16]<<8) | (page1[17]<<16);
2523 if( ((pageSize-1)&pageSize)!=0
2524 || pageSize>SQLITE_MAX_PAGE_SIZE
2525 || pageSize<=256
drh7dc385e2007-09-06 23:39:36 +00002526 ){
drh07d183d2005-05-01 22:52:42 +00002527 goto page1_init_failed;
2528 }
2529 assert( (pageSize & 7)==0 );
danielk1977f653d782008-03-20 11:04:21 +00002530 usableSize = pageSize - page1[20];
shaneh1df2db72010-08-18 02:28:48 +00002531 if( (u32)pageSize!=pBt->pageSize ){
danielk1977f653d782008-03-20 11:04:21 +00002532 /* After reading the first page of the database assuming a page size
2533 ** of BtShared.pageSize, we have discovered that the page-size is
2534 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
2535 ** zero and return SQLITE_OK. The caller will call this function
2536 ** again with the correct page-size.
2537 */
2538 releasePage(pPage1);
drh43b18e12010-08-17 19:40:08 +00002539 pBt->usableSize = usableSize;
2540 pBt->pageSize = pageSize;
drhf7141992008-06-19 00:16:08 +00002541 freeTempSpace(pBt);
drhfa9601a2009-06-18 17:22:39 +00002542 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
2543 pageSize-usableSize);
drh5e483932009-07-10 16:51:30 +00002544 return rc;
danielk1977f653d782008-03-20 11:04:21 +00002545 }
danecac6702011-02-09 18:19:20 +00002546 if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
drhc2a4bab2010-04-02 12:46:45 +00002547 rc = SQLITE_CORRUPT_BKPT;
2548 goto page1_init_failed;
2549 }
drhb33e1b92009-06-18 11:29:20 +00002550 if( usableSize<480 ){
drhb6f41482004-05-14 01:58:11 +00002551 goto page1_init_failed;
2552 }
drh43b18e12010-08-17 19:40:08 +00002553 pBt->pageSize = pageSize;
2554 pBt->usableSize = usableSize;
drh057cd3a2005-02-15 16:23:02 +00002555#ifndef SQLITE_OMIT_AUTOVACUUM
2556 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
danielk197727b1f952007-06-25 08:16:58 +00002557 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
drh057cd3a2005-02-15 16:23:02 +00002558#endif
drh306dc212001-05-21 13:45:10 +00002559 }
drhb6f41482004-05-14 01:58:11 +00002560
2561 /* maxLocal is the maximum amount of payload to store locally for
2562 ** a cell. Make sure it is small enough so that at least minFanout
2563 ** cells can will fit on one page. We assume a 10-byte page header.
2564 ** Besides the payload, the cell must store:
drh43605152004-05-29 21:46:49 +00002565 ** 2-byte pointer to the cell
drhb6f41482004-05-14 01:58:11 +00002566 ** 4-byte child pointer
2567 ** 9-byte nKey value
2568 ** 4-byte nData value
2569 ** 4-byte overflow page pointer
drhe22e03e2010-08-18 21:19:03 +00002570 ** So a cell consists of a 2-byte pointer, a header which is as much as
drh43605152004-05-29 21:46:49 +00002571 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
2572 ** page pointer.
drhb6f41482004-05-14 01:58:11 +00002573 */
shaneh1df2db72010-08-18 02:28:48 +00002574 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
2575 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
2576 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
2577 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
drhc9166342012-01-05 23:32:06 +00002578 if( pBt->maxLocal>127 ){
2579 pBt->max1bytePayload = 127;
2580 }else{
mistachkin0547e2f2012-01-08 00:54:02 +00002581 pBt->max1bytePayload = (u8)pBt->maxLocal;
drhc9166342012-01-05 23:32:06 +00002582 }
drh2e38c322004-09-03 18:38:44 +00002583 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
drh3aac2dd2004-04-26 14:10:20 +00002584 pBt->pPage1 = pPage1;
drhdd3cd972010-03-27 17:12:36 +00002585 pBt->nPage = nPage;
drhb6f41482004-05-14 01:58:11 +00002586 return SQLITE_OK;
drh306dc212001-05-21 13:45:10 +00002587
drh72f82862001-05-24 21:06:34 +00002588page1_init_failed:
drh3aac2dd2004-04-26 14:10:20 +00002589 releasePage(pPage1);
2590 pBt->pPage1 = 0;
drh72f82862001-05-24 21:06:34 +00002591 return rc;
drh306dc212001-05-21 13:45:10 +00002592}
2593
drh85ec3b62013-05-14 23:12:06 +00002594#ifndef NDEBUG
2595/*
2596** Return the number of cursors open on pBt. This is for use
2597** in assert() expressions, so it is only compiled if NDEBUG is not
2598** defined.
2599**
2600** Only write cursors are counted if wrOnly is true. If wrOnly is
2601** false then all cursors are counted.
2602**
2603** For the purposes of this routine, a cursor is any cursor that
peter.d.reid60ec9142014-09-06 16:39:46 +00002604** is capable of reading or writing to the database. Cursors that
drh85ec3b62013-05-14 23:12:06 +00002605** have been tripped into the CURSOR_FAULT state are not counted.
2606*/
2607static int countValidCursors(BtShared *pBt, int wrOnly){
2608 BtCursor *pCur;
2609 int r = 0;
2610 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
drh036dbec2014-03-11 23:40:44 +00002611 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
2612 && pCur->eState!=CURSOR_FAULT ) r++;
drh85ec3b62013-05-14 23:12:06 +00002613 }
2614 return r;
2615}
2616#endif
2617
drh306dc212001-05-21 13:45:10 +00002618/*
drhb8ca3072001-12-05 00:21:20 +00002619** If there are no outstanding cursors and we are not in the middle
2620** of a transaction but there is a read lock on the database, then
2621** this routine unrefs the first page of the database file which
2622** has the effect of releasing the read lock.
2623**
drhb8ca3072001-12-05 00:21:20 +00002624** If there is a transaction in progress, this routine is a no-op.
2625*/
danielk1977aef0bf62005-12-30 16:28:01 +00002626static void unlockBtreeIfUnused(BtShared *pBt){
drh1fee73e2007-08-29 04:00:57 +00002627 assert( sqlite3_mutex_held(pBt->mutex) );
drh85ec3b62013-05-14 23:12:06 +00002628 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
danielk19771bc9ee92009-07-04 15:41:02 +00002629 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
danielk1977c1761e82009-06-25 09:40:03 +00002630 assert( pBt->pPage1->aData );
2631 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
2632 assert( pBt->pPage1->aData );
2633 releasePage(pBt->pPage1);
drh3aac2dd2004-04-26 14:10:20 +00002634 pBt->pPage1 = 0;
drhb8ca3072001-12-05 00:21:20 +00002635 }
2636}
2637
2638/*
drhe39f2f92009-07-23 01:43:59 +00002639** If pBt points to an empty file then convert that empty file
2640** into a new empty database by initializing the first page of
2641** the database.
drh8b2f49b2001-06-08 00:21:52 +00002642*/
danielk1977aef0bf62005-12-30 16:28:01 +00002643static int newDatabase(BtShared *pBt){
drh9e572e62004-04-23 23:43:10 +00002644 MemPage *pP1;
2645 unsigned char *data;
drh8c42ca92001-06-22 19:15:00 +00002646 int rc;
drhd677b3d2007-08-20 22:48:41 +00002647
drh1fee73e2007-08-29 04:00:57 +00002648 assert( sqlite3_mutex_held(pBt->mutex) );
drhdd3cd972010-03-27 17:12:36 +00002649 if( pBt->nPage>0 ){
2650 return SQLITE_OK;
danielk1977ad0132d2008-06-07 08:58:22 +00002651 }
drh3aac2dd2004-04-26 14:10:20 +00002652 pP1 = pBt->pPage1;
drh9e572e62004-04-23 23:43:10 +00002653 assert( pP1!=0 );
2654 data = pP1->aData;
danielk19773b8a05f2007-03-19 17:44:26 +00002655 rc = sqlite3PagerWrite(pP1->pDbPage);
drh8b2f49b2001-06-08 00:21:52 +00002656 if( rc ) return rc;
drh9e572e62004-04-23 23:43:10 +00002657 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
2658 assert( sizeof(zMagicHeader)==16 );
shaneh1df2db72010-08-18 02:28:48 +00002659 data[16] = (u8)((pBt->pageSize>>8)&0xff);
2660 data[17] = (u8)((pBt->pageSize>>16)&0xff);
drh9e572e62004-04-23 23:43:10 +00002661 data[18] = 1;
2662 data[19] = 1;
drhf49661a2008-12-10 16:45:50 +00002663 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
2664 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
drhe5ae5732008-06-15 02:51:47 +00002665 data[21] = 64;
2666 data[22] = 32;
2667 data[23] = 32;
drhb6f41482004-05-14 01:58:11 +00002668 memset(&data[24], 0, 100-24);
drhe6c43812004-05-14 12:17:46 +00002669 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
drhc9166342012-01-05 23:32:06 +00002670 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
danielk1977003ba062004-11-04 02:57:33 +00002671#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977dddbcdc2007-04-26 14:42:34 +00002672 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
danielk1977418899a2007-06-24 10:14:00 +00002673 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
danielk1977dddbcdc2007-04-26 14:42:34 +00002674 put4byte(&data[36 + 4*4], pBt->autoVacuum);
danielk1977418899a2007-06-24 10:14:00 +00002675 put4byte(&data[36 + 7*4], pBt->incrVacuum);
danielk1977003ba062004-11-04 02:57:33 +00002676#endif
drhdd3cd972010-03-27 17:12:36 +00002677 pBt->nPage = 1;
2678 data[31] = 1;
drh8b2f49b2001-06-08 00:21:52 +00002679 return SQLITE_OK;
2680}
2681
2682/*
danb483eba2012-10-13 19:58:11 +00002683** Initialize the first page of the database file (creating a database
2684** consisting of a single page and no schema objects). Return SQLITE_OK
2685** if successful, or an SQLite error code otherwise.
2686*/
2687int sqlite3BtreeNewDb(Btree *p){
2688 int rc;
2689 sqlite3BtreeEnter(p);
2690 p->pBt->nPage = 0;
2691 rc = newDatabase(p->pBt);
2692 sqlite3BtreeLeave(p);
2693 return rc;
2694}
2695
2696/*
danielk1977ee5741e2004-05-31 10:01:34 +00002697** Attempt to start a new transaction. A write-transaction
drh684917c2004-10-05 02:41:42 +00002698** is started if the second argument is nonzero, otherwise a read-
2699** transaction. If the second argument is 2 or more and exclusive
2700** transaction is started, meaning that no other process is allowed
2701** to access the database. A preexisting transaction may not be
drhb8ef32c2005-03-14 02:01:49 +00002702** upgraded to exclusive by calling this routine a second time - the
drh684917c2004-10-05 02:41:42 +00002703** exclusivity flag only works for a new transaction.
drh8b2f49b2001-06-08 00:21:52 +00002704**
danielk1977ee5741e2004-05-31 10:01:34 +00002705** A write-transaction must be started before attempting any
2706** changes to the database. None of the following routines
2707** will work unless a transaction is started first:
drh8b2f49b2001-06-08 00:21:52 +00002708**
drh23e11ca2004-05-04 17:27:28 +00002709** sqlite3BtreeCreateTable()
2710** sqlite3BtreeCreateIndex()
2711** sqlite3BtreeClearTable()
2712** sqlite3BtreeDropTable()
2713** sqlite3BtreeInsert()
2714** sqlite3BtreeDelete()
2715** sqlite3BtreeUpdateMeta()
danielk197713adf8a2004-06-03 16:08:41 +00002716**
drhb8ef32c2005-03-14 02:01:49 +00002717** If an initial attempt to acquire the lock fails because of lock contention
2718** and the database was previously unlocked, then invoke the busy handler
2719** if there is one. But if there was previously a read-lock, do not
2720** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
2721** returned when there is already a read-lock in order to avoid a deadlock.
2722**
2723** Suppose there are two processes A and B. A has a read lock and B has
2724** a reserved lock. B tries to promote to exclusive but is blocked because
2725** of A's read lock. A tries to promote to reserved but is blocked by B.
2726** One or the other of the two processes must give way or there can be
2727** no progress. By returning SQLITE_BUSY and not invoking the busy callback
2728** when A already has a read lock, we encourage A to give up and let B
2729** proceed.
drha059ad02001-04-17 20:09:11 +00002730*/
danielk1977aef0bf62005-12-30 16:28:01 +00002731int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
danielk1977404ca072009-03-16 13:19:36 +00002732 sqlite3 *pBlock = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00002733 BtShared *pBt = p->pBt;
danielk1977ee5741e2004-05-31 10:01:34 +00002734 int rc = SQLITE_OK;
2735
drhd677b3d2007-08-20 22:48:41 +00002736 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00002737 btreeIntegrity(p);
2738
danielk1977ee5741e2004-05-31 10:01:34 +00002739 /* If the btree is already in a write-transaction, or it
2740 ** is already in a read-transaction and a read-transaction
2741 ** is requested, this is a no-op.
2742 */
danielk1977aef0bf62005-12-30 16:28:01 +00002743 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
drhd677b3d2007-08-20 22:48:41 +00002744 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002745 }
dan56c517a2013-09-26 11:04:33 +00002746 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
drhb8ef32c2005-03-14 02:01:49 +00002747
2748 /* Write transactions are not possible on a read-only database */
drhc9166342012-01-05 23:32:06 +00002749 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
drhd677b3d2007-08-20 22:48:41 +00002750 rc = SQLITE_READONLY;
2751 goto trans_begun;
danielk1977ee5741e2004-05-31 10:01:34 +00002752 }
2753
danielk1977404ca072009-03-16 13:19:36 +00002754#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977aef0bf62005-12-30 16:28:01 +00002755 /* If another database handle has already opened a write transaction
2756 ** on this shared-btree structure and a second write transaction is
danielk1977404ca072009-03-16 13:19:36 +00002757 ** requested, return SQLITE_LOCKED.
danielk1977aef0bf62005-12-30 16:28:01 +00002758 */
drhc9166342012-01-05 23:32:06 +00002759 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
2760 || (pBt->btsFlags & BTS_PENDING)!=0
2761 ){
danielk1977404ca072009-03-16 13:19:36 +00002762 pBlock = pBt->pWriter->db;
2763 }else if( wrflag>1 ){
danielk1977641b0f42007-12-21 04:47:25 +00002764 BtLock *pIter;
2765 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
2766 if( pIter->pBtree!=p ){
danielk1977404ca072009-03-16 13:19:36 +00002767 pBlock = pIter->pBtree->db;
2768 break;
danielk1977641b0f42007-12-21 04:47:25 +00002769 }
2770 }
2771 }
danielk1977404ca072009-03-16 13:19:36 +00002772 if( pBlock ){
2773 sqlite3ConnectionBlocked(p->db, pBlock);
2774 rc = SQLITE_LOCKED_SHAREDCACHE;
2775 goto trans_begun;
2776 }
danielk1977641b0f42007-12-21 04:47:25 +00002777#endif
2778
danielk1977602b4662009-07-02 07:47:33 +00002779 /* Any read-only or read-write transaction implies a read-lock on
2780 ** page 1. So if some other shared-cache client already has a write-lock
2781 ** on page 1, the transaction cannot be opened. */
drh4c301aa2009-07-15 17:25:45 +00002782 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
2783 if( SQLITE_OK!=rc ) goto trans_begun;
danielk1977602b4662009-07-02 07:47:33 +00002784
drhc9166342012-01-05 23:32:06 +00002785 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
2786 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
drhb8ef32c2005-03-14 02:01:49 +00002787 do {
danielk1977295dc102009-04-01 19:07:03 +00002788 /* Call lockBtree() until either pBt->pPage1 is populated or
2789 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
2790 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
2791 ** reading page 1 it discovers that the page-size of the database
2792 ** file is not pBt->pageSize. In this case lockBtree() will update
2793 ** pBt->pageSize to the page-size of the file on disk.
2794 */
2795 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
drh309169a2007-04-24 17:27:51 +00002796
drhb8ef32c2005-03-14 02:01:49 +00002797 if( rc==SQLITE_OK && wrflag ){
drhc9166342012-01-05 23:32:06 +00002798 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
drh309169a2007-04-24 17:27:51 +00002799 rc = SQLITE_READONLY;
2800 }else{
danielk1977d8293352009-04-30 09:10:37 +00002801 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
drh309169a2007-04-24 17:27:51 +00002802 if( rc==SQLITE_OK ){
2803 rc = newDatabase(pBt);
2804 }
drhb8ef32c2005-03-14 02:01:49 +00002805 }
2806 }
2807
danielk1977bd434552009-03-18 10:33:00 +00002808 if( rc!=SQLITE_OK ){
drhb8ef32c2005-03-14 02:01:49 +00002809 unlockBtreeIfUnused(pBt);
2810 }
danf9b76712010-06-01 14:12:45 +00002811 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
danielk19771ceedd32008-11-19 10:22:33 +00002812 btreeInvokeBusyHandler(pBt) );
danielk1977aef0bf62005-12-30 16:28:01 +00002813
2814 if( rc==SQLITE_OK ){
2815 if( p->inTrans==TRANS_NONE ){
2816 pBt->nTransaction++;
danielk1977602b4662009-07-02 07:47:33 +00002817#ifndef SQLITE_OMIT_SHARED_CACHE
2818 if( p->sharable ){
drhf2f105d2012-08-20 15:53:54 +00002819 assert( p->lock.pBtree==p && p->lock.iTable==1 );
danielk1977602b4662009-07-02 07:47:33 +00002820 p->lock.eLock = READ_LOCK;
2821 p->lock.pNext = pBt->pLock;
2822 pBt->pLock = &p->lock;
2823 }
2824#endif
danielk1977aef0bf62005-12-30 16:28:01 +00002825 }
2826 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
2827 if( p->inTrans>pBt->inTransaction ){
2828 pBt->inTransaction = p->inTrans;
2829 }
danielk1977404ca072009-03-16 13:19:36 +00002830 if( wrflag ){
dan59257dc2010-08-04 11:34:31 +00002831 MemPage *pPage1 = pBt->pPage1;
2832#ifndef SQLITE_OMIT_SHARED_CACHE
danielk1977404ca072009-03-16 13:19:36 +00002833 assert( !pBt->pWriter );
2834 pBt->pWriter = p;
drhc9166342012-01-05 23:32:06 +00002835 pBt->btsFlags &= ~BTS_EXCLUSIVE;
2836 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
danielk1977641b0f42007-12-21 04:47:25 +00002837#endif
dan59257dc2010-08-04 11:34:31 +00002838
2839 /* If the db-size header field is incorrect (as it may be if an old
2840 ** client has been writing the database file), update it now. Doing
2841 ** this sooner rather than later means the database size can safely
2842 ** re-read the database size from page 1 if a savepoint or transaction
2843 ** rollback occurs within the transaction.
2844 */
2845 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
2846 rc = sqlite3PagerWrite(pPage1->pDbPage);
2847 if( rc==SQLITE_OK ){
2848 put4byte(&pPage1->aData[28], pBt->nPage);
2849 }
2850 }
2851 }
danielk1977aef0bf62005-12-30 16:28:01 +00002852 }
2853
drhd677b3d2007-08-20 22:48:41 +00002854
2855trans_begun:
danielk1977fd7f0452008-12-17 17:30:26 +00002856 if( rc==SQLITE_OK && wrflag ){
danielk197712dd5492008-12-18 15:45:07 +00002857 /* This call makes sure that the pager has the correct number of
2858 ** open savepoints. If the second parameter is greater than 0 and
2859 ** the sub-journal is not already open, then it will be opened here.
2860 */
danielk1977fd7f0452008-12-17 17:30:26 +00002861 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
2862 }
danielk197712dd5492008-12-18 15:45:07 +00002863
danielk1977aef0bf62005-12-30 16:28:01 +00002864 btreeIntegrity(p);
drhd677b3d2007-08-20 22:48:41 +00002865 sqlite3BtreeLeave(p);
drhb8ca3072001-12-05 00:21:20 +00002866 return rc;
drha059ad02001-04-17 20:09:11 +00002867}
2868
danielk1977687566d2004-11-02 12:56:41 +00002869#ifndef SQLITE_OMIT_AUTOVACUUM
2870
2871/*
2872** Set the pointer-map entries for all children of page pPage. Also, if
2873** pPage contains cells that point to overflow pages, set the pointer
2874** map entries for the overflow pages as well.
2875*/
2876static int setChildPtrmaps(MemPage *pPage){
2877 int i; /* Counter variable */
2878 int nCell; /* Number of cells in page pPage */
danielk19772df71c72007-05-24 07:22:42 +00002879 int rc; /* Return code */
danielk1977aef0bf62005-12-30 16:28:01 +00002880 BtShared *pBt = pPage->pBt;
drhf49661a2008-12-10 16:45:50 +00002881 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002882 Pgno pgno = pPage->pgno;
2883
drh1fee73e2007-08-29 04:00:57 +00002884 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197730548662009-07-09 05:07:37 +00002885 rc = btreeInitPage(pPage);
danielk19772df71c72007-05-24 07:22:42 +00002886 if( rc!=SQLITE_OK ){
2887 goto set_child_ptrmaps_out;
2888 }
danielk1977687566d2004-11-02 12:56:41 +00002889 nCell = pPage->nCell;
2890
2891 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002892 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002893
drh98add2e2009-07-20 17:11:49 +00002894 ptrmapPutOvflPtr(pPage, pCell, &rc);
danielk197726836652005-01-17 01:33:13 +00002895
danielk1977687566d2004-11-02 12:56:41 +00002896 if( !pPage->leaf ){
2897 Pgno childPgno = get4byte(pCell);
drh98add2e2009-07-20 17:11:49 +00002898 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00002899 }
2900 }
2901
2902 if( !pPage->leaf ){
2903 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh98add2e2009-07-20 17:11:49 +00002904 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
danielk1977687566d2004-11-02 12:56:41 +00002905 }
2906
2907set_child_ptrmaps_out:
2908 pPage->isInit = isInitOrig;
2909 return rc;
2910}
2911
2912/*
drhf3aed592009-07-08 18:12:49 +00002913** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
2914** that it points to iTo. Parameter eType describes the type of pointer to
2915** be modified, as follows:
danielk1977687566d2004-11-02 12:56:41 +00002916**
2917** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
2918** page of pPage.
2919**
2920** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
2921** page pointed to by one of the cells on pPage.
2922**
2923** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
2924** overflow page in the list.
2925*/
danielk1977fdb7cdb2005-01-17 02:12:18 +00002926static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
drh1fee73e2007-08-29 04:00:57 +00002927 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc5053fb2008-11-27 02:22:10 +00002928 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977687566d2004-11-02 12:56:41 +00002929 if( eType==PTRMAP_OVERFLOW2 ){
danielk1977f78fc082004-11-02 14:40:32 +00002930 /* The pointer is always the first 4 bytes of the page in this case. */
danielk1977fdb7cdb2005-01-17 02:12:18 +00002931 if( get4byte(pPage->aData)!=iFrom ){
drh49285702005-09-17 15:20:26 +00002932 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002933 }
danielk1977f78fc082004-11-02 14:40:32 +00002934 put4byte(pPage->aData, iTo);
danielk1977687566d2004-11-02 12:56:41 +00002935 }else{
drhf49661a2008-12-10 16:45:50 +00002936 u8 isInitOrig = pPage->isInit;
danielk1977687566d2004-11-02 12:56:41 +00002937 int i;
2938 int nCell;
2939
danielk197730548662009-07-09 05:07:37 +00002940 btreeInitPage(pPage);
danielk1977687566d2004-11-02 12:56:41 +00002941 nCell = pPage->nCell;
2942
danielk1977687566d2004-11-02 12:56:41 +00002943 for(i=0; i<nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00002944 u8 *pCell = findCell(pPage, i);
danielk1977687566d2004-11-02 12:56:41 +00002945 if( eType==PTRMAP_OVERFLOW1 ){
2946 CellInfo info;
danielk197730548662009-07-09 05:07:37 +00002947 btreeParseCellPtr(pPage, pCell, &info);
drhe42a9b42011-08-31 13:27:19 +00002948 if( info.iOverflow
2949 && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
2950 && iFrom==get4byte(&pCell[info.iOverflow])
2951 ){
2952 put4byte(&pCell[info.iOverflow], iTo);
2953 break;
danielk1977687566d2004-11-02 12:56:41 +00002954 }
2955 }else{
2956 if( get4byte(pCell)==iFrom ){
2957 put4byte(pCell, iTo);
2958 break;
2959 }
2960 }
2961 }
2962
2963 if( i==nCell ){
danielk1977fdb7cdb2005-01-17 02:12:18 +00002964 if( eType!=PTRMAP_BTREE ||
2965 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
drh49285702005-09-17 15:20:26 +00002966 return SQLITE_CORRUPT_BKPT;
danielk1977fdb7cdb2005-01-17 02:12:18 +00002967 }
danielk1977687566d2004-11-02 12:56:41 +00002968 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
2969 }
2970
2971 pPage->isInit = isInitOrig;
2972 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00002973 return SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00002974}
2975
danielk1977003ba062004-11-04 02:57:33 +00002976
danielk19777701e812005-01-10 12:59:51 +00002977/*
2978** Move the open database page pDbPage to location iFreePage in the
2979** database. The pDbPage reference remains valid.
drhe64ca7b2009-07-16 18:21:17 +00002980**
2981** The isCommit flag indicates that there is no need to remember that
2982** the journal needs to be sync()ed before database page pDbPage->pgno
2983** can be written to. The caller has already promised not to write to that
2984** page.
danielk19777701e812005-01-10 12:59:51 +00002985*/
danielk1977003ba062004-11-04 02:57:33 +00002986static int relocatePage(
danielk1977aef0bf62005-12-30 16:28:01 +00002987 BtShared *pBt, /* Btree */
danielk19777701e812005-01-10 12:59:51 +00002988 MemPage *pDbPage, /* Open page to move */
2989 u8 eType, /* Pointer map 'type' entry for pDbPage */
2990 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
danielk19774c999992008-07-16 18:17:55 +00002991 Pgno iFreePage, /* The location to move pDbPage to */
drhe64ca7b2009-07-16 18:21:17 +00002992 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
danielk1977003ba062004-11-04 02:57:33 +00002993){
2994 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
2995 Pgno iDbPage = pDbPage->pgno;
2996 Pager *pPager = pBt->pPager;
2997 int rc;
2998
danielk1977a0bf2652004-11-04 14:30:04 +00002999 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3000 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
drh1fee73e2007-08-29 04:00:57 +00003001 assert( sqlite3_mutex_held(pBt->mutex) );
drhd0679ed2007-08-28 22:24:34 +00003002 assert( pDbPage->pBt==pBt );
danielk1977003ba062004-11-04 02:57:33 +00003003
drh85b623f2007-12-13 21:54:09 +00003004 /* Move page iDbPage from its current location to page number iFreePage */
danielk1977003ba062004-11-04 02:57:33 +00003005 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
3006 iDbPage, iFreePage, iPtrPage, eType));
danielk19774c999992008-07-16 18:17:55 +00003007 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
danielk1977003ba062004-11-04 02:57:33 +00003008 if( rc!=SQLITE_OK ){
3009 return rc;
3010 }
3011 pDbPage->pgno = iFreePage;
3012
3013 /* If pDbPage was a btree-page, then it may have child pages and/or cells
3014 ** that point to overflow pages. The pointer map entries for all these
3015 ** pages need to be changed.
3016 **
3017 ** If pDbPage is an overflow page, then the first 4 bytes may store a
3018 ** pointer to a subsequent overflow page. If this is the case, then
3019 ** the pointer map needs to be updated for the subsequent overflow page.
3020 */
danielk1977a0bf2652004-11-04 14:30:04 +00003021 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
danielk1977003ba062004-11-04 02:57:33 +00003022 rc = setChildPtrmaps(pDbPage);
3023 if( rc!=SQLITE_OK ){
3024 return rc;
3025 }
3026 }else{
3027 Pgno nextOvfl = get4byte(pDbPage->aData);
3028 if( nextOvfl!=0 ){
drh98add2e2009-07-20 17:11:49 +00003029 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
danielk1977003ba062004-11-04 02:57:33 +00003030 if( rc!=SQLITE_OK ){
3031 return rc;
3032 }
3033 }
3034 }
3035
3036 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
3037 ** that it points at iFreePage. Also fix the pointer map entry for
3038 ** iPtrPage.
3039 */
danielk1977a0bf2652004-11-04 14:30:04 +00003040 if( eType!=PTRMAP_ROOTPAGE ){
drhb00fc3b2013-08-21 23:42:32 +00003041 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00003042 if( rc!=SQLITE_OK ){
3043 return rc;
3044 }
danielk19773b8a05f2007-03-19 17:44:26 +00003045 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
danielk1977a0bf2652004-11-04 14:30:04 +00003046 if( rc!=SQLITE_OK ){
3047 releasePage(pPtrPage);
3048 return rc;
3049 }
danielk1977fdb7cdb2005-01-17 02:12:18 +00003050 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
danielk1977003ba062004-11-04 02:57:33 +00003051 releasePage(pPtrPage);
danielk1977fdb7cdb2005-01-17 02:12:18 +00003052 if( rc==SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +00003053 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
danielk1977fdb7cdb2005-01-17 02:12:18 +00003054 }
danielk1977003ba062004-11-04 02:57:33 +00003055 }
danielk1977003ba062004-11-04 02:57:33 +00003056 return rc;
3057}
3058
danielk1977dddbcdc2007-04-26 14:42:34 +00003059/* Forward declaration required by incrVacuumStep(). */
drh4f0c5872007-03-26 22:05:01 +00003060static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
danielk1977687566d2004-11-02 12:56:41 +00003061
3062/*
dan51f0b6d2013-02-22 20:16:34 +00003063** Perform a single step of an incremental-vacuum. If successful, return
3064** SQLITE_OK. If there is no work to do (and therefore no point in
3065** calling this function again), return SQLITE_DONE. Or, if an error
3066** occurs, return some other error code.
danielk1977dddbcdc2007-04-26 14:42:34 +00003067**
peter.d.reid60ec9142014-09-06 16:39:46 +00003068** More specifically, this function attempts to re-organize the database so
dan51f0b6d2013-02-22 20:16:34 +00003069** that the last page of the file currently in use is no longer in use.
danielk1977dddbcdc2007-04-26 14:42:34 +00003070**
dan51f0b6d2013-02-22 20:16:34 +00003071** Parameter nFin is the number of pages that this database would contain
3072** were this function called until it returns SQLITE_DONE.
3073**
3074** If the bCommit parameter is non-zero, this function assumes that the
3075** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
peter.d.reid60ec9142014-09-06 16:39:46 +00003076** or an error. bCommit is passed true for an auto-vacuum-on-commit
dan51f0b6d2013-02-22 20:16:34 +00003077** operation, or false for an incremental vacuum.
danielk1977dddbcdc2007-04-26 14:42:34 +00003078*/
dan51f0b6d2013-02-22 20:16:34 +00003079static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
danielk1977dddbcdc2007-04-26 14:42:34 +00003080 Pgno nFreeList; /* Number of pages still on the free-list */
drhdd3cd972010-03-27 17:12:36 +00003081 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003082
drh1fee73e2007-08-29 04:00:57 +00003083 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977fa542f12009-04-02 18:28:08 +00003084 assert( iLastPg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00003085
3086 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003087 u8 eType;
3088 Pgno iPtrPage;
3089
3090 nFreeList = get4byte(&pBt->pPage1->aData[36]);
danielk1977fa542f12009-04-02 18:28:08 +00003091 if( nFreeList==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003092 return SQLITE_DONE;
3093 }
3094
3095 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
3096 if( rc!=SQLITE_OK ){
3097 return rc;
3098 }
3099 if( eType==PTRMAP_ROOTPAGE ){
3100 return SQLITE_CORRUPT_BKPT;
3101 }
3102
3103 if( eType==PTRMAP_FREEPAGE ){
dan51f0b6d2013-02-22 20:16:34 +00003104 if( bCommit==0 ){
danielk1977dddbcdc2007-04-26 14:42:34 +00003105 /* Remove the page from the files free-list. This is not required
dan51f0b6d2013-02-22 20:16:34 +00003106 ** if bCommit is non-zero. In that case, the free-list will be
danielk1977dddbcdc2007-04-26 14:42:34 +00003107 ** truncated to zero after this function returns, so it doesn't
3108 ** matter if it still contains some garbage entries.
3109 */
3110 Pgno iFreePg;
3111 MemPage *pFreePg;
dan51f0b6d2013-02-22 20:16:34 +00003112 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
danielk1977dddbcdc2007-04-26 14:42:34 +00003113 if( rc!=SQLITE_OK ){
3114 return rc;
3115 }
3116 assert( iFreePg==iLastPg );
3117 releasePage(pFreePg);
3118 }
3119 } else {
3120 Pgno iFreePg; /* Index of free page to move pLastPg to */
3121 MemPage *pLastPg;
dan51f0b6d2013-02-22 20:16:34 +00003122 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
3123 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
danielk1977dddbcdc2007-04-26 14:42:34 +00003124
drhb00fc3b2013-08-21 23:42:32 +00003125 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
danielk1977dddbcdc2007-04-26 14:42:34 +00003126 if( rc!=SQLITE_OK ){
3127 return rc;
3128 }
3129
dan51f0b6d2013-02-22 20:16:34 +00003130 /* If bCommit is zero, this loop runs exactly once and page pLastPg
danielk1977b4626a32007-04-28 15:47:43 +00003131 ** is swapped with the first free page pulled off the free list.
3132 **
dan51f0b6d2013-02-22 20:16:34 +00003133 ** On the other hand, if bCommit is greater than zero, then keep
danielk1977b4626a32007-04-28 15:47:43 +00003134 ** looping until a free-page located within the first nFin pages
3135 ** of the file is found.
3136 */
dan51f0b6d2013-02-22 20:16:34 +00003137 if( bCommit==0 ){
3138 eMode = BTALLOC_LE;
3139 iNear = nFin;
3140 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003141 do {
3142 MemPage *pFreePg;
dan51f0b6d2013-02-22 20:16:34 +00003143 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
danielk1977dddbcdc2007-04-26 14:42:34 +00003144 if( rc!=SQLITE_OK ){
3145 releasePage(pLastPg);
3146 return rc;
3147 }
3148 releasePage(pFreePg);
dan51f0b6d2013-02-22 20:16:34 +00003149 }while( bCommit && iFreePg>nFin );
danielk1977dddbcdc2007-04-26 14:42:34 +00003150 assert( iFreePg<iLastPg );
danielk1977b4626a32007-04-28 15:47:43 +00003151
dane1df4e32013-03-05 11:27:04 +00003152 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
danielk1977dddbcdc2007-04-26 14:42:34 +00003153 releasePage(pLastPg);
3154 if( rc!=SQLITE_OK ){
3155 return rc;
danielk1977662278e2007-11-05 15:30:12 +00003156 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003157 }
3158 }
3159
dan51f0b6d2013-02-22 20:16:34 +00003160 if( bCommit==0 ){
danbc1a3c62013-02-23 16:40:46 +00003161 do {
danielk19773460d192008-12-27 15:23:13 +00003162 iLastPg--;
danbc1a3c62013-02-23 16:40:46 +00003163 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
3164 pBt->bDoTruncate = 1;
drhdd3cd972010-03-27 17:12:36 +00003165 pBt->nPage = iLastPg;
danielk1977dddbcdc2007-04-26 14:42:34 +00003166 }
3167 return SQLITE_OK;
3168}
3169
3170/*
dan51f0b6d2013-02-22 20:16:34 +00003171** The database opened by the first argument is an auto-vacuum database
3172** nOrig pages in size containing nFree free pages. Return the expected
3173** size of the database in pages following an auto-vacuum operation.
3174*/
3175static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
3176 int nEntry; /* Number of entries on one ptrmap page */
3177 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
3178 Pgno nFin; /* Return value */
3179
3180 nEntry = pBt->usableSize/5;
3181 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
3182 nFin = nOrig - nFree - nPtrmap;
3183 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
3184 nFin--;
3185 }
3186 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
3187 nFin--;
3188 }
dan51f0b6d2013-02-22 20:16:34 +00003189
3190 return nFin;
3191}
3192
3193/*
danielk1977dddbcdc2007-04-26 14:42:34 +00003194** A write-transaction must be opened before calling this function.
3195** It performs a single unit of work towards an incremental vacuum.
3196**
3197** If the incremental vacuum is finished after this function has run,
shanebe217792009-03-05 04:20:31 +00003198** SQLITE_DONE is returned. If it is not finished, but no error occurred,
danielk1977dddbcdc2007-04-26 14:42:34 +00003199** SQLITE_OK is returned. Otherwise an SQLite error code.
3200*/
3201int sqlite3BtreeIncrVacuum(Btree *p){
drhd677b3d2007-08-20 22:48:41 +00003202 int rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003203 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003204
3205 sqlite3BtreeEnter(p);
danielk1977dddbcdc2007-04-26 14:42:34 +00003206 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
3207 if( !pBt->autoVacuum ){
drhd677b3d2007-08-20 22:48:41 +00003208 rc = SQLITE_DONE;
3209 }else{
dan51f0b6d2013-02-22 20:16:34 +00003210 Pgno nOrig = btreePagecount(pBt);
3211 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
3212 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
3213
dan91384712013-02-24 11:50:43 +00003214 if( nOrig<nFin ){
3215 rc = SQLITE_CORRUPT_BKPT;
3216 }else if( nFree>0 ){
dan11dcd112013-03-15 18:29:18 +00003217 rc = saveAllCursors(pBt, 0, 0);
3218 if( rc==SQLITE_OK ){
3219 invalidateAllOverflowCache(pBt);
3220 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
3221 }
dan51f0b6d2013-02-22 20:16:34 +00003222 if( rc==SQLITE_OK ){
3223 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3224 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
3225 }
3226 }else{
3227 rc = SQLITE_DONE;
drhdd3cd972010-03-27 17:12:36 +00003228 }
danielk1977dddbcdc2007-04-26 14:42:34 +00003229 }
drhd677b3d2007-08-20 22:48:41 +00003230 sqlite3BtreeLeave(p);
3231 return rc;
danielk1977dddbcdc2007-04-26 14:42:34 +00003232}
3233
3234/*
danielk19773b8a05f2007-03-19 17:44:26 +00003235** This routine is called prior to sqlite3PagerCommit when a transaction
drhf7b54962013-05-28 12:11:54 +00003236** is committed for an auto-vacuum database.
danielk197724168722007-04-02 05:07:47 +00003237**
3238** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
3239** the database file should be truncated to during the commit process.
3240** i.e. the database has been reorganized so that only the first *pnTrunc
3241** pages are in use.
danielk1977687566d2004-11-02 12:56:41 +00003242*/
danielk19773460d192008-12-27 15:23:13 +00003243static int autoVacuumCommit(BtShared *pBt){
danielk1977dddbcdc2007-04-26 14:42:34 +00003244 int rc = SQLITE_OK;
danielk1977687566d2004-11-02 12:56:41 +00003245 Pager *pPager = pBt->pPager;
drhf94a1732008-09-30 17:18:17 +00003246 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00003247
drh1fee73e2007-08-29 04:00:57 +00003248 assert( sqlite3_mutex_held(pBt->mutex) );
danielk197792d4d7a2007-05-04 12:05:56 +00003249 invalidateAllOverflowCache(pBt);
danielk1977dddbcdc2007-04-26 14:42:34 +00003250 assert(pBt->autoVacuum);
3251 if( !pBt->incrVacuum ){
drhea8ffdf2009-07-22 00:35:23 +00003252 Pgno nFin; /* Number of pages in database after autovacuuming */
3253 Pgno nFree; /* Number of pages on the freelist initially */
drh41d628c2009-07-11 17:04:08 +00003254 Pgno iFree; /* The next page to be freed */
drh41d628c2009-07-11 17:04:08 +00003255 Pgno nOrig; /* Database size before freeing */
danielk1977687566d2004-11-02 12:56:41 +00003256
drhb1299152010-03-30 22:58:33 +00003257 nOrig = btreePagecount(pBt);
danielk1977ef165ce2009-04-06 17:50:03 +00003258 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
3259 /* It is not possible to create a database for which the final page
3260 ** is either a pointer-map page or the pending-byte page. If one
3261 ** is encountered, this indicates corruption.
3262 */
danielk19773460d192008-12-27 15:23:13 +00003263 return SQLITE_CORRUPT_BKPT;
3264 }
danielk1977ef165ce2009-04-06 17:50:03 +00003265
danielk19773460d192008-12-27 15:23:13 +00003266 nFree = get4byte(&pBt->pPage1->aData[36]);
dan51f0b6d2013-02-22 20:16:34 +00003267 nFin = finalDbSize(pBt, nOrig, nFree);
drhc5e47ac2009-06-04 00:11:56 +00003268 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
dan0aed84d2013-03-26 14:16:20 +00003269 if( nFin<nOrig ){
3270 rc = saveAllCursors(pBt, 0, 0);
3271 }
danielk19773460d192008-12-27 15:23:13 +00003272 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
dan51f0b6d2013-02-22 20:16:34 +00003273 rc = incrVacuumStep(pBt, nFin, iFree, 1);
danielk1977dddbcdc2007-04-26 14:42:34 +00003274 }
danielk19773460d192008-12-27 15:23:13 +00003275 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
danielk19773460d192008-12-27 15:23:13 +00003276 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
3277 put4byte(&pBt->pPage1->aData[32], 0);
3278 put4byte(&pBt->pPage1->aData[36], 0);
drhdd3cd972010-03-27 17:12:36 +00003279 put4byte(&pBt->pPage1->aData[28], nFin);
danbc1a3c62013-02-23 16:40:46 +00003280 pBt->bDoTruncate = 1;
drhdd3cd972010-03-27 17:12:36 +00003281 pBt->nPage = nFin;
danielk1977dddbcdc2007-04-26 14:42:34 +00003282 }
3283 if( rc!=SQLITE_OK ){
3284 sqlite3PagerRollback(pPager);
3285 }
danielk1977687566d2004-11-02 12:56:41 +00003286 }
3287
dan0aed84d2013-03-26 14:16:20 +00003288 assert( nRef>=sqlite3PagerRefcount(pPager) );
danielk1977687566d2004-11-02 12:56:41 +00003289 return rc;
3290}
danielk1977dddbcdc2007-04-26 14:42:34 +00003291
danielk1977a50d9aa2009-06-08 14:49:45 +00003292#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
3293# define setChildPtrmaps(x) SQLITE_OK
3294#endif
danielk1977687566d2004-11-02 12:56:41 +00003295
3296/*
drh80e35f42007-03-30 14:06:34 +00003297** This routine does the first phase of a two-phase commit. This routine
3298** causes a rollback journal to be created (if it does not already exist)
3299** and populated with enough information so that if a power loss occurs
3300** the database can be restored to its original state by playing back
3301** the journal. Then the contents of the journal are flushed out to
3302** the disk. After the journal is safely on oxide, the changes to the
3303** database are written into the database file and flushed to oxide.
3304** At the end of this call, the rollback journal still exists on the
3305** disk and we are still holding all locks, so the transaction has not
drh51898cf2009-04-19 20:51:06 +00003306** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
drh80e35f42007-03-30 14:06:34 +00003307** commit process.
3308**
3309** This call is a no-op if no write-transaction is currently active on pBt.
3310**
3311** Otherwise, sync the database file for the btree pBt. zMaster points to
3312** the name of a master journal file that should be written into the
3313** individual journal file, or is NULL, indicating no master journal file
3314** (single database transaction).
3315**
3316** When this is called, the master journal should already have been
3317** created, populated with this journal pointer and synced to disk.
3318**
3319** Once this is routine has returned, the only thing required to commit
3320** the write-transaction for this database file is to delete the journal.
3321*/
3322int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
3323 int rc = SQLITE_OK;
3324 if( p->inTrans==TRANS_WRITE ){
3325 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003326 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00003327#ifndef SQLITE_OMIT_AUTOVACUUM
3328 if( pBt->autoVacuum ){
danielk19773460d192008-12-27 15:23:13 +00003329 rc = autoVacuumCommit(pBt);
drh80e35f42007-03-30 14:06:34 +00003330 if( rc!=SQLITE_OK ){
drhd677b3d2007-08-20 22:48:41 +00003331 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003332 return rc;
3333 }
3334 }
danbc1a3c62013-02-23 16:40:46 +00003335 if( pBt->bDoTruncate ){
3336 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
3337 }
drh80e35f42007-03-30 14:06:34 +00003338#endif
drh49b9d332009-01-02 18:10:42 +00003339 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
drhd677b3d2007-08-20 22:48:41 +00003340 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003341 }
3342 return rc;
3343}
3344
3345/*
danielk197794b30732009-07-02 17:21:57 +00003346** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
3347** at the conclusion of a transaction.
3348*/
3349static void btreeEndTransaction(Btree *p){
3350 BtShared *pBt = p->pBt;
drh1713afb2013-06-28 01:24:57 +00003351 sqlite3 *db = p->db;
danielk197794b30732009-07-02 17:21:57 +00003352 assert( sqlite3BtreeHoldsMutex(p) );
3353
danbc1a3c62013-02-23 16:40:46 +00003354#ifndef SQLITE_OMIT_AUTOVACUUM
3355 pBt->bDoTruncate = 0;
3356#endif
danc0537fe2013-06-28 19:41:43 +00003357 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
danfa401de2009-10-16 14:55:03 +00003358 /* If there are other active statements that belong to this database
3359 ** handle, downgrade to a read-only transaction. The other statements
3360 ** may still be reading from the database. */
danielk197794b30732009-07-02 17:21:57 +00003361 downgradeAllSharedCacheTableLocks(p);
3362 p->inTrans = TRANS_READ;
3363 }else{
3364 /* If the handle had any kind of transaction open, decrement the
3365 ** transaction count of the shared btree. If the transaction count
3366 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
3367 ** call below will unlock the pager. */
3368 if( p->inTrans!=TRANS_NONE ){
3369 clearAllSharedCacheTableLocks(p);
3370 pBt->nTransaction--;
3371 if( 0==pBt->nTransaction ){
3372 pBt->inTransaction = TRANS_NONE;
3373 }
3374 }
3375
3376 /* Set the current transaction state to TRANS_NONE and unlock the
3377 ** pager if this call closed the only read or write transaction. */
3378 p->inTrans = TRANS_NONE;
3379 unlockBtreeIfUnused(pBt);
3380 }
3381
3382 btreeIntegrity(p);
3383}
3384
3385/*
drh2aa679f2001-06-25 02:11:07 +00003386** Commit the transaction currently in progress.
drh5e00f6c2001-09-13 13:46:56 +00003387**
drh6e345992007-03-30 11:12:08 +00003388** This routine implements the second phase of a 2-phase commit. The
drh51898cf2009-04-19 20:51:06 +00003389** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
3390** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
3391** routine did all the work of writing information out to disk and flushing the
drh6e345992007-03-30 11:12:08 +00003392** contents so that they are written onto the disk platter. All this
drh51898cf2009-04-19 20:51:06 +00003393** routine has to do is delete or truncate or zero the header in the
3394** the rollback journal (which causes the transaction to commit) and
3395** drop locks.
drh6e345992007-03-30 11:12:08 +00003396**
dan60939d02011-03-29 15:40:55 +00003397** Normally, if an error occurs while the pager layer is attempting to
3398** finalize the underlying journal file, this function returns an error and
3399** the upper layer will attempt a rollback. However, if the second argument
3400** is non-zero then this b-tree transaction is part of a multi-file
3401** transaction. In this case, the transaction has already been committed
3402** (by deleting a master journal file) and the caller will ignore this
3403** functions return code. So, even if an error occurs in the pager layer,
3404** reset the b-tree objects internal state to indicate that the write
3405** transaction has been closed. This is quite safe, as the pager will have
3406** transitioned to the error state.
3407**
drh5e00f6c2001-09-13 13:46:56 +00003408** This will release the write lock on the database file. If there
3409** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00003410*/
dan60939d02011-03-29 15:40:55 +00003411int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
danielk1977aef0bf62005-12-30 16:28:01 +00003412
drh075ed302010-10-14 01:17:30 +00003413 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
drhd677b3d2007-08-20 22:48:41 +00003414 sqlite3BtreeEnter(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003415 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003416
3417 /* If the handle has a write-transaction open, commit the shared-btrees
3418 ** transaction and set the shared state to TRANS_READ.
3419 */
3420 if( p->inTrans==TRANS_WRITE ){
danielk19777f7bc662006-01-23 13:47:47 +00003421 int rc;
drh075ed302010-10-14 01:17:30 +00003422 BtShared *pBt = p->pBt;
danielk1977aef0bf62005-12-30 16:28:01 +00003423 assert( pBt->inTransaction==TRANS_WRITE );
3424 assert( pBt->nTransaction>0 );
drh80e35f42007-03-30 14:06:34 +00003425 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
dan60939d02011-03-29 15:40:55 +00003426 if( rc!=SQLITE_OK && bCleanup==0 ){
drhd677b3d2007-08-20 22:48:41 +00003427 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00003428 return rc;
3429 }
danielk1977aef0bf62005-12-30 16:28:01 +00003430 pBt->inTransaction = TRANS_READ;
danbf0e57a2013-05-14 20:36:31 +00003431 btreeClearHasContent(pBt);
danielk1977ee5741e2004-05-31 10:01:34 +00003432 }
danielk1977aef0bf62005-12-30 16:28:01 +00003433
danielk197794b30732009-07-02 17:21:57 +00003434 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00003435 sqlite3BtreeLeave(p);
danielk19777f7bc662006-01-23 13:47:47 +00003436 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003437}
3438
drh80e35f42007-03-30 14:06:34 +00003439/*
3440** Do both phases of a commit.
3441*/
3442int sqlite3BtreeCommit(Btree *p){
3443 int rc;
drhd677b3d2007-08-20 22:48:41 +00003444 sqlite3BtreeEnter(p);
drh80e35f42007-03-30 14:06:34 +00003445 rc = sqlite3BtreeCommitPhaseOne(p, 0);
3446 if( rc==SQLITE_OK ){
dan60939d02011-03-29 15:40:55 +00003447 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
drh80e35f42007-03-30 14:06:34 +00003448 }
drhd677b3d2007-08-20 22:48:41 +00003449 sqlite3BtreeLeave(p);
drh80e35f42007-03-30 14:06:34 +00003450 return rc;
3451}
3452
drhc39e0002004-05-07 23:50:57 +00003453/*
drhfb982642007-08-30 01:19:59 +00003454** This routine sets the state to CURSOR_FAULT and the error
3455** code to errCode for every cursor on BtShared that pBtree
3456** references.
3457**
3458** Every cursor is tripped, including cursors that belong
3459** to other database connections that happen to be sharing
3460** the cache with pBtree.
3461**
3462** This routine gets called when a rollback occurs.
3463** All cursors using the same cache must be tripped
3464** to prevent them from trying to use the btree after
3465** the rollback. The rollback may have deleted tables
3466** or moved root pages, so it is not sufficient to
3467** save the state of the cursor. The cursor must be
3468** invalidated.
3469*/
3470void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
3471 BtCursor *p;
drh0f198a72012-02-13 16:43:16 +00003472 if( pBtree==0 ) return;
drhfb982642007-08-30 01:19:59 +00003473 sqlite3BtreeEnter(pBtree);
3474 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
danielk1977bc2ca9e2008-11-13 14:28:28 +00003475 int i;
danielk1977be51a652008-10-08 17:58:48 +00003476 sqlite3BtreeClearCursor(p);
drhfb982642007-08-30 01:19:59 +00003477 p->eState = CURSOR_FAULT;
drh4c301aa2009-07-15 17:25:45 +00003478 p->skipNext = errCode;
danielk1977bc2ca9e2008-11-13 14:28:28 +00003479 for(i=0; i<=p->iPage; i++){
3480 releasePage(p->apPage[i]);
3481 p->apPage[i] = 0;
3482 }
drhfb982642007-08-30 01:19:59 +00003483 }
3484 sqlite3BtreeLeave(pBtree);
3485}
3486
3487/*
drhecdc7532001-09-23 02:35:53 +00003488** Rollback the transaction in progress. All cursors will be
3489** invalided by this operation. Any attempt to use a cursor
3490** that was open at the beginning of this operation will result
3491** in an error.
drh5e00f6c2001-09-13 13:46:56 +00003492**
3493** This will release the write lock on the database file. If there
3494** are no active cursors, it also releases the read lock.
drha059ad02001-04-17 20:09:11 +00003495*/
drh0f198a72012-02-13 16:43:16 +00003496int sqlite3BtreeRollback(Btree *p, int tripCode){
danielk19778d34dfd2006-01-24 16:37:57 +00003497 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003498 BtShared *pBt = p->pBt;
drh24cd67e2004-05-10 16:18:47 +00003499 MemPage *pPage1;
danielk1977aef0bf62005-12-30 16:28:01 +00003500
drhd677b3d2007-08-20 22:48:41 +00003501 sqlite3BtreeEnter(p);
drh0f198a72012-02-13 16:43:16 +00003502 if( tripCode==SQLITE_OK ){
3503 rc = tripCode = saveAllCursors(pBt, 0, 0);
3504 }else{
3505 rc = SQLITE_OK;
danielk19772b8c13e2006-01-24 14:21:24 +00003506 }
drh0f198a72012-02-13 16:43:16 +00003507 if( tripCode ){
3508 sqlite3BtreeTripAllCursors(p, tripCode);
3509 }
danielk1977aef0bf62005-12-30 16:28:01 +00003510 btreeIntegrity(p);
danielk1977aef0bf62005-12-30 16:28:01 +00003511
3512 if( p->inTrans==TRANS_WRITE ){
danielk19778d34dfd2006-01-24 16:37:57 +00003513 int rc2;
danielk1977aef0bf62005-12-30 16:28:01 +00003514
danielk19778d34dfd2006-01-24 16:37:57 +00003515 assert( TRANS_WRITE==pBt->inTransaction );
danielk19773b8a05f2007-03-19 17:44:26 +00003516 rc2 = sqlite3PagerRollback(pBt->pPager);
danielk19778d34dfd2006-01-24 16:37:57 +00003517 if( rc2!=SQLITE_OK ){
3518 rc = rc2;
3519 }
3520
drh24cd67e2004-05-10 16:18:47 +00003521 /* The rollback may have destroyed the pPage1->aData value. So
danielk197730548662009-07-09 05:07:37 +00003522 ** call btreeGetPage() on page 1 again to make
drh16a9b832007-05-05 18:39:25 +00003523 ** sure pPage1->aData is set correctly. */
drhb00fc3b2013-08-21 23:42:32 +00003524 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
drh1f5b4672010-04-01 02:22:19 +00003525 int nPage = get4byte(28+(u8*)pPage1->aData);
3526 testcase( nPage==0 );
3527 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
3528 testcase( pBt->nPage!=nPage );
3529 pBt->nPage = nPage;
drh24cd67e2004-05-10 16:18:47 +00003530 releasePage(pPage1);
3531 }
drh85ec3b62013-05-14 23:12:06 +00003532 assert( countValidCursors(pBt, 1)==0 );
danielk1977aef0bf62005-12-30 16:28:01 +00003533 pBt->inTransaction = TRANS_READ;
danbf0e57a2013-05-14 20:36:31 +00003534 btreeClearHasContent(pBt);
drh24cd67e2004-05-10 16:18:47 +00003535 }
danielk1977aef0bf62005-12-30 16:28:01 +00003536
danielk197794b30732009-07-02 17:21:57 +00003537 btreeEndTransaction(p);
drhd677b3d2007-08-20 22:48:41 +00003538 sqlite3BtreeLeave(p);
drha059ad02001-04-17 20:09:11 +00003539 return rc;
3540}
3541
3542/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003543** Start a statement subtransaction. The subtransaction can be rolled
danielk1977bd434552009-03-18 10:33:00 +00003544** back independently of the main transaction. You must start a transaction
3545** before starting a subtransaction. The subtransaction is ended automatically
3546** if the main transaction commits or rolls back.
drhab01f612004-05-22 02:55:23 +00003547**
3548** Statement subtransactions are used around individual SQL statements
3549** that are contained within a BEGIN...COMMIT block. If a constraint
3550** error occurs within the statement, the effect of that one statement
3551** can be rolled back without having to rollback the entire transaction.
danielk1977bd434552009-03-18 10:33:00 +00003552**
3553** A statement sub-transaction is implemented as an anonymous savepoint. The
3554** value passed as the second parameter is the total number of savepoints,
3555** including the new anonymous savepoint, open on the B-Tree. i.e. if there
3556** are no active savepoints and no other statement-transactions open,
3557** iStatement is 1. This anonymous savepoint can be released or rolled back
3558** using the sqlite3BtreeSavepoint() function.
drh663fc632002-02-02 18:49:19 +00003559*/
danielk1977bd434552009-03-18 10:33:00 +00003560int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
drh663fc632002-02-02 18:49:19 +00003561 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00003562 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00003563 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00003564 assert( p->inTrans==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00003565 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk1977bd434552009-03-18 10:33:00 +00003566 assert( iStatement>0 );
3567 assert( iStatement>p->db->nSavepoint );
drh5e0ccc22010-03-29 19:36:52 +00003568 assert( pBt->inTransaction==TRANS_WRITE );
3569 /* At the pager level, a statement transaction is a savepoint with
3570 ** an index greater than all savepoints created explicitly using
3571 ** SQL statements. It is illegal to open, release or rollback any
3572 ** such savepoints while the statement transaction savepoint is active.
3573 */
3574 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
drhd677b3d2007-08-20 22:48:41 +00003575 sqlite3BtreeLeave(p);
drh663fc632002-02-02 18:49:19 +00003576 return rc;
3577}
3578
3579/*
danielk1977fd7f0452008-12-17 17:30:26 +00003580** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
3581** or SAVEPOINT_RELEASE. This function either releases or rolls back the
danielk197712dd5492008-12-18 15:45:07 +00003582** savepoint identified by parameter iSavepoint, depending on the value
3583** of op.
3584**
3585** Normally, iSavepoint is greater than or equal to zero. However, if op is
3586** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
3587** contents of the entire transaction are rolled back. This is different
3588** from a normal transaction rollback, as no locks are released and the
3589** transaction remains open.
danielk1977fd7f0452008-12-17 17:30:26 +00003590*/
3591int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
3592 int rc = SQLITE_OK;
3593 if( p && p->inTrans==TRANS_WRITE ){
3594 BtShared *pBt = p->pBt;
danielk1977fd7f0452008-12-17 17:30:26 +00003595 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
3596 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
3597 sqlite3BtreeEnter(p);
danielk1977fd7f0452008-12-17 17:30:26 +00003598 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
drh9f0bbf92009-01-02 21:08:09 +00003599 if( rc==SQLITE_OK ){
drhc9166342012-01-05 23:32:06 +00003600 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
3601 pBt->nPage = 0;
3602 }
drh9f0bbf92009-01-02 21:08:09 +00003603 rc = newDatabase(pBt);
drhdd3cd972010-03-27 17:12:36 +00003604 pBt->nPage = get4byte(28 + pBt->pPage1->aData);
drhb9b49bf2010-08-05 03:21:39 +00003605
3606 /* The database size was written into the offset 28 of the header
3607 ** when the transaction started, so we know that the value at offset
3608 ** 28 is nonzero. */
3609 assert( pBt->nPage>0 );
drh9f0bbf92009-01-02 21:08:09 +00003610 }
danielk1977fd7f0452008-12-17 17:30:26 +00003611 sqlite3BtreeLeave(p);
3612 }
3613 return rc;
3614}
3615
3616/*
drh8b2f49b2001-06-08 00:21:52 +00003617** Create a new cursor for the BTree whose root is on the page
danielk19773e8add92009-07-04 17:16:00 +00003618** iTable. If a read-only cursor is requested, it is assumed that
3619** the caller already has at least a read-only transaction open
3620** on the database already. If a write-cursor is requested, then
3621** the caller is assumed to have an open write transaction.
drh1bee3d72001-10-15 00:44:35 +00003622**
3623** If wrFlag==0, then the cursor can only be used for reading.
drhf74b8d92002-09-01 23:20:45 +00003624** If wrFlag==1, then the cursor can be used for reading or for
3625** writing if other conditions for writing are also met. These
3626** are the conditions that must be met in order for writing to
3627** be allowed:
drh6446c4d2001-12-15 14:22:18 +00003628**
drhf74b8d92002-09-01 23:20:45 +00003629** 1: The cursor must have been opened with wrFlag==1
3630**
drhfe5d71d2007-03-19 11:54:10 +00003631** 2: Other database connections that share the same pager cache
3632** but which are not in the READ_UNCOMMITTED state may not have
3633** cursors open with wrFlag==0 on the same table. Otherwise
3634** the changes made by this write cursor would be visible to
3635** the read cursors in the other database connection.
drhf74b8d92002-09-01 23:20:45 +00003636**
3637** 3: The database must be writable (not on read-only media)
3638**
3639** 4: There must be an active transaction.
3640**
drh6446c4d2001-12-15 14:22:18 +00003641** No checking is done to make sure that page iTable really is the
3642** root page of a b-tree. If it is not, then the cursor acquired
3643** will not work correctly.
danielk197771d5d2c2008-09-29 11:49:47 +00003644**
drhf25a5072009-11-18 23:01:25 +00003645** It is assumed that the sqlite3BtreeCursorZero() has been called
3646** on pCur to initialize the memory space prior to invoking this routine.
drha059ad02001-04-17 20:09:11 +00003647*/
drhd677b3d2007-08-20 22:48:41 +00003648static int btreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00003649 Btree *p, /* The btree */
3650 int iTable, /* Root page of table to open */
3651 int wrFlag, /* 1 to write. 0 read-only */
3652 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
3653 BtCursor *pCur /* Space for new cursor */
drh3aac2dd2004-04-26 14:10:20 +00003654){
danielk19773e8add92009-07-04 17:16:00 +00003655 BtShared *pBt = p->pBt; /* Shared b-tree handle */
drhecdc7532001-09-23 02:35:53 +00003656
drh1fee73e2007-08-29 04:00:57 +00003657 assert( sqlite3BtreeHoldsMutex(p) );
drhf49661a2008-12-10 16:45:50 +00003658 assert( wrFlag==0 || wrFlag==1 );
danielk197796d48e92009-06-29 06:00:37 +00003659
danielk1977602b4662009-07-02 07:47:33 +00003660 /* The following assert statements verify that if this is a sharable
3661 ** b-tree database, the connection is holding the required table locks,
3662 ** and that no other connection has any open cursor that conflicts with
3663 ** this lock. */
3664 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
danielk197796d48e92009-06-29 06:00:37 +00003665 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
3666
danielk19773e8add92009-07-04 17:16:00 +00003667 /* Assert that the caller has opened the required transaction. */
3668 assert( p->inTrans>TRANS_NONE );
3669 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
3670 assert( pBt->pPage1 && pBt->pPage1->aData );
3671
drhc9166342012-01-05 23:32:06 +00003672 if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
danielk197796d48e92009-06-29 06:00:37 +00003673 return SQLITE_READONLY;
drha0c9a112004-03-10 13:42:37 +00003674 }
drhb1299152010-03-30 22:58:33 +00003675 if( iTable==1 && btreePagecount(pBt)==0 ){
dana205a482011-08-27 18:48:57 +00003676 assert( wrFlag==0 );
3677 iTable = 0;
danielk19773e8add92009-07-04 17:16:00 +00003678 }
danielk1977aef0bf62005-12-30 16:28:01 +00003679
danielk1977aef0bf62005-12-30 16:28:01 +00003680 /* Now that no other errors can occur, finish filling in the BtCursor
danielk19773e8add92009-07-04 17:16:00 +00003681 ** variables and link the cursor into the BtShared list. */
danielk1977172114a2009-07-07 15:47:12 +00003682 pCur->pgnoRoot = (Pgno)iTable;
3683 pCur->iPage = -1;
drh1e968a02008-03-25 00:22:21 +00003684 pCur->pKeyInfo = pKeyInfo;
danielk1977aef0bf62005-12-30 16:28:01 +00003685 pCur->pBtree = p;
drhd0679ed2007-08-28 22:24:34 +00003686 pCur->pBt = pBt;
drh4c417182014-03-31 23:57:41 +00003687 assert( wrFlag==0 || wrFlag==BTCF_WriteFlag );
3688 pCur->curFlags = wrFlag;
drha059ad02001-04-17 20:09:11 +00003689 pCur->pNext = pBt->pCursor;
3690 if( pCur->pNext ){
3691 pCur->pNext->pPrev = pCur;
3692 }
3693 pBt->pCursor = pCur;
danielk1977da184232006-01-05 11:34:32 +00003694 pCur->eState = CURSOR_INVALID;
danielk1977aef0bf62005-12-30 16:28:01 +00003695 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003696}
drhd677b3d2007-08-20 22:48:41 +00003697int sqlite3BtreeCursor(
danielk1977cd3e8f72008-03-25 09:47:35 +00003698 Btree *p, /* The btree */
3699 int iTable, /* Root page of table to open */
3700 int wrFlag, /* 1 to write. 0 read-only */
3701 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
3702 BtCursor *pCur /* Write new cursor here */
drhd677b3d2007-08-20 22:48:41 +00003703){
3704 int rc;
3705 sqlite3BtreeEnter(p);
danielk1977cd3e8f72008-03-25 09:47:35 +00003706 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
drhd677b3d2007-08-20 22:48:41 +00003707 sqlite3BtreeLeave(p);
3708 return rc;
3709}
drh7f751222009-03-17 22:33:00 +00003710
3711/*
3712** Return the size of a BtCursor object in bytes.
3713**
3714** This interfaces is needed so that users of cursors can preallocate
3715** sufficient storage to hold a cursor. The BtCursor object is opaque
3716** to users so they cannot do the sizeof() themselves - they must call
3717** this routine.
3718*/
3719int sqlite3BtreeCursorSize(void){
drhc54055b2009-11-13 17:05:53 +00003720 return ROUND8(sizeof(BtCursor));
danielk1977cd3e8f72008-03-25 09:47:35 +00003721}
3722
drh7f751222009-03-17 22:33:00 +00003723/*
drhf25a5072009-11-18 23:01:25 +00003724** Initialize memory that will be converted into a BtCursor object.
3725**
3726** The simple approach here would be to memset() the entire object
3727** to zero. But it turns out that the apPage[] and aiIdx[] arrays
3728** do not need to be zeroed and they are large, so we can save a lot
3729** of run-time by skipping the initialization of those elements.
3730*/
3731void sqlite3BtreeCursorZero(BtCursor *p){
3732 memset(p, 0, offsetof(BtCursor, iPage));
3733}
3734
3735/*
drh5e00f6c2001-09-13 13:46:56 +00003736** Close a cursor. The read lock on the database file is released
drhbd03cae2001-06-02 02:40:57 +00003737** when the last cursor is closed.
drha059ad02001-04-17 20:09:11 +00003738*/
drh3aac2dd2004-04-26 14:10:20 +00003739int sqlite3BtreeCloseCursor(BtCursor *pCur){
drhff0587c2007-08-29 17:43:19 +00003740 Btree *pBtree = pCur->pBtree;
danielk1977cd3e8f72008-03-25 09:47:35 +00003741 if( pBtree ){
danielk197771d5d2c2008-09-29 11:49:47 +00003742 int i;
danielk1977cd3e8f72008-03-25 09:47:35 +00003743 BtShared *pBt = pCur->pBt;
3744 sqlite3BtreeEnter(pBtree);
danielk1977be51a652008-10-08 17:58:48 +00003745 sqlite3BtreeClearCursor(pCur);
danielk1977cd3e8f72008-03-25 09:47:35 +00003746 if( pCur->pPrev ){
3747 pCur->pPrev->pNext = pCur->pNext;
3748 }else{
3749 pBt->pCursor = pCur->pNext;
3750 }
3751 if( pCur->pNext ){
3752 pCur->pNext->pPrev = pCur->pPrev;
3753 }
danielk197771d5d2c2008-09-29 11:49:47 +00003754 for(i=0; i<=pCur->iPage; i++){
3755 releasePage(pCur->apPage[i]);
3756 }
danielk1977cd3e8f72008-03-25 09:47:35 +00003757 unlockBtreeIfUnused(pBt);
dan5a500af2014-03-11 20:33:04 +00003758 sqlite3DbFree(pBtree->db, pCur->aOverflow);
danielk1977cd3e8f72008-03-25 09:47:35 +00003759 /* sqlite3_free(pCur); */
3760 sqlite3BtreeLeave(pBtree);
drha059ad02001-04-17 20:09:11 +00003761 }
drh8c42ca92001-06-22 19:15:00 +00003762 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003763}
3764
drh5e2f8b92001-05-28 00:41:15 +00003765/*
drh86057612007-06-26 01:04:48 +00003766** Make sure the BtCursor* given in the argument has a valid
3767** BtCursor.info structure. If it is not already valid, call
danielk197730548662009-07-09 05:07:37 +00003768** btreeParseCell() to fill it in.
drhab01f612004-05-22 02:55:23 +00003769**
3770** BtCursor.info is a cache of the information in the current cell.
danielk197730548662009-07-09 05:07:37 +00003771** Using this cache reduces the number of calls to btreeParseCell().
drh86057612007-06-26 01:04:48 +00003772**
3773** 2007-06-25: There is a bug in some versions of MSVC that cause the
3774** compiler to crash when getCellInfo() is implemented as a macro.
3775** But there is a measureable speed advantage to using the macro on gcc
3776** (when less compiler optimizations like -Os or -O0 are used and the
peter.d.reid60ec9142014-09-06 16:39:46 +00003777** compiler is not doing aggressive inlining.) So we use a real function
drh86057612007-06-26 01:04:48 +00003778** for MSVC and a macro for everything else. Ticket #2457.
drh9188b382004-05-14 21:12:22 +00003779*/
drh9188b382004-05-14 21:12:22 +00003780#ifndef NDEBUG
danielk19771cc5ed82007-05-16 17:28:43 +00003781 static void assertCellInfo(BtCursor *pCur){
drh9188b382004-05-14 21:12:22 +00003782 CellInfo info;
danielk197771d5d2c2008-09-29 11:49:47 +00003783 int iPage = pCur->iPage;
drh51c6d962004-06-06 00:42:25 +00003784 memset(&info, 0, sizeof(info));
danielk197730548662009-07-09 05:07:37 +00003785 btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
dan7df42ab2014-01-20 18:25:44 +00003786 assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
drh9188b382004-05-14 21:12:22 +00003787 }
danielk19771cc5ed82007-05-16 17:28:43 +00003788#else
3789 #define assertCellInfo(x)
3790#endif
drh86057612007-06-26 01:04:48 +00003791#ifdef _MSC_VER
3792 /* Use a real function in MSVC to work around bugs in that compiler. */
3793 static void getCellInfo(BtCursor *pCur){
3794 if( pCur->info.nSize==0 ){
danielk197771d5d2c2008-09-29 11:49:47 +00003795 int iPage = pCur->iPage;
danielk197730548662009-07-09 05:07:37 +00003796 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
drh036dbec2014-03-11 23:40:44 +00003797 pCur->curFlags |= BTCF_ValidNKey;
drh86057612007-06-26 01:04:48 +00003798 }else{
3799 assertCellInfo(pCur);
3800 }
3801 }
3802#else /* if not _MSC_VER */
3803 /* Use a macro in all other compilers so that the function is inlined */
danielk197771d5d2c2008-09-29 11:49:47 +00003804#define getCellInfo(pCur) \
3805 if( pCur->info.nSize==0 ){ \
3806 int iPage = pCur->iPage; \
drh036dbec2014-03-11 23:40:44 +00003807 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
3808 pCur->curFlags |= BTCF_ValidNKey; \
danielk197771d5d2c2008-09-29 11:49:47 +00003809 }else{ \
3810 assertCellInfo(pCur); \
drh86057612007-06-26 01:04:48 +00003811 }
3812#endif /* _MSC_VER */
drh9188b382004-05-14 21:12:22 +00003813
drhea8ffdf2009-07-22 00:35:23 +00003814#ifndef NDEBUG /* The next routine used only within assert() statements */
3815/*
3816** Return true if the given BtCursor is valid. A valid cursor is one
3817** that is currently pointing to a row in a (non-empty) table.
3818** This is a verification routine is used only within assert() statements.
3819*/
3820int sqlite3BtreeCursorIsValid(BtCursor *pCur){
3821 return pCur && pCur->eState==CURSOR_VALID;
3822}
3823#endif /* NDEBUG */
3824
drh9188b382004-05-14 21:12:22 +00003825/*
drh3aac2dd2004-04-26 14:10:20 +00003826** Set *pSize to the size of the buffer needed to hold the value of
3827** the key for the current entry. If the cursor is not pointing
3828** to a valid entry, *pSize is set to 0.
3829**
drh4b70f112004-05-02 21:12:19 +00003830** For a table with the INTKEY flag set, this routine returns the key
drh3aac2dd2004-04-26 14:10:20 +00003831** itself, not the number of bytes in the key.
drhea8ffdf2009-07-22 00:35:23 +00003832**
3833** The caller must position the cursor prior to invoking this routine.
3834**
3835** This routine cannot fail. It always returns SQLITE_OK.
drh7e3b0a02001-04-28 16:52:40 +00003836*/
drh4a1c3802004-05-12 15:15:47 +00003837int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
drh1fee73e2007-08-29 04:00:57 +00003838 assert( cursorHoldsMutex(pCur) );
drhea8ffdf2009-07-22 00:35:23 +00003839 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
3840 if( pCur->eState!=CURSOR_VALID ){
3841 *pSize = 0;
3842 }else{
3843 getCellInfo(pCur);
3844 *pSize = pCur->info.nKey;
drh72f82862001-05-24 21:06:34 +00003845 }
drhea8ffdf2009-07-22 00:35:23 +00003846 return SQLITE_OK;
drha059ad02001-04-17 20:09:11 +00003847}
drh2af926b2001-05-15 00:39:25 +00003848
drh72f82862001-05-24 21:06:34 +00003849/*
drh0e1c19e2004-05-11 00:58:56 +00003850** Set *pSize to the number of bytes of data in the entry the
drhea8ffdf2009-07-22 00:35:23 +00003851** cursor currently points to.
3852**
3853** The caller must guarantee that the cursor is pointing to a non-NULL
3854** valid entry. In other words, the calling procedure must guarantee
3855** that the cursor has Cursor.eState==CURSOR_VALID.
3856**
3857** Failure is not possible. This function always returns SQLITE_OK.
3858** It might just as well be a procedure (returning void) but we continue
3859** to return an integer result code for historical reasons.
drh0e1c19e2004-05-11 00:58:56 +00003860*/
3861int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
drh1fee73e2007-08-29 04:00:57 +00003862 assert( cursorHoldsMutex(pCur) );
drhea8ffdf2009-07-22 00:35:23 +00003863 assert( pCur->eState==CURSOR_VALID );
3864 getCellInfo(pCur);
3865 *pSize = pCur->info.nData;
3866 return SQLITE_OK;
drh0e1c19e2004-05-11 00:58:56 +00003867}
3868
3869/*
danielk1977d04417962007-05-02 13:16:30 +00003870** Given the page number of an overflow page in the database (parameter
3871** ovfl), this function finds the page number of the next page in the
3872** linked list of overflow pages. If possible, it uses the auto-vacuum
3873** pointer-map data instead of reading the content of page ovfl to do so.
3874**
3875** If an error occurs an SQLite error code is returned. Otherwise:
3876**
danielk1977bea2a942009-01-20 17:06:27 +00003877** The page number of the next overflow page in the linked list is
3878** written to *pPgnoNext. If page ovfl is the last page in its linked
3879** list, *pPgnoNext is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003880**
danielk1977bea2a942009-01-20 17:06:27 +00003881** If ppPage is not NULL, and a reference to the MemPage object corresponding
3882** to page number pOvfl was obtained, then *ppPage is set to point to that
3883** reference. It is the responsibility of the caller to call releasePage()
3884** on *ppPage to free the reference. In no reference was obtained (because
3885** the pointer-map was used to obtain the value for *pPgnoNext), then
3886** *ppPage is set to zero.
danielk1977d04417962007-05-02 13:16:30 +00003887*/
3888static int getOverflowPage(
drhfa3be902009-07-07 02:44:07 +00003889 BtShared *pBt, /* The database file */
3890 Pgno ovfl, /* Current overflow page number */
danielk1977bea2a942009-01-20 17:06:27 +00003891 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
danielk1977d04417962007-05-02 13:16:30 +00003892 Pgno *pPgnoNext /* OUT: Next overflow page number */
3893){
3894 Pgno next = 0;
danielk1977bea2a942009-01-20 17:06:27 +00003895 MemPage *pPage = 0;
drh1bd10f82008-12-10 21:19:56 +00003896 int rc = SQLITE_OK;
danielk1977d04417962007-05-02 13:16:30 +00003897
drh1fee73e2007-08-29 04:00:57 +00003898 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bea2a942009-01-20 17:06:27 +00003899 assert(pPgnoNext);
danielk1977d04417962007-05-02 13:16:30 +00003900
3901#ifndef SQLITE_OMIT_AUTOVACUUM
3902 /* Try to find the next page in the overflow list using the
3903 ** autovacuum pointer-map pages. Guess that the next page in
3904 ** the overflow list is page number (ovfl+1). If that guess turns
3905 ** out to be wrong, fall back to loading the data of page
3906 ** number ovfl to determine the next page number.
3907 */
3908 if( pBt->autoVacuum ){
3909 Pgno pgno;
3910 Pgno iGuess = ovfl+1;
3911 u8 eType;
3912
3913 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
3914 iGuess++;
3915 }
3916
drhb1299152010-03-30 22:58:33 +00003917 if( iGuess<=btreePagecount(pBt) ){
danielk1977d04417962007-05-02 13:16:30 +00003918 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
danielk1977bea2a942009-01-20 17:06:27 +00003919 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
danielk1977d04417962007-05-02 13:16:30 +00003920 next = iGuess;
danielk1977bea2a942009-01-20 17:06:27 +00003921 rc = SQLITE_DONE;
danielk1977d04417962007-05-02 13:16:30 +00003922 }
3923 }
3924 }
3925#endif
3926
danielk1977d8a3f3d2009-07-11 11:45:23 +00003927 assert( next==0 || rc==SQLITE_DONE );
danielk1977bea2a942009-01-20 17:06:27 +00003928 if( rc==SQLITE_OK ){
drhb00fc3b2013-08-21 23:42:32 +00003929 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
danielk1977d8a3f3d2009-07-11 11:45:23 +00003930 assert( rc==SQLITE_OK || pPage==0 );
3931 if( rc==SQLITE_OK ){
danielk1977d04417962007-05-02 13:16:30 +00003932 next = get4byte(pPage->aData);
3933 }
danielk1977443c0592009-01-16 15:21:05 +00003934 }
danielk197745d68822009-01-16 16:23:38 +00003935
danielk1977bea2a942009-01-20 17:06:27 +00003936 *pPgnoNext = next;
3937 if( ppPage ){
3938 *ppPage = pPage;
3939 }else{
3940 releasePage(pPage);
3941 }
3942 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
danielk1977d04417962007-05-02 13:16:30 +00003943}
3944
danielk1977da107192007-05-04 08:32:13 +00003945/*
3946** Copy data from a buffer to a page, or from a page to a buffer.
3947**
3948** pPayload is a pointer to data stored on database page pDbPage.
3949** If argument eOp is false, then nByte bytes of data are copied
3950** from pPayload to the buffer pointed at by pBuf. If eOp is true,
3951** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
3952** of data are copied from the buffer pBuf to pPayload.
3953**
3954** SQLITE_OK is returned on success, otherwise an error code.
3955*/
3956static int copyPayload(
3957 void *pPayload, /* Pointer to page data */
3958 void *pBuf, /* Pointer to buffer */
3959 int nByte, /* Number of bytes to copy */
3960 int eOp, /* 0 -> copy from page, 1 -> copy to page */
3961 DbPage *pDbPage /* Page containing pPayload */
3962){
3963 if( eOp ){
3964 /* Copy data from buffer to page (a write operation) */
3965 int rc = sqlite3PagerWrite(pDbPage);
3966 if( rc!=SQLITE_OK ){
3967 return rc;
3968 }
3969 memcpy(pPayload, pBuf, nByte);
3970 }else{
3971 /* Copy data from page to buffer (a read operation) */
3972 memcpy(pBuf, pPayload, nByte);
3973 }
3974 return SQLITE_OK;
3975}
danielk1977d04417962007-05-02 13:16:30 +00003976
3977/*
danielk19779f8d6402007-05-02 17:48:45 +00003978** This function is used to read or overwrite payload information
dan5a500af2014-03-11 20:33:04 +00003979** for the entry that the pCur cursor is pointing to. The eOp
3980** argument is interpreted as follows:
3981**
3982** 0: The operation is a read. Populate the overflow cache.
3983** 1: The operation is a write. Populate the overflow cache.
3984** 2: The operation is a read. Do not populate the overflow cache.
danielk19779f8d6402007-05-02 17:48:45 +00003985**
3986** A total of "amt" bytes are read or written beginning at "offset".
3987** Data is read to or from the buffer pBuf.
drh72f82862001-05-24 21:06:34 +00003988**
drh3bcdfd22009-07-12 02:32:21 +00003989** The content being read or written might appear on the main page
3990** or be scattered out on multiple overflow pages.
danielk1977da107192007-05-04 08:32:13 +00003991**
dan5a500af2014-03-11 20:33:04 +00003992** If the current cursor entry uses one or more overflow pages and the
3993** eOp argument is not 2, this function may allocate space for and lazily
peter.d.reid60ec9142014-09-06 16:39:46 +00003994** populates the overflow page-list cache array (BtCursor.aOverflow).
dan5a500af2014-03-11 20:33:04 +00003995** Subsequent calls use this cache to make seeking to the supplied offset
3996** more efficient.
danielk1977da107192007-05-04 08:32:13 +00003997**
3998** Once an overflow page-list cache has been allocated, it may be
3999** invalidated if some other cursor writes to the same table, or if
4000** the cursor is moved to a different row. Additionally, in auto-vacuum
4001** mode, the following events may invalidate an overflow page-list cache.
4002**
4003** * An incremental vacuum,
4004** * A commit in auto_vacuum="full" mode,
4005** * Creating a table (may require moving an overflow page).
drh72f82862001-05-24 21:06:34 +00004006*/
danielk19779f8d6402007-05-02 17:48:45 +00004007static int accessPayload(
drh3aac2dd2004-04-26 14:10:20 +00004008 BtCursor *pCur, /* Cursor pointing to entry to read from */
danielk197789d40042008-11-17 14:20:56 +00004009 u32 offset, /* Begin reading this far into payload */
4010 u32 amt, /* Read this many bytes */
drh3aac2dd2004-04-26 14:10:20 +00004011 unsigned char *pBuf, /* Write the bytes into this buffer */
danielk19779f8d6402007-05-02 17:48:45 +00004012 int eOp /* zero to read. non-zero to write. */
drh3aac2dd2004-04-26 14:10:20 +00004013){
4014 unsigned char *aPayload;
danielk1977da107192007-05-04 08:32:13 +00004015 int rc = SQLITE_OK;
drhfa1a98a2004-05-14 19:08:17 +00004016 u32 nKey;
danielk19772dec9702007-05-02 16:48:37 +00004017 int iIdx = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00004018 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
danielk19770d065412008-11-12 18:21:36 +00004019 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
drh4c417182014-03-31 23:57:41 +00004020#ifdef SQLITE_DIRECT_OVERFLOW_READ
4021 int bEnd; /* True if reading to end of data */
4022#endif
drh3aac2dd2004-04-26 14:10:20 +00004023
danielk1977da107192007-05-04 08:32:13 +00004024 assert( pPage );
danielk1977da184232006-01-05 11:34:32 +00004025 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004026 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
drh1fee73e2007-08-29 04:00:57 +00004027 assert( cursorHoldsMutex(pCur) );
drha38c9512014-04-01 01:24:34 +00004028 assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */
danielk1977da107192007-05-04 08:32:13 +00004029
drh86057612007-06-26 01:04:48 +00004030 getCellInfo(pCur);
drh366fda62006-01-13 02:35:09 +00004031 aPayload = pCur->info.pCell + pCur->info.nHeader;
drhf49661a2008-12-10 16:45:50 +00004032 nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
drh4c417182014-03-31 23:57:41 +00004033#ifdef SQLITE_DIRECT_OVERFLOW_READ
dan9bc21b52014-03-20 18:56:35 +00004034 bEnd = (offset+amt==nKey+pCur->info.nData);
drh4c417182014-03-31 23:57:41 +00004035#endif
danielk1977da107192007-05-04 08:32:13 +00004036
drh3bcdfd22009-07-12 02:32:21 +00004037 if( NEVER(offset+amt > nKey+pCur->info.nData)
danielk19770d065412008-11-12 18:21:36 +00004038 || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
4039 ){
danielk1977da107192007-05-04 08:32:13 +00004040 /* Trying to read or write past the end of the data is an error */
danielk197767fd7a92008-09-10 17:53:35 +00004041 return SQLITE_CORRUPT_BKPT;
drh3aac2dd2004-04-26 14:10:20 +00004042 }
danielk1977da107192007-05-04 08:32:13 +00004043
4044 /* Check if data must be read/written to/from the btree page itself. */
drhfa1a98a2004-05-14 19:08:17 +00004045 if( offset<pCur->info.nLocal ){
drh2af926b2001-05-15 00:39:25 +00004046 int a = amt;
drhfa1a98a2004-05-14 19:08:17 +00004047 if( a+offset>pCur->info.nLocal ){
4048 a = pCur->info.nLocal - offset;
drh2af926b2001-05-15 00:39:25 +00004049 }
dan5a500af2014-03-11 20:33:04 +00004050 rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
drh2aa679f2001-06-25 02:11:07 +00004051 offset = 0;
drha34b6762004-05-07 13:30:42 +00004052 pBuf += a;
drh2af926b2001-05-15 00:39:25 +00004053 amt -= a;
drhdd793422001-06-28 01:54:48 +00004054 }else{
drhfa1a98a2004-05-14 19:08:17 +00004055 offset -= pCur->info.nLocal;
drhbd03cae2001-06-02 02:40:57 +00004056 }
danielk1977da107192007-05-04 08:32:13 +00004057
4058 if( rc==SQLITE_OK && amt>0 ){
danielk197789d40042008-11-17 14:20:56 +00004059 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
danielk1977da107192007-05-04 08:32:13 +00004060 Pgno nextPage;
4061
drhfa1a98a2004-05-14 19:08:17 +00004062 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
danielk1977da107192007-05-04 08:32:13 +00004063
drha38c9512014-04-01 01:24:34 +00004064 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
4065 ** Except, do not allocate aOverflow[] for eOp==2.
4066 **
4067 ** The aOverflow[] array is sized at one entry for each overflow page
4068 ** in the overflow chain. The page number of the first overflow page is
4069 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
4070 ** means "not yet known" (the cache is lazily populated).
danielk1977da107192007-05-04 08:32:13 +00004071 */
drh036dbec2014-03-11 23:40:44 +00004072 if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
danielk19772dec9702007-05-02 16:48:37 +00004073 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
dan5a500af2014-03-11 20:33:04 +00004074 if( nOvfl>pCur->nOvflAlloc ){
4075 Pgno *aNew = (Pgno*)sqlite3DbRealloc(
4076 pCur->pBtree->db, pCur->aOverflow, nOvfl*2*sizeof(Pgno)
4077 );
4078 if( aNew==0 ){
4079 rc = SQLITE_NOMEM;
4080 }else{
4081 pCur->nOvflAlloc = nOvfl*2;
4082 pCur->aOverflow = aNew;
4083 }
4084 }
4085 if( rc==SQLITE_OK ){
4086 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
drh036dbec2014-03-11 23:40:44 +00004087 pCur->curFlags |= BTCF_ValidOvfl;
danielk19772dec9702007-05-02 16:48:37 +00004088 }
4089 }
danielk1977da107192007-05-04 08:32:13 +00004090
4091 /* If the overflow page-list cache has been allocated and the
4092 ** entry for the first required overflow page is valid, skip
4093 ** directly to it.
4094 */
drh036dbec2014-03-11 23:40:44 +00004095 if( (pCur->curFlags & BTCF_ValidOvfl)!=0 && pCur->aOverflow[offset/ovflSize] ){
danielk19772dec9702007-05-02 16:48:37 +00004096 iIdx = (offset/ovflSize);
4097 nextPage = pCur->aOverflow[iIdx];
4098 offset = (offset%ovflSize);
4099 }
danielk1977da107192007-05-04 08:32:13 +00004100
4101 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
4102
danielk1977da107192007-05-04 08:32:13 +00004103 /* If required, populate the overflow page-list cache. */
drh036dbec2014-03-11 23:40:44 +00004104 if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
danielk1977da107192007-05-04 08:32:13 +00004105 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
4106 pCur->aOverflow[iIdx] = nextPage;
4107 }
danielk1977da107192007-05-04 08:32:13 +00004108
danielk1977d04417962007-05-02 13:16:30 +00004109 if( offset>=ovflSize ){
4110 /* The only reason to read this page is to obtain the page
danielk1977da107192007-05-04 08:32:13 +00004111 ** number for the next page in the overflow chain. The page
drhfd131da2007-08-07 17:13:03 +00004112 ** data is not required. So first try to lookup the overflow
4113 ** page-list cache, if any, then fall back to the getOverflowPage()
danielk1977da107192007-05-04 08:32:13 +00004114 ** function.
drha38c9512014-04-01 01:24:34 +00004115 **
4116 ** Note that the aOverflow[] array must be allocated because eOp!=2
4117 ** here. If eOp==2, then offset==0 and this branch is never taken.
danielk1977d04417962007-05-02 13:16:30 +00004118 */
drha38c9512014-04-01 01:24:34 +00004119 assert( eOp!=2 );
4120 assert( pCur->curFlags & BTCF_ValidOvfl );
4121 if( pCur->aOverflow[iIdx+1] ){
danielk1977da107192007-05-04 08:32:13 +00004122 nextPage = pCur->aOverflow[iIdx+1];
drha38c9512014-04-01 01:24:34 +00004123 }else{
danielk1977da107192007-05-04 08:32:13 +00004124 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
drha38c9512014-04-01 01:24:34 +00004125 }
danielk1977da107192007-05-04 08:32:13 +00004126 offset -= ovflSize;
danielk1977d04417962007-05-02 13:16:30 +00004127 }else{
danielk19779f8d6402007-05-02 17:48:45 +00004128 /* Need to read this page properly. It contains some of the
4129 ** range of data that is being read (eOp==0) or written (eOp!=0).
danielk1977d04417962007-05-02 13:16:30 +00004130 */
danf4ba1092011-10-08 14:57:07 +00004131#ifdef SQLITE_DIRECT_OVERFLOW_READ
4132 sqlite3_file *fd;
4133#endif
danielk1977cfe9a692004-06-16 12:00:29 +00004134 int a = amt;
danf4ba1092011-10-08 14:57:07 +00004135 if( a + offset > ovflSize ){
4136 a = ovflSize - offset;
danielk19779f8d6402007-05-02 17:48:45 +00004137 }
danf4ba1092011-10-08 14:57:07 +00004138
4139#ifdef SQLITE_DIRECT_OVERFLOW_READ
4140 /* If all the following are true:
4141 **
4142 ** 1) this is a read operation, and
4143 ** 2) data is required from the start of this overflow page, and
4144 ** 3) the database is file-backed, and
4145 ** 4) there is no open write-transaction, and
4146 ** 5) the database is not a WAL database,
dan9bc21b52014-03-20 18:56:35 +00004147 ** 6) all data from the page is being read.
danf4ba1092011-10-08 14:57:07 +00004148 **
4149 ** then data can be read directly from the database file into the
4150 ** output buffer, bypassing the page-cache altogether. This speeds
4151 ** up loading large records that span many overflow pages.
4152 */
dan5a500af2014-03-11 20:33:04 +00004153 if( (eOp&0x01)==0 /* (1) */
danf4ba1092011-10-08 14:57:07 +00004154 && offset==0 /* (2) */
dan9bc21b52014-03-20 18:56:35 +00004155 && (bEnd || a==ovflSize) /* (6) */
danf4ba1092011-10-08 14:57:07 +00004156 && pBt->inTransaction==TRANS_READ /* (4) */
4157 && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
4158 && pBt->pPage1->aData[19]==0x01 /* (5) */
4159 ){
4160 u8 aSave[4];
4161 u8 *aWrite = &pBuf[-4];
4162 memcpy(aSave, aWrite, 4);
dan27d47fb2011-12-21 17:00:16 +00004163 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
danf4ba1092011-10-08 14:57:07 +00004164 nextPage = get4byte(aWrite);
4165 memcpy(aWrite, aSave, 4);
4166 }else
4167#endif
4168
4169 {
4170 DbPage *pDbPage;
dan11dcd112013-03-15 18:29:18 +00004171 rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
dan5a500af2014-03-11 20:33:04 +00004172 ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
dan11dcd112013-03-15 18:29:18 +00004173 );
danf4ba1092011-10-08 14:57:07 +00004174 if( rc==SQLITE_OK ){
4175 aPayload = sqlite3PagerGetData(pDbPage);
4176 nextPage = get4byte(aPayload);
dan5a500af2014-03-11 20:33:04 +00004177 rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
danf4ba1092011-10-08 14:57:07 +00004178 sqlite3PagerUnref(pDbPage);
4179 offset = 0;
4180 }
4181 }
4182 amt -= a;
4183 pBuf += a;
danielk1977cfe9a692004-06-16 12:00:29 +00004184 }
drh2af926b2001-05-15 00:39:25 +00004185 }
drh2af926b2001-05-15 00:39:25 +00004186 }
danielk1977cfe9a692004-06-16 12:00:29 +00004187
danielk1977da107192007-05-04 08:32:13 +00004188 if( rc==SQLITE_OK && amt>0 ){
drh49285702005-09-17 15:20:26 +00004189 return SQLITE_CORRUPT_BKPT;
drha7fcb052001-12-14 15:09:55 +00004190 }
danielk1977da107192007-05-04 08:32:13 +00004191 return rc;
drh2af926b2001-05-15 00:39:25 +00004192}
4193
drh72f82862001-05-24 21:06:34 +00004194/*
drh3aac2dd2004-04-26 14:10:20 +00004195** Read part of the key associated with cursor pCur. Exactly
peter.d.reid60ec9142014-09-06 16:39:46 +00004196** "amt" bytes will be transferred into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00004197** begins at "offset".
drh8c1238a2003-01-02 14:43:55 +00004198**
drh5d1a8722009-07-22 18:07:40 +00004199** The caller must ensure that pCur is pointing to a valid row
4200** in the table.
4201**
drh3aac2dd2004-04-26 14:10:20 +00004202** Return SQLITE_OK on success or an error code if anything goes
4203** wrong. An error is returned if "offset+amt" is larger than
4204** the available payload.
drh72f82862001-05-24 21:06:34 +00004205*/
drha34b6762004-05-07 13:30:42 +00004206int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drh1fee73e2007-08-29 04:00:57 +00004207 assert( cursorHoldsMutex(pCur) );
drh5d1a8722009-07-22 18:07:40 +00004208 assert( pCur->eState==CURSOR_VALID );
4209 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
4210 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
4211 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
drh3aac2dd2004-04-26 14:10:20 +00004212}
4213
4214/*
drh3aac2dd2004-04-26 14:10:20 +00004215** Read part of the data associated with cursor pCur. Exactly
drha34b6762004-05-07 13:30:42 +00004216** "amt" bytes will be transfered into pBuf[]. The transfer
drh3aac2dd2004-04-26 14:10:20 +00004217** begins at "offset".
4218**
4219** Return SQLITE_OK on success or an error code if anything goes
4220** wrong. An error is returned if "offset+amt" is larger than
4221** the available payload.
drh72f82862001-05-24 21:06:34 +00004222*/
drh3aac2dd2004-04-26 14:10:20 +00004223int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
drhd677b3d2007-08-20 22:48:41 +00004224 int rc;
4225
danielk19773588ceb2008-06-10 17:30:26 +00004226#ifndef SQLITE_OMIT_INCRBLOB
4227 if ( pCur->eState==CURSOR_INVALID ){
4228 return SQLITE_ABORT;
4229 }
4230#endif
4231
drh1fee73e2007-08-29 04:00:57 +00004232 assert( cursorHoldsMutex(pCur) );
drha3460582008-07-11 21:02:53 +00004233 rc = restoreCursorPosition(pCur);
danielk1977da184232006-01-05 11:34:32 +00004234 if( rc==SQLITE_OK ){
4235 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004236 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
4237 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drhfb192682009-07-11 18:26:28 +00004238 rc = accessPayload(pCur, offset, amt, pBuf, 0);
danielk1977da184232006-01-05 11:34:32 +00004239 }
4240 return rc;
drh2af926b2001-05-15 00:39:25 +00004241}
4242
drh72f82862001-05-24 21:06:34 +00004243/*
drh0e1c19e2004-05-11 00:58:56 +00004244** Return a pointer to payload information from the entry that the
4245** pCur cursor is pointing to. The pointer is to the beginning of
drh2a8d2262013-12-09 20:43:22 +00004246** the key if index btrees (pPage->intKey==0) and is the data for
4247** table btrees (pPage->intKey==1). The number of bytes of available
4248** key/data is written into *pAmt. If *pAmt==0, then the value
4249** returned will not be a valid pointer.
drh0e1c19e2004-05-11 00:58:56 +00004250**
4251** This routine is an optimization. It is common for the entire key
4252** and data to fit on the local page and for there to be no overflow
4253** pages. When that is so, this routine can be used to access the
4254** key and data without making a copy. If the key and/or data spills
drh7f751222009-03-17 22:33:00 +00004255** onto overflow pages, then accessPayload() must be used to reassemble
drh0e1c19e2004-05-11 00:58:56 +00004256** the key/data and copy it into a preallocated buffer.
4257**
4258** The pointer returned by this routine looks directly into the cached
4259** page of the database. The data might change or move the next time
4260** any btree routine is called.
4261*/
drh2a8d2262013-12-09 20:43:22 +00004262static const void *fetchPayload(
drh0e1c19e2004-05-11 00:58:56 +00004263 BtCursor *pCur, /* Cursor pointing to entry to read from */
drh2a8d2262013-12-09 20:43:22 +00004264 u32 *pAmt /* Write the number of available bytes here */
drh0e1c19e2004-05-11 00:58:56 +00004265){
danielk197771d5d2c2008-09-29 11:49:47 +00004266 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
danielk1977da184232006-01-05 11:34:32 +00004267 assert( pCur->eState==CURSOR_VALID );
drh2a8d2262013-12-09 20:43:22 +00004268 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh1fee73e2007-08-29 04:00:57 +00004269 assert( cursorHoldsMutex(pCur) );
drh2a8d2262013-12-09 20:43:22 +00004270 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drh86dd3712014-03-25 11:00:21 +00004271 assert( pCur->info.nSize>0 );
drh2a8d2262013-12-09 20:43:22 +00004272 *pAmt = pCur->info.nLocal;
4273 return (void*)(pCur->info.pCell + pCur->info.nHeader);
drh0e1c19e2004-05-11 00:58:56 +00004274}
4275
4276
4277/*
drhe51c44f2004-05-30 20:46:09 +00004278** For the entry that cursor pCur is point to, return as
4279** many bytes of the key or data as are available on the local
4280** b-tree page. Write the number of available bytes into *pAmt.
drh0e1c19e2004-05-11 00:58:56 +00004281**
4282** The pointer returned is ephemeral. The key/data may move
drhd677b3d2007-08-20 22:48:41 +00004283** or be destroyed on the next call to any Btree routine,
4284** including calls from other threads against the same cache.
4285** Hence, a mutex on the BtShared should be held prior to calling
4286** this routine.
drh0e1c19e2004-05-11 00:58:56 +00004287**
4288** These routines is used to get quick access to key and data
4289** in the common case where no overflow pages are used.
drh0e1c19e2004-05-11 00:58:56 +00004290*/
drh501932c2013-11-21 21:59:53 +00004291const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
drh2a8d2262013-12-09 20:43:22 +00004292 return fetchPayload(pCur, pAmt);
drh0e1c19e2004-05-11 00:58:56 +00004293}
drh501932c2013-11-21 21:59:53 +00004294const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
drh2a8d2262013-12-09 20:43:22 +00004295 return fetchPayload(pCur, pAmt);
drh0e1c19e2004-05-11 00:58:56 +00004296}
4297
4298
4299/*
drh8178a752003-01-05 21:41:40 +00004300** Move the cursor down to a new child page. The newPgno argument is the
drhab01f612004-05-22 02:55:23 +00004301** page number of the child page to move to.
danielk1977a299d612009-07-13 11:22:10 +00004302**
4303** This function returns SQLITE_CORRUPT if the page-header flags field of
4304** the new child page does not match the flags field of the parent (i.e.
4305** if an intkey page appears to be the parent of a non-intkey page, or
4306** vice-versa).
drh72f82862001-05-24 21:06:34 +00004307*/
drh3aac2dd2004-04-26 14:10:20 +00004308static int moveToChild(BtCursor *pCur, u32 newPgno){
drh72f82862001-05-24 21:06:34 +00004309 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00004310 int i = pCur->iPage;
drh72f82862001-05-24 21:06:34 +00004311 MemPage *pNewPage;
drhd0679ed2007-08-28 22:24:34 +00004312 BtShared *pBt = pCur->pBt;
drh72f82862001-05-24 21:06:34 +00004313
drh1fee73e2007-08-29 04:00:57 +00004314 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004315 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004316 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
dan11dcd112013-03-15 18:29:18 +00004317 assert( pCur->iPage>=0 );
danielk197771d5d2c2008-09-29 11:49:47 +00004318 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
4319 return SQLITE_CORRUPT_BKPT;
4320 }
drhb00fc3b2013-08-21 23:42:32 +00004321 rc = getAndInitPage(pBt, newPgno, &pNewPage,
drh036dbec2014-03-11 23:40:44 +00004322 (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
drh6019e162001-07-02 17:51:45 +00004323 if( rc ) return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00004324 pCur->apPage[i+1] = pNewPage;
4325 pCur->aiIdx[i+1] = 0;
4326 pCur->iPage++;
4327
drh271efa52004-05-30 19:19:05 +00004328 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004329 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
danielk1977bd5969a2009-07-11 17:39:42 +00004330 if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
drh49285702005-09-17 15:20:26 +00004331 return SQLITE_CORRUPT_BKPT;
drh4be295b2003-12-16 03:44:47 +00004332 }
drh72f82862001-05-24 21:06:34 +00004333 return SQLITE_OK;
4334}
4335
danbb246c42012-01-12 14:25:55 +00004336#if 0
danielk1977bf93c562008-09-29 15:53:25 +00004337/*
4338** Page pParent is an internal (non-leaf) tree page. This function
4339** asserts that page number iChild is the left-child if the iIdx'th
4340** cell in page pParent. Or, if iIdx is equal to the total number of
4341** cells in pParent, that page number iChild is the right-child of
4342** the page.
4343*/
4344static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
4345 assert( iIdx<=pParent->nCell );
4346 if( iIdx==pParent->nCell ){
4347 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
4348 }else{
4349 assert( get4byte(findCell(pParent, iIdx))==iChild );
4350 }
4351}
4352#else
4353# define assertParentIndex(x,y,z)
4354#endif
4355
drh72f82862001-05-24 21:06:34 +00004356/*
drh5e2f8b92001-05-28 00:41:15 +00004357** Move the cursor up to the parent page.
4358**
4359** pCur->idx is set to the cell index that contains the pointer
4360** to the page we are coming from. If we are coming from the
4361** right-most child page then pCur->idx is set to one more than
drhbd03cae2001-06-02 02:40:57 +00004362** the largest cell index.
drh72f82862001-05-24 21:06:34 +00004363*/
danielk197730548662009-07-09 05:07:37 +00004364static void moveToParent(BtCursor *pCur){
drh1fee73e2007-08-29 04:00:57 +00004365 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004366 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004367 assert( pCur->iPage>0 );
4368 assert( pCur->apPage[pCur->iPage] );
danbb246c42012-01-12 14:25:55 +00004369
4370 /* UPDATE: It is actually possible for the condition tested by the assert
4371 ** below to be untrue if the database file is corrupt. This can occur if
4372 ** one cursor has modified page pParent while a reference to it is held
4373 ** by a second cursor. Which can only happen if a single page is linked
4374 ** into more than one b-tree structure in a corrupt database. */
4375#if 0
danielk1977bf93c562008-09-29 15:53:25 +00004376 assertParentIndex(
4377 pCur->apPage[pCur->iPage-1],
4378 pCur->aiIdx[pCur->iPage-1],
4379 pCur->apPage[pCur->iPage]->pgno
4380 );
danbb246c42012-01-12 14:25:55 +00004381#endif
dan6c2688c2012-01-12 15:05:03 +00004382 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
danbb246c42012-01-12 14:25:55 +00004383
danielk197771d5d2c2008-09-29 11:49:47 +00004384 releasePage(pCur->apPage[pCur->iPage]);
4385 pCur->iPage--;
drh271efa52004-05-30 19:19:05 +00004386 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004387 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
drh72f82862001-05-24 21:06:34 +00004388}
4389
4390/*
danielk19778f880a82009-07-13 09:41:45 +00004391** Move the cursor to point to the root page of its b-tree structure.
4392**
4393** If the table has a virtual root page, then the cursor is moved to point
4394** to the virtual root page instead of the actual root page. A table has a
4395** virtual root page when the actual root page contains no cells and a
4396** single child page. This can only happen with the table rooted at page 1.
4397**
4398** If the b-tree structure is empty, the cursor state is set to
4399** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
4400** cell located on the root (or virtual root) page and the cursor state
4401** is set to CURSOR_VALID.
4402**
4403** If this function returns successfully, it may be assumed that the
4404** page-header flags indicate that the [virtual] root-page is the expected
4405** kind of b-tree page (i.e. if when opening the cursor the caller did not
4406** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
4407** indicating a table b-tree, or if the caller did specify a KeyInfo
4408** structure the flags byte is set to 0x02 or 0x0A, indicating an index
4409** b-tree).
drh72f82862001-05-24 21:06:34 +00004410*/
drh5e2f8b92001-05-28 00:41:15 +00004411static int moveToRoot(BtCursor *pCur){
drh3aac2dd2004-04-26 14:10:20 +00004412 MemPage *pRoot;
drh777e4c42006-01-13 04:31:58 +00004413 int rc = SQLITE_OK;
drhbd03cae2001-06-02 02:40:57 +00004414
drh1fee73e2007-08-29 04:00:57 +00004415 assert( cursorHoldsMutex(pCur) );
drhfb982642007-08-30 01:19:59 +00004416 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
4417 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
4418 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
4419 if( pCur->eState>=CURSOR_REQUIRESEEK ){
4420 if( pCur->eState==CURSOR_FAULT ){
drh4c301aa2009-07-15 17:25:45 +00004421 assert( pCur->skipNext!=SQLITE_OK );
4422 return pCur->skipNext;
drhfb982642007-08-30 01:19:59 +00004423 }
danielk1977be51a652008-10-08 17:58:48 +00004424 sqlite3BtreeClearCursor(pCur);
drhbf700f32007-03-31 02:36:44 +00004425 }
danielk197771d5d2c2008-09-29 11:49:47 +00004426
4427 if( pCur->iPage>=0 ){
drh4e8fe3f2013-12-06 23:25:27 +00004428 while( pCur->iPage ) releasePage(pCur->apPage[pCur->iPage--]);
dana205a482011-08-27 18:48:57 +00004429 }else if( pCur->pgnoRoot==0 ){
4430 pCur->eState = CURSOR_INVALID;
4431 return SQLITE_OK;
drh777e4c42006-01-13 04:31:58 +00004432 }else{
drh4e8fe3f2013-12-06 23:25:27 +00004433 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
drh036dbec2014-03-11 23:40:44 +00004434 (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
drh4c301aa2009-07-15 17:25:45 +00004435 if( rc!=SQLITE_OK ){
drh777e4c42006-01-13 04:31:58 +00004436 pCur->eState = CURSOR_INVALID;
4437 return rc;
4438 }
danielk1977172114a2009-07-07 15:47:12 +00004439 pCur->iPage = 0;
drhc39e0002004-05-07 23:50:57 +00004440 }
danielk197771d5d2c2008-09-29 11:49:47 +00004441 pRoot = pCur->apPage[0];
4442 assert( pRoot->pgno==pCur->pgnoRoot );
dan7df42ab2014-01-20 18:25:44 +00004443
4444 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
4445 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
4446 ** NULL, the caller expects a table b-tree. If this is not the case,
4447 ** return an SQLITE_CORRUPT error.
4448 **
4449 ** Earlier versions of SQLite assumed that this test could not fail
4450 ** if the root page was already loaded when this function was called (i.e.
4451 ** if pCur->iPage>=0). But this is not so if the database is corrupted
4452 ** in such a way that page pRoot is linked into a second b-tree table
4453 ** (or the freelist). */
4454 assert( pRoot->intKey==1 || pRoot->intKey==0 );
4455 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
4456 return SQLITE_CORRUPT_BKPT;
4457 }
danielk19778f880a82009-07-13 09:41:45 +00004458
danielk197771d5d2c2008-09-29 11:49:47 +00004459 pCur->aiIdx[0] = 0;
drh271efa52004-05-30 19:19:05 +00004460 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004461 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
danielk197771d5d2c2008-09-29 11:49:47 +00004462
drh4e8fe3f2013-12-06 23:25:27 +00004463 if( pRoot->nCell>0 ){
4464 pCur->eState = CURSOR_VALID;
4465 }else if( !pRoot->leaf ){
drh8856d6a2004-04-29 14:42:46 +00004466 Pgno subpage;
drhc85240d2009-06-04 16:14:33 +00004467 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
drh43605152004-05-29 21:46:49 +00004468 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
danielk1977da184232006-01-05 11:34:32 +00004469 pCur->eState = CURSOR_VALID;
drh4b70f112004-05-02 21:12:19 +00004470 rc = moveToChild(pCur, subpage);
danielk197771d5d2c2008-09-29 11:49:47 +00004471 }else{
drh4e8fe3f2013-12-06 23:25:27 +00004472 pCur->eState = CURSOR_INVALID;
drh8856d6a2004-04-29 14:42:46 +00004473 }
4474 return rc;
drh72f82862001-05-24 21:06:34 +00004475}
drh2af926b2001-05-15 00:39:25 +00004476
drh5e2f8b92001-05-28 00:41:15 +00004477/*
4478** Move the cursor down to the left-most leaf entry beneath the
4479** entry to which it is currently pointing.
drh777e4c42006-01-13 04:31:58 +00004480**
4481** The left-most leaf is the one with the smallest key - the first
4482** in ascending order.
drh5e2f8b92001-05-28 00:41:15 +00004483*/
4484static int moveToLeftmost(BtCursor *pCur){
4485 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00004486 int rc = SQLITE_OK;
drh3aac2dd2004-04-26 14:10:20 +00004487 MemPage *pPage;
drh5e2f8b92001-05-28 00:41:15 +00004488
drh1fee73e2007-08-29 04:00:57 +00004489 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004490 assert( pCur->eState==CURSOR_VALID );
danielk197771d5d2c2008-09-29 11:49:47 +00004491 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
4492 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
4493 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
drh8178a752003-01-05 21:41:40 +00004494 rc = moveToChild(pCur, pgno);
drh5e2f8b92001-05-28 00:41:15 +00004495 }
drhd677b3d2007-08-20 22:48:41 +00004496 return rc;
drh5e2f8b92001-05-28 00:41:15 +00004497}
4498
drh2dcc9aa2002-12-04 13:40:25 +00004499/*
4500** Move the cursor down to the right-most leaf entry beneath the
4501** page to which it is currently pointing. Notice the difference
4502** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
4503** finds the left-most entry beneath the *entry* whereas moveToRightmost()
4504** finds the right-most entry beneath the *page*.
drh777e4c42006-01-13 04:31:58 +00004505**
4506** The right-most entry is the one with the largest key - the last
4507** key in ascending order.
drh2dcc9aa2002-12-04 13:40:25 +00004508*/
4509static int moveToRightmost(BtCursor *pCur){
4510 Pgno pgno;
drhd677b3d2007-08-20 22:48:41 +00004511 int rc = SQLITE_OK;
drh1bd10f82008-12-10 21:19:56 +00004512 MemPage *pPage = 0;
drh2dcc9aa2002-12-04 13:40:25 +00004513
drh1fee73e2007-08-29 04:00:57 +00004514 assert( cursorHoldsMutex(pCur) );
danielk1977da184232006-01-05 11:34:32 +00004515 assert( pCur->eState==CURSOR_VALID );
drhee6438d2014-09-01 13:29:32 +00004516 while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
drh43605152004-05-29 21:46:49 +00004517 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
danielk197771d5d2c2008-09-29 11:49:47 +00004518 pCur->aiIdx[pCur->iPage] = pPage->nCell;
drh8178a752003-01-05 21:41:40 +00004519 rc = moveToChild(pCur, pgno);
drhee6438d2014-09-01 13:29:32 +00004520 if( rc ) return rc;
drh2dcc9aa2002-12-04 13:40:25 +00004521 }
drhee6438d2014-09-01 13:29:32 +00004522 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
4523 assert( pCur->info.nSize==0 );
4524 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
4525 return SQLITE_OK;
drh2dcc9aa2002-12-04 13:40:25 +00004526}
4527
drh5e00f6c2001-09-13 13:46:56 +00004528/* Move the cursor to the first entry in the table. Return SQLITE_OK
4529** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00004530** or set *pRes to 1 if the table is empty.
drh5e00f6c2001-09-13 13:46:56 +00004531*/
drh3aac2dd2004-04-26 14:10:20 +00004532int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
drh5e00f6c2001-09-13 13:46:56 +00004533 int rc;
drhd677b3d2007-08-20 22:48:41 +00004534
drh1fee73e2007-08-29 04:00:57 +00004535 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004536 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
drh5e00f6c2001-09-13 13:46:56 +00004537 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004538 if( rc==SQLITE_OK ){
4539 if( pCur->eState==CURSOR_INVALID ){
dana205a482011-08-27 18:48:57 +00004540 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00004541 *pRes = 1;
drhd677b3d2007-08-20 22:48:41 +00004542 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00004543 assert( pCur->apPage[pCur->iPage]->nCell>0 );
drhd677b3d2007-08-20 22:48:41 +00004544 *pRes = 0;
4545 rc = moveToLeftmost(pCur);
4546 }
drh5e00f6c2001-09-13 13:46:56 +00004547 }
drh5e00f6c2001-09-13 13:46:56 +00004548 return rc;
4549}
drh5e2f8b92001-05-28 00:41:15 +00004550
drh9562b552002-02-19 15:00:07 +00004551/* Move the cursor to the last entry in the table. Return SQLITE_OK
4552** on success. Set *pRes to 0 if the cursor actually points to something
drh77c679c2002-02-19 22:43:58 +00004553** or set *pRes to 1 if the table is empty.
drh9562b552002-02-19 15:00:07 +00004554*/
drh3aac2dd2004-04-26 14:10:20 +00004555int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
drh9562b552002-02-19 15:00:07 +00004556 int rc;
drhd677b3d2007-08-20 22:48:41 +00004557
drh1fee73e2007-08-29 04:00:57 +00004558 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004559 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19773f632d52009-05-02 10:03:09 +00004560
4561 /* If the cursor already points to the last entry, this is a no-op. */
drh036dbec2014-03-11 23:40:44 +00004562 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
danielk19773f632d52009-05-02 10:03:09 +00004563#ifdef SQLITE_DEBUG
4564 /* This block serves to assert() that the cursor really does point
4565 ** to the last entry in the b-tree. */
4566 int ii;
4567 for(ii=0; ii<pCur->iPage; ii++){
4568 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
4569 }
4570 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
4571 assert( pCur->apPage[pCur->iPage]->leaf );
4572#endif
4573 return SQLITE_OK;
4574 }
4575
drh9562b552002-02-19 15:00:07 +00004576 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004577 if( rc==SQLITE_OK ){
4578 if( CURSOR_INVALID==pCur->eState ){
dana205a482011-08-27 18:48:57 +00004579 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
drhd677b3d2007-08-20 22:48:41 +00004580 *pRes = 1;
4581 }else{
4582 assert( pCur->eState==CURSOR_VALID );
4583 *pRes = 0;
4584 rc = moveToRightmost(pCur);
drh036dbec2014-03-11 23:40:44 +00004585 if( rc==SQLITE_OK ){
4586 pCur->curFlags |= BTCF_AtLast;
4587 }else{
4588 pCur->curFlags &= ~BTCF_AtLast;
4589 }
4590
drhd677b3d2007-08-20 22:48:41 +00004591 }
drh9562b552002-02-19 15:00:07 +00004592 }
drh9562b552002-02-19 15:00:07 +00004593 return rc;
4594}
4595
drhe14006d2008-03-25 17:23:32 +00004596/* Move the cursor so that it points to an entry near the key
drhe63d9992008-08-13 19:11:48 +00004597** specified by pIdxKey or intKey. Return a success code.
drh72f82862001-05-24 21:06:34 +00004598**
drhe63d9992008-08-13 19:11:48 +00004599** For INTKEY tables, the intKey parameter is used. pIdxKey
4600** must be NULL. For index tables, pIdxKey is used and intKey
4601** is ignored.
drh3aac2dd2004-04-26 14:10:20 +00004602**
drh5e2f8b92001-05-28 00:41:15 +00004603** If an exact match is not found, then the cursor is always
drhbd03cae2001-06-02 02:40:57 +00004604** left pointing at a leaf page which would hold the entry if it
drh5e2f8b92001-05-28 00:41:15 +00004605** were present. The cursor might point to an entry that comes
4606** before or after the key.
4607**
drh64022502009-01-09 14:11:04 +00004608** An integer is written into *pRes which is the result of
4609** comparing the key with the entry to which the cursor is
4610** pointing. The meaning of the integer written into
4611** *pRes is as follows:
drhbd03cae2001-06-02 02:40:57 +00004612**
4613** *pRes<0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004614** is smaller than intKey/pIdxKey or if the table is empty
drh1a844c32002-12-04 22:29:28 +00004615** and the cursor is therefore left point to nothing.
drhbd03cae2001-06-02 02:40:57 +00004616**
4617** *pRes==0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004618** exactly matches intKey/pIdxKey.
drhbd03cae2001-06-02 02:40:57 +00004619**
4620** *pRes>0 The cursor is left pointing at an entry that
drh64022502009-01-09 14:11:04 +00004621** is larger than intKey/pIdxKey.
drhd677b3d2007-08-20 22:48:41 +00004622**
drha059ad02001-04-17 20:09:11 +00004623*/
drhe63d9992008-08-13 19:11:48 +00004624int sqlite3BtreeMovetoUnpacked(
4625 BtCursor *pCur, /* The cursor to be moved */
4626 UnpackedRecord *pIdxKey, /* Unpacked index key */
4627 i64 intKey, /* The table key */
4628 int biasRight, /* If true, bias the search to the high end */
4629 int *pRes /* Write search results here */
drhe4d90812007-03-29 05:51:49 +00004630){
drh72f82862001-05-24 21:06:34 +00004631 int rc;
dan3b9330f2014-02-27 20:44:18 +00004632 RecordCompare xRecordCompare;
drhd677b3d2007-08-20 22:48:41 +00004633
drh1fee73e2007-08-29 04:00:57 +00004634 assert( cursorHoldsMutex(pCur) );
drhe5fe6902007-12-07 18:55:28 +00004635 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
danielk19775cb09632009-07-09 11:36:01 +00004636 assert( pRes );
danielk19773fd7cf52009-07-13 07:30:52 +00004637 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
drha2c20e42008-03-29 16:01:04 +00004638
4639 /* If the cursor is already positioned at the point we are trying
4640 ** to move to, then just return without doing any work */
drh036dbec2014-03-11 23:40:44 +00004641 if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
danielk197771d5d2c2008-09-29 11:49:47 +00004642 && pCur->apPage[0]->intKey
4643 ){
drhe63d9992008-08-13 19:11:48 +00004644 if( pCur->info.nKey==intKey ){
drha2c20e42008-03-29 16:01:04 +00004645 *pRes = 0;
4646 return SQLITE_OK;
4647 }
drh036dbec2014-03-11 23:40:44 +00004648 if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
drha2c20e42008-03-29 16:01:04 +00004649 *pRes = -1;
4650 return SQLITE_OK;
4651 }
4652 }
4653
dan1fed5da2014-02-25 21:01:25 +00004654 if( pIdxKey ){
4655 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
dan38fdead2014-04-01 10:19:02 +00004656 pIdxKey->errCode = 0;
dan3b9330f2014-02-27 20:44:18 +00004657 assert( pIdxKey->default_rc==1
4658 || pIdxKey->default_rc==0
4659 || pIdxKey->default_rc==-1
4660 );
drh13a747e2014-03-03 21:46:55 +00004661 }else{
drhb6e8fd12014-03-06 01:56:33 +00004662 xRecordCompare = 0; /* All keys are integers */
dan1fed5da2014-02-25 21:01:25 +00004663 }
4664
drh5e2f8b92001-05-28 00:41:15 +00004665 rc = moveToRoot(pCur);
drhd677b3d2007-08-20 22:48:41 +00004666 if( rc ){
4667 return rc;
4668 }
dana205a482011-08-27 18:48:57 +00004669 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
4670 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
4671 assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
danielk1977da184232006-01-05 11:34:32 +00004672 if( pCur->eState==CURSOR_INVALID ){
drhf328bc82004-05-10 23:29:49 +00004673 *pRes = -1;
dana205a482011-08-27 18:48:57 +00004674 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
drhc39e0002004-05-07 23:50:57 +00004675 return SQLITE_OK;
4676 }
danielk197771d5d2c2008-09-29 11:49:47 +00004677 assert( pCur->apPage[0]->intKey || pIdxKey );
drh14684382006-11-30 13:05:29 +00004678 for(;;){
drhec3e6b12013-11-25 02:38:55 +00004679 int lwr, upr, idx, c;
drh72f82862001-05-24 21:06:34 +00004680 Pgno chldPg;
danielk197771d5d2c2008-09-29 11:49:47 +00004681 MemPage *pPage = pCur->apPage[pCur->iPage];
drhec3e6b12013-11-25 02:38:55 +00004682 u8 *pCell; /* Pointer to current cell in pPage */
danielk1977171fff32009-07-11 05:06:51 +00004683
4684 /* pPage->nCell must be greater than zero. If this is the root-page
4685 ** the cursor would have been INVALID above and this for(;;) loop
4686 ** not run. If this is not the root-page, then the moveToChild() routine
danielk19773fd7cf52009-07-13 07:30:52 +00004687 ** would have already detected db corruption. Similarly, pPage must
4688 ** be the right kind (index or table) of b-tree page. Otherwise
4689 ** a moveToChild() or moveToRoot() call would have detected corruption. */
danielk1977171fff32009-07-11 05:06:51 +00004690 assert( pPage->nCell>0 );
danielk19773fd7cf52009-07-13 07:30:52 +00004691 assert( pPage->intKey==(pIdxKey==0) );
drh72f82862001-05-24 21:06:34 +00004692 lwr = 0;
4693 upr = pPage->nCell-1;
drhebf10b12013-11-25 17:38:26 +00004694 assert( biasRight==0 || biasRight==1 );
4695 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
drhd793f442013-11-25 14:10:15 +00004696 pCur->aiIdx[pCur->iPage] = (u16)idx;
dana4660bd2014-03-04 16:05:25 +00004697 if( xRecordCompare==0 ){
drhec3e6b12013-11-25 02:38:55 +00004698 for(;;){
danielk197711c327a2009-05-04 19:01:26 +00004699 i64 nCellKey;
drhec3e6b12013-11-25 02:38:55 +00004700 pCell = findCell(pPage, idx) + pPage->childPtrSize;
drhd172f862006-01-12 15:01:15 +00004701 if( pPage->hasData ){
drh9b2fc612013-11-25 20:14:13 +00004702 while( 0x80 <= *(pCell++) ){
4703 if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
4704 }
drhd172f862006-01-12 15:01:15 +00004705 }
drha2c20e42008-03-29 16:01:04 +00004706 getVarint(pCell, (u64*)&nCellKey);
drhbb933ef2013-11-25 15:01:38 +00004707 if( nCellKey<intKey ){
4708 lwr = idx+1;
4709 if( lwr>upr ){ c = -1; break; }
4710 }else if( nCellKey>intKey ){
4711 upr = idx-1;
4712 if( lwr>upr ){ c = +1; break; }
4713 }else{
4714 assert( nCellKey==intKey );
drh036dbec2014-03-11 23:40:44 +00004715 pCur->curFlags |= BTCF_ValidNKey;
drhec3e6b12013-11-25 02:38:55 +00004716 pCur->info.nKey = nCellKey;
drhd793f442013-11-25 14:10:15 +00004717 pCur->aiIdx[pCur->iPage] = (u16)idx;
drhec3e6b12013-11-25 02:38:55 +00004718 if( !pPage->leaf ){
4719 lwr = idx;
drhebf10b12013-11-25 17:38:26 +00004720 goto moveto_next_layer;
drhec3e6b12013-11-25 02:38:55 +00004721 }else{
4722 *pRes = 0;
4723 rc = SQLITE_OK;
4724 goto moveto_finish;
4725 }
drhd793f442013-11-25 14:10:15 +00004726 }
drhebf10b12013-11-25 17:38:26 +00004727 assert( lwr+upr>=0 );
4728 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
drhec3e6b12013-11-25 02:38:55 +00004729 }
4730 }else{
4731 for(;;){
4732 int nCell;
drhec3e6b12013-11-25 02:38:55 +00004733 pCell = findCell(pPage, idx) + pPage->childPtrSize;
4734
drhb2eced52010-08-12 02:41:12 +00004735 /* The maximum supported page-size is 65536 bytes. This means that
danielk197711c327a2009-05-04 19:01:26 +00004736 ** the maximum number of record bytes stored on an index B-Tree
drhb2eced52010-08-12 02:41:12 +00004737 ** page is less than 16384 bytes and may be stored as a 2-byte
danielk197711c327a2009-05-04 19:01:26 +00004738 ** varint. This information is used to attempt to avoid parsing
4739 ** the entire cell by checking for the cases where the record is
4740 ** stored entirely within the b-tree page by inspecting the first
4741 ** 2 bytes of the cell.
4742 */
drhec3e6b12013-11-25 02:38:55 +00004743 nCell = pCell[0];
drh72b8ef62013-12-06 22:44:51 +00004744 if( nCell<=pPage->max1bytePayload ){
danielk197711c327a2009-05-04 19:01:26 +00004745 /* This branch runs if the record-size field of the cell is a
4746 ** single byte varint and the record fits entirely on the main
4747 ** b-tree page. */
drh3def2352011-11-11 00:27:15 +00004748 testcase( pCell+nCell+1==pPage->aDataEnd );
drh75179de2014-09-16 14:37:35 +00004749 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
danielk197711c327a2009-05-04 19:01:26 +00004750 }else if( !(pCell[1] & 0x80)
4751 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
4752 ){
4753 /* The record-size field is a 2 byte varint and the record
4754 ** fits entirely on the main b-tree page. */
drh3def2352011-11-11 00:27:15 +00004755 testcase( pCell+nCell+2==pPage->aDataEnd );
drh75179de2014-09-16 14:37:35 +00004756 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
drhe51c44f2004-05-30 20:46:09 +00004757 }else{
danielk197711c327a2009-05-04 19:01:26 +00004758 /* The record flows over onto one or more overflow pages. In
4759 ** this case the whole cell needs to be parsed, a buffer allocated
4760 ** and accessPayload() used to retrieve the record into the
4761 ** buffer before VdbeRecordCompare() can be called. */
4762 void *pCellKey;
4763 u8 * const pCellBody = pCell - pPage->childPtrSize;
danielk197730548662009-07-09 05:07:37 +00004764 btreeParseCellPtr(pPage, pCellBody, &pCur->info);
shane60a4b532009-05-06 18:57:09 +00004765 nCell = (int)pCur->info.nKey;
danielk197711c327a2009-05-04 19:01:26 +00004766 pCellKey = sqlite3Malloc( nCell );
danielk19776507ecb2008-03-25 09:56:44 +00004767 if( pCellKey==0 ){
4768 rc = SQLITE_NOMEM;
4769 goto moveto_finish;
4770 }
drhd793f442013-11-25 14:10:15 +00004771 pCur->aiIdx[pCur->iPage] = (u16)idx;
dan5a500af2014-03-11 20:33:04 +00004772 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
drhec9b31f2009-08-25 13:53:49 +00004773 if( rc ){
4774 sqlite3_free(pCellKey);
4775 goto moveto_finish;
4776 }
drh75179de2014-09-16 14:37:35 +00004777 c = xRecordCompare(nCell, pCellKey, pIdxKey);
drhfacf0302008-06-17 15:12:00 +00004778 sqlite3_free(pCellKey);
drhe51c44f2004-05-30 20:46:09 +00004779 }
dan38fdead2014-04-01 10:19:02 +00004780 assert(
4781 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
dana7bf23c2014-05-02 17:12:41 +00004782 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
dan38fdead2014-04-01 10:19:02 +00004783 );
drhbb933ef2013-11-25 15:01:38 +00004784 if( c<0 ){
4785 lwr = idx+1;
4786 }else if( c>0 ){
4787 upr = idx-1;
4788 }else{
4789 assert( c==0 );
drh64022502009-01-09 14:11:04 +00004790 *pRes = 0;
drh1e968a02008-03-25 00:22:21 +00004791 rc = SQLITE_OK;
drhd793f442013-11-25 14:10:15 +00004792 pCur->aiIdx[pCur->iPage] = (u16)idx;
dan38fdead2014-04-01 10:19:02 +00004793 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
drh1e968a02008-03-25 00:22:21 +00004794 goto moveto_finish;
drh8b18dd42004-05-12 19:18:15 +00004795 }
drhebf10b12013-11-25 17:38:26 +00004796 if( lwr>upr ) break;
4797 assert( lwr+upr>=0 );
4798 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
drh72f82862001-05-24 21:06:34 +00004799 }
drh72f82862001-05-24 21:06:34 +00004800 }
drhb07028f2011-10-14 21:49:18 +00004801 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
danielk197771d5d2c2008-09-29 11:49:47 +00004802 assert( pPage->isInit );
drh3aac2dd2004-04-26 14:10:20 +00004803 if( pPage->leaf ){
drhec3e6b12013-11-25 02:38:55 +00004804 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
drhbb933ef2013-11-25 15:01:38 +00004805 pCur->aiIdx[pCur->iPage] = (u16)idx;
drhec3e6b12013-11-25 02:38:55 +00004806 *pRes = c;
4807 rc = SQLITE_OK;
4808 goto moveto_finish;
drhebf10b12013-11-25 17:38:26 +00004809 }
4810moveto_next_layer:
4811 if( lwr>=pPage->nCell ){
drh43605152004-05-29 21:46:49 +00004812 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh72f82862001-05-24 21:06:34 +00004813 }else{
danielk19771cc5ed82007-05-16 17:28:43 +00004814 chldPg = get4byte(findCell(pPage, lwr));
drh72f82862001-05-24 21:06:34 +00004815 }
drhf49661a2008-12-10 16:45:50 +00004816 pCur->aiIdx[pCur->iPage] = (u16)lwr;
drh8178a752003-01-05 21:41:40 +00004817 rc = moveToChild(pCur, chldPg);
drhec3e6b12013-11-25 02:38:55 +00004818 if( rc ) break;
drh72f82862001-05-24 21:06:34 +00004819 }
drh1e968a02008-03-25 00:22:21 +00004820moveto_finish:
drhd2022b02013-11-25 16:23:52 +00004821 pCur->info.nSize = 0;
drh036dbec2014-03-11 23:40:44 +00004822 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
drhe63d9992008-08-13 19:11:48 +00004823 return rc;
4824}
4825
drhd677b3d2007-08-20 22:48:41 +00004826
drh72f82862001-05-24 21:06:34 +00004827/*
drhc39e0002004-05-07 23:50:57 +00004828** Return TRUE if the cursor is not pointing at an entry of the table.
4829**
4830** TRUE will be returned after a call to sqlite3BtreeNext() moves
4831** past the last entry in the table or sqlite3BtreePrev() moves past
4832** the first entry. TRUE is also returned if the table is empty.
4833*/
4834int sqlite3BtreeEof(BtCursor *pCur){
danielk1977da184232006-01-05 11:34:32 +00004835 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
4836 ** have been deleted? This API will need to change to return an error code
4837 ** as well as the boolean result value.
4838 */
4839 return (CURSOR_VALID!=pCur->eState);
drhc39e0002004-05-07 23:50:57 +00004840}
4841
4842/*
drhbd03cae2001-06-02 02:40:57 +00004843** Advance the cursor to the next entry in the database. If
drh8c1238a2003-01-02 14:43:55 +00004844** successful then set *pRes=0. If the cursor
drhbd03cae2001-06-02 02:40:57 +00004845** was already pointing to the last entry in the database before
drh8c1238a2003-01-02 14:43:55 +00004846** this routine was called, then set *pRes=1.
drhe39a7322014-02-03 14:04:11 +00004847**
drhee6438d2014-09-01 13:29:32 +00004848** The main entry point is sqlite3BtreeNext(). That routine is optimized
4849** for the common case of merely incrementing the cell counter BtCursor.aiIdx
4850** to the next cell on the current page. The (slower) btreeNext() helper
4851** routine is called when it is necessary to move to a different page or
4852** to restore the cursor.
4853**
drhe39a7322014-02-03 14:04:11 +00004854** The calling function will set *pRes to 0 or 1. The initial *pRes value
4855** will be 1 if the cursor being stepped corresponds to an SQL index and
4856** if this routine could have been skipped if that SQL index had been
4857** a unique index. Otherwise the caller will have set *pRes to zero.
4858** Zero is the common case. The btree implementation is free to use the
4859** initial *pRes value as a hint to improve performance, but the current
4860** SQLite btree implementation does not. (Note that the comdb2 btree
4861** implementation does use this hint, however.)
drh72f82862001-05-24 21:06:34 +00004862*/
drhee6438d2014-09-01 13:29:32 +00004863static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
drh72f82862001-05-24 21:06:34 +00004864 int rc;
danielk197771d5d2c2008-09-29 11:49:47 +00004865 int idx;
danielk197797a227c2006-01-20 16:32:04 +00004866 MemPage *pPage;
drh8b18dd42004-05-12 19:18:15 +00004867
drh1fee73e2007-08-29 04:00:57 +00004868 assert( cursorHoldsMutex(pCur) );
drh9b47ee32013-08-20 03:13:51 +00004869 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
drhee6438d2014-09-01 13:29:32 +00004870 assert( *pRes==0 );
drhf66f26a2013-08-19 20:04:10 +00004871 if( pCur->eState!=CURSOR_VALID ){
drhee6438d2014-09-01 13:29:32 +00004872 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
drhf66f26a2013-08-19 20:04:10 +00004873 rc = restoreCursorPosition(pCur);
4874 if( rc!=SQLITE_OK ){
4875 return rc;
4876 }
4877 if( CURSOR_INVALID==pCur->eState ){
4878 *pRes = 1;
4879 return SQLITE_OK;
4880 }
drh9b47ee32013-08-20 03:13:51 +00004881 if( pCur->skipNext ){
4882 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
4883 pCur->eState = CURSOR_VALID;
4884 if( pCur->skipNext>0 ){
4885 pCur->skipNext = 0;
drh9b47ee32013-08-20 03:13:51 +00004886 return SQLITE_OK;
4887 }
drhf66f26a2013-08-19 20:04:10 +00004888 pCur->skipNext = 0;
drhf66f26a2013-08-19 20:04:10 +00004889 }
danielk1977da184232006-01-05 11:34:32 +00004890 }
danielk1977da184232006-01-05 11:34:32 +00004891
danielk197771d5d2c2008-09-29 11:49:47 +00004892 pPage = pCur->apPage[pCur->iPage];
4893 idx = ++pCur->aiIdx[pCur->iPage];
4894 assert( pPage->isInit );
danbb246c42012-01-12 14:25:55 +00004895
4896 /* If the database file is corrupt, it is possible for the value of idx
4897 ** to be invalid here. This can only occur if a second cursor modifies
4898 ** the page while cursor pCur is holding a reference to it. Which can
4899 ** only happen if the database is corrupt in such a way as to link the
4900 ** page into more than one b-tree structure. */
4901 testcase( idx>pPage->nCell );
danielk19776a43f9b2004-11-16 04:57:24 +00004902
danielk197771d5d2c2008-09-29 11:49:47 +00004903 if( idx>=pPage->nCell ){
drha34b6762004-05-07 13:30:42 +00004904 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00004905 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
drhee6438d2014-09-01 13:29:32 +00004906 if( rc ) return rc;
4907 return moveToLeftmost(pCur);
drh72f82862001-05-24 21:06:34 +00004908 }
drh5e2f8b92001-05-28 00:41:15 +00004909 do{
danielk197771d5d2c2008-09-29 11:49:47 +00004910 if( pCur->iPage==0 ){
drh8c1238a2003-01-02 14:43:55 +00004911 *pRes = 1;
danielk1977da184232006-01-05 11:34:32 +00004912 pCur->eState = CURSOR_INVALID;
drh5e2f8b92001-05-28 00:41:15 +00004913 return SQLITE_OK;
4914 }
danielk197730548662009-07-09 05:07:37 +00004915 moveToParent(pCur);
danielk197771d5d2c2008-09-29 11:49:47 +00004916 pPage = pCur->apPage[pCur->iPage];
4917 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
drh44845222008-07-17 18:39:57 +00004918 if( pPage->intKey ){
drhee6438d2014-09-01 13:29:32 +00004919 return sqlite3BtreeNext(pCur, pRes);
drh8b18dd42004-05-12 19:18:15 +00004920 }else{
drhee6438d2014-09-01 13:29:32 +00004921 return SQLITE_OK;
drh8b18dd42004-05-12 19:18:15 +00004922 }
drh8178a752003-01-05 21:41:40 +00004923 }
drh3aac2dd2004-04-26 14:10:20 +00004924 if( pPage->leaf ){
drh8178a752003-01-05 21:41:40 +00004925 return SQLITE_OK;
drhee6438d2014-09-01 13:29:32 +00004926 }else{
4927 return moveToLeftmost(pCur);
drh72f82862001-05-24 21:06:34 +00004928 }
drh72f82862001-05-24 21:06:34 +00004929}
drhee6438d2014-09-01 13:29:32 +00004930int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
4931 MemPage *pPage;
4932 assert( cursorHoldsMutex(pCur) );
4933 assert( pRes!=0 );
4934 assert( *pRes==0 || *pRes==1 );
4935 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
4936 pCur->info.nSize = 0;
4937 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
4938 *pRes = 0;
4939 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
4940 pPage = pCur->apPage[pCur->iPage];
4941 if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
4942 pCur->aiIdx[pCur->iPage]--;
4943 return btreeNext(pCur, pRes);
4944 }
4945 if( pPage->leaf ){
4946 return SQLITE_OK;
4947 }else{
4948 return moveToLeftmost(pCur);
4949 }
4950}
drh72f82862001-05-24 21:06:34 +00004951
drh3b7511c2001-05-26 13:15:44 +00004952/*
drh2dcc9aa2002-12-04 13:40:25 +00004953** Step the cursor to the back to the previous entry in the database. If
drh8178a752003-01-05 21:41:40 +00004954** successful then set *pRes=0. If the cursor
drh2dcc9aa2002-12-04 13:40:25 +00004955** was already pointing to the first entry in the database before
drh8178a752003-01-05 21:41:40 +00004956** this routine was called, then set *pRes=1.
drhe39a7322014-02-03 14:04:11 +00004957**
drhee6438d2014-09-01 13:29:32 +00004958** The main entry point is sqlite3BtreePrevious(). That routine is optimized
4959** for the common case of merely decrementing the cell counter BtCursor.aiIdx
4960** to the previous cell on the current page. The (slower) btreePrevious() helper
4961** routine is called when it is necessary to move to a different page or
4962** to restore the cursor.
4963**
drhe39a7322014-02-03 14:04:11 +00004964** The calling function will set *pRes to 0 or 1. The initial *pRes value
4965** will be 1 if the cursor being stepped corresponds to an SQL index and
4966** if this routine could have been skipped if that SQL index had been
4967** a unique index. Otherwise the caller will have set *pRes to zero.
4968** Zero is the common case. The btree implementation is free to use the
4969** initial *pRes value as a hint to improve performance, but the current
4970** SQLite btree implementation does not. (Note that the comdb2 btree
4971** implementation does use this hint, however.)
drh2dcc9aa2002-12-04 13:40:25 +00004972*/
drhee6438d2014-09-01 13:29:32 +00004973static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
drh2dcc9aa2002-12-04 13:40:25 +00004974 int rc;
drh8178a752003-01-05 21:41:40 +00004975 MemPage *pPage;
danielk1977da184232006-01-05 11:34:32 +00004976
drh1fee73e2007-08-29 04:00:57 +00004977 assert( cursorHoldsMutex(pCur) );
drh9b47ee32013-08-20 03:13:51 +00004978 assert( pRes!=0 );
drhee6438d2014-09-01 13:29:32 +00004979 assert( *pRes==0 );
drh9b47ee32013-08-20 03:13:51 +00004980 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
drhee6438d2014-09-01 13:29:32 +00004981 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
4982 assert( pCur->info.nSize==0 );
drhf66f26a2013-08-19 20:04:10 +00004983 if( pCur->eState!=CURSOR_VALID ){
drhee6438d2014-09-01 13:29:32 +00004984 assert( pCur->eState>=CURSOR_REQUIRESEEK );
4985 rc = btreeRestoreCursorPosition(pCur);
4986 if( rc!=SQLITE_OK ){
4987 return rc;
drhf66f26a2013-08-19 20:04:10 +00004988 }
4989 if( CURSOR_INVALID==pCur->eState ){
4990 *pRes = 1;
4991 return SQLITE_OK;
4992 }
drh9b47ee32013-08-20 03:13:51 +00004993 if( pCur->skipNext ){
4994 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
4995 pCur->eState = CURSOR_VALID;
4996 if( pCur->skipNext<0 ){
4997 pCur->skipNext = 0;
drh9b47ee32013-08-20 03:13:51 +00004998 return SQLITE_OK;
4999 }
drhf66f26a2013-08-19 20:04:10 +00005000 pCur->skipNext = 0;
drhf66f26a2013-08-19 20:04:10 +00005001 }
danielk1977da184232006-01-05 11:34:32 +00005002 }
danielk1977da184232006-01-05 11:34:32 +00005003
danielk197771d5d2c2008-09-29 11:49:47 +00005004 pPage = pCur->apPage[pCur->iPage];
5005 assert( pPage->isInit );
drha34b6762004-05-07 13:30:42 +00005006 if( !pPage->leaf ){
danielk197771d5d2c2008-09-29 11:49:47 +00005007 int idx = pCur->aiIdx[pCur->iPage];
5008 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
drhee6438d2014-09-01 13:29:32 +00005009 if( rc ) return rc;
drh2dcc9aa2002-12-04 13:40:25 +00005010 rc = moveToRightmost(pCur);
5011 }else{
danielk197771d5d2c2008-09-29 11:49:47 +00005012 while( pCur->aiIdx[pCur->iPage]==0 ){
5013 if( pCur->iPage==0 ){
danielk1977da184232006-01-05 11:34:32 +00005014 pCur->eState = CURSOR_INVALID;
drhc39e0002004-05-07 23:50:57 +00005015 *pRes = 1;
drh2dcc9aa2002-12-04 13:40:25 +00005016 return SQLITE_OK;
5017 }
danielk197730548662009-07-09 05:07:37 +00005018 moveToParent(pCur);
drh2dcc9aa2002-12-04 13:40:25 +00005019 }
drhee6438d2014-09-01 13:29:32 +00005020 assert( pCur->info.nSize==0 );
5021 assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
danielk197771d5d2c2008-09-29 11:49:47 +00005022
5023 pCur->aiIdx[pCur->iPage]--;
5024 pPage = pCur->apPage[pCur->iPage];
drh44845222008-07-17 18:39:57 +00005025 if( pPage->intKey && !pPage->leaf ){
drh8b18dd42004-05-12 19:18:15 +00005026 rc = sqlite3BtreePrevious(pCur, pRes);
5027 }else{
5028 rc = SQLITE_OK;
5029 }
drh2dcc9aa2002-12-04 13:40:25 +00005030 }
drh2dcc9aa2002-12-04 13:40:25 +00005031 return rc;
5032}
drhee6438d2014-09-01 13:29:32 +00005033int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
5034 assert( cursorHoldsMutex(pCur) );
5035 assert( pRes!=0 );
5036 assert( *pRes==0 || *pRes==1 );
5037 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5038 *pRes = 0;
5039 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
5040 pCur->info.nSize = 0;
5041 if( pCur->eState!=CURSOR_VALID
5042 || pCur->aiIdx[pCur->iPage]==0
5043 || pCur->apPage[pCur->iPage]->leaf==0
5044 ){
5045 return btreePrevious(pCur, pRes);
5046 }
5047 pCur->aiIdx[pCur->iPage]--;
5048 return SQLITE_OK;
5049}
drh2dcc9aa2002-12-04 13:40:25 +00005050
5051/*
drh3b7511c2001-05-26 13:15:44 +00005052** Allocate a new page from the database file.
5053**
danielk19773b8a05f2007-03-19 17:44:26 +00005054** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
drh3b7511c2001-05-26 13:15:44 +00005055** has already been called on the new page.) The new page has also
5056** been referenced and the calling routine is responsible for calling
danielk19773b8a05f2007-03-19 17:44:26 +00005057** sqlite3PagerUnref() on the new page when it is done.
drh3b7511c2001-05-26 13:15:44 +00005058**
5059** SQLITE_OK is returned on success. Any other return value indicates
5060** an error. *ppPage and *pPgno are undefined in the event of an error.
danielk19773b8a05f2007-03-19 17:44:26 +00005061** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
drhbea00b92002-07-08 10:59:50 +00005062**
drh82e647d2013-03-02 03:25:55 +00005063** If the "nearby" parameter is not 0, then an effort is made to
drh199e3cf2002-07-18 11:01:47 +00005064** locate a page close to the page number "nearby". This can be used in an
drhbea00b92002-07-08 10:59:50 +00005065** attempt to keep related pages close to each other in the database file,
5066** which in turn can make database access faster.
danielk1977cb1a7eb2004-11-05 12:27:02 +00005067**
drh82e647d2013-03-02 03:25:55 +00005068** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
5069** anywhere on the free-list, then it is guaranteed to be returned. If
5070** eMode is BTALLOC_LT then the page returned will be less than or equal
5071** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
5072** are no restrictions on which page is returned.
drh3b7511c2001-05-26 13:15:44 +00005073*/
drh4f0c5872007-03-26 22:05:01 +00005074static int allocateBtreePage(
drh82e647d2013-03-02 03:25:55 +00005075 BtShared *pBt, /* The btree */
5076 MemPage **ppPage, /* Store pointer to the allocated page here */
5077 Pgno *pPgno, /* Store the page number here */
5078 Pgno nearby, /* Search for a page near this one */
5079 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005080){
drh3aac2dd2004-04-26 14:10:20 +00005081 MemPage *pPage1;
drh8c42ca92001-06-22 19:15:00 +00005082 int rc;
drh35cd6432009-06-05 14:17:21 +00005083 u32 n; /* Number of pages on the freelist */
drh042d6a12009-06-17 13:57:16 +00005084 u32 k; /* Number of leaves on the trunk of the freelist */
drhd3627af2006-12-18 18:34:51 +00005085 MemPage *pTrunk = 0;
5086 MemPage *pPrevTrunk = 0;
drh1662b5a2009-06-04 19:06:09 +00005087 Pgno mxPage; /* Total size of the database file */
drh30e58752002-03-02 20:41:57 +00005088
drh1fee73e2007-08-29 04:00:57 +00005089 assert( sqlite3_mutex_held(pBt->mutex) );
dan09ff9e12013-03-11 11:49:03 +00005090 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
drh3aac2dd2004-04-26 14:10:20 +00005091 pPage1 = pBt->pPage1;
drhb1299152010-03-30 22:58:33 +00005092 mxPage = btreePagecount(pBt);
drh3aac2dd2004-04-26 14:10:20 +00005093 n = get4byte(&pPage1->aData[36]);
drhdf35a082009-07-09 02:24:35 +00005094 testcase( n==mxPage-1 );
5095 if( n>=mxPage ){
drh1662b5a2009-06-04 19:06:09 +00005096 return SQLITE_CORRUPT_BKPT;
5097 }
drh3aac2dd2004-04-26 14:10:20 +00005098 if( n>0 ){
drh91025292004-05-03 19:49:32 +00005099 /* There are pages on the freelist. Reuse one of those pages. */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005100 Pgno iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005101 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
5102
drh82e647d2013-03-02 03:25:55 +00005103 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00005104 ** shows that the page 'nearby' is somewhere on the free-list, then
5105 ** the entire-list will be searched for that page.
5106 */
5107#ifndef SQLITE_OMIT_AUTOVACUUM
dan51f0b6d2013-02-22 20:16:34 +00005108 if( eMode==BTALLOC_EXACT ){
5109 if( nearby<=mxPage ){
5110 u8 eType;
5111 assert( nearby>0 );
5112 assert( pBt->autoVacuum );
5113 rc = ptrmapGet(pBt, nearby, &eType, 0);
5114 if( rc ) return rc;
5115 if( eType==PTRMAP_FREEPAGE ){
5116 searchList = 1;
5117 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005118 }
dan51f0b6d2013-02-22 20:16:34 +00005119 }else if( eMode==BTALLOC_LE ){
5120 searchList = 1;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005121 }
5122#endif
5123
5124 /* Decrement the free-list count by 1. Set iTrunk to the index of the
5125 ** first free-list trunk page. iPrevTrunk is initially 1.
5126 */
danielk19773b8a05f2007-03-19 17:44:26 +00005127 rc = sqlite3PagerWrite(pPage1->pDbPage);
drh3b7511c2001-05-26 13:15:44 +00005128 if( rc ) return rc;
drh3aac2dd2004-04-26 14:10:20 +00005129 put4byte(&pPage1->aData[36], n-1);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005130
5131 /* The code within this loop is run only once if the 'searchList' variable
5132 ** is not true. Otherwise, it runs once for each trunk-page on the
drh82e647d2013-03-02 03:25:55 +00005133 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
5134 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
danielk1977cb1a7eb2004-11-05 12:27:02 +00005135 */
5136 do {
5137 pPrevTrunk = pTrunk;
5138 if( pPrevTrunk ){
5139 iTrunk = get4byte(&pPrevTrunk->aData[0]);
drhbea00b92002-07-08 10:59:50 +00005140 }else{
danielk1977cb1a7eb2004-11-05 12:27:02 +00005141 iTrunk = get4byte(&pPage1->aData[32]);
drhbea00b92002-07-08 10:59:50 +00005142 }
drhdf35a082009-07-09 02:24:35 +00005143 testcase( iTrunk==mxPage );
drh1662b5a2009-06-04 19:06:09 +00005144 if( iTrunk>mxPage ){
5145 rc = SQLITE_CORRUPT_BKPT;
5146 }else{
drhb00fc3b2013-08-21 23:42:32 +00005147 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
drh1662b5a2009-06-04 19:06:09 +00005148 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005149 if( rc ){
drhd3627af2006-12-18 18:34:51 +00005150 pTrunk = 0;
5151 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005152 }
drhb07028f2011-10-14 21:49:18 +00005153 assert( pTrunk!=0 );
5154 assert( pTrunk->aData!=0 );
danielk1977cb1a7eb2004-11-05 12:27:02 +00005155
drh93b4fc72011-04-07 14:47:01 +00005156 k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
danielk1977cb1a7eb2004-11-05 12:27:02 +00005157 if( k==0 && !searchList ){
5158 /* The trunk has no leaves and the list is not being searched.
5159 ** So extract the trunk page itself and use it as the newly
5160 ** allocated page */
5161 assert( pPrevTrunk==0 );
danielk19773b8a05f2007-03-19 17:44:26 +00005162 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00005163 if( rc ){
5164 goto end_allocate_page;
5165 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005166 *pPgno = iTrunk;
5167 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5168 *ppPage = pTrunk;
5169 pTrunk = 0;
5170 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
drh042d6a12009-06-17 13:57:16 +00005171 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00005172 /* Value of k is out of range. Database corruption */
drhd3627af2006-12-18 18:34:51 +00005173 rc = SQLITE_CORRUPT_BKPT;
5174 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005175#ifndef SQLITE_OMIT_AUTOVACUUM
dan51f0b6d2013-02-22 20:16:34 +00005176 }else if( searchList
5177 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
5178 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00005179 /* The list is being searched and this trunk page is the page
5180 ** to allocate, regardless of whether it has leaves.
5181 */
dan51f0b6d2013-02-22 20:16:34 +00005182 *pPgno = iTrunk;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005183 *ppPage = pTrunk;
5184 searchList = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00005185 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00005186 if( rc ){
5187 goto end_allocate_page;
5188 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005189 if( k==0 ){
5190 if( !pPrevTrunk ){
5191 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5192 }else{
danf48c3552010-08-23 15:41:24 +00005193 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
5194 if( rc!=SQLITE_OK ){
5195 goto end_allocate_page;
5196 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005197 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
5198 }
5199 }else{
5200 /* The trunk page is required by the caller but it contains
5201 ** pointers to free-list leaves. The first leaf becomes a trunk
5202 ** page in this case.
5203 */
5204 MemPage *pNewTrunk;
5205 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
drh1662b5a2009-06-04 19:06:09 +00005206 if( iNewTrunk>mxPage ){
5207 rc = SQLITE_CORRUPT_BKPT;
5208 goto end_allocate_page;
5209 }
drhdf35a082009-07-09 02:24:35 +00005210 testcase( iNewTrunk==mxPage );
drhb00fc3b2013-08-21 23:42:32 +00005211 rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005212 if( rc!=SQLITE_OK ){
drhd3627af2006-12-18 18:34:51 +00005213 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005214 }
danielk19773b8a05f2007-03-19 17:44:26 +00005215 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005216 if( rc!=SQLITE_OK ){
5217 releasePage(pNewTrunk);
drhd3627af2006-12-18 18:34:51 +00005218 goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005219 }
5220 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
5221 put4byte(&pNewTrunk->aData[4], k-1);
5222 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
drhd3627af2006-12-18 18:34:51 +00005223 releasePage(pNewTrunk);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005224 if( !pPrevTrunk ){
drhc5053fb2008-11-27 02:22:10 +00005225 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
danielk1977cb1a7eb2004-11-05 12:27:02 +00005226 put4byte(&pPage1->aData[32], iNewTrunk);
5227 }else{
danielk19773b8a05f2007-03-19 17:44:26 +00005228 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
drhd3627af2006-12-18 18:34:51 +00005229 if( rc ){
5230 goto end_allocate_page;
5231 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005232 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
5233 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005234 }
5235 pTrunk = 0;
5236 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
5237#endif
danielk1977e5765212009-06-17 11:13:28 +00005238 }else if( k>0 ){
danielk1977cb1a7eb2004-11-05 12:27:02 +00005239 /* Extract a leaf from the trunk */
drh042d6a12009-06-17 13:57:16 +00005240 u32 closest;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005241 Pgno iPage;
5242 unsigned char *aData = pTrunk->aData;
5243 if( nearby>0 ){
drh042d6a12009-06-17 13:57:16 +00005244 u32 i;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005245 closest = 0;
danf38b65a2013-02-22 20:57:47 +00005246 if( eMode==BTALLOC_LE ){
5247 for(i=0; i<k; i++){
5248 iPage = get4byte(&aData[8+i*4]);
dan87ade192013-02-23 17:49:16 +00005249 if( iPage<=nearby ){
danf38b65a2013-02-22 20:57:47 +00005250 closest = i;
5251 break;
5252 }
5253 }
5254 }else{
5255 int dist;
5256 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
5257 for(i=1; i<k; i++){
5258 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
5259 if( d2<dist ){
5260 closest = i;
5261 dist = d2;
5262 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005263 }
5264 }
5265 }else{
5266 closest = 0;
5267 }
5268
5269 iPage = get4byte(&aData[8+closest*4]);
drhdf35a082009-07-09 02:24:35 +00005270 testcase( iPage==mxPage );
drh1662b5a2009-06-04 19:06:09 +00005271 if( iPage>mxPage ){
5272 rc = SQLITE_CORRUPT_BKPT;
5273 goto end_allocate_page;
5274 }
drhdf35a082009-07-09 02:24:35 +00005275 testcase( iPage==mxPage );
dan51f0b6d2013-02-22 20:16:34 +00005276 if( !searchList
5277 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
5278 ){
danielk1977bea2a942009-01-20 17:06:27 +00005279 int noContent;
shane1f9e6aa2008-06-09 19:27:11 +00005280 *pPgno = iPage;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005281 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
5282 ": %d more free pages\n",
5283 *pPgno, closest+1, k, pTrunk->pgno, n-1));
drh93b4fc72011-04-07 14:47:01 +00005284 rc = sqlite3PagerWrite(pTrunk->pDbPage);
5285 if( rc ) goto end_allocate_page;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005286 if( closest<k-1 ){
5287 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
5288 }
5289 put4byte(&aData[4], k-1);
drhb00fc3b2013-08-21 23:42:32 +00005290 noContent = !btreeGetHasContent(pBt, *pPgno) ? PAGER_GET_NOCONTENT : 0;
5291 rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
danielk1977cb1a7eb2004-11-05 12:27:02 +00005292 if( rc==SQLITE_OK ){
danielk19773b8a05f2007-03-19 17:44:26 +00005293 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00005294 if( rc!=SQLITE_OK ){
5295 releasePage(*ppPage);
5296 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005297 }
5298 searchList = 0;
5299 }
drhee696e22004-08-30 16:52:17 +00005300 }
danielk1977cb1a7eb2004-11-05 12:27:02 +00005301 releasePage(pPrevTrunk);
drhd3627af2006-12-18 18:34:51 +00005302 pPrevTrunk = 0;
danielk1977cb1a7eb2004-11-05 12:27:02 +00005303 }while( searchList );
drh3b7511c2001-05-26 13:15:44 +00005304 }else{
danbc1a3c62013-02-23 16:40:46 +00005305 /* There are no pages on the freelist, so append a new page to the
5306 ** database image.
5307 **
5308 ** Normally, new pages allocated by this block can be requested from the
5309 ** pager layer with the 'no-content' flag set. This prevents the pager
5310 ** from trying to read the pages content from disk. However, if the
5311 ** current transaction has already run one or more incremental-vacuum
5312 ** steps, then the page we are about to allocate may contain content
5313 ** that is required in the event of a rollback. In this case, do
5314 ** not set the no-content flag. This causes the pager to load and journal
5315 ** the current page content before overwriting it.
5316 **
5317 ** Note that the pager will not actually attempt to load or journal
5318 ** content for any page that really does lie past the end of the database
5319 ** file on disk. So the effects of disabling the no-content optimization
5320 ** here are confined to those pages that lie between the end of the
5321 ** database image and the end of the database file.
5322 */
drhb00fc3b2013-08-21 23:42:32 +00005323 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate)) ? PAGER_GET_NOCONTENT : 0;
danbc1a3c62013-02-23 16:40:46 +00005324
drhdd3cd972010-03-27 17:12:36 +00005325 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
5326 if( rc ) return rc;
5327 pBt->nPage++;
5328 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
danielk1977bea2a942009-01-20 17:06:27 +00005329
danielk1977afcdd022004-10-31 16:25:42 +00005330#ifndef SQLITE_OMIT_AUTOVACUUM
drhdd3cd972010-03-27 17:12:36 +00005331 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
danielk1977afcdd022004-10-31 16:25:42 +00005332 /* If *pPgno refers to a pointer-map page, allocate two new pages
5333 ** at the end of the file instead of one. The first allocated page
5334 ** becomes a new pointer-map page, the second is used by the caller.
5335 */
danielk1977ac861692009-03-28 10:54:22 +00005336 MemPage *pPg = 0;
drhdd3cd972010-03-27 17:12:36 +00005337 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
5338 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
drhb00fc3b2013-08-21 23:42:32 +00005339 rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
danielk1977ac861692009-03-28 10:54:22 +00005340 if( rc==SQLITE_OK ){
5341 rc = sqlite3PagerWrite(pPg->pDbPage);
5342 releasePage(pPg);
5343 }
5344 if( rc ) return rc;
drhdd3cd972010-03-27 17:12:36 +00005345 pBt->nPage++;
5346 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
danielk1977afcdd022004-10-31 16:25:42 +00005347 }
5348#endif
drhdd3cd972010-03-27 17:12:36 +00005349 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
5350 *pPgno = pBt->nPage;
danielk1977afcdd022004-10-31 16:25:42 +00005351
danielk1977599fcba2004-11-08 07:13:13 +00005352 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhb00fc3b2013-08-21 23:42:32 +00005353 rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
drh3b7511c2001-05-26 13:15:44 +00005354 if( rc ) return rc;
danielk19773b8a05f2007-03-19 17:44:26 +00005355 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
danielk1977aac0a382005-01-16 11:07:06 +00005356 if( rc!=SQLITE_OK ){
5357 releasePage(*ppPage);
5358 }
drh3a4c1412004-05-09 20:40:11 +00005359 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
drh3b7511c2001-05-26 13:15:44 +00005360 }
danielk1977599fcba2004-11-08 07:13:13 +00005361
5362 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
drhd3627af2006-12-18 18:34:51 +00005363
5364end_allocate_page:
5365 releasePage(pTrunk);
5366 releasePage(pPrevTrunk);
danielk1977b247c212008-11-21 09:09:01 +00005367 if( rc==SQLITE_OK ){
5368 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
5369 releasePage(*ppPage);
dan7df42ab2014-01-20 18:25:44 +00005370 *ppPage = 0;
danielk1977b247c212008-11-21 09:09:01 +00005371 return SQLITE_CORRUPT_BKPT;
5372 }
5373 (*ppPage)->isInit = 0;
danielk1977a50d9aa2009-06-08 14:49:45 +00005374 }else{
5375 *ppPage = 0;
danielk1977eaa06f62008-09-18 17:34:44 +00005376 }
drh93b4fc72011-04-07 14:47:01 +00005377 assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
drh3b7511c2001-05-26 13:15:44 +00005378 return rc;
5379}
5380
5381/*
danielk1977bea2a942009-01-20 17:06:27 +00005382** This function is used to add page iPage to the database file free-list.
5383** It is assumed that the page is not already a part of the free-list.
drh5e2f8b92001-05-28 00:41:15 +00005384**
danielk1977bea2a942009-01-20 17:06:27 +00005385** The value passed as the second argument to this function is optional.
5386** If the caller happens to have a pointer to the MemPage object
5387** corresponding to page iPage handy, it may pass it as the second value.
5388** Otherwise, it may pass NULL.
5389**
5390** If a pointer to a MemPage object is passed as the second argument,
5391** its reference count is not altered by this function.
drh3b7511c2001-05-26 13:15:44 +00005392*/
danielk1977bea2a942009-01-20 17:06:27 +00005393static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
5394 MemPage *pTrunk = 0; /* Free-list trunk page */
5395 Pgno iTrunk = 0; /* Page number of free-list trunk page */
5396 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
5397 MemPage *pPage; /* Page being freed. May be NULL. */
5398 int rc; /* Return Code */
5399 int nFree; /* Initial number of pages on free-list */
drh8b2f49b2001-06-08 00:21:52 +00005400
danielk1977bea2a942009-01-20 17:06:27 +00005401 assert( sqlite3_mutex_held(pBt->mutex) );
5402 assert( iPage>1 );
5403 assert( !pMemPage || pMemPage->pgno==iPage );
5404
5405 if( pMemPage ){
5406 pPage = pMemPage;
5407 sqlite3PagerRef(pPage->pDbPage);
5408 }else{
5409 pPage = btreePageLookup(pBt, iPage);
5410 }
drh3aac2dd2004-04-26 14:10:20 +00005411
drha34b6762004-05-07 13:30:42 +00005412 /* Increment the free page count on pPage1 */
danielk19773b8a05f2007-03-19 17:44:26 +00005413 rc = sqlite3PagerWrite(pPage1->pDbPage);
danielk1977bea2a942009-01-20 17:06:27 +00005414 if( rc ) goto freepage_out;
5415 nFree = get4byte(&pPage1->aData[36]);
5416 put4byte(&pPage1->aData[36], nFree+1);
drh3aac2dd2004-04-26 14:10:20 +00005417
drhc9166342012-01-05 23:32:06 +00005418 if( pBt->btsFlags & BTS_SECURE_DELETE ){
drh5b47efa2010-02-12 18:18:39 +00005419 /* If the secure_delete option is enabled, then
5420 ** always fully overwrite deleted information with zeros.
5421 */
drhb00fc3b2013-08-21 23:42:32 +00005422 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
shaneh84f4b2f2010-02-26 01:46:54 +00005423 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
drh5b47efa2010-02-12 18:18:39 +00005424 ){
5425 goto freepage_out;
5426 }
5427 memset(pPage->aData, 0, pPage->pBt->pageSize);
danielk1977bea2a942009-01-20 17:06:27 +00005428 }
drhfcce93f2006-02-22 03:08:32 +00005429
danielk1977687566d2004-11-02 12:56:41 +00005430 /* If the database supports auto-vacuum, write an entry in the pointer-map
danielk1977cb1a7eb2004-11-05 12:27:02 +00005431 ** to indicate that the page is free.
danielk1977687566d2004-11-02 12:56:41 +00005432 */
danielk197785d90ca2008-07-19 14:25:15 +00005433 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00005434 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
danielk1977bea2a942009-01-20 17:06:27 +00005435 if( rc ) goto freepage_out;
danielk1977687566d2004-11-02 12:56:41 +00005436 }
danielk1977687566d2004-11-02 12:56:41 +00005437
danielk1977bea2a942009-01-20 17:06:27 +00005438 /* Now manipulate the actual database free-list structure. There are two
5439 ** possibilities. If the free-list is currently empty, or if the first
5440 ** trunk page in the free-list is full, then this page will become a
5441 ** new free-list trunk page. Otherwise, it will become a leaf of the
5442 ** first trunk page in the current free-list. This block tests if it
5443 ** is possible to add the page as a new free-list leaf.
5444 */
5445 if( nFree!=0 ){
drhc046e3e2009-07-15 11:26:44 +00005446 u32 nLeaf; /* Initial number of leaf cells on trunk page */
danielk1977bea2a942009-01-20 17:06:27 +00005447
5448 iTrunk = get4byte(&pPage1->aData[32]);
drhb00fc3b2013-08-21 23:42:32 +00005449 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
danielk1977bea2a942009-01-20 17:06:27 +00005450 if( rc!=SQLITE_OK ){
5451 goto freepage_out;
5452 }
5453
5454 nLeaf = get4byte(&pTrunk->aData[4]);
drheeb844a2009-08-08 18:01:07 +00005455 assert( pBt->usableSize>32 );
5456 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
danielk1977bea2a942009-01-20 17:06:27 +00005457 rc = SQLITE_CORRUPT_BKPT;
5458 goto freepage_out;
5459 }
drheeb844a2009-08-08 18:01:07 +00005460 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
danielk1977bea2a942009-01-20 17:06:27 +00005461 /* In this case there is room on the trunk page to insert the page
5462 ** being freed as a new leaf.
drh45b1fac2008-07-04 17:52:42 +00005463 **
5464 ** Note that the trunk page is not really full until it contains
5465 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
5466 ** coded. But due to a coding error in versions of SQLite prior to
5467 ** 3.6.0, databases with freelist trunk pages holding more than
5468 ** usableSize/4 - 8 entries will be reported as corrupt. In order
5469 ** to maintain backwards compatibility with older versions of SQLite,
drhc046e3e2009-07-15 11:26:44 +00005470 ** we will continue to restrict the number of entries to usableSize/4 - 8
drh45b1fac2008-07-04 17:52:42 +00005471 ** for now. At some point in the future (once everyone has upgraded
5472 ** to 3.6.0 or later) we should consider fixing the conditional above
5473 ** to read "usableSize/4-2" instead of "usableSize/4-8".
5474 */
danielk19773b8a05f2007-03-19 17:44:26 +00005475 rc = sqlite3PagerWrite(pTrunk->pDbPage);
drhf5345442007-04-09 12:45:02 +00005476 if( rc==SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00005477 put4byte(&pTrunk->aData[4], nLeaf+1);
5478 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
drhc9166342012-01-05 23:32:06 +00005479 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
danielk1977bea2a942009-01-20 17:06:27 +00005480 sqlite3PagerDontWrite(pPage->pDbPage);
5481 }
danielk1977bea2a942009-01-20 17:06:27 +00005482 rc = btreeSetHasContent(pBt, iPage);
drhf5345442007-04-09 12:45:02 +00005483 }
drh3a4c1412004-05-09 20:40:11 +00005484 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
danielk1977bea2a942009-01-20 17:06:27 +00005485 goto freepage_out;
drh3aac2dd2004-04-26 14:10:20 +00005486 }
drh3b7511c2001-05-26 13:15:44 +00005487 }
danielk1977bea2a942009-01-20 17:06:27 +00005488
5489 /* If control flows to this point, then it was not possible to add the
5490 ** the page being freed as a leaf page of the first trunk in the free-list.
5491 ** Possibly because the free-list is empty, or possibly because the
5492 ** first trunk in the free-list is full. Either way, the page being freed
5493 ** will become the new first trunk page in the free-list.
5494 */
drhb00fc3b2013-08-21 23:42:32 +00005495 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
drhc046e3e2009-07-15 11:26:44 +00005496 goto freepage_out;
5497 }
5498 rc = sqlite3PagerWrite(pPage->pDbPage);
5499 if( rc!=SQLITE_OK ){
danielk1977bea2a942009-01-20 17:06:27 +00005500 goto freepage_out;
5501 }
5502 put4byte(pPage->aData, iTrunk);
5503 put4byte(&pPage->aData[4], 0);
5504 put4byte(&pPage1->aData[32], iPage);
5505 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
5506
5507freepage_out:
5508 if( pPage ){
5509 pPage->isInit = 0;
5510 }
5511 releasePage(pPage);
5512 releasePage(pTrunk);
drh3b7511c2001-05-26 13:15:44 +00005513 return rc;
5514}
drhc314dc72009-07-21 11:52:34 +00005515static void freePage(MemPage *pPage, int *pRC){
5516 if( (*pRC)==SQLITE_OK ){
5517 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
5518 }
danielk1977bea2a942009-01-20 17:06:27 +00005519}
drh3b7511c2001-05-26 13:15:44 +00005520
5521/*
drh3aac2dd2004-04-26 14:10:20 +00005522** Free any overflow pages associated with the given Cell.
drh3b7511c2001-05-26 13:15:44 +00005523*/
drh3aac2dd2004-04-26 14:10:20 +00005524static int clearCell(MemPage *pPage, unsigned char *pCell){
danielk1977aef0bf62005-12-30 16:28:01 +00005525 BtShared *pBt = pPage->pBt;
drh6f11bef2004-05-13 01:12:56 +00005526 CellInfo info;
drh3aac2dd2004-04-26 14:10:20 +00005527 Pgno ovflPgno;
drh6f11bef2004-05-13 01:12:56 +00005528 int rc;
drh94440812007-03-06 11:42:19 +00005529 int nOvfl;
shaneh1df2db72010-08-18 02:28:48 +00005530 u32 ovflPageSize;
drh3b7511c2001-05-26 13:15:44 +00005531
drh1fee73e2007-08-29 04:00:57 +00005532 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk197730548662009-07-09 05:07:37 +00005533 btreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005534 if( info.iOverflow==0 ){
drha34b6762004-05-07 13:30:42 +00005535 return SQLITE_OK; /* No overflow pages. Return without doing anything */
drh3aac2dd2004-04-26 14:10:20 +00005536 }
drhe42a9b42011-08-31 13:27:19 +00005537 if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
mistachkin70a1b712012-09-28 18:13:35 +00005538 return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
drhe42a9b42011-08-31 13:27:19 +00005539 }
drh6f11bef2004-05-13 01:12:56 +00005540 ovflPgno = get4byte(&pCell[info.iOverflow]);
shane63207ab2009-02-04 01:49:30 +00005541 assert( pBt->usableSize > 4 );
drh94440812007-03-06 11:42:19 +00005542 ovflPageSize = pBt->usableSize - 4;
drh72365832007-03-06 15:53:44 +00005543 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
5544 assert( ovflPgno==0 || nOvfl>0 );
5545 while( nOvfl-- ){
shane63207ab2009-02-04 01:49:30 +00005546 Pgno iNext = 0;
danielk1977bea2a942009-01-20 17:06:27 +00005547 MemPage *pOvfl = 0;
drhb1299152010-03-30 22:58:33 +00005548 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
danielk1977e589a672009-04-11 16:06:15 +00005549 /* 0 is not a legal page number and page 1 cannot be an
5550 ** overflow page. Therefore if ovflPgno<2 or past the end of the
5551 ** file the database must be corrupt. */
drh49285702005-09-17 15:20:26 +00005552 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00005553 }
danielk1977bea2a942009-01-20 17:06:27 +00005554 if( nOvfl ){
5555 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
5556 if( rc ) return rc;
5557 }
dan887d4b22010-02-25 12:09:16 +00005558
shaneh1da207e2010-03-09 14:41:12 +00005559 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
dan887d4b22010-02-25 12:09:16 +00005560 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
5561 ){
5562 /* There is no reason any cursor should have an outstanding reference
5563 ** to an overflow page belonging to a cell that is being deleted/updated.
5564 ** So if there exists more than one reference to this page, then it
5565 ** must not really be an overflow page and the database must be corrupt.
5566 ** It is helpful to detect this before calling freePage2(), as
5567 ** freePage2() may zero the page contents if secure-delete mode is
5568 ** enabled. If this 'overflow' page happens to be a page that the
5569 ** caller is iterating through or using in some other way, this
5570 ** can be problematic.
5571 */
5572 rc = SQLITE_CORRUPT_BKPT;
5573 }else{
5574 rc = freePage2(pBt, pOvfl, ovflPgno);
5575 }
5576
danielk1977bea2a942009-01-20 17:06:27 +00005577 if( pOvfl ){
5578 sqlite3PagerUnref(pOvfl->pDbPage);
5579 }
drh3b7511c2001-05-26 13:15:44 +00005580 if( rc ) return rc;
danielk1977bea2a942009-01-20 17:06:27 +00005581 ovflPgno = iNext;
drh3b7511c2001-05-26 13:15:44 +00005582 }
drh5e2f8b92001-05-28 00:41:15 +00005583 return SQLITE_OK;
drh3b7511c2001-05-26 13:15:44 +00005584}
5585
5586/*
drh91025292004-05-03 19:49:32 +00005587** Create the byte sequence used to represent a cell on page pPage
5588** and write that byte sequence into pCell[]. Overflow pages are
5589** allocated and filled in as necessary. The calling procedure
5590** is responsible for making sure sufficient space has been allocated
5591** for pCell[].
5592**
5593** Note that pCell does not necessary need to point to the pPage->aData
5594** area. pCell might point to some temporary storage. The cell will
5595** be constructed in this temporary area then copied into pPage->aData
5596** later.
drh3b7511c2001-05-26 13:15:44 +00005597*/
5598static int fillInCell(
drh3aac2dd2004-04-26 14:10:20 +00005599 MemPage *pPage, /* The page that contains the cell */
drh4b70f112004-05-02 21:12:19 +00005600 unsigned char *pCell, /* Complete text of the cell */
drh4a1c3802004-05-12 15:15:47 +00005601 const void *pKey, i64 nKey, /* The key */
drh4b70f112004-05-02 21:12:19 +00005602 const void *pData,int nData, /* The data */
drhb026e052007-05-02 01:34:31 +00005603 int nZero, /* Extra zero bytes to append to pData */
drh4b70f112004-05-02 21:12:19 +00005604 int *pnSize /* Write cell size here */
drh3b7511c2001-05-26 13:15:44 +00005605){
drh3b7511c2001-05-26 13:15:44 +00005606 int nPayload;
drh8c6fa9b2004-05-26 00:01:53 +00005607 const u8 *pSrc;
drha34b6762004-05-07 13:30:42 +00005608 int nSrc, n, rc;
drh3aac2dd2004-04-26 14:10:20 +00005609 int spaceLeft;
5610 MemPage *pOvfl = 0;
drh9b171272004-05-08 02:03:22 +00005611 MemPage *pToRelease = 0;
drh3aac2dd2004-04-26 14:10:20 +00005612 unsigned char *pPrior;
5613 unsigned char *pPayload;
danielk1977aef0bf62005-12-30 16:28:01 +00005614 BtShared *pBt = pPage->pBt;
drh3aac2dd2004-04-26 14:10:20 +00005615 Pgno pgnoOvfl = 0;
drh4b70f112004-05-02 21:12:19 +00005616 int nHeader;
drh6f11bef2004-05-13 01:12:56 +00005617 CellInfo info;
drh3b7511c2001-05-26 13:15:44 +00005618
drh1fee73e2007-08-29 04:00:57 +00005619 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhd677b3d2007-08-20 22:48:41 +00005620
drhc5053fb2008-11-27 02:22:10 +00005621 /* pPage is not necessarily writeable since pCell might be auxiliary
5622 ** buffer space that is separate from the pPage buffer area */
5623 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
5624 || sqlite3PagerIswriteable(pPage->pDbPage) );
5625
drh91025292004-05-03 19:49:32 +00005626 /* Fill in the header. */
drh43605152004-05-29 21:46:49 +00005627 nHeader = 0;
drh91025292004-05-03 19:49:32 +00005628 if( !pPage->leaf ){
5629 nHeader += 4;
5630 }
drh8b18dd42004-05-12 19:18:15 +00005631 if( pPage->hasData ){
drh7599d4a2013-12-09 00:47:11 +00005632 nHeader += putVarint32(&pCell[nHeader], nData+nZero);
drh6f11bef2004-05-13 01:12:56 +00005633 }else{
drhb026e052007-05-02 01:34:31 +00005634 nData = nZero = 0;
drh91025292004-05-03 19:49:32 +00005635 }
drh6f11bef2004-05-13 01:12:56 +00005636 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
danielk197730548662009-07-09 05:07:37 +00005637 btreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00005638 assert( info.nHeader==nHeader );
5639 assert( info.nKey==nKey );
danielk197789d40042008-11-17 14:20:56 +00005640 assert( info.nData==(u32)(nData+nZero) );
drh6f11bef2004-05-13 01:12:56 +00005641
5642 /* Fill in the payload */
drhb026e052007-05-02 01:34:31 +00005643 nPayload = nData + nZero;
drh3aac2dd2004-04-26 14:10:20 +00005644 if( pPage->intKey ){
5645 pSrc = pData;
5646 nSrc = nData;
drh91025292004-05-03 19:49:32 +00005647 nData = 0;
drhf49661a2008-12-10 16:45:50 +00005648 }else{
danielk197731d31b82009-07-13 13:18:07 +00005649 if( NEVER(nKey>0x7fffffff || pKey==0) ){
5650 return SQLITE_CORRUPT_BKPT;
drh20abac22009-01-28 20:21:17 +00005651 }
drhf49661a2008-12-10 16:45:50 +00005652 nPayload += (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00005653 pSrc = pKey;
drhf49661a2008-12-10 16:45:50 +00005654 nSrc = (int)nKey;
drh3aac2dd2004-04-26 14:10:20 +00005655 }
drh6f11bef2004-05-13 01:12:56 +00005656 *pnSize = info.nSize;
5657 spaceLeft = info.nLocal;
drh3aac2dd2004-04-26 14:10:20 +00005658 pPayload = &pCell[nHeader];
drh6f11bef2004-05-13 01:12:56 +00005659 pPrior = &pCell[info.iOverflow];
drh3b7511c2001-05-26 13:15:44 +00005660
drh3b7511c2001-05-26 13:15:44 +00005661 while( nPayload>0 ){
5662 if( spaceLeft==0 ){
danielk1977afcdd022004-10-31 16:25:42 +00005663#ifndef SQLITE_OMIT_AUTOVACUUM
5664 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
danielk1977b39f70b2007-05-17 18:28:11 +00005665 if( pBt->autoVacuum ){
5666 do{
5667 pgnoOvfl++;
5668 } while(
5669 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
5670 );
danielk1977b39f70b2007-05-17 18:28:11 +00005671 }
danielk1977afcdd022004-10-31 16:25:42 +00005672#endif
drhf49661a2008-12-10 16:45:50 +00005673 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
danielk1977afcdd022004-10-31 16:25:42 +00005674#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977a19df672004-11-03 11:37:07 +00005675 /* If the database supports auto-vacuum, and the second or subsequent
5676 ** overflow page is being allocated, add an entry to the pointer-map
danielk19774ef24492007-05-23 09:52:41 +00005677 ** for that page now.
5678 **
5679 ** If this is the first overflow page, then write a partial entry
5680 ** to the pointer-map. If we write nothing to this pointer-map slot,
5681 ** then the optimistic overflow chain processing in clearCell()
mistachkin48864df2013-03-21 21:20:32 +00005682 ** may misinterpret the uninitialized values and delete the
danielk19774ef24492007-05-23 09:52:41 +00005683 ** wrong pages from the database.
danielk1977afcdd022004-10-31 16:25:42 +00005684 */
danielk19774ef24492007-05-23 09:52:41 +00005685 if( pBt->autoVacuum && rc==SQLITE_OK ){
5686 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
drh98add2e2009-07-20 17:11:49 +00005687 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
danielk197789a4be82007-05-23 13:34:32 +00005688 if( rc ){
5689 releasePage(pOvfl);
5690 }
danielk1977afcdd022004-10-31 16:25:42 +00005691 }
5692#endif
drh3b7511c2001-05-26 13:15:44 +00005693 if( rc ){
drh9b171272004-05-08 02:03:22 +00005694 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00005695 return rc;
5696 }
drhc5053fb2008-11-27 02:22:10 +00005697
5698 /* If pToRelease is not zero than pPrior points into the data area
5699 ** of pToRelease. Make sure pToRelease is still writeable. */
5700 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
5701
5702 /* If pPrior is part of the data area of pPage, then make sure pPage
5703 ** is still writeable */
5704 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
5705 || sqlite3PagerIswriteable(pPage->pDbPage) );
5706
drh3aac2dd2004-04-26 14:10:20 +00005707 put4byte(pPrior, pgnoOvfl);
drh9b171272004-05-08 02:03:22 +00005708 releasePage(pToRelease);
5709 pToRelease = pOvfl;
drh3aac2dd2004-04-26 14:10:20 +00005710 pPrior = pOvfl->aData;
5711 put4byte(pPrior, 0);
5712 pPayload = &pOvfl->aData[4];
drhb6f41482004-05-14 01:58:11 +00005713 spaceLeft = pBt->usableSize - 4;
drh3b7511c2001-05-26 13:15:44 +00005714 }
5715 n = nPayload;
5716 if( n>spaceLeft ) n = spaceLeft;
drhc5053fb2008-11-27 02:22:10 +00005717
5718 /* If pToRelease is not zero than pPayload points into the data area
5719 ** of pToRelease. Make sure pToRelease is still writeable. */
5720 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
5721
5722 /* If pPayload is part of the data area of pPage, then make sure pPage
5723 ** is still writeable */
5724 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
5725 || sqlite3PagerIswriteable(pPage->pDbPage) );
5726
drhb026e052007-05-02 01:34:31 +00005727 if( nSrc>0 ){
5728 if( n>nSrc ) n = nSrc;
5729 assert( pSrc );
5730 memcpy(pPayload, pSrc, n);
5731 }else{
5732 memset(pPayload, 0, n);
5733 }
drh3b7511c2001-05-26 13:15:44 +00005734 nPayload -= n;
drhde647132004-05-07 17:57:49 +00005735 pPayload += n;
drh9b171272004-05-08 02:03:22 +00005736 pSrc += n;
drh3aac2dd2004-04-26 14:10:20 +00005737 nSrc -= n;
drh3b7511c2001-05-26 13:15:44 +00005738 spaceLeft -= n;
drh3aac2dd2004-04-26 14:10:20 +00005739 if( nSrc==0 ){
5740 nSrc = nData;
5741 pSrc = pData;
5742 }
drhdd793422001-06-28 01:54:48 +00005743 }
drh9b171272004-05-08 02:03:22 +00005744 releasePage(pToRelease);
drh3b7511c2001-05-26 13:15:44 +00005745 return SQLITE_OK;
5746}
5747
drh14acc042001-06-10 19:56:58 +00005748/*
5749** Remove the i-th cell from pPage. This routine effects pPage only.
5750** The cell content is not freed or deallocated. It is assumed that
5751** the cell content has been copied someplace else. This routine just
5752** removes the reference to the cell from pPage.
5753**
5754** "sz" must be the number of bytes in the cell.
drh14acc042001-06-10 19:56:58 +00005755*/
drh98add2e2009-07-20 17:11:49 +00005756static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
drh43b18e12010-08-17 19:40:08 +00005757 u32 pc; /* Offset to cell content of cell being deleted */
drh43605152004-05-29 21:46:49 +00005758 u8 *data; /* pPage->aData */
5759 u8 *ptr; /* Used to move bytes around within data[] */
shanedcc50b72008-11-13 18:29:50 +00005760 int rc; /* The return code */
drhc314dc72009-07-21 11:52:34 +00005761 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
drh43605152004-05-29 21:46:49 +00005762
drh98add2e2009-07-20 17:11:49 +00005763 if( *pRC ) return;
5764
drh8c42ca92001-06-22 19:15:00 +00005765 assert( idx>=0 && idx<pPage->nCell );
drh43605152004-05-29 21:46:49 +00005766 assert( sz==cellSize(pPage, idx) );
danielk19773b8a05f2007-03-19 17:44:26 +00005767 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh1fee73e2007-08-29 04:00:57 +00005768 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhda200cc2004-05-09 11:51:38 +00005769 data = pPage->aData;
drh3def2352011-11-11 00:27:15 +00005770 ptr = &pPage->aCellIdx[2*idx];
shane0af3f892008-11-12 04:55:34 +00005771 pc = get2byte(ptr);
drhc314dc72009-07-21 11:52:34 +00005772 hdr = pPage->hdrOffset;
5773 testcase( pc==get2byte(&data[hdr+5]) );
5774 testcase( pc+sz==pPage->pBt->usableSize );
drh43b18e12010-08-17 19:40:08 +00005775 if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
drh98add2e2009-07-20 17:11:49 +00005776 *pRC = SQLITE_CORRUPT_BKPT;
5777 return;
shane0af3f892008-11-12 04:55:34 +00005778 }
shanedcc50b72008-11-13 18:29:50 +00005779 rc = freeSpace(pPage, pc, sz);
drh98add2e2009-07-20 17:11:49 +00005780 if( rc ){
5781 *pRC = rc;
5782 return;
shanedcc50b72008-11-13 18:29:50 +00005783 }
drh14acc042001-06-10 19:56:58 +00005784 pPage->nCell--;
drh9bb7c4f2013-12-09 01:58:11 +00005785 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
drhc314dc72009-07-21 11:52:34 +00005786 put2byte(&data[hdr+3], pPage->nCell);
drh43605152004-05-29 21:46:49 +00005787 pPage->nFree += 2;
drh14acc042001-06-10 19:56:58 +00005788}
5789
5790/*
5791** Insert a new cell on pPage at cell index "i". pCell points to the
5792** content of the cell.
5793**
5794** If the cell content will fit on the page, then put it there. If it
drh43605152004-05-29 21:46:49 +00005795** will not fit, then make a copy of the cell content into pTemp if
5796** pTemp is not null. Regardless of pTemp, allocate a new entry
drh2cbd78b2012-02-02 19:37:18 +00005797** in pPage->apOvfl[] and make it point to the cell content (either
drh43605152004-05-29 21:46:49 +00005798** in pTemp or the original pCell) and also record its index.
5799** Allocating a new entry in pPage->aCell[] implies that
5800** pPage->nOverflow is incremented.
danielk1977a3ad5e72005-01-07 08:56:44 +00005801**
5802** If nSkip is non-zero, then do not copy the first nSkip bytes of the
5803** cell. The caller will overwrite them after this function returns. If
drh4b238df2005-01-08 15:43:18 +00005804** nSkip is non-zero, then pCell may not point to an invalid memory location
danielk1977a3ad5e72005-01-07 08:56:44 +00005805** (but pCell+nSkip is always valid).
drh14acc042001-06-10 19:56:58 +00005806*/
drh98add2e2009-07-20 17:11:49 +00005807static void insertCell(
drh24cd67e2004-05-10 16:18:47 +00005808 MemPage *pPage, /* Page into which we are copying */
drh43605152004-05-29 21:46:49 +00005809 int i, /* New cell becomes the i-th cell of the page */
5810 u8 *pCell, /* Content of the new cell */
5811 int sz, /* Bytes of content in pCell */
danielk1977a3ad5e72005-01-07 08:56:44 +00005812 u8 *pTemp, /* Temp storage space for pCell, if needed */
drh98add2e2009-07-20 17:11:49 +00005813 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
5814 int *pRC /* Read and write return code from here */
drh24cd67e2004-05-10 16:18:47 +00005815){
drh383d30f2010-02-26 13:07:37 +00005816 int idx = 0; /* Where to write new cell content in data[] */
drh43605152004-05-29 21:46:49 +00005817 int j; /* Loop counter */
drh43605152004-05-29 21:46:49 +00005818 int end; /* First byte past the last cell pointer in data[] */
5819 int ins; /* Index in data[] where new cell pointer is inserted */
drh43605152004-05-29 21:46:49 +00005820 int cellOffset; /* Address of first cell pointer in data[] */
5821 u8 *data; /* The content of the whole page */
danielk19774dbaa892009-06-16 16:50:22 +00005822 int nSkip = (iChild ? 4 : 0);
5823
drh98add2e2009-07-20 17:11:49 +00005824 if( *pRC ) return;
5825
drh43605152004-05-29 21:46:49 +00005826 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
danf216e322014-08-14 19:53:37 +00005827 assert( MX_CELL(pPage->pBt)<=10921 );
5828 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
drh2cbd78b2012-02-02 19:37:18 +00005829 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
5830 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
drh1fee73e2007-08-29 04:00:57 +00005831 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhc9b9b8a2009-12-03 21:26:52 +00005832 /* The cell should normally be sized correctly. However, when moving a
5833 ** malformed cell from a leaf page to an interior page, if the cell size
5834 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
5835 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
5836 ** the term after the || in the following assert(). */
5837 assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
drh43605152004-05-29 21:46:49 +00005838 if( pPage->nOverflow || sz+2>pPage->nFree ){
drh24cd67e2004-05-10 16:18:47 +00005839 if( pTemp ){
danielk1977a3ad5e72005-01-07 08:56:44 +00005840 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
drh43605152004-05-29 21:46:49 +00005841 pCell = pTemp;
drh24cd67e2004-05-10 16:18:47 +00005842 }
danielk19774dbaa892009-06-16 16:50:22 +00005843 if( iChild ){
5844 put4byte(pCell, iChild);
5845 }
drh43605152004-05-29 21:46:49 +00005846 j = pPage->nOverflow++;
drh2cbd78b2012-02-02 19:37:18 +00005847 assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
5848 pPage->apOvfl[j] = pCell;
5849 pPage->aiOvfl[j] = (u16)i;
drh14acc042001-06-10 19:56:58 +00005850 }else{
danielk19776e465eb2007-08-21 13:11:00 +00005851 int rc = sqlite3PagerWrite(pPage->pDbPage);
5852 if( rc!=SQLITE_OK ){
drh98add2e2009-07-20 17:11:49 +00005853 *pRC = rc;
5854 return;
danielk19776e465eb2007-08-21 13:11:00 +00005855 }
5856 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
drh43605152004-05-29 21:46:49 +00005857 data = pPage->aData;
drh43605152004-05-29 21:46:49 +00005858 cellOffset = pPage->cellOffset;
drh0a45c272009-07-08 01:49:11 +00005859 end = cellOffset + 2*pPage->nCell;
drh43605152004-05-29 21:46:49 +00005860 ins = cellOffset + 2*i;
drh0a45c272009-07-08 01:49:11 +00005861 rc = allocateSpace(pPage, sz, &idx);
drh98add2e2009-07-20 17:11:49 +00005862 if( rc ){ *pRC = rc; return; }
drhc314dc72009-07-21 11:52:34 +00005863 /* The allocateSpace() routine guarantees the following two properties
5864 ** if it returns success */
5865 assert( idx >= end+2 );
drhfcd71b62011-04-05 22:08:24 +00005866 assert( idx+sz <= (int)pPage->pBt->usableSize );
drh43605152004-05-29 21:46:49 +00005867 pPage->nCell++;
drh0a45c272009-07-08 01:49:11 +00005868 pPage->nFree -= (u16)(2 + sz);
danielk1977a3ad5e72005-01-07 08:56:44 +00005869 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
danielk19774dbaa892009-06-16 16:50:22 +00005870 if( iChild ){
5871 put4byte(&data[idx], iChild);
5872 }
drh8f518832013-12-09 02:32:19 +00005873 memmove(&data[ins+2], &data[ins], end-ins);
drh43605152004-05-29 21:46:49 +00005874 put2byte(&data[ins], idx);
drh0a45c272009-07-08 01:49:11 +00005875 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
danielk1977a19df672004-11-03 11:37:07 +00005876#ifndef SQLITE_OMIT_AUTOVACUUM
5877 if( pPage->pBt->autoVacuum ){
5878 /* The cell may contain a pointer to an overflow page. If so, write
5879 ** the entry for the overflow page into the pointer map.
5880 */
drh98add2e2009-07-20 17:11:49 +00005881 ptrmapPutOvflPtr(pPage, pCell, pRC);
danielk1977a19df672004-11-03 11:37:07 +00005882 }
5883#endif
drh14acc042001-06-10 19:56:58 +00005884 }
5885}
5886
5887/*
drhfa1a98a2004-05-14 19:08:17 +00005888** Add a list of cells to a page. The page should be initially empty.
5889** The cells are guaranteed to fit on the page.
5890*/
5891static void assemblePage(
peter.d.reid60ec9142014-09-06 16:39:46 +00005892 MemPage *pPage, /* The page to be assembled */
drhfa1a98a2004-05-14 19:08:17 +00005893 int nCell, /* The number of cells to add to this page */
drh43605152004-05-29 21:46:49 +00005894 u8 **apCell, /* Pointers to cell bodies */
drha9121e42008-02-19 14:59:35 +00005895 u16 *aSize /* Sizes of the cells */
drhfa1a98a2004-05-14 19:08:17 +00005896){
5897 int i; /* Loop counter */
danielk1977fad91942009-04-29 17:49:59 +00005898 u8 *pCellptr; /* Address of next cell pointer */
drh43605152004-05-29 21:46:49 +00005899 int cellbody; /* Address of next cell body */
danielk1977fad91942009-04-29 17:49:59 +00005900 u8 * const data = pPage->aData; /* Pointer to data for pPage */
5901 const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
5902 const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
drhfa1a98a2004-05-14 19:08:17 +00005903
drh43605152004-05-29 21:46:49 +00005904 assert( pPage->nOverflow==0 );
drh1fee73e2007-08-29 04:00:57 +00005905 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
drhfcd71b62011-04-05 22:08:24 +00005906 assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
5907 && (int)MX_CELL(pPage->pBt)<=10921);
drhc5053fb2008-11-27 02:22:10 +00005908 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
danielk1977fad91942009-04-29 17:49:59 +00005909
5910 /* Check that the page has just been zeroed by zeroPage() */
5911 assert( pPage->nCell==0 );
drh5d433ce2010-08-14 16:02:52 +00005912 assert( get2byteNotZero(&data[hdr+5])==nUsable );
danielk1977fad91942009-04-29 17:49:59 +00005913
drh3def2352011-11-11 00:27:15 +00005914 pCellptr = &pPage->aCellIdx[nCell*2];
danielk1977fad91942009-04-29 17:49:59 +00005915 cellbody = nUsable;
5916 for(i=nCell-1; i>=0; i--){
drh61d2fe92011-06-03 23:28:33 +00005917 u16 sz = aSize[i];
danielk1977fad91942009-04-29 17:49:59 +00005918 pCellptr -= 2;
drh61d2fe92011-06-03 23:28:33 +00005919 cellbody -= sz;
danielk1977fad91942009-04-29 17:49:59 +00005920 put2byte(pCellptr, cellbody);
drh61d2fe92011-06-03 23:28:33 +00005921 memcpy(&data[cellbody], apCell[i], sz);
drhfa1a98a2004-05-14 19:08:17 +00005922 }
danielk1977fad91942009-04-29 17:49:59 +00005923 put2byte(&data[hdr+3], nCell);
5924 put2byte(&data[hdr+5], cellbody);
5925 pPage->nFree -= (nCell*2 + nUsable - cellbody);
drhf49661a2008-12-10 16:45:50 +00005926 pPage->nCell = (u16)nCell;
drhfa1a98a2004-05-14 19:08:17 +00005927}
5928
drh14acc042001-06-10 19:56:58 +00005929/*
drhc3b70572003-01-04 19:44:07 +00005930** The following parameters determine how many adjacent pages get involved
5931** in a balancing operation. NN is the number of neighbors on either side
5932** of the page that participate in the balancing operation. NB is the
5933** total number of pages that participate, including the target page and
5934** NN neighbors on either side.
5935**
5936** The minimum value of NN is 1 (of course). Increasing NN above 1
5937** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
5938** in exchange for a larger degradation in INSERT and UPDATE performance.
5939** The value of NN appears to give the best results overall.
5940*/
5941#define NN 1 /* Number of neighbors on either side of pPage */
5942#define NB (NN*2+1) /* Total pages involved in the balance */
5943
danielk1977ac245ec2005-01-14 13:50:11 +00005944
drh615ae552005-01-16 23:21:00 +00005945#ifndef SQLITE_OMIT_QUICKBALANCE
drhf222e712005-01-14 22:55:49 +00005946/*
5947** This version of balance() handles the common special case where
5948** a new entry is being inserted on the extreme right-end of the
5949** tree, in other words, when the new entry will become the largest
5950** entry in the tree.
5951**
drhc314dc72009-07-21 11:52:34 +00005952** Instead of trying to balance the 3 right-most leaf pages, just add
drhf222e712005-01-14 22:55:49 +00005953** a new page to the right-hand side and put the one new entry in
5954** that page. This leaves the right side of the tree somewhat
5955** unbalanced. But odds are that we will be inserting new entries
5956** at the end soon afterwards so the nearly empty page will quickly
5957** fill up. On average.
5958**
5959** pPage is the leaf page which is the right-most page in the tree.
5960** pParent is its parent. pPage must have a single overflow entry
5961** which is also the right-most entry on the page.
danielk1977a50d9aa2009-06-08 14:49:45 +00005962**
5963** The pSpace buffer is used to store a temporary copy of the divider
5964** cell that will be inserted into pParent. Such a cell consists of a 4
5965** byte page number followed by a variable length integer. In other
5966** words, at most 13 bytes. Hence the pSpace buffer must be at
5967** least 13 bytes in size.
drhf222e712005-01-14 22:55:49 +00005968*/
danielk1977a50d9aa2009-06-08 14:49:45 +00005969static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
5970 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
danielk19774dbaa892009-06-16 16:50:22 +00005971 MemPage *pNew; /* Newly allocated page */
danielk19776f235cc2009-06-04 14:46:08 +00005972 int rc; /* Return Code */
5973 Pgno pgnoNew; /* Page number of pNew */
danielk1977ac245ec2005-01-14 13:50:11 +00005974
drh1fee73e2007-08-29 04:00:57 +00005975 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
danielk1977a50d9aa2009-06-08 14:49:45 +00005976 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00005977 assert( pPage->nOverflow==1 );
5978
drh5d433ce2010-08-14 16:02:52 +00005979 /* This error condition is now caught prior to reaching this function */
mistachkin5f070c72012-10-18 10:35:19 +00005980 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
drhd677b3d2007-08-20 22:48:41 +00005981
danielk1977a50d9aa2009-06-08 14:49:45 +00005982 /* Allocate a new page. This page will become the right-sibling of
5983 ** pPage. Make the parent page writable, so that the new divider cell
5984 ** may be inserted. If both these operations are successful, proceed.
5985 */
drh4f0c5872007-03-26 22:05:01 +00005986 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
danielk19774dbaa892009-06-16 16:50:22 +00005987
danielk1977eaa06f62008-09-18 17:34:44 +00005988 if( rc==SQLITE_OK ){
danielk1977a50d9aa2009-06-08 14:49:45 +00005989
5990 u8 *pOut = &pSpace[4];
drh2cbd78b2012-02-02 19:37:18 +00005991 u8 *pCell = pPage->apOvfl[0];
danielk19776f235cc2009-06-04 14:46:08 +00005992 u16 szCell = cellSizePtr(pPage, pCell);
5993 u8 *pStop;
5994
drhc5053fb2008-11-27 02:22:10 +00005995 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
danielk1977e56b60e2009-06-10 09:11:06 +00005996 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
5997 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
danielk1977eaa06f62008-09-18 17:34:44 +00005998 assemblePage(pNew, 1, &pCell, &szCell);
danielk19774dbaa892009-06-16 16:50:22 +00005999
6000 /* If this is an auto-vacuum database, update the pointer map
6001 ** with entries for the new page, and any pointer from the
6002 ** cell on the page to an overflow page. If either of these
6003 ** operations fails, the return code is set, but the contents
6004 ** of the parent page are still manipulated by thh code below.
6005 ** That is Ok, at this point the parent page is guaranteed to
6006 ** be marked as dirty. Returning an error code will cause a
6007 ** rollback, undoing any changes made to the parent page.
6008 */
6009 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00006010 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
6011 if( szCell>pNew->minLocal ){
6012 ptrmapPutOvflPtr(pNew, pCell, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006013 }
6014 }
danielk1977eaa06f62008-09-18 17:34:44 +00006015
danielk19776f235cc2009-06-04 14:46:08 +00006016 /* Create a divider cell to insert into pParent. The divider cell
6017 ** consists of a 4-byte page number (the page number of pPage) and
6018 ** a variable length key value (which must be the same value as the
6019 ** largest key on pPage).
danielk1977eaa06f62008-09-18 17:34:44 +00006020 **
danielk19776f235cc2009-06-04 14:46:08 +00006021 ** To find the largest key value on pPage, first find the right-most
6022 ** cell on pPage. The first two fields of this cell are the
6023 ** record-length (a variable length integer at most 32-bits in size)
6024 ** and the key value (a variable length integer, may have any value).
6025 ** The first of the while(...) loops below skips over the record-length
6026 ** field. The second while(...) loop copies the key value from the
danielk1977a50d9aa2009-06-08 14:49:45 +00006027 ** cell on pPage into the pSpace buffer.
danielk1977eaa06f62008-09-18 17:34:44 +00006028 */
danielk1977eaa06f62008-09-18 17:34:44 +00006029 pCell = findCell(pPage, pPage->nCell-1);
danielk19776f235cc2009-06-04 14:46:08 +00006030 pStop = &pCell[9];
6031 while( (*(pCell++)&0x80) && pCell<pStop );
6032 pStop = &pCell[9];
6033 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
6034
danielk19774dbaa892009-06-16 16:50:22 +00006035 /* Insert the new divider cell into pParent. */
drh98add2e2009-07-20 17:11:49 +00006036 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
6037 0, pPage->pgno, &rc);
danielk19776f235cc2009-06-04 14:46:08 +00006038
6039 /* Set the right-child pointer of pParent to point to the new page. */
danielk1977eaa06f62008-09-18 17:34:44 +00006040 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
6041
danielk1977e08a3c42008-09-18 18:17:03 +00006042 /* Release the reference to the new page. */
6043 releasePage(pNew);
danielk1977ac11ee62005-01-15 12:45:51 +00006044 }
6045
danielk1977eaa06f62008-09-18 17:34:44 +00006046 return rc;
danielk1977ac245ec2005-01-14 13:50:11 +00006047}
drh615ae552005-01-16 23:21:00 +00006048#endif /* SQLITE_OMIT_QUICKBALANCE */
drh43605152004-05-29 21:46:49 +00006049
danielk19774dbaa892009-06-16 16:50:22 +00006050#if 0
drhc3b70572003-01-04 19:44:07 +00006051/*
danielk19774dbaa892009-06-16 16:50:22 +00006052** This function does not contribute anything to the operation of SQLite.
6053** it is sometimes activated temporarily while debugging code responsible
6054** for setting pointer-map entries.
6055*/
6056static int ptrmapCheckPages(MemPage **apPage, int nPage){
6057 int i, j;
6058 for(i=0; i<nPage; i++){
6059 Pgno n;
6060 u8 e;
6061 MemPage *pPage = apPage[i];
6062 BtShared *pBt = pPage->pBt;
6063 assert( pPage->isInit );
6064
6065 for(j=0; j<pPage->nCell; j++){
6066 CellInfo info;
6067 u8 *z;
6068
6069 z = findCell(pPage, j);
danielk197730548662009-07-09 05:07:37 +00006070 btreeParseCellPtr(pPage, z, &info);
danielk19774dbaa892009-06-16 16:50:22 +00006071 if( info.iOverflow ){
6072 Pgno ovfl = get4byte(&z[info.iOverflow]);
6073 ptrmapGet(pBt, ovfl, &e, &n);
6074 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
6075 }
6076 if( !pPage->leaf ){
6077 Pgno child = get4byte(z);
6078 ptrmapGet(pBt, child, &e, &n);
6079 assert( n==pPage->pgno && e==PTRMAP_BTREE );
6080 }
6081 }
6082 if( !pPage->leaf ){
6083 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
6084 ptrmapGet(pBt, child, &e, &n);
6085 assert( n==pPage->pgno && e==PTRMAP_BTREE );
6086 }
6087 }
6088 return 1;
6089}
6090#endif
6091
danielk1977cd581a72009-06-23 15:43:39 +00006092/*
6093** This function is used to copy the contents of the b-tree node stored
6094** on page pFrom to page pTo. If page pFrom was not a leaf page, then
6095** the pointer-map entries for each child page are updated so that the
6096** parent page stored in the pointer map is page pTo. If pFrom contained
6097** any cells with overflow page pointers, then the corresponding pointer
6098** map entries are also updated so that the parent page is page pTo.
6099**
6100** If pFrom is currently carrying any overflow cells (entries in the
drh2cbd78b2012-02-02 19:37:18 +00006101** MemPage.apOvfl[] array), they are not copied to pTo.
danielk1977cd581a72009-06-23 15:43:39 +00006102**
danielk197730548662009-07-09 05:07:37 +00006103** Before returning, page pTo is reinitialized using btreeInitPage().
danielk1977cd581a72009-06-23 15:43:39 +00006104**
6105** The performance of this function is not critical. It is only used by
6106** the balance_shallower() and balance_deeper() procedures, neither of
6107** which are called often under normal circumstances.
6108*/
drhc314dc72009-07-21 11:52:34 +00006109static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
6110 if( (*pRC)==SQLITE_OK ){
6111 BtShared * const pBt = pFrom->pBt;
6112 u8 * const aFrom = pFrom->aData;
6113 u8 * const aTo = pTo->aData;
6114 int const iFromHdr = pFrom->hdrOffset;
6115 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
drhdc9b5f82009-12-05 18:34:08 +00006116 int rc;
drhc314dc72009-07-21 11:52:34 +00006117 int iData;
6118
6119
6120 assert( pFrom->isInit );
6121 assert( pFrom->nFree>=iToHdr );
drhfcd71b62011-04-05 22:08:24 +00006122 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
drhc314dc72009-07-21 11:52:34 +00006123
6124 /* Copy the b-tree node content from page pFrom to page pTo. */
6125 iData = get2byte(&aFrom[iFromHdr+5]);
6126 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
6127 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
6128
6129 /* Reinitialize page pTo so that the contents of the MemPage structure
dan89e060e2009-12-05 18:03:50 +00006130 ** match the new data. The initialization of pTo can actually fail under
6131 ** fairly obscure circumstances, even though it is a copy of initialized
6132 ** page pFrom.
6133 */
drhc314dc72009-07-21 11:52:34 +00006134 pTo->isInit = 0;
dan89e060e2009-12-05 18:03:50 +00006135 rc = btreeInitPage(pTo);
6136 if( rc!=SQLITE_OK ){
6137 *pRC = rc;
6138 return;
6139 }
drhc314dc72009-07-21 11:52:34 +00006140
6141 /* If this is an auto-vacuum database, update the pointer-map entries
6142 ** for any b-tree or overflow pages that pTo now contains the pointers to.
6143 */
6144 if( ISAUTOVACUUM ){
6145 *pRC = setChildPtrmaps(pTo);
6146 }
danielk1977cd581a72009-06-23 15:43:39 +00006147 }
danielk1977cd581a72009-06-23 15:43:39 +00006148}
6149
6150/*
danielk19774dbaa892009-06-16 16:50:22 +00006151** This routine redistributes cells on the iParentIdx'th child of pParent
6152** (hereafter "the page") and up to 2 siblings so that all pages have about the
6153** same amount of free space. Usually a single sibling on either side of the
6154** page are used in the balancing, though both siblings might come from one
6155** side if the page is the first or last child of its parent. If the page
6156** has fewer than 2 siblings (something which can only happen if the page
6157** is a root page or a child of a root page) then all available siblings
6158** participate in the balancing.
drh8b2f49b2001-06-08 00:21:52 +00006159**
danielk19774dbaa892009-06-16 16:50:22 +00006160** The number of siblings of the page might be increased or decreased by
6161** one or two in an effort to keep pages nearly full but not over full.
drh14acc042001-06-10 19:56:58 +00006162**
danielk19774dbaa892009-06-16 16:50:22 +00006163** Note that when this routine is called, some of the cells on the page
6164** might not actually be stored in MemPage.aData[]. This can happen
6165** if the page is overfull. This routine ensures that all cells allocated
6166** to the page and its siblings fit into MemPage.aData[] before returning.
drh14acc042001-06-10 19:56:58 +00006167**
danielk19774dbaa892009-06-16 16:50:22 +00006168** In the course of balancing the page and its siblings, cells may be
6169** inserted into or removed from the parent page (pParent). Doing so
6170** may cause the parent page to become overfull or underfull. If this
6171** happens, it is the responsibility of the caller to invoke the correct
6172** balancing routine to fix this problem (see the balance() routine).
drh8c42ca92001-06-22 19:15:00 +00006173**
drh5e00f6c2001-09-13 13:46:56 +00006174** If this routine fails for any reason, it might leave the database
danielk19776067a9b2009-06-09 09:41:00 +00006175** in a corrupted state. So if this routine fails, the database should
drh5e00f6c2001-09-13 13:46:56 +00006176** be rolled back.
danielk19774dbaa892009-06-16 16:50:22 +00006177**
6178** The third argument to this function, aOvflSpace, is a pointer to a
drhcd09c532009-07-20 19:30:00 +00006179** buffer big enough to hold one page. If while inserting cells into the parent
6180** page (pParent) the parent page becomes overfull, this buffer is
6181** used to store the parent's overflow cells. Because this function inserts
danielk19774dbaa892009-06-16 16:50:22 +00006182** a maximum of four divider cells into the parent page, and the maximum
6183** size of a cell stored within an internal node is always less than 1/4
6184** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
6185** enough for all overflow cells.
6186**
6187** If aOvflSpace is set to a null pointer, this function returns
6188** SQLITE_NOMEM.
drh8b2f49b2001-06-08 00:21:52 +00006189*/
mistachkine7c54162012-10-02 22:54:27 +00006190#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
6191#pragma optimize("", off)
6192#endif
danielk19774dbaa892009-06-16 16:50:22 +00006193static int balance_nonroot(
6194 MemPage *pParent, /* Parent page of siblings being balanced */
6195 int iParentIdx, /* Index of "the page" in pParent */
danielk1977cd581a72009-06-23 15:43:39 +00006196 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
dan428c2182012-08-06 18:50:11 +00006197 int isRoot, /* True if pParent is a root-page */
6198 int bBulk /* True if this call is part of a bulk load */
danielk19774dbaa892009-06-16 16:50:22 +00006199){
drh16a9b832007-05-05 18:39:25 +00006200 BtShared *pBt; /* The whole database */
danielk1977634f2982005-03-28 08:44:07 +00006201 int nCell = 0; /* Number of cells in apCell[] */
6202 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
danielk1977a4124bd2008-12-23 10:37:47 +00006203 int nNew = 0; /* Number of pages in apNew[] */
danielk19774dbaa892009-06-16 16:50:22 +00006204 int nOld; /* Number of pages in apOld[] */
drh14acc042001-06-10 19:56:58 +00006205 int i, j, k; /* Loop counters */
drha34b6762004-05-07 13:30:42 +00006206 int nxDiv; /* Next divider slot in pParent->aCell[] */
shane85095702009-06-15 16:27:08 +00006207 int rc = SQLITE_OK; /* The return code */
shane36840fd2009-06-26 16:32:13 +00006208 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
drh8b18dd42004-05-12 19:18:15 +00006209 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
drh91025292004-05-03 19:49:32 +00006210 int usableSpace; /* Bytes in pPage beyond the header */
6211 int pageFlags; /* Value of pPage->aData[0] */
drh6019e162001-07-02 17:51:45 +00006212 int subtotal; /* Subtotal of bytes in cells on one page */
drhe5ae5732008-06-15 02:51:47 +00006213 int iSpace1 = 0; /* First unused byte of aSpace1[] */
danielk19776067a9b2009-06-09 09:41:00 +00006214 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
drhfacf0302008-06-17 15:12:00 +00006215 int szScratch; /* Size of scratch memory requested */
drhc3b70572003-01-04 19:44:07 +00006216 MemPage *apOld[NB]; /* pPage and up to two siblings */
drh4b70f112004-05-02 21:12:19 +00006217 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
drha2fce642004-06-05 00:01:44 +00006218 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
danielk19774dbaa892009-06-16 16:50:22 +00006219 u8 *pRight; /* Location in parent of right-sibling pointer */
6220 u8 *apDiv[NB-1]; /* Divider cells in pParent */
drha2fce642004-06-05 00:01:44 +00006221 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
6222 int szNew[NB+2]; /* Combined size of cells place on i-th page */
danielk197750f059b2005-03-29 02:54:03 +00006223 u8 **apCell = 0; /* All cells begin balanced */
drha9121e42008-02-19 14:59:35 +00006224 u16 *szCell; /* Local size of all cells in apCell[] */
danielk19774dbaa892009-06-16 16:50:22 +00006225 u8 *aSpace1; /* Space for copies of dividers cells */
6226 Pgno pgno; /* Temp var to store a page number in */
drh8b2f49b2001-06-08 00:21:52 +00006227
danielk1977a50d9aa2009-06-08 14:49:45 +00006228 pBt = pParent->pBt;
6229 assert( sqlite3_mutex_held(pBt->mutex) );
6230 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk1977474b7cc2008-07-09 11:49:46 +00006231
danielk1977e5765212009-06-17 11:13:28 +00006232#if 0
drh43605152004-05-29 21:46:49 +00006233 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
danielk1977e5765212009-06-17 11:13:28 +00006234#endif
drh2e38c322004-09-03 18:38:44 +00006235
danielk19774dbaa892009-06-16 16:50:22 +00006236 /* At this point pParent may have at most one overflow cell. And if
6237 ** this overflow cell is present, it must be the cell with
6238 ** index iParentIdx. This scenario comes about when this function
drhcd09c532009-07-20 19:30:00 +00006239 ** is called (indirectly) from sqlite3BtreeDelete().
6240 */
danielk19774dbaa892009-06-16 16:50:22 +00006241 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
drh2cbd78b2012-02-02 19:37:18 +00006242 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
danielk19774dbaa892009-06-16 16:50:22 +00006243
danielk197711a8a862009-06-17 11:49:52 +00006244 if( !aOvflSpace ){
6245 return SQLITE_NOMEM;
6246 }
6247
danielk1977a50d9aa2009-06-08 14:49:45 +00006248 /* Find the sibling pages to balance. Also locate the cells in pParent
6249 ** that divide the siblings. An attempt is made to find NN siblings on
6250 ** either side of pPage. More siblings are taken from one side, however,
6251 ** if there are fewer than NN siblings on the other side. If pParent
danielk19774dbaa892009-06-16 16:50:22 +00006252 ** has NB or fewer children then all children of pParent are taken.
6253 **
6254 ** This loop also drops the divider cells from the parent page. This
6255 ** way, the remainder of the function does not have to deal with any
drhcd09c532009-07-20 19:30:00 +00006256 ** overflow cells in the parent page, since if any existed they will
6257 ** have already been removed.
6258 */
danielk19774dbaa892009-06-16 16:50:22 +00006259 i = pParent->nOverflow + pParent->nCell;
6260 if( i<2 ){
drhc3b70572003-01-04 19:44:07 +00006261 nxDiv = 0;
danielk19774dbaa892009-06-16 16:50:22 +00006262 }else{
dan7d6885a2012-08-08 14:04:56 +00006263 assert( bBulk==0 || bBulk==1 );
danielk19774dbaa892009-06-16 16:50:22 +00006264 if( iParentIdx==0 ){
6265 nxDiv = 0;
6266 }else if( iParentIdx==i ){
dan7d6885a2012-08-08 14:04:56 +00006267 nxDiv = i-2+bBulk;
drh14acc042001-06-10 19:56:58 +00006268 }else{
dan7d6885a2012-08-08 14:04:56 +00006269 assert( bBulk==0 );
danielk19774dbaa892009-06-16 16:50:22 +00006270 nxDiv = iParentIdx-1;
drh8b2f49b2001-06-08 00:21:52 +00006271 }
dan7d6885a2012-08-08 14:04:56 +00006272 i = 2-bBulk;
danielk19774dbaa892009-06-16 16:50:22 +00006273 }
dan7d6885a2012-08-08 14:04:56 +00006274 nOld = i+1;
danielk19774dbaa892009-06-16 16:50:22 +00006275 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
6276 pRight = &pParent->aData[pParent->hdrOffset+8];
6277 }else{
6278 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
6279 }
6280 pgno = get4byte(pRight);
6281 while( 1 ){
dan11dcd112013-03-15 18:29:18 +00006282 rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
danielk19774dbaa892009-06-16 16:50:22 +00006283 if( rc ){
danielk197789bc4bc2009-07-21 19:25:24 +00006284 memset(apOld, 0, (i+1)*sizeof(MemPage*));
danielk19774dbaa892009-06-16 16:50:22 +00006285 goto balance_cleanup;
6286 }
danielk1977634f2982005-03-28 08:44:07 +00006287 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
danielk19774dbaa892009-06-16 16:50:22 +00006288 if( (i--)==0 ) break;
6289
drh2cbd78b2012-02-02 19:37:18 +00006290 if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
6291 apDiv[i] = pParent->apOvfl[0];
danielk19774dbaa892009-06-16 16:50:22 +00006292 pgno = get4byte(apDiv[i]);
6293 szNew[i] = cellSizePtr(pParent, apDiv[i]);
6294 pParent->nOverflow = 0;
6295 }else{
6296 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
6297 pgno = get4byte(apDiv[i]);
6298 szNew[i] = cellSizePtr(pParent, apDiv[i]);
6299
6300 /* Drop the cell from the parent page. apDiv[i] still points to
6301 ** the cell within the parent, even though it has been dropped.
6302 ** This is safe because dropping a cell only overwrites the first
6303 ** four bytes of it, and this function does not need the first
6304 ** four bytes of the divider cell. So the pointer is safe to use
danielk197711a8a862009-06-17 11:49:52 +00006305 ** later on.
6306 **
drh8a575d92011-10-12 17:00:28 +00006307 ** But not if we are in secure-delete mode. In secure-delete mode,
danielk197711a8a862009-06-17 11:49:52 +00006308 ** the dropCell() routine will overwrite the entire cell with zeroes.
6309 ** In this case, temporarily copy the cell into the aOvflSpace[]
6310 ** buffer. It will be copied out again as soon as the aSpace[] buffer
6311 ** is allocated. */
drhc9166342012-01-05 23:32:06 +00006312 if( pBt->btsFlags & BTS_SECURE_DELETE ){
drh8a575d92011-10-12 17:00:28 +00006313 int iOff;
6314
6315 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
drh43b18e12010-08-17 19:40:08 +00006316 if( (iOff+szNew[i])>(int)pBt->usableSize ){
dan2ed11e72010-02-26 15:09:19 +00006317 rc = SQLITE_CORRUPT_BKPT;
6318 memset(apOld, 0, (i+1)*sizeof(MemPage*));
6319 goto balance_cleanup;
6320 }else{
6321 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
6322 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
6323 }
drh5b47efa2010-02-12 18:18:39 +00006324 }
drh98add2e2009-07-20 17:11:49 +00006325 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006326 }
drh8b2f49b2001-06-08 00:21:52 +00006327 }
6328
drha9121e42008-02-19 14:59:35 +00006329 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
drh8d97f1f2005-05-05 18:14:13 +00006330 ** alignment */
drha9121e42008-02-19 14:59:35 +00006331 nMaxCells = (nMaxCells + 3)&~3;
drh8d97f1f2005-05-05 18:14:13 +00006332
drh8b2f49b2001-06-08 00:21:52 +00006333 /*
danielk1977634f2982005-03-28 08:44:07 +00006334 ** Allocate space for memory structures
6335 */
danielk19774dbaa892009-06-16 16:50:22 +00006336 k = pBt->pageSize + ROUND8(sizeof(MemPage));
drhfacf0302008-06-17 15:12:00 +00006337 szScratch =
drha9121e42008-02-19 14:59:35 +00006338 nMaxCells*sizeof(u8*) /* apCell */
6339 + nMaxCells*sizeof(u16) /* szCell */
drhe5ae5732008-06-15 02:51:47 +00006340 + pBt->pageSize /* aSpace1 */
danielk19774dbaa892009-06-16 16:50:22 +00006341 + k*nOld; /* Page copies (apCopy) */
drhfacf0302008-06-17 15:12:00 +00006342 apCell = sqlite3ScratchMalloc( szScratch );
danielk197711a8a862009-06-17 11:49:52 +00006343 if( apCell==0 ){
danielk1977634f2982005-03-28 08:44:07 +00006344 rc = SQLITE_NOMEM;
6345 goto balance_cleanup;
6346 }
drha9121e42008-02-19 14:59:35 +00006347 szCell = (u16*)&apCell[nMaxCells];
danielk19774dbaa892009-06-16 16:50:22 +00006348 aSpace1 = (u8*)&szCell[nMaxCells];
drhea598cb2009-04-05 12:22:08 +00006349 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
drh14acc042001-06-10 19:56:58 +00006350
6351 /*
6352 ** Load pointers to all cells on sibling pages and the divider cells
6353 ** into the local apCell[] array. Make copies of the divider cells
mistachkind5578432012-08-25 10:01:29 +00006354 ** into space obtained from aSpace1[] and remove the divider cells
drhb6f41482004-05-14 01:58:11 +00006355 ** from pParent.
drh4b70f112004-05-02 21:12:19 +00006356 **
6357 ** If the siblings are on leaf pages, then the child pointers of the
6358 ** divider cells are stripped from the cells before they are copied
drhe5ae5732008-06-15 02:51:47 +00006359 ** into aSpace1[]. In this way, all cells in apCell[] are without
drh4b70f112004-05-02 21:12:19 +00006360 ** child pointers. If siblings are not leaves, then all cell in
6361 ** apCell[] include child pointers. Either way, all cells in apCell[]
6362 ** are alike.
drh96f5b762004-05-16 16:24:36 +00006363 **
6364 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
6365 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
drh8b2f49b2001-06-08 00:21:52 +00006366 */
danielk1977a50d9aa2009-06-08 14:49:45 +00006367 leafCorrection = apOld[0]->leaf*4;
6368 leafData = apOld[0]->hasData;
drh8b2f49b2001-06-08 00:21:52 +00006369 for(i=0; i<nOld; i++){
danielk19774dbaa892009-06-16 16:50:22 +00006370 int limit;
6371
6372 /* Before doing anything else, take a copy of the i'th original sibling
6373 ** The rest of this function will use data from the copies rather
6374 ** that the original pages since the original pages will be in the
6375 ** process of being overwritten. */
6376 MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
6377 memcpy(pOld, apOld[i], sizeof(MemPage));
6378 pOld->aData = (void*)&pOld[1];
6379 memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
6380
6381 limit = pOld->nCell+pOld->nOverflow;
drh68f2a572011-06-03 17:50:49 +00006382 if( pOld->nOverflow>0 ){
6383 for(j=0; j<limit; j++){
6384 assert( nCell<nMaxCells );
6385 apCell[nCell] = findOverflowCell(pOld, j);
6386 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
6387 nCell++;
6388 }
6389 }else{
6390 u8 *aData = pOld->aData;
6391 u16 maskPage = pOld->maskPage;
6392 u16 cellOffset = pOld->cellOffset;
6393 for(j=0; j<limit; j++){
6394 assert( nCell<nMaxCells );
6395 apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
6396 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
6397 nCell++;
6398 }
6399 }
danielk19774dbaa892009-06-16 16:50:22 +00006400 if( i<nOld-1 && !leafData){
shane36840fd2009-06-26 16:32:13 +00006401 u16 sz = (u16)szNew[i];
danielk19774dbaa892009-06-16 16:50:22 +00006402 u8 *pTemp;
6403 assert( nCell<nMaxCells );
6404 szCell[nCell] = sz;
6405 pTemp = &aSpace1[iSpace1];
6406 iSpace1 += sz;
drhe22e03e2010-08-18 21:19:03 +00006407 assert( sz<=pBt->maxLocal+23 );
drhfcd71b62011-04-05 22:08:24 +00006408 assert( iSpace1 <= (int)pBt->pageSize );
danielk19774dbaa892009-06-16 16:50:22 +00006409 memcpy(pTemp, apDiv[i], sz);
6410 apCell[nCell] = pTemp+leafCorrection;
6411 assert( leafCorrection==0 || leafCorrection==4 );
shane36840fd2009-06-26 16:32:13 +00006412 szCell[nCell] = szCell[nCell] - leafCorrection;
danielk19774dbaa892009-06-16 16:50:22 +00006413 if( !pOld->leaf ){
6414 assert( leafCorrection==0 );
6415 assert( pOld->hdrOffset==0 );
6416 /* The right pointer of the child page pOld becomes the left
6417 ** pointer of the divider cell */
6418 memcpy(apCell[nCell], &pOld->aData[8], 4);
6419 }else{
6420 assert( leafCorrection==4 );
6421 if( szCell[nCell]<4 ){
6422 /* Do not allow any cells smaller than 4 bytes. */
6423 szCell[nCell] = 4;
danielk1977ac11ee62005-01-15 12:45:51 +00006424 }
6425 }
drh14acc042001-06-10 19:56:58 +00006426 nCell++;
drh8b2f49b2001-06-08 00:21:52 +00006427 }
drh8b2f49b2001-06-08 00:21:52 +00006428 }
6429
6430 /*
drh6019e162001-07-02 17:51:45 +00006431 ** Figure out the number of pages needed to hold all nCell cells.
6432 ** Store this number in "k". Also compute szNew[] which is the total
6433 ** size of all cells on the i-th page and cntNew[] which is the index
drh4b70f112004-05-02 21:12:19 +00006434 ** in apCell[] of the cell that divides page i from page i+1.
drh6019e162001-07-02 17:51:45 +00006435 ** cntNew[k] should equal nCell.
6436 **
drh96f5b762004-05-16 16:24:36 +00006437 ** Values computed by this block:
6438 **
6439 ** k: The total number of sibling pages
6440 ** szNew[i]: Spaced used on the i-th sibling page.
6441 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
6442 ** the right of the i-th sibling page.
6443 ** usableSpace: Number of bytes of space available on each sibling.
6444 **
drh8b2f49b2001-06-08 00:21:52 +00006445 */
drh43605152004-05-29 21:46:49 +00006446 usableSpace = pBt->usableSize - 12 + leafCorrection;
drh6019e162001-07-02 17:51:45 +00006447 for(subtotal=k=i=0; i<nCell; i++){
danielk1977634f2982005-03-28 08:44:07 +00006448 assert( i<nMaxCells );
drh43605152004-05-29 21:46:49 +00006449 subtotal += szCell[i] + 2;
drh4b70f112004-05-02 21:12:19 +00006450 if( subtotal > usableSpace ){
drh6019e162001-07-02 17:51:45 +00006451 szNew[k] = subtotal - szCell[i];
6452 cntNew[k] = i;
drh8b18dd42004-05-12 19:18:15 +00006453 if( leafData ){ i--; }
drh6019e162001-07-02 17:51:45 +00006454 subtotal = 0;
6455 k++;
drh9978c972010-02-23 17:36:32 +00006456 if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
drh6019e162001-07-02 17:51:45 +00006457 }
6458 }
6459 szNew[k] = subtotal;
6460 cntNew[k] = nCell;
6461 k++;
drh96f5b762004-05-16 16:24:36 +00006462
6463 /*
6464 ** The packing computed by the previous block is biased toward the siblings
6465 ** on the left side. The left siblings are always nearly full, while the
6466 ** right-most sibling might be nearly empty. This block of code attempts
6467 ** to adjust the packing of siblings to get a better balance.
6468 **
6469 ** This adjustment is more than an optimization. The packing above might
6470 ** be so out of balance as to be illegal. For example, the right-most
6471 ** sibling might be completely empty. This adjustment is not optional.
6472 */
drh6019e162001-07-02 17:51:45 +00006473 for(i=k-1; i>0; i--){
drh96f5b762004-05-16 16:24:36 +00006474 int szRight = szNew[i]; /* Size of sibling on the right */
6475 int szLeft = szNew[i-1]; /* Size of sibling on the left */
6476 int r; /* Index of right-most cell in left sibling */
6477 int d; /* Index of first cell to the left of right sibling */
6478
6479 r = cntNew[i-1] - 1;
6480 d = r + 1 - leafData;
danielk1977634f2982005-03-28 08:44:07 +00006481 assert( d<nMaxCells );
6482 assert( r<nMaxCells );
danf64cc492012-08-08 11:55:15 +00006483 while( szRight==0
6484 || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
6485 ){
drh43605152004-05-29 21:46:49 +00006486 szRight += szCell[d] + 2;
6487 szLeft -= szCell[r] + 2;
drh6019e162001-07-02 17:51:45 +00006488 cntNew[i-1]--;
drh96f5b762004-05-16 16:24:36 +00006489 r = cntNew[i-1] - 1;
6490 d = r + 1 - leafData;
drh6019e162001-07-02 17:51:45 +00006491 }
drh96f5b762004-05-16 16:24:36 +00006492 szNew[i] = szRight;
6493 szNew[i-1] = szLeft;
drh6019e162001-07-02 17:51:45 +00006494 }
drh09d0deb2005-08-02 17:13:09 +00006495
danielk19776f235cc2009-06-04 14:46:08 +00006496 /* Either we found one or more cells (cntnew[0])>0) or pPage is
drh09d0deb2005-08-02 17:13:09 +00006497 ** a virtual root page. A virtual root page is when the real root
6498 ** page is page 1 and we are the only child of that page.
drh2f32fba2012-01-02 16:38:57 +00006499 **
6500 ** UPDATE: The assert() below is not necessarily true if the database
6501 ** file is corrupt. The corruption will be detected and reported later
6502 ** in this procedure so there is no need to act upon it now.
drh09d0deb2005-08-02 17:13:09 +00006503 */
drh2f32fba2012-01-02 16:38:57 +00006504#if 0
drh09d0deb2005-08-02 17:13:09 +00006505 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
drh2f32fba2012-01-02 16:38:57 +00006506#endif
drh8b2f49b2001-06-08 00:21:52 +00006507
danielk1977e5765212009-06-17 11:13:28 +00006508 TRACE(("BALANCE: old: %d %d %d ",
6509 apOld[0]->pgno,
6510 nOld>=2 ? apOld[1]->pgno : 0,
6511 nOld>=3 ? apOld[2]->pgno : 0
6512 ));
6513
drh8b2f49b2001-06-08 00:21:52 +00006514 /*
drh6b308672002-07-08 02:16:37 +00006515 ** Allocate k new pages. Reuse old pages where possible.
drh8b2f49b2001-06-08 00:21:52 +00006516 */
drheac74422009-06-14 12:47:11 +00006517 if( apOld[0]->pgno<=1 ){
drh9978c972010-02-23 17:36:32 +00006518 rc = SQLITE_CORRUPT_BKPT;
drheac74422009-06-14 12:47:11 +00006519 goto balance_cleanup;
6520 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006521 pageFlags = apOld[0]->aData[0];
drh14acc042001-06-10 19:56:58 +00006522 for(i=0; i<k; i++){
drhda200cc2004-05-09 11:51:38 +00006523 MemPage *pNew;
drh6b308672002-07-08 02:16:37 +00006524 if( i<nOld ){
drhda200cc2004-05-09 11:51:38 +00006525 pNew = apNew[i] = apOld[i];
drh6b308672002-07-08 02:16:37 +00006526 apOld[i] = 0;
danielk19773b8a05f2007-03-19 17:44:26 +00006527 rc = sqlite3PagerWrite(pNew->pDbPage);
drhf5345442007-04-09 12:45:02 +00006528 nNew++;
danielk197728129562005-01-11 10:25:06 +00006529 if( rc ) goto balance_cleanup;
drh6b308672002-07-08 02:16:37 +00006530 }else{
drh7aa8f852006-03-28 00:24:44 +00006531 assert( i>0 );
dan428c2182012-08-06 18:50:11 +00006532 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
drh6b308672002-07-08 02:16:37 +00006533 if( rc ) goto balance_cleanup;
drhda200cc2004-05-09 11:51:38 +00006534 apNew[i] = pNew;
drhf5345442007-04-09 12:45:02 +00006535 nNew++;
danielk19774dbaa892009-06-16 16:50:22 +00006536
6537 /* Set the pointer-map entry for the new sibling page. */
6538 if( ISAUTOVACUUM ){
drh98add2e2009-07-20 17:11:49 +00006539 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006540 if( rc!=SQLITE_OK ){
6541 goto balance_cleanup;
6542 }
6543 }
drh6b308672002-07-08 02:16:37 +00006544 }
drh8b2f49b2001-06-08 00:21:52 +00006545 }
6546
danielk1977299b1872004-11-22 10:02:10 +00006547 /* Free any old pages that were not reused as new pages.
6548 */
6549 while( i<nOld ){
drhc314dc72009-07-21 11:52:34 +00006550 freePage(apOld[i], &rc);
danielk1977299b1872004-11-22 10:02:10 +00006551 if( rc ) goto balance_cleanup;
6552 releasePage(apOld[i]);
6553 apOld[i] = 0;
6554 i++;
6555 }
6556
drh8b2f49b2001-06-08 00:21:52 +00006557 /*
peter.d.reid60ec9142014-09-06 16:39:46 +00006558 ** Put the new pages in ascending order. This helps to
drhf9ffac92002-03-02 19:00:31 +00006559 ** keep entries in the disk file in order so that a scan
6560 ** of the table is a linear scan through the file. That
6561 ** in turn helps the operating system to deliver pages
6562 ** from the disk more rapidly.
6563 **
6564 ** An O(n^2) insertion sort algorithm is used, but since
drhc3b70572003-01-04 19:44:07 +00006565 ** n is never more than NB (a small constant), that should
6566 ** not be a problem.
drhf9ffac92002-03-02 19:00:31 +00006567 **
drhc3b70572003-01-04 19:44:07 +00006568 ** When NB==3, this one optimization makes the database
6569 ** about 25% faster for large insertions and deletions.
drhf9ffac92002-03-02 19:00:31 +00006570 */
6571 for(i=0; i<k-1; i++){
danielk19774dbaa892009-06-16 16:50:22 +00006572 int minV = apNew[i]->pgno;
drhf9ffac92002-03-02 19:00:31 +00006573 int minI = i;
6574 for(j=i+1; j<k; j++){
danielk19774dbaa892009-06-16 16:50:22 +00006575 if( apNew[j]->pgno<(unsigned)minV ){
drhf9ffac92002-03-02 19:00:31 +00006576 minI = j;
danielk19774dbaa892009-06-16 16:50:22 +00006577 minV = apNew[j]->pgno;
drhf9ffac92002-03-02 19:00:31 +00006578 }
6579 }
6580 if( minI>i ){
drhf9ffac92002-03-02 19:00:31 +00006581 MemPage *pT;
drhf9ffac92002-03-02 19:00:31 +00006582 pT = apNew[i];
drhf9ffac92002-03-02 19:00:31 +00006583 apNew[i] = apNew[minI];
drhf9ffac92002-03-02 19:00:31 +00006584 apNew[minI] = pT;
6585 }
6586 }
danielk1977e5765212009-06-17 11:13:28 +00006587 TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
danielk19774dbaa892009-06-16 16:50:22 +00006588 apNew[0]->pgno, szNew[0],
6589 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
6590 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
6591 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
6592 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
6593
6594 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
6595 put4byte(pRight, apNew[nNew-1]->pgno);
drh24cd67e2004-05-10 16:18:47 +00006596
drhf9ffac92002-03-02 19:00:31 +00006597 /*
drh14acc042001-06-10 19:56:58 +00006598 ** Evenly distribute the data in apCell[] across the new pages.
6599 ** Insert divider cells into pParent as necessary.
6600 */
6601 j = 0;
6602 for(i=0; i<nNew; i++){
danielk1977ac11ee62005-01-15 12:45:51 +00006603 /* Assemble the new sibling page. */
drh14acc042001-06-10 19:56:58 +00006604 MemPage *pNew = apNew[i];
drh19642e52005-03-29 13:17:45 +00006605 assert( j<nMaxCells );
drh10131482008-07-11 03:34:09 +00006606 zeroPage(pNew, pageFlags);
drhfa1a98a2004-05-14 19:08:17 +00006607 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
drh09d0deb2005-08-02 17:13:09 +00006608 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
drh43605152004-05-29 21:46:49 +00006609 assert( pNew->nOverflow==0 );
danielk1977ac11ee62005-01-15 12:45:51 +00006610
danielk1977ac11ee62005-01-15 12:45:51 +00006611 j = cntNew[i];
6612
6613 /* If the sibling page assembled above was not the right-most sibling,
6614 ** insert a divider cell into the parent page.
6615 */
danielk19771c3d2bf2009-06-23 16:40:17 +00006616 assert( i<nNew-1 || j==nCell );
6617 if( j<nCell ){
drh8b18dd42004-05-12 19:18:15 +00006618 u8 *pCell;
drh24cd67e2004-05-10 16:18:47 +00006619 u8 *pTemp;
drh8b18dd42004-05-12 19:18:15 +00006620 int sz;
danielk1977634f2982005-03-28 08:44:07 +00006621
6622 assert( j<nMaxCells );
drh8b18dd42004-05-12 19:18:15 +00006623 pCell = apCell[j];
6624 sz = szCell[j] + leafCorrection;
danielk19776067a9b2009-06-09 09:41:00 +00006625 pTemp = &aOvflSpace[iOvflSpace];
drh4b70f112004-05-02 21:12:19 +00006626 if( !pNew->leaf ){
drh43605152004-05-29 21:46:49 +00006627 memcpy(&pNew->aData[8], pCell, 4);
drh8b18dd42004-05-12 19:18:15 +00006628 }else if( leafData ){
drhfd131da2007-08-07 17:13:03 +00006629 /* If the tree is a leaf-data tree, and the siblings are leaves,
danielk1977ac11ee62005-01-15 12:45:51 +00006630 ** then there is no divider cell in apCell[]. Instead, the divider
6631 ** cell consists of the integer key for the right-most cell of
6632 ** the sibling-page assembled above only.
6633 */
drh6f11bef2004-05-13 01:12:56 +00006634 CellInfo info;
drh8b18dd42004-05-12 19:18:15 +00006635 j--;
danielk197730548662009-07-09 05:07:37 +00006636 btreeParseCellPtr(pNew, apCell[j], &info);
drhe5ae5732008-06-15 02:51:47 +00006637 pCell = pTemp;
danielk19774dbaa892009-06-16 16:50:22 +00006638 sz = 4 + putVarint(&pCell[4], info.nKey);
drh8b18dd42004-05-12 19:18:15 +00006639 pTemp = 0;
drh4b70f112004-05-02 21:12:19 +00006640 }else{
6641 pCell -= 4;
danielk19774aeff622007-05-12 09:30:47 +00006642 /* Obscure case for non-leaf-data trees: If the cell at pCell was
drh85b623f2007-12-13 21:54:09 +00006643 ** previously stored on a leaf node, and its reported size was 4
danielk19774aeff622007-05-12 09:30:47 +00006644 ** bytes, then it may actually be smaller than this
danielk197730548662009-07-09 05:07:37 +00006645 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
drh85b623f2007-12-13 21:54:09 +00006646 ** any cell). But it is important to pass the correct size to
danielk19774aeff622007-05-12 09:30:47 +00006647 ** insertCell(), so reparse the cell now.
6648 **
6649 ** Note that this can never happen in an SQLite data file, as all
6650 ** cells are at least 4 bytes. It only happens in b-trees used
6651 ** to evaluate "IN (SELECT ...)" and similar clauses.
6652 */
6653 if( szCell[j]==4 ){
6654 assert(leafCorrection==4);
6655 sz = cellSizePtr(pParent, pCell);
6656 }
drh4b70f112004-05-02 21:12:19 +00006657 }
danielk19776067a9b2009-06-09 09:41:00 +00006658 iOvflSpace += sz;
drhe22e03e2010-08-18 21:19:03 +00006659 assert( sz<=pBt->maxLocal+23 );
drhfcd71b62011-04-05 22:08:24 +00006660 assert( iOvflSpace <= (int)pBt->pageSize );
drh98add2e2009-07-20 17:11:49 +00006661 insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
danielk1977e80463b2004-11-03 03:01:16 +00006662 if( rc!=SQLITE_OK ) goto balance_cleanup;
drhc5053fb2008-11-27 02:22:10 +00006663 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
danielk197785d90ca2008-07-19 14:25:15 +00006664
drh14acc042001-06-10 19:56:58 +00006665 j++;
6666 nxDiv++;
6667 }
6668 }
drh6019e162001-07-02 17:51:45 +00006669 assert( j==nCell );
drh7aa8f852006-03-28 00:24:44 +00006670 assert( nOld>0 );
6671 assert( nNew>0 );
drh4b70f112004-05-02 21:12:19 +00006672 if( (pageFlags & PTF_LEAF)==0 ){
danielk197787c52b52008-07-19 11:49:07 +00006673 u8 *zChild = &apCopy[nOld-1]->aData[8];
6674 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
drh14acc042001-06-10 19:56:58 +00006675 }
6676
danielk197713bd99f2009-06-24 05:40:34 +00006677 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
6678 /* The root page of the b-tree now contains no cells. The only sibling
6679 ** page is the right-child of the parent. Copy the contents of the
6680 ** child page into the parent, decreasing the overall height of the
6681 ** b-tree structure by one. This is described as the "balance-shallower"
6682 ** sub-algorithm in some documentation.
6683 **
6684 ** If this is an auto-vacuum database, the call to copyNodeContent()
6685 ** sets all pointer-map entries corresponding to database image pages
6686 ** for which the pointer is stored within the content being copied.
6687 **
6688 ** The second assert below verifies that the child page is defragmented
6689 ** (it must be, as it was just reconstructed using assemblePage()). This
6690 ** is important if the parent page happens to be page 1 of the database
6691 ** image. */
6692 assert( nNew==1 );
6693 assert( apNew[0]->nFree ==
6694 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
6695 );
drhc314dc72009-07-21 11:52:34 +00006696 copyNodeContent(apNew[0], pParent, &rc);
6697 freePage(apNew[0], &rc);
danielk197713bd99f2009-06-24 05:40:34 +00006698 }else if( ISAUTOVACUUM ){
6699 /* Fix the pointer-map entries for all the cells that were shifted around.
6700 ** There are several different types of pointer-map entries that need to
6701 ** be dealt with by this routine. Some of these have been set already, but
6702 ** many have not. The following is a summary:
6703 **
6704 ** 1) The entries associated with new sibling pages that were not
6705 ** siblings when this function was called. These have already
6706 ** been set. We don't need to worry about old siblings that were
6707 ** moved to the free-list - the freePage() code has taken care
6708 ** of those.
6709 **
6710 ** 2) The pointer-map entries associated with the first overflow
6711 ** page in any overflow chains used by new divider cells. These
6712 ** have also already been taken care of by the insertCell() code.
6713 **
6714 ** 3) If the sibling pages are not leaves, then the child pages of
6715 ** cells stored on the sibling pages may need to be updated.
6716 **
6717 ** 4) If the sibling pages are not internal intkey nodes, then any
6718 ** overflow pages used by these cells may need to be updated
6719 ** (internal intkey nodes never contain pointers to overflow pages).
6720 **
6721 ** 5) If the sibling pages are not leaves, then the pointer-map
6722 ** entries for the right-child pages of each sibling may need
6723 ** to be updated.
6724 **
6725 ** Cases 1 and 2 are dealt with above by other code. The next
6726 ** block deals with cases 3 and 4 and the one after that, case 5. Since
6727 ** setting a pointer map entry is a relatively expensive operation, this
6728 ** code only sets pointer map entries for child or overflow pages that have
6729 ** actually moved between pages. */
danielk19774dbaa892009-06-16 16:50:22 +00006730 MemPage *pNew = apNew[0];
6731 MemPage *pOld = apCopy[0];
6732 int nOverflow = pOld->nOverflow;
6733 int iNextOld = pOld->nCell + nOverflow;
drh2cbd78b2012-02-02 19:37:18 +00006734 int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
danielk19774dbaa892009-06-16 16:50:22 +00006735 j = 0; /* Current 'old' sibling page */
6736 k = 0; /* Current 'new' sibling page */
drhc314dc72009-07-21 11:52:34 +00006737 for(i=0; i<nCell; i++){
danielk19774dbaa892009-06-16 16:50:22 +00006738 int isDivider = 0;
6739 while( i==iNextOld ){
6740 /* Cell i is the cell immediately following the last cell on old
6741 ** sibling page j. If the siblings are not leaf pages of an
6742 ** intkey b-tree, then cell i was a divider cell. */
drhb07028f2011-10-14 21:49:18 +00006743 assert( j+1 < ArraySize(apCopy) );
drhec739302012-08-14 18:43:39 +00006744 assert( j+1 < nOld );
danielk19774dbaa892009-06-16 16:50:22 +00006745 pOld = apCopy[++j];
6746 iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
6747 if( pOld->nOverflow ){
6748 nOverflow = pOld->nOverflow;
drh2cbd78b2012-02-02 19:37:18 +00006749 iOverflow = i + !leafData + pOld->aiOvfl[0];
danielk19774dbaa892009-06-16 16:50:22 +00006750 }
6751 isDivider = !leafData;
6752 }
6753
6754 assert(nOverflow>0 || iOverflow<i );
drh2cbd78b2012-02-02 19:37:18 +00006755 assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
6756 assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
danielk19774dbaa892009-06-16 16:50:22 +00006757 if( i==iOverflow ){
6758 isDivider = 1;
6759 if( (--nOverflow)>0 ){
6760 iOverflow++;
6761 }
6762 }
6763
6764 if( i==cntNew[k] ){
6765 /* Cell i is the cell immediately following the last cell on new
6766 ** sibling page k. If the siblings are not leaf pages of an
6767 ** intkey b-tree, then cell i is a divider cell. */
6768 pNew = apNew[++k];
6769 if( !leafData ) continue;
6770 }
danielk19774dbaa892009-06-16 16:50:22 +00006771 assert( j<nOld );
6772 assert( k<nNew );
6773
6774 /* If the cell was originally divider cell (and is not now) or
6775 ** an overflow cell, or if the cell was located on a different sibling
6776 ** page before the balancing, then the pointer map entries associated
6777 ** with any child or overflow pages need to be updated. */
6778 if( isDivider || pOld->pgno!=pNew->pgno ){
6779 if( !leafCorrection ){
drh98add2e2009-07-20 17:11:49 +00006780 ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006781 }
drh98add2e2009-07-20 17:11:49 +00006782 if( szCell[i]>pNew->minLocal ){
6783 ptrmapPutOvflPtr(pNew, apCell[i], &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006784 }
6785 }
6786 }
6787
6788 if( !leafCorrection ){
drh98add2e2009-07-20 17:11:49 +00006789 for(i=0; i<nNew; i++){
6790 u32 key = get4byte(&apNew[i]->aData[8]);
6791 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
danielk19774dbaa892009-06-16 16:50:22 +00006792 }
6793 }
6794
6795#if 0
6796 /* The ptrmapCheckPages() contains assert() statements that verify that
6797 ** all pointer map pages are set correctly. This is helpful while
6798 ** debugging. This is usually disabled because a corrupt database may
6799 ** cause an assert() statement to fail. */
6800 ptrmapCheckPages(apNew, nNew);
6801 ptrmapCheckPages(&pParent, 1);
6802#endif
6803 }
6804
danielk197771d5d2c2008-09-29 11:49:47 +00006805 assert( pParent->isInit );
danielk1977e5765212009-06-17 11:13:28 +00006806 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
6807 nOld, nNew, nCell));
danielk1977cd581a72009-06-23 15:43:39 +00006808
drh8b2f49b2001-06-08 00:21:52 +00006809 /*
drh14acc042001-06-10 19:56:58 +00006810 ** Cleanup before returning.
drh8b2f49b2001-06-08 00:21:52 +00006811 */
drh14acc042001-06-10 19:56:58 +00006812balance_cleanup:
drhfacf0302008-06-17 15:12:00 +00006813 sqlite3ScratchFree(apCell);
drh8b2f49b2001-06-08 00:21:52 +00006814 for(i=0; i<nOld; i++){
drh91025292004-05-03 19:49:32 +00006815 releasePage(apOld[i]);
drh8b2f49b2001-06-08 00:21:52 +00006816 }
drh14acc042001-06-10 19:56:58 +00006817 for(i=0; i<nNew; i++){
drh91025292004-05-03 19:49:32 +00006818 releasePage(apNew[i]);
drh8b2f49b2001-06-08 00:21:52 +00006819 }
danielk1977eaa06f62008-09-18 17:34:44 +00006820
drh8b2f49b2001-06-08 00:21:52 +00006821 return rc;
6822}
mistachkine7c54162012-10-02 22:54:27 +00006823#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
6824#pragma optimize("", on)
6825#endif
drh8b2f49b2001-06-08 00:21:52 +00006826
drh43605152004-05-29 21:46:49 +00006827
6828/*
danielk1977a50d9aa2009-06-08 14:49:45 +00006829** This function is called when the root page of a b-tree structure is
6830** overfull (has one or more overflow pages).
drh43605152004-05-29 21:46:49 +00006831**
danielk1977a50d9aa2009-06-08 14:49:45 +00006832** A new child page is allocated and the contents of the current root
6833** page, including overflow cells, are copied into the child. The root
6834** page is then overwritten to make it an empty page with the right-child
6835** pointer pointing to the new page.
6836**
6837** Before returning, all pointer-map entries corresponding to pages
6838** that the new child-page now contains pointers to are updated. The
6839** entry corresponding to the new right-child pointer of the root
6840** page is also updated.
6841**
6842** If successful, *ppChild is set to contain a reference to the child
6843** page and SQLITE_OK is returned. In this case the caller is required
6844** to call releasePage() on *ppChild exactly once. If an error occurs,
6845** an error code is returned and *ppChild is set to 0.
drh43605152004-05-29 21:46:49 +00006846*/
danielk1977a50d9aa2009-06-08 14:49:45 +00006847static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
6848 int rc; /* Return value from subprocedures */
6849 MemPage *pChild = 0; /* Pointer to a new child page */
shane5eff7cf2009-08-10 03:57:58 +00006850 Pgno pgnoChild = 0; /* Page number of the new child page */
danielk1977a50d9aa2009-06-08 14:49:45 +00006851 BtShared *pBt = pRoot->pBt; /* The BTree */
drh43605152004-05-29 21:46:49 +00006852
danielk1977a50d9aa2009-06-08 14:49:45 +00006853 assert( pRoot->nOverflow>0 );
drh1fee73e2007-08-29 04:00:57 +00006854 assert( sqlite3_mutex_held(pBt->mutex) );
danielk1977bc2ca9e2008-11-13 14:28:28 +00006855
danielk1977a50d9aa2009-06-08 14:49:45 +00006856 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
6857 ** page that will become the new right-child of pPage. Copy the contents
6858 ** of the node stored on pRoot into the new child page.
6859 */
drh98add2e2009-07-20 17:11:49 +00006860 rc = sqlite3PagerWrite(pRoot->pDbPage);
6861 if( rc==SQLITE_OK ){
6862 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
drhc314dc72009-07-21 11:52:34 +00006863 copyNodeContent(pRoot, pChild, &rc);
6864 if( ISAUTOVACUUM ){
6865 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
drh98add2e2009-07-20 17:11:49 +00006866 }
6867 }
6868 if( rc ){
danielk1977a50d9aa2009-06-08 14:49:45 +00006869 *ppChild = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00006870 releasePage(pChild);
danielk1977a50d9aa2009-06-08 14:49:45 +00006871 return rc;
danielk197771d5d2c2008-09-29 11:49:47 +00006872 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006873 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
6874 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
6875 assert( pChild->nCell==pRoot->nCell );
danielk197771d5d2c2008-09-29 11:49:47 +00006876
danielk1977a50d9aa2009-06-08 14:49:45 +00006877 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
6878
6879 /* Copy the overflow cells from pRoot to pChild */
drh2cbd78b2012-02-02 19:37:18 +00006880 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
6881 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
6882 memcpy(pChild->apOvfl, pRoot->apOvfl,
6883 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
danielk1977a50d9aa2009-06-08 14:49:45 +00006884 pChild->nOverflow = pRoot->nOverflow;
danielk1977a50d9aa2009-06-08 14:49:45 +00006885
6886 /* Zero the contents of pRoot. Then install pChild as the right-child. */
6887 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
6888 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
6889
6890 *ppChild = pChild;
6891 return SQLITE_OK;
drh43605152004-05-29 21:46:49 +00006892}
6893
6894/*
danielk197771d5d2c2008-09-29 11:49:47 +00006895** The page that pCur currently points to has just been modified in
6896** some way. This function figures out if this modification means the
6897** tree needs to be balanced, and if so calls the appropriate balancing
danielk1977a50d9aa2009-06-08 14:49:45 +00006898** routine. Balancing routines are:
6899**
6900** balance_quick()
danielk1977a50d9aa2009-06-08 14:49:45 +00006901** balance_deeper()
6902** balance_nonroot()
drh43605152004-05-29 21:46:49 +00006903*/
danielk1977a50d9aa2009-06-08 14:49:45 +00006904static int balance(BtCursor *pCur){
drh43605152004-05-29 21:46:49 +00006905 int rc = SQLITE_OK;
danielk1977a50d9aa2009-06-08 14:49:45 +00006906 const int nMin = pCur->pBt->usableSize * 2 / 3;
6907 u8 aBalanceQuickSpace[13];
6908 u8 *pFree = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00006909
shane75ac1de2009-06-09 18:58:52 +00006910 TESTONLY( int balance_quick_called = 0 );
6911 TESTONLY( int balance_deeper_called = 0 );
danielk1977a50d9aa2009-06-08 14:49:45 +00006912
6913 do {
6914 int iPage = pCur->iPage;
6915 MemPage *pPage = pCur->apPage[iPage];
6916
6917 if( iPage==0 ){
6918 if( pPage->nOverflow ){
6919 /* The root page of the b-tree is overfull. In this case call the
6920 ** balance_deeper() function to create a new child for the root-page
6921 ** and copy the current contents of the root-page to it. The
6922 ** next iteration of the do-loop will balance the child page.
6923 */
6924 assert( (balance_deeper_called++)==0 );
6925 rc = balance_deeper(pPage, &pCur->apPage[1]);
6926 if( rc==SQLITE_OK ){
6927 pCur->iPage = 1;
6928 pCur->aiIdx[0] = 0;
6929 pCur->aiIdx[1] = 0;
6930 assert( pCur->apPage[1]->nOverflow );
6931 }
danielk1977a50d9aa2009-06-08 14:49:45 +00006932 }else{
danielk1977a50d9aa2009-06-08 14:49:45 +00006933 break;
6934 }
6935 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
6936 break;
6937 }else{
6938 MemPage * const pParent = pCur->apPage[iPage-1];
6939 int const iIdx = pCur->aiIdx[iPage-1];
6940
6941 rc = sqlite3PagerWrite(pParent->pDbPage);
6942 if( rc==SQLITE_OK ){
6943#ifndef SQLITE_OMIT_QUICKBALANCE
6944 if( pPage->hasData
6945 && pPage->nOverflow==1
drh2cbd78b2012-02-02 19:37:18 +00006946 && pPage->aiOvfl[0]==pPage->nCell
danielk1977a50d9aa2009-06-08 14:49:45 +00006947 && pParent->pgno!=1
6948 && pParent->nCell==iIdx
6949 ){
6950 /* Call balance_quick() to create a new sibling of pPage on which
6951 ** to store the overflow cell. balance_quick() inserts a new cell
6952 ** into pParent, which may cause pParent overflow. If this
peter.d.reid60ec9142014-09-06 16:39:46 +00006953 ** happens, the next iteration of the do-loop will balance pParent
danielk1977a50d9aa2009-06-08 14:49:45 +00006954 ** use either balance_nonroot() or balance_deeper(). Until this
6955 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
6956 ** buffer.
6957 **
6958 ** The purpose of the following assert() is to check that only a
6959 ** single call to balance_quick() is made for each call to this
6960 ** function. If this were not verified, a subtle bug involving reuse
6961 ** of the aBalanceQuickSpace[] might sneak in.
6962 */
6963 assert( (balance_quick_called++)==0 );
6964 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
6965 }else
6966#endif
6967 {
6968 /* In this case, call balance_nonroot() to redistribute cells
6969 ** between pPage and up to 2 of its sibling pages. This involves
6970 ** modifying the contents of pParent, which may cause pParent to
6971 ** become overfull or underfull. The next iteration of the do-loop
6972 ** will balance the parent page to correct this.
6973 **
6974 ** If the parent page becomes overfull, the overflow cell or cells
6975 ** are stored in the pSpace buffer allocated immediately below.
6976 ** A subsequent iteration of the do-loop will deal with this by
6977 ** calling balance_nonroot() (balance_deeper() may be called first,
6978 ** but it doesn't deal with overflow cells - just moves them to a
6979 ** different page). Once this subsequent call to balance_nonroot()
6980 ** has completed, it is safe to release the pSpace buffer used by
6981 ** the previous call, as the overflow cell data will have been
6982 ** copied either into the body of a database page or into the new
6983 ** pSpace buffer passed to the latter call to balance_nonroot().
6984 */
6985 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
dan428c2182012-08-06 18:50:11 +00006986 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
danielk1977a50d9aa2009-06-08 14:49:45 +00006987 if( pFree ){
6988 /* If pFree is not NULL, it points to the pSpace buffer used
6989 ** by a previous call to balance_nonroot(). Its contents are
6990 ** now stored either on real database pages or within the
6991 ** new pSpace buffer, so it may be safely freed here. */
6992 sqlite3PageFree(pFree);
6993 }
6994
danielk19774dbaa892009-06-16 16:50:22 +00006995 /* The pSpace buffer will be freed after the next call to
6996 ** balance_nonroot(), or just before this function returns, whichever
6997 ** comes first. */
danielk1977a50d9aa2009-06-08 14:49:45 +00006998 pFree = pSpace;
danielk1977a50d9aa2009-06-08 14:49:45 +00006999 }
7000 }
7001
7002 pPage->nOverflow = 0;
7003
7004 /* The next iteration of the do-loop balances the parent page. */
7005 releasePage(pPage);
7006 pCur->iPage--;
drh43605152004-05-29 21:46:49 +00007007 }
danielk1977a50d9aa2009-06-08 14:49:45 +00007008 }while( rc==SQLITE_OK );
7009
7010 if( pFree ){
7011 sqlite3PageFree(pFree);
drh43605152004-05-29 21:46:49 +00007012 }
7013 return rc;
7014}
7015
drhf74b8d92002-09-01 23:20:45 +00007016
7017/*
drh3b7511c2001-05-26 13:15:44 +00007018** Insert a new record into the BTree. The key is given by (pKey,nKey)
7019** and the data is given by (pData,nData). The cursor is used only to
drh91025292004-05-03 19:49:32 +00007020** define what table the record should be inserted into. The cursor
drh4b70f112004-05-02 21:12:19 +00007021** is left pointing at a random location.
7022**
7023** For an INTKEY table, only the nKey value of the key is used. pKey is
7024** ignored. For a ZERODATA table, the pData and nData are both ignored.
danielk1977de630352009-05-04 11:42:29 +00007025**
7026** If the seekResult parameter is non-zero, then a successful call to
danielk19773509a652009-07-06 18:56:13 +00007027** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
danielk1977de630352009-05-04 11:42:29 +00007028** been performed. seekResult is the search result returned (a negative
7029** number if pCur points at an entry that is smaller than (pKey, nKey), or
peter.d.reid60ec9142014-09-06 16:39:46 +00007030** a positive value if pCur points at an entry that is larger than
danielk1977de630352009-05-04 11:42:29 +00007031** (pKey, nKey)).
7032**
drh3e9ca092009-09-08 01:14:48 +00007033** If the seekResult parameter is non-zero, then the caller guarantees that
7034** cursor pCur is pointing at the existing copy of a row that is to be
7035** overwritten. If the seekResult parameter is 0, then cursor pCur may
7036** point to any entry or to no entry at all and so this function has to seek
danielk1977de630352009-05-04 11:42:29 +00007037** the cursor before the new key can be inserted.
drh3b7511c2001-05-26 13:15:44 +00007038*/
drh3aac2dd2004-04-26 14:10:20 +00007039int sqlite3BtreeInsert(
drh5c4d9702001-08-20 00:33:58 +00007040 BtCursor *pCur, /* Insert data into the table of this cursor */
drh4a1c3802004-05-12 15:15:47 +00007041 const void *pKey, i64 nKey, /* The key of the new record */
drhe4d90812007-03-29 05:51:49 +00007042 const void *pData, int nData, /* The data of the new record */
drhb026e052007-05-02 01:34:31 +00007043 int nZero, /* Number of extra 0 bytes to append to data */
danielk1977de630352009-05-04 11:42:29 +00007044 int appendBias, /* True if this is likely an append */
danielk19773509a652009-07-06 18:56:13 +00007045 int seekResult /* Result of prior MovetoUnpacked() call */
drh3b7511c2001-05-26 13:15:44 +00007046){
drh3b7511c2001-05-26 13:15:44 +00007047 int rc;
drh3e9ca092009-09-08 01:14:48 +00007048 int loc = seekResult; /* -1: before desired location +1: after */
drh1d452e12009-11-01 19:26:59 +00007049 int szNew = 0;
danielk197771d5d2c2008-09-29 11:49:47 +00007050 int idx;
drh3b7511c2001-05-26 13:15:44 +00007051 MemPage *pPage;
drhd677b3d2007-08-20 22:48:41 +00007052 Btree *p = pCur->pBtree;
7053 BtShared *pBt = p->pBt;
drha34b6762004-05-07 13:30:42 +00007054 unsigned char *oldCell;
drh2e38c322004-09-03 18:38:44 +00007055 unsigned char *newCell = 0;
drh3b7511c2001-05-26 13:15:44 +00007056
drh98add2e2009-07-20 17:11:49 +00007057 if( pCur->eState==CURSOR_FAULT ){
7058 assert( pCur->skipNext!=SQLITE_OK );
7059 return pCur->skipNext;
7060 }
7061
drh1fee73e2007-08-29 04:00:57 +00007062 assert( cursorHoldsMutex(pCur) );
drh036dbec2014-03-11 23:40:44 +00007063 assert( (pCur->curFlags & BTCF_WriteFlag)!=0 && pBt->inTransaction==TRANS_WRITE
drhc9166342012-01-05 23:32:06 +00007064 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk197796d48e92009-06-29 06:00:37 +00007065 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
7066
danielk197731d31b82009-07-13 13:18:07 +00007067 /* Assert that the caller has been consistent. If this cursor was opened
7068 ** expecting an index b-tree, then the caller should be inserting blob
7069 ** keys with no associated data. If the cursor was opened expecting an
7070 ** intkey table, the caller should be inserting integer keys with a
7071 ** blob of associated data. */
7072 assert( (pKey==0)==(pCur->pKeyInfo==0) );
7073
danielk19779c3acf32009-05-02 07:36:49 +00007074 /* Save the positions of any other cursors open on this table.
7075 **
danielk19773509a652009-07-06 18:56:13 +00007076 ** In some cases, the call to btreeMoveto() below is a no-op. For
danielk19779c3acf32009-05-02 07:36:49 +00007077 ** example, when inserting data into a table with auto-generated integer
7078 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
7079 ** integer key to use. It then calls this function to actually insert the
danielk19773509a652009-07-06 18:56:13 +00007080 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
danielk19779c3acf32009-05-02 07:36:49 +00007081 ** that the cursor is already where it needs to be and returns without
7082 ** doing any work. To avoid thwarting these optimizations, it is important
7083 ** not to clear the cursor here.
7084 */
drh4c301aa2009-07-15 17:25:45 +00007085 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
7086 if( rc ) return rc;
drhd60f4f42012-03-23 14:23:52 +00007087
drhd60f4f42012-03-23 14:23:52 +00007088 if( pCur->pKeyInfo==0 ){
drhe0670b62014-02-12 21:31:12 +00007089 /* If this is an insert into a table b-tree, invalidate any incrblob
7090 ** cursors open on the row being replaced */
drhd60f4f42012-03-23 14:23:52 +00007091 invalidateIncrblobCursors(p, nKey, 0);
drhe0670b62014-02-12 21:31:12 +00007092
7093 /* If the cursor is currently on the last row and we are appending a
7094 ** new row onto the end, set the "loc" to avoid an unnecessary btreeMoveto()
7095 ** call */
drh036dbec2014-03-11 23:40:44 +00007096 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0 && pCur->info.nKey==nKey-1 ){
drhe0670b62014-02-12 21:31:12 +00007097 loc = -1;
7098 }
drhd60f4f42012-03-23 14:23:52 +00007099 }
7100
drh4c301aa2009-07-15 17:25:45 +00007101 if( !loc ){
7102 rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
7103 if( rc ) return rc;
danielk1977da184232006-01-05 11:34:32 +00007104 }
danielk1977b980d2212009-06-22 18:03:51 +00007105 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
danielk1977da184232006-01-05 11:34:32 +00007106
danielk197771d5d2c2008-09-29 11:49:47 +00007107 pPage = pCur->apPage[pCur->iPage];
drh4a1c3802004-05-12 15:15:47 +00007108 assert( pPage->intKey || nKey>=0 );
drh44845222008-07-17 18:39:57 +00007109 assert( pPage->leaf || !pPage->intKey );
danielk19778f880a82009-07-13 09:41:45 +00007110
drh3a4c1412004-05-09 20:40:11 +00007111 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
7112 pCur->pgnoRoot, nKey, nData, pPage->pgno,
7113 loc==0 ? "overwrite" : "new entry"));
danielk197771d5d2c2008-09-29 11:49:47 +00007114 assert( pPage->isInit );
danielk197752ae7242008-03-25 14:24:56 +00007115 allocateTempSpace(pBt);
7116 newCell = pBt->pTmpSpace;
drh2e38c322004-09-03 18:38:44 +00007117 if( newCell==0 ) return SQLITE_NOMEM;
drhb026e052007-05-02 01:34:31 +00007118 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
drh2e38c322004-09-03 18:38:44 +00007119 if( rc ) goto end_insert;
drh43605152004-05-29 21:46:49 +00007120 assert( szNew==cellSizePtr(pPage, newCell) );
drhfcd71b62011-04-05 22:08:24 +00007121 assert( szNew <= MX_CELL_SIZE(pBt) );
danielk197771d5d2c2008-09-29 11:49:47 +00007122 idx = pCur->aiIdx[pCur->iPage];
danielk1977b980d2212009-06-22 18:03:51 +00007123 if( loc==0 ){
drha9121e42008-02-19 14:59:35 +00007124 u16 szOld;
danielk197771d5d2c2008-09-29 11:49:47 +00007125 assert( idx<pPage->nCell );
danielk19776e465eb2007-08-21 13:11:00 +00007126 rc = sqlite3PagerWrite(pPage->pDbPage);
7127 if( rc ){
7128 goto end_insert;
7129 }
danielk197771d5d2c2008-09-29 11:49:47 +00007130 oldCell = findCell(pPage, idx);
drh4b70f112004-05-02 21:12:19 +00007131 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00007132 memcpy(newCell, oldCell, 4);
drh4b70f112004-05-02 21:12:19 +00007133 }
drh43605152004-05-29 21:46:49 +00007134 szOld = cellSizePtr(pPage, oldCell);
drh4b70f112004-05-02 21:12:19 +00007135 rc = clearCell(pPage, oldCell);
drh98add2e2009-07-20 17:11:49 +00007136 dropCell(pPage, idx, szOld, &rc);
drh2e38c322004-09-03 18:38:44 +00007137 if( rc ) goto end_insert;
drh7c717f72001-06-24 20:39:41 +00007138 }else if( loc<0 && pPage->nCell>0 ){
drh4b70f112004-05-02 21:12:19 +00007139 assert( pPage->leaf );
danielk197771d5d2c2008-09-29 11:49:47 +00007140 idx = ++pCur->aiIdx[pCur->iPage];
drh14acc042001-06-10 19:56:58 +00007141 }else{
drh4b70f112004-05-02 21:12:19 +00007142 assert( pPage->leaf );
drh3b7511c2001-05-26 13:15:44 +00007143 }
drh98add2e2009-07-20 17:11:49 +00007144 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
danielk19773f632d52009-05-02 10:03:09 +00007145 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
drh9bf9e9c2008-12-05 20:01:43 +00007146
mistachkin48864df2013-03-21 21:20:32 +00007147 /* If no error has occurred and pPage has an overflow cell, call balance()
danielk1977a50d9aa2009-06-08 14:49:45 +00007148 ** to redistribute the cells within the tree. Since balance() may move
drh036dbec2014-03-11 23:40:44 +00007149 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
danielk1977a50d9aa2009-06-08 14:49:45 +00007150 ** variables.
danielk19773f632d52009-05-02 10:03:09 +00007151 **
danielk1977a50d9aa2009-06-08 14:49:45 +00007152 ** Previous versions of SQLite called moveToRoot() to move the cursor
7153 ** back to the root page as balance() used to invalidate the contents
danielk197754109bb2009-06-23 11:22:29 +00007154 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
7155 ** set the cursor state to "invalid". This makes common insert operations
7156 ** slightly faster.
danielk19773f632d52009-05-02 10:03:09 +00007157 **
danielk1977a50d9aa2009-06-08 14:49:45 +00007158 ** There is a subtle but important optimization here too. When inserting
7159 ** multiple records into an intkey b-tree using a single cursor (as can
7160 ** happen while processing an "INSERT INTO ... SELECT" statement), it
7161 ** is advantageous to leave the cursor pointing to the last entry in
7162 ** the b-tree if possible. If the cursor is left pointing to the last
7163 ** entry in the table, and the next row inserted has an integer key
7164 ** larger than the largest existing key, it is possible to insert the
7165 ** row without seeking the cursor. This can be a big performance boost.
danielk19773f632d52009-05-02 10:03:09 +00007166 */
danielk1977a50d9aa2009-06-08 14:49:45 +00007167 pCur->info.nSize = 0;
danielk1977a50d9aa2009-06-08 14:49:45 +00007168 if( rc==SQLITE_OK && pPage->nOverflow ){
drh036dbec2014-03-11 23:40:44 +00007169 pCur->curFlags &= ~(BTCF_ValidNKey);
danielk1977a50d9aa2009-06-08 14:49:45 +00007170 rc = balance(pCur);
7171
7172 /* Must make sure nOverflow is reset to zero even if the balance()
danielk197754109bb2009-06-23 11:22:29 +00007173 ** fails. Internal data structure corruption will result otherwise.
7174 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
7175 ** from trying to save the current position of the cursor. */
danielk1977a50d9aa2009-06-08 14:49:45 +00007176 pCur->apPage[pCur->iPage]->nOverflow = 0;
danielk197754109bb2009-06-23 11:22:29 +00007177 pCur->eState = CURSOR_INVALID;
danielk19773f632d52009-05-02 10:03:09 +00007178 }
danielk1977a50d9aa2009-06-08 14:49:45 +00007179 assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
drh9bf9e9c2008-12-05 20:01:43 +00007180
drh2e38c322004-09-03 18:38:44 +00007181end_insert:
drh5e2f8b92001-05-28 00:41:15 +00007182 return rc;
7183}
7184
7185/*
drh4b70f112004-05-02 21:12:19 +00007186** Delete the entry that the cursor is pointing to. The cursor
peter.d.reid60ec9142014-09-06 16:39:46 +00007187** is left pointing at an arbitrary location.
drh3b7511c2001-05-26 13:15:44 +00007188*/
drh3aac2dd2004-04-26 14:10:20 +00007189int sqlite3BtreeDelete(BtCursor *pCur){
drhd677b3d2007-08-20 22:48:41 +00007190 Btree *p = pCur->pBtree;
danielk19774dbaa892009-06-16 16:50:22 +00007191 BtShared *pBt = p->pBt;
7192 int rc; /* Return code */
7193 MemPage *pPage; /* Page to delete cell from */
7194 unsigned char *pCell; /* Pointer to cell to delete */
7195 int iCellIdx; /* Index of cell to delete */
7196 int iCellDepth; /* Depth of node containing pCell */
drh8b2f49b2001-06-08 00:21:52 +00007197
drh1fee73e2007-08-29 04:00:57 +00007198 assert( cursorHoldsMutex(pCur) );
drh64022502009-01-09 14:11:04 +00007199 assert( pBt->inTransaction==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00007200 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
drh036dbec2014-03-11 23:40:44 +00007201 assert( pCur->curFlags & BTCF_WriteFlag );
danielk197796d48e92009-06-29 06:00:37 +00007202 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
7203 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
7204
danielk19774dbaa892009-06-16 16:50:22 +00007205 if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
7206 || NEVER(pCur->eState!=CURSOR_VALID)
7207 ){
7208 return SQLITE_ERROR; /* Something has gone awry. */
drhf74b8d92002-09-01 23:20:45 +00007209 }
danielk1977da184232006-01-05 11:34:32 +00007210
danielk19774dbaa892009-06-16 16:50:22 +00007211 iCellDepth = pCur->iPage;
7212 iCellIdx = pCur->aiIdx[iCellDepth];
7213 pPage = pCur->apPage[iCellDepth];
7214 pCell = findCell(pPage, iCellIdx);
7215
7216 /* If the page containing the entry to delete is not a leaf page, move
7217 ** the cursor to the largest entry in the tree that is smaller than
7218 ** the entry being deleted. This cell will replace the cell being deleted
7219 ** from the internal node. The 'previous' entry is used for this instead
7220 ** of the 'next' entry, as the previous entry is always a part of the
7221 ** sub-tree headed by the child page of the cell being deleted. This makes
7222 ** balancing the tree following the delete operation easier. */
7223 if( !pPage->leaf ){
drhe39a7322014-02-03 14:04:11 +00007224 int notUsed = 0;
drh4c301aa2009-07-15 17:25:45 +00007225 rc = sqlite3BtreePrevious(pCur, &notUsed);
7226 if( rc ) return rc;
danielk19774dbaa892009-06-16 16:50:22 +00007227 }
7228
7229 /* Save the positions of any other cursors open on this table before
7230 ** making any modifications. Make the page containing the entry to be
7231 ** deleted writable. Then free any overflow pages associated with the
drha4ec1d42009-07-11 13:13:11 +00007232 ** entry and finally remove the cell itself from within the page.
7233 */
7234 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
7235 if( rc ) return rc;
drhd60f4f42012-03-23 14:23:52 +00007236
7237 /* If this is a delete operation to remove a row from a table b-tree,
7238 ** invalidate any incrblob cursors open on the row being deleted. */
7239 if( pCur->pKeyInfo==0 ){
7240 invalidateIncrblobCursors(p, pCur->info.nKey, 0);
7241 }
7242
drha4ec1d42009-07-11 13:13:11 +00007243 rc = sqlite3PagerWrite(pPage->pDbPage);
7244 if( rc ) return rc;
7245 rc = clearCell(pPage, pCell);
drh98add2e2009-07-20 17:11:49 +00007246 dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
drha4ec1d42009-07-11 13:13:11 +00007247 if( rc ) return rc;
danielk1977e6efa742004-11-10 11:55:10 +00007248
danielk19774dbaa892009-06-16 16:50:22 +00007249 /* If the cell deleted was not located on a leaf page, then the cursor
7250 ** is currently pointing to the largest entry in the sub-tree headed
7251 ** by the child-page of the cell that was just deleted from an internal
7252 ** node. The cell from the leaf node needs to be moved to the internal
7253 ** node to replace the deleted cell. */
drh4b70f112004-05-02 21:12:19 +00007254 if( !pPage->leaf ){
danielk19774dbaa892009-06-16 16:50:22 +00007255 MemPage *pLeaf = pCur->apPage[pCur->iPage];
7256 int nCell;
7257 Pgno n = pCur->apPage[iCellDepth+1]->pgno;
7258 unsigned char *pTmp;
danielk1977e6efa742004-11-10 11:55:10 +00007259
danielk19774dbaa892009-06-16 16:50:22 +00007260 pCell = findCell(pLeaf, pLeaf->nCell-1);
7261 nCell = cellSizePtr(pLeaf, pCell);
drhfcd71b62011-04-05 22:08:24 +00007262 assert( MX_CELL_SIZE(pBt) >= nCell );
danielk197771d5d2c2008-09-29 11:49:47 +00007263
danielk19774dbaa892009-06-16 16:50:22 +00007264 allocateTempSpace(pBt);
7265 pTmp = pBt->pTmpSpace;
danielk19772f78fc62008-09-30 09:31:45 +00007266
drha4ec1d42009-07-11 13:13:11 +00007267 rc = sqlite3PagerWrite(pLeaf->pDbPage);
drh98add2e2009-07-20 17:11:49 +00007268 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
7269 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
drha4ec1d42009-07-11 13:13:11 +00007270 if( rc ) return rc;
drh5e2f8b92001-05-28 00:41:15 +00007271 }
danielk19774dbaa892009-06-16 16:50:22 +00007272
7273 /* Balance the tree. If the entry deleted was located on a leaf page,
7274 ** then the cursor still points to that page. In this case the first
7275 ** call to balance() repairs the tree, and the if(...) condition is
7276 ** never true.
7277 **
7278 ** Otherwise, if the entry deleted was on an internal node page, then
7279 ** pCur is pointing to the leaf page from which a cell was removed to
7280 ** replace the cell deleted from the internal node. This is slightly
7281 ** tricky as the leaf node may be underfull, and the internal node may
7282 ** be either under or overfull. In this case run the balancing algorithm
7283 ** on the leaf node first. If the balance proceeds far enough up the
7284 ** tree that we can be sure that any problem in the internal node has
7285 ** been corrected, so be it. Otherwise, after balancing the leaf node,
7286 ** walk the cursor up the tree to the internal node and balance it as
7287 ** well. */
7288 rc = balance(pCur);
7289 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
7290 while( pCur->iPage>iCellDepth ){
7291 releasePage(pCur->apPage[pCur->iPage--]);
7292 }
7293 rc = balance(pCur);
7294 }
7295
danielk19776b456a22005-03-21 04:04:02 +00007296 if( rc==SQLITE_OK ){
7297 moveToRoot(pCur);
7298 }
drh5e2f8b92001-05-28 00:41:15 +00007299 return rc;
drh3b7511c2001-05-26 13:15:44 +00007300}
drh8b2f49b2001-06-08 00:21:52 +00007301
7302/*
drhc6b52df2002-01-04 03:09:29 +00007303** Create a new BTree table. Write into *piTable the page
7304** number for the root page of the new table.
7305**
drhab01f612004-05-22 02:55:23 +00007306** The type of type is determined by the flags parameter. Only the
7307** following values of flags are currently in use. Other values for
7308** flags might not work:
7309**
7310** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
7311** BTREE_ZERODATA Used for SQL indices
drh8b2f49b2001-06-08 00:21:52 +00007312*/
drhd4187c72010-08-30 22:15:45 +00007313static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
danielk1977aef0bf62005-12-30 16:28:01 +00007314 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00007315 MemPage *pRoot;
7316 Pgno pgnoRoot;
7317 int rc;
drhd4187c72010-08-30 22:15:45 +00007318 int ptfFlags; /* Page-type flage for the root page of new table */
drhd677b3d2007-08-20 22:48:41 +00007319
drh1fee73e2007-08-29 04:00:57 +00007320 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00007321 assert( pBt->inTransaction==TRANS_WRITE );
drhc9166342012-01-05 23:32:06 +00007322 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
danielk1977e6efa742004-11-10 11:55:10 +00007323
danielk1977003ba062004-11-04 02:57:33 +00007324#ifdef SQLITE_OMIT_AUTOVACUUM
drh4f0c5872007-03-26 22:05:01 +00007325 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
drhd677b3d2007-08-20 22:48:41 +00007326 if( rc ){
7327 return rc;
7328 }
danielk1977003ba062004-11-04 02:57:33 +00007329#else
danielk1977687566d2004-11-02 12:56:41 +00007330 if( pBt->autoVacuum ){
danielk1977003ba062004-11-04 02:57:33 +00007331 Pgno pgnoMove; /* Move a page here to make room for the root-page */
7332 MemPage *pPageMove; /* The page to move to. */
7333
danielk197720713f32007-05-03 11:43:33 +00007334 /* Creating a new table may probably require moving an existing database
7335 ** to make room for the new tables root page. In case this page turns
7336 ** out to be an overflow page, delete all overflow page-map caches
7337 ** held by open cursors.
7338 */
danielk197792d4d7a2007-05-04 12:05:56 +00007339 invalidateAllOverflowCache(pBt);
danielk197720713f32007-05-03 11:43:33 +00007340
danielk1977003ba062004-11-04 02:57:33 +00007341 /* Read the value of meta[3] from the database to determine where the
7342 ** root page of the new table should go. meta[3] is the largest root-page
7343 ** created so far, so the new root-page is (meta[3]+1).
7344 */
danielk1977602b4662009-07-02 07:47:33 +00007345 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
danielk1977003ba062004-11-04 02:57:33 +00007346 pgnoRoot++;
7347
danielk1977599fcba2004-11-08 07:13:13 +00007348 /* The new root-page may not be allocated on a pointer-map page, or the
7349 ** PENDING_BYTE page.
7350 */
drh72190432008-01-31 14:54:43 +00007351 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
danielk1977599fcba2004-11-08 07:13:13 +00007352 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
danielk1977003ba062004-11-04 02:57:33 +00007353 pgnoRoot++;
7354 }
7355 assert( pgnoRoot>=3 );
7356
7357 /* Allocate a page. The page that currently resides at pgnoRoot will
7358 ** be moved to the allocated page (unless the allocated page happens
7359 ** to reside at pgnoRoot).
7360 */
dan51f0b6d2013-02-22 20:16:34 +00007361 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
danielk1977003ba062004-11-04 02:57:33 +00007362 if( rc!=SQLITE_OK ){
danielk1977687566d2004-11-02 12:56:41 +00007363 return rc;
7364 }
danielk1977003ba062004-11-04 02:57:33 +00007365
7366 if( pgnoMove!=pgnoRoot ){
danielk1977f35843b2007-04-07 15:03:17 +00007367 /* pgnoRoot is the page that will be used for the root-page of
7368 ** the new table (assuming an error did not occur). But we were
7369 ** allocated pgnoMove. If required (i.e. if it was not allocated
7370 ** by extending the file), the current page at position pgnoMove
7371 ** is already journaled.
7372 */
drheeb844a2009-08-08 18:01:07 +00007373 u8 eType = 0;
7374 Pgno iPtrPage = 0;
danielk1977003ba062004-11-04 02:57:33 +00007375
danf7679ad2013-04-03 11:38:36 +00007376 /* Save the positions of any open cursors. This is required in
7377 ** case they are holding a reference to an xFetch reference
7378 ** corresponding to page pgnoRoot. */
7379 rc = saveAllCursors(pBt, 0, 0);
danielk1977003ba062004-11-04 02:57:33 +00007380 releasePage(pPageMove);
danf7679ad2013-04-03 11:38:36 +00007381 if( rc!=SQLITE_OK ){
7382 return rc;
7383 }
danielk1977f35843b2007-04-07 15:03:17 +00007384
7385 /* Move the page currently at pgnoRoot to pgnoMove. */
drhb00fc3b2013-08-21 23:42:32 +00007386 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00007387 if( rc!=SQLITE_OK ){
7388 return rc;
7389 }
7390 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
drh27731d72009-06-22 12:05:10 +00007391 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
7392 rc = SQLITE_CORRUPT_BKPT;
7393 }
7394 if( rc!=SQLITE_OK ){
danielk1977003ba062004-11-04 02:57:33 +00007395 releasePage(pRoot);
7396 return rc;
7397 }
drhccae6022005-02-26 17:31:26 +00007398 assert( eType!=PTRMAP_ROOTPAGE );
7399 assert( eType!=PTRMAP_FREEPAGE );
danielk19774c999992008-07-16 18:17:55 +00007400 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
danielk1977003ba062004-11-04 02:57:33 +00007401 releasePage(pRoot);
danielk1977f35843b2007-04-07 15:03:17 +00007402
7403 /* Obtain the page at pgnoRoot */
danielk1977003ba062004-11-04 02:57:33 +00007404 if( rc!=SQLITE_OK ){
7405 return rc;
7406 }
drhb00fc3b2013-08-21 23:42:32 +00007407 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
danielk1977003ba062004-11-04 02:57:33 +00007408 if( rc!=SQLITE_OK ){
7409 return rc;
7410 }
danielk19773b8a05f2007-03-19 17:44:26 +00007411 rc = sqlite3PagerWrite(pRoot->pDbPage);
danielk1977003ba062004-11-04 02:57:33 +00007412 if( rc!=SQLITE_OK ){
7413 releasePage(pRoot);
7414 return rc;
7415 }
7416 }else{
7417 pRoot = pPageMove;
7418 }
7419
danielk197742741be2005-01-08 12:42:39 +00007420 /* Update the pointer-map and meta-data with the new root-page number. */
drh98add2e2009-07-20 17:11:49 +00007421 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
danielk1977003ba062004-11-04 02:57:33 +00007422 if( rc ){
7423 releasePage(pRoot);
7424 return rc;
7425 }
drhbf592832010-03-30 15:51:12 +00007426
7427 /* When the new root page was allocated, page 1 was made writable in
7428 ** order either to increase the database filesize, or to decrement the
7429 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
7430 */
7431 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
danielk1977aef0bf62005-12-30 16:28:01 +00007432 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
drhbf592832010-03-30 15:51:12 +00007433 if( NEVER(rc) ){
danielk1977003ba062004-11-04 02:57:33 +00007434 releasePage(pRoot);
7435 return rc;
7436 }
danielk197742741be2005-01-08 12:42:39 +00007437
danielk1977003ba062004-11-04 02:57:33 +00007438 }else{
drh4f0c5872007-03-26 22:05:01 +00007439 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
danielk1977003ba062004-11-04 02:57:33 +00007440 if( rc ) return rc;
danielk1977687566d2004-11-02 12:56:41 +00007441 }
7442#endif
danielk19773b8a05f2007-03-19 17:44:26 +00007443 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
drhd4187c72010-08-30 22:15:45 +00007444 if( createTabFlags & BTREE_INTKEY ){
7445 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
7446 }else{
7447 ptfFlags = PTF_ZERODATA | PTF_LEAF;
7448 }
7449 zeroPage(pRoot, ptfFlags);
danielk19773b8a05f2007-03-19 17:44:26 +00007450 sqlite3PagerUnref(pRoot->pDbPage);
drhd4187c72010-08-30 22:15:45 +00007451 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
drh8b2f49b2001-06-08 00:21:52 +00007452 *piTable = (int)pgnoRoot;
7453 return SQLITE_OK;
7454}
drhd677b3d2007-08-20 22:48:41 +00007455int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
7456 int rc;
7457 sqlite3BtreeEnter(p);
7458 rc = btreeCreateTable(p, piTable, flags);
7459 sqlite3BtreeLeave(p);
7460 return rc;
7461}
drh8b2f49b2001-06-08 00:21:52 +00007462
7463/*
7464** Erase the given database page and all its children. Return
7465** the page to the freelist.
7466*/
drh4b70f112004-05-02 21:12:19 +00007467static int clearDatabasePage(
danielk1977aef0bf62005-12-30 16:28:01 +00007468 BtShared *pBt, /* The BTree that contains the table */
drh7ab641f2009-11-24 02:37:02 +00007469 Pgno pgno, /* Page number to clear */
7470 int freePageFlag, /* Deallocate page if true */
7471 int *pnChange /* Add number of Cells freed to this counter */
drh4b70f112004-05-02 21:12:19 +00007472){
danielk1977146ba992009-07-22 14:08:13 +00007473 MemPage *pPage;
drh8b2f49b2001-06-08 00:21:52 +00007474 int rc;
drh4b70f112004-05-02 21:12:19 +00007475 unsigned char *pCell;
7476 int i;
dan8ce71842014-01-14 20:14:09 +00007477 int hdr;
drh8b2f49b2001-06-08 00:21:52 +00007478
drh1fee73e2007-08-29 04:00:57 +00007479 assert( sqlite3_mutex_held(pBt->mutex) );
drhb1299152010-03-30 22:58:33 +00007480 if( pgno>btreePagecount(pBt) ){
drh49285702005-09-17 15:20:26 +00007481 return SQLITE_CORRUPT_BKPT;
danielk1977a1cb1832005-02-12 08:59:55 +00007482 }
7483
dan11dcd112013-03-15 18:29:18 +00007484 rc = getAndInitPage(pBt, pgno, &pPage, 0);
danielk1977146ba992009-07-22 14:08:13 +00007485 if( rc ) return rc;
dan8ce71842014-01-14 20:14:09 +00007486 hdr = pPage->hdrOffset;
drh4b70f112004-05-02 21:12:19 +00007487 for(i=0; i<pPage->nCell; i++){
danielk19771cc5ed82007-05-16 17:28:43 +00007488 pCell = findCell(pPage, i);
drh4b70f112004-05-02 21:12:19 +00007489 if( !pPage->leaf ){
danielk197762c14b32008-11-19 09:05:26 +00007490 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00007491 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00007492 }
drh4b70f112004-05-02 21:12:19 +00007493 rc = clearCell(pPage, pCell);
danielk19776b456a22005-03-21 04:04:02 +00007494 if( rc ) goto cleardatabasepage_out;
drh8b2f49b2001-06-08 00:21:52 +00007495 }
drha34b6762004-05-07 13:30:42 +00007496 if( !pPage->leaf ){
dan8ce71842014-01-14 20:14:09 +00007497 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
danielk19776b456a22005-03-21 04:04:02 +00007498 if( rc ) goto cleardatabasepage_out;
danielk1977c7af4842008-10-27 13:59:33 +00007499 }else if( pnChange ){
7500 assert( pPage->intKey );
7501 *pnChange += pPage->nCell;
drh2aa679f2001-06-25 02:11:07 +00007502 }
7503 if( freePageFlag ){
drhc314dc72009-07-21 11:52:34 +00007504 freePage(pPage, &rc);
danielk19773b8a05f2007-03-19 17:44:26 +00007505 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
dan8ce71842014-01-14 20:14:09 +00007506 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
drh2aa679f2001-06-25 02:11:07 +00007507 }
danielk19776b456a22005-03-21 04:04:02 +00007508
7509cleardatabasepage_out:
drh4b70f112004-05-02 21:12:19 +00007510 releasePage(pPage);
drh2aa679f2001-06-25 02:11:07 +00007511 return rc;
drh8b2f49b2001-06-08 00:21:52 +00007512}
7513
7514/*
drhab01f612004-05-22 02:55:23 +00007515** Delete all information from a single table in the database. iTable is
7516** the page number of the root of the table. After this routine returns,
7517** the root page is empty, but still exists.
7518**
7519** This routine will fail with SQLITE_LOCKED if there are any open
7520** read cursors on the table. Open write cursors are moved to the
7521** root of the table.
danielk1977c7af4842008-10-27 13:59:33 +00007522**
7523** If pnChange is not NULL, then table iTable must be an intkey table. The
7524** integer value pointed to by pnChange is incremented by the number of
7525** entries in the table.
drh8b2f49b2001-06-08 00:21:52 +00007526*/
danielk1977c7af4842008-10-27 13:59:33 +00007527int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
drh8b2f49b2001-06-08 00:21:52 +00007528 int rc;
danielk1977aef0bf62005-12-30 16:28:01 +00007529 BtShared *pBt = p->pBt;
drhd677b3d2007-08-20 22:48:41 +00007530 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00007531 assert( p->inTrans==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +00007532
drhc046e3e2009-07-15 11:26:44 +00007533 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
drhd60f4f42012-03-23 14:23:52 +00007534
drhc046e3e2009-07-15 11:26:44 +00007535 if( SQLITE_OK==rc ){
drhd60f4f42012-03-23 14:23:52 +00007536 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
7537 ** is the root of a table b-tree - if it is not, the following call is
7538 ** a no-op). */
7539 invalidateIncrblobCursors(p, 0, 1);
danielk197762c14b32008-11-19 09:05:26 +00007540 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
drh8b2f49b2001-06-08 00:21:52 +00007541 }
drhd677b3d2007-08-20 22:48:41 +00007542 sqlite3BtreeLeave(p);
7543 return rc;
drh8b2f49b2001-06-08 00:21:52 +00007544}
7545
7546/*
drh079a3072014-03-19 14:10:55 +00007547** Delete all information from the single table that pCur is open on.
7548**
7549** This routine only work for pCur on an ephemeral table.
7550*/
7551int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
7552 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
7553}
7554
7555/*
drh8b2f49b2001-06-08 00:21:52 +00007556** Erase all information in a table and add the root of the table to
7557** the freelist. Except, the root of the principle table (the one on
drhab01f612004-05-22 02:55:23 +00007558** page 1) is never added to the freelist.
7559**
7560** This routine will fail with SQLITE_LOCKED if there are any open
7561** cursors on the table.
drh205f48e2004-11-05 00:43:11 +00007562**
7563** If AUTOVACUUM is enabled and the page at iTable is not the last
7564** root page in the database file, then the last root page
7565** in the database file is moved into the slot formerly occupied by
7566** iTable and that last slot formerly occupied by the last root page
7567** is added to the freelist instead of iTable. In this say, all
7568** root pages are kept at the beginning of the database file, which
7569** is necessary for AUTOVACUUM to work right. *piMoved is set to the
7570** page number that used to be the last root page in the file before
7571** the move. If no page gets moved, *piMoved is set to 0.
7572** The last root page is recorded in meta[3] and the value of
7573** meta[3] is updated by this procedure.
drh8b2f49b2001-06-08 00:21:52 +00007574*/
danielk197789d40042008-11-17 14:20:56 +00007575static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
drh8b2f49b2001-06-08 00:21:52 +00007576 int rc;
danielk1977a0bf2652004-11-04 14:30:04 +00007577 MemPage *pPage = 0;
danielk1977aef0bf62005-12-30 16:28:01 +00007578 BtShared *pBt = p->pBt;
danielk1977a0bf2652004-11-04 14:30:04 +00007579
drh1fee73e2007-08-29 04:00:57 +00007580 assert( sqlite3BtreeHoldsMutex(p) );
drh64022502009-01-09 14:11:04 +00007581 assert( p->inTrans==TRANS_WRITE );
danielk1977a0bf2652004-11-04 14:30:04 +00007582
danielk1977e6efa742004-11-10 11:55:10 +00007583 /* It is illegal to drop a table if any cursors are open on the
7584 ** database. This is because in auto-vacuum mode the backend may
7585 ** need to move another root-page to fill a gap left by the deleted
7586 ** root page. If an open cursor was using this page a problem would
7587 ** occur.
drhc046e3e2009-07-15 11:26:44 +00007588 **
7589 ** This error is caught long before control reaches this point.
danielk1977e6efa742004-11-10 11:55:10 +00007590 */
drhc046e3e2009-07-15 11:26:44 +00007591 if( NEVER(pBt->pCursor) ){
danielk1977404ca072009-03-16 13:19:36 +00007592 sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
7593 return SQLITE_LOCKED_SHAREDCACHE;
drh5df72a52002-06-06 23:16:05 +00007594 }
danielk1977a0bf2652004-11-04 14:30:04 +00007595
drhb00fc3b2013-08-21 23:42:32 +00007596 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
drh2aa679f2001-06-25 02:11:07 +00007597 if( rc ) return rc;
danielk1977c7af4842008-10-27 13:59:33 +00007598 rc = sqlite3BtreeClearTable(p, iTable, 0);
danielk19776b456a22005-03-21 04:04:02 +00007599 if( rc ){
7600 releasePage(pPage);
7601 return rc;
7602 }
danielk1977a0bf2652004-11-04 14:30:04 +00007603
drh205f48e2004-11-05 00:43:11 +00007604 *piMoved = 0;
danielk1977a0bf2652004-11-04 14:30:04 +00007605
drh4b70f112004-05-02 21:12:19 +00007606 if( iTable>1 ){
danielk1977a0bf2652004-11-04 14:30:04 +00007607#ifdef SQLITE_OMIT_AUTOVACUUM
drhc314dc72009-07-21 11:52:34 +00007608 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00007609 releasePage(pPage);
7610#else
7611 if( pBt->autoVacuum ){
7612 Pgno maxRootPgno;
danielk1977602b4662009-07-02 07:47:33 +00007613 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00007614
7615 if( iTable==maxRootPgno ){
7616 /* If the table being dropped is the table with the largest root-page
7617 ** number in the database, put the root page on the free list.
7618 */
drhc314dc72009-07-21 11:52:34 +00007619 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00007620 releasePage(pPage);
7621 if( rc!=SQLITE_OK ){
7622 return rc;
7623 }
7624 }else{
7625 /* The table being dropped does not have the largest root-page
7626 ** number in the database. So move the page that does into the
7627 ** gap left by the deleted root-page.
7628 */
7629 MemPage *pMove;
7630 releasePage(pPage);
drhb00fc3b2013-08-21 23:42:32 +00007631 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00007632 if( rc!=SQLITE_OK ){
7633 return rc;
7634 }
danielk19774c999992008-07-16 18:17:55 +00007635 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
danielk1977a0bf2652004-11-04 14:30:04 +00007636 releasePage(pMove);
7637 if( rc!=SQLITE_OK ){
7638 return rc;
7639 }
drhfe3313f2009-07-21 19:02:20 +00007640 pMove = 0;
drhb00fc3b2013-08-21 23:42:32 +00007641 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
drhc314dc72009-07-21 11:52:34 +00007642 freePage(pMove, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00007643 releasePage(pMove);
7644 if( rc!=SQLITE_OK ){
7645 return rc;
7646 }
7647 *piMoved = maxRootPgno;
7648 }
7649
danielk1977599fcba2004-11-08 07:13:13 +00007650 /* Set the new 'max-root-page' value in the database header. This
7651 ** is the old value less one, less one more if that happens to
7652 ** be a root-page number, less one again if that is the
7653 ** PENDING_BYTE_PAGE.
7654 */
danielk197787a6e732004-11-05 12:58:25 +00007655 maxRootPgno--;
drhe1849652009-07-15 18:15:22 +00007656 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
7657 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
danielk197787a6e732004-11-05 12:58:25 +00007658 maxRootPgno--;
7659 }
danielk1977599fcba2004-11-08 07:13:13 +00007660 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
7661
danielk1977aef0bf62005-12-30 16:28:01 +00007662 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
danielk1977a0bf2652004-11-04 14:30:04 +00007663 }else{
drhc314dc72009-07-21 11:52:34 +00007664 freePage(pPage, &rc);
danielk1977a0bf2652004-11-04 14:30:04 +00007665 releasePage(pPage);
7666 }
7667#endif
drh2aa679f2001-06-25 02:11:07 +00007668 }else{
drhc046e3e2009-07-15 11:26:44 +00007669 /* If sqlite3BtreeDropTable was called on page 1.
7670 ** This really never should happen except in a corrupt
7671 ** database.
7672 */
drha34b6762004-05-07 13:30:42 +00007673 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
danielk1977a0bf2652004-11-04 14:30:04 +00007674 releasePage(pPage);
drh8b2f49b2001-06-08 00:21:52 +00007675 }
drh8b2f49b2001-06-08 00:21:52 +00007676 return rc;
7677}
drhd677b3d2007-08-20 22:48:41 +00007678int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
7679 int rc;
7680 sqlite3BtreeEnter(p);
dan7733a4d2011-09-02 18:03:16 +00007681 rc = btreeDropTable(p, iTable, piMoved);
drhd677b3d2007-08-20 22:48:41 +00007682 sqlite3BtreeLeave(p);
7683 return rc;
7684}
drh8b2f49b2001-06-08 00:21:52 +00007685
drh001bbcb2003-03-19 03:14:00 +00007686
drh8b2f49b2001-06-08 00:21:52 +00007687/*
danielk1977602b4662009-07-02 07:47:33 +00007688** This function may only be called if the b-tree connection already
7689** has a read or write transaction open on the database.
7690**
drh23e11ca2004-05-04 17:27:28 +00007691** Read the meta-information out of a database file. Meta[0]
7692** is the number of free pages currently in the database. Meta[1]
drha3b321d2004-05-11 09:31:31 +00007693** through meta[15] are available for use by higher layers. Meta[0]
7694** is read-only, the others are read/write.
7695**
7696** The schema layer numbers meta values differently. At the schema
7697** layer (and the SetCookie and ReadCookie opcodes) the number of
7698** free pages is not visible. So Cookie[0] is the same as Meta[1].
drh8b2f49b2001-06-08 00:21:52 +00007699*/
danielk1977602b4662009-07-02 07:47:33 +00007700void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
danielk1977aef0bf62005-12-30 16:28:01 +00007701 BtShared *pBt = p->pBt;
drh8b2f49b2001-06-08 00:21:52 +00007702
drhd677b3d2007-08-20 22:48:41 +00007703 sqlite3BtreeEnter(p);
danielk1977602b4662009-07-02 07:47:33 +00007704 assert( p->inTrans>TRANS_NONE );
danielk1977e0d9e6f2009-07-03 16:25:06 +00007705 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
danielk1977602b4662009-07-02 07:47:33 +00007706 assert( pBt->pPage1 );
drh23e11ca2004-05-04 17:27:28 +00007707 assert( idx>=0 && idx<=15 );
danielk1977ea897302008-09-19 15:10:58 +00007708
danielk1977602b4662009-07-02 07:47:33 +00007709 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
drhae157872004-08-14 19:20:09 +00007710
danielk1977602b4662009-07-02 07:47:33 +00007711 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
7712 ** database, mark the database as read-only. */
danielk1977003ba062004-11-04 02:57:33 +00007713#ifdef SQLITE_OMIT_AUTOVACUUM
drhc9166342012-01-05 23:32:06 +00007714 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
7715 pBt->btsFlags |= BTS_READ_ONLY;
7716 }
danielk1977003ba062004-11-04 02:57:33 +00007717#endif
drhae157872004-08-14 19:20:09 +00007718
drhd677b3d2007-08-20 22:48:41 +00007719 sqlite3BtreeLeave(p);
drh8b2f49b2001-06-08 00:21:52 +00007720}
7721
7722/*
drh23e11ca2004-05-04 17:27:28 +00007723** Write meta-information back into the database. Meta[0] is
7724** read-only and may not be written.
drh8b2f49b2001-06-08 00:21:52 +00007725*/
danielk1977aef0bf62005-12-30 16:28:01 +00007726int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
7727 BtShared *pBt = p->pBt;
drh4b70f112004-05-02 21:12:19 +00007728 unsigned char *pP1;
drha34b6762004-05-07 13:30:42 +00007729 int rc;
drh23e11ca2004-05-04 17:27:28 +00007730 assert( idx>=1 && idx<=15 );
drhd677b3d2007-08-20 22:48:41 +00007731 sqlite3BtreeEnter(p);
drh64022502009-01-09 14:11:04 +00007732 assert( p->inTrans==TRANS_WRITE );
7733 assert( pBt->pPage1!=0 );
7734 pP1 = pBt->pPage1->aData;
7735 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
7736 if( rc==SQLITE_OK ){
7737 put4byte(&pP1[36 + idx*4], iMeta);
danielk19774152e672007-09-12 17:01:45 +00007738#ifndef SQLITE_OMIT_AUTOVACUUM
danielk19770d19f7a2009-06-03 11:25:07 +00007739 if( idx==BTREE_INCR_VACUUM ){
drh64022502009-01-09 14:11:04 +00007740 assert( pBt->autoVacuum || iMeta==0 );
7741 assert( iMeta==0 || iMeta==1 );
7742 pBt->incrVacuum = (u8)iMeta;
drhd677b3d2007-08-20 22:48:41 +00007743 }
drh64022502009-01-09 14:11:04 +00007744#endif
drh5df72a52002-06-06 23:16:05 +00007745 }
drhd677b3d2007-08-20 22:48:41 +00007746 sqlite3BtreeLeave(p);
7747 return rc;
drh8b2f49b2001-06-08 00:21:52 +00007748}
drh8c42ca92001-06-22 19:15:00 +00007749
danielk1977a5533162009-02-24 10:01:51 +00007750#ifndef SQLITE_OMIT_BTREECOUNT
7751/*
7752** The first argument, pCur, is a cursor opened on some b-tree. Count the
7753** number of entries in the b-tree and write the result to *pnEntry.
7754**
7755** SQLITE_OK is returned if the operation is successfully executed.
7756** Otherwise, if an error is encountered (i.e. an IO error or database
7757** corruption) an SQLite error code is returned.
7758*/
7759int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
7760 i64 nEntry = 0; /* Value to return in *pnEntry */
7761 int rc; /* Return code */
dana205a482011-08-27 18:48:57 +00007762
7763 if( pCur->pgnoRoot==0 ){
7764 *pnEntry = 0;
7765 return SQLITE_OK;
7766 }
danielk1977a5533162009-02-24 10:01:51 +00007767 rc = moveToRoot(pCur);
7768
7769 /* Unless an error occurs, the following loop runs one iteration for each
7770 ** page in the B-Tree structure (not including overflow pages).
7771 */
7772 while( rc==SQLITE_OK ){
7773 int iIdx; /* Index of child node in parent */
7774 MemPage *pPage; /* Current page of the b-tree */
7775
7776 /* If this is a leaf page or the tree is not an int-key tree, then
7777 ** this page contains countable entries. Increment the entry counter
7778 ** accordingly.
7779 */
7780 pPage = pCur->apPage[pCur->iPage];
7781 if( pPage->leaf || !pPage->intKey ){
7782 nEntry += pPage->nCell;
7783 }
7784
7785 /* pPage is a leaf node. This loop navigates the cursor so that it
7786 ** points to the first interior cell that it points to the parent of
7787 ** the next page in the tree that has not yet been visited. The
7788 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
7789 ** of the page, or to the number of cells in the page if the next page
7790 ** to visit is the right-child of its parent.
7791 **
7792 ** If all pages in the tree have been visited, return SQLITE_OK to the
7793 ** caller.
7794 */
7795 if( pPage->leaf ){
7796 do {
7797 if( pCur->iPage==0 ){
7798 /* All pages of the b-tree have been visited. Return successfully. */
7799 *pnEntry = nEntry;
7800 return SQLITE_OK;
7801 }
danielk197730548662009-07-09 05:07:37 +00007802 moveToParent(pCur);
danielk1977a5533162009-02-24 10:01:51 +00007803 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
7804
7805 pCur->aiIdx[pCur->iPage]++;
7806 pPage = pCur->apPage[pCur->iPage];
7807 }
7808
7809 /* Descend to the child node of the cell that the cursor currently
7810 ** points at. This is the right-child if (iIdx==pPage->nCell).
7811 */
7812 iIdx = pCur->aiIdx[pCur->iPage];
7813 if( iIdx==pPage->nCell ){
7814 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
7815 }else{
7816 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
7817 }
7818 }
7819
shanebe217792009-03-05 04:20:31 +00007820 /* An error has occurred. Return an error code. */
danielk1977a5533162009-02-24 10:01:51 +00007821 return rc;
7822}
7823#endif
drhdd793422001-06-28 01:54:48 +00007824
drhdd793422001-06-28 01:54:48 +00007825/*
drh5eddca62001-06-30 21:53:53 +00007826** Return the pager associated with a BTree. This routine is used for
7827** testing and debugging only.
drhdd793422001-06-28 01:54:48 +00007828*/
danielk1977aef0bf62005-12-30 16:28:01 +00007829Pager *sqlite3BtreePager(Btree *p){
7830 return p->pBt->pPager;
drhdd793422001-06-28 01:54:48 +00007831}
drh5eddca62001-06-30 21:53:53 +00007832
drhb7f91642004-10-31 02:22:47 +00007833#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00007834/*
7835** Append a message to the error message string.
7836*/
drh2e38c322004-09-03 18:38:44 +00007837static void checkAppendMsg(
7838 IntegrityCk *pCheck,
7839 char *zMsg1,
7840 const char *zFormat,
7841 ...
7842){
7843 va_list ap;
drh1dcdbc02007-01-27 02:24:54 +00007844 if( !pCheck->mxErr ) return;
7845 pCheck->mxErr--;
7846 pCheck->nErr++;
drh2e38c322004-09-03 18:38:44 +00007847 va_start(ap, zFormat);
drhf089aa42008-07-08 19:34:06 +00007848 if( pCheck->errMsg.nChar ){
7849 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
drh5eddca62001-06-30 21:53:53 +00007850 }
drhf089aa42008-07-08 19:34:06 +00007851 if( zMsg1 ){
drha6353a32013-12-09 19:03:26 +00007852 sqlite3StrAccumAppendAll(&pCheck->errMsg, zMsg1);
drhf089aa42008-07-08 19:34:06 +00007853 }
7854 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
7855 va_end(ap);
drhb49bc862013-08-21 21:12:10 +00007856 if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
drhc890fec2008-08-01 20:10:08 +00007857 pCheck->mallocFailed = 1;
7858 }
drh5eddca62001-06-30 21:53:53 +00007859}
drhb7f91642004-10-31 02:22:47 +00007860#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00007861
drhb7f91642004-10-31 02:22:47 +00007862#ifndef SQLITE_OMIT_INTEGRITY_CHECK
dan1235bb12012-04-03 17:43:28 +00007863
7864/*
7865** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
7866** corresponds to page iPg is already set.
7867*/
7868static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
7869 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
7870 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
7871}
7872
7873/*
7874** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
7875*/
7876static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
7877 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
7878 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
7879}
7880
7881
drh5eddca62001-06-30 21:53:53 +00007882/*
7883** Add 1 to the reference count for page iPage. If this is the second
7884** reference to the page, add an error message to pCheck->zErrMsg.
peter.d.reid60ec9142014-09-06 16:39:46 +00007885** Return 1 if there are 2 or more references to the page and 0 if
drh5eddca62001-06-30 21:53:53 +00007886** if this is the first reference to the page.
7887**
7888** Also check that the page number is in bounds.
7889*/
danielk197789d40042008-11-17 14:20:56 +00007890static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
drh5eddca62001-06-30 21:53:53 +00007891 if( iPage==0 ) return 1;
danielk197789d40042008-11-17 14:20:56 +00007892 if( iPage>pCheck->nPage ){
drh2e38c322004-09-03 18:38:44 +00007893 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
drh5eddca62001-06-30 21:53:53 +00007894 return 1;
7895 }
dan1235bb12012-04-03 17:43:28 +00007896 if( getPageReferenced(pCheck, iPage) ){
drh2e38c322004-09-03 18:38:44 +00007897 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00007898 return 1;
7899 }
dan1235bb12012-04-03 17:43:28 +00007900 setPageReferenced(pCheck, iPage);
7901 return 0;
drh5eddca62001-06-30 21:53:53 +00007902}
7903
danielk1977afcdd022004-10-31 16:25:42 +00007904#ifndef SQLITE_OMIT_AUTOVACUUM
7905/*
7906** Check that the entry in the pointer-map for page iChild maps to
7907** page iParent, pointer type ptrType. If not, append an error message
7908** to pCheck.
7909*/
7910static void checkPtrmap(
7911 IntegrityCk *pCheck, /* Integrity check context */
7912 Pgno iChild, /* Child page number */
7913 u8 eType, /* Expected pointer map type */
7914 Pgno iParent, /* Expected pointer map parent page number */
7915 char *zContext /* Context description (used for error msg) */
7916){
7917 int rc;
7918 u8 ePtrmapType;
7919 Pgno iPtrmapParent;
7920
7921 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
7922 if( rc!=SQLITE_OK ){
drhb56cd552009-05-01 13:16:54 +00007923 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
danielk1977afcdd022004-10-31 16:25:42 +00007924 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
7925 return;
7926 }
7927
7928 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
7929 checkAppendMsg(pCheck, zContext,
7930 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
7931 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
7932 }
7933}
7934#endif
7935
drh5eddca62001-06-30 21:53:53 +00007936/*
7937** Check the integrity of the freelist or of an overflow page list.
7938** Verify that the number of pages on the list is N.
7939*/
drh30e58752002-03-02 20:41:57 +00007940static void checkList(
7941 IntegrityCk *pCheck, /* Integrity checking context */
7942 int isFreeList, /* True for a freelist. False for overflow page list */
7943 int iPage, /* Page number for first page in the list */
7944 int N, /* Expected number of pages in the list */
7945 char *zContext /* Context for error messages */
7946){
7947 int i;
drh3a4c1412004-05-09 20:40:11 +00007948 int expected = N;
7949 int iFirst = iPage;
drh1dcdbc02007-01-27 02:24:54 +00007950 while( N-- > 0 && pCheck->mxErr ){
danielk19773b8a05f2007-03-19 17:44:26 +00007951 DbPage *pOvflPage;
7952 unsigned char *pOvflData;
drh5eddca62001-06-30 21:53:53 +00007953 if( iPage<1 ){
drh2e38c322004-09-03 18:38:44 +00007954 checkAppendMsg(pCheck, zContext,
7955 "%d of %d pages missing from overflow list starting at %d",
drh3a4c1412004-05-09 20:40:11 +00007956 N+1, expected, iFirst);
drh5eddca62001-06-30 21:53:53 +00007957 break;
7958 }
7959 if( checkRef(pCheck, iPage, zContext) ) break;
danielk19773b8a05f2007-03-19 17:44:26 +00007960 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
drh2e38c322004-09-03 18:38:44 +00007961 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
drh5eddca62001-06-30 21:53:53 +00007962 break;
7963 }
danielk19773b8a05f2007-03-19 17:44:26 +00007964 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
drh30e58752002-03-02 20:41:57 +00007965 if( isFreeList ){
danielk19773b8a05f2007-03-19 17:44:26 +00007966 int n = get4byte(&pOvflData[4]);
danielk1977687566d2004-11-02 12:56:41 +00007967#ifndef SQLITE_OMIT_AUTOVACUUM
7968 if( pCheck->pBt->autoVacuum ){
7969 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
7970 }
7971#endif
drh43b18e12010-08-17 19:40:08 +00007972 if( n>(int)pCheck->pBt->usableSize/4-2 ){
drh2e38c322004-09-03 18:38:44 +00007973 checkAppendMsg(pCheck, zContext,
7974 "freelist leaf count too big on page %d", iPage);
drhee696e22004-08-30 16:52:17 +00007975 N--;
7976 }else{
7977 for(i=0; i<n; i++){
danielk19773b8a05f2007-03-19 17:44:26 +00007978 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
danielk1977687566d2004-11-02 12:56:41 +00007979#ifndef SQLITE_OMIT_AUTOVACUUM
7980 if( pCheck->pBt->autoVacuum ){
7981 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
7982 }
7983#endif
7984 checkRef(pCheck, iFreePage, zContext);
drhee696e22004-08-30 16:52:17 +00007985 }
7986 N -= n;
drh30e58752002-03-02 20:41:57 +00007987 }
drh30e58752002-03-02 20:41:57 +00007988 }
danielk1977afcdd022004-10-31 16:25:42 +00007989#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00007990 else{
7991 /* If this database supports auto-vacuum and iPage is not the last
7992 ** page in this overflow list, check that the pointer-map entry for
7993 ** the following page matches iPage.
7994 */
7995 if( pCheck->pBt->autoVacuum && N>0 ){
danielk19773b8a05f2007-03-19 17:44:26 +00007996 i = get4byte(pOvflData);
danielk1977687566d2004-11-02 12:56:41 +00007997 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
7998 }
danielk1977afcdd022004-10-31 16:25:42 +00007999 }
8000#endif
danielk19773b8a05f2007-03-19 17:44:26 +00008001 iPage = get4byte(pOvflData);
8002 sqlite3PagerUnref(pOvflPage);
drh5eddca62001-06-30 21:53:53 +00008003 }
8004}
drhb7f91642004-10-31 02:22:47 +00008005#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00008006
drhb7f91642004-10-31 02:22:47 +00008007#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00008008/*
8009** Do various sanity checks on a single page of a tree. Return
8010** the tree depth. Root pages return 0. Parents of root pages
8011** return 1, and so forth.
8012**
8013** These checks are done:
8014**
8015** 1. Make sure that cells and freeblocks do not overlap
8016** but combine to completely cover the page.
drhda200cc2004-05-09 11:51:38 +00008017** NO 2. Make sure cell keys are in order.
8018** NO 3. Make sure no key is less than or equal to zLowerBound.
8019** NO 4. Make sure no key is greater than or equal to zUpperBound.
drh5eddca62001-06-30 21:53:53 +00008020** 5. Check the integrity of overflow pages.
8021** 6. Recursively call checkTreePage on all children.
8022** 7. Verify that the depth of all children is the same.
drh6019e162001-07-02 17:51:45 +00008023** 8. Make sure this page is at least 33% full or else it is
drh5eddca62001-06-30 21:53:53 +00008024** the root of the tree.
8025*/
8026static int checkTreePage(
drhaaab5722002-02-19 13:39:21 +00008027 IntegrityCk *pCheck, /* Context for the sanity check */
drh5eddca62001-06-30 21:53:53 +00008028 int iPage, /* Page number of the page to check */
shaneh195475d2010-02-19 04:28:08 +00008029 char *zParentContext, /* Parent context */
8030 i64 *pnParentMinKey,
8031 i64 *pnParentMaxKey
drh5eddca62001-06-30 21:53:53 +00008032){
8033 MemPage *pPage;
drhda200cc2004-05-09 11:51:38 +00008034 int i, rc, depth, d2, pgno, cnt;
drh43605152004-05-29 21:46:49 +00008035 int hdr, cellStart;
8036 int nCell;
drhda200cc2004-05-09 11:51:38 +00008037 u8 *data;
danielk1977aef0bf62005-12-30 16:28:01 +00008038 BtShared *pBt;
drh4f26bb62005-09-08 14:17:20 +00008039 int usableSize;
drh5eddca62001-06-30 21:53:53 +00008040 char zContext[100];
shane0af3f892008-11-12 04:55:34 +00008041 char *hit = 0;
shaneh195475d2010-02-19 04:28:08 +00008042 i64 nMinKey = 0;
8043 i64 nMaxKey = 0;
drh5eddca62001-06-30 21:53:53 +00008044
drh5bb3eb92007-05-04 13:15:55 +00008045 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
danielk1977ef73ee92004-11-06 12:26:07 +00008046
drh5eddca62001-06-30 21:53:53 +00008047 /* Check that the page exists
8048 */
drhd9cb6ac2005-10-20 07:28:17 +00008049 pBt = pCheck->pBt;
drhb6f41482004-05-14 01:58:11 +00008050 usableSize = pBt->usableSize;
drh5eddca62001-06-30 21:53:53 +00008051 if( iPage==0 ) return 0;
8052 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
drhb00fc3b2013-08-21 23:42:32 +00008053 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
drh2e38c322004-09-03 18:38:44 +00008054 checkAppendMsg(pCheck, zContext,
8055 "unable to get the page. error code=%d", rc);
drh5eddca62001-06-30 21:53:53 +00008056 return 0;
8057 }
danielk197793caf5a2009-07-11 06:55:33 +00008058
8059 /* Clear MemPage.isInit to make sure the corruption detection code in
8060 ** btreeInitPage() is executed. */
8061 pPage->isInit = 0;
danielk197730548662009-07-09 05:07:37 +00008062 if( (rc = btreeInitPage(pPage))!=0 ){
drh64022502009-01-09 14:11:04 +00008063 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
drh16a9b832007-05-05 18:39:25 +00008064 checkAppendMsg(pCheck, zContext,
danielk197730548662009-07-09 05:07:37 +00008065 "btreeInitPage() returns error code %d", rc);
drh91025292004-05-03 19:49:32 +00008066 releasePage(pPage);
drh5eddca62001-06-30 21:53:53 +00008067 return 0;
8068 }
8069
8070 /* Check out all the cells.
8071 */
8072 depth = 0;
drh1dcdbc02007-01-27 02:24:54 +00008073 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
drh6f11bef2004-05-13 01:12:56 +00008074 u8 *pCell;
danielk197789d40042008-11-17 14:20:56 +00008075 u32 sz;
drh6f11bef2004-05-13 01:12:56 +00008076 CellInfo info;
drh5eddca62001-06-30 21:53:53 +00008077
8078 /* Check payload overflow pages
8079 */
drh5bb3eb92007-05-04 13:15:55 +00008080 sqlite3_snprintf(sizeof(zContext), zContext,
8081 "On tree page %d cell %d: ", iPage, i);
danielk19771cc5ed82007-05-16 17:28:43 +00008082 pCell = findCell(pPage,i);
danielk197730548662009-07-09 05:07:37 +00008083 btreeParseCellPtr(pPage, pCell, &info);
drh6f11bef2004-05-13 01:12:56 +00008084 sz = info.nData;
drhf49661a2008-12-10 16:45:50 +00008085 if( !pPage->intKey ) sz += (int)info.nKey;
shaneh195475d2010-02-19 04:28:08 +00008086 /* For intKey pages, check that the keys are in order.
8087 */
8088 else if( i==0 ) nMinKey = nMaxKey = info.nKey;
8089 else{
8090 if( info.nKey <= nMaxKey ){
8091 checkAppendMsg(pCheck, zContext,
8092 "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
8093 }
8094 nMaxKey = info.nKey;
8095 }
drh72365832007-03-06 15:53:44 +00008096 assert( sz==info.nPayload );
danielk19775be31f52009-03-30 13:53:43 +00008097 if( (sz>info.nLocal)
8098 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
8099 ){
drhb6f41482004-05-14 01:58:11 +00008100 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
danielk1977afcdd022004-10-31 16:25:42 +00008101 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
8102#ifndef SQLITE_OMIT_AUTOVACUUM
8103 if( pBt->autoVacuum ){
danielk1977687566d2004-11-02 12:56:41 +00008104 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00008105 }
8106#endif
8107 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
drh5eddca62001-06-30 21:53:53 +00008108 }
8109
8110 /* Check sanity of left child page.
8111 */
drhda200cc2004-05-09 11:51:38 +00008112 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00008113 pgno = get4byte(pCell);
danielk1977afcdd022004-10-31 16:25:42 +00008114#ifndef SQLITE_OMIT_AUTOVACUUM
8115 if( pBt->autoVacuum ){
8116 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
8117 }
8118#endif
shaneh195475d2010-02-19 04:28:08 +00008119 d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
drhda200cc2004-05-09 11:51:38 +00008120 if( i>0 && d2!=depth ){
8121 checkAppendMsg(pCheck, zContext, "Child page depth differs");
8122 }
8123 depth = d2;
drh5eddca62001-06-30 21:53:53 +00008124 }
drh5eddca62001-06-30 21:53:53 +00008125 }
shaneh195475d2010-02-19 04:28:08 +00008126
drhda200cc2004-05-09 11:51:38 +00008127 if( !pPage->leaf ){
drh43605152004-05-29 21:46:49 +00008128 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
drh5bb3eb92007-05-04 13:15:55 +00008129 sqlite3_snprintf(sizeof(zContext), zContext,
8130 "On page %d at right child: ", iPage);
danielk1977afcdd022004-10-31 16:25:42 +00008131#ifndef SQLITE_OMIT_AUTOVACUUM
8132 if( pBt->autoVacuum ){
shaneh195475d2010-02-19 04:28:08 +00008133 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
danielk1977afcdd022004-10-31 16:25:42 +00008134 }
8135#endif
shaneh195475d2010-02-19 04:28:08 +00008136 checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
drhda200cc2004-05-09 11:51:38 +00008137 }
drh5eddca62001-06-30 21:53:53 +00008138
shaneh195475d2010-02-19 04:28:08 +00008139 /* For intKey leaf pages, check that the min/max keys are in order
8140 ** with any left/parent/right pages.
8141 */
8142 if( pPage->leaf && pPage->intKey ){
8143 /* if we are a left child page */
8144 if( pnParentMinKey ){
8145 /* if we are the left most child page */
8146 if( !pnParentMaxKey ){
8147 if( nMaxKey > *pnParentMinKey ){
8148 checkAppendMsg(pCheck, zContext,
8149 "Rowid %lld out of order (max larger than parent min of %lld)",
8150 nMaxKey, *pnParentMinKey);
8151 }
8152 }else{
8153 if( nMinKey <= *pnParentMinKey ){
8154 checkAppendMsg(pCheck, zContext,
8155 "Rowid %lld out of order (min less than parent min of %lld)",
8156 nMinKey, *pnParentMinKey);
8157 }
8158 if( nMaxKey > *pnParentMaxKey ){
8159 checkAppendMsg(pCheck, zContext,
8160 "Rowid %lld out of order (max larger than parent max of %lld)",
8161 nMaxKey, *pnParentMaxKey);
8162 }
8163 *pnParentMinKey = nMaxKey;
8164 }
8165 /* else if we're a right child page */
8166 } else if( pnParentMaxKey ){
8167 if( nMinKey <= *pnParentMaxKey ){
8168 checkAppendMsg(pCheck, zContext,
8169 "Rowid %lld out of order (min less than parent max of %lld)",
8170 nMinKey, *pnParentMaxKey);
8171 }
8172 }
8173 }
8174
drh5eddca62001-06-30 21:53:53 +00008175 /* Check for complete coverage of the page
8176 */
drhda200cc2004-05-09 11:51:38 +00008177 data = pPage->aData;
8178 hdr = pPage->hdrOffset;
drhf7141992008-06-19 00:16:08 +00008179 hit = sqlite3PageMalloc( pBt->pageSize );
drhc890fec2008-08-01 20:10:08 +00008180 if( hit==0 ){
8181 pCheck->mallocFailed = 1;
8182 }else{
drh5d433ce2010-08-14 16:02:52 +00008183 int contentOffset = get2byteNotZero(&data[hdr+5]);
drhd7c7ecd2009-07-14 17:48:06 +00008184 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
shane5780ebd2008-11-11 17:36:30 +00008185 memset(hit+contentOffset, 0, usableSize-contentOffset);
8186 memset(hit, 1, contentOffset);
drh2e38c322004-09-03 18:38:44 +00008187 nCell = get2byte(&data[hdr+3]);
8188 cellStart = hdr + 12 - 4*pPage->leaf;
8189 for(i=0; i<nCell; i++){
8190 int pc = get2byte(&data[cellStart+i*2]);
drh9b78f792010-08-14 21:21:24 +00008191 u32 size = 65536;
drh2e38c322004-09-03 18:38:44 +00008192 int j;
drh8c2bbb62009-07-10 02:52:20 +00008193 if( pc<=usableSize-4 ){
danielk1977daca5432008-08-25 11:57:16 +00008194 size = cellSizePtr(pPage, &data[pc]);
8195 }
drh43b18e12010-08-17 19:40:08 +00008196 if( (int)(pc+size-1)>=usableSize ){
danielk19777701e812005-01-10 12:59:51 +00008197 checkAppendMsg(pCheck, 0,
shaneh195475d2010-02-19 04:28:08 +00008198 "Corruption detected in cell %d on page %d",i,iPage);
danielk19777701e812005-01-10 12:59:51 +00008199 }else{
8200 for(j=pc+size-1; j>=pc; j--) hit[j]++;
8201 }
drh2e38c322004-09-03 18:38:44 +00008202 }
drh8c2bbb62009-07-10 02:52:20 +00008203 i = get2byte(&data[hdr+1]);
8204 while( i>0 ){
8205 int size, j;
8206 assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
8207 size = get2byte(&data[i+2]);
8208 assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
8209 for(j=i+size-1; j>=i; j--) hit[j]++;
8210 j = get2byte(&data[i]);
8211 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
8212 assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
8213 i = j;
drh2e38c322004-09-03 18:38:44 +00008214 }
8215 for(i=cnt=0; i<usableSize; i++){
8216 if( hit[i]==0 ){
8217 cnt++;
8218 }else if( hit[i]>1 ){
8219 checkAppendMsg(pCheck, 0,
8220 "Multiple uses for byte %d of page %d", i, iPage);
8221 break;
8222 }
8223 }
8224 if( cnt!=data[hdr+7] ){
8225 checkAppendMsg(pCheck, 0,
drh8c2bbb62009-07-10 02:52:20 +00008226 "Fragmentation of %d bytes reported as %d on page %d",
drh2e38c322004-09-03 18:38:44 +00008227 cnt, data[hdr+7], iPage);
drh5eddca62001-06-30 21:53:53 +00008228 }
8229 }
drh8c2bbb62009-07-10 02:52:20 +00008230 sqlite3PageFree(hit);
drh4b70f112004-05-02 21:12:19 +00008231 releasePage(pPage);
drhda200cc2004-05-09 11:51:38 +00008232 return depth+1;
drh5eddca62001-06-30 21:53:53 +00008233}
drhb7f91642004-10-31 02:22:47 +00008234#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
drh5eddca62001-06-30 21:53:53 +00008235
drhb7f91642004-10-31 02:22:47 +00008236#ifndef SQLITE_OMIT_INTEGRITY_CHECK
drh5eddca62001-06-30 21:53:53 +00008237/*
8238** This routine does a complete check of the given BTree file. aRoot[] is
8239** an array of pages numbers were each page number is the root page of
8240** a table. nRoot is the number of entries in aRoot.
8241**
danielk19773509a652009-07-06 18:56:13 +00008242** A read-only or read-write transaction must be opened before calling
8243** this function.
8244**
drhc890fec2008-08-01 20:10:08 +00008245** Write the number of error seen in *pnErr. Except for some memory
drhe43ba702008-12-05 22:40:08 +00008246** allocation errors, an error message held in memory obtained from
drhc890fec2008-08-01 20:10:08 +00008247** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
drhe43ba702008-12-05 22:40:08 +00008248** returned. If a memory allocation error occurs, NULL is returned.
drh5eddca62001-06-30 21:53:53 +00008249*/
drh1dcdbc02007-01-27 02:24:54 +00008250char *sqlite3BtreeIntegrityCheck(
8251 Btree *p, /* The btree to be checked */
8252 int *aRoot, /* An array of root pages numbers for individual trees */
8253 int nRoot, /* Number of entries in aRoot[] */
8254 int mxErr, /* Stop reporting errors after this many */
8255 int *pnErr /* Write number of errors seen to this variable */
8256){
danielk197789d40042008-11-17 14:20:56 +00008257 Pgno i;
drh5eddca62001-06-30 21:53:53 +00008258 int nRef;
drhaaab5722002-02-19 13:39:21 +00008259 IntegrityCk sCheck;
danielk1977aef0bf62005-12-30 16:28:01 +00008260 BtShared *pBt = p->pBt;
drhf089aa42008-07-08 19:34:06 +00008261 char zErr[100];
drh5eddca62001-06-30 21:53:53 +00008262
drhd677b3d2007-08-20 22:48:41 +00008263 sqlite3BtreeEnter(p);
danielk19773509a652009-07-06 18:56:13 +00008264 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
danielk19773b8a05f2007-03-19 17:44:26 +00008265 nRef = sqlite3PagerRefcount(pBt->pPager);
drh5eddca62001-06-30 21:53:53 +00008266 sCheck.pBt = pBt;
8267 sCheck.pPager = pBt->pPager;
drhb1299152010-03-30 22:58:33 +00008268 sCheck.nPage = btreePagecount(sCheck.pBt);
drh1dcdbc02007-01-27 02:24:54 +00008269 sCheck.mxErr = mxErr;
8270 sCheck.nErr = 0;
drhc890fec2008-08-01 20:10:08 +00008271 sCheck.mallocFailed = 0;
drh1dcdbc02007-01-27 02:24:54 +00008272 *pnErr = 0;
drh0de8c112002-07-06 16:32:14 +00008273 if( sCheck.nPage==0 ){
drhd677b3d2007-08-20 22:48:41 +00008274 sqlite3BtreeLeave(p);
drh0de8c112002-07-06 16:32:14 +00008275 return 0;
8276 }
dan1235bb12012-04-03 17:43:28 +00008277
8278 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
8279 if( !sCheck.aPgRef ){
drh1dcdbc02007-01-27 02:24:54 +00008280 *pnErr = 1;
drhd677b3d2007-08-20 22:48:41 +00008281 sqlite3BtreeLeave(p);
drhc890fec2008-08-01 20:10:08 +00008282 return 0;
danielk1977ac245ec2005-01-14 13:50:11 +00008283 }
drh42cac6d2004-11-20 20:31:11 +00008284 i = PENDING_BYTE_PAGE(pBt);
dan1235bb12012-04-03 17:43:28 +00008285 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
drh32055c22012-12-12 14:30:03 +00008286 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
drhb9755982010-07-24 16:34:37 +00008287 sCheck.errMsg.useMalloc = 2;
drh5eddca62001-06-30 21:53:53 +00008288
8289 /* Check the integrity of the freelist
8290 */
drha34b6762004-05-07 13:30:42 +00008291 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
8292 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
drh5eddca62001-06-30 21:53:53 +00008293
8294 /* Check all the tables.
8295 */
danielk197789d40042008-11-17 14:20:56 +00008296 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
drh4ff6dfa2002-03-03 23:06:00 +00008297 if( aRoot[i]==0 ) continue;
danielk1977687566d2004-11-02 12:56:41 +00008298#ifndef SQLITE_OMIT_AUTOVACUUM
danielk1977687566d2004-11-02 12:56:41 +00008299 if( pBt->autoVacuum && aRoot[i]>1 ){
8300 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
8301 }
8302#endif
shaneh195475d2010-02-19 04:28:08 +00008303 checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
drh5eddca62001-06-30 21:53:53 +00008304 }
8305
8306 /* Make sure every page in the file is referenced
8307 */
drh1dcdbc02007-01-27 02:24:54 +00008308 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
danielk1977afcdd022004-10-31 16:25:42 +00008309#ifdef SQLITE_OMIT_AUTOVACUUM
dan1235bb12012-04-03 17:43:28 +00008310 if( getPageReferenced(&sCheck, i)==0 ){
drh2e38c322004-09-03 18:38:44 +00008311 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
drh5eddca62001-06-30 21:53:53 +00008312 }
danielk1977afcdd022004-10-31 16:25:42 +00008313#else
8314 /* If the database supports auto-vacuum, make sure no tables contain
8315 ** references to pointer-map pages.
8316 */
dan1235bb12012-04-03 17:43:28 +00008317 if( getPageReferenced(&sCheck, i)==0 &&
danielk1977266664d2006-02-10 08:24:21 +00008318 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00008319 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
8320 }
dan1235bb12012-04-03 17:43:28 +00008321 if( getPageReferenced(&sCheck, i)!=0 &&
danielk1977266664d2006-02-10 08:24:21 +00008322 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
danielk1977afcdd022004-10-31 16:25:42 +00008323 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
8324 }
8325#endif
drh5eddca62001-06-30 21:53:53 +00008326 }
8327
drh64022502009-01-09 14:11:04 +00008328 /* Make sure this analysis did not leave any unref() pages.
8329 ** This is an internal consistency check; an integrity check
8330 ** of the integrity check.
drh5eddca62001-06-30 21:53:53 +00008331 */
drh64022502009-01-09 14:11:04 +00008332 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
drh2e38c322004-09-03 18:38:44 +00008333 checkAppendMsg(&sCheck, 0,
drh5eddca62001-06-30 21:53:53 +00008334 "Outstanding page count goes from %d to %d during this analysis",
danielk19773b8a05f2007-03-19 17:44:26 +00008335 nRef, sqlite3PagerRefcount(pBt->pPager)
drh5eddca62001-06-30 21:53:53 +00008336 );
drh5eddca62001-06-30 21:53:53 +00008337 }
8338
8339 /* Clean up and report errors.
8340 */
drhd677b3d2007-08-20 22:48:41 +00008341 sqlite3BtreeLeave(p);
dan1235bb12012-04-03 17:43:28 +00008342 sqlite3_free(sCheck.aPgRef);
drhc890fec2008-08-01 20:10:08 +00008343 if( sCheck.mallocFailed ){
8344 sqlite3StrAccumReset(&sCheck.errMsg);
8345 *pnErr = sCheck.nErr+1;
8346 return 0;
8347 }
drh1dcdbc02007-01-27 02:24:54 +00008348 *pnErr = sCheck.nErr;
drhf089aa42008-07-08 19:34:06 +00008349 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
8350 return sqlite3StrAccumFinish(&sCheck.errMsg);
drh5eddca62001-06-30 21:53:53 +00008351}
drhb7f91642004-10-31 02:22:47 +00008352#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
paulb95a8862003-04-01 21:16:41 +00008353
drh73509ee2003-04-06 20:44:45 +00008354/*
drhd4e0bb02012-05-27 01:19:04 +00008355** Return the full pathname of the underlying database file. Return
8356** an empty string if the database is in-memory or a TEMP database.
drhd0679ed2007-08-28 22:24:34 +00008357**
8358** The pager filename is invariant as long as the pager is
8359** open so it is safe to access without the BtShared mutex.
drh73509ee2003-04-06 20:44:45 +00008360*/
danielk1977aef0bf62005-12-30 16:28:01 +00008361const char *sqlite3BtreeGetFilename(Btree *p){
8362 assert( p->pBt->pPager!=0 );
drhd4e0bb02012-05-27 01:19:04 +00008363 return sqlite3PagerFilename(p->pBt->pPager, 1);
drh73509ee2003-04-06 20:44:45 +00008364}
8365
8366/*
danielk19775865e3d2004-06-14 06:03:57 +00008367** Return the pathname of the journal file for this database. The return
8368** value of this routine is the same regardless of whether the journal file
8369** has been created or not.
drhd0679ed2007-08-28 22:24:34 +00008370**
8371** The pager journal filename is invariant as long as the pager is
8372** open so it is safe to access without the BtShared mutex.
danielk19775865e3d2004-06-14 06:03:57 +00008373*/
danielk1977aef0bf62005-12-30 16:28:01 +00008374const char *sqlite3BtreeGetJournalname(Btree *p){
8375 assert( p->pBt->pPager!=0 );
danielk19773b8a05f2007-03-19 17:44:26 +00008376 return sqlite3PagerJournalname(p->pBt->pPager);
danielk19775865e3d2004-06-14 06:03:57 +00008377}
8378
danielk19771d850a72004-05-31 08:26:49 +00008379/*
8380** Return non-zero if a transaction is active.
8381*/
danielk1977aef0bf62005-12-30 16:28:01 +00008382int sqlite3BtreeIsInTrans(Btree *p){
drhe5fe6902007-12-07 18:55:28 +00008383 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
danielk1977aef0bf62005-12-30 16:28:01 +00008384 return (p && (p->inTrans==TRANS_WRITE));
danielk19771d850a72004-05-31 08:26:49 +00008385}
8386
dana550f2d2010-08-02 10:47:05 +00008387#ifndef SQLITE_OMIT_WAL
8388/*
8389** Run a checkpoint on the Btree passed as the first argument.
8390**
8391** Return SQLITE_LOCKED if this or any other connection has an open
8392** transaction on the shared-cache the argument Btree is connected to.
dana58f26f2010-11-16 18:56:51 +00008393**
dancdc1f042010-11-18 12:11:05 +00008394** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
dana550f2d2010-08-02 10:47:05 +00008395*/
dancdc1f042010-11-18 12:11:05 +00008396int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
dana550f2d2010-08-02 10:47:05 +00008397 int rc = SQLITE_OK;
8398 if( p ){
8399 BtShared *pBt = p->pBt;
8400 sqlite3BtreeEnter(p);
8401 if( pBt->inTransaction!=TRANS_NONE ){
8402 rc = SQLITE_LOCKED;
8403 }else{
dancdc1f042010-11-18 12:11:05 +00008404 rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
dana550f2d2010-08-02 10:47:05 +00008405 }
8406 sqlite3BtreeLeave(p);
8407 }
8408 return rc;
8409}
8410#endif
8411
danielk19771d850a72004-05-31 08:26:49 +00008412/*
danielk19772372c2b2006-06-27 16:34:56 +00008413** Return non-zero if a read (or write) transaction is active.
8414*/
8415int sqlite3BtreeIsInReadTrans(Btree *p){
drh64022502009-01-09 14:11:04 +00008416 assert( p );
drhe5fe6902007-12-07 18:55:28 +00008417 assert( sqlite3_mutex_held(p->db->mutex) );
drh64022502009-01-09 14:11:04 +00008418 return p->inTrans!=TRANS_NONE;
danielk19772372c2b2006-06-27 16:34:56 +00008419}
8420
danielk197704103022009-02-03 16:51:24 +00008421int sqlite3BtreeIsInBackup(Btree *p){
8422 assert( p );
8423 assert( sqlite3_mutex_held(p->db->mutex) );
8424 return p->nBackup!=0;
8425}
8426
danielk19772372c2b2006-06-27 16:34:56 +00008427/*
danielk1977da184232006-01-05 11:34:32 +00008428** This function returns a pointer to a blob of memory associated with
drh85b623f2007-12-13 21:54:09 +00008429** a single shared-btree. The memory is used by client code for its own
danielk1977da184232006-01-05 11:34:32 +00008430** purposes (for example, to store a high-level schema associated with
8431** the shared-btree). The btree layer manages reference counting issues.
8432**
8433** The first time this is called on a shared-btree, nBytes bytes of memory
8434** are allocated, zeroed, and returned to the caller. For each subsequent
8435** call the nBytes parameter is ignored and a pointer to the same blob
8436** of memory returned.
8437**
danielk1977171bfed2008-06-23 09:50:50 +00008438** If the nBytes parameter is 0 and the blob of memory has not yet been
8439** allocated, a null pointer is returned. If the blob has already been
8440** allocated, it is returned as normal.
8441**
danielk1977da184232006-01-05 11:34:32 +00008442** Just before the shared-btree is closed, the function passed as the
8443** xFree argument when the memory allocation was made is invoked on the
drh4fa7d7c2011-04-03 02:41:00 +00008444** blob of allocated memory. The xFree function should not call sqlite3_free()
danielk1977da184232006-01-05 11:34:32 +00008445** on the memory, the btree layer does that.
8446*/
8447void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
8448 BtShared *pBt = p->pBt;
drh27641702007-08-22 02:56:42 +00008449 sqlite3BtreeEnter(p);
danielk1977171bfed2008-06-23 09:50:50 +00008450 if( !pBt->pSchema && nBytes ){
drhb9755982010-07-24 16:34:37 +00008451 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
danielk1977da184232006-01-05 11:34:32 +00008452 pBt->xFreeSchema = xFree;
8453 }
drh27641702007-08-22 02:56:42 +00008454 sqlite3BtreeLeave(p);
danielk1977da184232006-01-05 11:34:32 +00008455 return pBt->pSchema;
8456}
8457
danielk1977c87d34d2006-01-06 13:00:28 +00008458/*
danielk1977404ca072009-03-16 13:19:36 +00008459** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
8460** btree as the argument handle holds an exclusive lock on the
8461** sqlite_master table. Otherwise SQLITE_OK.
danielk1977c87d34d2006-01-06 13:00:28 +00008462*/
8463int sqlite3BtreeSchemaLocked(Btree *p){
drh27641702007-08-22 02:56:42 +00008464 int rc;
drhe5fe6902007-12-07 18:55:28 +00008465 assert( sqlite3_mutex_held(p->db->mutex) );
drh27641702007-08-22 02:56:42 +00008466 sqlite3BtreeEnter(p);
danielk1977404ca072009-03-16 13:19:36 +00008467 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
8468 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
drh27641702007-08-22 02:56:42 +00008469 sqlite3BtreeLeave(p);
8470 return rc;
danielk1977c87d34d2006-01-06 13:00:28 +00008471}
8472
drha154dcd2006-03-22 22:10:07 +00008473
8474#ifndef SQLITE_OMIT_SHARED_CACHE
8475/*
8476** Obtain a lock on the table whose root page is iTab. The
8477** lock is a write lock if isWritelock is true or a read lock
8478** if it is false.
8479*/
danielk1977c00da102006-01-07 13:21:04 +00008480int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
danielk19772e94d4d2006-01-09 05:36:27 +00008481 int rc = SQLITE_OK;
danielk1977602b4662009-07-02 07:47:33 +00008482 assert( p->inTrans!=TRANS_NONE );
drh6a9ad3d2008-04-02 16:29:30 +00008483 if( p->sharable ){
8484 u8 lockType = READ_LOCK + isWriteLock;
8485 assert( READ_LOCK+1==WRITE_LOCK );
8486 assert( isWriteLock==0 || isWriteLock==1 );
danielk1977602b4662009-07-02 07:47:33 +00008487
drh6a9ad3d2008-04-02 16:29:30 +00008488 sqlite3BtreeEnter(p);
drhc25eabe2009-02-24 18:57:31 +00008489 rc = querySharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00008490 if( rc==SQLITE_OK ){
drhc25eabe2009-02-24 18:57:31 +00008491 rc = setSharedCacheTableLock(p, iTab, lockType);
drh6a9ad3d2008-04-02 16:29:30 +00008492 }
8493 sqlite3BtreeLeave(p);
danielk1977c00da102006-01-07 13:21:04 +00008494 }
8495 return rc;
8496}
drha154dcd2006-03-22 22:10:07 +00008497#endif
danielk1977b82e7ed2006-01-11 14:09:31 +00008498
danielk1977b4e9af92007-05-01 17:49:49 +00008499#ifndef SQLITE_OMIT_INCRBLOB
8500/*
8501** Argument pCsr must be a cursor opened for writing on an
8502** INTKEY table currently pointing at a valid table entry.
8503** This function modifies the data stored as part of that entry.
danielk1977ecaecf92009-07-08 08:05:35 +00008504**
8505** Only the data content may only be modified, it is not possible to
8506** change the length of the data stored. If this function is called with
8507** parameters that attempt to write past the end of the existing data,
8508** no modifications are made and SQLITE_CORRUPT is returned.
danielk1977b4e9af92007-05-01 17:49:49 +00008509*/
danielk1977dcbb5d32007-05-04 18:36:44 +00008510int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
danielk1977c9000e62009-07-08 13:55:28 +00008511 int rc;
drh1fee73e2007-08-29 04:00:57 +00008512 assert( cursorHoldsMutex(pCsr) );
drhe5fe6902007-12-07 18:55:28 +00008513 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
drh036dbec2014-03-11 23:40:44 +00008514 assert( pCsr->curFlags & BTCF_Incrblob );
danielk19773588ceb2008-06-10 17:30:26 +00008515
danielk1977c9000e62009-07-08 13:55:28 +00008516 rc = restoreCursorPosition(pCsr);
8517 if( rc!=SQLITE_OK ){
8518 return rc;
8519 }
danielk19773588ceb2008-06-10 17:30:26 +00008520 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
8521 if( pCsr->eState!=CURSOR_VALID ){
8522 return SQLITE_ABORT;
danielk1977dcbb5d32007-05-04 18:36:44 +00008523 }
8524
dan227a1c42013-04-03 11:17:39 +00008525 /* Save the positions of all other cursors open on this table. This is
8526 ** required in case any of them are holding references to an xFetch
8527 ** version of the b-tree page modified by the accessPayload call below.
drh370c9f42013-04-03 20:04:04 +00008528 **
8529 ** Note that pCsr must be open on a BTREE_INTKEY table and saveCursorPosition()
8530 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
8531 ** saveAllCursors can only return SQLITE_OK.
dan227a1c42013-04-03 11:17:39 +00008532 */
drh370c9f42013-04-03 20:04:04 +00008533 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
8534 assert( rc==SQLITE_OK );
dan227a1c42013-04-03 11:17:39 +00008535
danielk1977c9000e62009-07-08 13:55:28 +00008536 /* Check some assumptions:
danielk1977dcbb5d32007-05-04 18:36:44 +00008537 ** (a) the cursor is open for writing,
danielk1977c9000e62009-07-08 13:55:28 +00008538 ** (b) there is a read/write transaction open,
8539 ** (c) the connection holds a write-lock on the table (if required),
8540 ** (d) there are no conflicting read-locks, and
8541 ** (e) the cursor points at a valid row of an intKey table.
danielk1977d04417962007-05-02 13:16:30 +00008542 */
drh036dbec2014-03-11 23:40:44 +00008543 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
danielk19774f029602009-07-08 18:45:37 +00008544 return SQLITE_READONLY;
8545 }
drhc9166342012-01-05 23:32:06 +00008546 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
8547 && pCsr->pBt->inTransaction==TRANS_WRITE );
danielk197796d48e92009-06-29 06:00:37 +00008548 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
8549 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
danielk1977c9000e62009-07-08 13:55:28 +00008550 assert( pCsr->apPage[pCsr->iPage]->intKey );
danielk1977b4e9af92007-05-01 17:49:49 +00008551
drhfb192682009-07-11 18:26:28 +00008552 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
danielk1977b4e9af92007-05-01 17:49:49 +00008553}
danielk19772dec9702007-05-02 16:48:37 +00008554
8555/*
dan5a500af2014-03-11 20:33:04 +00008556** Mark this cursor as an incremental blob cursor.
danielk19772dec9702007-05-02 16:48:37 +00008557*/
dan5a500af2014-03-11 20:33:04 +00008558void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
drh036dbec2014-03-11 23:40:44 +00008559 pCur->curFlags |= BTCF_Incrblob;
danielk19772dec9702007-05-02 16:48:37 +00008560}
danielk1977b4e9af92007-05-01 17:49:49 +00008561#endif
dane04dc882010-04-20 18:53:15 +00008562
8563/*
8564** Set both the "read version" (single byte at byte offset 18) and
8565** "write version" (single byte at byte offset 19) fields in the database
8566** header to iVersion.
8567*/
8568int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
8569 BtShared *pBt = pBtree->pBt;
8570 int rc; /* Return code */
8571
dane04dc882010-04-20 18:53:15 +00008572 assert( iVersion==1 || iVersion==2 );
8573
danb9780022010-04-21 18:37:57 +00008574 /* If setting the version fields to 1, do not automatically open the
8575 ** WAL connection, even if the version fields are currently set to 2.
8576 */
drhc9166342012-01-05 23:32:06 +00008577 pBt->btsFlags &= ~BTS_NO_WAL;
8578 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
danb9780022010-04-21 18:37:57 +00008579
8580 rc = sqlite3BtreeBeginTrans(pBtree, 0);
dane04dc882010-04-20 18:53:15 +00008581 if( rc==SQLITE_OK ){
8582 u8 *aData = pBt->pPage1->aData;
danb9780022010-04-21 18:37:57 +00008583 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
danede6eb82010-04-22 06:27:04 +00008584 rc = sqlite3BtreeBeginTrans(pBtree, 2);
danb9780022010-04-21 18:37:57 +00008585 if( rc==SQLITE_OK ){
8586 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
8587 if( rc==SQLITE_OK ){
8588 aData[18] = (u8)iVersion;
8589 aData[19] = (u8)iVersion;
8590 }
8591 }
8592 }
dane04dc882010-04-20 18:53:15 +00008593 }
8594
drhc9166342012-01-05 23:32:06 +00008595 pBt->btsFlags &= ~BTS_NO_WAL;
dane04dc882010-04-20 18:53:15 +00008596 return rc;
8597}
dan428c2182012-08-06 18:50:11 +00008598
8599/*
8600** set the mask of hint flags for cursor pCsr. Currently the only valid
8601** values are 0 and BTREE_BULKLOAD.
8602*/
8603void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
8604 assert( mask==BTREE_BULKLOAD || mask==0 );
8605 pCsr->hints = mask;
8606}
drh781597f2014-05-21 08:21:07 +00008607
8608/*
8609** Return true if the given Btree is read-only.
8610*/
8611int sqlite3BtreeIsReadonly(Btree *p){
8612 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
8613}